Skip to content
Source
Sign inSign up
fuko/trytanstackdb.com
Open History to see the last commit

history-tracker.ts

99 lines3.5 KB

1import { useRouter } from "@tanstack/react-router";
2import type { RouterHistory } from "@tanstack/react-router";
3import { useSyncExternalStore } from "react";
4​
5import { isSheetOpen } from "./app-sheet-history";
6​
7/**
8 * Remembers the history entries we've seen, for as long as the router lives.
9 * The History API can't tell us whether "forward" is possible or what the
10 * previous entry was, so we record every navigation ourselves. Living outside
11 * React means remounting the browser frame (e.g. on a responsive layout
12 * change) doesn't lose track.
13 */
14export interface HistorySnapshot {
15 /** Position of the current entry (`__TSR_index`). */
16 index: number;
17 /** Furthest entry reachable with "forward". */
18 lastIndex: number;
19 /** Pathnames by index, for the entries we've seen. */
20 paths: ReadonlyArray<string | undefined>;
21 /** Whether each entry has the app sheet open (small screens; see `app-sheet-history.ts`). */
22 sheetOpen: ReadonlyArray<boolean | undefined>;
24​
25interface Tracker {
26 getSnapshot: () => HistorySnapshot;
27 subscribe: (listener: () => void) => () => void;
29​
30const trackers = new WeakMap<RouterHistory, Tracker>();
31​
32function entryIndex(state: unknown): number {
33 return (state as { __TSR_index?: number } | null)?.__TSR_index ?? 0;
35​
36function createTracker(history: RouterHistory): Tracker {
37 const index = entryIndex(history.location.state);
38 const paths: Array<string | undefined> = [];
39 const sheetOpen: Array<boolean | undefined> = [];
40 paths[index] = history.location.pathname;
41 sheetOpen[index] = isSheetOpen(history.location.state, history.location.pathname);
42 let snapshot: HistorySnapshot = { index, lastIndex: index, paths, sheetOpen };
43 const listeners = new Set<() => void>();
44​
45 history.subscribe(({ location, action }) => {
46 const index = entryIndex(location.state);
47 const paths = [...snapshot.paths];
48 const sheetOpen = [...snapshot.sheetOpen];
49 // A push discards everything that was ahead of the new entry.
50 if (action.type === "PUSH") paths.length = sheetOpen.length = index;
51 paths[index] = location.pathname;
52 sheetOpen[index] = isSheetOpen(location.state, location.pathname);
53 snapshot = {
54 index,
55 lastIndex: action.type === "PUSH" ? index : Math.max(snapshot.lastIndex, index),
56 paths,
57 sheetOpen,
58 };
59 for (const listener of listeners) listener();
60 });
61​
62 return {
63 getSnapshot: () => snapshot,
64 subscribe: (listener) => {
65 listeners.add(listener);
66 return () => listeners.delete(listener);
67 },
68 };
70​
71function trackerFor(history: RouterHistory): Tracker {
72 let tracker = trackers.get(history);
73 if (!tracker) {
74 tracker = createTracker(history);
75 trackers.set(history, tracker);
76 }
77 return tracker;
79​
80export function useHistorySnapshot(): HistorySnapshot {
81 const { history } = useRouter();
82 const tracker = trackerFor(history);
83 return useSyncExternalStore(tracker.subscribe, tracker.getSnapshot, tracker.getSnapshot);
85​
86/** The entry "back" would go to, if we've seen it. */
87export function usePreviousEntry(): { pathname: string; sheetOpen: boolean } | undefined {
88 const { index, paths, sheetOpen } = useHistorySnapshot();
89 const pathname = paths[index - 1];
90 return pathname === undefined
91 ? undefined
92 : { pathname, sheetOpen: sheetOpen[index - 1] ?? false };
94​
95/** Whether the current entry has the app sheet open. */
96export function useCurrentEntrySheetOpen(): boolean {
97 const { index, sheetOpen } = useHistorySnapshot();
98 return sheetOpen[index] ?? false;