Prettier fixes

This commit is contained in:
Behind The Math
2019-02-11 23:17:28 -05:00
parent 8386b355c9
commit 2e459fb7bc
16 changed files with 531 additions and 425 deletions

View File

@@ -1,8 +1,8 @@
var noop = require("./util/noop")
var noop = require("./util/noop");
module.exports = function(request) {
if (request && request.readyState < 4) {
request.onreadystatechange = noop
request.abort()
request.onreadystatechange = noop;
request.abort();
}
}
};

View File

@@ -1,42 +1,48 @@
module.exports = function(el) {
var code = (el.text || el.textContent || el.innerHTML || "")
var src = (el.src || "")
var parent = el.parentNode || document.querySelector("head") || document.documentElement
var script = document.createElement("script")
var code = el.text || el.textContent || el.innerHTML || "";
var src = el.src || "";
var parent =
el.parentNode || 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. Cant be executed correctly. Code skipped ", el)
console.log(
"Script contains document.write. Cant be executed correctly. Code skipped ",
el
);
}
return false
return false;
}
script.type = "text/javascript"
script.type = "text/javascript";
script.id = el.id;
/* istanbul ignore if */
if (src !== "") {
script.src = src
script.async = false // force synchronous loading of peripheral JS
script.src = src;
script.async = false; // force synchronous loading of peripheral JS
}
if (code !== "") {
try {
script.appendChild(document.createTextNode(code))
}
catch (e) {
script.appendChild(document.createTextNode(code));
} catch (e) {
/* istanbul ignore next */
// old IEs have funky script nodes
script.text = code
script.text = code;
}
}
// execute
parent.appendChild(script)
parent.appendChild(script);
// avoid pollution only in head or body tags
if ((parent instanceof HTMLHeadElement || parent instanceof HTMLBodyElement) && parent.contains(script)) {
parent.removeChild(script)
if (
(parent instanceof HTMLHeadElement || parent instanceof HTMLBodyElement) &&
parent.contains(script)
) {
parent.removeChild(script);
}
return true
}
return true;
};

View File

@@ -1,18 +1,18 @@
var forEachEls = require("./foreach-els")
var evalScript = require("./eval-script")
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) {
if (el.tagName.toLowerCase() === "script") {
evalScript(el)
evalScript(el);
}
forEachEls(el.querySelectorAll("script"), function(script) {
if (!script.type || script.type.toLowerCase() === "text/javascript") {
if (script.parentNode) {
script.parentNode.removeChild(script)
script.parentNode.removeChild(script);
}
evalScript(script)
evalScript(script);
}
})
}
});
};

View File

@@ -1,9 +1,13 @@
/* 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)
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)
}
return fn.call(context, els);
};

View File

@@ -1,8 +1,8 @@
var forEachEls = require("./foreach-els")
var forEachEls = require("./foreach-els");
module.exports = function(selectors, cb, context, DOMcontext) {
DOMcontext = DOMcontext || document
DOMcontext = DOMcontext || document;
selectors.forEach(function(selector) {
forEachEls(DOMcontext.querySelectorAll(selector), cb, context)
})
}
forEachEls(DOMcontext.querySelectorAll(selector), cb, context);
});
};

View File

@@ -1,8 +1,12 @@
module.exports = function() {
// Borrowed wholesale from https://github.com/defunkt/jquery-pjax
return window.history &&
return (
window.history &&
window.history.pushState &&
window.history.replaceState &&
// pushState isnt reliable on iOS until 5.
!navigator.userAgent.match(/((iPod|iPhone|iPad).+\bOS\s+[1-4]\D|WebApps\/.+CFNetwork)/)
}
!navigator.userAgent.match(
/((iPod|iPhone|iPad).+\bOS\s+[1-4]\D|WebApps\/.+CFNetwork)/
)
);
};

View File

@@ -1,41 +1,53 @@
/* global _gaq: true, ga: true */
var defaultSwitches = require("./switches")
var defaultSwitches = require("./switches");
module.exports = function(options) {
options = options || {}
options.elements = options.elements || "a[href], form[action]"
options.selectors = options.selectors || ["title", ".js-Pjax"]
options.switches = options.switches || {}
options.switchesOptions = options.switchesOptions || {}
options.history = (typeof options.history === "undefined") ? true : options.history
options.analytics = (typeof options.analytics === "function" || options.analytics === false) ? options.analytics : defaultAnalytics
options.scrollTo = (typeof options.scrollTo === "undefined") ? 0 : options.scrollTo
options.scrollRestoration = (typeof options.scrollRestoration !== "undefined") ? options.scrollRestoration : true
options.cacheBust = (typeof options.cacheBust === "undefined") ? true : options.cacheBust
options.debug = options.debug || false
options.timeout = options.timeout || 0
options.currentUrlFullReload = (typeof options.currentUrlFullReload === "undefined") ? false : options.currentUrlFullReload
options = options || {};
options.elements = options.elements || "a[href], form[action]";
options.selectors = options.selectors || ["title", ".js-Pjax"];
options.switches = options.switches || {};
options.switchesOptions = options.switchesOptions || {};
options.history =
typeof options.history === "undefined" ? true : options.history;
options.analytics =
typeof options.analytics === "function" || options.analytics === false
? options.analytics
: defaultAnalytics;
options.scrollTo =
typeof options.scrollTo === "undefined" ? 0 : options.scrollTo;
options.scrollRestoration =
typeof options.scrollRestoration !== "undefined"
? options.scrollRestoration
: true;
options.cacheBust =
typeof options.cacheBust === "undefined" ? true : options.cacheBust;
options.debug = options.debug || false;
options.timeout = options.timeout || 0;
options.currentUrlFullReload =
typeof options.currentUrlFullReload === "undefined"
? false
: options.currentUrlFullReload;
// We cant replace body.outerHTML or head.outerHTML.
// It creates a bug where a new body or head are created in the DOM.
// If you set head.outerHTML, a new body tag is appended, so the DOM has 2 body nodes, and vice versa
if (!options.switches.head) {
options.switches.head = defaultSwitches.switchElementsAlt
options.switches.head = defaultSwitches.switchElementsAlt;
}
if (!options.switches.body) {
options.switches.body = defaultSwitches.switchElementsAlt
options.switches.body = defaultSwitches.switchElementsAlt;
}
return options
}
return options;
};
/* istanbul ignore next */
function defaultAnalytics() {
if (window._gaq) {
_gaq.push(["_trackPageview"])
_gaq.push(["_trackPageview"]);
}
if (window.ga) {
ga("send", "pageview", {page: location.pathname, title: document.title})
ga("send", "pageview", { page: location.pathname, title: document.title });
}
}

View File

@@ -1,70 +1,71 @@
var clone = require("../util/clone.js")
var newUid = require("../uniqueid.js")
var trigger = require("../events/trigger.js")
var clone = require("../util/clone");
var newUid = require("../uniqueid");
var trigger = require("../events/trigger");
module.exports = function(responseText, request, href, options) {
options = clone(options || this.options)
options.request = request
options = clone(options || this.options);
options.request = request;
// Fail if unable to load HTML via AJAX
if (responseText === false) {
trigger(document, "pjax:complete pjax:error", options)
trigger(document, "pjax:complete pjax:error", options);
return
return;
}
// push scroll position to history
var currentState = window.history.state || {}
window.history.replaceState({
var currentState = window.history.state || {};
window.history.replaceState(
{
url: currentState.url || window.location.href,
title: currentState.title || document.title,
uid: currentState.uid || newUid(),
scrollPos: [document.documentElement.scrollLeft || document.body.scrollLeft,
document.documentElement.scrollTop || document.body.scrollTop]
scrollPos: [
document.documentElement.scrollLeft || document.body.scrollLeft,
document.documentElement.scrollTop || document.body.scrollTop
]
},
document.title, window.location)
document.title,
window.location.href
);
// Check for redirects
var oldHref = href
var oldHref = href;
if (request.responseURL) {
if (href !== request.responseURL) {
href = request.responseURL
href = request.responseURL;
}
}
else if (request.getResponseHeader("X-PJAX-URL")) {
href = request.getResponseHeader("X-PJAX-URL")
}
else if (request.getResponseHeader("X-XHR-Redirected-To")) {
href = request.getResponseHeader("X-XHR-Redirected-To")
} else if (request.getResponseHeader("X-PJAX-URL")) {
href = request.getResponseHeader("X-PJAX-URL");
} else if (request.getResponseHeader("X-XHR-Redirected-To")) {
href = request.getResponseHeader("X-XHR-Redirected-To");
}
// Add back the hash if it was removed
var a = document.createElement("a")
a.href = oldHref
var oldHash = a.hash
a.href = href
var a = document.createElement("a");
a.href = oldHref;
var oldHash = a.hash;
a.href = href;
if (oldHash && !a.hash) {
a.hash = oldHash
href = a.href
a.hash = oldHash;
href = a.href;
}
this.state.href = href
this.state.options = options
this.state.href = href;
this.state.options = options;
try {
this.loadContent(responseText, options)
}
catch (e) {
trigger(document, "pjax:error", options)
this.loadContent(responseText, options);
} catch (e) {
trigger(document, "pjax:error", options);
if (!this.options.debug) {
if (console && console.error) {
console.error("Pjax switch fail: ", e)
console.error("Pjax switch fail: ", e);
}
return this.latestChance(href)
}
else {
throw e
return this.latestChance(href);
} else {
throw e;
}
}
}
};

View File

@@ -1,78 +1,86 @@
var updateQueryString = require("./util/update-query-string");
module.exports = function(location, options, callback) {
options = options || {}
var queryString
var requestOptions = options.requestOptions || {}
var requestMethod = (requestOptions.requestMethod || "GET").toUpperCase()
var requestParams = requestOptions.requestParams || null
options = options || {};
var queryString;
var requestOptions = options.requestOptions || {};
var requestMethod = (requestOptions.requestMethod || "GET").toUpperCase();
var requestParams = requestOptions.requestParams || null;
var formData = requestOptions.formData || null;
var requestPayload = null
var request = new XMLHttpRequest()
var timeout = options.timeout || 0
var requestPayload = null;
var request = new XMLHttpRequest();
var timeout = options.timeout || 0;
request.onreadystatechange = function() {
if (request.readyState === 4) {
if (request.status === 200) {
callback(request.responseText, request, location, options)
}
else if (request.status !== 0) {
callback(null, request, location, options)
callback(request.responseText, request, location, options);
} else if (request.status !== 0) {
callback(null, request, location, options);
}
}
}
};
request.onerror = function(e) {
console.log(e)
callback(null, request, location, options)
}
console.log(e);
callback(null, request, location, options);
};
request.ontimeout = function() {
callback(null, request, location, options)
}
callback(null, request, location, options);
};
// Prepare the request payload for forms, if available
if (requestParams && requestParams.length) {
// Build query string
queryString = (requestParams.map(function(param) {return param.name + "=" + param.value})).join("&")
queryString = requestParams
.map(function(param) {
return param.name + "=" + param.value;
})
.join("&");
switch (requestMethod) {
case "GET":
// Reset query string to avoid an issue with repeat submissions where checkboxes that were
// previously checked are incorrectly preserved
location = location.split("?")[0]
location = location.split("?")[0];
// Append new query string
location += "?" + queryString
break
location += "?" + queryString;
break;
case "POST":
// Send query string as request payload
requestPayload = queryString
break
requestPayload = queryString;
break;
}
}
else if (formData) {
requestPayload = formData
} else if (formData) {
requestPayload = formData;
}
// Add a timestamp as part of the query string if cache busting is enabled
if (options.cacheBust) {
location = updateQueryString(location, "t", Date.now())
location = updateQueryString(location, "t", Date.now());
}
request.open(requestMethod, location, true)
request.timeout = timeout
request.setRequestHeader("X-Requested-With", "XMLHttpRequest")
request.setRequestHeader("X-PJAX", "true")
request.setRequestHeader("X-PJAX-Selectors", JSON.stringify(options.selectors))
request.open(requestMethod, location, true);
request.timeout = timeout;
request.setRequestHeader("X-Requested-With", "XMLHttpRequest");
request.setRequestHeader("X-PJAX", "true");
request.setRequestHeader(
"X-PJAX-Selectors",
JSON.stringify(options.selectors)
);
// Send the proper header information for POST forms
if (requestPayload && requestMethod === "POST" && !formData) {
request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
request.setRequestHeader(
"Content-Type",
"application/x-www-form-urlencoded"
);
}
request.send(requestPayload)
request.send(requestPayload);
return request
}
return request;
};

View File

@@ -1,37 +1,59 @@
var forEachEls = require("./foreach-els")
var forEachEls = require("./foreach-els");
var defaultSwitches = require("./switches")
var defaultSwitches = require("./switches");
module.exports = function(switches, switchesOptions, selectors, fromEl, toEl, options) {
var switchesQueue = []
module.exports = function(
switches,
switchesOptions,
selectors,
fromEl,
toEl,
options
) {
var switchesQueue = [];
selectors.forEach(function(selector) {
var newEls = fromEl.querySelectorAll(selector)
var oldEls = toEl.querySelectorAll(selector)
var newEls = fromEl.querySelectorAll(selector);
var oldEls = toEl.querySelectorAll(selector);
if (this.log) {
this.log("Pjax switch", selector, newEls, oldEls)
this.log("Pjax switch", selector, newEls, oldEls);
}
if (newEls.length !== oldEls.length) {
throw "DOM doesnt look the same on new loaded page: " + selector + " - new " + newEls.length + ", old " + oldEls.length
throw "DOM doesnt 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)
}
forEachEls(
newEls,
function(newEl, i) {
var oldEl = oldEls[i];
if (this.log) {
this.log("newEl", newEl, "oldEl", oldEl);
}
var callback = (switches[selector]) ?
switches[selector].bind(this, oldEl, newEl, options, switchesOptions[selector]) :
defaultSwitches.outerHTML.bind(this, oldEl, newEl, options)
var callback = switches[selector]
? switches[selector].bind(
this,
oldEl,
newEl,
options,
switchesOptions[selector]
)
: defaultSwitches.outerHTML.bind(this, oldEl, newEl, options);
switchesQueue.push(callback)
}, this)
}, this)
switchesQueue.push(callback);
},
this
);
}, this);
this.state.numPendingSwitches = switchesQueue.length
this.state.numPendingSwitches = switchesQueue.length;
switchesQueue.forEach(function(queuedSwitch) {
queuedSwitch()
})
}
queuedSwitch();
});
};

View File

@@ -1,122 +1,140 @@
var on = require("./events/on.js")
var on = require("./events/on");
module.exports = {
outerHTML: function(oldEl, newEl) {
oldEl.outerHTML = newEl.outerHTML
this.onSwitch()
oldEl.outerHTML = newEl.outerHTML;
this.onSwitch();
},
innerHTML: function(oldEl, newEl) {
oldEl.innerHTML = newEl.innerHTML
oldEl.innerHTML = newEl.innerHTML;
if (newEl.className === "") {
oldEl.removeAttribute("class")
}
else {
oldEl.className = newEl.className
oldEl.removeAttribute("class");
} else {
oldEl.className = newEl.className;
}
this.onSwitch()
this.onSwitch();
},
switchElementsAlt: function(oldEl, newEl) {
oldEl.innerHTML = newEl.innerHTML
oldEl.innerHTML = newEl.innerHTML;
// Copy attributes from the new element to the old one
if (newEl.hasAttributes()) {
var attrs = newEl.attributes
var attrs = newEl.attributes;
for (var i = 0; i < attrs.length; i++) {
oldEl.attributes.setNamedItem(attrs[i].cloneNode())
oldEl.attributes.setNamedItem(attrs[i].cloneNode());
}
}
this.onSwitch()
this.onSwitch();
},
// Equivalent to outerHTML(), but doesn't require switchElementsAlt() for <head> and <body>
replaceNode: function(oldEl, newEl) {
oldEl.parentNode.replaceChild(newEl, oldEl)
this.onSwitch()
oldEl.parentNode.replaceChild(newEl, oldEl);
this.onSwitch();
},
sideBySide: function(oldEl, newEl, options, switchOptions) {
var forEach = Array.prototype.forEach
var elsToRemove = []
var elsToAdd = []
var fragToAppend = document.createDocumentFragment()
var animationEventNames = "animationend webkitAnimationEnd MSAnimationEnd oanimationend"
var animatedElsNumber = 0
var forEach = Array.prototype.forEach;
var elsToRemove = [];
var elsToAdd = [];
var fragToAppend = document.createDocumentFragment();
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
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);
}
});
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");
});
elsToAdd.forEach(function(el) {
el.className = el.className.replace(el.getAttribute("data-pjax-classes"), "")
el.removeAttribute("data-pjax-classes")
})
elsToAdd = null; // free memory
elsToRemove = null; // free memory
elsToAdd = null // free memory
elsToRemove = null // free memory
// this is to trigger some repaint (example: picturefill)
this.onSwitch();
}
}.bind(this);
// this is to trigger some repaint (example: picturefill)
this.onSwitch()
}
}.bind(this)
switchOptions = switchOptions || {}
switchOptions = switchOptions || {};
forEach.call(oldEl.childNodes, function(el) {
elsToRemove.push(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.className = el.className.replace(
el.getAttribute("data-pjax-classes"),
""
);
el.removeAttribute("data-pjax-classes");
}
el.classList.add("js-Pjax-remove")
el.classList.add("js-Pjax-remove");
if (switchOptions.callbacks && switchOptions.callbacks.removeElement) {
switchOptions.callbacks.removeElement(el)
switchOptions.callbacks.removeElement(el);
}
if (switchOptions.classNames) {
el.className += " " + switchOptions.classNames.remove + " " + (options.backward ? switchOptions.classNames.backward : switchOptions.classNames.forward)
el.className +=
" " +
switchOptions.classNames.remove +
" " +
(options.backward
? switchOptions.classNames.backward
: switchOptions.classNames.forward);
}
animatedElsNumber++
on(el, animationEventNames, sexyAnimationEnd, true)
animatedElsNumber++;
on(el, animationEventNames, sexyAnimationEnd, true);
}
})
});
forEach.call(newEl.childNodes, function(el) {
if (el.classList) {
var addClasses = ""
var addClasses = "";
if (switchOptions.classNames) {
addClasses = " js-Pjax-add " + switchOptions.classNames.add + " " + (options.backward ? switchOptions.classNames.forward : switchOptions.classNames.backward)
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)
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)
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.className = newEl.className;
oldEl.appendChild(fragToAppend);
}
}
};

View File

@@ -1,8 +1,8 @@
module.exports = (function() {
var counter = 0
var counter = 0;
return function() {
var id = ("pjax" + (new Date().getTime())) + "_" + counter
counter++
return id
}
})()
var id = "pjax" + new Date().getTime() + "_" + counter;
counter++;
return id;
};
})();