示例工程 20-routing-and-panels

20-routing-and-panels/app/src/lib/router.ts

typescript · 2.7 KB

import { useCallback, useEffect, useRef, useState } from "react";

export type Route =
  | { name: "docs"; id: string }
  | { name: "settings" }
  | { name: "notfound"; path: string };

export function parseHash(hash: string): Route {
  const clean = hash.replace(/^#\/?/, "");
  if (clean === "settings") return { name: "settings" };
  if (clean.startsWith("docs/")) {
    const id = clean.slice("docs/".length);
    if (id.length > 0) return { name: "docs", id };
  }
  return { name: "notfound", path: clean };
}

export function hashOf(route: Route): string {
  if (route.name === "docs") return `#/docs/${route.id}`;
  if (route.name === "settings") return "#/settings";
  return `#/${route.path}`;
}

export function useRouter() {
  const initialHash =
    window.location.hash.length > 0 ? window.location.hash : "#/docs/intro";
  const [route, setRoute] = useState<Route>(() => parseHash(initialHash));
  const [revision, setRevision] = useState(0);
  const stack = useRef<string[]>([initialHash]);
  const index = useRef(0);
  const suppress = useRef(false);

  useEffect(() => {
    if (!window.location.hash) {
      window.location.hash = "#/docs/intro";
    }
    const onHash = (): void => {
      const nextHash = window.location.hash || "#/docs/intro";
      if (suppress.current) {
        suppress.current = false;
        setRoute(parseHash(nextHash));
        setRevision((value) => value + 1);
        return;
      }
      if (nextHash === stack.current[index.current]) return;
      stack.current = stack.current.slice(0, index.current + 1);
      stack.current.push(nextHash);
      index.current = stack.current.length - 1;
      setRoute(parseHash(nextHash));
      setRevision((value) => value + 1);
    };
    window.addEventListener("hashchange", onHash);
    return () => window.removeEventListener("hashchange", onHash);
  }, []);

  const navigate = useCallback((path: string) => {
    const hash = path.startsWith("#") ? path : `#${path}`;
    if (hash === window.location.hash) return;
    window.location.hash = hash;
  }, []);

  const go = useCallback((next: number) => {
    const target = stack.current[next];
    if (target === undefined) return;
    index.current = next;
    suppress.current = true;
    window.location.hash = target;
    setRoute(parseHash(target));
    setRevision((value) => value + 1);
  }, []);

  const back = useCallback(() => {
    if (index.current > 0) go(index.current - 1);
  }, [go]);

  const forward = useCallback(() => {
    if (index.current < stack.current.length - 1) go(index.current + 1);
  }, [go]);

  return {
    route,
    revision,
    navigate,
    back,
    forward,
    canBack: revision >= 0 && index.current > 0,
    canForward: revision >= 0 && index.current < stack.current.length - 1,
  };
}