API Docs for: 3.18.1
Show:

File: pjax/js/pjax-base.js

  1. /**
  2. `Y.Router` extension that provides the core plumbing for enhanced navigation
  3. implemented using the pjax technique (HTML5 pushState + Ajax).
  4.  
  5. @module pjax
  6. @submodule pjax-base
  7. @since 3.5.0
  8. **/
  9.  
  10. var win = Y.config.win,
  11.  
  12. // The CSS class name used to filter link clicks from only the links which
  13. // the pjax enhanced navigation should be used.
  14. CLASS_PJAX = Y.ClassNameManager.getClassName('pjax'),
  15.  
  16. /**
  17. Fired when navigating to a URL via Pjax.
  18.  
  19. When the `navigate()` method is called or a pjax link is clicked, this event
  20. will be fired if the browser supports HTML5 history _and_ the router has a
  21. route handler for the specified URL.
  22.  
  23. This is a useful event to listen to for adding a visual loading indicator
  24. while the route handlers are busy handling the URL change.
  25.  
  26. @event navigate
  27. @param {String} url The URL that the router will dispatch to its route
  28. handlers in order to fulfill the enhanced navigation "request".
  29. @param {Boolean} [force=false] Whether the enhanced navigation should occur
  30. even in browsers without HTML5 history.
  31. @param {String} [hash] The hash-fragment (including "#") of the `url`. This
  32. will be present when the `url` differs from the current URL only by its
  33. hash and `navigateOnHash` has been set to `true`.
  34. @param {Event} [originEvent] The event that caused the navigation. Usually
  35. this would be a click event from a "pjax" anchor element.
  36. @param {Boolean} [replace] Whether or not the current history entry will be
  37. replaced, or a new entry will be created. Will default to `true` if the
  38. specified `url` is the same as the current URL.
  39. @since 3.5.0
  40. **/
  41. EVT_NAVIGATE = 'navigate';
  42.  
  43. /**
  44. `Y.Router` extension that provides the core plumbing for enhanced navigation
  45. implemented using the pjax technique (HTML5 `pushState` + Ajax).
  46.  
  47. This makes it easy to enhance the navigation between the URLs of an application
  48. in HTML5 history capable browsers by delegating to the router to fulfill the
  49. "request" and seamlessly falling-back to using standard full-page reloads in
  50. older, less-capable browsers.
  51.  
  52. The `PjaxBase` class isn't useful on its own, but can be mixed into a
  53. `Router`-based class to add Pjax functionality to that Router. For a pre-made
  54. standalone Pjax router, see the `Pjax` class.
  55.  
  56. var MyRouter = Y.Base.create('myRouter', Y.Router, [Y.PjaxBase], {
  57. // ...
  58. });
  59.  
  60. @class PjaxBase
  61. @extensionfor Router
  62. @since 3.5.0
  63. **/
  64. function PjaxBase() {}
  65.  
  66. PjaxBase.prototype = {
  67. // -- Protected Properties -------------------------------------------------
  68.  
  69. /**
  70. Holds the delegated pjax-link click handler.
  71.  
  72. @property _pjaxEvents
  73. @type EventHandle
  74. @protected
  75. @since 3.5.0
  76. **/
  77.  
  78. // -- Lifecycle Methods ----------------------------------------------------
  79. initializer: function () {
  80. this.publish(EVT_NAVIGATE, {defaultFn: this._defNavigateFn});
  81.  
  82. // Pjax is all about progressively enhancing the navigation between
  83. // "pages", so by default we only want to handle and route link clicks
  84. // in HTML5 `pushState`-compatible browsers.
  85. if (this.get('html5')) {
  86. this._pjaxBindUI();
  87. }
  88. },
  89.  
  90. destructor: function () {
  91. if (this._pjaxEvents) {
  92. this._pjaxEvents.detach();
  93. }
  94. },
  95.  
  96. // -- Public Methods -------------------------------------------------------
  97.  
  98. /**
  99. Navigates to the specified URL if there is a route handler that matches. In
  100. browsers capable of using HTML5 history, the navigation will be enhanced by
  101. firing the `navigate` event and having the router handle the "request".
  102. Non-HTML5 browsers will navigate to the new URL via manipulation of
  103. `window.location`.
  104.  
  105. When there is a route handler for the specified URL and it is being
  106. navigated to, this method will return `true`, otherwise it will return
  107. `false`.
  108.  
  109. **Note:** The specified URL _must_ be of the same origin as the current URL,
  110. otherwise an error will be logged and navigation will not occur. This is
  111. intended as both a security constraint and a purposely imposed limitation as
  112. it does not make sense to tell the router to navigate to a URL on a
  113. different scheme, host, or port.
  114.  
  115. @method navigate
  116. @param {String} url The URL to navigate to. This must be of the same origin
  117. as the current URL.
  118. @param {Object} [options] Additional options to configure the navigation.
  119. These are mixed into the `navigate` event facade.
  120. @param {Boolean} [options.replace] Whether or not the current history
  121. entry will be replaced, or a new entry will be created. Will default
  122. to `true` if the specified `url` is the same as the current URL.
  123. @param {Boolean} [options.force=false] Whether the enhanced navigation
  124. should occur even in browsers without HTML5 history.
  125. @return {Boolean} `true` if the URL was navigated to, `false` otherwise.
  126. @since 3.5.0
  127. **/
  128. navigate: function (url, options) {
  129. // The `_navigate()` method expects fully-resolved URLs.
  130. url = this._resolveURL(url);
  131.  
  132. if (this._navigate(url, options)) {
  133. return true;
  134. }
  135.  
  136. if (!this._hasSameOrigin(url)) {
  137. Y.error('Security error: The new URL must be of the same origin as the current URL.');
  138. return false;
  139. }
  140.  
  141. if (this.get('allowFallThrough')) {
  142. // Send paths with the same origin but no matching routes to window.location if specified.
  143. win.location = url;
  144. return true;
  145. }
  146.  
  147. return false;
  148. },
  149.  
  150. // -- Protected Methods ----------------------------------------------------
  151.  
  152. /**
  153. Utility method to test whether a specified link/anchor node's `href` is of
  154. the same origin as the page's current location.
  155.  
  156. This normalize browser inconsistencies with how the `port` is reported for
  157. anchor elements (IE reports a value for the default port, e.g. "80").
  158.  
  159. @method _isLinkSameOrigin
  160. @param {Node} link The anchor element to test whether its `href` is of the
  161. same origin as the page's current location.
  162. @return {Boolean} Whether or not the link's `href` is of the same origin as
  163. the page's current location.
  164. @protected
  165. @since 3.6.0
  166. **/
  167. _isLinkSameOrigin: function (link) {
  168. var location = Y.getLocation(),
  169. protocol = location.protocol,
  170. hostname = location.hostname,
  171. port = parseInt(location.port, 10) || null,
  172. linkPort;
  173.  
  174. // Link must have the same `protocol` and `hostname` as the page's
  175. // currrent location.
  176. if (link.get('protocol') !== protocol ||
  177. link.get('hostname') !== hostname) {
  178.  
  179. return false;
  180. }
  181.  
  182. linkPort = parseInt(link.get('port'), 10) || null;
  183.  
  184. // Normalize ports. In most cases browsers use an empty string when the
  185. // port is the default port, but IE does weird things with anchor
  186. // elements, so to be sure, this will re-assign the default ports before
  187. // they are compared.
  188. if (protocol === 'http:') {
  189. port || (port = 80);
  190. linkPort || (linkPort = 80);
  191. } else if (protocol === 'https:') {
  192. port || (port = 443);
  193. linkPort || (linkPort = 443);
  194. }
  195.  
  196. // Finally, to be from the same origin, the link's `port` must match the
  197. // page's current `port`.
  198. return linkPort === port;
  199. },
  200.  
  201. /**
  202. Underlying implementation for `navigate()`.
  203.  
  204. @method _navigate
  205. @param {String} url The fully-resolved URL that the router should dispatch
  206. to its route handlers to fulfill the enhanced navigation "request", or use
  207. to update `window.location` in non-HTML5 history capable browsers.
  208. @param {Object} [options] Additional options to configure the navigation.
  209. These are mixed into the `navigate` event facade.
  210. @param {Boolean} [options.replace] Whether or not the current history
  211. entry will be replaced, or a new entry will be created. Will default
  212. to `true` if the specified `url` is the same as the current URL.
  213. @param {Boolean} [options.force=false] Whether the enhanced navigation
  214. should occur even in browsers without HTML5 history.
  215. @return {Boolean} `true` if the URL was navigated to, `false` otherwise.
  216. @protected
  217. @since 3.5.0
  218. **/
  219. _navigate: function (url, options) {
  220. url = this._upgradeURL(url);
  221.  
  222. // Navigation can only be enhanced if there is a route-handler.
  223. if (!this.hasRoute(url)) {
  224. return false;
  225. }
  226.  
  227. // Make a copy of `options` before modifying it.
  228. options = Y.merge(options, {url: url});
  229.  
  230. var currentURL = this._getURL(),
  231. hash, hashlessURL;
  232.  
  233. // Captures the `url`'s hash and returns a URL without that hash.
  234. hashlessURL = url.replace(/(#.*)$/, function (u, h, i) {
  235. hash = h;
  236. return u.substring(i);
  237. });
  238.  
  239. if (hash && hashlessURL === currentURL.replace(/#.*$/, '')) {
  240. // When the specified `url` and current URL only differ by the hash,
  241. // the browser should handle this in-page navigation normally.
  242. if (!this.get('navigateOnHash')) {
  243. return false;
  244. }
  245.  
  246. options.hash = hash;
  247. }
  248.  
  249. // When navigating to the same URL as the current URL, behave like a
  250. // browser and replace the history entry instead of creating a new one.
  251. 'replace' in options || (options.replace = url === currentURL);
  252.  
  253. // The `navigate` event will only fire and therefore enhance the
  254. // navigation to the new URL in HTML5 history enabled browsers or when
  255. // forced. Otherwise it will fallback to assigning or replacing the URL
  256. // on `window.location`.
  257. if (this.get('html5') || options.force) {
  258. this.fire(EVT_NAVIGATE, options);
  259. } else if (win) {
  260. if (options.replace) {
  261. win.location.replace(url);
  262. } else {
  263. win.location = url;
  264. }
  265. }
  266.  
  267. return true;
  268. },
  269.  
  270. /**
  271. Binds the delegation of link-click events that match the `linkSelector` to
  272. the `_onLinkClick()` handler.
  273.  
  274. By default this method will only be called if the browser is capable of
  275. using HTML5 history.
  276.  
  277. @method _pjaxBindUI
  278. @protected
  279. @since 3.5.0
  280. **/
  281. _pjaxBindUI: function () {
  282. // Only bind link if we haven't already.
  283. if (!this._pjaxEvents) {
  284. this._pjaxEvents = Y.one('body').delegate('click',
  285. this._onLinkClick, this.get('linkSelector'), this);
  286. }
  287. },
  288.  
  289. // -- Protected Event Handlers ---------------------------------------------
  290.  
  291. /**
  292. Default handler for the `navigate` event.
  293.  
  294. Adds a new history entry or replaces the current entry for the specified URL
  295. and will scroll the page to the top if configured to do so.
  296.  
  297. @method _defNavigateFn
  298. @param {EventFacade} e
  299. @protected
  300. @since 3.5.0
  301. **/
  302. _defNavigateFn: function (e) {
  303. this[e.replace ? 'replace' : 'save'](e.url);
  304.  
  305. if (win && this.get('scrollToTop')) {
  306. // Scroll to the top of the page. The timeout ensures that the
  307. // scroll happens after navigation begins, so that the current
  308. // scroll position will be restored if the user clicks the back
  309. // button.
  310. setTimeout(function () {
  311. win.scroll(0, 0);
  312. }, 1);
  313. }
  314. },
  315.  
  316. /**
  317. Handler for delegated link-click events which match the `linkSelector`.
  318.  
  319. This will attempt to enhance the navigation to the link element's `href` by
  320. passing the URL to the `_navigate()` method. When the navigation is being
  321. enhanced, the default action is prevented.
  322.  
  323. If the user clicks a link with the middle/right mouse buttons, or is holding
  324. down the Ctrl or Command keys, this method's behavior is not applied and
  325. allows the native behavior to occur. Similarly, if the router is not capable
  326. or handling the URL because no route-handlers match, the link click will
  327. behave natively.
  328.  
  329. @method _onLinkClick
  330. @param {EventFacade} e
  331. @protected
  332. @since 3.5.0
  333. **/
  334. _onLinkClick: function (e) {
  335. var link, url, navigated;
  336.  
  337. // Allow the native behavior on middle/right-click, or when Ctrl or
  338. // Command are pressed.
  339. if (e.button !== 1 || e.ctrlKey || e.metaKey) { return; }
  340.  
  341. link = e.currentTarget;
  342.  
  343. // Only allow anchor elements because we need access to its `protocol`,
  344. // `host`, and `href` attributes.
  345. if (link.get('tagName').toUpperCase() !== 'A') {
  346. Y.log('pjax link-click navigation requires an anchor element.', 'warn', 'PjaxBase');
  347. return;
  348. }
  349.  
  350. // Same origin check to prevent trying to navigate to URLs from other
  351. // sites or things like mailto links.
  352. if (!this._isLinkSameOrigin(link)) {
  353. return;
  354. }
  355.  
  356. // All browsers fully resolve an anchor's `href` property.
  357. url = link.get('href');
  358.  
  359. // Try and navigate to the URL via the router, and prevent the default
  360. // link-click action if we do.
  361. if (url) {
  362. navigated = this._navigate(url, {originEvent: e});
  363.  
  364. if (navigated) {
  365. e.preventDefault();
  366. }
  367. }
  368. }
  369. };
  370.  
  371. PjaxBase.ATTRS = {
  372. /**
  373. CSS selector string used to filter link click events so that only the links
  374. which match it will have the enhanced navigation behavior of Pjax applied.
  375.  
  376. When a link is clicked and that link matches this selector, Pjax will
  377. attempt to dispatch to any route handlers matching the link's `href` URL. If
  378. HTML5 history is not supported or if no route handlers match, the link click
  379. will be handled by the browser just like any old link.
  380.  
  381. @attribute linkSelector
  382. @type String|Function
  383. @default "a.yui3-pjax"
  384. @initOnly
  385. @since 3.5.0
  386. **/
  387. linkSelector: {
  388. value : 'a.' + CLASS_PJAX,
  389. writeOnce: 'initOnly'
  390. },
  391.  
  392. /**
  393. Whether navigating to a hash-fragment identifier on the current page should
  394. be enhanced and cause the `navigate` event to fire.
  395.  
  396. By default Pjax allows the browser to perform its default action when a user
  397. is navigating within a page by clicking in-page links
  398. (e.g. `<a href="#top">Top of page</a>`) and does not attempt to interfere or
  399. enhance in-page navigation.
  400.  
  401. @attribute navigateOnHash
  402. @type Boolean
  403. @default false
  404. @since 3.5.0
  405. **/
  406. navigateOnHash: {
  407. value: false
  408. },
  409.  
  410. /**
  411. Whether the page should be scrolled to the top after navigating to a URL.
  412.  
  413. When the user clicks the browser's back button, the previous scroll position
  414. will be maintained.
  415.  
  416. @attribute scrollToTop
  417. @type Boolean
  418. @default true
  419. @since 3.5.0
  420. **/
  421. scrollToTop: {
  422. value: true
  423. },
  424.  
  425. /**
  426. Whether to set `window.location` when calling `navigate()`
  427. if no routes match the specified URL.
  428.  
  429. @attribute allowFallThrough
  430. @type Boolean
  431. @default true
  432. @since 3.18.0
  433. **/
  434. allowFallThrough: {
  435. value: true
  436. }
  437. };
  438.  
  439. Y.PjaxBase = PjaxBase;