Use anchor for better accessibility and restore history

This commit is contained in:
Chi Vinh Le
2018-08-07 17:37:02 +02:00
parent dff3e40005
commit 52b36e2db0
24 changed files with 264 additions and 115 deletions
@@ -0,0 +1,18 @@
import buildURL from "./buildURL";
it("should default to window.location", () => {
const url = buildURL();
expect(url).toBe("http://localhost/");
});
it("should build from parameters", () => {
const url = buildURL({
protocol: "https",
hostname: "hostname",
port: "8080",
pathname: "/pathname",
search: "search",
hash: "#hash",
});
expect(url).toBe("https//hostname:8080/pathname?search#hash");
});
@@ -0,0 +1,17 @@
export default function buildURL({
protocol = window.location.protocol,
hostname = window.location.hostname,
port = window.location.port,
pathname = window.location.pathname,
search = window.location.search,
hash = window.location.hash,
} = {}) {
if (search && search[0] !== "?") {
search = `?${search}`;
} else if (search === "?") {
search = "";
}
return `${protocol}//${hostname}${
port ? `:${port}` : ""
}${pathname}${search}${hash}`;
}
+2
View File
@@ -0,0 +1,2 @@
export { default as buildURL } from "./buildURL";
export { default as parseURL } from "./parseURL";
@@ -0,0 +1,20 @@
import parseURL from "./parseURL";
it("should parse url", () => {
const testCases: [[string, ReturnType<typeof parseURL>]] = [
[
"https://coralproject.net",
{
protocol: "https:",
hostname: "coralproject.net",
port: "",
pathname: "/",
search: "",
hash: "",
},
],
];
testCases.forEach(([url, expected]) => {
expect(parseURL(url)).toEqual(expected);
});
});
@@ -0,0 +1,14 @@
import { pick } from "lodash";
export default function parseURL(url: string) {
const parser = document.createElement("a");
parser.href = url;
return pick(parser, [
"protocol",
"hostname",
"port",
"pathname",
"search",
"hash",
]);
}