Open History to see the last commit
1/**
2 * Thread-scoped right-panel surface state.
3 *
4 * This is intentionally a shallow workspace model: it owns an ordered set of
5 * surface descriptors and the active surface, while each feature continues to
6 * own its durable resource state. Browser surfaces point at preview tab ids,
7 * terminal surfaces point at terminal session ids, file surfaces point at
8 * workspace paths, and diff/plan/files remain singleton surfaces.
9 */
10import { scopedThreadKey } from "@t3tools/client-runtime";
11import type { ScopedThreadRef } from "@t3tools/contracts";
12import { create } from "zustand";
13import { createJSONStorage, persist } from "zustand/middleware";
14
15import { resolveStorage } from "./lib/storage";
16
17export const RIGHT_PANEL_KINDS = ["plan", "diff", "files", "file", "preview", "terminal"] as const;
18export type RightPanelKind = (typeof RIGHT_PANEL_KINDS)[number];
19
20export type RightPanelSurface =
21 | { id: `browser:${string}`; kind: "preview"; resourceId: string }
22 | { id: "browser:new"; kind: "preview"; resourceId: null }
23 | {
24 id: `terminal:${string}`;
25 kind: "terminal";
26 resourceId: string;
27 terminalIds: string[];
28 activeTerminalId: string;
29 splitDirection?: "horizontal" | "vertical";
30 }
31 | { id: "diff"; kind: "diff" }
32 | { id: "files"; kind: "files" }
33 | { id: `file:${string}`; kind: "file"; relativePath: string }
34 | { id: "plan"; kind: "plan" };
35
36const RIGHT_PANEL_STORAGE_KEY = "t3code:right-panel-state:v2";
37const RIGHT_PANEL_STORAGE_VERSION = 6;
38
39export interface ThreadRightPanelState {
40 isOpen: boolean;
41 activeSurfaceId: string | null;
42 surfaces: RightPanelSurface[];
43}
44
45interface RightPanelStoreState {
46 byThreadKey: Record<string, ThreadRightPanelState>;
47 open: (ref: ScopedThreadRef, kind: Exclude<RightPanelKind, "file" | "terminal">) => void;
48 openBrowser: (ref: ScopedThreadRef, tabId: string | null) => void;
49 openFile: (ref: ScopedThreadRef, relativePath: string) => void;
50 openTerminal: (ref: ScopedThreadRef, terminalId: string) => void;
51 splitTerminal: (
52 ref: ScopedThreadRef,
53 surfaceId: string,
54 terminalId: string,
55 direction?: "horizontal" | "vertical",
56 ) => void;
57 activateTerminal: (ref: ScopedThreadRef, surfaceId: string, terminalId: string) => void;
58 closeTerminal: (ref: ScopedThreadRef, surfaceId: string, terminalId: string) => void;
59 activateSurface: (ref: ScopedThreadRef, surfaceId: string) => void;
60 closeSurface: (ref: ScopedThreadRef, surfaceId: string) => void;
61 reconcileBrowserSurfaces: (ref: ScopedThreadRef, tabIds: readonly string[]) => void;
62 reconcileFileSurfaces: (ref: ScopedThreadRef, workspaceAvailable: boolean) => void;
63 show: (ref: ScopedThreadRef) => void;
64 close: (ref: ScopedThreadRef) => void;
65 toggleVisibility: (ref: ScopedThreadRef) => void;
66 toggle: (ref: ScopedThreadRef, kind: Exclude<RightPanelKind, "file" | "terminal">) => void;
67 removeThread: (ref: ScopedThreadRef) => void;
68}
69
70const EMPTY_THREAD_STATE: ThreadRightPanelState = {
71 isOpen: false,
72 activeSurfaceId: null,
73 surfaces: [],
74};
75
76const singletonSurface = (
77 kind: Exclude<RightPanelKind, "file" | "preview" | "terminal">,
78): RightPanelSurface => {
79 switch (kind) {
80 case "diff":
81 return { id: "diff", kind };
82 case "files":
83 return { id: "files", kind };
84 case "plan":
85 return { id: "plan", kind };
86 }
87};
88
89const browserSurface = (tabId: string | null): RightPanelSurface =>
90 tabId
91 ? { id: `browser:${tabId}`, kind: "preview", resourceId: tabId }
92 : { id: "browser:new", kind: "preview", resourceId: null };
93
94const fileSurface = (relativePath: string): RightPanelSurface => ({
95 id: `file:${relativePath}`,
96 kind: "file",
97 relativePath,
98});
99
100const terminalSurface = (terminalId: string): RightPanelSurface => ({
101 id: `terminal:${terminalId}`,
102 kind: "terminal",
103 resourceId: terminalId,
104 terminalIds: [terminalId],
105 activeTerminalId: terminalId,
106});
107
108const upsertSurface = (
109 current: ThreadRightPanelState,
110 surface: RightPanelSurface,
111 activate = true,
112): ThreadRightPanelState => ({
113 isOpen: true,
114 surfaces: current.surfaces.some((entry) => entry.id === surface.id)
115 ? current.surfaces
116 : [...current.surfaces, surface],
117 activeSurfaceId: activate ? surface.id : current.activeSurfaceId,
118});
119
120const updateThread = (
121 byThreadKey: Record<string, ThreadRightPanelState>,
122 threadKey: string,
123 updater: (current: ThreadRightPanelState) => ThreadRightPanelState,
124): Record<string, ThreadRightPanelState> => {
125 const current = byThreadKey[threadKey] ?? EMPTY_THREAD_STATE;
126 const next = updater(current);
127 if (!next.isOpen && next.activeSurfaceId === null && next.surfaces.length === 0) {
128 if (!(threadKey in byThreadKey)) return byThreadKey;
129 const { [threadKey]: _removed, ...rest } = byThreadKey;
130 return rest;
131 }
132 if (next === current) return byThreadKey;
133 return { ...byThreadKey, [threadKey]: next };
134};
135
136export function migratePersistedRightPanelState(persistedState: unknown): {
137 byThreadKey: Record<string, ThreadRightPanelState>;
138} {
139 if (!persistedState || typeof persistedState !== "object") {
140 return { byThreadKey: {} };
141 }
142 const byThreadKey =
143 "byThreadKey" in persistedState &&
144 persistedState.byThreadKey &&
145 typeof persistedState.byThreadKey === "object"
146 ? Object.fromEntries(
147 Object.entries(persistedState.byThreadKey as Record<string, ThreadRightPanelState>).map(
148 ([threadKey, threadState]) => {
149 const validThreadState =
150 threadState && typeof threadState === "object" ? threadState : null;
151 const surfaces = Array.isArray(validThreadState?.surfaces)
152 ? validThreadState.surfaces.flatMap<RightPanelSurface>((surface) => {
153 if (surface.kind !== "terminal") return [surface];
154 if (
155 !("resourceId" in surface) ||
156 typeof surface.resourceId !== "string" ||
157 surface.id !== `terminal:${surface.resourceId}`
158 ) {
159 return [];
160 }
161 const terminalIds =
162 "terminalIds" in surface && Array.isArray(surface.terminalIds)
163 ? [
164 ...new Set(
165 surface.terminalIds.filter(
166 (terminalId): terminalId is string =>
167 typeof terminalId === "string",
168 ),
169 ),
170 ]
171 : [surface.resourceId];
172 const activeTerminalId =
173 "activeTerminalId" in surface &&
174 typeof surface.activeTerminalId === "string" &&
175 terminalIds.includes(surface.activeTerminalId)
176 ? surface.activeTerminalId
177 : (terminalIds[0] ?? surface.resourceId);
178 return [
179 {
180 ...surface,
181 terminalIds: terminalIds.length > 0 ? terminalIds : [surface.resourceId],
182 activeTerminalId,
183 },
184 ];
185 })
186 : [];
187 const activeSurfaceId = surfaces.some(
188 (surface) => surface.id === validThreadState?.activeSurfaceId,
189 )
190 ? (validThreadState?.activeSurfaceId ?? null)
191 : null;
192 const isOpen =
193 typeof validThreadState?.isOpen === "boolean"
194 ? validThreadState.isOpen
195 : activeSurfaceId !== null;
196 return [threadKey, { isOpen, surfaces, activeSurfaceId }];
197 },
198 ),
199 )
200 : {};
201 return { byThreadKey };
202}
203
204export const useRightPanelStore = create<RightPanelStoreState>()(
205 persist(
206 (set) => ({
207 byThreadKey: {},
208 open: (ref, kind) =>
209 set((state) => ({
210 byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) => {
211 if (kind === "preview") {
212 const existing = current.surfaces.find((surface) => surface.kind === "preview");
213 return upsertSurface(current, existing ?? browserSurface(null));
214 }
215 return upsertSurface(current, singletonSurface(kind));
216 }),
217 })),
218 openBrowser: (ref, tabId) =>
219 set((state) => ({
220 byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) => {
221 const surface = browserSurface(tabId);
222 const withoutPlaceholder = tabId
223 ? current.surfaces.filter((entry) => entry.id !== "browser:new")
224 : current.surfaces;
225 return upsertSurface({ ...current, surfaces: withoutPlaceholder }, surface);
226 }),
227 })),
228 openFile: (ref, relativePath) =>
229 set((state) => ({
230 byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) => {
231 const withoutStandaloneExplorer = current.surfaces.filter(
232 (surface) => surface.kind !== "files",
233 );
234 return upsertSurface(
235 { ...current, surfaces: withoutStandaloneExplorer },
236 fileSurface(relativePath),
237 );
238 }),
239 })),
240 openTerminal: (ref, terminalId) =>
241 set((state) => ({
242 byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) =>
243 upsertSurface(current, terminalSurface(terminalId)),
244 ),
245 })),
246 splitTerminal: (ref, surfaceId, terminalId, direction = "horizontal") =>
247 set((state) => ({
248 byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) => ({
249 ...current,
250 isOpen: true,
251 activeSurfaceId: surfaceId,
252 surfaces: current.surfaces.map((surface) => {
253 if (surface.id !== surfaceId || surface.kind !== "terminal") return surface;
254 const { splitDirection: _splitDirection, ...baseSurface } = surface;
255 return {
256 ...baseSurface,
257 terminalIds: surface.terminalIds.includes(terminalId)
258 ? surface.terminalIds
259 : [...surface.terminalIds, terminalId],
260 activeTerminalId: terminalId,
261 ...(direction === "vertical" ? { splitDirection: "vertical" as const } : {}),
262 };
263 }),
264 })),
265 })),
266 activateTerminal: (ref, surfaceId, terminalId) =>
267 set((state) => ({
268 byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) => ({
269 ...current,
270 activeSurfaceId: surfaceId,
271 surfaces: current.surfaces.map((surface) =>
272 surface.id === surfaceId &&
273 surface.kind === "terminal" &&
274 surface.terminalIds.includes(terminalId)
275 ? { ...surface, activeTerminalId: terminalId }
276 : surface,
277 ),
278 })),
279 })),
280 closeTerminal: (ref, surfaceId, terminalId) =>
281 set((state) => ({
282 byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) => {
283 const surface = current.surfaces.find(
284 (entry) => entry.id === surfaceId && entry.kind === "terminal",
285 );
286 if (!surface || surface.kind !== "terminal") return current;
287 const terminalIds = surface.terminalIds.filter((id) => id !== terminalId);
288 if (terminalIds.length === 0) {
289 const index = current.surfaces.findIndex((entry) => entry.id === surfaceId);
290 const surfaces = current.surfaces.filter((entry) => entry.id !== surfaceId);
291 const fallback = surfaces[Math.min(index, surfaces.length - 1)] ?? null;
292 return {
293 ...current,
294 surfaces,
295 activeSurfaceId:
296 current.activeSurfaceId === surfaceId
297 ? (fallback?.id ?? null)
298 : current.activeSurfaceId,
299 };
300 }
301 return {
302 ...current,
303 surfaces: current.surfaces.map((entry) =>
304 entry.id === surfaceId && entry.kind === "terminal"
305 ? {
306 ...entry,
307 terminalIds,
308 activeTerminalId:
309 entry.activeTerminalId === terminalId
310 ? (terminalIds.at(-1) ?? terminalIds[0]!)
311 : entry.activeTerminalId,
312 }
313 : entry,
314 ),
315 };
316 }),
317 })),
318 activateSurface: (ref, surfaceId) =>
319 set((state) => ({
320 byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) =>
321 current.surfaces.some((surface) => surface.id === surfaceId)
322 ? { ...current, isOpen: true, activeSurfaceId: surfaceId }
323 : current,
324 ),
325 })),
326 closeSurface: (ref, surfaceId) =>
327 set((state) => ({
328 byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) => {
329 const index = current.surfaces.findIndex((surface) => surface.id === surfaceId);
330 if (index < 0) return current;
331 const surfaces = current.surfaces.filter((surface) => surface.id !== surfaceId);
332 if (current.activeSurfaceId !== surfaceId) return { ...current, surfaces };
333 const fallback = surfaces[Math.min(index, surfaces.length - 1)] ?? null;
334 return { ...current, surfaces, activeSurfaceId: fallback?.id ?? null };
335 }),
336 })),
337 reconcileBrowserSurfaces: (ref, tabIds) =>
338 set((state) => ({
339 byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) => {
340 const validIds = new Set(tabIds.map((tabId) => `browser:${tabId}`));
341 const nonBrowser = current.surfaces.filter((surface) => surface.kind !== "preview");
342 const existingBrowser = current.surfaces.filter(
343 (surface): surface is Extract<RightPanelSurface, { kind: "preview" }> =>
344 surface.kind === "preview" &&
345 surface.id !== "browser:new" &&
346 validIds.has(surface.id),
347 );
348 const knownIds = new Set(existingBrowser.map((surface) => surface.id));
349 const added = tabIds
350 .filter((tabId) => !knownIds.has(`browser:${tabId}`))
351 .map((tabId) => browserSurface(tabId));
352 const surfaces = [...nonBrowser, ...existingBrowser, ...added];
353 const activeStillExists = surfaces.some(
354 (surface) => surface.id === current.activeSurfaceId,
355 );
356 const fallbackBrowser = surfaces.find((surface) => surface.kind === "preview");
357 return {
358 ...current,
359 surfaces,
360 activeSurfaceId: activeStillExists
361 ? current.activeSurfaceId
362 : (fallbackBrowser?.id ?? surfaces[0]?.id ?? null),
363 };
364 }),
365 })),
366 reconcileFileSurfaces: (ref, workspaceAvailable) =>
367 set((state) => ({
368 byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) => {
369 if (workspaceAvailable) return current;
370 const surfaces = current.surfaces.filter(
371 (surface) => surface.kind !== "files" && surface.kind !== "file",
372 );
373 if (surfaces.length === current.surfaces.length) return current;
374 const activeStillExists = surfaces.some(
375 (surface) => surface.id === current.activeSurfaceId,
376 );
377 return {
378 ...current,
379 isOpen: surfaces.length > 0 ? current.isOpen : false,
380 surfaces,
381 activeSurfaceId: activeStillExists
382 ? current.activeSurfaceId
383 : (surfaces.at(-1)?.id ?? null),
384 };
385 }),
386 })),
387 show: (ref) =>
388 set((state) => ({
389 byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) =>
390 current.isOpen ? current : { ...current, isOpen: true },
391 ),
392 })),
393 close: (ref) =>
394 set((state) => ({
395 byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) =>
396 current.isOpen ? { ...current, isOpen: false } : current,
397 ),
398 })),
399 toggleVisibility: (ref) =>
400 set((state) => ({
401 byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) => ({
402 ...current,
403 isOpen: !current.isOpen,
404 })),
405 })),
406 toggle: (ref, kind) =>
407 set((state) => ({
408 byThreadKey: updateThread(state.byThreadKey, scopedThreadKey(ref), (current) => {
409 const active = current.surfaces.find(
410 (surface) => surface.id === current.activeSurfaceId,
411 );
412 if (current.isOpen && active?.kind === kind) {
413 return { ...current, isOpen: false };
414 }
415 if (kind === "preview") {
416 const existing = current.surfaces.find((surface) => surface.kind === "preview");
417 return upsertSurface(current, existing ?? browserSurface(null));
418 }
419 return upsertSurface(current, singletonSurface(kind));
420 }),
421 })),
422 removeThread: (ref) =>
423 set((state) => {
424 const threadKey = scopedThreadKey(ref);
425 if (!(threadKey in state.byThreadKey)) return state;
426 const { [threadKey]: _removed, ...rest } = state.byThreadKey;
427 return { byThreadKey: rest };
428 }),
429 }),
430 {
431 name: RIGHT_PANEL_STORAGE_KEY,
432 version: RIGHT_PANEL_STORAGE_VERSION,
433 storage: createJSONStorage(() =>
434 resolveStorage(typeof window !== "undefined" ? window.localStorage : undefined),
435 ),
436 partialize: (state) => ({ byThreadKey: state.byThreadKey }),
437 migrate: migratePersistedRightPanelState,
438 },
439 ),
440);
441
442export function selectThreadRightPanelState(
443 byThreadKey: Record<string, ThreadRightPanelState>,
444 ref: ScopedThreadRef | null | undefined,
445): ThreadRightPanelState {
446 if (!ref) return EMPTY_THREAD_STATE;
447 return byThreadKey[scopedThreadKey(ref)] ?? EMPTY_THREAD_STATE;
448}
449
450export function selectActiveRightPanel(
451 byThreadKey: Record<string, ThreadRightPanelState>,
452 ref: ScopedThreadRef | null | undefined,
453): RightPanelKind | null {
454 const state = selectThreadRightPanelState(byThreadKey, ref);
455 if (!state.isOpen) return null;
456 return state.surfaces.find((surface) => surface.id === state.activeSurfaceId)?.kind ?? null;
457}
458
459export function selectActiveRightPanelSurface(
460 byThreadKey: Record<string, ThreadRightPanelState>,
461 ref: ScopedThreadRef | null | undefined,
462): RightPanelSurface | null {
463 const state = selectThreadRightPanelState(byThreadKey, ref);
464 if (!state.isOpen) return null;
465 return state.surfaces.find((surface) => surface.id === state.activeSurfaceId) ?? null;
466}
467
468export function selectActiveRightPanelKindWithUrl(
469 byThreadKey: Record<string, ThreadRightPanelState>,
470 ref: ScopedThreadRef | null | undefined,
471 diffSearchActive: boolean,
472): RightPanelKind | null {
473 if (!selectThreadRightPanelState(byThreadKey, ref).isOpen) return null;
474 if (diffSearchActive) return "diff";
475 return selectActiveRightPanel(byThreadKey, ref);
476}