Build mobile apps with simple HTML, CSS, and JS components. http://goratchet.com/
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

525 lines
14 KiB

/* ========================================================================
* Ratchet: push.js v2.0.2
* http://goratchet.com/components#push
* ========================================================================
* inspired by @defunkt's jquery.pjax.js
10 years ago
* Copyright 2015 Connor Sears
* Licensed under MIT (https://github.com/twbs/ratchet/blob/master/LICENSE)
* ======================================================================== */
12 years ago
/* global _gaq: true */
!(function () {
'use strict';
12 years ago
var noop = function () {};
// Pushstate caching
12 years ago
// ==================
var isScrolling;
var maxCacheLength = 20;
var cacheMapping = sessionStorage;
var domCache = {};
// Change these to unquoted camelcase in the next major version bump
12 years ago
var transitionMap = {
'slide-in' : 'slide-out',
'slide-out' : 'slide-in',
fade : 'fade'
12 years ago
};
12 years ago
var bars = {
bartab : '.bar-tab',
barnav : '.bar-nav',
12 years ago
barfooter : '.bar-footer',
barheadersecondary : '.bar-header-secondary'
};
12 years ago
var cacheReplace = function (data, updates) {
PUSH.id = data.id;
if (updates) {
data = getCached(data.id);
}
12 years ago
cacheMapping[data.id] = JSON.stringify(data);
window.history.replaceState(data.id, data.title, data.url);
};
var cachePush = function () {
var id = PUSH.id;
var cacheForwardStack = JSON.parse(cacheMapping.cacheForwardStack || '[]');
var cacheBackStack = JSON.parse(cacheMapping.cacheBackStack || '[]');
cacheBackStack.push(id);
while (cacheForwardStack.length) {
delete cacheMapping[cacheForwardStack.shift()];
}
while (cacheBackStack.length > maxCacheLength) {
delete cacheMapping[cacheBackStack.shift()];
}
12 years ago
if (getCached(PUSH.id).url) {
window.history.pushState(null, '', getCached(PUSH.id).url);
}
12 years ago
cacheMapping.cacheForwardStack = JSON.stringify(cacheForwardStack);
cacheMapping.cacheBackStack = JSON.stringify(cacheBackStack);
};
var cachePop = function (id, direction) {
var forward = direction === 'forward';
12 years ago
var cacheForwardStack = JSON.parse(cacheMapping.cacheForwardStack || '[]');
var cacheBackStack = JSON.parse(cacheMapping.cacheBackStack || '[]');
var pushStack = forward ? cacheBackStack : cacheForwardStack;
var popStack = forward ? cacheForwardStack : cacheBackStack;
if (PUSH.id) {
pushStack.push(PUSH.id);
}
12 years ago
popStack.pop();
cacheMapping.cacheForwardStack = JSON.stringify(cacheForwardStack);
cacheMapping.cacheBackStack = JSON.stringify(cacheBackStack);
};
var getCached = function (id) {
return JSON.parse(cacheMapping[id] || null) || {};
};
var getTarget = function (e) {
var target = findTarget(e.target);
if (!target ||
e.which > 1 ||
e.metaKey ||
e.ctrlKey ||
isScrolling ||
location.protocol !== target.protocol ||
location.host !== target.host ||
!target.hash && /#/.test(target.href) ||
target.hash && target.href.replace(target.hash, '') === location.href.replace(location.hash, '') ||
target.getAttribute('data-ignore') === 'push') { return; }
12 years ago
return target;
};
// Main event handlers (touchend, popstate)
// ==========================================
var touchend = function (e) {
var target = getTarget(e);
if (!target) {
return;
}
12 years ago
e.preventDefault();
PUSH({
url : target.href,
hash : target.hash,
timeout : target.getAttribute('data-timeout'),
transition : target.getAttribute('data-transition')
});
};
var popstate = function (e) {
var key;
var barElement;
var activeObj;
var activeDom;
var direction;
var transition;
var transitionFrom;
var transitionFromObj;
var id = e.state;
if (!id || !cacheMapping[id]) {
return;
}
12 years ago
direction = PUSH.id < id ? 'forward' : 'back';
cachePop(id, direction);
activeObj = getCached(id);
activeDom = domCache[id];
if (activeObj.title) {
document.title = activeObj.title;
}
12 years ago
if (direction === 'back') {
transitionFrom = JSON.parse(direction === 'back' ? cacheMapping.cacheForwardStack : cacheMapping.cacheBackStack);
12 years ago
transitionFromObj = getCached(transitionFrom[transitionFrom.length - 1]);
} else {
transitionFromObj = activeObj;
}
if (direction === 'back' && !transitionFromObj.id) {
return (PUSH.id = id);
}
12 years ago
transition = direction === 'back' ? transitionMap[transitionFromObj.transition] : transitionFromObj.transition;
12 years ago
if (!activeDom) {
return PUSH({
id : activeObj.id,
url : activeObj.url,
title : activeObj.title,
timeout : activeObj.timeout,
transition : transition,
ignorePush : true
});
}
if (transitionFromObj.transition) {
activeObj = extendWithDom(activeObj, '.content', activeDom.cloneNode(true));
for (key in bars) {
if (bars.hasOwnProperty(key)) {
barElement = document.querySelector(bars[key]);
if (activeObj[key]) {
swapContent(activeObj[key], barElement);
} else if (barElement) {
barElement.parentNode.removeChild(barElement);
}
}
12 years ago
}
}
swapContent(
(activeObj.contents || activeDom).cloneNode(true),
document.querySelector('.content'),
transition, function () {
triggerStateChange();
}
12 years ago
);
PUSH.id = id;
document.body.offsetHeight; // force reflow to prevent scroll
};
// Core PUSH functionality
// =======================
var PUSH = function (options) {
var key;
var xhr = PUSH.xhr;
12 years ago
options.container = options.container || options.transition ? document.querySelector('.content') : document.body;
var isFileProtocol = /^file:/.test(window.location.protocol);
12 years ago
for (key in bars) {
if (bars.hasOwnProperty(key)) {
options[key] = options[key] || document.querySelector(bars[key]);
}
12 years ago
}
if (xhr && xhr.readyState < 4) {
xhr.onreadystatechange = noop;
xhr.abort();
12 years ago
}
xhr = new XMLHttpRequest();
if (isFileProtocol) {
xhr.open('GET', options.url, false);
} else {
xhr.open('GET', options.url, true);
xhr.setRequestHeader('X-PUSH', 'true');
12 years ago
xhr.onreadystatechange = function () {
if (options._timeout) {
clearTimeout(options._timeout);
}
if (xhr.readyState === 4) {
if (xhr.status === 200) {
success(xhr, options);
} else {
failure(options.url);
}
}
};
}
12 years ago
if (!PUSH.id) {
cacheReplace({
id : +new Date(),
12 years ago
url : window.location.href,
title : document.title,
timeout : options.timeout,
transition : options.transition
12 years ago
});
}
cacheCurrentContent();
12 years ago
if (options.timeout) {
options._timeout = setTimeout(function () { xhr.abort('timeout'); }, options.timeout);
}
xhr.send();
if (isFileProtocol) {
if (xhr.status === 0 || xhr.status === 200) {
success(xhr, options);
} else {
failure(options.url);
}
}
if (xhr.readyState && !options.ignorePush) {
cachePush();
}
12 years ago
};
function cacheCurrentContent () {
domCache[PUSH.id] = document.body.cloneNode(true);
}
12 years ago
// Main XHR handlers
// =================
var success = function (xhr, options) {
var key;
var barElement;
var data = parseXHR(xhr, options);
if (!data.contents) {
return locationReplace(options.url);
}
12 years ago
if (data.title) {
document.title = data.title;
}
12 years ago
if (options.transition) {
for (key in bars) {
if (bars.hasOwnProperty(key)) {
barElement = document.querySelector(bars[key]);
if (data[key]) {
swapContent(data[key], barElement);
} else if (barElement) {
barElement.parentNode.removeChild(barElement);
}
}
12 years ago
}
}
swapContent(data.contents, options.container, options.transition, function () {
cacheReplace({
id : options.id || +new Date(),
12 years ago
url : data.url,
title : data.title,
timeout : options.timeout,
transition : options.transition
}, options.id);
triggerStateChange();
});
if (!options.ignorePush && window._gaq) {
_gaq.push(['_trackPageview']); // google analytics
}
if (!options.hash) {
return;
}
12 years ago
};
var failure = function (url) {
throw new Error('Could not get: ' + url);
12 years ago
};
// PUSH helpers
// ============
var swapContent = function (swap, container, transition, complete) {
var enter;
var containerDirection;
var swapDirection;
if (!transition) {
if (container) {
container.innerHTML = swap.innerHTML;
} else if (swap.classList.contains('content')) {
document.body.appendChild(swap);
} else {
document.body.insertBefore(swap, document.querySelector('.content'));
}
12 years ago
} else {
enter = /in$/.test(transition);
12 years ago
if (transition === 'fade') {
12 years ago
container.classList.add('in');
container.classList.add('fade');
swap.classList.add('fade');
}
if (/slide/.test(transition)) {
swap.classList.add('sliding-in', enter ? 'right' : 'left');
swap.classList.add('sliding');
container.classList.add('sliding');
12 years ago
}
container.parentNode.insertBefore(swap, container);
}
if (!transition) {
if (complete) {
complete();
}
}
12 years ago
if (transition === 'fade') {
12 years ago
container.offsetWidth; // force reflow
container.classList.remove('in');
var fadeContainerEnd = function () {
container.removeEventListener(window.RATCHET.getTransitionEnd, fadeContainerEnd);
12 years ago
swap.classList.add('in');
swap.addEventListener(window.RATCHET.getTransitionEnd, fadeSwapEnd);
};
var fadeSwapEnd = function () {
swap.removeEventListener(window.RATCHET.getTransitionEnd, fadeSwapEnd);
12 years ago
container.parentNode.removeChild(container);
swap.classList.remove('fade');
swap.classList.remove('in');
if (complete) {
complete();
}
};
container.addEventListener(window.RATCHET.getTransitionEnd, fadeContainerEnd);
12 years ago
}
if (/slide/.test(transition)) {
var slideEnd = function () {
swap.removeEventListener(window.RATCHET.getTransitionEnd, slideEnd);
swap.classList.remove('sliding', 'sliding-in');
12 years ago
swap.classList.remove(swapDirection);
container.parentNode.removeChild(container);
if (complete) {
complete();
}
};
container.offsetWidth; // force reflow
swapDirection = enter ? 'right' : 'left';
containerDirection = enter ? 'left' : 'right';
container.classList.add(containerDirection);
swap.classList.remove(swapDirection);
swap.addEventListener(window.RATCHET.getTransitionEnd, slideEnd);
12 years ago
}
};
var triggerStateChange = function () {
var e = new CustomEvent('push', {
detail: { state: getCached(PUSH.id) },
bubbles: true,
cancelable: true
});
window.dispatchEvent(e);
};
var findTarget = function (target) {
var i;
var toggles = document.querySelectorAll('a');
12 years ago
for (; target && target !== document; target = target.parentNode) {
for (i = toggles.length; i--;) {
if (toggles[i] === target) {
return target;
}
}
12 years ago
}
};
var locationReplace = function (url) {
window.history.replaceState(null, '', '#');
window.location.replace(url);
};
var extendWithDom = function (obj, fragment, dom) {
var i;
var result = {};
12 years ago
for (i in obj) {
if (obj.hasOwnProperty(i)) {
result[i] = obj[i];
}
}
12 years ago
Object.keys(bars).forEach(function (key) {
var el = dom.querySelector(bars[key]);
if (el) {
el.parentNode.removeChild(el);
}
12 years ago
result[key] = el;
});
result.contents = dom.querySelector(fragment);
return result;
};
var parseXHR = function (xhr, options) {
var head;
var body;
var data = {};
var responseText = xhr.responseText;
data.url = options.url;
if (!responseText) {
return data;
}
12 years ago
if (/<html/i.test(responseText)) {
head = document.createElement('div');
body = document.createElement('div');
head.innerHTML = responseText.match(/<head[^>]*>([\s\S.]*)<\/head>/i)[0];
body.innerHTML = responseText.match(/<body[^>]*>([\s\S.]*)<\/body>/i)[0];
12 years ago
} else {
head = body = document.createElement('div');
head.innerHTML = responseText;
}
data.title = head.querySelector('title') || document.querySelector('title');
var text = 'innerText' in data.title ? 'innerText' : 'textContent';
data.title = data.title && data.title[text].trim();
12 years ago
if (options.transition) {
data = extendWithDom(data, '.content', body);
} else {
data.contents = body;
}
12 years ago
return data;
};
// Attach PUSH event handlers
// ==========================
window.addEventListener('touchstart', function () { isScrolling = false; });
window.addEventListener('touchmove', function () { isScrolling = true; });
12 years ago
window.addEventListener('touchend', touchend);
window.addEventListener('click', function (e) {
if (getTarget(e)) {
e.preventDefault();
}
});
12 years ago
window.addEventListener('popstate', popstate);
// TODO : Remove this line in the next major version
11 years ago
window.PUSH = PUSH;
window.RATCHET.push = PUSH;
12 years ago
}());