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

ReopenClosedViewShortcut.tsx

289 lines10.9 KB

1import { m } from "../i18n/messages";
2import { thrownErrorMessage } from "@t3tools/client-runtime/errors";
3import { useAtomValue } from "@effect/atom-react";
4import {
5 scopeProjectRef,
6 scopedThreadKey,
7 scopeThreadRef,
8} from "@t3tools/client-runtime/environment";
9import type { ScopedThreadRef } from "@t3tools/contracts";
10import { linkOptions, useNavigate, useParams, useRouter } from "@tanstack/react-router";
11import { useGT } from "gt-react";
12import { useEffect, useEffectEvent, useRef } from "react";
13​
14import { isCommandPaletteOpen } from "../commandPaletteBus";
15import { useClosedViewStore } from "../closedViewStore";
16import { useComposerDraftStore } from "../composerDraftStore";
17import { environmentCatalog } from "../connection/catalog";
18import { effectiveShortcutsForCommand, resolveShortcutCommand } from "../keybindings";
19import { isEditableFocused } from "../lib/editableFocus";
20import { isPreviewFocused } from "../lib/previewFocus";
21import { isTerminalFocused } from "../lib/terminalFocus";
22import { isModelPickerOpen } from "../modelPickerVisibility";
23import {
24 planNextReopen,
25 pullRequestsSearchForRestore,
26 reopenClosedView,
27} from "../reopenClosedView";
28import {
29 ISSUES_PANEL_REF,
30 PULL_REQUESTS_PANEL_REF,
31 selectActiveRightPanel,
32 selectSelectedRightPanelSurface,
33 selectThreadRightPanelState,
34 useRightPanelStore,
35} from "../rightPanelStore";
36import { serverEnvironment } from "../state/server";
37import { appAtomRegistry } from "../rpc/atomRegistry";
38import { readProject, readThreadShell } from "../state/entities";
39import { previewEnvironment } from "../state/preview";
40import { primaryServerKeybindingsAtom } from "../state/server";
41import { environmentShell } from "../state/shell";
42import { useAtomCommand } from "../state/use-atom-command";
43import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../terminalUiStateStore";
44import {
45 buildDraftThreadRouteParams,
46 buildThreadRouteParams,
47 resolveThreadRouteTarget,
48} from "../threadRoutes";
49import { toastManager } from "./ui/toast";
50import { readIssueListPreferences } from "./issue/issueListPreferences";
51​
52declare module "@tanstack/react-router" {
53 interface HistoryState {
54 reopenedViewId?: string;
55 }
57​
58const PREVIEW_FORWARDED_COMMANDS = [
59 "workspace.focusNext",
60 "workspace.focusPrevious",
61 "sidebar.toggle",
62 "rightPanel.toggle",
63 "rightPanel.toggleMaximized",
64 "rightPanel.new",
65 "rightPanel.close",
66 "preview.focusUrl",
67 "preview.zoomIn",
68 "preview.zoomOut",
69 "preview.resetZoom",
70 "preview.find",
71] as const;
72​
73const isGlobalPullRequests = (ref: ScopedThreadRef) =>
74 scopedThreadKey(ref) === scopedThreadKey(PULL_REQUESTS_PANEL_REF);
75const isGlobalIssues = (ref: ScopedThreadRef) =>
76 scopedThreadKey(ref) === scopedThreadKey(ISSUES_PANEL_REF);
77​
78export function ReopenClosedViewShortcut() {
79 const gt = useGT();
80 const navigate = useNavigate();
81 const router = useRouter();
82 const params = useParams({ strict: false });
83 const target = resolveThreadRouteTarget(params);
84 const draft = useComposerDraftStore((state) =>
85 target?.kind === "draft" ? state.getDraftSession(target.draftId) : null,
86 );
87 const threadRef =
88 target?.kind === "server"
89 ? target.threadRef
90 : draft
91 ? (draft.promotedTo ?? scopeThreadRef(draft.environmentId, draft.threadId))
92 : null;
93 const terminalOpen = useTerminalUiStateStore(
94 (state) =>
95 selectThreadTerminalUiState(state.terminalUiStateByThreadKey, threadRef).terminalOpen,
96 );
97 const previewOpen = useRightPanelStore(
98 (state) => selectActiveRightPanel(state.byThreadKey, threadRef) === "preview",
99 );
100 const keybindings = useAtomValue(primaryServerKeybindingsAtom);
101 const hasHistory = useClosedViewStore((state) => state.entries.length > 0);
102 const openPreview = useAtomCommand(previewEnvironment.open);
103 const pending = useRef(Promise.resolve());
104 type ReopenNavigation = { location: typeof router.history.location };
105 const reopenNavigation = useRef<ReopenNavigation | null>(null);
106​
107 const reopenNext = useEffectEvent(async (request: ReopenNavigation) => {
108 const catalog = appAtomRegistry.get(environmentCatalog.catalogValueAtom);
109 const drafts = useComposerDraftStore.getState();
110 const panelsByThread = useRightPanelStore.getState().byThreadKey;
111 const { drop, restore } = planNextReopen(useClosedViewStore.getState().entries, (entry) => {
112 const ref = entry.threadRef;
113 const panel = selectThreadRightPanelState(panelsByThread, ref);
114 if (isGlobalPullRequests(ref) || isGlobalIssues(ref)) {
115 return {
116 environmentKnown: true,
117 catalogReady: true,
118 ownerExists: true,
119 sideChatExists: true,
120 shellLive: true,
121 panel,
122 };
123 }
124 return {
125 environmentKnown: catalog.entries.has(ref.environmentId),
126 catalogReady: catalog.isReady,
127 ownerExists: readThreadShell(ref) !== null || drafts.getDraftThreadByRef(ref) !== null,
128 sideChatExists:
129 entry.kind !== "panel-tab" ||
130 entry.surface.kind !== "thread" ||
131 readThreadShell(scopeThreadRef(ref.environmentId, entry.surface.threadId)) !== null ||
132 // The shell leaves idle subagents out, so one it does not list may still exist.
133 appAtomRegistry.get(serverEnvironment.configValueAtom(ref.environmentId))
134 ?.shellThreadFamilies === true,
135 shellLive:
136 appAtomRegistry.get(environmentShell.stateValueAtom(ref.environmentId)).status === "live",
137 panel,
138 };
139 });
140 for (const entry of drop) useClosedViewStore.getState().remove(entry.id);
141 if (!restore) return;
142​
143 const ref = restore.threadRef;
144 const globalPullRequests = isGlobalPullRequests(ref);
145 const globalIssues = isGlobalIssues(ref);
146 const thread = globalPullRequests || globalIssues ? null : readThreadShell(ref);
147 const owner = thread ?? drafts.getDraftThreadByRef(ref);
148 const project = owner ? readProject(scopeProjectRef(ref.environmentId, owner.projectId)) : null;
149 if (!(await reopenClosedView(restore, { openPreview, workspaceAvailable: project !== null }))) {
150 useClosedViewStore.getState().defer(restore.id);
151 return;
152 }
153 useClosedViewStore.getState().remove(restore.id);
154 if (router.history.location !== request.location) return;
155​
156 let destination;
157 if (globalPullRequests) {
158 const selected = selectSelectedRightPanelSurface(
159 useRightPanelStore.getState().byThreadKey,
160 ref,
161 );
162 destination = linkOptions({
163 to: "/pull-requests",
164 search: (previous) => pullRequestsSearchForRestore(previous, selected),
165 });
166 } else if (globalIssues) {
167 destination = linkOptions({ to: "/issues", search: readIssueListPreferences() });
168 } else {
169 const draftId = thread === null ? drafts.getDraftIdByRef(ref) : null;
170 destination =
171 draftId !== null
172 ? linkOptions({ to: "/draft/$draftId", params: buildDraftThreadRouteParams(draftId) })
173 : linkOptions({ to: "/$environmentId/$threadId", params: buildThreadRouteParams(ref) });
174 }
175​
176 const { history } = router;
177 if (router.buildLocation(destination).publicHref === history.location.href) {
178 const { reopenedViewId } = history.location.state;
179 await navigate({ ...destination, state: reopenedViewId ? { reopenedViewId } : {} });
180 return;
181 }
182​
183 // An allowing blocker can defer the commit. Only the reopen's first history hop extends the queue.
184 const unsubscribe = history.subscribe(({ location, action }) => {
185 if (location === request.location) return;
186 unsubscribe();
187 if (action.type === "PUSH" && location.state.reopenedViewId === restore.id) {
188 request.location = location;
189 }
190 });
191 try {
192 await navigate({ ...destination, state: { reopenedViewId: restore.id } });
193 } catch (error) {
194 unsubscribe();
195 throw error;
196 }
197 unsubscribe();
198 });
199​
200 const enqueueReopen = useEffectEvent(() => {
201 const location = router.history.location;
202 const previous = reopenNavigation.current;
203 const request = previous?.location === location ? previous : { location };
204 reopenNavigation.current = request;
205 pending.current = pending.current
206 .then(() => reopenNext(request))
207 .catch((error: unknown) => {
208 toastManager.add({
209 type: "error",
210 title: gt("Could not reopen view"),
211 description: thrownErrorMessage(error, m) ?? String(error),
212 });
213 });
214 });
215​
216 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- subscribes to window keydown and the desktop menu action for the reopen closed view shortcut
217 useEffect(() => {
218 const onKeyDown = (event: KeyboardEvent) => {
219 if (
220 event.defaultPrevented ||
221 isCommandPaletteOpen() ||
222 useClosedViewStore.getState().entries.length === 0 ||
223 (event.target instanceof HTMLElement && event.target.closest("[data-keybinding-capture]"))
224 )
225 return;
226 const command = resolveShortcutCommand(event, keybindings, {
227 context: {
228 terminalFocus: isTerminalFocused(),
229 terminalOpen,
230 previewFocus: isPreviewFocused(),
231 previewOpen,
232 editableFocus: isEditableFocused(event.target),
233 modelPickerOpen: isModelPickerOpen(),
234 },
235 });
236 if (command !== "view.reopenClosed") return;
237 event.preventDefault();
238 event.stopPropagation();
239 if (!event.repeat) enqueueReopen();
240 };
241 window.addEventListener("keydown", onKeyDown, true);
242 const unsubscribe = window.desktopBridge?.onMenuAction((action) => {
243 if (action === "view.reopenClosed" && !isCommandPaletteOpen()) enqueueReopen();
244 });
245 return () => {
246 window.removeEventListener("keydown", onKeyDown, true);
247 unsubscribe?.();
248 };
249 }, [keybindings, previewOpen, terminalOpen]);
250​
251 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- registers forwarded shortcut chords with the desktop preview bridge and clears them on cleanup
252 useEffect(() => {
253 const preview = window.desktopBridge?.preview;
254 if (!preview) return;
255 const options = {
256 context: {
257 previewFocus: true,
258 previewOpen: true,
259 rightPanelOpen: true,
260 terminalFocus: false,
261 terminalOpen,
262 editableFocus: false,
263 modelPickerOpen: false,
264 isDesktop: true,
265 isWeb: false,
266 },
267 };
268 // Guest browser processes miss app keydown listeners; desktop forwards the chords as menu actions.
269 const commands = [
270 ...(hasHistory ? (["view.reopenClosed"] as const) : []),
271 ...PREVIEW_FORWARDED_COMMANDS,
272 ];
273 void preview
274 .setForwardedShortcuts(
275 commands.flatMap((command) =>
276 effectiveShortcutsForCommand(keybindings, command, options).map((shortcut) => ({
277 command,
278 shortcut,
279 })),
280 ),
281 )
282 .catch(() => undefined);
283 return () => {
284 void preview.setForwardedShortcuts([]).catch(() => undefined);
285 };
286 }, [hasHistory, keybindings, terminalOpen]);
287​
288 return null;