UNPKG

@layr/react-integration

Version:
75 lines 3.7 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.BrowserNavigatorPlugin = void 0; const tslib_1 = require("tslib"); const navigator_1 = require("@layr/navigator"); const react_1 = tslib_1.__importStar(require("react")); const core_helpers_1 = require("core-helpers"); function BrowserNavigatorPlugin() { return function (navigator) { navigator.addAddressableMethodWrapper(function (receiver, method, params) { if ((0, core_helpers_1.hasOwnProperty)(method, '__isView')) { return react_1.default.createElement(method, params); } else { return method.call(receiver, params); } }); navigator.addCustomRouteDecorator(function (method) { method.Link = function ({ params, hash, ...props }) { const to = method.generateURL(params, { hash }); return navigator.Link({ to, ...props }); }; }); Object.assign(navigator, { Link(props) { const { to, className, activeClassName, style, activeStyle, ...otherProps } = props; if ('onClick' in props) { throw new Error(`The 'onClick' prop is not allowed in the 'Link' component`); } const handleClick = (0, react_1.useCallback)((event) => { if (!(event.shiftKey || event.ctrlKey || event.altKey || event.metaKey)) { event.preventDefault(); navigator.navigate(to, { defer: false }); } }, [to]); const currentPath = navigator.getCurrentPath(); const linkPath = (0, navigator_1.normalizeURL)(to).pathname; const isActive = linkPath === currentPath; const { actualClassName, actualStyle } = (0, react_1.useMemo)(() => { let actualClassName = className; let actualStyle = style; if (isActive) { if (activeClassName !== undefined) { const classes = actualClassName !== undefined ? [actualClassName] : []; classes.push(activeClassName); actualClassName = classes.join(' '); } if (activeStyle !== undefined) { actualStyle = { ...actualStyle, ...activeStyle }; } } return { actualClassName, actualStyle }; }, [isActive, className, activeClassName, style, activeStyle]); return (react_1.default.createElement("a", { href: to, onClick: handleClick, className: actualClassName, style: actualStyle, ...otherProps })); }, useBlocker(isBlocked) { (0, react_1.useEffect)(() => () => { // Always unblock the navigator when the associated React component unmounts navigator.unblock(); }, []); navigator.setIsBlocked(isBlocked); }, useBeforeNavigate(beforeNavigate) { (0, react_1.useEffect)(() => () => { // Always remove the navigator `beforeNavigate` hook when the associated // React component unmounts navigator.setBeforeNavigate(undefined); }, []); navigator.setBeforeNavigate(beforeNavigate); } }); }; } exports.BrowserNavigatorPlugin = BrowserNavigatorPlugin; //# sourceMappingURL=plugins.js.map