Skip to content

Commit 652a6ca

Browse files
refactor(web): command palette state lives in a store, git and branch pickers drop timer and sync effects
The command palette held its open state in a component reducer, so every way in (sidebar buttons, Cmd+N, PR links) went through a window CustomEvent that an effect relayed into the reducer, its shortcuts were one window listener re-attached whenever the theme, keybindings, terminal or preview state changed, and an open intent ("Add project", "New thread in...") was applied by a layout effect that cleared it again in the parent. GitActionsControl ran its own focus/visibility listener, interval and timeout effects, and BranchPicker measured its fades two frames after opening and scrolled to top from a previous-value effect. - Palette state is a zustand store driven by the same reducer. openCommandPalette dispatches to it directly. Palette, theme and usage shortcuts are one dispatcher scope installed at app start, live only while a palette is mounted, and read the route, panels and theme at key time. - An intent bumps a session; the palette view is keyed by it and starts in the intent's submenu on its first render. "Add project" and "New thread in..." submenus resolve their items while rendering, so they follow projects and environments as they load. - GitActionsControl: elapsed time reads the shared second clock, the inline success hides at a deadline, and focus/visibility status refresh is one shared atom per checkout (vcsStatusRevalidation, wake option restored in client-runtime with this consumer). - BranchPicker: fades follow a ResizeObserver from the list's ref callback; typing scrolls the list to top in the input handler. - AddProjectToMachineDialog: no effect closes it when its project goes away; the dialog's open state follows the project and the request ends when the close finishes. Each request remounts the dialog. Effects kept: the palette's browse-navigation cleanup, GitActionsControl's live-branch draft sync, BranchToolbarBranchSelector's default-branch write (both feed the send path, which still reads the stored branch). Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 71ba6b3 commit 652a6ca

19 files changed

Lines changed: 682 additions & 393 deletions

‎apps/web/src/appInit.tsx‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@ import { getRouter, type AppRouter } from "./router";
4343
import { appAtomRegistry } from "./rpc/atomRegistry";
4444
import { primaryServerConfigAtom } from "./state/server";
4545
import { installChatRouteCommands } from "./shortcuts/chatRouteCommands";
46+
import { installCommandPaletteCommands } from "./shortcuts/commandPaletteCommands";
4647
import { registerOpenFavoriteEditorCommand } from "./components/chat/OpenInPickerShortcut";
4748
import { environmentThreadShells } from "./state/threads";
4849
import { resolveThreadRouteTarget } from "./threadRoutes";
@@ -172,6 +173,7 @@ export function startAppServices(): AppRouter {
172173
startPreviewTitleRecording();
173174
startBrowserProfileReporting();
174175
installChatRouteCommands(router);
176+
installCommandPaletteCommands(router);
175177
registerOpenFavoriteEditorCommand();
176178
startThreadOverlayRetention(router);
177179
// Drafts promote as their server threads arrive, wherever the user is.

‎apps/web/src/commandPaletteBus.ts‎

Lines changed: 17 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,34 +1,35 @@
11
import type { EnvironmentId, PullRequestLinkedThreadsResult } from "@t3tools/contracts";
22

3+
import { dispatchCommandPalette } from "./commandPaletteStore";
4+
35
export interface CommandPaletteLinkedThreads {
46
readonly environmentId: EnvironmentId;
57
readonly threads: PullRequestLinkedThreadsResult["threads"];
68
}
79

8-
const COMMAND_PALETTE_OPEN_EVENT = "t3code:open-command-palette";
9-
1010
export interface CommandPaletteOpenDetail {
1111
readonly open?: "add-project" | "new-thread-in";
1212
readonly query?: string;
1313
readonly linkedThreads?: CommandPaletteLinkedThreads;
1414
}
1515

16-
export function openCommandPalette(detail?: CommandPaletteOpenDetail): void {
17-
window.dispatchEvent(
18-
new CustomEvent(COMMAND_PALETTE_OPEN_EVENT, detail ? { detail } : undefined),
19-
);
20-
}
21-
22-
export function onOpenCommandPalette(
23-
listener: (detail: CommandPaletteOpenDetail) => void,
24-
): () => void {
25-
const handler = (event: Event) => {
26-
listener((event as CustomEvent<CommandPaletteOpenDetail>).detail ?? {});
27-
};
28-
window.addEventListener(COMMAND_PALETTE_OPEN_EVENT, handler);
29-
return () => window.removeEventListener(COMMAND_PALETTE_OPEN_EVENT, handler);
16+
export function openCommandPalette(detail: CommandPaletteOpenDetail = {}): void {
17+
if (detail.open === "new-thread-in") {
18+
dispatchCommandPalette({ _tag: "OpenNewThreadIn" });
19+
} else if (detail.open === "add-project") {
20+
dispatchCommandPalette({ _tag: "OpenAddProject" });
21+
} else if (detail.query !== undefined) {
22+
dispatchCommandPalette({
23+
_tag: "OpenSearch",
24+
query: detail.query,
25+
...(detail.linkedThreads ? { linkedThreads: detail.linkedThreads } : {}),
26+
});
27+
} else {
28+
dispatchCommandPalette({ _tag: "SetOpen", open: true });
29+
}
3030
}
3131

32+
/** True while the palette popup is on screen, including its closing animation. */
3233
export function isCommandPaletteOpen(): boolean {
3334
return (
3435
typeof document !== "undefined" && document.querySelector("[data-command-palette]") !== null
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
import { create } from "zustand";
2+
3+
import {
4+
type CommandPaletteUiAction,
5+
type CommandPaletteUiState,
6+
reduceCommandPaletteUiState,
7+
} from "./components/CommandPalette.logic";
8+
9+
const INITIAL_STATE: CommandPaletteUiState = {
10+
open: false,
11+
mode: "command",
12+
openIntent: null,
13+
session: 0,
14+
};
15+
16+
export const useCommandPaletteStore = create<CommandPaletteUiState>(() => INITIAL_STATE);
17+
18+
export function dispatchCommandPalette(action: CommandPaletteUiAction): void {
19+
useCommandPaletteStore.setState((state) => reduceCommandPaletteUiState(state, action), true);
20+
}
21+
22+
// The palette is only mounted on app-shell routes (not /pair, sign-in or
23+
// landings), so its shortcuts must stay inert elsewhere.
24+
let mountedPalettes = 0;
25+
26+
export function isCommandPaletteMounted(): boolean {
27+
return mountedPalettes > 0;
28+
}
29+
30+
/** Ref callback for the palette's root; an unmounted palette cannot stay open. */
31+
export function commandPaletteMountRef(node: Element | null): (() => void) | undefined {
32+
if (node === null) return undefined;
33+
mountedPalettes += 1;
34+
return () => {
35+
mountedPalettes -= 1;
36+
if (mountedPalettes === 0) {
37+
useCommandPaletteStore.setState(
38+
(state) => ({ ...INITIAL_STATE, session: state.session + 1 }),
39+
true,
40+
);
41+
}
42+
};
43+
}

‎apps/web/src/components/AddProjectToMachineDialog.tsx‎

Lines changed: 16 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ import {
1717
cloneUrlProtocol,
1818
} from "@t3tools/shared/cloneUrl";
1919
import { ArrowRightIcon } from "lucide-react";
20-
import { useEffect, useId, useState } from "react";
20+
import { useId, useState } from "react";
2121
import { create } from "zustand";
2222

2323
import { type DraftId, useComposerDraftStore } from "../composerDraftStore";
@@ -31,7 +31,7 @@ import {
3131
} from "../lib/addProjectToMachine";
3232
import { formatBytes } from "../lib/formatBytes";
3333
import { newProjectId } from "../lib/utils";
34-
import { useProject } from "../state/entities";
34+
import { readProject, useProject } from "../state/entities";
3535
import { useEnvironments } from "../state/environments";
3636
import { projectEnvironment } from "../state/projects";
3737
import { useEnvironmentQuery } from "../state/query";
@@ -58,20 +58,25 @@ interface AddProjectToMachineRequest {
5858
readonly targetEnvironmentId: EnvironmentId | null;
5959
}
6060

61-
const useRequest = create<{ request: AddProjectToMachineRequest | null }>(() => ({
61+
const useRequest = create<{ request: AddProjectToMachineRequest | null; session: number }>(() => ({
6262
request: null,
63+
session: 0,
6364
}));
6465

6566
/** Opens the dialog that clones a project onto another connected machine. */
6667
export function openAddProjectToMachine(request: AddProjectToMachineRequest) {
67-
useRequest.setState({ request });
68+
// The dialog closes itself when its project goes away, so it must not open
69+
// for one that is already gone and then appear when it loads.
70+
if (readProject(request.projectRef) === null) return;
71+
useRequest.setState((state) => ({ request, session: state.session + 1 }));
6872
}
6973

7074
const close = () => useRequest.setState({ request: null });
7175

7276
export function AddProjectToMachineDialogHost() {
7377
const request = useRequest((state) => state.request);
74-
return request ? <AddProjectToMachineDialog request={request} /> : null;
78+
const session = useRequest((state) => state.session);
79+
return request ? <AddProjectToMachineDialog key={session} request={request} /> : null;
7580
}
7681

7782
function AddProjectToMachineDialog({ request }: { request: AddProjectToMachineRequest }) {
@@ -128,10 +133,6 @@ function AddProjectToMachineDialog({ request }: { request: AddProjectToMachineRe
128133
project === null ||
129134
target === null ||
130135
(canListFiles && ignoredFiles.data === null && ignoredFiles.error === null);
131-
useEffect(() => {
132-
if (project === null) close();
133-
}, [project]);
134-
135136
const toggleFile = (path: string, checked: boolean) => {
136137
const next = new Set(selectedFiles);
137138
if (checked) next.add(path);
@@ -196,10 +197,15 @@ function AddProjectToMachineDialog({ request }: { request: AddProjectToMachineRe
196197

197198
return (
198199
<Dialog
199-
open
200+
open={project !== null}
200201
onOpenChange={(open) => {
201202
if (!open) close();
202203
}}
204+
// A user close unmounts at once through onOpenChange; this ends a request
205+
// whose project vanished while the dialog was open.
206+
onOpenChangeComplete={(open) => {
207+
if (!open) close();
208+
}}
203209
>
204210
<DialogPopup className="sm:max-w-xl">
205211
<form

‎apps/web/src/components/BranchPicker.tsx‎

Lines changed: 21 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,9 @@
11
import type { VcsRef } from "@t3tools/contracts";
22
import { LegendList, type LegendListRef } from "@legendapp/list/react";
3-
import {
4-
useEffect,
5-
useId,
6-
useLayoutEffect,
7-
useRef,
8-
useState,
9-
type ComponentProps,
10-
type ReactNode,
11-
} from "react";
3+
import { useId, useRef, useState, type ComponentProps, type ReactNode } from "react";
124

135
import { MiddleTruncate } from "./ui/middle-truncate";
6+
import { observeResize } from "../lib/observeResize";
147
import { cn } from "../lib/utils";
158
import { shouldLoadNextBranchPageAfterScroll } from "../state/paginatedBranches";
169
import { RefreshIcon } from "./ui/refresh-icon";
@@ -32,7 +25,6 @@ export function BranchPicker({
3225
filteredItems,
3326
value,
3427
query,
35-
resultsQuery,
3628
onQueryChange,
3729
open,
3830
onOpenChange,
@@ -51,7 +43,6 @@ export function BranchPicker({
5143
filteredItems: string[];
5244
value: string | null;
5345
query: string;
54-
resultsQuery: string;
5546
onQueryChange: (value: string) => void;
5647
open: boolean;
5748
onOpenChange: (open: boolean) => void;
@@ -121,32 +112,22 @@ export function BranchPicker({
121112
setShowBottomBranchScrollFade(maxScrollOffset - scrollElement.scrollTop > 1);
122113
};
123114

124-
useLayoutEffect(() => {
125-
if (!open) {
126-
return;
127-
}
128-
129-
let nestedFrame = 0;
130-
const frame = requestAnimationFrame(() => {
131-
updateBranchListScrollFades();
132-
nestedFrame = requestAnimationFrame(updateBranchListScrollFades);
133-
});
115+
// The popup mounts the list when it opens. Its content settles over a few
116+
// frames as rows measure, so the fades follow the scroller and its content.
117+
const attachBranchList = (list: LegendListRef | null) => {
118+
branchListRef.current = list;
119+
const scrollElement = list?.getScrollableNode?.();
120+
if (!(scrollElement instanceof HTMLElement)) return;
121+
const content = scrollElement.firstElementChild;
122+
const stopObserving = observeResize(
123+
content ? [scrollElement, content] : scrollElement,
124+
updateBranchListScrollFades,
125+
);
134126
return () => {
135-
cancelAnimationFrame(frame);
136-
cancelAnimationFrame(nestedFrame);
127+
stopObserving();
128+
branchListRef.current = null;
137129
};
138-
}, [open, updateBranchListScrollFades]);
139-
140-
const previousResultsQuery = useRef<string | null>(null);
141-
useEffect(() => {
142-
if (!open) {
143-
previousResultsQuery.current = null;
144-
return;
145-
}
146-
if (previousResultsQuery.current === resultsQuery) return;
147-
previousResultsQuery.current = resultsQuery;
148-
void branchListRef.current?.scrollToOffset?.({ offset: 0, animated: false });
149-
}, [resultsQuery, open]);
130+
};
150131

151132
return (
152133
<Combobox
@@ -173,7 +154,10 @@ export function BranchPicker({
173154
<ComboboxSearchInput
174155
placeholder="Search refs..."
175156
value={query}
176-
onChange={(event) => onQueryChange(event.target.value)}
157+
onChange={(event) => {
158+
onQueryChange(event.target.value);
159+
void branchListRef.current?.scrollToOffset?.({ offset: 0, animated: false });
160+
}}
177161
onKeyDown={(event) => {
178162
if (event.key !== "Enter" || event.nativeEvent.isComposing || event.keyCode === 229)
179163
return;
@@ -193,7 +177,7 @@ export function BranchPicker({
193177
<div className="relative flex min-h-0 w-full max-h-56 flex-1 flex-col overflow-hidden">
194178
<ComboboxListVirtualized className="flex size-full min-h-0 min-w-0 flex-col">
195179
<LegendList<string>
196-
ref={branchListRef}
180+
ref={attachBranchList}
197181
data={filteredItems}
198182
keyExtractor={(item) => item}
199183
{...(getItemType ? { getItemType } : {})}

‎apps/web/src/components/BranchToolbarBranchSelector.tsx‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -652,7 +652,6 @@ export function BranchToolbarBranchSelector({
652652
onSelectItem={selectPickerItem}
653653
value={resolvedActiveBranch}
654654
query={branchQuery}
655-
resultsQuery={deferredTrimmedBranchQuery}
656655
onQueryChange={setBranchQuery}
657656
hasNextPage={hasNextPage}
658657
isFetchingNextPage={isFetchingNextPage}
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
import { describe, expect, it } from "vite-plus/test";
2+
import { page } from "vite-plus/test/browser";
3+
4+
import { render } from "../../test/render";
5+
import { openCommandPalette } from "../commandPaletteBus";
6+
import { useCommandPaletteStore } from "../commandPaletteStore";
7+
import { CommandPalette } from "./CommandPalette";
8+
9+
function setup() {
10+
useCommandPaletteStore.setState(useCommandPaletteStore.getInitialState(), true);
11+
}
12+
13+
describe("CommandPalette open intents", () => {
14+
it("opens New thread in... with focus in the search input, not the Back button", async () => {
15+
setup();
16+
await using _screen = await render(<CommandPalette>{null}</CommandPalette>);
17+
18+
openCommandPalette({ open: "new-thread-in" });
19+
20+
await expect.element(page.getByPlaceholder("Search...")).toHaveFocus();
21+
});
22+
23+
it("opens a search intent with its query in the focused input", async () => {
24+
setup();
25+
await using _screen = await render(<CommandPalette>{null}</CommandPalette>);
26+
27+
openCommandPalette({ query: "acme" });
28+
29+
const input = page.getByPlaceholder("Search commands, projects, and threads...");
30+
await expect.element(input).toHaveFocus();
31+
await expect.element(input).toHaveValue("acme");
32+
});
33+
});

0 commit comments

Comments
 (0)