Skip to content

Commit

Permalink
avoid injecting duplicate instances into the 404 page
Browse files Browse the repository at this point in the history
  • Loading branch information
SidneyNemzer committed Sep 24, 2022
1 parent 2638edd commit 4b5c5a5
Showing 1 changed file with 52 additions and 39 deletions.
91 changes: 52 additions & 39 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,46 +1,59 @@
import App from "./App.svelte";
import { testPaths } from "./check-url";
import { CONTAINER_PARENT_SELECTOR } from "./constants";

const parent = document.querySelector(CONTAINER_PARENT_SELECTOR);

const segments = [
{
content: "github.com",
left: 0,
right: 0,
hovered: false,
},
...window.location.pathname
.split("/")
.filter((segment) => segment !== "")
.map((segment) => ({
content: segment,
import { CLASS_PREFIX, CONTAINER_PARENT_SELECTOR } from "./constants";

const mainClassname = CLASS_PREFIX + "main";

const main = () => {
if (document.querySelector("." + mainClassname)) {
// Already injected content, nothing to do. This can occur when navigating
// with the browser back button to a 404 page.
return;
}

const div = document.createElement("div");
div.classList.add(mainClassname);

const parent = document.querySelector(CONTAINER_PARENT_SELECTOR);
parent.insertAdjacentElement("afterend", div);

const segments = [
{
content: "github.com",
left: 0,
right: 0,
hovered: false,
})),
];

const div = document.createElement("div");
parent.insertAdjacentElement("afterend", div);

const app = new App({
target: div,
props: { segments, status: "loading", index: 1 },
});

const onPathTested = (index: number, ok: boolean) => {
if (ok) {
// Given index was ok, move to the next segment. Shifted by one extra due to
// `github.com` prefix.
app.$set({ index: index + 2, status: "loading" });
} else {
// Given index returned 404, mark it as errored. Shifted by one extra due to
// `github.com` prefix.
app.$set({ index: index + 1, status: "error" });
}
},
...window.location.pathname
.split("/")
.filter((segment) => segment !== "")
.map((segment) => ({
content: segment,
left: 0,
right: 0,
hovered: false,
})),
];

const app = new App({
target: div,
props: { segments, status: "loading", index: 1 },
});

const onPathTested = (index: number, ok: boolean) => {
if (ok) {
// Given index was ok, move to the next segment. Shifted by one extra due to
// `github.com` prefix.
app.$set({ index: index + 2, status: "loading" });
} else {
// Given index returned 404, mark it as errored. Shifted by one extra due to
// `github.com` prefix.
app.$set({ index: index + 1, status: "error" });
}
};

// TODO catch errors here
testPaths(window.location.pathname, onPathTested);
};

// TODO catch errors here
testPaths(window.location.pathname, onPathTested);
main();

0 comments on commit 4b5c5a5

Please sign in to comment.