Open History to see the last commit
1import { useEffect, useState, type ReactNode } from "react";
2
3export interface InspectorPane {
4 readonly key: string;
5 readonly render: () => ReactNode;
6 /** Opening one of these panes soon mounts the others too, so switching between them is instant. */
7 readonly prewarm?: boolean;
8 /** The pane is a native stack of its own, which draws its bar and insets its content itself. */
9 readonly nativeStack?: boolean;
10}
11
12/** What a route shows in the workspace's inspector: its panes and the one on screen. */
13export interface InspectorContent {
14 readonly panes: ReadonlyArray<InspectorPane>;
15 readonly active: string;
16 /** A failed pane renders again when one of these changes. */
17 readonly resetKeys?: ReadonlyArray<unknown>;
18}
19
20const PREWARM_DELAY_MS = 350;
21
22/**
23 * The panes to keep mounted: every pane opened since the inspector appeared, plus prewarmed ones.
24 * A mounted pane keeps its state and scroll position while another is on screen.
25 */
26export function useMountedInspectorPanes(content: InspectorContent | undefined) {
27 const [opened, setOpened] = useState<ReadonlySet<string>>(() => new Set());
28 const active = content?.active;
29 const prewarms = content?.panes.filter((pane) => pane.prewarm) ?? [];
30 const prewarmSignature = prewarms.some((pane) => pane.key === active)
31 ? prewarms.map((pane) => pane.key).join("\n")
32 : "";
33
34 if (active !== undefined && !opened.has(active)) {
35 setOpened(new Set([...opened, active]));
36 }
37
38 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- prewarms the other panes on a timer after one opens
39 useEffect(() => {
40 if (prewarmSignature === "") return;
41 const timeout = setTimeout(() => {
42 setOpened((current) => {
43 const keys = prewarmSignature.split("\n");
44 return keys.every((key) => current.has(key)) ? current : new Set([...current, ...keys]);
45 });
46 }, PREWARM_DELAY_MS);
47 return () => clearTimeout(timeout);
48 }, [prewarmSignature]);
49
50 return content?.panes.filter((pane) => opened.has(pane.key)) ?? [];
51}