The best way to control Claude Code, Codex and more from any computer or phone

main
tsx 71 lines 1.91 KB
Raw
1 /**
2 * A ~60-line history-API router — deliberately dependency-free so the
3 * example stays a *plain* React SPA. Deep links work because the site is
4 * deployed with `assets: { notFoundHandling: "single-page-application" }`.
5 */
6 import {
7 createContext,
8 useContext,
9 useEffect,
10 useState,
11 type MouseEvent,
12 type ReactNode,
13 } from "react";
14
15 interface RouterState {
16 readonly path: string;
17 readonly navigate: (to: string) => void;
18 }
19
20 const RouterContext = createContext<RouterState>({
21 path: "/",
22 navigate: () => {},
23 });
24
25 export const Router = ({ children }: { children: ReactNode }) => {
26 const [path, setPath] = useState(location.pathname);
27 useEffect(() => {
28 const onPop = () => setPath(location.pathname);
29 window.addEventListener("popstate", onPop);
30 return () => window.removeEventListener("popstate", onPop);
31 }, []);
32 const navigate = (to: string) => {
33 history.pushState(null, "", to);
34 setPath(new URL(to, location.origin).pathname);
35 window.scrollTo(0, 0);
36 };
37 return <RouterContext.Provider value={{ path, navigate }}>{children}</RouterContext.Provider>;
38 };
39
40 export const useRouter = () => useContext(RouterContext);
41
42 export const Link = ({
43 to,
44 className,
45 children,
46 title,
47 }: {
48 to: string;
49 className?: string;
50 children: ReactNode;
51 title?: string;
52 }) => {
53 const { navigate } = useRouter();
54 const onClick = (event: MouseEvent) => {
55 if (event.metaKey || event.ctrlKey || event.shiftKey) return;
56 event.preventDefault();
57 navigate(to);
58 };
59 return (
60 <a href={to} onClick={onClick} className={className} title={title}>
61 {children}
62 </a>
63 );
64 };
65
66 /** Splits a pathname into decoded segments. */
67 export const segments = (path: string): string[] =>
68 path.split("/").filter(Boolean).map(decodeURIComponent);
69
70 /** Builds a pathname from raw segments, encoding each. */
71 export const href = (...parts: string[]): string => "/" + parts.map(encodeURIComponent).join("/");