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

ReopenClosedViewShortcut.tsx

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