UNPKG

@react-navigation/core

Version:

Core utilities for building navigators

69 lines (67 loc) 3.04 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.CHILD_STATE = void 0; exports.useRouteCache = useRouteCache; var React = _interopRequireWildcard(require("react")); var _isRecordEqual = require("./isRecordEqual.js"); function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function (e) { return e ? t : r; })(e); } function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != typeof e && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && {}.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; } /** * Utilities such as `getFocusedRouteNameFromRoute` need to access state. * So we need a way to suppress the warning for those use cases. * This is fine since they are internal utilities and this is not public API. */ const CHILD_STATE = exports.CHILD_STATE = Symbol('CHILD_STATE'); /** * Hook to cache route props for each screen in the navigator. * This lets add warnings and modifications to the route object but keep references between renders. */ function useRouteCache(routes) { // Cache object which holds route objects for each screen const cache = React.useMemo(() => ({ current: new Map() }), []); if (process.env.NODE_ENV === 'production') { // We don't want the overhead of creating extra maps every render in prod return routes; } cache.current = routes.reduce((acc, route) => { const previous = cache.current.get(route.key); const { state, ...routeWithoutState } = route; let proxy; if (previous && (0, _isRecordEqual.isRecordEqual)(previous, routeWithoutState)) { // If a cached route object already exists, reuse it proxy = previous; } else { proxy = routeWithoutState; } if (process.env.NODE_ENV !== 'production') { // FIXME: since the state is updated with mutation, the route object cannot be frozen // As a workaround, loop through the object and make the properties readonly for (const key in proxy) { // @ts-expect-error: this is fine since we are looping through the object const value = proxy[key]; Object.defineProperty(proxy, key, { enumerable: true, configurable: true, writable: false, value }); } } Object.defineProperty(proxy, CHILD_STATE, { enumerable: false, configurable: true, value: state }); acc.set(route.key, proxy); return acc; }, new Map()); return Array.from(cache.current.values()); } //# sourceMappingURL=useRouteCache.js.map