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

@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.8.0 to 0.8.2

80

dist/index.d.ts
import React from "react";
import { As, AssignableRef, ComponentWithAs, ComponentWithForwardedRef, DistributiveOmit, PropsFromAs, PropsWithAs } from "./types";
import { As, AssignableRef, ComponentWithAs, ComponentWithForwardedRef, DistributiveOmit, PropsFromAs, PropsWithAs, SingleOrArray } from "./types";
/**

@@ -46,8 +46,7 @@ * React currently throws a warning when using useLayoutEffect on the server.

*/
export declare function assignRef<T = any>(ref: AssignableRef<T> | undefined, value: any): void;
export declare function boolOrBoolString(value: any): boolean;
export declare function assignRef<RefValueType = any>(ref: AssignableRef<RefValueType> | undefined, value: any): void;
export declare function boolOrBoolString(value: any): value is "true" | true;
export declare function canUseDOM(): boolean;
export declare function cloneValidElement<P>(element: React.ReactElement<P> | React.ReactNode, props?: Partial<P> & React.Attributes, ...children: React.ReactNode[]): React.ReactElement<P> | React.ReactNode;
export declare function createNamedContext<T>(name: string, defaultValue: T): React.Context<T>;
export declare function findLastIndex<T = any>(array: T[], predicate: (element: T, index?: number, arr?: T[]) => boolean): number;
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>;
/**

@@ -57,3 +56,2 @@ * Get the scrollbar offset distance.

export declare function getScrollbarOffset(): number;
export declare function isUndefined(value: any): boolean;
/**

@@ -69,4 +67,8 @@ * Joins strings to format IDs for compound components.

export declare function noop(): void;
export declare function useConstant<T>(fn: () => T): T;
/**
* React hook for creating a value exactly once.
* @see https://github.com/Andarist/use-constant
*/
export declare function useConstant<ValueType>(fn: () => ValueType): ValueType;
/**
* Passes or assigns a value to multiple refs (typically a DOM node). Useful for

@@ -78,3 +80,3 @@ * dealing with components that need an explicit ref for DOM calculations but

*/
export declare function useForkedRef<T = any>(...refs: (AssignableRef<T> | undefined)[]): ((node: any) => void) | null;
export declare function useForkedRef<RefValueType = any>(...refs: (AssignableRef<RefValueType> | undefined)[]): ((node: any) => void) | null;
/**

@@ -85,3 +87,3 @@ * Returns the previous value of a reference after a component update.

*/
export declare function usePrevious<T = any>(value: T): T | null;
export declare function usePrevious<ValueType = any>(value: ValueType): ValueType | null;
/**

@@ -93,3 +95,3 @@ * Call an effect after a component update, skipping the initial mount.

*/
export declare function useUpdateEffect(effect: () => any, deps?: any[]): void;
export declare function useUpdateEffect(effect: React.EffectCallback, deps?: React.DependencyList): void;
/**

@@ -103,3 +105,3 @@ * Wraps a lib-defined event handler and a user-defined event handler, returning

*/
export declare function wrapEvent<E extends React.SyntheticEvent | Event>(theirHandler: ((event: E) => any) | undefined, ourHandler: (event: E) => any): (event: E) => any;
export declare function wrapEvent<EventType extends React.SyntheticEvent | Event>(theirHandler: ((event: EventType) => any) | undefined, ourHandler: (event: EventType) => any): (event: EventType) => any;
/**

@@ -119,46 +121,10 @@ * This is a hack for sure. The thing is, getting a component to intelligently

*/
export declare function forwardRefWithAs<P, T extends As>(comp: (props: PropsFromAs<T, P>, ref: React.RefObject<any>) => JSX.Element): ComponentWithAs<T, P>;
export { As, AssignableRef, ComponentWithAs, ComponentWithForwardedRef, DistributiveOmit, PropsFromAs, PropsWithAs };
export declare type Descendant<T, P = {}> = P & {
element: (T extends HTMLElement ? T : HTMLElement) | null;
index: number;
};
export interface IDescendantContext<T, P> {
descendants: Descendant<T, P>[];
registerDescendant(descendant: Descendant<T, P>): void;
unregisterDescendant(element: (T extends HTMLElement ? T : HTMLElement) | null): void;
}
export declare function createDescendantContext<T, P = {}>(name: string, initialValue?: {}): React.Context<IDescendantContext<T, P>>;
/**
* This hook registers our descendant by passing it into an array. We can then
* search that array by to find its index when registering it in the component.
* We use this for focus management, keyboard navigation, and typeahead
* functionality for some components.
*
* The hook accepts the element node and (optionally) a key. The key is useful
* if multiple descendants have identical text values and we need to
* differentiate siblings for some reason.
*
* Our main goals with this are:
* 1) maximum composability,
* 2) minimal API friction
* 3) SSR compatibility*
* 4) concurrent safe
* 5) index always up-to-date with the tree despite changes
* 6) works with memoization of any component in the tree (hopefully)
*
* * As for SSR, the good news is that we don't actually need the index on the
* server for most use-cases, as we are only using it to determine the order of
* composed descendants for keyboard navigation. However, in the few cases where
* this is not the case, we can require an explicit index from the app.
*/
export declare function useDescendant<T, P>({ context, element, ...rest }: Omit<Descendant<T, P>, "index"> & {
context: React.Context<IDescendantContext<T, P>>;
}, indexProp?: number): number;
export declare function useDescendants<T, P = {}>(): [Descendant<T, P>[], React.Dispatch<React.SetStateAction<Descendant<T, P>[]>>];
export declare function DescendantProvider<T, P>({ context: Ctx, children, items, set }: {
context: React.Context<IDescendantContext<T, P>>;
children: React.ReactNode;
items: Descendant<T, P>[];
set: React.Dispatch<React.SetStateAction<Descendant<T, P>[]>>;
}): JSX.Element;
export declare function forwardRefWithAs<Props, ComponentType extends As>(comp: (props: PropsFromAs<ComponentType, Props>, ref: React.RefObject<any>) => React.ReactElement | null): ComponentWithAs<ComponentType, Props>;
export declare function getOwnerDocument<T extends HTMLElement = HTMLElement>(element: T | null): Document | null;
export declare let ponyfillGlobal: any;
export declare function isBoolean(value: any): value is boolean;
export declare function isFunction(value: any): value is Function;
export declare function isNumber(value: any): value is number;
export declare function isString(value: any): value is string;
export declare function useControlledSwitchWarning(controlPropValue: any, controlPropName: string, componentName: string): void;
export { As, AssignableRef, ComponentWithAs, ComponentWithForwardedRef, DistributiveOmit, PropsFromAs, PropsWithAs, SingleOrArray, };
import * as React from "react";
import { Validator } from "prop-types";
export declare type AssignableRef<T = any> = React.Ref<T | null>;
declare type ReactElement = React.ReactElement;
/**
* Type can be either a single `T` or an array of `T`
* React.Ref uses the readonly type `React.RefObject` instead of
* `React.MutableRefObject`, We pretty much always assume ref objects are
* mutable (at least when we create them), so this type is a workaround so some
* of the weird mechanics of using refs with TS.
*/
export declare type SingleOrArray<T> = T[] | T;
export declare type AssignableRef<ValueType> = {
bivarianceHack(instance: ValueType | null): void;
}["bivarianceHack"] | React.MutableRefObject<ValueType | null> | null;
/**
* Type can be either a single `ValueType` or an array of `ValueType`
*/
export declare type SingleOrArray<ValueType> = ValueType[] | ValueType;
/**
* The built-in utility type `Omit` does not distribute over unions. So if you

@@ -31,18 +39,19 @@ * have:

*/
export declare type DistributiveOmit<T, K extends PropertyKey> = T extends any ? Omit<T, K> : never;
export declare type As<P = any> = React.ElementType<P>;
export declare type PropsWithAs<T extends As, P> = P & Omit<React.ComponentPropsWithRef<T>, "as" | keyof P> & {
as?: T;
export declare type DistributiveOmit<BaseType, Key extends PropertyKey> = BaseType extends any ? Omit<BaseType, Key> : never;
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<T extends As, P> = (PropsWithAs<T, P> & {
as: T;
}) & PropsWithAs<T, P>;
export declare type ComponentWithForwardedRef<T extends React.ElementType, P> = React.ForwardRefExoticComponent<P & React.HTMLProps<React.ElementType<T>> & React.ComponentPropsWithRef<T>>;
export interface ComponentWithAs<T extends As, P> {
<TT extends As>(props: PropsWithAs<TT, P>): JSX.Element;
(props: PropsWithAs<T, P>): JSX.Element;
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 ComponentWithAs<ComponentType extends As, ComponentProps> {
<TT extends As>(props: PropsWithAs<TT, ComponentProps>): ReactElement | null;
(props: PropsWithAs<ComponentType, ComponentProps>): ReactElement | null;
displayName?: string;
propTypes?: {
[key: string]: Validator<any>;
};
propTypes?: React.WeakValidationMap<PropsWithAs<ComponentType, ComponentProps>>;
contextTypes?: React.ValidationMap<any>;
defaultProps?: Partial<PropsWithAs<ComponentType, ComponentProps>>;
}
export {};

@@ -9,36 +9,5 @@ 'use strict';

var React__default = _interopDefault(React);
var warning = _interopDefault(require('warning'));
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);
}
function _objectWithoutPropertiesLoose(source, excluded) {
if (source == null) return {};
var target = {};
var sourceKeys = Object.keys(source);
var key, i;
for (i = 0; i < sourceKeys.length; i++) {
key = sourceKeys[i];
if (excluded.indexOf(key) >= 0) continue;
target[key] = source[key];
}
return target;
}
/* eslint-disable no-restricted-globals, eqeqeq, */
/**

@@ -76,3 +45,2 @@ * React currently throws a warning when using useLayoutEffect on the server.

canUseDOM() ? React__default.useLayoutEffect : React__default.useEffect;
var useLayoutEffect = useIsomorphicLayoutEffect;
var checkedPkgs = {};

@@ -87,12 +55,14 @@ /**

exports.checkStyles = function checkStyles(packageName) {};
exports.checkStyles = function checkStyles(packageName) {
return void packageName;
};
{
exports.checkStyles = function checkStyles(pkg) {
exports.checkStyles = function checkStyles(packageName) {
// only check once per package
if (checkedPkgs[pkg]) return;
checkedPkgs[pkg] = true;
if (checkedPkgs[packageName]) return;
checkedPkgs[packageName] = true;
if ( parseInt(window.getComputedStyle(document.body).getPropertyValue("--reach-" + pkg), 10) !== 1) {
console.warn("@reach/" + pkg + " 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/" + pkg + "/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/" + pkg + "/styles.css\" />\n\n For more information visit https://ui.reach.tech/styling.\n ");
if ( 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\";\nimport warning from 'warning';\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 ");
}

@@ -111,7 +81,6 @@ };

if (typeof ref === "function") {
if (isFunction(ref)) {
ref(value);
} else {
try {
// @ts-ignore
ref.current = value;

@@ -124,3 +93,3 @@ } catch (error) {

function boolOrBoolString(value) {
return value === "false" ? false : Boolean(value);
return value === "true" ? true : isBoolean(value) ? value : false;
}

@@ -131,6 +100,2 @@ function canUseDOM() {

function cloneValidElement(element, props) {
if (!React.isValidElement(element)) {
return element;
}
for (var _len = arguments.length, children = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {

@@ -140,3 +105,3 @@ children[_key - 2] = arguments[_key];

return React.cloneElement.apply(void 0, [element, props].concat(children));
return React.isValidElement(element) ? React.cloneElement.apply(void 0, [element, props].concat(children)) : element;
}

@@ -148,23 +113,2 @@ function createNamedContext(name, defaultValue) {

}
function findLastIndex(array, predicate) {
var length = array.length >>> 0;
if (!length) {
return -1;
}
var n = length - 1;
while (n >= 0) {
var value = array[n];
if (predicate(value, n, array)) {
return n;
}
--n;
}
return -1;
}
/**

@@ -183,5 +127,2 @@ * Get the scrollbar offset distance.

}
function isUndefined(value) {
return typeof value === "undefined";
}
/**

@@ -206,4 +147,7 @@ * Joins strings to format IDs for compound components.

function noop() {} // React hook for creating a value exactly once.
// https://github.com/Andarist/use-constant
function noop() {}
/**
* React hook for creating a value exactly once.
* @see https://github.com/Andarist/use-constant
*/

@@ -315,179 +259,44 @@ function useConstant(fn) {

}
function createDescendantContext(name, initialValue) {
if (initialValue === void 0) {
initialValue = {};
}
function getOwnerDocument(element) {
return element && element.ownerDocument ? element.ownerDocument : canUseDOM() ? document : null;
} // https://github.com/zloirock/core-js/issues/86#issuecomment-115759028
return createNamedContext(name, _extends({
descendants: [],
registerDescendant: noop,
unregisterDescendant: noop
}, initialValue));
var ponyfillGlobal = typeof window != "undefined" && window.Math == Math ? window : typeof self != "undefined" && self.Math == Math ? self :
/*#__PURE__*/
// eslint-disable-next-line no-new-func
Function("return this")();
function isBoolean(value) {
return typeof value === "boolean";
}
/**
* This hook registers our descendant by passing it into an array. We can then
* search that array by to find its index when registering it in the component.
* We use this for focus management, keyboard navigation, and typeahead
* functionality for some components.
*
* The hook accepts the element node and (optionally) a key. The key is useful
* if multiple descendants have identical text values and we need to
* differentiate siblings for some reason.
*
* Our main goals with this are:
* 1) maximum composability,
* 2) minimal API friction
* 3) SSR compatibility*
* 4) concurrent safe
* 5) index always up-to-date with the tree despite changes
* 6) works with memoization of any component in the tree (hopefully)
*
* * As for SSR, the good news is that we don't actually need the index on the
* server for most use-cases, as we are only using it to determine the order of
* composed descendants for keyboard navigation. However, in the few cases where
* this is not the case, we can require an explicit index from the app.
*/
function useDescendant(_ref, indexProp) {
var context = _ref.context,
element = _ref.element,
rest = _objectWithoutPropertiesLoose(_ref, ["context", "element"]);
var _useState = React.useState(),
forceUpdate = _useState[1];
var _useContext = React.useContext(context),
registerDescendant = _useContext.registerDescendant,
unregisterDescendant = _useContext.unregisterDescendant,
descendants = _useContext.descendants; // Prevent any flashing
useLayoutEffect(function () {
if (!element) forceUpdate({}); // @ts-ignore
registerDescendant(_extends({
element: element
}, rest));
return function () {
return unregisterDescendant(element);
}; // eslint-disable-next-line react-hooks/exhaustive-deps
}, [element].concat(Object.values(rest)));
return indexProp !== null && indexProp !== void 0 ? indexProp : descendants.findIndex(function (_ref2) {
var _el = _ref2.element;
return _el === element;
});
function isFunction(value) {
return !!(value && {}.toString.call(value) == "[object Function]");
}
function useDescendants() {
return React.useState([]);
function isNumber(value) {
return typeof value === "number";
}
function DescendantProvider(_ref3) {
var Ctx = _ref3.context,
children = _ref3.children,
items = _ref3.items,
set = _ref3.set;
var registerDescendant = React__default.useCallback(function (_ref4) {
var element = _ref4.element,
rest = _objectWithoutPropertiesLoose(_ref4, ["element"]);
if (!element) {
return;
}
set(function (items) {
if (items.find(function (_ref5) {
var _el = _ref5.element;
return _el === element;
}) == null) {
/*
* When registering a descendant, we need to make sure we insert in
* into the array in the same order that it appears in the DOM. So as
* new descendants are added or maybe some are removed, we always know
* that the array is up-to-date and correct.
*
* So here we look at our registered descendants and see if the new
* element we are adding appears earlier than an existing descendant's
* DOM node via `node.compareDocumentPosition`. If it does, we insert
* the new element at this index. Because `registerDescendant` will be
* called in an effect every time the descendants state value changes,
* we should be sure that this index is accurate when descendent
* elements come or go from our component.
*/
var index = items.findIndex(function (_ref6) {
var existingElement = _ref6.element;
if (!existingElement || !element) {
return false;
}
/*
* Does this element's DOM node appear before another item in the
* array in our DOM tree? If so, return true to grab the index at
* this point in the array so we know where to insert the new
* element.
*/
return Boolean(existingElement.compareDocumentPosition(element) & Node.DOCUMENT_POSITION_PRECEDING);
});
var newItem = _extends({
element: element,
index: index
}, rest); // If an index is not found we will push the element to the end.
if (index === -1) {
return [].concat(items, [newItem]);
}
return [].concat(items.slice(0, index), [newItem], items.slice(index));
}
return items;
});
},
function isString(value) {
return typeof value === "string";
}
function useControlledSwitchWarning(controlPropValue, controlPropName, componentName) {
/*
* setDescendants is a state setter initialized by the useDescendants hook.
* We can safely ignore the lint warning here because it will not change
* between renders.
* Determine whether or not the component is controlled and warn the developer
* if this changes unexpectedly.
*/
// eslint-disable-next-line react-hooks/exhaustive-deps
[]);
var unregisterDescendant = React.useCallback(function (element) {
if (!element) {
return;
}
var isControlled = controlPropValue != null;
set(function (items) {
return items.filter(function (_ref7) {
var _el = _ref7.element;
return element !== _el;
});
});
},
/*
* setDescendants is a state setter initialized by the useDescendants hook.
* We can safely ignore the lint warning here because it will not change
* between renders.
*/
// eslint-disable-next-line react-hooks/exhaustive-deps
[]); // Not sure about this just yet, may bail on this and let components deal
var _useRef = React.useRef(isControlled),
wasControlled = _useRef.current;
/* let focusNodes = descendants
.filter(({ disabled }) => !disabled)
.map(({ element }) => element); */
// @ts-ignore
var effect = noop;
var value = React.useMemo(function () {
return {
descendants: items,
registerDescendant: registerDescendant,
unregisterDescendant: unregisterDescendant
{
effect = function effect() {
warning(!(!isControlled && wasControlled), "`" + componentName + "` is changing from uncontrolled to be controlled. Reach UI components should not switch from uncontrolled to controlled (or vice versa). Decide between using a controlled or uncontrolled `" + componentName + "` for the lifetime of the component. Check the `" + controlPropName + "` prop.") ;
warning(!(!isControlled && wasControlled), "`" + componentName + "` is changing from controlled to be uncontrolled. Reach UI components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled `" + componentName + "` for the lifetime of the component. Check the `" + controlPropName + "` prop.") ;
};
}, [items, registerDescendant, unregisterDescendant]);
return React__default.createElement(Ctx.Provider, {
value: value
}, children);
}
React.useEffect(effect, [componentName, controlPropName, isControlled]);
}
exports.DescendantProvider = DescendantProvider;
exports.assignRef = assignRef;

@@ -497,13 +306,15 @@ exports.boolOrBoolString = boolOrBoolString;

exports.cloneValidElement = cloneValidElement;
exports.createDescendantContext = createDescendantContext;
exports.createNamedContext = createNamedContext;
exports.findLastIndex = findLastIndex;
exports.forwardRefWithAs = forwardRefWithAs;
exports.getOwnerDocument = getOwnerDocument;
exports.getScrollbarOffset = getScrollbarOffset;
exports.isUndefined = isUndefined;
exports.isBoolean = isBoolean;
exports.isFunction = isFunction;
exports.isNumber = isNumber;
exports.isString = isString;
exports.makeId = makeId;
exports.noop = noop;
exports.ponyfillGlobal = ponyfillGlobal;
exports.useConstant = useConstant;
exports.useDescendant = useDescendant;
exports.useDescendants = useDescendants;
exports.useControlledSwitchWarning = useControlledSwitchWarning;
exports.useForkedRef = useForkedRef;

@@ -510,0 +321,0 @@ exports.useIsomorphicLayoutEffect = useIsomorphicLayoutEffect;

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

"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e,n=require("react"),t=(e=n)&&"object"==typeof e&&"default"in e?e.default:e;function r(){return(r=Object.assign||function(e){for(var n=1;n<arguments.length;n++){var t=arguments[n];for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])}return e}).apply(this,arguments)}function o(e,n){if(null==e)return{};var t,r,o={},u=Object.keys(e);for(r=0;r<u.length;r++)n.indexOf(t=u[r])>=0||(o[t]=e[t]);return o}var u=f()?t.useLayoutEffect:t.useEffect,c=u;function i(e,n){if(null!=e)if("function"==typeof e)e(n);else try{e.current=n}catch(t){throw new Error('Cannot assign value "'+n+'" to ref "'+e+'"')}}function f(){return"undefined"!=typeof window&&void 0!==window.document&&void 0!==window.document.createElement}function s(e,t){var r=n.createContext(t);return r.displayName=e,r}function a(){}exports.DescendantProvider=function(e){var u=e.context,c=e.children,i=e.items,f=e.set,s=t.useCallback((function(e){var n=e.element,t=o(e,["element"]);n&&f((function(e){if(null==e.find((function(e){return e.element===n}))){var o=e.findIndex((function(e){var t=e.element;return!(!t||!n)&&Boolean(t.compareDocumentPosition(n)&Node.DOCUMENT_POSITION_PRECEDING)})),u=r({element:n,index:o},t);return-1===o?[].concat(e,[u]):[].concat(e.slice(0,o),[u],e.slice(o))}return e}))}),[]),a=n.useCallback((function(e){e&&f((function(n){return n.filter((function(n){return e!==n.element}))}))}),[]),l=n.useMemo((function(){return{descendants:i,registerDescendant:s,unregisterDescendant:a}}),[i,s,a]);return t.createElement(u.Provider,{value:l},c)},exports.assignRef=i,exports.boolOrBoolString=function(e){return"false"!==e&&Boolean(e)},exports.canUseDOM=f,exports.checkStyles=function(e){},exports.cloneValidElement=function(e,t){if(!n.isValidElement(e))return e;for(var r=arguments.length,o=new Array(r>2?r-2:0),u=2;u<r;u++)o[u-2]=arguments[u];return n.cloneElement.apply(void 0,[e,t].concat(o))},exports.createDescendantContext=function(e,n){return void 0===n&&(n={}),s(e,r({descendants:[],registerDescendant:a,unregisterDescendant:a},n))},exports.createNamedContext=s,exports.findLastIndex=function(e,n){var t=e.length>>>0;if(!t)return-1;for(var r=t-1;r>=0;){if(n(e[r],r,e))return r;--r}return-1},exports.forwardRefWithAs=function(e){return t.forwardRef(e)},exports.getScrollbarOffset=function(){try{if(window.innerWidth>document.documentElement.clientWidth)return window.innerWidth-document.documentElement.clientWidth}catch(e){}return 0},exports.isUndefined=function(e){return void 0===e},exports.makeId=function(){for(var e=arguments.length,n=new Array(e),t=0;t<e;t++)n[t]=arguments[t];return n.filter((function(e){return null!=e})).join("--")},exports.noop=a,exports.useConstant=function(e){var n=t.useRef();return n.current||(n.current={v:e()}),n.current.v},exports.useDescendant=function(e,t){var u=e.context,i=e.element,f=o(e,["context","element"]),s=n.useState()[1],a=n.useContext(u),l=a.registerDescendant,d=a.unregisterDescendant,p=a.descendants;return c((function(){return i||s({}),l(r({element:i},f)),function(){return d(i)}}),[i].concat(Object.values(f))),null!=t?t:p.findIndex((function(e){return e.element===i}))},exports.useDescendants=function(){return n.useState([])},exports.useForkedRef=function(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];return n.useMemo((function(){return t.every((function(e){return null==e}))?null:function(e){t.forEach((function(n){i(n,e)}))}}),t)},exports.useIsomorphicLayoutEffect=u,exports.usePrevious=function(e){var t=n.useRef(null);return n.useEffect((function(){t.current=e}),[e]),t.current},exports.useUpdateEffect=function(e,t){var r=n.useRef(!1);n.useEffect((function(){r.current?e():r.current=!0}),t)},exports.wrapEvent=function(e,n){return function(t){if(e&&e(t),!t.defaultPrevented)return n(t)}};
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e,n=require("react"),t=(e=n)&&"object"==typeof e&&"default"in e?e.default:e;require("warning");var r=u()?t.useLayoutEffect:t.useEffect;function o(e,n){if(null!=e)if(s(e))e(n);else try{e.current=n}catch(t){throw new Error('Cannot assign value "'+n+'" to ref "'+e+'"')}}function u(){return"undefined"!=typeof window&&void 0!==window.document&&void 0!==window.document.createElement}function i(){}var c="undefined"!=typeof window&&window.Math==Math?window:"undefined"!=typeof self&&self.Math==Math?self:Function("return this")();function f(e){return"boolean"==typeof e}function s(e){return!(!e||"[object Function]"!={}.toString.call(e))}exports.assignRef=o,exports.boolOrBoolString=function(e){return"true"===e||!!f(e)&&e},exports.canUseDOM=u,exports.checkStyles=function(e){},exports.cloneValidElement=function(e,t){for(var r=arguments.length,o=new Array(r>2?r-2:0),u=2;u<r;u++)o[u-2]=arguments[u];return n.isValidElement(e)?n.cloneElement.apply(void 0,[e,t].concat(o)):e},exports.createNamedContext=function(e,t){var r=n.createContext(t);return r.displayName=e,r},exports.forwardRefWithAs=function(e){return t.forwardRef(e)},exports.getOwnerDocument=function(e){return e&&e.ownerDocument?e.ownerDocument:u()?document:null},exports.getScrollbarOffset=function(){try{if(window.innerWidth>document.documentElement.clientWidth)return window.innerWidth-document.documentElement.clientWidth}catch(e){}return 0},exports.isBoolean=f,exports.isFunction=s,exports.isNumber=function(e){return"number"==typeof e},exports.isString=function(e){return"string"==typeof e},exports.makeId=function(){for(var e=arguments.length,n=new Array(e),t=0;t<e;t++)n[t]=arguments[t];return n.filter((function(e){return null!=e})).join("--")},exports.noop=i,exports.ponyfillGlobal=c,exports.useConstant=function(e){var n=t.useRef();return n.current||(n.current={v:e()}),n.current.v},exports.useControlledSwitchWarning=function(e,t,r){var o=null!=e;n.useRef(o),n.useEffect(i,[r,t,o])},exports.useForkedRef=function(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];return n.useMemo((function(){return t.every((function(e){return null==e}))?null:function(e){t.forEach((function(n){o(n,e)}))}}),t)},exports.useIsomorphicLayoutEffect=r,exports.usePrevious=function(e){var t=n.useRef(null);return n.useEffect((function(){t.current=e}),[e]),t.current},exports.useUpdateEffect=function(e,t){var r=n.useRef(!1);n.useEffect((function(){r.current?e():r.current=!0}),t)},exports.wrapEvent=function(e,n){return function(t){if(e&&e(t),!t.defaultPrevented)return n(t)}};
//# sourceMappingURL=utils.cjs.production.min.js.map

@@ -1,36 +0,5 @@

import React, { isValidElement, cloneElement, createContext, useMemo, useRef, useEffect, useState, useContext, useCallback } from 'react';
import React, { isValidElement, cloneElement, createContext, useMemo, useRef, useEffect } from 'react';
import warning from 'warning';
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);
}
function _objectWithoutPropertiesLoose(source, excluded) {
if (source == null) return {};
var target = {};
var sourceKeys = Object.keys(source);
var key, i;
for (i = 0; i < sourceKeys.length; i++) {
key = sourceKeys[i];
if (excluded.indexOf(key) >= 0) continue;
target[key] = source[key];
}
return target;
}
/* eslint-disable no-restricted-globals, eqeqeq, */
/**

@@ -68,3 +37,2 @@ * React currently throws a warning when using useLayoutEffect on the server.

canUseDOM() ? React.useLayoutEffect : React.useEffect;
var useLayoutEffect = useIsomorphicLayoutEffect;
var checkedPkgs = {};

@@ -79,12 +47,14 @@ /**

var checkStyles = function checkStyles(packageName) {};
var checkStyles = function checkStyles(packageName) {
return void packageName;
};
if (process.env.NODE_ENV !== "production") {
checkStyles = function checkStyles(pkg) {
checkStyles = function checkStyles(packageName) {
// only check once per package
if (checkedPkgs[pkg]) return;
checkedPkgs[pkg] = true;
if (checkedPkgs[packageName]) return;
checkedPkgs[packageName] = true;
if (process.env.NODE_ENV !== "test" && parseInt(window.getComputedStyle(document.body).getPropertyValue("--reach-" + pkg), 10) !== 1) {
console.warn("@reach/" + pkg + " 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/" + pkg + "/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/" + pkg + "/styles.css\" />\n\n For more information visit https://ui.reach.tech/styling.\n ");
if (process.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\";\nimport warning from 'warning';\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 ");
}

@@ -103,7 +73,6 @@ };

if (typeof ref === "function") {
if (isFunction(ref)) {
ref(value);
} else {
try {
// @ts-ignore
ref.current = value;

@@ -116,3 +85,3 @@ } catch (error) {

function boolOrBoolString(value) {
return value === "false" ? false : Boolean(value);
return value === "true" ? true : isBoolean(value) ? value : false;
}

@@ -123,6 +92,2 @@ function canUseDOM() {

function cloneValidElement(element, props) {
if (!isValidElement(element)) {
return element;
}
for (var _len = arguments.length, children = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {

@@ -132,3 +97,3 @@ children[_key - 2] = arguments[_key];

return cloneElement.apply(void 0, [element, props].concat(children));
return isValidElement(element) ? cloneElement.apply(void 0, [element, props].concat(children)) : element;
}

@@ -140,23 +105,2 @@ function createNamedContext(name, defaultValue) {

}
function findLastIndex(array, predicate) {
var length = array.length >>> 0;
if (!length) {
return -1;
}
var n = length - 1;
while (n >= 0) {
var value = array[n];
if (predicate(value, n, array)) {
return n;
}
--n;
}
return -1;
}
/**

@@ -175,5 +119,2 @@ * Get the scrollbar offset distance.

}
function isUndefined(value) {
return typeof value === "undefined";
}
/**

@@ -198,4 +139,7 @@ * Joins strings to format IDs for compound components.

function noop() {} // React hook for creating a value exactly once.
// https://github.com/Andarist/use-constant
function noop() {}
/**
* React hook for creating a value exactly once.
* @see https://github.com/Andarist/use-constant
*/

@@ -307,179 +251,45 @@ function useConstant(fn) {

}
function createDescendantContext(name, initialValue) {
if (initialValue === void 0) {
initialValue = {};
}
function getOwnerDocument(element) {
return element && element.ownerDocument ? element.ownerDocument : canUseDOM() ? document : null;
} // https://github.com/zloirock/core-js/issues/86#issuecomment-115759028
return createNamedContext(name, _extends({
descendants: [],
registerDescendant: noop,
unregisterDescendant: noop
}, initialValue));
var ponyfillGlobal = typeof window != "undefined" && window.Math == Math ? window : typeof self != "undefined" && self.Math == Math ? self :
/*#__PURE__*/
// eslint-disable-next-line no-new-func
Function("return this")();
function isBoolean(value) {
return typeof value === "boolean";
}
/**
* This hook registers our descendant by passing it into an array. We can then
* search that array by to find its index when registering it in the component.
* We use this for focus management, keyboard navigation, and typeahead
* functionality for some components.
*
* The hook accepts the element node and (optionally) a key. The key is useful
* if multiple descendants have identical text values and we need to
* differentiate siblings for some reason.
*
* Our main goals with this are:
* 1) maximum composability,
* 2) minimal API friction
* 3) SSR compatibility*
* 4) concurrent safe
* 5) index always up-to-date with the tree despite changes
* 6) works with memoization of any component in the tree (hopefully)
*
* * As for SSR, the good news is that we don't actually need the index on the
* server for most use-cases, as we are only using it to determine the order of
* composed descendants for keyboard navigation. However, in the few cases where
* this is not the case, we can require an explicit index from the app.
*/
function useDescendant(_ref, indexProp) {
var context = _ref.context,
element = _ref.element,
rest = _objectWithoutPropertiesLoose(_ref, ["context", "element"]);
var _useState = useState(),
forceUpdate = _useState[1];
var _useContext = useContext(context),
registerDescendant = _useContext.registerDescendant,
unregisterDescendant = _useContext.unregisterDescendant,
descendants = _useContext.descendants; // Prevent any flashing
useLayoutEffect(function () {
if (!element) forceUpdate({}); // @ts-ignore
registerDescendant(_extends({
element: element
}, rest));
return function () {
return unregisterDescendant(element);
}; // eslint-disable-next-line react-hooks/exhaustive-deps
}, [element].concat(Object.values(rest)));
return indexProp !== null && indexProp !== void 0 ? indexProp : descendants.findIndex(function (_ref2) {
var _el = _ref2.element;
return _el === element;
});
function isFunction(value) {
return !!(value && {}.toString.call(value) == "[object Function]");
}
function useDescendants() {
return useState([]);
function isNumber(value) {
return typeof value === "number";
}
function DescendantProvider(_ref3) {
var Ctx = _ref3.context,
children = _ref3.children,
items = _ref3.items,
set = _ref3.set;
var registerDescendant = React.useCallback(function (_ref4) {
var element = _ref4.element,
rest = _objectWithoutPropertiesLoose(_ref4, ["element"]);
if (!element) {
return;
}
set(function (items) {
if (items.find(function (_ref5) {
var _el = _ref5.element;
return _el === element;
}) == null) {
/*
* When registering a descendant, we need to make sure we insert in
* into the array in the same order that it appears in the DOM. So as
* new descendants are added or maybe some are removed, we always know
* that the array is up-to-date and correct.
*
* So here we look at our registered descendants and see if the new
* element we are adding appears earlier than an existing descendant's
* DOM node via `node.compareDocumentPosition`. If it does, we insert
* the new element at this index. Because `registerDescendant` will be
* called in an effect every time the descendants state value changes,
* we should be sure that this index is accurate when descendent
* elements come or go from our component.
*/
var index = items.findIndex(function (_ref6) {
var existingElement = _ref6.element;
if (!existingElement || !element) {
return false;
}
/*
* Does this element's DOM node appear before another item in the
* array in our DOM tree? If so, return true to grab the index at
* this point in the array so we know where to insert the new
* element.
*/
return Boolean(existingElement.compareDocumentPosition(element) & Node.DOCUMENT_POSITION_PRECEDING);
});
var newItem = _extends({
element: element,
index: index
}, rest); // If an index is not found we will push the element to the end.
if (index === -1) {
return [].concat(items, [newItem]);
}
return [].concat(items.slice(0, index), [newItem], items.slice(index));
}
return items;
});
},
function isString(value) {
return typeof value === "string";
}
function useControlledSwitchWarning(controlPropValue, controlPropName, componentName) {
/*
* setDescendants is a state setter initialized by the useDescendants hook.
* We can safely ignore the lint warning here because it will not change
* between renders.
* Determine whether or not the component is controlled and warn the developer
* if this changes unexpectedly.
*/
// eslint-disable-next-line react-hooks/exhaustive-deps
[]);
var unregisterDescendant = useCallback(function (element) {
if (!element) {
return;
}
var isControlled = controlPropValue != null;
set(function (items) {
return items.filter(function (_ref7) {
var _el = _ref7.element;
return element !== _el;
});
});
},
/*
* setDescendants is a state setter initialized by the useDescendants hook.
* We can safely ignore the lint warning here because it will not change
* between renders.
*/
// eslint-disable-next-line react-hooks/exhaustive-deps
[]); // Not sure about this just yet, may bail on this and let components deal
var _useRef = useRef(isControlled),
wasControlled = _useRef.current;
/* let focusNodes = descendants
.filter(({ disabled }) => !disabled)
.map(({ element }) => element); */
// @ts-ignore
var effect = noop;
var value = useMemo(function () {
return {
descendants: items,
registerDescendant: registerDescendant,
unregisterDescendant: unregisterDescendant
if (process.env.NODE_ENV !== "production") {
effect = function effect() {
process.env.NODE_ENV !== "production" ? warning(!(!isControlled && wasControlled), "`" + componentName + "` is changing from uncontrolled to be controlled. Reach UI components should not switch from uncontrolled to controlled (or vice versa). Decide between using a controlled or uncontrolled `" + componentName + "` for the lifetime of the component. Check the `" + controlPropName + "` prop.") : void 0;
process.env.NODE_ENV !== "production" ? warning(!(!isControlled && wasControlled), "`" + componentName + "` is changing from controlled to be uncontrolled. Reach UI components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled `" + componentName + "` for the lifetime of the component. Check the `" + controlPropName + "` prop.") : void 0;
};
}, [items, registerDescendant, unregisterDescendant]);
return React.createElement(Ctx.Provider, {
value: value
}, children);
}
useEffect(effect, [componentName, controlPropName, isControlled]);
}
export { DescendantProvider, assignRef, boolOrBoolString, canUseDOM, checkStyles, cloneValidElement, createDescendantContext, createNamedContext, findLastIndex, forwardRefWithAs, getScrollbarOffset, isUndefined, makeId, noop, useConstant, useDescendant, useDescendants, useForkedRef, useIsomorphicLayoutEffect, usePrevious, useUpdateEffect, wrapEvent };
export { assignRef, boolOrBoolString, canUseDOM, checkStyles, cloneValidElement, createNamedContext, forwardRefWithAs, getOwnerDocument, getScrollbarOffset, isBoolean, isFunction, isNumber, isString, makeId, noop, ponyfillGlobal, useConstant, useControlledSwitchWarning, useForkedRef, useIsomorphicLayoutEffect, usePrevious, useUpdateEffect, wrapEvent };
//# sourceMappingURL=utils.esm.js.map
{
"name": "@reach/utils",
"version": "0.8.0",
"version": "0.8.2",
"description": "Internal, shared utilities for Reach UI.",

@@ -13,3 +13,3 @@ "author": "React Training <hello@reacttraining.com>",

"scripts": {
"build": "yarn clean && cross-env NODE_ENV=production tsdx build --format=cjs,esm --tsconfig tsconfig.build.json",
"build": "yarn clean && yarn compile",
"clean": "rm -rf ./dist",

@@ -29,3 +29,7 @@ "compile": "cross-env NODE_ENV=production tsdx build --format=cjs,esm --tsconfig tsconfig.build.json"

],
"gitHead": "7702c46373c7f11adc21184e7def9977203e9326"
"dependencies": {
"tslib": "^1.10.0",
"warning": "^4.0.3"
},
"gitHead": "ed24a5bb43a87adc36179283ca1de2c5af4ea26e"
}

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

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