fix(app): drive the directory picker with explicit state machines (#61934)

This commit is contained in:
Luke Parker 2026-11-04 23:00:38 -06:00 • committed by GitHub
parent 602725f572
commit 795ffefd85
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
8 changed files with 1737 additions and 437 deletions

View file

@ -1,8 +1,74 @@
import { expect, test } from "@playwright/test"
import { expect, test, type Page } from "@playwright/test"
import { holdRoute } from "../utils/app"
import type { MockServerConfig } from "../utils/mock-server"
import { fileNode, openSettings } from "../utils/workspace"
test.use({ viewport: { width: 1440, height: 900 } })
const directory = "C:/OpenCode/Picker"
// Opens the folder picker from Settings > Projects once its root has listed.
async function openPicker(page: Page, input: Pick<MockServerConfig, "fileList" | "findFiles">) {
await openSettings(page, { name: "Picker", seed: { tabs: [] }, ...input })
await page.getByTestId("settings-screen").getByRole("tab", { name: "Projects", exact: true }).click()
await page.getByRole("button", { name: "Add project", exact: true }).click()
const picker = page.getByRole("dialog", { name: "Open project", exact: true })
await expect(picker.getByRole("button", { name: "Select folder", exact: true })).toBeEnabled()
return picker
}
test("Tab and Enter while suggestions load act on the typed folder, not the previous suggestions", async ({ page }) => {
const picker = await openPicker(page, {
fileList: (path) =>
path === directory ? ["alpha", "beta"].map((name) => fileNode(directory, name, "directory")) : [],
findFiles: (input) => ["alpha", "beta"].filter((name) => input.query.length >= 3 && name.startsWith(input.query)),
})
const input = picker.getByRole("combobox")
await input.fill("alp")
await expect(picker.getByRole("option")).toHaveText(["C:\\OpenCode\\Picker\\alpha/"])
const search = await holdRoute(page, /\/api\/fs\/find\?(.*&)?query=beta(&|$)/)
await input.fill("beta")
await search.arrived
await expect(picker.getByRole("option")).toHaveCount(0)
await input.press("Tab")
await expect(input).toHaveValue("beta")
await input.press("Enter")
await expect(input).toHaveValue("C:\\OpenCode\\Picker\\beta\\")
await expect(picker.locator(".directory-picker-selection-text")).toHaveText("C:\\…\\Picker\\beta")
search.release()
})
test("a folder that cannot be listed leaves the root readable and retries when expanded", async ({ page }) => {
let failures = 0
const picker = await openPicker(page, {
fileList: (path) => {
if (path === `${directory}/locked`) {
failures += 1
return Promise.reject(new Error("Permission denied"))
}
return path === directory ? ["locked", "open"].map((name) => fileNode(directory, name, "directory")) : []
},
})
// The root preloads its folders, so the locked one fails once before the user touches it.
await expect.poll(() => failures).toBe(1)
await picker.getByRole("treeitem", { name: "locked", exact: true }).click()
await expect.poll(() => failures).toBe(2)
await expect(picker.getByText("Unable to read this folder")).toHaveCount(0)
await expect(picker.getByRole("treeitem", { name: "open", exact: true })).toBeVisible()
await expect(picker.getByRole("button", { name: "Select folder", exact: true })).toBeEnabled()
})
test("the folder picker's tree scrolls with the mouse wheel inside the modal", async ({ page }) => {
const directory = "/projects/big"
let listing = false

View file

@ -0,0 +1,225 @@
import { expect, test } from "bun:test"
import {
createPickerComboboxState,
pickerComboboxView,
transitionPickerCombobox,
type PickerComboboxContext,
type PickerComboboxEvent,
type PickerComboboxState,
type PickerComboboxTransition,
type PickerSuggestion,
} from "./combobox-machine"
import { pickerMode } from "./domain"
const context: PickerComboboxContext = {
policy: pickerMode("directory"),
home: "/home/luke",
root: "/projects",
fallback: "/home/luke",
locationDirectory: "/projects",
}
const key = (name: string, options: { shiftKey?: boolean; composing?: boolean } = {}): PickerComboboxEvent => ({
type: "key.down",
key: name,
shiftKey: options.shiftKey ?? false,
composing: options.composing ?? false,
})
const directory = (absolute: string): PickerSuggestion => ({ absolute, type: "directory" })
function run(events: PickerComboboxEvent[], state = createPickerComboboxState(), input = context) {
return events.reduce<PickerComboboxTransition>(
(current, event) => transitionPickerCombobox(current.state, event, input),
{ state, effects: [], preventDefault: false, stopPropagation: false },
)
}
function attempt(state: PickerComboboxState) {
return state.status === "disposed" ? 0 : state.attempt
}
// Types `input` and resolves its search with `items`.
function opened(input: string, items: PickerSuggestion[]) {
const typed = run([{ type: "input.changed", value: input }])
return run([{ type: "search.resolved", attempt: attempt(typed.state), items }], typed.state).state
}
test("Enter while the next query searches submits the typed path, not the previous query's first result", () => {
const old = opened("/projects/old", [directory("/projects/old-repo")])
const typed = run([{ type: "input.changed", value: "/projects/new" }], old)
const entered = run([key("Enter")], typed.state)
expect(typed.state.status).toBe("loading")
expect(pickerComboboxView(typed.state).items).toEqual([])
expect(entered.preventDefault).toBeTrue()
expect(entered.effects).toEqual([{ type: "search.cancel" }, { type: "choose.directory", path: "/projects/new" }])
expect(entered.state).toEqual({ status: "closed", attempt: attempt(typed.state), input: "/projects/new/" })
})
test("Tab while the next query searches completes nothing", () => {
const old = opened("/projects/old", [directory("/projects/old-repo")])
const typed = run([{ type: "input.changed", value: "/projects/new" }], old)
const tabbed = run([key("Tab")], typed.state)
expect(tabbed.state).toBe(typed.state)
expect(tabbed.effects).toEqual([])
expect(tabbed.preventDefault).toBeFalse()
})
test("results of an earlier search never open the list for later input", () => {
const first = run([{ type: "input.changed", value: "/projects/old" }])
const second = run([{ type: "input.changed", value: "/projects/new" }], first.state)
const late = run([{ type: "search.resolved", attempt: attempt(first.state), items: [directory("/x")] }], second.state)
expect(second.effects).toEqual([
{ type: "selection.clear" },
{ type: "search.start", attempt: attempt(first.state) + 1, query: "/projects/new", timeoutMs: 10_000 },
])
expect(late.state).toBe(second.state)
})
test.each([
["~/op", 0],
["~/opencode/", -1],
["C:\\Users\\luke\\", -1],
["~", -1],
["~/", -1],
["/", -1],
])("%p highlights suggestion %p until the user steps", (input, active) => {
const items = [directory("/home/luke/opencode"), directory("/home/luke/opera")]
const state = opened(input, items)
const entered = run([key("Enter")], state)
expect(pickerComboboxView(state).active).toBe(active)
expect(entered.effects.at(-1)).toEqual({
type: "choose.directory",
path: active === 0 ? "/home/luke/opencode" : input,
})
expect(pickerComboboxView(run([key("ArrowDown")], state).state).active).toBe(active === 0 ? 1 : 0)
})
test("arrow keys wrap through the list and reopen a closed list after a search", () => {
const state = opened("~/op", [directory("/home/luke/a"), directory("/home/luke/b")])
const up = run([key("ArrowUp")], state)
const closed = run([key("Escape")], state)
const reopening = run([key("ArrowDown")], closed.state)
expect(pickerComboboxView(up.state).active).toBe(1)
expect(up.preventDefault).toBeTrue()
expect(reopening.state).toMatchObject({ status: "loading", step: 1 })
expect(reopening.effects).toEqual([
{ type: "search.start", attempt: attempt(state) + 1, query: "~/op", timeoutMs: 10_000 },
])
const resolved = run(
[{ type: "search.resolved", attempt: attempt(reopening.state), items: [directory("/a"), directory("/b")] }],
reopening.state,
)
expect(pickerComboboxView(resolved.state).active).toBe(1)
})
test("Escape closes an open list without reaching the dialog, and otherwise passes through", () => {
const state = opened("~/op", [directory("/home/luke/a")])
const escaped = run([key("Escape")], state)
const passed = run([key("Escape")], escaped.state)
expect(escaped).toMatchObject({
state: { status: "closed", input: "~/op" },
preventDefault: true,
stopPropagation: true,
})
expect(passed).toMatchObject({ preventDefault: false, stopPropagation: false })
expect(passed.state).toBe(escaped.state)
})
test("Shift+Tab and IME Enter pass through", () => {
const state = opened("~/op", [directory("/home/luke/a")])
expect(run([key("Tab", { shiftKey: true })], state)).toMatchObject({ preventDefault: false, effects: [] })
expect(run([key("Enter", { composing: true })], state)).toMatchObject({ preventDefault: false, effects: [] })
})
test("hovering the active item again keeps the same state", () => {
const state = opened("~/op", [directory("/home/luke/a"), directory("/home/luke/b")])
const hovered = run([{ type: "item.hovered", index: 1 }], state)
expect(pickerComboboxView(hovered.state).active).toBe(1)
expect(run([{ type: "item.hovered", index: 1 }], hovered.state).state).toBe(hovered.state)
expect(run([{ type: "item.hovered", index: 5 }], hovered.state).state).toBe(hovered.state)
})
test("Tab completes a folder and searches inside it, and chooses a file", () => {
const files = { ...context, policy: pickerMode("file", "/projects") }
const state = opened("~/op", [directory("/home/luke/opencode")])
const folder = run([key("Tab")], state)
const file = { absolute: "/projects/src/index.ts", type: "file" as const }
const typed = run([{ type: "input.changed", value: "src/in" }], createPickerComboboxState(), files)
const listed = run([{ type: "search.resolved", attempt: attempt(typed.state), items: [file] }], typed.state, files)
expect(folder.preventDefault).toBeTrue()
expect(folder.state).toMatchObject({ status: "loading", input: "~/opencode/" })
expect(folder.effects).toEqual([
{ type: "search.start", attempt: attempt(state) + 1, query: "~/opencode/", timeoutMs: 10_000 },
])
for (const event of [key("Tab"), { type: "item.clicked", index: 0 } as const]) {
const chosen = run([event], listed.state, files)
expect(chosen.state).toMatchObject({ status: "closed", input: "/projects/src/index.ts" })
expect(chosen.effects).toEqual([{ type: "choose.file", absolute: file.absolute }])
}
})
test("clicking a folder suggestion chooses it and shows it as the input", () => {
const state = opened("~/op", [directory("/home/luke/opencode")])
const clicked = run([{ type: "item.clicked", index: 0 }], state)
expect(clicked.state).toMatchObject({ status: "closed", input: "~/opencode/" })
expect(clicked.effects).toEqual([{ type: "choose.directory", path: "/home/luke/opencode" }])
})
test("input typed before the location resolves searches once the location arrives", () => {
const booting = { ...context, root: "", locationDirectory: undefined }
const typed = run([{ type: "input.changed", value: "~/op" }], createPickerComboboxState(), booting)
const located = run([{ type: "context.changed" }], typed.state)
expect(typed.state).toMatchObject({ status: "open", input: "~/op", items: [] })
expect(typed.effects).toEqual([{ type: "selection.clear" }])
expect(located.state).toMatchObject({ status: "loading", input: "~/op" })
expect(located.effects).toEqual([
{ type: "search.start", attempt: attempt(typed.state) + 1, query: "~/op", timeoutMs: 10_000 },
])
expect(run([{ type: "context.changed" }], createPickerComboboxState()).state.status).toBe("closed")
})
test.each(["search.failed", "search.timed-out"] as const)("%s opens an empty list", (type) => {
const typed = run([{ type: "input.changed", value: "~/op" }])
const settled = run([{ type, attempt: attempt(typed.state) }], typed.state)
expect(settled.state).toMatchObject({ status: "open", items: [], active: null })
expect(pickerComboboxView(settled.state).listboxOpen).toBeFalse()
expect(settled.effects).toEqual(type === "search.timed-out" ? [{ type: "search.cancel" }] : [])
})
test("clearing, dismissing and disposing cancel a running search", () => {
const typed = run([{ type: "input.changed", value: "~/op" }])
const cleared = run([{ type: "cleared" }], typed.state)
const dismissed = run([{ type: "dismissed" }], typed.state)
const disposed = run([{ type: "disposed" }], typed.state)
expect(cleared).toMatchObject({ state: { status: "closed", input: "" }, effects: [{ type: "search.cancel" }] })
expect(dismissed).toMatchObject({ state: { status: "closed", input: "~/op" }, effects: [{ type: "search.cancel" }] })
expect(disposed).toMatchObject({ state: { status: "disposed" }, effects: [{ type: "search.cancel" }] })
expect(run([{ type: "input.changed", value: "x" }], disposed.state).state).toBe(disposed.state)
expect(run([{ type: "cleared" }], cleared.state).state).toBe(cleared.state)
})
test("input equal to the open root has nothing to suggest", () => {
const typed = run([{ type: "input.changed", value: "/projects/" }])
expect(typed.state).toMatchObject({ status: "open", items: [] })
expect(typed.effects).toEqual([{ type: "selection.clear" }])
})

View file

@ -0,0 +1,292 @@
import {
cleanPickerInput,
displayInputDirectory,
displayPickerPath,
nextSuggestionIndex,
resolvePickerTarget,
type PickerPolicy,
} from "./domain"
/** Bounded fallback so a hung search cannot keep suggestions loading forever. */
export const PICKER_SEARCH_TIMEOUT_MS = 10_000
export type PickerSuggestion = { readonly absolute: string; readonly type: "file" | "directory" }
/** What the input resolves and searches against. `fallback` is the base for relative input before a root opens. */
export type PickerComboboxContext = {
readonly policy: PickerPolicy
readonly home: string
readonly root: string
readonly fallback: string
readonly locationDirectory: string | undefined
}
/**
* The path input and its suggestion list. Only `open` holds items, and only for its `input`, so a key pressed while the
* next search runs never acts on the previous query's results. `active` is null until the user steps or hovers;
* `step` is an arrow key pressed while the search runs.
*/
export type PickerComboboxState =
| { readonly status: "closed"; readonly attempt: number; readonly input: string }
| { readonly status: "loading"; readonly attempt: number; readonly input: string; readonly step?: -1 | 1 }
| {
readonly status: "open"
readonly attempt: number
readonly input: string
readonly items: readonly PickerSuggestion[]
readonly active: number | null
}
| { readonly status: "disposed" }
export type PickerComboboxEvent =
| { readonly type: "input.changed"; readonly value: string }
| { readonly type: "cleared" }
| { readonly type: "dismissed" }
| { readonly type: "context.changed" }
| { readonly type: "item.hovered"; readonly index: number }
| { readonly type: "item.clicked"; readonly index: number }
| { readonly type: "key.down"; readonly key: string; readonly shiftKey: boolean; readonly composing: boolean }
| { readonly type: "search.resolved"; readonly attempt: number; readonly items: readonly PickerSuggestion[] }
| { readonly type: "search.failed"; readonly attempt: number }
| { readonly type: "search.timed-out"; readonly attempt: number }
| { readonly type: "disposed" }
export type PickerComboboxEffect =
| { readonly type: "search.start"; readonly attempt: number; readonly query: string; readonly timeoutMs: number }
| { readonly type: "search.cancel" }
| { readonly type: "selection.clear" }
| { readonly type: "choose.directory"; readonly path: string }
| { readonly type: "choose.file"; readonly absolute: string }
export type PickerComboboxTransition = {
readonly state: PickerComboboxState
readonly effects: readonly PickerComboboxEffect[]
readonly preventDefault: boolean
readonly stopPropagation: boolean
}
type LiveCombobox = Exclude<PickerComboboxState, { status: "disposed" }>
type OpenCombobox = Extract<PickerComboboxState, { status: "open" }>
export function createPickerComboboxState(): PickerComboboxState {
return { status: "closed", attempt: 0, input: "" }
}
export function transitionPickerCombobox(
state: PickerComboboxState,
event: PickerComboboxEvent,
context: PickerComboboxContext,
): PickerComboboxTransition {
if (state.status === "disposed") return unchanged(state)
if (event.type === "disposed") return result({ status: "disposed" }, cancel(state))
if (event.type === "input.changed") {
const input = cleanPickerInput(event.value)
// Trailing whitespace cleans to the same input; the running search or open list still matches it.
if (input === state.input && (state.status !== "closed" || !input)) {
return result(state, [{ type: "selection.clear" }])
}
return withInput(state, input, context, [{ type: "selection.clear" }])
}
if (event.type === "cleared") {
if (state.status === "closed" && !state.input) return unchanged(state)
return result({ status: "closed", attempt: state.attempt, input: "" }, cancel(state))
}
if (event.type === "dismissed") {
if (state.status === "closed") return unchanged(state)
return result(close(state, state.input), cancel(state))
}
if (event.type === "context.changed") {
if (state.status === "closed") return unchanged(state)
return withInput(state, state.input, context, [])
}
if (event.type === "search.resolved" || event.type === "search.failed" || event.type === "search.timed-out") {
if (state.status !== "loading" || event.attempt !== state.attempt) return unchanged(state)
const items = event.type === "search.resolved" ? event.items : []
const open: OpenCombobox = { status: "open", attempt: state.attempt, input: state.input, items, active: null }
const effects = event.type === "search.timed-out" ? cancel(state) : []
return result(state.step && items.length > 0 ? step(open, state.step) : open, effects)
}
if (event.type === "item.hovered") {
if (state.status !== "open" || state.active === event.index || !state.items[event.index]) return unchanged(state)
return result({ ...state, active: event.index })
}
if (event.type === "item.clicked") {
const item = state.status === "open" ? state.items[event.index] : undefined
if (!item) return unchanged(state)
return choose(state, item, context)
}
return key(state, event, context)
}
export function effectiveActiveIndex(state: PickerComboboxState) {
if (state.status !== "open" || state.items.length === 0) return -1
if (state.active !== null) return state.active
// Input that names a folder ("~", "~/", "/", "src/", "C:\\Users\\") submits that folder unless the user steps.
return state.input === "~" || /[\\/]$/.test(state.input) ? -1 : 0
}
// Input equal to the open root has nothing to suggest, and searches need a server location.
export function canSearchPickerInput(input: string, context: PickerComboboxContext) {
if (!input || !context.locationDirectory) return false
if (!context.root) return true
return input.replace(/\/+$/, "") !== displayPickerPath(context.root, input, context.home).replace(/\/+$/, "")
}
export function pickerComboboxView(state: PickerComboboxState) {
const items = state.status === "open" ? state.items : []
const active = effectiveActiveIndex(state)
return {
input: state.status === "disposed" ? "" : state.input,
items,
listboxOpen: items.length > 0,
active,
activeDescendant: active >= 0 ? `directory-picker-suggestion-${active}` : undefined,
}
}
function key(
state: LiveCombobox,
event: Extract<PickerComboboxEvent, { type: "key.down" }>,
context: PickerComboboxContext,
): PickerComboboxTransition {
const items = state.status === "open" ? state.items : []
if (event.key === "Escape") {
if (state.status !== "open" || items.length === 0) return unchanged(state)
return { ...result(close(state, state.input)), preventDefault: true, stopPropagation: true }
}
if (event.key === "Tab") {
if (event.shiftKey || state.status !== "open" || items.length === 0) return unchanged(state)
const match = items[state.active ?? 0] ?? items[0]!
if (match.type === "file") return handled(choose(state, match, context))
const value = displayPickerPath(match.absolute, state.input, context.home)
return handled(withInput(state, value.endsWith("/") ? value : value + "/", context, []))
}
if (event.key === "ArrowDown" || event.key === "ArrowUp") {
const delta = event.key === "ArrowDown" ? 1 : -1
if (state.status === "open") return items.length > 0 ? handled(result(step(state, delta))) : unchanged(state)
if (state.status === "loading") return handled(result({ ...state, step: delta }))
if (!canSearchPickerInput(state.input, context)) return unchanged(state)
const searching = withInput(state, state.input, context, [])
return handled(
searching.state.status === "loading" ? { ...searching, state: { ...searching.state, step: delta } } : searching,
)
}
if (event.key !== "Enter" || event.composing) return unchanged(state)
const active = effectiveActiveIndex(state)
if (state.status === "open" && active >= 0) return handled(choose(state, state.items[active]!, context))
const value = state.input ? resolve(state.input, context) : undefined
if (!value) return handled(unchanged(state))
return handled(
result(close(state, displayInputDirectory(value, context.home)), [
...cancel(state),
{ type: "choose.directory", path: state.input },
]),
)
}
function choose(state: LiveCombobox, item: PickerSuggestion, context: PickerComboboxContext) {
if (item.type === "file") {
return result(close(state, displayPickerPath(item.absolute, state.input, context.home)), [
...cancel(state),
{ type: "choose.file", absolute: item.absolute },
])
}
const value = resolve(item.absolute, context)
if (!value) return unchanged(state)
return result(close(state, displayInputDirectory(value, context.home)), [
...cancel(state),
{ type: "choose.directory", path: item.absolute },
])
}
function withInput(
state: LiveCombobox,
input: string,
context: PickerComboboxContext,
effects: readonly PickerComboboxEffect[],
): PickerComboboxTransition {
if (!input) return result(close(state, ""), [...cancel(state), ...effects])
if (!canSearchPickerInput(input, context)) {
return result({ status: "open", attempt: state.attempt, input, items: [], active: null }, [
...cancel(state),
...effects,
])
}
const attempt = state.attempt + 1
return result({ status: "loading", attempt, input }, [
...effects,
{ type: "search.start", attempt, query: input, timeoutMs: PICKER_SEARCH_TIMEOUT_MS },
])
}
function step(state: OpenCombobox, delta: -1 | 1): OpenCombobox {
return { ...state, active: nextSuggestionIndex(effectiveActiveIndex(state), delta, state.items.length) }
}
function resolve(path: string, context: PickerComboboxContext) {
return resolvePickerTarget(context.policy, path, context.home, context.root || context.fallback)
}
function close(state: LiveCombobox, input: string): PickerComboboxState {
return { status: "closed", attempt: state.attempt, input }
}
function cancel(state: PickerComboboxState): PickerComboboxEffect[] {
return state.status === "loading" ? [{ type: "search.cancel" }] : []
}
function handled(transition: PickerComboboxTransition): PickerComboboxTransition {
return { ...transition, preventDefault: true }
}
function result(state: PickerComboboxState, effects: readonly PickerComboboxEffect[] = []): PickerComboboxTransition {
return { state, effects, preventDefault: false, stopPropagation: false }
}
function unchanged(state: PickerComboboxState): PickerComboboxTransition {
return result(state)
}

View file

@ -12,9 +12,7 @@ import {
import { TextInput } from "@opencode/ui/text-input"
import { Tooltip } from "@opencode/ui/tooltip"
import { useDialog } from "@opencode/ui/context/dialog"
import { getFilename } from "@opencode/util/path"
import { createEffect, createMemo, createResource, For, onCleanup, onMount, Show } from "solid-js"
import { createStore } from "solid-js/store"
import { createEffect, createMemo, createSignal, For, on, onCleanup, onMount, Show, untrack } from "solid-js"
import { useServer } from "@/runtime/server/current"
import { inferHomeDirectory } from "@/runtime/server/global-sync/bootstrap"
import { useLanguage } from "@/runtime/i18n/language"
@ -23,16 +21,11 @@ import { pathKey } from "@/workspaces/path-key"
import type { LocationRef } from "@opencode/client/promise"
import {
absoluteTreePath,
activeTreeNavigation,
canonicalPickerPath,
nextSuggestionIndex,
pickerFileSearchQuery,
pickerAbsoluteInput,
pickerMode,
cleanPickerInput,
createPriorityTaskQueue,
createDirectorySearch,
currentPickerSuggestions,
displayPickerPath,
shortenPickerRecentPath,
pickerParent,
@ -41,6 +34,23 @@ import {
pickerRelativePath,
pickerAbsolutePath,
} from "./domain"
import {
createPickerTreeState,
hasPickerGitRepo,
pickerTreeView,
transitionPickerTree,
type PickerNode,
type PickerTreeEffect,
type PickerTreeEvent,
} from "./tree-machine"
import {
createPickerComboboxState,
pickerComboboxView,
transitionPickerCombobox,
type PickerComboboxEffect,
type PickerComboboxEvent,
type PickerSuggestion,
} from "./combobox-machine"
import "./dialog.css"
const TREE_SPRITE_SHEET = `<svg xmlns="http://www.w3.org/2000/svg" data-icon-sprite aria-hidden="true" width="0" height="0" style="display:none"><symbol id="picker-chevron-down" viewBox="0 0 14 14"><path d="M4 5.5L7 8.5L10 5.5" fill="none" stroke="currentColor"/></symbol></svg>`
@ -73,24 +83,22 @@ export function DirectoryPickerDialog(props: DirectoryPickerDialogProps) {
directory: language.t("dialog.directory.action.selectFolder"),
}
const [state, setState] = createStore({
root: "",
input: "",
selected: "",
suggestionsOpen: false,
activeSuggestion: -1,
loading: false,
error: false,
rootValid: false,
// One signal holds both immutable machine states, so a write replaces them whole and never merges into shared objects.
const [machines, setMachines] = createSignal({
tree: createPickerTreeState(),
combobox: createPickerComboboxState(),
})
const listings = new Map<string, Promise<Array<{ name: string; type: "file" | "directory" }> | undefined>>()
const loads = createPriorityTaskQueue<Array<{ name: string; type: "file" | "directory" }> | undefined>(3)
const gitRepos = new Set<string>()
const treeMachine = createMemo(() => machines().tree)
const treeView = createMemo(() => pickerTreeView(treeMachine(), policy))
const treeRoot = createMemo(() => treeView().root)
const comboboxView = createMemo(() => pickerComboboxView(machines().combobox))
const loads = createPriorityTaskQueue<PickerNode[]>(3)
const treeTimers = new Set<ReturnType<typeof setTimeout>>()
let activeSearch: { controller: AbortController; timer: ReturnType<typeof setTimeout> } | undefined
let tree: FileTree | undefined
let container: HTMLDivElement | undefined
let pathArea: HTMLDivElement | undefined
let navigation = 0
const knownGitRepos = createMemo(() => {
const keys = new Set<string>()
@ -110,12 +118,6 @@ export function DirectoryPickerDialog(props: DirectoryPickerDialogProps) {
return keys
})
const [fallbackPath] = createResource(
() => (props.location ? undefined : true),
() => sdk.api.location.get().catch(() => undefined),
{ initialValue: undefined },
)
const home = createMemo(
() =>
sync.data.path.home || inferHomeDirectory(props.location?.directory ?? ""),
@ -123,19 +125,19 @@ export function DirectoryPickerDialog(props: DirectoryPickerDialogProps) {
const subtitle = createMemo(() => (servers.local(props.server) ? undefined : serverName(props.server)))
const location = createMemo(() => {
const current = props.location ?? fallbackPath.latest
const location = createMemo(
() => {
const directory = props.location?.directory ?? treeView().locationDirectory
return current ? { directory: current.directory } : undefined
})
return directory ? { directory } : undefined
},
undefined,
{ equals: (previous, next) => previous?.directory === next?.directory },
)
const start = createMemo(
() =>
props.start ||
home() ||
props.location?.directory ||
sync.data.path.directory ||
fallbackPath.latest?.directory,
props.start || home() || props.location?.directory || sync.data.path.directory || treeView().locationDirectory,
)
const recentProjects = createMemo(() => {
@ -156,369 +158,250 @@ export function DirectoryPickerDialog(props: DirectoryPickerDialogProps) {
.slice(0, 5)
})
const search = createDirectorySearch({ sdk, home, location, base: () => state.root || start() })
const [suggestions] = createResource(
() => state.input,
async (value) => {
const cleaned = cleanPickerInput(value)
const typed = cleaned.replace(/\/+$/, "")
const current = displayPickerPath(state.root, value, home()).replace(/\/+$/, "")
if (!cleaned || (state.root && typed === current)) return { query: value, items: [] }
const directories = (await search(value)).map((absolute) => ({ absolute, type: "directory" as const }))
if (!policy.includeFiles) return { query: value, items: directories.slice(0, 5) }
const base = location()?.directory
if (!base) return { query: value, items: directories.slice(0, 5) }
const query = pickerRelativePath(base, pickerAbsoluteInput(cleaned, home(), state.root || base))
if (query === undefined) return { query: value, items: directories.slice(0, 5) }
const files = await sdk.api.file
.find({
location: location(),
query,
type: "file",
limit: 20,
})
.then((result) => result.data)
.catch(() => [])
const results = [
...directories,
...files.map((entry) => ({ absolute: pickerAbsolutePath(entry.path, base), type: "file" as const })),
]
return {
query: value,
items: Array.from(new Map(results.map((result) => [result.absolute, result])).values()).slice(0, 8),
}
},
)
const currentSuggestions = createMemo(() =>
currentPickerSuggestions(suggestions.latest, state.input, suggestions.loading),
)
const resolvedResult = createMemo(() => policy.result(state.root, state.selected, state.rootValid))
const search = createDirectorySearch({ sdk, home, location, base: () => treeView().root || start() })
const fullSelectionPath = createMemo(() => {
const value = resolvedResult()
const value = treeView().result
return value ? displayPickerPath(value, "", home()) : ""
})
const shortSelectionPath = createMemo(() => {
const value = resolvedResult()
const value = treeView().result
return value ? shortenPickerRecentPath(value, home()) : ""
})
async function load(path: string, generation: number, priority: "user" | "background" = "user") {
const key = path.replace(/\/+$/, "")
setState("error", false)
const absolute = absoluteTreePath(state.root, key)
const existing = listings.get(key)
function navigation(path: string) {
return { path, home: home(), fallback: start() || home(), located: Boolean(location()) }
}
if (existing && priority === "user") loads.promote(`${generation}:${key}`)
function dispatchTree(event: PickerTreeEvent) {
untrack(() => {
const previous = machines().tree
const next = transitionPickerTree(previous, event, policy)
const request =
existing ??
loads.schedule(`${generation}:${key}`, priority, () => {
if (!activeTreeNavigation(generation, navigation)) return Promise.resolve(undefined)
const current = location()
if (next.state !== previous) setMachines((current) => ({ ...current, tree: next.state }))
next.effects.forEach(
(effect) => void Promise.try(() => runTreeEffect(effect)).catch((cause: unknown) => console.error(cause)),
)
})
}
if (!current) return Promise.resolve(undefined)
function dispatchCombobox(event: PickerComboboxEvent) {
return untrack(() => {
const previous = machines().combobox
return listPickerDirectory(sdk, current, absolute).catch(() => undefined)
const next = transitionPickerCombobox(previous, event, {
policy,
home: home(),
root: treeView().root,
fallback: start() || home(),
locationDirectory: location()?.directory,
})
listings.set(key, request)
const nodes = await request
if (!activeTreeNavigation(generation, navigation)) return false
if (!nodes) {
listings.delete(key)
if (!key) setState("error", true)
return false
}
const isRepo = nodes.some((node) => node.name === ".git")
const repoKey = pathKey(canonicalPickerPath(absolute))
const newlyDiscoveredRepo = isRepo && !gitRepos.has(repoKey)
if (newlyDiscoveredRepo) gitRepos.add(repoKey)
const entries = policy
.entries(
key,
nodes.filter((node) => node.name !== ".git"),
if (next.state !== previous) setMachines((current) => ({ ...current, combobox: next.state }))
next.effects.forEach(
(effect) => void Promise.try(() => runComboboxEffect(effect)).catch((cause: unknown) => console.error(cause)),
)
.filter((item) => !tree?.getItem(item))
if (entries.length > 0) {
tree?.batch(entries.map((item) => ({ type: "add", path: item })))
}
return next
})
}
if (newlyDiscoveredRepo) {
tree?.setComposition(tree.getComposition())
}
// Preloading the root's folders makes their first expand instant and finds git repos for the badge.
if (!key && priority === "user") {
for (const node of nodes) {
if (node.type === "directory" && node.name !== ".git") void load(node.name, generation, "background")
function runTreeEffect(effect: PickerTreeEffect) {
if (effect.type === "resolve-location") {
const settle = (event: Extract<PickerTreeEvent, { attempt: number }>) => {
clearTimeout(timer)
treeTimers.delete(timer)
dispatchTree(event)
}
}
return true
}
const timer = setTimeout(() => settle({ type: "location.timed-out", attempt: effect.attempt }), effect.timeoutMs)
function displayInputDirectory(path: string) {
const displayed = displayPickerPath(path, state.input, home())
const separator = displayed.includes("\\") ? "\\" : "/"
return displayed.endsWith(separator) ? displayed : displayed + separator
}
function expandTreeDirectory(path: string) {
const item = tree?.getItem(`${path}/`)
if (item && "expand" in item && !item.isExpanded()) item.expand()
}
function selectOnlyTreeItem(entry: string) {
for (const selectedPath of tree?.getSelectedPaths() ?? []) {
if (selectedPath !== entry) tree?.getItem(selectedPath)?.deselect()
}
tree?.getItem(entry)?.select()
tree?.focusPath(entry)
// The tree measures newly expanded rows after this frame, so an immediate scroll clamps to the old height.
requestAnimationFrame(() => tree?.scrollToPath(entry, { offset: "center" }))
}
async function navigate(path: string, options?: { selectChild?: string; input?: string }) {
const value = policy.navigation(
pickerAbsoluteInput(cleanPickerInput(path), home(), state.root || start() || home()),
)
if (!value) return
const token = ++navigation
setState({
loading: true,
rootValid: false,
selected: "",
suggestionsOpen: false,
activeSuggestion: -1,
root: value,
input: options?.input ?? "",
})
listings.clear()
tree?.resetPaths([])
const valid = await load("", token)
if (!activeTreeNavigation(token, navigation)) return
setState({
rootValid: valid,
loading: false,
})
if (!valid) return
if (!options?.selectChild) {
if (!tree?.getFocusedPath()) tree?.focusNearestPath(null)
treeTimers.add(timer)
void Promise.try(() => sdk.api.location.get()).then(
(current) => settle({ type: "location.resolved", attempt: effect.attempt, directory: current?.directory }),
() => settle({ type: "location.failed", attempt: effect.attempt }),
)
return
}
const entry = `${getFilename(options.selectChild)}/`
selectOnlyTreeItem(entry)
setState("selected", policy.selection(value, entry) ?? options.selectChild)
}
if (effect.type === "list") {
const failed = { type: "dir.failed" as const, dir: effect.dir, attempt: effect.attempt }
async function selectDirectory(path: string, options?: { fromInput?: boolean }) {
const value = policy.navigation(
pickerAbsoluteInput(cleanPickerInput(path), home(), state.root || start() || home()),
)
void loads
.schedule(String(effect.attempt), effect.priority, (signal) => {
const current = location()
if (!value) return
const nextInput = options?.fromInput ? displayInputDirectory(value) : state.input
const relative = state.root && state.rootValid ? pickerRelativePath(state.root, value) : undefined
if (!current) return Promise.reject(new Error("The picker has no server location"))
if (relative === "") {
// The timeout starts when the listing does, so preloads waiting in the queue cannot expire. Aborting the
// job cancels the request and frees its queue slot, so hung listings cannot block the next root.
const timer = setTimeout(() => {
treeTimers.delete(timer)
dispatchTree({ type: "dir.timed-out", dir: effect.dir, attempt: effect.attempt })
loads.abort(String(effect.attempt))
}, effect.timeoutMs)
treeTimers.add(timer)
return listPickerDirectory(sdk, current, absoluteTreePath(effect.root, effect.dir), signal).finally(() => {
clearTimeout(timer)
treeTimers.delete(timer)
})
})
.then(
(nodes) =>
dispatchTree(nodes ? { type: "dir.loaded", dir: effect.dir, attempt: effect.attempt, nodes } : failed),
() => dispatchTree(failed),
)
return
}
if (effect.type === "promote") return loads.promote(String(effect.attempt))
if (effect.type === "queue.reset") {
loads.clear()
treeTimers.forEach((timer) => clearTimeout(timer))
treeTimers.clear()
return
}
if (effect.type === "tree.reset") return tree?.resetPaths([])
if (effect.type === "tree.add") {
const paths = effect.paths.filter((path) => !tree?.getItem(path))
if (paths.length > 0) tree?.batch(paths.map((path) => ({ type: "add", path })))
return
}
if (effect.type === "tree.expand") {
const item = tree?.getItem(`${effect.dir}/`)
if (item && "expand" in item && !item.isExpanded()) item.expand()
return
}
if (effect.type === "tree.select") {
for (const selectedPath of tree?.getSelectedPaths() ?? []) {
if (selectedPath !== effect.entry) tree?.getItem(selectedPath)?.deselect()
}
tree?.getItem(effect.entry)?.select()
tree?.focusPath(effect.entry)
// The tree measures newly expanded rows after this frame, so an immediate scroll clamps to the old height.
requestAnimationFrame(() => tree?.scrollToPath(effect.entry, { offset: "center" }))
return
}
if (effect.type === "tree.clear-selection") {
for (const selectedPath of tree?.getSelectedPaths() ?? []) {
tree?.getItem(selectedPath)?.deselect()
}
tree?.focusNearestPath(null)
setState({
selected: "",
suggestionsOpen: false,
activeSuggestion: -1,
input: nextInput,
})
return
}
if (relative) {
const token = navigation
const segments = relative.split("/").filter(Boolean)
const entry = `${relative}/`
setState({
suggestionsOpen: false,
activeSuggestion: -1,
input: nextInput,
})
if (effect.type === "tree.focus-initial") {
if (!tree?.getFocusedPath()) tree?.focusNearestPath(null)
const ancestors = segments.slice(0, -1).map((_, index) => segments.slice(0, index + 1).join("/"))
return
}
for (const ancestor of ancestors) {
const loaded = await load(ancestor, token)
tree?.setComposition(tree.getComposition())
}
if (!activeTreeNavigation(token, navigation)) return
function runComboboxEffect(effect: PickerComboboxEffect) {
if (effect.type === "search.start") {
stopSearch()
const controller = new AbortController()
if (!loaded) break
expandTreeDirectory(ancestor)
const settle = (event: Extract<PickerComboboxEvent, { attempt: number }>) => {
if (activeSearch?.controller === controller) stopSearch()
dispatchCombobox(event)
}
if (!tree?.getItem(entry)) {
await navigate(value, { input: nextInput })
return
activeSearch = {
controller,
timer: setTimeout(() => settle({ type: "search.timed-out", attempt: effect.attempt }), effect.timeoutMs),
}
selectOnlyTreeItem(entry)
setState("selected", policy.selection(state.root, entry) ?? value)
if (!options?.fromInput) return
expandTreeDirectory(relative)
await load(relative, token)
void Promise.try(() => suggestions(effect.query, controller.signal)).then(
(items) => settle({ type: "search.resolved", attempt: effect.attempt, items }),
() => settle({ type: "search.failed", attempt: effect.attempt }),
)
return
}
const parent = pickerParent(value)
const leaf = getFilename(value)
if (effect.type === "search.cancel") return stopSearch()
if (parent && leaf && parent !== value && parent === home()) {
await navigate(parent, { selectChild: value, input: nextInput })
if (effect.type === "selection.clear") return dispatchTree({ type: "selection.cleared" })
return
if (effect.type === "choose.directory") {
return dispatchTree({ type: "directory.chosen", ...navigation(effect.path), fromInput: true })
}
await navigate(value, { input: nextInput })
dispatchTree({ type: "file.chosen", absolute: effect.absolute, home: home() })
}
function complete() {
const items = currentSuggestions()
const match = items[state.activeSuggestion] ?? items[0]
function stopSearch() {
if (!activeSearch) return
activeSearch.controller.abort()
clearTimeout(activeSearch.timer)
activeSearch = undefined
}
if (!match) return
const value = displayPickerPath(match.absolute, state.input, home())
setState("input", match.type === "directory" && !value.endsWith("/") ? value + "/" : value)
async function suggestions(value: string, signal: AbortSignal): Promise<PickerSuggestion[]> {
const directories = (await search(value, { signal })).map((absolute) => ({ absolute, type: "directory" as const }))
if (match.type === "file") {
setState({
selected: policy.selection(state.root, pickerFileSearchQuery(state.root, match.absolute, home())) ?? "",
suggestionsOpen: false,
activeSuggestion: -1,
if (!policy.includeFiles) return directories.slice(0, 5)
const current = location()
const base = current?.directory
if (!base) return directories.slice(0, 5)
const query = pickerRelativePath(base, pickerAbsoluteInput(value, home(), treeView().root || base))
if (query === undefined || signal.aborted) return directories.slice(0, 5)
const files = await sdk.api.file
.find({
location: current,
query,
type: "file",
limit: 20,
})
}
.then((result) => result.data)
.catch(() => [])
const results = [
...directories,
...files.map((entry) => ({ absolute: pickerAbsolutePath(entry.path, base), type: "file" as const })),
]
return Array.from(new Map(results.map((result) => [result.absolute, result])).values()).slice(0, 8)
}
function chooseSuggestion(suggestion: { absolute: string; type: "file" | "directory" }) {
if (suggestion.type === "directory") {
void selectDirectory(suggestion.absolute, { fromInput: true })
// A root the mode does not allow (a file picker's parent outside its base) keeps the input as it was.
function navigate(path: string) {
const previous = untrack(machines).tree
dispatchTree({ type: "navigate", ...navigation(path) })
return
}
setState({
input: displayPickerPath(suggestion.absolute, state.input, home()),
selected: policy.selection(state.root, pickerFileSearchQuery(state.root, suggestion.absolute, home())) ?? "",
suggestionsOpen: false,
activeSuggestion: -1,
})
}
function moveSuggestion(delta: -1 | 1) {
setState("suggestionsOpen", true)
setState("activeSuggestion", nextSuggestionIndex(activeSuggestionIndex(), delta, currentSuggestions().length))
}
function activeSuggestionIndex() {
if (!state.suggestionsOpen) return -1
if (state.activeSuggestion >= 0) return state.activeSuggestion
const raw = cleanPickerInput(state.input)
if (raw === "~" || raw === "~/" || raw === "/" || raw.endsWith("/")) return -1
return currentSuggestions().length > 0 ? 0 : -1
}
function activeSuggestionValue() {
return currentSuggestions()[activeSuggestionIndex()]
}
const keyActions = new Map([
["ArrowDown", () => moveSuggestion(1)],
["ArrowUp", () => moveSuggestion(-1)],
[
"Enter",
() => {
const suggestion = activeSuggestionValue()
if (suggestion) {
chooseSuggestion(suggestion)
return
}
if (state.input.trim()) void selectDirectory(state.input, { fromInput: true })
},
],
["Tab", complete],
])
function handleInputKey(event: KeyboardEvent) {
if (event.key === "Escape" && state.suggestionsOpen && currentSuggestions().length > 0) {
event.preventDefault()
event.stopPropagation()
setState({
suggestionsOpen: false,
activeSuggestion: -1,
})
return
}
if (event.key === "Tab") {
if (event.shiftKey || !state.suggestionsOpen || currentSuggestions().length === 0) return
event.preventDefault()
complete()
return
}
if ((event.key === "ArrowDown" || event.key === "ArrowUp") && currentSuggestions().length === 0) return
const action = keyActions.get(event.key)
if (!action) return
event.preventDefault()
action()
if (untrack(machines).tree !== previous) dispatchCombobox({ type: "cleared" })
}
function resolve() {
const path = resolvedResult()
const path = treeView().result
if (!path) return
props.onSelect(props.multiple ? [path] : path)
@ -528,10 +411,7 @@ export function DirectoryPickerDialog(props: DirectoryPickerDialogProps) {
onMount(() => {
const closeSuggestions = (event: PointerEvent) => {
if (event.target instanceof Node && pathArea?.contains(event.target)) return
setState({
suggestionsOpen: false,
activeSuggestion: -1,
})
dispatchCombobox({ type: "dismissed" })
}
document.addEventListener("pointerdown", closeSuggestions)
@ -555,9 +435,13 @@ export function DirectoryPickerDialog(props: DirectoryPickerDialogProps) {
},
renderRowDecoration(context) {
if (context.row.kind !== "directory") return null
const key = pathKey(canonicalPickerPath(absoluteTreePath(state.root, context.item.path)))
const current = untrack(machines).tree
if (!gitRepos.has(key) && !knownGitRepos().has(key)) return null
const key = pathKey(
canonicalPickerPath(absoluteTreePath(pickerTreeView(current, policy).root, context.item.path)),
)
if (!hasPickerGitRepo(current, context.item.path) && !knownGitRepos().has(key)) return null
return { text: language.t("dialog.directory.gitRepo") }
},
@ -651,11 +535,10 @@ export function DirectoryPickerDialog(props: DirectoryPickerDialogProps) {
}
`,
onExpansionChange(change) {
if (change.expanded) void load(change.path, navigation)
if (change.expanded) dispatchTree({ type: "dir.expanded", dir: change.path })
},
onSelectionChange(paths) {
const path = paths.at(-1)
setState("selected", path ? (policy.selection(state.root, path) ?? "") : "")
dispatchTree({ type: "tree.selected", path: paths.at(-1) })
},
})
@ -664,14 +547,28 @@ export function DirectoryPickerDialog(props: DirectoryPickerDialogProps) {
tree.getFileTreeContainer()?.classList.add("directory-picker-tree")
})
// Opens the first root. Without a dialog location the tree first resolves the server's default one.
createEffect(() => {
if (treeMachine().status !== "booting") return
if (!location()) return dispatchTree({ type: "location.requested" })
const path = start()
if (!path || !location() || state.root) return
void navigate(path)
if (path) dispatchTree({ type: "navigate", ...navigation(path) })
})
onCleanup(() => tree?.cleanUp())
// Suggestions search against the root and location, so a search started before either arrived runs again.
createEffect(
on([() => location()?.directory, treeRoot], () => dispatchCombobox({ type: "context.changed" }), {
defer: true,
}),
)
onCleanup(() => {
dispatchTree({ type: "disposed" })
dispatchCombobox({ type: "disposed" })
tree?.cleanUp()
})
return (
<Dialog size="large" fit class="directory-picker">
@ -691,67 +588,67 @@ export function DirectoryPickerDialog(props: DirectoryPickerDialogProps) {
<DialogBody class="directory-picker-body">
<div class="directory-picker-path" ref={pathArea}>
<TextInput
value={state.input}
value={comboboxView().input}
placeholder={language.t("dialog.directory.search.placeholder")}
autofocus
autocomplete="off"
spellcheck={false}
showClearButton={!!state.input}
onClearClick={() => {
setState({
input: "",
suggestionsOpen: false,
activeSuggestion: -1,
})
}}
showClearButton={!!comboboxView().input}
onClearClick={() => dispatchCombobox({ type: "cleared" })}
class="directory-picker-input"
onInput={(event) => {
setState({
input: cleanPickerInput(event.currentTarget.value),
selected: "",
suggestionsOpen: true,
activeSuggestion: -1,
})
}}
onInput={(event) => dispatchCombobox({ type: "input.changed", value: event.currentTarget.value })}
role="combobox"
aria-label={language.t("dialog.directory.search.placeholder")}
aria-autocomplete="list"
aria-expanded={state.suggestionsOpen}
aria-expanded={comboboxView().listboxOpen}
aria-controls="directory-picker-suggestions"
aria-activedescendant={
activeSuggestionIndex() >= 0 ? `directory-picker-suggestion-${activeSuggestionIndex()}` : undefined
}
onKeyDown={handleInputKey}
aria-activedescendant={comboboxView().activeDescendant}
onKeyDown={(event) => {
const next = dispatchCombobox({
type: "key.down",
key: event.key,
shiftKey: event.shiftKey,
composing: event.isComposing,
})
if (next.preventDefault) event.preventDefault()
if (next.stopPropagation) event.stopPropagation()
}}
/>
<div class="directory-picker-actions">
<Button size="normal" variant="ghost" onClick={() => void navigate(home() || state.root)}>
<Button size="normal" variant="ghost" onClick={() => navigate(home() || treeView().root)}>
~
</Button>
<Button size="normal" variant="ghost" onClick={() => void navigate(pickerRoot(state.root) || state.root)}>
<Button
size="normal"
variant="ghost"
onClick={() => navigate(pickerRoot(treeView().root) || treeView().root)}
>
{language.t("dialog.directory.root")}
</Button>
<Button
size="normal"
variant="ghost"
onClick={() => void navigate(pickerParent(state.selected || state.root))}
onClick={() => navigate(pickerParent(treeView().selected || treeView().root))}
>
{language.t("dialog.directory.parent")}
</Button>
</div>
<Show when={state.suggestionsOpen && currentSuggestions().length > 0}>
<Show when={comboboxView().listboxOpen}>
<div id="directory-picker-suggestions" role="listbox" class="directory-picker-suggestions">
<For each={currentSuggestions()}>
<For each={comboboxView().items}>
{(suggestion, index) => (
<button
id={`directory-picker-suggestion-${index()}`}
data-directory-path={suggestion.absolute}
role="option"
aria-selected={index() === activeSuggestionIndex()}
data-active={index() === activeSuggestionIndex() ? "" : undefined}
onPointerMove={() => setState("activeSuggestion", index())}
onClick={() => chooseSuggestion(suggestion)}
aria-selected={index() === comboboxView().active}
data-active={index() === comboboxView().active ? "" : undefined}
onPointerMove={() => dispatchCombobox({ type: "item.hovered", index: index() })}
onClick={() => dispatchCombobox({ type: "item.clicked", index: index() })}
>
{displayPickerPath(suggestion.absolute, state.input, home())}
{displayPickerPath(suggestion.absolute, comboboxView().input, home())}
{suggestion.type === "directory" ? "/" : ""}
</button>
)}
@ -779,7 +676,10 @@ export function DirectoryPickerDialog(props: DirectoryPickerDialogProps) {
name: name(),
path: shortPath(),
})}
onClick={() => void selectDirectory(project.worktree)}
onClick={() => {
dispatchCombobox({ type: "dismissed" })
dispatchTree({ type: "directory.chosen", ...navigation(project.worktree), fromInput: false })
}}
>
<ProjectAvatar
class="shrink-0"
@ -805,10 +705,10 @@ export function DirectoryPickerDialog(props: DirectoryPickerDialogProps) {
on:touchmove={(event) => event.stopPropagation()}
on:wheel={{ handleEvent: (event: WheelEvent) => event.stopPropagation(), passive: true }}
>
<Show when={state.loading}>
<Show when={treeView().loading}>
<div class="directory-picker-state">{language.t("common.loading")}</div>
</Show>
<Show when={!state.loading && state.error}>
<Show when={treeView().error}>
<div class="directory-picker-state">{language.t("dialog.directory.readError")}</div>
</Show>
</div>
@ -827,7 +727,7 @@ export function DirectoryPickerDialog(props: DirectoryPickerDialogProps) {
<Button variant="neutral" onClick={() => dialog.close()}>
{language.t("common.cancel")}
</Button>
<Button variant="contrast" disabled={!resolvedResult()} onClick={resolve}>
<Button variant="contrast" disabled={!treeView().result} onClick={resolve}>
{action[policy.action]}
</Button>
</DialogFooter>

View file

@ -1,14 +1,12 @@
import { expect, test } from "bun:test"
import {
absoluteTreePath,
activeTreeNavigation,
nextSuggestionIndex,
pickerFileSearchQuery,
pickerMode,
selectedTreePath,
treeEntries,
treePathWithin,
currentPickerSuggestions,
createDirectorySearch,
createPriorityTaskQueue,
listPickerDirectory,
@ -21,9 +19,11 @@ import {
type Sdk = Parameters<typeof listPickerDirectory>[0]
// The picker only reads `api.file.find` and `api.file.list`.
const sdk = (file: { find?: (input: never) => Promise<unknown>; list?: (input: never) => Promise<unknown> }) =>
({ api: { file } }) as unknown as Sdk
type FileApi = { find?: (input: never) => Promise<object>; list?: (input: never, options: never) => Promise<object> }
// SAFETY: the picker only reads `api.file.find` and `api.file.list`, which every fake here provides.
// oxlint-disable-next-line anti-slop/no-chained-type-assertions -- a partial fake stands in for the generated SDK client
const sdk = (file: FileApi) => ({ api: { file } }) as unknown as Sdk
test("maps server directory entries into Pierre paths", () => {
expect(
@ -142,13 +142,6 @@ test.each([
expect(actual).toBe(expected)
})
test("exposes autocomplete results only for their source query", () => {
const result = { query: "/repo/src", items: ["/repo/src/index.ts"] }
expect(currentPickerSuggestions(result, "/repo/src")).toEqual(result.items)
expect(currentPickerSuggestions(result, "/repo/test")).toEqual([])
expect(currentPickerSuggestions(result, "/repo/test", true)).toEqual(result.items)
})
test("resolves directory autocomplete from the browser root without changing location", async () => {
const calls: unknown[] = []
const location = { directory: "/repo", workspace: "workspace_1" }
@ -261,7 +254,7 @@ test("keeps literal tilde directory names in server listing and search results",
expect(await search("nested")).toEqual(["/repo/~/nested"])
})
test("discards stale typed results without changing the request location", async () => {
test("discards aborted typed results without changing the request location", async () => {
const location = { directory: "/repo" }
const pending = Promise.withResolvers<{
@ -288,7 +281,9 @@ test("discards stale typed results without changing the request location", async
location: () => location,
})
const stale = search("old")
const aborted = new AbortController()
const stale = search("old", { signal: aborted.signal })
aborted.abort()
expect(await search("new")).toEqual(["/repo/new"])
pending.resolve({ location, data: [{ path: "old/", type: "directory" }] })
expect(await stale).toEqual([])
@ -330,8 +325,8 @@ const projects = Array.from({ length: 60 }, (_, index) => ({ path: `project-${in
const fallbacks: {
name: string
query: string
find: () => Promise<unknown>
list: () => Promise<unknown>
find: () => Promise<object>
list: () => Promise<object>
expected: string[]
listed: string[]
}[] = [
@ -452,11 +447,62 @@ test("limits background tasks and prioritizes newly requested work", async () =>
expect(maximum).toBe(2)
})
test.each([
[3, 3, true],
[2, 3, false],
])("a tree mutation from navigation %p applies during navigation %p: %p", (request, current, expected) => {
expect(activeTreeNavigation(request, current)).toBe(expected)
test("clearing the queue frees slots held by tasks that never settle", async () => {
const queue = createPriorityTaskQueue<string>(3)
const signals: AbortSignal[] = []
const started: string[] = []
const hang = (name: string) => (signal: AbortSignal) => {
started.push(name)
signals.push(signal)
return new Promise<string>(() => {})
}
const hung = ["a", "b", "c"].map((name) => queue.schedule(name, "background", hang(name)))
const queued = queue.schedule("queued", "background", hang("queued"))
await Promise.resolve()
queue.clear()
expect(await Promise.all([...hung, queued])).toEqual([undefined, undefined, undefined, undefined])
expect(signals.map((signal) => signal.aborted)).toEqual([true, true, true])
expect(await queue.schedule("next", "user", async () => "next")).toBe("next")
expect(started).toEqual(["a", "b", "c"])
})
test("aborting one running task frees its slot for the next", async () => {
const queue = createPriorityTaskQueue<string>(1)
const aborted = Promise.withResolvers<void>()
const hung = queue.schedule("hung", "user", (signal) => {
signal.addEventListener("abort", () => aborted.resolve())
return new Promise<string>(() => {})
})
const next = queue.schedule("next", "background", async () => "next")
await Promise.resolve()
queue.abort("hung")
await aborted.promise
expect(await hung).toBeUndefined()
expect(await next).toBe("next")
})
test("listing a folder passes the abort signal to the request", async () => {
const controller = new AbortController()
const signals: unknown[] = []
const api = sdk({
list: async (_input: never, options: { signal?: AbortSignal }) => {
signals.push(options.signal)
return { location: { directory: "/repo" }, data: [] }
},
})
await listPickerDirectory(api, { directory: "/repo" }, "/repo", controller.signal)
expect(signals).toEqual([controller.signal])
})
test("wraps autocomplete keyboard navigation", () => {

View file

@ -123,26 +123,30 @@ export function pickerRelativePath(base: string | undefined, path: string) {
return targetPath.slice(prefix.length)
}
export function currentPickerSuggestions<T>(
result: { query: string; items: readonly T[] } | undefined,
query: string,
loading = false,
) {
if (result?.query !== query && !loading) return []
export type PickerPolicy = ReturnType<typeof pickerMode>
return result?.items ?? []
// The folder a typed or chosen path opens, or undefined when the mode does not allow it.
export function resolvePickerTarget(policy: PickerPolicy, path: string, home: string, base: string) {
return policy.navigation(pickerAbsoluteInput(cleanPickerInput(path), home, base))
}
export function activeTreeNavigation(request: number, current: number) {
return request === current
export function displayInputDirectory(path: string, home: string) {
const displayed = displayPickerPath(path, "", home)
const separator = displayed.includes("\\") ? "\\" : "/"
return displayed.endsWith(separator) ? displayed : displayed + separator
}
// `abort(key)` and `clear()` abort the task's signal and resolve its promise with undefined at once, so a task that
// never settles cannot keep its slot.
export function createPriorityTaskQueue<T>(concurrency: number) {
type Job = {
key: string
priority: "user" | "background"
promise: Promise<T>
promise: Promise<T | undefined>
controller: AbortController
run: () => void
settle: (outcome: { value: T | undefined } | { error: unknown }) => void
}
const jobs = new Map<string, Job>()
@ -160,7 +164,7 @@ export function createPriorityTaskQueue<T>(concurrency: number) {
}
}
const schedule = (key: string, priority: Job["priority"], task: () => Promise<T>) => {
const schedule = (key: string, priority: Job["priority"], task: (signal: AbortSignal) => Promise<T>) => {
const existing = jobs.get(key)
if (existing) {
@ -169,32 +173,36 @@ export function createPriorityTaskQueue<T>(concurrency: number) {
return existing.promise
}
const deferred = Promise.withResolvers<T>()
const deferred = Promise.withResolvers<T | undefined>()
const controller = new AbortController()
const state = { running: false, settled: false }
const job: Job = {
key,
priority,
promise: deferred.promise,
controller,
run: () => {
const complete = () => {
active--
jobs.delete(key)
drain()
}
state.running = true
Promise.resolve()
.then(task)
.then(() => (controller.signal.aborted ? undefined : task(controller.signal)))
.then(
(value) => {
complete()
deferred.resolve(value)
},
(error) => {
complete()
deferred.reject(error)
},
(value) => job.settle({ value }),
(error) => job.settle({ error }),
)
},
settle: (outcome) => {
if (state.settled) return
state.settled = true
jobs.delete(key)
dequeue(job)
if (state.running) active--
if ("error" in outcome) deferred.reject(outcome.error)
else deferred.resolve(outcome.value)
drain()
},
}
jobs.set(key, job)
@ -204,6 +212,21 @@ export function createPriorityTaskQueue<T>(concurrency: number) {
return job.promise
}
const dequeue = (job: Job) => {
const queue = job.priority === "user" ? user : background
const index = queue.indexOf(job)
if (index !== -1) queue.splice(index, 1)
}
const abort = (key: string) => {
const job = jobs.get(key)
if (!job) return
job.controller.abort()
job.settle({ value: undefined })
}
const promote = (key: string) => {
const job = jobs.get(key)
@ -216,7 +239,12 @@ export function createPriorityTaskQueue<T>(concurrency: number) {
user.push(job)
}
return { schedule, promote }
// Queued jobs go first, so aborting a running one never starts a job that is about to be dropped.
const clear = () => {
;[...user, ...background, ...jobs.values()].forEach((job) => abort(job.key))
}
return { schedule, promote, abort, clear }
}
export function nextSuggestionIndex(current: number, delta: -1 | 1, count: number) {
@ -401,8 +429,9 @@ export async function listPickerDirectory(
sdk: ServerSDK,
location: { directory: string; workspace?: string },
directory: string,
signal?: AbortSignal,
) {
const result = await sdk.api.file.list({ location, path: directory })
const result = await sdk.api.file.list({ location, path: directory }, { signal })
return result.data.map((entry) => {
const absolute = pickerAbsolutePath(entry.path, result.location.directory)
@ -418,7 +447,6 @@ export function createDirectorySearch(args: {
home: () => string
}) {
const cache = new Map<string, Promise<Array<{ name: string; absolute: string }>>>()
let current = 0
const scoped = (value: string) => {
const raw = normalizePickerDrive(value)
@ -465,14 +493,13 @@ export function createDirectorySearch(args: {
return fuzzysort.go(query, items, { key: "name", limit }).map((item) => item.obj.absolute)
}
return async (filter: string) => {
const token = ++current
const active = () => token === current
return async (filter: string, options?: { signal?: AbortSignal }): Promise<string[]> => {
const active = () => !options?.signal?.aborted
const value = cleanPickerInput(filter)
const input = scoped(value)
const location = args.location()
if (!input || !location) return [] as string[]
if (!input || !location) return []
const raw = normalizePickerDrive(value)
const pathInput = raw.startsWith("~") || !!pickerRoot(raw) || raw.includes("/")
const query = normalizePickerDrive(input.path)

View file

@ -0,0 +1,256 @@
import { expect, test } from "bun:test"
import { pickerMode } from "./domain"
import {
createPickerTreeState,
hasPickerGitRepo,
pickerTreeView,
transitionPickerTree,
type PickerNode,
type PickerTreeEvent,
type PickerTreeState,
type PickerTreeTransition,
} from "./tree-machine"
const HOME = "/home/user"
const policy = pickerMode("directory")
const folder = (name: string): PickerNode => ({ name, type: "directory" })
const navigate = (path: string, located = true): PickerTreeEvent => ({
type: "navigate",
path,
home: HOME,
fallback: HOME,
located,
})
const choose = (path: string, fromInput = false): PickerTreeEvent => ({
type: "directory.chosen",
path,
home: HOME,
fallback: HOME,
located: true,
fromInput,
})
function run(events: PickerTreeEvent[], state = createPickerTreeState(), mode = policy) {
return events.reduce<PickerTreeTransition>((current, event) => transitionPickerTree(current.state, event, mode), {
state,
effects: [],
})
}
// Opens `root` and lists it. Its folders preload with attempts 2, 3, ... in order.
function ready(root: string, nodes: PickerNode[]) {
return run([navigate(root), { type: "dir.loaded", dir: "", attempt: 1, nodes }]).state
}
function dirs(state: PickerTreeState) {
return state.status === "ready" ? state.dirs : {}
}
test("a child folder that fails leaves the root readable and retries on its next expand", () => {
const state = ready(HOME, [folder("work")])
for (const type of ["dir.failed", "dir.timed-out"] as const) {
const failed = run([{ type, dir: "work", attempt: 2 }], state)
const retried = run([{ type: "dir.expanded", dir: "work/" }], failed.state)
expect(pickerTreeView(failed.state, policy)).toMatchObject({ error: false, loading: false, result: HOME })
expect(dirs(failed.state).work).toEqual({ status: "failed" })
expect(retried.effects).toEqual([
{ type: "list", root: HOME, dir: "work", attempt: 3, priority: "user", timeoutMs: 30_000 },
])
}
})
test("a root that fails shows the read error and cannot be confirmed, whatever settles later", () => {
const failed = run([navigate(HOME), { type: "dir.failed", dir: "", attempt: 1 }])
const late = run(
[
{ type: "dir.loaded", dir: "work", attempt: 2, nodes: [] },
{ type: "dir.expanded", dir: "work" },
],
failed.state,
)
expect(failed.effects).toEqual([{ type: "queue.reset" }])
expect(pickerTreeView(failed.state, policy)).toMatchObject({ error: true, loading: false, result: undefined })
expect(late.state).toBe(failed.state)
expect(
pickerTreeView(run([navigate(HOME), { type: "dir.timed-out", dir: "", attempt: 1 }]).state, policy).error,
).toBeTrue()
})
test("a newer choice wins over a reveal still waiting on its ancestors", () => {
const state = ready(HOME, [folder("work"), folder("fast-repo")])
const revealing = run([choose(`${HOME}/work/slow/repo-a`)], state)
expect(revealing.effects).toEqual([{ type: "promote", attempt: 2 }])
for (const newer of [
choose(`${HOME}/fast-repo`),
{ type: "tree.selected", path: "fast-repo/" } as const,
{ type: "selection.cleared" } as const,
]) {
const chosen = run([newer], revealing.state)
const settled = run([{ type: "dir.loaded", dir: "work", attempt: 2, nodes: [folder("slow")] }], chosen.state)
expect(settled.effects).toEqual([{ type: "tree.add", paths: ["work/slow/"] }])
expect(pickerTreeView(settled.state, policy).selected).toBe(pickerTreeView(chosen.state, policy).selected)
expect(settled.state).toMatchObject({ status: "ready", root: HOME, reveal: undefined })
}
})
test("a reveal expands each listed ancestor, then selects the folder and lists it when typed", () => {
const state = ready(HOME, [folder("work")])
const revealing = run([choose(`${HOME}/work/slow/repo-a`, true)], state)
const work = run([{ type: "dir.loaded", dir: "work", attempt: 2, nodes: [folder("slow")] }], revealing.state)
const slow = run([{ type: "dir.loaded", dir: "work/slow", attempt: 3, nodes: [folder("repo-a")] }], work.state)
expect(work.effects).toEqual([
{ type: "tree.add", paths: ["work/slow/"] },
{ type: "tree.expand", dir: "work" },
{ type: "list", root: HOME, dir: "work/slow", attempt: 3, priority: "user", timeoutMs: 30_000 },
])
expect(slow.effects).toEqual([
{ type: "tree.add", paths: ["work/slow/repo-a/"] },
{ type: "tree.expand", dir: "work/slow" },
{ type: "tree.select", entry: "work/slow/repo-a/" },
{ type: "tree.expand", dir: "work/slow/repo-a" },
{ type: "list", root: HOME, dir: "work/slow/repo-a", attempt: 4, priority: "user", timeoutMs: 30_000 },
])
expect(pickerTreeView(slow.state, policy)).toMatchObject({
selected: `${HOME}/work/slow/repo-a`,
result: `${HOME}/work/slow/repo-a`,
})
})
test("a revealed folder the listings do not show opens as the root instead", () => {
const state = ready(HOME, [folder("work")])
const revealing = run([choose(`${HOME}/work/missing`)], state)
const listed = run([{ type: "dir.loaded", dir: "work", attempt: 2, nodes: [] }], revealing.state)
const failed = run([{ type: "dir.failed", dir: "work", attempt: 2 }], revealing.state)
for (const settled of [listed, failed]) {
expect(settled.state).toMatchObject({ status: "loading", root: `${HOME}/work/missing`, attempt: 3 })
expect(settled.effects).toEqual([
{ type: "queue.reset" },
{ type: "tree.reset" },
{ type: "list", root: `${HOME}/work/missing`, dir: "", attempt: 3, priority: "user", timeoutMs: 30_000 },
])
}
})
test("choosing the root clears the selection", () => {
const state = run([{ type: "tree.selected", path: "work/" }], ready(HOME, [folder("work")])).state
const chosen = run([choose(HOME)], state)
expect(pickerTreeView(state, policy).selected).toBe(`${HOME}/work`)
expect(chosen.effects).toEqual([{ type: "tree.clear-selection" }])
expect(pickerTreeView(chosen.state, policy)).toMatchObject({ selected: "", result: HOME })
})
test("a new root drops the previous root's listings and selection", () => {
const state = run([{ type: "tree.selected", path: "work/" }], ready(HOME, [folder("work")])).state
const moved = run([navigate("/srv")], state)
expect(moved.state).toMatchObject({ status: "loading", root: "/srv", attempt: 3 })
expect(moved.effects).toEqual([
{ type: "queue.reset" },
{ type: "tree.reset" },
{ type: "list", root: "/srv", dir: "", attempt: 3, priority: "user", timeoutMs: 30_000 },
])
expect(pickerTreeView(moved.state, policy)).toMatchObject({ selected: "", loading: true, result: undefined })
for (const late of [
{ type: "dir.loaded", dir: "", attempt: 1, nodes: [] },
{ type: "dir.loaded", dir: "work", attempt: 2, nodes: [] },
{ type: "dir.failed", dir: "", attempt: 1 },
{ type: "dir.timed-out", dir: "work", attempt: 2 },
] as const) {
expect(run([late], moved.state).state).toBe(moved.state)
}
})
test("a folder of home outside the root opens home with that folder selected", () => {
const state = ready("/srv", [])
const chosen = run([choose(`${HOME}/notes`)], state)
const listed = run([{ type: "dir.loaded", dir: "", attempt: 2, nodes: [folder("notes")] }], chosen.state)
expect(chosen.state).toMatchObject({ status: "loading", root: HOME, selectChild: `${HOME}/notes` })
expect(listed.effects).toEqual([
{ type: "tree.add", paths: ["notes/"] },
{ type: "tree.select", entry: "notes/" },
{ type: "list", root: HOME, dir: "notes", attempt: 3, priority: "background", timeoutMs: 30_000 },
])
expect(pickerTreeView(listed.state, policy).selected).toBe(`${HOME}/notes`)
})
test("without a dialog location the picker resolves one, and a failure or timeout ends in the read error", () => {
const requested = run([{ type: "location.requested" }])
expect(requested.effects).toEqual([{ type: "resolve-location", attempt: 1, timeoutMs: 30_000 }])
expect(pickerTreeView(requested.state, policy).loading).toBeTrue()
expect(run([{ type: "location.requested" }], requested.state).state).toBe(requested.state)
expect(run([{ type: "location.failed", attempt: 9 }], requested.state).state).toBe(requested.state)
for (const event of [
{ type: "location.failed", attempt: 1 },
{ type: "location.timed-out", attempt: 1 },
{ type: "location.resolved", attempt: 1, directory: undefined },
] as const) {
const failed = run([event], requested.state)
expect(pickerTreeView(failed.state, policy)).toMatchObject({ loading: false, error: true })
const retried = run([navigate(HOME, false)], failed.state)
const resolved = run([{ type: "location.resolved", attempt: 2, directory: "/srv/app" }], retried.state)
expect(retried.effects).toEqual([
{ type: "queue.reset" },
{ type: "tree.reset" },
{ type: "resolve-location", attempt: 2, timeoutMs: 30_000 },
])
expect(resolved.state).toMatchObject({ status: "loading", root: HOME, locationDirectory: "/srv/app" })
expect(pickerTreeView(resolved.state, policy).locationDirectory).toBe("/srv/app")
}
const located = run([{ type: "location.resolved", attempt: 1, directory: "/srv/app" }], requested.state)
expect(located.state).toEqual({ status: "booting", issued: 1, locationDirectory: "/srv/app" })
expect(pickerTreeView(located.state, policy).loading).toBeFalse()
})
test("expanding a folder that is still preloading moves it ahead of the queue", () => {
const state = ready(HOME, [folder("work"), folder("repo")])
const expanded = run([{ type: "dir.expanded", dir: "repo/" }], state)
expect(expanded.effects).toEqual([{ type: "promote", attempt: 3 }])
expect(run([{ type: "dir.expanded", dir: "repo/" }], expanded.state).state).toBe(expanded.state)
})
test("a listing that contains .git badges its folder once", () => {
const state = ready(HOME, [folder("repo")])
const listed = run([{ type: "dir.loaded", dir: "repo", attempt: 2, nodes: [folder(".git"), folder("src")] }], state)
expect(listed.effects).toEqual([{ type: "tree.add", paths: ["repo/src/"] }, { type: "tree.refresh-decorations" }])
expect(hasPickerGitRepo(listed.state, "repo/")).toBeTrue()
expect(hasPickerGitRepo(listed.state, "other/")).toBeFalse()
})
test("a file picker ignores roots outside its base", () => {
const files = pickerMode("file", "/repo")
const state = run([navigate("/repo")], createPickerTreeState(), files).state
expect(run([navigate("/tmp")], state, files).state).toBe(state)
})
test("disposing drops queued work and ignores later results", () => {
const disposed = run([navigate(HOME), { type: "disposed" }])
expect(disposed.effects).toEqual([{ type: "queue.reset" }])
expect(run([{ type: "dir.loaded", dir: "", attempt: 1, nodes: [] }], disposed.state).state).toBe(disposed.state)
})

View file

@ -0,0 +1,488 @@
import { getFilename } from "@opencode/util/path"
import {
pickerFileSearchQuery,
pickerParent,
pickerRelativePath,
resolvePickerTarget,
type PickerPolicy,
} from "./domain"
/** Bounded fallback so a hung location or listing request cannot leave the picker loading forever. */
export const PICKER_LOAD_TIMEOUT_MS = 30_000
export type PickerNode = { readonly name: string; readonly type: "file" | "directory" }
/** One folder's listing inside the current root, keyed by its tree path without a trailing slash ("" is the root). */
export type PickerDirState =
| { readonly status: "loading"; readonly attempt: number; readonly priority: "user" | "background" }
| { readonly status: "ready" }
| { readonly status: "failed" }
/** A chosen folder inside the root. Its ancestors list and expand in order from `index`, then it is selected. */
export type PickerReveal = {
readonly target: string
readonly relative: string
readonly index: number
readonly fromInput: boolean
}
/** The root to open, and the child of it to select once it lists. */
export type PickerTarget = { readonly root: string; readonly selectChild?: string }
/**
* The folder browser. `issued` numbers every location and listing request, so a result for an earlier root, reveal or
* location request never matches a later one. Without a dialog location, `locating` is the attempt of the fallback
* `location.get()` request and `pending` the root to open once it resolves; the resolved directory then travels with
* every phase as `locationDirectory`.
*/
export type PickerTreeState =
| {
readonly status: "booting"
readonly issued: number
readonly locating?: number
readonly locationDirectory?: string
readonly pending?: PickerTarget
}
| {
readonly status: "loading"
readonly issued: number
readonly attempt: number
readonly root: string
readonly selectChild?: string
readonly locationDirectory?: string
}
| {
readonly status: "ready"
readonly issued: number
readonly root: string
readonly selected: string
readonly dirs: Readonly<Record<string, PickerDirState>>
readonly entries: Readonly<Record<string, true>>
readonly gitRepos: Readonly<Record<string, true>>
readonly reveal?: PickerReveal
readonly locationDirectory?: string
}
| { readonly status: "error"; readonly issued: number; readonly root: string; readonly locationDirectory?: string }
| { readonly status: "disposed" }
/** `fallback` is the base for relative paths before a root opens; `located` says whether a server location exists. */
type PickerNavigation = {
readonly path: string
readonly home: string
readonly fallback: string
readonly located: boolean
}
export type PickerTreeEvent =
| { readonly type: "location.requested" }
| { readonly type: "location.resolved"; readonly attempt: number; readonly directory: string | undefined }
| { readonly type: "location.failed"; readonly attempt: number }
| { readonly type: "location.timed-out"; readonly attempt: number }
| ({ readonly type: "navigate" } & PickerNavigation)
| ({ readonly type: "directory.chosen"; readonly fromInput: boolean } & PickerNavigation)
| { readonly type: "file.chosen"; readonly absolute: string; readonly home: string }
| { readonly type: "selection.cleared" }
| { readonly type: "tree.selected"; readonly path: string | undefined }
| { readonly type: "dir.expanded"; readonly dir: string }
| {
readonly type: "dir.loaded"
readonly dir: string
readonly attempt: number
readonly nodes: readonly PickerNode[]
}
| { readonly type: "dir.failed"; readonly dir: string; readonly attempt: number }
| { readonly type: "dir.timed-out"; readonly dir: string; readonly attempt: number }
| { readonly type: "disposed" }
export type PickerTreeEffect =
| { readonly type: "resolve-location"; readonly attempt: number; readonly timeoutMs: number }
| {
readonly type: "list"
readonly root: string
readonly dir: string
readonly attempt: number
readonly priority: "user" | "background"
readonly timeoutMs: number
}
| { readonly type: "promote"; readonly attempt: number }
| { readonly type: "queue.reset" }
| { readonly type: "tree.reset" }
| { readonly type: "tree.add"; readonly paths: readonly string[] }
| { readonly type: "tree.expand"; readonly dir: string }
| { readonly type: "tree.select"; readonly entry: string }
| { readonly type: "tree.clear-selection" }
| { readonly type: "tree.focus-initial" }
| { readonly type: "tree.refresh-decorations" }
export type PickerTreeTransition = { readonly state: PickerTreeState; readonly effects: readonly PickerTreeEffect[] }
type LiveTree = Exclude<PickerTreeState, { status: "disposed" }>
type ReadyTree = Extract<PickerTreeState, { status: "ready" }>
export function createPickerTreeState(): PickerTreeState {
return { status: "booting", issued: 0 }
}
export function transitionPickerTree(
state: PickerTreeState,
event: PickerTreeEvent,
policy: PickerPolicy,
): PickerTreeTransition {
if (state.status === "disposed") return unchanged(state)
if (event.type === "disposed") return { state: { status: "disposed" }, effects: [{ type: "queue.reset" }] }
if (event.type === "location.requested") {
if (state.status !== "booting" || state.locating !== undefined || state.locationDirectory) return unchanged(state)
const attempt = state.issued + 1
return { state: { ...state, issued: attempt, locating: attempt }, effects: [resolveLocation(attempt)] }
}
if (event.type === "location.resolved" || event.type === "location.failed" || event.type === "location.timed-out") {
return settleLocation(state, event)
}
if (event.type === "navigate") {
const root = target(state, event, policy)
if (!root) return unchanged(state)
return open(state, { root }, event.located)
}
if (event.type === "directory.chosen") return choose(state, event, policy)
if (event.type === "dir.loaded" || event.type === "dir.failed" || event.type === "dir.timed-out") {
return settleListing(state, event, policy)
}
if (state.status !== "ready") return unchanged(state)
if (event.type === "dir.expanded") {
const dir = event.dir.replace(/\/+$/, "")
if (!dir) return unchanged(state)
return requestDir(state, dir, [])
}
if (event.type === "tree.selected") {
return select(state, event.path ? (policy.selection(state.root, event.path) ?? "") : "")
}
if (event.type === "selection.cleared") return select(state, "")
return select(
state,
policy.selection(state.root, pickerFileSearchQuery(state.root, event.absolute, event.home)) ?? "",
)
}
export function pickerTreeView(state: PickerTreeState, policy: PickerPolicy) {
return {
root: rootOf(state),
selected: state.status === "ready" ? state.selected : "",
loading: (state.status === "booting" && state.locating !== undefined) || state.status === "loading",
error: state.status === "error",
result: state.status === "ready" ? policy.result(state.root, state.selected, true) : undefined,
locationDirectory: state.status === "disposed" ? undefined : state.locationDirectory,
}
}
export function hasPickerGitRepo(state: PickerTreeState, dir: string) {
return state.status === "ready" && Boolean(state.gitRepos[dir.replace(/\/+$/, "")])
}
function settleLocation(
state: LiveTree,
event: Extract<PickerTreeEvent, { type: "location.resolved" | "location.failed" | "location.timed-out" }>,
): PickerTreeTransition {
if (state.status !== "booting" || state.locating !== event.attempt) return unchanged(state)
if (event.type === "location.resolved" && event.directory) {
const located = { status: "booting" as const, issued: state.issued, locationDirectory: event.directory }
if (state.pending) return open(located, state.pending, true)
return { state: located, effects: [] }
}
return { state: { status: "error", issued: state.issued, root: state.pending?.root ?? "" }, effects: [] }
}
function choose(
state: LiveTree,
event: Extract<PickerTreeEvent, { type: "directory.chosen" }>,
policy: PickerPolicy,
): PickerTreeTransition {
const value = target(state, event, policy)
if (!value) return unchanged(state)
if (state.status === "ready") {
const relative = pickerRelativePath(state.root, value)
if (relative === "") {
return { state: { ...state, selected: "", reveal: undefined }, effects: [{ type: "tree.clear-selection" }] }
}
if (relative) {
return advanceReveal(
{ ...state, reveal: { target: value, relative, index: 0, fromInput: event.fromInput } },
[],
policy,
)
}
}
const parent = pickerParent(value)
if (parent && getFilename(value) && parent !== value && parent === event.home) {
return open(state, { root: parent, selectChild: value }, event.located)
}
return open(state, { root: value }, event.located)
}
// A new root drops every listing, queued preload and reveal of the previous one.
function open(state: LiveTree, next: PickerTarget, located: boolean): PickerTreeTransition {
const attempt = state.issued + 1
if (!located) {
if (state.status === "booting" && state.locating !== undefined) {
return { state: { ...state, pending: next }, effects: [] }
}
return {
state: { status: "booting", issued: attempt, locating: attempt, pending: next },
effects: [{ type: "queue.reset" }, { type: "tree.reset" }, resolveLocation(attempt)],
}
}
return {
state: {
status: "loading",
issued: attempt,
attempt,
root: next.root,
selectChild: next.selectChild,
locationDirectory: state.locationDirectory,
},
effects: [{ type: "queue.reset" }, { type: "tree.reset" }, list(next.root, "", attempt, "user")],
}
}
function settleListing(
state: LiveTree,
event: Extract<PickerTreeEvent, { type: "dir.loaded" | "dir.failed" | "dir.timed-out" }>,
policy: PickerPolicy,
): PickerTreeTransition {
if (state.status === "loading") {
if (event.dir !== "" || event.attempt !== state.attempt) return unchanged(state)
if (event.type !== "dir.loaded") {
return {
state: { status: "error", issued: state.issued, root: state.root, locationDirectory: state.locationDirectory },
effects: [{ type: "queue.reset" }],
}
}
return openRoot(state, event.nodes, policy)
}
if (state.status !== "ready") return unchanged(state)
const entry = state.dirs[event.dir]
if (entry?.status !== "loading" || entry.attempt !== event.attempt) return unchanged(state)
const waiting = state.reveal !== undefined && revealAncestors(state.reveal.relative)[state.reveal.index] === event.dir
if (event.type !== "dir.loaded") {
// A child folder that fails stays retryable on its next expand; the root stays usable.
const failed = { ...state, dirs: { ...state.dirs, [event.dir]: { status: "failed" as const } } }
if (waiting && failed.reveal) return finishReveal(failed, failed.reveal, [], policy)
return { state: failed, effects: [] }
}
const listed = absorb(state, event.dir, event.nodes, policy)
if (waiting) return advanceReveal(listed.state, listed.effects, policy)
return listed
}
// Preloading the root's folders makes their first expand instant and finds git repos for the badge.
function openRoot(
state: Extract<PickerTreeState, { status: "loading" }>,
nodes: readonly PickerNode[],
policy: PickerPolicy,
): PickerTreeTransition {
const listed = absorb(
{
status: "ready",
issued: state.issued,
root: state.root,
selected: "",
dirs: {},
entries: {},
gitRepos: {},
locationDirectory: state.locationDirectory,
},
"",
nodes,
policy,
)
const children = nodes.flatMap((node) => (node.type === "directory" && node.name !== ".git" ? [node.name] : []))
const entry = state.selectChild ? `${getFilename(state.selectChild)}/` : undefined
return {
state: {
...listed.state,
issued: state.issued + children.length,
selected: entry ? (policy.selection(state.root, entry) ?? "") : "",
dirs: {
...listed.state.dirs,
...Object.fromEntries(
children.map((name, index) => [
name,
{ status: "loading" as const, attempt: state.issued + index + 1, priority: "background" as const },
]),
),
},
},
effects: [
...listed.effects,
entry ? { type: "tree.select", entry } : { type: "tree.focus-initial" },
...children.map((name, index) => list(state.root, name, state.issued + index + 1, "background")),
],
}
}
function absorb(state: ReadyTree, dir: string, nodes: readonly PickerNode[], policy: PickerPolicy) {
const paths = policy
.entries(
dir,
nodes.filter((node) => node.name !== ".git"),
)
.filter((path) => !state.entries[path])
const repo = nodes.some((node) => node.name === ".git") && !state.gitRepos[dir]
const effects: PickerTreeEffect[] = []
if (paths.length > 0) effects.push({ type: "tree.add", paths })
if (repo) effects.push({ type: "tree.refresh-decorations" })
return {
state: {
...state,
dirs: { ...state.dirs, [dir]: { status: "ready" as const } },
entries:
paths.length > 0
? { ...state.entries, ...Object.fromEntries(paths.map((path) => [path, true] as const)) }
: state.entries,
gitRepos: repo ? { ...state.gitRepos, [dir]: true as const } : state.gitRepos,
},
effects,
}
}
// Expands the listed ancestors in order and waits on the first one that has not listed yet.
function advanceReveal(state: ReadyTree, effects: readonly PickerTreeEffect[], policy: PickerPolicy) {
const reveal = state.reveal
if (!reveal) return { state, effects }
const ancestors = revealAncestors(reveal.relative)
const index = ancestors.findIndex((dir, at) => at >= reveal.index && state.dirs[dir]?.status !== "ready")
const expanded = [
...effects,
...ancestors
.slice(reveal.index, index === -1 ? undefined : index)
.map((dir) => ({ type: "tree.expand" as const, dir })),
]
if (index === -1) return finishReveal(state, reveal, expanded, policy)
return requestDir({ ...state, reveal: { ...reveal, index } }, ancestors[index]!, expanded)
}
// A folder the listings did not show opens as the new root instead.
function finishReveal(
state: ReadyTree,
reveal: PickerReveal,
effects: readonly PickerTreeEffect[],
policy: PickerPolicy,
): PickerTreeTransition {
const entry = `${reveal.relative}/`
if (!state.entries[entry]) return open({ ...state, reveal: undefined }, { root: reveal.target }, true)
const selected = { ...state, reveal: undefined, selected: policy.selection(state.root, entry) ?? "" }
const selecting = [...effects, { type: "tree.select" as const, entry }]
if (!reveal.fromInput) return { state: selected, effects: selecting }
return requestDir(selected, reveal.relative, [...selecting, { type: "tree.expand", dir: reveal.relative }])
}
function requestDir(state: ReadyTree, dir: string, effects: readonly PickerTreeEffect[]): PickerTreeTransition {
const entry = state.dirs[dir]
if (!entry || entry.status === "failed") {
const attempt = state.issued + 1
return {
state: {
...state,
issued: attempt,
dirs: { ...state.dirs, [dir]: { status: "loading", attempt, priority: "user" } },
},
effects: [...effects, list(state.root, dir, attempt, "user")],
}
}
if (entry.status === "loading" && entry.priority === "background") {
return {
state: { ...state, dirs: { ...state.dirs, [dir]: { ...entry, priority: "user" } } },
effects: [...effects, { type: "promote", attempt: entry.attempt }],
}
}
return { state, effects }
}
function select(state: ReadyTree, selected: string): PickerTreeTransition {
if (selected === state.selected && !state.reveal) return unchanged(state)
return { state: { ...state, selected, reveal: undefined }, effects: [] }
}
function target(state: LiveTree, event: PickerNavigation, policy: PickerPolicy) {
return resolvePickerTarget(policy, event.path, event.home, rootOf(state) || event.fallback)
}
function rootOf(state: PickerTreeState) {
return state.status === "booting" || state.status === "disposed" ? "" : state.root
}
function revealAncestors(relative: string) {
const segments = relative.split("/").filter(Boolean)
return segments.slice(0, -1).map((_, index) => segments.slice(0, index + 1).join("/"))
}
function resolveLocation(attempt: number): PickerTreeEffect {
return { type: "resolve-location", attempt, timeoutMs: PICKER_LOAD_TIMEOUT_MS }
}
function list(root: string, dir: string, attempt: number, priority: "user" | "background"): PickerTreeEffect {
return { type: "list", root, dir, attempt, priority, timeoutMs: PICKER_LOAD_TIMEOUT_MS }
}
function unchanged(state: PickerTreeState): PickerTreeTransition {
return { state, effects: [] }
}