@bianic-ui/utils
Version:
Common utilties and types for Bianic UI
83 lines (71 loc) • 1.94 kB
JavaScript
import * as React from "react";
import { isFunction } from "./assertion";
/**
* Creates a named context, provider, and hook.
*
* @param options create context options
*/
export function createContext(options) {
if (options === void 0) {
options = {};
}
var {
strict = true,
errorMessage = "useContext: `context` is undefined. Seems you forgot to wrap component within the Provider",
name
} = options;
var Context = /*#__PURE__*/React.createContext(undefined);
Context.displayName = name;
function useContext() {
var context = React.useContext(Context);
if (!context && strict) {
throw new Error(errorMessage);
}
return context;
}
return [Context.Provider, useContext, Context];
}
/**
* Gets only the valid children of a component,
* and ignores any nullish or falsy child.
*
* @param children the children
*/
export function getValidChildren(children) {
return React.Children.toArray(children).filter(child => /*#__PURE__*/React.isValidElement(child));
}
/**
* Assigns a value to a ref function or object
*
* @param ref the ref to assign to
* @param value the value
*/
export function assignRef(ref, value) {
if (ref == null) return;
if (isFunction(ref)) {
ref(value);
return;
}
try {
//@ts-ignore
ref.current = value;
} catch (error) {
throw new Error("Cannot assign value '" + value + "' to ref '" + ref + "'");
}
}
/**
* Combine multiple React refs into a single ref function.
* This is used mostly when you need to allow consumers forward refs to
* internal components
*
* @param refs refs to assign to value to
*/
export function mergeRefs() {
for (var _len = arguments.length, refs = new Array(_len), _key = 0; _key < _len; _key++) {
refs[_key] = arguments[_key];
}
return value => {
refs.forEach(ref => assignRef(ref, value));
};
}
//# sourceMappingURL=react-helpers.js.map