Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@restart/hooks

Package Overview
Dependencies
Maintainers
3
Versions
65
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@restart/hooks - npm Package Compare versions

Comparing version 0.4.9 to 0.4.10

cjs/useIsInitialRenderRef.d.ts

27

cjs/index.js
"use strict";
exports.__esModule = true;
var _useCallbackRef = _interopRequireDefault(require("./useCallbackRef"));
exports.useCallbackRef = _useCallbackRef.default;
var _useCommittedRef = _interopRequireDefault(require("./useCommittedRef"));
exports.useCommittedRef = _useCommittedRef.default;
var _useEventCallback = _interopRequireDefault(require("./useEventCallback"));
exports.useEventCallback = _useEventCallback.default;
var _useEventListener = _interopRequireDefault(require("./useEventListener"));
exports.useEventListener = _useEventListener.default;
var _useGlobalListener = _interopRequireDefault(require("./useGlobalListener"));
exports.useGlobalListener = _useGlobalListener.default;
var _useInterval = _interopRequireDefault(require("./useInterval"));
exports.useInterval = _useInterval.default;
var _useRafInterval = _interopRequireDefault(require("./useRafInterval"));
exports.useRafInterval = _useRafInterval.default;
var _useMergeState = _interopRequireDefault(require("./useMergeState"));
exports.useMergeState = _useMergeState.default;
var _useMergeStateFromProps = _interopRequireDefault(require("./useMergeStateFromProps"));
exports.useMergeStateFromProps = _useMergeStateFromProps.default;
var _useMounted = _interopRequireDefault(require("./useMounted"));
exports.useMounted = _useMounted.default;
var _usePrevious = _interopRequireDefault(require("./usePrevious"));
exports.usePrevious = _usePrevious.default;
var _useImage = _interopRequireDefault(require("./useImage"));
exports.useImage = _useImage.default;
var _useResizeObserver = _interopRequireDefault(require("./useResizeObserver"));
exports.useResizeObserver = _useResizeObserver.default;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

32

cjs/useAnimationFrame.js

@@ -5,13 +5,7 @@ "use strict";

exports.default = useAnimationFrame;
var _react = require("react");
var _useMounted = _interopRequireDefault(require("./useMounted"));
var _useStableMemo = _interopRequireDefault(require("./useStableMemo"));
var _useWillUnmount = _interopRequireDefault(require("./useWillUnmount"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**

@@ -43,6 +37,5 @@ * Returns a controller object for requesting and cancelling an animation freame that is properly cleaned up

function useAnimationFrame() {
var isMounted = (0, _useMounted.default)();
var handle = (0, _react.useRef)();
var cancel = function cancel() {
const isMounted = (0, _useMounted.default)();
const handle = (0, _react.useRef)();
const cancel = () => {
if (handle.current != null) {

@@ -52,14 +45,11 @@ cancelAnimationFrame(handle.current);

};
(0, _useWillUnmount.default)(cancel);
return (0, _useStableMemo.default)(function () {
return {
request: function request(cancelPrevious, fn) {
if (!isMounted()) return;
if (cancelPrevious) cancel();
handle.current = requestAnimationFrame(fn || cancelPrevious);
},
cancel: cancel
};
}, []);
return (0, _useStableMemo.default)(() => ({
request(cancelPrevious, fn) {
if (!isMounted()) return;
if (cancelPrevious) cancel();
handle.current = requestAnimationFrame(fn || cancelPrevious);
},
cancel
}), []);
}

@@ -1,3 +0,3 @@

export declare type BreakpointDirection = 'up' | 'down' | true;
export declare type BreakpointMap<TKey extends string> = Partial<Record<TKey, BreakpointDirection>>;
export type BreakpointDirection = 'up' | 'down' | true;
export type BreakpointMap<TKey extends string> = Partial<Record<TKey, BreakpointDirection>>;
/**

@@ -26,11 +26,11 @@ * Create a responsive hook we a set of breakpoint names and widths.

export declare function createBreakpointHook<TKey extends string>(breakpointValues: Record<TKey, string | number>): {
(breakpointMap: BreakpointMap<TKey>, window?: Window | undefined): boolean;
(breakpoint: TKey, direction?: BreakpointDirection | undefined, window?: Window | undefined): boolean;
(breakpointMap: BreakpointMap<TKey>, window?: Window): boolean;
(breakpoint: TKey, direction?: BreakpointDirection, window?: Window): boolean;
};
export declare type DefaultBreakpoints = 'xs' | 'sm' | 'md' | 'lg' | 'xl' | 'xxl';
export declare type DefaultBreakpointMap = BreakpointMap<DefaultBreakpoints>;
export type DefaultBreakpoints = 'xs' | 'sm' | 'md' | 'lg' | 'xl' | 'xxl';
export type DefaultBreakpointMap = BreakpointMap<DefaultBreakpoints>;
declare const useBreakpoint: {
(breakpointMap: Partial<Record<DefaultBreakpoints, BreakpointDirection>>, window?: Window | undefined): boolean;
(breakpoint: DefaultBreakpoints, direction?: BreakpointDirection | undefined, window?: Window | undefined): boolean;
(breakpointMap: Partial<Record<DefaultBreakpoints, BreakpointDirection>>, window?: Window): boolean;
(breakpoint: DefaultBreakpoints, direction?: BreakpointDirection, window?: Window): boolean;
};
export default useBreakpoint;

@@ -6,9 +6,5 @@ "use strict";

exports.default = void 0;
var _useMediaQuery = _interopRequireDefault(require("./useMediaQuery"));
var _react = require("react");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**

@@ -37,4 +33,3 @@ * Create a responsive hook we a set of breakpoint names and widths.

function createBreakpointHook(breakpointValues) {
var names = Object.keys(breakpointValues);
const names = Object.keys(breakpointValues);
function and(query, next) {

@@ -44,26 +39,21 @@ if (query === next) {

}
return query ? query + " and " + next : next;
return query ? `${query} and ${next}` : next;
}
function getNext(breakpoint) {
return names[Math.min(names.indexOf(breakpoint) + 1, names.length - 1)];
}
function getMaxQuery(breakpoint) {
var next = getNext(breakpoint);
var value = breakpointValues[next];
if (typeof value === 'number') value = value - 0.2 + "px";else value = "calc(" + value + " - 0.2px)";
return "(max-width: " + value + ")";
const next = getNext(breakpoint);
let value = breakpointValues[next];
if (typeof value === 'number') value = `${value - 0.2}px`;else value = `calc(${value} - 0.2px)`;
return `(max-width: ${value})`;
}
function getMinQuery(breakpoint) {
var value = breakpointValues[breakpoint];
let value = breakpointValues[breakpoint];
if (typeof value === 'number') {
value = value + "px";
value = `${value}px`;
}
return `(min-width: ${value})`;
}
return "(min-width: " + value + ")";
}
/**

@@ -85,6 +75,21 @@ * Match a set of breakpoints

/**
* Match a single breakpoint exactly, up, or down.
*
* ```tsx
* const PhoneOnly = () => {
* const isSmall = useBreakpoint('sm', 'down');
*
* if (isSmall) return <div>On a Small Screen!</div>
* return null;
* }
* ```
*
* @param breakpoint The breakpoint key
* @param direction A direction 'up' for a max, 'down' for min, true to match only the breakpoint
* @param window Optionally specify the target window to match against (useful when rendering into iframes)
*/
function useBreakpoint(breakpointOrMap, direction, window) {
var breakpointMap;
let breakpointMap;
if (typeof breakpointOrMap === 'object') {

@@ -95,31 +100,21 @@ breakpointMap = breakpointOrMap;

} else {
var _breakpointMap;
direction = direction || true;
breakpointMap = (_breakpointMap = {}, _breakpointMap[breakpointOrMap] = direction, _breakpointMap);
breakpointMap = {
[breakpointOrMap]: direction
};
}
var query = (0, _react.useMemo)(function () {
return Object.entries(breakpointMap).reduce(function (query, _ref) {
var key = _ref[0],
direction = _ref[1];
if (direction === 'up' || direction === true) {
query = and(query, getMinQuery(key));
}
if (direction === 'down' || direction === true) {
query = and(query, getMaxQuery(key));
}
return query;
}, '');
}, [JSON.stringify(breakpointMap)]);
let query = (0, _react.useMemo)(() => Object.entries(breakpointMap).reduce((query, [key, direction]) => {
if (direction === 'up' || direction === true) {
query = and(query, getMinQuery(key));
}
if (direction === 'down' || direction === true) {
query = and(query, getMaxQuery(key));
}
return query;
}, ''), [JSON.stringify(breakpointMap)]);
return (0, _useMediaQuery.default)(query, window);
}
return useBreakpoint;
}
var useBreakpoint = createBreakpointHook({
const useBreakpoint = createBreakpointHook({
xs: 0,

@@ -126,0 +121,0 @@ sm: 576,

@@ -5,5 +5,3 @@ "use strict";

exports.default = useCallbackRef;
var _react = require("react");
/**

@@ -10,0 +8,0 @@ * A convenience hook around `useState` designed to be paired with

@@ -5,5 +5,3 @@ "use strict";

exports.default = void 0;
var _react = require("react");
/**

@@ -19,4 +17,4 @@ * Creates a `Ref` whose value is updated in an effect, ensuring the most recent

function useCommittedRef(value) {
var ref = (0, _react.useRef)(value);
(0, _react.useEffect)(function () {
const ref = (0, _react.useRef)(value);
(0, _react.useEffect)(() => {
ref.current = value;

@@ -26,4 +24,3 @@ }, [value]);

}
var _default = useCommittedRef;
exports.default = _default;
import { DependencyList, EffectCallback } from 'react';
export declare type EffectHook = (effect: EffectCallback, deps?: DependencyList) => void;
export declare type IsEqual<TDeps extends DependencyList> = (nextDeps: TDeps, prevDeps: TDeps) => boolean;
export declare type CustomEffectOptions<TDeps extends DependencyList> = {
export type EffectHook = (effect: EffectCallback, deps?: DependencyList) => void;
export type IsEqual<TDeps extends DependencyList> = (nextDeps: TDeps, prevDeps: TDeps) => boolean;
export type CustomEffectOptions<TDeps extends DependencyList> = {
isEqual: IsEqual<TDeps>;

@@ -6,0 +6,0 @@ effectHook?: EffectHook;

@@ -5,23 +5,35 @@ "use strict";

exports.default = void 0;
var _react = require("react");
var _useMounted = _interopRequireDefault(require("./useMounted"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* a useEffect() hook with customized depedency comparision
*
* @param effect The effect callback
* @param dependencies A list of dependencies
* @param isEqual A function comparing the next and previous dependencyLists
*/
/**
* a useEffect() hook with customized depedency comparision
*
* @param effect The effect callback
* @param dependencies A list of dependencies
* @param options
* @param options.isEqual A function comparing the next and previous dependencyLists
* @param options.effectHook the underlying effect hook used, defaults to useEffect
*/
function useCustomEffect(effect, dependencies, isEqualOrOptions) {
var isMounted = (0, _useMounted.default)();
var _ref = typeof isEqualOrOptions === 'function' ? {
const isMounted = (0, _useMounted.default)();
const {
isEqual,
effectHook = _react.useEffect
} = typeof isEqualOrOptions === 'function' ? {
isEqual: isEqualOrOptions
} : isEqualOrOptions,
isEqual = _ref.isEqual,
_ref$effectHook = _ref.effectHook,
effectHook = _ref$effectHook === void 0 ? _react.useEffect : _ref$effectHook;
var dependenciesRef = (0, _react.useRef)();
} : isEqualOrOptions;
const dependenciesRef = (0, _react.useRef)();
dependenciesRef.current = dependencies;
var cleanupRef = (0, _react.useRef)(null);
effectHook(function () {
const cleanupRef = (0, _react.useRef)(null);
effectHook(() => {
// If the ref the is `null` it's either the first effect or the last effect

@@ -31,9 +43,7 @@ // ran and was cleared, meaning _this_ update should run, b/c the equality

if (cleanupRef.current === null) {
var cleanup = effect();
cleanupRef.current = function () {
const cleanup = effect();
cleanupRef.current = () => {
if (isMounted() && isEqual(dependenciesRef.current, dependencies)) {
return;
}
cleanupRef.current = null;

@@ -43,3 +53,2 @@ if (cleanup) cleanup();

}
return cleanupRef.current;

@@ -49,4 +58,3 @@ });

}
var _default = useCustomEffect;
exports.default = _default;

@@ -5,9 +5,5 @@ "use strict";

exports.default = useDebouncedCallback;
var _react = require("react");
var _useTimeout = _interopRequireDefault(require("./useTimeout"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**

@@ -21,12 +17,8 @@ * Creates a debounced function that will invoke the input function after the

function useDebouncedCallback(fn, delay) {
var timeout = (0, _useTimeout.default)();
return (0, _react.useCallback)(function () {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
timeout.set(function () {
fn.apply(void 0, args);
const timeout = (0, _useTimeout.default)();
return (0, _react.useCallback)((...args) => {
timeout.set(() => {
fn(...args);
}, delay);
}, [fn, delay]);
}

@@ -5,9 +5,5 @@ "use strict";

exports.default = useDebouncedState;
var _react = require("react");
var _useDebouncedCallback = _interopRequireDefault(require("./useDebouncedCallback"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**

@@ -27,8 +23,5 @@ * Similar to `useState`, except the setter function is debounced by

function useDebouncedState(initialState, delay) {
var _useState = (0, _react.useState)(initialState),
state = _useState[0],
setState = _useState[1];
var debouncedSetState = (0, _useDebouncedCallback.default)(setState, delay);
const [state, setState] = (0, _react.useState)(initialState);
const debouncedSetState = (0, _useDebouncedCallback.default)(setState, delay);
return [state, debouncedSetState];
}

@@ -5,9 +5,5 @@ "use strict";

exports.default = void 0;
var _react = require("react");
var _useDebouncedState2 = _interopRequireDefault(require("./useDebouncedState"));
var _useDebouncedState = _interopRequireDefault(require("./useDebouncedState"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**

@@ -22,13 +18,6 @@ * Debounce a value change by a specified number of milliseconds. Useful

*/
function useDebouncedValue(value, delayMs) {
if (delayMs === void 0) {
delayMs = 500;
}
var _useDebouncedState = (0, _useDebouncedState2.default)(value, delayMs),
debouncedValue = _useDebouncedState[0],
setDebouncedValue = _useDebouncedState[1];
function useDebouncedValue(value, delayMs = 500) {
const [debouncedValue, setDebouncedValue] = (0, _useDebouncedState.default)(value, delayMs);
(0, _react.useDebugValue)(debouncedValue);
(0, _react.useEffect)(function () {
(0, _react.useEffect)(() => {
setDebouncedValue(value);

@@ -38,4 +27,3 @@ }, [value, delayMs]);

}
var _default = useDebouncedValue;
exports.default = _default;

@@ -5,14 +5,10 @@ "use strict";

exports.default = useEventCallback;
var _react = require("react");
var _useCommittedRef = _interopRequireDefault(require("./useCommittedRef"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function useEventCallback(fn) {
var ref = (0, _useCommittedRef.default)(fn);
return (0, _react.useCallback)(function () {
return ref.current && ref.current.apply(ref, arguments);
const ref = (0, _useCommittedRef.default)(fn);
return (0, _react.useCallback)(function (...args) {
return ref.current && ref.current(...args);
}, [ref]);
}

@@ -1,2 +0,2 @@

declare type EventHandler<T, K extends keyof DocumentEventMap> = (this: T, ev: DocumentEventMap[K]) => any;
type EventHandler<T, K extends keyof DocumentEventMap> = (this: T, ev: DocumentEventMap[K]) => any;
/**

@@ -3,0 +3,0 @@ * Attaches an event handler outside directly to specified DOM element

@@ -5,9 +5,5 @@ "use strict";

exports.default = useEventListener;
var _react = require("react");
var _useEventCallback = _interopRequireDefault(require("./useEventCallback"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**

@@ -22,15 +18,9 @@ * Attaches an event handler outside directly to specified DOM element

*/
function useEventListener(eventTarget, event, listener, capture) {
if (capture === void 0) {
capture = false;
}
var handler = (0, _useEventCallback.default)(listener);
(0, _react.useEffect)(function () {
var target = typeof eventTarget === 'function' ? eventTarget() : eventTarget;
function useEventListener(eventTarget, event, listener, capture = false) {
const handler = (0, _useEventCallback.default)(listener);
(0, _react.useEffect)(() => {
const target = typeof eventTarget === 'function' ? eventTarget() : eventTarget;
target.addEventListener(event, handler, capture);
return function () {
return target.removeEventListener(event, handler, capture);
};
return () => target.removeEventListener(event, handler, capture);
}, [eventTarget]);
}

@@ -5,11 +5,6 @@ "use strict";

exports.default = useFocusManager;
var _react = require("react");
var _useEventCallback = _interopRequireDefault(require("./useEventCallback"));
var _useMounted = _interopRequireDefault(require("./useMounted"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**

@@ -41,36 +36,41 @@ * useFocusManager provides a way to track and manage focus as it moves around

function useFocusManager(opts) {
var isMounted = (0, _useMounted.default)();
var lastFocused = (0, _react.useRef)();
var handle = (0, _react.useRef)();
var willHandle = (0, _useEventCallback.default)(opts.willHandle);
var didHandle = (0, _useEventCallback.default)(opts.didHandle);
var onChange = (0, _useEventCallback.default)(opts.onChange);
var isDisabled = (0, _useEventCallback.default)(opts.isDisabled);
var handleFocusChange = (0, _react.useCallback)(function (focused, event) {
const isMounted = (0, _useMounted.default)();
const lastFocused = (0, _react.useRef)();
const handle = (0, _react.useRef)();
const willHandle = (0, _useEventCallback.default)(opts.willHandle);
const didHandle = (0, _useEventCallback.default)(opts.didHandle);
const onChange = (0, _useEventCallback.default)(opts.onChange);
const isDisabled = (0, _useEventCallback.default)(opts.isDisabled);
const handleChange = (0, _react.useCallback)((focused, event) => {
if (focused !== lastFocused.current) {
didHandle == null ? void 0 : didHandle(focused, event);
// only fire a change when unmounted if its a blur
if (isMounted() || !focused) {
lastFocused.current = focused;
onChange == null ? void 0 : onChange(focused, event);
}
}
}, [isMounted, didHandle, onChange, lastFocused]);
const handleFocusChange = (0, _react.useCallback)((focused, event) => {
if (isDisabled()) return;
if (event && event.persist) event.persist();
if (willHandle && willHandle(focused, event) === false) return;
if ((willHandle == null ? void 0 : willHandle(focused, event)) === false) {
return;
}
clearTimeout(handle.current);
handle.current = window.setTimeout(function () {
if (focused !== lastFocused.current) {
if (didHandle) didHandle(focused, event); // only fire a change when unmounted if its a blur
if (isMounted() || !focused) {
lastFocused.current = focused;
onChange && onChange(focused, event);
}
}
});
}, [isMounted, willHandle, didHandle, onChange, lastFocused]);
var handleBlur = (0, _react.useCallback)(function (event) {
if (!isDisabled()) handleFocusChange(false, event);
}, [handleFocusChange, isDisabled]);
var handleFocus = (0, _react.useCallback)(function (event) {
if (!isDisabled()) handleFocusChange(true, event);
}, [handleFocusChange, isDisabled]);
return (0, _react.useMemo)(function () {
return {
onBlur: handleBlur,
onFocus: handleFocus
};
}, [handleBlur, handleFocus]);
if (focused) {
handleChange(focused, event);
} else {
handle.current = window.setTimeout(() => handleChange(focused, event));
}
}, [willHandle, handleChange]);
return (0, _react.useMemo)(() => ({
onBlur: event => {
handleFocusChange(false, event);
},
onFocus: event => {
handleFocusChange(true, event);
}
}), [handleFocusChange]);
}

@@ -5,5 +5,3 @@ "use strict";

exports.default = useForceUpdate;
var _react = require("react");
/**

@@ -27,9 +25,5 @@ * Returns a function that triggers a component update. the hook equivalent to

// The toggling state value is designed to defeat React optimizations for skipping
// updates when they are stricting equal to the last state value
var _useReducer = (0, _react.useReducer)(function (state) {
return !state;
}, false),
dispatch = _useReducer[1];
// updates when they are strictly equal to the last state value
const [, dispatch] = (0, _react.useReducer)(state => !state, false);
return dispatch;
}

@@ -1,2 +0,2 @@

declare type DocumentEventHandler<K extends keyof DocumentEventMap> = (this: Document, ev: DocumentEventMap[K]) => any;
type DocumentEventHandler<K extends keyof DocumentEventMap> = (this: Document, ev: DocumentEventMap[K]) => any;
/**

@@ -3,0 +3,0 @@ * Attaches an event handler outside directly to the `document`,

@@ -5,9 +5,5 @@ "use strict";

exports.default = useGlobalListener;
var _useEventListener = _interopRequireDefault(require("./useEventListener"));
var _react = require("react");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**

@@ -27,11 +23,5 @@ * Attaches an event handler outside directly to the `document`,

*/
function useGlobalListener(event, handler, capture) {
if (capture === void 0) {
capture = false;
}
var documentTarget = (0, _react.useCallback)(function () {
return document;
}, []);
function useGlobalListener(event, handler, capture = false) {
const documentTarget = (0, _react.useCallback)(() => document, []);
return (0, _useEventListener.default)(documentTarget, event, handler, capture);
}

@@ -1,2 +0,2 @@

declare type State = {
type State = {
image: HTMLImageElement | null;

@@ -3,0 +3,0 @@ error: unknown | null;

@@ -5,5 +5,3 @@ "use strict";

exports.default = useImage;
var _react = require("react");
/**

@@ -35,13 +33,9 @@ * Fetch and load an image for programatic use such as in a `<canvas>` element.

function useImage(imageOrUrl, crossOrigin) {
var _useState = (0, _react.useState)({
const [state, setState] = (0, _react.useState)({
image: null,
error: null
}),
state = _useState[0],
setState = _useState[1];
(0, _react.useEffect)(function () {
});
(0, _react.useEffect)(() => {
if (!imageOrUrl) return undefined;
var image;
let image;
if (typeof imageOrUrl === 'string') {

@@ -53,6 +47,5 @@ image = new Image();

image = imageOrUrl;
if (image.complete && image.naturalHeight > 0) {
setState({
image: image,
image,
error: null

@@ -63,20 +56,17 @@ });

}
function onLoad() {
setState({
image: image,
image,
error: null
});
}
function onError(error) {
setState({
image: image,
error: error
image,
error
});
}
image.addEventListener('load', onLoad);
image.addEventListener('error', onError);
return function () {
return () => {
image.removeEventListener('load', onLoad);

@@ -83,0 +73,0 @@ image.removeEventListener('error', onError);

@@ -5,8 +5,5 @@ "use strict";

exports.default = void 0;
var _useUpdateImmediateEffect = _interopRequireDefault(require("./useUpdateImmediateEffect"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var _default = _useUpdateImmediateEffect.default;
exports.default = _default;

@@ -5,17 +5,37 @@ "use strict";

exports.default = void 0;
var _react = require("react");
var _useStableMemo = _interopRequireDefault(require("./useStableMemo"));
var _useIsomorphicEffect = _interopRequireDefault(require("./useIsomorphicEffect"));
var _useEventCallback = _interopRequireDefault(require("./useEventCallback"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Setup an [`IntersectionObserver`](https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserver) on
* a DOM Element that returns it's entries as they arrive.
*
* @param element The DOM element to observe
* @param init IntersectionObserver options with a notable change,
* unlike a plain IntersectionObserver `root: null` means "not provided YET",
* and the hook will wait until it receives a non-null value to set up the observer.
* This change allows for easier syncing of element and root values in a React
* context.
*/
/**
* Setup an [`IntersectionObserver`](https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserver) on
* a DOM Element. This overload does not trigger component updates when receiving new
* entries. This allows for finer grained performance optimizations by the consumer.
*
* @param element The DOM element to observe
* @param callback A listener for intersection updates.
* @param init IntersectionObserver options with a notable change,
* unlike a plain IntersectionObserver `root: null` means "not provided YET",
* and the hook will wait until it receives a non-null value to set up the observer.
* This change allows for easier syncing of element and root values in a React
* context.
*
*/
function useIntersectionObserver(element, callbackOrOptions, maybeOptions) {
var callback;
var options;
let callback;
let options;
if (typeof callbackOrOptions === 'function') {

@@ -27,25 +47,20 @@ callback = callbackOrOptions;

}
const {
threshold,
root,
rootMargin
} = options;
const [entries, setEntry] = (0, _react.useState)(null);
const handler = (0, _useEventCallback.default)(callback || setEntry);
var _options = options,
threshold = _options.threshold,
root = _options.root,
rootMargin = _options.rootMargin;
var _useState = (0, _react.useState)(null),
entries = _useState[0],
setEntry = _useState[1];
var handler = (0, _useEventCallback.default)(callback || setEntry); // We wait for element to exist before constructing
var observer = (0, _useStableMemo.default)(function () {
return root !== null && typeof IntersectionObserver !== 'undefined' && new IntersectionObserver(handler, {
threshold: threshold,
root: root,
rootMargin: rootMargin
});
}, [handler, root, rootMargin, threshold && JSON.stringify(threshold)]);
(0, _useIsomorphicEffect.default)(function () {
// We wait for element to exist before constructing
const observer = (0, _useStableMemo.default)(() => root !== null && typeof IntersectionObserver !== 'undefined' && new IntersectionObserver(handler, {
threshold,
root,
rootMargin
}), [handler, root, rootMargin, threshold && JSON.stringify(threshold)]);
(0, _useIsomorphicEffect.default)(() => {
if (!element || !observer) return;
observer.observe(element);
return function () {
return () => {
observer.unobserve(element);

@@ -56,4 +71,3 @@ };

}
var _default = useIntersectionObserver;
exports.default = _default;

@@ -5,25 +5,72 @@ "use strict";

exports.default = void 0;
var _react = require("react");
var _useCommittedRef = _interopRequireDefault(require("./useCommittedRef"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* Creates a `setInterval` that is properly cleaned up when a component unmounted
*
* ```tsx
* function Timer() {
* const [timer, setTimer] = useState(0)
* useInterval(() => setTimer(i => i + 1), 1000)
*
* return <span>{timer} seconds past</span>
* }
* ```
*
* @param fn an function run on each interval
* @param ms The milliseconds duration of the interval
*/
function useInterval(fn, ms, paused, runImmediately) {
if (paused === void 0) {
paused = false;
}
/**
* Creates a pausable `setInterval` that is properly cleaned up when a component unmounted
*
* ```tsx
* const [paused, setPaused] = useState(false)
* const [timer, setTimer] = useState(0)
*
* useInterval(() => setTimer(i => i + 1), 1000, paused)
*
* return (
* <span>
* {timer} seconds past
*
* <button onClick={() => setPaused(p => !p)}>{paused ? 'Play' : 'Pause' }</button>
* </span>
* )
* ```
*
* @param fn an function run on each interval
* @param ms The milliseconds duration of the interval
* @param paused Whether or not the interval is currently running
*/
if (runImmediately === void 0) {
runImmediately = false;
}
/**
* Creates a pausable `setInterval` that _fires_ immediately and is
* properly cleaned up when a component unmounted
*
* ```tsx
* const [timer, setTimer] = useState(-1)
* useInterval(() => setTimer(i => i + 1), 1000, false, true)
*
* // will update to 0 on the first effect
* return <span>{timer} seconds past</span>
* ```
*
* @param fn an function run on each interval
* @param ms The milliseconds duration of the interval
* @param paused Whether or not the interval is currently running
* @param runImmediately Whether to run the function immediately on mount or unpause
* rather than waiting for the first interval to elapse
*
var handle;
var fnRef = (0, _useCommittedRef.default)(fn); // this ref is necessary b/c useEffect will sometimes miss a paused toggle
*/
function useInterval(fn, ms, paused = false, runImmediately = false) {
let handle;
const fnRef = (0, _useCommittedRef.default)(fn);
// this ref is necessary b/c useEffect will sometimes miss a paused toggle
// orphaning a setTimeout chain in the aether, so relying on it's refresh logic is not reliable.
var pausedRef = (0, _useCommittedRef.default)(paused);
var tick = function tick() {
const pausedRef = (0, _useCommittedRef.default)(paused);
const tick = () => {
if (pausedRef.current) return;

@@ -34,8 +81,7 @@ fnRef.current();

var schedule = function schedule() {
const schedule = () => {
clearTimeout(handle);
handle = setTimeout(tick, ms);
};
(0, _react.useEffect)(function () {
(0, _react.useEffect)(() => {
if (runImmediately) {

@@ -46,10 +92,6 @@ tick();

}
return function () {
return clearTimeout(handle);
};
return () => clearTimeout(handle);
}, [paused, runImmediately]);
}
var _default = useInterval;
exports.default = _default;
import { useEffect } from 'react';
declare const _default: typeof useEffect;
/**

@@ -11,2 +10,3 @@ * Is `useLayoutEffect` in a DOM or React Native environment, otherwise resolves to useEffect

*/
declare const _default: typeof useEffect;
export default _default;

@@ -5,9 +5,10 @@ "use strict";

exports.default = void 0;
var _react = require("react");
const isReactNative = typeof global !== 'undefined' &&
// @ts-ignore
global.navigator &&
// @ts-ignore
global.navigator.product === 'ReactNative';
const isDOM = typeof document !== 'undefined';
var isReactNative = typeof global !== 'undefined' && // @ts-ignore
global.navigator && // @ts-ignore
global.navigator.product === 'ReactNative';
var isDOM = typeof document !== 'undefined';
/**

@@ -21,5 +22,3 @@ * Is `useLayoutEffect` in a DOM or React Native environment, otherwise resolves to useEffect

*/
var _default = isDOM || isReactNative ? _react.useLayoutEffect : _react.useEffect;
exports.default = _default;

@@ -5,60 +5,28 @@ "use strict";

exports.default = exports.ObservableMap = void 0;
var _useForceUpdate = _interopRequireDefault(require("./useForceUpdate"));
var _useStableMemo = _interopRequireDefault(require("./useStableMemo"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
function _wrapNativeSuper(Class) { var _cache = typeof Map === "function" ? new Map() : undefined; _wrapNativeSuper = function _wrapNativeSuper(Class) { if (Class === null || !_isNativeFunction(Class)) return Class; if (typeof Class !== "function") { throw new TypeError("Super expression must either be null or a function"); } if (typeof _cache !== "undefined") { if (_cache.has(Class)) return _cache.get(Class); _cache.set(Class, Wrapper); } function Wrapper() { return _construct(Class, arguments, _getPrototypeOf(this).constructor); } Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true } }); return _setPrototypeOf(Wrapper, Class); }; return _wrapNativeSuper(Class); }
function _construct(Parent, args, Class) { if (_isNativeReflectConstruct()) { _construct = Reflect.construct; } else { _construct = function _construct(Parent, args, Class) { var a = [null]; a.push.apply(a, args); var Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) _setPrototypeOf(instance, Class.prototype); return instance; }; } return _construct.apply(null, arguments); }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
function _isNativeFunction(fn) { return Function.toString.call(fn).indexOf("[native code]") !== -1; }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
var ObservableMap = /*#__PURE__*/function (_Map) {
_inheritsLoose(ObservableMap, _Map);
function ObservableMap(listener, init) {
var _this;
_this = _Map.call(this, init) || this;
_this.listener = listener;
return _this;
class ObservableMap extends Map {
constructor(listener, init) {
super(init);
this.listener = listener;
}
var _proto = ObservableMap.prototype;
_proto.set = function set(key, value) {
_Map.prototype.set.call(this, key, value); // When initializing the Map, the base Map calls this.set() before the
set(key, value) {
super.set(key, value);
// When initializing the Map, the base Map calls this.set() before the
// listener is assigned so it will be undefined
if (this.listener) this.listener(this);
return this;
};
_proto.delete = function _delete(key) {
var result = _Map.prototype.delete.call(this, key);
}
delete(key) {
let result = super.delete(key);
this.listener(this);
return result;
};
_proto.clear = function clear() {
_Map.prototype.clear.call(this);
}
clear() {
super.clear();
this.listener(this);
};
}
}
return ObservableMap;
}( /*#__PURE__*/_wrapNativeSuper(Map));
/**

@@ -86,14 +54,8 @@ * Create and return a [Map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) that triggers rerenders when it's updated.

*/
exports.ObservableMap = ObservableMap;
function useMap(init) {
var forceUpdate = (0, _useForceUpdate.default)();
return (0, _useStableMemo.default)(function () {
return new ObservableMap(forceUpdate, init);
}, []);
const forceUpdate = (0, _useForceUpdate.default)();
return (0, _useStableMemo.default)(() => new ObservableMap(forceUpdate, init), []);
}
var _default = useMap;
exports.default = _default;

@@ -5,17 +5,11 @@ "use strict";

exports.default = useMediaQuery;
var _useIsomorphicEffect = _interopRequireDefault(require("./useIsomorphicEffect"));
var _react = require("react");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var matchersByWindow = new WeakMap();
var getMatcher = function getMatcher(query, targetWindow) {
const matchersByWindow = new WeakMap();
const getMatcher = (query, targetWindow) => {
if (!query || !targetWindow) return undefined;
var matchers = matchersByWindow.get(targetWindow) || new Map();
const matchers = matchersByWindow.get(targetWindow) || new Map();
matchersByWindow.set(targetWindow, matchers);
var mql = matchers.get(query);
let mql = matchers.get(query);
if (!mql) {

@@ -26,3 +20,2 @@ mql = targetWindow.matchMedia(query);

}
return mql;

@@ -49,41 +42,23 @@ };

*/
function useMediaQuery(query, targetWindow) {
if (targetWindow === void 0) {
targetWindow = typeof window === 'undefined' ? undefined : window;
}
var mql = getMatcher(query, targetWindow);
var _useState = (0, _react.useState)(function () {
return mql ? mql.matches : false;
}),
matches = _useState[0],
setMatches = _useState[1];
(0, _useIsomorphicEffect.default)(function () {
var mql = getMatcher(query, targetWindow);
function useMediaQuery(query, targetWindow = typeof window === 'undefined' ? undefined : window) {
const mql = getMatcher(query, targetWindow);
const [matches, setMatches] = (0, _react.useState)(() => mql ? mql.matches : false);
(0, _useIsomorphicEffect.default)(() => {
let mql = getMatcher(query, targetWindow);
if (!mql) {
return setMatches(false);
}
var matchers = matchersByWindow.get(targetWindow);
var handleChange = function handleChange() {
let matchers = matchersByWindow.get(targetWindow);
const handleChange = () => {
setMatches(mql.matches);
};
mql.refCount++;
mql.addListener(handleChange);
handleChange();
return function () {
return () => {
mql.removeListener(handleChange);
mql.refCount--;
if (mql.refCount <= 0) {
matchers == null ? void 0 : matchers.delete(mql.media);
}
mql = undefined;

@@ -90,0 +65,0 @@ };

/// <reference types="react" />
declare type CallbackRef<T> = (ref: T | null) => void;
declare type Ref<T> = React.MutableRefObject<T> | CallbackRef<T>;
type CallbackRef<T> = (ref: T | null) => void;
type Ref<T> = React.MutableRefObject<T> | CallbackRef<T>;
export declare function mergeRefs<T>(refA?: Ref<T> | null, refB?: Ref<T> | null): (value: T | null) => void;

@@ -5,0 +5,0 @@ /**

"use strict";
exports.__esModule = true;
exports.default = void 0;
exports.mergeRefs = mergeRefs;
exports.default = void 0;
var _react = require("react");
var toFnRef = function toFnRef(ref) {
return !ref || typeof ref === 'function' ? ref : function (value) {
ref.current = value;
};
const toFnRef = ref => !ref || typeof ref === 'function' ? ref : value => {
ref.current = value;
};
function mergeRefs(refA, refB) {
var a = toFnRef(refA);
var b = toFnRef(refB);
return function (value) {
const a = toFnRef(refA);
const b = toFnRef(refB);
return value => {
if (a) a(value);

@@ -23,2 +18,3 @@ if (b) b(value);

}
/**

@@ -40,11 +36,6 @@ * Create and returns a single callback ref composed from two other Refs.

*/
function useMergedRefs(refA, refB) {
return (0, _react.useMemo)(function () {
return mergeRefs(refA, refB);
}, [refA, refB]);
return (0, _react.useMemo)(() => mergeRefs(refA, refB), [refA, refB]);
}
var _default = useMergedRefs;
exports.default = _default;

@@ -1,6 +0,6 @@

declare type Updater<TState> = (state: TState) => Partial<TState> | null;
type Updater<TState> = (state: TState) => Partial<TState> | null;
/**
* Updates state, partial updates are merged into existing state values
*/
export declare type MergeStateSetter<TState> = (update: Updater<TState> | Partial<TState> | null) => void;
export type MergeStateSetter<TState> = (update: Updater<TState> | Partial<TState> | null) => void;
/**

@@ -7,0 +7,0 @@ * Mimics a React class component's state model, of having a single unified

@@ -5,7 +5,7 @@ "use strict";

exports.default = useMergeState;
var _react = require("react");
/**
* Updates state, partial updates are merged into existing state values
*/
function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
/**

@@ -27,18 +27,12 @@ * Mimics a React class component's state model, of having a single unified

function useMergeState(initialState) {
var _useState = (0, _react.useState)(initialState),
state = _useState[0],
setState = _useState[1];
var updater = (0, _react.useCallback)(function (update) {
const [state, setState] = (0, _react.useState)(initialState);
const updater = (0, _react.useCallback)(update => {
if (update === null) return;
if (typeof update === 'function') {
setState(function (state) {
var nextState = update(state);
return nextState == null ? state : _extends({}, state, nextState);
setState(state => {
const nextState = update(state);
return nextState == null ? state : Object.assign({}, state, nextState);
});
} else {
setState(function (state) {
return _extends({}, state, update);
});
setState(state => Object.assign({}, state, update));
}

@@ -45,0 +39,0 @@ }, [setState]);

import { MergeStateSetter } from './useMergeState';
declare type Mapper<TProps, TState> = (props: TProps, state: TState) => null | Partial<TState>;
export default function useMergeStateFromProps<TProps, TState>(props: TProps, gDSFP: Mapper<TProps, TState>, initialState: TState): [TState, MergeStateSetter<TState>];
type Mapper<TProps, TState> = (props: TProps, state: TState) => null | Partial<TState>;
export default function useMergeStateFromProps<TProps, TState extends {}>(props: TProps, gDSFP: Mapper<TProps, TState>, initialState: TState): [TState, MergeStateSetter<TState>];
export {};

@@ -5,15 +5,9 @@ "use strict";

exports.default = useMergeStateFromProps;
var _useMergeState2 = _interopRequireDefault(require("./useMergeState"));
var _useMergeState = _interopRequireDefault(require("./useMergeState"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function useMergeStateFromProps(props, gDSFP, initialState) {
var _useMergeState = (0, _useMergeState2.default)(initialState),
state = _useMergeState[0],
setState = _useMergeState[1];
var nextState = gDSFP(props, state);
const [state, setState] = (0, _useMergeState.default)(initialState);
const nextState = gDSFP(props, state);
if (nextState !== null) setState(nextState);
return [state, setState];
}

@@ -5,5 +5,3 @@ "use strict";

exports.default = useMounted;
var _react = require("react");
/**

@@ -30,9 +28,7 @@ * Track whether a component is current mounted. Generally less preferable than

function useMounted() {
var mounted = (0, _react.useRef)(true);
var isMounted = (0, _react.useRef)(function () {
return mounted.current;
});
(0, _react.useEffect)(function () {
const mounted = (0, _react.useRef)(true);
const isMounted = (0, _react.useRef)(() => mounted.current);
(0, _react.useEffect)(() => {
mounted.current = true;
return function () {
return () => {
mounted.current = false;

@@ -39,0 +35,0 @@ };

@@ -5,5 +5,3 @@ "use strict";

exports.default = void 0;
var _react = require("react");
/**

@@ -29,4 +27,3 @@ * Run's an effect on mount, and is cleaned up on unmount. Generally

}
var _default = useMountEffect;
exports.default = _default;

@@ -5,22 +5,12 @@ "use strict";

exports.default = void 0;
var _useCustomEffect = _interopRequireDefault(require("./useCustomEffect"));
var _dequal = require("dequal");
var _useImmediateUpdateEffect = _interopRequireDefault(require("./useImmediateUpdateEffect"));
var _useEventCallback = _interopRequireDefault(require("./useEventCallback"));
var _react = require("react");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function isDepsEqual(_ref, _ref2) {
var nextElement = _ref[0],
nextConfig = _ref[1];
var prevElement = _ref2[0],
prevConfig = _ref2[1];
function isDepsEqual([nextElement, nextConfig], [prevElement, prevConfig]) {
return nextElement === prevElement && (0, _dequal.dequal)(nextConfig, prevConfig);
}
/**

@@ -47,18 +37,33 @@ * Observe mutations on a DOM node or tree of DOM nodes.

/**
* Observe mutations on a DOM node or tree of DOM nodes.
* use a `MutationObserver` and return records as the are received.
*
* ```tsx
* const [element, attachRef] = useCallbackRef(null);
*
* const records = useMutationObserver(element, { subtree: true });
*
* return (
* <div ref={attachRef} />
* )
* ```
*
* @param element The DOM element to observe
* @param config The observer configuration
*/
function useMutationObserver(element, config, callback) {
var _useState = (0, _react.useState)(null),
records = _useState[0],
setRecords = _useState[1];
const [records, setRecords] = (0, _react.useState)(null);
const handler = (0, _useEventCallback.default)(callback || setRecords);
(0, _useCustomEffect.default)(() => {
if (!element) return;
var handler = (0, _useEventCallback.default)(callback || setRecords);
(0, _useCustomEffect.default)(function () {
if (!element) return; // The behavior around reusing mutation observers is confusing
// The behavior around reusing mutation observers is confusing
// observing again _should_ disable the last listener but doesn't
// seem to always be the case, maybe just in JSDOM? In any case the cost
// to redeclaring it is gonna be fairly low anyway, so make it simple
var observer = new MutationObserver(handler);
const observer = new MutationObserver(handler);
observer.observe(element, config);
return function () {
return () => {
observer.disconnect();

@@ -74,4 +79,3 @@ };

}
var _default = useMutationObserver;
exports.default = _default;

@@ -5,5 +5,3 @@ "use strict";

exports.default = usePrevious;
var _react = require("react");
/**

@@ -27,4 +25,4 @@ * Store the last of some value. Tracked via a `Ref` only updating it

function usePrevious(value) {
var ref = (0, _react.useRef)(null);
(0, _react.useEffect)(function () {
const ref = (0, _react.useRef)(null);
(0, _react.useEffect)(() => {
ref.current = value;

@@ -31,0 +29,0 @@ });

@@ -5,26 +5,16 @@ "use strict";

exports.default = void 0;
var _react = require("react");
var _useCommittedRef = _interopRequireDefault(require("./useCommittedRef"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function useRafInterval(fn, ms, paused) {
if (paused === void 0) {
paused = false;
}
var handle;
var start = new Date().getTime();
var fnRef = (0, _useCommittedRef.default)(fn); // this ref is necessary b/c useEffect will sometimes miss a paused toggle
function useRafInterval(fn, ms, paused = false) {
let handle;
let start = new Date().getTime();
const fnRef = (0, _useCommittedRef.default)(fn);
// this ref is necessary b/c useEffect will sometimes miss a paused toggle
// orphaning a setTimeout chain in the aether, so relying on it's refresh logic is not reliable.
var pausedRef = (0, _useCommittedRef.default)(paused);
const pausedRef = (0, _useCommittedRef.default)(paused);
function loop() {
var current = new Date().getTime();
var delta = current - start;
const current = new Date().getTime();
const delta = current - start;
if (pausedRef.current) return;
if (delta >= ms && fnRef.current) {

@@ -34,16 +24,11 @@ fnRef.current();

}
cancelAnimationFrame(handle);
handle = requestAnimationFrame(loop);
}
(0, _react.useEffect)(function () {
(0, _react.useEffect)(() => {
handle = requestAnimationFrame(loop);
return function () {
return cancelAnimationFrame(handle);
};
return () => cancelAnimationFrame(handle);
}, []);
}
var _default = useRafInterval;
exports.default = _default;
/// <reference types="react" />
/**
* Exactly the same as `useRef` except that the initial value is set via a
* factroy function. Useful when the default is relatively costly to construct.
* factory function. Useful when the default is relatively costly to construct.
*

@@ -6,0 +6,0 @@ * ```ts

@@ -5,9 +5,8 @@ "use strict";

exports.default = useRefWithInitialValueFactory;
var _react = require("react");
const dft = Symbol('default value sigil');
var dft = Symbol('default value sigil');
/**
* Exactly the same as `useRef` except that the initial value is set via a
* factroy function. Useful when the default is relatively costly to construct.
* factory function. Useful when the default is relatively costly to construct.
*

@@ -22,11 +21,8 @@ * ```ts

*/
function useRefWithInitialValueFactory(initialValueFactory) {
var ref = (0, _react.useRef)(dft);
const ref = (0, _react.useRef)(dft);
if (ref.current === dft) {
ref.current = initialValueFactory();
}
return ref;
}

@@ -5,17 +5,12 @@ "use strict";

exports.default = useResizeObserver;
var _react = require("react");
var _useIsomorphicEffect = _interopRequireDefault(require("./useIsomorphicEffect"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var targetMap = new WeakMap();
var resizeObserver;
const targetMap = new WeakMap();
let resizeObserver;
function getResizeObserver() {
// eslint-disable-next-line no-return-assign
return resizeObserver = resizeObserver || new window.ResizeObserver(function (entries) {
entries.forEach(function (entry) {
var handler = targetMap.get(entry.target);
return resizeObserver = resizeObserver || new window.ResizeObserver(entries => {
entries.forEach(entry => {
const handler = targetMap.get(entry.target);
if (handler) handler(entry.contentRect);

@@ -25,2 +20,3 @@ });

}
/**

@@ -44,17 +40,12 @@ * Efficiently observe size changes on an element. Depends on the `ResizeObserver` api,

*/
function useResizeObserver(element) {
var _useState = (0, _react.useState)(null),
rect = _useState[0],
setRect = _useState[1];
(0, _useIsomorphicEffect.default)(function () {
const [rect, setRect] = (0, _react.useState)(null);
(0, _useIsomorphicEffect.default)(() => {
if (!element) return;
getResizeObserver().observe(element);
setRect(element.getBoundingClientRect());
targetMap.set(element, function (rect) {
targetMap.set(element, rect => {
setRect(rect);
});
return function () {
return () => {
targetMap.delete(element);

@@ -61,0 +52,0 @@ };

import { Dispatch, SetStateAction } from 'react';
import { AsyncSetState } from './useStateAsync';
declare type StateSetter<TState> = Dispatch<SetStateAction<TState>>;
type StateSetter<TState> = Dispatch<SetStateAction<TState>>;
/**

@@ -5,0 +5,0 @@ * `useSafeState` takes the return value of a `useState` hook and wraps the

@@ -5,12 +5,20 @@ "use strict";

exports.default = void 0;
var _react = require("react");
var _useMounted = _interopRequireDefault(require("./useMounted"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* `useSafeState` takes the return value of a `useState` hook and wraps the
* setter to prevent updates onces the component has unmounted. Can used
* with `useMergeState` and `useStateAsync` as well
*
* @param state The return value of a useStateHook
*
* ```ts
* const [show, setShow] = useSafeState(useState(true));
* ```
*/
function useSafeState(state) {
var isMounted = (0, _useMounted.default)();
return [state[0], (0, _react.useCallback)(function (nextState) {
const isMounted = (0, _useMounted.default)();
return [state[0], (0, _react.useCallback)(nextState => {
if (!isMounted()) return;

@@ -20,4 +28,3 @@ return state[1](nextState);

}
var _default = useSafeState;
exports.default = _default;

@@ -5,60 +5,28 @@ "use strict";

exports.default = exports.ObservableSet = void 0;
var _useForceUpdate = _interopRequireDefault(require("./useForceUpdate"));
var _useStableMemo = _interopRequireDefault(require("./useStableMemo"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
function _wrapNativeSuper(Class) { var _cache = typeof Map === "function" ? new Map() : undefined; _wrapNativeSuper = function _wrapNativeSuper(Class) { if (Class === null || !_isNativeFunction(Class)) return Class; if (typeof Class !== "function") { throw new TypeError("Super expression must either be null or a function"); } if (typeof _cache !== "undefined") { if (_cache.has(Class)) return _cache.get(Class); _cache.set(Class, Wrapper); } function Wrapper() { return _construct(Class, arguments, _getPrototypeOf(this).constructor); } Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true } }); return _setPrototypeOf(Wrapper, Class); }; return _wrapNativeSuper(Class); }
function _construct(Parent, args, Class) { if (_isNativeReflectConstruct()) { _construct = Reflect.construct; } else { _construct = function _construct(Parent, args, Class) { var a = [null]; a.push.apply(a, args); var Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) _setPrototypeOf(instance, Class.prototype); return instance; }; } return _construct.apply(null, arguments); }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
function _isNativeFunction(fn) { return Function.toString.call(fn).indexOf("[native code]") !== -1; }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
var ObservableSet = /*#__PURE__*/function (_Set) {
_inheritsLoose(ObservableSet, _Set);
function ObservableSet(listener, init) {
var _this;
_this = _Set.call(this, init) || this;
_this.listener = listener;
return _this;
class ObservableSet extends Set {
constructor(listener, init) {
super(init);
this.listener = listener;
}
var _proto = ObservableSet.prototype;
_proto.add = function add(value) {
_Set.prototype.add.call(this, value); // When initializing the Set, the base Set calls this.add() before the
add(value) {
super.add(value);
// When initializing the Set, the base Set calls this.add() before the
// listener is assigned so it will be undefined
if (this.listener) this.listener(this);
return this;
};
_proto.delete = function _delete(value) {
var result = _Set.prototype.delete.call(this, value);
}
delete(value) {
const result = super.delete(value);
this.listener(this);
return result;
};
_proto.clear = function clear() {
_Set.prototype.clear.call(this);
}
clear() {
super.clear();
this.listener(this);
};
}
}
return ObservableSet;
}( /*#__PURE__*/_wrapNativeSuper(Set));
/**

@@ -83,14 +51,8 @@ * Create and return a [Set](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set) that triggers rerenders when it's updated.

*/
exports.ObservableSet = ObservableSet;
function useSet(init) {
var forceUpdate = (0, _useForceUpdate.default)();
return (0, _useStableMemo.default)(function () {
return new ObservableSet(forceUpdate, init);
}, []);
const forceUpdate = (0, _useForceUpdate.default)();
return (0, _useStableMemo.default)(() => new ObservableSet(forceUpdate, init), []);
}
var _default = useSet;
exports.default = _default;

@@ -5,9 +5,6 @@ "use strict";

exports.default = useStableMemo;
var _react = require("react");
function isEqual(a, b) {
if (a.length !== b.length) return false;
for (var i = 0; i < a.length; i++) {
for (let i = 0; i < a.length; i++) {
if (a[i] !== b[i]) {

@@ -17,6 +14,4 @@ return false;

}
return true;
}
/**

@@ -31,21 +26,21 @@ * Identical to `useMemo` _except_ that it provides a semantic guarantee that

function useStableMemo(factory, deps) {
var isValid = true;
var valueRef = (0, _react.useRef)(); // initial hook call
let isValid = true;
const valueRef = (0, _react.useRef)();
// initial hook call
if (!valueRef.current) {
valueRef.current = {
deps: deps,
deps,
result: factory()
}; // subsequent calls
};
// subsequent calls
} else {
isValid = !!(deps && valueRef.current.deps && isEqual(deps, valueRef.current.deps));
}
var cache = isValid ? valueRef.current : {
deps: deps,
const cache = isValid ? valueRef.current : {
deps,
result: factory()
}; // must update immediately so any sync renders here don't cause an infinite loop
};
// must update immediately so any sync renders here don't cause an infinite loop
valueRef.current = cache;
return cache.result;
}
import React from 'react';
export declare type AsyncSetState<TState> = (stateUpdate: React.SetStateAction<TState>) => Promise<TState>;
export type AsyncSetState<TState> = (stateUpdate: React.SetStateAction<TState>) => Promise<TState>;
/**

@@ -4,0 +4,0 @@ * A hook that mirrors `useState` in function and API, expect that setState

@@ -5,5 +5,3 @@ "use strict";

exports.default = useStateAsync;
var _react = require("react");
/**

@@ -27,19 +25,14 @@ * A hook that mirrors `useState` in function and API, expect that setState

function useStateAsync(initialState) {
var _useState = (0, _react.useState)(initialState),
state = _useState[0],
setState = _useState[1];
var resolvers = (0, _react.useRef)([]);
(0, _react.useEffect)(function () {
resolvers.current.forEach(function (resolve) {
return resolve(state);
});
const [state, setState] = (0, _react.useState)(initialState);
const resolvers = (0, _react.useRef)([]);
(0, _react.useEffect)(() => {
resolvers.current.forEach(resolve => resolve(state));
resolvers.current.length = 0;
}, [state]);
var setStateAsync = (0, _react.useCallback)(function (update) {
return new Promise(function (resolve, reject) {
setState(function (prevState) {
const setStateAsync = (0, _react.useCallback)(update => {
return new Promise((resolve, reject) => {
setState(prevState => {
try {
var nextState; // ugly instanceof for typescript
let nextState;
// ugly instanceof for typescript
if (update instanceof Function) {

@@ -49,7 +42,7 @@ nextState = update(prevState);

nextState = update;
} // If state does not change, we must resolve the promise because
}
// If state does not change, we must resolve the promise because
// react won't re-render and effect will not resolve. If there are already
// resolvers queued, then it should be safe to assume an update will happen
if (!resolvers.current.length && Object.is(nextState, prevState)) {

@@ -60,3 +53,2 @@ resolve(nextState);

}
return nextState;

@@ -63,0 +55,0 @@ } catch (e) {

import { SyntheticEvent } from 'react';
export declare type ThrottledHandler<TEvent> = ((event: TEvent) => void) & {
export type ThrottledHandler<TEvent> = ((event: TEvent) => void) & {
clear(): void;

@@ -34,2 +34,2 @@ };

*/
export default function useThrottledEventHandler<TEvent = SyntheticEvent>(handler: (event: TEvent) => void): ThrottledHandler<TEvent>;
export default function useThrottledEventHandler<TEvent extends object = SyntheticEvent>(handler: (event: TEvent) => void): ThrottledHandler<TEvent>;

@@ -5,17 +5,7 @@ "use strict";

exports.default = useThrottledEventHandler;
var _react = require("react");
var _useMounted = _interopRequireDefault(require("./useMounted"));
var _useEventCallback = _interopRequireDefault(require("./useEventCallback"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
var isSyntheticEvent = function isSyntheticEvent(event) {
return typeof event.persist === 'function';
};
const isSyntheticEvent = event => typeof event.persist === 'function';
/**

@@ -51,17 +41,16 @@ * Creates a event handler function throttled by `requestAnimationFrame` that

function useThrottledEventHandler(handler) {
var isMounted = (0, _useMounted.default)();
var eventHandler = (0, _useEventCallback.default)(handler);
var nextEventInfoRef = (0, _react.useRef)({
const isMounted = (0, _useMounted.default)();
const eventHandler = (0, _useEventCallback.default)(handler);
const nextEventInfoRef = (0, _react.useRef)({
event: null,
handle: null
});
var clear = function clear() {
const clear = () => {
cancelAnimationFrame(nextEventInfoRef.current.handle);
nextEventInfoRef.current.handle = null;
};
var handlePointerMoveAnimation = function handlePointerMoveAnimation() {
var next = nextEventInfoRef.current;
const handlePointerMoveAnimation = () => {
const {
current: next
} = nextEventInfoRef;
if (next.handle && next.event) {

@@ -73,19 +62,15 @@ if (isMounted()) {

}
next.event = null;
};
var throttledHandler = function throttledHandler(event) {
const throttledHandler = event => {
if (!isMounted()) return;
if (isSyntheticEvent(event)) {
event.persist();
} // Special handling for a React.Konva event which reuses the
}
// Special handling for a React.Konva event which reuses the
// event object as it bubbles, setting target
else if ('evt' in event) {
event = _extends({}, event);
}
event = Object.assign({}, event);
}
nextEventInfoRef.current.event = event;
if (!nextEventInfoRef.current.handle) {

@@ -95,5 +80,4 @@ nextEventInfoRef.current.handle = requestAnimationFrame(handlePointerMoveAnimation);

};
throttledHandler.clear = clear;
return throttledHandler;
}

@@ -5,11 +5,6 @@ "use strict";

exports.default = useTimeout;
var _react = require("react");
var _useMounted = _interopRequireDefault(require("./useMounted"));
var _useWillUnmount = _interopRequireDefault(require("./useWillUnmount"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/*

@@ -23,10 +18,8 @@ * Browsers including Internet Explorer, Chrome, Safari, and Firefox store the

*/
var MAX_DELAY_MS = Math.pow(2, 31) - 1;
const MAX_DELAY_MS = 2 ** 31 - 1;
function setChainedTimeout(handleRef, fn, timeoutAtMs) {
var delayMs = timeoutAtMs - Date.now();
handleRef.current = delayMs <= MAX_DELAY_MS ? setTimeout(fn, delayMs) : setTimeout(function () {
return setChainedTimeout(handleRef, fn, timeoutAtMs);
}, MAX_DELAY_MS);
const delayMs = timeoutAtMs - Date.now();
handleRef.current = delayMs <= MAX_DELAY_MS ? setTimeout(fn, delayMs) : setTimeout(() => setChainedTimeout(handleRef, fn, timeoutAtMs), MAX_DELAY_MS);
}
/**

@@ -50,24 +43,13 @@ * Returns a controller object for setting a timeout that is properly cleaned up

*/
function useTimeout() {
var isMounted = (0, _useMounted.default)(); // types are confused between node and web here IDK
const isMounted = (0, _useMounted.default)();
var handleRef = (0, _react.useRef)();
(0, _useWillUnmount.default)(function () {
return clearTimeout(handleRef.current);
});
return (0, _react.useMemo)(function () {
var clear = function clear() {
return clearTimeout(handleRef.current);
};
function set(fn, delayMs) {
if (delayMs === void 0) {
delayMs = 0;
}
// types are confused between node and web here IDK
const handleRef = (0, _react.useRef)();
(0, _useWillUnmount.default)(() => clearTimeout(handleRef.current));
return (0, _react.useMemo)(() => {
const clear = () => clearTimeout(handleRef.current);
function set(fn, delayMs = 0) {
if (!isMounted()) return;
clear();
if (delayMs <= MAX_DELAY_MS) {

@@ -80,8 +62,7 @@ // For simplicity, if the timeout is short, just set a normal timeout.

}
return {
set: set,
clear: clear
set,
clear
};
}, []);
}

@@ -24,2 +24,2 @@ /**

*/
export default function useToggleState(initialState?: boolean): [boolean, (value?: boolean | undefined) => void];
export default function useToggleState(initialState?: boolean): [boolean, (value?: boolean) => void];

@@ -5,5 +5,3 @@ "use strict";

exports.default = useToggleState;
var _react = require("react");
/**

@@ -32,10 +30,4 @@ * Create a state setter pair for a boolean value that can be "switched".

*/
function useToggleState(initialState) {
if (initialState === void 0) {
initialState = false;
}
return (0, _react.useReducer)(function (state, action) {
return action == null ? !state : action;
}, initialState);
function useToggleState(initialState = false) {
return (0, _react.useReducer)((state, action) => action == null ? !state : action, initialState);
}

@@ -5,5 +5,3 @@ "use strict";

exports.default = useUpdatedRef;
var _react = require("react");
/**

@@ -16,5 +14,5 @@ * Returns a ref that is immediately updated with the new value

function useUpdatedRef(value) {
var valueRef = (0, _react.useRef)(value);
const valueRef = (0, _react.useRef)(value);
valueRef.current = value;
return valueRef;
}

@@ -5,5 +5,3 @@ "use strict";

exports.default = void 0;
var _react = require("react");
/**

@@ -30,4 +28,4 @@ * Runs an effect only when the dependencies have changed, skipping the

function useUpdateEffect(fn, deps) {
var isFirst = (0, _react.useRef)(true);
(0, _react.useEffect)(function () {
const isFirst = (0, _react.useRef)(true);
(0, _react.useEffect)(() => {
if (isFirst.current) {

@@ -37,8 +35,6 @@ isFirst.current = false;

}
return fn();
}, deps);
}
var _default = useUpdateEffect;
exports.default = _default;

@@ -5,11 +5,6 @@ "use strict";

exports.default = void 0;
var _react = require("react");
var _useStableMemo = _interopRequireDefault(require("./useStableMemo"));
var _useWillUnmount = _interopRequireDefault(require("./useWillUnmount"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**

@@ -32,8 +27,8 @@ * An _immediate_ effect that runs an effect callback when its dependency array

function useUpdateImmediateEffect(effect, deps) {
var firstRef = (0, _react.useRef)(true);
var tearDown = (0, _react.useRef)();
(0, _useWillUnmount.default)(function () {
const firstRef = (0, _react.useRef)(true);
const tearDown = (0, _react.useRef)();
(0, _useWillUnmount.default)(() => {
if (tearDown.current) tearDown.current();
});
(0, _useStableMemo.default)(function () {
(0, _useStableMemo.default)(() => {
if (firstRef.current) {

@@ -43,3 +38,2 @@ firstRef.current = false;

}
if (tearDown.current) tearDown.current();

@@ -49,4 +43,3 @@ tearDown.current = effect();

}
var _default = useUpdateImmediateEffect;
exports.default = _default;

@@ -5,5 +5,3 @@ "use strict";

exports.default = void 0;
var _react = require("react");
/**

@@ -30,4 +28,4 @@ * Runs a layout effect only when the dependencies have changed, skipping the

function useUpdateLayoutEffect(fn, deps) {
var isFirst = (0, _react.useRef)(true);
(0, _react.useLayoutEffect)(function () {
const isFirst = (0, _react.useRef)(true);
(0, _react.useLayoutEffect)(() => {
if (isFirst.current) {

@@ -37,8 +35,6 @@ isFirst.current = false;

}
return fn();
}, deps);
}
var _default = useUpdateLayoutEffect;
exports.default = _default;

@@ -5,9 +5,5 @@ "use strict";

exports.default = useWillUnmount;
var _useUpdatedRef = _interopRequireDefault(require("./useUpdatedRef"));
var _react = require("react");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**

@@ -20,8 +16,4 @@ * Attach a callback that fires when a component unmounts

function useWillUnmount(fn) {
var onUnmount = (0, _useUpdatedRef.default)(fn);
(0, _react.useEffect)(function () {
return function () {
return onUnmount.current();
};
}, []);
const onUnmount = (0, _useUpdatedRef.default)(fn);
(0, _react.useEffect)(() => () => onUnmount.current(), []);
}

@@ -5,3 +5,2 @@ import { useRef } from 'react';

import useWillUnmount from './useWillUnmount';
/**

@@ -33,6 +32,5 @@ * Returns a controller object for requesting and cancelling an animation freame that is properly cleaned up

export default function useAnimationFrame() {
var isMounted = useMounted();
var handle = useRef();
var cancel = function cancel() {
const isMounted = useMounted();
const handle = useRef();
const cancel = () => {
if (handle.current != null) {

@@ -42,14 +40,11 @@ cancelAnimationFrame(handle.current);

};
useWillUnmount(cancel);
return useStableMemo(function () {
return {
request: function request(cancelPrevious, fn) {
if (!isMounted()) return;
if (cancelPrevious) cancel();
handle.current = requestAnimationFrame(fn || cancelPrevious);
},
cancel: cancel
};
}, []);
return useStableMemo(() => ({
request(cancelPrevious, fn) {
if (!isMounted()) return;
if (cancelPrevious) cancel();
handle.current = requestAnimationFrame(fn || cancelPrevious);
},
cancel
}), []);
}

@@ -1,3 +0,3 @@

export declare type BreakpointDirection = 'up' | 'down' | true;
export declare type BreakpointMap<TKey extends string> = Partial<Record<TKey, BreakpointDirection>>;
export type BreakpointDirection = 'up' | 'down' | true;
export type BreakpointMap<TKey extends string> = Partial<Record<TKey, BreakpointDirection>>;
/**

@@ -26,11 +26,11 @@ * Create a responsive hook we a set of breakpoint names and widths.

export declare function createBreakpointHook<TKey extends string>(breakpointValues: Record<TKey, string | number>): {
(breakpointMap: BreakpointMap<TKey>, window?: Window | undefined): boolean;
(breakpoint: TKey, direction?: BreakpointDirection | undefined, window?: Window | undefined): boolean;
(breakpointMap: BreakpointMap<TKey>, window?: Window): boolean;
(breakpoint: TKey, direction?: BreakpointDirection, window?: Window): boolean;
};
export declare type DefaultBreakpoints = 'xs' | 'sm' | 'md' | 'lg' | 'xl' | 'xxl';
export declare type DefaultBreakpointMap = BreakpointMap<DefaultBreakpoints>;
export type DefaultBreakpoints = 'xs' | 'sm' | 'md' | 'lg' | 'xl' | 'xxl';
export type DefaultBreakpointMap = BreakpointMap<DefaultBreakpoints>;
declare const useBreakpoint: {
(breakpointMap: Partial<Record<DefaultBreakpoints, BreakpointDirection>>, window?: Window | undefined): boolean;
(breakpoint: DefaultBreakpoints, direction?: BreakpointDirection | undefined, window?: Window | undefined): boolean;
(breakpointMap: Partial<Record<DefaultBreakpoints, BreakpointDirection>>, window?: Window): boolean;
(breakpoint: DefaultBreakpoints, direction?: BreakpointDirection, window?: Window): boolean;
};
export default useBreakpoint;
import useMediaQuery from './useMediaQuery';
import { useMemo } from 'react';
/**

@@ -27,4 +26,3 @@ * Create a responsive hook we a set of breakpoint names and widths.

export function createBreakpointHook(breakpointValues) {
var names = Object.keys(breakpointValues);
const names = Object.keys(breakpointValues);
function and(query, next) {

@@ -34,26 +32,21 @@ if (query === next) {

}
return query ? query + " and " + next : next;
return query ? `${query} and ${next}` : next;
}
function getNext(breakpoint) {
return names[Math.min(names.indexOf(breakpoint) + 1, names.length - 1)];
}
function getMaxQuery(breakpoint) {
var next = getNext(breakpoint);
var value = breakpointValues[next];
if (typeof value === 'number') value = value - 0.2 + "px";else value = "calc(" + value + " - 0.2px)";
return "(max-width: " + value + ")";
const next = getNext(breakpoint);
let value = breakpointValues[next];
if (typeof value === 'number') value = `${value - 0.2}px`;else value = `calc(${value} - 0.2px)`;
return `(max-width: ${value})`;
}
function getMinQuery(breakpoint) {
var value = breakpointValues[breakpoint];
let value = breakpointValues[breakpoint];
if (typeof value === 'number') {
value = value + "px";
value = `${value}px`;
}
return `(min-width: ${value})`;
}
return "(min-width: " + value + ")";
}
/**

@@ -75,6 +68,21 @@ * Match a set of breakpoints

/**
* Match a single breakpoint exactly, up, or down.
*
* ```tsx
* const PhoneOnly = () => {
* const isSmall = useBreakpoint('sm', 'down');
*
* if (isSmall) return <div>On a Small Screen!</div>
* return null;
* }
* ```
*
* @param breakpoint The breakpoint key
* @param direction A direction 'up' for a max, 'down' for min, true to match only the breakpoint
* @param window Optionally specify the target window to match against (useful when rendering into iframes)
*/
function useBreakpoint(breakpointOrMap, direction, window) {
var breakpointMap;
let breakpointMap;
if (typeof breakpointOrMap === 'object') {

@@ -85,30 +93,21 @@ breakpointMap = breakpointOrMap;

} else {
var _breakpointMap;
direction = direction || true;
breakpointMap = (_breakpointMap = {}, _breakpointMap[breakpointOrMap] = direction, _breakpointMap);
breakpointMap = {
[breakpointOrMap]: direction
};
}
var query = useMemo(function () {
return Object.entries(breakpointMap).reduce(function (query, _ref) {
var key = _ref[0],
direction = _ref[1];
if (direction === 'up' || direction === true) {
query = and(query, getMinQuery(key));
}
if (direction === 'down' || direction === true) {
query = and(query, getMaxQuery(key));
}
return query;
}, '');
}, [JSON.stringify(breakpointMap)]);
let query = useMemo(() => Object.entries(breakpointMap).reduce((query, [key, direction]) => {
if (direction === 'up' || direction === true) {
query = and(query, getMinQuery(key));
}
if (direction === 'down' || direction === true) {
query = and(query, getMaxQuery(key));
}
return query;
}, ''), [JSON.stringify(breakpointMap)]);
return useMediaQuery(query, window);
}
return useBreakpoint;
}
var useBreakpoint = createBreakpointHook({
const useBreakpoint = createBreakpointHook({
xs: 0,

@@ -115,0 +114,0 @@ sm: 576,

import { useState } from 'react';
/**

@@ -26,5 +27,4 @@ * A convenience hook around `useState` designed to be paired with

*/
export default function useCallbackRef() {
return useState(null);
}
import { useEffect, useRef } from 'react';
/**

@@ -11,6 +12,5 @@ * Creates a `Ref` whose value is updated in an effect, ensuring the most recent

*/
function useCommittedRef(value) {
var ref = useRef(value);
useEffect(function () {
const ref = useRef(value);
useEffect(() => {
ref.current = value;

@@ -20,3 +20,2 @@ }, [value]);

}
export default useCommittedRef;
import { DependencyList, EffectCallback } from 'react';
export declare type EffectHook = (effect: EffectCallback, deps?: DependencyList) => void;
export declare type IsEqual<TDeps extends DependencyList> = (nextDeps: TDeps, prevDeps: TDeps) => boolean;
export declare type CustomEffectOptions<TDeps extends DependencyList> = {
export type EffectHook = (effect: EffectCallback, deps?: DependencyList) => void;
export type IsEqual<TDeps extends DependencyList> = (nextDeps: TDeps, prevDeps: TDeps) => boolean;
export type CustomEffectOptions<TDeps extends DependencyList> = {
isEqual: IsEqual<TDeps>;

@@ -6,0 +6,0 @@ effectHook?: EffectHook;

import { useRef, useEffect, useDebugValue } from 'react';
import useMounted from './useMounted';
/**
* a useEffect() hook with customized depedency comparision
*
* @param effect The effect callback
* @param dependencies A list of dependencies
* @param isEqual A function comparing the next and previous dependencyLists
*/
/**
* a useEffect() hook with customized depedency comparision
*
* @param effect The effect callback
* @param dependencies A list of dependencies
* @param options
* @param options.isEqual A function comparing the next and previous dependencyLists
* @param options.effectHook the underlying effect hook used, defaults to useEffect
*/
function useCustomEffect(effect, dependencies, isEqualOrOptions) {
var isMounted = useMounted();
var _ref = typeof isEqualOrOptions === 'function' ? {
const isMounted = useMounted();
const {
isEqual,
effectHook = useEffect
} = typeof isEqualOrOptions === 'function' ? {
isEqual: isEqualOrOptions
} : isEqualOrOptions,
isEqual = _ref.isEqual,
_ref$effectHook = _ref.effectHook,
effectHook = _ref$effectHook === void 0 ? useEffect : _ref$effectHook;
var dependenciesRef = useRef();
} : isEqualOrOptions;
const dependenciesRef = useRef();
dependenciesRef.current = dependencies;
var cleanupRef = useRef(null);
effectHook(function () {
const cleanupRef = useRef(null);
effectHook(() => {
// If the ref the is `null` it's either the first effect or the last effect

@@ -22,9 +38,7 @@ // ran and was cleared, meaning _this_ update should run, b/c the equality

if (cleanupRef.current === null) {
var cleanup = effect();
cleanupRef.current = function () {
const cleanup = effect();
cleanupRef.current = () => {
if (isMounted() && isEqual(dependenciesRef.current, dependencies)) {
return;
}
cleanupRef.current = null;

@@ -34,3 +48,2 @@ if (cleanup) cleanup();

}
return cleanupRef.current;

@@ -40,3 +53,2 @@ });

}
export default useCustomEffect;
import { useCallback } from 'react';
import useTimeout from './useTimeout';
/**

@@ -10,14 +11,9 @@ * Creates a debounced function that will invoke the input function after the

*/
export default function useDebouncedCallback(fn, delay) {
var timeout = useTimeout();
return useCallback(function () {
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
timeout.set(function () {
fn.apply(void 0, args);
const timeout = useTimeout();
return useCallback((...args) => {
timeout.set(() => {
fn(...args);
}, delay);
}, [fn, delay]);
}
import { useState } from 'react';
import useDebouncedCallback from './useDebouncedCallback';
/**

@@ -16,10 +17,6 @@ * Similar to `useState`, except the setter function is debounced by

*/
export default function useDebouncedState(initialState, delay) {
var _useState = useState(initialState),
state = _useState[0],
setState = _useState[1];
var debouncedSetState = useDebouncedCallback(setState, delay);
const [state, setState] = useState(initialState);
const debouncedSetState = useDebouncedCallback(setState, delay);
return [state, debouncedSetState];
}
import { useEffect, useDebugValue } from 'react';
import useDebouncedState from './useDebouncedState';
/**

@@ -12,14 +13,6 @@ * Debounce a value change by a specified number of milliseconds. Useful

*/
function useDebouncedValue(value, delayMs) {
if (delayMs === void 0) {
delayMs = 500;
}
var _useDebouncedState = useDebouncedState(value, delayMs),
debouncedValue = _useDebouncedState[0],
setDebouncedValue = _useDebouncedState[1];
function useDebouncedValue(value, delayMs = 500) {
const [debouncedValue, setDebouncedValue] = useDebouncedState(value, delayMs);
useDebugValue(debouncedValue);
useEffect(function () {
useEffect(() => {
setDebouncedValue(value);

@@ -29,3 +22,2 @@ }, [value, delayMs]);

}
export default useDebouncedValue;
import { useCallback } from 'react';
import useCommittedRef from './useCommittedRef';
export default function useEventCallback(fn) {
var ref = useCommittedRef(fn);
return useCallback(function () {
return ref.current && ref.current.apply(ref, arguments);
const ref = useCommittedRef(fn);
return useCallback(function (...args) {
return ref.current && ref.current(...args);
}, [ref]);
}

@@ -1,2 +0,2 @@

declare type EventHandler<T, K extends keyof DocumentEventMap> = (this: T, ev: DocumentEventMap[K]) => any;
type EventHandler<T, K extends keyof DocumentEventMap> = (this: T, ev: DocumentEventMap[K]) => any;
/**

@@ -3,0 +3,0 @@ * Attaches an event handler outside directly to specified DOM element

import { useEffect } from 'react';
import useEventCallback from './useEventCallback';
/**

@@ -13,15 +12,9 @@ * Attaches an event handler outside directly to specified DOM element

*/
export default function useEventListener(eventTarget, event, listener, capture) {
if (capture === void 0) {
capture = false;
}
var handler = useEventCallback(listener);
useEffect(function () {
var target = typeof eventTarget === 'function' ? eventTarget() : eventTarget;
export default function useEventListener(eventTarget, event, listener, capture = false) {
const handler = useEventCallback(listener);
useEffect(() => {
const target = typeof eventTarget === 'function' ? eventTarget() : eventTarget;
target.addEventListener(event, handler, capture);
return function () {
return target.removeEventListener(event, handler, capture);
};
return () => target.removeEventListener(event, handler, capture);
}, [eventTarget]);
}
import { useCallback, useMemo, useRef } from 'react';
import useEventCallback from './useEventCallback';
import useMounted from './useMounted';
/**

@@ -31,36 +30,41 @@ * useFocusManager provides a way to track and manage focus as it moves around

export default function useFocusManager(opts) {
var isMounted = useMounted();
var lastFocused = useRef();
var handle = useRef();
var willHandle = useEventCallback(opts.willHandle);
var didHandle = useEventCallback(opts.didHandle);
var onChange = useEventCallback(opts.onChange);
var isDisabled = useEventCallback(opts.isDisabled);
var handleFocusChange = useCallback(function (focused, event) {
const isMounted = useMounted();
const lastFocused = useRef();
const handle = useRef();
const willHandle = useEventCallback(opts.willHandle);
const didHandle = useEventCallback(opts.didHandle);
const onChange = useEventCallback(opts.onChange);
const isDisabled = useEventCallback(opts.isDisabled);
const handleChange = useCallback((focused, event) => {
if (focused !== lastFocused.current) {
didHandle == null ? void 0 : didHandle(focused, event);
// only fire a change when unmounted if its a blur
if (isMounted() || !focused) {
lastFocused.current = focused;
onChange == null ? void 0 : onChange(focused, event);
}
}
}, [isMounted, didHandle, onChange, lastFocused]);
const handleFocusChange = useCallback((focused, event) => {
if (isDisabled()) return;
if (event && event.persist) event.persist();
if (willHandle && willHandle(focused, event) === false) return;
if ((willHandle == null ? void 0 : willHandle(focused, event)) === false) {
return;
}
clearTimeout(handle.current);
handle.current = window.setTimeout(function () {
if (focused !== lastFocused.current) {
if (didHandle) didHandle(focused, event); // only fire a change when unmounted if its a blur
if (isMounted() || !focused) {
lastFocused.current = focused;
onChange && onChange(focused, event);
}
}
});
}, [isMounted, willHandle, didHandle, onChange, lastFocused]);
var handleBlur = useCallback(function (event) {
if (!isDisabled()) handleFocusChange(false, event);
}, [handleFocusChange, isDisabled]);
var handleFocus = useCallback(function (event) {
if (!isDisabled()) handleFocusChange(true, event);
}, [handleFocusChange, isDisabled]);
return useMemo(function () {
return {
onBlur: handleBlur,
onFocus: handleFocus
};
}, [handleBlur, handleFocus]);
if (focused) {
handleChange(focused, event);
} else {
handle.current = window.setTimeout(() => handleChange(focused, event));
}
}, [willHandle, handleChange]);
return useMemo(() => ({
onBlur: event => {
handleFocusChange(false, event);
},
onFocus: event => {
handleFocusChange(true, event);
}
}), [handleFocusChange]);
}
import { useReducer } from 'react';
/**

@@ -18,12 +19,7 @@ * Returns a function that triggers a component update. the hook equivalent to

*/
export default function useForceUpdate() {
// The toggling state value is designed to defeat React optimizations for skipping
// updates when they are stricting equal to the last state value
var _useReducer = useReducer(function (state) {
return !state;
}, false),
dispatch = _useReducer[1];
// updates when they are strictly equal to the last state value
const [, dispatch] = useReducer(state => !state, false);
return dispatch;
}

@@ -1,2 +0,2 @@

declare type DocumentEventHandler<K extends keyof DocumentEventMap> = (this: Document, ev: DocumentEventMap[K]) => any;
type DocumentEventHandler<K extends keyof DocumentEventMap> = (this: Document, ev: DocumentEventMap[K]) => any;
/**

@@ -3,0 +3,0 @@ * Attaches an event handler outside directly to the `document`,

import useEventListener from './useEventListener';
import { useCallback } from 'react';
/**

@@ -18,11 +17,5 @@ * Attaches an event handler outside directly to the `document`,

*/
export default function useGlobalListener(event, handler, capture) {
if (capture === void 0) {
capture = false;
}
var documentTarget = useCallback(function () {
return document;
}, []);
export default function useGlobalListener(event, handler, capture = false) {
const documentTarget = useCallback(() => document, []);
return useEventListener(documentTarget, event, handler, capture);
}

@@ -1,2 +0,2 @@

declare type State = {
type State = {
image: HTMLImageElement | null;

@@ -3,0 +3,0 @@ error: unknown | null;

import { useState, useEffect } from 'react';
/**

@@ -29,13 +28,9 @@ * Fetch and load an image for programatic use such as in a `<canvas>` element.

export default function useImage(imageOrUrl, crossOrigin) {
var _useState = useState({
const [state, setState] = useState({
image: null,
error: null
}),
state = _useState[0],
setState = _useState[1];
useEffect(function () {
});
useEffect(() => {
if (!imageOrUrl) return undefined;
var image;
let image;
if (typeof imageOrUrl === 'string') {

@@ -47,6 +42,5 @@ image = new Image();

image = imageOrUrl;
if (image.complete && image.naturalHeight > 0) {
setState({
image: image,
image,
error: null

@@ -57,20 +51,17 @@ });

}
function onLoad() {
setState({
image: image,
image,
error: null
});
}
function onError(error) {
setState({
image: image,
error: error
image,
error
});
}
image.addEventListener('load', onLoad);
image.addEventListener('error', onError);
return function () {
return () => {
image.removeEventListener('load', onLoad);

@@ -77,0 +68,0 @@ image.removeEventListener('error', onError);

@@ -5,2 +5,3 @@ import { useState } from 'react';

import useEventCallback from './useEventCallback';
/**

@@ -18,6 +19,20 @@ * Setup an [`IntersectionObserver`](https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserver) on

/**
* Setup an [`IntersectionObserver`](https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserver) on
* a DOM Element. This overload does not trigger component updates when receiving new
* entries. This allows for finer grained performance optimizations by the consumer.
*
* @param element The DOM element to observe
* @param callback A listener for intersection updates.
* @param init IntersectionObserver options with a notable change,
* unlike a plain IntersectionObserver `root: null` means "not provided YET",
* and the hook will wait until it receives a non-null value to set up the observer.
* This change allows for easier syncing of element and root values in a React
* context.
*
*/
function useIntersectionObserver(element, callbackOrOptions, maybeOptions) {
var callback;
var options;
let callback;
let options;
if (typeof callbackOrOptions === 'function') {

@@ -29,25 +44,20 @@ callback = callbackOrOptions;

}
const {
threshold,
root,
rootMargin
} = options;
const [entries, setEntry] = useState(null);
const handler = useEventCallback(callback || setEntry);
var _options = options,
threshold = _options.threshold,
root = _options.root,
rootMargin = _options.rootMargin;
var _useState = useState(null),
entries = _useState[0],
setEntry = _useState[1];
var handler = useEventCallback(callback || setEntry); // We wait for element to exist before constructing
var observer = useStableMemo(function () {
return root !== null && typeof IntersectionObserver !== 'undefined' && new IntersectionObserver(handler, {
threshold: threshold,
root: root,
rootMargin: rootMargin
});
}, [handler, root, rootMargin, threshold && JSON.stringify(threshold)]);
useEffect(function () {
// We wait for element to exist before constructing
const observer = useStableMemo(() => root !== null && typeof IntersectionObserver !== 'undefined' && new IntersectionObserver(handler, {
threshold,
root,
rootMargin
}), [handler, root, rootMargin, threshold && JSON.stringify(threshold)]);
useEffect(() => {
if (!element || !observer) return;
observer.observe(element);
return function () {
return () => {
observer.unobserve(element);

@@ -58,3 +68,2 @@ };

}
export default useIntersectionObserver;
import { useEffect } from 'react';
import useCommittedRef from './useCommittedRef';
/**

@@ -19,18 +20,53 @@ * Creates a `setInterval` that is properly cleaned up when a component unmounted

function useInterval(fn, ms, paused, runImmediately) {
if (paused === void 0) {
paused = false;
}
/**
* Creates a pausable `setInterval` that is properly cleaned up when a component unmounted
*
* ```tsx
* const [paused, setPaused] = useState(false)
* const [timer, setTimer] = useState(0)
*
* useInterval(() => setTimer(i => i + 1), 1000, paused)
*
* return (
* <span>
* {timer} seconds past
*
* <button onClick={() => setPaused(p => !p)}>{paused ? 'Play' : 'Pause' }</button>
* </span>
* )
* ```
*
* @param fn an function run on each interval
* @param ms The milliseconds duration of the interval
* @param paused Whether or not the interval is currently running
*/
if (runImmediately === void 0) {
runImmediately = false;
}
/**
* Creates a pausable `setInterval` that _fires_ immediately and is
* properly cleaned up when a component unmounted
*
* ```tsx
* const [timer, setTimer] = useState(-1)
* useInterval(() => setTimer(i => i + 1), 1000, false, true)
*
* // will update to 0 on the first effect
* return <span>{timer} seconds past</span>
* ```
*
* @param fn an function run on each interval
* @param ms The milliseconds duration of the interval
* @param paused Whether or not the interval is currently running
* @param runImmediately Whether to run the function immediately on mount or unpause
* rather than waiting for the first interval to elapse
*
var handle;
var fnRef = useCommittedRef(fn); // this ref is necessary b/c useEffect will sometimes miss a paused toggle
*/
function useInterval(fn, ms, paused = false, runImmediately = false) {
let handle;
const fnRef = useCommittedRef(fn);
// this ref is necessary b/c useEffect will sometimes miss a paused toggle
// orphaning a setTimeout chain in the aether, so relying on it's refresh logic is not reliable.
var pausedRef = useCommittedRef(paused);
var tick = function tick() {
const pausedRef = useCommittedRef(paused);
const tick = () => {
if (pausedRef.current) return;

@@ -41,8 +77,7 @@ fnRef.current();

var schedule = function schedule() {
const schedule = () => {
clearTimeout(handle);
handle = setTimeout(tick, ms);
};
useEffect(function () {
useEffect(() => {
if (runImmediately) {

@@ -53,9 +88,5 @@ tick();

}
return function () {
return clearTimeout(handle);
};
return () => clearTimeout(handle);
}, [paused, runImmediately]);
}
export default useInterval;
import { useEffect } from 'react';
declare const _default: typeof useEffect;
/**

@@ -11,2 +10,3 @@ * Is `useLayoutEffect` in a DOM or React Native environment, otherwise resolves to useEffect

*/
declare const _default: typeof useEffect;
export default _default;
import { useEffect, useLayoutEffect } from 'react';
var isReactNative = typeof global !== 'undefined' && // @ts-ignore
global.navigator && // @ts-ignore
const isReactNative = typeof global !== 'undefined' &&
// @ts-ignore
global.navigator &&
// @ts-ignore
global.navigator.product === 'ReactNative';
var isDOM = typeof document !== 'undefined';
const isDOM = typeof document !== 'undefined';
/**

@@ -14,3 +17,2 @@ * Is `useLayoutEffect` in a DOM or React Native environment, otherwise resolves to useEffect

*/
export default isDOM || isReactNative ? useLayoutEffect : useEffect;

@@ -1,54 +0,26 @@

function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
function _wrapNativeSuper(Class) { var _cache = typeof Map === "function" ? new Map() : undefined; _wrapNativeSuper = function _wrapNativeSuper(Class) { if (Class === null || !_isNativeFunction(Class)) return Class; if (typeof Class !== "function") { throw new TypeError("Super expression must either be null or a function"); } if (typeof _cache !== "undefined") { if (_cache.has(Class)) return _cache.get(Class); _cache.set(Class, Wrapper); } function Wrapper() { return _construct(Class, arguments, _getPrototypeOf(this).constructor); } Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true } }); return _setPrototypeOf(Wrapper, Class); }; return _wrapNativeSuper(Class); }
function _construct(Parent, args, Class) { if (_isNativeReflectConstruct()) { _construct = Reflect.construct; } else { _construct = function _construct(Parent, args, Class) { var a = [null]; a.push.apply(a, args); var Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) _setPrototypeOf(instance, Class.prototype); return instance; }; } return _construct.apply(null, arguments); }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
function _isNativeFunction(fn) { return Function.toString.call(fn).indexOf("[native code]") !== -1; }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
import useForceUpdate from './useForceUpdate';
import useStableMemo from './useStableMemo';
export var ObservableMap = /*#__PURE__*/function (_Map) {
_inheritsLoose(ObservableMap, _Map);
function ObservableMap(listener, init) {
var _this;
_this = _Map.call(this, init) || this;
_this.listener = listener;
return _this;
export class ObservableMap extends Map {
constructor(listener, init) {
super(init);
this.listener = listener;
}
var _proto = ObservableMap.prototype;
_proto.set = function set(key, value) {
_Map.prototype.set.call(this, key, value); // When initializing the Map, the base Map calls this.set() before the
set(key, value) {
super.set(key, value);
// When initializing the Map, the base Map calls this.set() before the
// listener is assigned so it will be undefined
if (this.listener) this.listener(this);
return this;
};
_proto.delete = function _delete(key) {
var result = _Map.prototype.delete.call(this, key);
}
delete(key) {
let result = super.delete(key);
this.listener(this);
return result;
};
_proto.clear = function clear() {
_Map.prototype.clear.call(this);
}
clear() {
super.clear();
this.listener(this);
};
}
}
return ObservableMap;
}( /*#__PURE__*/_wrapNativeSuper(Map));
/**

@@ -76,10 +48,6 @@ * Create and return a [Map](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) that triggers rerenders when it's updated.

*/
function useMap(init) {
var forceUpdate = useForceUpdate();
return useStableMemo(function () {
return new ObservableMap(forceUpdate, init);
}, []);
const forceUpdate = useForceUpdate();
return useStableMemo(() => new ObservableMap(forceUpdate, init), []);
}
export default useMap;
import useEffect from './useIsomorphicEffect';
import { useState } from 'react';
var matchersByWindow = new WeakMap();
var getMatcher = function getMatcher(query, targetWindow) {
const matchersByWindow = new WeakMap();
const getMatcher = (query, targetWindow) => {
if (!query || !targetWindow) return undefined;
var matchers = matchersByWindow.get(targetWindow) || new Map();
const matchers = matchersByWindow.get(targetWindow) || new Map();
matchersByWindow.set(targetWindow, matchers);
var mql = matchers.get(query);
let mql = matchers.get(query);
if (!mql) {

@@ -16,3 +14,2 @@ mql = targetWindow.matchMedia(query);

}
return mql;

@@ -39,41 +36,23 @@ };

*/
export default function useMediaQuery(query, targetWindow) {
if (targetWindow === void 0) {
targetWindow = typeof window === 'undefined' ? undefined : window;
}
var mql = getMatcher(query, targetWindow);
var _useState = useState(function () {
return mql ? mql.matches : false;
}),
matches = _useState[0],
setMatches = _useState[1];
useEffect(function () {
var mql = getMatcher(query, targetWindow);
export default function useMediaQuery(query, targetWindow = typeof window === 'undefined' ? undefined : window) {
const mql = getMatcher(query, targetWindow);
const [matches, setMatches] = useState(() => mql ? mql.matches : false);
useEffect(() => {
let mql = getMatcher(query, targetWindow);
if (!mql) {
return setMatches(false);
}
var matchers = matchersByWindow.get(targetWindow);
var handleChange = function handleChange() {
let matchers = matchersByWindow.get(targetWindow);
const handleChange = () => {
setMatches(mql.matches);
};
mql.refCount++;
mql.addListener(handleChange);
handleChange();
return function () {
return () => {
mql.removeListener(handleChange);
mql.refCount--;
if (mql.refCount <= 0) {
matchers == null ? void 0 : matchers.delete(mql.media);
}
mql = undefined;

@@ -80,0 +59,0 @@ };

/// <reference types="react" />
declare type CallbackRef<T> = (ref: T | null) => void;
declare type Ref<T> = React.MutableRefObject<T> | CallbackRef<T>;
type CallbackRef<T> = (ref: T | null) => void;
type Ref<T> = React.MutableRefObject<T> | CallbackRef<T>;
export declare function mergeRefs<T>(refA?: Ref<T> | null, refB?: Ref<T> | null): (value: T | null) => void;

@@ -5,0 +5,0 @@ /**

import { useMemo } from 'react';
var toFnRef = function toFnRef(ref) {
return !ref || typeof ref === 'function' ? ref : function (value) {
ref.current = value;
};
const toFnRef = ref => !ref || typeof ref === 'function' ? ref : value => {
ref.current = value;
};
export function mergeRefs(refA, refB) {
var a = toFnRef(refA);
var b = toFnRef(refB);
return function (value) {
const a = toFnRef(refA);
const b = toFnRef(refB);
return value => {
if (a) a(value);

@@ -17,2 +13,3 @@ if (b) b(value);

}
/**

@@ -34,9 +31,5 @@ * Create and returns a single callback ref composed from two other Refs.

*/
function useMergedRefs(refA, refB) {
return useMemo(function () {
return mergeRefs(refA, refB);
}, [refA, refB]);
return useMemo(() => mergeRefs(refA, refB), [refA, refB]);
}
export default useMergedRefs;

@@ -1,6 +0,6 @@

declare type Updater<TState> = (state: TState) => Partial<TState> | null;
type Updater<TState> = (state: TState) => Partial<TState> | null;
/**
* Updates state, partial updates are merged into existing state values
*/
export declare type MergeStateSetter<TState> = (update: Updater<TState> | Partial<TState> | null) => void;
export type MergeStateSetter<TState> = (update: Updater<TState> | Partial<TState> | null) => void;
/**

@@ -7,0 +7,0 @@ * Mimics a React class component's state model, of having a single unified

@@ -1,6 +0,8 @@

function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
import { useCallback, useState } from 'react';
/**
* Updates state, partial updates are merged into existing state values
*/
/**
* Mimics a React class component's state model, of having a single unified

@@ -21,18 +23,12 @@ * `state` object and an updater that merges updates into the existing state, as

export default function useMergeState(initialState) {
var _useState = useState(initialState),
state = _useState[0],
setState = _useState[1];
var updater = useCallback(function (update) {
const [state, setState] = useState(initialState);
const updater = useCallback(update => {
if (update === null) return;
if (typeof update === 'function') {
setState(function (state) {
var nextState = update(state);
return nextState == null ? state : _extends({}, state, nextState);
setState(state => {
const nextState = update(state);
return nextState == null ? state : Object.assign({}, state, nextState);
});
} else {
setState(function (state) {
return _extends({}, state, update);
});
setState(state => Object.assign({}, state, update));
}

@@ -39,0 +35,0 @@ }, [setState]);

import { MergeStateSetter } from './useMergeState';
declare type Mapper<TProps, TState> = (props: TProps, state: TState) => null | Partial<TState>;
export default function useMergeStateFromProps<TProps, TState>(props: TProps, gDSFP: Mapper<TProps, TState>, initialState: TState): [TState, MergeStateSetter<TState>];
type Mapper<TProps, TState> = (props: TProps, state: TState) => null | Partial<TState>;
export default function useMergeStateFromProps<TProps, TState extends {}>(props: TProps, gDSFP: Mapper<TProps, TState>, initialState: TState): [TState, MergeStateSetter<TState>];
export {};
import useMergeState from './useMergeState';
export default function useMergeStateFromProps(props, gDSFP, initialState) {
var _useMergeState = useMergeState(initialState),
state = _useMergeState[0],
setState = _useMergeState[1];
var nextState = gDSFP(props, state);
const [state, setState] = useMergeState(initialState);
const nextState = gDSFP(props, state);
if (nextState !== null) setState(nextState);
return [state, setState];
}
import { useRef, useEffect } from 'react';
/**

@@ -22,11 +23,8 @@ * Track whether a component is current mounted. Generally less preferable than

*/
export default function useMounted() {
var mounted = useRef(true);
var isMounted = useRef(function () {
return mounted.current;
});
useEffect(function () {
const mounted = useRef(true);
const isMounted = useRef(() => mounted.current);
useEffect(() => {
mounted.current = true;
return function () {
return () => {
mounted.current = false;

@@ -33,0 +31,0 @@ };

import { useEffect } from 'react';
/**

@@ -19,7 +20,5 @@ * Run's an effect on mount, and is cleaned up on unmount. Generally

*/
function useMountEffect(effect) {
return useEffect(effect, []);
}
export default useMountEffect;

@@ -6,10 +6,6 @@ import useCustomEffect from './useCustomEffect';

import { useState } from 'react';
function isDepsEqual(_ref, _ref2) {
var nextElement = _ref[0],
nextConfig = _ref[1];
var prevElement = _ref2[0],
prevConfig = _ref2[1];
function isDepsEqual([nextElement, nextConfig], [prevElement, prevConfig]) {
return nextElement === prevElement && dequal(nextConfig, prevConfig);
}
/**

@@ -36,18 +32,33 @@ * Observe mutations on a DOM node or tree of DOM nodes.

/**
* Observe mutations on a DOM node or tree of DOM nodes.
* use a `MutationObserver` and return records as the are received.
*
* ```tsx
* const [element, attachRef] = useCallbackRef(null);
*
* const records = useMutationObserver(element, { subtree: true });
*
* return (
* <div ref={attachRef} />
* )
* ```
*
* @param element The DOM element to observe
* @param config The observer configuration
*/
function useMutationObserver(element, config, callback) {
var _useState = useState(null),
records = _useState[0],
setRecords = _useState[1];
const [records, setRecords] = useState(null);
const handler = useEventCallback(callback || setRecords);
useCustomEffect(() => {
if (!element) return;
var handler = useEventCallback(callback || setRecords);
useCustomEffect(function () {
if (!element) return; // The behavior around reusing mutation observers is confusing
// The behavior around reusing mutation observers is confusing
// observing again _should_ disable the last listener but doesn't
// seem to always be the case, maybe just in JSDOM? In any case the cost
// to redeclaring it is gonna be fairly low anyway, so make it simple
var observer = new MutationObserver(handler);
const observer = new MutationObserver(handler);
observer.observe(element, config);
return function () {
return () => {
observer.disconnect();

@@ -63,3 +74,2 @@ };

}
export default useMutationObserver;
import { useEffect, useRef } from 'react';
/**

@@ -19,6 +20,5 @@ * Store the last of some value. Tracked via a `Ref` only updating it

*/
export default function usePrevious(value) {
var ref = useRef(null);
useEffect(function () {
const ref = useRef(null);
useEffect(() => {
ref.current = value;

@@ -25,0 +25,0 @@ });

import { useEffect } from 'react';
import useCommittedRef from './useCommittedRef';
function useRafInterval(fn, ms, paused) {
if (paused === void 0) {
paused = false;
}
var handle;
var start = new Date().getTime();
var fnRef = useCommittedRef(fn); // this ref is necessary b/c useEffect will sometimes miss a paused toggle
function useRafInterval(fn, ms, paused = false) {
let handle;
let start = new Date().getTime();
const fnRef = useCommittedRef(fn);
// this ref is necessary b/c useEffect will sometimes miss a paused toggle
// orphaning a setTimeout chain in the aether, so relying on it's refresh logic is not reliable.
var pausedRef = useCommittedRef(paused);
const pausedRef = useCommittedRef(paused);
function loop() {
var current = new Date().getTime();
var delta = current - start;
const current = new Date().getTime();
const delta = current - start;
if (pausedRef.current) return;
if (delta >= ms && fnRef.current) {

@@ -25,15 +18,10 @@ fnRef.current();

}
cancelAnimationFrame(handle);
handle = requestAnimationFrame(loop);
}
useEffect(function () {
useEffect(() => {
handle = requestAnimationFrame(loop);
return function () {
return cancelAnimationFrame(handle);
};
return () => cancelAnimationFrame(handle);
}, []);
}
export default useRafInterval;
/// <reference types="react" />
/**
* Exactly the same as `useRef` except that the initial value is set via a
* factroy function. Useful when the default is relatively costly to construct.
* factory function. Useful when the default is relatively costly to construct.
*

@@ -6,0 +6,0 @@ * ```ts

import { useRef } from 'react';
var dft = Symbol('default value sigil');
const dft = Symbol('default value sigil');
/**
* Exactly the same as `useRef` except that the initial value is set via a
* factroy function. Useful when the default is relatively costly to construct.
* factory function. Useful when the default is relatively costly to construct.
*

@@ -15,11 +16,8 @@ * ```ts

*/
export default function useRefWithInitialValueFactory(initialValueFactory) {
var ref = useRef(dft);
const ref = useRef(dft);
if (ref.current === dft) {
ref.current = initialValueFactory();
}
return ref;
}
import { useState } from 'react';
import useEffect from './useIsomorphicEffect';
var targetMap = new WeakMap();
var resizeObserver;
const targetMap = new WeakMap();
let resizeObserver;
function getResizeObserver() {
// eslint-disable-next-line no-return-assign
return resizeObserver = resizeObserver || new window.ResizeObserver(function (entries) {
entries.forEach(function (entry) {
var handler = targetMap.get(entry.target);
return resizeObserver = resizeObserver || new window.ResizeObserver(entries => {
entries.forEach(entry => {
const handler = targetMap.get(entry.target);
if (handler) handler(entry.contentRect);

@@ -15,2 +14,3 @@ });

}
/**

@@ -34,17 +34,12 @@ * Efficiently observe size changes on an element. Depends on the `ResizeObserver` api,

*/
export default function useResizeObserver(element) {
var _useState = useState(null),
rect = _useState[0],
setRect = _useState[1];
useEffect(function () {
const [rect, setRect] = useState(null);
useEffect(() => {
if (!element) return;
getResizeObserver().observe(element);
setRect(element.getBoundingClientRect());
targetMap.set(element, function (rect) {
targetMap.set(element, rect => {
setRect(rect);
});
return function () {
return () => {
targetMap.delete(element);

@@ -51,0 +46,0 @@ };

import { Dispatch, SetStateAction } from 'react';
import { AsyncSetState } from './useStateAsync';
declare type StateSetter<TState> = Dispatch<SetStateAction<TState>>;
type StateSetter<TState> = Dispatch<SetStateAction<TState>>;
/**

@@ -5,0 +5,0 @@ * `useSafeState` takes the return value of a `useState` hook and wraps the

import { useCallback } from 'react';
import useMounted from './useMounted';
/**
* `useSafeState` takes the return value of a `useState` hook and wraps the
* setter to prevent updates onces the component has unmounted. Can used
* with `useMergeState` and `useStateAsync` as well
*
* @param state The return value of a useStateHook
*
* ```ts
* const [show, setShow] = useSafeState(useState(true));
* ```
*/
function useSafeState(state) {
var isMounted = useMounted();
return [state[0], useCallback(function (nextState) {
const isMounted = useMounted();
return [state[0], useCallback(nextState => {
if (!isMounted()) return;

@@ -11,3 +23,2 @@ return state[1](nextState);

}
export default useSafeState;

@@ -1,54 +0,26 @@

function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); }
function _wrapNativeSuper(Class) { var _cache = typeof Map === "function" ? new Map() : undefined; _wrapNativeSuper = function _wrapNativeSuper(Class) { if (Class === null || !_isNativeFunction(Class)) return Class; if (typeof Class !== "function") { throw new TypeError("Super expression must either be null or a function"); } if (typeof _cache !== "undefined") { if (_cache.has(Class)) return _cache.get(Class); _cache.set(Class, Wrapper); } function Wrapper() { return _construct(Class, arguments, _getPrototypeOf(this).constructor); } Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true } }); return _setPrototypeOf(Wrapper, Class); }; return _wrapNativeSuper(Class); }
function _construct(Parent, args, Class) { if (_isNativeReflectConstruct()) { _construct = Reflect.construct; } else { _construct = function _construct(Parent, args, Class) { var a = [null]; a.push.apply(a, args); var Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) _setPrototypeOf(instance, Class.prototype); return instance; }; } return _construct.apply(null, arguments); }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
function _isNativeFunction(fn) { return Function.toString.call(fn).indexOf("[native code]") !== -1; }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
import useForceUpdate from './useForceUpdate';
import useStableMemo from './useStableMemo';
export var ObservableSet = /*#__PURE__*/function (_Set) {
_inheritsLoose(ObservableSet, _Set);
function ObservableSet(listener, init) {
var _this;
_this = _Set.call(this, init) || this;
_this.listener = listener;
return _this;
export class ObservableSet extends Set {
constructor(listener, init) {
super(init);
this.listener = listener;
}
var _proto = ObservableSet.prototype;
_proto.add = function add(value) {
_Set.prototype.add.call(this, value); // When initializing the Set, the base Set calls this.add() before the
add(value) {
super.add(value);
// When initializing the Set, the base Set calls this.add() before the
// listener is assigned so it will be undefined
if (this.listener) this.listener(this);
return this;
};
_proto.delete = function _delete(value) {
var result = _Set.prototype.delete.call(this, value);
}
delete(value) {
const result = super.delete(value);
this.listener(this);
return result;
};
_proto.clear = function clear() {
_Set.prototype.clear.call(this);
}
clear() {
super.clear();
this.listener(this);
};
}
}
return ObservableSet;
}( /*#__PURE__*/_wrapNativeSuper(Set));
/**

@@ -73,10 +45,6 @@ * Create and return a [Set](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set) that triggers rerenders when it's updated.

*/
function useSet(init) {
var forceUpdate = useForceUpdate();
return useStableMemo(function () {
return new ObservableSet(forceUpdate, init);
}, []);
const forceUpdate = useForceUpdate();
return useStableMemo(() => new ObservableSet(forceUpdate, init), []);
}
export default useSet;
import { useRef } from 'react';
function isEqual(a, b) {
if (a.length !== b.length) return false;
for (var i = 0; i < a.length; i++) {
for (let i = 0; i < a.length; i++) {
if (a[i] !== b[i]) {

@@ -11,6 +9,4 @@ return false;

}
return true;
}
/**

@@ -25,21 +21,21 @@ * Identical to `useMemo` _except_ that it provides a semantic guarantee that

export default function useStableMemo(factory, deps) {
var isValid = true;
var valueRef = useRef(); // initial hook call
let isValid = true;
const valueRef = useRef();
// initial hook call
if (!valueRef.current) {
valueRef.current = {
deps: deps,
deps,
result: factory()
}; // subsequent calls
};
// subsequent calls
} else {
isValid = !!(deps && valueRef.current.deps && isEqual(deps, valueRef.current.deps));
}
var cache = isValid ? valueRef.current : {
deps: deps,
const cache = isValid ? valueRef.current : {
deps,
result: factory()
}; // must update immediately so any sync renders here don't cause an infinite loop
};
// must update immediately so any sync renders here don't cause an infinite loop
valueRef.current = cache;
return cache.result;
}
import React from 'react';
export declare type AsyncSetState<TState> = (stateUpdate: React.SetStateAction<TState>) => Promise<TState>;
export type AsyncSetState<TState> = (stateUpdate: React.SetStateAction<TState>) => Promise<TState>;
/**

@@ -4,0 +4,0 @@ * A hook that mirrors `useState` in function and API, expect that setState

import { useCallback, useEffect, useRef, useState } from 'react';
/**

@@ -21,19 +20,14 @@ * A hook that mirrors `useState` in function and API, expect that setState

export default function useStateAsync(initialState) {
var _useState = useState(initialState),
state = _useState[0],
setState = _useState[1];
var resolvers = useRef([]);
useEffect(function () {
resolvers.current.forEach(function (resolve) {
return resolve(state);
});
const [state, setState] = useState(initialState);
const resolvers = useRef([]);
useEffect(() => {
resolvers.current.forEach(resolve => resolve(state));
resolvers.current.length = 0;
}, [state]);
var setStateAsync = useCallback(function (update) {
return new Promise(function (resolve, reject) {
setState(function (prevState) {
const setStateAsync = useCallback(update => {
return new Promise((resolve, reject) => {
setState(prevState => {
try {
var nextState; // ugly instanceof for typescript
let nextState;
// ugly instanceof for typescript
if (update instanceof Function) {

@@ -43,7 +37,7 @@ nextState = update(prevState);

nextState = update;
} // If state does not change, we must resolve the promise because
}
// If state does not change, we must resolve the promise because
// react won't re-render and effect will not resolve. If there are already
// resolvers queued, then it should be safe to assume an update will happen
if (!resolvers.current.length && Object.is(nextState, prevState)) {

@@ -54,3 +48,2 @@ resolve(nextState);

}
return nextState;

@@ -57,0 +50,0 @@ } catch (e) {

import { SyntheticEvent } from 'react';
export declare type ThrottledHandler<TEvent> = ((event: TEvent) => void) & {
export type ThrottledHandler<TEvent> = ((event: TEvent) => void) & {
clear(): void;

@@ -34,2 +34,2 @@ };

*/
export default function useThrottledEventHandler<TEvent = SyntheticEvent>(handler: (event: TEvent) => void): ThrottledHandler<TEvent>;
export default function useThrottledEventHandler<TEvent extends object = SyntheticEvent>(handler: (event: TEvent) => void): ThrottledHandler<TEvent>;

@@ -1,11 +0,5 @@

function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }
import { useRef } from 'react';
import useMounted from './useMounted';
import useEventCallback from './useEventCallback';
var isSyntheticEvent = function isSyntheticEvent(event) {
return typeof event.persist === 'function';
};
const isSyntheticEvent = event => typeof event.persist === 'function';
/**

@@ -41,17 +35,16 @@ * Creates a event handler function throttled by `requestAnimationFrame` that

export default function useThrottledEventHandler(handler) {
var isMounted = useMounted();
var eventHandler = useEventCallback(handler);
var nextEventInfoRef = useRef({
const isMounted = useMounted();
const eventHandler = useEventCallback(handler);
const nextEventInfoRef = useRef({
event: null,
handle: null
});
var clear = function clear() {
const clear = () => {
cancelAnimationFrame(nextEventInfoRef.current.handle);
nextEventInfoRef.current.handle = null;
};
var handlePointerMoveAnimation = function handlePointerMoveAnimation() {
var next = nextEventInfoRef.current;
const handlePointerMoveAnimation = () => {
const {
current: next
} = nextEventInfoRef;
if (next.handle && next.event) {

@@ -63,19 +56,15 @@ if (isMounted()) {

}
next.event = null;
};
var throttledHandler = function throttledHandler(event) {
const throttledHandler = event => {
if (!isMounted()) return;
if (isSyntheticEvent(event)) {
event.persist();
} // Special handling for a React.Konva event which reuses the
}
// Special handling for a React.Konva event which reuses the
// event object as it bubbles, setting target
else if ('evt' in event) {
event = _extends({}, event);
}
event = Object.assign({}, event);
}
nextEventInfoRef.current.event = event;
if (!nextEventInfoRef.current.handle) {

@@ -85,5 +74,4 @@ nextEventInfoRef.current.handle = requestAnimationFrame(handlePointerMoveAnimation);

};
throttledHandler.clear = clear;
return throttledHandler;
}
import { useMemo, useRef } from 'react';
import useMounted from './useMounted';
import useWillUnmount from './useWillUnmount';
/*

@@ -12,11 +13,8 @@ * Browsers including Internet Explorer, Chrome, Safari, and Firefox store the

*/
var MAX_DELAY_MS = Math.pow(2, 31) - 1;
const MAX_DELAY_MS = 2 ** 31 - 1;
function setChainedTimeout(handleRef, fn, timeoutAtMs) {
var delayMs = timeoutAtMs - Date.now();
handleRef.current = delayMs <= MAX_DELAY_MS ? setTimeout(fn, delayMs) : setTimeout(function () {
return setChainedTimeout(handleRef, fn, timeoutAtMs);
}, MAX_DELAY_MS);
const delayMs = timeoutAtMs - Date.now();
handleRef.current = delayMs <= MAX_DELAY_MS ? setTimeout(fn, delayMs) : setTimeout(() => setChainedTimeout(handleRef, fn, timeoutAtMs), MAX_DELAY_MS);
}
/**

@@ -40,24 +38,13 @@ * Returns a controller object for setting a timeout that is properly cleaned up

*/
export default function useTimeout() {
var isMounted = useMounted(); // types are confused between node and web here IDK
const isMounted = useMounted();
var handleRef = useRef();
useWillUnmount(function () {
return clearTimeout(handleRef.current);
});
return useMemo(function () {
var clear = function clear() {
return clearTimeout(handleRef.current);
};
function set(fn, delayMs) {
if (delayMs === void 0) {
delayMs = 0;
}
// types are confused between node and web here IDK
const handleRef = useRef();
useWillUnmount(() => clearTimeout(handleRef.current));
return useMemo(() => {
const clear = () => clearTimeout(handleRef.current);
function set(fn, delayMs = 0) {
if (!isMounted()) return;
clear();
if (delayMs <= MAX_DELAY_MS) {

@@ -70,8 +57,7 @@ // For simplicity, if the timeout is short, just set a normal timeout.

}
return {
set: set,
clear: clear
set,
clear
};
}, []);
}

@@ -24,2 +24,2 @@ /**

*/
export default function useToggleState(initialState?: boolean): [boolean, (value?: boolean | undefined) => void];
export default function useToggleState(initialState?: boolean): [boolean, (value?: boolean) => void];
import { useReducer } from 'react';
/**

@@ -25,11 +26,4 @@ * Create a state setter pair for a boolean value that can be "switched".

*/
export default function useToggleState(initialState) {
if (initialState === void 0) {
initialState = false;
}
return useReducer(function (state, action) {
return action == null ? !state : action;
}, initialState);
export default function useToggleState(initialState = false) {
return useReducer((state, action) => action == null ? !state : action, initialState);
}
import { useRef } from 'react';
/**

@@ -8,7 +9,6 @@ * Returns a ref that is immediately updated with the new value

*/
export default function useUpdatedRef(value) {
var valueRef = useRef(value);
const valueRef = useRef(value);
valueRef.current = value;
return valueRef;
}
import { useEffect, useRef } from 'react';
/**

@@ -22,6 +23,5 @@ * Runs an effect only when the dependencies have changed, skipping the

*/
function useUpdateEffect(fn, deps) {
var isFirst = useRef(true);
useEffect(function () {
const isFirst = useRef(true);
useEffect(() => {
if (isFirst.current) {

@@ -31,7 +31,5 @@ isFirst.current = false;

}
return fn();
}, deps);
}
export default useUpdateEffect;
import { useRef } from 'react';
import useStableMemo from './useStableMemo';
import useWillUnmount from './useWillUnmount';
/**

@@ -20,10 +21,9 @@ * An _immediate_ effect that runs an effect callback when its dependency array

*/
function useUpdateImmediateEffect(effect, deps) {
var firstRef = useRef(true);
var tearDown = useRef();
useWillUnmount(function () {
const firstRef = useRef(true);
const tearDown = useRef();
useWillUnmount(() => {
if (tearDown.current) tearDown.current();
});
useStableMemo(function () {
useStableMemo(() => {
if (firstRef.current) {

@@ -33,3 +33,2 @@ firstRef.current = false;

}
if (tearDown.current) tearDown.current();

@@ -39,3 +38,2 @@ tearDown.current = effect();

}
export default useUpdateImmediateEffect;
import { useLayoutEffect, useRef } from 'react';
/**

@@ -22,6 +23,5 @@ * Runs a layout effect only when the dependencies have changed, skipping the

*/
function useUpdateLayoutEffect(fn, deps) {
var isFirst = useRef(true);
useLayoutEffect(function () {
const isFirst = useRef(true);
useLayoutEffect(() => {
if (isFirst.current) {

@@ -31,7 +31,5 @@ isFirst.current = false;

}
return fn();
}, deps);
}
export default useUpdateLayoutEffect;
import useUpdatedRef from './useUpdatedRef';
import { useEffect } from 'react';
/**

@@ -9,10 +10,5 @@ * Attach a callback that fires when a component unmounts

*/
export default function useWillUnmount(fn) {
var onUnmount = useUpdatedRef(fn);
useEffect(function () {
return function () {
return onUnmount.current();
};
}, []);
const onUnmount = useUpdatedRef(fn);
useEffect(() => () => onUnmount.current(), []);
}
{
"name": "@restart/hooks",
"version": "0.4.9",
"version": "0.4.10",
"main": "cjs/index.js",

@@ -34,5 +34,5 @@ "types": "cjs/index.d.ts",

"preset": "@4c",
"rootDir": "./test",
"testEnvironment": "jsdom",
"setupFilesAfterEnv": [
"./setup.js"
"./test/setup.js"
]

@@ -56,4 +56,4 @@ },

"dependencies": {
"dequal": "^2.0.2"
"dequal": "^2.0.3"
}
}
SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc