Prettier fixes

This commit is contained in:
Behind The Math
2019-03-03 01:37:45 -05:00
parent 3c1a4b2e18
commit c13149626b
32 changed files with 1318 additions and 903 deletions

View File

@@ -1,11 +1,11 @@
var forEachEls = require("../foreach-els")
var forEachEls = require("../foreach-els");
module.exports = function(els, events, listener, useCapture) {
events = (typeof events === "string" ? events.split(" ") : events)
events = typeof events === "string" ? events.split(" ") : events;
events.forEach(function(e) {
forEachEls(els, function(el) {
el.removeEventListener(e, listener, useCapture)
})
})
}
el.removeEventListener(e, listener, useCapture);
});
});
};

View File

@@ -1,11 +1,11 @@
var forEachEls = require("../foreach-els")
var forEachEls = require("../foreach-els");
module.exports = function(els, events, listener, useCapture) {
events = (typeof events === "string" ? events.split(" ") : events)
events = typeof events === "string" ? events.split(" ") : events;
events.forEach(function(e) {
forEachEls(els, function(el) {
el.addEventListener(e, listener, useCapture)
})
})
}
el.addEventListener(e, listener, useCapture);
});
});
};

View File

@@ -1,31 +1,31 @@
var forEachEls = require("../foreach-els")
var forEachEls = require("../foreach-els");
module.exports = function(els, events, opts) {
events = (typeof events === "string" ? events.split(" ") : events)
events = typeof events === "string" ? events.split(" ") : events;
events.forEach(function(e) {
var event
event = document.createEvent("HTMLEvents")
event.initEvent(e, true, true)
event.eventName = e
var event;
event = document.createEvent("HTMLEvents");
event.initEvent(e, true, true);
event.eventName = e;
if (opts) {
Object.keys(opts).forEach(function(key) {
event[key] = opts[key]
})
event[key] = opts[key];
});
}
forEachEls(els, function(el) {
var domFix = false
var domFix = false;
if (!el.parentNode && el !== document && el !== window) {
// THANK YOU IE (9/10/11)
// dispatchEvent doesn't work if the element is not in the DOM
domFix = true
document.body.appendChild(el)
domFix = true;
document.body.appendChild(el);
}
el.dispatchEvent(event)
el.dispatchEvent(event);
if (domFix) {
el.parentNode.removeChild(el)
}
})
})
el.parentNode.removeChild(el);
}
});
});
};

View File

@@ -1,123 +1,139 @@
var on = require("../events/on")
var clone = require("../util/clone")
var on = require("../events/on");
var clone = require("../util/clone");
var attrState = "data-pjax-state"
var attrState = "data-pjax-state";
var formAction = function(el, event) {
if (isDefaultPrevented(event)) {
return
return;
}
// Since loadUrl modifies options and we may add our own modifications below,
// clone it so the changes don't persist
var options = clone(this.options)
var options = clone(this.options);
// Initialize requestOptions
options.requestOptions = {
requestUrl: el.getAttribute("action") || window.location.href,
requestMethod: el.getAttribute("method") || "GET"
}
};
// create a testable virtual link of the form action
var virtLinkElement = document.createElement("a")
virtLinkElement.setAttribute("href", options.requestOptions.requestUrl)
var virtLinkElement = document.createElement("a");
virtLinkElement.setAttribute("href", options.requestOptions.requestUrl);
var attrValue = checkIfShouldAbort(virtLinkElement, options)
var attrValue = checkIfShouldAbort(virtLinkElement, options);
if (attrValue) {
el.setAttribute(attrState, attrValue)
return
el.setAttribute(attrState, attrValue);
return;
}
event.preventDefault()
event.preventDefault();
if (el.enctype === "multipart/form-data") {
options.requestOptions.formData = new FormData(el)
}
else {
options.requestOptions.requestParams = parseFormElements(el)
options.requestOptions.formData = new FormData(el);
} else {
options.requestOptions.requestParams = parseFormElements(el);
}
el.setAttribute(attrState, "submit")
el.setAttribute(attrState, "submit");
options.triggerElement = el
this.loadUrl(virtLinkElement.href, options)
}
options.triggerElement = el;
this.loadUrl(virtLinkElement.href, options);
};
function parseFormElements(el) {
var requestParams = []
var formElements = el.elements
var requestParams = [];
var formElements = el.elements;
for (var i = 0; i < formElements.length; i++) {
var element = formElements[i]
var tagName = element.tagName.toLowerCase()
var element = formElements[i];
var tagName = element.tagName.toLowerCase();
// jscs:disable disallowImplicitTypeConversion
if (!!element.name && element.attributes !== undefined && tagName !== "button") {
if (
!!element.name &&
element.attributes !== undefined &&
tagName !== "button"
) {
// jscs:enable disallowImplicitTypeConversion
var type = element.attributes.type
var type = element.attributes.type;
if ((!type || type.value !== "checkbox" && type.value !== "radio") || element.checked) {
if (
!type ||
(type.value !== "checkbox" && type.value !== "radio") ||
element.checked
) {
// Build array of values to submit
var values = []
var values = [];
if (tagName === "select") {
var opt
var opt;
for (var j = 0; j < element.options.length; j++) {
opt = element.options[j]
opt = element.options[j];
if (opt.selected && !opt.disabled) {
values.push(opt.hasAttribute("value") ? opt.value : opt.text)
values.push(opt.hasAttribute("value") ? opt.value : opt.text);
}
}
}
else {
values.push(element.value)
} else {
values.push(element.value);
}
for (var k = 0; k < values.length; k++) {
requestParams.push({
name: encodeURIComponent(element.name),
value: encodeURIComponent(values[k])
})
});
}
}
}
}
return requestParams
return requestParams;
}
function checkIfShouldAbort(virtLinkElement, options) {
// Ignore external links.
if (virtLinkElement.protocol !== window.location.protocol || virtLinkElement.host !== window.location.host) {
return "external"
if (
virtLinkElement.protocol !== window.location.protocol ||
virtLinkElement.host !== window.location.host
) {
return "external";
}
// Ignore click if we are on an anchor on the same page
if (virtLinkElement.hash && virtLinkElement.href.replace(virtLinkElement.hash, "") === window.location.href.replace(location.hash, "")) {
return "anchor"
if (
virtLinkElement.hash &&
virtLinkElement.href.replace(virtLinkElement.hash, "") ===
window.location.href.replace(location.hash, "")
) {
return "anchor";
}
// Ignore empty anchor "foo.html#"
if (virtLinkElement.href === window.location.href.split("#")[0] + "#") {
return "anchor-empty"
return "anchor-empty";
}
// if declared as a full reload, just normally submit the form
if (options.currentUrlFullReload && virtLinkElement.href === window.location.href.split("#")[0]) {
return "reload"
if (
options.currentUrlFullReload &&
virtLinkElement.href === window.location.href.split("#")[0]
) {
return "reload";
}
}
var isDefaultPrevented = function(event) {
return event.defaultPrevented || event.returnValue === false
}
return event.defaultPrevented || event.returnValue === false;
};
module.exports = function(el) {
var that = this
var that = this;
el.setAttribute(attrState, "")
el.setAttribute(attrState, "");
on(el, "submit", function(event) {
formAction.call(that, el, event)
})
}
formAction.call(that, el, event);
});
};

View File

@@ -1,82 +1,99 @@
var on = require("../events/on")
var clone = require("../util/clone")
var on = require("../events/on");
var clone = require("../util/clone");
var attrState = "data-pjax-state"
var attrState = "data-pjax-state";
var linkAction = function(el, event) {
if (isDefaultPrevented(event)) {
return
return;
}
// Since loadUrl modifies options and we may add our own modifications below,
// clone it so the changes don't persist
var options = clone(this.options)
var options = clone(this.options);
var attrValue = checkIfShouldAbort(el, event)
var attrValue = checkIfShouldAbort(el, event);
if (attrValue) {
el.setAttribute(attrState, attrValue)
return
el.setAttribute(attrState, attrValue);
return;
}
event.preventDefault()
event.preventDefault();
// dont do "nothing" if user try to reload the page by clicking the same link twice
if (
this.options.currentUrlFullReload &&
el.href === window.location.href.split("#")[0]
) {
el.setAttribute(attrState, "reload")
this.reload()
return
el.setAttribute(attrState, "reload");
this.reload();
return;
}
el.setAttribute(attrState, "load")
el.setAttribute(attrState, "load");
options.triggerElement = el
this.loadUrl(el.href, options)
}
options.triggerElement = el;
this.loadUrl(el.href, options);
};
function checkIfShouldAbort(el, event) {
// Dont break browser special behavior on links (like page in new window)
if (event.which > 1 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) {
return "modifier"
if (
event.which > 1 ||
event.metaKey ||
event.ctrlKey ||
event.shiftKey ||
event.altKey
) {
return "modifier";
}
// we do test on href now to prevent unexpected behavior if for some reason
// user have href that can be dynamically updated
// Ignore external links.
if (el.protocol !== window.location.protocol || el.host !== window.location.host) {
return "external"
if (
el.protocol !== window.location.protocol ||
el.host !== window.location.host
) {
return "external";
}
// Ignore anchors on the same page (keep native behavior)
if (el.hash && el.href.replace(el.hash, "") === window.location.href.replace(location.hash, "")) {
return "anchor"
if (
el.hash &&
el.href.replace(el.hash, "") ===
window.location.href.replace(location.hash, "")
) {
return "anchor";
}
// Ignore empty anchor "foo.html#"
if (el.href === window.location.href.split("#")[0] + "#") {
return "anchor-empty"
return "anchor-empty";
}
}
var isDefaultPrevented = function(event) {
return event.defaultPrevented || event.returnValue === false
}
return event.defaultPrevented || event.returnValue === false;
};
module.exports = function(el) {
var that = this
var that = this;
el.setAttribute(attrState, "")
el.setAttribute(attrState, "");
on(el, "click", function(event) {
linkAction.call(that, el, event)
})
linkAction.call(that, el, event);
});
on(el, "keyup", function(event) {
on(
el,
"keyup",
function(event) {
if (event.keyCode === 13) {
linkAction.call(that, el, event)
}
}.bind(this))
linkAction.call(that, el, event);
}
}.bind(this)
);
};

View File

@@ -1,11 +1,11 @@
module.exports = function() {
if (this.options.debug && console) {
if (typeof console.log === "function") {
console.log.apply(console, arguments)
console.log.apply(console, arguments);
}
// IE is weird
else if (console.log) {
console.log(arguments)
}
console.log(arguments);
}
}
};

View File

@@ -1,22 +1,22 @@
var attrState = "data-pjax-state"
var attrState = "data-pjax-state";
module.exports = function(el) {
switch (el.tagName.toLowerCase()) {
case "a":
// only attach link if el does not already have link attached
if (!el.hasAttribute(attrState)) {
this.attachLink(el)
this.attachLink(el);
}
break
break;
case "form":
// only attach link if el does not already have link attached
if (!el.hasAttribute(attrState)) {
this.attachForm(el)
this.attachForm(el);
}
break
break;
default:
throw "Pjax can only be applied on <a> or <form> submit"
}
throw "Pjax can only be applied on <a> or <form> submit";
}
};

View File

@@ -1,13 +1,13 @@
module.exports = function(obj) {
/* istanbul ignore if */
if (null === obj || "object" !== typeof obj) {
return obj
return obj;
}
var copy = obj.constructor()
var copy = obj.constructor();
for (var attr in obj) {
if (obj.hasOwnProperty(attr)) {
copy[attr] = obj[attr]
copy[attr] = obj[attr];
}
}
return copy
}
return copy;
};

View File

@@ -1,12 +1,12 @@
module.exports = function contains(doc, selectors, el) {
for (var i = 0; i < selectors.length; i++) {
var selectedEls = doc.querySelectorAll(selectors[i])
var selectedEls = doc.querySelectorAll(selectors[i]);
for (var j = 0; j < selectedEls.length; j++) {
if (selectedEls[j].contains(el)) {
return true
return true;
}
}
}
return false
}
return false;
};

View File

@@ -1,21 +1,21 @@
module.exports = function(target) {
if (target == null) {
return null
return null;
}
var to = Object(target)
var to = Object(target);
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i]
var source = arguments[i];
if (source != null) {
for (var key in source) {
// Avoid bugs when hasOwnProperty is shadowed
if (Object.prototype.hasOwnProperty.call(source, key)) {
to[key] = source[key]
to[key] = source[key];
}
}
}
}
return to
}
return to;
};

View File

@@ -1 +1 @@
module.exports = function() {}
module.exports = function() {};

View File

@@ -1,10 +1,9 @@
module.exports = function(uri, key, value) {
var re = new RegExp("([?&])" + key + "=.*?(&|$)", "i")
var separator = uri.indexOf("?") !== -1 ? "&" : "?"
var re = new RegExp("([?&])" + key + "=.*?(&|$)", "i");
var separator = uri.indexOf("?") !== -1 ? "&" : "?";
if (uri.match(re)) {
return uri.replace(re, "$1" + key + "=" + value + "$2")
}
else {
return uri + separator + key + "=" + value
}
return uri.replace(re, "$1" + key + "=" + value + "$2");
} else {
return uri + separator + key + "=" + value;
}
};

View File

@@ -1,18 +1,18 @@
var tape = require("tape")
var tape = require("tape");
var abortRequest = require("../../lib/abort-request.js")
var sendRequest = require("../../lib/send-request.js")
var abortRequest = require("../../lib/abort-request.js");
var sendRequest = require("../../lib/send-request.js");
// Polyfill responseURL property into XMLHttpRequest if it doesn't exist,
// just for the purposes of this test
// This polyfill is not complete; it won't show the updated location if a
// redirection occurred, but it's fine for our purposes.
if (!("responseURL" in XMLHttpRequest.prototype)) {
var nativeOpen = XMLHttpRequest.prototype.open
var nativeOpen = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function(method, url) {
this.responseURL = url
return nativeOpen.apply(this, arguments)
}
this.responseURL = url;
return nativeOpen.apply(this, arguments);
};
}
tape("test aborting xhr request", function(t) {
@@ -20,37 +20,36 @@ tape("test aborting xhr request", function(t) {
options: {
cacheBust: true
}
})
});
t.test("- pending request is aborted", function(t) {
var r = requestCacheBust("https://httpbin.org/delay/10", {}, function() {
t.fail("xhr was not aborted")
})
t.equal(r.readyState, 1, "xhr readyState is '1' (SENT)")
abortRequest(r)
t.equal(r.readyState, 0, "xhr readyState is '0' (ABORTED)")
t.equal(r.status, 0, "xhr HTTP status is '0' (ABORTED)")
t.equal(r.responseText, "", "xhr response is empty")
t.end()
})
t.fail("xhr was not aborted");
});
t.equal(r.readyState, 1, "xhr readyState is '1' (SENT)");
abortRequest(r);
t.equal(r.readyState, 0, "xhr readyState is '0' (ABORTED)");
t.equal(r.status, 0, "xhr HTTP status is '0' (ABORTED)");
t.equal(r.responseText, "", "xhr response is empty");
t.end();
});
t.test("- request is not aborted if it has already completed", function(t) {
var r = requestCacheBust("https://httpbin.org/get", {}, function() {
abortRequest(r)
t.equal(r.readyState, 4, "xhr readyState is '4' (DONE)")
t.equal(r.status, 200, "xhr HTTP status is '200' (OK)")
t.end()
})
})
abortRequest(r);
t.equal(r.readyState, 4, "xhr readyState is '4' (DONE)");
t.equal(r.status, 200, "xhr HTTP status is '200' (OK)");
t.end();
});
});
t.test("- request is not aborted if it is undefined", function(t) {
var r
var r;
try {
abortRequest(r)
abortRequest(r);
} catch (e) {
t.fail("aborting an undefined request threw an error");
}
catch (e) {
t.fail("aborting an undefined request threw an error")
}
t.equal(typeof r, "undefined", "undefined xhr was ignored")
t.end()
})
t.end()
})
t.equal(typeof r, "undefined", "undefined xhr was ignored");
t.end();
});
t.end();
});

View File

@@ -1,31 +1,38 @@
var tape = require("tape")
var tape = require("tape");
var evalScript = require("../../lib/eval-script")
var evalScript = require("../../lib/eval-script");
tape("test evalScript method", function(t) {
document.body.className = ""
document.body.className = "";
var script = document.createElement("script")
script.innerHTML = "document.body.className = 'executed'"
var script = document.createElement("script");
script.innerHTML = "document.body.className = 'executed'";
t.equal(document.body.className, "", "script hasn't been executed yet")
t.equal(document.body.className, "", "script hasn't been executed yet");
evalScript(script)
t.equal(document.body.className, "executed", "script has been properly executed")
evalScript(script);
t.equal(
document.body.className,
"executed",
"script has been properly executed"
);
script.innerHTML = "document.write('failure')"
var bodyText = "document.write hasn't been executed"
document.body.text = bodyText
evalScript(script)
t.equal(document.body.text, bodyText, "document.write hasn't been executed")
script.innerHTML = "document.write('failure')";
var bodyText = "document.write hasn't been executed";
document.body.text = bodyText;
evalScript(script);
t.equal(document.body.text, bodyText, "document.write hasn't been executed");
t.end()
})
t.end();
});
tape("evalScript should not throw an error if the script removed itself", function(t) {
var script = document.createElement("script")
tape(
"evalScript should not throw an error if the script removed itself",
function(t) {
var script = document.createElement("script");
script.id = "myScript";
script.innerHTML = "const script = document.querySelector('#myScript');" +
script.innerHTML =
"const script = document.querySelector('#myScript');" +
"script.parentNode.removeChild(script);";
try {
@@ -38,4 +45,5 @@ tape("evalScript should not throw an error if the script removed itself", functi
}
t.end();
})
}
);

View File

@@ -1,110 +1,177 @@
var tape = require("tape")
var tape = require("tape");
var on = require("../../lib/events/on")
var off = require("../../lib/events/off")
var trigger = require("../../lib/events/trigger")
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 el = document.createElement("div");
var el2 = document.createElement("span");
var els = [el, el2];
var classCb = function() {
this.className += "on"
}
this.className += "on";
};
var attrCb = function() {
this.setAttribute("data-state", this.getAttribute("data-state") + "ON")
}
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 = "";
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")
el.className = "off";
off(el, "click", classCb);
trigger(el, "click");
t.equal(el.className, "off", "triggered event didn't fire detached callback");
t.end()
})
t.end();
});
tape("test events on/off/trigger for multiple elements, one event", function(t) {
el.className = ""
el2.className = ""
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")
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")
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()
})
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")
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")
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()
})
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")
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")
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()
})
t.end();
}
);
tape("test events on top level elements", function(t) {
var el = document
var el = document;
el.className = ""
on(el, "click", classCb)
trigger(el, "click")
t.equal(el.className, "on", "attached callback has been fired properly on document")
el.className = "";
on(el, "click", classCb);
trigger(el, "click");
t.equal(
el.className,
"on",
"attached callback has been fired properly on document"
);
el = window
el = window;
el.className = ""
el.className = "";
// With jsdom, the default this is global, not window, so we need to explicitly bind to window.
on(el, "click", classCb.bind(window))
trigger(el, "click")
t.equal(el.className, "on", "attached callback has been fired properly on window")
on(el, "click", classCb.bind(window));
trigger(el, "click");
t.equal(
el.className,
"on",
"attached callback has been fired properly on window"
);
t.end()
})
t.end();
});

View File

@@ -1,29 +1,49 @@
var tape = require("tape")
var tape = require("tape");
var executeScripts = require("../../lib/execute-scripts")
var executeScripts = require("../../lib/execute-scripts");
tape("test executeScripts method when the script tag is inside a container", function(t) {
document.body.className = ""
tape(
"test executeScripts method when the script tag is inside a container",
function(t) {
document.body.className = "";
var container = document.createElement("div")
container.innerHTML = "<" + "script" + ">document.body.className = 'executed';</" + "script" + "><" + "script" + ">document.body.className += ' correctly';</" + "script" + ">"
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.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()
})
t.end();
}
);
tape("test executeScripts method with just a script tag", function(t) {
document.body.className = ""
document.body.className = "";
var script = document.createElement("script")
script.innerHTML = "document.body.className = 'executed correctly';"
var script = document.createElement("script");
script.innerHTML = "document.body.className = 'executed correctly';";
t.equal(document.body.className, "", "script hasn't been executed yet")
executeScripts(script)
t.equal(document.body.className, "executed correctly", "script has been properly executed")
t.equal(document.body.className, "", "script hasn't been executed yet");
executeScripts(script);
t.equal(
document.body.className,
"executed correctly",
"script has been properly executed"
);
t.end()
})
t.end();
});

View File

@@ -1,45 +1,60 @@
var tape = require("tape")
var tape = require("tape");
var forEachEls = require("../../lib/foreach-els.js")
var forEachEls = require("../../lib/foreach-els.js");
var div = document.createElement("div")
var span = document.createElement("span")
var div = document.createElement("div");
var span = document.createElement("span");
var cb = function(el) {
el.innerHTML = "boom"
}
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()
})
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"
div.innerHTML = "div tag";
span.innerHTML = "span tag";
forEachEls([div, span], cb)
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.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()
})
t.end();
});
tape("test forEachEls on a NodeList", function(t) {
div.innerHTML = "div tag"
span.innerHTML = "span tag"
div.innerHTML = "div tag";
span.innerHTML = "span tag";
var frag = document.createDocumentFragment()
frag.appendChild(div)
frag.appendChild(span)
forEachEls(frag.childNodes, cb)
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.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()
})
t.end();
});

View File

@@ -1,24 +1,40 @@
var tape = require("tape")
var tape = require("tape");
var forEachEls = require("../../lib/foreach-selectors.js")
var forEachEls = require("../../lib/foreach-selectors.js");
var cb = function(el) {
el.className = "modified"
}
el.className = "modified";
};
tape("test forEachSelector", function(t) {
forEachEls(["html", "body"], cb)
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")
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 = ""
document.documentElement.className = "";
document.body.className = "";
forEachEls(["html", "body"], cb, null, document.documentElement)
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.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()
})
t.end();
});

View File

@@ -1,8 +1,11 @@
var tape = require("tape")
var tape = require("tape");
var isSupported = require("../../lib/is-supported.js")
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()
})
t.true(
isSupported(),
"well, we run test on supported browser, so it should be ok here"
);
t.end();
});

View File

@@ -1,160 +1,231 @@
var tape = require("tape")
var tape = require("tape");
var on = require("../../../lib/events/on")
var trigger = require("../../../lib/events/trigger")
var attachForm = require("../../../lib/proto/attach-form")
var on = require("../../../lib/events/on");
var trigger = require("../../../lib/events/trigger");
var attachForm = require("../../../lib/proto/attach-form");
var attr = "data-pjax-state"
var attr = "data-pjax-state";
tape("test attach form prototype method", function(t) {
var form = document.createElement("form")
var loadUrlCalled = false
var form = document.createElement("form");
var loadUrlCalled = false;
attachForm.call({
attachForm.call(
{
options: {
currentUrlFullReload: true
},
loadUrl: function() {
loadUrlCalled = true
loadUrlCalled = true;
}
}, form)
},
form
);
var internalUri = window.location.protocol + "//" + window.location.host + window.location.pathname + window.location.search
var internalUri =
window.location.protocol +
"//" +
window.location.host +
window.location.pathname +
window.location.search;
form.action = "http://external.com/"
trigger(form, "submit")
t.equal(form.getAttribute(attr), "external", "external url stop behavior")
form.action = "http://external.com/";
trigger(form, "submit");
t.equal(form.getAttribute(attr), "external", "external url stop behavior");
form.action = internalUri + "#anchor"
trigger(form, "submit")
t.equal(form.getAttribute(attr), "anchor", "internal anchor stop behavior")
form.action = internalUri + "#anchor";
trigger(form, "submit");
t.equal(form.getAttribute(attr), "anchor", "internal anchor stop behavior");
window.location.hash = "#anchor"
form.action = internalUri + "#another-anchor"
trigger(form, "submit")
t.equal(form.getAttribute(attr), "anchor", "different anchors stop behavior")
window.location.hash = ""
window.location.hash = "#anchor";
form.action = internalUri + "#another-anchor";
trigger(form, "submit");
t.equal(form.getAttribute(attr), "anchor", "different anchors stop behavior");
window.location.hash = "";
form.action = internalUri + "#"
trigger(form, "submit")
t.equal(form.getAttribute(attr), "anchor-empty", "empty anchor stop behavior")
form.action = internalUri + "#";
trigger(form, "submit");
t.equal(
form.getAttribute(attr),
"anchor-empty",
"empty anchor stop behavior"
);
form.action = window.location.href
trigger(form, "submit")
t.equal(form.getAttribute(attr), "reload", "submitting when currentUrlFullReload is true will submit normally, without XHR")
t.equal(loadUrlCalled, false, "loadUrl() not called")
form.action = window.location.href;
trigger(form, "submit");
t.equal(
form.getAttribute(attr),
"reload",
"submitting when currentUrlFullReload is true will submit normally, without XHR"
);
t.equal(loadUrlCalled, false, "loadUrl() not called");
form.action = window.location.protocol + "//" + window.location.host + "/internal"
form.method = "POST"
trigger(form, "submit")
t.equal(form.getAttribute(attr), "submit", "triggering a POST request to the next page")
t.equal(loadUrlCalled, true, "loadUrl() called correctly")
form.action =
window.location.protocol + "//" + window.location.host + "/internal";
form.method = "POST";
trigger(form, "submit");
t.equal(
form.getAttribute(attr),
"submit",
"triggering a POST request to the next page"
);
t.equal(loadUrlCalled, true, "loadUrl() called correctly");
loadUrlCalled = false
form.setAttribute(attr, "")
form.action = window.location.protocol + "//" + window.location.host + "/internal"
form.method = "GET"
trigger(form, "submit")
t.equal(form.getAttribute(attr), "submit", "triggering a GET request to the next page")
t.equal(loadUrlCalled, true, "loadUrl() called correctly")
loadUrlCalled = false;
form.setAttribute(attr, "");
form.action =
window.location.protocol + "//" + window.location.host + "/internal";
form.method = "GET";
trigger(form, "submit");
t.equal(
form.getAttribute(attr),
"submit",
"triggering a GET request to the next page"
);
t.equal(loadUrlCalled, true, "loadUrl() called correctly");
t.end()
})
t.end();
});
tape("test attach form preventDefaulted events", function(t) {
var loadUrlCalled = false
var form = document.createElement("form")
var loadUrlCalled = false;
var form = document.createElement("form");
// This needs to be before the call to attachForm()
on(form, "submit", function(event) { event.preventDefault() })
on(form, "submit", function(event) {
event.preventDefault();
});
attachForm.call({
attachForm.call(
{
options: {},
loadUrl: function() {
loadUrlCalled = true
loadUrlCalled = true;
}
}, form)
},
form
);
form.action = "#"
trigger(form, "submit")
t.equal(loadUrlCalled, false, "events that are preventDefaulted should not fire callback")
form.action = "#";
trigger(form, "submit");
t.equal(
loadUrlCalled,
false,
"events that are preventDefaulted should not fire callback"
);
t.end()
})
t.end();
});
tape("test options are not modified by attachForm", function(t) {
var form = document.createElement("form")
var options = {foo: "bar"}
var loadUrl = function() {}
var form = document.createElement("form");
var options = { foo: "bar" };
var loadUrl = function() {};
attachForm.call({options: options, loadUrl: loadUrl}, form)
attachForm.call({ options: options, loadUrl: loadUrl }, form);
form.action = window.location.protocol + "//" + window.location.host + window.location.pathname + window.location.search
form.method = "GET"
trigger(form, "submit")
form.action =
window.location.protocol +
"//" +
window.location.host +
window.location.pathname +
window.location.search;
form.method = "GET";
trigger(form, "submit");
t.equal(1, Object.keys(options).length, "options object that is passed in should not be modified")
t.equal("bar", options.foo, "options object that is passed in should not be modified")
t.equal(
1,
Object.keys(options).length,
"options object that is passed in should not be modified"
);
t.equal(
"bar",
options.foo,
"options object that is passed in should not be modified"
);
t.end()
})
t.end();
});
tape("test form elements parsed correctly", function(t) {
t.plan(1)
t.plan(1);
var form = document.createElement("form")
var input = document.createElement("input")
input.name = "input"
input.value = "value"
form.appendChild(input)
var form = document.createElement("form");
var input = document.createElement("input");
input.name = "input";
input.value = "value";
form.appendChild(input);
var params = [{
var params = [
{
name: "input",
value: "value"
}]
}
];
var pjax = {
options: {},
loadUrl: function(href, options) {
t.same(options.requestOptions.requestParams, params, "form elements parsed correctly")
}
t.same(
options.requestOptions.requestParams,
params,
"form elements parsed correctly"
);
}
};
attachForm.call(pjax, form)
attachForm.call(pjax, form);
form.action = window.location.protocol + "//" + window.location.host + "/internal"
form.action =
window.location.protocol + "//" + window.location.host + "/internal";
trigger(form, "submit")
trigger(form, "submit");
// see loadUrl defined above
t.end()
})
t.end();
});
tape("test form.enctype=\"multipart/form-data\"", function(t) {
t.plan(4)
tape('test form.enctype="multipart/form-data"', function(t) {
t.plan(4);
var form = document.createElement("form")
form.enctype = "multipart/form-data"
var input = document.createElement("input")
input.name = "input"
input.value = "value"
form.appendChild(input)
var form = document.createElement("form");
form.enctype = "multipart/form-data";
var input = document.createElement("input");
input.name = "input";
input.value = "value";
form.appendChild(input);
var pjax = {
options: {},
loadUrl: function(href, options) {
t.equals(options.requestOptions.requestParams, undefined, "form elements not parsed manually")
t.true(options.requestOptions.formData instanceof FormData, "requestOptions.formData is a FormData")
t.equals(Array.from(options.requestOptions.formData.entries()).length, 1, "correct number of FormData elements")
t.equals(options.requestOptions.formData.get("input"), "value", "FormData element value set correctly")
}
t.equals(
options.requestOptions.requestParams,
undefined,
"form elements not parsed manually"
);
t.true(
options.requestOptions.formData instanceof FormData,
"requestOptions.formData is a FormData"
);
t.equals(
Array.from(options.requestOptions.formData.entries()).length,
1,
"correct number of FormData elements"
);
t.equals(
options.requestOptions.formData.get("input"),
"value",
"FormData element value set correctly"
);
}
};
attachForm.call(pjax, form)
attachForm.call(pjax, form);
form.action = window.location.protocol + "//" + window.location.host + "/internal"
form.action =
window.location.protocol + "//" + window.location.host + "/internal";
trigger(form, "submit")
trigger(form, "submit");
// see loadUrl defined above
t.end()
})
t.end();
});

View File

@@ -1,143 +1,190 @@
var tape = require("tape")
var tape = require("tape");
var on = require("../../../lib/events/on")
var trigger = require("../../../lib/events/trigger")
var attachLink = require("../../../lib/proto/attach-link")
var on = require("../../../lib/events/on");
var trigger = require("../../../lib/events/trigger");
var attachLink = require("../../../lib/proto/attach-link");
var attr = "data-pjax-state"
var attr = "data-pjax-state";
tape("test attach link prototype method", function(t) {
var a = document.createElement("a")
var loadUrlCalled = false
var a = document.createElement("a");
var loadUrlCalled = false;
attachLink.call({
attachLink.call(
{
options: {},
loadUrl: function() {
loadUrlCalled = true
loadUrlCalled = true;
}
}, a)
},
a
);
var internalUri = window.location.protocol + "//" + window.location.host + window.location.pathname + window.location.search
var internalUri =
window.location.protocol +
"//" +
window.location.host +
window.location.pathname +
window.location.search;
a.href = internalUri
trigger(a, "click", {metaKey: true})
t.equal(a.getAttribute(attr), "modifier", "event key modifier stop behavior")
a.href = internalUri;
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 = "http://external.com/";
trigger(a, "click");
t.equal(a.getAttribute(attr), "external", "external url stop behavior");
window.location.hash = "#anchor"
a.href = internalUri + "#anchor"
trigger(a, "click")
t.equal(a.getAttribute(attr), "anchor", "internal anchor stop behavior")
window.location.hash = "#anchor";
a.href = internalUri + "#anchor";
trigger(a, "click");
t.equal(a.getAttribute(attr), "anchor", "internal anchor stop behavior");
a.href = internalUri + "#another-anchor"
trigger(a, "click")
t.equal(a.getAttribute(attr), "anchor", "different anchors stop behavior")
window.location.hash = ""
a.href = internalUri + "#another-anchor";
trigger(a, "click");
t.equal(a.getAttribute(attr), "anchor", "different 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");
t.equal(a.getAttribute(attr), "anchor-empty", "empty anchor stop behavior");
a.href = window.location.protocol + "//" + window.location.host + "/internal"
trigger(a, "click")
t.equals(a.getAttribute(attr), "load", "triggering an internal link sets the state attribute to 'load'")
t.equals(loadUrlCalled, true, "triggering an internal link actually loads the page")
a.href = window.location.protocol + "//" + window.location.host + "/internal";
trigger(a, "click");
t.equals(
a.getAttribute(attr),
"load",
"triggering an internal link sets the state attribute to 'load'"
);
t.equals(
loadUrlCalled,
true,
"triggering an internal link actually loads the page"
);
t.end()
})
t.end();
});
tape("test attach link preventDefaulted events", function(t) {
var loadUrlCalled = false
var a = document.createElement("a")
var loadUrlCalled = false;
var a = document.createElement("a");
// This needs to be before the call to attachLink()
on(a, "click", function(event) {
event.preventDefault()
})
event.preventDefault();
});
attachLink.call({
attachLink.call(
{
options: {},
loadUrl: function() {
loadUrlCalled = true
loadUrlCalled = true;
}
}, a)
},
a
);
a.href = "#"
trigger(a, "click")
t.equal(loadUrlCalled, false, "events that are preventDefaulted should not fire callback")
a.href = "#";
trigger(a, "click");
t.equal(
loadUrlCalled,
false,
"events that are preventDefaulted should not fire callback"
);
t.end()
})
t.end();
});
tape("test options are not modified by attachLink", function(t) {
var a = document.createElement("a")
var options = {foo: "bar"}
var loadUrl = function() {}
var a = document.createElement("a");
var options = { foo: "bar" };
var loadUrl = function() {};
attachLink.call({options: options, loadUrl: loadUrl}, a)
attachLink.call({ options: options, loadUrl: loadUrl }, a);
a.href = window.location.protocol + "//" + window.location.host + window.location.pathname + window.location.search
a.href =
window.location.protocol +
"//" +
window.location.host +
window.location.pathname +
window.location.search;
trigger(a, "click")
trigger(a, "click");
t.equal(1, Object.keys(options).length, "options object that is passed in should not be modified")
t.equal("bar", options.foo, "options object that is passed in should not be modified")
t.equal(
1,
Object.keys(options).length,
"options object that is passed in should not be modified"
);
t.equal(
"bar",
options.foo,
"options object that is passed in should not be modified"
);
t.end()
})
t.end();
});
tape("test link triggered by keyboard", function(t) {
var a = document.createElement("a")
var a = document.createElement("a");
var pjax = {
options: {},
loadUrl: function() {
t.equal(a.getAttribute(attr), "load", "triggering a internal link actually loads the page")
}
t.equal(
a.getAttribute(attr),
"load",
"triggering a internal link actually loads the page"
);
}
};
t.plan(3)
t.plan(3);
attachLink.call(pjax, a)
attachLink.call(pjax, a);
a.href = window.location.protocol + "//" + window.location.host + "/internal"
a.href = window.location.protocol + "//" + window.location.host + "/internal";
trigger(a, "keyup", {keyCode: 14})
t.equal(a.getAttribute(attr), "", "keycode other than 13 doesn't trigger anything")
trigger(a, "keyup", { keyCode: 14 });
t.equal(
a.getAttribute(attr),
"",
"keycode other than 13 doesn't trigger anything"
);
trigger(a, "keyup", {keyCode: 13, metaKey: true})
t.equal(a.getAttribute(attr), "modifier", "event key modifier stop behavior")
trigger(a, "keyup", { keyCode: 13, metaKey: true });
t.equal(a.getAttribute(attr), "modifier", "event key modifier stop behavior");
trigger(a, "keyup", {keyCode: 13})
trigger(a, "keyup", { keyCode: 13 });
// see loadUrl defined above
t.end()
})
t.end();
});
tape("test link with the same URL as the current one, when currentUrlFullReload set to true", function(t) {
var a = document.createElement("a")
tape(
"test link with the same URL as the current one, when currentUrlFullReload set to true",
function(t) {
var a = document.createElement("a");
var pjax = {
options: {
currentUrlFullReload: true
},
reload: function() {
t.pass("this.reload() was called correctly")
t.pass("this.reload() was called correctly");
},
loadUrl: function() {
t.fail("loadUrl() was called wrongly")
t.fail("loadUrl() was called wrongly");
}
};
t.plan(2);
attachLink.call(pjax, a);
a.href = window.location.href;
trigger(a, "click");
t.equal(a.getAttribute(attr), "reload", "reload stop behavior");
t.end();
}
t.plan(2)
attachLink.call(pjax, a)
a.href = window.location.href
trigger(a, "click")
t.equal(a.getAttribute(attr), "reload", "reload stop behavior")
t.end()
})
);

View File

@@ -1,39 +1,43 @@
var tape = require("tape")
var tape = require("tape");
var handleReponse = require("../../../lib/proto/handle-response")
var noop = require("../../../lib/util/noop")
var handleReponse = require("../../../lib/proto/handle-response");
var noop = require("../../../lib/util/noop");
var href = "https://example.org/"
var href = "https://example.org/";
var storeEventHandler
var pjaxErrorEventTriggerTest
var storeEventHandler;
var pjaxErrorEventTriggerTest;
tape("test events triggered when handleResponse(false) is called", function(t) {
t.plan(3)
t.plan(3);
var pjax = {
options: {
test: 1
}
}
};
var events = []
var events = [];
storeEventHandler = function(e) {
events.push(e.type)
events.push(e.type);
t.equal(e.test, 1)
}
t.equal(e.test, 1);
};
document.addEventListener("pjax:complete", storeEventHandler)
document.addEventListener("pjax:error", storeEventHandler)
document.addEventListener("pjax:complete", storeEventHandler);
document.addEventListener("pjax:error", storeEventHandler);
handleReponse.bind(pjax)(false, null)
handleReponse.bind(pjax)(false, null);
t.same(events, ["pjax:complete", "pjax:error"], "calling handleResponse(false) triggers 'pjax:complete' and 'pjax:error'")
t.same(
events,
["pjax:complete", "pjax:error"],
"calling handleResponse(false) triggers 'pjax:complete' and 'pjax:error'"
);
t.end()
})
t.end();
});
tape("test when handleResponse() is called normally", function(t) {
var pjax = {
@@ -42,167 +46,209 @@ tape("test when handleResponse() is called normally", function(t) {
},
loadContent: noop,
state: {}
}
};
var request = {
getResponseHeader: noop
}
};
handleReponse.bind(pjax)("", request, "href")
handleReponse.bind(pjax)("", request, "href");
delete window.history.state.uid
t.same(window.history.state, {
delete window.history.state.uid;
t.same(
window.history.state,
{
url: href,
title: "",
scrollPos: [0, 0]
}, "window.history.state is set correctly")
t.equals(pjax.state.href, "href", "this.state.href is set correctly")
t.equals(Object.keys(pjax.state.options).length, 2, "this.state.options is set correctly")
t.same(pjax.state.options.request, request, "this.state.options is set correctly")
t.equals(pjax.state.options.test, 1, "this.state.options is set correctly")
},
"window.history.state is set correctly"
);
t.equals(pjax.state.href, "href", "this.state.href is set correctly");
t.equals(
Object.keys(pjax.state.options).length,
2,
"this.state.options is set correctly"
);
t.same(
pjax.state.options.request,
request,
"this.state.options is set correctly"
);
t.equals(pjax.state.options.test, 1, "this.state.options is set correctly");
t.end()
})
t.end();
});
tape("test when handleResponse() is called normally with request.responseURL", function(t) {
tape(
"test when handleResponse() is called normally with request.responseURL",
function(t) {
var pjax = {
options: {},
loadContent: noop,
state: {}
}
};
var request = {
responseURL: href + "1",
getResponseHeader: noop
};
handleReponse.bind(pjax)("", request, "");
t.equals(
pjax.state.href,
request.responseURL,
"this.state.href is set correctly"
);
t.end();
}
);
handleReponse.bind(pjax)("", request, "")
t.equals(pjax.state.href, request.responseURL, "this.state.href is set correctly")
t.end()
})
tape("test when handleResponse() is called normally with X-PJAX-URL", function(t) {
tape("test when handleResponse() is called normally with X-PJAX-URL", function(
t
) {
var pjax = {
options: {},
loadContent: noop,
state: {}
}
};
var request = {
getResponseHeader: function(header) {
if (header === "X-PJAX-URL") {
return href + "2"
}
return href + "2";
}
}
};
handleReponse.bind(pjax)("", request, "")
handleReponse.bind(pjax)("", request, "");
t.equals(pjax.state.href, href + "2", "this.state.href is set correctly")
t.equals(pjax.state.href, href + "2", "this.state.href is set correctly");
t.end()
})
t.end();
});
tape("test when handleResponse() is called normally with X-XHR-Redirected-To", function(t) {
tape(
"test when handleResponse() is called normally with X-XHR-Redirected-To",
function(t) {
var pjax = {
options: {},
loadContent: noop,
state: {}
}
};
var request = {
getResponseHeader: function(header) {
if (header === "X-XHR-Redirected-To") {
return href + "3"
return href + "3";
}
}
};
handleReponse.bind(pjax)("", request, "");
t.equals(pjax.state.href, href + "3", "this.state.href is set correctly");
t.end();
}
handleReponse.bind(pjax)("", request, "")
t.equals(pjax.state.href, href + "3", "this.state.href is set correctly")
t.end()
})
);
tape("test when handleResponse() is called normally with a hash", function(t) {
var pjax = {
options: {},
loadContent: noop,
state: {}
}
};
var request = {
responseURL: href + "2",
getResponseHeader: noop
}
};
handleReponse.bind(pjax)("", request, href + "1#test")
handleReponse.bind(pjax)("", request, href + "1#test");
t.equals(pjax.state.href, href + "2#test", "this.state.href is set correctly")
t.equals(
pjax.state.href,
href + "2#test",
"this.state.href is set correctly"
);
t.end()
})
t.end();
});
tape("test try...catch for loadContent() when options.debug is true", function(t) {
t.plan(2)
tape("test try...catch for loadContent() when options.debug is true", function(
t
) {
t.plan(2);
var pjax = {
options: {},
loadContent: noop,
state: {}
}
};
var request = {
getResponseHeader: noop
}
};
pjax.loadContent = function() {
throw new Error()
}
pjax.options.debug = true
throw new Error();
};
pjax.options.debug = true;
document.removeEventListener("pjax:error", storeEventHandler)
document.removeEventListener("pjax:error", storeEventHandler);
pjaxErrorEventTriggerTest = function() {
t.pass("pjax:error event triggered")
}
document.addEventListener("pjax:error", pjaxErrorEventTriggerTest)
t.pass("pjax:error event triggered");
};
document.addEventListener("pjax:error", pjaxErrorEventTriggerTest);
t.throws(function() {
handleReponse.bind(pjax)("", request, "")
}, Error, "error is rethrown")
t.throws(
function() {
handleReponse.bind(pjax)("", request, "");
},
Error,
"error is rethrown"
);
t.end()
})
t.end();
});
tape("test try...catch for loadContent()", function(t) {
t.plan(2)
t.plan(2);
var pjax = {
options: {},
loadContent: noop,
state: {}
}
};
var request = {
getResponseHeader: noop
}
};
pjax.loadContent = function() {
throw new Error()
}
throw new Error();
};
pjax.latestChance = function() {
return true
}
pjax.options.debug = false
return true;
};
pjax.options.debug = false;
document.removeEventListener("pjax:error", pjaxErrorEventTriggerTest)
document.removeEventListener("pjax:error", pjaxErrorEventTriggerTest);
t.doesNotThrow(function() {
t.equals(handleReponse.bind(pjax)("", request, ""), true, "this.latestChance() is called")
}, Error, "error is not thrown")
t.doesNotThrow(
function() {
t.equals(
handleReponse.bind(pjax)("", request, ""),
true,
"this.latestChance() is called"
);
},
Error,
"error is not thrown"
);
t.end()
})
t.end();
});

View File

@@ -1,27 +1,31 @@
var tape = require("tape")
var tape = require("tape");
var parseElement = require("../../../lib/proto/parse-element")
var parseElement = require("../../../lib/proto/parse-element");
var pjax = {
attachLink: function() { return true },
attachForm: function() { return true }
attachLink: function() {
return true;
},
attachForm: function() {
return true;
}
};
tape("test parse element prototype method", function(t) {
t.doesNotThrow(function() {
var a = document.createElement("a")
parseElement.call(pjax, a)
}, "<a> element can be parsed")
var a = document.createElement("a");
parseElement.call(pjax, a);
}, "<a> element can be parsed");
t.doesNotThrow(function() {
var form = document.createElement("form")
parseElement.call(pjax, form)
}, "<form> element can be parsed")
var form = document.createElement("form");
parseElement.call(pjax, form);
}, "<form> element can be parsed");
t.throws(function() {
var el = document.createElement("div")
parseElement.call(pjax, el)
}, "<div> element cannot be parsed")
var el = document.createElement("div");
parseElement.call(pjax, el);
}, "<div> element cannot be parsed");
t.end()
})
t.end();
});

View File

@@ -1,137 +1,165 @@
var tape = require("tape")
var tape = require("tape");
var sendRequest = require("../../lib/send-request.js")
var sendRequest = require("../../lib/send-request.js");
// Polyfill responseURL property into XMLHttpRequest if it doesn't exist,
// just for the purposes of this test
// This polyfill is not complete; it won't show the updated location if a
// redirection occurred, but it's fine for our purposes.
if (!("responseURL" in XMLHttpRequest.prototype)) {
var nativeOpen = XMLHttpRequest.prototype.open
var nativeOpen = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function(method, url) {
this.responseURL = url
return nativeOpen.apply(this, arguments)
}
this.responseURL = url;
return nativeOpen.apply(this, arguments);
};
}
tape("test xhr request", function(t) {
var url = "https://httpbin.org/get"
var url = "https://httpbin.org/get";
t.test("- request is made, gets a result, and is cache-busted", function(t) {
var r = sendRequest(url, { cacheBust: true }, function(result) {
t.equal(r.responseURL.indexOf("?"), url.length, "XHR URL is cache-busted when configured to be")
t.equal(
r.responseURL.indexOf("?"),
url.length,
"XHR URL is cache-busted when configured to be"
);
try {
result = JSON.parse(result)
result = JSON.parse(result);
} catch (e) {
t.fail("xhr doesn't get a JSON response");
}
catch (e) {
t.fail("xhr doesn't get a JSON response")
}
t.same(typeof result, "object", "xhr request get a result")
t.end()
})
})
t.test("- request is not cache-busted when configured not to be", function(t) {
t.same(typeof result, "object", "xhr request get a result");
t.end();
});
});
t.test("- request is not cache-busted when configured not to be", function(
t
) {
var r = sendRequest(url, {}, function() {
t.equal(r.responseURL, url, "XHR URL is left untouched")
t.end()
})
})
t.end()
})
t.equal(r.responseURL, url, "XHR URL is left untouched");
t.end();
});
});
t.end();
});
tape("request headers are sent properly", function(t) {
var url = "https://httpbin.org/headers"
var url = "https://httpbin.org/headers";
var options = {
selectors: ["div.pjax", "div.container"]
}
};
sendRequest(url, options, function(responseText) {
var headers = JSON.parse(responseText).headers
var headers = JSON.parse(responseText).headers;
t.equals(headers["X-Requested-With"], "XMLHttpRequest", "X-Requested-With header is set correctly")
t.equals(
headers["X-Requested-With"],
"XMLHttpRequest",
"X-Requested-With header is set correctly"
);
// Httpbin.org changes the case to 'X-Pjax'
t.equals(headers["X-Pjax"], "true", "X-PJAX header is set correctly")
t.equals(headers["X-Pjax-Selectors"], "[\"div.pjax\",\"div.container\"]", "X-PJAX-Selectors header is set correctly")
t.equals(headers["X-Pjax"], "true", "X-PJAX header is set correctly");
t.equals(
headers["X-Pjax-Selectors"],
'["div.pjax","div.container"]',
"X-PJAX-Selectors header is set correctly"
);
t.end()
})
})
t.end();
});
});
tape("HTTP status codes other than 200 are handled properly", function(t) {
var url = "https://httpbin.org/status/400"
var url = "https://httpbin.org/status/400";
sendRequest(url, {}, function(responseText, request) {
t.equals(responseText, null, "responseText is null")
t.equals(request.status, 400, "HTTP status code is correct")
t.equals(responseText, null, "responseText is null");
t.equals(request.status, 400, "HTTP status code is correct");
t.end()
})
})
t.end();
});
});
tape.skip("XHR error is handled properly", function(t) {
var url = "https://encrypted.google.com/foobar"
var url = "https://encrypted.google.com/foobar";
sendRequest(url, {}, function(responseText) {
t.equals(responseText, null, "responseText is null")
t.equals(responseText, null, "responseText is null");
t.end()
})
})
t.end();
});
});
tape("POST body data is sent properly", function(t) {
var url = "https://httpbin.org/post"
var params = [{
var url = "https://httpbin.org/post";
var params = [
{
name: "test",
value: "1"
}];
}
];
var options = {
requestOptions: {
requestMethod: "POST",
requestParams: params
}
}
};
sendRequest(url, options, function(responseText) {
var response = JSON.parse(responseText)
var response = JSON.parse(responseText);
t.same(response.form[params[0].name], params[0].value, "requestParams were sent properly")
t.equals(response.headers["Content-Type"], "application/x-www-form-urlencoded", "Content-Type header was set properly")
t.same(
response.form[params[0].name],
params[0].value,
"requestParams were sent properly"
);
t.equals(
response.headers["Content-Type"],
"application/x-www-form-urlencoded",
"Content-Type header was set properly"
);
t.end()
})
})
t.end();
});
});
tape("GET query data is sent properly", function(t) {
var url = "https://httpbin.org/get"
var params = [{
var url = "https://httpbin.org/get";
var params = [
{
name: "test",
value: "1"
}];
}
];
var options = {
requestOptions: {
requestParams: params
}
}
};
sendRequest(url, options, function(responseText) {
var response = JSON.parse(responseText)
var response = JSON.parse(responseText);
t.same(response.args[params[0].name], params[0].value, "requestParams were sent properly")
t.same(
response.args[params[0].name],
params[0].value,
"requestParams were sent properly"
);
t.end()
})
})
t.end();
});
});
tape("XHR timeout is handled properly", function(t) {
var url = "https://httpbin.org/delay/5"
var url = "https://httpbin.org/delay/5";
var options = {
timeout: 1000
}
};
sendRequest(url, options, function(responseText) {
t.equals(responseText, null, "responseText is null")
t.end()
})
})
t.equals(responseText, null, "responseText is null");
t.end();
});
});

View File

@@ -1,33 +1,33 @@
var tape = require("tape")
var tape = require("tape");
var switchesSelectors = require("../../lib/switches-selectors.js")
var noop = require("../../lib/util/noop")
var switchesSelectors = require("../../lib/switches-selectors.js");
var noop = require("../../lib/util/noop");
var pjax = {
onSwitch: function() {
console.log("Switched")
console.log("Switched");
},
state: {},
log: noop
}
};
// @author darylteo
tape("test switchesSelectors", function(t) {
// switchesSelectors relies on a higher level function callback
// should really be passed in instead so I'll leave it here as a TODO:
var tmpEl = document.implementation.createHTMLDocument()
var tmpEl = document.implementation.createHTMLDocument();
// a div container is used because swapping the containers
// will generate a new element, so things get weird
// using "body" generates a lot of testling cruft that I don't
// want so let's avoid that
var container = document.createElement("div")
container.innerHTML = "<p>Original Text</p><span>No Change</span>"
document.body.appendChild(container)
var container = document.createElement("div");
container.innerHTML = "<p>Original Text</p><span>No Change</span>";
document.body.appendChild(container);
var container2 = tmpEl.createElement("div")
container2.innerHTML = "<p>New Text</p><span>New Span</span>"
tmpEl.body.appendChild(container2)
var container2 = tmpEl.createElement("div");
container2.innerHTML = "<p>New Text</p><span>New Span</span>";
tmpEl.body.appendChild(container2);
switchesSelectors.bind(pjax)(
{}, // switches
@@ -36,39 +36,49 @@ tape("test switchesSelectors", function(t) {
tmpEl, // fromEl
document, // toEl,
{} // options
)
);
t.equals(container.innerHTML, "<p>New Text</p><span>No Change</span>", "Elements correctly switched")
t.equals(
container.innerHTML,
"<p>New Text</p><span>No Change</span>",
"Elements correctly switched"
);
t.end()
})
t.end();
});
tape("test switchesSelectors when number of elements don't match", function(t) {
var newTempDoc = document.implementation.createHTMLDocument()
var originalTempDoc = document.implementation.createHTMLDocument()
var newTempDoc = document.implementation.createHTMLDocument();
var originalTempDoc = document.implementation.createHTMLDocument();
// a div container is used because swapping the containers
// will generate a new element, so things get weird
// using "body" generates a lot of testling cruft that I don't
// want so let's avoid that
var container = originalTempDoc.createElement("div")
container.innerHTML = "<p>Original text</p><span>No change</span>"
originalTempDoc.body.appendChild(container)
var container = originalTempDoc.createElement("div");
container.innerHTML = "<p>Original text</p><span>No change</span>";
originalTempDoc.body.appendChild(container);
var container2 = newTempDoc.createElement("div")
container2.innerHTML = "<p>New text</p><p>More new text</p><span>New span</span>"
newTempDoc.body.appendChild(container2)
var container2 = newTempDoc.createElement("div");
container2.innerHTML =
"<p>New text</p><p>More new text</p><span>New span</span>";
newTempDoc.body.appendChild(container2);
var switchSelectorsFn = switchesSelectors.bind(pjax,
var switchSelectorsFn = switchesSelectors.bind(
pjax,
{}, // switches
{}, // switchesOptions
["p"], // selectors,
newTempDoc, // fromEl
originalTempDoc, // toEl,
{} // options
)
);
t.throws(switchSelectorsFn, null, "error was thrown properly since number of elements don't match")
t.throws(
switchSelectorsFn,
null,
"error was thrown properly since number of elements don't match"
);
t.end()
})
t.end();
});

View File

@@ -1,78 +1,94 @@
var tape = require("tape")
var switches = require("../../lib/switches")
var noop = require("../../lib/util/noop")
var tape = require("tape");
var switches = require("../../lib/switches");
var noop = require("../../lib/util/noop");
tape("test outerHTML switch", function(t) {
var outerHTML = switches.outerHTML
var outerHTML = switches.outerHTML;
var doc = document.implementation.createHTMLDocument()
var doc = document.implementation.createHTMLDocument();
var container = doc.createElement("div")
container.innerHTML = "<p id='p'>Original Text</p>"
doc.body.appendChild(container)
var container = doc.createElement("div");
container.innerHTML = "<p id='p'>Original Text</p>";
doc.body.appendChild(container);
var p = doc.createElement("p")
p.innerHTML = "New Text"
var p = doc.createElement("p");
p.innerHTML = "New Text";
outerHTML.bind({
onSwitch: noop
})(doc.querySelector("p"), p)
})(doc.querySelector("p"), p);
t.equals(doc.querySelector("p").innerHTML, "New Text", "Elements correctly switched")
t.notEquals(doc.querySelector("p").id, "p", "other attributes overwritten correctly")
t.equals(
doc.querySelector("p").innerHTML,
"New Text",
"Elements correctly switched"
);
t.notEquals(
doc.querySelector("p").id,
"p",
"other attributes overwritten correctly"
);
t.end()
})
t.end();
});
tape("test innerHTML switch", function(t) {
var innerHTML = switches.innerHTML
var innerHTML = switches.innerHTML;
var doc = document.implementation.createHTMLDocument()
var doc = document.implementation.createHTMLDocument();
var container = doc.createElement("div")
container.innerHTML = "<p id='p'>Original Text</p>"
doc.body.appendChild(container)
var container = doc.createElement("div");
container.innerHTML = "<p id='p'>Original Text</p>";
doc.body.appendChild(container);
var p = doc.createElement("p")
p.innerHTML = "New Text"
p.className = "p"
var p = doc.createElement("p");
p.innerHTML = "New Text";
p.className = "p";
innerHTML.bind({
onSwitch: noop
})(doc.querySelector("p"), p)
})(doc.querySelector("p"), p);
t.equals(doc.querySelector("p").innerHTML, "New Text", "Elements correctly switched")
t.equals(doc.querySelector("p").className, "p", "classname set correctly")
t.equals(doc.querySelector("p").id, "p", "other attributes set correctly")
t.equals(
doc.querySelector("p").innerHTML,
"New Text",
"Elements correctly switched"
);
t.equals(doc.querySelector("p").className, "p", "classname set correctly");
t.equals(doc.querySelector("p").id, "p", "other attributes set correctly");
p.removeAttribute("class")
p.removeAttribute("class");
innerHTML.bind({
onSwitch: noop
})(doc.querySelector("p"), p)
})(doc.querySelector("p"), p);
t.equals(doc.querySelector("p").className, "", "classname set correctly")
t.equals(doc.querySelector("p").className, "", "classname set correctly");
t.end()
})
t.end();
});
tape("test replaceNode switch", function(t) {
var replaceNode = switches.replaceNode
var replaceNode = switches.replaceNode;
var doc = document.implementation.createHTMLDocument()
var doc = document.implementation.createHTMLDocument();
var container = doc.createElement("div")
container.innerHTML = "<p>Original Text</p>"
doc.body.appendChild(container)
var container = doc.createElement("div");
container.innerHTML = "<p>Original Text</p>";
doc.body.appendChild(container);
var p = doc.createElement("p")
p.innerHTML = "New Text"
var p = doc.createElement("p");
p.innerHTML = "New Text";
replaceNode.bind({
onSwitch: noop
})(doc.querySelector("p"), p)
})(doc.querySelector("p"), p);
t.equals(doc.querySelector("div").innerHTML, "<p>New Text</p>", "Elements correctly switched")
t.equals(
doc.querySelector("div").innerHTML,
"<p>New Text</p>",
"Elements correctly switched"
);
t.end()
})
t.end();
});

View File

@@ -1,12 +1,12 @@
var tape = require("tape")
var tape = require("tape");
var uniqueid = require("../../lib/uniqueid.js")
var uniqueid = require("../../lib/uniqueid.js");
tape("test uniqueid", function(t) {
var a = uniqueid()
var b = uniqueid()
var a = uniqueid();
var b = uniqueid();
t.notEqual(a,b,"Two calls to uniqueid produce different values")
t.notEqual(a, b, "Two calls to uniqueid produce different values");
t.end()
})
t.end();
});

View File

@@ -1,17 +1,21 @@
var tape = require("tape")
var tape = require("tape");
var clone = require("../../../lib/util/clone")
var clone = require("../../../lib/util/clone");
tape("test clone method", function(t) {
var obj = {one: 1, two: 2}
var cloned = clone(obj)
var obj = { one: 1, two: 2 };
var cloned = clone(obj);
t.notEqual(obj, cloned, "cloned object isn't the original object")
t.notEqual(obj, cloned, "cloned object isn't the original object");
t.same(obj, cloned, "cloned object has the same values as original object")
t.same(obj, cloned, "cloned object has the same values as original object");
cloned.three = 3
t.notSame(obj, cloned, "modified cloned object doesn't have the same values as original object")
cloned.three = 3;
t.notSame(
obj,
cloned,
"modified cloned object doesn't have the same values as original object"
);
t.end()
})
t.end();
});

View File

@@ -1,16 +1,25 @@
var tape = require("tape")
var tape = require("tape");
var contains = require("../../../lib/util/contains.js")
var contains = require("../../../lib/util/contains.js");
tape("test contains function", function(t) {
var tempDoc = document.implementation.createHTMLDocument()
tempDoc.body.innerHTML = "<div><p id='el' class='js-Pjax'></p></div><span></span>"
var selectors = ["div"]
var el = tempDoc.body.querySelector("#el")
t.equal(contains(tempDoc, selectors, el), true, "contains() returns true when a selector contains the element")
var tempDoc = document.implementation.createHTMLDocument();
tempDoc.body.innerHTML =
"<div><p id='el' class='js-Pjax'></p></div><span></span>";
var selectors = ["div"];
var el = tempDoc.body.querySelector("#el");
t.equal(
contains(tempDoc, selectors, el),
true,
"contains() returns true when a selector contains the element"
);
selectors = ["span"]
t.equal(contains(tempDoc, selectors, el), false, "contains() returns false when the selectors do not contain the element")
selectors = ["span"];
t.equal(
contains(tempDoc, selectors, el),
false,
"contains() returns false when the selectors do not contain the element"
);
t.end()
})
t.end();
});

View File

@@ -1,17 +1,25 @@
var tape = require("tape")
var tape = require("tape");
var extend = require("../../../lib/util/extend")
var extend = require("../../../lib/util/extend");
tape("test extend method", function(t) {
var obj = {one: 1, two: 2}
var obj = { one: 1, two: 2 };
var extended = extend({}, obj, {two: "two", three: 3})
t.notEqual(obj, extended, "extended object isn't the original object")
t.notSame(obj, extended, "extended object doesn't have the same values as original object")
t.notSame(obj.two, extended.two, "extended object value overwrites value from original object")
var extended = extend({}, obj, { two: "two", three: 3 });
t.notEqual(obj, extended, "extended object isn't the original object");
t.notSame(
obj,
extended,
"extended object doesn't have the same values as original object"
);
t.notSame(
obj.two,
extended.two,
"extended object value overwrites value from original object"
);
extended = extend(null)
t.equals(extended, null, "passing null returns null")
extended = extend(null);
t.equals(extended, null, "passing null returns null");
t.end()
})
t.end();
});

View File

@@ -1,9 +1,9 @@
var tape = require("tape")
var tape = require("tape");
var noop = require("../../../lib/util/noop")
var noop = require("../../../lib/util/noop");
tape("test noop function", function(t) {
t.equal(typeof noop, "function", "noop is a function")
t.equal(noop(), undefined, "noop() returns nothing")
t.end()
})
t.equal(typeof noop, "function", "noop is a function");
t.equal(noop(), undefined, "noop() returns nothing");
t.end();
});

View File

@@ -1,21 +1,33 @@
var tape = require("tape")
var tape = require("tape");
var updateQueryString = require("../../../lib/util/update-query-string")
var updateQueryString = require("../../../lib/util/update-query-string");
tape("test update query string method", function(t) {
var url = "http://example.com"
var updatedUrl = updateQueryString(url, "foo", "bar")
var url = "http://example.com";
var updatedUrl = updateQueryString(url, "foo", "bar");
t.notEqual(url, updatedUrl, "update query string modifies URL")
t.equal(updatedUrl, url + "?foo=bar", "update query string creates new query string when no query string params are set")
t.notEqual(url, updatedUrl, "update query string modifies URL");
t.equal(
updatedUrl,
url + "?foo=bar",
"update query string creates new query string when no query string params are set"
);
updatedUrl = updateQueryString(updatedUrl, "foo", "baz")
updatedUrl = updateQueryString(updatedUrl, "foo", "baz");
t.equal(updatedUrl, url + "?foo=baz", "update query string updates existing query string param")
t.equal(
updatedUrl,
url + "?foo=baz",
"update query string updates existing query string param"
);
updatedUrl = updateQueryString(updatedUrl, "bar", "")
updatedUrl = updateQueryString(updatedUrl, "bar", "");
t.equal(updatedUrl, url + "?foo=baz&bar=", "update query string appends to existing query string")
t.equal(
updatedUrl,
url + "?foo=baz&bar=",
"update query string appends to existing query string"
);
t.end()
})
t.end();
});