Version 3.18.1
Show:

File: app/js/router.js

  1. /**
  2. Provides URL-based routing using HTML5 `pushState()` or the location hash.
  3. @module app
  4. @submodule router
  5. @since 3.4.0
  6. **/
  7. var HistoryHash = Y.HistoryHash,
  8. QS = Y.QueryString,
  9. YArray = Y.Array,
  10. YLang = Y.Lang,
  11. YObject = Y.Object,
  12. win = Y.config.win,
  13. // Holds all the active router instances. This supports the static
  14. // `dispatch()` method which causes all routers to dispatch.
  15. instances = [],
  16. // We have to queue up pushState calls to avoid race conditions, since the
  17. // popstate event doesn't actually provide any info on what URL it's
  18. // associated with.
  19. saveQueue = [],
  20. /**
  21. Fired when the router is ready to begin dispatching to route handlers.
  22. You shouldn't need to wait for this event unless you plan to implement some
  23. kind of custom dispatching logic. It's used internally in order to avoid
  24. dispatching to an initial route if a browser history change occurs first.
  25. @event ready
  26. @param {Boolean} dispatched `true` if routes have already been dispatched
  27. (most likely due to a history change).
  28. @fireOnce
  29. **/
  30. EVT_READY = 'ready';
  31. /**
  32. Provides URL-based routing using HTML5 `pushState()` or the location hash.
  33. This makes it easy to wire up route handlers for different application states
  34. while providing full back/forward navigation support and bookmarkable, shareable
  35. URLs.
  36. @class Router
  37. @param {Object} [config] Config properties.
  38. @param {Boolean} [config.html5] Overrides the default capability detection
  39. and forces this router to use (`true`) or not use (`false`) HTML5
  40. history.
  41. @param {String} [config.root=''] Root path from which all routes should be
  42. evaluated.
  43. @param {Array} [config.routes=[]] Array of route definition objects.
  44. @constructor
  45. @extends Base
  46. @since 3.4.0
  47. **/
  48. function Router() {
  49. Router.superclass.constructor.apply(this, arguments);
  50. }
  51. Y.Router = Y.extend(Router, Y.Base, {
  52. // -- Protected Properties -------------------------------------------------
  53. /**
  54. Whether or not `_dispatch()` has been called since this router was
  55. instantiated.
  56. @property _dispatched
  57. @type Boolean
  58. @default undefined
  59. @protected
  60. **/
  61. /**
  62. Whether or not we're currently in the process of dispatching to routes.
  63. @property _dispatching
  64. @type Boolean
  65. @default undefined
  66. @protected
  67. **/
  68. /**
  69. History event handle for the `history:change` or `hashchange` event
  70. subscription.
  71. @property _historyEvents
  72. @type EventHandle
  73. @protected
  74. **/
  75. /**
  76. Cached copy of the `html5` attribute for internal use.
  77. @property _html5
  78. @type Boolean
  79. @protected
  80. **/
  81. /**
  82. Map which holds the registered param handlers in the form:
  83. `name` -> RegExp | Function.
  84. @property _params
  85. @type Object
  86. @protected
  87. @since 3.12.0
  88. **/
  89. /**
  90. Whether or not the `ready` event has fired yet.
  91. @property _ready
  92. @type Boolean
  93. @default undefined
  94. @protected
  95. **/
  96. /**
  97. Regex used to break up a URL string around the URL's path.
  98. Subpattern captures:
  99. 1. Origin, everything before the URL's path-part.
  100. 2. The URL's path-part.
  101. 3. The URL's query.
  102. 4. The URL's hash fragment.
  103. @property _regexURL
  104. @type RegExp
  105. @protected
  106. @since 3.5.0
  107. **/
  108. _regexURL: /^((?:[^\/#?:]+:\/\/|\/\/)[^\/]*)?([^?#]*)(\?[^#]*)?(#.*)?$/,
  109. /**
  110. Regex used to match parameter placeholders in route paths.
  111. Subpattern captures:
  112. 1. Parameter prefix character. Either a `:` for subpath parameters that
  113. should only match a single level of a path, or `*` for splat parameters
  114. that should match any number of path levels.
  115. 2. Parameter name, if specified, otherwise it is a wildcard match.
  116. @property _regexPathParam
  117. @type RegExp
  118. @protected
  119. **/
  120. _regexPathParam: /([:*])([\w\-]+)?/g,
  121. /**
  122. Regex that matches and captures the query portion of a URL, minus the
  123. preceding `?` character, and discarding the hash portion of the URL if any.
  124. @property _regexUrlQuery
  125. @type RegExp
  126. @protected
  127. **/
  128. _regexUrlQuery: /\?([^#]*).*$/,
  129. /**
  130. Regex that matches everything before the path portion of a URL (the origin).
  131. This will be used to strip this part of the URL from a string when we
  132. only want the path.
  133. @property _regexUrlOrigin
  134. @type RegExp
  135. @protected
  136. **/
  137. _regexUrlOrigin: /^(?:[^\/#?:]+:\/\/|\/\/)[^\/]*/,
  138. /**
  139. Collection of registered routes.
  140. @property _routes
  141. @type Array
  142. @protected
  143. **/
  144. // -- Lifecycle Methods ----------------------------------------------------
  145. initializer: function (config) {
  146. var self = this;
  147. self._html5 = self.get('html5');
  148. self._params = {};
  149. self._routes = [];
  150. self._url = self._getURL();
  151. // Necessary because setters don't run on init.
  152. self._setRoutes(config && config.routes ? config.routes :
  153. self.get('routes'));
  154. // Set up a history instance or hashchange listener.
  155. if (self._html5) {
  156. self._history = new Y.HistoryHTML5({force: true});
  157. self._historyEvents =
  158. Y.after('history:change', self._afterHistoryChange, self);
  159. } else {
  160. self._historyEvents =
  161. Y.on('hashchange', self._afterHistoryChange, win, self);
  162. }
  163. // Fire a `ready` event once we're ready to route. We wait first for all
  164. // subclass initializers to finish, then for window.onload, and then an
  165. // additional 20ms to allow the browser to fire a useless initial
  166. // `popstate` event if it wants to (and Chrome always wants to).
  167. self.publish(EVT_READY, {
  168. defaultFn : self._defReadyFn,
  169. fireOnce : true,
  170. preventable: false
  171. });
  172. self.once('initializedChange', function () {
  173. Y.once('load', function () {
  174. setTimeout(function () {
  175. self.fire(EVT_READY, {dispatched: !!self._dispatched});
  176. }, 20);
  177. });
  178. });
  179. // Store this router in the collection of all active router instances.
  180. instances.push(this);
  181. },
  182. destructor: function () {
  183. var instanceIndex = YArray.indexOf(instances, this);
  184. // Remove this router from the collection of active router instances.
  185. if (instanceIndex > -1) {
  186. instances.splice(instanceIndex, 1);
  187. }
  188. if (this._historyEvents) {
  189. this._historyEvents.detach();
  190. }
  191. },
  192. // -- Public Methods -------------------------------------------------------
  193. /**
  194. Dispatches to the first route handler that matches the current URL, if any.
  195. If `dispatch()` is called before the `ready` event has fired, it will
  196. automatically wait for the `ready` event before dispatching. Otherwise it
  197. will dispatch immediately.
  198. @method dispatch
  199. @chainable
  200. **/
  201. dispatch: function () {
  202. this.once(EVT_READY, function () {
  203. var req, res;
  204. this._ready = true;
  205. if (!this.upgrade()) {
  206. req = this._getRequest('dispatch');
  207. res = this._getResponse(req);
  208. this._dispatch(req, res);
  209. }
  210. });
  211. return this;
  212. },
  213. /**
  214. Gets the current route path.
  215. @method getPath
  216. @return {String} Current route path.
  217. **/
  218. getPath: function () {
  219. return this._getPath();
  220. },
  221. /**
  222. Returns `true` if this router has at least one route that matches the
  223. specified URL, `false` otherwise. This also checks that any named `param`
  224. handlers also accept app param values in the `url`.
  225. This method enforces the same-origin security constraint on the specified
  226. `url`; any URL which is not from the same origin as the current URL will
  227. always return `false`.
  228. @method hasRoute
  229. @param {String} url URL to match.
  230. @return {Boolean} `true` if there's at least one matching route, `false`
  231. otherwise.
  232. **/
  233. hasRoute: function (url) {
  234. var path, routePath, routes;
  235. if (!this._hasSameOrigin(url)) {
  236. return false;
  237. }
  238. if (!this._html5) {
  239. url = this._upgradeURL(url);
  240. }
  241. // Get just the path portion of the specified `url`. The `match()`
  242. // method does some special checking that the `path` is within the root.
  243. path = this.removeQuery(url.replace(this._regexUrlOrigin, ''));
  244. routes = this.match(path);
  245. if (!routes.length) {
  246. return false;
  247. }
  248. routePath = this.removeRoot(path);
  249. // Check that there's at least one route whose param handlers also
  250. // accept all the param values.
  251. return !!YArray.filter(routes, function (route) {
  252. // Get the param values for the route and path to see whether the
  253. // param handlers accept or reject the param values. Include any
  254. // route whose named param handlers accept *all* param values. This
  255. // will return `false` if a param handler rejects a param value.
  256. return this._getParamValues(route, routePath);
  257. }, this).length;
  258. },
  259. /**
  260. Returns an array of route objects that match the specified URL path.
  261. If this router has a `root`, then the specified `path` _must_ be
  262. semantically within the `root` path to match any routes.
  263. This method is called internally to determine which routes match the current
  264. path whenever the URL changes. You may override it if you want to customize
  265. the route matching logic, although this usually shouldn't be necessary.
  266. Each returned route object has the following properties:
  267. * `callback`: A function or a string representing the name of a function
  268. this router that should be executed when the route is triggered.
  269. * `keys`: An array of strings representing the named parameters defined in
  270. the route's path specification, if any.
  271. * `path`: The route's path specification, which may be either a string or
  272. a regex.
  273. * `regex`: A regular expression version of the route's path specification.
  274. This regex is used to determine whether the route matches a given path.
  275. @example
  276. router.route('/foo', function () {});
  277. router.match('/foo');
  278. // => [{callback: ..., keys: [], path: '/foo', regex: ...}]
  279. @method match
  280. @param {String} path URL path to match. This should be an absolute path that
  281. starts with a slash: "/".
  282. @return {Object[]} Array of route objects that match the specified path.
  283. **/
  284. match: function (path) {
  285. var root = this.get('root');
  286. if (root) {
  287. // The `path` must be semantically within this router's `root` path
  288. // or mount point, if it's not then no routes should be considered a
  289. // match.
  290. if (!this._pathHasRoot(root, path)) {
  291. return [];
  292. }
  293. // Remove this router's `root` from the `path` before checking the
  294. // routes for any matches.
  295. path = this.removeRoot(path);
  296. }
  297. return YArray.filter(this._routes, function (route) {
  298. return path.search(route.regex) > -1;
  299. });
  300. },
  301. /**
  302. Adds a handler for a route param specified by _name_.
  303. Param handlers can be registered via this method and are used to
  304. validate/format values of named params in routes before dispatching to the
  305. route's handler functions. Using param handlers allows routes to defined
  306. using string paths which allows for `req.params` to use named params, but
  307. still applying extra validation or formatting to the param values parsed
  308. from the URL.
  309. If a param handler regex or function returns a value of `false`, `null`,
  310. `undefined`, or `NaN`, the current route will not match and be skipped. All
  311. other return values will be used in place of the original param value parsed
  312. from the URL.
  313. @example
  314. router.param('postId', function (value) {
  315. return parseInt(value, 10);
  316. });
  317. router.param('username', /^\w+$/);
  318. router.route('/posts/:postId', function (req) {
  319. Y.log('Post: ' + req.params.id);
  320. });
  321. router.route('/users/:username', function (req) {
  322. // `req.params.username` is an array because the result of calling
  323. // `exec()` on the regex is assigned as the param's value.
  324. Y.log('User: ' + req.params.username[0]);
  325. });
  326. router.route('*', function () {
  327. Y.log('Catch-all no routes matched!');
  328. });
  329. // URLs which match routes:
  330. router.save('/posts/1'); // => "Post: 1"
  331. router.save('/users/ericf'); // => "User: ericf"
  332. // URLs which do not match routes because params fail validation:
  333. router.save('/posts/a'); // => "Catch-all no routes matched!"
  334. router.save('/users/ericf,rgrove'); // => "Catch-all no routes matched!"
  335. @method param
  336. @param {String} name Name of the param used in route paths.
  337. @param {Function|RegExp} handler Function to invoke or regular expression to
  338. `exec()` during route dispatching whose return value is used as the new
  339. param value. Values of `false`, `null`, `undefined`, or `NaN` will cause
  340. the current route to not match and be skipped. When a function is
  341. specified, it will be invoked in the context of this instance with the
  342. following parameters:
  343. @param {String} handler.value The current param value parsed from the URL.
  344. @param {String} handler.name The name of the param.
  345. @chainable
  346. @since 3.12.0
  347. **/
  348. param: function (name, handler) {
  349. this._params[name] = handler;
  350. return this;
  351. },
  352. /**
  353. Removes the `root` URL from the front of _url_ (if it's there) and returns
  354. the result. The returned path will always have a leading `/`.
  355. @method removeRoot
  356. @param {String} url URL.
  357. @return {String} Rootless path.
  358. **/
  359. removeRoot: function (url) {
  360. var root = this.get('root'),
  361. path;
  362. // Strip out the non-path part of the URL, if any (e.g.
  363. // "http://foo.com"), so that we're left with just the path.
  364. url = url.replace(this._regexUrlOrigin, '');
  365. // Return the host-less URL if there's no `root` path to further remove.
  366. if (!root) {
  367. return url;
  368. }
  369. path = this.removeQuery(url);
  370. // Remove the `root` from the `url` if it's the same or its path is
  371. // semantically within the root path.
  372. if (path === root || this._pathHasRoot(root, path)) {
  373. url = url.substring(root.length);
  374. }
  375. return url.charAt(0) === '/' ? url : '/' + url;
  376. },
  377. /**
  378. Removes a query string from the end of the _url_ (if one exists) and returns
  379. the result.
  380. @method removeQuery
  381. @param {String} url URL.
  382. @return {String} Queryless path.
  383. **/
  384. removeQuery: function (url) {
  385. return url.replace(/\?.*$/, '');
  386. },
  387. /**
  388. Replaces the current browser history entry with a new one, and dispatches to
  389. the first matching route handler, if any.
  390. Behind the scenes, this method uses HTML5 `pushState()` in browsers that
  391. support it (or the location hash in older browsers and IE) to change the
  392. URL.
  393. The specified URL must share the same origin (i.e., protocol, host, and
  394. port) as the current page, or an error will occur.
  395. @example
  396. // Starting URL: http://example.com/
  397. router.replace('/path/');
  398. // New URL: http://example.com/path/
  399. router.replace('/path?foo=bar');
  400. // New URL: http://example.com/path?foo=bar
  401. router.replace('/');
  402. // New URL: http://example.com/
  403. @method replace
  404. @param {String} [url] URL to set. This URL needs to be of the same origin as
  405. the current URL. This can be a URL relative to the router's `root`
  406. attribute. If no URL is specified, the page's current URL will be used.
  407. @chainable
  408. @see save()
  409. **/
  410. replace: function (url) {
  411. return this._queue(url, true);
  412. },
  413. /**
  414. Adds a route handler for the specified `route`.
  415. The `route` parameter may be a string or regular expression to represent a
  416. URL path, or a route object. If it's a string (which is most common), it may
  417. contain named parameters: `:param` will match any single part of a URL path
  418. (not including `/` characters), and `*param` will match any number of parts
  419. of a URL path (including `/` characters). These named parameters will be
  420. made available as keys on the `req.params` object that's passed to route
  421. handlers.
  422. If the `route` parameter is a regex, all pattern matches will be made
  423. available as numbered keys on `req.params`, starting with `0` for the full
  424. match, then `1` for the first subpattern match, and so on.
  425. Alternatively, an object can be provided to represent the route and it may
  426. contain a `path` property which is a string or regular expression which
  427. causes the route to be process as described above. If the route object
  428. already contains a `regex` or `regexp` property, the route will be
  429. considered fully-processed and will be associated with any `callacks`
  430. specified on the object and those specified as parameters to this method.
  431. **Note:** Any additional data contained on the route object will be
  432. preserved.
  433. Here's a set of sample routes along with URL paths that they match:
  434. * Route: `/photos/:tag/:page`
  435. * URL: `/photos/kittens/1`, params: `{tag: 'kittens', page: '1'}`
  436. * URL: `/photos/puppies/2`, params: `{tag: 'puppies', page: '2'}`
  437. * Route: `/file/*path`
  438. * URL: `/file/foo/bar/baz.txt`, params: `{path: 'foo/bar/baz.txt'}`
  439. * URL: `/file/foo`, params: `{path: 'foo'}`
  440. **Middleware**: Routes also support an arbitrary number of callback
  441. functions. This allows you to easily reuse parts of your route-handling code
  442. with different route. This method is liberal in how it processes the
  443. specified `callbacks`, you can specify them as separate arguments, or as
  444. arrays, or both.
  445. If multiple route match a given URL, they will be executed in the order they
  446. were added. The first route that was added will be the first to be executed.
  447. **Passing Control**: Invoking the `next()` function within a route callback
  448. will pass control to the next callback function (if any) or route handler
  449. (if any). If a value is passed to `next()`, it's assumed to be an error,
  450. therefore stopping the dispatch chain, unless that value is: `"route"`,
  451. which is special case and dispatching will skip to the next route handler.
  452. This allows middleware to skip any remaining middleware for a particular
  453. route.
  454. @example
  455. router.route('/photos/:tag/:page', function (req, res, next) {
  456. Y.log('Current tag: ' + req.params.tag);
  457. Y.log('Current page number: ' + req.params.page);
  458. });
  459. // Using middleware.
  460. router.findUser = function (req, res, next) {
  461. req.user = this.get('users').findById(req.params.user);
  462. next();
  463. };
  464. router.route('/users/:user', 'findUser', function (req, res, next) {
  465. // The `findUser` middleware puts the `user` object on the `req`.
  466. Y.log('Current user:' req.user.get('name'));
  467. });
  468. @method route
  469. @param {String|RegExp|Object} route Route to match. May be a string or a
  470. regular expression, or a route object.
  471. @param {Array|Function|String} callbacks* Callback functions to call
  472. whenever this route is triggered. These can be specified as separate
  473. arguments, or in arrays, or both. If a callback is specified as a
  474. string, the named function will be called on this router instance.
  475. @param {Object} callbacks.req Request object containing information about
  476. the request. It contains the following properties.
  477. @param {Array|Object} callbacks.req.params Captured parameters matched
  478. by the route path specification. If a string path was used and
  479. contained named parameters, then this will be a key/value hash mapping
  480. parameter names to their matched values. If a regex path was used,
  481. this will be an array of subpattern matches starting at index 0 for
  482. the full match, then 1 for the first subpattern match, and so on.
  483. @param {String} callbacks.req.path The current URL path.
  484. @param {Number} callbacks.req.pendingCallbacks Number of remaining
  485. callbacks the route handler has after this one in the dispatch chain.
  486. @param {Number} callbacks.req.pendingRoutes Number of matching routes
  487. after this one in the dispatch chain.
  488. @param {Object} callbacks.req.query Query hash representing the URL
  489. query string, if any. Parameter names are keys, and are mapped to
  490. parameter values.
  491. @param {Object} callbacks.req.route Reference to the current route
  492. object whose callbacks are being dispatched.
  493. @param {Object} callbacks.req.router Reference to this router instance.
  494. @param {String} callbacks.req.src What initiated the dispatch. In an
  495. HTML5 browser, when the back/forward buttons are used, this property
  496. will have a value of "popstate". When the `dispath()` method is
  497. called, the `src` will be `"dispatch"`.
  498. @param {String} callbacks.req.url The full URL.
  499. @param {Object} callbacks.res Response object containing methods and
  500. information that relate to responding to a request. It contains the
  501. following properties.
  502. @param {Object} callbacks.res.req Reference to the request object.
  503. @param {Function} callbacks.next Function to pass control to the next
  504. callback or the next matching route if no more callbacks (middleware)
  505. exist for the current route handler. If you don't call this function,
  506. then no further callbacks or route handlers will be executed, even if
  507. there are more that match. If you do call this function, then the next
  508. callback (if any) or matching route handler (if any) will be called.
  509. All of these functions will receive the same `req` and `res` objects
  510. that were passed to this route (so you can use these objects to pass
  511. data along to subsequent callbacks and routes).
  512. @param {String} [callbacks.next.err] Optional error which will stop the
  513. dispatch chaining for this `req`, unless the value is `"route"`, which
  514. is special cased to jump skip past any callbacks for the current route
  515. and pass control the next route handler.
  516. @chainable
  517. **/
  518. route: function (route, callbacks) {
  519. // Grab callback functions from var-args.
  520. callbacks = YArray(arguments, 1, true);
  521. var keys, regex;
  522. // Supports both the `route(path, callbacks)` and `route(config)` call
  523. // signatures, allowing for fully-processed route configs to be passed.
  524. if (typeof route === 'string' || YLang.isRegExp(route)) {
  525. // Flatten `callbacks` into a single dimension array.
  526. callbacks = YArray.flatten(callbacks);
  527. keys = [];
  528. regex = this._getRegex(route, keys);
  529. route = {
  530. callbacks: callbacks,
  531. keys : keys,
  532. path : route,
  533. regex : regex
  534. };
  535. } else {
  536. // Look for any configured `route.callbacks` and fallback to
  537. // `route.callback` for back-compat, append var-arg `callbacks`,
  538. // then flatten the entire collection to a single dimension array.
  539. callbacks = YArray.flatten(
  540. [route.callbacks || route.callback || []].concat(callbacks)
  541. );
  542. // Check for previously generated regex, also fallback to `regexp`
  543. // for greater interop.
  544. keys = route.keys;
  545. regex = route.regex || route.regexp;
  546. // Generates the route's regex if it doesn't already have one.
  547. if (!regex) {
  548. keys = [];
  549. regex = this._getRegex(route.path, keys);
  550. }
  551. // Merge specified `route` config object with processed data.
  552. route = Y.merge(route, {
  553. callbacks: callbacks,
  554. keys : keys,
  555. path : route.path || regex,
  556. regex : regex
  557. });
  558. }
  559. this._routes.push(route);
  560. return this;
  561. },
  562. /**
  563. Saves a new browser history entry and dispatches to the first matching route
  564. handler, if any.
  565. Behind the scenes, this method uses HTML5 `pushState()` in browsers that
  566. support it (or the location hash in older browsers and IE) to change the
  567. URL and create a history entry.
  568. The specified URL must share the same origin (i.e., protocol, host, and
  569. port) as the current page, or an error will occur.
  570. @example
  571. // Starting URL: http://example.com/
  572. router.save('/path/');
  573. // New URL: http://example.com/path/
  574. router.save('/path?foo=bar');
  575. // New URL: http://example.com/path?foo=bar
  576. router.save('/');
  577. // New URL: http://example.com/
  578. @method save
  579. @param {String} [url] URL to set. This URL needs to be of the same origin as
  580. the current URL. This can be a URL relative to the router's `root`
  581. attribute. If no URL is specified, the page's current URL will be used.
  582. @chainable
  583. @see replace()
  584. **/
  585. save: function (url) {
  586. return this._queue(url);
  587. },
  588. /**
  589. Upgrades a hash-based URL to an HTML5 URL if necessary. In non-HTML5
  590. browsers, this method is a noop.
  591. @method upgrade
  592. @return {Boolean} `true` if the URL was upgraded, `false` otherwise.
  593. **/
  594. upgrade: function () {
  595. if (!this._html5) {
  596. return false;
  597. }
  598. // Get the resolve hash path.
  599. var hashPath = this._getHashPath();
  600. if (hashPath) {
  601. // This is an HTML5 browser and we have a hash-based path in the
  602. // URL, so we need to upgrade the URL to a non-hash URL. This
  603. // will trigger a `history:change` event, which will in turn
  604. // trigger a dispatch.
  605. this.once(EVT_READY, function () {
  606. this.replace(hashPath);
  607. });
  608. return true;
  609. }
  610. return false;
  611. },
  612. // -- Protected Methods ----------------------------------------------------
  613. /**
  614. Wrapper around `decodeURIComponent` that also converts `+` chars into
  615. spaces.
  616. @method _decode
  617. @param {String} string String to decode.
  618. @return {String} Decoded string.
  619. @protected
  620. **/
  621. _decode: function (string) {
  622. return decodeURIComponent(string.replace(/\+/g, ' '));
  623. },
  624. /**
  625. Shifts the topmost `_save()` call off the queue and executes it. Does
  626. nothing if the queue is empty.
  627. @method _dequeue
  628. @chainable
  629. @see _queue
  630. @protected
  631. **/
  632. _dequeue: function () {
  633. var self = this,
  634. fn;
  635. // If window.onload hasn't yet fired, wait until it has before
  636. // dequeueing. This will ensure that we don't call pushState() before an
  637. // initial popstate event has fired.
  638. if (!YUI.Env.windowLoaded) {
  639. Y.once('load', function () {
  640. self._dequeue();
  641. });
  642. return this;
  643. }
  644. fn = saveQueue.shift();
  645. return fn ? fn() : this;
  646. },
  647. /**
  648. Dispatches to the first route handler that matches the specified _path_.
  649. If called before the `ready` event has fired, the dispatch will be aborted.
  650. This ensures normalized behavior between Chrome (which fires a `popstate`
  651. event on every pageview) and other browsers (which do not).
  652. @method _dispatch
  653. @param {object} req Request object.
  654. @param {String} res Response object.
  655. @chainable
  656. @protected
  657. **/
  658. _dispatch: function (req, res) {
  659. var self = this,
  660. routes = self.match(req.path),
  661. callbacks = [],
  662. routePath, paramValues;
  663. self._dispatching = self._dispatched = true;
  664. if (!routes || !routes.length) {
  665. self._dispatching = false;
  666. return self;
  667. }
  668. routePath = self.removeRoot(req.path);
  669. function next(err) {
  670. var callback, name, route;
  671. if (err) {
  672. // Special case "route" to skip to the next route handler
  673. // avoiding any additional callbacks for the current route.
  674. if (err === 'route') {
  675. callbacks = [];
  676. next();
  677. } else {
  678. Y.error(err);
  679. }
  680. } else if ((callback = callbacks.shift())) {
  681. if (typeof callback === 'string') {
  682. name = callback;
  683. callback = self[name];
  684. if (!callback) {
  685. Y.error('Router: Callback not found: ' + name, null, 'router');
  686. }
  687. }
  688. // Allow access to the number of remaining callbacks for the
  689. // route.
  690. req.pendingCallbacks = callbacks.length;
  691. callback.call(self, req, res, next);
  692. } else if ((route = routes.shift())) {
  693. paramValues = self._getParamValues(route, routePath);
  694. if (!paramValues) {
  695. // Skip this route because one of the param handlers
  696. // rejected a param value in the `routePath`.
  697. next('route');
  698. return;
  699. }
  700. // Expose the processed param values.
  701. req.params = paramValues;
  702. // Allow access to current route and the number of remaining
  703. // routes for this request.
  704. req.route = route;
  705. req.pendingRoutes = routes.length;
  706. // Make a copy of this route's `callbacks` so the original array
  707. // is preserved.
  708. callbacks = route.callbacks.concat();
  709. // Execute this route's `callbacks`.
  710. next();
  711. }
  712. }
  713. next();
  714. self._dispatching = false;
  715. return self._dequeue();
  716. },
  717. /**
  718. Returns the resolved path from the hash fragment, or an empty string if the
  719. hash is not path-like.
  720. @method _getHashPath
  721. @param {String} [hash] Hash fragment to resolve into a path. By default this
  722. will be the hash from the current URL.
  723. @return {String} Current hash path, or an empty string if the hash is empty.
  724. @protected
  725. **/
  726. _getHashPath: function (hash) {
  727. hash || (hash = HistoryHash.getHash());
  728. // Make sure the `hash` is path-like.
  729. if (hash && hash.charAt(0) === '/') {
  730. return this._joinURL(hash);
  731. }
  732. return '';
  733. },
  734. /**
  735. Gets the location origin (i.e., protocol, host, and port) as a URL.
  736. @example
  737. http://example.com
  738. @method _getOrigin
  739. @return {String} Location origin (i.e., protocol, host, and port).
  740. @protected
  741. **/
  742. _getOrigin: function () {
  743. var location = Y.getLocation();
  744. return location.origin || (location.protocol + '//' + location.host);
  745. },
  746. /**
  747. Getter for the `params` attribute.
  748. @method _getParams
  749. @return {Object} Mapping of param handlers: `name` -> RegExp | Function.
  750. @protected
  751. @since 3.12.0
  752. **/
  753. _getParams: function () {
  754. return Y.merge(this._params);
  755. },
  756. /**
  757. Gets the param values for the specified `route` and `path`, suitable to use
  758. form `req.params`.
  759. **Note:** This method will return `false` if a named param handler rejects a
  760. param value.
  761. @method _getParamValues
  762. @param {Object} route The route to get param values for.
  763. @param {String} path The route path (root removed) that provides the param
  764. values.
  765. @return {Boolean|Array|Object} The collection of processed param values.
  766. Either a hash of `name` -> `value` for named params processed by this
  767. router's param handlers, or an array of matches for a route with unnamed
  768. params. If a named param handler rejects a value, then `false` will be
  769. returned.
  770. @protected
  771. @since 3.16.0
  772. **/
  773. _getParamValues: function (route, path) {
  774. var matches, paramsMatch, paramValues;
  775. // Decode each of the path params so that the any URL-encoded path
  776. // segments are decoded in the `req.params` object.
  777. matches = YArray.map(route.regex.exec(path) || [], function (match) {
  778. // Decode matches, or coerce `undefined` matches to an empty
  779. // string to match expectations of working with `req.params`
  780. // in the context of route dispatching, and normalize
  781. // browser differences in their handling of regex NPCGs:
  782. // https://github.com/yui/yui3/issues/1076
  783. return (match && this._decode(match)) || '';
  784. }, this);
  785. // Simply return the array of decoded values when the route does *not*
  786. // use named parameters.
  787. if (matches.length - 1 !== route.keys.length) {
  788. return matches;
  789. }
  790. // Remove the first "match" from the param values, because it's just the
  791. // `path` processed by the route's regex, and map the values to the keys
  792. // to create the name params collection.
  793. paramValues = YArray.hash(route.keys, matches.slice(1));
  794. // Pass each named param value to its handler, if there is one, for
  795. // validation/processing. If a param value is rejected by a handler,
  796. // then the params don't match and a falsy value is returned.
  797. paramsMatch = YArray.every(route.keys, function (name) {
  798. var paramHandler = this._params[name],
  799. value = paramValues[name];
  800. if (paramHandler && value && typeof value === 'string') {
  801. // Check if `paramHandler` is a RegExp, because this
  802. // is true in Android 2.3 and other browsers!
  803. // `typeof /.*/ === 'function'`
  804. value = YLang.isRegExp(paramHandler) ?
  805. paramHandler.exec(value) :
  806. paramHandler.call(this, value, name);
  807. if (value !== false && YLang.isValue(value)) {
  808. // Update the named param to the value from the handler.
  809. paramValues[name] = value;
  810. return true;
  811. }
  812. // Consider the param value as rejected by the handler.
  813. return false;
  814. }
  815. return true;
  816. }, this);
  817. if (paramsMatch) {
  818. return paramValues;
  819. }
  820. // Signal that a param value was rejected by a named param handler.
  821. return false;
  822. },
  823. /**
  824. Gets the current route path.
  825. @method _getPath
  826. @return {String} Current route path.
  827. @protected
  828. **/
  829. _getPath: function () {
  830. var path = (!this._html5 && this._getHashPath()) ||
  831. Y.getLocation().pathname;
  832. return this.removeQuery(path);
  833. },
  834. /**
  835. Returns the current path root after popping off the last path segment,
  836. making it useful for resolving other URL paths against.
  837. The path root will always begin and end with a '/'.
  838. @method _getPathRoot
  839. @return {String} The URL's path root.
  840. @protected
  841. @since 3.5.0
  842. **/
  843. _getPathRoot: function () {
  844. var slash = '/',
  845. path = Y.getLocation().pathname,
  846. segments;
  847. if (path.charAt(path.length - 1) === slash) {
  848. return path;
  849. }
  850. segments = path.split(slash);
  851. segments.pop();
  852. return segments.join(slash) + slash;
  853. },
  854. /**
  855. Gets the current route query string.
  856. @method _getQuery
  857. @return {String} Current route query string.
  858. @protected
  859. **/
  860. _getQuery: function () {
  861. var location = Y.getLocation(),
  862. hash, matches;
  863. if (this._html5) {
  864. return location.search.substring(1);
  865. }
  866. hash = HistoryHash.getHash();
  867. matches = hash.match(this._regexUrlQuery);
  868. return hash && matches ? matches[1] : location.search.substring(1);
  869. },
  870. /**
  871. Creates a regular expression from the given route specification. If _path_
  872. is already a regex, it will be returned unmodified.
  873. @method _getRegex
  874. @param {String|RegExp} path Route path specification.
  875. @param {Array} keys Array reference to which route parameter names will be
  876. added.
  877. @return {RegExp} Route regex.
  878. @protected
  879. **/
  880. _getRegex: function (path, keys) {
  881. if (YLang.isRegExp(path)) {
  882. return path;
  883. }
  884. // Special case for catchall paths.
  885. if (path === '*') {
  886. return (/.*/);
  887. }
  888. path = path.replace(this._regexPathParam, function (match, operator, key) {
  889. // Only `*` operators are supported for key-less matches to allowing
  890. // in-path wildcards like: '/foo/*'.
  891. if (!key) {
  892. return operator === '*' ? '.*' : match;
  893. }
  894. keys.push(key);
  895. return operator === '*' ? '(.*?)' : '([^/#?]+)';
  896. });
  897. return new RegExp('^' + path + '$');
  898. },
  899. /**
  900. Gets a request object that can be passed to a route handler.
  901. @method _getRequest
  902. @param {String} src What initiated the URL change and need for the request.
  903. @return {Object} Request object.
  904. @protected
  905. **/
  906. _getRequest: function (src) {
  907. return {
  908. path : this._getPath(),
  909. query : this._parseQuery(this._getQuery()),
  910. url : this._getURL(),
  911. router: this,
  912. src : src
  913. };
  914. },
  915. /**
  916. Gets a response object that can be passed to a route handler.
  917. @method _getResponse
  918. @param {Object} req Request object.
  919. @return {Object} Response Object.
  920. @protected
  921. **/
  922. _getResponse: function (req) {
  923. return {req: req};
  924. },
  925. /**
  926. Getter for the `routes` attribute.
  927. @method _getRoutes
  928. @return {Object[]} Array of route objects.
  929. @protected
  930. **/
  931. _getRoutes: function () {
  932. return this._routes.concat();
  933. },
  934. /**
  935. Gets the current full URL.
  936. @method _getURL
  937. @return {String} URL.
  938. @protected
  939. **/
  940. _getURL: function () {
  941. var url = Y.getLocation().toString();
  942. if (!this._html5) {
  943. url = this._upgradeURL(url);
  944. }
  945. return url;
  946. },
  947. /**
  948. Returns `true` when the specified `url` is from the same origin as the
  949. current URL; i.e., the protocol, host, and port of the URLs are the same.
  950. All host or path relative URLs are of the same origin. A scheme-relative URL
  951. is first prefixed with the current scheme before being evaluated.
  952. @method _hasSameOrigin
  953. @param {String} url URL to compare origin with the current URL.
  954. @return {Boolean} Whether the URL has the same origin of the current URL.
  955. @protected
  956. **/
  957. _hasSameOrigin: function (url) {
  958. var origin = ((url && url.match(this._regexUrlOrigin)) || [])[0];
  959. // Prepend current scheme to scheme-relative URLs.
  960. if (origin && origin.indexOf('//') === 0) {
  961. origin = Y.getLocation().protocol + origin;
  962. }
  963. return !origin || origin === this._getOrigin();
  964. },
  965. /**
  966. Joins the `root` URL to the specified _url_, normalizing leading/trailing
  967. `/` characters.
  968. @example
  969. router.set('root', '/foo');
  970. router._joinURL('bar'); // => '/foo/bar'
  971. router._joinURL('/bar'); // => '/foo/bar'
  972. router.set('root', '/foo/');
  973. router._joinURL('bar'); // => '/foo/bar'
  974. router._joinURL('/bar'); // => '/foo/bar'
  975. @method _joinURL
  976. @param {String} url URL to append to the `root` URL.
  977. @return {String} Joined URL.
  978. @protected
  979. **/
  980. _joinURL: function (url) {
  981. var root = this.get('root');
  982. // Causes `url` to _always_ begin with a "/".
  983. url = this.removeRoot(url);
  984. if (url.charAt(0) === '/') {
  985. url = url.substring(1);
  986. }
  987. return root && root.charAt(root.length - 1) === '/' ?
  988. root + url :
  989. root + '/' + url;
  990. },
  991. /**
  992. Returns a normalized path, ridding it of any '..' segments and properly
  993. handling leading and trailing slashes.
  994. @method _normalizePath
  995. @param {String} path URL path to normalize.
  996. @return {String} Normalized path.
  997. @protected
  998. @since 3.5.0
  999. **/
  1000. _normalizePath: function (path) {
  1001. var dots = '..',
  1002. slash = '/',
  1003. i, len, normalized, segments, segment, stack;
  1004. if (!path || path === slash) {
  1005. return slash;
  1006. }
  1007. segments = path.split(slash);
  1008. stack = [];
  1009. for (i = 0, len = segments.length; i < len; ++i) {
  1010. segment = segments[i];
  1011. if (segment === dots) {
  1012. stack.pop();
  1013. } else if (segment) {
  1014. stack.push(segment);
  1015. }
  1016. }
  1017. normalized = slash + stack.join(slash);
  1018. // Append trailing slash if necessary.
  1019. if (normalized !== slash && path.charAt(path.length - 1) === slash) {
  1020. normalized += slash;
  1021. }
  1022. return normalized;
  1023. },
  1024. /**
  1025. Parses a URL query string into a key/value hash. If `Y.QueryString.parse` is
  1026. available, this method will be an alias to that.
  1027. @method _parseQuery
  1028. @param {String} query Query string to parse.
  1029. @return {Object} Hash of key/value pairs for query parameters.
  1030. @protected
  1031. **/
  1032. _parseQuery: QS && QS.parse ? QS.parse : function (query) {
  1033. var decode = this._decode,
  1034. params = query.split('&'),
  1035. i = 0,
  1036. len = params.length,
  1037. result = {},
  1038. param;
  1039. for (; i < len; ++i) {
  1040. param = params[i].split('=');
  1041. if (param[0]) {
  1042. result[decode(param[0])] = decode(param[1] || '');
  1043. }
  1044. }
  1045. return result;
  1046. },
  1047. /**
  1048. Returns `true` when the specified `path` is semantically within the
  1049. specified `root` path.
  1050. If the `root` does not end with a trailing slash ("/"), one will be added
  1051. before the `path` is evaluated against the root path.
  1052. @example
  1053. this._pathHasRoot('/app', '/app/foo'); // => true
  1054. this._pathHasRoot('/app/', '/app/foo'); // => true
  1055. this._pathHasRoot('/app/', '/app/'); // => true
  1056. this._pathHasRoot('/app', '/foo/bar'); // => false
  1057. this._pathHasRoot('/app/', '/foo/bar'); // => false
  1058. this._pathHasRoot('/app/', '/app'); // => false
  1059. this._pathHasRoot('/app', '/app'); // => false
  1060. @method _pathHasRoot
  1061. @param {String} root Root path used to evaluate whether the specificed
  1062. `path` is semantically within. A trailing slash ("/") will be added if
  1063. it does not already end with one.
  1064. @param {String} path Path to evaluate for containing the specified `root`.
  1065. @return {Boolean} Whether or not the `path` is semantically within the
  1066. `root` path.
  1067. @protected
  1068. @since 3.13.0
  1069. **/
  1070. _pathHasRoot: function (root, path) {
  1071. var rootPath = root.charAt(root.length - 1) === '/' ? root : root + '/';
  1072. return path.indexOf(rootPath) === 0;
  1073. },
  1074. /**
  1075. Queues up a `_save()` call to run after all previously-queued calls have
  1076. finished.
  1077. This is necessary because if we make multiple `_save()` calls before the
  1078. first call gets dispatched, then both calls will dispatch to the last call's
  1079. URL.
  1080. All arguments passed to `_queue()` will be passed on to `_save()` when the
  1081. queued function is executed.
  1082. @method _queue
  1083. @chainable
  1084. @see _dequeue
  1085. @protected
  1086. **/
  1087. _queue: function () {
  1088. var args = arguments,
  1089. self = this;
  1090. saveQueue.push(function () {
  1091. if (self._html5) {
  1092. if (Y.UA.ios && Y.UA.ios < 5) {
  1093. // iOS <5 has buggy HTML5 history support, and needs to be
  1094. // synchronous.
  1095. self._save.apply(self, args);
  1096. } else {
  1097. // Wrapped in a timeout to ensure that _save() calls are
  1098. // always processed asynchronously. This ensures consistency
  1099. // between HTML5- and hash-based history.
  1100. setTimeout(function () {
  1101. self._save.apply(self, args);
  1102. }, 1);
  1103. }
  1104. } else {
  1105. self._dispatching = true; // otherwise we'll dequeue too quickly
  1106. self._save.apply(self, args);
  1107. }
  1108. return self;
  1109. });
  1110. return !this._dispatching ? this._dequeue() : this;
  1111. },
  1112. /**
  1113. Returns the normalized result of resolving the `path` against the current
  1114. path. Falsy values for `path` will return just the current path.
  1115. @method _resolvePath
  1116. @param {String} path URL path to resolve.
  1117. @return {String} Resolved path.
  1118. @protected
  1119. @since 3.5.0
  1120. **/
  1121. _resolvePath: function (path) {
  1122. if (!path) {
  1123. return Y.getLocation().pathname;
  1124. }
  1125. if (path.charAt(0) !== '/') {
  1126. path = this._getPathRoot() + path;
  1127. }
  1128. return this._normalizePath(path);
  1129. },
  1130. /**
  1131. Resolves the specified URL against the current URL.
  1132. This method resolves URLs like a browser does and will always return an
  1133. absolute URL. When the specified URL is already absolute, it is assumed to
  1134. be fully resolved and is simply returned as is. Scheme-relative URLs are
  1135. prefixed with the current protocol. Relative URLs are giving the current
  1136. URL's origin and are resolved and normalized against the current path root.
  1137. @method _resolveURL
  1138. @param {String} url URL to resolve.
  1139. @return {String} Resolved URL.
  1140. @protected
  1141. @since 3.5.0
  1142. **/
  1143. _resolveURL: function (url) {
  1144. var parts = url && url.match(this._regexURL),
  1145. origin, path, query, hash, resolved;
  1146. if (!parts) {
  1147. return Y.getLocation().toString();
  1148. }
  1149. origin = parts[1];
  1150. path = parts[2];
  1151. query = parts[3];
  1152. hash = parts[4];
  1153. // Absolute and scheme-relative URLs are assumed to be fully-resolved.
  1154. if (origin) {
  1155. // Prepend the current scheme for scheme-relative URLs.
  1156. if (origin.indexOf('//') === 0) {
  1157. origin = Y.getLocation().protocol + origin;
  1158. }
  1159. return origin + (path || '/') + (query || '') + (hash || '');
  1160. }
  1161. // Will default to the current origin and current path.
  1162. resolved = this._getOrigin() + this._resolvePath(path);
  1163. // A path or query for the specified URL trumps the current URL's.
  1164. if (path || query) {
  1165. return resolved + (query || '') + (hash || '');
  1166. }
  1167. query = this._getQuery();
  1168. return resolved + (query ? ('?' + query) : '') + (hash || '');
  1169. },
  1170. /**
  1171. Saves a history entry using either `pushState()` or the location hash.
  1172. This method enforces the same-origin security constraint; attempting to save
  1173. a `url` that is not from the same origin as the current URL will result in
  1174. an error.
  1175. @method _save
  1176. @param {String} [url] URL for the history entry.
  1177. @param {Boolean} [replace=false] If `true`, the current history entry will
  1178. be replaced instead of a new one being added.
  1179. @chainable
  1180. @protected
  1181. **/
  1182. _save: function (url, replace) {
  1183. var urlIsString = typeof url === 'string',
  1184. currentPath, root, hash;
  1185. // Perform same-origin check on the specified URL.
  1186. if (urlIsString && !this._hasSameOrigin(url)) {
  1187. Y.error('Security error: The new URL must be of the same origin as the current URL.');
  1188. return this;
  1189. }
  1190. // Joins the `url` with the `root`.
  1191. if (urlIsString) {
  1192. url = this._joinURL(url);
  1193. }
  1194. // Force _ready to true to ensure that the history change is handled
  1195. // even if _save is called before the `ready` event fires.
  1196. this._ready = true;
  1197. if (this._html5) {
  1198. this._history[replace ? 'replace' : 'add'](null, {url: url});
  1199. } else {
  1200. currentPath = Y.getLocation().pathname;
  1201. root = this.get('root');
  1202. hash = HistoryHash.getHash();
  1203. if (!urlIsString) {
  1204. url = hash;
  1205. }
  1206. // Determine if the `root` already exists in the current location's
  1207. // `pathname`, and if it does then we can exclude it from the
  1208. // hash-based path. No need to duplicate the info in the URL.
  1209. if (root === currentPath || root === this._getPathRoot()) {
  1210. url = this.removeRoot(url);
  1211. }
  1212. // The `hashchange` event only fires when the new hash is actually
  1213. // different. This makes sure we'll always dequeue and dispatch
  1214. // _all_ router instances, mimicking the HTML5 behavior.
  1215. if (url === hash) {
  1216. Y.Router.dispatch();
  1217. } else {
  1218. HistoryHash[replace ? 'replaceHash' : 'setHash'](url);
  1219. }
  1220. }
  1221. return this;
  1222. },
  1223. /**
  1224. Setter for the `params` attribute.
  1225. @method _setParams
  1226. @param {Object} params Map in the form: `name` -> RegExp | Function.
  1227. @return {Object} The map of params: `name` -> RegExp | Function.
  1228. @protected
  1229. @since 3.12.0
  1230. **/
  1231. _setParams: function (params) {
  1232. this._params = {};
  1233. YObject.each(params, function (regex, name) {
  1234. this.param(name, regex);
  1235. }, this);
  1236. return Y.merge(this._params);
  1237. },
  1238. /**
  1239. Setter for the `routes` attribute.
  1240. @method _setRoutes
  1241. @param {Object[]} routes Array of route objects.
  1242. @return {Object[]} Array of route objects.
  1243. @protected
  1244. **/
  1245. _setRoutes: function (routes) {
  1246. this._routes = [];
  1247. YArray.each(routes, function (route) {
  1248. this.route(route);
  1249. }, this);
  1250. return this._routes.concat();
  1251. },
  1252. /**
  1253. Upgrades a hash-based URL to a full-path URL, if necessary.
  1254. The specified `url` will be upgraded if its of the same origin as the
  1255. current URL and has a path-like hash. URLs that don't need upgrading will be
  1256. returned as-is.
  1257. @example
  1258. app._upgradeURL('http://example.com/#/foo/'); // => 'http://example.com/foo/';
  1259. @method _upgradeURL
  1260. @param {String} url The URL to upgrade from hash-based to full-path.
  1261. @return {String} The upgraded URL, or the specified URL untouched.
  1262. @protected
  1263. @since 3.5.0
  1264. **/
  1265. _upgradeURL: function (url) {
  1266. // We should not try to upgrade paths for external URLs.
  1267. if (!this._hasSameOrigin(url)) {
  1268. return url;
  1269. }
  1270. var hash = (url.match(/#(.*)$/) || [])[1] || '',
  1271. hashPrefix = Y.HistoryHash.hashPrefix,
  1272. hashPath;
  1273. // Strip any hash prefix, like hash-bangs.
  1274. if (hashPrefix && hash.indexOf(hashPrefix) === 0) {
  1275. hash = hash.replace(hashPrefix, '');
  1276. }
  1277. // If the hash looks like a URL path, assume it is, and upgrade it!
  1278. if (hash) {
  1279. hashPath = this._getHashPath(hash);
  1280. if (hashPath) {
  1281. return this._resolveURL(hashPath);
  1282. }
  1283. }
  1284. return url;
  1285. },
  1286. // -- Protected Event Handlers ---------------------------------------------
  1287. /**
  1288. Handles `history:change` and `hashchange` events.
  1289. @method _afterHistoryChange
  1290. @param {EventFacade} e
  1291. @protected
  1292. **/
  1293. _afterHistoryChange: function (e) {
  1294. var self = this,
  1295. src = e.src,
  1296. prevURL = self._url,
  1297. currentURL = self._getURL(),
  1298. req, res;
  1299. self._url = currentURL;
  1300. // Handles the awkwardness that is the `popstate` event. HTML5 browsers
  1301. // fire `popstate` right before they fire `hashchange`, and Chrome fires
  1302. // `popstate` on page load. If this router is not ready or the previous
  1303. // and current URLs only differ by their hash, then we want to ignore
  1304. // this `popstate` event.
  1305. if (src === 'popstate' &&
  1306. (!self._ready || prevURL.replace(/#.*$/, '') === currentURL.replace(/#.*$/, ''))) {
  1307. return;
  1308. }
  1309. req = self._getRequest(src);
  1310. res = self._getResponse(req);
  1311. self._dispatch(req, res);
  1312. },
  1313. // -- Default Event Handlers -----------------------------------------------
  1314. /**
  1315. Default handler for the `ready` event.
  1316. @method _defReadyFn
  1317. @param {EventFacade} e
  1318. @protected
  1319. **/
  1320. _defReadyFn: function (e) {
  1321. this._ready = true;
  1322. }
  1323. }, {
  1324. // -- Static Properties ----------------------------------------------------
  1325. NAME: 'router',
  1326. ATTRS: {
  1327. /**
  1328. Whether or not this browser is capable of using HTML5 history.
  1329. Setting this to `false` will force the use of hash-based history even on
  1330. HTML5 browsers, but please don't do this unless you understand the
  1331. consequences.
  1332. @attribute html5
  1333. @type Boolean
  1334. @initOnly
  1335. **/
  1336. html5: {
  1337. // Android versions lower than 3.0 are buggy and don't update
  1338. // window.location after a pushState() call, so we fall back to
  1339. // hash-based history for them.
  1340. //
  1341. // See http://code.google.com/p/android/issues/detail?id=17471
  1342. valueFn: function () { return Y.Router.html5; },
  1343. writeOnce: 'initOnly'
  1344. },
  1345. /**
  1346. Map of params handlers in the form: `name` -> RegExp | Function.
  1347. If a param handler regex or function returns a value of `false`, `null`,
  1348. `undefined`, or `NaN`, the current route will not match and be skipped.
  1349. All other return values will be used in place of the original param
  1350. value parsed from the URL.
  1351. This attribute is intended to be used to set params at init time, or to
  1352. completely reset all params after init. To add params after init without
  1353. resetting all existing params, use the `param()` method.
  1354. @attribute params
  1355. @type Object
  1356. @default `{}`
  1357. @see param
  1358. @since 3.12.0
  1359. **/
  1360. params: {
  1361. value : {},
  1362. getter: '_getParams',
  1363. setter: '_setParams'
  1364. },
  1365. /**
  1366. Absolute root path from which all routes should be evaluated.
  1367. For example, if your router is running on a page at
  1368. `http://example.com/myapp/` and you add a route with the path `/`, your
  1369. route will never execute, because the path will always be preceded by
  1370. `/myapp`. Setting `root` to `/myapp` would cause all routes to be
  1371. evaluated relative to that root URL, so the `/` route would then execute
  1372. when the user browses to `http://example.com/myapp/`.
  1373. @example
  1374. router.set('root', '/myapp');
  1375. router.route('/foo', function () { ... });
  1376. Y.log(router.hasRoute('/foo')); // => false
  1377. Y.log(router.hasRoute('/myapp/foo')); // => true
  1378. // Updates the URL to: "/myapp/foo"
  1379. router.save('/foo');
  1380. @attribute root
  1381. @type String
  1382. @default `''`
  1383. **/
  1384. root: {
  1385. value: ''
  1386. },
  1387. /**
  1388. Array of route objects.
  1389. Each item in the array must be an object with the following properties
  1390. in order to be processed by the router:
  1391. * `path`: String or regex representing the path to match. See the docs
  1392. for the `route()` method for more details.
  1393. * `callbacks`: Function or a string representing the name of a
  1394. function on this router instance that should be called when the
  1395. route is triggered. An array of functions and/or strings may also be
  1396. provided. See the docs for the `route()` method for more details.
  1397. If a route object contains a `regex` or `regexp` property, or if its
  1398. `path` is a regular express, then the route will be considered to be
  1399. fully-processed. Any fully-processed routes may contain the following
  1400. properties:
  1401. * `regex`: The regular expression representing the path to match, this
  1402. property may also be named `regexp` for greater compatibility.
  1403. * `keys`: Array of named path parameters used to populate `req.params`
  1404. objects when dispatching to route handlers.
  1405. Any additional data contained on these route objects will be retained.
  1406. This is useful to store extra metadata about a route; e.g., a `name` to
  1407. give routes logical names.
  1408. This attribute is intended to be used to set routes at init time, or to
  1409. completely reset all routes after init. To add routes after init without
  1410. resetting all existing routes, use the `route()` method.
  1411. @attribute routes
  1412. @type Object[]
  1413. @default `[]`
  1414. @see route
  1415. **/
  1416. routes: {
  1417. value : [],
  1418. getter: '_getRoutes',
  1419. setter: '_setRoutes'
  1420. }
  1421. },
  1422. // Used as the default value for the `html5` attribute, and for testing.
  1423. html5: Y.HistoryBase.html5 && (!Y.UA.android || Y.UA.android >= 3),
  1424. // To make this testable.
  1425. _instances: instances,
  1426. /**
  1427. Dispatches to the first route handler that matches the specified `path` for
  1428. all active router instances.
  1429. This provides a mechanism to cause all active router instances to dispatch
  1430. to their route handlers without needing to change the URL or fire the
  1431. `history:change` or `hashchange` event.
  1432. @method dispatch
  1433. @static
  1434. @since 3.6.0
  1435. **/
  1436. dispatch: function () {
  1437. var i, len, router, req, res;
  1438. for (i = 0, len = instances.length; i < len; i += 1) {
  1439. router = instances[i];
  1440. if (router) {
  1441. req = router._getRequest('dispatch');
  1442. res = router._getResponse(req);
  1443. router._dispatch(req, res);
  1444. }
  1445. }
  1446. }
  1447. });
  1448. /**
  1449. The `Controller` class was deprecated in YUI 3.5.0 and is now an alias for the
  1450. `Router` class. Use that class instead. This alias will be removed in a future
  1451. version of YUI.
  1452. @class Controller
  1453. @constructor
  1454. @extends Base
  1455. @deprecated Use `Router` instead.
  1456. @see Router
  1457. **/
  1458. Y.Controller = Y.Router;