UNPKG

react-enroute

Version:
75 lines (60 loc) 1.98 kB
"use strict"; exports.__esModule = true; exports.Router = Router; exports.loc = exports.isPath = exports.genLocation = exports.findPath = void 0; var _react = require("react"); var _utils = require("./utils"); exports.findPathValue = _utils.findPathValue; exports.genLocation = _utils.genLocation; exports.loc = _utils.loc; exports.isPath = _utils.isPath; exports.findPath = _utils.findPath; var _debug = require("./debug"); function Router(_ref) { var location = _ref.location, options = _ref.options, children = _ref.children; // null or undefined if (location == null) return null; var routes = addRoutes(children, {}); return renderMatch(routes, location, options); } function addRoutes(elements, routes, parent) { _react.Children.forEach(elements, function (element) { var route = createRoute(element, parent); routes[route.path] = route; var children = element.props.children; addRoutes(children, routes, route); }); return routes; } function createRoute(element, parent) { var path = fullPath(element.props.path, parent); path = removeEdgeSlashes(path); return { path: path, parent: parent, element: element }; } function fullPath(path, parent) { if (!path) return parent ? parent.path : ''; // index route if (!parent || path[0] === '/') return path; // root or absolute return parent.path + '/' + path; } function renderMatch(routes, location, options) { location = removeEdgeSlashes(location); var result = (0, _utils.findPathValue)(routes, location, options); if (result) return render(result.value, result.params); (0, _debug.warnNotFound)(routes, location); return null; } function render(route, params, children) { var element = route.element, parent = route.parent; var node = (0, _react.cloneElement)(element, params, children); return parent ? render(parent, params, node) : node; } function removeEdgeSlashes(path) { return path.replace(/^\/|\/$/g, ''); }