UNPKG

react-view-router

Version:
248 lines 9.71 kB
const _excluded = ["router", "onRouteActive", "onRouteInactive", "onRouteChange", "exact", "activeClass", "exactActiveClass", "tag", "to", "replace", "append", "event", "children"]; function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var n = Object.getOwnPropertySymbols(e); for (r = 0; r < n.length; r++) o = n[r], -1 === t.indexOf(o) && {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; } function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (-1 !== e.indexOf(n)) continue; t[n] = r[n]; } return t; } function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; } function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; } function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); } import React from 'react'; import PropTypes from 'prop-types'; import { camelize, normalizeLocation, getHostRouterView, isPropChanged } from './util'; function guardEvent(e) { // don't redirect with control keys if (e.metaKey || e.altKey || e.ctrlKey || e.shiftKey) return; // don't redirect when preventDefault called if (e.defaultPrevented) return; // don't redirect on right click if (e.button !== undefined && e.button !== 0) return; // don't redirect if `target="_blank"` if (e.currentTarget && e.currentTarget.getAttribute) { const target = e.currentTarget.getAttribute('target'); if (/\b_blank\b/i.test(target)) return; } // this may be a Weex event which doesn't have this method if (e.preventDefault) { e.preventDefault(); } return true; } let routerLinkSeed = 0; class RouterLink extends React.Component { constructor(props) { super(props); _defineProperty(this, "unplugin", void 0); const router = props.router; this.state = { inited: false, router, routerView: null, seed: routerLinkSeed++, isMatched: false }; } _remount() { const { seed } = this.state; let { router } = this.state; if (this.unplugin) { this.unplugin(); this.unplugin = undefined; } const routerView = router ? router.viewRoot : getHostRouterView(this); if (!router && routerView) router = routerView.state.router; this.unplugin = router ? router.plugin({ name: `router-link-plugin-${seed}`, onRouteChange: currentRoute => { const { isMatched: isMatchedOld } = this.state; const { onRouteChange, onRouteActive, onRouteInactive } = this.props; const isMatched = this.isMatched(currentRoute); this.setState({ isMatched }); if (isMatched !== isMatchedOld) { if (isMatched) onRouteActive && onRouteActive(currentRoute, this);else onRouteInactive && onRouteInactive(currentRoute, this); } if (onRouteChange) onRouteChange(currentRoute, this); } }) : undefined; const { onRouteActive } = this.props; const isMatched = Boolean(router && this.isMatched(router.currentRoute, routerView)); if (router && isMatched) onRouteActive && onRouteActive(router.currentRoute, this); const state = { inited: true, router, routerView, isMatched }; this.setState(state); } getFallbackClassName(isMatched) { const { exact } = this.props; let { activeClass, exactActiveClass } = this.props; const { router } = this.state; if (router) { if (router.linkActiveClass) { activeClass = activeClass ? `${activeClass} ${router.linkActiveClass}` : router.linkActiveClass; } if (router.linkExactActiveClass) { exactActiveClass = exactActiveClass ? `${exactActiveClass} ${router.linkExactActiveClass}` : router.linkExactActiveClass; } } let fallbackClass = ''; if (isMatched) fallbackClass = exact ? exactActiveClass : activeClass; return fallbackClass; } isMatched(currentRoute = null, routerView = null) { const router = this.state.router; if (!currentRoute && router) currentRoute = router.currentRoute; if (!currentRoute) return false; const { exact, append } = this.props; let { to } = this.props; if (!routerView) routerView = this.state.routerView; to = normalizeLocation(to, { route: routerView ? routerView.state.currentRoute : null, append, queryProps: router && router.queryProps }); let isMatched = false; if (to && currentRoute) { isMatched = exact ? to.path === currentRoute.path : currentRoute.path.startsWith(to.path); } return isMatched; } componentDidMount() { this._remount(); } componentWillUnmount() { if (this.unplugin) { this.unplugin(); this.unplugin = undefined; } } shouldComponentUpdate(nextProps, nextState) { if (isPropChanged(this.props, nextProps)) return true; if (this.state.inited !== nextState.inited) return true; if (this.state.isMatched !== nextState.isMatched) return true; return false; } componentDidUpdate(prevProps) { const newState = {}; if (this.props.router !== prevProps.router) newState.router = this.props.router; // if (this.props.to !== prevProps.to) { // if (!isPlainObject(this.props.to) || !isPlainObject(prevProps.to) // || isPropChanged(this.props.to, prevProps.to)) { // newState.to = this.props.to; // } // } if (Object.keys(newState).length) { this.setState(newState, () => this._remount()); } } render() { if (!this.state.inited) return null; if (!this.props.tag) return this.props.children; let _this$props = this.props, { // eslint-disable-next-line no-unused-vars, prefer-const router: router1, onRouteActive, onRouteInactive, onRouteChange, exact, activeClass, exactActiveClass, // eslint-disable-next-line prefer-const tag, to, replace, append, event, // eslint-disable-next-line prefer-const children = [] } = _this$props, remainProps = _objectWithoutProperties(_this$props, _excluded); const { router, isMatched, routerView } = this.state; const events = {}; to = normalizeLocation(to, { route: routerView ? routerView.state.currentRoute : null, append, queryProps: router && router.queryProps }); const fallbackClass = this.getFallbackClassName(isMatched); if (fallbackClass) { if (remainProps.className) remainProps.className = `${fallbackClass} ${remainProps.className}`;else remainProps.className = fallbackClass; } if (!Array.isArray(event)) event = event ? [event] : []; event.forEach(evt => { if (!evt) return; const eventName = evt.startsWith('on') ? evt : camelize(`on-${evt}`); events[eventName] = e => { if (!to || !router || remainProps.disabled) return; if (remainProps[eventName] && remainProps[eventName](e, to) === false) return; guardEvent(e); if (replace) router.replace(to);else router.push(to); }; }); if (to && tag === 'a') remainProps.href = to.path; return /*#__PURE__*/React.createElement(tag, _objectSpread(_objectSpread({}, remainProps), events), children); } } _defineProperty(RouterLink, "propTypes", void 0); _defineProperty(RouterLink, "defaultProps", void 0); RouterLink.propTypes = { className: PropTypes.string, to: PropTypes.oneOfType([PropTypes.string, PropTypes.object]).isRequired, replace: PropTypes.bool, append: PropTypes.bool, tag: PropTypes.oneOfType([PropTypes.string, PropTypes.elementType]), activeClass: PropTypes.string, exact: PropTypes.bool, disabled: PropTypes.bool, exactActiveClass: PropTypes.string, event: PropTypes.oneOfType([PropTypes.string, PropTypes.arrayOf(PropTypes.string)]), onRouteChange: PropTypes.func, onRouteActive: PropTypes.func, onRouteInactive: PropTypes.func }; RouterLink.defaultProps = { tag: '', activeClass: 'router-link-active', exactActiveClass: 'exact-active-class', event: 'click' }; export { RouterLink, guardEvent }; export default function createRouterLink(router) { return /*#__PURE__*/React.forwardRef((props, ref) => /*#__PURE__*/React.createElement(RouterLink, _objectSpread(_objectSpread({ router }, props), {}, { ref }), props.children)); }