Compare commits
66 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a601e301cd | ||
|
|
c16996d2b2 | ||
|
|
af8783587c | ||
|
|
14f997c8d1 | ||
|
|
9a86044f90 | ||
|
|
e6a35f38e4 | ||
|
|
3d50ae9131 | ||
|
|
949d1be1a0 | ||
|
|
a119033870 | ||
|
|
482ba2c117 | ||
|
|
7e81f791a9 | ||
|
|
d4ba34e5ed | ||
|
|
ea7d1d2fce | ||
|
|
1d087e8b00 | ||
|
|
3bc67f245c | ||
|
|
332cd4e876 | ||
|
|
db02366324 | ||
|
|
b5bf998fc6 | ||
|
|
74e224c018 | ||
|
|
165532d43c | ||
|
|
414650113b | ||
|
|
a6c9b57647 | ||
|
|
f4e5ec254a | ||
|
|
f1976c3a10 | ||
|
|
799dd51597 | ||
|
|
76026cf8d9 | ||
|
|
b6702a5ea0 | ||
|
|
673c483ccb | ||
|
|
d1536eb228 | ||
|
|
681aa74e1d | ||
|
|
3f3fa761e1 | ||
|
|
0d6643cf7a | ||
|
|
4a4fb6fbc6 | ||
|
|
d5395c3d07 | ||
|
|
8c05692004 | ||
|
|
13b3485111 | ||
|
|
b1de220555 | ||
|
|
b4f7aceab6 | ||
|
|
1cc1aa9d04 | ||
|
|
52d7971dc5 | ||
|
|
9ac709b5d8 | ||
|
|
fa27e05606 | ||
|
|
106b14b851 | ||
|
|
2990f93a20 | ||
|
|
5644893c59 | ||
|
|
7631cc92c7 | ||
|
|
25a725c858 | ||
|
|
f93efb0c00 | ||
|
|
cac43b7c59 | ||
|
|
dd590bae28 | ||
|
|
48376db0ef | ||
|
|
a17a6b90be | ||
|
|
7541d82095 | ||
|
|
e0d33c9e18 | ||
|
|
ce28c1adc3 | ||
|
|
fa72f25fd5 | ||
|
|
743196fe7e | ||
|
|
0a14fd9e70 | ||
|
|
02fabcca8d | ||
|
|
c65507ec50 | ||
|
|
075cc43b68 | ||
|
|
2b4c614890 | ||
|
|
f9c5929e2d | ||
|
|
54ed7a276c | ||
|
|
d72e2a852c | ||
|
|
1320dae352 |
2
.gitignore
vendored
2
.gitignore
vendored
@@ -1 +1,3 @@
|
||||
.DS_Store
|
||||
node_modules/
|
||||
tests/scripts/index.html
|
||||
|
||||
147
.jscs.json
147
.jscs.json
@@ -1,147 +0,0 @@
|
||||
{
|
||||
"excludeFiles": [
|
||||
]
|
||||
, "requireCurlyBraces": [
|
||||
"if"
|
||||
, "else"
|
||||
, "for"
|
||||
, "while"
|
||||
, "do"
|
||||
, "try"
|
||||
, "catch"
|
||||
]
|
||||
, "requireSpaceAfterKeywords": [
|
||||
"if"
|
||||
, "else"
|
||||
, "for"
|
||||
, "while"
|
||||
, "do"
|
||||
, "switch"
|
||||
, "return"
|
||||
, "try"
|
||||
, "catch"
|
||||
]
|
||||
, "requireSpacesInFunctionExpression": {
|
||||
"beforeOpeningCurlyBrace": true
|
||||
}
|
||||
, "disallowSpacesInFunctionExpression": {
|
||||
"beforeOpeningRoundBrace": true
|
||||
}
|
||||
, "disallowEmptyBlocks": true
|
||||
, "disallowSpacesInsideObjectBrackets": true
|
||||
, "disallowSpacesInsideArrayBrackets": true
|
||||
, "disallowSpacesInsideParentheses": true
|
||||
, "disallowSpaceAfterObjectKeys": true
|
||||
, "disallowCommaBeforeLineBreak": true
|
||||
, "requireOperatorBeforeLineBreak": [
|
||||
"?"
|
||||
, "+"
|
||||
, "-"
|
||||
, "/"
|
||||
, "*"
|
||||
, "="
|
||||
, "=="
|
||||
, "==="
|
||||
, "!="
|
||||
, "!=="
|
||||
, ">"
|
||||
, ">="
|
||||
, "<"
|
||||
, "<="
|
||||
]
|
||||
, "disallowLeftStickedOperators": [
|
||||
"?"
|
||||
, "+"
|
||||
, "-"
|
||||
, "/"
|
||||
, "*"
|
||||
, "="
|
||||
, "=="
|
||||
, "==="
|
||||
, "!="
|
||||
, "!=="
|
||||
, ">"
|
||||
, ">="
|
||||
, "<"
|
||||
, "<="
|
||||
]
|
||||
, "requireRightStickedOperators": [
|
||||
"!"
|
||||
]
|
||||
, "disallowRightStickedOperators": [
|
||||
"?"
|
||||
, "+"
|
||||
, "/"
|
||||
, "*"
|
||||
, ":"
|
||||
, "="
|
||||
, "=="
|
||||
, "==="
|
||||
, "!="
|
||||
, "!=="
|
||||
, ">"
|
||||
, ">="
|
||||
, "<"
|
||||
, "<="
|
||||
]
|
||||
, "disallowSpaceAfterPrefixUnaryOperators": [
|
||||
"++"
|
||||
, "--"
|
||||
, "+"
|
||||
, "-"
|
||||
, "~"
|
||||
, "!"
|
||||
]
|
||||
, "disallowSpaceBeforePostfixUnaryOperators": [
|
||||
"++"
|
||||
, "--"
|
||||
]
|
||||
, "requireSpaceBeforeBinaryOperators": [
|
||||
"+"
|
||||
, "-"
|
||||
, "/"
|
||||
, "*"
|
||||
, "="
|
||||
, "=="
|
||||
, "==="
|
||||
, "!="
|
||||
, "!=="
|
||||
]
|
||||
, "requireSpaceAfterBinaryOperators": [
|
||||
"+"
|
||||
, "-"
|
||||
, "/"
|
||||
, "*"
|
||||
, "="
|
||||
, "=="
|
||||
, "==="
|
||||
, "!="
|
||||
, "!=="
|
||||
]
|
||||
, "disallowImplicitTypeConversion": [
|
||||
"numeric"
|
||||
, "boolean"
|
||||
, "binary"
|
||||
, "string"
|
||||
]
|
||||
, "disallowKeywords": [
|
||||
"with"
|
||||
]
|
||||
, "disallowMultipleLineStrings": true
|
||||
|
||||
, "validateQuoteMarks": "\""
|
||||
, "disallowMixedSpacesAndTabs": true
|
||||
, "disallowTrailingWhitespace": true
|
||||
|
||||
, "requireKeywordsOnNewLine": [
|
||||
]
|
||||
, "requireLineFeedAtFileEnd": true
|
||||
, "requireCapitalizedConstructors": true
|
||||
, "safeContextKeyword": "that"
|
||||
|
||||
, "validateJSDoc": {
|
||||
"checkParamNames": true
|
||||
, "checkRedundantParams": true
|
||||
, "requireParamTypes": true
|
||||
}
|
||||
}
|
||||
130
.jscsrc
Normal file
130
.jscsrc
Normal file
@@ -0,0 +1,130 @@
|
||||
{
|
||||
"excludeFiles": [
|
||||
"node_modules/**"
|
||||
],
|
||||
"fileExtensions": [
|
||||
".js"
|
||||
],
|
||||
"requireCurlyBraces": [
|
||||
"if",
|
||||
"else",
|
||||
"for",
|
||||
"while",
|
||||
"do",
|
||||
"try",
|
||||
"catch"
|
||||
],
|
||||
"requireSpaceAfterKeywords": [
|
||||
"if",
|
||||
"else",
|
||||
"for",
|
||||
"while",
|
||||
"do",
|
||||
"switch",
|
||||
"return",
|
||||
"try",
|
||||
"catch"
|
||||
],
|
||||
"requireSpaceBeforeBlockStatements": true,
|
||||
"requireParenthesesAroundIIFE": true,
|
||||
"requireSpacesInConditionalExpression": {
|
||||
"afterTest": true,
|
||||
"beforeConsequent": true,
|
||||
"afterConsequent": true,
|
||||
"beforeAlternate": true
|
||||
},
|
||||
"requireSpacesInFunctionExpression": {
|
||||
"beforeOpeningCurlyBrace": true
|
||||
},
|
||||
"disallowSpacesInFunctionExpression": {
|
||||
"beforeOpeningRoundBrace": true
|
||||
},
|
||||
"disallowMultipleVarDecl": true,
|
||||
"requireBlocksOnNewline": 1,
|
||||
"disallowPaddingNewlinesInBlocks": true,
|
||||
"disallowEmptyBlocks": true,
|
||||
"disallowSpacesInsideObjectBrackets": true,
|
||||
"disallowSpacesInsideArrayBrackets": true,
|
||||
"disallowSpacesInsideParentheses": true,
|
||||
"disallowQuotedKeysInObjects": "allButReserved",
|
||||
"disallowSpaceAfterObjectKeys": true,
|
||||
"requireCommaBeforeLineBreak": true,
|
||||
"requireOperatorBeforeLineBreak": [
|
||||
"?",
|
||||
"+",
|
||||
"-",
|
||||
"/",
|
||||
"*",
|
||||
"=",
|
||||
"==",
|
||||
"===",
|
||||
"!=",
|
||||
"!==",
|
||||
">",
|
||||
">=",
|
||||
"<",
|
||||
"<="
|
||||
],
|
||||
"disallowSpaceAfterPrefixUnaryOperators": [
|
||||
"++",
|
||||
"--",
|
||||
"+",
|
||||
"-",
|
||||
"~",
|
||||
"!"
|
||||
],
|
||||
"disallowSpaceBeforePostfixUnaryOperators": [
|
||||
"++",
|
||||
"--"
|
||||
],
|
||||
"requireSpaceBeforeBinaryOperators": [
|
||||
"+",
|
||||
"-",
|
||||
"/",
|
||||
"*",
|
||||
"=",
|
||||
"==",
|
||||
"===",
|
||||
"!=",
|
||||
"!=="
|
||||
],
|
||||
"requireSpaceAfterBinaryOperators": [
|
||||
"+",
|
||||
"-",
|
||||
"/",
|
||||
"*",
|
||||
"=",
|
||||
"==",
|
||||
"===",
|
||||
"!=",
|
||||
"!=="
|
||||
],
|
||||
"disallowImplicitTypeConversion": [
|
||||
"numeric",
|
||||
"boolean",
|
||||
"binary",
|
||||
"string"
|
||||
],
|
||||
"requireCamelCaseOrUpperCaseIdentifiers": "ignoreProperties",
|
||||
"disallowKeywords": [
|
||||
"with"
|
||||
],
|
||||
"disallowMultipleLineStrings": true,
|
||||
"validateQuoteMarks": "\"",
|
||||
"validateIndentation": 2,
|
||||
"disallowMixedSpacesAndTabs": true,
|
||||
"disallowTrailingWhitespace": true,
|
||||
"requireKeywordsOnNewLine": [
|
||||
"else"
|
||||
],
|
||||
"requireLineFeedAtFileEnd": true,
|
||||
"requireCapitalizedConstructors": true,
|
||||
"safeContextKeyword": "that",
|
||||
"requireDotNotation": true,
|
||||
"validateJSDoc": {
|
||||
"checkParamNames": true,
|
||||
"checkRedundantParams": true,
|
||||
"requireParamTypes": true
|
||||
},
|
||||
"requireSpaceAfterLineComment": true
|
||||
}
|
||||
@@ -1,4 +1,9 @@
|
||||
{
|
||||
"asi": true
|
||||
, "laxcomma": true
|
||||
"newcap": false,
|
||||
"undef": true,
|
||||
"unused": true,
|
||||
"asi": true,
|
||||
"esnext": true,
|
||||
"node": true,
|
||||
"browser": true
|
||||
}
|
||||
|
||||
7
.travis.yml
Normal file
7
.travis.yml
Normal file
@@ -0,0 +1,7 @@
|
||||
language: "node_js"
|
||||
before_script:
|
||||
# testling use headless browser
|
||||
# on travis-ci, firefox is the default one
|
||||
# & it needs a display to works
|
||||
- export DISPLAY=:99.0
|
||||
- sh -e /etc/init.d/xvfb start
|
||||
35
CHANGELOG.md
35
CHANGELOG.md
@@ -1,14 +1,33 @@
|
||||
# Changelog
|
||||
# unreleased
|
||||
|
||||
## 0.1.2 - 2014-04-03
|
||||
-
|
||||
|
||||
- pjax.js relocated in `src/`
|
||||
- <html> attributes of pjaxified document are now available
|
||||
# 0.2.0 - 2015-02-04
|
||||
|
||||
## 0.1.1 - 2014-04-02
|
||||
- Fixed: prevent scrollTo from being converted from false to 0 ([#33](https://github.com/MoOx/pjax/pull/33))
|
||||
- Changed: code exploded in commonjs style
|
||||
- Added: lots of tests
|
||||
- Added: `refresh` method to force update a DOM element ([#36](https://github.com/MoOx/pjax/pull/36))
|
||||
|
||||
- Safer UMD wrapper (fix concat issue)
|
||||
# 0.1.4 - 2014-10-14
|
||||
|
||||
## 0.1.0 - 2014-03-24
|
||||
- Fixed: allow to load pages without any attributes on `<html>` element (fix [#6](https://github.com/MoOx/pjax/issues/6))
|
||||
- Fixed: make `Pjax.switches.sideBySide` method usable (fix [#13](https://github.com/MoOx/pjax/issues/13))
|
||||
|
||||
Initial release
|
||||
# 0.1.3 - 2014-09-16
|
||||
|
||||
- Fixed: clicking on the current url somewhere does not produce a full reload by default (see option `currentUrlFullReload`)
|
||||
- Fixed: `document.implementation.createHTMLDocument` error (in IE10, ref [#16](https://github.com/MoOx/pjax/pull/16))
|
||||
|
||||
# 0.1.2 - 2014-04-03
|
||||
|
||||
- Changed: `pjax.js` relocated in `src/`
|
||||
- Fixed: `<html>` attributes of pjaxified document are now available
|
||||
|
||||
# 0.1.1 - 2014-04-02
|
||||
|
||||
- Fixed: safer UMD wrapper (fix concat issue)
|
||||
|
||||
# 0.1.0 - 2014-03-24
|
||||
|
||||
✨ Initial release
|
||||
|
||||
185
CONTRIBUTING.md
185
CONTRIBUTING.md
@@ -1,185 +0,0 @@
|
||||
# Contributing Guide
|
||||
|
||||
Please take a moment to review this document in order to make the contribution
|
||||
process easy and effective for everyone involved.
|
||||
|
||||
Following these guidelines helps to communicate that you respect the time of
|
||||
the developers managing and developing this open source project. In return,
|
||||
they should reciprocate that respect in addressing your issue, assessing
|
||||
changes, and helping you finalize your pull requests.
|
||||
|
||||
|
||||
## Using the issue tracker
|
||||
|
||||
The issue tracker is the preferred channel for [bug reports](#bugs),
|
||||
[features requests](#features) and [submitting pull
|
||||
requests](#pull-requests).
|
||||
|
||||
|
||||
<a name="bugs"></a>
|
||||
## Bug reports
|
||||
|
||||
A bug is a _demonstrable problem_ that is caused by the code in the repository.
|
||||
Good bug reports are extremely helpful - thank you!
|
||||
|
||||
Guidelines for bug reports:
|
||||
|
||||
1. **Use the GitHub issue search** — check if the issue has already been
|
||||
reported.
|
||||
|
||||
2. **Check if the issue has been fixed** — try to reproduce it using the
|
||||
latest `master` or development branch in the repository.
|
||||
|
||||
3. **Isolate the problem** — ideally create a [reduced test
|
||||
case](http://css-tricks.com/6263-reduced-test-cases/).
|
||||
|
||||
A good bug report shouldn't leave others needing to chase you up for more
|
||||
information. Please try to be as detailed as possible in your report. What is
|
||||
your environment? What steps will reproduce the issue? What OS experiences the
|
||||
problem? What would you expect to be the outcome? All these details will help
|
||||
people to fix any potential bugs.
|
||||
|
||||
Example:
|
||||
|
||||
> Short and descriptive example bug report title
|
||||
>
|
||||
> A summary of the issue and the browser/OS environment in which it occurs. If
|
||||
> suitable, include the steps required to reproduce the bug.
|
||||
>
|
||||
> 1. This is the first step
|
||||
> 2. This is the second step
|
||||
> 3. Further steps, etc.
|
||||
>
|
||||
> `<url>` - a link to the reduced test case
|
||||
>
|
||||
> Any other information you want to share that is relevant to the issue being
|
||||
> reported. This might include the lines of code that you have identified as
|
||||
> causing the bug, and potential solutions (and your opinions on their
|
||||
> merits).
|
||||
|
||||
|
||||
<a name="features"></a>
|
||||
## Feature requests
|
||||
|
||||
Feature requests are welcome. But take a moment to find out whether your idea
|
||||
fits with the scope and aims of the project. It's up to *you* to make a strong
|
||||
case to convince the project's developers of the merits of this feature. Please
|
||||
provide as much detail and context as possible.
|
||||
|
||||
|
||||
<a name="pull-requests"></a>
|
||||
## Pull requests
|
||||
|
||||
Good pull requests - patches, improvements, new features - are a fantastic
|
||||
help. They should remain focused in scope and avoid containing unrelated
|
||||
commits.
|
||||
|
||||
**Please ask first** before embarking on any significant pull request (e.g.
|
||||
implementing features, refactoring code), otherwise you risk spending a lot of
|
||||
time working on something that the project's developers might not want to merge
|
||||
into the project.
|
||||
|
||||
Please adhere to the coding conventions used throughout a project (indentation,
|
||||
accurate comments, etc.) and any other requirements (such as test coverage).
|
||||
|
||||
Adhering to the following this process is the best way to get your work
|
||||
included in the project:
|
||||
|
||||
1. [Fork](http://help.github.com/fork-a-repo/) the project, clone your fork,
|
||||
and configure the remotes:
|
||||
|
||||
```bash
|
||||
# Clone your fork of the repo into the current directory
|
||||
git clone https://github.com/<your-username>/happyplan
|
||||
# Navigate to the newly cloned directory
|
||||
cd happyplan
|
||||
# Assign the original repo to a remote called "upstream"
|
||||
git remote add upstream https://github.com/happyplan/happyplan
|
||||
```
|
||||
|
||||
2. If you cloned a while ago, get the latest changes from upstream:
|
||||
|
||||
```bash
|
||||
git checkout master
|
||||
git pull upstream master
|
||||
```
|
||||
|
||||
3. Create a new topic branch (off the main project development branch) to
|
||||
contain your feature, change, or fix:
|
||||
|
||||
```bash
|
||||
git checkout -b <topic-branch-name>
|
||||
```
|
||||
|
||||
4. Make sure to update, or add to the tests when appropriate. Patches and
|
||||
features will not be accepted without tests. Run `npm test` to check that
|
||||
all tests pass after you've made changes.
|
||||
|
||||
5. Commit your changes in logical chunks. Please adhere to these [git commit
|
||||
message guidelines](http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html)
|
||||
or your code is unlikely be merged into the main project. Use Git's
|
||||
[interactive rebase](https://help.github.com/articles/interactive-rebase)
|
||||
feature to tidy up your commits before making them public.
|
||||
|
||||
6. Locally merge (or rebase) the upstream development branch into your topic branch:
|
||||
|
||||
```bash
|
||||
git pull [--rebase] upstream master
|
||||
```
|
||||
|
||||
7. Push your topic branch up to your fork:
|
||||
|
||||
```bash
|
||||
git push origin <topic-branch-name>
|
||||
```
|
||||
|
||||
8. [Open a Pull Request](https://help.github.com/articles/using-pull-requests/)
|
||||
with a clear title and description.
|
||||
|
||||
9. If you are asked to amend your changes before they can be merged in, please
|
||||
use `git commit --amend` (or rebasing for multi-commit Pull Requests) and
|
||||
force push to your remote feature branch. You may also be asked to squash
|
||||
commits.
|
||||
|
||||
**IMPORTANT**: By submitting a patch, you agree to license your work under the
|
||||
same license as that used by the project.
|
||||
|
||||
|
||||
<a name="maintainers"></a>
|
||||
## Maintainers
|
||||
|
||||
If you have commit access, please follow this process for merging patches and cutting new releases.
|
||||
|
||||
### Reviewing changes
|
||||
|
||||
1. Check that a change is within the scope and philosophy of the project.
|
||||
2. Check that a change has any necessary tests and a proper, descriptive commit message.
|
||||
3. Checkout the change and test it locally.
|
||||
4. If the change is good, and authored by someone who cannot commit to
|
||||
`master`, please try to avoid using GitHub's merge button. Apply the change
|
||||
to `master` locally (feel free to amend any minor problems in the author's
|
||||
original commit if necessary).
|
||||
5. If the change is good, and authored by another maintainer/collaborator, give
|
||||
them a "Ship it!" comment and let them handle the merge.
|
||||
|
||||
### Submitting changes
|
||||
|
||||
1. All non-trivial changes should be put up for review using GitHub Pull
|
||||
Requests.
|
||||
2. Your change should not be merged into `master` (or another feature branch),
|
||||
without at least one "Ship it!" comment from another maintainer/collaborator
|
||||
on the project. "Looks good to me" is not the same as "Ship it!".
|
||||
3. Try to avoid using GitHub's merge button. Locally rebase your change onto
|
||||
`master` and then push to GitHub.
|
||||
4. Once a feature branch has been merged into its target branch, please delete
|
||||
the feature branch from the remote repository.
|
||||
|
||||
### Releasing a new version
|
||||
|
||||
1. Include all new functional changes in the CHANGELOG.
|
||||
2. Use a dedicated commit to increment the version. The version needs to be
|
||||
added to the `CHANGELOG.md` (inc. date) and the `package.json`.
|
||||
3. The commit message must be of `v0.0.0` format.
|
||||
4. Create an annotated tag for the version: `git tag -m "v0.0.0" v0.0.0`.
|
||||
5. Push the changes and tags to GitHub: `git push --tags origin master`.
|
||||
6. Publish the new version to npm: `npm publish`.
|
||||
@@ -1,6 +1,6 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2014 "MoOx" Maxime Thirouin
|
||||
Copyright (c) 2014 Maxime Thirouin
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of
|
||||
this software and associated documentation files (the "Software"), to deal in
|
||||
147
README.md
147
README.md
@@ -1,8 +1,9 @@
|
||||
# Pjax
|
||||
# Pjax [](https://travis-ci.org/MoOx/pjax)
|
||||
|
||||
<img align="right" src="https://dl.dropboxusercontent.com/u/14108185/memes/mind-blow.gif">
|
||||
|
||||
> When Ajax navigation meets Push State
|
||||
[](https://ci.testling.com/MoOx/pjax)
|
||||
|
||||
> Easily enable fast Ajax navigation on any website (using pushState + xhr)
|
||||
|
||||
Pjax is ~~a jQuery plugin~~ **a standalone JavaScript module** that uses
|
||||
ajax (XmlHttpRequest) and
|
||||
@@ -10,13 +11,18 @@ ajax (XmlHttpRequest) and
|
||||
to deliver a fast browsing experience.
|
||||
|
||||
_It allow you to completely transform 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 they browse an app.
|
||||
Especially for user that have low bandwidth connection._
|
||||
|
||||
## No tests or Demo ?
|
||||
**No more full page reload. No more lots of HTTP request.**
|
||||
|
||||
There is still some work to make this repo sexy with tests & simple demo.
|
||||
# Note: current master is WIP.
|
||||
|
||||
For now [you can see this running on my website](http://moox.io), with sexy CSS animations when switching pages.
|
||||
Checkout [v0.1.4](https://github.com/MoOx/pjax/tree/a17a6b90bebefd8f5209e6a6f7d8c5d59296232a) for latest "stable" (no tests so kind of funny to call that stable).
|
||||
|
||||
## Demo
|
||||
|
||||
[You can see this running on my website](http://moox.io), with sexy CSS animations when switching pages.
|
||||
|
||||
## How Pjax works
|
||||
|
||||
@@ -131,8 +137,8 @@ Let's talk more about the most basic way to get started:
|
||||
|
||||
```js
|
||||
new Pjax({
|
||||
elements: "a" // default is "a[href], form[action]"
|
||||
, selectors: ["title", ".my-Header", ".my-Content", ".my-Sidebar"]
|
||||
elements: "a", // default is "a[href], form[action]"
|
||||
selectors: ["title", ".my-Header", ".my-Content", ".my-Sidebar"]
|
||||
})
|
||||
```
|
||||
|
||||
@@ -199,8 +205,8 @@ Examples:
|
||||
|
||||
```js
|
||||
new Pjax({
|
||||
selectors: ["title", ".Navbar", ".js-Pjax"]
|
||||
, switches: {
|
||||
selectors: ["title", ".Navbar", ".js-Pjax"],
|
||||
switches: {
|
||||
// "title": Pjax.switches.outerHTML // default behavior
|
||||
".Navbar": function(oldEl, newEl, options) {
|
||||
// here it's a stupid example since it's the default behavior too
|
||||
@@ -223,7 +229,7 @@ Callbacks are binded to Pjax instance itself to allow you to reuse it (ex: `this
|
||||
|
||||
###### Create a switch callback
|
||||
|
||||
Your function can do whatever you want, be should
|
||||
Your function can do whatever you want, but you need to:
|
||||
|
||||
- replace oldEl content by newEl content in some fashion
|
||||
- call `this.onSwitch()` to trigger attached callback.
|
||||
@@ -245,23 +251,23 @@ with or without [WOW.js](https://github.com/matthieua/WOW).
|
||||
|
||||
```js
|
||||
new Pjax({
|
||||
selectors: ["title", ".js-Pjax"]
|
||||
, switches: {
|
||||
selectors: ["title", ".js-Pjax"],
|
||||
switches: {
|
||||
".js-Pjax": Pjax.switches.sideBySide
|
||||
}
|
||||
, switchesClasses: {
|
||||
},
|
||||
switchesOptions: {
|
||||
".js-Pjax": {
|
||||
classNames: {
|
||||
// class added on the element that will be removed
|
||||
remove: "Animated Animated--reverse Animate--fast Animate--noDelay"
|
||||
remove: "Animated Animated--reverse Animate--fast Animate--noDelay",
|
||||
// class added on the element that will be added
|
||||
, add: "Animated"
|
||||
add: "Animated",
|
||||
// class added on the element when it go backward
|
||||
, backward: "Animate--slideInRight"
|
||||
backward: "Animate--slideInRight",
|
||||
// class added on the element when it go forward (used for new page too)
|
||||
, forward: "Animate--slideInLeft"
|
||||
}
|
||||
, callbacks: {
|
||||
forward: "Animate--slideInLeft"
|
||||
},
|
||||
callbacks: {
|
||||
// to make a nice transition with 2 pages as the same time
|
||||
// we are playing with absolute positioning for element we are removing
|
||||
// & we need live metrics to have something great
|
||||
@@ -274,7 +280,7 @@ new Pjax({
|
||||
})
|
||||
```
|
||||
_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
|
||||
|
||||
@@ -384,6 +390,10 @@ Value (in px) to scrollTo when a page is switched.
|
||||
Enable verbose mode & doesn't use fallback when there is an error.
|
||||
Useful to debug page layout differences.
|
||||
|
||||
##### `currentUrlFullReload` (Boolean, default to false)
|
||||
|
||||
When set to true, clicking on a link that point the current url trigger a full page reload.
|
||||
|
||||
#### Extend Pjax
|
||||
|
||||
Pjax prototype & utilities methods can be used & changed so you can patch or hack
|
||||
@@ -391,14 +401,6 @@ Pjax behavior, as you wish.
|
||||
|
||||
Here is a summary of functions:
|
||||
|
||||
- `Pjax.isSupported` (`function()`): return wheter or not the browser handle pushState correctly
|
||||
- `Pjax.on` (`function(els, events, listener, useCapture)`): addEventListener, that handles NodeList & supports space separated event name
|
||||
- `Pjax.off` (`function(els, events, listener, useCapture)`): removeEventListener, that handles NodeList & supports space separated event name
|
||||
- `Pjax.trigger` (`function(els, events)`): fireEvent, that handles NodeList & supports space separated event name
|
||||
- `Pjax.clone` (`function(obj)`): clone object
|
||||
- `Pjax.executeScripts` (`function(el)`): execute scripts that are inside an element (script src or inline scripts through `Pjax.evalScript`)
|
||||
- `Pjax.evalScript` (`function(el)`): execute inline script. Don't execute a script if it contains `document.write`.
|
||||
|
||||
- `Pjax.prototype.log` (`function()`): console.log function that is enable/disabled by `debug` option
|
||||
- `Pjax.prototype.getElements` (`function(el)`): retrieve elements to attach Pjax behavior
|
||||
- `Pjax.prototype.parseDOM` (`function(el)`): parse DOM to attach behavior using `Pjax.prototype.getElements` & `Pjax.prototype.attachLink`
|
||||
@@ -472,23 +474,78 @@ document.addEventListener("pjax:success", whenContainerReady)
|
||||
|
||||
---
|
||||
|
||||
## [Changelog](CHANGELOG.md)
|
||||
## FAQ
|
||||
|
||||
### Q: Disqus doesn't work anymore, how can I fix that ?
|
||||
|
||||
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`
|
||||
arra (or just wrap it with class="js-Pjax") & be sure to have a least the empty
|
||||
wrapper on each page (to avoid differences of DOM between pages)
|
||||
- edit your disqus snippet like the one below
|
||||
|
||||
#### Disqus snippet before pjax integration
|
||||
|
||||
```html
|
||||
<script>
|
||||
var disqus_shortname = 'YOURSHORTNAME'
|
||||
var disqus_identifier = 'PAGEID'
|
||||
var disqus_url = 'PAGEURL'
|
||||
var disqus_script = 'embed.js'
|
||||
(function(d,s) {
|
||||
s = d.createElement('script');s.async=1;s.src = '//' + disqus_shortname + '.disqus.com/'+disqus_script;
|
||||
(d.getElementsByTagName('head')[0]).appendChild(s);
|
||||
})(document)
|
||||
</script>
|
||||
```
|
||||
|
||||
#### Disqus snippet after Pjax integration
|
||||
|
||||
```html
|
||||
<div class="js-Pjax"><!-- need to be here on every pjaxified page, even if empty -->
|
||||
<!-- if (blah blah) { // eventual server side test to know wheter or not you include this script -->
|
||||
<script>
|
||||
var disqus_shortname = 'YOURSHORTNAME'
|
||||
var disqus_identifier = 'PAGEID'
|
||||
var disqus_url = 'PAGEURL'
|
||||
var disqus_script = 'embed.js'
|
||||
|
||||
// here we will only load the disqus <script> if not already loaded
|
||||
if (!window.DISQUS) {
|
||||
(function(d,s) {
|
||||
s = d.createElement('script');s.async=1;s.src = '//' + disqus_shortname + '.disqus.com/'+disqus_script;
|
||||
(d.getElementsByTagName('head')[0]).appendChild(s);
|
||||
})(document)
|
||||
}
|
||||
// if disqus <script> already loaded, we just reset disqus the right way
|
||||
// see http://help.disqus.com/customer/portal/articles/472107-using-disqus-on-ajax-sites
|
||||
else {
|
||||
DISQUS.reset({
|
||||
reload: true,
|
||||
config: function () {
|
||||
this.page.identifier = disqus_identifier
|
||||
this.page.url = disqus_url
|
||||
}
|
||||
})
|
||||
}
|
||||
</script>
|
||||
<!-- } -->
|
||||
</div>
|
||||
```
|
||||
|
||||
**Note: The thing you need to understand is that Pjax handle inline `<script>` only for container you are reloading.**
|
||||
|
||||
---
|
||||
|
||||
## Contributing
|
||||
|
||||
Please read the file nobody reads (make me lie) [CONTRIBUTING.md](CONTRIBUTING.md)
|
||||
Work on a branch, install dev-dependencies, respect coding style & run tests before submitting a bug fix or a feature.
|
||||
|
||||
### tl;dr;
|
||||
$ git clone https://github.com/MoOx/pjax.git
|
||||
$ git checkout -b patch-1
|
||||
$ npm install
|
||||
$ npm test
|
||||
|
||||
Fork, clone, then
|
||||
## [Changelog](CHANGELOG.md)
|
||||
|
||||
```shell
|
||||
$ npm i -g gulp
|
||||
$ npm i
|
||||
$ gulp
|
||||
```
|
||||
|
||||
Now you can work on the file, then make a commit and a push something when gulp doesn't show any error.
|
||||
Thanks.
|
||||
|
||||
## [License](LICENSE-MIT)
|
||||
## [License](LICENSE)
|
||||
|
||||
11
TODO.md
11
TODO.md
@@ -1,11 +0,0 @@
|
||||
## @todo
|
||||
|
||||
- Add tests, like a lot
|
||||
- handle hash in url (see https://github.com/defunkt/jquery-pjax/blob/master/jquery.pjax.js#L287-L303)
|
||||
- add keyboard support
|
||||
- add timeout option (600ms ?)
|
||||
- add form support
|
||||
- add cache
|
||||
- abort previous pjax request when several requests are made by a crazy person clicking everywhere
|
||||
- better switchFallback ?
|
||||
- handle document.write scripts ?
|
||||
23
bower.json
23
bower.json
@@ -1,17 +1,7 @@
|
||||
{
|
||||
"name": "pjax",
|
||||
"version": "0.1.2",
|
||||
"description": "Boost browsing experience using Ajax navigation (+ Push state)",
|
||||
"main": "src/pjax.js",
|
||||
"homepage": "https://github.com/MoOx/pjax",
|
||||
"authors": [
|
||||
"Maxime Thirouin <m@moox.io>"
|
||||
],
|
||||
"moduleType": [
|
||||
"amd",
|
||||
"globals",
|
||||
"node"
|
||||
],
|
||||
"version": "0.1.4",
|
||||
"description": "Easily enable fast Ajax navigation on any website (using pushState + xhr)",
|
||||
"keywords": [
|
||||
"pjax",
|
||||
"push",
|
||||
@@ -21,11 +11,18 @@
|
||||
"transition",
|
||||
"animation"
|
||||
],
|
||||
"main": "src/pjax.js",
|
||||
"homepage": "https://github.com/MoOx/pjax",
|
||||
"authors": [
|
||||
"Maxime Thirouin"
|
||||
],
|
||||
"license": "MIT",
|
||||
"moduleType": [
|
||||
"node"
|
||||
],
|
||||
"ignore": [
|
||||
"**/.*",
|
||||
"node_modules",
|
||||
"bower_components",
|
||||
"test",
|
||||
"tests"
|
||||
]
|
||||
|
||||
56
gulpfile.js
56
gulpfile.js
@@ -1,56 +0,0 @@
|
||||
var pkg = require("./package.json")
|
||||
, gulp = require("gulp")
|
||||
, plumber = require("gulp-plumber")
|
||||
|
||||
///
|
||||
// JS Lint
|
||||
///
|
||||
var jshint = require("gulp-jshint")
|
||||
, jsonFiles = [".jshintrc", "*.json"]
|
||||
, jsFiles = ["*.js", "src/**/*.js"]
|
||||
gulp.task("scripts.lint", function() {
|
||||
gulp.src([].concat(jsonFiles).concat(jsFiles))
|
||||
.pipe(plumber())
|
||||
.pipe(jshint(".jshintrc"))
|
||||
.pipe(jshint.reporter("jshint-stylish"))
|
||||
})
|
||||
|
||||
///
|
||||
// JS Code Sniffing
|
||||
///
|
||||
var jscs = require("gulp-jscs")
|
||||
gulp.task("scripts.cs", function() {
|
||||
gulp.src(jsFiles)
|
||||
.pipe(plumber())
|
||||
.pipe(jscs())
|
||||
})
|
||||
|
||||
// JS Alias
|
||||
gulp.task("scripts", ["scripts.lint", "scripts.cs"])
|
||||
|
||||
///
|
||||
// Watch
|
||||
///
|
||||
gulp.task("watch", function() {
|
||||
gulp.watch(jsFiles, ["scripts"])
|
||||
})
|
||||
|
||||
///
|
||||
// Publish gh-branch
|
||||
///
|
||||
var buildBranch = require("buildbranch")
|
||||
gulp.task("publish", ["test"], function(cb) {
|
||||
buildBranch({folder: "src"}
|
||||
, function(err) {
|
||||
if (err) {
|
||||
throw err
|
||||
}
|
||||
console.log(pkg.name + " published.")
|
||||
cb()
|
||||
})
|
||||
})
|
||||
|
||||
// Aliases
|
||||
gulp.task("build", ["scripts"])
|
||||
gulp.task("test", ["build"])
|
||||
gulp.task("default", ["test", "watch"])
|
||||
230
index.js
Normal file
230
index.js
Normal file
@@ -0,0 +1,230 @@
|
||||
|
||||
var newUid = require("./lib/uniqueid.js")
|
||||
|
||||
var on = require("./lib/events/on.js")
|
||||
// var off = require("./lib/events/on.js")
|
||||
var trigger = require("./lib/events/trigger.js")
|
||||
|
||||
var Pjax = function(options) {
|
||||
this.firstrun = true
|
||||
|
||||
var parseOptions = require("./lib/proto/parse-options.js");
|
||||
parseOptions.apply(this,[options])
|
||||
this.log("Pjax options", this.options)
|
||||
|
||||
this.maxUid = this.lastUid = newUid()
|
||||
|
||||
this.parseDOM(document)
|
||||
|
||||
on(window, "popstate", function(st) {
|
||||
if (st.state) {
|
||||
var opt = Pjax.clone(this.options)
|
||||
opt.url = st.state.url
|
||||
opt.title = st.state.title
|
||||
opt.history = false
|
||||
|
||||
if (st.state.uid < this.lastUid) {
|
||||
opt.backward = true
|
||||
}
|
||||
else {
|
||||
opt.forward = true
|
||||
}
|
||||
this.lastUid = st.state.uid
|
||||
|
||||
// @todo implement history cache here, based on uid
|
||||
this.loadUrl(st.state.url, opt)
|
||||
}
|
||||
}.bind(this))
|
||||
}
|
||||
|
||||
Pjax.prototype = {
|
||||
log: require("./lib/proto/log.js"),
|
||||
|
||||
getElements: require("./lib/proto/get-elements.js"),
|
||||
|
||||
parseDOM: require("./lib/proto/parse-dom.js"),
|
||||
|
||||
refresh: require("./lib/proto/refresh.js"),
|
||||
|
||||
attachLink: require("./lib/proto/attach-link.js"),
|
||||
|
||||
forEachSelectors: function(cb, context, DOMcontext) {
|
||||
return require("./lib/foreach-selectors.js")(this.options.selectors, cb, context, DOMcontext)
|
||||
},
|
||||
|
||||
switchSelectors: function(selectors, fromEl, toEl, options) {
|
||||
return require("./lib/switches-selectors.js")(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) {
|
||||
window.location = href
|
||||
},
|
||||
|
||||
onSwitch: function() {
|
||||
trigger(window, "resize scroll")
|
||||
},
|
||||
|
||||
loadContent: function(html, options) {
|
||||
var tmpEl = document.implementation.createHTMLDocument()
|
||||
|
||||
// parse HTML attributes to copy them
|
||||
// since we are forced to use documentElement.innerHTML (outerHTML can't be used for <html>)
|
||||
var htmlRegex = /<html[^>]+>/gi
|
||||
var htmlAttribsRegex = /\s?[a-z:]+(?:\=(?:\'|\")[^\'\">]+(?:\'|\"))*/gi
|
||||
var matches = html.match(htmlRegex)
|
||||
if (matches && matches.length) {
|
||||
matches = matches[0].match(htmlAttribsRegex)
|
||||
if (matches.length) {
|
||||
matches.shift()
|
||||
matches.forEach(function(htmlAttrib) {
|
||||
var attr = htmlAttrib.trim().split("=")
|
||||
tmpEl.documentElement.setAttribute(attr[0], attr[1].slice(1, -1))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
tmpEl.documentElement.innerHTML = html
|
||||
this.log("load content", tmpEl.documentElement.attributes, tmpEl.documentElement.innerHTML.length)
|
||||
|
||||
// Clear out any focused controls before inserting new page contents.
|
||||
// we clear focus on non form elements
|
||||
if (document.activeElement && !document.activeElement.value) {
|
||||
try {
|
||||
document.activeElement.blur()
|
||||
} catch (e) { }
|
||||
}
|
||||
|
||||
// try {
|
||||
this.switchSelectors(this.options.selectors, tmpEl, document, options)
|
||||
|
||||
// FF bug: Won’t autofocus fields that are inserted via JS.
|
||||
// This behavior is incorrect. So if theres no current focus, autofocus
|
||||
// the last field.
|
||||
//
|
||||
// http://www.w3.org/html/wg/drafts/html/master/forms.html
|
||||
var autofocusEl = Array.prototype.slice.call(document.querySelectorAll("[autofocus]")).pop()
|
||||
if (autofocusEl && document.activeElement !== autofocusEl) {
|
||||
autofocusEl.focus();
|
||||
}
|
||||
|
||||
// execute scripts when DOM have been completely updated
|
||||
this.options.selectors.forEach(function(selector) {
|
||||
Pjax.forEachEls(document.querySelectorAll(selector), function(el) {
|
||||
Pjax.executeScripts(el)
|
||||
})
|
||||
})
|
||||
// }
|
||||
// catch(e) {
|
||||
// if (this.options.debug) {
|
||||
// this.log("Pjax switch fail: ", e)
|
||||
// }
|
||||
// this.switchFallback(tmpEl, document)
|
||||
// }
|
||||
},
|
||||
|
||||
doRequest: require("./lib/request.js"),
|
||||
|
||||
loadUrl: function(href, options) {
|
||||
this.log("load href", href, options)
|
||||
|
||||
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.firstrun = false
|
||||
window.history.replaceState({
|
||||
url: window.location.href,
|
||||
title: document.title,
|
||||
uid: this.maxUid
|
||||
},
|
||||
document.title)
|
||||
}
|
||||
|
||||
// Update browser history
|
||||
this.lastUid = this.maxUid = newUid()
|
||||
window.history.pushState({
|
||||
url: href,
|
||||
title: options.title,
|
||||
uid: this.maxUid
|
||||
},
|
||||
options.title,
|
||||
href)
|
||||
}
|
||||
|
||||
this.forEachSelectors(function(el) {
|
||||
this.parseDOM(el)
|
||||
}, this)
|
||||
|
||||
// Fire Events
|
||||
trigger(document,"pjax:complete pjax:success", options)
|
||||
|
||||
options.analytics()
|
||||
|
||||
// Scroll page to top on new page load
|
||||
if (options.scrollTo !== false) {
|
||||
if (options.scrollTo.length > 1) {
|
||||
window.scrollTo(options.scrollTo[0], options.scrollTo[1])
|
||||
}
|
||||
else {
|
||||
window.scrollTo(0, options.scrollTo)
|
||||
}
|
||||
}
|
||||
}.bind(this))
|
||||
}
|
||||
}
|
||||
|
||||
Pjax.isSupported = require("./lib/is-supported.js");
|
||||
|
||||
//arguably could do `if( require("./lib/is-supported.js")()) {` but that might be a little to simple
|
||||
if (Pjax.isSupported()) {
|
||||
module.exports = Pjax
|
||||
}
|
||||
// if there isn’t required browser functions, returning stupid api
|
||||
else {
|
||||
var stupidPjax = function() {}
|
||||
for (var key in Pjax.prototype) {
|
||||
if (Pjax.prototype.hasOwnProperty(key) && typeof Pjax.prototype[key] === "function") {
|
||||
stupidPjax[key] = stupidPjax
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = stupidPjax
|
||||
}
|
||||
12
lib/clone.js
Normal file
12
lib/clone.js
Normal file
@@ -0,0 +1,12 @@
|
||||
module.exports = function(obj) {
|
||||
if (null === obj || "object" != typeof obj) {
|
||||
return obj
|
||||
}
|
||||
var copy = obj.constructor()
|
||||
for (var attr in obj) {
|
||||
if (obj.hasOwnProperty(attr)) {
|
||||
copy[attr] = obj[attr]
|
||||
}
|
||||
}
|
||||
return copy
|
||||
}
|
||||
29
lib/eval-script.js
Normal file
29
lib/eval-script.js
Normal file
@@ -0,0 +1,29 @@
|
||||
module.exports = function(el) {
|
||||
// console.log("going to execute script", el)
|
||||
|
||||
var code = (el.text || el.textContent || el.innerHTML || "")
|
||||
var head = document.querySelector("head") || document.documentElement
|
||||
var script = document.createElement("script")
|
||||
|
||||
if (code.match("document.write")) {
|
||||
if (console && console.log) {
|
||||
console.log("Script contains document.write. Can’t be executed correctly. Code skipped ", el)
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
script.type = "text/javascript"
|
||||
try {
|
||||
script.appendChild(document.createTextNode(code))
|
||||
}
|
||||
catch (e) {
|
||||
// old IEs have funky script nodes
|
||||
script.text = code
|
||||
}
|
||||
|
||||
// execute
|
||||
head.insertBefore(script, head.firstChild)
|
||||
head.removeChild(script) // avoid pollution
|
||||
|
||||
return true
|
||||
}
|
||||
11
lib/events/off.js
Normal file
11
lib/events/off.js
Normal file
@@ -0,0 +1,11 @@
|
||||
var forEachEls = require("../foreach-els")
|
||||
|
||||
module.exports = function(els, events, listener, useCapture) {
|
||||
events = (typeof events === "string" ? events.split(" ") : events)
|
||||
|
||||
events.forEach(function(e) {
|
||||
forEachEls(els, function(el) {
|
||||
el.removeEventListener(e, listener, useCapture)
|
||||
})
|
||||
})
|
||||
}
|
||||
11
lib/events/on.js
Normal file
11
lib/events/on.js
Normal file
@@ -0,0 +1,11 @@
|
||||
var forEachEls = require("../foreach-els")
|
||||
|
||||
module.exports = function(els, events, listener, useCapture) {
|
||||
events = (typeof events === "string" ? events.split(" ") : events)
|
||||
|
||||
events.forEach(function(e) {
|
||||
forEachEls(els, function(el) {
|
||||
el.addEventListener(e, listener, useCapture)
|
||||
})
|
||||
})
|
||||
}
|
||||
31
lib/events/trigger.js
Normal file
31
lib/events/trigger.js
Normal file
@@ -0,0 +1,31 @@
|
||||
var forEachEls = require("../foreach-els")
|
||||
|
||||
module.exports = function(els, events, opts) {
|
||||
events = (typeof events === "string" ? events.split(" ") : events)
|
||||
|
||||
events.forEach(function(e) {
|
||||
var event // = new CustomEvent(e) // doesn't everywhere yet
|
||||
event = document.createEvent("HTMLEvents")
|
||||
event.initEvent(e, true, true)
|
||||
event.eventName = e
|
||||
if (opts) {
|
||||
Object.keys(opts).forEach(function(key) {
|
||||
event[key] = opts[key]
|
||||
})
|
||||
}
|
||||
|
||||
forEachEls(els, function(el) {
|
||||
var domFix = false
|
||||
if (!el.parentNode) {
|
||||
// THANKS YOU IE (9/10//11 concerned)
|
||||
// dispatchEvent doesn't work if element is not in the dom
|
||||
domFix = true
|
||||
document.body.appendChild(el)
|
||||
}
|
||||
el.dispatchEvent(event)
|
||||
if (domFix) {
|
||||
el.parentNode.removeChild(el)
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
15
lib/execute-scripts.js
Normal file
15
lib/execute-scripts.js
Normal file
@@ -0,0 +1,15 @@
|
||||
var forEachEls = require("./foreach-els")
|
||||
var evalScript = require("./eval-script")
|
||||
// Finds and executes scripts (used for newly added elements)
|
||||
// Needed since innerHTML does not run scripts
|
||||
module.exports = function(el) {
|
||||
// console.log("going to execute scripts for ", el)
|
||||
forEachEls(el.querySelectorAll("script"), function(script) {
|
||||
if (!script.type || script.type.toLowerCase() === "text/javascript") {
|
||||
if (script.parentNode) {
|
||||
script.parentNode.removeChild(script)
|
||||
}
|
||||
evalScript(script)
|
||||
}
|
||||
})
|
||||
}
|
||||
9
lib/foreach-els.js
Normal file
9
lib/foreach-els.js
Normal file
@@ -0,0 +1,9 @@
|
||||
/* global HTMLCollection: true */
|
||||
|
||||
module.exports = function(els, fn, context) {
|
||||
if (els instanceof HTMLCollection || els instanceof NodeList || els instanceof Array) {
|
||||
return Array.prototype.forEach.call(els, fn, context)
|
||||
}
|
||||
// assume simple dom element
|
||||
return fn.call(context, els)
|
||||
}
|
||||
8
lib/foreach-selectors.js
Normal file
8
lib/foreach-selectors.js
Normal file
@@ -0,0 +1,8 @@
|
||||
var forEachEls = require("./foreach-els")
|
||||
|
||||
module.exports = function(selectors, cb, context, DOMcontext) {
|
||||
DOMcontext = DOMcontext || document
|
||||
selectors.forEach(function(selector) {
|
||||
forEachEls(DOMcontext.querySelectorAll(selector), cb, context)
|
||||
})
|
||||
}
|
||||
8
lib/is-supported.js
Normal file
8
lib/is-supported.js
Normal file
@@ -0,0 +1,8 @@
|
||||
module.exports = function() {
|
||||
// Borrowed wholesale from https://github.com/defunkt/jquery-pjax
|
||||
return window.history &&
|
||||
window.history.pushState &&
|
||||
window.history.replaceState &&
|
||||
// pushState isn’t reliable on iOS until 5.
|
||||
!navigator.userAgent.match(/((iPod|iPhone|iPad).+\bOS\s+[1-4]\D|WebApps\/.+CFNetwork)/)
|
||||
}
|
||||
20
lib/polyfills/Function.prototype.bind.js
Normal file
20
lib/polyfills/Function.prototype.bind.js
Normal file
@@ -0,0 +1,20 @@
|
||||
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
|
||||
}
|
||||
}
|
||||
74
lib/proto/attach-link.js
Normal file
74
lib/proto/attach-link.js
Normal file
@@ -0,0 +1,74 @@
|
||||
require("../polyfills/Function.prototype.bind")
|
||||
|
||||
var on = require("../events/on")
|
||||
var clone = require("../clone")
|
||||
|
||||
var attrClick = "data-pjax-click-state"
|
||||
var attrKey = "data-pjax-keyup-state"
|
||||
|
||||
var linkAction = function(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) {
|
||||
el.setAttribute(attrClick, "modifier")
|
||||
return
|
||||
}
|
||||
|
||||
// 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) {
|
||||
el.setAttribute(attrClick, "external")
|
||||
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
|
||||
}
|
||||
|
||||
event.preventDefault()
|
||||
|
||||
// don’t do "nothing" if user try to reload the page by clicking the same link twice
|
||||
if (el.href === window.location.href.split("#")[0]) {
|
||||
el.setAttribute(attrClick, "reload")
|
||||
this.reload()
|
||||
return
|
||||
}
|
||||
|
||||
el.setAttribute(attrClick, "load")
|
||||
this.loadUrl(el.href, clone(this.options))
|
||||
}
|
||||
|
||||
module.exports = function(el) {
|
||||
var that = this
|
||||
|
||||
on(el, "click", function(event) {
|
||||
linkAction.call(that, el, event)
|
||||
})
|
||||
|
||||
on(el, "keyup", function(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) {
|
||||
el.setAttribute(attrKey, "modifier")
|
||||
return
|
||||
}
|
||||
|
||||
if (event.keyCode == 13) {
|
||||
linkAction.call(that, el, event)
|
||||
}
|
||||
}.bind(this))
|
||||
}
|
||||
3
lib/proto/get-elements.js
Normal file
3
lib/proto/get-elements.js
Normal file
@@ -0,0 +1,3 @@
|
||||
module.exports = function(el) {
|
||||
return el.querySelectorAll(this.options.elements)
|
||||
}
|
||||
11
lib/proto/log.js
Normal file
11
lib/proto/log.js
Normal file
@@ -0,0 +1,11 @@
|
||||
module.exports = function() {
|
||||
if (this.options.debug && console) {
|
||||
if (typeof console.log === "function") {
|
||||
console.log.apply(console, arguments);
|
||||
}
|
||||
// ie is weird
|
||||
else if (console.log) {
|
||||
console.log(arguments);
|
||||
}
|
||||
}
|
||||
}
|
||||
7
lib/proto/parse-dom.js
Normal file
7
lib/proto/parse-dom.js
Normal file
@@ -0,0 +1,7 @@
|
||||
var forEachEls = require("../foreach-els")
|
||||
|
||||
var parseElement = require("./parse-element")
|
||||
|
||||
module.exports = function(el) {
|
||||
forEachEls(this.getElements(el), parseElement, this)
|
||||
}
|
||||
17
lib/proto/parse-element.js
Normal file
17
lib/proto/parse-element.js
Normal file
@@ -0,0 +1,17 @@
|
||||
module.exports = function(el) {
|
||||
switch (el.tagName.toLowerCase()) {
|
||||
case "a":
|
||||
// only attach link if el does not already have link attached
|
||||
if (!el.hasAttribute('data-pjax-click-state')) {
|
||||
this.attachLink(el)
|
||||
}
|
||||
break
|
||||
|
||||
case "form":
|
||||
throw "Pjax doesnt support <form> yet."
|
||||
break
|
||||
|
||||
default:
|
||||
throw "Pjax can only be applied on <a> or <form> submit"
|
||||
}
|
||||
}
|
||||
37
lib/proto/parse-options.js
Normal file
37
lib/proto/parse-options.js
Normal file
@@ -0,0 +1,37 @@
|
||||
/* 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) {
|
||||
// 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: options.url, title: options.title})
|
||||
}
|
||||
}
|
||||
this.options.scrollTo = (typeof this.options.scrollTo === 'undefined') ? 0 : this.options.scrollTo;
|
||||
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() {}
|
||||
}
|
||||
}
|
||||
6
lib/proto/refresh.js
Normal file
6
lib/proto/refresh.js
Normal file
@@ -0,0 +1,6 @@
|
||||
|
||||
var parseDom = require("./parse-dom")
|
||||
|
||||
module.exports = function(el) {
|
||||
parseDom(el || document)
|
||||
}
|
||||
3
lib/reload.js
Normal file
3
lib/reload.js
Normal file
@@ -0,0 +1,3 @@
|
||||
module.exports = function() {
|
||||
window.location.reload()
|
||||
}
|
||||
19
lib/request.js
Normal file
19
lib/request.js
Normal file
@@ -0,0 +1,19 @@
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
request.open("GET", location + (!/[?&]/.test(location) ? "?" : "&") + (new Date().getTime()), true)
|
||||
request.setRequestHeader("X-Requested-With", "XMLHttpRequest")
|
||||
request.send(null)
|
||||
return request
|
||||
}
|
||||
35
lib/switches-selectors.js
Normal file
35
lib/switches-selectors.js
Normal file
@@ -0,0 +1,35 @@
|
||||
var forEachEls = require("./foreach-els")
|
||||
|
||||
var defaultSwitches = require("./switches")
|
||||
|
||||
module.exports = function(switches, switchesOptions, selectors, fromEl, toEl, options) {
|
||||
selectors.forEach(function(selector) {
|
||||
var newEls = fromEl.querySelectorAll(selector)
|
||||
var oldEls = toEl.querySelectorAll(selector)
|
||||
if (this.log) {
|
||||
this.log("Pjax switch", selector, newEls, oldEls)
|
||||
}
|
||||
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
|
||||
}
|
||||
|
||||
forEachEls(newEls, function(newEl, i) {
|
||||
var oldEl = oldEls[i]
|
||||
if (this.log) {
|
||||
this.log("newEl", newEl, "oldEl", oldEl)
|
||||
}
|
||||
if (switches[selector]) {
|
||||
switches[selector].bind(this)(oldEl, newEl, options, switchesOptions[selector])
|
||||
}
|
||||
else {
|
||||
defaultSwitches.outerHTML.bind(this)(oldEl, newEl, options)
|
||||
}
|
||||
}, this)
|
||||
}, this)
|
||||
}
|
||||
115
lib/switches.js
Normal file
115
lib/switches.js
Normal file
@@ -0,0 +1,115 @@
|
||||
var on = require("./events/on.js")
|
||||
// var off = require("./lib/events/on.js")
|
||||
// var trigger = require("./lib/events/trigger.js")
|
||||
|
||||
|
||||
module.exports = {
|
||||
outerHTML: function(oldEl, newEl) {
|
||||
oldEl.outerHTML = newEl.outerHTML
|
||||
this.onSwitch()
|
||||
},
|
||||
|
||||
innerHTML: function(oldEl, newEl) {
|
||||
oldEl.innerHTML = newEl.innerHTML
|
||||
oldEl.className = newEl.className
|
||||
this.onSwitch()
|
||||
},
|
||||
|
||||
sideBySide: function(oldEl, newEl, options, switchOptions) {
|
||||
var forEach = Array.prototype.forEach
|
||||
var elsToRemove = []
|
||||
var elsToAdd = []
|
||||
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 animatedElsNumber = 0
|
||||
var sexyAnimationEnd = function(e) {
|
||||
if (e.target != e.currentTarget) {
|
||||
// end triggered by an animation on a child
|
||||
return
|
||||
}
|
||||
|
||||
animatedElsNumber--
|
||||
if (animatedElsNumber <= 0 && elsToRemove) {
|
||||
elsToRemove.forEach(function(el) {
|
||||
// browsing quickly can make the el
|
||||
// already removed by last page update ?
|
||||
if (el.parentNode) {
|
||||
el.parentNode.removeChild(el)
|
||||
}
|
||||
})
|
||||
|
||||
elsToAdd.forEach(function(el) {
|
||||
el.className = el.className.replace(el.getAttribute("data-pjax-classes"), "")
|
||||
el.removeAttribute("data-pjax-classes")
|
||||
// Pjax.off(el, animationEventNames, sexyAnimationEnd, true)
|
||||
})
|
||||
|
||||
elsToAdd = 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.onSwitch()
|
||||
// Pjax.trigger(window, "scroll")
|
||||
}
|
||||
}.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 || {}
|
||||
|
||||
forEach.call(oldEl.childNodes, function(el) {
|
||||
elsToRemove.push(el)
|
||||
if (el.classList && !el.classList.contains("js-Pjax-remove")) {
|
||||
// for fast switch, clean element that just have been added, & not cleaned yet.
|
||||
if (el.hasAttribute("data-pjax-classes")) {
|
||||
el.className = el.className.replace(el.getAttribute("data-pjax-classes"), "")
|
||||
el.removeAttribute("data-pjax-classes")
|
||||
}
|
||||
el.classList.add("js-Pjax-remove")
|
||||
if (switchOptions.callbacks && switchOptions.callbacks.removeElement) {
|
||||
switchOptions.callbacks.removeElement(el)
|
||||
}
|
||||
if (switchOptions.classNames) {
|
||||
el.className += " " + switchOptions.classNames.remove + " " + (options.backward ? switchOptions.classNames.backward : switchOptions.classNames.forward)
|
||||
}
|
||||
animatedElsNumber++
|
||||
on(el, animationEventNames, sexyAnimationEnd, true)
|
||||
}
|
||||
})
|
||||
|
||||
forEach.call(newEl.childNodes, function(el) {
|
||||
if (el.classList) {
|
||||
var addClasses = ""
|
||||
if (switchOptions.classNames) {
|
||||
addClasses = " js-Pjax-add " + switchOptions.classNames.add + " " + (options.backward ? switchOptions.classNames.forward : switchOptions.classNames.backward)
|
||||
}
|
||||
if (switchOptions.callbacks && switchOptions.callbacks.addElement) {
|
||||
switchOptions.callbacks.addElement(el)
|
||||
}
|
||||
el.className += addClasses
|
||||
el.setAttribute("data-pjax-classes", addClasses)
|
||||
elsToAdd.push(el)
|
||||
fragToAppend.appendChild(el)
|
||||
animatedElsNumber++
|
||||
on(el, animationEventNames, sexyAnimationEnd, true)
|
||||
}
|
||||
})
|
||||
|
||||
// pass all className of the parent
|
||||
oldEl.className = newEl.className
|
||||
oldEl.appendChild(fragToAppend)
|
||||
|
||||
// oldEl.style.height = relevantHeight + "px"
|
||||
}
|
||||
}
|
||||
8
lib/uniqueid.js
Normal file
8
lib/uniqueid.js
Normal file
@@ -0,0 +1,8 @@
|
||||
module.exports = (function() {
|
||||
var counter = 0
|
||||
return function() {
|
||||
var id = ("pjax" + (new Date().getTime())) + "_" + counter
|
||||
counter++
|
||||
return id
|
||||
}
|
||||
})()
|
||||
60
package.json
60
package.json
@@ -1,15 +1,7 @@
|
||||
{
|
||||
"name": "pjax",
|
||||
"version": "0.1.2",
|
||||
"description": "Boost browsing experience using Ajax navigation (+ Push state)",
|
||||
"main": "src/pjax.js",
|
||||
"scripts": {
|
||||
"test": "echo \"Error: no test specified\" && exit 1"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/MoOx/pjax.git"
|
||||
},
|
||||
"version": "0.2.0",
|
||||
"description": "Easily enable fast Ajax navigation on any website (using pushState + xhr)",
|
||||
"keywords": [
|
||||
"pjax",
|
||||
"push",
|
||||
@@ -19,18 +11,48 @@
|
||||
"transition",
|
||||
"animation"
|
||||
],
|
||||
"author": "MoOx <m@moox.io>",
|
||||
"license": "MIT",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/MoOx/pjax.git"
|
||||
},
|
||||
"homepage": "https://github.com/MoOx/pjax",
|
||||
"bugs": {
|
||||
"url": "https://github.com/MoOx/pjax/issues"
|
||||
},
|
||||
"homepage": "https://github.com/MoOx/pjax",
|
||||
"author": "Maxime Thirouin",
|
||||
"license": "MIT",
|
||||
"main": "src/pjax.js",
|
||||
"files": [
|
||||
"CHANGELOG.md",
|
||||
"LICENSE",
|
||||
"src"
|
||||
],
|
||||
"devDependencies": {
|
||||
"jshint-stylish": "^0.1.5",
|
||||
"gulp-jscs": "^0.3.2",
|
||||
"gulp-plumber": "^0.5.6",
|
||||
"gulp": "^3.5.6",
|
||||
"gulp-jshint": "^1.5.1",
|
||||
"buildbranch": "0.0.1"
|
||||
"browserify": "^3.46.0",
|
||||
"coverify": "^1.0.6",
|
||||
"jscs": "^1.6.2",
|
||||
"jshint": "^2.5.6",
|
||||
"tape": "^3.0.0",
|
||||
"testling": "^1.6.1"
|
||||
},
|
||||
"scripts": {
|
||||
"lint": "jscs **/*.js && jshint . --exclude-path .gitignore",
|
||||
"test": "npm run lint && testling",
|
||||
"test--html": "testling --html > tests/scripts/index.html",
|
||||
"coverage": "browserify -t coverify tests/**/*.js | testling | coverify"
|
||||
},
|
||||
"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"
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
605
src/pjax.js
605
src/pjax.js
@@ -1,605 +0,0 @@
|
||||
;(function(root, factory) {
|
||||
if (typeof exports === "object") {
|
||||
// CommonJS
|
||||
module.exports = factory()
|
||||
}
|
||||
else if (typeof define === "function" && define.amd) {
|
||||
// AMD
|
||||
define([], factory)
|
||||
}
|
||||
else {
|
||||
// Global Variables
|
||||
root.Pjax = factory()
|
||||
}
|
||||
}(this, function() {
|
||||
"use strict";
|
||||
|
||||
function newUid() {
|
||||
return (new Date().getTime())
|
||||
}
|
||||
|
||||
var Pjax = function(options) {
|
||||
this.firstrun = true
|
||||
|
||||
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) {
|
||||
// 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": options.url, "title": options.title})
|
||||
}
|
||||
}
|
||||
this.options.scrollTo = this.options.scrollTo || 0
|
||||
this.options.debug = this.options.debug || false
|
||||
|
||||
this.maxUid = this.lastUid = newUid()
|
||||
|
||||
// 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
|
||||
}
|
||||
|
||||
this.log("Pjax options", this.options)
|
||||
|
||||
if (typeof options.analytics !== "function") {
|
||||
options.analytics = function() {}
|
||||
}
|
||||
|
||||
this.parseDOM(document)
|
||||
|
||||
Pjax.on(window, "popstate", function(st) {
|
||||
if (st.state) {
|
||||
var opt = Pjax.clone(this.options)
|
||||
opt.url = st.state.url
|
||||
opt.title = st.state.title
|
||||
opt.history = false
|
||||
|
||||
if (st.state.uid < this.lastUid) {
|
||||
opt.backward = true
|
||||
}
|
||||
else {
|
||||
opt.forward = true
|
||||
}
|
||||
this.lastUid = st.state.uid
|
||||
|
||||
// @todo implement history cache here, based on uid
|
||||
this.loadUrl(st.state.url, opt)
|
||||
}
|
||||
}.bind(this))
|
||||
|
||||
}
|
||||
|
||||
// make internal methods public
|
||||
Pjax.isSupported = function() {
|
||||
// Borrowed wholesale from https://github.com/defunkt/jquery-pjax
|
||||
return window.history &&
|
||||
window.history.pushState &&
|
||||
window.history.replaceState &&
|
||||
// pushState isn’t reliable on iOS until 5.
|
||||
!navigator.userAgent.match(/((iPod|iPhone|iPad).+\bOS\s+[1-4]|WebApps\/.+CFNetwork)/)
|
||||
}
|
||||
|
||||
Pjax.forEachEls = function(els, fn, context) {
|
||||
if (els instanceof HTMLCollection || els instanceof NodeList) {
|
||||
return Array.prototype.forEach.call(els, fn, context)
|
||||
}
|
||||
// assume simple dom element
|
||||
fn.call(context, els)
|
||||
}
|
||||
|
||||
Pjax.on = function(els, events, listener, useCapture) {
|
||||
events = (typeof events === "string" ? events.split(" ") : events)
|
||||
|
||||
events.forEach(function(e) {
|
||||
Pjax.forEachEls(els, function(el) {
|
||||
el.addEventListener(e, listener, useCapture)
|
||||
})
|
||||
}, this)
|
||||
}
|
||||
|
||||
Pjax.off = function(els, events, listener, useCapture) {
|
||||
events = (typeof events === "string" ? events.split(" ") : events)
|
||||
|
||||
events.forEach(function(e) {
|
||||
Pjax.forEachEls(els, function(el) {
|
||||
el.removeEventListener(e, listener, useCapture)
|
||||
})
|
||||
}, this)
|
||||
}
|
||||
|
||||
Pjax.trigger = function(els, events) {
|
||||
events = (typeof events === "string" ? events.split(" ") : events)
|
||||
|
||||
events.forEach(function(e) {
|
||||
var event
|
||||
if (document.createEvent) {
|
||||
event = document.createEvent("HTMLEvents")
|
||||
event.initEvent(e, true, true)
|
||||
}
|
||||
else {
|
||||
event = document.createEventObject()
|
||||
event.eventType = e
|
||||
}
|
||||
|
||||
event.eventName = e
|
||||
|
||||
if (document.createEvent) {
|
||||
Pjax.forEachEls(els, function(el) {
|
||||
el.dispatchEvent(event)
|
||||
})
|
||||
}
|
||||
else {
|
||||
Pjax.forEachEls(els, function(el) {
|
||||
el.fireEvent("on" + event.eventType, event)
|
||||
})
|
||||
}
|
||||
}, this)
|
||||
}
|
||||
|
||||
Pjax.clone = function(obj) {
|
||||
if (null === obj || "object" != typeof obj) {
|
||||
return obj
|
||||
}
|
||||
var copy = obj.constructor()
|
||||
for (var attr in obj) {
|
||||
if (obj.hasOwnProperty(attr)) {
|
||||
copy[attr] = obj[attr]
|
||||
}
|
||||
}
|
||||
return copy
|
||||
}
|
||||
|
||||
// Finds and executes scripts (used for newly added elements)
|
||||
// Needed since innerHTML does not run scripts
|
||||
Pjax.executeScripts = function(el) {
|
||||
// console.log("going to execute scripts for ", el)
|
||||
Pjax.forEachEls(el.querySelectorAll("script"), function(script) {
|
||||
if (!script.type || script.type.toLowerCase() === "text/javascript") {
|
||||
if (script.parentNode) {
|
||||
script.parentNode.removeChild(script)
|
||||
}
|
||||
Pjax.evalScript(script)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
Pjax.evalScript = function(el) {
|
||||
// console.log("going to execute script", el)
|
||||
|
||||
var code = (el.text || el.textContent || el.innerHTML || "")
|
||||
, head = document.querySelector("head") || document.documentElement
|
||||
, script = document.createElement("script")
|
||||
|
||||
if (code.match("document.write")) {
|
||||
if (console && console.log) {
|
||||
console.log("Script contains document.write. Can’t be executed correctly. Code skipped ", el)
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
script.type = "text/javascript"
|
||||
try {
|
||||
script.appendChild(document.createTextNode(code))
|
||||
}
|
||||
catch (e) {
|
||||
// old IEs have funky script nodes
|
||||
script.text = code
|
||||
}
|
||||
|
||||
// execute
|
||||
head.insertBefore(script, head.firstChild)
|
||||
head.removeChild(script) // avoid pollution
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
Pjax.prototype = {
|
||||
log: function() {
|
||||
if (this.options.debug && console) {
|
||||
if (typeof console.log === "function") {
|
||||
console.log.apply(console, arguments);
|
||||
}
|
||||
// ie is weird
|
||||
else if (console.log) {
|
||||
console.log(arguments);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
, getElements: function(el) {
|
||||
return el.querySelectorAll(this.options.elements)
|
||||
}
|
||||
|
||||
, parseDOM: function(el) {
|
||||
Pjax.forEachEls(this.getElements(el), function(el) {
|
||||
switch (el.tagName.toLowerCase()) {
|
||||
case "a": this.attachLink(el)
|
||||
break
|
||||
case "form":
|
||||
// todo
|
||||
this.log("Pjax doesnt support <form> yet. TODO :)")
|
||||
break
|
||||
default:
|
||||
throw "Pjax can only be applied on <a> or <form> submit"
|
||||
}
|
||||
}, this)
|
||||
}
|
||||
|
||||
, attachLink: function(el) {
|
||||
Pjax.on(el, "click", function(event) {
|
||||
//var el = event.currentTarget
|
||||
|
||||
// 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 -1
|
||||
}
|
||||
|
||||
// Ignore external links.
|
||||
if (el.protocol !== window.location.protocol || el.host !== window.location.host) {
|
||||
return -2
|
||||
}
|
||||
|
||||
// Ignore anchors on the same page
|
||||
if (el.pathname === location.pathname && el.hash.length > 0) {
|
||||
return -3
|
||||
}
|
||||
|
||||
// Ignore anchors on the same page
|
||||
if (el.hash && el.href.replace(el.hash, "") === location.href.replace(location.hash, "")) {
|
||||
return -4
|
||||
}
|
||||
|
||||
// Ignore empty anchor "foo.html#"
|
||||
if (el.href === location.href + "#") {
|
||||
return -5
|
||||
}
|
||||
|
||||
event.preventDefault()
|
||||
|
||||
// don’t do "nothing" if user try to reload the page
|
||||
if (el.href === window.location.href) {
|
||||
window.location.reload()
|
||||
return -6
|
||||
}
|
||||
|
||||
this.loadUrl(el.href, Pjax.clone(this.options))
|
||||
}.bind(this))
|
||||
|
||||
Pjax.on(el, "keyup", function(event) {
|
||||
this.log("pjax todo")
|
||||
// todo handle a link hitted by keyboard (enter/space) when focus is on it
|
||||
}.bind(this))
|
||||
}
|
||||
|
||||
, forEachSelectors: function(cb, context, DOMcontext) {
|
||||
DOMcontext = DOMcontext || document
|
||||
this.options.selectors.forEach(function(selector) {
|
||||
Pjax.forEachEls(DOMcontext.querySelectorAll(selector), cb, context)
|
||||
})
|
||||
}
|
||||
|
||||
, switchSelectors: function(selectors, fromEl, toEl, options) {
|
||||
selectors.forEach(function(selector) {
|
||||
var newEls = fromEl.querySelectorAll(selector)
|
||||
var oldEls = toEl.querySelectorAll(selector)
|
||||
this.log("Pjax switch", selector, newEls, oldEls)
|
||||
if (newEls.length !== oldEls.length) {
|
||||
// Pjax.forEachEls(newEls, function(el) {
|
||||
// this.log("newEl", el, el.outerHTML)
|
||||
// }, this)
|
||||
// Pjax.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
|
||||
}
|
||||
|
||||
Pjax.forEachEls(newEls, function(newEl, i) {
|
||||
var oldEl = oldEls[i]
|
||||
this.log("newEl", newEl, "oldEl", oldEl)
|
||||
if (this.options.switches[selector]) {
|
||||
this.options.switches[selector].bind(this)(oldEl, newEl, options, this.options.switchesOptions[selector])
|
||||
}
|
||||
else {
|
||||
Pjax.switches.outerHTML.bind(this)(oldEl, newEl, options)
|
||||
}
|
||||
}, this)
|
||||
}, this)
|
||||
}
|
||||
|
||||
// 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) {
|
||||
window.location = href
|
||||
}
|
||||
|
||||
, onSwitch: function() {
|
||||
Pjax.trigger(window, "resize scroll")
|
||||
}
|
||||
|
||||
, loadContent: function(html, options) {
|
||||
var tmpEl = document.implementation.createHTMLDocument()
|
||||
|
||||
// parse HTML attributes to copy them
|
||||
// since we are forced to use documentElement.innerHTML (outerHTML can't be used for <html>)
|
||||
, htmlRegex = /<html[^>]+>/gi
|
||||
, htmlAttribsRegex = /\s?[a-z:]+(?:\=(?:\'|\")[^\'\">]+(?:\'|\"))*/gi
|
||||
, matches = html.match(htmlRegex)
|
||||
if (matches.length) {
|
||||
matches = matches[0].match(htmlAttribsRegex)
|
||||
if (matches.length) {
|
||||
matches.shift()
|
||||
matches.forEach(function(htmlAttrib) {
|
||||
var attr = htmlAttrib.trim().split("=")
|
||||
tmpEl.documentElement.setAttribute(attr[0], attr[1].slice(1, -1))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
tmpEl.documentElement.innerHTML = html
|
||||
this.log("load content", tmpEl.documentElement.attributes, tmpEl.documentElement.innerHTML.length)
|
||||
// try {
|
||||
this.switchSelectors(this.options.selectors, tmpEl, document, options)
|
||||
|
||||
// FF bug: Won’t autofocus fields that are inserted via JS.
|
||||
// This behavior is incorrect. So if theres no current focus, autofocus
|
||||
// the last field.
|
||||
//
|
||||
// http://www.w3.org/html/wg/drafts/html/master/forms.html
|
||||
var autofocusEl = Array.prototype.slice.call(document.querySelectorAll("[autofocus]")).pop()
|
||||
if (autofocusEl && document.activeElement !== autofocusEl) {
|
||||
autofocusEl.focus();
|
||||
}
|
||||
|
||||
// execute scripts when DOM have been completely updated
|
||||
this.options.selectors.forEach(function(selector) {
|
||||
Pjax.forEachEls(document.querySelectorAll(selector), function(el) {
|
||||
Pjax.executeScripts(el)
|
||||
})
|
||||
})
|
||||
// }
|
||||
// catch(e) {
|
||||
// if (this.options.debug) {
|
||||
// this.log("Pjax switch fail: ", e)
|
||||
// }
|
||||
// this.switchFallback(tmpEl, document)
|
||||
// }
|
||||
}
|
||||
|
||||
, doRequest: function(location, callback) {
|
||||
var request = new XMLHttpRequest()
|
||||
|
||||
request.onreadystatechange = function() {
|
||||
if (request.readyState === 4 && request.status === 200) {
|
||||
callback(request.responseText)
|
||||
}
|
||||
else if (request.readyState === 4 && (request.status === 404 || request.status === 500)){
|
||||
callback(false)
|
||||
}
|
||||
}
|
||||
|
||||
request.open("GET", location + (!/[?&]/.test(location) ? "?" : "&") + (new Date().getTime()), true)
|
||||
request.setRequestHeader("X-Requested-With", "XMLHttpRequest")
|
||||
request.send(null)
|
||||
}
|
||||
|
||||
, loadUrl: function(href, options) {
|
||||
this.log("load href", href, options)
|
||||
|
||||
Pjax.trigger(document, "pjax:send", options);
|
||||
|
||||
// Do the request
|
||||
this.doRequest(href, function(html) {
|
||||
|
||||
// Fail if unable to load HTML via AJAX
|
||||
if (html === false) {
|
||||
Pjax.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.firstrun = false
|
||||
window.history.replaceState({
|
||||
"url": window.location.href
|
||||
, "title": document.title
|
||||
, "uid": this.maxUid
|
||||
}
|
||||
, document.title)
|
||||
}
|
||||
|
||||
// Update browser history
|
||||
this.lastUid = this.maxUid = newUid()
|
||||
window.history.pushState({
|
||||
"url": href
|
||||
, "title": options.title
|
||||
, "uid": this.maxUid
|
||||
}
|
||||
, options.title
|
||||
, href)
|
||||
}
|
||||
|
||||
this.forEachSelectors(function(el) {
|
||||
this.parseDOM(el)
|
||||
}, this)
|
||||
|
||||
// Fire Events
|
||||
Pjax.trigger(document,"pjax:complete pjax:success", options)
|
||||
|
||||
options.analytics()
|
||||
|
||||
// Scroll page to top on new page load
|
||||
if (options.scrollTo !== false) {
|
||||
if (options.scrollTo.length > 1) {
|
||||
window.scrollTo(options.scrollTo[0], options.scrollTo[1])
|
||||
}
|
||||
else {
|
||||
window.scrollTo(0, options.scrollTo)
|
||||
}
|
||||
}
|
||||
}.bind(this))
|
||||
}
|
||||
}
|
||||
|
||||
Pjax.switches = {
|
||||
outerHTML: function(oldEl, newEl, options) {
|
||||
oldEl.outerHTML = newEl.outerHTML
|
||||
this.onSwitch()
|
||||
}
|
||||
|
||||
, innerHTML: function(oldEl, newEl, options) {
|
||||
oldEl.innerHTML = newEl.innerHTML
|
||||
oldEl.className = newEl.className
|
||||
this.onSwitch()
|
||||
}
|
||||
|
||||
, sideBySide: function(oldEl, newEl, options, switchOptions) {
|
||||
var elsToRemove = []
|
||||
, elsToAdd = []
|
||||
, fragToAppend = document.createDocumentFragment()
|
||||
// height transition are shitty on safari
|
||||
// so commented for now (until I found something ?)
|
||||
// , relevantHeight = 0
|
||||
, animationEventNames = "animationend webkitAnimationEnd MSAnimationEnd oanimationend"
|
||||
, animatedElsNumber = 0
|
||||
, sexyAnimationEnd = function(e) {
|
||||
if (e.target != e.currentTarget) {
|
||||
// end triggered by an animation on a child
|
||||
return
|
||||
}
|
||||
|
||||
animatedElsNumber--
|
||||
if (animatedElsNumber <= 0 && elsToRemove) {
|
||||
elsToRemove.forEach(function(el) {
|
||||
// browsing quickly can make the el
|
||||
// already removed by last page update ?
|
||||
if (el.parentNode) {
|
||||
el.parentNode.removeChild(el)
|
||||
}
|
||||
})
|
||||
|
||||
elsToAdd.forEach(function(el) {
|
||||
el.className = el.className.replace(el.getAttribute("data-pjax-classes"), "")
|
||||
el.removeAttribute("data-pjax-classes")
|
||||
// Pjax.off(el, animationEventNames, sexyAnimationEnd, true)
|
||||
})
|
||||
|
||||
elsToAdd = 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.onSwitch()
|
||||
//Pjax.trigger(window, "scroll")
|
||||
}
|
||||
}.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"
|
||||
|
||||
forEach.call(oldEl.childNodes, function(el) {
|
||||
elsToRemove.push(el)
|
||||
if (el.classList && !el.classList.contains("js-Pjax-remove")) {
|
||||
// for fast switch, clean element that just have been added, & not cleaned yet.
|
||||
if (el.hasAttribute("data-pjax-classes")) {
|
||||
el.className = el.className.replace(el.getAttribute("data-pjax-classes"), "")
|
||||
el.removeAttribute("data-pjax-classes")
|
||||
}
|
||||
el.classList.add("js-Pjax-remove")
|
||||
if (switchOptions.callbacks && switchOptions.callbacks.removeElement) {
|
||||
switchOptions.callbacks.removeElement(el)
|
||||
}
|
||||
el.className += " " + switchOptions.classNames.remove + " " + (options.backward ? switchOptions.classNames.backward : switchOptions.classNames.forward)
|
||||
animatedElsNumber++
|
||||
Pjax.on(el, animationEventNames, sexyAnimationEnd, true)
|
||||
}
|
||||
})
|
||||
|
||||
forEach.call(newEl.childNodes, function(el) {
|
||||
if (el.classList) {
|
||||
var addClasses = " js-Pjax-add " + switchOptions.classNames.add + " " + (options.backward ? switchOptions.classNames.forward : switchOptions.classNames.backward)
|
||||
if (switchOptions.callbacks && switchOptions.callbacks.addElement) {
|
||||
switchOptions.callbacks.addElement(el)
|
||||
}
|
||||
el.className += addClasses
|
||||
el.setAttribute("data-pjax-classes", addClasses)
|
||||
elsToAdd.push(el)
|
||||
fragToAppend.appendChild(el)
|
||||
animatedElsNumber++
|
||||
Pjax.on(el, animationEventNames, sexyAnimationEnd, true)
|
||||
}
|
||||
})
|
||||
|
||||
// pass all className of the parent
|
||||
oldEl.className = newEl.className
|
||||
oldEl.appendChild(fragToAppend)
|
||||
|
||||
// oldEl.style.height = relevantHeight + "px"
|
||||
}
|
||||
}
|
||||
|
||||
if (Pjax.isSupported()) {
|
||||
return Pjax
|
||||
}
|
||||
// if there isn’t required browser functions, returning stupid api
|
||||
else {
|
||||
var stupidPjax = function() {}
|
||||
for (var key in Pjax.prototype) {
|
||||
if (Pjax.prototype.hasOwnProperty(key) && typeof Pjax.prototype[key] === "function") {
|
||||
stupidPjax[key] = stupidPjax
|
||||
}
|
||||
}
|
||||
|
||||
return stupidPjax
|
||||
}
|
||||
|
||||
}));
|
||||
12496
tests/index.html
Normal file
12496
tests/index.html
Normal file
File diff suppressed because one or more lines are too long
17
tests/lib/clone.js
Normal file
17
tests/lib/clone.js
Normal file
@@ -0,0 +1,17 @@
|
||||
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()
|
||||
})
|
||||
22
tests/lib/eval-scripts.js
Normal file
22
tests/lib/eval-scripts.js
Normal file
@@ -0,0 +1,22 @@
|
||||
var tape = require("tape")
|
||||
|
||||
var evalScript = require("../../lib/eval-script")
|
||||
|
||||
tape("test evalScript method", function(t) {
|
||||
document.body.className = ""
|
||||
|
||||
var script = document.createElement("script")
|
||||
script.innerHTML = "document.body.className = 'executed'"
|
||||
|
||||
t.equal(document.body.className, "", "script hasn't been executed yet")
|
||||
|
||||
evalScript(script)
|
||||
t.equal(document.body.className, "executed", "script has been properly executed")
|
||||
|
||||
// script.innerHTML = "document.write('failure')"
|
||||
// var bodyText = document.body.text
|
||||
// evalScript(script)
|
||||
// t.equal(document.body.text, bodyText, "document.write hasn't been executed")
|
||||
|
||||
t.end()
|
||||
})
|
||||
92
tests/lib/events.js
Normal file
92
tests/lib/events.js
Normal file
@@ -0,0 +1,92 @@
|
||||
var tape = require("tape")
|
||||
|
||||
var on = require("../../lib/events/on")
|
||||
var off = require("../../lib/events/off")
|
||||
var trigger = require("../../lib/events/trigger")
|
||||
|
||||
var el = document.createElement("div")
|
||||
var el2 = document.createElement("span")
|
||||
var els = [el, el2]
|
||||
// var eventType2 = "resize"
|
||||
// var eventsType = "click resize"
|
||||
var classCb = function() {
|
||||
this.className += "on"
|
||||
}
|
||||
var attrCb = function() {
|
||||
this.setAttribute("data-state", this.getAttribute("data-state") + "ON")
|
||||
}
|
||||
|
||||
tape("test events on/off/trigger for one element, one event", function(t) {
|
||||
el.className = ""
|
||||
on(el, "click", classCb)
|
||||
trigger(el, "click")
|
||||
t.equal(el.className, "on", "attached callback has been fired properly")
|
||||
|
||||
el.className = "off"
|
||||
off(el, "click", classCb)
|
||||
trigger(el, "click")
|
||||
t.equal(el.className, "off", "triggered event didn't fire detached callback")
|
||||
|
||||
t.end()
|
||||
})
|
||||
|
||||
tape("test events on/off/trigger for multiple elements, one event", function(t) {
|
||||
el.className = ""
|
||||
el2.className = ""
|
||||
|
||||
on(els, "click", classCb)
|
||||
trigger(els, "click")
|
||||
t.equal(el.className, "on", "attached callback has been fired properly on the first element")
|
||||
t.equal(el2.className, "on", "attached callback has been fired properly on the second element")
|
||||
|
||||
el.className = "off"
|
||||
el2.className = "off"
|
||||
off(els, "click", classCb)
|
||||
trigger(els, "click")
|
||||
t.equal(el.className, "off", "triggered event didn't fire detached callback on the first element")
|
||||
t.equal(el2.className, "off", "triggered event didn't fire detached callback on the second element")
|
||||
|
||||
t.end()
|
||||
})
|
||||
|
||||
tape("test events on/off/trigger for one element, multiple events", function(t) {
|
||||
el.className = ""
|
||||
on(el, "click mouseover", classCb)
|
||||
trigger(el, "click mouseover")
|
||||
t.equal(el.className, "onon", "attached callbacks have been fired properly")
|
||||
|
||||
el.className = "off"
|
||||
off(el, "click mouseover", classCb)
|
||||
trigger(el, "click mouseover")
|
||||
t.equal(el.className, "off", "triggered events didn't fire detached callback")
|
||||
|
||||
t.end()
|
||||
})
|
||||
|
||||
tape("test events on/off/trigger for multiple elements, multiple events", function(t) {
|
||||
el.className = ""
|
||||
el2.className = ""
|
||||
el.setAttribute("data-state", "")
|
||||
el2.setAttribute("data-state", "")
|
||||
on(els, "click mouseover", classCb)
|
||||
on(els, "resize scroll", attrCb)
|
||||
trigger(els, "click mouseover resize scroll")
|
||||
t.equal(el.className, "onon", "attached callbacks has been fired properly on the first element")
|
||||
t.equal(el.getAttribute("data-state"), "ONON", "attached callbacks has been fired properly on the first element")
|
||||
t.equal(el2.className, "onon", "attached callbacks has been fired properly on the second element")
|
||||
t.equal(el2.getAttribute("data-state"), "ONON", "attached callbacks has been fired properly on the second element")
|
||||
|
||||
el.className = "off"
|
||||
el2.className = "off"
|
||||
el.setAttribute("data-state", "off")
|
||||
el2.setAttribute("data-state", "off")
|
||||
off(els, "click mouseover", classCb)
|
||||
off(els, "resize scroll", attrCb)
|
||||
trigger(els, "click mouseover resize scroll")
|
||||
t.equal(el.className, "off", "triggered events didn't fire detached callbacks on the first element")
|
||||
t.equal(el.getAttribute("data-state"), "off", "triggered events didn't fire detached callbacks on the first element")
|
||||
t.equal(el2.className, "off", "triggered events didn't fire detached callbacks on the first element")
|
||||
t.equal(el2.getAttribute("data-state"), "off", "triggered events didn't fire detached callbacks on the first element")
|
||||
|
||||
t.end()
|
||||
})
|
||||
16
tests/lib/execute-scripts.js
Normal file
16
tests/lib/execute-scripts.js
Normal file
@@ -0,0 +1,16 @@
|
||||
var tape = require("tape")
|
||||
|
||||
var executeScripts = require("../../lib/execute-scripts")
|
||||
|
||||
tape("test executeScripts method", function(t) {
|
||||
document.body.className = ""
|
||||
|
||||
var container = document.createElement("div")
|
||||
container.innerHTML = "<" + "script" + ">document.body.className = 'executed';</" + "script" + "><" + "script" + ">document.body.className += ' correctly';</" + "script" + ">"
|
||||
|
||||
t.equal(document.body.className, "", "script hasn't been executed yet")
|
||||
executeScripts(container)
|
||||
t.equal(document.body.className, "executed correctly", "script has been properly executed")
|
||||
|
||||
t.end()
|
||||
})
|
||||
45
tests/lib/foreach-els.js
Normal file
45
tests/lib/foreach-els.js
Normal file
@@ -0,0 +1,45 @@
|
||||
var tape = require("tape")
|
||||
|
||||
var forEachEls = require("../../lib/foreach-els.js")
|
||||
|
||||
var div = document.createElement("div")
|
||||
var span = document.createElement("span")
|
||||
var cb = function(el) {
|
||||
el.innerHTML = "boom"
|
||||
}
|
||||
|
||||
tape("test forEachEls on one element", function(t) {
|
||||
div.innerHTML = "div tag"
|
||||
forEachEls(div, cb)
|
||||
|
||||
t.equal(div.innerHTML, "boom", "works correctly on one element")
|
||||
t.end()
|
||||
})
|
||||
|
||||
|
||||
tape("test forEachEls on an array", function(t) {
|
||||
div.innerHTML = "div tag"
|
||||
span.innerHTML = "span tag"
|
||||
|
||||
forEachEls([div, span], cb)
|
||||
|
||||
t.equal(div.innerHTML, "boom", "works correctly on the first element of the array")
|
||||
t.equal(span.innerHTML, "boom", "works correctly on the last element of the array")
|
||||
|
||||
t.end()
|
||||
})
|
||||
|
||||
tape("test forEachEls on a NodeList", function(t) {
|
||||
div.innerHTML = "div tag"
|
||||
span.innerHTML = "span tag"
|
||||
|
||||
var frag = document.createDocumentFragment()
|
||||
frag.appendChild(div)
|
||||
frag.appendChild(span)
|
||||
forEachEls(frag.childNodes, cb)
|
||||
|
||||
t.equal(div.innerHTML, "boom", "works correctly on the first element of the document fragment")
|
||||
t.equal(span.innerHTML, "boom", "works correctly on the last element of the document fragment")
|
||||
|
||||
t.end()
|
||||
})
|
||||
24
tests/lib/foreach-selectors.js
Normal file
24
tests/lib/foreach-selectors.js
Normal file
@@ -0,0 +1,24 @@
|
||||
var tape = require("tape")
|
||||
|
||||
var forEachEls = require("../../lib/foreach-selectors.js")
|
||||
|
||||
var cb = function(el) {
|
||||
el.className = "modified"
|
||||
}
|
||||
|
||||
tape("test forEachSelector", function(t) {
|
||||
forEachEls(["html", "body"], cb)
|
||||
|
||||
t.equal(document.documentElement.className, "modified", "callback has been executed on first selector")
|
||||
t.equal(document.body.className, "modified", "callback has been executed on first selector")
|
||||
|
||||
document.documentElement.className = ""
|
||||
document.body.className = ""
|
||||
|
||||
forEachEls(["html", "body"], cb, null, document.documentElement)
|
||||
|
||||
t.equal(document.documentElement.className, "", "callback has not been executed on first selector when context is used")
|
||||
t.equal(document.body.className, "modified", "callback has been executed on first selector when context is used")
|
||||
|
||||
t.end()
|
||||
})
|
||||
8
tests/lib/is-supported.js
Normal file
8
tests/lib/is-supported.js
Normal file
@@ -0,0 +1,8 @@
|
||||
var tape = require("tape")
|
||||
|
||||
var isSupported = require("../../lib/is-supported.js")
|
||||
|
||||
tape("test isSupported method", function(t) {
|
||||
t.true(isSupported(), "well, we run test on supported browser, so it should be ok here")
|
||||
t.end()
|
||||
})
|
||||
58
tests/lib/proto/attach-link.js
Normal file
58
tests/lib/proto/attach-link.js
Normal file
@@ -0,0 +1,58 @@
|
||||
var tape = require("tape")
|
||||
|
||||
var on = require("../../../lib/events/on")
|
||||
var trigger = require("../../../lib/events/trigger")
|
||||
var attachLink = require("../../../lib/proto/attach-link")
|
||||
|
||||
var a = document.createElement("a")
|
||||
var attr = "data-pjax-click-state"
|
||||
var preventDefault = function(e) { e.preventDefault() }
|
||||
|
||||
tape("test attach link prototype method", function(t) {
|
||||
t.plan(7)
|
||||
|
||||
attachLink.call({
|
||||
options: {},
|
||||
reload: function() {
|
||||
t.equal(a.getAttribute(attr), "reload", "triggering exact same url reload the page")
|
||||
},
|
||||
loadUrl: function() {
|
||||
t.equal(a.getAttribute(attr), "load", "triggering a internal link actually load the page")
|
||||
}
|
||||
}, a)
|
||||
|
||||
var internalUri = window.location.protocol + "//" + window.location.host + window.location.pathname + window.location.search
|
||||
|
||||
a.href = internalUri
|
||||
on(a, "click", preventDefault) // to avoid link to be open (break testing env)
|
||||
trigger(a, "click", {metaKey: true})
|
||||
t.equal(a.getAttribute(attr), "modifier", "event key modifier stop behavior")
|
||||
|
||||
a.href = "http://external.com/"
|
||||
trigger(a, "click")
|
||||
t.equal(a.getAttribute(attr), "external", "external url stop behavior")
|
||||
|
||||
a.href = internalUri + "#anchor"
|
||||
trigger(a, "click")
|
||||
t.equal(a.getAttribute(attr), "anchor-present", "internal anchor stop behavior")
|
||||
|
||||
window.location.hash = "#anchor"
|
||||
a.href = internalUri + "#another-anchor"
|
||||
trigger(a, "click")
|
||||
t.notEqual(a.getAttribute(attr), "anchor", "differents anchors stop behavior")
|
||||
window.location.hash = ""
|
||||
|
||||
a.href = internalUri + "#"
|
||||
trigger(a, "click")
|
||||
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"
|
||||
trigger(a, "click")
|
||||
// see loadUrl defined above
|
||||
|
||||
t.end()
|
||||
})
|
||||
17
tests/lib/proto/parse-element.js
Normal file
17
tests/lib/proto/parse-element.js
Normal file
@@ -0,0 +1,17 @@
|
||||
var tape = require("tape")
|
||||
|
||||
var parseElement = require("../../../lib/proto/parse-element")
|
||||
var protoMock = {attachLink: function() { return true}}
|
||||
tape("test parse element prototype method", function(t) {
|
||||
t.doesNotThrow(function() {
|
||||
var a = document.createElement("a")
|
||||
parseElement.call(protoMock, a)
|
||||
}, "<a> element can be parsed")
|
||||
|
||||
t.throws(function() {
|
||||
var form = document.createElement("form")
|
||||
parseElement.call(protoMock, form)
|
||||
}, "<form> cannot be used (for now)")
|
||||
|
||||
t.end()
|
||||
})
|
||||
72
tests/lib/proto/parse-options.js
Normal file
72
tests/lib/proto/parse-options.js
Normal file
@@ -0,0 +1,72 @@
|
||||
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.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()
|
||||
})
|
||||
16
tests/lib/request.js
Normal file
16
tests/lib/request.js
Normal file
@@ -0,0 +1,16 @@
|
||||
var tape = require("tape")
|
||||
|
||||
var request = require("../../lib/request.js")
|
||||
|
||||
tape("test xhr request", function(t) {
|
||||
request("https://api.github.com/", function(result) {
|
||||
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()
|
||||
})
|
||||
})
|
||||
9
tests/lib/switch-selectors.js
Normal file
9
tests/lib/switch-selectors.js
Normal file
@@ -0,0 +1,9 @@
|
||||
var tape = require("tape")
|
||||
|
||||
// var switchesSelectors = require("../../lib/switches-selectors.js")
|
||||
|
||||
tape("test switchesSelectors", function(t) {
|
||||
t.fail()
|
||||
|
||||
t.end()
|
||||
})
|
||||
12
tests/lib/uniqueid.js
Normal file
12
tests/lib/uniqueid.js
Normal file
@@ -0,0 +1,12 @@
|
||||
var tape = require("tape")
|
||||
|
||||
var uniqueid = require("../../lib/uniqueid.js")
|
||||
|
||||
tape("test uniqueid", function(t) {
|
||||
var a = uniqueid()
|
||||
var b = uniqueid()
|
||||
|
||||
t.notEqual(a,b,"Two calls to uniqueid produce different values")
|
||||
|
||||
t.end()
|
||||
})
|
||||
Reference in New Issue
Block a user