mirror of
https://github.com/anomalyco/opencode.git
synced 2026-11-19 00:03:13 +03:00
feat(desktop): redesign remote project picker (#55711)
Co-authored-by: Brendan Allan <git@brendonovich.dev>
This commit is contained in:
committed by
GitHub
Unverified
parent
6d273cf45f
commit
a3f9af118f
@@ -76,7 +76,7 @@ test("creates a session in a new project and selects its model", async ({ page }
|
||||
await expectAppVisible(addProject)
|
||||
await addProject.click()
|
||||
const picker = page.getByRole("dialog", { name: "Open project", exact: true })
|
||||
await expect(picker.getByRole("combobox")).toHaveValue("C:\\OpenCode\\NewProject")
|
||||
await expect(picker.getByRole("combobox")).toHaveValue("")
|
||||
|
||||
const listing = page.waitForRequest((request) => {
|
||||
const url = new URL(request.url())
|
||||
|
||||
@@ -360,6 +360,10 @@ export const dict = {
|
||||
|
||||
"dialog.directory.action.selectFile": "Select file",
|
||||
"dialog.directory.action.selectFolder": "Select folder",
|
||||
"dialog.directory.search.placeholder": "Search projects or enter ~/path…",
|
||||
"dialog.directory.recent": "Recent",
|
||||
"dialog.directory.recentProject": "{{name}} ({{path}})",
|
||||
"dialog.directory.gitRepo": "git repo",
|
||||
"dialog.directory.root": "Root",
|
||||
"dialog.directory.parent": "Parent",
|
||||
"dialog.directory.readError": "Unable to read this folder",
|
||||
|
||||
@@ -2,7 +2,7 @@ import { describe, expect, test } from "bun:test"
|
||||
import { QueryClient } from "@tanstack/solid-query"
|
||||
import { OpenCode } from "@opencode/client/promise"
|
||||
import { createStore } from "solid-js/store"
|
||||
import { bootstrapGlobal, loadPathQuery, loadProjectsQuery } from "./bootstrap"
|
||||
import { bootstrapGlobal, inferHomeDirectory, loadPathQuery, loadProjectsQuery } from "./bootstrap"
|
||||
import { ServerScope } from "@/runtime/server/scope"
|
||||
import type { ServerApi } from "@/runtime/server/api"
|
||||
import { createServerTransport } from "@/runtime/server/client"
|
||||
@@ -131,6 +131,10 @@ describe("query keys", () => {
|
||||
|
||||
expect(calls).toEqual([{ location: { directory: "/repo/subpath" } }])
|
||||
expect(result).toMatchObject({ directory: "/repo/subpath", worktree: "/repo" })
|
||||
expect(inferHomeDirectory("/Users/kamil/Developer/opencode")).toBe("/Users/kamil")
|
||||
expect(inferHomeDirectory("/home/ubuntu/workspace/repo")).toBe("/home/ubuntu")
|
||||
expect(inferHomeDirectory("C:\\Users\\luke\\repo")).toBe("C:\\Users\\luke")
|
||||
expect(inferHomeDirectory("/repo/subpath")).toBe("")
|
||||
})
|
||||
|
||||
test("loads project metadata in server order without enumerating any project's worktrees", async () => {
|
||||
|
||||
@@ -102,7 +102,10 @@ export async function bootstrapGlobal(input: {
|
||||
}) {
|
||||
const slow = [
|
||||
() => input.queryClient.fetchQuery(loadGlobalConfigQuery(input.scope)),
|
||||
() => input.queryClient.fetchQuery(loadPathQuery(input.scope, null, input.serverAPI.location)),
|
||||
() =>
|
||||
input.queryClient
|
||||
.fetchQuery(loadPathQuery(input.scope, null, input.serverAPI.location))
|
||||
.then((data) => input.setGlobalStore("path", data)),
|
||||
() =>
|
||||
loadProjects({
|
||||
scope: input.scope,
|
||||
@@ -119,6 +122,15 @@ function projectID(directory: string, projects: Project[]) {
|
||||
return projects.find((project) => project.worktree === directory || project.sandboxes?.includes(directory))?.id
|
||||
}
|
||||
|
||||
export function inferHomeDirectory(path: string) {
|
||||
const normalized = path.replaceAll("\\", "/")
|
||||
const match = /^(\/Users\/[^/]+|\/home\/[^/]+|\/root|[A-Za-z]:\/Users\/[^/]+)(?=\/|$)/.exec(normalized)
|
||||
|
||||
if (!match) return ""
|
||||
|
||||
return path.includes("\\") ? match[1]!.replaceAll("/", "\\") : match[1]!
|
||||
}
|
||||
|
||||
export const loadPathQuery = (scope: ServerScope, directory: string | null, api: LocationApi) =>
|
||||
queryOptions<Path>({
|
||||
queryKey: [scope, directory, "path"],
|
||||
@@ -128,7 +140,7 @@ export const loadPathQuery = (scope: ServerScope, directory: string | null, api:
|
||||
config: "",
|
||||
worktree: location.project.directory,
|
||||
directory: location.directory,
|
||||
home: "",
|
||||
home: inferHomeDirectory(location.directory) || inferHomeDirectory(location.project.directory),
|
||||
})),
|
||||
})
|
||||
|
||||
|
||||
@@ -101,8 +101,11 @@ export function TabNavItem(props: {
|
||||
|
||||
if (!session) return
|
||||
const home = serverCtx()?.sync.data.path.home
|
||||
const directory = session.location.directory
|
||||
|
||||
return home ? session.location.directory.replace(home, "~") : session.location.directory
|
||||
if (!home || !directory.startsWith(home) || !/^([/\\]|$)/.test(directory.slice(home.length))) return directory
|
||||
|
||||
return "~" + directory.slice(home.length)
|
||||
})
|
||||
|
||||
// Only label the server when multiple servers are connected, and never the current one.
|
||||
|
||||
@@ -1,29 +1,84 @@
|
||||
.directory-picker-header {
|
||||
display: flex;
|
||||
min-width: 0;
|
||||
flex: 1;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.directory-picker-subtitle {
|
||||
overflow: hidden;
|
||||
color: var(--v2-text-text-muted);
|
||||
font-size: 11px;
|
||||
font-weight: 440;
|
||||
line-height: var(--line-height-tight);
|
||||
letter-spacing: 0.05px;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.directory-picker-body {
|
||||
display: flex;
|
||||
min-height: 0;
|
||||
flex: 1;
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
padding: 2px 16px 0;
|
||||
padding: 14px 16px 0;
|
||||
}
|
||||
|
||||
.directory-picker-path {
|
||||
position: relative;
|
||||
z-index: 10;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.directory-picker-input {
|
||||
min-width: 0;
|
||||
width: auto;
|
||||
flex: 1 1 0%;
|
||||
}
|
||||
|
||||
.directory-picker-actions {
|
||||
display: flex;
|
||||
flex-shrink: 0;
|
||||
gap: 2px;
|
||||
}
|
||||
|
||||
.directory-picker-recent {
|
||||
display: flex;
|
||||
width: 100%;
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.directory-picker-recent-label {
|
||||
color: var(--v2-text-text-base);
|
||||
font-size: 13px;
|
||||
font-weight: 530;
|
||||
line-height: var(--line-height-compact);
|
||||
letter-spacing: -0.04px;
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
.directory-picker-recent-list {
|
||||
display: flex;
|
||||
width: 100%;
|
||||
flex-wrap: wrap;
|
||||
align-items: flex-start;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.directory-picker-recent-item {
|
||||
max-width: 240px;
|
||||
}
|
||||
|
||||
.directory-picker-suggestions {
|
||||
position: absolute;
|
||||
z-index: 20;
|
||||
top: 36px;
|
||||
top: 34px;
|
||||
right: 0;
|
||||
left: 0;
|
||||
display: flex;
|
||||
@@ -40,7 +95,8 @@
|
||||
padding: 6px 8px;
|
||||
border-radius: 4px;
|
||||
color: var(--v2-text-text-muted);
|
||||
font-size: 12px;
|
||||
font-size: 13px;
|
||||
line-height: var(--line-height-compact);
|
||||
text-align: left;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
@@ -56,33 +112,39 @@
|
||||
position: relative;
|
||||
z-index: 0;
|
||||
isolation: isolate;
|
||||
height: 280px;
|
||||
min-height: 0;
|
||||
flex: 1;
|
||||
overflow: auto;
|
||||
border: 1px solid var(--v2-border-border-base);
|
||||
flex: 1 1 280px;
|
||||
overflow: hidden;
|
||||
padding: 6px;
|
||||
border: 0.5px solid var(--v2-border-border-base);
|
||||
border-radius: 6px;
|
||||
background: transparent;
|
||||
background: var(--v2-background-bg-base);
|
||||
}
|
||||
|
||||
.directory-picker-tree {
|
||||
display: block;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
--trees-bg-override: transparent;
|
||||
--trees-bg-override: var(--v2-background-bg-base);
|
||||
--trees-fg-override: var(--v2-text-text-base);
|
||||
--trees-fg-muted-override: var(--v2-text-text-muted);
|
||||
--trees-bg-muted-override: transparent;
|
||||
--trees-selected-bg-override: transparent;
|
||||
--trees-selected-bg-override: var(--v2-overlay-simple-overlay-pressed);
|
||||
--trees-selected-fg-override: var(--v2-text-text-base);
|
||||
--trees-selected-focused-border-color-override: transparent;
|
||||
--trees-focus-ring-color-override: transparent;
|
||||
--trees-focus-ring-width-override: 0px;
|
||||
--trees-focus-ring-offset-override: 0px;
|
||||
--trees-selected-focused-border-color-override: var(--v2-border-border-focus);
|
||||
--trees-focus-ring-color-override: var(--v2-border-border-focus);
|
||||
--trees-focus-ring-width-override: 1px;
|
||||
--trees-focus-ring-offset-override: -1px;
|
||||
--trees-border-color-override: var(--v2-border-border-base);
|
||||
--trees-font-family-override: var(--font-family-sans);
|
||||
--trees-font-size-override: 12px;
|
||||
--trees-font-size-override: 13px;
|
||||
--trees-item-height: 24px;
|
||||
--trees-border-radius-override: 4px;
|
||||
--trees-padding-inline-override: 0px;
|
||||
--trees-item-margin-x-override: 0px;
|
||||
--trees-item-padding-x-override: 8px;
|
||||
--trees-item-row-gap-override: 6px;
|
||||
}
|
||||
|
||||
.directory-picker-state {
|
||||
@@ -92,16 +154,27 @@
|
||||
display: grid;
|
||||
place-items: center;
|
||||
color: var(--v2-text-text-muted);
|
||||
font-size: 12px;
|
||||
font-size: 13px;
|
||||
line-height: var(--line-height-compact);
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.directory-picker-selection {
|
||||
display: flex;
|
||||
overflow: hidden;
|
||||
flex-shrink: 0;
|
||||
color: var(--v2-text-text-muted);
|
||||
font-size: 12px;
|
||||
line-height: 16px;
|
||||
min-width: 0;
|
||||
flex: 1 1 0%;
|
||||
align-self: center;
|
||||
}
|
||||
|
||||
.directory-picker-selection-text {
|
||||
overflow: hidden;
|
||||
min-width: 0;
|
||||
color: var(--v2-text-text-faint);
|
||||
font-size: 13px;
|
||||
font-weight: 440;
|
||||
line-height: var(--line-height-compact);
|
||||
letter-spacing: -0.04px;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
@@ -2,27 +2,39 @@ import "@pierre/trees/web-components"
|
||||
import { FileTree } from "@pierre/trees"
|
||||
import { Dialog, DialogBody, DialogFooter, DialogHeader, DialogTitle } from "@opencode/ui/dialog"
|
||||
import { Button } from "@opencode/ui/button"
|
||||
import { Divider } from "@opencode/ui/divider"
|
||||
import {
|
||||
displayName,
|
||||
getProjectAvatarSource,
|
||||
getProjectAvatarVariant,
|
||||
ProjectAvatar,
|
||||
} from "@opencode/ui/project-avatar"
|
||||
import { TextInput } from "@opencode/ui/text-input"
|
||||
import { Tooltip } from "@opencode/ui/tooltip"
|
||||
import { useDialog } from "@opencode/ui/context/dialog"
|
||||
import { createEffect, createMemo, createResource, createSignal, For, onCleanup, onMount, Show } from "solid-js"
|
||||
import { getFilename } from "@opencode/util/path"
|
||||
import { createEffect, createMemo, createResource, For, onCleanup, onMount, Show } from "solid-js"
|
||||
import { createStore } from "solid-js/store"
|
||||
import { useGlobal } from "@/runtime/server/runtime"
|
||||
import { inferHomeDirectory } from "@/runtime/server/global-sync/bootstrap"
|
||||
import { useLanguage } from "@/runtime/i18n/language"
|
||||
import { ServerConnection } from "@/runtime/server/registry"
|
||||
import { ServerConnection, serverName } from "@/runtime/server/registry"
|
||||
import { pathKey } from "@/workspaces/path-key"
|
||||
import type { LocationRef } from "@opencode/client/promise"
|
||||
import {
|
||||
absoluteTreePath,
|
||||
activeTreeNavigation,
|
||||
advanceTreePreload,
|
||||
canonicalPickerPath,
|
||||
nextSuggestionIndex,
|
||||
pickerFileSearchQuery,
|
||||
pickerAbsoluteInput,
|
||||
pickerMode,
|
||||
preloadTreeDirectories,
|
||||
cleanPickerInput,
|
||||
createPriorityTaskQueue,
|
||||
createDirectorySearch,
|
||||
currentPickerSuggestions,
|
||||
displayPickerPath,
|
||||
shortenPickerRecentPath,
|
||||
pickerParent,
|
||||
pickerRoot,
|
||||
listPickerDirectory,
|
||||
@@ -30,7 +42,12 @@ import {
|
||||
pickerAbsolutePath,
|
||||
} from "./domain"
|
||||
import "./dialog.css"
|
||||
import { Divider } from "@opencode/ui/divider"
|
||||
|
||||
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>`
|
||||
|
||||
const FOLDER_CLOSED_MASK = `url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='14' height='14' viewBox='0 0 14 14' fill='none'%3E%3Cpath d='M1.1667 1.75V11.6667H12.8334V3.5H7.58337L5.83337 1.75H1.1667Z' stroke='black' stroke-miterlimit='10' stroke-linecap='square'/%3E%3C/svg%3E")`
|
||||
|
||||
const FOLDER_OPEN_MASK = `url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='14' height='14' viewBox='0 0 14 14' fill='none'%3E%3Cpath opacity='0.3' d='M5.64738 1.70126H1.31254V11.9099H2.86062L4.12109 6.85385H12.6867V3.64608H7.29826L5.90031 1.99948L5.80973 1.89266L5.78666 1.86532L5.78068 1.85848L5.77897 1.85592L5.64738 1.70126Z' fill='black'/%3E%3Cpath d='M3.88891 11.4722H3.30558C2.44613 11.4722 1.75002 11.4722 1.75002 11.4722V3.69444C1.75002 2.835 1.75002 2.13889 1.75002 2.13889H5.44488C5.44488 2.13889 5.6148 2.33956 5.91035 2.68722L7.09569 4.08333H12.2492C12.2492 4.08333 12.2492 4.77944 12.2492 5.63889V6.41667M12.0267 10.3211L12.6475 7.88666C12.8368 7.14543 13.0279 6.41665 13.0279 6.41665H3.81968C3.81968 6.41665 3.7268 6.77054 3.59719 7.27999L2.90344 10.0022C2.71418 10.7434 2.52785 11.4722 2.52785 11.4722H11.7297C11.7297 11.4722 11.8536 11.0001 12.0267 10.3211Z' stroke='black'/%3E%3C/svg%3E")`
|
||||
|
||||
interface DirectoryPickerDialogProps {
|
||||
title?: string
|
||||
@@ -44,7 +61,9 @@ interface DirectoryPickerDialogProps {
|
||||
|
||||
export function DirectoryPickerDialog(props: DirectoryPickerDialogProps) {
|
||||
const global = useGlobal()
|
||||
const { sync, sdk } = global.ensureServerCtx(props.server)
|
||||
const serverCtx = global.ensureServerCtx(props.server)
|
||||
const sync = serverCtx.sync
|
||||
const sdk = serverCtx.sdk
|
||||
const dialog = useDialog()
|
||||
const language = useLanguage()
|
||||
const policy = pickerMode(props.mode ?? "directory", props.start)
|
||||
@@ -54,29 +73,55 @@ export function DirectoryPickerDialog(props: DirectoryPickerDialogProps) {
|
||||
directory: language.t("dialog.directory.action.selectFolder"),
|
||||
}
|
||||
|
||||
const [root, setRoot] = createSignal("")
|
||||
const [input, setInput] = createSignal("")
|
||||
const [selected, setSelected] = createSignal("")
|
||||
const [suggestionsOpen, setSuggestionsOpen] = createSignal(false)
|
||||
const [activeSuggestion, setActiveSuggestion] = createSignal(-1)
|
||||
const [loading, setLoading] = createSignal(false)
|
||||
const [error, setError] = createSignal(false)
|
||||
const [rootValid, setRootValid] = createSignal(false)
|
||||
const [state, setState] = createStore({
|
||||
root: "",
|
||||
input: "",
|
||||
selected: "",
|
||||
suggestionsOpen: false,
|
||||
activeSuggestion: -1,
|
||||
loading: false,
|
||||
error: false,
|
||||
rootValid: false,
|
||||
})
|
||||
|
||||
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 advanced = new Set<string>()
|
||||
const gitRepos = new Set<string>()
|
||||
let tree: FileTree | undefined
|
||||
let container: HTMLDivElement | undefined
|
||||
let pathArea: HTMLDivElement | undefined
|
||||
let navigation = 0
|
||||
|
||||
const knownGitRepos = createMemo(() => {
|
||||
const keys = new Set<string>()
|
||||
const items = [...serverCtx.projects.list(), ...sync.data.project]
|
||||
|
||||
for (const project of items) {
|
||||
if (!project.worktree || project.id === "global") continue
|
||||
|
||||
if (project.vcs && project.vcs !== "git") continue
|
||||
keys.add(pathKey(canonicalPickerPath(project.worktree)))
|
||||
|
||||
for (const sandbox of project.sandboxes ?? []) {
|
||||
keys.add(pathKey(canonicalPickerPath(sandbox)))
|
||||
}
|
||||
}
|
||||
|
||||
return keys
|
||||
})
|
||||
|
||||
const [fallbackPath] = createResource(
|
||||
() => (props.location ? undefined : true),
|
||||
() => sdk.api.location.get().catch(() => undefined),
|
||||
{ initialValue: undefined },
|
||||
)
|
||||
|
||||
const home = createMemo(() => sync.data.path.home || "")
|
||||
const home = createMemo(
|
||||
() =>
|
||||
sync.data.path.home || inferHomeDirectory(props.location?.directory ?? ""),
|
||||
)
|
||||
|
||||
const subtitle = createMemo(() => (ServerConnection.local(props.server) ? undefined : serverName(props.server)))
|
||||
|
||||
const location = createMemo(() => {
|
||||
const current = props.location ?? fallbackPath.latest
|
||||
@@ -87,64 +132,98 @@ export function DirectoryPickerDialog(props: DirectoryPickerDialogProps) {
|
||||
const start = createMemo(
|
||||
() =>
|
||||
props.start ||
|
||||
sync.data.path.home ||
|
||||
home() ||
|
||||
props.location?.directory ||
|
||||
sync.data.path.directory ||
|
||||
fallbackPath.latest?.directory,
|
||||
)
|
||||
|
||||
const search = createDirectorySearch({ sdk, home, location, base: () => root() || start() })
|
||||
const recentProjects = createMemo(() => {
|
||||
if ((props.mode ?? "directory") !== "directory") return []
|
||||
const seen = new Set<string>()
|
||||
const items = [...serverCtx.projects.list(), ...sync.data.project]
|
||||
|
||||
const [suggestions] = createResource(input, async (value) => {
|
||||
const cleaned = cleanPickerInput(value)
|
||||
const typed = cleaned.replace(/\/+$/, "")
|
||||
const current = displayPickerPath(root(), value, home()).replace(/\/+$/, "")
|
||||
return items
|
||||
.filter((project) => {
|
||||
if (!project.worktree || project.id === "global") return false
|
||||
const key = pathKey(project.worktree)
|
||||
|
||||
if (!cleaned || (root() && typed === current)) return { query: value, items: [] }
|
||||
const directories = (await search(value)).map((absolute) => ({ absolute, type: "directory" as const }))
|
||||
if (seen.has(key)) return false
|
||||
seen.add(key)
|
||||
|
||||
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(), 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,
|
||||
return true
|
||||
})
|
||||
.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),
|
||||
}
|
||||
.slice(0, 5)
|
||||
})
|
||||
|
||||
const currentSuggestions = createMemo(() => currentPickerSuggestions(suggestions.latest, input()))
|
||||
const search = createDirectorySearch({ sdk, home, location, base: () => state.root || start() })
|
||||
|
||||
async function load(path: string, generation: number, eager = false) {
|
||||
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 fullSelectionPath = createMemo(() => {
|
||||
const value = resolvedResult()
|
||||
|
||||
return value ? displayPickerPath(value, "", home()) : ""
|
||||
})
|
||||
const shortSelectionPath = createMemo(() => {
|
||||
const value = resolvedResult()
|
||||
|
||||
return value ? shortenPickerRecentPath(value, home()) : ""
|
||||
})
|
||||
|
||||
async function load(path: string, generation: number, priority: "user" | "background" = "user") {
|
||||
const key = path.replace(/\/+$/, "")
|
||||
setError(false)
|
||||
const absolute = absoluteTreePath(root(), key)
|
||||
setState("error", false)
|
||||
const absolute = absoluteTreePath(state.root, key)
|
||||
const existing = listings.get(key)
|
||||
|
||||
if (existing && !eager) loads.promote(`${generation}:${key}`)
|
||||
if (existing && priority === "user") loads.promote(`${generation}:${key}`)
|
||||
|
||||
const request =
|
||||
existing ??
|
||||
loads.schedule(`${generation}:${key}`, eager ? "background" : "user", () => {
|
||||
loads.schedule(`${generation}:${key}`, priority, () => {
|
||||
if (!activeTreeNavigation(generation, navigation)) return Promise.resolve(undefined)
|
||||
const current = location()
|
||||
|
||||
@@ -161,79 +240,226 @@ export function DirectoryPickerDialog(props: DirectoryPickerDialogProps) {
|
||||
if (!nodes) {
|
||||
listings.delete(key)
|
||||
|
||||
if (!key) setError(true)
|
||||
if (!key) setState("error", true)
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
tree?.batch(policy.entries(key, nodes).map((item) => ({ type: "add", path: item })))
|
||||
const isRepo = nodes.some((node) => node.name === ".git")
|
||||
const repoKey = pathKey(canonicalPickerPath(absolute))
|
||||
const newlyDiscoveredRepo = isRepo && !gitRepos.has(repoKey)
|
||||
|
||||
if (!eager && advanceTreePreload(advanced, key)) {
|
||||
for (const directory of preloadTreeDirectories(key, nodes)) void load(directory, generation, true)
|
||||
if (newlyDiscoveredRepo) gitRepos.add(repoKey)
|
||||
|
||||
const entries = policy
|
||||
.entries(
|
||||
key,
|
||||
nodes.filter((node) => node.name !== ".git"),
|
||||
)
|
||||
.filter((item) => !tree?.getItem(item))
|
||||
|
||||
if (entries.length > 0) {
|
||||
tree?.batch(entries.map((item) => ({ type: "add", path: item })))
|
||||
}
|
||||
|
||||
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")
|
||||
}
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
async function navigate(path: string) {
|
||||
const value = policy.navigation(pickerAbsoluteInput(cleanPickerInput(path), home(), root() || start() || home()))
|
||||
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
|
||||
setLoading(true)
|
||||
setRootValid(false)
|
||||
setSelected("")
|
||||
setSuggestionsOpen(false)
|
||||
setActiveSuggestion(-1)
|
||||
setRoot(value)
|
||||
setInput(displayPickerPath(value, value, home()))
|
||||
setState({
|
||||
loading: true,
|
||||
rootValid: false,
|
||||
selected: "",
|
||||
suggestionsOpen: false,
|
||||
activeSuggestion: -1,
|
||||
root: value,
|
||||
input: options?.input ?? "",
|
||||
})
|
||||
listings.clear()
|
||||
advanced.clear()
|
||||
tree?.resetPaths([])
|
||||
const valid = await load("", token)
|
||||
|
||||
if (!activeTreeNavigation(token, navigation)) return
|
||||
setRootValid(valid)
|
||||
setLoading(false)
|
||||
setState({
|
||||
rootValid: valid,
|
||||
loading: false,
|
||||
})
|
||||
|
||||
if (!valid) return
|
||||
|
||||
if (!options?.selectChild) {
|
||||
if (!tree?.getFocusedPath()) tree?.focusNearestPath(null)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
const entry = `${getFilename(options.selectChild)}/`
|
||||
selectOnlyTreeItem(entry)
|
||||
setState("selected", policy.selection(value, entry) ?? options.selectChild)
|
||||
}
|
||||
|
||||
async function selectDirectory(path: string, options?: { fromInput?: boolean }) {
|
||||
const value = policy.navigation(
|
||||
pickerAbsoluteInput(cleanPickerInput(path), home(), state.root || start() || home()),
|
||||
)
|
||||
|
||||
if (!value) return
|
||||
const nextInput = options?.fromInput ? displayInputDirectory(value) : state.input
|
||||
const relative = state.root && state.rootValid ? pickerRelativePath(state.root, value) : undefined
|
||||
|
||||
if (relative === "") {
|
||||
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,
|
||||
})
|
||||
|
||||
const ancestors = segments.slice(0, -1).map((_, index) => segments.slice(0, index + 1).join("/"))
|
||||
|
||||
for (const ancestor of ancestors) {
|
||||
const loaded = await load(ancestor, token)
|
||||
|
||||
if (!activeTreeNavigation(token, navigation)) return
|
||||
|
||||
if (!loaded) break
|
||||
expandTreeDirectory(ancestor)
|
||||
}
|
||||
|
||||
if (!tree?.getItem(entry)) {
|
||||
await navigate(value, { input: nextInput })
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
selectOnlyTreeItem(entry)
|
||||
setState("selected", policy.selection(state.root, entry) ?? value)
|
||||
|
||||
if (!options?.fromInput) return
|
||||
expandTreeDirectory(relative)
|
||||
await load(relative, token)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
const parent = pickerParent(value)
|
||||
const leaf = getFilename(value)
|
||||
|
||||
if (parent && leaf && parent !== value && parent === home()) {
|
||||
await navigate(parent, { selectChild: value, input: nextInput })
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
await navigate(value, { input: nextInput })
|
||||
}
|
||||
|
||||
function complete() {
|
||||
const items = currentSuggestions()
|
||||
const match = items[activeSuggestion()] ?? items[0]
|
||||
const match = items[state.activeSuggestion] ?? items[0]
|
||||
|
||||
if (!match) return
|
||||
const value = displayPickerPath(match.absolute, input(), home())
|
||||
setInput(match.type === "directory" && !value.endsWith("/") ? value + "/" : value)
|
||||
const value = displayPickerPath(match.absolute, state.input, home())
|
||||
setState("input", match.type === "directory" && !value.endsWith("/") ? value + "/" : value)
|
||||
|
||||
if (match.type === "file") {
|
||||
setSelected(policy.selection(root(), pickerFileSearchQuery(root(), match.absolute, home())) ?? "")
|
||||
setSuggestionsOpen(false)
|
||||
setActiveSuggestion(-1)
|
||||
setState({
|
||||
selected: policy.selection(state.root, pickerFileSearchQuery(state.root, match.absolute, home())) ?? "",
|
||||
suggestionsOpen: false,
|
||||
activeSuggestion: -1,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
function chooseSuggestion(suggestion: { absolute: string; type: "file" | "directory" }) {
|
||||
if (suggestion.type === "directory") {
|
||||
void navigate(suggestion.absolute)
|
||||
void selectDirectory(suggestion.absolute, { fromInput: true })
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
setInput(displayPickerPath(suggestion.absolute, input(), home()))
|
||||
setSelected(policy.selection(root(), pickerFileSearchQuery(root(), suggestion.absolute, home())) ?? "")
|
||||
setSuggestionsOpen(false)
|
||||
setActiveSuggestion(-1)
|
||||
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) {
|
||||
setSuggestionsOpen(true)
|
||||
setActiveSuggestion((current) => nextSuggestionIndex(current, delta, currentSuggestions().length))
|
||||
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() {
|
||||
const items = currentSuggestions()
|
||||
|
||||
return items[activeSuggestion()] ?? items[0]
|
||||
return currentSuggestions()[activeSuggestionIndex()]
|
||||
}
|
||||
|
||||
const keyActions = new Map([
|
||||
@@ -244,26 +470,49 @@ export function DirectoryPickerDialog(props: DirectoryPickerDialogProps) {
|
||||
() => {
|
||||
const suggestion = activeSuggestionValue()
|
||||
|
||||
if (suggestion) chooseSuggestion(suggestion)
|
||||
if (suggestion) {
|
||||
chooseSuggestion(suggestion)
|
||||
|
||||
if (!suggestion) void navigate(input())
|
||||
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
|
||||
|
||||
if (event.key === "Tab" && event.shiftKey) return
|
||||
event.preventDefault()
|
||||
action()
|
||||
}
|
||||
|
||||
function resolve() {
|
||||
const path = policy.result(root(), selected(), rootValid())
|
||||
const path = resolvedResult()
|
||||
|
||||
if (!path) return
|
||||
props.onSelect(props.multiple ? [path] : path)
|
||||
@@ -273,8 +522,10 @@ export function DirectoryPickerDialog(props: DirectoryPickerDialogProps) {
|
||||
onMount(() => {
|
||||
const closeSuggestions = (event: PointerEvent) => {
|
||||
if (event.target instanceof Node && pathArea?.contains(event.target)) return
|
||||
setSuggestionsOpen(false)
|
||||
setActiveSuggestion(-1)
|
||||
setState({
|
||||
suggestionsOpen: false,
|
||||
activeSuggestion: -1,
|
||||
})
|
||||
}
|
||||
|
||||
document.addEventListener("pointerdown", closeSuggestions)
|
||||
@@ -283,18 +534,111 @@ export function DirectoryPickerDialog(props: DirectoryPickerDialogProps) {
|
||||
paths: [],
|
||||
flattenEmptyDirectories: false,
|
||||
initialExpansion: "closed",
|
||||
itemHeight: 24,
|
||||
stickyFolders: true,
|
||||
icons: {
|
||||
spriteSheet: TREE_SPRITE_SHEET,
|
||||
remap: {
|
||||
"file-tree-icon-chevron": {
|
||||
name: "picker-chevron-down",
|
||||
width: 14,
|
||||
height: 14,
|
||||
viewBox: "0 0 14 14",
|
||||
},
|
||||
},
|
||||
},
|
||||
renderRowDecoration(context) {
|
||||
if (context.row.kind !== "directory") return null
|
||||
const key = pathKey(canonicalPickerPath(absoluteTreePath(state.root, context.item.path)))
|
||||
|
||||
if (!gitRepos.has(key) && !knownGitRepos().has(key)) return null
|
||||
|
||||
return { text: language.t("dialog.directory.gitRepo") }
|
||||
},
|
||||
unsafeCSS: `
|
||||
button[data-type="item"] {
|
||||
height: 24px !important;
|
||||
min-height: 24px !important;
|
||||
padding: 4px 8px !important;
|
||||
margin: 0 !important;
|
||||
gap: 6px !important;
|
||||
border-radius: 4px !important;
|
||||
background: transparent !important;
|
||||
box-shadow: none !important;
|
||||
color: var(--v2-text-text-muted) !important;
|
||||
font-size: 13px !important;
|
||||
font-weight: 440 !important;
|
||||
letter-spacing: -0.04px !important;
|
||||
}
|
||||
button[data-type="item"]:hover {
|
||||
background: var(--v2-overlay-simple-overlay-hover) !important;
|
||||
color: var(--v2-text-text-muted) !important;
|
||||
}
|
||||
button[data-type="item"][data-file-tree-sticky-row="true"] {
|
||||
background-color: var(--v2-background-bg-base) !important;
|
||||
}
|
||||
button[data-type="item"][data-file-tree-sticky-row="true"]:hover {
|
||||
background:
|
||||
linear-gradient(0deg, var(--v2-overlay-simple-overlay-hover), var(--v2-overlay-simple-overlay-hover)),
|
||||
var(--v2-background-bg-base) !important;
|
||||
}
|
||||
button[data-type="item"][aria-selected="true"],
|
||||
button[data-type="item"][data-item-selected="true"] {
|
||||
background:
|
||||
linear-gradient(0deg, var(--v2-overlay-simple-overlay-pressed), var(--v2-overlay-simple-overlay-pressed)),
|
||||
var(--v2-background-bg-base) !important;
|
||||
box-shadow: inset 0 0 0 0.5px var(--v2-border-border-base) !important;
|
||||
color: var(--v2-text-text-base) !important;
|
||||
font-weight: 530 !important;
|
||||
}
|
||||
button[data-type="item"]:focus-visible {
|
||||
outline: none !important;
|
||||
box-shadow: none !important;
|
||||
}
|
||||
[data-item-type="folder"] > [data-item-section="icon"] {
|
||||
width: auto !important;
|
||||
gap: 6px !important;
|
||||
color: var(--v2-icon-icon-muted) !important;
|
||||
}
|
||||
[data-item-type="folder"] > [data-item-section="icon"] > svg {
|
||||
width: 14px !important;
|
||||
height: 14px !important;
|
||||
flex-shrink: 0 !important;
|
||||
transform: none !important;
|
||||
}
|
||||
[aria-expanded="false"][data-item-type="folder"]
|
||||
> [data-item-section="icon"]
|
||||
> [data-icon-name="file-tree-icon-chevron"] {
|
||||
transform: rotate(-90deg) !important;
|
||||
}
|
||||
[data-item-type="folder"] > [data-item-section="icon"]::after {
|
||||
content: "";
|
||||
display: block;
|
||||
width: 14px;
|
||||
height: 14px;
|
||||
flex-shrink: 0;
|
||||
background-color: currentColor;
|
||||
-webkit-mask-image: ${FOLDER_CLOSED_MASK};
|
||||
mask-image: ${FOLDER_CLOSED_MASK};
|
||||
-webkit-mask-repeat: no-repeat;
|
||||
mask-repeat: no-repeat;
|
||||
-webkit-mask-size: 14px 14px;
|
||||
mask-size: 14px 14px;
|
||||
}
|
||||
[aria-expanded="true"][data-item-type="folder"] > [data-item-section="icon"]::after,
|
||||
[data-file-tree-sticky-row="true"][data-item-type="folder"] > [data-item-section="icon"]::after {
|
||||
-webkit-mask-image: ${FOLDER_OPEN_MASK};
|
||||
mask-image: ${FOLDER_OPEN_MASK};
|
||||
}
|
||||
[data-item-section="decoration"] > span {
|
||||
height: 16px;
|
||||
padding: 0 4px;
|
||||
border-radius: 2px;
|
||||
background: var(--v2-background-bg-layer-03);
|
||||
color: var(--v2-text-text-muted);
|
||||
font-size: 11px;
|
||||
font-weight: 530;
|
||||
line-height: 12px;
|
||||
letter-spacing: 0.05px;
|
||||
}
|
||||
[data-file-tree-virtualized-scroll] {
|
||||
overscroll-behavior: contain;
|
||||
@@ -306,7 +650,7 @@ export function DirectoryPickerDialog(props: DirectoryPickerDialogProps) {
|
||||
},
|
||||
onSelectionChange(paths) {
|
||||
const path = paths.at(-1)
|
||||
setSelected(path ? (policy.selection(root(), path) ?? "") : "")
|
||||
setState("selected", path ? (policy.selection(state.root, path) ?? "") : "")
|
||||
},
|
||||
})
|
||||
|
||||
@@ -318,53 +662,78 @@ export function DirectoryPickerDialog(props: DirectoryPickerDialogProps) {
|
||||
createEffect(() => {
|
||||
const path = start()
|
||||
|
||||
if (!path || !location() || root()) return
|
||||
if (!path || !location() || state.root) return
|
||||
void navigate(path)
|
||||
})
|
||||
|
||||
onCleanup(() => tree?.cleanUp())
|
||||
|
||||
return (
|
||||
<Dialog size="large" class="directory-picker">
|
||||
<Dialog size="large" fit class="directory-picker">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{props.title ?? language.t("command.project.open")}</DialogTitle>
|
||||
<div class="directory-picker-header">
|
||||
<DialogTitle>{props.title ?? language.t("command.project.open")}</DialogTitle>
|
||||
<Show when={subtitle()}>
|
||||
{(value) => (
|
||||
<div class="directory-picker-subtitle" dir="ltr">
|
||||
{value()}
|
||||
</div>
|
||||
)}
|
||||
</Show>
|
||||
</div>
|
||||
</DialogHeader>
|
||||
<Divider />
|
||||
<DialogBody class="directory-picker-body pt-4!">
|
||||
<DialogBody class="directory-picker-body">
|
||||
<div class="directory-picker-path" ref={pathArea}>
|
||||
<TextInput
|
||||
value={input()}
|
||||
value={state.input}
|
||||
placeholder={language.t("dialog.directory.search.placeholder")}
|
||||
autofocus
|
||||
autocomplete="off"
|
||||
spellcheck={false}
|
||||
class="!w-full"
|
||||
showClearButton={!!state.input}
|
||||
onClearClick={() => {
|
||||
setState({
|
||||
input: "",
|
||||
suggestionsOpen: false,
|
||||
activeSuggestion: -1,
|
||||
})
|
||||
}}
|
||||
class="directory-picker-input"
|
||||
onInput={(event) => {
|
||||
setInput(cleanPickerInput(event.currentTarget.value))
|
||||
setSelected("")
|
||||
setSuggestionsOpen(true)
|
||||
setActiveSuggestion(-1)
|
||||
setState({
|
||||
input: cleanPickerInput(event.currentTarget.value),
|
||||
selected: "",
|
||||
suggestionsOpen: true,
|
||||
activeSuggestion: -1,
|
||||
})
|
||||
}}
|
||||
role="combobox"
|
||||
aria-label={language.t("dialog.directory.search.placeholder")}
|
||||
aria-autocomplete="list"
|
||||
aria-expanded={suggestionsOpen()}
|
||||
aria-expanded={state.suggestionsOpen}
|
||||
aria-controls="directory-picker-suggestions"
|
||||
aria-activedescendant={
|
||||
activeSuggestion() >= 0 ? `directory-picker-suggestion-${activeSuggestion()}` : undefined
|
||||
activeSuggestionIndex() >= 0 ? `directory-picker-suggestion-${activeSuggestionIndex()}` : undefined
|
||||
}
|
||||
onKeyDown={handleInputKey}
|
||||
/>
|
||||
<div class="directory-picker-actions">
|
||||
<Button size="small" variant="ghost" onClick={() => void navigate(home())}>
|
||||
<Button size="normal" variant="ghost" onClick={() => void navigate(home() || state.root)}>
|
||||
~
|
||||
</Button>
|
||||
<Button size="small" variant="ghost" onClick={() => void navigate(pickerRoot(root()) || root())}>
|
||||
<Button size="normal" variant="ghost" onClick={() => void navigate(pickerRoot(state.root) || state.root)}>
|
||||
{language.t("dialog.directory.root")}
|
||||
</Button>
|
||||
<Button size="small" variant="ghost" onClick={() => void navigate(pickerParent(root()))}>
|
||||
<Button
|
||||
size="normal"
|
||||
variant="ghost"
|
||||
onClick={() => void navigate(pickerParent(state.selected || state.root))}
|
||||
>
|
||||
{language.t("dialog.directory.parent")}
|
||||
</Button>
|
||||
</div>
|
||||
<Show when={suggestionsOpen() && currentSuggestions().length > 0}>
|
||||
<Show when={state.suggestionsOpen && currentSuggestions().length > 0}>
|
||||
<div id="directory-picker-suggestions" role="listbox" class="directory-picker-suggestions">
|
||||
<For each={currentSuggestions()}>
|
||||
{(suggestion, index) => (
|
||||
@@ -372,12 +741,12 @@ export function DirectoryPickerDialog(props: DirectoryPickerDialogProps) {
|
||||
id={`directory-picker-suggestion-${index()}`}
|
||||
data-directory-path={suggestion.absolute}
|
||||
role="option"
|
||||
aria-selected={index() === activeSuggestion()}
|
||||
data-active={index() === activeSuggestion() ? "" : undefined}
|
||||
onPointerMove={() => setActiveSuggestion(index())}
|
||||
aria-selected={index() === activeSuggestionIndex()}
|
||||
data-active={index() === activeSuggestionIndex() ? "" : undefined}
|
||||
onPointerMove={() => setState("activeSuggestion", index())}
|
||||
onClick={() => chooseSuggestion(suggestion)}
|
||||
>
|
||||
{displayPickerPath(suggestion.absolute, input(), home())}
|
||||
{displayPickerPath(suggestion.absolute, state.input, home())}
|
||||
{suggestion.type === "directory" ? "/" : ""}
|
||||
</button>
|
||||
)}
|
||||
@@ -385,6 +754,44 @@ export function DirectoryPickerDialog(props: DirectoryPickerDialogProps) {
|
||||
</div>
|
||||
</Show>
|
||||
</div>
|
||||
<Show when={recentProjects().length > 0}>
|
||||
<div class="directory-picker-recent">
|
||||
<div class="directory-picker-recent-label">{language.t("dialog.directory.recent")}</div>
|
||||
<div class="directory-picker-recent-list">
|
||||
<For each={recentProjects()}>
|
||||
{(project) => {
|
||||
const name = () => displayName(project)
|
||||
const fullPath = () => displayPickerPath(project.worktree, "", home())
|
||||
const shortPath = () => shortenPickerRecentPath(project.worktree, home())
|
||||
|
||||
return (
|
||||
<Tooltip placement="top" value={<bdi dir="ltr">{fullPath()}</bdi>}>
|
||||
<Button
|
||||
size="normal"
|
||||
variant="neutral"
|
||||
class="directory-picker-recent-item"
|
||||
aria-label={language.t("dialog.directory.recentProject", {
|
||||
name: name(),
|
||||
path: shortPath(),
|
||||
})}
|
||||
onClick={() => void selectDirectory(project.worktree)}
|
||||
>
|
||||
<ProjectAvatar
|
||||
class="shrink-0"
|
||||
aria-hidden="true"
|
||||
fallback={name()}
|
||||
src={getProjectAvatarSource(project.id, project.icon)}
|
||||
variant={getProjectAvatarVariant(project.icon?.color)}
|
||||
/>
|
||||
<span class="min-w-0 truncate">{name()}</span>
|
||||
</Button>
|
||||
</Tooltip>
|
||||
)
|
||||
}}
|
||||
</For>
|
||||
</div>
|
||||
</div>
|
||||
</Show>
|
||||
<div
|
||||
class="directory-picker-browser"
|
||||
ref={container}
|
||||
@@ -393,20 +800,29 @@ export function DirectoryPickerDialog(props: DirectoryPickerDialogProps) {
|
||||
on:touchmove={(event) => event.stopPropagation()}
|
||||
on:wheel={{ handleEvent: (event: WheelEvent) => event.stopPropagation(), passive: true }}
|
||||
>
|
||||
<Show when={loading()}>
|
||||
<Show when={state.loading}>
|
||||
<div class="directory-picker-state">{language.t("common.loading")}</div>
|
||||
</Show>
|
||||
<Show when={!loading() && error()}>
|
||||
<Show when={!state.loading && state.error}>
|
||||
<div class="directory-picker-state">{language.t("dialog.directory.readError")}</div>
|
||||
</Show>
|
||||
</div>
|
||||
<div class="directory-picker-selection">{policy.result(root(), selected(), rootValid())}</div>
|
||||
</DialogBody>
|
||||
<DialogFooter>
|
||||
<Tooltip
|
||||
placement="top"
|
||||
disabled={!fullSelectionPath() || fullSelectionPath() === shortSelectionPath()}
|
||||
value={<bdi dir="ltr">{fullSelectionPath()}</bdi>}
|
||||
class="directory-picker-selection"
|
||||
>
|
||||
<span dir="ltr" class="directory-picker-selection-text">
|
||||
{shortSelectionPath()}
|
||||
</span>
|
||||
</Tooltip>
|
||||
<Button variant="neutral" onClick={() => dialog.close()}>
|
||||
{language.t("common.cancel")}
|
||||
</Button>
|
||||
<Button variant="contrast" disabled={!policy.result(root(), selected(), rootValid())} onClick={resolve}>
|
||||
<Button variant="contrast" disabled={!resolvedResult()} onClick={resolve}>
|
||||
{action[policy.action]}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
|
||||
@@ -2,12 +2,10 @@ import { expect, test } from "bun:test"
|
||||
import {
|
||||
absoluteTreePath,
|
||||
activeTreeNavigation,
|
||||
advanceTreePreload,
|
||||
nextSuggestionIndex,
|
||||
nextTreeScrollTop,
|
||||
pickerFileSearchQuery,
|
||||
pickerMode,
|
||||
preloadTreeDirectories,
|
||||
selectedTreePath,
|
||||
treeEntries,
|
||||
treePathWithin,
|
||||
@@ -16,6 +14,7 @@ import {
|
||||
createPriorityTaskQueue,
|
||||
listPickerDirectory,
|
||||
displayPickerPath,
|
||||
shortenPickerRecentPath,
|
||||
pickerParent,
|
||||
pickerRoot,
|
||||
pickerAbsoluteInput,
|
||||
@@ -114,6 +113,12 @@ test.each([
|
||||
["relative input", pickerAbsoluteInput("src", "C:/Users/luke", "C:/Users/luke/repo"), "C:/Users/luke/repo/src"],
|
||||
["file search", pickerFileSearchQuery("/home/luke/repos", "/home/luke/repos/src/in", "/home/luke"), "src/in"],
|
||||
["file search", pickerFileSearchQuery("/home/luke", "~/repos/op", "/home/luke"), "repos/op"],
|
||||
["recent short 2-level tilde", shortenPickerRecentPath("/home/luke/Developer/opencode", "/home/luke"), "~/Developer/opencode"],
|
||||
["recent deep tilde", shortenPickerRecentPath("/home/luke/workspaces/anomalyco/opencode/packages/app", "/home/luke"), "~/…/packages/app"],
|
||||
["recent short 2-level root", shortenPickerRecentPath("/workspace/billing-api", "/home/luke"), "/workspace/billing-api"],
|
||||
["recent deep root", shortenPickerRecentPath("/srv/clients/acme/services/payments-gateway", "/home/luke"), "/srv/…/services/payments-gateway"],
|
||||
["recent short Windows", shortenPickerRecentPath("C:/OpenCode/NewProject", ""), "C:\\OpenCode\\NewProject"],
|
||||
["recent deep Windows", shortenPickerRecentPath("C:/Users/luke/work/acme/repo", "C:/Users/luke"), "C:\\…\\acme\\repo"],
|
||||
])("uses the selected server path format for %s: %p", (_name, actual, expected) => {
|
||||
expect(actual).toBe(expected)
|
||||
})
|
||||
@@ -122,6 +127,7 @@ 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 () => {
|
||||
@@ -390,21 +396,6 @@ test("searches from an absolute root without a default base", async () => {
|
||||
expect(directories).toEqual(["/"])
|
||||
})
|
||||
|
||||
test("identifies the next directory level to preload once for every expanded directory", () => {
|
||||
expect(
|
||||
preloadTreeDirectories("src/", [
|
||||
{ name: "components", type: "directory" },
|
||||
{ name: "index.ts", type: "file" },
|
||||
{ name: "utils", type: "directory" },
|
||||
]),
|
||||
).toEqual(["src/components/", "src/utils/"])
|
||||
|
||||
const advanced = new Set<string>()
|
||||
expect(advanceTreePreload(advanced, "")).toBeTrue()
|
||||
expect(advanceTreePreload(advanced, "")).toBeFalse()
|
||||
expect(advanceTreePreload(advanced, "repos/")).toBeTrue()
|
||||
})
|
||||
|
||||
test("limits background tasks and prioritizes newly requested work", async () => {
|
||||
const queue = createPriorityTaskQueue<void>(2)
|
||||
const first = Promise.withResolvers<void>()
|
||||
|
||||
@@ -123,27 +123,14 @@ 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) {
|
||||
if (result?.query !== query) return []
|
||||
|
||||
return result.items
|
||||
}
|
||||
|
||||
export function preloadTreeDirectories(
|
||||
parent: string,
|
||||
nodes: ReadonlyArray<{ name: string; type: "file" | "directory" }>,
|
||||
export function currentPickerSuggestions<T>(
|
||||
result: { query: string; items: readonly T[] } | undefined,
|
||||
query: string,
|
||||
loading = false,
|
||||
) {
|
||||
return treeEntries(
|
||||
parent,
|
||||
nodes.filter((node) => node.type === "directory"),
|
||||
)
|
||||
}
|
||||
if (result?.query !== query && !loading) return []
|
||||
|
||||
export function advanceTreePreload(advanced: Set<string>, path: string) {
|
||||
if (advanced.has(path)) return false
|
||||
advanced.add(path)
|
||||
|
||||
return true
|
||||
return result?.items ?? []
|
||||
}
|
||||
|
||||
export function activeTreeNavigation(request: number, current: number) {
|
||||
@@ -384,6 +371,36 @@ export function displayPickerPath(path: string, input: string, home: string) {
|
||||
return pickerTilde(value, home) || value
|
||||
}
|
||||
|
||||
export function shortenPickerRecentPath(path: string, home: string) {
|
||||
const display = displayPickerPath(path, "", home)
|
||||
|
||||
if (display.startsWith("~/")) {
|
||||
const parts = display.slice(2).split("/").filter(Boolean)
|
||||
|
||||
if (parts.length <= 2) return display
|
||||
|
||||
return `~/…/${parts.slice(-2).join("/")}`
|
||||
}
|
||||
|
||||
if (display.startsWith("/") && !display.startsWith("//")) {
|
||||
const parts = display.slice(1).split("/").filter(Boolean)
|
||||
|
||||
if (parts.length <= 2) return display
|
||||
|
||||
return `/${parts[0]}/…/${parts.slice(-2).join("/")}`
|
||||
}
|
||||
|
||||
if (/^[A-Za-z]:\\/.test(display)) {
|
||||
const parts = display.split("\\").filter(Boolean)
|
||||
|
||||
if (parts.length <= 3) return display
|
||||
|
||||
return `${parts[0]}\\…\\${parts.slice(-2).join("\\")}`
|
||||
}
|
||||
|
||||
return display
|
||||
}
|
||||
|
||||
export async function listPickerDirectory(
|
||||
sdk: ServerSDK,
|
||||
location: { directory: string; workspace?: string },
|
||||
|
||||
Reference in New Issue
Block a user