Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

rightPanelStore.ts

706 lines27.5 KB

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/environment";
11import type { ScopedThreadRef } from "@t3tools/contracts";
12import { create } from "zustand";
13import { createJSONStorage, persist } from "zustand/middleware";
14​
15import { resolveStorage } from "./lib/storage";
16import type { ThreadPanelPresentation } from "./rightPanelLayout";
17​
18export const RIGHT_PANEL_KINDS = ["plan", "diff", "files", "file", "preview", "terminal"] as const;
19export type RightPanelKind = (typeof RIGHT_PANEL_KINDS)[number];
20​
21export type RightPanelSurface =
22 | { id: `browser:${string}`; kind: "preview"; resourceId: string }
23 | { id: "browser:new"; kind: "preview"; resourceId: null }
24 | {
25 id: `terminal:${string}`;
26 kind: "terminal";
27 resourceId: string;
28 terminalIds: string[];
29 activeTerminalId: string;
30 splitDirection?: "horizontal" | "vertical";
31 }
32 | { id: "diff"; kind: "diff" }
33 | { id: "files"; kind: "files" }
34 | {
35 id: `file:${string}`;
36 kind: "file";
37 relativePath: string;
38 revealLine: number | null;
39 revealRequestId: number;
40 }
41 | { id: "plan"; kind: "plan" };
42​
43const RIGHT_PANEL_STORAGE_KEY = "t3code:right-panel-state:v2";
44const RIGHT_PANEL_STORAGE_VERSION = 8;
45​
46export interface ThreadRightPanelState {
47 isOpen: boolean;
48 activeSurfaceId: string | null;
49 surfaces: RightPanelSurface[];
51​
52export interface ThreadPanelVisibility {
53 inlineOpen: boolean;
54 popoverOpen: boolean;
56​
57interface RightPanelStoreState {
58 byThreadKey: Record<string, ThreadRightPanelState>;
59 threadPanelVisibilityByThreadKey: Record<string, ThreadPanelVisibility>;
60 open: (ref: ScopedThreadRef, kind: Exclude<RightPanelKind, "file" | "terminal">) => void;
61 openBrowser: (ref: ScopedThreadRef, tabId: string | null) => void;
62 openFile: (ref: ScopedThreadRef, relativePath: string, line?: number) => void;
63 openTerminal: (ref: ScopedThreadRef, terminalId: string) => void;
64 splitTerminal: (
65 ref: ScopedThreadRef,
66 surfaceId: string,
67 terminalId: string,
68 direction?: "horizontal" | "vertical",
69 ) => void;
70 activateTerminal: (ref: ScopedThreadRef, surfaceId: string, terminalId: string) => void;
71 closeTerminal: (ref: ScopedThreadRef, surfaceId: string, terminalId: string) => void;
72 activateSurface: (ref: ScopedThreadRef, surfaceId: string) => void;
73 closeSurface: (ref: ScopedThreadRef, surfaceId: string) => void;
74 closeOtherSurfaces: (ref: ScopedThreadRef, surfaceId: string) => void;
75 closeSurfacesToRight: (ref: ScopedThreadRef, surfaceId: string) => void;
76 closeAllSurfaces: (ref: ScopedThreadRef) => void;
77 reconcileBrowserSurfaces: (ref: ScopedThreadRef, tabIds: readonly string[]) => void;
78 reconcileFileSurfaces: (ref: ScopedThreadRef, workspaceAvailable: boolean) => void;
79 show: (ref: ScopedThreadRef) => void;
80 close: (ref: ScopedThreadRef) => void;
81 toggleVisibility: (ref: ScopedThreadRef) => void;
82 toggle: (ref: ScopedThreadRef, kind: Exclude<RightPanelKind, "file" | "terminal">) => void;
83 setThreadPanelOpen: (
84 ref: ScopedThreadRef,
85 presentation: ThreadPanelPresentation,
86 open: boolean,
87 ) => void;
88 toggleThreadPanel: (ref: ScopedThreadRef, presentation: ThreadPanelPresentation) => void;
89 removeThread: (ref: ScopedThreadRef) => void;
91​
92const EMPTY_THREAD_STATE: ThreadRightPanelState = {
93 isOpen: false,
94 activeSurfaceId: null,
95 surfaces: [],
96};
97​
98const DEFAULT_THREAD_PANEL_VISIBILITY: ThreadPanelVisibility = {
99 inlineOpen: true,
100 popoverOpen: false,
101};
102​
103const singletonSurface = (
104 kind: Exclude<RightPanelKind, "file" | "preview" | "terminal">,
105): RightPanelSurface => {
106 switch (kind) {
107 case "diff":
108 return { id: "diff", kind };
109 case "files":
110 return { id: "files", kind };
111 case "plan":
112 return { id: "plan", kind };
113 }
114};
115​
116const browserSurface = (tabId: string | null): RightPanelSurface =>
117 tabId
118 ? { id: `browser:${tabId}`, kind: "preview", resourceId: tabId }
119 : { id: "browser:new", kind: "preview", resourceId: null };
120​
121const fileSurface = (
122 relativePath: string,
123 revealLine: number | null,
124 revealRequestId: number,
125): RightPanelSurface => ({
126 id: `file:${relativePath}`,
127 kind: "file",
128 relativePath,
129 revealLine,
130 revealRequestId,
131});
132​
133const terminalSurface = (terminalId: string): RightPanelSurface => ({
134 id: `terminal:${terminalId}`,
135 kind: "terminal",
136 resourceId: terminalId,
137 terminalIds: [terminalId],
138 activeTerminalId: terminalId,
139});
140​
141const upsertSurface = (
142 current: ThreadRightPanelState,
143 surface: RightPanelSurface,
144 activate = true,
145): ThreadRightPanelState => ({
146 isOpen: true,
147 surfaces: current.surfaces.some((entry) => entry.id === surface.id)
148 ? current.surfaces
149 : [...current.surfaces, surface],
150 activeSurfaceId: activate ? surface.id : current.activeSurfaceId,
151});
152​
153const updateThreadStateMap = (
154 byThreadKey: Record<string, ThreadRightPanelState>,
155 threadKey: string,
156 updater: (current: ThreadRightPanelState) => ThreadRightPanelState,
157): Record<string, ThreadRightPanelState> => {
158 const current = byThreadKey[threadKey] ?? EMPTY_THREAD_STATE;
159 const next = updater(current);
160 if (!next.isOpen && next.activeSurfaceId === null && next.surfaces.length === 0) {
161 if (!(threadKey in byThreadKey)) return byThreadKey;
162 const { [threadKey]: _removed, ...rest } = byThreadKey;
163 return rest;
164 }
165 if (next === current) return byThreadKey;
166 return { ...byThreadKey, [threadKey]: next };
167};
168​
169const updateThreadPanelVisibilityMap = (
170 byThreadKey: Record<string, ThreadPanelVisibility>,
171 threadKey: string,
172 updater: (current: ThreadPanelVisibility) => ThreadPanelVisibility,
173): Record<string, ThreadPanelVisibility> => {
174 const current = byThreadKey[threadKey] ?? DEFAULT_THREAD_PANEL_VISIBILITY;
175 const next = updater(current);
176 if (next.inlineOpen && !next.popoverOpen) {
177 if (!(threadKey in byThreadKey)) return byThreadKey;
178 const { [threadKey]: _removed, ...rest } = byThreadKey;
179 return rest;
180 }
181 if (next === current) return byThreadKey;
182 return { ...byThreadKey, [threadKey]: next };
183};
184​
185type RightPanelStoreData = Pick<
186 RightPanelStoreState,
187 "byThreadKey" | "threadPanelVisibilityByThreadKey"
188>;
189​
190/**
191 * Applies a real right-panel mutation and its thread-panel transition atomically.
192 * This is the only path real panel actions use, so visibility never has to be
193 * reconciled after the fact in React.
194 */
195const updateThread = (
196 state: RightPanelStoreData,
197 ref: ScopedThreadRef,
198 updater: (current: ThreadRightPanelState) => ThreadRightPanelState,
199): RightPanelStoreData => {
200 const threadKey = scopedThreadKey(ref);
201 const current = state.byThreadKey[threadKey] ?? EMPTY_THREAD_STATE;
202 const byThreadKey = updateThreadStateMap(state.byThreadKey, threadKey, updater);
203 const next = byThreadKey[threadKey] ?? EMPTY_THREAD_STATE;
204 let threadPanelVisibilityByThreadKey = state.threadPanelVisibilityByThreadKey;
205​
206 if (!current.isOpen && next.isOpen) {
207 threadPanelVisibilityByThreadKey = updateThreadPanelVisibilityMap(
208 threadPanelVisibilityByThreadKey,
209 threadKey,
210 (visibility) => (visibility.popoverOpen ? { ...visibility, popoverOpen: false } : visibility),
211 );
212 } else if (current.isOpen && !next.isOpen) {
213 threadPanelVisibilityByThreadKey = updateThreadPanelVisibilityMap(
214 threadPanelVisibilityByThreadKey,
215 threadKey,
216 (visibility) =>
217 visibility.popoverOpen && !visibility.inlineOpen
218 ? { ...visibility, inlineOpen: true }
219 : visibility,
220 );
221 }
222​
223 return { byThreadKey, threadPanelVisibilityByThreadKey };
224};
225​
226function normalizeRevealLine(line: number | undefined): number | null {
227 if (line === undefined || !Number.isFinite(line)) return null;
228 return Math.max(1, Math.trunc(line));
230​
231export function migratePersistedRightPanelState(persistedState: unknown): {
232 byThreadKey: Record<string, ThreadRightPanelState>;
233 threadPanelVisibilityByThreadKey: Record<string, ThreadPanelVisibility>;
234} {
235 if (!persistedState || typeof persistedState !== "object") {
236 return { byThreadKey: {}, threadPanelVisibilityByThreadKey: {} };
237 }
238 const byThreadKey =
239 "byThreadKey" in persistedState &&
240 persistedState.byThreadKey &&
241 typeof persistedState.byThreadKey === "object"
242 ? Object.fromEntries(
243 Object.entries(persistedState.byThreadKey as Record<string, ThreadRightPanelState>).map(
244 ([threadKey, threadState]) => {
245 const validThreadState =
246 threadState && typeof threadState === "object" ? threadState : null;
247 const surfaces = Array.isArray(validThreadState?.surfaces)
248 ? validThreadState.surfaces.flatMap<RightPanelSurface>((surface) => {
249 if (surface.kind === "file") {
250 const revealLine =
251 typeof surface.revealLine === "number" &&
252 Number.isFinite(surface.revealLine)
253 ? Math.max(1, Math.trunc(surface.revealLine))
254 : null;
255 const revealRequestId =
256 typeof surface.revealRequestId === "number" &&
257 Number.isSafeInteger(surface.revealRequestId) &&
258 surface.revealRequestId >= 0
259 ? surface.revealRequestId
260 : 0;
261 return [{ ...surface, revealLine, revealRequestId }];
262 }
263 if (surface.kind !== "terminal") return [surface];
264 if (
265 !("resourceId" in surface) ||
266 typeof surface.resourceId !== "string" ||
267 surface.id !== `terminal:${surface.resourceId}`
268 ) {
269 return [];
270 }
271 const terminalIds =
272 "terminalIds" in surface && Array.isArray(surface.terminalIds)
273 ? [
274 ...new Set(
275 surface.terminalIds.filter(
276 (terminalId): terminalId is string =>
277 typeof terminalId === "string",
278 ),
279 ),
280 ]
281 : [surface.resourceId];
282 const activeTerminalId =
283 "activeTerminalId" in surface &&
284 typeof surface.activeTerminalId === "string" &&
285 terminalIds.includes(surface.activeTerminalId)
286 ? surface.activeTerminalId
287 : (terminalIds[0] ?? surface.resourceId);
288 return [
289 {
290 ...surface,
291 terminalIds: terminalIds.length > 0 ? terminalIds : [surface.resourceId],
292 activeTerminalId,
293 },
294 ];
295 })
296 : [];
297 const activeSurfaceId = surfaces.some(
298 (surface) => surface.id === validThreadState?.activeSurfaceId,
299 )
300 ? (validThreadState?.activeSurfaceId ?? null)
301 : null;
302 const isOpen =
303 typeof validThreadState?.isOpen === "boolean"
304 ? validThreadState.isOpen
305 : activeSurfaceId !== null;
306 return [threadKey, { isOpen, surfaces, activeSurfaceId }];
307 },
308 ),
309 )
310 : {};
311 const threadPanelVisibilityByThreadKey =
312 "threadPanelVisibilityByThreadKey" in persistedState &&
313 persistedState.threadPanelVisibilityByThreadKey &&
314 typeof persistedState.threadPanelVisibilityByThreadKey === "object"
315 ? Object.fromEntries(
316 Object.entries(
317 persistedState.threadPanelVisibilityByThreadKey as Record<string, unknown>,
318 ).flatMap(([threadKey, value]) => {
319 if (!value || typeof value !== "object" || !("inlineOpen" in value)) return [];
320 return value.inlineOpen === false
321 ? [[threadKey, { inlineOpen: false, popoverOpen: false }]]
322 : [];
323 }),
324 )
325 : {};
326 return { byThreadKey, threadPanelVisibilityByThreadKey };
328​
329export const useRightPanelStore = create<RightPanelStoreState>()(
330 persist(
331 (set) => ({
332 byThreadKey: {},
333 threadPanelVisibilityByThreadKey: {},
334 open: (ref, kind) =>
335 set((state) =>
336 updateThread(state, ref, (current) => {
337 if (kind === "preview") {
338 const existing = current.surfaces.find((surface) => surface.kind === "preview");
339 return upsertSurface(current, existing ?? browserSurface(null));
340 }
341 return upsertSurface(current, singletonSurface(kind));
342 }),
343 ),
344 openBrowser: (ref, tabId) =>
345 set((state) =>
346 updateThread(state, ref, (current) => {
347 const surface = browserSurface(tabId);
348 const withoutPlaceholder = tabId
349 ? current.surfaces.filter((entry) => entry.id !== "browser:new")
350 : current.surfaces;
351 return upsertSurface({ ...current, surfaces: withoutPlaceholder }, surface);
352 }),
353 ),
354 openFile: (ref, relativePath, line) =>
355 set((state) =>
356 updateThread(state, ref, (current) => {
357 const withoutStandaloneExplorer = current.surfaces.filter(
358 (surface) => surface.kind !== "files",
359 );
360 const surfaceId = `file:${relativePath}` as const;
361 const existing = withoutStandaloneExplorer.find(
362 (surface): surface is Extract<RightPanelSurface, { kind: "file" }> =>
363 surface.id === surfaceId && surface.kind === "file",
364 );
365 const surface = fileSurface(
366 relativePath,
367 normalizeRevealLine(line),
368 (existing?.revealRequestId ?? 0) + 1,
369 );
370 return {
371 isOpen: true,
372 activeSurfaceId: surface.id,
373 surfaces: existing
374 ? withoutStandaloneExplorer.map((entry) =>
375 entry.id === surface.id ? surface : entry,
376 )
377 : [...withoutStandaloneExplorer, surface],
378 };
379 }),
380 ),
381 openTerminal: (ref, terminalId) =>
382 set((state) =>
383 updateThread(state, ref, (current) =>
384 upsertSurface(current, terminalSurface(terminalId)),
385 ),
386 ),
387 splitTerminal: (ref, surfaceId, terminalId, direction = "horizontal") =>
388 set((state) =>
389 updateThread(state, ref, (current) => ({
390 ...current,
391 isOpen: true,
392 activeSurfaceId: surfaceId,
393 surfaces: current.surfaces.map((surface) => {
394 if (surface.id !== surfaceId || surface.kind !== "terminal") return surface;
395 const { splitDirection: _splitDirection, ...baseSurface } = surface;
396 return {
397 ...baseSurface,
398 terminalIds: surface.terminalIds.includes(terminalId)
399 ? surface.terminalIds
400 : [...surface.terminalIds, terminalId],
401 activeTerminalId: terminalId,
402 ...(direction === "vertical" ? { splitDirection: "vertical" as const } : {}),
403 };
404 }),
405 })),
406 ),
407 activateTerminal: (ref, surfaceId, terminalId) =>
408 set((state) =>
409 updateThread(state, ref, (current) => ({
410 ...current,
411 activeSurfaceId: surfaceId,
412 surfaces: current.surfaces.map((surface) =>
413 surface.id === surfaceId &&
414 surface.kind === "terminal" &&
415 surface.terminalIds.includes(terminalId)
416 ? { ...surface, activeTerminalId: terminalId }
417 : surface,
418 ),
419 })),
420 ),
421 closeTerminal: (ref, surfaceId, terminalId) =>
422 set((state) =>
423 updateThread(state, ref, (current) => {
424 const surface = current.surfaces.find(
425 (entry) => entry.id === surfaceId && entry.kind === "terminal",
426 );
427 if (!surface || surface.kind !== "terminal") return current;
428 const terminalIds = surface.terminalIds.filter((id) => id !== terminalId);
429 if (terminalIds.length === 0) {
430 const index = current.surfaces.findIndex((entry) => entry.id === surfaceId);
431 const surfaces = current.surfaces.filter((entry) => entry.id !== surfaceId);
432 const fallback = surfaces[Math.min(index, surfaces.length - 1)] ?? null;
433 return {
434 ...current,
435 isOpen: surfaces.length > 0 && current.isOpen,
436 surfaces,
437 activeSurfaceId:
438 current.activeSurfaceId === surfaceId
439 ? (fallback?.id ?? null)
440 : current.activeSurfaceId,
441 };
442 }
443 return {
444 ...current,
445 surfaces: current.surfaces.map((entry) =>
446 entry.id === surfaceId && entry.kind === "terminal"
447 ? {
448 ...entry,
449 terminalIds,
450 activeTerminalId:
451 entry.activeTerminalId === terminalId
452 ? (terminalIds.at(-1) ?? terminalIds[0]!)
453 : entry.activeTerminalId,
454 }
455 : entry,
456 ),
457 };
458 }),
459 ),
460 activateSurface: (ref, surfaceId) =>
461 set((state) =>
462 updateThread(state, ref, (current) =>
463 current.surfaces.some((surface) => surface.id === surfaceId)
464 ? { ...current, isOpen: true, activeSurfaceId: surfaceId }
465 : current,
466 ),
467 ),
468 closeSurface: (ref, surfaceId) =>
469 set((state) =>
470 updateThread(state, ref, (current) => {
471 const index = current.surfaces.findIndex((surface) => surface.id === surfaceId);
472 if (index < 0) return current;
473 const surfaces = current.surfaces.filter((surface) => surface.id !== surfaceId);
474 if (current.activeSurfaceId !== surfaceId) {
475 return { ...current, isOpen: surfaces.length > 0 && current.isOpen, surfaces };
476 }
477 const fallback = surfaces[Math.min(index, surfaces.length - 1)] ?? null;
478 return {
479 ...current,
480 isOpen: surfaces.length > 0 && current.isOpen,
481 surfaces,
482 activeSurfaceId: fallback?.id ?? null,
483 };
484 }),
485 ),
486 closeOtherSurfaces: (ref, surfaceId) =>
487 set((state) =>
488 updateThread(state, ref, (current) => {
489 const surface = current.surfaces.find((entry) => entry.id === surfaceId);
490 if (!surface || current.surfaces.length === 1) return current;
491 return {
492 ...current,
493 isOpen: true,
494 surfaces: [surface],
495 activeSurfaceId: surface.id,
496 };
497 }),
498 ),
499 closeSurfacesToRight: (ref, surfaceId) =>
500 set((state) =>
501 updateThread(state, ref, (current) => {
502 const index = current.surfaces.findIndex((surface) => surface.id === surfaceId);
503 if (index < 0 || index === current.surfaces.length - 1) return current;
504 const surfaces = current.surfaces.slice(0, index + 1);
505 const activeStillExists = surfaces.some(
506 (surface) => surface.id === current.activeSurfaceId,
507 );
508 return {
509 ...current,
510 surfaces,
511 activeSurfaceId: activeStillExists ? current.activeSurfaceId : surfaceId,
512 };
513 }),
514 ),
515 closeAllSurfaces: (ref) =>
516 set((state) =>
517 updateThread(state, ref, (current) =>
518 current.surfaces.length === 0
519 ? current
520 : { ...current, isOpen: false, surfaces: [], activeSurfaceId: null },
521 ),
522 ),
523 reconcileBrowserSurfaces: (ref, tabIds) =>
524 set((state) =>
525 updateThread(state, ref, (current) => {
526 const validIds = new Set(tabIds.map((tabId) => `browser:${tabId}`));
527 const nonBrowser = current.surfaces.filter((surface) => surface.kind !== "preview");
528 const existingBrowser = current.surfaces.filter(
529 (surface): surface is Extract<RightPanelSurface, { kind: "preview" }> =>
530 surface.kind === "preview" &&
531 surface.id !== "browser:new" &&
532 validIds.has(surface.id),
533 );
534 const knownIds = new Set(existingBrowser.map((surface) => surface.id));
535 const added = tabIds
536 .filter((tabId) => !knownIds.has(`browser:${tabId}`))
537 .map((tabId) => browserSurface(tabId));
538 const surfaces = [...nonBrowser, ...existingBrowser, ...added];
539 const activeStillExists = surfaces.some(
540 (surface) => surface.id === current.activeSurfaceId,
541 );
542 const fallbackBrowser = surfaces.find((surface) => surface.kind === "preview");
543 return {
544 ...current,
545 surfaces,
546 activeSurfaceId: activeStillExists
547 ? current.activeSurfaceId
548 : (fallbackBrowser?.id ?? surfaces[0]?.id ?? null),
549 };
550 }),
551 ),
552 reconcileFileSurfaces: (ref, workspaceAvailable) =>
553 set((state) =>
554 updateThread(state, ref, (current) => {
555 if (workspaceAvailable) return current;
556 const surfaces = current.surfaces.filter(
557 (surface) => surface.kind !== "files" && surface.kind !== "file",
558 );
559 if (surfaces.length === current.surfaces.length) return current;
560 const activeStillExists = surfaces.some(
561 (surface) => surface.id === current.activeSurfaceId,
562 );
563 return {
564 ...current,
565 isOpen: surfaces.length > 0 ? current.isOpen : false,
566 surfaces,
567 activeSurfaceId: activeStillExists
568 ? current.activeSurfaceId
569 : (surfaces.at(-1)?.id ?? null),
570 };
571 }),
572 ),
573 show: (ref) =>
574 set((state) =>
575 updateThread(state, ref, (current) =>
576 current.isOpen ? current : { ...current, isOpen: true },
577 ),
578 ),
579 close: (ref) =>
580 set((state) =>
581 updateThread(state, ref, (current) =>
582 current.isOpen ? { ...current, isOpen: false } : current,
583 ),
584 ),
585 toggleVisibility: (ref) =>
586 set((state) =>
587 updateThread(state, ref, (current) => ({
588 ...current,
589 isOpen: !current.isOpen,
590 })),
591 ),
592 toggle: (ref, kind) =>
593 set((state) =>
594 updateThread(state, ref, (current) => {
595 const active = current.surfaces.find(
596 (surface) => surface.id === current.activeSurfaceId,
597 );
598 if (current.isOpen && active?.kind === kind) {
599 return { ...current, isOpen: false };
600 }
601 if (kind === "preview") {
602 const existing = current.surfaces.find((surface) => surface.kind === "preview");
603 return upsertSurface(current, existing ?? browserSurface(null));
604 }
605 return upsertSurface(current, singletonSurface(kind));
606 }),
607 ),
608 setThreadPanelOpen: (ref, presentation, open) =>
609 set((state) => ({
610 threadPanelVisibilityByThreadKey: updateThreadPanelVisibilityMap(
611 state.threadPanelVisibilityByThreadKey,
612 scopedThreadKey(ref),
613 (visibility) => {
614 const key = presentation === "inline" ? "inlineOpen" : "popoverOpen";
615 return visibility[key] === open ? visibility : { ...visibility, [key]: open };
616 },
617 ),
618 })),
619 toggleThreadPanel: (ref, presentation) =>
620 set((state) => ({
621 threadPanelVisibilityByThreadKey: updateThreadPanelVisibilityMap(
622 state.threadPanelVisibilityByThreadKey,
623 scopedThreadKey(ref),
624 (visibility) =>
625 presentation === "inline"
626 ? { ...visibility, inlineOpen: !visibility.inlineOpen }
627 : { ...visibility, popoverOpen: !visibility.popoverOpen },
628 ),
629 })),
630 removeThread: (ref) =>
631 set((state) => {
632 const threadKey = scopedThreadKey(ref);
633 if (
634 !(threadKey in state.byThreadKey) &&
635 !(threadKey in state.threadPanelVisibilityByThreadKey)
636 ) {
637 return state;
638 }
639 const { [threadKey]: _removedPanel, ...byThreadKey } = state.byThreadKey;
640 const { [threadKey]: _removedVisibility, ...threadPanelVisibilityByThreadKey } =
641 state.threadPanelVisibilityByThreadKey;
642 return { byThreadKey, threadPanelVisibilityByThreadKey };
643 }),
644 }),
645 {
646 name: RIGHT_PANEL_STORAGE_KEY,
647 version: RIGHT_PANEL_STORAGE_VERSION,
648 storage: createJSONStorage(() =>
649 resolveStorage(typeof window !== "undefined" ? window.localStorage : undefined),
650 ),
651 partialize: (state) => ({
652 byThreadKey: state.byThreadKey,
653 threadPanelVisibilityByThreadKey: Object.fromEntries(
654 Object.entries(state.threadPanelVisibilityByThreadKey).flatMap(
655 ([threadKey, visibility]) =>
656 visibility.inlineOpen ? [] : [[threadKey, { inlineOpen: false, popoverOpen: false }]],
657 ),
658 ),
659 }),
660 migrate: migratePersistedRightPanelState,
661 },
662 ),
663);
664​
665export function selectThreadRightPanelState(
666 byThreadKey: Record<string, ThreadRightPanelState>,
667 ref: ScopedThreadRef | null | undefined,
668): ThreadRightPanelState {
669 if (!ref) return EMPTY_THREAD_STATE;
670 return byThreadKey[scopedThreadKey(ref)] ?? EMPTY_THREAD_STATE;
672​
673export function selectThreadPanelVisibility(
674 byThreadKey: Record<string, ThreadPanelVisibility>,
675 ref: ScopedThreadRef | null | undefined,
676): ThreadPanelVisibility {
677 if (!ref) return DEFAULT_THREAD_PANEL_VISIBILITY;
678 return byThreadKey[scopedThreadKey(ref)] ?? DEFAULT_THREAD_PANEL_VISIBILITY;
680​
681export function selectThreadPanelOpen(
682 byThreadKey: Record<string, ThreadPanelVisibility>,
683 ref: ScopedThreadRef | null | undefined,
684 presentation: ThreadPanelPresentation,
685): boolean {
686 const visibility = selectThreadPanelVisibility(byThreadKey, ref);
687 return presentation === "inline" ? visibility.inlineOpen : visibility.popoverOpen;
689​
690export function selectActiveRightPanel(
691 byThreadKey: Record<string, ThreadRightPanelState>,
692 ref: ScopedThreadRef | null | undefined,
693): RightPanelKind | null {
694 const state = selectThreadRightPanelState(byThreadKey, ref);
695 if (!state.isOpen) return null;
696 return state.surfaces.find((surface) => surface.id === state.activeSurfaceId)?.kind ?? null;
698​
699export function selectActiveRightPanelSurface(
700 byThreadKey: Record<string, ThreadRightPanelState>,
701 ref: ScopedThreadRef | null | undefined,
702): RightPanelSurface | null {
703 const state = selectThreadRightPanelState(byThreadKey, ref);
704 if (!state.isOpen) return null;
705 return state.surfaces.find((surface) => surface.id === state.activeSurfaceId) ?? null;