Skip to content

feat: support options.replace in hash router #523

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Apr 15, 2025
Merged
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
5 changes: 4 additions & 1 deletion packages/wouter-preact/types/use-hash-location.d.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import { Path } from "./location-hook.js";

export function navigate<S = any>(to: Path, options?: { state: S }): void;
export function navigate<S = any>(
to: Path,
options?: { state?: S; replace?: boolean }
): void;

export function useHashLocation(options?: {
ssrPath?: Path;
Expand Down
31 changes: 18 additions & 13 deletions packages/wouter/src/use-hash-location.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,21 +22,26 @@ const subscribeToHashUpdates = (callback) => {
// leading '#' is ignored, leading '/' is optional
const currentHashLocation = () => "/" + location.hash.replace(/^#?\/?/, "");

export const navigate = (to, { state = null } = {}) => {
// calling `replaceState` allows us to set the history
// state without creating an extra entry
export const navigate = (to, { state = null, replace = false } = {}) => {
const [hash, search] = to.replace(/^#?\/?/, "").split("?");

history.replaceState(
state,
"",
// keep the current pathname, but replace query string and hash
location.pathname +
(search ? `?${search}` : location.search) +
// update location hash, this will cause `hashchange` event to fire
// normalise the value before updating, so it's always preceeded with "#/"
(location.hash = `#/${hash}`)
);
const newRelativePath =
location.pathname + (search ? `?${search}` : location.search) + `#/${hash}`;
const oldURL = location.href;
const newURL = new URL(newRelativePath, location.origin).href;

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

const event =
typeof HashChangeEvent !== "undefined"
? new HashChangeEvent("hashchange", { oldURL, newURL })
: new Event("hashchange", { detail: { oldURL, newURL } });

dispatchEvent(event);
};

export const useHashLocation = ({ ssrPath = "/" } = {}) => [
Expand Down
68 changes: 67 additions & 1 deletion packages/wouter/test/use-hash-location.test.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { it, expect, beforeEach } from "vitest";
import { it, expect, beforeEach, vi } from "vitest";
import { renderHook, render } from "@testing-library/react";
import { renderToStaticMarkup } from "react-dom/server";

Expand Down Expand Up @@ -208,3 +208,69 @@ it("defines a custom way of rendering link hrefs", () => {

expect(getByTestId("link")).toHaveAttribute("href", "#/app");
});

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

// case: replace, expect no history stack changes
const historyStackCountBeforeReplace = history.length;
navigate("/app/users", { replace: true });
expect(location.hash).toBe("#/app/users");
expect(history.length).toBe(historyStackCountBeforeReplace);

// case: push, expect history stack increase by 1
const historyStackCountBeforePush = history.length;
navigate("/app/users/2");
expect(location.hash).toBe("#/app/users/2");
expect(history.length).toBe(historyStackCountBeforePush + 1);
});

it("dispatches hashchange event when options.replace is true", () => {
const { result } = renderHook(() => useHashLocation());
const [, navigate] = result.current;

const hashChangeFn = vi.fn();
addEventListener("hashchange", hashChangeFn);

navigate("/foo/bar", { replace: true });
expect(hashChangeFn).toBeCalled();

removeEventListener("hashchange", hashChangeFn);
});

it("detects history change when navigate with options.replace is called", async () => {
const nextTick = () => new Promise((resolve) => setTimeout(resolve, 0));

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

const newPath = "/foo/bar/baz";
navigate(newPath, { replace: true });
await nextTick();
expect(result.current[0]).toBe(newPath);
});

it("uses string URLs as hashchange event payload", () => {
const { result } = renderHook(() => useHashLocation());
const [, navigate] = result.current;

const relativeOldPath = "/foo";
const relativeNewPath = "/foo/bar/#hash";
const baseURL = "http://localhost:3000/#";

navigate(relativeOldPath);

let changeEvent = new HashChangeEvent("hashchange");
const hashChangeFn = (event: HashChangeEvent) => {
changeEvent = event;
};

addEventListener("hashchange", hashChangeFn);

navigate(relativeNewPath);
expect(changeEvent?.newURL).toBe(`${baseURL}${relativeNewPath}`);
expect(changeEvent?.oldURL).toBe(`${baseURL}${relativeOldPath}`);

removeEventListener("hashchange", hashChangeFn);
});
5 changes: 4 additions & 1 deletion packages/wouter/types/use-hash-location.d.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import { Path } from "./location-hook.js";

export function navigate<S = any>(to: Path, options?: { state: S }): void;
export function navigate<S = any>(
to: Path,
options?: { state?: S; replace?: boolean }
): void;

export function useHashLocation(options?: {
ssrPath?: Path;
Expand Down