Socket
Socket
Sign inDemoInstall

@reach/utils

Package Overview
Dependencies
Maintainers
4
Versions
53
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@reach/utils - npm Package Compare versions

Comparing version 0.14.0 to 0.15.0

can-use-dom/dist/reach-utils-can-use-dom.cjs.d.ts

304

dist/declarations/src/index.d.ts

@@ -1,278 +0,26 @@

import * as React from "react";
import type { As, AssignableRef, ComponentWithAs, ComponentWithForwardedRef, DistributiveOmit, ElementTagNameMap, ForwardRefExoticComponentWithAs, ForwardRefWithAsRenderFunction, FunctionComponentWithAs, MemoExoticComponentWithAs, PropsFromAs, PropsWithAs, SingleOrArray, ThenArg } from "./types";
/**
* React currently throws a warning when using useLayoutEffect on the server.
* To get around it, we can conditionally useEffect on the server (no-op) and
* useLayoutEffect in the browser. We occasionally need useLayoutEffect to
* ensure we don't get a render flash for certain operations, but we may also
* need affected components to render on the server. One example is when setting
* a component's descendants to retrieve their index values.
*
* Important to note that using this hook as an escape hatch will break the
* eslint dependency warnings unless you rename the import to `useLayoutEffect`.
* Use sparingly only when the effect won't effect the rendered HTML to avoid
* any server/client mismatch.
*
* If a useLayoutEffect is needed and the result would create a mismatch, it's
* likely that the component in question shouldn't be rendered on the server at
* all, so a better approach would be to lazily render those in a parent
* component after client-side hydration.
*
* TODO: We are calling useLayoutEffect in a couple of places that will likely
* cause some issues for SSR users, whether the warning shows or not. Audit and
* fix these.
*
* https://gist.github.com/gaearon/e7d97cdf38a2907924ea12e4ebdf3c85
* https://github.com/reduxjs/react-redux/blob/master/src/utils/useIsomorphicLayoutEffect.js
*
* @param effect
* @param deps
*/
export declare const useIsomorphicLayoutEffect: typeof React.useEffect;
/**
* Copy of Facebook's warning package.
*
* Similar to invariant but only logs a warning if the condition is not met.
* This can be used to log issues in development environments in critical paths.
* Removing the logging code for production environments will keep the same
* logic and follow the same code paths.
*
* @see https://github.com/BerkeleyTrue/warning/blob/master/warning.js
*/
export declare const warning: (condition: any, format?: string | undefined, ...extra: any[]) => void;
/**
* When in dev mode, checks that styles for a given @reach package are loaded.
*
* @param packageName Name of the package to check.
* @example checkStyles("dialog") will check for styles for @reach/dialog
*/
declare let checkStyles: (packageName: string) => void;
export { checkStyles };
/**
* Passes or assigns an arbitrary value to a ref function or object.
*
* @param ref
* @param value
*/
export declare function assignRef<RefValueType = any>(ref: AssignableRef<RefValueType> | null | undefined, value: any): void;
/**
* Checks true|"true" vs false|"false"
*
* @param value
*/
export declare function boolOrBoolString(value: any): value is "true" | true;
export declare function canUseDOM(): boolean;
/**
* Type-safe clone element
*
* @param element
* @param props
* @param children
*/
export declare function cloneValidElement<Props>(element: React.ReactElement<Props> | React.ReactNode, props?: Partial<Props> & React.Attributes, ...children: React.ReactNode[]): React.ReactElement<Props> | React.ReactNode;
export declare function createNamedContext<ContextValueType>(name: string, defaultValue: ContextValueType): React.Context<ContextValueType>;
/**
* This is a hack for sure. The thing is, getting a component to intelligently
* infer props based on a component or JSX string passed into an `as` prop is
* kind of a huge pain. Getting it to work and satisfy the constraints of
* `forwardRef` seems dang near impossible. To avoid needing to do this awkward
* type song-and-dance every time we want to forward a ref into a component
* that accepts an `as` prop, we abstract all of that mess to this function for
* the time time being.
*/
export declare function forwardRefWithAs<Props, DefaultComponentType extends As = "div">(render: ForwardRefWithAsRenderFunction<DefaultComponentType, Props>): ForwardRefExoticComponentWithAs<DefaultComponentType, Props>;
export declare function memoWithAs<Props, DefaultComponentType extends As = "div">(Component: FunctionComponentWithAs<DefaultComponentType, Props>, propsAreEqual?: (prevProps: Readonly<React.PropsWithChildren<Props>>, nextProps: Readonly<React.PropsWithChildren<Props>>) => boolean): MemoExoticComponentWithAs<DefaultComponentType, Props>;
/**
* Get the size of the working document minus the scrollbar offset.
*
* @param element
*/
export declare function getDocumentDimensions(element?: HTMLElement | null | undefined): {
width: number;
height: number;
};
/**
* Get the scoll position of the global window object relative to a given node.
*
* @param element
*/
export declare function getScrollPosition(element?: HTMLElement | null | undefined): {
scrollX: number;
scrollY: number;
};
/**
* Get a computed style value by property.
*
* @param element
* @param styleProp
*/
export declare function getElementComputedStyle(element: Element, styleProp: string): string | null;
/**
* Get an element's owner document. Useful when components are used in iframes
* or other environments like dev tools.
*
* @param element
*/
export declare function getOwnerDocument<T extends Element>(element: T | null | undefined): Document | null;
/**
* TODO: Remove in 1.0
*/
export declare function getOwnerWindow<T extends Element>(element: T | null | undefined): (Window & typeof globalThis) | null;
/**
* Get the scrollbar offset distance.
*
* TODO: Remove in 1.0 (we used this in public examples)
*/
export declare function getScrollbarOffset(): number;
/**
* Checks whether or not a value is a boolean.
*
* @param value
*/
export declare function isBoolean(value: any): value is boolean;
/**
* Checks whether or not a value is a function.
*
* @param value
*/
export declare function isFunction(value: any): value is Function;
/**
* Checks whether or not a value is a number.
*
* @param value
*/
export declare function isNumber(value: any): value is number;
/**
* Detects right clicks
*
* @param nativeEvent
*/
export declare function isRightClick(nativeEvent: MouseEvent | PointerEvent | TouchEvent): boolean;
/**
* Checks whether or not a value is a string.
*
* @param value
*/
export declare function isString(value: any): value is string;
/**
* Joins strings to format IDs for compound components.
*
* @param args
*/
export declare function makeId(...args: (string | number | null | undefined)[]): string;
/**
* No-op function.
*/
export declare function noop(): void;
/**
* Convert our state strings for HTML data attributes.
* No need for a fancy kebab-caser here, we know what our state strings are!
*
* @param state
*/
export declare function stateToAttributeString(state: any): string;
/**
* Check if a component is controlled or uncontrolled and return the correct
* state value and setter accordingly. If the component state is controlled by
* the app, the setter is a noop.
*
* @param controlledValue
* @param defaultValue
*/
export declare function useControlledState<T = any>(controlledValue: T | undefined, defaultValue: T): [T, React.Dispatch<React.SetStateAction<T>>];
/**
* Logs a warning in dev mode when a component switches from controlled to
* uncontrolled, or vice versa
*
* A single prop should typically be used to determine whether or not a
* component is controlled or not.
*
* @param controlledValue
* @param controlledPropName
* @param componentName
*/
declare let useControlledSwitchWarning: (controlledValue: any, controlledPropName: string, componentName: string) => void;
export { useControlledSwitchWarning };
declare let useCheckStyles: (packageName: string) => void;
export { useCheckStyles };
/**
* React hook for creating a value exactly once.
* @see https://github.com/Andarist/use-constant
*/
export declare function useConstant<ValueType>(fn: () => ValueType): ValueType;
/**
* @param callback
*/
export declare function useEventCallback<E extends Event | React.SyntheticEvent>(callback: (event: E, ...args: any[]) => void): (event: E, ...args: any[]) => void;
export declare function useLazyRef<F extends (...args: any[]) => any>(fn: F): React.MutableRefObject<ReturnType<F>>;
/**
* TODO: Remove in 1.0
* @alias useStableCallback
* @param callback
*/
export declare const useCallbackProp: typeof useStableCallback;
/**
* Adds a DOM event listener
*
* @param eventName
* @param listener
* @param element
*/
export declare function useEventListener<K extends keyof WindowEventMap>(eventName: K, listener: (event: WindowEventMap[K]) => any, element?: HTMLElement | Document | Window | EventTarget): void;
/**
* Detect when focus changes in our document.
*
* @param handleChange
* @param when
* @param ownerDocument
*/
export declare function useFocusChange(handleChange?: (activeElement: Element | null, previousActiveElement: Element | null, event?: FocusEvent) => void, when?: "focus" | "blur", ownerDocument?: Document): void;
/**
* Forces a re-render, similar to `forceUpdate` in class components.
*/
export declare function useForceUpdate(): () => void;
/**
* Passes or assigns a value to multiple refs (typically a DOM node). Useful for
* dealing with components that need an explicit ref for DOM calculations but
* also forwards refs assigned by an app.
*
* @param refs Refs to fork
*/
export declare function useForkedRef<RefValueType = any>(...refs: (AssignableRef<RefValueType> | null | undefined)[]): ((node: any) => void) | null;
/**
* Returns the previous value of a reference after a component update.
*
* @param value
*/
export declare function usePrevious<ValueType = any>(value: ValueType): ValueType | null;
/**
* Converts a callback to a ref to avoid triggering re-renders when passed as a
* prop and exposed as a stable function to avoid executing effects when
* passed as a dependency.
*/
export declare function useStableCallback<T extends (...args: any[]) => any>(callback: T | null | undefined): T;
/**
* Call an effect after a component update, skipping the initial mount.
*
* @param effect Effect to call
* @param deps Effect dependency list
*/
export declare function useUpdateEffect(effect: React.EffectCallback, deps?: React.DependencyList): void;
/**
* Just a lil state logger
*
* @param state
* @param DEBUG
*/
declare let useStateLogger: (state: string, DEBUG: boolean) => void;
export { useStateLogger };
/**
* Wraps a lib-defined event handler and a user-defined event handler, returning
* a single handler that allows a user to prevent lib-defined handlers from
* firing.
*
* @param theirHandler User-supplied event handler
* @param ourHandler Library-supplied event handler
*/
export declare function wrapEvent<EventType extends React.SyntheticEvent | Event>(theirHandler: ((event: EventType) => any) | undefined, ourHandler: (event: EventType) => any): (event: EventType) => any;
export type { As, AssignableRef, ComponentWithAs, ComponentWithForwardedRef, DistributiveOmit, ElementTagNameMap, ForwardRefExoticComponentWithAs, FunctionComponentWithAs, MemoExoticComponentWithAs, PropsFromAs, PropsWithAs, SingleOrArray, ThenArg, };
export * from "./can-use-dom";
export * from "./clone-valid-element";
export * from "./compose-event-handlers";
export * from "./compose-refs";
export * from "./computed-styles";
export * from "./context";
export * from "./dev-utils";
export * from "./get-document-dimensions";
export * from "./get-scroll-position";
export * from "./get-scrollbar-offset";
export * from "./is-right-click";
export * from "./make-id";
export * from "./noop";
export * from "./owner-document";
export * from "./polymorphic";
export * from "./type-check";
export * from "./use-constant";
export * from "./use-controlled-state";
export * from "./use-event-listener";
export * from "./use-focus-change";
export * from "./use-force-update";
export * from "./use-isomorphic-layout-effect";
export * from "./use-lazy-ref";
export * from "./use-previous";
export * from "./use-stable-callback";
export * from "./use-update-effect";

@@ -55,71 +55,4 @@ import * as React from "react";

export declare type ThenArg<T> = T extends PromiseLike<infer U> ? U : T;
export declare type As<BaseProps = any> = React.ElementType<BaseProps>;
export declare type PropsWithAs<ComponentType extends As, ComponentProps> = ComponentProps & Omit<React.ComponentPropsWithRef<ComponentType>, "as" | keyof ComponentProps> & {
as?: ComponentType;
};
export declare type PropsFromAs<ComponentType extends As, ComponentProps> = (PropsWithAs<ComponentType, ComponentProps> & {
as: ComponentType;
}) & PropsWithAs<ComponentType, ComponentProps>;
export declare type ComponentWithForwardedRef<ElementType extends React.ElementType, ComponentProps> = React.ForwardRefExoticComponent<ComponentProps & React.HTMLProps<React.ElementType<ElementType>> & React.ComponentPropsWithRef<ElementType>>;
export interface FunctionComponentWithAs<DefaultComponentType extends As, ComponentProps> {
/**
* Inherited from React.FunctionComponent with modifications to support `as`
*/
<ComponentType extends As>(props: PropsWithAs<ComponentType, ComponentProps>, context?: any): React.ReactElement<any, any> | null;
(props: PropsWithAs<DefaultComponentType, ComponentProps>, context?: any): React.ReactElement<any, any> | null;
/**
* Inherited from React.FunctionComponent
*/
displayName?: string;
propTypes?: React.WeakValidationMap<PropsWithAs<DefaultComponentType, ComponentProps>>;
contextTypes?: React.ValidationMap<any>;
defaultProps?: Partial<PropsWithAs<DefaultComponentType, ComponentProps>>;
}
export interface ComponentWithAs<ComponentType extends As, ComponentProps> extends FunctionComponentWithAs<ComponentType, ComponentProps> {
}
interface ExoticComponentWithAs<DefaultComponentType extends As, ComponentProps> {
/**
* **NOTE**: Exotic components are not callable.
* Inherited from React.ExoticComponent with modifications to support `as`
*/
(props: PropsWithAs<DefaultComponentType, ComponentProps>): React.ReactElement | null;
<ComponentType extends As>(props: PropsWithAs<ComponentType, ComponentProps> & {
as: ComponentType;
}): React.ReactElement | null;
/**
* Inherited from React.ExoticComponent
*/
readonly $$typeof: symbol;
}
interface NamedExoticComponentWithAs<DefaultComponentType extends As, ComponentProps> extends ExoticComponentWithAs<DefaultComponentType, ComponentProps> {
/**
* Inherited from React.NamedExoticComponent
*/
displayName?: string;
}
export interface ForwardRefExoticComponentWithAs<DefaultComponentType extends As, ComponentProps> extends NamedExoticComponentWithAs<DefaultComponentType, ComponentProps> {
/**
* Inherited from React.ForwardRefExoticComponent
* Will show `ForwardRef(${Component.displayName || Component.name})` in devtools by default,
* but can be given its own specific name
*/
defaultProps?: Partial<PropsWithAs<DefaultComponentType, ComponentProps>>;
propTypes?: React.WeakValidationMap<PropsWithAs<DefaultComponentType, ComponentProps>>;
}
export interface MemoExoticComponentWithAs<DefaultComponentType extends As, ComponentProps> extends NamedExoticComponentWithAs<DefaultComponentType, ComponentProps> {
readonly type: DefaultComponentType extends React.ComponentType ? DefaultComponentType : FunctionComponentWithAs<DefaultComponentType, ComponentProps>;
}
export interface ForwardRefWithAsRenderFunction<DefaultComponentType extends As, ComponentProps = {}> {
(props: React.PropsWithChildren<PropsFromAs<DefaultComponentType, ComponentProps>>, ref: ((instance: (DefaultComponentType extends keyof ElementTagNameMap ? ElementTagNameMap[DefaultComponentType] : any) | null) => void) | React.MutableRefObject<(DefaultComponentType extends keyof ElementTagNameMap ? ElementTagNameMap[DefaultComponentType] : any) | null> | null): React.ReactElement | null;
displayName?: string;
/**
* defaultProps are not supported on render functions
*/
defaultProps?: never;
/**
* propTypes are not supported on render functions
*/
propTypes?: never;
}
export declare type ElementTagNameMap = HTMLElementTagNameMap & Pick<SVGElementTagNameMap, Exclude<keyof SVGElementTagNameMap, keyof HTMLElementTagNameMap>>;
export {};
declare const _default: {};
export default _default;

@@ -5,714 +5,65 @@ 'use strict';

var React = require('react');
var fbWarning = require('warning');
var canUseDom_dist_reachUtilsCanUseDom = require('../can-use-dom/dist/reach-utils-can-use-dom.cjs.dev.js');
var cloneValidElement_dist_reachUtilsCloneValidElement = require('../clone-valid-element/dist/reach-utils-clone-valid-element.cjs.dev.js');
var composeEventHandlers_dist_reachUtilsComposeEventHandlers = require('../compose-event-handlers/dist/reach-utils-compose-event-handlers.cjs.dev.js');
var composeRefs_dist_reachUtilsComposeRefs = require('../compose-refs/dist/reach-utils-compose-refs.cjs.dev.js');
var computedStyles_dist_reachUtilsComputedStyles = require('../computed-styles/dist/reach-utils-computed-styles.cjs.dev.js');
var context_dist_reachUtilsContext = require('../context/dist/reach-utils-context.cjs.dev.js');
var devUtils_dist_reachUtilsDevUtils = require('../dev-utils/dist/reach-utils-dev-utils.cjs.dev.js');
var getDocumentDimensions_dist_reachUtilsGetDocumentDimensions = require('../get-document-dimensions/dist/reach-utils-get-document-dimensions.cjs.dev.js');
var getScrollPosition_dist_reachUtilsGetScrollPosition = require('../get-scroll-position/dist/reach-utils-get-scroll-position.cjs.dev.js');
var getScrollbarOffset_dist_reachUtilsGetScrollbarOffset = require('../get-scrollbar-offset/dist/reach-utils-get-scrollbar-offset.cjs.dev.js');
var isRightClick_dist_reachUtilsIsRightClick = require('../is-right-click/dist/reach-utils-is-right-click.cjs.dev.js');
var makeId_dist_reachUtilsMakeId = require('../make-id/dist/reach-utils-make-id.cjs.dev.js');
var noop_dist_reachUtilsNoop = require('../noop/dist/reach-utils-noop.cjs.dev.js');
var ownerDocument_dist_reachUtilsOwnerDocument = require('../owner-document/dist/reach-utils-owner-document.cjs.dev.js');
var typeCheck_dist_reachUtilsTypeCheck = require('../type-check/dist/reach-utils-type-check.cjs.dev.js');
var useConstant_dist_reachUtilsUseConstant = require('../use-constant/dist/reach-utils-use-constant.cjs.dev.js');
var useControlledState_dist_reachUtilsUseControlledState = require('../use-controlled-state/dist/reach-utils-use-controlled-state.cjs.dev.js');
var useEventListener_dist_reachUtilsUseEventListener = require('../use-event-listener/dist/reach-utils-use-event-listener.cjs.dev.js');
var useFocusChange_dist_reachUtilsUseFocusChange = require('../use-focus-change/dist/reach-utils-use-focus-change.cjs.dev.js');
var useForceUpdate_dist_reachUtilsUseForceUpdate = require('../use-force-update/dist/reach-utils-use-force-update.cjs.dev.js');
var useIsomorphicLayoutEffect_dist_reachUtilsUseIsomorphicLayoutEffect = require('../use-isomorphic-layout-effect/dist/reach-utils-use-isomorphic-layout-effect.cjs.dev.js');
var useLazyRef_dist_reachUtilsUseLazyRef = require('../use-lazy-ref/dist/reach-utils-use-lazy-ref.cjs.dev.js');
var usePrevious_dist_reachUtilsUsePrevious = require('../use-previous/dist/reach-utils-use-previous.cjs.dev.js');
var useStableCallback_dist_reachUtilsUseStableCallback = require('../use-stable-callback/dist/reach-utils-use-stable-callback.cjs.dev.js');
var useUpdateEffect_dist_reachUtilsUseUpdateEffect = require('../use-update-effect/dist/reach-utils-use-update-effect.cjs.dev.js');
require('react');
function _interopDefault (e) { return e && e.__esModule ? e : { 'default': e }; }
function _interopNamespace(e) {
if (e && e.__esModule) return e;
var n = Object.create(null);
if (e) {
Object.keys(e).forEach(function (k) {
if (k !== 'default') {
var d = Object.getOwnPropertyDescriptor(e, k);
Object.defineProperty(n, k, d.get ? d : {
enumerable: true,
get: function () {
return e[k];
}
});
}
});
}
n['default'] = e;
return Object.freeze(n);
}
var React__namespace = /*#__PURE__*/_interopNamespace(React);
var fbWarning__default = /*#__PURE__*/_interopDefault(fbWarning);
/* eslint-disable no-restricted-globals, eqeqeq */
/**
* React currently throws a warning when using useLayoutEffect on the server.
* To get around it, we can conditionally useEffect on the server (no-op) and
* useLayoutEffect in the browser. We occasionally need useLayoutEffect to
* ensure we don't get a render flash for certain operations, but we may also
* need affected components to render on the server. One example is when setting
* a component's descendants to retrieve their index values.
*
* Important to note that using this hook as an escape hatch will break the
* eslint dependency warnings unless you rename the import to `useLayoutEffect`.
* Use sparingly only when the effect won't effect the rendered HTML to avoid
* any server/client mismatch.
*
* If a useLayoutEffect is needed and the result would create a mismatch, it's
* likely that the component in question shouldn't be rendered on the server at
* all, so a better approach would be to lazily render those in a parent
* component after client-side hydration.
*
* TODO: We are calling useLayoutEffect in a couple of places that will likely
* cause some issues for SSR users, whether the warning shows or not. Audit and
* fix these.
*
* https://gist.github.com/gaearon/e7d97cdf38a2907924ea12e4ebdf3c85
* https://github.com/reduxjs/react-redux/blob/master/src/utils/useIsomorphicLayoutEffect.js
*
* @param effect
* @param deps
*/
var useIsomorphicLayoutEffect = /*#__PURE__*/canUseDOM() ? React.useLayoutEffect : React.useEffect;
var checkedPkgs = {};
/**
* Copy of Facebook's warning package.
*
* Similar to invariant but only logs a warning if the condition is not met.
* This can be used to log issues in development environments in critical paths.
* Removing the logging code for production environments will keep the same
* logic and follow the same code paths.
*
* @see https://github.com/BerkeleyTrue/warning/blob/master/warning.js
*/
var warning = fbWarning__default['default'];
/**
* When in dev mode, checks that styles for a given @reach package are loaded.
*
* @param packageName Name of the package to check.
* @example checkStyles("dialog") will check for styles for @reach/dialog
*/
exports.checkStyles = noop;
if (process.env.NODE_ENV !== "production") {
// In CJS files, process.env.NODE_ENV is stripped from our build, but we need
// it to prevent style checks from clogging up user logs while testing.
// This is a workaround until we can tweak the build a bit to accommodate.
var _ref = typeof process !== "undefined" ? process : {
env: {
NODE_ENV: "development"
}
},
env = _ref.env;
exports.checkStyles = function checkStyles(packageName) {
// only check once per package
if (checkedPkgs[packageName]) return;
checkedPkgs[packageName] = true;
if (env.NODE_ENV !== "test" && parseInt(window.getComputedStyle(document.body).getPropertyValue("--reach-" + packageName), 10) !== 1) {
console.warn("@reach/" + packageName + " styles not found. If you are using a bundler like webpack or parcel include this in the entry file of your app before any of your own styles:\n\n import \"@reach/" + packageName + "/styles.css\";\n\n Otherwise you'll need to include them some other way:\n\n <link rel=\"stylesheet\" type=\"text/css\" href=\"node_modules/@reach/" + packageName + "/styles.css\" />\n\n For more information visit https://ui.reach.tech/styling.\n ");
}
};
}
/**
* Passes or assigns an arbitrary value to a ref function or object.
*
* @param ref
* @param value
*/
function assignRef(ref, value) {
if (ref == null) return;
if (isFunction(ref)) {
ref(value);
} else {
try {
ref.current = value;
} catch (error) {
throw new Error("Cannot assign value \"" + value + "\" to ref \"" + ref + "\"");
}
}
}
/**
* Checks true|"true" vs false|"false"
*
* @param value
*/
function boolOrBoolString(value) {
return value === "true" ? true : isBoolean(value) ? value : false;
}
function canUseDOM() {
return !!(typeof window !== "undefined" && window.document && window.document.createElement);
}
/**
* Type-safe clone element
*
* @param element
* @param props
* @param children
*/
function cloneValidElement(element, props) {
for (var _len = arguments.length, children = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
children[_key - 2] = arguments[_key];
}
return /*#__PURE__*/React.isValidElement(element) ? React.cloneElement.apply(React__namespace, [element, props].concat(children)) : element;
}
function createNamedContext(name, defaultValue) {
var Ctx = /*#__PURE__*/React.createContext(defaultValue);
Ctx.displayName = name;
return Ctx;
}
/**
* This is a hack for sure. The thing is, getting a component to intelligently
* infer props based on a component or JSX string passed into an `as` prop is
* kind of a huge pain. Getting it to work and satisfy the constraints of
* `forwardRef` seems dang near impossible. To avoid needing to do this awkward
* type song-and-dance every time we want to forward a ref into a component
* that accepts an `as` prop, we abstract all of that mess to this function for
* the time time being.
*/
function forwardRefWithAs(render) {
return /*#__PURE__*/React.forwardRef(render);
}
function memoWithAs(Component, propsAreEqual) {
return /*#__PURE__*/React.memo(Component, propsAreEqual);
}
/**
* Get the size of the working document minus the scrollbar offset.
*
* @param element
*/
function getDocumentDimensions(element) {
var _ownerDocument$docume, _ownerDocument$docume2;
var ownerDocument = getOwnerDocument(element);
var ownerWindow = ownerDocument.defaultView || window;
if (!ownerDocument) {
return {
width: 0,
height: 0
};
}
return {
width: (_ownerDocument$docume = ownerDocument.documentElement.clientWidth) != null ? _ownerDocument$docume : ownerWindow.innerWidth,
height: (_ownerDocument$docume2 = ownerDocument.documentElement.clientHeight) != null ? _ownerDocument$docume2 : ownerWindow.innerHeight
};
}
/**
* Get the scoll position of the global window object relative to a given node.
*
* @param element
*/
function getScrollPosition(element) {
var ownerDocument = getOwnerDocument(element);
var ownerWindow = ownerDocument.defaultView || window;
if (!ownerDocument) {
return {
scrollX: 0,
scrollY: 0
};
}
return {
scrollX: ownerWindow.scrollX,
scrollY: ownerWindow.scrollY
};
}
/**
* Get a computed style value by property.
*
* @param element
* @param styleProp
*/
function getElementComputedStyle(element, styleProp) {
var ownerDocument = getOwnerDocument(element);
var ownerWindow = (ownerDocument == null ? void 0 : ownerDocument.defaultView) || window;
if (ownerWindow) {
return ownerWindow.getComputedStyle(element, null).getPropertyValue(styleProp);
}
return null;
}
/**
* Get an element's owner document. Useful when components are used in iframes
* or other environments like dev tools.
*
* @param element
*/
function getOwnerDocument(element) {
return canUseDOM() ? element ? element.ownerDocument : document : null;
}
/**
* TODO: Remove in 1.0
*/
function getOwnerWindow(element) {
var ownerDocument = getOwnerDocument(element);
return ownerDocument ? ownerDocument.defaultView || window : null;
}
/**
* Get the scrollbar offset distance.
*
* TODO: Remove in 1.0 (we used this in public examples)
*/
function getScrollbarOffset() {
try {
if (window.innerWidth > document.documentElement.clientWidth) {
return window.innerWidth - document.documentElement.clientWidth;
}
} catch (err) {}
return 0;
}
/**
* Checks whether or not a value is a boolean.
*
* @param value
*/
function isBoolean(value) {
return typeof value === "boolean";
}
/**
* Checks whether or not a value is a function.
*
* @param value
*/
function isFunction(value) {
return !!(value && {}.toString.call(value) == "[object Function]");
}
/**
* Checks whether or not a value is a number.
*
* @param value
*/
function isNumber(value) {
return typeof value === "number" && !isNaN(value);
}
/**
* Detects right clicks
*
* @param nativeEvent
*/
function isRightClick(nativeEvent) {
return "which" in nativeEvent ? nativeEvent.which === 3 : "button" in nativeEvent ? nativeEvent.button === 2 : false;
}
/**
* Checks whether or not a value is a string.
*
* @param value
*/
function isString(value) {
return typeof value === "string";
}
/**
* Joins strings to format IDs for compound components.
*
* @param args
*/
function makeId() {
for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
return args.filter(function (val) {
return val != null;
}).join("--");
}
/**
* No-op function.
*/
function noop() {}
/**
* Convert our state strings for HTML data attributes.
* No need for a fancy kebab-caser here, we know what our state strings are!
*
* @param state
*/
function stateToAttributeString(state) {
return String(state).replace(/([\s_]+)/g, "-").toLowerCase();
}
/**
* Check if a component is controlled or uncontrolled and return the correct
* state value and setter accordingly. If the component state is controlled by
* the app, the setter is a noop.
*
* @param controlledValue
* @param defaultValue
*/
function useControlledState(controlledValue, defaultValue) {
var controlledRef = React.useRef(controlledValue != null);
var _React$useState = React.useState(defaultValue),
valueState = _React$useState[0],
setValue = _React$useState[1];
var set = React.useCallback(function (n) {
if (!controlledRef.current) {
setValue(n);
}
}, []);
return [controlledRef.current ? controlledValue : valueState, set];
}
/**
* Logs a warning in dev mode when a component switches from controlled to
* uncontrolled, or vice versa
*
* A single prop should typically be used to determine whether or not a
* component is controlled or not.
*
* @param controlledValue
* @param controlledPropName
* @param componentName
*/
exports.useControlledSwitchWarning = noop;
if (process.env.NODE_ENV !== "production") {
exports.useControlledSwitchWarning = function useControlledSwitchWarning(controlledValue, controlledPropName, componentName) {
var controlledRef = React.useRef(controlledValue != null);
var nameCache = React.useRef({
componentName: componentName,
controlledPropName: controlledPropName
});
React.useEffect(function () {
nameCache.current = {
componentName: componentName,
controlledPropName: controlledPropName
};
}, [componentName, controlledPropName]);
React.useEffect(function () {
var wasControlled = controlledRef.current;
var _nameCache$current = nameCache.current,
componentName = _nameCache$current.componentName,
controlledPropName = _nameCache$current.controlledPropName;
var isControlled = controlledValue != null;
if (wasControlled !== isControlled) {
console.error("A component is changing an " + (wasControlled ? "" : "un") + "controlled `" + controlledPropName + "` state of " + componentName + " to be " + (wasControlled ? "un" : "") + "controlled. This is likely caused by the value changing from undefined to a defined value, which should not happen. Decide between using a controlled or uncontrolled " + componentName + " element for the lifetime of the component.\nMore info: https://fb.me/react-controlled-components");
}
}, [controlledValue]);
};
}
exports.useCheckStyles = noop;
if (process.env.NODE_ENV !== "production") {
exports.useCheckStyles = function useCheckStyles(pkg) {
var name = React.useRef(pkg);
React.useEffect(function () {
return void (name.current = pkg);
}, [pkg]);
React.useEffect(function () {
return exports.checkStyles(name.current);
}, []);
};
}
/**
* React hook for creating a value exactly once.
* @see https://github.com/Andarist/use-constant
*/
function useConstant(fn) {
var ref = React.useRef();
if (!ref.current) {
ref.current = {
v: fn()
};
}
return ref.current.v;
}
/**
* @param callback
*/
function useEventCallback(callback) {
var ref = React.useRef(callback);
useIsomorphicLayoutEffect(function () {
ref.current = callback;
});
return React.useCallback(function (event) {
for (var _len3 = arguments.length, args = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) {
args[_key3 - 1] = arguments[_key3];
}
return ref.current.apply(ref, [event].concat(args));
}, []);
}
function useLazyRef(fn) {
var ref = React.useRef({
__internalSet: true
});
if (ref.current && ref.current.__internalSet === true) {
ref.current = fn();
}
return ref;
}
/**
* TODO: Remove in 1.0
* @alias useStableCallback
* @param callback
*/
var useCallbackProp = useStableCallback;
/**
* Adds a DOM event listener
*
* @param eventName
* @param listener
* @param element
*/
function useEventListener(eventName, listener, element) {
if (element === void 0) {
element = window;
}
var savedHandler = React.useRef(listener);
React.useEffect(function () {
savedHandler.current = listener;
}, [listener]);
React.useEffect(function () {
var isSupported = element && element.addEventListener;
if (!isSupported) {
if (process.env.NODE_ENV !== "production") {
console.warn("Event listener not supported on the element provided");
}
return;
}
function eventListener(event) {
savedHandler.current(event);
}
element.addEventListener(eventName, eventListener);
return function () {
element.removeEventListener(eventName, eventListener);
};
}, [eventName, element]);
}
/**
* Detect when focus changes in our document.
*
* @param handleChange
* @param when
* @param ownerDocument
*/
function useFocusChange(handleChange, when, ownerDocument) {
if (handleChange === void 0) {
handleChange = console.log;
}
if (when === void 0) {
when = "focus";
}
if (ownerDocument === void 0) {
ownerDocument = document;
}
var lastActiveElement = React.useRef(ownerDocument.activeElement);
React.useEffect(function () {
lastActiveElement.current = ownerDocument.activeElement;
function onChange(event) {
if (lastActiveElement.current !== ownerDocument.activeElement) {
handleChange(ownerDocument.activeElement, lastActiveElement.current, event);
lastActiveElement.current = ownerDocument.activeElement;
}
}
ownerDocument.addEventListener(when, onChange, true);
return function () {
ownerDocument.removeEventListener(when, onChange);
};
}, [when, handleChange, ownerDocument]);
}
/**
* Forces a re-render, similar to `forceUpdate` in class components.
*/
function useForceUpdate() {
var _React$useState2 = React.useState(Object.create(null)),
dispatch = _React$useState2[1];
return React.useCallback(function () {
dispatch(Object.create(null));
}, []);
}
/**
* Passes or assigns a value to multiple refs (typically a DOM node). Useful for
* dealing with components that need an explicit ref for DOM calculations but
* also forwards refs assigned by an app.
*
* @param refs Refs to fork
*/
function useForkedRef() {
for (var _len4 = arguments.length, refs = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
refs[_key4] = arguments[_key4];
}
return React.useMemo(function () {
if (refs.every(function (ref) {
return ref == null;
})) {
return null;
}
return function (node) {
refs.forEach(function (ref) {
assignRef(ref, node);
});
}; // eslint-disable-next-line react-hooks/exhaustive-deps
}, [].concat(refs));
}
/**
* Returns the previous value of a reference after a component update.
*
* @param value
*/
function usePrevious(value) {
var ref = React.useRef(null);
React.useEffect(function () {
ref.current = value;
}, [value]);
return ref.current;
}
/**
* Converts a callback to a ref to avoid triggering re-renders when passed as a
* prop and exposed as a stable function to avoid executing effects when
* passed as a dependency.
*/
function useStableCallback(callback) {
var callbackRef = React.useRef(callback);
React.useEffect(function () {
callbackRef.current = callback;
}); // eslint-disable-next-line react-hooks/exhaustive-deps
return React.useCallback(function () {
callbackRef.current && callbackRef.current.apply(callbackRef, arguments);
}, []);
}
/**
* Call an effect after a component update, skipping the initial mount.
*
* @param effect Effect to call
* @param deps Effect dependency list
*/
function useUpdateEffect(effect, deps) {
var mounted = React.useRef(false);
React.useEffect(function () {
if (mounted.current) {
effect();
} else {
mounted.current = true;
} // eslint-disable-next-line react-hooks/exhaustive-deps
}, deps);
}
/**
* Just a lil state logger
*
* @param state
* @param DEBUG
*/
exports.useStateLogger = noop;
if (process.env.NODE_ENV !== "production") {
exports.useStateLogger = function useStateLogger(state, DEBUG) {
if (DEBUG === void 0) {
DEBUG = false;
}
var debugRef = React.useRef(DEBUG);
React.useEffect(function () {
debugRef.current = DEBUG;
}, [DEBUG]);
React.useEffect(function () {
if (debugRef.current) {
console.group("State Updated");
console.log("%c" + state, "font-weight: normal; font-size: 120%; font-style: italic;");
console.groupEnd();
}
}, [state]);
};
}
/**
* Wraps a lib-defined event handler and a user-defined event handler, returning
* a single handler that allows a user to prevent lib-defined handlers from
* firing.
*
* @param theirHandler User-supplied event handler
* @param ourHandler Library-supplied event handler
*/
function wrapEvent(theirHandler, ourHandler) {
return function (event) {
theirHandler && theirHandler(event);
if (!event.defaultPrevented) {
return ourHandler(event);
}
};
} // Export types
exports.assignRef = assignRef;
exports.boolOrBoolString = boolOrBoolString;
exports.canUseDOM = canUseDOM;
exports.cloneValidElement = cloneValidElement;
exports.createNamedContext = createNamedContext;
exports.forwardRefWithAs = forwardRefWithAs;
exports.getDocumentDimensions = getDocumentDimensions;
exports.getElementComputedStyle = getElementComputedStyle;
exports.getOwnerDocument = getOwnerDocument;
exports.getOwnerWindow = getOwnerWindow;
exports.getScrollPosition = getScrollPosition;
exports.getScrollbarOffset = getScrollbarOffset;
exports.isBoolean = isBoolean;
exports.isFunction = isFunction;
exports.isNumber = isNumber;
exports.isRightClick = isRightClick;
exports.isString = isString;
exports.makeId = makeId;
exports.memoWithAs = memoWithAs;
exports.noop = noop;
exports.stateToAttributeString = stateToAttributeString;
exports.useCallbackProp = useCallbackProp;
exports.useConstant = useConstant;
exports.useControlledState = useControlledState;
exports.useEventCallback = useEventCallback;
exports.useEventListener = useEventListener;
exports.useFocusChange = useFocusChange;
exports.useForceUpdate = useForceUpdate;
exports.useForkedRef = useForkedRef;
exports.useIsomorphicLayoutEffect = useIsomorphicLayoutEffect;
exports.useLazyRef = useLazyRef;
exports.usePrevious = usePrevious;
exports.useStableCallback = useStableCallback;
exports.useUpdateEffect = useUpdateEffect;
exports.warning = warning;
exports.wrapEvent = wrapEvent;
exports.canUseDOM = canUseDom_dist_reachUtilsCanUseDom.canUseDOM;
exports.cloneValidElement = cloneValidElement_dist_reachUtilsCloneValidElement.cloneValidElement;
exports.composeEventHandlers = composeEventHandlers_dist_reachUtilsComposeEventHandlers.composeEventHandlers;
exports.assignRef = composeRefs_dist_reachUtilsComposeRefs.assignRef;
exports.useComposedRefs = composeRefs_dist_reachUtilsComposeRefs.useComposedRefs;
exports.getComputedStyle = computedStyles_dist_reachUtilsComputedStyles.getComputedStyle;
exports.getComputedStyles = computedStyles_dist_reachUtilsComputedStyles.getComputedStyles;
exports.createNamedContext = context_dist_reachUtilsContext.createNamedContext;
exports.checkStyles = devUtils_dist_reachUtilsDevUtils.checkStyles;
exports.useCheckStyles = devUtils_dist_reachUtilsDevUtils.useCheckStyles;
exports.useControlledSwitchWarning = devUtils_dist_reachUtilsDevUtils.useControlledSwitchWarning;
exports.useStateLogger = devUtils_dist_reachUtilsDevUtils.useStateLogger;
exports.getDocumentDimensions = getDocumentDimensions_dist_reachUtilsGetDocumentDimensions.getDocumentDimensions;
exports.getScrollPosition = getScrollPosition_dist_reachUtilsGetScrollPosition.getScrollPosition;
exports.getScrollbarOffset = getScrollbarOffset_dist_reachUtilsGetScrollbarOffset.getScrollbarOffset;
exports.isRightClick = isRightClick_dist_reachUtilsIsRightClick.isRightClick;
exports.makeId = makeId_dist_reachUtilsMakeId.makeId;
exports.noop = noop_dist_reachUtilsNoop.noop;
exports.getOwnerDocument = ownerDocument_dist_reachUtilsOwnerDocument.getOwnerDocument;
exports.getOwnerWindow = ownerDocument_dist_reachUtilsOwnerDocument.getOwnerWindow;
exports.isBoolean = typeCheck_dist_reachUtilsTypeCheck.isBoolean;
exports.isFunction = typeCheck_dist_reachUtilsTypeCheck.isFunction;
exports.isNumber = typeCheck_dist_reachUtilsTypeCheck.isNumber;
exports.isString = typeCheck_dist_reachUtilsTypeCheck.isString;
exports.useConstant = useConstant_dist_reachUtilsUseConstant.useConstant;
exports.useControlledState = useControlledState_dist_reachUtilsUseControlledState.useControlledState;
exports.useEventListener = useEventListener_dist_reachUtilsUseEventListener.useEventListener;
exports.useFocusChange = useFocusChange_dist_reachUtilsUseFocusChange.useFocusChange;
exports.useForceUpdate = useForceUpdate_dist_reachUtilsUseForceUpdate.useForceUpdate;
exports.useIsomorphicLayoutEffect = useIsomorphicLayoutEffect_dist_reachUtilsUseIsomorphicLayoutEffect.useIsomorphicLayoutEffect;
exports.useLazyRef = useLazyRef_dist_reachUtilsUseLazyRef.useLazyRef;
exports.usePrevious = usePrevious_dist_reachUtilsUsePrevious.usePrevious;
exports.useStableCallback = useStableCallback_dist_reachUtilsUseStableCallback.useStableCallback;
exports.useStableLayoutCallback = useStableCallback_dist_reachUtilsUseStableCallback.useStableLayoutCallback;
exports.useUpdateEffect = useUpdateEffect_dist_reachUtilsUseUpdateEffect.useUpdateEffect;

@@ -5,633 +5,65 @@ 'use strict';

var React = require('react');
var fbWarning = require('warning');
var canUseDom_dist_reachUtilsCanUseDom = require('../can-use-dom/dist/reach-utils-can-use-dom.cjs.prod.js');
var cloneValidElement_dist_reachUtilsCloneValidElement = require('../clone-valid-element/dist/reach-utils-clone-valid-element.cjs.prod.js');
var composeEventHandlers_dist_reachUtilsComposeEventHandlers = require('../compose-event-handlers/dist/reach-utils-compose-event-handlers.cjs.prod.js');
var composeRefs_dist_reachUtilsComposeRefs = require('../compose-refs/dist/reach-utils-compose-refs.cjs.prod.js');
var computedStyles_dist_reachUtilsComputedStyles = require('../computed-styles/dist/reach-utils-computed-styles.cjs.prod.js');
var context_dist_reachUtilsContext = require('../context/dist/reach-utils-context.cjs.prod.js');
var devUtils_dist_reachUtilsDevUtils = require('../dev-utils/dist/reach-utils-dev-utils.cjs.prod.js');
var getDocumentDimensions_dist_reachUtilsGetDocumentDimensions = require('../get-document-dimensions/dist/reach-utils-get-document-dimensions.cjs.prod.js');
var getScrollPosition_dist_reachUtilsGetScrollPosition = require('../get-scroll-position/dist/reach-utils-get-scroll-position.cjs.prod.js');
var getScrollbarOffset_dist_reachUtilsGetScrollbarOffset = require('../get-scrollbar-offset/dist/reach-utils-get-scrollbar-offset.cjs.prod.js');
var isRightClick_dist_reachUtilsIsRightClick = require('../is-right-click/dist/reach-utils-is-right-click.cjs.prod.js');
var makeId_dist_reachUtilsMakeId = require('../make-id/dist/reach-utils-make-id.cjs.prod.js');
var noop_dist_reachUtilsNoop = require('../noop/dist/reach-utils-noop.cjs.prod.js');
var ownerDocument_dist_reachUtilsOwnerDocument = require('../owner-document/dist/reach-utils-owner-document.cjs.prod.js');
var typeCheck_dist_reachUtilsTypeCheck = require('../type-check/dist/reach-utils-type-check.cjs.prod.js');
var useConstant_dist_reachUtilsUseConstant = require('../use-constant/dist/reach-utils-use-constant.cjs.prod.js');
var useControlledState_dist_reachUtilsUseControlledState = require('../use-controlled-state/dist/reach-utils-use-controlled-state.cjs.prod.js');
var useEventListener_dist_reachUtilsUseEventListener = require('../use-event-listener/dist/reach-utils-use-event-listener.cjs.prod.js');
var useFocusChange_dist_reachUtilsUseFocusChange = require('../use-focus-change/dist/reach-utils-use-focus-change.cjs.prod.js');
var useForceUpdate_dist_reachUtilsUseForceUpdate = require('../use-force-update/dist/reach-utils-use-force-update.cjs.prod.js');
var useIsomorphicLayoutEffect_dist_reachUtilsUseIsomorphicLayoutEffect = require('../use-isomorphic-layout-effect/dist/reach-utils-use-isomorphic-layout-effect.cjs.prod.js');
var useLazyRef_dist_reachUtilsUseLazyRef = require('../use-lazy-ref/dist/reach-utils-use-lazy-ref.cjs.prod.js');
var usePrevious_dist_reachUtilsUsePrevious = require('../use-previous/dist/reach-utils-use-previous.cjs.prod.js');
var useStableCallback_dist_reachUtilsUseStableCallback = require('../use-stable-callback/dist/reach-utils-use-stable-callback.cjs.prod.js');
var useUpdateEffect_dist_reachUtilsUseUpdateEffect = require('../use-update-effect/dist/reach-utils-use-update-effect.cjs.prod.js');
require('react');
function _interopDefault (e) { return e && e.__esModule ? e : { 'default': e }; }
function _interopNamespace(e) {
if (e && e.__esModule) return e;
var n = Object.create(null);
if (e) {
Object.keys(e).forEach(function (k) {
if (k !== 'default') {
var d = Object.getOwnPropertyDescriptor(e, k);
Object.defineProperty(n, k, d.get ? d : {
enumerable: true,
get: function () {
return e[k];
}
});
}
});
}
n['default'] = e;
return Object.freeze(n);
}
var React__namespace = /*#__PURE__*/_interopNamespace(React);
var fbWarning__default = /*#__PURE__*/_interopDefault(fbWarning);
/* eslint-disable no-restricted-globals, eqeqeq */
/**
* React currently throws a warning when using useLayoutEffect on the server.
* To get around it, we can conditionally useEffect on the server (no-op) and
* useLayoutEffect in the browser. We occasionally need useLayoutEffect to
* ensure we don't get a render flash for certain operations, but we may also
* need affected components to render on the server. One example is when setting
* a component's descendants to retrieve their index values.
*
* Important to note that using this hook as an escape hatch will break the
* eslint dependency warnings unless you rename the import to `useLayoutEffect`.
* Use sparingly only when the effect won't effect the rendered HTML to avoid
* any server/client mismatch.
*
* If a useLayoutEffect is needed and the result would create a mismatch, it's
* likely that the component in question shouldn't be rendered on the server at
* all, so a better approach would be to lazily render those in a parent
* component after client-side hydration.
*
* TODO: We are calling useLayoutEffect in a couple of places that will likely
* cause some issues for SSR users, whether the warning shows or not. Audit and
* fix these.
*
* https://gist.github.com/gaearon/e7d97cdf38a2907924ea12e4ebdf3c85
* https://github.com/reduxjs/react-redux/blob/master/src/utils/useIsomorphicLayoutEffect.js
*
* @param effect
* @param deps
*/
var useIsomorphicLayoutEffect = /*#__PURE__*/canUseDOM() ? React.useLayoutEffect : React.useEffect;
/**
* Copy of Facebook's warning package.
*
* Similar to invariant but only logs a warning if the condition is not met.
* This can be used to log issues in development environments in critical paths.
* Removing the logging code for production environments will keep the same
* logic and follow the same code paths.
*
* @see https://github.com/BerkeleyTrue/warning/blob/master/warning.js
*/
var warning = fbWarning__default['default'];
/**
* When in dev mode, checks that styles for a given @reach package are loaded.
*
* @param packageName Name of the package to check.
* @example checkStyles("dialog") will check for styles for @reach/dialog
*/
var checkStyles = noop;
/**
* Passes or assigns an arbitrary value to a ref function or object.
*
* @param ref
* @param value
*/
function assignRef(ref, value) {
if (ref == null) return;
if (isFunction(ref)) {
ref(value);
} else {
try {
ref.current = value;
} catch (error) {
throw new Error("Cannot assign value \"" + value + "\" to ref \"" + ref + "\"");
}
}
}
/**
* Checks true|"true" vs false|"false"
*
* @param value
*/
function boolOrBoolString(value) {
return value === "true" ? true : isBoolean(value) ? value : false;
}
function canUseDOM() {
return !!(typeof window !== "undefined" && window.document && window.document.createElement);
}
/**
* Type-safe clone element
*
* @param element
* @param props
* @param children
*/
function cloneValidElement(element, props) {
for (var _len = arguments.length, children = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
children[_key - 2] = arguments[_key];
}
return /*#__PURE__*/React.isValidElement(element) ? React.cloneElement.apply(React__namespace, [element, props].concat(children)) : element;
}
function createNamedContext(name, defaultValue) {
var Ctx = /*#__PURE__*/React.createContext(defaultValue);
Ctx.displayName = name;
return Ctx;
}
/**
* This is a hack for sure. The thing is, getting a component to intelligently
* infer props based on a component or JSX string passed into an `as` prop is
* kind of a huge pain. Getting it to work and satisfy the constraints of
* `forwardRef` seems dang near impossible. To avoid needing to do this awkward
* type song-and-dance every time we want to forward a ref into a component
* that accepts an `as` prop, we abstract all of that mess to this function for
* the time time being.
*/
function forwardRefWithAs(render) {
return /*#__PURE__*/React.forwardRef(render);
}
function memoWithAs(Component, propsAreEqual) {
return /*#__PURE__*/React.memo(Component, propsAreEqual);
}
/**
* Get the size of the working document minus the scrollbar offset.
*
* @param element
*/
function getDocumentDimensions(element) {
var _ownerDocument$docume, _ownerDocument$docume2;
var ownerDocument = getOwnerDocument(element);
var ownerWindow = ownerDocument.defaultView || window;
if (!ownerDocument) {
return {
width: 0,
height: 0
};
}
return {
width: (_ownerDocument$docume = ownerDocument.documentElement.clientWidth) != null ? _ownerDocument$docume : ownerWindow.innerWidth,
height: (_ownerDocument$docume2 = ownerDocument.documentElement.clientHeight) != null ? _ownerDocument$docume2 : ownerWindow.innerHeight
};
}
/**
* Get the scoll position of the global window object relative to a given node.
*
* @param element
*/
function getScrollPosition(element) {
var ownerDocument = getOwnerDocument(element);
var ownerWindow = ownerDocument.defaultView || window;
if (!ownerDocument) {
return {
scrollX: 0,
scrollY: 0
};
}
return {
scrollX: ownerWindow.scrollX,
scrollY: ownerWindow.scrollY
};
}
/**
* Get a computed style value by property.
*
* @param element
* @param styleProp
*/
function getElementComputedStyle(element, styleProp) {
var ownerDocument = getOwnerDocument(element);
var ownerWindow = (ownerDocument == null ? void 0 : ownerDocument.defaultView) || window;
if (ownerWindow) {
return ownerWindow.getComputedStyle(element, null).getPropertyValue(styleProp);
}
return null;
}
/**
* Get an element's owner document. Useful when components are used in iframes
* or other environments like dev tools.
*
* @param element
*/
function getOwnerDocument(element) {
return canUseDOM() ? element ? element.ownerDocument : document : null;
}
/**
* TODO: Remove in 1.0
*/
function getOwnerWindow(element) {
var ownerDocument = getOwnerDocument(element);
return ownerDocument ? ownerDocument.defaultView || window : null;
}
/**
* Get the scrollbar offset distance.
*
* TODO: Remove in 1.0 (we used this in public examples)
*/
function getScrollbarOffset() {
try {
if (window.innerWidth > document.documentElement.clientWidth) {
return window.innerWidth - document.documentElement.clientWidth;
}
} catch (err) {}
return 0;
}
/**
* Checks whether or not a value is a boolean.
*
* @param value
*/
function isBoolean(value) {
return typeof value === "boolean";
}
/**
* Checks whether or not a value is a function.
*
* @param value
*/
function isFunction(value) {
return !!(value && {}.toString.call(value) == "[object Function]");
}
/**
* Checks whether or not a value is a number.
*
* @param value
*/
function isNumber(value) {
return typeof value === "number" && !isNaN(value);
}
/**
* Detects right clicks
*
* @param nativeEvent
*/
function isRightClick(nativeEvent) {
return "which" in nativeEvent ? nativeEvent.which === 3 : "button" in nativeEvent ? nativeEvent.button === 2 : false;
}
/**
* Checks whether or not a value is a string.
*
* @param value
*/
function isString(value) {
return typeof value === "string";
}
/**
* Joins strings to format IDs for compound components.
*
* @param args
*/
function makeId() {
for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
return args.filter(function (val) {
return val != null;
}).join("--");
}
/**
* No-op function.
*/
function noop() {}
/**
* Convert our state strings for HTML data attributes.
* No need for a fancy kebab-caser here, we know what our state strings are!
*
* @param state
*/
function stateToAttributeString(state) {
return String(state).replace(/([\s_]+)/g, "-").toLowerCase();
}
/**
* Check if a component is controlled or uncontrolled and return the correct
* state value and setter accordingly. If the component state is controlled by
* the app, the setter is a noop.
*
* @param controlledValue
* @param defaultValue
*/
function useControlledState(controlledValue, defaultValue) {
var controlledRef = React.useRef(controlledValue != null);
var _React$useState = React.useState(defaultValue),
valueState = _React$useState[0],
setValue = _React$useState[1];
var set = React.useCallback(function (n) {
if (!controlledRef.current) {
setValue(n);
}
}, []);
return [controlledRef.current ? controlledValue : valueState, set];
}
/**
* Logs a warning in dev mode when a component switches from controlled to
* uncontrolled, or vice versa
*
* A single prop should typically be used to determine whether or not a
* component is controlled or not.
*
* @param controlledValue
* @param controlledPropName
* @param componentName
*/
var useControlledSwitchWarning = noop;
var useCheckStyles = noop;
/**
* React hook for creating a value exactly once.
* @see https://github.com/Andarist/use-constant
*/
function useConstant(fn) {
var ref = React.useRef();
if (!ref.current) {
ref.current = {
v: fn()
};
}
return ref.current.v;
}
/**
* @param callback
*/
function useEventCallback(callback) {
var ref = React.useRef(callback);
useIsomorphicLayoutEffect(function () {
ref.current = callback;
});
return React.useCallback(function (event) {
for (var _len3 = arguments.length, args = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) {
args[_key3 - 1] = arguments[_key3];
}
return ref.current.apply(ref, [event].concat(args));
}, []);
}
function useLazyRef(fn) {
var ref = React.useRef({
__internalSet: true
});
if (ref.current && ref.current.__internalSet === true) {
ref.current = fn();
}
return ref;
}
/**
* TODO: Remove in 1.0
* @alias useStableCallback
* @param callback
*/
var useCallbackProp = useStableCallback;
/**
* Adds a DOM event listener
*
* @param eventName
* @param listener
* @param element
*/
function useEventListener(eventName, listener, element) {
if (element === void 0) {
element = window;
}
var savedHandler = React.useRef(listener);
React.useEffect(function () {
savedHandler.current = listener;
}, [listener]);
React.useEffect(function () {
var isSupported = element && element.addEventListener;
if (!isSupported) {
return;
}
function eventListener(event) {
savedHandler.current(event);
}
element.addEventListener(eventName, eventListener);
return function () {
element.removeEventListener(eventName, eventListener);
};
}, [eventName, element]);
}
/**
* Detect when focus changes in our document.
*
* @param handleChange
* @param when
* @param ownerDocument
*/
function useFocusChange(handleChange, when, ownerDocument) {
if (handleChange === void 0) {
handleChange = console.log;
}
if (when === void 0) {
when = "focus";
}
if (ownerDocument === void 0) {
ownerDocument = document;
}
var lastActiveElement = React.useRef(ownerDocument.activeElement);
React.useEffect(function () {
lastActiveElement.current = ownerDocument.activeElement;
function onChange(event) {
if (lastActiveElement.current !== ownerDocument.activeElement) {
handleChange(ownerDocument.activeElement, lastActiveElement.current, event);
lastActiveElement.current = ownerDocument.activeElement;
}
}
ownerDocument.addEventListener(when, onChange, true);
return function () {
ownerDocument.removeEventListener(when, onChange);
};
}, [when, handleChange, ownerDocument]);
}
/**
* Forces a re-render, similar to `forceUpdate` in class components.
*/
function useForceUpdate() {
var _React$useState2 = React.useState(Object.create(null)),
dispatch = _React$useState2[1];
return React.useCallback(function () {
dispatch(Object.create(null));
}, []);
}
/**
* Passes or assigns a value to multiple refs (typically a DOM node). Useful for
* dealing with components that need an explicit ref for DOM calculations but
* also forwards refs assigned by an app.
*
* @param refs Refs to fork
*/
function useForkedRef() {
for (var _len4 = arguments.length, refs = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
refs[_key4] = arguments[_key4];
}
return React.useMemo(function () {
if (refs.every(function (ref) {
return ref == null;
})) {
return null;
}
return function (node) {
refs.forEach(function (ref) {
assignRef(ref, node);
});
}; // eslint-disable-next-line react-hooks/exhaustive-deps
}, [].concat(refs));
}
/**
* Returns the previous value of a reference after a component update.
*
* @param value
*/
function usePrevious(value) {
var ref = React.useRef(null);
React.useEffect(function () {
ref.current = value;
}, [value]);
return ref.current;
}
/**
* Converts a callback to a ref to avoid triggering re-renders when passed as a
* prop and exposed as a stable function to avoid executing effects when
* passed as a dependency.
*/
function useStableCallback(callback) {
var callbackRef = React.useRef(callback);
React.useEffect(function () {
callbackRef.current = callback;
}); // eslint-disable-next-line react-hooks/exhaustive-deps
return React.useCallback(function () {
callbackRef.current && callbackRef.current.apply(callbackRef, arguments);
}, []);
}
/**
* Call an effect after a component update, skipping the initial mount.
*
* @param effect Effect to call
* @param deps Effect dependency list
*/
function useUpdateEffect(effect, deps) {
var mounted = React.useRef(false);
React.useEffect(function () {
if (mounted.current) {
effect();
} else {
mounted.current = true;
} // eslint-disable-next-line react-hooks/exhaustive-deps
}, deps);
}
/**
* Just a lil state logger
*
* @param state
* @param DEBUG
*/
var useStateLogger = noop;
/**
* Wraps a lib-defined event handler and a user-defined event handler, returning
* a single handler that allows a user to prevent lib-defined handlers from
* firing.
*
* @param theirHandler User-supplied event handler
* @param ourHandler Library-supplied event handler
*/
function wrapEvent(theirHandler, ourHandler) {
return function (event) {
theirHandler && theirHandler(event);
if (!event.defaultPrevented) {
return ourHandler(event);
}
};
} // Export types
exports.assignRef = assignRef;
exports.boolOrBoolString = boolOrBoolString;
exports.canUseDOM = canUseDOM;
exports.checkStyles = checkStyles;
exports.cloneValidElement = cloneValidElement;
exports.createNamedContext = createNamedContext;
exports.forwardRefWithAs = forwardRefWithAs;
exports.getDocumentDimensions = getDocumentDimensions;
exports.getElementComputedStyle = getElementComputedStyle;
exports.getOwnerDocument = getOwnerDocument;
exports.getOwnerWindow = getOwnerWindow;
exports.getScrollPosition = getScrollPosition;
exports.getScrollbarOffset = getScrollbarOffset;
exports.isBoolean = isBoolean;
exports.isFunction = isFunction;
exports.isNumber = isNumber;
exports.isRightClick = isRightClick;
exports.isString = isString;
exports.makeId = makeId;
exports.memoWithAs = memoWithAs;
exports.noop = noop;
exports.stateToAttributeString = stateToAttributeString;
exports.useCallbackProp = useCallbackProp;
exports.useCheckStyles = useCheckStyles;
exports.useConstant = useConstant;
exports.useControlledState = useControlledState;
exports.useControlledSwitchWarning = useControlledSwitchWarning;
exports.useEventCallback = useEventCallback;
exports.useEventListener = useEventListener;
exports.useFocusChange = useFocusChange;
exports.useForceUpdate = useForceUpdate;
exports.useForkedRef = useForkedRef;
exports.useIsomorphicLayoutEffect = useIsomorphicLayoutEffect;
exports.useLazyRef = useLazyRef;
exports.usePrevious = usePrevious;
exports.useStableCallback = useStableCallback;
exports.useStateLogger = useStateLogger;
exports.useUpdateEffect = useUpdateEffect;
exports.warning = warning;
exports.wrapEvent = wrapEvent;
exports.canUseDOM = canUseDom_dist_reachUtilsCanUseDom.canUseDOM;
exports.cloneValidElement = cloneValidElement_dist_reachUtilsCloneValidElement.cloneValidElement;
exports.composeEventHandlers = composeEventHandlers_dist_reachUtilsComposeEventHandlers.composeEventHandlers;
exports.assignRef = composeRefs_dist_reachUtilsComposeRefs.assignRef;
exports.useComposedRefs = composeRefs_dist_reachUtilsComposeRefs.useComposedRefs;
exports.getComputedStyle = computedStyles_dist_reachUtilsComputedStyles.getComputedStyle;
exports.getComputedStyles = computedStyles_dist_reachUtilsComputedStyles.getComputedStyles;
exports.createNamedContext = context_dist_reachUtilsContext.createNamedContext;
exports.checkStyles = devUtils_dist_reachUtilsDevUtils.checkStyles;
exports.useCheckStyles = devUtils_dist_reachUtilsDevUtils.useCheckStyles;
exports.useControlledSwitchWarning = devUtils_dist_reachUtilsDevUtils.useControlledSwitchWarning;
exports.useStateLogger = devUtils_dist_reachUtilsDevUtils.useStateLogger;
exports.getDocumentDimensions = getDocumentDimensions_dist_reachUtilsGetDocumentDimensions.getDocumentDimensions;
exports.getScrollPosition = getScrollPosition_dist_reachUtilsGetScrollPosition.getScrollPosition;
exports.getScrollbarOffset = getScrollbarOffset_dist_reachUtilsGetScrollbarOffset.getScrollbarOffset;
exports.isRightClick = isRightClick_dist_reachUtilsIsRightClick.isRightClick;
exports.makeId = makeId_dist_reachUtilsMakeId.makeId;
exports.noop = noop_dist_reachUtilsNoop.noop;
exports.getOwnerDocument = ownerDocument_dist_reachUtilsOwnerDocument.getOwnerDocument;
exports.getOwnerWindow = ownerDocument_dist_reachUtilsOwnerDocument.getOwnerWindow;
exports.isBoolean = typeCheck_dist_reachUtilsTypeCheck.isBoolean;
exports.isFunction = typeCheck_dist_reachUtilsTypeCheck.isFunction;
exports.isNumber = typeCheck_dist_reachUtilsTypeCheck.isNumber;
exports.isString = typeCheck_dist_reachUtilsTypeCheck.isString;
exports.useConstant = useConstant_dist_reachUtilsUseConstant.useConstant;
exports.useControlledState = useControlledState_dist_reachUtilsUseControlledState.useControlledState;
exports.useEventListener = useEventListener_dist_reachUtilsUseEventListener.useEventListener;
exports.useFocusChange = useFocusChange_dist_reachUtilsUseFocusChange.useFocusChange;
exports.useForceUpdate = useForceUpdate_dist_reachUtilsUseForceUpdate.useForceUpdate;
exports.useIsomorphicLayoutEffect = useIsomorphicLayoutEffect_dist_reachUtilsUseIsomorphicLayoutEffect.useIsomorphicLayoutEffect;
exports.useLazyRef = useLazyRef_dist_reachUtilsUseLazyRef.useLazyRef;
exports.usePrevious = usePrevious_dist_reachUtilsUsePrevious.usePrevious;
exports.useStableCallback = useStableCallback_dist_reachUtilsUseStableCallback.useStableCallback;
exports.useStableLayoutCallback = useStableCallback_dist_reachUtilsUseStableCallback.useStableLayoutCallback;
exports.useUpdateEffect = useUpdateEffect_dist_reachUtilsUseUpdateEffect.useUpdateEffect;

@@ -1,654 +0,26 @@

import * as React from 'react';
import { useLayoutEffect, useEffect, isValidElement, cloneElement, createContext, forwardRef, memo, useRef, useState, useCallback, useMemo } from 'react';
import fbWarning from 'warning';
/* eslint-disable no-restricted-globals, eqeqeq */
/**
* React currently throws a warning when using useLayoutEffect on the server.
* To get around it, we can conditionally useEffect on the server (no-op) and
* useLayoutEffect in the browser. We occasionally need useLayoutEffect to
* ensure we don't get a render flash for certain operations, but we may also
* need affected components to render on the server. One example is when setting
* a component's descendants to retrieve their index values.
*
* Important to note that using this hook as an escape hatch will break the
* eslint dependency warnings unless you rename the import to `useLayoutEffect`.
* Use sparingly only when the effect won't effect the rendered HTML to avoid
* any server/client mismatch.
*
* If a useLayoutEffect is needed and the result would create a mismatch, it's
* likely that the component in question shouldn't be rendered on the server at
* all, so a better approach would be to lazily render those in a parent
* component after client-side hydration.
*
* TODO: We are calling useLayoutEffect in a couple of places that will likely
* cause some issues for SSR users, whether the warning shows or not. Audit and
* fix these.
*
* https://gist.github.com/gaearon/e7d97cdf38a2907924ea12e4ebdf3c85
* https://github.com/reduxjs/react-redux/blob/master/src/utils/useIsomorphicLayoutEffect.js
*
* @param effect
* @param deps
*/
var useIsomorphicLayoutEffect = /*#__PURE__*/canUseDOM() ? useLayoutEffect : useEffect;
var checkedPkgs = {};
/**
* Copy of Facebook's warning package.
*
* Similar to invariant but only logs a warning if the condition is not met.
* This can be used to log issues in development environments in critical paths.
* Removing the logging code for production environments will keep the same
* logic and follow the same code paths.
*
* @see https://github.com/BerkeleyTrue/warning/blob/master/warning.js
*/
var warning = fbWarning;
/**
* When in dev mode, checks that styles for a given @reach package are loaded.
*
* @param packageName Name of the package to check.
* @example checkStyles("dialog") will check for styles for @reach/dialog
*/
var checkStyles = noop;
if (process.env.NODE_ENV !== "production") {
// In CJS files, process.env.NODE_ENV is stripped from our build, but we need
// it to prevent style checks from clogging up user logs while testing.
// This is a workaround until we can tweak the build a bit to accommodate.
var _ref = typeof process !== "undefined" ? process : {
env: {
NODE_ENV: "development"
}
},
env = _ref.env;
checkStyles = function checkStyles(packageName) {
// only check once per package
if (checkedPkgs[packageName]) return;
checkedPkgs[packageName] = true;
if (env.NODE_ENV !== "test" && parseInt(window.getComputedStyle(document.body).getPropertyValue("--reach-" + packageName), 10) !== 1) {
console.warn("@reach/" + packageName + " styles not found. If you are using a bundler like webpack or parcel include this in the entry file of your app before any of your own styles:\n\n import \"@reach/" + packageName + "/styles.css\";\n\n Otherwise you'll need to include them some other way:\n\n <link rel=\"stylesheet\" type=\"text/css\" href=\"node_modules/@reach/" + packageName + "/styles.css\" />\n\n For more information visit https://ui.reach.tech/styling.\n ");
}
};
}
/**
* Passes or assigns an arbitrary value to a ref function or object.
*
* @param ref
* @param value
*/
function assignRef(ref, value) {
if (ref == null) return;
if (isFunction(ref)) {
ref(value);
} else {
try {
ref.current = value;
} catch (error) {
throw new Error("Cannot assign value \"" + value + "\" to ref \"" + ref + "\"");
}
}
}
/**
* Checks true|"true" vs false|"false"
*
* @param value
*/
function boolOrBoolString(value) {
return value === "true" ? true : isBoolean(value) ? value : false;
}
function canUseDOM() {
return !!(typeof window !== "undefined" && window.document && window.document.createElement);
}
/**
* Type-safe clone element
*
* @param element
* @param props
* @param children
*/
function cloneValidElement(element, props) {
for (var _len = arguments.length, children = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
children[_key - 2] = arguments[_key];
}
return /*#__PURE__*/isValidElement(element) ? cloneElement.apply(React, [element, props].concat(children)) : element;
}
function createNamedContext(name, defaultValue) {
var Ctx = /*#__PURE__*/createContext(defaultValue);
Ctx.displayName = name;
return Ctx;
}
/**
* This is a hack for sure. The thing is, getting a component to intelligently
* infer props based on a component or JSX string passed into an `as` prop is
* kind of a huge pain. Getting it to work and satisfy the constraints of
* `forwardRef` seems dang near impossible. To avoid needing to do this awkward
* type song-and-dance every time we want to forward a ref into a component
* that accepts an `as` prop, we abstract all of that mess to this function for
* the time time being.
*/
function forwardRefWithAs(render) {
return /*#__PURE__*/forwardRef(render);
}
function memoWithAs(Component, propsAreEqual) {
return /*#__PURE__*/memo(Component, propsAreEqual);
}
/**
* Get the size of the working document minus the scrollbar offset.
*
* @param element
*/
function getDocumentDimensions(element) {
var _ownerDocument$docume, _ownerDocument$docume2;
var ownerDocument = getOwnerDocument(element);
var ownerWindow = ownerDocument.defaultView || window;
if (!ownerDocument) {
return {
width: 0,
height: 0
};
}
return {
width: (_ownerDocument$docume = ownerDocument.documentElement.clientWidth) != null ? _ownerDocument$docume : ownerWindow.innerWidth,
height: (_ownerDocument$docume2 = ownerDocument.documentElement.clientHeight) != null ? _ownerDocument$docume2 : ownerWindow.innerHeight
};
}
/**
* Get the scoll position of the global window object relative to a given node.
*
* @param element
*/
function getScrollPosition(element) {
var ownerDocument = getOwnerDocument(element);
var ownerWindow = ownerDocument.defaultView || window;
if (!ownerDocument) {
return {
scrollX: 0,
scrollY: 0
};
}
return {
scrollX: ownerWindow.scrollX,
scrollY: ownerWindow.scrollY
};
}
/**
* Get a computed style value by property.
*
* @param element
* @param styleProp
*/
function getElementComputedStyle(element, styleProp) {
var ownerDocument = getOwnerDocument(element);
var ownerWindow = (ownerDocument == null ? void 0 : ownerDocument.defaultView) || window;
if (ownerWindow) {
return ownerWindow.getComputedStyle(element, null).getPropertyValue(styleProp);
}
return null;
}
/**
* Get an element's owner document. Useful when components are used in iframes
* or other environments like dev tools.
*
* @param element
*/
function getOwnerDocument(element) {
return canUseDOM() ? element ? element.ownerDocument : document : null;
}
/**
* TODO: Remove in 1.0
*/
function getOwnerWindow(element) {
var ownerDocument = getOwnerDocument(element);
return ownerDocument ? ownerDocument.defaultView || window : null;
}
/**
* Get the scrollbar offset distance.
*
* TODO: Remove in 1.0 (we used this in public examples)
*/
function getScrollbarOffset() {
try {
if (window.innerWidth > document.documentElement.clientWidth) {
return window.innerWidth - document.documentElement.clientWidth;
}
} catch (err) {}
return 0;
}
/**
* Checks whether or not a value is a boolean.
*
* @param value
*/
function isBoolean(value) {
return typeof value === "boolean";
}
/**
* Checks whether or not a value is a function.
*
* @param value
*/
function isFunction(value) {
return !!(value && {}.toString.call(value) == "[object Function]");
}
/**
* Checks whether or not a value is a number.
*
* @param value
*/
function isNumber(value) {
return typeof value === "number" && !isNaN(value);
}
/**
* Detects right clicks
*
* @param nativeEvent
*/
function isRightClick(nativeEvent) {
return "which" in nativeEvent ? nativeEvent.which === 3 : "button" in nativeEvent ? nativeEvent.button === 2 : false;
}
/**
* Checks whether or not a value is a string.
*
* @param value
*/
function isString(value) {
return typeof value === "string";
}
/**
* Joins strings to format IDs for compound components.
*
* @param args
*/
function makeId() {
for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
return args.filter(function (val) {
return val != null;
}).join("--");
}
/**
* No-op function.
*/
function noop() {}
/**
* Convert our state strings for HTML data attributes.
* No need for a fancy kebab-caser here, we know what our state strings are!
*
* @param state
*/
function stateToAttributeString(state) {
return String(state).replace(/([\s_]+)/g, "-").toLowerCase();
}
/**
* Check if a component is controlled or uncontrolled and return the correct
* state value and setter accordingly. If the component state is controlled by
* the app, the setter is a noop.
*
* @param controlledValue
* @param defaultValue
*/
function useControlledState(controlledValue, defaultValue) {
var controlledRef = useRef(controlledValue != null);
var _React$useState = useState(defaultValue),
valueState = _React$useState[0],
setValue = _React$useState[1];
var set = useCallback(function (n) {
if (!controlledRef.current) {
setValue(n);
}
}, []);
return [controlledRef.current ? controlledValue : valueState, set];
}
/**
* Logs a warning in dev mode when a component switches from controlled to
* uncontrolled, or vice versa
*
* A single prop should typically be used to determine whether or not a
* component is controlled or not.
*
* @param controlledValue
* @param controlledPropName
* @param componentName
*/
var useControlledSwitchWarning = noop;
if (process.env.NODE_ENV !== "production") {
useControlledSwitchWarning = function useControlledSwitchWarning(controlledValue, controlledPropName, componentName) {
var controlledRef = useRef(controlledValue != null);
var nameCache = useRef({
componentName: componentName,
controlledPropName: controlledPropName
});
useEffect(function () {
nameCache.current = {
componentName: componentName,
controlledPropName: controlledPropName
};
}, [componentName, controlledPropName]);
useEffect(function () {
var wasControlled = controlledRef.current;
var _nameCache$current = nameCache.current,
componentName = _nameCache$current.componentName,
controlledPropName = _nameCache$current.controlledPropName;
var isControlled = controlledValue != null;
if (wasControlled !== isControlled) {
console.error("A component is changing an " + (wasControlled ? "" : "un") + "controlled `" + controlledPropName + "` state of " + componentName + " to be " + (wasControlled ? "un" : "") + "controlled. This is likely caused by the value changing from undefined to a defined value, which should not happen. Decide between using a controlled or uncontrolled " + componentName + " element for the lifetime of the component.\nMore info: https://fb.me/react-controlled-components");
}
}, [controlledValue]);
};
}
var useCheckStyles = noop;
if (process.env.NODE_ENV !== "production") {
useCheckStyles = function useCheckStyles(pkg) {
var name = useRef(pkg);
useEffect(function () {
return void (name.current = pkg);
}, [pkg]);
useEffect(function () {
return checkStyles(name.current);
}, []);
};
}
/**
* React hook for creating a value exactly once.
* @see https://github.com/Andarist/use-constant
*/
function useConstant(fn) {
var ref = useRef();
if (!ref.current) {
ref.current = {
v: fn()
};
}
return ref.current.v;
}
/**
* @param callback
*/
function useEventCallback(callback) {
var ref = useRef(callback);
useIsomorphicLayoutEffect(function () {
ref.current = callback;
});
return useCallback(function (event) {
for (var _len3 = arguments.length, args = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) {
args[_key3 - 1] = arguments[_key3];
}
return ref.current.apply(ref, [event].concat(args));
}, []);
}
function useLazyRef(fn) {
var ref = useRef({
__internalSet: true
});
if (ref.current && ref.current.__internalSet === true) {
ref.current = fn();
}
return ref;
}
/**
* TODO: Remove in 1.0
* @alias useStableCallback
* @param callback
*/
var useCallbackProp = useStableCallback;
/**
* Adds a DOM event listener
*
* @param eventName
* @param listener
* @param element
*/
function useEventListener(eventName, listener, element) {
if (element === void 0) {
element = window;
}
var savedHandler = useRef(listener);
useEffect(function () {
savedHandler.current = listener;
}, [listener]);
useEffect(function () {
var isSupported = element && element.addEventListener;
if (!isSupported) {
if (process.env.NODE_ENV !== "production") {
console.warn("Event listener not supported on the element provided");
}
return;
}
function eventListener(event) {
savedHandler.current(event);
}
element.addEventListener(eventName, eventListener);
return function () {
element.removeEventListener(eventName, eventListener);
};
}, [eventName, element]);
}
/**
* Detect when focus changes in our document.
*
* @param handleChange
* @param when
* @param ownerDocument
*/
function useFocusChange(handleChange, when, ownerDocument) {
if (handleChange === void 0) {
handleChange = console.log;
}
if (when === void 0) {
when = "focus";
}
if (ownerDocument === void 0) {
ownerDocument = document;
}
var lastActiveElement = useRef(ownerDocument.activeElement);
useEffect(function () {
lastActiveElement.current = ownerDocument.activeElement;
function onChange(event) {
if (lastActiveElement.current !== ownerDocument.activeElement) {
handleChange(ownerDocument.activeElement, lastActiveElement.current, event);
lastActiveElement.current = ownerDocument.activeElement;
}
}
ownerDocument.addEventListener(when, onChange, true);
return function () {
ownerDocument.removeEventListener(when, onChange);
};
}, [when, handleChange, ownerDocument]);
}
/**
* Forces a re-render, similar to `forceUpdate` in class components.
*/
function useForceUpdate() {
var _React$useState2 = useState(Object.create(null)),
dispatch = _React$useState2[1];
return useCallback(function () {
dispatch(Object.create(null));
}, []);
}
/**
* Passes or assigns a value to multiple refs (typically a DOM node). Useful for
* dealing with components that need an explicit ref for DOM calculations but
* also forwards refs assigned by an app.
*
* @param refs Refs to fork
*/
function useForkedRef() {
for (var _len4 = arguments.length, refs = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
refs[_key4] = arguments[_key4];
}
return useMemo(function () {
if (refs.every(function (ref) {
return ref == null;
})) {
return null;
}
return function (node) {
refs.forEach(function (ref) {
assignRef(ref, node);
});
}; // eslint-disable-next-line react-hooks/exhaustive-deps
}, [].concat(refs));
}
/**
* Returns the previous value of a reference after a component update.
*
* @param value
*/
function usePrevious(value) {
var ref = useRef(null);
useEffect(function () {
ref.current = value;
}, [value]);
return ref.current;
}
/**
* Converts a callback to a ref to avoid triggering re-renders when passed as a
* prop and exposed as a stable function to avoid executing effects when
* passed as a dependency.
*/
function useStableCallback(callback) {
var callbackRef = useRef(callback);
useEffect(function () {
callbackRef.current = callback;
}); // eslint-disable-next-line react-hooks/exhaustive-deps
return useCallback(function () {
callbackRef.current && callbackRef.current.apply(callbackRef, arguments);
}, []);
}
/**
* Call an effect after a component update, skipping the initial mount.
*
* @param effect Effect to call
* @param deps Effect dependency list
*/
function useUpdateEffect(effect, deps) {
var mounted = useRef(false);
useEffect(function () {
if (mounted.current) {
effect();
} else {
mounted.current = true;
} // eslint-disable-next-line react-hooks/exhaustive-deps
}, deps);
}
/**
* Just a lil state logger
*
* @param state
* @param DEBUG
*/
var useStateLogger = noop;
if (process.env.NODE_ENV !== "production") {
useStateLogger = function useStateLogger(state, DEBUG) {
if (DEBUG === void 0) {
DEBUG = false;
}
var debugRef = useRef(DEBUG);
useEffect(function () {
debugRef.current = DEBUG;
}, [DEBUG]);
useEffect(function () {
if (debugRef.current) {
console.group("State Updated");
console.log("%c" + state, "font-weight: normal; font-size: 120%; font-style: italic;");
console.groupEnd();
}
}, [state]);
};
}
/**
* Wraps a lib-defined event handler and a user-defined event handler, returning
* a single handler that allows a user to prevent lib-defined handlers from
* firing.
*
* @param theirHandler User-supplied event handler
* @param ourHandler Library-supplied event handler
*/
function wrapEvent(theirHandler, ourHandler) {
return function (event) {
theirHandler && theirHandler(event);
if (!event.defaultPrevented) {
return ourHandler(event);
}
};
} // Export types
export { assignRef, boolOrBoolString, canUseDOM, checkStyles, cloneValidElement, createNamedContext, forwardRefWithAs, getDocumentDimensions, getElementComputedStyle, getOwnerDocument, getOwnerWindow, getScrollPosition, getScrollbarOffset, isBoolean, isFunction, isNumber, isRightClick, isString, makeId, memoWithAs, noop, stateToAttributeString, useCallbackProp, useCheckStyles, useConstant, useControlledState, useControlledSwitchWarning, useEventCallback, useEventListener, useFocusChange, useForceUpdate, useForkedRef, useIsomorphicLayoutEffect, useLazyRef, usePrevious, useStableCallback, useStateLogger, useUpdateEffect, warning, wrapEvent };
export { canUseDOM } from '../can-use-dom/dist/reach-utils-can-use-dom.esm.js';
export { cloneValidElement } from '../clone-valid-element/dist/reach-utils-clone-valid-element.esm.js';
export { composeEventHandlers } from '../compose-event-handlers/dist/reach-utils-compose-event-handlers.esm.js';
export { assignRef, useComposedRefs } from '../compose-refs/dist/reach-utils-compose-refs.esm.js';
export { getComputedStyle, getComputedStyles } from '../computed-styles/dist/reach-utils-computed-styles.esm.js';
export { createNamedContext } from '../context/dist/reach-utils-context.esm.js';
export { checkStyles, useCheckStyles, useControlledSwitchWarning, useStateLogger } from '../dev-utils/dist/reach-utils-dev-utils.esm.js';
export { getDocumentDimensions } from '../get-document-dimensions/dist/reach-utils-get-document-dimensions.esm.js';
export { getScrollPosition } from '../get-scroll-position/dist/reach-utils-get-scroll-position.esm.js';
export { getScrollbarOffset } from '../get-scrollbar-offset/dist/reach-utils-get-scrollbar-offset.esm.js';
export { isRightClick } from '../is-right-click/dist/reach-utils-is-right-click.esm.js';
export { makeId } from '../make-id/dist/reach-utils-make-id.esm.js';
export { noop } from '../noop/dist/reach-utils-noop.esm.js';
export { getOwnerDocument, getOwnerWindow } from '../owner-document/dist/reach-utils-owner-document.esm.js';
export { isBoolean, isFunction, isNumber, isString } from '../type-check/dist/reach-utils-type-check.esm.js';
export { useConstant } from '../use-constant/dist/reach-utils-use-constant.esm.js';
export { useControlledState } from '../use-controlled-state/dist/reach-utils-use-controlled-state.esm.js';
export { useEventListener } from '../use-event-listener/dist/reach-utils-use-event-listener.esm.js';
export { useFocusChange } from '../use-focus-change/dist/reach-utils-use-focus-change.esm.js';
export { useForceUpdate } from '../use-force-update/dist/reach-utils-use-force-update.esm.js';
export { useIsomorphicLayoutEffect } from '../use-isomorphic-layout-effect/dist/reach-utils-use-isomorphic-layout-effect.esm.js';
export { useLazyRef } from '../use-lazy-ref/dist/reach-utils-use-lazy-ref.esm.js';
export { usePrevious } from '../use-previous/dist/reach-utils-use-previous.esm.js';
export { useStableCallback, useStableLayoutCallback } from '../use-stable-callback/dist/reach-utils-use-stable-callback.esm.js';
export { useUpdateEffect } from '../use-update-effect/dist/reach-utils-use-update-effect.esm.js';
import 'react';
{
"name": "@reach/utils",
"version": "0.14.0",
"version": "0.15.0",
"description": "Internal, shared utilities for Reach UI.",
"author": "React Training <hello@reacttraining.com>",
"license": "MIT",
"sideEffects": false,
"repository": {

@@ -14,9 +13,8 @@ "type": "git",

"dependencies": {
"@types/warning": "^3.0.0",
"tslib": "^2.1.0",
"warning": "^4.0.3"
"tiny-warning": "^1.0.3",
"tslib": "^2.1.0"
},
"devDependencies": {
"react": "^17.0.1",
"react-dom": "^17.0.1"
"react": "^17.0.2",
"react-dom": "^17.0.2"
},

@@ -32,3 +30,30 @@ "peerDependencies": {

"README.md",
"dist"
"dist",
"can-use-dom",
"clone-valid-element",
"compose-event-handlers",
"compose-refs",
"computed-styles",
"context",
"dev-utils",
"get-document-dimensions",
"get-scroll-position",
"get-scrollbar-offset",
"is-right-click",
"make-id",
"noop",
"owner-document",
"polymorphic",
"type-check",
"types",
"use-constant",
"use-controlled-state",
"use-event-listener",
"use-focus-change",
"use-force-update",
"use-isomorphic-layout-effect",
"use-lazy-ref",
"use-previous",
"use-stable-callback",
"use-update-effect"
],

@@ -39,3 +64,35 @@ "eslintIgnore": [

],
"gitHead": "80f6ca5f8d25a10887e2bd34d60094402b9bc0a7"
"preconstruct": {
"entrypoints": [
"index.ts",
"can-use-dom.ts",
"clone-valid-element.ts",
"compose-event-handlers.ts",
"compose-refs.ts",
"computed-styles.ts",
"context.ts",
"dev-utils.ts",
"get-document-dimensions.ts",
"get-scroll-position.ts",
"get-scrollbar-offset.ts",
"is-right-click.ts",
"make-id.ts",
"noop.ts",
"owner-document.ts",
"polymorphic.ts",
"type-check.ts",
"types.ts",
"use-constant.ts",
"use-controlled-state.ts",
"use-event-listener.ts",
"use-focus-change.ts",
"use-force-update.ts",
"use-isomorphic-layout-effect.ts",
"use-lazy-ref.ts",
"use-previous.ts",
"use-stable-callback.ts",
"use-update-effect.ts"
]
},
"gitHead": "1449650359c119c1afe25973aa7584e09e2c88bc"
}
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