UNPKG

@navikt/ds-react

Version:

React components from the Norwegian Labour and Welfare Administration.

50 lines 2.65 kB
var __rest = (this && this.__rest) || function (s, e) { var t = {}; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; } return t; }; /** * Custom createContext to consolidate context-implementation across the system * Inspired by: * - https://github.com/radix-ui/primitives/blob/main/packages/react/context/src/createContext.tsx * - https://github.com/chakra-ui/chakra-ui/blob/5ec0be610b5a69afba01a9c22365155c1b519136/packages/hooks/context/src/index.ts */ import React, { createContext as createReactContext, forwardRef, useContext as useReactContext, } from "react"; function getErrorMessage(hook, provider) { return `${hook} returned \`undefined\`. Seems you forgot to wrap component within ${provider}`; } export function createContext(options = {}) { const { name, hookName = "useContext", providerName = "Provider", errorMessage, defaultValue, } = options; const Context = createReactContext(defaultValue); /** * We use forwardRef to allow `ref` to be used as a regular context value * @see https://reactjs.org/docs/forwarding-refs.html#forwarding-refs-to-dom-components */ const Provider = forwardRef((_a, ref) => { // Only re-memoize when prop values change var { children } = _a, context = __rest(_a, ["children"]); // biome-ignore lint/correctness/useExhaustiveDependencies: Object.values(context) includes all dependencies. const value = React.useMemo(() => context, Object.values(context)); // eslint-disable-line react-hooks/exhaustive-deps return (React.createElement(Context.Provider, { value: ref ? Object.assign(Object.assign({}, value), { ref }) : value }, children)); }); function useContext(strict = true) { var _a; const context = useReactContext(Context); if (!context && strict) { const error = new Error(errorMessage !== null && errorMessage !== void 0 ? errorMessage : getErrorMessage(hookName, providerName)); error.name = "ContextError"; (_a = Error.captureStackTrace) === null || _a === void 0 ? void 0 : _a.call(Error, error, useContext); throw error; } return context; } Context.displayName = name; return [Provider, useContext]; } //# sourceMappingURL=create-context.js.map