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

rightPanelStore.ts

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