Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

swup

Package Overview
Dependencies
Maintainers
1
Versions
144
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

swup - npm Package Compare versions

Comparing version 0.1.4 to 0.2.0

.idea/misc.xml

129

lib/index.js

@@ -17,6 +17,2 @@ 'use strict';

var _enquire = require('enquire.js');
var _enquire2 = _interopRequireDefault(_enquire);
var _delegate = require('delegate');

@@ -26,2 +22,6 @@

var _detectie = require('detectie');
var _detectie2 = _interopRequireDefault(_detectie);
var _Cache = require('./Cache');

@@ -91,2 +91,6 @@

var _preloadPages = require('./modules/preloadPages');
var _preloadPages2 = _interopRequireDefault(_preloadPages);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

@@ -98,4 +102,2 @@

function Swup(setOptions) {
var _this = this;
_classCallCheck(this, Swup);

@@ -113,2 +115,3 @@

support: true,
disableIE: false,

@@ -130,4 +133,4 @@ animateScrollToAnchor: false,

/**
* helper variables
*/
* helper variables
*/
// mobile detection variable

@@ -161,2 +164,6 @@ this.mobile = false;

this.updateTransition = _updateTransition2.default;
this.preloadPages = _preloadPages2.default;
this.detectie = _detectie2.default;
this.enable = this.enable;
this.destroy = this.destroy;

@@ -167,10 +174,5 @@ /**

if (this.options.scroll) {
_enquire2.default.register('screen and (max-width: 47.9375em)', {
match: function match() {
_this.mobile = true;
},
unmatch: function unmatch() {
_this.mobile = false;
}
});
if (window.innerWidth <= 767) {
this.mobile = true;
}
}

@@ -184,14 +186,12 @@

this.getUrl();
this.prepare();
this.enable();
}
_createClass(Swup, [{
key: 'prepare',
value: function prepare() {
var _this2 = this;
key: 'enable',
value: function enable() {
/**
* support check
*/
if (this.support) {
if (this.options.support) {
// check pushState support

@@ -215,7 +215,16 @@ if (!('pushState' in window.history)) {

}
/**
* disable IE
*/
if (this.options.disableIE && this.detectie()) {
return;
}
// variable to keep event listeners from "delegate"
this.delegatedListeners = {};
/**
* link click handler
*/
(0, _delegate2.default)(document, this.options.LINK_SELECTOR, 'click', this.linkClickHandler.bind(this));
this.delegatedListeners.click = (0, _delegate2.default)(document, this.options.LINK_SELECTOR, 'click', this.linkClickHandler.bind(this));

@@ -225,3 +234,3 @@ /**

*/
(0, _delegate2.default)(document.body, this.options.LINK_SELECTOR, 'mouseover', this.linkMouseoverHandler.bind(this));
this.delegatedListeners.mouseover = (0, _delegate2.default)(document.body, this.options.LINK_SELECTOR, 'mouseover', this.linkMouseoverHandler.bind(this));

@@ -231,13 +240,3 @@ /**

*/
window.onpopstate = function (event) {
var link = new _Link2.default();
link.setPath(event.state ? event.state.url : window.location.pathname);
if (link.getHash() != '') {
_this2.scrollToElement = link.getHash();
} else {
event.preventDefault();
}
_this2.triggerEvent('popState');
_this2.loadPage(link.getPath(), event);
};
window.addEventListener('popstate', this.popStateHandler.bind(this));

@@ -252,6 +251,37 @@ /**

}
/**
* mark swup blocks in html
*/
this.markSwupElements(document.documentElement);
/**
* trigger page view event
*/
this.triggerEvent('pageView');
/**
* preload pages if possible
*/
this.preloadPages();
}
}, {
key: 'destroy',
value: function destroy() {
// remove delegated listeners
this.delegatedListeners.click.destroy();
this.delegatedListeners.mouseover.destroy();
// remove popstate listener
window.removeEventListener('popstate', this.popStateHandler.bind(this));
// empty cache
this.cache.empty();
// remove swup data atributes from blocks
document.querySelectorAll('[data-swup]').forEach(function (element) {
delete element.dataset.swup;
});
}
}, {
key: 'linkClickHandler',

@@ -303,4 +333,4 @@ value: function linkClickHandler(event) {

key: 'linkMouseoverHandler',
value: function linkMouseoverHandler() {
var _this3 = this;
value: function linkMouseoverHandler(event) {
var _this = this;

@@ -313,15 +343,15 @@ this.triggerEvent('hoverLink');

this.preloadPromise = new Promise(function (resolve) {
_this3.getPage(link.getPath(), function (response) {
_this.getPage(link.getPath(), function (response) {
if (response === null) {
console.warn('Server error.');
_this3.triggerEvent('serverError');
_this.triggerEvent('serverError');
} else {
_this3.triggerEvent('pagePreloaded');
_this.triggerEvent('pagePreloaded');
// get json data
var page = _this3.getDataFromHtml(response);
var page = _this.getDataFromHtml(response);
page.url = link.getPath();
_this3.cache.cacheUrl(page, _this3.options.debugMode);
_this.cache.cacheUrl(page, _this.options.debugMode);
}
resolve();
_this3.preloadPromise = null;
_this.preloadPromise = null;
});

@@ -333,2 +363,15 @@ });

}
}, {
key: 'popStateHandler',
value: function popStateHandler(event) {
var link = new _Link2.default();
link.setPath(event.state ? event.state.url : window.location.pathname);
if (link.getHash() != '') {
this.scrollToElement = link.getHash();
} else {
event.preventDefault();
}
this.triggerEvent('popState');
this.loadPage(link.getPath(), event);
}
}]);

@@ -335,0 +378,0 @@

@@ -33,3 +33,4 @@ 'use strict';

document.body.className.split(' ').forEach(function (className) {
if (className.includes(_this.options.pageClassPrefix)) {
// empty string for page class
if (className != "" && className.includes(_this.options.pageClassPrefix)) {
document.body.classList.remove(className);

@@ -40,5 +41,8 @@ }

page.pageClass.split(' ').forEach(function (className) {
document.body.classList.add(className);
});
// empty string for page class
if (page.pageClass != "") {
page.pageClass.split(' ').forEach(function (className) {
document.body.classList.add(className);
});
}

@@ -60,2 +64,5 @@ // scrolling

//preload pages if possible
this.preloadPages();
Promise.all(promises).then(function () {

@@ -62,0 +69,0 @@ _this.triggerEvent('animationInDone');

{
"name": "swup",
"version": "0.1.4",
"description": "Css animating between website pages.",
"version": "0.2.0",
"description": "Animated page transitions with css - simple, quick and fun.",
"main": "lib/index.js",

@@ -19,3 +19,3 @@ "scripts": {

"delegate": "^3.1.3",
"enquire.js": "^2.1.6"
"detectie": "^1.0.0"
},

@@ -22,0 +22,0 @@ "devDependencies": {

# swup
Swup lets you easily create site equipped with animated transitions between pages, without all that hassle of dealing with popstates, requests... All you have to care about is css transitions. Whether the site is ready or you are just starting, swup implementation is very easy and straight forward.
Animated page transitions with css - simple, quick and fun.
## Introduction
### What it does
* Swup takes care of browser history... without breaking it - animation is disabled for popstate events, browsers native window scrollTop amount is remembered and your page won't be jumping around on that iOS/OSX swipe for previous/next page.
* Swup works with your code. Need to attach your JS on the loaded content? Need to trigger some analytics events? ...or simply want to close a sidebar on page transition. No problem. Swup emits whole bunch of events that you can use in your code.
* Swup takes care of timing. Is your "out" animation done before page is loaded? It'll wait for the page to load to continue... Is your page loaded before animation is done? It'll wait for all your css transitions to finish... All you need is to define that buttery smooth transition, and swup does the rest.
### What it doesn't
* Swup never loads same page twice (when cache option is enabled). Actually, once you've visited several pages of site, you can even disable your internet connection and continue browsing.
* Swup doesn't wait for next page to be loaded to start the animation - it all happens at the same time. While user is trying to process what is happening on screen, your request is being served. With preload option enabled it can even start loading your page before you click the link... and don't worry, swup won't start another request to the same page in case you click the link while it's being preloaded.
* Swup works with any server side rendered content and it doesn't require any setup on server. While it would be possible to limit the data sent from server to minimum and serve only blocks required by swup, it would require setup on server... and let's face it, those few extra lines of html is usually not what's slowing your load time.
## Installation

@@ -43,3 +55,3 @@ ```shell

Add the `swup` id to the main element in html so it is replaced with the main element of the loaded page. Also add the class that handles the animations of the element - `a-fade`.
Add the `swup` id to the main element in html so it is replaced with the main element of the loaded page. Also add class that handles animations of the element - `a-fade`.
```html

@@ -70,10 +82,10 @@ <main id="swup" class="a-fade">

```
And that's it! Swup loads the page, handles the classes for the css animation, waits for the animation to finish/page to load, replaces the content and fades your content back, as well as changes the title of your page to the loaded one, and exchanges the classes of the body element (more in options section).
And that's it! Swup loads the page, handles classes for the css animation, waits for the animation to finish/page to load, replaces content and fades your content back. Swup also changes title of your page to the loaded one, and exchanges classes of body element (more in options section).
In some cases there is a need to animate elements that are common for all pages, but may for example display or hide for some pages, change color or whatever... In that case you would usually like to start the animation on the click of the link, instead of when the next page is loaded. For this purpose there is special class added to your html tag on transition start and removed once the process of page transition is done.
This special class takes form of `to-{whatever is the route of new page}`, where only exception is homepage, which does not have any route and so `to-homepage` is added.
In some cases there is a need to animate elements that are common for all pages, but may for example display or hide for some pages, change color or whatever.. Let's assume we want navigation to change background color for different pages, based on body class. In that case you would usually like to start the animation on the click of the link, instead of when the next page is loaded. For this purpose there is special class added to your html tag on transition start and removed once the process of page transition is done.
This special class takes form of `to-{whatever is the route of new page}`, where only exception is homepage, which does not have any route and so `to-homepage` is used.
Animation to dynamic pages with unknown routes (blog posts, etc.) can be animated to using data attribute `data-swup-class` set on link element. Swup takes the content of the attribute of clicked link and adds class name on html tag in a format `to-{content of the attribute}`, and also removes it after the whole process of routing is done. So for blog posts, you would want to add `data-swup-class="blog-post"`, which would be added to html tag as `to-blog-post`.
Lets assume we want our header to be blue on homepage (/), but yellow in about (/about) page.
Let's assume we want our header to be blue on homepage (/), but yellow in about (/about) page.
```css

@@ -90,3 +102,3 @@ header {

```
For the color to start changing right after the click on the link, simply change add...
For the color to start changing right after the click on the link, simply add...
```css

@@ -102,3 +114,3 @@ html.to-homepage header {

## options
## Options
Swup has a several options passed into a constructor as an object.

@@ -111,3 +123,3 @@ ```javascript

### Link Selector
Link selector defines link elements will trigger the transition. Default form is shown below.
Link selector defines link elements that will trigger the transition. Default form is shown below.
```javascript

@@ -117,6 +129,7 @@ LINK_SELECTOR: 'a[href^="/"]:not([data-no-swup]), a[href^="#"]:not([data-no-swup]), a[xlink\\:href]'

In case you want to exclude links for some routes, lightbox or any other functionality, simply extend the selector. By default, you can simply add **data-no-swup** attribute if you want to exclude just a few.
**Note:** it is recommended to disable transition between the language versions of your site, for multiple reasons (replacing of header/footer elements, analytics...).
**Note:** it is recommended to disable transition between language versions of your site, for multiple reasons (replacing of header/footer, analytics...).
### Elements
Elements option defines the array of elements to be replaced. Elements option usually contains the main elements with a content of the page. However, elements can include any element that is common for all transitioned pages. Example of such additional element is the "change language" link, which appears the same across site, but leads to a different link on each page. Options defaults to the single element of id `#swup`.
Elements option defines the array of elements to be replaced. Elements option usually contains the main element with content of the page. However, elements can include any element that is common for all transitioned pages. Example of such additional element is the "change language" link, which appears the same across site, but leads to a different link on each page. Option defaults to the single element of id `#swup`.
```javascript

@@ -129,3 +142,3 @@ options = {

### Animation Selector
As swup is built on animations, it is required to define the elements that are being animated. Usually you would like to give the elements some common class or class prefix. By default option is set to `[class^='a-']`, which selects all elements with class attribute beginning with prexif `a-`.
As swup is built on animations, it is required to define the elements that are being animated. Usually you would like to give the elements some common class or class prefix. By default option is set to `[class^='a-']`, which selects all elements with class attribute beginning with prefix `a-`.
```javascript

@@ -142,3 +155,3 @@ animationSelector: '[class^="a-"]'

### Page Class Prefix
CSS styles are very often based on the class of the page defined in body element. Swup replaces the body classes for each loaded page. However, the site may use the body class attribute for functionality such as opening of some sort of menu by adding class to the body element. In that case, you may want to define a prefix for your page style classes such as `page-`, so only those are replaced. By default option is set to `''` and all classes of body element are replaced during the transition. In case of no classes are used on body element, simply set the options to `false`.
Css styles are very often based on the class of the page defined in body element. Swup replaces the body classes for each loaded page. However, the site may use the body class attribute for functionality such as opening of some sort of menu by adding class to the body element. In that case, you may want to define a prefix for your page style classes such as `page-`, so only those are replaced. By default option is set to `''` and all classes of body element are replaced during the transition. In case of no classes are used on body element, simply set option to `false`.
```javascript

@@ -149,3 +162,3 @@ pageClassPrefix: 'page-'

### Scroll
Swup has a built in scroll control, where page smoothly scrolls to the top on desktop, and jumps directly to the top on mobile (as menu is usually fixed for mobile sites). The scrolls to the anchor elements in url are also handled. This feature can be turned of and you can use your own scroll based on the emitted events discussed in events section. By default the options is set to `true`. Scrolling has several other options, such as `scrollDuration` - duration of the scroll, which is set to 0 by default (expects the page to be fully invisible while transitioning). Another options are `animateScrollToAnchor` and `animateScrollOnMobile`, where the name speaks for itself. Last is `doScrollingRightAway`, which determines whether scroll starts immediately, or after the content is replaced.
Swup has a built in scroll control, where page smoothly scrolls to the top on desktop, and jumps directly to the top on mobile. Scroll to the anchor elements in url are also handled. This feature can be turned off and you can use your own scroll based on the emitted events discussed in events section. By default the option is set to `true`. Scrolling has several other options, such as `scrollDuration` - duration of the scroll, which is set to 0 by default (expects the page to be fully invisible while transitioning). Another options are `animateScrollToAnchor` and `animateScrollOnMobile`, where the name speaks for itself. Last is `doScrollingRightAway`, which determines whether scroll starts immediately after click on link, or after the content is replaced.

@@ -157,3 +170,3 @@ ```javascript

### Support
Due to the use of promises, transitionEnd and pushState features of javascript, swup has a basic support check built in to avoid breaking of the site in case of older browser that do not support used features. However, as there may always be some exceptions for browsers, or different polyfills (that may or may not work) can be used, this support check can be disabled and you can use your own support check before creating the instance. Support option is enabled by default.
Due to the use of promises, transitionEnd and pushState features of javascript, swup has a basic support check built in to avoid breaking of the site in case of older browser that do not support used features. However, as there may always be some exceptions for browsers, or different polyfills may be used on page (that may or may not work), this support check can be disabled and you can use your own support check before creating the instance. Support option is enabled by default.
```javascript

@@ -171,4 +184,10 @@ support: true

### Disable IE
While swup itself should run without problem in IE Edge (or other IE with help of some polyfills), I have ran into multiple problems on IE (including Edge), related to updating browser history, replacing large parts of page with javascript or performance of animation on large elements. That's why swup allows to simply disable the whole thing in all IE browsers with `disableIE` option. Swup is enabled in IE by default.
```javasrripts
disableIE: false
```
### Debug Mode
Debug mode is very useful for integrating swup into your site. When enabled, swup displays emitted events (see events section) in console, as well as contents of the cache when changed. Options defaults to false.
Debug mode is very useful for integrating swup into your site. When enabled, swup displays emitted events (see events section) in console, as well as contents of the cache when changed. Option defaults to false.
```javasrripts

@@ -191,3 +210,4 @@ debugMode: false

preload: true,
support: true
support: true,
disableIE: false,
animateScrollToAnchor: false,

@@ -201,3 +221,3 @@ animateScrollOnMobile: false,

## Events
As it usually is when loading the page with ajax, there may be many constrains such as analytics or enabling the scripts for replaced content. For this purpose, swup emits whole bunch of events triggered on document while working, which can be used as follows:
As it usually is when loading page with JS, there may be many constrains such as analytics or enabling the scripts for replaced content. For this purpose, swup emits whole bunch of events triggered on document while working, which can be used as follows:
```javascripts

@@ -225,10 +245,10 @@ // trigger page view for GTM

* **swup:hoverLink** - triggers when link for transition is hovered
* **swup:clickLink** - triggers when link for transition is hovered
* **swup:animationOutDone** - triggers when animating (out) of all animated elements is done
* **swup:clickLink** - triggers when link for transition is clicked
* **swup:animationOutDone** - triggers when transition of all animated elements is done (after click of link and before content is replaced)
* **swup:pagePreloaded** - triggers when the preload of some page is done
* **swup:pageLoaded** - triggers when the loading of some page is done (differs from previous only by the source of event - hover/click)
* **swup:pageLoaded** - triggers when loading of some page is done (differs from previous only by the source of event - hover/click)
* **swup:scrollStart** - triggers when built in scroll is started
* **swup:scrollDone** - triggers when built in scroll is done
* **swup:animationInDone** - triggers when animating (in) of all animated elements is done
* **swup:pageRetrievedFromCache** - triggers when page is retrieved from cache and no loading is necessary
* **swup:animationInDone** - triggers when transition of all animated elements is done (after content is replaced)
* **swup:pageRetrievedFromCache** - triggers when page is retrieved from cache and no request is necessary

@@ -243,6 +263,8 @@ ## API

```
or possibly use built in function for your own purpose
or use built in function for your own stuff
```javascript
// navigates to /someRoute with the animations and all
// navigates to /someRoute with the animations and all...
swup.loadPage('/someRoute', false)
// or disable swup
swup.destroy()
```

@@ -249,0 +271,0 @@

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc