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

sideChatStore.ts

81 lines2.7 KB

1import type { ThreadId } from "@t3tools/contracts";
2import { create } from "zustand";
3import { createJSONStorage, persist } from "zustand/middleware";
4​
5import { resolveStorage } from "./lib/storage";
6import type { RightPanelSurface } from "./rightPanelStore";
7​
8export type SideChatHistoryChoice = "with" | "without";
9​
10interface SideChatPreferenceState {
11 /** What the split "+" starts, so the common choice is one click. */
12 history: SideChatHistoryChoice;
13 setHistory: (history: SideChatHistoryChoice) => void;
15​
16export const useSideChatPreferenceStore = create<SideChatPreferenceState>()(
17 persist(
18 (set) => ({
19 history: "with",
20 setHistory: (history) => set({ history }),
21 }),
22 {
23 name: "t3code:side-chat-preference:v1",
24 version: 1,
25 storage: createJSONStorage(() =>
26 resolveStorage(typeof window !== "undefined" ? window.localStorage : undefined),
27 ),
28 partialize: (state) => ({ history: state.history }),
29 },
30 ),
31);
32​
33interface SideChatFocusState {
34 /**
35 * Parent thread key to the side chat its composer talks to. It counts only
36 * while that side chat's tab is the open panel's active one, see
37 * `resolveFocusedSideChat`.
38 */
39 byParent: Record<string, ThreadId>;
40 focus: (parentKey: string, childThreadId: ThreadId) => void;
41 /** Back to the parent; with a child id, only if that side chat still has focus. */
42 release: (parentKey: string, childThreadId?: ThreadId) => void;
44​
45export const useSideChatFocusStore = create<SideChatFocusState>()((set) => ({
46 byParent: {},
47 focus: (parentKey, childThreadId) =>
48 set((state) =>
49 state.byParent[parentKey] === childThreadId
50 ? state
51 : { byParent: { ...state.byParent, [parentKey]: childThreadId } },
52 ),
53 release: (parentKey, childThreadId) =>
54 set((state) => {
55 const current = state.byParent[parentKey];
56 if (current === undefined || (childThreadId !== undefined && current !== childThreadId)) {
57 return state;
58 }
59 const { [parentKey]: _released, ...byParent } = state.byParent;
60 return { byParent };
61 }),
62}));
63​
64/**
65 * The side chat a thread's composer talks to: the one picked, while its tab is
66 * the active surface of an open panel. Closing the panel or switching tabs
67 * hands the composer back without anything having to release it.
68 */
69export function resolveFocusedSideChat(input: {
70 readonly picked: ThreadId | null;
71 readonly panelOpen: boolean;
72 readonly activeSurface: RightPanelSurface | null;
73}): ThreadId | null {
74 const { picked, activeSurface } = input;
75 return picked !== null &&
76 input.panelOpen &&
77 activeSurface?.kind === "aside" &&
78 activeSurface.threadId === picked
79 ? picked
80 : null;