Skip to content

graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs

Python

Fix folder picker keyboard result navigation

yxlyx9e6becab0fb5
diff --git a/apps/native/components/site/FolderPicker.tsx b/apps/native/components/site/FolderPicker.tsx
index c1cb9913..eaf47d19 100644
--- a/apps/native/components/site/FolderPicker.tsx
+++ b/apps/native/components/site/FolderPicker.tsx
@@ -1,6 +1,6 @@
"use client";
-import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";
+import { useCallback, useEffect, useId, useLayoutEffect, useMemo, useRef, useState, type ReactNode } from "react";
import {
cycleFolderSort,
displayDirPath,
@@ -13,6 +13,7 @@ import {
sameDir,
saveFolderView,
splitFolderQuery,
+ stepFolderSelection,
uniqueFolderName,
type FolderSort,
type FolderView,
@@ -72,15 +73,20 @@ export function FolderPicker({ startPath, onPick, onClose }: { startPath?: strin
const [busy, setBusy] = useState(false);
const [view, setView] = useState<FolderView>(() => loadFolderView(typeof localStorage === "undefined" ? null : localStorage));
const [creating, setCreating] = useState<string | null>(null);
+ const [active, setActive] = useState<number | null>(null);
// Only the newest navigation may land: a slow listing of a big folder
// must not overwrite the one the user has already moved on to.
const seq = useRef(0);
const pickRef = useRef(onPick);
pickRef.current = onPick;
const creatingRef = useRef(false);
+ const results = useRef<HTMLDivElement>(null);
+ const keyboard = useRef(false);
+ const listId = useId();
const go = useCallback(async (target: string, opts: { pick?: boolean; refresh?: boolean } = {}) => {
const n = (seq.current += 1);
const refresh = opts.refresh === true;
+ setActive(null);
if (!refresh) setBusy(true);
setError(null);
try {
@@ -122,6 +128,18 @@ export function FolderPicker({ startPath, onPick, onClose }: { startPath?: strin
() => (listing ? presentFolderEntries(listing.entries, parsed.needle, view) : []),
[listing, parsed.needle, view],
);
+ const activeEntry = active == null ? undefined : shown[active];
+ useLayoutEffect(() => {
+ if (active == null || !keyboard.current) return;
+ keyboard.current = false;
+ const viewport = results.current;
+ const row = viewport?.querySelector<HTMLElement>(`[data-folder-index="${active}"]`);
+ if (!viewport || !row) return;
+ const viewportRect = viewport.getBoundingClientRect();
+ const rowRect = row.getBoundingClientRect();
+ if (rowRect.top < viewportRect.top) viewport.scrollTop -= viewportRect.top - rowRect.top;
+ else if (rowRect.bottom > viewportRect.bottom) viewport.scrollTop += rowRect.bottom - viewportRect.bottom;
+ }, [active]);
const crumbs = listing ? listing.path.split("/").filter(Boolean) : [];
const crumbPath = (i: number) => `/${crumbs.slice(0, i + 1).join("/")}`;
@@ -130,6 +148,7 @@ export function FolderPicker({ startPath, onPick, onClose }: { startPath?: strin
const beginCreate = () => {
if (!listing) return;
+ setActive(null);
const needle = parsed.needle.trim();
const base = needle && folderNameError(needle) == null ? needle : "untitled folder";
setView((current) => (current.gitOnly ? { ...current, gitOnly: false } : current));
@@ -176,11 +195,30 @@ export function FolderPicker({ startPath, onPick, onClose }: { startPath?: strin
// Editing an explicit lookup retires it and makes the new path
// actionable immediately, even if the old folder is still loading.
if (busy) { seq.current++; setBusy(false); }
+ setActive(null);
+ keyboard.current = false;
+ if (results.current) results.current.scrollTop = 0;
setTyped(event.target.value); setError(null);
}}
+ onKeyDown={(event) => {
+ if (event.nativeEvent.isComposing) return;
+ if (event.key === "ArrowDown" || event.key === "ArrowUp") {
+ event.preventDefault();
+ keyboard.current = shown.length > 0;
+ setActive((current) => stepFolderSelection(shown.length, current, event.key === "ArrowDown" ? "down" : "up"));
+ } else if (event.key === "Enter" && activeEntry) {
+ event.preventDefault();
+ void go(activeEntry.path);
+ }
+ }}
spellCheck={false}
autoFocus
+ role="combobox"
aria-label="Folder path"
+ aria-autocomplete="list"
+ aria-expanded={listing != null}
+ aria-controls={listId}
+ aria-activedescendant={activeEntry ? `${listId}-folder-${active}` : undefined}
placeholder="/path/to/project"
className={`${FIELD} font-mono text-[12.5px]`}
/>
@@ -205,14 +243,20 @@ export function FolderPicker({ startPath, onPick, onClose }: { startPath?: strin
<Chip
active={view.sort === "name"}
title={sortTitle("name", view)}
- onClick={() => setView((current) => cycleFolderSort(current, "name"))}
+ onClick={() => {
+ setActive(null);
+ setView((current) => cycleFolderSort(current, "name"));
+ }}
>
Name
</Chip>
<Chip
active={view.sort === "modified"}
title={sortTitle("modified", view)}
- onClick={() => setView((current) => cycleFolderSort(current, "modified"))}
+ onClick={() => {
+ setActive(null);
+ setView((current) => cycleFolderSort(current, "modified"));
+ }}
>
Modified
</Chip>
@@ -221,7 +265,10 @@ export function FolderPicker({ startPath, onPick, onClose }: { startPath?: strin
active={view.gitOnly}
pressed={view.gitOnly}
title={view.gitOnly ? "Showing git repositories. Click to show every folder." : "Only git repositories"}
- onClick={() => setView((current) => ({ ...current, gitOnly: !current.gitOnly }))}
+ onClick={() => {
+ setActive(null);
+ setView((current) => ({ ...current, gitOnly: !current.gitOnly }));
+ }}
>
Git
</Chip>
@@ -251,7 +298,7 @@ export function FolderPicker({ startPath, onPick, onClose }: { startPath?: strin
)}
</div>
- <div className="min-h-0 flex-1 overflow-y-auto" style={{ minHeight: 200 }}>
+ <div ref={results} className="min-h-0 flex-1 overflow-y-auto" style={{ minHeight: 200 }}>
{busy && <p role="status" className="px-4 py-3 text-[12.5px] text-ink-3">Reading folder…</p>}
{error && <p role="alert" className="px-4 py-3 text-[12.5px] text-red">{error}</p>}
{!listing && !busy && !error && <p className="px-4 py-3 text-[12.5px] text-ink-3">Press Enter to browse, or open this folder directly.</p>}
@@ -317,42 +364,53 @@ export function FolderPicker({ startPath, onPick, onClose }: { startPath?: strin
/>
</form>
)}
- {shown.map((entry) => (
- <div
- key={entry.path}
- className="group flex h-8 items-center gap-2 rounded-[7px] px-2 transition-colors duration-100 hover:bg-hover"
- >
- <button
- type="button"
- onClick={() => void go(entry.path)}
- title={entry.path}
- className="flex min-w-0 flex-1 items-center gap-2 text-left"
- >
- <span className={`flex size-4 shrink-0 items-center justify-center ${entry.git ? "text-accent-ink" : "text-ink-3"}`}>
- <IconFolder size={14} />
- </span>
- <span className="min-w-0 flex-1 truncate text-[13px] text-ink">{entry.name}</span>
- </button>
- {view.sort === "modified" && entry.mtime > 0 && (
- <span className="shrink-0 font-mono text-[11px] text-ink-3 tabular-nums" title={formatFolderModified(entry.mtime)}>
- {formatFolderAge(entry.mtime)}
- </span>
- )}
- {entry.git && <GitBadge />}
- <button
- type="button"
- onClick={() => onPick(entry.path)}
- className="h-6 shrink-0 rounded-[6px] px-1.5 text-[11.5px] font-medium text-ink-3 opacity-0 transition-[opacity,background-color,color] duration-100 group-hover:opacity-100 hover:bg-hover-2 hover:text-ink focus:opacity-100"
+ <div id={listId} role="listbox" aria-label="Matching folders" className="flex flex-col">
+ {shown.map((entry, index) => (
+ <div
+ key={entry.path}
+ data-folder-index={index}
+ onPointerMove={() => {
+ keyboard.current = false;
+ setActive(index);
+ }}
+ className={`group flex h-8 items-center gap-2 rounded-[7px] px-2 transition-colors duration-100 ${index === active ? "bg-hover" : "hover:bg-hover"}`}
>
- Use
- </button>
- </div>
- ))}
- {shown.length === 0 && creating == null && (
- <p className="px-2 py-2 text-[12.5px] text-ink-3">
- {parsed.needle ? "No folders match this name." : view.gitOnly ? "No git folders here" : "No folders here"}
- </p>
- )}
+ <button
+ id={`${listId}-folder-${index}`}
+ type="button"
+ role="option"
+ aria-selected={index === active}
+ onFocus={() => setActive(index)}
+ onClick={() => void go(entry.path)}
+ title={entry.path}
+ className="flex min-w-0 flex-1 items-center gap-2 text-left"
+ >
+ <span className={`flex size-4 shrink-0 items-center justify-center ${entry.git ? "text-accent-ink" : "text-ink-3"}`}>
+ <IconFolder size={14} />
+ </span>
+ <span className="min-w-0 flex-1 truncate text-[13px] text-ink">{entry.name}</span>
+ </button>
+ {view.sort === "modified" && entry.mtime > 0 && (
+ <span className="shrink-0 font-mono text-[11px] text-ink-3 tabular-nums" title={formatFolderModified(entry.mtime)}>
+ {formatFolderAge(entry.mtime)}
+ </span>
+ )}
+ {entry.git && <GitBadge />}
+ <button
+ type="button"
+ onClick={() => onPick(entry.path)}
+ className="h-6 shrink-0 rounded-[6px] px-1.5 text-[11.5px] font-medium text-ink-3 opacity-0 transition-[opacity,background-color,color] duration-100 group-hover:opacity-100 hover:bg-hover-2 hover:text-ink focus:opacity-100"
+ >
+ Use
+ </button>
+ </div>
+ ))}
+ {shown.length === 0 && creating == null && (
+ <p className="px-2 py-2 text-[12.5px] text-ink-3">
+ {parsed.needle ? "No folders match this name." : view.gitOnly ? "No git folders here" : "No folders here"}
+ </p>
+ )}
+ </div>
</div>
)}
</div>
diff --git a/apps/native/electron/projects-visual.cjs b/apps/native/electron/projects-visual.cjs
index 727fc102..d4326fc3 100644
--- a/apps/native/electron/projects-visual.cjs
+++ b/apps/native/electron/projects-visual.cjs
@@ -69,11 +69,25 @@ async function runProjectVisuals({ win, origin, output }) {
await js(`document.querySelector('button[aria-label="Files"]').click()`);
await wait(`!!document.querySelector('[aria-label="Workspace files"]')`);
assert.equal(await js(`!!document.querySelector('[aria-label="Workspace changes"]')`), false);
+ await js(`(()=>{window.folderPickerFetch=window.fetch;window.fetch=(input,options)=>{const url=new URL(String(input),location.origin);if(url.pathname!='/api/workspaces'||options?.method)return window.folderPickerFetch(input,options);const requested=(url.searchParams.get('path')||'/demo/folder-42').replace(/\\/+$/,'');const entries=requested.endsWith('/meld-v3')||requested.endsWith('/melody')?[]:[{name:'meld-v3',path:requested+'/meld-v3',git:true,mtime:2},{name:'melody',path:requested+'/melody',git:false,mtime:1}];return Promise.resolve(new Response(JSON.stringify({path:requested+'/',parent:'/demo',git:false,home:'/demo',default:'/demo/folder-42',entries}),{headers:{'content-type':'application/json'}}));};})()`);
await js(`document.querySelector('button[aria-label="Open folder…"]').click()`);
- await wait(`!!document.querySelector('[role="dialog"][aria-label="Open a folder"]')`);
+ const folderDialog = '[role="dialog"][aria-label="Open a folder"]';
+ await wait(`document.querySelectorAll('${folderDialog} [role="option"]').length===2`);
+ await js(`(()=>{const e=document.querySelector('${folderDialog} input[aria-label="Folder path"]'),base=e.value.replace(/\\/+$/,'');e.focus();Object.getOwnPropertyDescriptor(HTMLInputElement.prototype,'value').set.call(e,base+'/mel');e.dispatchEvent(new Event('input',{bubbles:true}));})()`);
+ await wait(`document.querySelectorAll('${folderDialog} [role="option"]').length===2`);
+ await js(`document.querySelector('${folderDialog} input[aria-label="Folder path"]').dispatchEvent(new KeyboardEvent('keydown',{key:'ArrowDown',bubbles:true,cancelable:true}))`);
+ const firstFolder = await js(`document.querySelector('${folderDialog} input[aria-label="Folder path"]').getAttribute('aria-activedescendant')`);
+ await js(`document.querySelector('${folderDialog} input[aria-label="Folder path"]').dispatchEvent(new KeyboardEvent('keydown',{key:'ArrowDown',bubbles:true,cancelable:true}))`);
+ const secondFolder = await js(`document.querySelector('${folderDialog} input[aria-label="Folder path"]').getAttribute('aria-activedescendant')`);
+ assert.ok(firstFolder && secondFolder && firstFolder !== secondFolder, 'ArrowDown moves the active folder result');
+ const selectedPath = await js(`document.getElementById(${JSON.stringify(secondFolder)}).title`);
+ await js(`document.querySelector('${folderDialog} input[aria-label="Folder path"]').dispatchEvent(new KeyboardEvent('keydown',{key:'Enter',bubbles:true,cancelable:true}))`);
+ await wait(`document.querySelector('${folderDialog} input[aria-label="Folder path"]').value===${JSON.stringify(selectedPath + '/')}`);
+ assert.equal(await js(`document.activeElement===document.querySelector('${folderDialog} input[aria-label="Folder path"]')`), true, 'keyboard folder navigation keeps focus in the path field');
+ await js(`window.fetch=window.folderPickerFetch;delete window.folderPickerFetch`);
// Unmount the picker before navigating: an in-flight listing + loadURL
// left the renderer unable to run the next suite's scripts.
- await js(`document.querySelector('[role="dialog"][aria-label="Open a folder"] button[aria-label="Close"]').click()`);
+ await js(`document.querySelector('${folderDialog} button[aria-label="Close"]').click()`);
await wait(`!document.querySelector('[role="dialog"][aria-label="Open a folder"]')`);
await wc.loadURL(origin);
await wait(`!!document.querySelector('[data-workspace-ready="true"] textarea[aria-label="Prompt"]')`);
diff --git a/apps/native/lib/folder-picker.test.ts b/apps/native/lib/folder-picker.test.ts
index 782c2ad3..2c631e08 100644
--- a/apps/native/lib/folder-picker.test.ts
+++ b/apps/native/lib/folder-picker.test.ts
@@ -16,6 +16,7 @@ import {
sameDir,
saveFolderView,
splitFolderQuery,
+ stepFolderSelection,
uniqueFolderName,
} from "./folder-picker.ts";
@@ -98,6 +99,18 @@ describe("rankFolderEntries", () => {
});
});
+describe("stepFolderSelection", () => {
+ it("starts from the nearest end, clamps, and leaves an empty list unselected", () => {
+ assert.equal(stepFolderSelection(3, null, "down"), 0);
+ assert.equal(stepFolderSelection(3, null, "up"), 2);
+ assert.equal(stepFolderSelection(3, 0, "up"), 0);
+ assert.equal(stepFolderSelection(3, 0, "down"), 1);
+ assert.equal(stepFolderSelection(3, 2, "down"), 2);
+ assert.equal(stepFolderSelection(0, null, "down"), null);
+ assert.equal(stepFolderSelection(0, 0, "up"), null);
+ });
+});
+
describe("presentFolderEntries", () => {
const entries = [
{ name: "zeta", path: "/demo/zeta", git: false, mtime: 400 },
diff --git a/apps/native/lib/folder-picker.ts b/apps/native/lib/folder-picker.ts
index 586f40f1..95d2e85d 100644
--- a/apps/native/lib/folder-picker.ts
+++ b/apps/native/lib/folder-picker.ts
@@ -99,6 +99,20 @@ export function rankFolderEntries<T extends RankableFolder>(entries: readonly T[
return scored.map((row) => row.item);
}
+/** Move an explicit keyboard selection through the visible folder results.
+ * A null selection preserves Enter's typed-path behavior until an arrow key
+ * chooses the first (Down) or last (Up) result. */
+export function stepFolderSelection(
+ length: number,
+ active: number | null,
+ direction: "up" | "down",
+): number | null {
+ if (length <= 0) return null;
+ if (active == null) return direction === "down" ? 0 : length - 1;
+ const delta = direction === "down" ? 1 : -1;
+ return Math.max(0, Math.min(length - 1, active + delta));
+}
+
export function parseFolderView(raw: unknown): FolderView {
if (!raw || typeof raw !== "object") return { ...DEFAULT_FOLDER_VIEW };
const rec = raw as Record<string, unknown>;