Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(search): keep ⌘K selection on the top row as results land (MUL-10220) (#11584)
Jiayuan Zhang62ee7f498878
diff --git a/packages/views/search/search-command.test.tsx b/packages/views/search/search-command.test.tsxindex 553dcf516c..3202abaae1 100644--- a/packages/views/search/search-command.test.tsx+++ b/packages/views/search/search-command.test.tsx@@ -1587,4 +1587,99 @@ describe("SearchCommand", () => {expect(useSearchStore.getState().open).toBe(true);});});++ // MUL-10220: cmdk picks the first enabled row when the input changes, which+ // is often a local doc title hit while issue rows are still loading.+ describe("selection while results land", () => {+ const runbookIssue = {+ ...makeIssue({ id: "issue-runbook", identifier: "MUL-300", title: "Runbook checklist" }),+ match_source: "title",+ };+ let resolveIssues: (() => void) | null = null;++ const typeRunbook = async (user: ReturnType<typeof userEvent.setup>) => {+ seed(docTreeOptions("ws-test"), {+ folders: [],+ docs: [+ { id: "doc-release", title: "Release runbook", folderId: null },+ { id: "doc-oncall", title: "Oncall runbook", folderId: null },+ ],+ });+ api("searchIssues").mockImplementation(({ q }: { q: string }) =>+ q === "runbook"+ ? new Promise((resolve) => {+ resolveIssues = () => resolve({ issues: [runbookIssue], total: 1 });+ })+ : Promise.resolve({ issues: [], total: 0 }),+ );+ renderSearch();+ await user.type(input(), "runbook");+ await waitFor(() => expect(selectedValue()).toBe("doc:doc-release"));+ };++ const landIssues = async () => {+ await waitFor(() => expect(resolveIssues).not.toBeNull());+ await act(async () => resolveIssues!());+ await waitFor(() => expect(renderedValues()[0]).toBe("issue-runbook"));+ };++ beforeEach(() => {+ resolveIssues = null;+ });++ it("moves the selection to the top row when higher-ranked results arrive", async () => {+ const user = userEvent.setup();+ await typeRunbook(user);+ await landIssues();++ expect(selectedValue()).toBe("issue-runbook");+ fireEvent.keyDown(input(), { key: "n", ctrlKey: true });+ expect(selectedValue()).toBe("doc:doc-release");+ fireEvent.keyDown(input(), { key: "p", ctrlKey: true });+ expect(selectedValue()).toBe("issue-runbook");+ });++ it("keeps a row the user moved to while results land", async () => {+ const user = userEvent.setup();+ await typeRunbook(user);+ fireEvent.keyDown(input(), { key: "n", ctrlKey: true });+ expect(selectedValue()).toBe("doc:doc-oncall");+ await landIssues();++ expect(selectedValue()).toBe("doc:doc-oncall");+ });++ it("scrolls the list back to the top row it selects", async () => {+ const user = userEvent.setup();+ await typeRunbook(user);+ const list = document.querySelector<HTMLElement>("[cmdk-list]")!;+ list.scrollTop = 120;+ await landIssues();++ expect(selectedValue()).toBe("issue-runbook");+ expect(list.scrollTop).toBe(0);+ });++ it("ignores pointer moves over headings and disabled rows", async () => {+ const user = userEvent.setup();+ await typeRunbook(user);+ fireEvent.pointerMove(screen.getByText("Docs"));+ const handRow = document.querySelector<HTMLElement>('[cmdk-item=""][data-value="hand-to-agent"]')!;+ expect(handRow).toHaveAttribute("aria-disabled", "true");+ fireEvent.pointerMove(handRow);+ await landIssues();++ expect(selectedValue()).toBe("issue-runbook");+ });++ it("keeps a row the pointer moved to while results land", async () => {+ const user = userEvent.setup();+ await typeRunbook(user);+ fireEvent.pointerMove(document.querySelector('[cmdk-item=""][data-value="doc:doc-oncall"]')!);+ expect(selectedValue()).toBe("doc:doc-oncall");+ await landIssues();++ expect(selectedValue()).toBe("doc:doc-oncall");+ });+ });});diff --git a/packages/views/search/search-command.tsx b/packages/views/search/search-command.tsxindex d9da9e29ae..c30499e4c5 100644--- a/packages/views/search/search-command.tsx+++ b/packages/views/search/search-command.tsx@@ -157,6 +157,13 @@ function PaletteBody({}const PALETTE_NAV_DURATION = 0.14;+const ENABLED_ITEM = '[cmdk-item=""]:not([aria-disabled="true"])';++/** Keys cmdk moves the selection on: arrows, and ⌃N/⌃J/⌃P/⌃K. */+function isSelectionKey(e: Pick<KeyboardEvent, "key" | "ctrlKey">) {+ if (e.key === "ArrowDown" || e.key === "ArrowUp") return true;+ return e.ctrlKey && (e.key === "n" || e.key === "j" || e.key === "p" || e.key === "k");+}/** Everything that reads the palette API lives under its provider. */function PaletteFrame({@@ -184,6 +191,12 @@ function PaletteFrame({// The selected row's value. cmdk picks the first row only when it is empty.const [selected, setSelected] = useState("");+ // cmdk picks the first enabled row when the input changes, while the new+ // query's server rows are still loading and disabled, and keeps that pick+ // when they land above it. Until the user moves the selection, the effect+ // below keeps it on the top row.+ const selectionMovedRef = useRef(false);+ const selectionScopeRef = useRef("");const inputRef = useRef<HTMLInputElement>(null);const listRef = useRef<HTMLDivElement>(null);@@ -198,6 +211,11 @@ function PaletteFrame({}const navDirection = navDirectionRef.current;const pageKey = current ? `${stack.length}:${current.page.type}` : "root";+ const selectionScope = `${pageKey}\n${inputValue}`;+ if (selectionScope !== selectionScopeRef.current) {+ selectionScopeRef.current = selectionScope;+ selectionMovedRef.current = false;+ }const [listHeight, setListHeight] = useState<number | undefined>(undefined);const [animateHeight, setAnimateHeight] = useState(false);@@ -265,6 +283,18 @@ function PaletteFrame({// items and search results from clearing on frame 1 of the exit animation.const model = useRootModel(rawQuery, contexts, { active: true });+ useLayoutEffect(() => {+ const list = listRef.current;+ if (!active || !list || selectionMovedRef.current) return;+ const first = list.querySelector(ENABLED_ITEM);+ const value = first?.getAttribute("data-value");+ if (!first || !value || value === selected) return;+ setSelected(value);+ // cmdk scrolls only selections it makes itself, and this one lands first.+ list.scrollTop = 0;+ first.scrollIntoView({ block: "nearest" });+ }, [active, selected, model, current, pageQuery]);+const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {// cmdk's root handler intercepts Home/End for list navigation; stop// propagation so the browser moves the text caret instead.@@ -292,6 +322,7 @@ function PaletteFrame({if (e.key === "Enter") {recordIntent({ button: 0, metaKey: e.metaKey, ctrlKey: e.ctrlKey, shiftKey: e.shiftKey });}+ if (isSelectionKey(e)) selectionMovedRef.current = true;}}className="flex size-full flex-col overflow-hidden rounded-xl bg-popover text-popover-foreground">@@ -337,6 +368,10 @@ function PaletteFrame({<CommandPrimitive.Listref={listRef}+ // cmdk selects the enabled row under a moving pointer, and nothing else.+ onPointerMove={(e) => {+ if ((e.target as Element).closest(ENABLED_ITEM)) selectionMovedRef.current = true;+ }}style={listHeight !== undefined ? { height: listHeight } : undefined}className={cn("max-h-[min(440px,55vh)] overflow-y-auto overflow-x-hidden py-1",