react-router
Version:
A complete routing library for React
1,575 lines (1,196 loc) • 127 kB
JavaScript
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory(require("react"));
else if(typeof define === 'function' && define.amd)
define(["react"], factory);
else if(typeof exports === 'object')
exports["ReactRouter"] = factory(require("react"));
else
root["ReactRouter"] = factory(root["React"]);
})(this, function(__WEBPACK_EXTERNAL_MODULE_2__) {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
exports.propTypes = exports.createServerRenderContext = exports.matchPattern = exports.StaticRouter = exports.ServerRouter = exports.MemoryRouter = exports.HashRouter = exports.BrowserRouter = exports.Redirect = exports.NavigationPrompt = exports.Miss = exports.Match = exports.Link = undefined;
var _Link2 = __webpack_require__(1);
var _Link3 = _interopRequireDefault(_Link2);
var _Match2 = __webpack_require__(9);
var _Match3 = _interopRequireDefault(_Match2);
var _Miss2 = __webpack_require__(15);
var _Miss3 = _interopRequireDefault(_Miss2);
var _NavigationPrompt2 = __webpack_require__(16);
var _NavigationPrompt3 = _interopRequireDefault(_NavigationPrompt2);
var _Redirect2 = __webpack_require__(17);
var _Redirect3 = _interopRequireDefault(_Redirect2);
var _BrowserRouter2 = __webpack_require__(18);
var _BrowserRouter3 = _interopRequireDefault(_BrowserRouter2);
var _HashRouter2 = __webpack_require__(34);
var _HashRouter3 = _interopRequireDefault(_HashRouter2);
var _MemoryRouter2 = __webpack_require__(36);
var _MemoryRouter3 = _interopRequireDefault(_MemoryRouter2);
var _ServerRouter2 = __webpack_require__(38);
var _ServerRouter3 = _interopRequireDefault(_ServerRouter2);
var _StaticRouter2 = __webpack_require__(28);
var _StaticRouter3 = _interopRequireDefault(_StaticRouter2);
var _matchPattern2 = __webpack_require__(11);
var _matchPattern3 = _interopRequireDefault(_matchPattern2);
var _createServerRenderContext2 = __webpack_require__(39);
var _createServerRenderContext3 = _interopRequireDefault(_createServerRenderContext2);
var _PropTypes = __webpack_require__(8);
var _propTypes = _interopRequireWildcard(_PropTypes);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.Link = _Link3.default;
exports.Match = _Match3.default;
exports.Miss = _Miss3.default;
exports.NavigationPrompt = _NavigationPrompt3.default;
exports.Redirect = _Redirect3.default;
// High-level wrappers
exports.BrowserRouter = _BrowserRouter3.default;
exports.HashRouter = _HashRouter3.default;
exports.MemoryRouter = _MemoryRouter3.default;
exports.ServerRouter = _ServerRouter3.default;
// Low-level building block
exports.StaticRouter = _StaticRouter3.default;
// Util for server rendering "pre-render match"
exports.matchPattern = _matchPattern3.default;
// Util for server rendering context
exports.createServerRenderContext = _createServerRenderContext3.default;
// React PropTypes for all Components
exports.propTypes = _propTypes;
/***/ },
/* 1 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var _Broadcasts = __webpack_require__(3);
var _PropTypes = __webpack_require__(8);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var Link = function (_React$Component) {
_inherits(Link, _React$Component);
function Link() {
var _temp, _this, _ret;
_classCallCheck(this, Link);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = _possibleConstructorReturn(this, _React$Component.call.apply(_React$Component, [this].concat(args))), _this), _this.handleClick = function (event) {
if (_this.props.onClick) _this.props.onClick(event);
if (!event.defaultPrevented && // onClick prevented default
!_this.props.target && // let browser handle "target=_blank" etc.
!isModifiedEvent(event) && isLeftClickEvent(event)) {
event.preventDefault();
_this.handleTransition();
}
}, _this.handleTransition = function () {
var router = _this.context.router;
var _this$props = _this.props,
to = _this$props.to,
replace = _this$props.replace;
var navigate = replace ? router.replaceWith : router.transitionTo;
navigate(to);
}, _temp), _possibleConstructorReturn(_this, _ret);
}
Link.prototype.render = function render() {
var _this2 = this;
var router = this.context.router;
var _props = this.props,
to = _props.to,
style = _props.style,
activeStyle = _props.activeStyle,
className = _props.className,
activeClassName = _props.activeClassName,
getIsActive = _props.isActive,
activeOnlyWhenExact = _props.activeOnlyWhenExact,
replace = _props.replace,
children = _props.children,
rest = _objectWithoutProperties(_props, ['to', 'style', 'activeStyle', 'className', 'activeClassName', 'isActive', 'activeOnlyWhenExact', 'replace', 'children']);
return _react2.default.createElement(
_Broadcasts.LocationSubscriber,
null,
function (location) {
var isActive = getIsActive(location, createLocationDescriptor(to), _this2.props);
// If children is a function, we are using a Function as Children Component
// so useful values will be passed down to the children function.
if (typeof children == 'function') {
return children({
isActive: isActive,
location: location,
href: router ? router.createHref(to) : to,
onClick: _this2.handleClick,
transition: _this2.handleTransition
});
}
// Maybe we should use <Match> here? Not sure how the custom `isActive`
// prop would shake out, also, this check happens a LOT so maybe its good
// to optimize here w/ a faster isActive check, so we'd need to benchmark
// any attempt at changing to use <Match>
return _react2.default.createElement('a', _extends({}, rest, {
href: router ? router.createHref(to) : to,
onClick: _this2.handleClick,
style: isActive ? _extends({}, style, activeStyle) : style,
className: isActive ? [className, activeClassName].join(' ').trim() : className,
children: children
}));
}
);
};
return Link;
}(_react2.default.Component);
Link.defaultProps = {
replace: false,
activeOnlyWhenExact: false,
className: '',
activeClassName: '',
style: {},
activeStyle: {},
isActive: function isActive(location, to, props) {
return pathIsActive(to.pathname, location.pathname, props.activeOnlyWhenExact) && queryIsActive(to.query, location.query);
}
};
Link.contextTypes = {
router: _PropTypes.routerContext.isRequired
};
if (false) {
Link.propTypes = {
to: _react.PropTypes.oneOfType([_react.PropTypes.string, _react.PropTypes.object]).isRequired,
replace: _react.PropTypes.bool,
activeStyle: _react.PropTypes.object,
activeClassName: _react.PropTypes.string,
activeOnlyWhenExact: _react.PropTypes.bool,
isActive: _react.PropTypes.func,
children: _react.PropTypes.oneOfType([_react.PropTypes.node, _react.PropTypes.func]),
// props we have to deal with but aren't necessarily
// part of the Link API
style: _react.PropTypes.object,
className: _react.PropTypes.string,
target: _react.PropTypes.string,
onClick: _react.PropTypes.func
};
}
// we should probably use LocationUtils.createLocationDescriptor
var createLocationDescriptor = function createLocationDescriptor(to) {
return (typeof to === 'undefined' ? 'undefined' : _typeof(to)) === 'object' ? to : { pathname: to };
};
var pathIsActive = function pathIsActive(to, pathname, activeOnlyWhenExact) {
return activeOnlyWhenExact ? pathname === to : pathname.indexOf(to) === 0;
};
var queryIsActive = function queryIsActive(query, activeQuery) {
if (activeQuery == null) return query == null;
if (query == null) return true;
return deepEqual(query, activeQuery);
};
var isLeftClickEvent = function isLeftClickEvent(event) {
return event.button === 0;
};
var isModifiedEvent = function isModifiedEvent(event) {
return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey);
};
var deepEqual = function deepEqual(a, b) {
if (a == b) return true;
if (a == null || b == null) return false;
if (Array.isArray(a)) {
return Array.isArray(b) && a.length === b.length && a.every(function (item, index) {
return deepEqual(item, b[index]);
});
}
if ((typeof a === 'undefined' ? 'undefined' : _typeof(a)) === 'object') {
for (var p in a) {
if (!Object.prototype.hasOwnProperty.call(a, p)) {
continue;
}
if (a[p] === undefined) {
if (b[p] !== undefined) {
return false;
}
} else if (!Object.prototype.hasOwnProperty.call(b, p)) {
return false;
} else if (!deepEqual(a[p], b[p])) {
return false;
}
}
return true;
}
return String(a) === String(b);
};
exports.default = Link;
/***/ },
/* 2 */
/***/ function(module, exports) {
module.exports = __WEBPACK_EXTERNAL_MODULE_2__;
/***/ },
/* 3 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
exports.LocationSubscriber = exports.LocationBroadcast = undefined;
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var _reactBroadcast = __webpack_require__(4);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var LocationChannel = 'location';
var LocationBroadcast = exports.LocationBroadcast = function LocationBroadcast(props) {
return _react2.default.createElement(_reactBroadcast.Broadcast, _extends({}, props, { channel: LocationChannel }));
};
var LocationSubscriber = exports.LocationSubscriber = function LocationSubscriber(props) {
return _react2.default.createElement(_reactBroadcast.Subscriber, _extends({}, props, { channel: LocationChannel }));
};
/***/ },
/* 4 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
exports.Subscriber = exports.Broadcast = undefined;
var _Broadcast2 = __webpack_require__(5);
var _Broadcast3 = _interopRequireDefault(_Broadcast2);
var _Subscriber2 = __webpack_require__(7);
var _Subscriber3 = _interopRequireDefault(_Subscriber2);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
exports.Broadcast = _Broadcast3.default;
exports.Subscriber = _Subscriber3.default;
/***/ },
/* 5 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _invariant = __webpack_require__(6);
var _invariant2 = _interopRequireDefault(_invariant);
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var createBroadcast = function createBroadcast(initialValue) {
var listeners = [];
var currentValue = initialValue;
return {
publish: function publish(value) {
currentValue = value;
listeners.forEach(function (listener) {
return listener(currentValue);
});
},
subscribe: function subscribe(listener) {
listeners.push(listener);
// Publish to this subscriber once immediately.
listener(currentValue);
return function () {
return listeners = listeners.filter(function (item) {
return item !== listener;
});
};
}
};
};
/**
* A <Broadcast> provides a generic way for descendants to "subscribe"
* to some value that changes over time, bypassing any intermediate
* shouldComponentUpdate's in the hierarchy. It puts all subscription
* functions on context.broadcasts, keyed by "channel".
*
* To use it, a subscriber must opt-in to context.broadcasts. See the
* <Subscriber> component for a reference implementation.
*/
var Broadcast = function (_React$Component) {
_inherits(Broadcast, _React$Component);
function Broadcast() {
var _temp, _this, _ret;
_classCallCheck(this, Broadcast);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = _possibleConstructorReturn(this, _React$Component.call.apply(_React$Component, [this].concat(args))), _this), _this.broadcast = createBroadcast(_this.props.value), _temp), _possibleConstructorReturn(_this, _ret);
}
Broadcast.prototype.getBroadcastsContext = function getBroadcastsContext() {
var _extends2;
var channel = this.props.channel;
var broadcasts = this.context.broadcasts;
return _extends({}, broadcasts, (_extends2 = {}, _extends2[channel] = this.broadcast.subscribe, _extends2));
};
Broadcast.prototype.getChildContext = function getChildContext() {
return {
broadcasts: this.getBroadcastsContext()
};
};
Broadcast.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) {
!(this.props.channel === nextProps.channel) ? false ? (0, _invariant2.default)(false, 'You cannot change <Broadcast channel>') : (0, _invariant2.default)(false) : void 0;
if (this.props.value !== nextProps.value) this.broadcast.publish(nextProps.value);
};
Broadcast.prototype.render = function render() {
return _react2.default.Children.only(this.props.children);
};
return Broadcast;
}(_react2.default.Component);
Broadcast.contextTypes = {
broadcasts: _react.PropTypes.object
};
Broadcast.childContextTypes = {
broadcasts: _react.PropTypes.object.isRequired
};
if (false) {
Broadcast.propTypes = {
channel: _react.PropTypes.string.isRequired,
children: _react.PropTypes.node.isRequired,
value: _react.PropTypes.any
};
}
exports.default = Broadcast;
/***/ },
/* 6 */
/***/ function(module, exports, __webpack_require__) {
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
'use strict';
/**
* Use invariant() to assert state which your program assumes to be true.
*
* Provide sprintf-style format (only %s is supported) and arguments
* to provide information about what broke and what you were
* expecting.
*
* The invariant message will be stripped in production, but the invariant
* will remain to ensure logic does not differ in production.
*/
var invariant = function(condition, format, a, b, c, d, e, f) {
if (false) {
if (format === undefined) {
throw new Error('invariant requires an error message argument');
}
}
if (!condition) {
var error;
if (format === undefined) {
error = new Error(
'Minified exception occurred; use the non-minified dev environment ' +
'for the full error message and additional helpful warnings.'
);
} else {
var args = [a, b, c, d, e, f];
var argIndex = 0;
error = new Error(
format.replace(/%s/g, function() { return args[argIndex++]; })
);
error.name = 'Invariant Violation';
}
error.framesToPop = 1; // we don't care about invariant's own frame
throw error;
}
};
module.exports = invariant;
/***/ },
/* 7 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _invariant = __webpack_require__(6);
var _invariant2 = _interopRequireDefault(_invariant);
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
/**
* A <Subscriber> pulls the value for a channel off of context.broadcasts
* and passes it to its children function.
*/
var Subscriber = function (_React$Component) {
_inherits(Subscriber, _React$Component);
function Subscriber() {
var _temp, _this, _ret;
_classCallCheck(this, Subscriber);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = _possibleConstructorReturn(this, _React$Component.call.apply(_React$Component, [this].concat(args))), _this), _this.state = {
value: null
}, _temp), _possibleConstructorReturn(_this, _ret);
}
Subscriber.prototype.componentWillMount = function componentWillMount() {
var _this2 = this;
var channel = this.props.channel;
if (this.context.broadcasts) {
var subscribe = this.context.broadcasts[channel];
!(typeof subscribe === 'function') ? false ? (0, _invariant2.default)(false, '<Subscriber channel="%s"> must be rendered in the context of a <Broadcast channel="%s">', channel, channel) : (0, _invariant2.default)(false) : void 0;
this.unsubscribe = subscribe(function (value) {
// This function will be called once immediately.
_this2.setState({ value: value });
});
}
};
Subscriber.prototype.componentWillUnmount = function componentWillUnmount() {
if (this.unsubscribe) this.unsubscribe();
};
Subscriber.prototype.render = function render() {
return this.props.children(this.state.value);
};
return Subscriber;
}(_react2.default.Component);
Subscriber.contextTypes = {
broadcasts: _react2.default.PropTypes.object
};
if (false) {
Subscriber.propTypes = {
channel: _react.PropTypes.string.isRequired,
children: _react.PropTypes.func.isRequired
};
}
exports.default = Subscriber;
/***/ },
/* 8 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
exports.routerContext = exports.historyContext = exports.location = exports.history = exports.matchContext = exports.action = undefined;
var _react = __webpack_require__(2);
var action = exports.action = _react.PropTypes.oneOf(['PUSH', 'REPLACE', 'POP']);
var matchContext = exports.matchContext = _react.PropTypes.shape({
addMatch: _react.PropTypes.func.isRequired,
removeMatch: _react.PropTypes.func.isRequired
});
var history = exports.history = _react.PropTypes.shape({
listen: _react.PropTypes.func.isRequired,
listenBefore: _react.PropTypes.func.isRequired,
push: _react.PropTypes.func.isRequired,
replace: _react.PropTypes.func.isRequired,
go: _react.PropTypes.func.isRequired
});
var location = exports.location = _react.PropTypes.shape({
pathname: _react.PropTypes.string.isRequired,
search: _react.PropTypes.string.isRequired,
hash: _react.PropTypes.string.isRequired,
state: _react.PropTypes.any,
key: _react.PropTypes.string
});
var historyContext = exports.historyContext = _react.PropTypes.shape({
action: action.isRequired,
location: location.isRequired,
push: _react.PropTypes.func.isRequired,
replace: _react.PropTypes.func.isRequired,
go: _react.PropTypes.func.isRequired,
goBack: _react.PropTypes.func.isRequired,
goForward: _react.PropTypes.func.isRequired,
canGo: _react.PropTypes.func,
block: _react.PropTypes.func.isRequired
});
var routerContext = exports.routerContext = _react.PropTypes.shape({
transitionTo: _react.PropTypes.func.isRequired,
replaceWith: _react.PropTypes.func.isRequired,
blockTransitions: _react.PropTypes.func.isRequired,
createHref: _react.PropTypes.func.isRequired
});
/***/ },
/* 9 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var _MatchProvider = __webpack_require__(10);
var _MatchProvider2 = _interopRequireDefault(_MatchProvider);
var _matchPattern = __webpack_require__(11);
var _matchPattern2 = _interopRequireDefault(_matchPattern);
var _Broadcasts = __webpack_require__(3);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var RegisterMatch = function (_React$Component) {
_inherits(RegisterMatch, _React$Component);
function RegisterMatch() {
_classCallCheck(this, RegisterMatch);
return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
}
RegisterMatch.prototype.registerMatch = function registerMatch() {
var matchContext = this.context.match;
var match = this.props.match;
if (match && matchContext) {
matchContext.addMatch(match);
}
};
RegisterMatch.prototype.componentWillMount = function componentWillMount() {
if (this.context.serverRouter) {
this.registerMatch();
}
};
RegisterMatch.prototype.componentDidMount = function componentDidMount() {
if (!this.context.serverRouter) {
this.registerMatch();
}
};
RegisterMatch.prototype.componentDidUpdate = function componentDidUpdate(prevProps) {
var match = this.context.match;
if (match) {
if (prevProps.match && !this.props.match) {
match.removeMatch(prevProps.match);
} else if (!prevProps.match && this.props.match) {
match.addMatch(this.props.match);
}
}
};
RegisterMatch.prototype.componentWillUnmount = function componentWillUnmount() {
if (this.props.match) {
this.context.match.removeMatch(this.props.match);
}
};
RegisterMatch.prototype.render = function render() {
return _react2.default.Children.only(this.props.children);
};
return RegisterMatch;
}(_react2.default.Component);
RegisterMatch.contextTypes = {
match: _react.PropTypes.object,
serverRouter: _react.PropTypes.object
};
if (false) {
RegisterMatch.propTypes = {
children: _react.PropTypes.node.isRequired,
match: _react.PropTypes.any
};
}
var Match = function (_React$Component2) {
_inherits(Match, _React$Component2);
function Match() {
_classCallCheck(this, Match);
return _possibleConstructorReturn(this, _React$Component2.apply(this, arguments));
}
Match.prototype.render = function render() {
var _this3 = this;
return _react2.default.createElement(
_Broadcasts.LocationSubscriber,
null,
function (location) {
var _props = _this3.props,
children = _props.children,
render = _props.render,
Component = _props.component,
pattern = _props.pattern,
exactly = _props.exactly;
var matchContext = _this3.context.match;
var parent = matchContext && matchContext.parent;
var match = (0, _matchPattern2.default)(pattern, location, exactly, parent);
var props = _extends({}, match, { location: location, pattern: pattern });
return _react2.default.createElement(
RegisterMatch,
{ match: match },
_react2.default.createElement(
_MatchProvider2.default,
{ match: match },
children ? children(_extends({ matched: !!match }, props)) : match ? render ? render(props) : _react2.default.createElement(Component, props) : null
)
);
}
);
};
return Match;
}(_react2.default.Component);
Match.defaultProps = {
exactly: false
};
Match.contextTypes = {
match: _react.PropTypes.object
};
if (false) {
Match.propTypes = {
pattern: _react.PropTypes.string,
exactly: _react.PropTypes.bool,
children: _react.PropTypes.func,
render: _react.PropTypes.func,
component: _react.PropTypes.func
};
}
exports.default = Match;
/***/ },
/* 10 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _react = __webpack_require__(2);
var _react2 = _interopRequireDefault(_react);
var _PropTypes = __webpack_require__(8);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var MatchProvider = function (_React$Component) {
_inherits(MatchProvider, _React$Component);
function MatchProvider(props) {
_classCallCheck(this, MatchProvider);
// **IMPORTANT** we must mutate matches, never reassign, in order for
// server rendering to work w/ the two-pass render approach for Miss
var _this = _possibleConstructorReturn(this, _React$Component.call(this, props));
_this.addMatch = function (match) {
_this.matches.push(match);
};
_this.removeMatch = function (match) {
_this.matches.splice(_this.matches.indexOf(match), 1);
};
_this.matches = [];
_this.subscribers = [];
_this.hasMatches = null; // use null for initial value
_this.serverRouterIndex = null;
return _this;
}
MatchProvider.prototype.getChildContext = function getChildContext() {
var _this2 = this;
return {
match: {
addMatch: this.addMatch,
removeMatch: this.removeMatch,
matches: this.matches,
parent: this.props.match,
serverRouterIndex: this.serverRouterIndex,
subscribe: function subscribe(fn) {
_this2.subscribers.push(fn);
return function () {
_this2.subscribers.splice(_this2.subscribers.indexOf(fn), 1);
};
}
}
};
};
MatchProvider.prototype.componentDidUpdate = function componentDidUpdate() {
this.notifySubscribers();
};
MatchProvider.prototype.componentWillMount = function componentWillMount() {
var serverRouter = this.context.serverRouter;
if (serverRouter) {
this.serverRouterIndex = serverRouter.registerMatchContext(this.matches);
}
};
MatchProvider.prototype.componentDidMount = function componentDidMount() {
// React's contract is that cDM of descendants is called before cDM of
// ancestors, so here we can safely check if we found a match
this.notifySubscribers();
};
MatchProvider.prototype.notifySubscribers = function notifySubscribers() {
var _this3 = this;
if (this.subscribers.length) {
this.hasMatches = this.matches.length !== 0;
this.subscribers.forEach(function (fn) {
return fn(_this3.hasMatches);
});
}
};
MatchProvider.prototype.render = function render() {
return this.props.children;
};
return MatchProvider;
}(_react2.default.Component);
MatchProvider.childContextTypes = {
match: _PropTypes.matchContext.isRequired
};
MatchProvider.contextTypes = {
serverRouter: _react.PropTypes.object
};
if (false) {
MatchProvider.propTypes = {
match: _react.PropTypes.any,
children: _react.PropTypes.node
};
}
exports.default = MatchProvider;
/***/ },
/* 11 */
/***/ function(module, exports, __webpack_require__) {
'use strict';
exports.__esModule = true;
var _pathToRegexp = __webpack_require__(12);
var _pathToRegexp2 = _interopRequireDefault(_pathToRegexp);
var _MatcherCache = __webpack_require__(14);
var _MatcherCache2 = _interopRequireDefault(_MatcherCache);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// cache[exactly][pattern] contains getMatcher(pattern, exactly)
var cache = {
true: new _MatcherCache2.default(),
false: new _MatcherCache2.default()
};
var getMatcher = function getMatcher(pattern, exactly) {
var exactlyStr = exactly ? 'true' : 'false';
var matcher = cache[exactlyStr].get(pattern);
if (!matcher) {
var keys = [];
var regex = (0, _pathToRegexp2.default)(pattern, keys, { end: exactly, strict: true });
matcher = { keys: keys, regex: regex };
cache[exactlyStr].set(pattern, matcher);
}
return matcher;
};
var parseParams = function parseParams(pattern, match, keys) {
return match.slice(1).filter(function (value) {
return value !== undefined;
}).reduce(function (params, value, index) {
params[keys[index].name] = decodeURIComponent(value);
return params;
}, {});
};
var matchPattern = function matchPattern(pattern, location, matchExactly, parent) {
var specialCase = !matchExactly && pattern === '/';
if (specialCase) {
return {
params: null,
isExact: location.pathname === '/',
pathname: '/'
};
} else {
if (parent && pattern.charAt(0) !== '/') {
pattern = parent.pathname + (parent.pathname.charAt(parent.pathname.length - 1) !== '/' ? '/' : '') + pattern;
}
var matcher = getMatcher(pattern, matchExactly);
var match = matcher.regex.exec(location.pathname);
if (match) {
var params = parseParams(pattern, match, matcher.keys);
var pathname = match[0];
var isExact = pathname === location.pathname;
return { params: params, isExact: isExact, pathname: pathname };
} else {
return null;
}
}
};
exports.default = matchPattern;
/***/ },
/* 12 */
/***/ function(module, exports, __webpack_require__) {
var isarray = __webpack_require__(13)
/**
* Expose `pathToRegexp`.
*/
module.exports = pathToRegexp
module.exports.parse = parse
module.exports.compile = compile
module.exports.tokensToFunction = tokensToFunction
module.exports.tokensToRegExp = tokensToRegExp
/**
* The main path matching regexp utility.
*
* @type {RegExp}
*/
var PATH_REGEXP = new RegExp([
// Match escaped characters that would otherwise appear in future matches.
// This allows the user to escape special characters that won't transform.
'(\\\\.)',
// Match Express-style parameters and un-named parameters with a prefix
// and optional suffixes. Matches appear as:
//
// "/:test(\\d+)?" => ["/", "test", "\d+", undefined, "?", undefined]
// "/route(\\d+)" => [undefined, undefined, undefined, "\d+", undefined, undefined]
// "/*" => ["/", undefined, undefined, undefined, undefined, "*"]
'([\\/.])?(?:(?:\\:(\\w+)(?:\\(((?:\\\\.|[^\\\\()])+)\\))?|\\(((?:\\\\.|[^\\\\()])+)\\))([+*?])?|(\\*))'
].join('|'), 'g')
/**
* Parse a string for the raw tokens.
*
* @param {string} str
* @param {Object=} options
* @return {!Array}
*/
function parse (str, options) {
var tokens = []
var key = 0
var index = 0
var path = ''
var defaultDelimiter = options && options.delimiter || '/'
var res
while ((res = PATH_REGEXP.exec(str)) != null) {
var m = res[0]
var escaped = res[1]
var offset = res.index
path += str.slice(index, offset)
index = offset + m.length
// Ignore already escaped sequences.
if (escaped) {
path += escaped[1]
continue
}
var next = str[index]
var prefix = res[2]
var name = res[3]
var capture = res[4]
var group = res[5]
var modifier = res[6]
var asterisk = res[7]
// Push the current path onto the tokens.
if (path) {
tokens.push(path)
path = ''
}
var partial = prefix != null && next != null && next !== prefix
var repeat = modifier === '+' || modifier === '*'
var optional = modifier === '?' || modifier === '*'
var delimiter = res[2] || defaultDelimiter
var pattern = capture || group
tokens.push({
name: name || key++,
prefix: prefix || '',
delimiter: delimiter,
optional: optional,
repeat: repeat,
partial: partial,
asterisk: !!asterisk,
pattern: pattern ? escapeGroup(pattern) : (asterisk ? '.*' : '[^' + escapeString(delimiter) + ']+?')
})
}
// Match any characters still remaining.
if (index < str.length) {
path += str.substr(index)
}
// If the path exists, push it onto the end.
if (path) {
tokens.push(path)
}
return tokens
}
/**
* Compile a string to a template function for the path.
*
* @param {string} str
* @param {Object=} options
* @return {!function(Object=, Object=)}
*/
function compile (str, options) {
return tokensToFunction(parse(str, options))
}
/**
* Prettier encoding of URI path segments.
*
* @param {string}
* @return {string}
*/
function encodeURIComponentPretty (str) {
return encodeURI(str).replace(/[\/?#]/g, function (c) {
return '%' + c.charCodeAt(0).toString(16).toUpperCase()
})
}
/**
* Encode the asterisk parameter. Similar to `pretty`, but allows slashes.
*
* @param {string}
* @return {string}
*/
function encodeAsterisk (str) {
return encodeURI(str).replace(/[?#]/g, function (c) {
return '%' + c.charCodeAt(0).toString(16).toUpperCase()
})
}
/**
* Expose a method for transforming tokens into the path function.
*/
function tokensToFunction (tokens) {
// Compile all the tokens into regexps.
var matches = new Array(tokens.length)
// Compile all the patterns before compilation.
for (var i = 0; i < tokens.length; i++) {
if (typeof tokens[i] === 'object') {
matches[i] = new RegExp('^(?:' + tokens[i].pattern + ')$')
}
}
return function (obj, opts) {
var path = ''
var data = obj || {}
var options = opts || {}
var encode = options.pretty ? encodeURIComponentPretty : encodeURIComponent
for (var i = 0; i < tokens.length; i++) {
var token = tokens[i]
if (typeof token === 'string') {
path += token
continue
}
var value = data[token.name]
var segment
if (value == null) {
if (token.optional) {
// Prepend partial segment prefixes.
if (token.partial) {
path += token.prefix
}
continue
} else {
throw new TypeError('Expected "' + token.name + '" to be defined')
}
}
if (isarray(value)) {
if (!token.repeat) {
throw new TypeError('Expected "' + token.name + '" to not repeat, but received `' + JSON.stringify(value) + '`')
}
if (value.length === 0) {
if (token.optional) {
continue
} else {
throw new TypeError('Expected "' + token.name + '" to not be empty')
}
}
for (var j = 0; j < value.length; j++) {
segment = encode(value[j])
if (!matches[i].test(segment)) {
throw new TypeError('Expected all "' + token.name + '" to match "' + token.pattern + '", but received `' + JSON.stringify(segment) + '`')
}
path += (j === 0 ? token.prefix : token.delimiter) + segment
}
continue
}
segment = token.asterisk ? encodeAsterisk(value) : encode(value)
if (!matches[i].test(segment)) {
throw new TypeError('Expected "' + token.name + '" to match "' + token.pattern + '", but received "' + segment + '"')
}
path += token.prefix + segment
}
return path
}
}
/**
* Escape a regular expression string.
*
* @param {string} str
* @return {string}
*/
function escapeString (str) {
return str.replace(/([.+*?=^!:${}()[\]|\/\\])/g, '\\$1')
}
/**
* Escape the capturing group by escaping special characters and meaning.
*
* @param {string} group
* @return {string}
*/
function escapeGroup (group) {
return group.replace(/([=!:$\/()])/g, '\\$1')
}
/**
* Attach the keys as a property of the regexp.
*
* @param {!RegExp} re
* @param {Array} keys
* @return {!RegExp}
*/
function attachKeys (re, keys) {
re.keys = keys
return re
}
/**
* Get the flags for a regexp from the options.
*
* @param {Object} options
* @return {string}
*/
function flags (options) {
return options.sensitive ? '' : 'i'
}
/**
* Pull out keys from a regexp.
*
* @param {!RegExp} path
* @param {!Array} keys
* @return {!RegExp}
*/
function regexpToRegexp (path, keys) {
// Use a negative lookahead to match only capturing groups.
var groups = path.source.match(/\((?!\?)/g)
if (groups) {
for (var i = 0; i < groups.length; i++) {
keys.push({
name: i,
prefix: null,
delimiter: null,
optional: false,
repeat: false,
partial: false,
asterisk: false,
pattern: null
})
}
}
return attachKeys(path, keys)
}
/**
* Transform an array into a regexp.
*
* @param {!Array} path
* @param {Array} keys
* @param {!Object} options
* @return {!RegExp}
*/
function arrayToRegexp (path, keys, options) {
var parts = []
for (var i = 0; i < path.length; i++) {
parts.push(pathToRegexp(path[i], keys, options).source)
}
var regexp = new RegExp('(?:' + parts.join('|') + ')', flags(options))
return attachKeys(regexp, keys)
}
/**
* Create a path regexp from string input.
*
* @param {string} path
* @param {!Array} keys
* @param {!Object} options
* @return {!RegExp}
*/
function stringToRegexp (path, keys, options) {
return tokensToRegExp(parse(path, options), keys, options)
}
/**
* Expose a function for taking tokens and returning a RegExp.
*
* @param {!Array} tokens
* @param {(Array|Object)=} keys
* @param {Object=} options
* @return {!RegExp}
*/
function tokensToRegExp (tokens, keys, options) {
if (!isarray(keys)) {
options = /** @type {!Object} */ (keys || options)
keys = []
}
options = options || {}
var strict = options.strict
var end = options.end !== false
var route = ''
// Iterate over the tokens and create our regexp string.
for (var i = 0; i < tokens.length; i++) {
var token = tokens[i]
if (typeof token === 'string') {
route += escapeString(token)
} else {
var prefix = escapeString(token.prefix)
var capture = '(?:' + token.pattern + ')'
keys.push(token)
if (token.repeat) {
capture += '(?:' + prefix + capture + ')*'
}
if (token.optional) {
if (!token.partial) {
capture = '(?:' + prefix + '(' + capture + '))?'
} else {
capture = prefix + '(' + capture + ')?'
}
} else {
capture = prefix + '(' + capture + ')'
}
route += capture
}
}
var delimiter = escapeString(options.delimiter || '/')
var endsWithDelimiter = route.slice(-delimiter.length) === delimiter
// In non-strict mode we allow a slash at the end of match. If the path to
// match already ends with a slash, we remove it for consistency. The slash
// is valid at the end of a path match, not in the middle. This is important
// in non-ending mode, where "/test/" shouldn't match "/test//route".
if (!strict) {
route = (endsWithDelimiter ? route.slice(0, -delimiter.length) : route) + '(?:' + delimiter + '(?=$))?'
}
if (end) {
route += '$'
} else {
// In non-ending mode, we need the capturing groups to match as much as
// possible by using a positive lookahead to the end or next path segment.
route += strict && endsWithDelimiter ? '' : '(?=' + delimiter + '|$)'
}
return attachKeys(new RegExp('^' + route, flags(options)), keys)
}
/**
* Normalize the given path string, returning a regular expression.
*
* An empty array can be passed in for the keys, which will hold the
* placeholder key descriptions. For example, using `/user/:id`, `keys` will
* contain `[{ name: 'id', delimiter: '/', optional: false, repeat: false }]`.
*
* @param {(string|RegExp|Array)} path
* @param {(Array|Object)=} keys
* @param {Object=} options
* @return {!RegExp}
*/
function pathToRegexp (path, keys, options) {
if (!isarray(keys)) {
options = /** @type {!Object} */ (keys || options)
keys = []
}
options = options || {}
if (path instanceof RegExp) {
return regexpToRegexp(path, /** @type {!Array} */ (keys))
}
if (isarray(path)) {
return arrayToRegexp(/** @type {!Array} */ (path), /** @type {!Array} */ (keys), options)
}
return stringToRegexp(/** @type {string} */ (path), /** @type {!Array} */ (keys), options)
}
/***/ },
/* 13 */
/***/ function(module, exports) {
module.exports = Array.isArray || function (arr) {
return Object.prototype.toString.call(arr) == '[object Array]';
};
/***/ },
/* 14 */
/***/ function(module, exports) {
"use strict";
exports.__esModule = true;
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
// Simple cache - NEW cached items are added to cachedKeys array. When cache is
// full, oldest key is removed from array and item is removed from cache
var DEFAULT_OPTIONS = {
limit: 200
};
var MatcherCache = function () {
function MatcherCache() {
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
_classCallCheck(this, MatcherCache);
this.cache = {};
this.cachedKeys = [];
var mergedOptions = _extends({}, DEFAULT_OPTIONS, options);
this.options = mergedOptions;
}
MatcherCache.prototype.set = function set(key, value) {
// If t