Compare commits
84 Commits
0.2.4
...
feature/ya
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5bbeb31ca6 | ||
|
|
f639a8eae1 | ||
|
|
e49d8947f7 | ||
|
|
7d26a75fdf | ||
|
|
358b6f6836 | ||
|
|
d3447a95aa | ||
|
|
d6bf21ed22 | ||
|
|
17d8262025 | ||
|
|
75eb83dbc2 | ||
|
|
5e41a32cf4 | ||
|
|
a2982cfcba | ||
|
|
2166866967 | ||
|
|
c1e5bf9c78 | ||
|
|
333ee344f4 | ||
|
|
05fa833169 | ||
|
|
f98f2dd63b | ||
|
|
07baae8e4d | ||
|
|
0c7af354fd | ||
|
|
2d210c3305 | ||
|
|
a72880d205 | ||
|
|
57aed828ac | ||
|
|
63bc2af226 | ||
|
|
20e987929e | ||
|
|
90d26d641c | ||
|
|
93c0a5bb9b | ||
|
|
8718da35c6 | ||
|
|
31e1e7e405 | ||
|
|
05163d9fb5 | ||
|
|
a15c94c55a | ||
|
|
2d4df39f72 | ||
|
|
fa05e94f07 | ||
|
|
e3df2b1c3d | ||
|
|
01fb72ceeb | ||
|
|
f642eec047 | ||
|
|
cc384b9b16 | ||
|
|
f559ca2914 | ||
|
|
137322543c | ||
|
|
f7f68b2e50 | ||
|
|
ff62289683 | ||
|
|
3205596f3e | ||
|
|
3c8cd087c5 | ||
|
|
12f3be21fb | ||
|
|
b74fbc4178 | ||
|
|
8fcef04c9e | ||
|
|
feb85382f2 | ||
|
|
f196604d73 | ||
|
|
526a0883a2 | ||
|
|
486ef0e0ba | ||
|
|
6000ad5620 | ||
|
|
9845244948 | ||
|
|
e7935d9c74 | ||
|
|
e4b3952589 | ||
|
|
546b9abba3 | ||
|
|
bc2432b18c | ||
|
|
37d303ed66 | ||
|
|
b5c2120d08 | ||
|
|
ca61c4a840 | ||
|
|
cd09cc88d1 | ||
|
|
b98e3ef914 | ||
|
|
36ed7079b1 | ||
|
|
6fa51e58f8 | ||
|
|
cb9c37fcb3 | ||
|
|
92d5e09494 | ||
|
|
3bd101bb1d | ||
|
|
c0d64e41b8 | ||
|
|
e586440964 | ||
|
|
a2e6cfc0af | ||
|
|
6491e32437 | ||
|
|
d3d5ef7a11 | ||
|
|
0916c74171 | ||
|
|
0781f820ee | ||
|
|
a7b584c469 | ||
|
|
be5d58d550 | ||
|
|
1e40a0d70b | ||
|
|
75eddfcab6 | ||
|
|
352e7114b6 | ||
|
|
af57adaafb | ||
|
|
09f14fc86c | ||
|
|
b17457f5a2 | ||
|
|
86e5a2281a | ||
|
|
109e78347f | ||
|
|
cb3b6b8a5d | ||
|
|
6dffeba21a | ||
|
|
acdd87ef3d |
2
.gitignore
vendored
2
.gitignore
vendored
@@ -2,3 +2,5 @@
|
|||||||
node_modules/
|
node_modules/
|
||||||
tests/scripts/index.html
|
tests/scripts/index.html
|
||||||
pjax.js
|
pjax.js
|
||||||
|
.nyc_output/
|
||||||
|
pjax.min.js
|
||||||
|
|||||||
6
.jscsrc
6
.jscsrc
@@ -1,6 +1,8 @@
|
|||||||
{
|
{
|
||||||
"excludeFiles": [
|
"excludeFiles": [
|
||||||
"node_modules/**"
|
"node_modules/**",
|
||||||
|
"pjax.js",
|
||||||
|
"pjax.min.js"
|
||||||
],
|
],
|
||||||
"fileExtensions": [
|
"fileExtensions": [
|
||||||
".js"
|
".js"
|
||||||
@@ -121,7 +123,7 @@
|
|||||||
"requireCapitalizedConstructors": true,
|
"requireCapitalizedConstructors": true,
|
||||||
"safeContextKeyword": "that",
|
"safeContextKeyword": "that",
|
||||||
"requireDotNotation": true,
|
"requireDotNotation": true,
|
||||||
"validateJSDoc": {
|
"jsDoc": {
|
||||||
"checkParamNames": true,
|
"checkParamNames": true,
|
||||||
"checkRedundantParams": true,
|
"checkRedundantParams": true,
|
||||||
"requireParamTypes": true
|
"requireParamTypes": true
|
||||||
|
|||||||
12
.travis.yml
12
.travis.yml
@@ -1,7 +1,7 @@
|
|||||||
language: "node_js"
|
language: "node_js"
|
||||||
before_script:
|
node_js:
|
||||||
# testling use headless browser
|
- "6"
|
||||||
# on travis-ci, firefox is the default one
|
- "8"
|
||||||
# & it needs a display to works
|
# Force Travis to use npm v5
|
||||||
- export DISPLAY=:99.0
|
# https://github.com/travis-ci/travis-ci/issues/4653#issuecomment-194051953
|
||||||
- sh -e /etc/init.d/xvfb start
|
before_install: if [[ `npm -v` != 5* ]]; then npm i -g npm@5; fi
|
||||||
|
|||||||
59
CHANGELOG.md
59
CHANGELOG.md
@@ -1,3 +1,62 @@
|
|||||||
|
# 0.2.6 - 2018-04-30
|
||||||
|
|
||||||
|
- Fixed: Form submission for GET requests.
|
||||||
|
([#129](https://github.com/MoOx/pjax/pull/129) - @robinnorth)
|
||||||
|
- Fixed: Refactor `loadUrl()` to make manually calling simpler.
|
||||||
|
([#134](https://github.com/MoOx/pjax/pull/134) - @robinnorth)
|
||||||
|
- Fixed: Support multiple select fields in form submissions.
|
||||||
|
([#147](https://github.com/MoOx/pjax/pull/147) - @robinnorth)
|
||||||
|
- Fixed: Use the same options object in `handle-response` as in `send-request`. This way, `pjax.state.options` will also have the request options.
|
||||||
|
([#148](https://github.com/MoOx/pjax/pull/148) - @BehindTheMath)
|
||||||
|
- Added: Move the XHR callback to a separate method, and trigger an error event if the response cannot be parsed.
|
||||||
|
([#137](https://github.com/MoOx/pjax/pull/137) - @BehindTheMath)
|
||||||
|
- Added: TypeScript definitions.
|
||||||
|
([#138](https://github.com/MoOx/pjax/pull/138) - @BehindTheMath)
|
||||||
|
- Added: `replaceNode` switch, as an alternative to the `outerHTML` switch.
|
||||||
|
([#141](https://github.com/MoOx/pjax/pull/141) - @BehindTheMath)
|
||||||
|
- Added: `X-PJAX-Selectors` HTTP header. This is a serialized JSON array of selectors, taken from `options.selectors`. You can use this to send back only the elements that Pjax will use to switch, instead of sending the whole page.
|
||||||
|
([#144](https://github.com/MoOx/pjax/pull/144) - @BehindTheMath)
|
||||||
|
- Added: An option to use `FormData` to submit forms.
|
||||||
|
([#153](https://github.com/MoOx/pjax/pull/153) - @BehindTheMath)
|
||||||
|
- Added: Tests.
|
||||||
|
([f98f2dd](https://github.com/MoOx/pjax/commit/f98f2dd63b48113ff91b6bd8808257bfc723ef6b), [#145](https://github.com/MoOx/pjax/pull/145) - @robinnorth, @BehindTheMath)
|
||||||
|
|
||||||
|
# 0.2.5 - 2018-02-02
|
||||||
|
|
||||||
|
- Fixed: Async switch functions now work correctly, because the DOM is now parsed after all the switches finish.
|
||||||
|
([#79](https://github.com/MoOx/pjax/pull/79), [#110](https://github.com/MoOx/pjax/pull/110) - @oskarrough, @BehindTheMath, @robinnorth)
|
||||||
|
- Fixed: Bug on IE11 preventing AJAX page refresh.
|
||||||
|
([#81](https://github.com/MoOx/pjax/pull/81) - @CPTechnikVX)
|
||||||
|
- Fixed: Default switches are now available as `Pjax.switches`.
|
||||||
|
([#92](https://github.com/MoOx/pjax/pull/92) - @BehindTheMath)
|
||||||
|
- Fixed: An error that was caused by a missing `switchElementsAlt`.
|
||||||
|
([#93](https://github.com/MoOx/pjax/pull/93), [#104](https://github.com/MoOx/pjax/pull/104) - @BehindTheMath, @robinnorth)
|
||||||
|
- Fixed: Incorrect `main` field in npm package
|
||||||
|
([#105](https://github.com/MoOx/pjax/pull/105) - @robinnorth)
|
||||||
|
- Fixed: A pending XHR is now aborted if the user navigates somewhere else before the request is finished.
|
||||||
|
([#114](https://github.com/MoOx/pjax/pull/114) - @robinnorth)
|
||||||
|
- Fixed: When rendering new content, focus will now be removed only from elements within one of the containers manipulated by Pjax.
|
||||||
|
([#116](https://github.com/MoOx/pjax/pull/116) - @BehindTheMath)
|
||||||
|
- Fixed: Stop dispatching extraneous `pjax:complete` events when external scripts load
|
||||||
|
([#118](https://github.com/MoOx/pjax/pull/118) - @robinnorth)
|
||||||
|
- Added: Send the `X-PJAX` header with XHR requests.
|
||||||
|
([#80](https://github.com/MoOx/pjax/pull/80) - @bram1028)
|
||||||
|
- Added: Direct download link for script tags. (@MoOx)
|
||||||
|
- Added: Pass the element that triggered Pjax to the `pjax:send` event.
|
||||||
|
([#94](https://github.com/MoOx/pjax/pull/94) - @BehindTheMath)
|
||||||
|
- Added: An option to set a timeout for XHR requests.
|
||||||
|
([#95](https://github.com/MoOx/pjax/pull/95) - @BehindTheMath)
|
||||||
|
- Added: Checks for XHR redirects
|
||||||
|
([#101](https://github.com/MoOx/pjax/pull/101) - @BehindTheMath)
|
||||||
|
- Added: Save scroll position with history, and restore when navigating backwards or forwards.
|
||||||
|
([#110](https://github.com/MoOx/pjax/pull/110), [#119](https://github.com/MoOx/pjax/pull/119) - @BehindTheMath, @robinnorth)
|
||||||
|
- Added: Scroll to element position when URL contains a hash
|
||||||
|
([#110](https://github.com/MoOx/pjax/pull/110) - @BehindTheMath)
|
||||||
|
- Added: Minified version of the Pjax bundle.
|
||||||
|
([#115](https://github.com/MoOx/pjax/pull/115) - @BehindTheMath)
|
||||||
|
- Changed: Miscellaneous code and tests cleanup.
|
||||||
|
([#96](https://github.com/MoOx/pjax/pull/96), [#98](https://github.com/MoOx/pjax/pull/98), [#99](https://github.com/MoOx/pjax/pull/99), [#100](https://github.com/MoOx/pjax/pull/1070), [#107](https://github.com/MoOx/pjax/pull/107), [#113](https://github.com/MoOx/pjax/pull/113), [#120](https://github.com/MoOx/pjax/pull/120) - @BehindTheMath, @MoOx, @robinnorth)
|
||||||
|
|
||||||
# 0.2.4 - 2016-06-28
|
# 0.2.4 - 2016-06-28
|
||||||
|
|
||||||
- Fixed: ``refresh`` should now work (use `this.parseDOM` for refresh)
|
- Fixed: ``refresh`` should now work (use `this.parseDOM` for refresh)
|
||||||
|
|||||||
395
README.md
395
README.md
@@ -1,62 +1,77 @@
|
|||||||
# Pjax
|
# Pjax
|
||||||
|
|
||||||
[](https://travis-ci.org/MoOx/pjax) [@todo fix CI](https://github.com/MoOx/pjax/issues/63).
|
[](https://travis-ci.org/MoOx/pjax).
|
||||||
|
|
||||||
> Easily enable fast Ajax navigation on any website (using pushState + xhr)
|
> Easily enable fast AJAX navigation on any website (using pushState() + XHR)
|
||||||
|
|
||||||
Pjax is ~~a jQuery plugin~~ **a standalone JavaScript module** that uses
|
Pjax is **a standalone JavaScript module** that uses
|
||||||
ajax (XmlHttpRequest) and
|
AJAX (XmlHttpRequest) and
|
||||||
[pushState()](https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history)
|
[pushState()](https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history)
|
||||||
to deliver a fast browsing experience.
|
to deliver a fast browsing experience.
|
||||||
|
|
||||||
_It allow you to completely transform user experience of standard websites
|
_It allows you to completely transform the user experience of standard websites
|
||||||
(server side generated or static ones) to make them feel they browse an app.
|
(server-side generated or static ones) to make them feel like they are browsing an app,
|
||||||
Especially for user that have low bandwidth connection._
|
especially for users with low bandwidth connection._
|
||||||
|
|
||||||
**No more full page reload. No more lots of HTTP request.**
|
**No more full page reloads. No more multiple HTTP requests.**
|
||||||
|
|
||||||
|
_Pjax does not rely on other libraries, like jQuery or similar. It is written entirely in vanilla JS._
|
||||||
|
|
||||||
## Demo
|
## Installation
|
||||||
|
|
||||||
[You can see this running on my website](http://moox.io), with sexy CSS animations when switching pages.
|
- You can install Pjax from **npm**:
|
||||||
|
```shell
|
||||||
|
npm install pjax
|
||||||
|
```
|
||||||
|
|
||||||
|
- You can also link directly to the [bundle](https://cdn.jsdelivr.net/npm/pjax/pjax.js):
|
||||||
|
```html
|
||||||
|
<script src="https://cdn.jsdelivr.net/npm/pjax@VERSION/pjax.js"></script>
|
||||||
|
```
|
||||||
|
Or the [minified bundle](https://cdn.jsdelivr.net/npm/pjax/pjax.min.js):
|
||||||
|
```html
|
||||||
|
<script src="https://cdn.jsdelivr.net/npm/pjax@VERSION/pjax.min.js"></script>
|
||||||
|
```
|
||||||
|
|
||||||
## How Pjax works
|
## How Pjax works
|
||||||
|
|
||||||
Pjax loads page using ajax & updates the browser's current url using pushState without reloading your page's layout or any resources (js, css), giving a fast page load.
|
Pjax loads pages using AJAX and updates the browser's current URL using `pushState()` without reloading your page's layout or any resources (JS, CSS), giving a fast page load.
|
||||||
_But under the hood, it's just ONE http request with a pushState() call._
|
|
||||||
Obviously, for [browsers that don't support pushState()](http://caniuse.com/#search=pushstate) Pjax fully degrades (yeah, it doesn't do anything at all).
|
|
||||||
|
|
||||||
It simply works with all permalinks & can update all parts of the page you
|
_But under the hood, it's just ONE HTTP request with a `pushState()` call._
|
||||||
want (including html metas, title, navigation state).
|
|
||||||
|
|
||||||
- It's not limited to one container, like jQuery-Pjax is,
|
Obviously, for [browsers that don't support `history.pushState()`](http://caniuse.com/#search=pushstate) Pjax gracefully degrades and does not do anything at all.
|
||||||
- It fully support browser history (back & forward buttons),
|
|
||||||
- It **will** support keyboard browsing (@todo),
|
It simply works with all permalinks and can update all parts of the page you
|
||||||
- Automatically fallback to classic navigation for externals pages (thanks to Capitain Obvious help),
|
want (including HTML metas, title, and navigation state).
|
||||||
- Automatically fallback to classic navigation for internals pages that will not have the appropriated DOM tree,
|
|
||||||
|
- It's not limited to one container, like jQuery-Pjax is.
|
||||||
|
- It fully supports browser history (back and forward buttons).
|
||||||
|
- It supports keyboard browsing.
|
||||||
|
- Automatically falls back to standard navigation for external pages (thanks to Captain Obvious's help).
|
||||||
|
- Automatically falls back to standard navigation for internal pages that do not have an appropriate DOM tree.
|
||||||
- You can add pretty cool CSS transitions (animations) very easily.
|
- You can add pretty cool CSS transitions (animations) very easily.
|
||||||
- It's around 3kb (minified & gzipped).
|
- It's around 4kb (minified and gzipped).
|
||||||
|
|
||||||
### Under the hood
|
### Under the hood
|
||||||
|
|
||||||
- It listen to every clicks on links _you want_ (by default all of them),
|
- It listens to every click on links _you want_ (by default all of them).
|
||||||
- When an internal link is clicked, Pjax grabs HTML from your server via ajax,
|
- When an internal link is clicked, Pjax grabs HTML from your server via AJAX.
|
||||||
- Pjax render pages DOM tree (without loading any resources - images, css, js...)
|
- Pjax renders the page's DOM tree (without loading any resources - images, CSS, JS...).
|
||||||
- It check if all defined parts can be replaced:
|
- It checks that all defined parts can be replaced:
|
||||||
- if page doesn't suit requirement, classic navigation used,
|
- If the page doesn't meet the requirements, standard navigation is used.
|
||||||
- if page suits requirement, Pjax does all defined DOM replacements
|
- If the page meets the requirements, Pjax does all defined DOM replacements.
|
||||||
- Then, it updates the browser's current url using pushState
|
- Then it updates the browser's current URL using `pushState()`.
|
||||||
|
|
||||||
## Overview
|
## Overview
|
||||||
|
|
||||||
Pjax is fully automatic. You won't need to setup anything on the existing HTML.
|
Pjax is fully automatic. You don't need to setup anything in the existing HTML.
|
||||||
You just need to designate some elements on your page that will be replaced when
|
You just need to designate some elements on your page that will be replaced when
|
||||||
you navigate your site.
|
you navigate your site.
|
||||||
|
|
||||||
Consider the following page.
|
Consider the following page.
|
||||||
|
|
||||||
```html
|
```html
|
||||||
<!doctype html>
|
<!DOCTYPE html>
|
||||||
<html>
|
<html>
|
||||||
<head>
|
<head>
|
||||||
<!-- metas, title, styles, ... -->
|
<!-- metas, title, styles, ... -->
|
||||||
@@ -74,7 +89,7 @@ Consider the following page.
|
|||||||
</html>
|
</html>
|
||||||
```
|
```
|
||||||
|
|
||||||
We want Pjax to grab the url `/blah` then replace `.my-Content` with whatever it gets back.
|
We want Pjax to intercept the URL `/blah`, and replace `.my-Content` with the results of the request.
|
||||||
Oh and the `<nav>` (that contains a status marker somewhere) can be updated too (or stay the same, as you wish).
|
Oh and the `<nav>` (that contains a status marker somewhere) can be updated too (or stay the same, as you wish).
|
||||||
And also the `<aside>` please.
|
And also the `<aside>` please.
|
||||||
So we want to update `[".my-Header", ".my-Content", ".my-Sidebar"]`, **without reloading styles nor scripts**.
|
So we want to update `[".my-Header", ".my-Content", ".my-Sidebar"]`, **without reloading styles nor scripts**.
|
||||||
@@ -82,73 +97,57 @@ So we want to update `[".my-Header", ".my-Content", ".my-Sidebar"]`, **without r
|
|||||||
We do this by telling Pjax to listen on `a` tags and use CSS selectors defined above (without forgetting minimal meta):
|
We do this by telling Pjax to listen on `a` tags and use CSS selectors defined above (without forgetting minimal meta):
|
||||||
|
|
||||||
``` javascript
|
``` javascript
|
||||||
new Pjax({ selectors: ["title", ".my-Header", ".my-Content", ".my-Sidebar"] })
|
var pjax = new Pjax({ selectors: ["title", ".my-Header", ".my-Content", ".my-Sidebar"] })
|
||||||
```
|
```
|
||||||
|
|
||||||
Now when someone in a Pjax-compatible browser clicks "blah" the content of all selectors will be replaced with the one found in the "blah" content.
|
Now, when someone in a Pjax-compatible browser clicks "blah", the content of all selectors will be replaced with the one found in the "blah" content.
|
||||||
|
|
||||||
_Magic! For real!_ **There is completely no need to do anything on server side!**
|
_Magic! For real!_ **There is no need to do anything server-side!**
|
||||||
|
|
||||||
## Differences with [jQuery-pjax](https://github.com/defunkt/jquery-pjax)
|
## Differences with [jQuery-pjax](https://github.com/defunkt/jquery-pjax)
|
||||||
|
|
||||||
- No jQuery dependency,
|
- No jQuery dependency
|
||||||
- Not limited to a container,
|
- Not limited to a container
|
||||||
- No server side requirements,
|
- No server-side requirements
|
||||||
- Works for CommonJS environment (browserify), AMD (RequireJS) or even globally,
|
- Works for CommonJS environment (Webpack/Browserify), AMD (RequireJS) or even globally
|
||||||
- Allow page transition with CSS animations,
|
- Allow page transition with CSS animations
|
||||||
- Can be easily hacked since every method is public (so overridable)
|
- Can be easily tweaked, since every method is public (and as a result, overridable)
|
||||||
|
|
||||||
## Installation
|
|
||||||
|
|
||||||
You can install pjax from **npm**
|
|
||||||
|
|
||||||
```shell
|
|
||||||
$ npm install pjax
|
|
||||||
```
|
|
||||||
|
|
||||||
Or using **bower**
|
|
||||||
|
|
||||||
```shell
|
|
||||||
$ bower install pjax
|
|
||||||
```
|
|
||||||
|
|
||||||
Pjax can obviously be downloaded directly.
|
|
||||||
|
|
||||||
## No dependencies
|
|
||||||
|
|
||||||
_There is nothing you need. No jQuery or something._
|
|
||||||
|
|
||||||
## Compatibility
|
## Compatibility
|
||||||
|
|
||||||
Pjax only works with [browsers that support the `history.pushState` API](http://caniuse.com/#search=pushstate).
|
Pjax only works with [browsers that support the `history.pushState()` API](http://caniuse.com/#search=pushstate).
|
||||||
When the API isn't supported Pjax goes into fallback mode (it just does nothing).
|
When the API isn't supported, Pjax goes into fallback mode (and it just does nothing).
|
||||||
|
|
||||||
To see if Pjax is actually supported by your browser, use `Pjax.isSupported()`.
|
To see if Pjax is actually supported by your browser, use `Pjax.isSupported()`.
|
||||||
|
|
||||||
## Usage
|
## Usage
|
||||||
|
|
||||||
### `new Pjax()`
|
### Methods
|
||||||
|
|
||||||
Let's talk more about the most basic way to get started:
|
#### `new Pjax()`
|
||||||
|
|
||||||
|
Let's talk more about the most basic way to get started.
|
||||||
|
|
||||||
|
When instantiating `Pjax`, you can pass options in to the constructor as an object:
|
||||||
|
|
||||||
```js
|
```js
|
||||||
new Pjax({
|
var pjax = new Pjax({
|
||||||
elements: "a", // default is "a[href], form[action]"
|
elements: "a", // default is "a[href], form[action]"
|
||||||
selectors: ["title", ".my-Header", ".my-Content", ".my-Sidebar"]
|
selectors: ["title", ".my-Header", ".my-Content", ".my-Sidebar"]
|
||||||
})
|
})
|
||||||
```
|
```
|
||||||
|
|
||||||
This will enable Pjax on all links and designate the part to replace using CSS selectors `"title", ".my-Header", ".my-Content", ".my-Sidebar"`.
|
This will enable Pjax on all links, and designate the part to replace using CSS selectors `"title", ".my-Header", ".my-Content", ".my-Sidebar"`.
|
||||||
|
|
||||||
For some reason, you might want to just target some elements to apply Pjax behavior.
|
For some reason, you might want to just target some elements to apply Pjax behavior.
|
||||||
In that case, you can 2 differents things:
|
In that case, you can do two different things:
|
||||||
|
|
||||||
- use a custom selector like "a.js-Pjax" or ".js-Pjax a" depending on what you want.
|
- Use a custom selector like "a.js-Pjax" or ".js-Pjax a" depending on what you want.
|
||||||
- override `Pjax.prototype.getElements` that just basically `querSelectorAll` the `elements` option. In this function you just need to return a `NodeList`.
|
- Override `Pjax.prototype.getElements` that just basically `querySelectorAll` the `elements` option. In this function you just need to return a `NodeList`.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
// use case 1
|
// use case 1
|
||||||
new Pjax({ elements: "a.js-Pjax" })
|
var pjax = new Pjax({ elements: "a.js-Pjax" })
|
||||||
|
|
||||||
|
|
||||||
// use case 2
|
// use case 2
|
||||||
@@ -156,20 +155,60 @@ Pjax.prototype.getElements = function() {
|
|||||||
return document.getElementsByClassName(".js-Pjax")
|
return document.getElementsByClassName(".js-Pjax")
|
||||||
}
|
}
|
||||||
|
|
||||||
new Pjax({})
|
var pjax = new Pjax()
|
||||||
```
|
```
|
||||||
|
|
||||||
When instanciating a `Pjax` object, you need to pass all options as an object:
|
#### `loadUrl(href, [options])`
|
||||||
|
|
||||||
#### Options
|
With this method, you can manually trigger loading of a URL:
|
||||||
|
|
||||||
##### `elements` (String, default "a[href], form[action]")
|
```js
|
||||||
|
var pjax = new Pjax()
|
||||||
|
|
||||||
CSS Selector to use to retrieve links to apply Pjax
|
// use case 1 (without options override)
|
||||||
|
pjax.loadUrl("/your-url")
|
||||||
|
|
||||||
##### `selectors` (Array, default ["title", ".js-Pjax"])
|
// use case 2 (with options override)
|
||||||
|
pjax.loadUrl("/your-other-url", {timeout: 10})
|
||||||
|
```
|
||||||
|
|
||||||
CSS Selectors to replace. If a query returns multiples items, it will just keep the index.
|
#### `handleResponse(responseText, request, href)`
|
||||||
|
|
||||||
|
This method takes the raw response, processes the URL, then calls `pjax.loadContent()` to actually load it into the DOM.
|
||||||
|
|
||||||
|
It is passed the following arguments:
|
||||||
|
|
||||||
|
* **responseText** (string): This is the raw response text. This is equivalent to `request.responseText`.
|
||||||
|
* **request** (XMLHttpRequest): This is the XHR object.
|
||||||
|
* **href** (string): This is the URL that was passed to `loadUrl()`.
|
||||||
|
|
||||||
|
You can override this if you want to process the data before, or instead of, it being loaded into the DOM.
|
||||||
|
|
||||||
|
For example, if you want to check for a JSON response, you could do the following:
|
||||||
|
|
||||||
|
```js
|
||||||
|
var pjax = new Pjax();
|
||||||
|
|
||||||
|
pjax._handleResponse = pjax.handleResponse;
|
||||||
|
|
||||||
|
pjax.handleResponse = function(responseText, request, href) {
|
||||||
|
if (request.responseText.match("<html")) {
|
||||||
|
pjax._handleResponse(responseText, request, href);
|
||||||
|
} else {
|
||||||
|
// handle response here
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Options
|
||||||
|
|
||||||
|
##### `elements` (String, default: `"a[href], form[action]"`)
|
||||||
|
|
||||||
|
CSS selector to use to retrieve links to apply Pjax to.
|
||||||
|
|
||||||
|
##### `selectors` (Array, default: `["title", ".js-Pjax"]`)
|
||||||
|
|
||||||
|
CSS selectors to replace. If a query returns multiples items, it will just keep the index.
|
||||||
|
|
||||||
Example of what you can do:
|
Example of what you can do:
|
||||||
|
|
||||||
@@ -189,18 +228,18 @@ Example of what you can do:
|
|||||||
```
|
```
|
||||||
|
|
||||||
This example is correct and should work "as expected".
|
This example is correct and should work "as expected".
|
||||||
_If there is not the same amount of DOM element from current page and new page,
|
_If the current page and new page do not have the same amount of DOM elements,
|
||||||
the Pjax behavior will fallback to normal page load._
|
Pjax will fall back to normal page load._
|
||||||
|
|
||||||
##### `switches` (Object, default {})
|
##### `switches` (Object, default: `{}`)
|
||||||
|
|
||||||
Objects containing callbacks that can be used to switch old element with new element.
|
Objects containing callbacks that can be used to switch old elements with new elements.
|
||||||
Keys should be one of the defined selector.
|
Keys should be one of the defined selectors.
|
||||||
|
|
||||||
Examples:
|
Examples:
|
||||||
|
|
||||||
```js
|
```js
|
||||||
new Pjax({
|
var pjax = new Pjax({
|
||||||
selectors: ["title", ".Navbar", ".js-Pjax"],
|
selectors: ["title", ".Navbar", ".js-Pjax"],
|
||||||
switches: {
|
switches: {
|
||||||
// "title": Pjax.switches.outerHTML // default behavior
|
// "title": Pjax.switches.outerHTML // default behavior
|
||||||
@@ -215,22 +254,23 @@ new Pjax({
|
|||||||
})
|
})
|
||||||
```
|
```
|
||||||
|
|
||||||
Callbacks are binded to Pjax instance itself to allow you to reuse it (ex: `this.onSwitch()`)
|
Callbacks are bound to Pjax instance itself to allow you to reuse it (ex: `this.onSwitch()`)
|
||||||
|
|
||||||
###### Existing switches callback
|
###### Existing switches callback
|
||||||
|
|
||||||
- `Pjax.switches.outerHTML`: default behavior, replace elements using outerHTML
|
- `Pjax.switches.outerHTML`: default behavior, replace elements using outerHTML
|
||||||
- `Pjax.switches.innerHTML`: replace elements using innerHTML & copy className too
|
- `Pjax.switches.innerHTML`: replace elements using innerHTML and copy className too
|
||||||
- `Pjax.switches.sideBySide`: smart replacement that allow you to have both elements in the same parent when you want to use CSS animations. Old elements are removed when all childs have been fully animated ([animationEnd](http://www.w3.org/TR/css3-animations/#animationend) event triggered)
|
- `Pjax.switches.replaceNode`: replace elements using replaceChild
|
||||||
|
- `Pjax.switches.sideBySide`: smart replacement that allows you to have both elements in the same parent when you want to use CSS animations. Old elements are removed when all children have been fully animated ([animationEnd](http://www.w3.org/TR/css3-animations/#animationend) event triggered)
|
||||||
|
|
||||||
###### Create a switch callback
|
###### Create a switch callback
|
||||||
|
|
||||||
Your function can do whatever you want, but you need to:
|
Your function can do whatever you want, but you need to:
|
||||||
|
|
||||||
- replace oldEl content by newEl content in some fashion
|
- replace `oldEl`'s content with `newEl`'s content in some fashion
|
||||||
- call `this.onSwitch()` to trigger attached callback.
|
- call `this.onSwitch()` to trigger the attached callback.
|
||||||
|
|
||||||
Here is the default behavior as example
|
Here is the default behavior as an example:
|
||||||
|
|
||||||
```js
|
```js
|
||||||
function(oldEl, newEl, pjaxRequestOptions, switchesClasses) {
|
function(oldEl, newEl, pjaxRequestOptions, switchesClasses) {
|
||||||
@@ -239,14 +279,14 @@ function(oldEl, newEl, pjaxRequestOptions, switchesClasses) {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
##### `switchesOptions` (Object, default {})
|
##### `switchesOptions` (Object, default: `{}`)
|
||||||
|
|
||||||
This are options that can be used during switch by switchers ( for now, only `Pjax.switches.sideBySide` use it).
|
These are options that can be used during switch by switchers (for now, only `Pjax.switches.sideBySide` uses it).
|
||||||
Very convenient when you use something like [Animate.css](https://github.com/daneden/animate.css)
|
This is very convenient when you use something like [Animate.css](https://github.com/daneden/animate.css)
|
||||||
with or without [WOW.js](https://github.com/matthieua/WOW).
|
with or without [WOW.js](https://github.com/matthieua/WOW).
|
||||||
|
|
||||||
```js
|
```js
|
||||||
new Pjax({
|
var pjax = new Pjax({
|
||||||
selectors: ["title", ".js-Pjax"],
|
selectors: ["title", ".js-Pjax"],
|
||||||
switches: {
|
switches: {
|
||||||
".js-Pjax": Pjax.switches.sideBySide
|
".js-Pjax": Pjax.switches.sideBySide
|
||||||
@@ -279,7 +319,7 @@ new Pjax({
|
|||||||
_Note that remove class include `Animated--reverse` which is a simple way to not have
|
_Note that remove class include `Animated--reverse` which is a simple way to not have
|
||||||
to create duplicate transition for (slideIn + reverse => slideOut)._
|
to create duplicate transition for (slideIn + reverse => slideOut)._
|
||||||
|
|
||||||
The following CSS will be required to make something nice
|
The following CSS will be required to make something nice:
|
||||||
|
|
||||||
```css
|
```css
|
||||||
/*
|
/*
|
||||||
@@ -337,8 +377,7 @@ The following CSS will be required to make something nice
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
To get understand this CSS, here is a HTML snippet
|
To give context to this CSS, here is an HTML snippet:
|
||||||
|
|
||||||
|
|
||||||
```html
|
```html
|
||||||
<!doctype html>
|
<!doctype html>
|
||||||
@@ -366,92 +405,167 @@ To get understand this CSS, here is a HTML snippet
|
|||||||
</html>
|
</html>
|
||||||
```
|
```
|
||||||
|
|
||||||
##### `history` (Boolean, default true)
|
##### `history` (Boolean, default: `true`)
|
||||||
|
|
||||||
Enable pushState. Only disable if you are crazy.
|
Enable the use of `pushState()`. Disabling this will prevent Pjax from updating browser history.
|
||||||
Internaly, this option is used when `popstate` is used (to not pushState again).
|
However, there is almost no use case where you would want to do that.
|
||||||
You should forget that option.
|
|
||||||
|
|
||||||
##### `analytics` (Function, default to a function that push `_gaq` `trackPageview` or send `ga` `pageview`
|
Internally, this option is used when a `popstate` event triggers Pjax (to not `pushState()` again).
|
||||||
|
|
||||||
Function that allow you to add behavior for analytics. By default it try to track
|
##### `analytics` (Function | Boolean, default: a function that pushes `_gaq` `_trackPageview` or sends `ga` `pageview`
|
||||||
a pageview with Google Analytics.
|
|
||||||
It's called every time a page is switched, even for history buttons.
|
|
||||||
|
|
||||||
##### `scrollTo` (Integer, default to 0)
|
Function that allows you to add behavior for analytics. By default it tries to track
|
||||||
|
a pageview with Google Analytics (if it exists on the page).
|
||||||
|
It's called every time a page is switched, even for history navigation.
|
||||||
|
|
||||||
Value (in px) to scrollTo when a page is switched.
|
Set to `false` to disable this behavior.
|
||||||
|
|
||||||
##### `cacheBust` (Boolean, default true)
|
##### `scrollTo` (Integer | \[Integer, Integer\] | False, default: `0`)
|
||||||
|
|
||||||
When set to true,
|
When set to an integer, this is the value (in px from the top of the page) to scroll to when a page is switched.
|
||||||
append a timestamp query string segment to the requested URLs
|
|
||||||
|
When set to an array of 2 integers (\[x, y\]), this is the value to scroll both horizontally and vertically.
|
||||||
|
|
||||||
|
Set this to `false` to disable scrolling, which will mean the page will stay in that same position it was before loading the new elements.
|
||||||
|
|
||||||
|
##### `scrollRestoration` (Boolean, default: `true`)
|
||||||
|
|
||||||
|
When set to true, attempt to restore the scroll position when navigating backwards or forwards.
|
||||||
|
|
||||||
|
##### `cacheBust` (Boolean, default: `true`)
|
||||||
|
|
||||||
|
When set to true, append a timestamp query string segment to the requested URLs
|
||||||
in order to skip browser cache.
|
in order to skip browser cache.
|
||||||
|
|
||||||
##### `debug` (Boolean, default to false)
|
##### `debug` (Boolean, default: `false`)
|
||||||
|
|
||||||
Enable verbose mode & doesn't use fallback when there is an error.
|
Enables verbose mode. Useful to debug page layout differences.
|
||||||
Useful to debug page layout differences.
|
|
||||||
|
|
||||||
##### `currentUrlFullReload` (Boolean, default to false)
|
##### `currentUrlFullReload` (Boolean, default: `false`)
|
||||||
|
|
||||||
When set to true, clicking on a link that point the current url trigger a full page reload.
|
When set to true, clicking on a link that points to the current URL will trigger a full page reload.
|
||||||
|
|
||||||
|
When set to `false`, clicking on such a link will cause Pjax to load the
|
||||||
|
current page like any page.
|
||||||
|
If you want to add some custom behavior, add a click listener to the link,
|
||||||
|
and set `preventDefault` to true, to prevent Pjax from receiving the event.
|
||||||
|
|
||||||
|
Note: this must be done before Pjax is instantiated. Otherwise, Pjax's
|
||||||
|
event handler will be called first, and preventDefault() won't be called yet.
|
||||||
|
|
||||||
|
Here is some sample code:
|
||||||
|
|
||||||
|
```js
|
||||||
|
var links = document.querySelectorAll(".js-Pjax");
|
||||||
|
|
||||||
|
for (var i = 0; i < links.length; i++) {
|
||||||
|
var el = links[i]
|
||||||
|
|
||||||
|
el.addEventListener("click", function(e) {
|
||||||
|
if (el.href === window.location.href.split("#")[0]) {
|
||||||
|
e.preventDefault();
|
||||||
|
console.log("Link to current page clicked");
|
||||||
|
// Custom code goes here.
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
var pjax = new Pjax()
|
||||||
|
```
|
||||||
|
|
||||||
|
(Note that if `cacheBust` is set to true, the code that checks if the href
|
||||||
|
is the same as the current page's URL will not work, due to the query string
|
||||||
|
appended to force a cache bust).
|
||||||
|
|
||||||
|
##### `timeout` (Integer, default: `0`)
|
||||||
|
|
||||||
|
The timeout in milliseconds for the XHR requests. Set to 0 to disable the timeout.
|
||||||
|
|
||||||
### Events
|
### Events
|
||||||
|
|
||||||
Pjax fires a number of events regardless of how its invoked.
|
Pjax fires a number of events regardless of how it's invoked.
|
||||||
|
|
||||||
All events are fired from the _document_, not the link was clicked.
|
All events are fired from the _document_, not the link that was clicked.
|
||||||
|
|
||||||
#### Ajax related events
|
|
||||||
|
|
||||||
* `pjax:send` - Fired after the Pjax request begins.
|
* `pjax:send` - Fired after the Pjax request begins.
|
||||||
* `pjax:complete` - Fired after the Pjax request finishes.
|
* `pjax:complete` - Fired after the Pjax request finishes.
|
||||||
* `pjax:success` - Fired after the Pjax request succeeds.
|
* `pjax:success` - Fired after the Pjax request succeeds.
|
||||||
* `pjax:error` - Fired after the Pjax request fails. Returning false will prevent the the fallback redirect.
|
* `pjax:error` - Fired after the Pjax request fails. The request object will be passed along as `event.options.request`.
|
||||||
|
|
||||||
`send` and `complete` are a good pair of events to use if you are implementing a loading indicator (eg: [topbar](http://buunguyen.github.io/topbar/))
|
`send` and `complete` are a good pair of events to use if you are implementing a loading indicator (eg: [topbar](http://buunguyen.github.io/topbar/))
|
||||||
|
|
||||||
```js
|
```js
|
||||||
$(document).on('pjax:send', topbar.show)
|
document.addEventListener('pjax:send', topbar.show)
|
||||||
$(document).on('pjax:complete', topbar.hide)
|
document.addEventListener('pjax:complete', topbar.hide)
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### HTTP Headers
|
||||||
|
|
||||||
|
Pjax uses several custom headers when it makes and receives HTTP requests.
|
||||||
|
If the requests are going to your server, you can use those headers for
|
||||||
|
some meta information about the response.
|
||||||
|
|
||||||
|
##### Request headers
|
||||||
|
|
||||||
|
Pjax sends the following headers with every request:
|
||||||
|
|
||||||
|
* `X-Requested-With: "XMLHttpRequest"`
|
||||||
|
* `X-PJAX: "true"`
|
||||||
|
* `X-PJAX-Selectors`: A serialized JSON array of selectors, taken from
|
||||||
|
`options.selectors`. You can use this to send back only the elements that
|
||||||
|
Pjax will use to switch, instead of sending the whole page. Use `JSON.parse()`
|
||||||
|
server-side to deserialize it back to an array.
|
||||||
|
|
||||||
|
##### Response headers
|
||||||
|
|
||||||
|
Pjax looks for the following headers on the response:
|
||||||
|
|
||||||
|
* `X-PJAX-URL` or `X-XHR-Redirected-To`
|
||||||
|
|
||||||
|
Pjax first checks the `responseURL` property on the XHR object to
|
||||||
|
check if the request was redirected by the server. Most browsers support
|
||||||
|
this, but not all. To ensure Pjax will be able to tell when the request
|
||||||
|
is redirected, you can include one of these headers with the response,
|
||||||
|
set to the final URL.
|
||||||
|
|
||||||
|
|
||||||
#### Note about DOM ready state
|
#### Note about DOM ready state
|
||||||
|
|
||||||
Most of the time, you have code attached & related to the current DOM, that you only execute when page/dom is ready.
|
Most of the time, you will have code related to the current DOM that you only execute when the DOM is ready.
|
||||||
Since Pjax doesn't magically rexecute you previous code each time you load a page, you need to make a simple thing to rexecute appropriate code:
|
|
||||||
|
Since Pjax doesn't magically re-execute your previous code each time you load a page, you need to add some simple code to achieve this:
|
||||||
|
|
||||||
```js
|
```js
|
||||||
function whenDOMReady() {
|
function whenDOMReady() {
|
||||||
// do you stuff
|
// do your stuff
|
||||||
}
|
}
|
||||||
|
|
||||||
whenDOMReady()
|
whenDOMReady()
|
||||||
|
|
||||||
new Pjax()
|
var pjax = new Pjax()
|
||||||
|
|
||||||
document.addEventListener("pjax:success", whenDOMReady)
|
document.addEventListener("pjax:success", whenDOMReady)
|
||||||
```
|
```
|
||||||
|
|
||||||
_Note: Don't create the Pjax in the `whenDOMReady` function._
|
_Note: Don't create the Pjax instance in the `whenDOMReady` function._
|
||||||
|
|
||||||
For my concern & usage, I `js-Pjax`ify all body children, including stuff like navigation & footer (to get navigation state easily updated).
|
For my concern and usage, I `js-Pjax`-ify all body children, including stuff like navigation and footer (to get navigation state easily updated).
|
||||||
So attached behavior are rexecuted each time a page is loaded, like in the snippet above.
|
|
||||||
|
The attached behavior is re-executed each time a page is loaded, like in the snippet above.
|
||||||
|
|
||||||
If you want to just update a specific part (it's totally a good idea), you can just
|
If you want to just update a specific part (it's totally a good idea), you can just
|
||||||
add the DOM related code in a function & rexecute this function when "pjax:success" event is done.
|
add the DOM-related code in a function and re-execute this function when "pjax:success" event is fired.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
// do your global stuff
|
// do your global stuff
|
||||||
//... dom ready blah blah
|
//... DOM ready blah blah
|
||||||
|
|
||||||
function whenContainerReady() {
|
function whenContainerReady() {
|
||||||
// do your container related stuff
|
// do your container related stuff
|
||||||
}
|
}
|
||||||
whenContainerReady()
|
whenContainerReady()
|
||||||
|
|
||||||
new Pjax()
|
var pjax = new Pjax()
|
||||||
|
|
||||||
document.addEventListener("pjax:success", whenContainerReady)
|
document.addEventListener("pjax:success", whenContainerReady)
|
||||||
```
|
```
|
||||||
@@ -463,12 +577,12 @@ document.addEventListener("pjax:success", whenContainerReady)
|
|||||||
### Q: Disqus doesn't work anymore, how can I fix that ?
|
### Q: Disqus doesn't work anymore, how can I fix that ?
|
||||||
|
|
||||||
A: There is a few things you need to do:
|
A: There is a few things you need to do:
|
||||||
- wrap your disqus snippet into a dom element that you will add to the `selector`
|
- wrap your Disqus snippet into a DOM element that you will add to the `selector`
|
||||||
arra (or just wrap it with class="js-Pjax") & be sure to have a least the empty
|
property (or just wrap it with `class="js-Pjax"`) and be sure to have at least the empty
|
||||||
wrapper on each page (to avoid differences of DOM between pages)
|
wrapper on each page (to avoid differences of DOM between pages)
|
||||||
- edit your disqus snippet like the one below
|
- edit your Disqus snippet like the one below
|
||||||
|
|
||||||
#### Disqus snippet before pjax integration
|
#### Disqus snippet before Pjax integration
|
||||||
|
|
||||||
```html
|
```html
|
||||||
<script>
|
<script>
|
||||||
@@ -486,8 +600,8 @@ wrapper on each page (to avoid differences of DOM between pages)
|
|||||||
#### Disqus snippet after Pjax integration
|
#### Disqus snippet after Pjax integration
|
||||||
|
|
||||||
```html
|
```html
|
||||||
<div class="js-Pjax"><!-- need to be here on every pjaxified page, even if empty -->
|
<div class="js-Pjax"><!-- needs to be here on every Pjax-ified page, even if empty -->
|
||||||
<!-- if (blah blah) { // eventual server side test to know wheter or not you include this script -->
|
<!-- if (blah blah) { // eventual server-side test to know whether or not you include this script -->
|
||||||
<script>
|
<script>
|
||||||
var disqus_shortname = 'YOURSHORTNAME'
|
var disqus_shortname = 'YOURSHORTNAME'
|
||||||
var disqus_identifier = 'PAGEID'
|
var disqus_identifier = 'PAGEID'
|
||||||
@@ -517,13 +631,13 @@ wrapper on each page (to avoid differences of DOM between pages)
|
|||||||
</div>
|
</div>
|
||||||
```
|
```
|
||||||
|
|
||||||
**Note: The thing you need to understand is that Pjax handle inline `<script>` only for container you are reloading.**
|
**Note: Pjax only handles inline `<script>` blocks for the container you are switching.**
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Examples
|
## Examples
|
||||||
|
|
||||||
Clone this repository and run `npm run example`, then open `http://localhost:3000/example` in your browser.
|
Clone this repository and run `npm run example`, which will open the example app in your browser.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -531,9 +645,8 @@ Clone this repository and run `npm run example`, then open `http://localhost:300
|
|||||||
|
|
||||||
* ⇄ Pull requests and ★ Stars are always welcome.
|
* ⇄ Pull requests and ★ Stars are always welcome.
|
||||||
* For bugs and feature requests, please create an issue.
|
* For bugs and feature requests, please create an issue.
|
||||||
* Pull requests must be accompanied by passing automated tests (`$ npm test`).
|
* Pull requests must be accompanied by passing automated tests (`npm test`). If the API is changed, please update the Typescript definitions as well (`pjax.d.ts`).
|
||||||
|
|
||||||
## [CHANGELOG](CHANGELOG.md)
|
## [CHANGELOG](CHANGELOG.md)
|
||||||
|
|
||||||
## [LICENSE](LICENSE)
|
## [LICENSE](LICENSE)
|
||||||
|
|
||||||
|
|||||||
29
bower.json
29
bower.json
@@ -1,29 +0,0 @@
|
|||||||
{
|
|
||||||
"name": "pjax",
|
|
||||||
"version": "0.2.4",
|
|
||||||
"description": "Easily enable fast Ajax navigation on any website (using pushState + xhr)",
|
|
||||||
"keywords": [
|
|
||||||
"pjax",
|
|
||||||
"push",
|
|
||||||
"state",
|
|
||||||
"ajax",
|
|
||||||
"navigation",
|
|
||||||
"transition",
|
|
||||||
"animation"
|
|
||||||
],
|
|
||||||
"main": "pjax.js",
|
|
||||||
"homepage": "https://github.com/MoOx/pjax",
|
|
||||||
"authors": [
|
|
||||||
"Maxime Thirouin"
|
|
||||||
],
|
|
||||||
"license": "MIT",
|
|
||||||
"moduleType": [
|
|
||||||
"node"
|
|
||||||
],
|
|
||||||
"ignore": [
|
|
||||||
"**/.*",
|
|
||||||
"node_modules",
|
|
||||||
"test",
|
|
||||||
"tests"
|
|
||||||
]
|
|
||||||
}
|
|
||||||
@@ -1,4 +1,31 @@
|
|||||||
/* global Pjax */
|
/* global Pjax */
|
||||||
|
var pjax;
|
||||||
|
var initButtons = function() {
|
||||||
|
var buttons = document.querySelectorAll("button[data-manual-trigger]")
|
||||||
|
|
||||||
|
if (!buttons) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// jshint -W083
|
||||||
|
for (var i = 0; i < buttons.length; i++) {
|
||||||
|
buttons[i].addEventListener("click", function(e) {
|
||||||
|
var el = e.currentTarget
|
||||||
|
|
||||||
|
if (el.getAttribute("data-manual-trigger-override") === "true") {
|
||||||
|
// Manually load URL with overridden Pjax instance options
|
||||||
|
pjax.loadUrl("/example/page2.html", {cacheBust: false})
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
// Manually load URL with current Pjax instance options
|
||||||
|
pjax.loadUrl("/example/page2.html")
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
// jshint +W083
|
||||||
|
}
|
||||||
|
|
||||||
console.log("Document initialized:", window.location.href)
|
console.log("Document initialized:", window.location.href)
|
||||||
|
|
||||||
document.addEventListener("pjax:send", function() {
|
document.addEventListener("pjax:send", function() {
|
||||||
@@ -15,12 +42,20 @@ document.addEventListener("pjax:error", function() {
|
|||||||
|
|
||||||
document.addEventListener("pjax:success", function() {
|
document.addEventListener("pjax:success", function() {
|
||||||
console.log("Event: pjax:success", arguments)
|
console.log("Event: pjax:success", arguments)
|
||||||
|
|
||||||
|
// Init page content
|
||||||
|
initButtons()
|
||||||
})
|
})
|
||||||
|
|
||||||
document.addEventListener("DOMContentLoaded", function() {
|
document.addEventListener("DOMContentLoaded", function() {
|
||||||
var pjax = new Pjax({
|
// Init Pjax instance
|
||||||
selectors: [".body"],
|
pjax = new Pjax({
|
||||||
// currentUrlFullReload: true,
|
elements: [".js-Pjax"],
|
||||||
|
selectors: [".body", "title"],
|
||||||
|
cacheBust: true
|
||||||
})
|
})
|
||||||
console.log("Pjax initialized.", pjax)
|
console.log("Pjax initialized.", pjax)
|
||||||
|
|
||||||
|
// Init page content
|
||||||
|
initButtons()
|
||||||
})
|
})
|
||||||
|
|||||||
138
example/forms.html
Normal file
138
example/forms.html
Normal file
@@ -0,0 +1,138 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<title>Forms</title>
|
||||||
|
<script src="../pjax.js"></script>
|
||||||
|
<script src="example.js"></script>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div class="body">
|
||||||
|
<h1>Forms</h1>
|
||||||
|
Hello. Try out the examples below and inspect the results in your browser's developer tools, or go to the <a href="index.html" class="js-Pjax">Index</a>.
|
||||||
|
|
||||||
|
<h3>GET form</h3>
|
||||||
|
|
||||||
|
<form action="" method="get" class="js-Pjax" id="get-form">
|
||||||
|
<label for="get-form-text">Text input:</label>
|
||||||
|
<input type="text" name="textInput" id="get-form-text" value="Foobar" />
|
||||||
|
|
||||||
|
<br />
|
||||||
|
<br />
|
||||||
|
|
||||||
|
<label for="get-form-number">Number input:</label>
|
||||||
|
<input type="number" name="numberInput" id="get-form-number" value="1" />
|
||||||
|
|
||||||
|
<br />
|
||||||
|
<br />
|
||||||
|
|
||||||
|
<label for="get-form-email">Email input:</label>
|
||||||
|
<input type="email" name="emailInput" id="get-form-email" value="example@example.com" />
|
||||||
|
|
||||||
|
<br />
|
||||||
|
<br />
|
||||||
|
|
||||||
|
<label for="get-form-textarea">Textarea:</label>
|
||||||
|
<textarea name="textarea" id="get-form-textarea">This is some text</textarea>
|
||||||
|
|
||||||
|
<br />
|
||||||
|
<br />
|
||||||
|
|
||||||
|
<fieldset>
|
||||||
|
<label for="get-form-radio-1">Radio input:</label>
|
||||||
|
<input type="radio" name="radioInput" value="radio-1" checked id="get-form-radio-1" />
|
||||||
|
|
||||||
|
<label for="get-form-radio-2">Radio input alt:</label>
|
||||||
|
<input type="radio" name="radioInput" value="radio-2" id="get-form-radio-2" />
|
||||||
|
</fieldset>
|
||||||
|
|
||||||
|
<br />
|
||||||
|
<br />
|
||||||
|
|
||||||
|
<label for="get-form-checkbox">Checkbox input:</label>
|
||||||
|
<input type="checkbox" name="checkboxInput" checked id="get-form-checkbox" />
|
||||||
|
|
||||||
|
<br />
|
||||||
|
<br />
|
||||||
|
|
||||||
|
<label for="get-form-select">Select list:</label>
|
||||||
|
<select multiple name="select" id="get-form-select">
|
||||||
|
<option>
|
||||||
|
Option 1
|
||||||
|
</option>
|
||||||
|
<option>
|
||||||
|
Option 2
|
||||||
|
</option>
|
||||||
|
</select>
|
||||||
|
|
||||||
|
<br />
|
||||||
|
<br />
|
||||||
|
|
||||||
|
<input type="submit" value="Submit" />
|
||||||
|
</form>
|
||||||
|
|
||||||
|
<br />
|
||||||
|
<br />
|
||||||
|
|
||||||
|
<h3>POST form</h3>
|
||||||
|
|
||||||
|
<form action="" method="post" class="js-Pjax" id="post-form">
|
||||||
|
<label for="post-form-text">Text input:</label>
|
||||||
|
<input type="text" name="textInput" id="post-form-text" value="Foobar" />
|
||||||
|
|
||||||
|
<br />
|
||||||
|
<br />
|
||||||
|
|
||||||
|
<label for="post-form-number">Number input:</label>
|
||||||
|
<input type="number" name="numberInput" id="post-form-number" value="1" />
|
||||||
|
|
||||||
|
<br />
|
||||||
|
<br />
|
||||||
|
|
||||||
|
<label for="post-form-email">Email input:</label>
|
||||||
|
<input type="email" name="emailInput" id="post-form-email" value="example@example.com" />
|
||||||
|
|
||||||
|
<br />
|
||||||
|
<br />
|
||||||
|
|
||||||
|
<label for="post-form-textarea">Textarea:</label>
|
||||||
|
<textarea name="textarea" id="post-form-textarea">This is some text</textarea>
|
||||||
|
|
||||||
|
<br />
|
||||||
|
<br />
|
||||||
|
|
||||||
|
<fieldset>
|
||||||
|
<label for="post-form-radio-1">Radio input:</label>
|
||||||
|
<input type="radio" name="radioInput" value="radio-1" checked id="post-form-radio-1" />
|
||||||
|
|
||||||
|
<label for="post-form-radio-2">Radio input alt:</label>
|
||||||
|
<input type="radio" name="radioInput" value="radio-2" id="post-form-radio-2" />
|
||||||
|
</fieldset>
|
||||||
|
|
||||||
|
<br />
|
||||||
|
<br />
|
||||||
|
|
||||||
|
<label for="post-form-checkbox">Checkbox input:</label>
|
||||||
|
<input type="checkbox" name="checkboxInput" checked id="post-form-checkbox" />
|
||||||
|
|
||||||
|
<br />
|
||||||
|
<br />
|
||||||
|
|
||||||
|
<label for="post-form-select">Select list:</label>
|
||||||
|
<select multiple name="select" id="post-form-select">
|
||||||
|
<option>
|
||||||
|
Option 1
|
||||||
|
</option>
|
||||||
|
<option>
|
||||||
|
Option 2
|
||||||
|
</option>
|
||||||
|
</select>
|
||||||
|
|
||||||
|
<br />
|
||||||
|
<br />
|
||||||
|
|
||||||
|
<input type="submit" value="Submit" />
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -1,17 +1,29 @@
|
|||||||
<!doctype html>
|
<!doctype html>
|
||||||
<html>
|
<html>
|
||||||
<head>
|
<head>
|
||||||
<meta charset='utf-8'>
|
<meta charset="utf-8">
|
||||||
<title>Hello</title>
|
<title>Hello</title>
|
||||||
<script src='../pjax.js'></script>
|
<script src="../pjax.js"></script>
|
||||||
<script src='example.js'></script>
|
<script src="example.js"></script>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<div class='body'>
|
<div class="body">
|
||||||
<h1>Index</h1>
|
<h1>Index</h1>
|
||||||
Hello.
|
Hello.
|
||||||
Go to <a href='page2.html'>Page 2</a> and view your console to see Pjax events.
|
Go to <a href="page2.html" class="js-Pjax">Page 2</a> or <a href="page3.html" class="js-Pjax">Page 3</a> and view your console to see Pjax events.
|
||||||
Clicking on <a href='index.html'>this page</a> will just reload the page entierly.
|
Clicking on <a href="index.html">this page</a> will do nothing.
|
||||||
|
|
||||||
|
<h2>Manual URL loading</h2>
|
||||||
|
|
||||||
|
You can use Pjax's <i>loadUrl</i> method to manually load a URL. Click the buttons below to try it out!<br /><br />
|
||||||
|
|
||||||
|
<button data-manual-trigger>loadUrl with current options</button><br /><br />
|
||||||
|
<button data-manual-trigger data-manual-trigger-override="true">loadUrl with overridden options (no cache busting)</button>
|
||||||
|
|
||||||
|
<h2>Forms</h2>
|
||||||
|
|
||||||
|
You can submit GET or POST forms with Pjax! Go to the <a href="forms.html">form examples</a> to try it out.
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
@@ -1,15 +1,15 @@
|
|||||||
<!doctype html>
|
<!doctype html>
|
||||||
<html>
|
<html>
|
||||||
<head>
|
<head>
|
||||||
<meta charset='utf-8'>
|
<meta charset="utf-8">
|
||||||
<title>Hello</title>
|
<title>Page 2</title>
|
||||||
<script src='../pjax.js'></script>
|
<script src="../pjax.js"></script>
|
||||||
<script src='example.js'></script>
|
<script src="example.js"></script>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<div class='body'>
|
<div class="body">
|
||||||
<h1>Page 2</h1>
|
<h1>Page 2</h1>
|
||||||
Hello. Go to <a href='index.html'>Index</a>.
|
Hello. Go to <a href="index.html" class="js-Pjax">Index</a>.
|
||||||
</div>
|
</div>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|||||||
15
example/page3.html
Normal file
15
example/page3.html
Normal file
@@ -0,0 +1,15 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<title>Page 3</title>
|
||||||
|
<script src="../pjax.js"></script>
|
||||||
|
<script src="example.js"></script>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div class="body">
|
||||||
|
<h1>Page 3</h1>
|
||||||
|
Hello. Go to <a href="index.html" class="js-Pjax">Index</a>.
|
||||||
|
</div>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
205
index.d.ts
vendored
Normal file
205
index.d.ts
vendored
Normal file
@@ -0,0 +1,205 @@
|
|||||||
|
declare class Pjax {
|
||||||
|
options: Pjax.IOptions;
|
||||||
|
|
||||||
|
constructor(options?: Partial<Pjax.IOptions>);
|
||||||
|
|
||||||
|
static switches: {
|
||||||
|
[key in DefaultSwitches]: Pjax.Switch
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Checks if Pjax is supported by the environment.
|
||||||
|
*/
|
||||||
|
static isSupported: () => boolean;
|
||||||
|
|
||||||
|
log: VoidFunction;
|
||||||
|
|
||||||
|
getElements(el: Element | Document): NodeListOf<Element>;
|
||||||
|
|
||||||
|
parseDOM(el: Element | Document): void;
|
||||||
|
|
||||||
|
refresh: ElementFunction;
|
||||||
|
|
||||||
|
reload: VoidFunction;
|
||||||
|
|
||||||
|
attachLink(el: HTMLAnchorElement): void;
|
||||||
|
|
||||||
|
attachForm(el: HTMLFormElement): void;
|
||||||
|
|
||||||
|
forEachSelectors(cb: ElementFunction, context: Pjax, DOMcontext?: Element | Document): void;
|
||||||
|
|
||||||
|
switchesSelectors(selectors: string[], fromEl: Element | Document, toEl: Element | Document, options: Pjax.IOptions): void;
|
||||||
|
|
||||||
|
latestChance(href: string): void;
|
||||||
|
|
||||||
|
onSwitch: VoidFunction;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Loads the HTML from the response into the DOM.
|
||||||
|
*
|
||||||
|
* @param {string} html
|
||||||
|
* @param {Pjax.IOptions} options
|
||||||
|
*/
|
||||||
|
loadContent(html: string, options: Pjax.IOptions): void;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Aborts an ongoing XHR request.
|
||||||
|
*
|
||||||
|
* @param {XMLHttpRequest} request
|
||||||
|
*/
|
||||||
|
abortRequest(request: XMLHttpRequest): void;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Makes the XHR request.
|
||||||
|
*
|
||||||
|
* @param {string} location The URI for the request.
|
||||||
|
* @param {Pjax.IOptions | null} options
|
||||||
|
* @param {(requestText: string, request: XMLHttpRequest, href: string) => void} callback The callback to call when
|
||||||
|
* the response is received. The signature should match that of <code>handleResponse</code>.
|
||||||
|
* @returns {XMLHttpRequest}
|
||||||
|
*/
|
||||||
|
doRequest(location: string, options: Pjax.IOptions | null,
|
||||||
|
callback: (requestText: string, request: XMLHttpRequest, href: string) => void): XMLHttpRequest;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Saves the state, updates the URL if there were any redirects, then calls loadContent().
|
||||||
|
*
|
||||||
|
* @param {string} requestText The raw text of the response. Same as <code>request.responseText</code>.
|
||||||
|
* @param {XMLHttpRequest} request The XHR object.
|
||||||
|
* @param {string} href The original URI used to initiate the request.
|
||||||
|
* @param options The Pjax options object used for the request
|
||||||
|
*/
|
||||||
|
handleResponse(requestText: string, request: XMLHttpRequest, href: string, options?: Pjax.IOptions): void;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Initiates the request by calling <code>doRequest()</code>.
|
||||||
|
* @param {string} href
|
||||||
|
* @param {Pjax.IOptions} options
|
||||||
|
*/
|
||||||
|
loadUrl(href: string, options?: Pjax.IOptions): void;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Called after all switches complete (even async).
|
||||||
|
*/
|
||||||
|
afterAllSwitches: VoidFunction;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Allows reassignment of existing prototype functions to be able to do something before calling the original function.
|
||||||
|
* For example:
|
||||||
|
*
|
||||||
|
* <pre>
|
||||||
|
* pjax._handleResponse = pjax.handleResponse;
|
||||||
|
* pjax.handleResponse = (requestText: string, request: XMLHttpRequest, href: string) => {
|
||||||
|
* return pjax._handleResponse(requestText, request, href);
|
||||||
|
* }
|
||||||
|
* </pre>
|
||||||
|
*/
|
||||||
|
[key: string]: Function | Pjax.IOptions;
|
||||||
|
}
|
||||||
|
|
||||||
|
declare namespace Pjax {
|
||||||
|
export interface IOptions {
|
||||||
|
/**
|
||||||
|
* CSS selector to use to retrieve links to apply Pjax to.
|
||||||
|
*/
|
||||||
|
elements: string;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* CSS selectors for the elements to replace.
|
||||||
|
*/
|
||||||
|
selectors: string[];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Objects containing callbacks that can be used to switch old elements with new elements.
|
||||||
|
* Keys should be one of the defined selectors.
|
||||||
|
*/
|
||||||
|
switches: StringKeyedObject<Switch>;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* These are options that can be used during switches.
|
||||||
|
* Keys should be one of the defined selectors.
|
||||||
|
*/
|
||||||
|
switchesOptions: StringKeyedObject;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Enable the use of pushState(). Disabling this will prevent Pjax from updating browser history.
|
||||||
|
* Internally, this option is used when a popstate event triggers Pjax (to not pushState() again).
|
||||||
|
*/
|
||||||
|
history: boolean;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Function that allows you to add behavior for analytics.
|
||||||
|
* By default it tries to track a pageview with Google Analytics (if it exists on the page).
|
||||||
|
* It's called every time a page is switched, even for history navigation.
|
||||||
|
* Set to false to disable this behavior.
|
||||||
|
*/
|
||||||
|
analytics: Function | false;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* When set to an integer, this is the value (in px from the top of the page) to scroll to when a page is switched.
|
||||||
|
* When set to an array of 2 integers ([x, y]), this is the value to scroll both horizontally and vertically.
|
||||||
|
* Set this to false to disable scrolling, which will mean the page will stay in that same position it was before
|
||||||
|
* loading the new elements.
|
||||||
|
*/
|
||||||
|
scrollTo: number | [number, number] | false;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* When set to true, attempt to restore the scroll position when navigating backwards or forwards.
|
||||||
|
*/
|
||||||
|
scrollRestoration: boolean;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* When set to true, append a timestamp query string segment to the requested URLs in order to skip browser cache.
|
||||||
|
*/
|
||||||
|
cacheBust: boolean;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Enables verbose mode.
|
||||||
|
*/
|
||||||
|
debug: boolean;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The timeout in milliseconds for the XHR requests. Set to 0 to disable the timeout.
|
||||||
|
*/
|
||||||
|
timeout: number;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* When set to true, clicking on a link that points to the current URL will trigger a full page reload.
|
||||||
|
* (Note that if cacheBust is set to true, the code that checks if the href is the same as the current page's URL
|
||||||
|
* will not work, due to the query string appended to force a cache bust).
|
||||||
|
*/
|
||||||
|
currentUrlFullReload: boolean;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Hold the information to make an XHR request.
|
||||||
|
*/
|
||||||
|
requestOptions?: {
|
||||||
|
requestUrl?: string;
|
||||||
|
requestMethod?: string;
|
||||||
|
requestParams?: IRequestParams[];
|
||||||
|
formData?: FormData;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export type Switch = (oldEl: Element, newEl: Element, options?: IOptions, switchesOptions?: StringKeyedObject) => void;
|
||||||
|
|
||||||
|
export interface IRequestParams {
|
||||||
|
name: string,
|
||||||
|
value: string
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
interface StringKeyedObject<T = any> {
|
||||||
|
[key: string]: T
|
||||||
|
}
|
||||||
|
|
||||||
|
type ElementFunction = (el: Element) => void;
|
||||||
|
|
||||||
|
declare enum DefaultSwitches {
|
||||||
|
innerHTML = "innerHTML",
|
||||||
|
ouetrHTML = "outerHTML",
|
||||||
|
sideBySide = "sideBySide",
|
||||||
|
replaceNode = "replaceNode"
|
||||||
|
}
|
||||||
|
|
||||||
|
export = Pjax;
|
||||||
213
index.js
213
index.js
@@ -1,22 +1,32 @@
|
|||||||
var clone = require('./lib/clone.js')
|
var executeScripts = require("./lib/execute-scripts.js")
|
||||||
var executeScripts = require('./lib/execute-scripts.js')
|
|
||||||
|
|
||||||
var forEachEls = require("./lib/foreach-els.js")
|
var forEachEls = require("./lib/foreach-els.js")
|
||||||
|
var parseOptions = require("./lib/parse-options.js")
|
||||||
|
var switches = require("./lib/switches")
|
||||||
var newUid = require("./lib/uniqueid.js")
|
var newUid = require("./lib/uniqueid.js")
|
||||||
|
|
||||||
var on = require("./lib/events/on.js")
|
var on = require("./lib/events/on.js")
|
||||||
// var off = require("./lib/events/on.js")
|
|
||||||
var trigger = require("./lib/events/trigger.js")
|
var trigger = require("./lib/events/trigger.js")
|
||||||
|
|
||||||
|
var clone = require("./lib/util/clone.js")
|
||||||
|
var contains = require("./lib/util/contains.js")
|
||||||
|
var extend = require("./lib/util/extend.js")
|
||||||
|
var noop = require("./lib/util/noop")
|
||||||
|
|
||||||
var Pjax = function(options) {
|
var Pjax = function(options) {
|
||||||
this.firstrun = true
|
this.state = {
|
||||||
|
numPendingSwitches: 0,
|
||||||
|
href: null,
|
||||||
|
options: null
|
||||||
|
}
|
||||||
|
|
||||||
var parseOptions = require("./lib/proto/parse-options.js");
|
|
||||||
parseOptions.apply(this,[options])
|
this.options = parseOptions(options)
|
||||||
this.log("Pjax options", this.options)
|
this.log("Pjax options", this.options)
|
||||||
|
|
||||||
|
if (this.options.scrollRestoration && "scrollRestoration" in history) {
|
||||||
|
history.scrollRestoration = "manual"
|
||||||
|
}
|
||||||
|
|
||||||
this.maxUid = this.lastUid = newUid()
|
this.maxUid = this.lastUid = newUid()
|
||||||
|
|
||||||
this.parseDOM(document)
|
this.parseDOM(document)
|
||||||
@@ -27,7 +37,7 @@ var Pjax = function(options) {
|
|||||||
opt.url = st.state.url
|
opt.url = st.state.url
|
||||||
opt.title = st.state.title
|
opt.title = st.state.title
|
||||||
opt.history = false
|
opt.history = false
|
||||||
|
opt.scrollPos = st.state.scrollPos
|
||||||
if (st.state.uid < this.lastUid) {
|
if (st.state.uid < this.lastUid) {
|
||||||
opt.backward = true
|
opt.backward = true
|
||||||
}
|
}
|
||||||
@@ -42,19 +52,32 @@ var Pjax = function(options) {
|
|||||||
}.bind(this))
|
}.bind(this))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Pjax.switches = switches
|
||||||
|
|
||||||
Pjax.prototype = {
|
Pjax.prototype = {
|
||||||
log: require("./lib/proto/log.js"),
|
log: require("./lib/proto/log.js"),
|
||||||
|
|
||||||
getElements: require("./lib/proto/get-elements.js"),
|
getElements: function(el) {
|
||||||
|
return el.querySelectorAll(this.options.elements)
|
||||||
|
},
|
||||||
|
|
||||||
parseDOM: require("./lib/proto/parse-dom.js"),
|
parseDOM: function(el) {
|
||||||
|
var parseElement = require("./lib/proto/parse-element")
|
||||||
|
forEachEls(this.getElements(el), parseElement, this)
|
||||||
|
},
|
||||||
|
|
||||||
refresh: require("./lib/proto/refresh.js"),
|
refresh: function(el) {
|
||||||
|
this.parseDOM(el || document)
|
||||||
|
},
|
||||||
|
|
||||||
reload: require("./lib/reload.js"),
|
reload: function() {
|
||||||
|
window.location.reload()
|
||||||
|
},
|
||||||
|
|
||||||
attachLink: require("./lib/proto/attach-link.js"),
|
attachLink: require("./lib/proto/attach-link.js"),
|
||||||
|
|
||||||
|
attachForm: require("./lib/proto/attach-form.js"),
|
||||||
|
|
||||||
forEachSelectors: function(cb, context, DOMcontext) {
|
forEachSelectors: function(cb, context, DOMcontext) {
|
||||||
return require("./lib/foreach-selectors.js").bind(this)(this.options.selectors, cb, context, DOMcontext)
|
return require("./lib/foreach-selectors.js").bind(this)(this.options.selectors, cb, context, DOMcontext)
|
||||||
},
|
},
|
||||||
@@ -63,25 +86,23 @@ Pjax.prototype = {
|
|||||||
return require("./lib/switches-selectors.js").bind(this)(this.options.switches, this.options.switchesOptions, selectors, fromEl, toEl, options)
|
return require("./lib/switches-selectors.js").bind(this)(this.options.switches, this.options.switchesOptions, selectors, fromEl, toEl, options)
|
||||||
},
|
},
|
||||||
|
|
||||||
// too much problem with the code below
|
|
||||||
// + it’s too dangerous
|
|
||||||
// switchFallback: function(fromEl, toEl) {
|
|
||||||
// this.switchSelectors(["head", "body"], fromEl, toEl)
|
|
||||||
// // execute script when DOM is like it should be
|
|
||||||
// Pjax.executeScripts(document.querySelector("head"))
|
|
||||||
// Pjax.executeScripts(document.querySelector("body"))
|
|
||||||
// }
|
|
||||||
|
|
||||||
latestChance: function(href) {
|
latestChance: function(href) {
|
||||||
window.location = href
|
window.location = href
|
||||||
},
|
},
|
||||||
|
|
||||||
onSwitch: function() {
|
onSwitch: function() {
|
||||||
trigger(window, "resize scroll")
|
trigger(window, "resize scroll")
|
||||||
|
|
||||||
|
this.state.numPendingSwitches--
|
||||||
|
|
||||||
|
// debounce calls, so we only run this once after all switches are finished.
|
||||||
|
if (this.state.numPendingSwitches === 0) {
|
||||||
|
this.afterAllSwitches()
|
||||||
|
}
|
||||||
},
|
},
|
||||||
|
|
||||||
loadContent: function(html, options) {
|
loadContent: function(html, options) {
|
||||||
var tmpEl = document.implementation.createHTMLDocument()
|
var tmpEl = document.implementation.createHTMLDocument("pjax")
|
||||||
|
|
||||||
// parse HTML attributes to copy them
|
// parse HTML attributes to copy them
|
||||||
// since we are forced to use documentElement.innerHTML (outerHTML can't be used for <html>)
|
// since we are forced to use documentElement.innerHTML (outerHTML can't be used for <html>)
|
||||||
@@ -108,16 +129,38 @@ Pjax.prototype = {
|
|||||||
this.log("load content", tmpEl.documentElement.attributes, tmpEl.documentElement.innerHTML.length)
|
this.log("load content", tmpEl.documentElement.attributes, tmpEl.documentElement.innerHTML.length)
|
||||||
|
|
||||||
// Clear out any focused controls before inserting new page contents.
|
// Clear out any focused controls before inserting new page contents.
|
||||||
// we clear focus on non form elements
|
if (document.activeElement && contains(document, this.options.selectors, document.activeElement)) {
|
||||||
if (document.activeElement && !document.activeElement.value) {
|
|
||||||
try {
|
try {
|
||||||
document.activeElement.blur()
|
document.activeElement.blur()
|
||||||
} catch (e) { }
|
} catch (e) { }
|
||||||
}
|
}
|
||||||
|
|
||||||
// try {
|
|
||||||
this.switchSelectors(this.options.selectors, tmpEl, document, options)
|
this.switchSelectors(this.options.selectors, tmpEl, document, options)
|
||||||
|
},
|
||||||
|
|
||||||
|
abortRequest: require("./lib/abort-request.js"),
|
||||||
|
|
||||||
|
doRequest: require("./lib/send-request.js"),
|
||||||
|
|
||||||
|
handleResponse: require("./lib/proto/handle-response.js"),
|
||||||
|
|
||||||
|
loadUrl: function(href, options) {
|
||||||
|
options = typeof options === "object" ?
|
||||||
|
extend({}, this.options, options) :
|
||||||
|
clone(this.options)
|
||||||
|
|
||||||
|
this.log("load href", href, options)
|
||||||
|
|
||||||
|
// Abort any previous request
|
||||||
|
this.abortRequest(this.request)
|
||||||
|
|
||||||
|
trigger(document, "pjax:send", options)
|
||||||
|
|
||||||
|
// Do the request
|
||||||
|
this.request = this.doRequest(href, options, this.handleResponse.bind(this))
|
||||||
|
},
|
||||||
|
|
||||||
|
afterAllSwitches: function() {
|
||||||
// FF bug: Won’t autofocus fields that are inserted via JS.
|
// FF bug: Won’t autofocus fields that are inserted via JS.
|
||||||
// This behavior is incorrect. So if theres no current focus, autofocus
|
// This behavior is incorrect. So if theres no current focus, autofocus
|
||||||
// the last field.
|
// the last field.
|
||||||
@@ -125,7 +168,7 @@ Pjax.prototype = {
|
|||||||
// http://www.w3.org/html/wg/drafts/html/master/forms.html
|
// http://www.w3.org/html/wg/drafts/html/master/forms.html
|
||||||
var autofocusEl = Array.prototype.slice.call(document.querySelectorAll("[autofocus]")).pop()
|
var autofocusEl = Array.prototype.slice.call(document.querySelectorAll("[autofocus]")).pop()
|
||||||
if (autofocusEl && document.activeElement !== autofocusEl) {
|
if (autofocusEl && document.activeElement !== autofocusEl) {
|
||||||
autofocusEl.focus();
|
autofocusEl.focus()
|
||||||
}
|
}
|
||||||
|
|
||||||
// execute scripts when DOM have been completely updated
|
// execute scripts when DOM have been completely updated
|
||||||
@@ -134,71 +177,32 @@ Pjax.prototype = {
|
|||||||
executeScripts(el)
|
executeScripts(el)
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
// }
|
|
||||||
// catch(e) {
|
|
||||||
// if (this.options.debug) {
|
|
||||||
// this.log("Pjax switch fail: ", e)
|
|
||||||
// }
|
|
||||||
// this.switchFallback(tmpEl, document)
|
|
||||||
// }
|
|
||||||
},
|
|
||||||
|
|
||||||
doRequest: require("./lib/request.js"),
|
var state = this.state
|
||||||
|
|
||||||
loadUrl: function(href, options) {
|
if (state.options.history) {
|
||||||
this.log("load href", href, options)
|
if (!window.history.state) {
|
||||||
|
|
||||||
trigger(document, "pjax:send", options);
|
|
||||||
|
|
||||||
// Do the request
|
|
||||||
this.doRequest(href, function(html) {
|
|
||||||
// Fail if unable to load HTML via AJAX
|
|
||||||
if (html === false) {
|
|
||||||
trigger(document,"pjax:complete pjax:error", options)
|
|
||||||
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// Clear out any focused controls before inserting new page contents.
|
|
||||||
document.activeElement.blur()
|
|
||||||
|
|
||||||
try {
|
|
||||||
this.loadContent(html, options)
|
|
||||||
}
|
|
||||||
catch (e) {
|
|
||||||
if (!this.options.debug) {
|
|
||||||
if (console && console.error) {
|
|
||||||
console.error("Pjax switch fail: ", e)
|
|
||||||
}
|
|
||||||
this.latestChance(href)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
throw e
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (options.history) {
|
|
||||||
if (this.firstrun) {
|
|
||||||
this.lastUid = this.maxUid = newUid()
|
this.lastUid = this.maxUid = newUid()
|
||||||
this.firstrun = false
|
|
||||||
window.history.replaceState({
|
window.history.replaceState({
|
||||||
url: window.location.href,
|
url: window.location.href,
|
||||||
title: document.title,
|
title: document.title,
|
||||||
uid: this.maxUid
|
uid: this.maxUid,
|
||||||
|
scrollPos: [0, 0]
|
||||||
},
|
},
|
||||||
document.title)
|
document.title)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Update browser history
|
// Update browser history
|
||||||
this.lastUid = this.maxUid = newUid()
|
this.lastUid = this.maxUid = newUid()
|
||||||
|
|
||||||
window.history.pushState({
|
window.history.pushState({
|
||||||
url: href,
|
url: state.href,
|
||||||
title: options.title,
|
title: state.options.title,
|
||||||
uid: this.maxUid
|
uid: this.maxUid,
|
||||||
|
scrollPos: [0, 0]
|
||||||
},
|
},
|
||||||
options.title,
|
state.options.title,
|
||||||
href)
|
state.href)
|
||||||
}
|
}
|
||||||
|
|
||||||
this.forEachSelectors(function(el) {
|
this.forEachSelectors(function(el) {
|
||||||
@@ -206,24 +210,57 @@ Pjax.prototype = {
|
|||||||
}, this)
|
}, this)
|
||||||
|
|
||||||
// Fire Events
|
// Fire Events
|
||||||
trigger(document,"pjax:complete pjax:success", options)
|
trigger(document,"pjax:complete pjax:success", state.options)
|
||||||
|
|
||||||
options.analytics()
|
if (typeof state.options.analytics === "function") {
|
||||||
|
state.options.analytics()
|
||||||
|
}
|
||||||
|
|
||||||
|
if (state.options.history) {
|
||||||
|
// First parse url and check for hash to override scroll
|
||||||
|
var a = document.createElement("a")
|
||||||
|
a.href = this.state.href
|
||||||
|
if (a.hash) {
|
||||||
|
var name = a.hash.slice(1)
|
||||||
|
name = decodeURIComponent(name)
|
||||||
|
|
||||||
|
var curtop = 0
|
||||||
|
var target = document.getElementById(name) || document.getElementsByName(name)[0]
|
||||||
|
if (target) {
|
||||||
|
// http://stackoverflow.com/questions/8111094/cross-browser-javascript-function-to-find-actual-position-of-an-element-in-page
|
||||||
|
if (target.offsetParent) {
|
||||||
|
do {
|
||||||
|
curtop += target.offsetTop
|
||||||
|
|
||||||
|
target = target.offsetParent
|
||||||
|
} while (target)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
window.scrollTo(0, curtop)
|
||||||
|
}
|
||||||
|
else if (state.options.scrollTo !== false) {
|
||||||
// Scroll page to top on new page load
|
// Scroll page to top on new page load
|
||||||
if (options.scrollTo !== false) {
|
if (state.options.scrollTo.length > 1) {
|
||||||
if (options.scrollTo.length > 1) {
|
window.scrollTo(state.options.scrollTo[0], state.options.scrollTo[1])
|
||||||
window.scrollTo(options.scrollTo[0], options.scrollTo[1])
|
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
window.scrollTo(0, options.scrollTo)
|
window.scrollTo(0, state.options.scrollTo)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}.bind(this))
|
}
|
||||||
|
else if (state.options.scrollRestoration && state.options.scrollPos) {
|
||||||
|
window.scrollTo(state.options.scrollPos[0], state.options.scrollPos[1])
|
||||||
|
}
|
||||||
|
|
||||||
|
this.state = {
|
||||||
|
numPendingSwitches: 0,
|
||||||
|
href: null,
|
||||||
|
options: null
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Pjax.isSupported = require("./lib/is-supported.js");
|
Pjax.isSupported = require("./lib/is-supported.js")
|
||||||
|
|
||||||
// arguably could do `if( require("./lib/is-supported.js")()) {` but that might be a little to simple
|
// arguably could do `if( require("./lib/is-supported.js")()) {` but that might be a little to simple
|
||||||
if (Pjax.isSupported()) {
|
if (Pjax.isSupported()) {
|
||||||
@@ -231,10 +268,10 @@ if (Pjax.isSupported()) {
|
|||||||
}
|
}
|
||||||
// if there isn’t required browser functions, returning stupid api
|
// if there isn’t required browser functions, returning stupid api
|
||||||
else {
|
else {
|
||||||
var stupidPjax = function() {}
|
var stupidPjax = noop
|
||||||
for (var key in Pjax.prototype) {
|
for (var key in Pjax.prototype) {
|
||||||
if (Pjax.prototype.hasOwnProperty(key) && typeof Pjax.prototype[key] === "function") {
|
if (Pjax.prototype.hasOwnProperty(key) && typeof Pjax.prototype[key] === "function") {
|
||||||
stupidPjax[key] = stupidPjax
|
stupidPjax[key] = noop
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
8
lib/abort-request.js
Normal file
8
lib/abort-request.js
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
var noop = require("./util/noop")
|
||||||
|
|
||||||
|
module.exports = function(request) {
|
||||||
|
if (request && request.readyState < 4) {
|
||||||
|
request.onreadystatechange = noop
|
||||||
|
request.abort()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,8 +1,7 @@
|
|||||||
module.exports = function(el) {
|
module.exports = function(el) {
|
||||||
// console.log("going to execute script", el)
|
|
||||||
|
|
||||||
var code = (el.text || el.textContent || el.innerHTML || "")
|
var code = (el.text || el.textContent || el.innerHTML || "")
|
||||||
var head = document.querySelector("head") || document.documentElement
|
var src = (el.src || "")
|
||||||
|
var parent = el.parentNode || document.querySelector("head") || document.documentElement
|
||||||
var script = document.createElement("script")
|
var script = document.createElement("script")
|
||||||
|
|
||||||
if (code.match("document.write")) {
|
if (code.match("document.write")) {
|
||||||
@@ -13,17 +12,30 @@ module.exports = function(el) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
script.type = "text/javascript"
|
script.type = "text/javascript"
|
||||||
|
|
||||||
|
/* istanbul ignore if */
|
||||||
|
if (src !== "") {
|
||||||
|
script.src = src
|
||||||
|
script.async = false // force synchronous loading of peripheral JS
|
||||||
|
}
|
||||||
|
|
||||||
|
if (code !== "") {
|
||||||
try {
|
try {
|
||||||
script.appendChild(document.createTextNode(code))
|
script.appendChild(document.createTextNode(code))
|
||||||
}
|
}
|
||||||
catch (e) {
|
catch (e) {
|
||||||
|
/* istanbul ignore next */
|
||||||
// old IEs have funky script nodes
|
// old IEs have funky script nodes
|
||||||
script.text = code
|
script.text = code
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// execute
|
// execute
|
||||||
head.insertBefore(script, head.firstChild)
|
parent.appendChild(script)
|
||||||
head.removeChild(script) // avoid pollution
|
// avoid pollution only in head or body tags
|
||||||
|
if (parent instanceof HTMLHeadElement || parent instanceof HTMLBodyElement) {
|
||||||
|
parent.removeChild(script)
|
||||||
|
}
|
||||||
|
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ module.exports = function(els, events, opts) {
|
|||||||
events = (typeof events === "string" ? events.split(" ") : events)
|
events = (typeof events === "string" ? events.split(" ") : events)
|
||||||
|
|
||||||
events.forEach(function(e) {
|
events.forEach(function(e) {
|
||||||
var event // = new CustomEvent(e) // doesn't everywhere yet
|
var event
|
||||||
event = document.createEvent("HTMLEvents")
|
event = document.createEvent("HTMLEvents")
|
||||||
event.initEvent(e, true, true)
|
event.initEvent(e, true, true)
|
||||||
event.eventName = e
|
event.eventName = e
|
||||||
@@ -17,8 +17,8 @@ module.exports = function(els, events, opts) {
|
|||||||
forEachEls(els, function(el) {
|
forEachEls(els, function(el) {
|
||||||
var domFix = false
|
var domFix = false
|
||||||
if (!el.parentNode && el !== document && el !== window) {
|
if (!el.parentNode && el !== document && el !== window) {
|
||||||
// THANKS YOU IE (9/10//11 concerned)
|
// THANK YOU IE (9/10/11)
|
||||||
// dispatchEvent doesn't work if element is not in the dom
|
// dispatchEvent doesn't work if the element is not in the DOM
|
||||||
domFix = true
|
domFix = true
|
||||||
document.body.appendChild(el)
|
document.body.appendChild(el)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,7 +3,10 @@ var evalScript = require("./eval-script")
|
|||||||
// Finds and executes scripts (used for newly added elements)
|
// Finds and executes scripts (used for newly added elements)
|
||||||
// Needed since innerHTML does not run scripts
|
// Needed since innerHTML does not run scripts
|
||||||
module.exports = function(el) {
|
module.exports = function(el) {
|
||||||
// console.log("going to execute scripts for ", el)
|
if (el.tagName.toLowerCase() === "script") {
|
||||||
|
evalScript(el)
|
||||||
|
}
|
||||||
|
|
||||||
forEachEls(el.querySelectorAll("script"), function(script) {
|
forEachEls(el.querySelectorAll("script"), function(script) {
|
||||||
if (!script.type || script.type.toLowerCase() === "text/javascript") {
|
if (!script.type || script.type.toLowerCase() === "text/javascript") {
|
||||||
if (script.parentNode) {
|
if (script.parentNode) {
|
||||||
|
|||||||
@@ -4,6 +4,6 @@ module.exports = function(els, fn, context) {
|
|||||||
if (els instanceof HTMLCollection || els instanceof NodeList || els instanceof Array) {
|
if (els instanceof HTMLCollection || els instanceof NodeList || els instanceof Array) {
|
||||||
return Array.prototype.forEach.call(els, fn, context)
|
return Array.prototype.forEach.call(els, fn, context)
|
||||||
}
|
}
|
||||||
// assume simple dom element
|
// assume simple DOM element
|
||||||
return fn.call(context, els)
|
return fn.call(context, els)
|
||||||
}
|
}
|
||||||
|
|||||||
41
lib/parse-options.js
Normal file
41
lib/parse-options.js
Normal file
@@ -0,0 +1,41 @@
|
|||||||
|
/* global _gaq: true, ga: true */
|
||||||
|
|
||||||
|
var defaultSwitches = require("./switches")
|
||||||
|
|
||||||
|
module.exports = function(options) {
|
||||||
|
options = options || {}
|
||||||
|
options.elements = options.elements || "a[href], form[action]"
|
||||||
|
options.selectors = options.selectors || ["title", ".js-Pjax"]
|
||||||
|
options.switches = options.switches || {}
|
||||||
|
options.switchesOptions = options.switchesOptions || {}
|
||||||
|
options.history = options.history || true
|
||||||
|
options.analytics = (typeof options.analytics === "function" || options.analytics === false) ? options.analytics : defaultAnalytics
|
||||||
|
options.scrollTo = (typeof options.scrollTo === "undefined") ? 0 : options.scrollTo
|
||||||
|
options.scrollRestoration = (typeof options.scrollRestoration !== "undefined") ? options.scrollRestoration : true
|
||||||
|
options.cacheBust = (typeof options.cacheBust === "undefined") ? true : options.cacheBust
|
||||||
|
options.debug = options.debug || false
|
||||||
|
options.timeout = options.timeout || 0
|
||||||
|
options.currentUrlFullReload = (typeof options.currentUrlFullReload === "undefined") ? false : options.currentUrlFullReload
|
||||||
|
|
||||||
|
// We can’t replace body.outerHTML or head.outerHTML.
|
||||||
|
// It creates a bug where a new body or head are created in the DOM.
|
||||||
|
// If you set head.outerHTML, a new body tag is appended, so the DOM has 2 body nodes, and vice versa
|
||||||
|
if (!options.switches.head) {
|
||||||
|
options.switches.head = defaultSwitches.switchElementsAlt
|
||||||
|
}
|
||||||
|
if (!options.switches.body) {
|
||||||
|
options.switches.body = defaultSwitches.switchElementsAlt
|
||||||
|
}
|
||||||
|
|
||||||
|
return options
|
||||||
|
}
|
||||||
|
|
||||||
|
/* istanbul ignore next */
|
||||||
|
function defaultAnalytics() {
|
||||||
|
if (window._gaq) {
|
||||||
|
_gaq.push(["_trackPageview"])
|
||||||
|
}
|
||||||
|
if (window.ga) {
|
||||||
|
ga("send", "pageview", {page: location.pathname, title: document.title})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,20 +0,0 @@
|
|||||||
if (!Function.prototype.bind) {
|
|
||||||
Function.prototype.bind = function(oThis) {
|
|
||||||
if (typeof this !== "function") {
|
|
||||||
// closest thing possible to the ECMAScript 5 internal IsCallable function
|
|
||||||
throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable")
|
|
||||||
}
|
|
||||||
|
|
||||||
var aArgs = Array.prototype.slice.call(arguments, 1)
|
|
||||||
var that = this
|
|
||||||
var Fnoop = function() {}
|
|
||||||
var fBound = function() {
|
|
||||||
return that.apply(this instanceof Fnoop && oThis ? this : oThis, aArgs.concat(Array.prototype.slice.call(arguments)))
|
|
||||||
}
|
|
||||||
|
|
||||||
Fnoop.prototype = this.prototype
|
|
||||||
fBound.prototype = new Fnoop()
|
|
||||||
|
|
||||||
return fBound
|
|
||||||
}
|
|
||||||
}
|
|
||||||
132
lib/proto/attach-form.js
Normal file
132
lib/proto/attach-form.js
Normal file
@@ -0,0 +1,132 @@
|
|||||||
|
var on = require("../events/on")
|
||||||
|
var clone = require("../util/clone")
|
||||||
|
|
||||||
|
var attrState = "data-pjax-state"
|
||||||
|
|
||||||
|
var formAction = function(el, event) {
|
||||||
|
if (isDefaultPrevented(event)) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Since loadUrl modifies options and we may add our own modifications below,
|
||||||
|
// clone it so the changes don't persist
|
||||||
|
var options = clone(this.options)
|
||||||
|
|
||||||
|
// Initialize requestOptions
|
||||||
|
options.requestOptions = {
|
||||||
|
requestUrl: el.getAttribute("action") || window.location.href,
|
||||||
|
requestMethod: el.getAttribute("method") || "GET"
|
||||||
|
}
|
||||||
|
|
||||||
|
// create a testable virtual link of the form action
|
||||||
|
var virtLinkElement = document.createElement("a")
|
||||||
|
virtLinkElement.setAttribute("href", options.requestOptions.requestUrl)
|
||||||
|
|
||||||
|
var attrValue = checkIfShouldAbort(virtLinkElement, options)
|
||||||
|
if (attrValue) {
|
||||||
|
el.setAttribute(attrState, attrValue)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
event.preventDefault()
|
||||||
|
|
||||||
|
if (el.enctype === "multipart/form-data") {
|
||||||
|
options.requestOptions.formData = new FormData(el)
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
options.requestOptions.requestParams = parseFormElements(el)
|
||||||
|
}
|
||||||
|
|
||||||
|
el.setAttribute(attrState, "submit")
|
||||||
|
|
||||||
|
options.triggerElement = el
|
||||||
|
this.loadUrl(virtLinkElement.href, options)
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseFormElements(el) {
|
||||||
|
var requestParams = []
|
||||||
|
|
||||||
|
for (var elementKey in el.elements) {
|
||||||
|
if (Number.isNaN(Number(elementKey))) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
var element = el.elements[elementKey]
|
||||||
|
var tagName = element.tagName.toLowerCase()
|
||||||
|
// jscs:disable disallowImplicitTypeConversion
|
||||||
|
if (!!element.name && element.attributes !== undefined && tagName !== "button") {
|
||||||
|
// jscs:enable disallowImplicitTypeConversion
|
||||||
|
var type = element.attributes.type
|
||||||
|
|
||||||
|
if ((!type || type.value !== "checkbox" && type.value !== "radio") || element.checked) {
|
||||||
|
// Build array of values to submit
|
||||||
|
var values = []
|
||||||
|
|
||||||
|
if (tagName === "select") {
|
||||||
|
var opt
|
||||||
|
|
||||||
|
for (var i = 0; i < element.options.length; i++) {
|
||||||
|
opt = element.options[i]
|
||||||
|
if (opt.selected) {
|
||||||
|
values.push(opt.value || opt.text)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
values.push(element.value)
|
||||||
|
}
|
||||||
|
|
||||||
|
for (var j = 0; j < values.length; j++) {
|
||||||
|
requestParams.push({
|
||||||
|
name: encodeURIComponent(element.name),
|
||||||
|
value: encodeURIComponent(values[j])
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return requestParams
|
||||||
|
}
|
||||||
|
|
||||||
|
function checkIfShouldAbort(virtLinkElement, options) {
|
||||||
|
// Ignore external links.
|
||||||
|
if (virtLinkElement.protocol !== window.location.protocol || virtLinkElement.host !== window.location.host) {
|
||||||
|
return "external"
|
||||||
|
}
|
||||||
|
|
||||||
|
// Ignore click if we are on an anchor on the same page
|
||||||
|
if (virtLinkElement.hash && virtLinkElement.href.replace(virtLinkElement.hash, "") === window.location.href.replace(location.hash, "")) {
|
||||||
|
return "anchor"
|
||||||
|
}
|
||||||
|
|
||||||
|
// Ignore empty anchor "foo.html#"
|
||||||
|
if (virtLinkElement.href === window.location.href.split("#")[0] + "#") {
|
||||||
|
return "anchor-empty"
|
||||||
|
}
|
||||||
|
|
||||||
|
// if declared as a full reload, just normally submit the form
|
||||||
|
if (options.currentUrlFullReload && virtLinkElement.href === window.location.href.split("#")[0]) {
|
||||||
|
return "reload"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var isDefaultPrevented = function(event) {
|
||||||
|
return event.defaultPrevented || event.returnValue === false
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = function(el) {
|
||||||
|
var that = this
|
||||||
|
|
||||||
|
el.setAttribute(attrState, "")
|
||||||
|
|
||||||
|
on(el, "submit", function(event) {
|
||||||
|
formAction.call(that, el, event)
|
||||||
|
})
|
||||||
|
|
||||||
|
on(el, "keyup", function(event) {
|
||||||
|
if (event.keyCode === 13) {
|
||||||
|
formAction.call(that, el, event)
|
||||||
|
}
|
||||||
|
}.bind(this))
|
||||||
|
}
|
||||||
@@ -1,42 +1,20 @@
|
|||||||
require("../polyfills/Function.prototype.bind")
|
|
||||||
|
|
||||||
var on = require("../events/on")
|
var on = require("../events/on")
|
||||||
var clone = require("../clone")
|
var clone = require("../util/clone")
|
||||||
|
|
||||||
var attrClick = "data-pjax-click-state"
|
var attrState = "data-pjax-state"
|
||||||
var attrKey = "data-pjax-keyup-state"
|
|
||||||
|
|
||||||
var linkAction = function(el, event) {
|
var linkAction = function(el, event) {
|
||||||
// Don’t break browser special behavior on links (like page in new window)
|
if (isDefaultPrevented(event)) {
|
||||||
if (event.which > 1 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) {
|
|
||||||
el.setAttribute(attrClick, "modifier")
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// we do test on href now to prevent unexpected behavior if for some reason
|
// Since loadUrl modifies options and we may add our own modifications below,
|
||||||
// user have href that can be dynamically updated
|
// clone it so the changes don't persist
|
||||||
|
var options = clone(this.options)
|
||||||
|
|
||||||
// Ignore external links.
|
var attrValue = checkIfShouldAbort(el, event)
|
||||||
if (el.protocol !== window.location.protocol || el.host !== window.location.host) {
|
if (attrValue) {
|
||||||
el.setAttribute(attrClick, "external")
|
el.setAttribute(attrState, attrValue)
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// Ignore click if we are on an anchor on the same page
|
|
||||||
if (el.pathname === window.location.pathname && el.hash.length > 0) {
|
|
||||||
el.setAttribute(attrClick, "anchor-present")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// Ignore anchors on the same page (keep native behavior)
|
|
||||||
if (el.hash && el.href.replace(el.hash, "") === window.location.href.replace(location.hash, "")) {
|
|
||||||
el.setAttribute(attrClick, "anchor")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// Ignore empty anchor "foo.html#"
|
|
||||||
if (el.href === window.location.href.split("#")[0] + "#") {
|
|
||||||
el.setAttribute(attrClick, "anchor-empty")
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -47,42 +25,57 @@ var linkAction = function(el, event) {
|
|||||||
this.options.currentUrlFullReload &&
|
this.options.currentUrlFullReload &&
|
||||||
el.href === window.location.href.split("#")[0]
|
el.href === window.location.href.split("#")[0]
|
||||||
) {
|
) {
|
||||||
el.setAttribute(attrClick, "reload")
|
el.setAttribute(attrState, "reload")
|
||||||
this.reload()
|
this.reload()
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
el.setAttribute(attrClick, "load")
|
el.setAttribute(attrState, "load")
|
||||||
this.loadUrl(el.href, clone(this.options))
|
|
||||||
|
options.triggerElement = el
|
||||||
|
this.loadUrl(el.href, options)
|
||||||
|
}
|
||||||
|
|
||||||
|
function checkIfShouldAbort(el, event) {
|
||||||
|
// Don’t break browser special behavior on links (like page in new window)
|
||||||
|
if (event.which > 1 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) {
|
||||||
|
return "modifier"
|
||||||
|
}
|
||||||
|
|
||||||
|
// we do test on href now to prevent unexpected behavior if for some reason
|
||||||
|
// user have href that can be dynamically updated
|
||||||
|
|
||||||
|
// Ignore external links.
|
||||||
|
if (el.protocol !== window.location.protocol || el.host !== window.location.host) {
|
||||||
|
return "external"
|
||||||
|
}
|
||||||
|
|
||||||
|
// Ignore anchors on the same page (keep native behavior)
|
||||||
|
if (el.hash && el.href.replace(el.hash, "") === window.location.href.replace(location.hash, "")) {
|
||||||
|
return "anchor"
|
||||||
|
}
|
||||||
|
|
||||||
|
// Ignore empty anchor "foo.html#"
|
||||||
|
if (el.href === window.location.href.split("#")[0] + "#") {
|
||||||
|
return "anchor-empty"
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
var isDefaultPrevented = function(event) {
|
var isDefaultPrevented = function(event) {
|
||||||
return event.defaultPrevented || event.returnValue === false;
|
return event.defaultPrevented || event.returnValue === false
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = function(el) {
|
module.exports = function(el) {
|
||||||
var that = this
|
var that = this
|
||||||
|
|
||||||
on(el, "click", function(event) {
|
el.setAttribute(attrState, "")
|
||||||
if (isDefaultPrevented(event)) {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
|
on(el, "click", function(event) {
|
||||||
linkAction.call(that, el, event)
|
linkAction.call(that, el, event)
|
||||||
})
|
})
|
||||||
|
|
||||||
on(el, "keyup", function(event) {
|
on(el, "keyup", function(event) {
|
||||||
if (isDefaultPrevented(event)) {
|
if (event.keyCode === 13) {
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// Don’t break browser special behavior on links (like page in new window)
|
|
||||||
if (event.which > 1 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) {
|
|
||||||
el.setAttribute(attrKey, "modifier")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if (event.keyCode == 13) {
|
|
||||||
linkAction.call(that, el, event)
|
linkAction.call(that, el, event)
|
||||||
}
|
}
|
||||||
}.bind(this))
|
}.bind(this))
|
||||||
|
|||||||
@@ -1,3 +0,0 @@
|
|||||||
module.exports = function(el) {
|
|
||||||
return el.querySelectorAll(this.options.elements)
|
|
||||||
}
|
|
||||||
70
lib/proto/handle-response.js
Normal file
70
lib/proto/handle-response.js
Normal file
@@ -0,0 +1,70 @@
|
|||||||
|
var clone = require("../util/clone.js")
|
||||||
|
var newUid = require("../uniqueid.js")
|
||||||
|
var trigger = require("../events/trigger.js")
|
||||||
|
|
||||||
|
module.exports = function(responseText, request, href, options) {
|
||||||
|
options = clone(options || this.options)
|
||||||
|
options.request = request
|
||||||
|
|
||||||
|
// Fail if unable to load HTML via AJAX
|
||||||
|
if (responseText === false) {
|
||||||
|
trigger(document, "pjax:complete pjax:error", options)
|
||||||
|
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// push scroll position to history
|
||||||
|
var currentState = window.history.state || {}
|
||||||
|
window.history.replaceState({
|
||||||
|
url: currentState.url || window.location.href,
|
||||||
|
title: currentState.title || document.title,
|
||||||
|
uid: currentState.uid || newUid(),
|
||||||
|
scrollPos: [document.documentElement.scrollLeft || document.body.scrollLeft,
|
||||||
|
document.documentElement.scrollTop || document.body.scrollTop]
|
||||||
|
},
|
||||||
|
document.title, window.location)
|
||||||
|
|
||||||
|
// Check for redirects
|
||||||
|
var oldHref = href
|
||||||
|
if (request.responseURL) {
|
||||||
|
if (href !== request.responseURL) {
|
||||||
|
href = request.responseURL
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if (request.getResponseHeader("X-PJAX-URL")) {
|
||||||
|
href = request.getResponseHeader("X-PJAX-URL")
|
||||||
|
}
|
||||||
|
else if (request.getResponseHeader("X-XHR-Redirected-To")) {
|
||||||
|
href = request.getResponseHeader("X-XHR-Redirected-To")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add back the hash if it was removed
|
||||||
|
var a = document.createElement("a")
|
||||||
|
a.href = oldHref
|
||||||
|
var oldHash = a.hash
|
||||||
|
a.href = href
|
||||||
|
if (oldHash && !a.hash) {
|
||||||
|
a.hash = oldHash
|
||||||
|
href = a.href
|
||||||
|
}
|
||||||
|
|
||||||
|
this.state.href = href
|
||||||
|
this.state.options = options
|
||||||
|
|
||||||
|
try {
|
||||||
|
this.loadContent(responseText, this.options)
|
||||||
|
}
|
||||||
|
catch (e) {
|
||||||
|
trigger(document, "pjax:error", options)
|
||||||
|
|
||||||
|
if (!this.options.debug) {
|
||||||
|
if (console && console.error) {
|
||||||
|
console.error("Pjax switch fail: ", e)
|
||||||
|
}
|
||||||
|
return this.latestChance(href)
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
throw e
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,11 +1,11 @@
|
|||||||
module.exports = function() {
|
module.exports = function() {
|
||||||
if (this.options.debug && console) {
|
if (this.options.debug && console) {
|
||||||
if (typeof console.log === "function") {
|
if (typeof console.log === "function") {
|
||||||
console.log.apply(console, arguments);
|
console.log.apply(console, arguments)
|
||||||
}
|
}
|
||||||
// ie is weird
|
// IE is weird
|
||||||
else if (console.log) {
|
else if (console.log) {
|
||||||
console.log(arguments);
|
console.log(arguments)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +0,0 @@
|
|||||||
var forEachEls = require("../foreach-els")
|
|
||||||
|
|
||||||
var parseElement = require("./parse-element")
|
|
||||||
|
|
||||||
module.exports = function(el) {
|
|
||||||
forEachEls(this.getElements(el), parseElement, this)
|
|
||||||
}
|
|
||||||
@@ -1,14 +1,19 @@
|
|||||||
|
var attrState = "data-pjax-state"
|
||||||
|
|
||||||
module.exports = function(el) {
|
module.exports = function(el) {
|
||||||
switch (el.tagName.toLowerCase()) {
|
switch (el.tagName.toLowerCase()) {
|
||||||
case "a":
|
case "a":
|
||||||
// only attach link if el does not already have link attached
|
// only attach link if el does not already have link attached
|
||||||
if (!el.hasAttribute('data-pjax-click-state')) {
|
if (!el.hasAttribute(attrState)) {
|
||||||
this.attachLink(el)
|
this.attachLink(el)
|
||||||
}
|
}
|
||||||
break
|
break
|
||||||
|
|
||||||
case "form":
|
case "form":
|
||||||
throw "Pjax doesnt support <form> yet."
|
// only attach link if el does not already have link attached
|
||||||
|
if (!el.hasAttribute(attrState)) {
|
||||||
|
this.attachForm(el)
|
||||||
|
}
|
||||||
break
|
break
|
||||||
|
|
||||||
default:
|
default:
|
||||||
|
|||||||
@@ -1,38 +0,0 @@
|
|||||||
/* global _gaq: true, ga: true */
|
|
||||||
|
|
||||||
module.exports = function(options){
|
|
||||||
this.options = options
|
|
||||||
this.options.elements = this.options.elements || "a[href], form[action]"
|
|
||||||
this.options.selectors = this.options.selectors || ["title", ".js-Pjax"]
|
|
||||||
this.options.switches = this.options.switches || {}
|
|
||||||
this.options.switchesOptions = this.options.switchesOptions || {}
|
|
||||||
this.options.history = this.options.history || true
|
|
||||||
this.options.analytics = this.options.analytics || function() {
|
|
||||||
// options.backward or options.foward can be true or undefined
|
|
||||||
// by default, we do track back/foward hit
|
|
||||||
// https://productforums.google.com/forum/#!topic/analytics/WVwMDjLhXYk
|
|
||||||
if (window._gaq) {
|
|
||||||
_gaq.push(["_trackPageview"])
|
|
||||||
}
|
|
||||||
if (window.ga) {
|
|
||||||
ga("send", "pageview", {page: location.pathname, title: document.title})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
this.options.scrollTo = (typeof this.options.scrollTo === 'undefined') ? 0 : this.options.scrollTo;
|
|
||||||
this.options.cacheBust = (typeof this.options.cacheBust === 'undefined') ? true : this.options.cacheBust
|
|
||||||
this.options.debug = this.options.debug || false
|
|
||||||
|
|
||||||
// we can’t replace body.outerHTML or head.outerHTML
|
|
||||||
// it create a bug where new body or new head are created in the dom
|
|
||||||
// if you set head.outerHTML, a new body tag is appended, so the dom get 2 body
|
|
||||||
// & it break the switchFallback which replace head & body
|
|
||||||
if (!this.options.switches.head) {
|
|
||||||
this.options.switches.head = this.switchElementsAlt
|
|
||||||
}
|
|
||||||
if (!this.options.switches.body) {
|
|
||||||
this.options.switches.body = this.switchElementsAlt
|
|
||||||
}
|
|
||||||
if (typeof options.analytics !== "function") {
|
|
||||||
options.analytics = function() {}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,3 +0,0 @@
|
|||||||
module.exports = function(el) {
|
|
||||||
this.parseDOM(el || document)
|
|
||||||
}
|
|
||||||
@@ -1,3 +0,0 @@
|
|||||||
module.exports = function() {
|
|
||||||
window.location.reload()
|
|
||||||
}
|
|
||||||
@@ -1,24 +0,0 @@
|
|||||||
module.exports = function(location, callback) {
|
|
||||||
var request = new XMLHttpRequest()
|
|
||||||
|
|
||||||
request.onreadystatechange = function() {
|
|
||||||
if (request.readyState === 4) {
|
|
||||||
if (request.status === 200) {
|
|
||||||
callback(request.responseText, request)
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
callback(null, request)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Add a timestamp as part of the query string if cache busting is enabled
|
|
||||||
if (this.options.cacheBust) {
|
|
||||||
location += (!/[?&]/.test(location) ? "?" : "&") + new Date().getTime()
|
|
||||||
}
|
|
||||||
|
|
||||||
request.open("GET", location, true)
|
|
||||||
request.setRequestHeader("X-Requested-With", "XMLHttpRequest")
|
|
||||||
request.send(null)
|
|
||||||
return request
|
|
||||||
}
|
|
||||||
78
lib/send-request.js
Normal file
78
lib/send-request.js
Normal file
@@ -0,0 +1,78 @@
|
|||||||
|
var updateQueryString = require("./util/update-query-string");
|
||||||
|
|
||||||
|
module.exports = function(location, options, callback) {
|
||||||
|
options = options || {}
|
||||||
|
var queryString
|
||||||
|
var requestOptions = options.requestOptions || {}
|
||||||
|
var requestMethod = (requestOptions.requestMethod || "GET").toUpperCase()
|
||||||
|
var requestParams = requestOptions.requestParams || null
|
||||||
|
var formData = requestOptions.formData || null;
|
||||||
|
var requestPayload = null
|
||||||
|
var request = new XMLHttpRequest()
|
||||||
|
var timeout = options.timeout || 0
|
||||||
|
|
||||||
|
request.onreadystatechange = function() {
|
||||||
|
if (request.readyState === 4) {
|
||||||
|
if (request.status === 200) {
|
||||||
|
callback(request.responseText, request, location, options)
|
||||||
|
}
|
||||||
|
else if (request.status !== 0) {
|
||||||
|
callback(null, request, location, options)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
request.onerror = function(e) {
|
||||||
|
console.log(e)
|
||||||
|
callback(null, request, location, options)
|
||||||
|
}
|
||||||
|
|
||||||
|
request.ontimeout = function() {
|
||||||
|
callback(null, request, location, options)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Prepare the request payload for forms, if available
|
||||||
|
if (requestParams && requestParams.length) {
|
||||||
|
// Build query string
|
||||||
|
queryString = (requestParams.map(function(param) {return param.name + "=" + param.value})).join("&")
|
||||||
|
|
||||||
|
switch (requestMethod) {
|
||||||
|
case "GET":
|
||||||
|
// Reset query string to avoid an issue with repeat submissions where checkboxes that were
|
||||||
|
// previously checked are incorrectly preserved
|
||||||
|
location = location.split("?")[0]
|
||||||
|
|
||||||
|
// Append new query string
|
||||||
|
location += "?" + queryString
|
||||||
|
break
|
||||||
|
|
||||||
|
case "POST":
|
||||||
|
// Send query string as request payload
|
||||||
|
requestPayload = queryString
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if (formData) {
|
||||||
|
requestPayload = formData
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add a timestamp as part of the query string if cache busting is enabled
|
||||||
|
if (options.cacheBust) {
|
||||||
|
location = updateQueryString(location, "t", Date.now())
|
||||||
|
}
|
||||||
|
|
||||||
|
request.open(requestMethod, location, true)
|
||||||
|
request.timeout = timeout
|
||||||
|
request.setRequestHeader("X-Requested-With", "XMLHttpRequest")
|
||||||
|
request.setRequestHeader("X-PJAX", "true")
|
||||||
|
request.setRequestHeader("X-PJAX-Selectors", JSON.stringify(options.selectors))
|
||||||
|
|
||||||
|
// Send the proper header information for POST forms
|
||||||
|
if (requestPayload && requestMethod === "POST") {
|
||||||
|
request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
|
||||||
|
}
|
||||||
|
|
||||||
|
request.send(requestPayload)
|
||||||
|
|
||||||
|
return request
|
||||||
|
}
|
||||||
@@ -3,6 +3,8 @@ var forEachEls = require("./foreach-els")
|
|||||||
var defaultSwitches = require("./switches")
|
var defaultSwitches = require("./switches")
|
||||||
|
|
||||||
module.exports = function(switches, switchesOptions, selectors, fromEl, toEl, options) {
|
module.exports = function(switches, switchesOptions, selectors, fromEl, toEl, options) {
|
||||||
|
var switchesQueue = []
|
||||||
|
|
||||||
selectors.forEach(function(selector) {
|
selectors.forEach(function(selector) {
|
||||||
var newEls = fromEl.querySelectorAll(selector)
|
var newEls = fromEl.querySelectorAll(selector)
|
||||||
var oldEls = toEl.querySelectorAll(selector)
|
var oldEls = toEl.querySelectorAll(selector)
|
||||||
@@ -10,12 +12,6 @@ module.exports = function(switches, switchesOptions, selectors, fromEl, toEl, op
|
|||||||
this.log("Pjax switch", selector, newEls, oldEls)
|
this.log("Pjax switch", selector, newEls, oldEls)
|
||||||
}
|
}
|
||||||
if (newEls.length !== oldEls.length) {
|
if (newEls.length !== oldEls.length) {
|
||||||
// forEachEls(newEls, function(el) {
|
|
||||||
// this.log("newEl", el, el.outerHTML)
|
|
||||||
// }, this)
|
|
||||||
// forEachEls(oldEls, function(el) {
|
|
||||||
// this.log("oldEl", el, el.outerHTML)
|
|
||||||
// }, this)
|
|
||||||
throw "DOM doesn’t look the same on new loaded page: ’" + selector + "’ - new " + newEls.length + ", old " + oldEls.length
|
throw "DOM doesn’t look the same on new loaded page: ’" + selector + "’ - new " + newEls.length + ", old " + oldEls.length
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -24,12 +20,18 @@ module.exports = function(switches, switchesOptions, selectors, fromEl, toEl, op
|
|||||||
if (this.log) {
|
if (this.log) {
|
||||||
this.log("newEl", newEl, "oldEl", oldEl)
|
this.log("newEl", newEl, "oldEl", oldEl)
|
||||||
}
|
}
|
||||||
if (switches[selector]) {
|
|
||||||
switches[selector].bind(this)(oldEl, newEl, options, switchesOptions[selector])
|
var callback = (switches[selector]) ?
|
||||||
}
|
switches[selector].bind(this, oldEl, newEl, options, switchesOptions[selector]) :
|
||||||
else {
|
defaultSwitches.outerHTML.bind(this, oldEl, newEl, options)
|
||||||
defaultSwitches.outerHTML.bind(this)(oldEl, newEl, options)
|
|
||||||
}
|
switchesQueue.push(callback)
|
||||||
}, this)
|
}, this)
|
||||||
}, this)
|
}, this)
|
||||||
|
|
||||||
|
this.state.numPendingSwitches = switchesQueue.length
|
||||||
|
|
||||||
|
switchesQueue.forEach(function(queuedSwitch) {
|
||||||
|
queuedSwitch()
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,4 @@
|
|||||||
var on = require("./events/on.js")
|
var on = require("./events/on.js")
|
||||||
// var off = require("./lib/events/on.js")
|
|
||||||
// var trigger = require("./lib/events/trigger.js")
|
|
||||||
|
|
||||||
|
|
||||||
module.exports = {
|
module.exports = {
|
||||||
outerHTML: function(oldEl, newEl) {
|
outerHTML: function(oldEl, newEl) {
|
||||||
@@ -11,7 +8,34 @@ module.exports = {
|
|||||||
|
|
||||||
innerHTML: function(oldEl, newEl) {
|
innerHTML: function(oldEl, newEl) {
|
||||||
oldEl.innerHTML = newEl.innerHTML
|
oldEl.innerHTML = newEl.innerHTML
|
||||||
|
|
||||||
|
if (newEl.className === "") {
|
||||||
|
oldEl.removeAttribute("class")
|
||||||
|
}
|
||||||
|
else {
|
||||||
oldEl.className = newEl.className
|
oldEl.className = newEl.className
|
||||||
|
}
|
||||||
|
|
||||||
|
this.onSwitch()
|
||||||
|
},
|
||||||
|
|
||||||
|
switchElementsAlt: function(oldEl, newEl) {
|
||||||
|
oldEl.innerHTML = newEl.innerHTML
|
||||||
|
|
||||||
|
// Copy attributes from the new element to the old one
|
||||||
|
if (newEl.hasAttributes()) {
|
||||||
|
var attrs = newEl.attributes
|
||||||
|
for (var i = 0; i < attrs.length; i++) {
|
||||||
|
oldEl.attributes.setNamedItem(attrs[i].cloneNode())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
this.onSwitch()
|
||||||
|
},
|
||||||
|
|
||||||
|
// Equivalent to outerHTML(), but doesn't require switchElementsAlt() for <head> and <body>
|
||||||
|
replaceNode: function(oldEl, newEl) {
|
||||||
|
oldEl.parentNode.replaceChild(newEl, oldEl)
|
||||||
this.onSwitch()
|
this.onSwitch()
|
||||||
},
|
},
|
||||||
|
|
||||||
@@ -20,13 +44,10 @@ module.exports = {
|
|||||||
var elsToRemove = []
|
var elsToRemove = []
|
||||||
var elsToAdd = []
|
var elsToAdd = []
|
||||||
var fragToAppend = document.createDocumentFragment()
|
var fragToAppend = document.createDocumentFragment()
|
||||||
// height transition are shitty on safari
|
|
||||||
// so commented for now (until I found something ?)
|
|
||||||
// var relevantHeight = 0
|
|
||||||
var animationEventNames = "animationend webkitAnimationEnd MSAnimationEnd oanimationend"
|
var animationEventNames = "animationend webkitAnimationEnd MSAnimationEnd oanimationend"
|
||||||
var animatedElsNumber = 0
|
var animatedElsNumber = 0
|
||||||
var sexyAnimationEnd = function(e) {
|
var sexyAnimationEnd = function(e) {
|
||||||
if (e.target != e.currentTarget) {
|
if (e.target !== e.currentTarget) {
|
||||||
// end triggered by an animation on a child
|
// end triggered by an animation on a child
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -44,28 +65,16 @@ module.exports = {
|
|||||||
elsToAdd.forEach(function(el) {
|
elsToAdd.forEach(function(el) {
|
||||||
el.className = el.className.replace(el.getAttribute("data-pjax-classes"), "")
|
el.className = el.className.replace(el.getAttribute("data-pjax-classes"), "")
|
||||||
el.removeAttribute("data-pjax-classes")
|
el.removeAttribute("data-pjax-classes")
|
||||||
// Pjax.off(el, animationEventNames, sexyAnimationEnd, true)
|
|
||||||
})
|
})
|
||||||
|
|
||||||
elsToAdd = null // free memory
|
elsToAdd = null // free memory
|
||||||
elsToRemove = null // free memory
|
elsToRemove = null // free memory
|
||||||
|
|
||||||
// assume the height is now useless (avoid bug since there is overflow hidden on the parent)
|
|
||||||
// oldEl.style.height = "auto"
|
|
||||||
|
|
||||||
// this is to trigger some repaint (example: picturefill)
|
// this is to trigger some repaint (example: picturefill)
|
||||||
this.onSwitch()
|
this.onSwitch()
|
||||||
// Pjax.trigger(window, "scroll")
|
|
||||||
}
|
}
|
||||||
}.bind(this)
|
}.bind(this)
|
||||||
|
|
||||||
// Force height to be able to trigger css animation
|
|
||||||
// here we get the relevant height
|
|
||||||
// oldEl.parentNode.appendChild(newEl)
|
|
||||||
// relevantHeight = newEl.getBoundingClientRect().height
|
|
||||||
// oldEl.parentNode.removeChild(newEl)
|
|
||||||
// oldEl.style.height = oldEl.getBoundingClientRect().height + "px"
|
|
||||||
|
|
||||||
switchOptions = switchOptions || {}
|
switchOptions = switchOptions || {}
|
||||||
|
|
||||||
forEach.call(oldEl.childNodes, function(el) {
|
forEach.call(oldEl.childNodes, function(el) {
|
||||||
@@ -109,7 +118,5 @@ module.exports = {
|
|||||||
// pass all className of the parent
|
// pass all className of the parent
|
||||||
oldEl.className = newEl.className
|
oldEl.className = newEl.className
|
||||||
oldEl.appendChild(fragToAppend)
|
oldEl.appendChild(fragToAppend)
|
||||||
|
|
||||||
// oldEl.style.height = relevantHeight + "px"
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
module.exports = function(obj) {
|
module.exports = function(obj) {
|
||||||
if (null === obj || "object" != typeof obj) {
|
/* istanbul ignore if */
|
||||||
|
if (null === obj || "object" !== typeof obj) {
|
||||||
return obj
|
return obj
|
||||||
}
|
}
|
||||||
var copy = obj.constructor()
|
var copy = obj.constructor()
|
||||||
12
lib/util/contains.js
Normal file
12
lib/util/contains.js
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
module.exports = function contains(doc, selectors, el) {
|
||||||
|
for (var i = 0; i < selectors.length; i++) {
|
||||||
|
var selectedEls = doc.querySelectorAll(selectors[i])
|
||||||
|
for (var j = 0; j < selectedEls.length; j++) {
|
||||||
|
if (selectedEls[j].contains(el)) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return false
|
||||||
|
}
|
||||||
21
lib/util/extend.js
Normal file
21
lib/util/extend.js
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
module.exports = function(target) {
|
||||||
|
if (target == null) {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
var to = Object(target)
|
||||||
|
|
||||||
|
for (var i = 1; i < arguments.length; i++) {
|
||||||
|
var source = arguments[i]
|
||||||
|
|
||||||
|
if (source != null) {
|
||||||
|
for (var key in source) {
|
||||||
|
// Avoid bugs when hasOwnProperty is shadowed
|
||||||
|
if (Object.prototype.hasOwnProperty.call(source, key)) {
|
||||||
|
to[key] = source[key]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return to
|
||||||
|
}
|
||||||
1
lib/util/noop.js
Normal file
1
lib/util/noop.js
Normal file
@@ -0,0 +1 @@
|
|||||||
|
module.exports = function() {}
|
||||||
10
lib/util/update-query-string.js
Normal file
10
lib/util/update-query-string.js
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
module.exports = function(uri, key, value) {
|
||||||
|
var re = new RegExp("([?&])" + key + "=.*?(&|$)", "i")
|
||||||
|
var separator = uri.indexOf("?") !== -1 ? "&" : "?"
|
||||||
|
if (uri.match(re)) {
|
||||||
|
return uri.replace(re, "$1" + key + "=" + value + "$2")
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
return uri + separator + key + "=" + value
|
||||||
|
}
|
||||||
|
}
|
||||||
70
package.json
70
package.json
@@ -1,11 +1,10 @@
|
|||||||
{
|
{
|
||||||
"name": "pjax",
|
"name": "pjax",
|
||||||
"version": "0.2.4",
|
"version": "0.2.6",
|
||||||
"description": "Easily enable fast Ajax navigation on any website (using pushState + xhr)",
|
"description": "Easily enable fast AJAX navigation on any website (using pushState + XHR)",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"pjax",
|
"pjax",
|
||||||
"push",
|
"pushstate",
|
||||||
"state",
|
|
||||||
"ajax",
|
"ajax",
|
||||||
"navigation",
|
"navigation",
|
||||||
"transition",
|
"transition",
|
||||||
@@ -13,52 +12,45 @@
|
|||||||
],
|
],
|
||||||
"repository": "https://github.com/MoOx/pjax.git",
|
"repository": "https://github.com/MoOx/pjax.git",
|
||||||
"author": "Maxime Thirouin",
|
"author": "Maxime Thirouin",
|
||||||
|
"contributors": [
|
||||||
|
"BehindTheMath",
|
||||||
|
"Robin North (http://robinnorth.co.uk)"
|
||||||
|
],
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"main": "src/pjax.js",
|
"main": "index.js",
|
||||||
"files": [
|
"files": [
|
||||||
"index.js",
|
"index.js",
|
||||||
"lib",
|
"lib",
|
||||||
"pjax.js"
|
"pjax.js",
|
||||||
|
"pjax.min.js"
|
||||||
],
|
],
|
||||||
|
"types": "index.d.ts",
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"browserify": "^3.46.0",
|
"browserify": "^15.0.0",
|
||||||
"coverify": "^1.0.6",
|
"jscs": "^3.0.7",
|
||||||
"jscs": "^1.6.2",
|
"jsdom": "^11.5.1",
|
||||||
|
"jsdom-global": "^3.0.2",
|
||||||
"jshint": "^2.5.6",
|
"jshint": "^2.5.6",
|
||||||
"npmpub": "^3.1.0",
|
"npmpub": "^3.1.0",
|
||||||
|
"nyc": "^11.4.1",
|
||||||
"opn-cli": "^3.1.0",
|
"opn-cli": "^3.1.0",
|
||||||
"serve": "1.4.0",
|
"serve": "^6.4.4",
|
||||||
"tape": "^3.0.0",
|
"tap-nyc": "^1.0.3",
|
||||||
"testling": "^1.6.1"
|
"tap-spec": "^4.1.1",
|
||||||
|
"tape": "^4.8.0",
|
||||||
|
"uglify-js": "^3.3.8"
|
||||||
},
|
},
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"lint": "jscs **/*.js && jshint . --exclude-path .gitignore",
|
"lint": "jscs . && jshint . --exclude-path .gitignore",
|
||||||
"standalone": "browserify index.js --standalone Pjax > pjax.js",
|
"standalone": "browserify index.js --standalone Pjax > pjax.js",
|
||||||
"tests": "testling",
|
"build": "yarn run standalone && uglifyjs pjax.js -o pjax.min.js",
|
||||||
"test": "npm run lint && npm run standalone && npm run tests",
|
"build-debug": "browserify index.js --debug --standalone Pjax > pjax.js",
|
||||||
"test--html": "testling --html > tests/scripts/index.html",
|
"tests": "tape -r ./tests/setup.js \"./tests/**/*.js\"",
|
||||||
"coverage": "browserify -t coverify tests/**/*.js | testling | coverify",
|
"test": "yarn run lint && yarn run tests | tap-spec",
|
||||||
"example": "opn http://localhost:3000/example/; serve .",
|
"coverage-tests": "yarn run tests | tap-nyc",
|
||||||
"prepublish": "npm run standalone",
|
"coverage": "nyc -x \"tests/**\" yarn run coverage-tests",
|
||||||
"#release": "testling does not work in a process launch by npm... :facepalm:",
|
"example": "opn http://localhost:3000/example/ && serve -p 3000 .",
|
||||||
"release": "echo \"npmpub --skip-test --dry && npm test && npmpub --skip-test --skip-cleanup\""
|
"prepublish": "yarn run build",
|
||||||
},
|
"release": "npmpub"
|
||||||
"testling": {
|
|
||||||
"files": "tests/**/*.js",
|
|
||||||
"browsers": [
|
|
||||||
"ie/10..latest",
|
|
||||||
"firefox/4.0",
|
|
||||||
"firefox/latest",
|
|
||||||
"firefox/nightly",
|
|
||||||
"chrome/10",
|
|
||||||
"chrome/latest",
|
|
||||||
"chrome/canary",
|
|
||||||
"opera/12..latest",
|
|
||||||
"opera/next",
|
|
||||||
"safari/5.1..latest",
|
|
||||||
"ipad/6.0..latest",
|
|
||||||
"iphone/6.0..latest",
|
|
||||||
"android-browser/4.2..latest"
|
|
||||||
]
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
12496
tests/index.html
12496
tests/index.html
File diff suppressed because one or more lines are too long
56
tests/lib/abort-request.js
Normal file
56
tests/lib/abort-request.js
Normal file
@@ -0,0 +1,56 @@
|
|||||||
|
var tape = require("tape")
|
||||||
|
|
||||||
|
var abortRequest = require("../../lib/abort-request.js")
|
||||||
|
var sendRequest = require("../../lib/send-request.js")
|
||||||
|
|
||||||
|
// Polyfill responseURL property into XMLHttpRequest if it doesn't exist,
|
||||||
|
// just for the purposes of this test
|
||||||
|
// This polyfill is not complete; it won't show the updated location if a
|
||||||
|
// redirection occurred, but it's fine for our purposes.
|
||||||
|
if (!("responseURL" in XMLHttpRequest.prototype)) {
|
||||||
|
var nativeOpen = XMLHttpRequest.prototype.open
|
||||||
|
XMLHttpRequest.prototype.open = function(method, url) {
|
||||||
|
this.responseURL = url
|
||||||
|
return nativeOpen.apply(this, arguments)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
tape("test aborting xhr request", function(t) {
|
||||||
|
var requestCacheBust = sendRequest.bind({
|
||||||
|
options: {
|
||||||
|
cacheBust: true
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
t.test("- pending request is aborted", function(t) {
|
||||||
|
var r = requestCacheBust("https://httpbin.org/delay/10", {}, function() {
|
||||||
|
t.fail("xhr was not aborted")
|
||||||
|
})
|
||||||
|
t.equal(r.readyState, 1, "xhr readyState is '1' (SENT)")
|
||||||
|
abortRequest(r)
|
||||||
|
t.equal(r.readyState, 0, "xhr readyState is '0' (ABORTED)")
|
||||||
|
t.equal(r.status, 0, "xhr HTTP status is '0' (ABORTED)")
|
||||||
|
t.equal(r.responseText, "", "xhr response is empty")
|
||||||
|
t.end()
|
||||||
|
})
|
||||||
|
t.test("- request is not aborted if it has already completed", function(t) {
|
||||||
|
var r = requestCacheBust("https://httpbin.org/get", {}, function() {
|
||||||
|
abortRequest(r)
|
||||||
|
t.equal(r.readyState, 4, "xhr readyState is '4' (DONE)")
|
||||||
|
t.equal(r.status, 200, "xhr HTTP status is '200' (OK)")
|
||||||
|
t.end()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
t.test("- request is not aborted if it is undefined", function(t) {
|
||||||
|
var r
|
||||||
|
try {
|
||||||
|
abortRequest(r)
|
||||||
|
}
|
||||||
|
catch (e) {
|
||||||
|
t.fail("aborting an undefined request threw an error")
|
||||||
|
}
|
||||||
|
t.equal(typeof r, "undefined", "undefined xhr was ignored")
|
||||||
|
t.end()
|
||||||
|
})
|
||||||
|
t.end()
|
||||||
|
})
|
||||||
@@ -1,17 +0,0 @@
|
|||||||
var tape = require("tape")
|
|
||||||
|
|
||||||
var clone = require("../../lib/clone")
|
|
||||||
|
|
||||||
tape("test clone method", function(t) {
|
|
||||||
var obj = {one: 1, two: 2}
|
|
||||||
var cloned = clone(obj)
|
|
||||||
|
|
||||||
t.notEqual(obj, cloned, "cloned object isn't the object")
|
|
||||||
|
|
||||||
t.same(obj, cloned, "cloned object have the same values than object")
|
|
||||||
|
|
||||||
cloned.tree = 3
|
|
||||||
t.notSame(obj, cloned, "modified cloned object haven't the same values than object")
|
|
||||||
|
|
||||||
t.end()
|
|
||||||
})
|
|
||||||
@@ -13,10 +13,11 @@ tape("test evalScript method", function(t) {
|
|||||||
evalScript(script)
|
evalScript(script)
|
||||||
t.equal(document.body.className, "executed", "script has been properly executed")
|
t.equal(document.body.className, "executed", "script has been properly executed")
|
||||||
|
|
||||||
// script.innerHTML = "document.write('failure')"
|
script.innerHTML = "document.write('failure')"
|
||||||
// var bodyText = document.body.text
|
var bodyText = "document.write hasn't been executed"
|
||||||
// evalScript(script)
|
document.body.text = bodyText
|
||||||
// t.equal(document.body.text, bodyText, "document.write hasn't been executed")
|
evalScript(script)
|
||||||
|
t.equal(document.body.text, bodyText, "document.write hasn't been executed")
|
||||||
|
|
||||||
t.end()
|
t.end()
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -7,8 +7,7 @@ var trigger = require("../../lib/events/trigger")
|
|||||||
var el = document.createElement("div")
|
var el = document.createElement("div")
|
||||||
var el2 = document.createElement("span")
|
var el2 = document.createElement("span")
|
||||||
var els = [el, el2]
|
var els = [el, el2]
|
||||||
// var eventType2 = "resize"
|
|
||||||
// var eventsType = "click resize"
|
|
||||||
var classCb = function() {
|
var classCb = function() {
|
||||||
this.className += "on"
|
this.className += "on"
|
||||||
}
|
}
|
||||||
@@ -92,17 +91,18 @@ tape("test events on/off/trigger for multiple elements, multiple events", functi
|
|||||||
})
|
})
|
||||||
|
|
||||||
tape("test events on top level elements", function(t) {
|
tape("test events on top level elements", function(t) {
|
||||||
var el = document;
|
var el = document
|
||||||
|
|
||||||
el.className = ""
|
el.className = ""
|
||||||
on(el, "click", classCb)
|
on(el, "click", classCb)
|
||||||
trigger(el, "click")
|
trigger(el, "click")
|
||||||
t.equal(el.className, "on", "attached callback has been fired properly on document")
|
t.equal(el.className, "on", "attached callback has been fired properly on document")
|
||||||
|
|
||||||
el = window;
|
el = window
|
||||||
|
|
||||||
el.className = ""
|
el.className = ""
|
||||||
on(el, "click", classCb)
|
// With jsdom, the default this is global, not window, so we need to explicitly bind to window.
|
||||||
|
on(el, "click", classCb.bind(window))
|
||||||
trigger(el, "click")
|
trigger(el, "click")
|
||||||
t.equal(el.className, "on", "attached callback has been fired properly on window")
|
t.equal(el.className, "on", "attached callback has been fired properly on window")
|
||||||
|
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ var tape = require("tape")
|
|||||||
|
|
||||||
var executeScripts = require("../../lib/execute-scripts")
|
var executeScripts = require("../../lib/execute-scripts")
|
||||||
|
|
||||||
tape("test executeScripts method", function(t) {
|
tape("test executeScripts method when the script tag is inside a container", function(t) {
|
||||||
document.body.className = ""
|
document.body.className = ""
|
||||||
|
|
||||||
var container = document.createElement("div")
|
var container = document.createElement("div")
|
||||||
@@ -14,3 +14,16 @@ tape("test executeScripts method", function(t) {
|
|||||||
|
|
||||||
t.end()
|
t.end()
|
||||||
})
|
})
|
||||||
|
|
||||||
|
tape("test executeScripts method with just a script tag", function(t) {
|
||||||
|
document.body.className = ""
|
||||||
|
|
||||||
|
var script = document.createElement("script")
|
||||||
|
script.innerHTML = "document.body.className = 'executed correctly';"
|
||||||
|
|
||||||
|
t.equal(document.body.className, "", "script hasn't been executed yet")
|
||||||
|
executeScripts(script)
|
||||||
|
t.equal(document.body.className, "executed correctly", "script has been properly executed")
|
||||||
|
|
||||||
|
t.end()
|
||||||
|
})
|
||||||
|
|||||||
49
tests/lib/parse-options.js
Normal file
49
tests/lib/parse-options.js
Normal file
@@ -0,0 +1,49 @@
|
|||||||
|
var tape = require("tape")
|
||||||
|
|
||||||
|
var parseOptions = require("../../lib/parse-options.js")
|
||||||
|
tape("test parse initalization options function", function(t) {
|
||||||
|
t.test("- default options", function(t) {
|
||||||
|
var pjax = {}
|
||||||
|
pjax.options = parseOptions({})
|
||||||
|
|
||||||
|
t.equal(pjax.options.elements, "a[href], form[action]")
|
||||||
|
t.equal(pjax.options.selectors.length, 2, "selectors length")
|
||||||
|
t.equal(pjax.options.selectors[0], "title")
|
||||||
|
t.equal(pjax.options.selectors[1], ".js-Pjax")
|
||||||
|
|
||||||
|
t.equal(typeof pjax.options.switches, "object")
|
||||||
|
t.equal(Object.keys(pjax.options.switches).length, 2)// head and body
|
||||||
|
|
||||||
|
t.equal(typeof pjax.options.switchesOptions, "object")
|
||||||
|
t.equal(Object.keys(pjax.options.switchesOptions).length, 0)
|
||||||
|
|
||||||
|
t.equal(pjax.options.history, true)
|
||||||
|
t.equal(typeof pjax.options.analytics, "function")
|
||||||
|
t.equal(pjax.options.scrollTo, 0)
|
||||||
|
t.equal(pjax.options.scrollRestoration, true)
|
||||||
|
t.equal(pjax.options.cacheBust, true)
|
||||||
|
t.equal(pjax.options.debug, false)
|
||||||
|
t.equal(pjax.options.currentUrlFullReload, false)
|
||||||
|
t.end()
|
||||||
|
})
|
||||||
|
|
||||||
|
// verify analytics always ends up as a function even when passed not a function
|
||||||
|
t.test("- analytics is a function", function(t) {
|
||||||
|
var pjax = {}
|
||||||
|
pjax.options = parseOptions({analytics: "some string"})
|
||||||
|
|
||||||
|
t.deepEqual(typeof pjax.options.analytics, "function")
|
||||||
|
t.end()
|
||||||
|
})
|
||||||
|
|
||||||
|
// verify that the value false for scrollTo is not squashed
|
||||||
|
t.test("- scrollTo remains false", function(t) {
|
||||||
|
var pjax = {}
|
||||||
|
pjax.options = parseOptions({scrollTo: false})
|
||||||
|
|
||||||
|
t.deepEqual(pjax.options.scrollTo, false)
|
||||||
|
t.end()
|
||||||
|
})
|
||||||
|
|
||||||
|
t.end()
|
||||||
|
})
|
||||||
184
tests/lib/proto/attach-form.js
Normal file
184
tests/lib/proto/attach-form.js
Normal file
@@ -0,0 +1,184 @@
|
|||||||
|
var tape = require("tape")
|
||||||
|
|
||||||
|
var on = require("../../../lib/events/on")
|
||||||
|
var trigger = require("../../../lib/events/trigger")
|
||||||
|
var attachForm = require("../../../lib/proto/attach-form")
|
||||||
|
|
||||||
|
var attr = "data-pjax-state"
|
||||||
|
|
||||||
|
tape("test attach form prototype method", function(t) {
|
||||||
|
var form = document.createElement("form")
|
||||||
|
var loadUrlCalled = false
|
||||||
|
|
||||||
|
attachForm.call({
|
||||||
|
options: {
|
||||||
|
currentUrlFullReload: true
|
||||||
|
},
|
||||||
|
loadUrl: function() {
|
||||||
|
loadUrlCalled = true
|
||||||
|
}
|
||||||
|
}, form)
|
||||||
|
|
||||||
|
var internalUri = window.location.protocol + "//" + window.location.host + window.location.pathname + window.location.search
|
||||||
|
|
||||||
|
form.action = "http://external.com/"
|
||||||
|
trigger(form, "submit")
|
||||||
|
t.equal(form.getAttribute(attr), "external", "external url stop behavior")
|
||||||
|
|
||||||
|
form.action = internalUri + "#anchor"
|
||||||
|
trigger(form, "submit")
|
||||||
|
t.equal(form.getAttribute(attr), "anchor", "internal anchor stop behavior")
|
||||||
|
|
||||||
|
window.location.hash = "#anchor"
|
||||||
|
form.action = internalUri + "#another-anchor"
|
||||||
|
trigger(form, "submit")
|
||||||
|
t.equal(form.getAttribute(attr), "anchor", "different anchors stop behavior")
|
||||||
|
window.location.hash = ""
|
||||||
|
|
||||||
|
form.action = internalUri + "#"
|
||||||
|
trigger(form, "submit")
|
||||||
|
t.equal(form.getAttribute(attr), "anchor-empty", "empty anchor stop behavior")
|
||||||
|
|
||||||
|
form.action = window.location.href
|
||||||
|
trigger(form, "submit")
|
||||||
|
t.equal(form.getAttribute(attr), "reload", "submitting when currentUrlFullReload is true will submit normally, without XHR")
|
||||||
|
t.equal(loadUrlCalled, false, "loadUrl() not called")
|
||||||
|
|
||||||
|
form.action = window.location.protocol + "//" + window.location.host + "/internal"
|
||||||
|
form.method = "POST"
|
||||||
|
trigger(form, "submit")
|
||||||
|
t.equal(form.getAttribute(attr), "submit", "triggering a POST request to the next page")
|
||||||
|
t.equal(loadUrlCalled, true, "loadUrl() called correctly")
|
||||||
|
|
||||||
|
loadUrlCalled = false
|
||||||
|
form.setAttribute(attr, "")
|
||||||
|
form.action = window.location.protocol + "//" + window.location.host + "/internal"
|
||||||
|
form.method = "GET"
|
||||||
|
trigger(form, "submit")
|
||||||
|
t.equal(form.getAttribute(attr), "submit", "triggering a GET request to the next page")
|
||||||
|
t.equal(loadUrlCalled, true, "loadUrl() called correctly")
|
||||||
|
|
||||||
|
t.end()
|
||||||
|
})
|
||||||
|
|
||||||
|
tape("test attach form preventDefaulted events", function(t) {
|
||||||
|
var loadUrlCalled = false
|
||||||
|
var form = document.createElement("form")
|
||||||
|
|
||||||
|
// This needs to be before the call to attachForm()
|
||||||
|
on(form, "submit", function(event) { event.preventDefault() })
|
||||||
|
|
||||||
|
attachForm.call({
|
||||||
|
options: {},
|
||||||
|
loadUrl: function() {
|
||||||
|
loadUrlCalled = true
|
||||||
|
}
|
||||||
|
}, form)
|
||||||
|
|
||||||
|
form.action = "#"
|
||||||
|
trigger(form, "submit")
|
||||||
|
t.equal(loadUrlCalled, false, "events that are preventDefaulted should not fire callback")
|
||||||
|
|
||||||
|
t.end()
|
||||||
|
})
|
||||||
|
|
||||||
|
tape("test options are not modified by attachForm", function(t) {
|
||||||
|
var form = document.createElement("form")
|
||||||
|
var options = {foo: "bar"}
|
||||||
|
var loadUrl = function() {}
|
||||||
|
|
||||||
|
attachForm.call({options: options, loadUrl: loadUrl}, form)
|
||||||
|
|
||||||
|
form.action = window.location.protocol + "//" + window.location.host + window.location.pathname + window.location.search
|
||||||
|
form.method = "GET"
|
||||||
|
trigger(form, "submit")
|
||||||
|
|
||||||
|
t.equal(1, Object.keys(options).length, "options object that is passed in should not be modified")
|
||||||
|
t.equal("bar", options.foo, "options object that is passed in should not be modified")
|
||||||
|
|
||||||
|
t.end()
|
||||||
|
})
|
||||||
|
|
||||||
|
tape("test submit triggered by keyboard", function(t) {
|
||||||
|
var form = document.createElement("form")
|
||||||
|
var pjax = {
|
||||||
|
options: {},
|
||||||
|
loadUrl: function() {
|
||||||
|
t.equal(form.getAttribute(attr), "submit", "triggering a internal link actually submits the form")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
t.plan(2)
|
||||||
|
|
||||||
|
attachForm.call(pjax, form)
|
||||||
|
|
||||||
|
form.action = window.location.protocol + "//" + window.location.host + "/internal"
|
||||||
|
|
||||||
|
trigger(form, "keyup", {keyCode: 14})
|
||||||
|
t.equal(form.getAttribute(attr), "", "keycode other than 13 doesn't trigger anything")
|
||||||
|
|
||||||
|
trigger(form, "keyup", {keyCode: 13})
|
||||||
|
// see loadUrl defined above
|
||||||
|
|
||||||
|
t.end()
|
||||||
|
})
|
||||||
|
|
||||||
|
tape("test form elements parsed correctly", function(t) {
|
||||||
|
t.plan(1)
|
||||||
|
|
||||||
|
var form = document.createElement("form")
|
||||||
|
var input = document.createElement("input")
|
||||||
|
input.name = "input"
|
||||||
|
input.value = "value"
|
||||||
|
form.appendChild(input)
|
||||||
|
|
||||||
|
var params = [{
|
||||||
|
name: "input",
|
||||||
|
value: "value"
|
||||||
|
}]
|
||||||
|
var pjax = {
|
||||||
|
options: {},
|
||||||
|
loadUrl: function(href, options) {
|
||||||
|
t.same(options.requestOptions.requestParams, params, "form elements parsed correctly")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
attachForm.call(pjax, form)
|
||||||
|
|
||||||
|
form.action = window.location.protocol + "//" + window.location.host + "/internal"
|
||||||
|
|
||||||
|
trigger(form, "submit")
|
||||||
|
// see loadUrl defined above
|
||||||
|
|
||||||
|
t.end()
|
||||||
|
})
|
||||||
|
|
||||||
|
tape("test form.enctype=\"multipart/form-data\"", function(t) {
|
||||||
|
t.plan(4)
|
||||||
|
|
||||||
|
var form = document.createElement("form")
|
||||||
|
form.enctype = "multipart/form-data"
|
||||||
|
var input = document.createElement("input")
|
||||||
|
input.name = "input"
|
||||||
|
input.value = "value"
|
||||||
|
form.appendChild(input)
|
||||||
|
|
||||||
|
var pjax = {
|
||||||
|
options: {},
|
||||||
|
loadUrl: function(href, options) {
|
||||||
|
t.equals(options.requestOptions.requestParams, undefined, "form elements not parsed manually")
|
||||||
|
t.true(options.requestOptions.formData instanceof FormData, "requestOptions.formData is a FormData")
|
||||||
|
t.equals(Array.from(options.requestOptions.formData.entries()).length, 1, "correct number of FormData elements")
|
||||||
|
t.equals(options.requestOptions.formData.get("input"), "value", "FormData element value set correctly")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
attachForm.call(pjax, form)
|
||||||
|
|
||||||
|
form.action = window.location.protocol + "//" + window.location.host + "/internal"
|
||||||
|
|
||||||
|
trigger(form, "submit")
|
||||||
|
// see loadUrl defined above
|
||||||
|
|
||||||
|
t.end()
|
||||||
|
})
|
||||||
@@ -4,27 +4,22 @@ var on = require("../../../lib/events/on")
|
|||||||
var trigger = require("../../../lib/events/trigger")
|
var trigger = require("../../../lib/events/trigger")
|
||||||
var attachLink = require("../../../lib/proto/attach-link")
|
var attachLink = require("../../../lib/proto/attach-link")
|
||||||
|
|
||||||
var a = document.createElement("a")
|
var attr = "data-pjax-state"
|
||||||
var attr = "data-pjax-click-state"
|
|
||||||
var preventDefault = function(e) { e.preventDefault() }
|
|
||||||
|
|
||||||
tape("test attach link prototype method", function(t) {
|
tape("test attach link prototype method", function(t) {
|
||||||
t.plan(7)
|
var a = document.createElement("a")
|
||||||
|
var loadUrlCalled = false
|
||||||
|
|
||||||
attachLink.call({
|
attachLink.call({
|
||||||
options: {},
|
options: {},
|
||||||
reload: function() {
|
|
||||||
t.equal(a.getAttribute(attr), "reload", "triggering exact same url reload the page")
|
|
||||||
},
|
|
||||||
loadUrl: function() {
|
loadUrl: function() {
|
||||||
t.equal(a.getAttribute(attr), "load", "triggering a internal link actually load the page")
|
loadUrlCalled = true
|
||||||
}
|
}
|
||||||
}, a)
|
}, a)
|
||||||
|
|
||||||
var internalUri = window.location.protocol + "//" + window.location.host + window.location.pathname + window.location.search
|
var internalUri = window.location.protocol + "//" + window.location.host + window.location.pathname + window.location.search
|
||||||
|
|
||||||
a.href = internalUri
|
a.href = internalUri
|
||||||
on(a, "click", preventDefault) // to avoid link to be open (break testing env)
|
|
||||||
trigger(a, "click", {metaKey: true})
|
trigger(a, "click", {metaKey: true})
|
||||||
t.equal(a.getAttribute(attr), "modifier", "event key modifier stop behavior")
|
t.equal(a.getAttribute(attr), "modifier", "event key modifier stop behavior")
|
||||||
|
|
||||||
@@ -32,46 +27,117 @@ tape("test attach link prototype method", function(t) {
|
|||||||
trigger(a, "click")
|
trigger(a, "click")
|
||||||
t.equal(a.getAttribute(attr), "external", "external url stop behavior")
|
t.equal(a.getAttribute(attr), "external", "external url stop behavior")
|
||||||
|
|
||||||
|
window.location.hash = "#anchor"
|
||||||
a.href = internalUri + "#anchor"
|
a.href = internalUri + "#anchor"
|
||||||
trigger(a, "click")
|
trigger(a, "click")
|
||||||
t.equal(a.getAttribute(attr), "anchor-present", "internal anchor stop behavior")
|
t.equal(a.getAttribute(attr), "anchor", "internal anchor stop behavior")
|
||||||
|
|
||||||
window.location.hash = "#anchor"
|
|
||||||
a.href = internalUri + "#another-anchor"
|
a.href = internalUri + "#another-anchor"
|
||||||
trigger(a, "click")
|
trigger(a, "click")
|
||||||
t.notEqual(a.getAttribute(attr), "anchor", "differents anchors stop behavior")
|
t.equal(a.getAttribute(attr), "anchor", "different anchors stop behavior")
|
||||||
window.location.hash = ""
|
window.location.hash = ""
|
||||||
|
|
||||||
a.href = internalUri + "#"
|
a.href = internalUri + "#"
|
||||||
trigger(a, "click")
|
trigger(a, "click")
|
||||||
t.equal(a.getAttribute(attr), "anchor-empty", "empty anchor stop behavior")
|
t.equal(a.getAttribute(attr), "anchor-empty", "empty anchor stop behavior")
|
||||||
|
|
||||||
a.href = internalUri
|
|
||||||
trigger(a, "click")
|
|
||||||
// see reload defined above
|
|
||||||
|
|
||||||
a.href = window.location.protocol + "//" + window.location.host + "/internal"
|
a.href = window.location.protocol + "//" + window.location.host + "/internal"
|
||||||
trigger(a, "click")
|
trigger(a, "click")
|
||||||
// see loadUrl defined above
|
t.equals(a.getAttribute(attr), "load", "triggering an internal link sets the state attribute to 'load'")
|
||||||
|
t.equals(loadUrlCalled, true, "triggering an internal link actually loads the page")
|
||||||
|
|
||||||
t.end()
|
t.end()
|
||||||
})
|
})
|
||||||
|
|
||||||
tape("test attach link preventDefaulted events", function(t) {
|
tape("test attach link preventDefaulted events", function(t) {
|
||||||
var callbacked = false
|
var loadUrlCalled = false
|
||||||
var a = document.createElement("a")
|
var a = document.createElement("a")
|
||||||
|
|
||||||
|
// This needs to be before the call to attachLink()
|
||||||
|
on(a, "click", function(event) {
|
||||||
|
event.preventDefault()
|
||||||
|
})
|
||||||
|
|
||||||
attachLink.call({
|
attachLink.call({
|
||||||
options: {},
|
options: {},
|
||||||
loadUrl: function() {
|
loadUrl: function() {
|
||||||
callbacked = true
|
loadUrlCalled = true
|
||||||
}
|
}
|
||||||
}, a)
|
}, a)
|
||||||
|
|
||||||
a.href = "#"
|
a.href = "#"
|
||||||
on(a, "click", preventDefault)
|
|
||||||
trigger(a, "click")
|
trigger(a, "click")
|
||||||
t.equal(callbacked, false, "events that are preventDefaulted should not fire callback")
|
t.equal(loadUrlCalled, false, "events that are preventDefaulted should not fire callback")
|
||||||
|
|
||||||
|
t.end()
|
||||||
|
})
|
||||||
|
|
||||||
|
tape("test options are not modified by attachLink", function(t) {
|
||||||
|
var a = document.createElement("a")
|
||||||
|
var options = {foo: "bar"}
|
||||||
|
var loadUrl = function() {}
|
||||||
|
|
||||||
|
attachLink.call({options: options, loadUrl: loadUrl}, a)
|
||||||
|
|
||||||
|
a.href = window.location.protocol + "//" + window.location.host + window.location.pathname + window.location.search
|
||||||
|
|
||||||
|
trigger(a, "click")
|
||||||
|
|
||||||
|
t.equal(1, Object.keys(options).length, "options object that is passed in should not be modified")
|
||||||
|
t.equal("bar", options.foo, "options object that is passed in should not be modified")
|
||||||
|
|
||||||
|
t.end()
|
||||||
|
})
|
||||||
|
|
||||||
|
tape("test link triggered by keyboard", function(t) {
|
||||||
|
var a = document.createElement("a")
|
||||||
|
var pjax = {
|
||||||
|
options: {},
|
||||||
|
loadUrl: function() {
|
||||||
|
t.equal(a.getAttribute(attr), "load", "triggering a internal link actually loads the page")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
t.plan(3)
|
||||||
|
|
||||||
|
attachLink.call(pjax, a)
|
||||||
|
|
||||||
|
a.href = window.location.protocol + "//" + window.location.host + "/internal"
|
||||||
|
|
||||||
|
trigger(a, "keyup", {keyCode: 14})
|
||||||
|
t.equal(a.getAttribute(attr), "", "keycode other than 13 doesn't trigger anything")
|
||||||
|
|
||||||
|
trigger(a, "keyup", {keyCode: 13, metaKey: true})
|
||||||
|
t.equal(a.getAttribute(attr), "modifier", "event key modifier stop behavior")
|
||||||
|
|
||||||
|
trigger(a, "keyup", {keyCode: 13})
|
||||||
|
// see loadUrl defined above
|
||||||
|
|
||||||
|
t.end()
|
||||||
|
})
|
||||||
|
|
||||||
|
tape("test link with the same URL as the current one, when currentUrlFullReload set to true", function(t) {
|
||||||
|
var a = document.createElement("a")
|
||||||
|
var pjax = {
|
||||||
|
options: {
|
||||||
|
currentUrlFullReload: true
|
||||||
|
},
|
||||||
|
reload: function() {
|
||||||
|
t.pass("this.reload() was called correctly")
|
||||||
|
},
|
||||||
|
loadUrl: function() {
|
||||||
|
t.fail("loadUrl() was called wrongly")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
t.plan(2)
|
||||||
|
|
||||||
|
attachLink.call(pjax, a)
|
||||||
|
|
||||||
|
a.href = window.location.href
|
||||||
|
|
||||||
|
trigger(a, "click")
|
||||||
|
t.equal(a.getAttribute(attr), "reload", "reload stop behavior")
|
||||||
|
|
||||||
t.end()
|
t.end()
|
||||||
})
|
})
|
||||||
|
|||||||
208
tests/lib/proto/handle-response.js
Normal file
208
tests/lib/proto/handle-response.js
Normal file
@@ -0,0 +1,208 @@
|
|||||||
|
var tape = require("tape")
|
||||||
|
|
||||||
|
var handleReponse = require("../../../lib/proto/handle-response")
|
||||||
|
var noop = require("../../../lib/util/noop")
|
||||||
|
|
||||||
|
var href = "https://example.org/"
|
||||||
|
|
||||||
|
var storeEventHandler
|
||||||
|
var pjaxErrorEventTriggerTest
|
||||||
|
|
||||||
|
tape("test events triggered when handleResponse(false) is called", function(t) {
|
||||||
|
t.plan(3)
|
||||||
|
|
||||||
|
var pjax = {
|
||||||
|
options: {
|
||||||
|
test: 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var events = []
|
||||||
|
|
||||||
|
storeEventHandler = function(e) {
|
||||||
|
events.push(e.type)
|
||||||
|
|
||||||
|
t.equal(e.test, 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
document.addEventListener("pjax:complete", storeEventHandler)
|
||||||
|
document.addEventListener("pjax:error", storeEventHandler)
|
||||||
|
|
||||||
|
handleReponse.bind(pjax)(false, null)
|
||||||
|
|
||||||
|
t.same(events, ["pjax:complete", "pjax:error"], "calling handleResponse(false) triggers 'pjax:complete' and 'pjax:error'")
|
||||||
|
|
||||||
|
t.end()
|
||||||
|
})
|
||||||
|
|
||||||
|
tape("test when handleResponse() is called normally", function(t) {
|
||||||
|
var pjax = {
|
||||||
|
options: {
|
||||||
|
test: 1
|
||||||
|
},
|
||||||
|
loadContent: noop,
|
||||||
|
state: {}
|
||||||
|
}
|
||||||
|
|
||||||
|
var request = {
|
||||||
|
getResponseHeader: noop
|
||||||
|
}
|
||||||
|
|
||||||
|
handleReponse.bind(pjax)("", request, "href")
|
||||||
|
|
||||||
|
delete window.history.state.uid
|
||||||
|
t.same(window.history.state, {
|
||||||
|
url: href,
|
||||||
|
title: "",
|
||||||
|
scrollPos: [0, 0]
|
||||||
|
}, "window.history.state is set correctly")
|
||||||
|
t.equals(pjax.state.href, "href", "this.state.href is set correctly")
|
||||||
|
t.equals(Object.keys(pjax.state.options).length, 2, "this.state.options is set correctly")
|
||||||
|
t.same(pjax.state.options.request, request, "this.state.options is set correctly")
|
||||||
|
t.equals(pjax.state.options.test, 1, "this.state.options is set correctly")
|
||||||
|
|
||||||
|
t.end()
|
||||||
|
})
|
||||||
|
|
||||||
|
tape("test when handleResponse() is called normally with request.responseURL", function(t) {
|
||||||
|
var pjax = {
|
||||||
|
options: {},
|
||||||
|
loadContent: noop,
|
||||||
|
state: {}
|
||||||
|
}
|
||||||
|
|
||||||
|
var request = {
|
||||||
|
responseURL: href + "1",
|
||||||
|
getResponseHeader: noop
|
||||||
|
}
|
||||||
|
|
||||||
|
handleReponse.bind(pjax)("", request, "")
|
||||||
|
|
||||||
|
t.equals(pjax.state.href, request.responseURL, "this.state.href is set correctly")
|
||||||
|
|
||||||
|
t.end()
|
||||||
|
})
|
||||||
|
|
||||||
|
tape("test when handleResponse() is called normally with X-PJAX-URL", function(t) {
|
||||||
|
var pjax = {
|
||||||
|
options: {},
|
||||||
|
loadContent: noop,
|
||||||
|
state: {}
|
||||||
|
}
|
||||||
|
|
||||||
|
var request = {
|
||||||
|
getResponseHeader: function(header) {
|
||||||
|
if (header === "X-PJAX-URL") {
|
||||||
|
return href + "2"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
handleReponse.bind(pjax)("", request, "")
|
||||||
|
|
||||||
|
t.equals(pjax.state.href, href + "2", "this.state.href is set correctly")
|
||||||
|
|
||||||
|
t.end()
|
||||||
|
})
|
||||||
|
|
||||||
|
tape("test when handleResponse() is called normally with X-XHR-Redirected-To", function(t) {
|
||||||
|
var pjax = {
|
||||||
|
options: {},
|
||||||
|
loadContent: noop,
|
||||||
|
state: {}
|
||||||
|
}
|
||||||
|
|
||||||
|
var request = {
|
||||||
|
getResponseHeader: function(header) {
|
||||||
|
if (header === "X-XHR-Redirected-To") {
|
||||||
|
return href + "3"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
handleReponse.bind(pjax)("", request, "")
|
||||||
|
|
||||||
|
t.equals(pjax.state.href, href + "3", "this.state.href is set correctly")
|
||||||
|
|
||||||
|
t.end()
|
||||||
|
})
|
||||||
|
|
||||||
|
tape("test when handleResponse() is called normally with a hash", function(t) {
|
||||||
|
var pjax = {
|
||||||
|
options: {},
|
||||||
|
loadContent: noop,
|
||||||
|
state: {}
|
||||||
|
}
|
||||||
|
|
||||||
|
var request = {
|
||||||
|
responseURL: href + "2",
|
||||||
|
getResponseHeader: noop
|
||||||
|
}
|
||||||
|
|
||||||
|
handleReponse.bind(pjax)("", request, href + "1#test")
|
||||||
|
|
||||||
|
t.equals(pjax.state.href, href + "2#test", "this.state.href is set correctly")
|
||||||
|
|
||||||
|
t.end()
|
||||||
|
})
|
||||||
|
|
||||||
|
tape("test try...catch for loadContent() when options.debug is true", function(t) {
|
||||||
|
t.plan(2)
|
||||||
|
|
||||||
|
var pjax = {
|
||||||
|
options: {},
|
||||||
|
loadContent: noop,
|
||||||
|
state: {}
|
||||||
|
}
|
||||||
|
|
||||||
|
var request = {
|
||||||
|
getResponseHeader: noop
|
||||||
|
}
|
||||||
|
|
||||||
|
pjax.loadContent = function() {
|
||||||
|
throw new Error()
|
||||||
|
}
|
||||||
|
pjax.options.debug = true
|
||||||
|
|
||||||
|
document.removeEventListener("pjax:error", storeEventHandler)
|
||||||
|
pjaxErrorEventTriggerTest = function() {
|
||||||
|
t.pass("pjax:error event triggered")
|
||||||
|
}
|
||||||
|
document.addEventListener("pjax:error", pjaxErrorEventTriggerTest)
|
||||||
|
|
||||||
|
t.throws(function() {
|
||||||
|
handleReponse.bind(pjax)("", request, "")
|
||||||
|
}, Error, "error is rethrown")
|
||||||
|
|
||||||
|
t.end()
|
||||||
|
})
|
||||||
|
|
||||||
|
tape("test try...catch for loadContent()", function(t) {
|
||||||
|
t.plan(2)
|
||||||
|
|
||||||
|
var pjax = {
|
||||||
|
options: {},
|
||||||
|
loadContent: noop,
|
||||||
|
state: {}
|
||||||
|
}
|
||||||
|
|
||||||
|
var request = {
|
||||||
|
getResponseHeader: noop
|
||||||
|
}
|
||||||
|
|
||||||
|
pjax.loadContent = function() {
|
||||||
|
throw new Error()
|
||||||
|
}
|
||||||
|
pjax.latestChance = function() {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
pjax.options.debug = false
|
||||||
|
|
||||||
|
document.removeEventListener("pjax:error", pjaxErrorEventTriggerTest)
|
||||||
|
|
||||||
|
t.doesNotThrow(function() {
|
||||||
|
t.equals(handleReponse.bind(pjax)("", request, ""), true, "this.latestChance() is called")
|
||||||
|
}, Error, "error is not thrown")
|
||||||
|
|
||||||
|
t.end()
|
||||||
|
})
|
||||||
@@ -1,17 +1,27 @@
|
|||||||
var tape = require("tape")
|
var tape = require("tape")
|
||||||
|
|
||||||
var parseElement = require("../../../lib/proto/parse-element")
|
var parseElement = require("../../../lib/proto/parse-element")
|
||||||
var protoMock = {attachLink: function() { return true}}
|
|
||||||
|
var pjax = {
|
||||||
|
attachLink: function() { return true },
|
||||||
|
attachForm: function() { return true }
|
||||||
|
}
|
||||||
|
|
||||||
tape("test parse element prototype method", function(t) {
|
tape("test parse element prototype method", function(t) {
|
||||||
t.doesNotThrow(function() {
|
t.doesNotThrow(function() {
|
||||||
var a = document.createElement("a")
|
var a = document.createElement("a")
|
||||||
parseElement.call(protoMock, a)
|
parseElement.call(pjax, a)
|
||||||
}, "<a> element can be parsed")
|
}, "<a> element can be parsed")
|
||||||
|
|
||||||
t.throws(function() {
|
t.doesNotThrow(function() {
|
||||||
var form = document.createElement("form")
|
var form = document.createElement("form")
|
||||||
parseElement.call(protoMock, form)
|
parseElement.call(pjax, form)
|
||||||
}, "<form> cannot be used (for now)")
|
}, "<form> element can be parsed")
|
||||||
|
|
||||||
|
t.throws(function() {
|
||||||
|
var el = document.createElement("div")
|
||||||
|
parseElement.call(pjax, el)
|
||||||
|
}, "<div> element cannot be parsed")
|
||||||
|
|
||||||
t.end()
|
t.end()
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -1,73 +0,0 @@
|
|||||||
var tape = require("tape")
|
|
||||||
|
|
||||||
var parseOptions = require("../../../lib/proto/parse-options.js")
|
|
||||||
tape("test parse initalization options function", function(t) {
|
|
||||||
// via http://stackoverflow.com/questions/1173549/how-to-determine-if-an-object-is-an-object-literal-in-javascript
|
|
||||||
function isObjLiteral(_obj) {
|
|
||||||
var _test = _obj;
|
|
||||||
return ( typeof _obj !== 'object' || _obj === null ?
|
|
||||||
false :
|
|
||||||
(
|
|
||||||
(function () {
|
|
||||||
while (!false) {
|
|
||||||
if ( Object.getPrototypeOf( _test = Object.getPrototypeOf(_test) ) === null) {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return Object.getPrototypeOf(_obj) === _test;
|
|
||||||
})()
|
|
||||||
)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
function enumerableKeys(_obj) {
|
|
||||||
var c = 0;
|
|
||||||
for(var n in _obj){ n = n; c++; }
|
|
||||||
return c;
|
|
||||||
}
|
|
||||||
t.test("- default options", function(t){
|
|
||||||
var body_1 = {};
|
|
||||||
var options_1 = {};
|
|
||||||
parseOptions.apply(body_1,[options_1]);
|
|
||||||
|
|
||||||
t.deepEqual(body_1.options.elements,"a[href], form[action]");
|
|
||||||
t.deepEqual(body_1.options.selectors.length,2,"selectors length");
|
|
||||||
t.deepEqual(body_1.options.selectors[0],"title");
|
|
||||||
t.deepEqual(body_1.options.selectors[1],".js-Pjax");
|
|
||||||
|
|
||||||
t.deepEqual(isObjLiteral(body_1.options.switches),true);
|
|
||||||
t.deepEqual(enumerableKeys(body_1.options.switches),2);//head and body
|
|
||||||
|
|
||||||
t.deepEqual(isObjLiteral(body_1.options.switchesOptions),true);
|
|
||||||
t.deepEqual(enumerableKeys(body_1.options.switchesOptions),0);
|
|
||||||
|
|
||||||
t.deepEqual(body_1.options.history,true);
|
|
||||||
|
|
||||||
//TODO analytics is a little weird right now
|
|
||||||
t.deepEqual(typeof body_1.options.analytics,"function");
|
|
||||||
|
|
||||||
t.deepEqual(body_1.options.scrollTo,0);
|
|
||||||
t.deepEqual(body_1.options.cacheBust,true);
|
|
||||||
t.deepEqual(body_1.options.debug,false);
|
|
||||||
t.end();
|
|
||||||
});
|
|
||||||
|
|
||||||
//verify analytics always ends up as a function even when passed not a function
|
|
||||||
t.test("- analytics is a function", function(t){
|
|
||||||
var body_2 = {};
|
|
||||||
var options_2 = {analytics:"some string"};
|
|
||||||
parseOptions.apply(body_2,[options_2]);
|
|
||||||
|
|
||||||
t.deepEqual(typeof body_2.options.analytics,"function");
|
|
||||||
t.end();
|
|
||||||
});
|
|
||||||
//verify that the value false for scrollTo is not squashed
|
|
||||||
t.test("- scrollTo remains false", function(t){
|
|
||||||
var body_3 = {};
|
|
||||||
var options_3 = {scrollTo:false};
|
|
||||||
parseOptions.apply(body_3,[options_3]);
|
|
||||||
|
|
||||||
t.deepEqual( body_3.options.scrollTo,false);
|
|
||||||
t.end();
|
|
||||||
});
|
|
||||||
t.end()
|
|
||||||
})
|
|
||||||
@@ -1,48 +0,0 @@
|
|||||||
var tape = require("tape")
|
|
||||||
|
|
||||||
var request = require("../../lib/request.js")
|
|
||||||
|
|
||||||
// Polyfill responseURL property into XMLHttpRequest if it doesn't exist,
|
|
||||||
// just for the purposes of this test
|
|
||||||
// This polyfill is not complete; it won't show the updated location if a
|
|
||||||
// redirection occurred, but it's fine for our purposes.
|
|
||||||
if (!('responseURL' in XMLHttpRequest.prototype)) {
|
|
||||||
var nativeOpen = XMLHttpRequest.prototype.open
|
|
||||||
XMLHttpRequest.prototype.open = function (method, url) {
|
|
||||||
this.responseURL = url
|
|
||||||
return nativeOpen.apply(this, arguments)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
tape("test xhr request", function(t) {
|
|
||||||
t.test("- request is made, gets a result, and is cache-busted", function(t) {
|
|
||||||
var requestCacheBust = request.bind({
|
|
||||||
options: {
|
|
||||||
cacheBust: true,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
var r = requestCacheBust("https://api.github.com/", function(result) {
|
|
||||||
t.equal(r.responseURL.indexOf("?"), 23, "XHR URL is cache-busted when configured to be")
|
|
||||||
try {
|
|
||||||
result = JSON.parse(result)
|
|
||||||
}
|
|
||||||
catch (e) {
|
|
||||||
t.fail("xhr doesn't get a JSON response")
|
|
||||||
}
|
|
||||||
t.same(typeof result, "object", "xhr request get a result")
|
|
||||||
t.end()
|
|
||||||
})
|
|
||||||
})
|
|
||||||
t.test("- request is not cache-busted when configured not to be", function(t) {
|
|
||||||
var requestNoCacheBust = request.bind({
|
|
||||||
options: {
|
|
||||||
cacheBust: false,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
var r = requestNoCacheBust("https://api.github.com/", function() {
|
|
||||||
t.equal(r.responseURL, "https://api.github.com/", "XHR URL is left untouched")
|
|
||||||
t.end()
|
|
||||||
})
|
|
||||||
})
|
|
||||||
t.end()
|
|
||||||
})
|
|
||||||
137
tests/lib/send-request.js
Normal file
137
tests/lib/send-request.js
Normal file
@@ -0,0 +1,137 @@
|
|||||||
|
var tape = require("tape")
|
||||||
|
|
||||||
|
var sendRequest = require("../../lib/send-request.js")
|
||||||
|
|
||||||
|
// Polyfill responseURL property into XMLHttpRequest if it doesn't exist,
|
||||||
|
// just for the purposes of this test
|
||||||
|
// This polyfill is not complete; it won't show the updated location if a
|
||||||
|
// redirection occurred, but it's fine for our purposes.
|
||||||
|
if (!("responseURL" in XMLHttpRequest.prototype)) {
|
||||||
|
var nativeOpen = XMLHttpRequest.prototype.open
|
||||||
|
XMLHttpRequest.prototype.open = function(method, url) {
|
||||||
|
this.responseURL = url
|
||||||
|
return nativeOpen.apply(this, arguments)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
tape("test xhr request", function(t) {
|
||||||
|
var url = "https://httpbin.org/get"
|
||||||
|
|
||||||
|
t.test("- request is made, gets a result, and is cache-busted", function(t) {
|
||||||
|
var r = sendRequest(url, {cacheBust: true}, function(result) {
|
||||||
|
t.equal(r.responseURL.indexOf("?"), url.length, "XHR URL is cache-busted when configured to be")
|
||||||
|
try {
|
||||||
|
result = JSON.parse(result)
|
||||||
|
}
|
||||||
|
catch (e) {
|
||||||
|
t.fail("xhr doesn't get a JSON response")
|
||||||
|
}
|
||||||
|
t.same(typeof result, "object", "xhr request get a result")
|
||||||
|
t.end()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
t.test("- request is not cache-busted when configured not to be", function(t) {
|
||||||
|
var r = sendRequest(url, {}, function() {
|
||||||
|
t.equal(r.responseURL, url, "XHR URL is left untouched")
|
||||||
|
t.end()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
t.end()
|
||||||
|
})
|
||||||
|
|
||||||
|
tape("request headers are sent properly", function(t) {
|
||||||
|
var url = "https://httpbin.org/headers"
|
||||||
|
var options = {
|
||||||
|
selectors: ["div.pjax", "div.container"]
|
||||||
|
}
|
||||||
|
|
||||||
|
sendRequest(url, options, function(responseText) {
|
||||||
|
var headers = JSON.parse(responseText).headers
|
||||||
|
|
||||||
|
t.equals(headers["X-Requested-With"], "XMLHttpRequest", "X-Requested-With header is set correctly")
|
||||||
|
// Httpbin.org changes the case to 'X-Pjax'
|
||||||
|
t.equals(headers["X-Pjax"], "true", "X-PJAX header is set correctly")
|
||||||
|
t.equals(headers["X-Pjax-Selectors"], "[\"div.pjax\",\"div.container\"]", "X-PJAX-Selectors header is set correctly")
|
||||||
|
|
||||||
|
t.end()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
tape("HTTP status codes other than 200 are handled properly", function(t) {
|
||||||
|
var url = "https://httpbin.org/status/400"
|
||||||
|
|
||||||
|
sendRequest(url, {}, function(responseText, request) {
|
||||||
|
t.equals(responseText, null, "responseText is null")
|
||||||
|
t.equals(request.status, 400, "HTTP status code is correct")
|
||||||
|
|
||||||
|
t.end()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
tape.skip("XHR error is handled properly", function(t) {
|
||||||
|
var url = "https://encrypted.google.com/foobar"
|
||||||
|
|
||||||
|
sendRequest(url, {}, function(responseText) {
|
||||||
|
t.equals(responseText, null, "responseText is null")
|
||||||
|
|
||||||
|
t.end()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
tape("POST body data is sent properly", function(t) {
|
||||||
|
var url = "https://httpbin.org/post"
|
||||||
|
var params = [{
|
||||||
|
name: "test",
|
||||||
|
value: "1"
|
||||||
|
}];
|
||||||
|
var options = {
|
||||||
|
requestOptions: {
|
||||||
|
requestMethod: "POST",
|
||||||
|
requestParams: params
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
sendRequest(url, options, function(responseText) {
|
||||||
|
var response = JSON.parse(responseText)
|
||||||
|
|
||||||
|
t.same(response.form[params[0].name], params[0].value, "requestParams were sent properly")
|
||||||
|
t.equals(response.headers["Content-Type"], "application/x-www-form-urlencoded", "Content-Type header was set properly")
|
||||||
|
|
||||||
|
t.end()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
tape("GET query data is sent properly", function(t) {
|
||||||
|
var url = "https://httpbin.org/get"
|
||||||
|
var params = [{
|
||||||
|
name: "test",
|
||||||
|
value: "1"
|
||||||
|
}];
|
||||||
|
var options = {
|
||||||
|
requestOptions: {
|
||||||
|
requestParams: params
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
sendRequest(url, options, function(responseText) {
|
||||||
|
var response = JSON.parse(responseText)
|
||||||
|
|
||||||
|
t.same(response.args[params[0].name], params[0].value, "requestParams were sent properly")
|
||||||
|
|
||||||
|
t.end()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
tape("XHR timeout is handled properly", function(t) {
|
||||||
|
var url = "https://httpbin.org/delay/5"
|
||||||
|
var options = {
|
||||||
|
timeout: 1000
|
||||||
|
}
|
||||||
|
|
||||||
|
sendRequest(url, options, function(responseText) {
|
||||||
|
t.equals(responseText, null, "responseText is null")
|
||||||
|
|
||||||
|
t.end()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
@@ -1,17 +1,20 @@
|
|||||||
var tape = require("tape")
|
var tape = require("tape")
|
||||||
|
|
||||||
var switchesSelectors = require("../../lib/switches-selectors.js")
|
var switchesSelectors = require("../../lib/switches-selectors.js")
|
||||||
|
var noop = require("../../lib/util/noop")
|
||||||
|
|
||||||
|
var pjax = {
|
||||||
|
onSwitch: function() {
|
||||||
|
console.log("Switched")
|
||||||
|
},
|
||||||
|
state: {},
|
||||||
|
log: noop
|
||||||
|
}
|
||||||
|
|
||||||
// @author darylteo
|
// @author darylteo
|
||||||
tape("test switchesSelectors", function(t) {
|
tape("test switchesSelectors", function(t) {
|
||||||
// switchesSelectors relies on a higher level function callback
|
// switchesSelectors relies on a higher level function callback
|
||||||
// should really be passed in instead so I'll leave it here as a TODO:
|
// should really be passed in instead so I'll leave it here as a TODO:
|
||||||
var pjax = {
|
|
||||||
onSwitch: function() {
|
|
||||||
console.log('Switched')
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
var tmpEl = document.implementation.createHTMLDocument()
|
var tmpEl = document.implementation.createHTMLDocument()
|
||||||
|
|
||||||
// a div container is used because swapping the containers
|
// a div container is used because swapping the containers
|
||||||
@@ -29,13 +32,43 @@ tape("test switchesSelectors", function(t) {
|
|||||||
switchesSelectors.bind(pjax)(
|
switchesSelectors.bind(pjax)(
|
||||||
{}, // switches
|
{}, // switches
|
||||||
{}, // switchesOptions
|
{}, // switchesOptions
|
||||||
['p'], //selectors,
|
["p"], // selectors,
|
||||||
tmpEl, // fromEl
|
tmpEl, // fromEl
|
||||||
document, // toEl,
|
document, // toEl,
|
||||||
{} // options
|
{} // options
|
||||||
)
|
)
|
||||||
|
|
||||||
t.equals(container.innerHTML, '<p>New Text</p><span>No Change</span>', 'Elements correctly switched')
|
t.equals(container.innerHTML, "<p>New Text</p><span>No Change</span>", "Elements correctly switched")
|
||||||
|
|
||||||
|
t.end()
|
||||||
|
})
|
||||||
|
|
||||||
|
tape("test switchesSelectors when number of elements don't match", function(t) {
|
||||||
|
var newTempDoc = document.implementation.createHTMLDocument()
|
||||||
|
var originalTempDoc = document.implementation.createHTMLDocument()
|
||||||
|
|
||||||
|
// a div container is used because swapping the containers
|
||||||
|
// will generate a new element, so things get weird
|
||||||
|
// using "body" generates a lot of testling cruft that I don't
|
||||||
|
// want so let's avoid that
|
||||||
|
var container = originalTempDoc.createElement("div")
|
||||||
|
container.innerHTML = "<p>Original text</p><span>No change</span>"
|
||||||
|
originalTempDoc.body.appendChild(container)
|
||||||
|
|
||||||
|
var container2 = newTempDoc.createElement("div")
|
||||||
|
container2.innerHTML = "<p>New text</p><p>More new text</p><span>New span</span>"
|
||||||
|
newTempDoc.body.appendChild(container2)
|
||||||
|
|
||||||
|
var switchSelectorsFn = switchesSelectors.bind(pjax,
|
||||||
|
{}, // switches
|
||||||
|
{}, // switchesOptions
|
||||||
|
["p"], // selectors,
|
||||||
|
newTempDoc, // fromEl
|
||||||
|
originalTempDoc, // toEl,
|
||||||
|
{} // options
|
||||||
|
)
|
||||||
|
|
||||||
|
t.throws(switchSelectorsFn, null, "error was thrown properly since number of elements don't match")
|
||||||
|
|
||||||
t.end()
|
t.end()
|
||||||
})
|
})
|
||||||
|
|||||||
78
tests/lib/switches.js
Normal file
78
tests/lib/switches.js
Normal file
@@ -0,0 +1,78 @@
|
|||||||
|
var tape = require("tape")
|
||||||
|
var switches = require("../../lib/switches")
|
||||||
|
var noop = require("../../lib/util/noop")
|
||||||
|
|
||||||
|
tape("test outerHTML switch", function(t) {
|
||||||
|
var outerHTML = switches.outerHTML
|
||||||
|
|
||||||
|
var doc = document.implementation.createHTMLDocument()
|
||||||
|
|
||||||
|
var container = doc.createElement("div")
|
||||||
|
container.innerHTML = "<p id='p'>Original Text</p>"
|
||||||
|
doc.body.appendChild(container)
|
||||||
|
|
||||||
|
var p = doc.createElement("p")
|
||||||
|
p.innerHTML = "New Text"
|
||||||
|
|
||||||
|
outerHTML.bind({
|
||||||
|
onSwitch: noop
|
||||||
|
})(doc.querySelector("p"), p)
|
||||||
|
|
||||||
|
t.equals(doc.querySelector("p").innerHTML, "New Text", "Elements correctly switched")
|
||||||
|
t.notEquals(doc.querySelector("p").id, "p", "other attributes overwritten correctly")
|
||||||
|
|
||||||
|
t.end()
|
||||||
|
})
|
||||||
|
|
||||||
|
tape("test innerHTML switch", function(t) {
|
||||||
|
var innerHTML = switches.innerHTML
|
||||||
|
|
||||||
|
var doc = document.implementation.createHTMLDocument()
|
||||||
|
|
||||||
|
var container = doc.createElement("div")
|
||||||
|
container.innerHTML = "<p id='p'>Original Text</p>"
|
||||||
|
doc.body.appendChild(container)
|
||||||
|
|
||||||
|
var p = doc.createElement("p")
|
||||||
|
p.innerHTML = "New Text"
|
||||||
|
p.className = "p"
|
||||||
|
|
||||||
|
innerHTML.bind({
|
||||||
|
onSwitch: noop
|
||||||
|
})(doc.querySelector("p"), p)
|
||||||
|
|
||||||
|
t.equals(doc.querySelector("p").innerHTML, "New Text", "Elements correctly switched")
|
||||||
|
t.equals(doc.querySelector("p").className, "p", "classname set correctly")
|
||||||
|
t.equals(doc.querySelector("p").id, "p", "other attributes set correctly")
|
||||||
|
|
||||||
|
p.removeAttribute("class")
|
||||||
|
|
||||||
|
innerHTML.bind({
|
||||||
|
onSwitch: noop
|
||||||
|
})(doc.querySelector("p"), p)
|
||||||
|
|
||||||
|
t.equals(doc.querySelector("p").className, "", "classname set correctly")
|
||||||
|
|
||||||
|
t.end()
|
||||||
|
})
|
||||||
|
|
||||||
|
tape("test replaceNode switch", function(t) {
|
||||||
|
var replaceNode = switches.replaceNode
|
||||||
|
|
||||||
|
var doc = document.implementation.createHTMLDocument()
|
||||||
|
|
||||||
|
var container = doc.createElement("div")
|
||||||
|
container.innerHTML = "<p>Original Text</p>"
|
||||||
|
doc.body.appendChild(container)
|
||||||
|
|
||||||
|
var p = doc.createElement("p")
|
||||||
|
p.innerHTML = "New Text"
|
||||||
|
|
||||||
|
replaceNode.bind({
|
||||||
|
onSwitch: noop
|
||||||
|
})(doc.querySelector("p"), p)
|
||||||
|
|
||||||
|
t.equals(doc.querySelector("div").innerHTML, "<p>New Text</p>", "Elements correctly switched")
|
||||||
|
|
||||||
|
t.end()
|
||||||
|
})
|
||||||
17
tests/lib/util/clone.js
Normal file
17
tests/lib/util/clone.js
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
var tape = require("tape")
|
||||||
|
|
||||||
|
var clone = require("../../../lib/util/clone")
|
||||||
|
|
||||||
|
tape("test clone method", function(t) {
|
||||||
|
var obj = {one: 1, two: 2}
|
||||||
|
var cloned = clone(obj)
|
||||||
|
|
||||||
|
t.notEqual(obj, cloned, "cloned object isn't the original object")
|
||||||
|
|
||||||
|
t.same(obj, cloned, "cloned object has the same values as original object")
|
||||||
|
|
||||||
|
cloned.three = 3
|
||||||
|
t.notSame(obj, cloned, "modified cloned object doesn't have the same values as original object")
|
||||||
|
|
||||||
|
t.end()
|
||||||
|
})
|
||||||
16
tests/lib/util/contains.js
Normal file
16
tests/lib/util/contains.js
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
var tape = require("tape")
|
||||||
|
|
||||||
|
var contains = require("../../../lib/util/contains.js")
|
||||||
|
|
||||||
|
tape("test contains function", function(t) {
|
||||||
|
var tempDoc = document.implementation.createHTMLDocument()
|
||||||
|
tempDoc.body.innerHTML = "<div><p id='el' class='js-Pjax'></p></div><span></span>"
|
||||||
|
var selectors = ["div"]
|
||||||
|
var el = tempDoc.body.querySelector("#el")
|
||||||
|
t.equal(contains(tempDoc, selectors, el), true, "contains() returns true when a selector contains the element")
|
||||||
|
|
||||||
|
selectors = ["span"]
|
||||||
|
t.equal(contains(tempDoc, selectors, el), false, "contains() returns false when the selectors do not contain the element")
|
||||||
|
|
||||||
|
t.end()
|
||||||
|
})
|
||||||
17
tests/lib/util/extend.js
Normal file
17
tests/lib/util/extend.js
Normal file
@@ -0,0 +1,17 @@
|
|||||||
|
var tape = require("tape")
|
||||||
|
|
||||||
|
var extend = require("../../../lib/util/extend")
|
||||||
|
|
||||||
|
tape("test extend method", function(t) {
|
||||||
|
var obj = {one: 1, two: 2}
|
||||||
|
|
||||||
|
var extended = extend({}, obj, {two: "two", three: 3})
|
||||||
|
t.notEqual(obj, extended, "extended object isn't the original object")
|
||||||
|
t.notSame(obj, extended, "extended object doesn't have the same values as original object")
|
||||||
|
t.notSame(obj.two, extended.two, "extended object value overwrites value from original object")
|
||||||
|
|
||||||
|
extended = extend(null)
|
||||||
|
t.equals(extended, null, "passing null returns null")
|
||||||
|
|
||||||
|
t.end()
|
||||||
|
})
|
||||||
9
tests/lib/util/noop.js
Normal file
9
tests/lib/util/noop.js
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
var tape = require("tape")
|
||||||
|
|
||||||
|
var noop = require("../../../lib/util/noop")
|
||||||
|
|
||||||
|
tape("test noop function", function(t) {
|
||||||
|
t.equal(typeof noop, "function", "noop is a function")
|
||||||
|
t.equal(noop(), undefined, "noop() returns nothing")
|
||||||
|
t.end()
|
||||||
|
})
|
||||||
21
tests/lib/util/update-query-string.js
Normal file
21
tests/lib/util/update-query-string.js
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
var tape = require("tape")
|
||||||
|
|
||||||
|
var updateQueryString = require("../../../lib/util/update-query-string")
|
||||||
|
|
||||||
|
tape("test update query string method", function(t) {
|
||||||
|
var url = "http://example.com"
|
||||||
|
var updatedUrl = updateQueryString(url, "foo", "bar")
|
||||||
|
|
||||||
|
t.notEqual(url, updatedUrl, "update query string modifies URL")
|
||||||
|
t.equal(updatedUrl, url + "?foo=bar", "update query string creates new query string when no query string params are set")
|
||||||
|
|
||||||
|
updatedUrl = updateQueryString(updatedUrl, "foo", "baz")
|
||||||
|
|
||||||
|
t.equal(updatedUrl, url + "?foo=baz", "update query string updates existing query string param")
|
||||||
|
|
||||||
|
updatedUrl = updateQueryString(updatedUrl, "bar", "")
|
||||||
|
|
||||||
|
t.equal(updatedUrl, url + "?foo=baz&bar=", "update query string appends to existing query string")
|
||||||
|
|
||||||
|
t.end()
|
||||||
|
})
|
||||||
6
tests/setup.js
Normal file
6
tests/setup.js
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
var jsdomOptions = {
|
||||||
|
url: "https://example.org/",
|
||||||
|
runScripts: "dangerously"
|
||||||
|
}
|
||||||
|
|
||||||
|
require("jsdom-global")("", jsdomOptions)
|
||||||
41
tests/test.ts
Normal file
41
tests/test.ts
Normal file
@@ -0,0 +1,41 @@
|
|||||||
|
import Pjax = require("../index");
|
||||||
|
|
||||||
|
let options: Pjax.IOptions = {
|
||||||
|
elements: "a.pjax, form.pjax",
|
||||||
|
selectors: ["div.pjax"],
|
||||||
|
switches: {
|
||||||
|
"a.pjax": (oldEl, newEl) => {
|
||||||
|
oldEl.parentNode.replaceChild(newEl, oldEl);
|
||||||
|
this.onSwitch();
|
||||||
|
},
|
||||||
|
"form.pjax": Pjax.switches.innerHTML
|
||||||
|
},
|
||||||
|
switchesOptions: {},
|
||||||
|
history: true,
|
||||||
|
analytics: false,
|
||||||
|
scrollTo: 1,
|
||||||
|
scrollRestoration: false,
|
||||||
|
cacheBust: false,
|
||||||
|
debug: true,
|
||||||
|
timeout: 60000,
|
||||||
|
currentUrlFullReload: true
|
||||||
|
};
|
||||||
|
|
||||||
|
options.analytics = () => {};
|
||||||
|
options.scrollTo = [1, 1];
|
||||||
|
options.scrollTo = false;
|
||||||
|
|
||||||
|
if (Pjax.isSupported()) {
|
||||||
|
delete options.switchesOptions;
|
||||||
|
const pjax = new Pjax(options);
|
||||||
|
|
||||||
|
pjax.reload();
|
||||||
|
pjax.loadUrl("https://example.org", options);
|
||||||
|
|
||||||
|
pjax._handleResponse = pjax.handleResponse;
|
||||||
|
pjax.handleResponse = (requestText: string, request: XMLHttpRequest, href: string) => {
|
||||||
|
pjax.abortRequest(request);
|
||||||
|
|
||||||
|
return pjax._handleResponse(requestText, request, href);
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user