Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 16 additions & 7 deletions packages/wouter/src/use-hash-location.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,17 +23,26 @@ const subscribeToHashUpdates = (callback) => {
const currentHashLocation = () => "/" + location.hash.replace(/^#?\/?/, "");

export const navigate = (to, { state = null, replace = false } = {}) => {
const [hash, search] = to.replace(/^#?\/?/, "").split("?");

const newRelativePath =
location.pathname + (search ? `?${search}` : location.search) + `#/${hash}`;
const oldURL = location.href;
const newURL = new URL(newRelativePath, location.origin).href;
let newURL, newHistoryStatePath;

if (location.protocol === "data:") {
const newHash = "#/" + to.replace(/^#?\/?/, "");
newHistoryStatePath = newHash;
newURL = oldURL.split("#")[0] + newHash;
} else {
const [hash, search] = to.replace(/^#?\/?/, "").split("?");
newHistoryStatePath =
location.pathname +
(search ? `?${search}` : location.search) +
`#/${hash}`;
newURL = new URL(newHistoryStatePath, location.origin).href;
}

if (replace) {
history.replaceState(state, "", newRelativePath);
history.replaceState(state, "", newHistoryStatePath);
} else {
history.pushState(state, "", newRelativePath);
history.pushState(state, "", newHistoryStatePath);
}

const event =
Expand Down
27 changes: 27 additions & 0 deletions packages/wouter/test/use-hash-location.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -209,6 +209,33 @@ it("defines a custom way of rendering link hrefs", () => {
expect(getByTestId("link")).toHaveAttribute("href", "#/app");
});

it("handles navigation with data: protocol", async () => {
const originalHref = location.href;
location.href = "data:text/html,content";

expect(location.protocol).toBe("data:");

const { result } = renderHook(() => useHashLocation());
const [, navigate] = result.current;
const initialHistoryLength = history.length;

await waitForHashChangeEvent(() => {
navigate("/new-path");
});

expect(location.hash).toBe("#/new-path");
expect(history.length).toBe(initialHistoryLength + 1);

await waitForHashChangeEvent(() => {
navigate("/another-path", { replace: true });
});

expect(location.hash).toBe("#/another-path");
expect(history.length).toBe(initialHistoryLength + 1);

location.href = originalHref;
});

it("interacts properly with the history stack", () => {
const { result } = renderHook(() => useHashLocation());
const [, navigate] = result.current;
Expand Down