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

history-tracker.ts

81 lines2.6 KB

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