perf(webui): bound workspace picker rendering and directory scans
This commit is contained in:
1 parent
63e172b2b1
commit
0246d6500b
13 files changed
+155
-100
No files matched your search
@@ -7,6 +7,7 @@ import os
|
||||
import platform
|
||||
import socket
|
||||
import stat
|
||||
from collections.abc import Iterator
|
||||
from pathlib import Path
|
||||
from typing import TypedDict
|
||||
|
||||
@@ -57,27 +58,29 @@ def browse_workspace_directories(
|
||||
partial = True
|
||||
path = path.resolve(strict=True)
|
||||
folded_query = query.casefold()
|
||||
matches: list[ProjectDirectory] = []
|
||||
with os.scandir(path) as entries:
|
||||
for entry in entries:
|
||||
name = entry.name.casefold()
|
||||
if not name.startswith(prefix) or folded_query not in name:
|
||||
continue
|
||||
try:
|
||||
if not entry.is_dir():
|
||||
def matching_directories() -> Iterator[ProjectDirectory]:
|
||||
with os.scandir(path) as entries:
|
||||
for entry in entries:
|
||||
name = entry.name.casefold()
|
||||
if not name.startswith(prefix) or folded_query not in name:
|
||||
continue
|
||||
hidden = entry.name.startswith(".") or (
|
||||
os.name == "nt"
|
||||
and bool(entry.stat(follow_symlinks=False).st_file_attributes & stat.FILE_ATTRIBUTE_HIDDEN)
|
||||
)
|
||||
if show_hidden or prefix.startswith(".") or not hidden:
|
||||
matches.append({"name": entry.name, "path": entry.path})
|
||||
except OSError:
|
||||
continue
|
||||
try:
|
||||
if not entry.is_dir():
|
||||
continue
|
||||
hidden = entry.name.startswith(".") or (
|
||||
os.name == "nt"
|
||||
and bool(entry.stat(follow_symlinks=False).st_file_attributes & stat.FILE_ATTRIBUTE_HIDDEN)
|
||||
)
|
||||
if show_hidden or prefix.startswith(".") or not hidden:
|
||||
yield {"name": entry.name, "path": entry.path}
|
||||
except OSError:
|
||||
continue
|
||||
|
||||
matches = heapq.nsmallest(501, matching_directories(), key=lambda item: item["name"].casefold())
|
||||
return {
|
||||
"path": str(path),
|
||||
"parent": str(path.parent) if path.parent != path else None,
|
||||
"entries": heapq.nsmallest(500, matches, key=lambda item: item["name"].casefold()),
|
||||
"entries": matches[:500],
|
||||
"partial": partial,
|
||||
"truncated": len(matches) > 500,
|
||||
"host": socket.gethostname(),
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { FullAccessIcon, WorkspaceIcon, RestrictedAccessIcon } from "@/components/icons/product-icons";
|
||||
import type { ReactElement } from "react";
|
||||
import type { HTMLAttributes, ReactElement } from "react";
|
||||
import { useCallback, useEffect, useId, useLayoutEffect, useMemo, useRef, useState } from "react";
|
||||
import { Check, FolderOpen, Search, Star } from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
@@ -43,6 +43,58 @@ function WorkspacePickerTooltip({ label, children }: { label: string; children:
|
||||
);
|
||||
}
|
||||
|
||||
const DIRECTORY_ROW_HEIGHT = 44;
|
||||
const DIRECTORY_OVERSCAN = 4;
|
||||
|
||||
function WorkspaceDirectoryColumn({ options, activeIndex, renderOption, children, ...props }: {
|
||||
options: PickerOption[];
|
||||
activeIndex: number | null;
|
||||
renderOption: (option: PickerOption, index: number) => ReactElement;
|
||||
} & HTMLAttributes<HTMLDivElement>) {
|
||||
const viewportRef = useRef<HTMLDivElement>(null);
|
||||
const [firstRow, setFirstRow] = useState(0);
|
||||
const [visibleRows, setVisibleRows] = useState(1);
|
||||
useLayoutEffect(() => {
|
||||
const viewport = viewportRef.current;
|
||||
if (!viewport) return;
|
||||
const measure = () => setVisibleRows(Math.max(1, Math.ceil(viewport.clientHeight / DIRECTORY_ROW_HEIGHT)));
|
||||
measure();
|
||||
const observer = new ResizeObserver(measure);
|
||||
observer.observe(viewport);
|
||||
return () => observer.disconnect();
|
||||
}, []);
|
||||
useLayoutEffect(() => {
|
||||
const viewport = viewportRef.current;
|
||||
if (!viewport) return;
|
||||
viewport.scrollTop = 0;
|
||||
setFirstRow(0);
|
||||
}, [options]);
|
||||
useLayoutEffect(() => {
|
||||
const viewport = viewportRef.current;
|
||||
if (!viewport || activeIndex === null) return;
|
||||
const top = activeIndex * DIRECTORY_ROW_HEIGHT + 4;
|
||||
const bottom = top + DIRECTORY_ROW_HEIGHT;
|
||||
if (top < viewport.scrollTop) viewport.scrollTop = top;
|
||||
else if (bottom > viewport.scrollTop + viewport.clientHeight) viewport.scrollTop = Math.max(0, bottom - viewport.clientHeight);
|
||||
setFirstRow(Math.floor(viewport.scrollTop / DIRECTORY_ROW_HEIGHT));
|
||||
}, [activeIndex, visibleRows, options]);
|
||||
const start = Math.max(0, firstRow - DIRECTORY_OVERSCAN);
|
||||
const end = Math.min(options.length, firstRow + visibleRows + DIRECTORY_OVERSCAN);
|
||||
return (
|
||||
<div {...props} ref={viewportRef} onScroll={event => setFirstRow(Math.floor(event.currentTarget.scrollTop / DIRECTORY_ROW_HEIGHT))}>
|
||||
<div role="presentation" className="relative" style={{ height: options.length * DIRECTORY_ROW_HEIGHT }}>
|
||||
{options.slice(start, end).map((option, offset) => {
|
||||
const index = start + offset;
|
||||
return <div key={`${option.kind}-${option.path}`} role="presentation" className="absolute inset-x-0" style={{ top: index * DIRECTORY_ROW_HEIGHT }}>
|
||||
{renderOption(option, index)}
|
||||
</div>;
|
||||
})}
|
||||
</div>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function WorkspaceDirectorySkeleton() {
|
||||
const { t } = useTranslation();
|
||||
const viewportRef = useRef<HTMLDivElement>(null);
|
||||
@@ -50,7 +102,7 @@ function WorkspaceDirectorySkeleton() {
|
||||
useLayoutEffect(() => {
|
||||
const viewport = viewportRef.current;
|
||||
if (!viewport) return;
|
||||
const measure = () => setRows(Math.max(1, Math.ceil(viewport.clientHeight / 44)));
|
||||
const measure = () => setRows(Math.max(1, Math.ceil(viewport.clientHeight / DIRECTORY_ROW_HEIGHT)));
|
||||
measure();
|
||||
const observer = new ResizeObserver(measure);
|
||||
observer.observe(viewport);
|
||||
@@ -245,6 +297,16 @@ export function WorkspaceProjectPicker({ isHero, connected = false, disabled, sc
|
||||
if (viewport) viewport.scrollLeft = viewport.clientWidth * Math.max(0, previousColumns.length + 1 - visibleColumns) / visibleColumns;
|
||||
}, [previousColumns.length, visibleColumns]);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const viewport = columnsRef.current;
|
||||
if (!viewport || !highlightActive) return;
|
||||
const width = viewport.clientWidth / visibleColumns;
|
||||
const left = activeColumn * width;
|
||||
const right = left + width;
|
||||
if (left < viewport.scrollLeft) viewport.scrollLeft = left;
|
||||
else if (right > viewport.scrollLeft + viewport.clientWidth) viewport.scrollLeft = right - viewport.clientWidth;
|
||||
}, [activeColumn, highlightActive, visibleColumns]);
|
||||
|
||||
function changeDraft(value: string, resetColumns = true) {
|
||||
setHighlightActive(false);
|
||||
if (resetColumns) { setPreviousColumns([]); setActiveColumn(0); }
|
||||
@@ -330,9 +392,10 @@ export function WorkspaceProjectPicker({ isHero, connected = false, disabled, sc
|
||||
...(defaultScope ? [{ name: t("workspace.dialog.defaultProject"), path: defaultScope.project_path }] : []),
|
||||
...(currentProjectScope ? [{ name: projectLabel, path: currentProjectScope.project_path }] : []),
|
||||
].filter((project, index, all) => all.findIndex(item => sameWorkspacePath(item.path, project.path)) === index && !isFavorite(project.path));
|
||||
const options: PickerOption[] = directory && !loading
|
||||
? directory.entries.map(entry => ({ ...entry, kind: "directory" })) : [];
|
||||
if (!canBrowse && absoluteDraft) options.push({ name: t("workspace.dialog.usePath"), path: pathDraft.trim(), kind: "manual" });
|
||||
const options = useMemo<PickerOption[]>(() => {
|
||||
if (directory && !loading) return directory.entries.map(entry => ({ ...entry, kind: "directory" }));
|
||||
return !canBrowse && absoluteDraft ? [{ name: t("workspace.dialog.usePath"), path: pathDraft.trim(), kind: "manual" }] : [];
|
||||
}, [directory, loading, canBrowse, absoluteDraft, pathDraft, t]);
|
||||
function openShortcut(project: ProjectDirectory) {
|
||||
if (!canBrowse) { void chooseProject(project.path, project.name); return; }
|
||||
setBasePath(project.path);
|
||||
@@ -354,8 +417,9 @@ export function WorkspaceProjectPicker({ isHero, connected = false, disabled, sc
|
||||
const id = ++completionRequest.current;
|
||||
const session = pickerSession.current;
|
||||
try {
|
||||
const result = await directoryCache.load(request.path, request.query, showHidden || request.query.startsWith("."));
|
||||
const result = await directoryCache.load(requestedPath, folderQuery, showHidden || request.query.startsWith("."), true);
|
||||
if (id !== completionRequest.current || session !== pickerSession.current) return;
|
||||
if (absoluteDraft && !result.partial && request.query) { navigate(result.path); return; }
|
||||
const prefix = request.query.toLocaleLowerCase();
|
||||
const first = result.entries.find(entry => entry.name.toLocaleLowerCase().startsWith(prefix));
|
||||
if (first) navigate(first.path);
|
||||
@@ -392,7 +456,7 @@ export function WorkspaceProjectPicker({ isHero, connected = false, disabled, sc
|
||||
if ((event.key === "ArrowDown" || event.key === "ArrowUp") && !event.altKey && activeOptions.length) {
|
||||
event.preventDefault();
|
||||
const next = (activeOption + (event.key === "ArrowDown" ? 1 : -1) + activeOptions.length) % activeOptions.length;
|
||||
setHighlightActive(true); setActiveIndex(next); document.getElementById(`${optionsId}-${activeColumn}-${next}`)?.scrollIntoView({ block: "nearest" });
|
||||
setHighlightActive(true); setActiveIndex(next);
|
||||
} else if (event.key === "ArrowLeft" && activeColumn > 0 && event.currentTarget.selectionStart === 0 && event.currentTarget.selectionEnd === 0) {
|
||||
event.preventDefault();
|
||||
const parent = columns[activeColumn - 1];
|
||||
@@ -429,9 +493,10 @@ export function WorkspaceProjectPicker({ isHero, connected = false, disabled, sc
|
||||
))}
|
||||
</nav>
|
||||
<div ref={attachColumns} data-workspace-columns className="flex flex-1 min-h-0 min-w-0 overflow-x-auto overscroll-x-contain">
|
||||
{columns.map((column, columnIndex) => <div key={columnIndex} id={`${optionsId}-${columnIndex}`} role="listbox" aria-label={column.path || t("thread.composer.workspace.projectAria")} aria-busy={columnIndex === previousColumns.length && loading} style={{ width: `${100 / visibleColumns}%` }} className={cn("min-w-0 shrink-0 overflow-x-hidden overflow-y-auto border-r border-transparent px-1 py-1", !!columns[columnIndex + 1]?.options.length && "border-border/50")}>
|
||||
{column.options.map((option, index) => <div key={`${option.kind}-${option.path}`} role="presentation" className="workspace-picker-row relative" data-keyboard-active={highlightActive && columnIndex === activeColumn && index === activeOption ? "" : undefined}>
|
||||
<button id={`${optionsId}-${columnIndex}-${index}`} type="button" role="option" aria-label={option.path} aria-selected={sameWorkspacePath(column.selectedPath, option.path)} disabled={pickingFolder}
|
||||
{columns.map((column, columnIndex) => <WorkspaceDirectoryColumn key={columnIndex} options={column.options} activeIndex={highlightActive && columnIndex === activeColumn ? activeOption : null}
|
||||
id={`${optionsId}-${columnIndex}`} role="listbox" aria-label={column.path || t("thread.composer.workspace.projectAria")} aria-busy={columnIndex === previousColumns.length && loading} style={{ width: `${100 / visibleColumns}%` }} className={cn("min-w-0 shrink-0 overflow-x-hidden overflow-y-auto border-r border-transparent px-1 py-1", !!columns[columnIndex + 1]?.options.length && "border-border/50")}
|
||||
renderOption={(option, index) => <div role="presentation" className="workspace-picker-row relative" data-keyboard-active={highlightActive && columnIndex === activeColumn && index === activeOption ? "" : undefined}>
|
||||
<button id={`${optionsId}-${columnIndex}-${index}`} type="button" role="option" aria-label={option.path} aria-selected={sameWorkspacePath(column.selectedPath, option.path)} aria-posinset={index + 1} aria-setsize={column.options.length} disabled={pickingFolder}
|
||||
onPointerMove={() => { setHighlightActive(false); setActiveColumn(columnIndex); setActiveIndex(index); }}
|
||||
onMouseDown={event => event.preventDefault()} onClick={() => activate(option, columnIndex)}
|
||||
className={cn(floatingItemClassName, floatingItemFocusClassName, "flex min-h-11 w-full min-w-0 items-center gap-3 px-3 py-2 text-left hover:bg-foreground/[0.055] dark:hover:bg-white/[0.08] disabled:opacity-50", canFavorite && "pr-12",
|
||||
@@ -441,11 +506,11 @@ export function WorkspaceProjectPicker({ isHero, connected = false, disabled, sc
|
||||
{sameWorkspacePath(option.path, scope?.project_path ?? defaultScope.project_path) && <Check className="h-4 w-4 shrink-0 text-muted-foreground" />}
|
||||
</button>
|
||||
{favoriteButton(option.path)}
|
||||
</div>)}
|
||||
</div>}>
|
||||
{columnIndex === previousColumns.length && loading && <WorkspaceDirectorySkeleton />}
|
||||
{columnIndex === previousColumns.length && directory?.truncated && <p className="px-3 py-2 text-[11px] text-muted-foreground">{t("workspace.picker.truncated")}</p>}
|
||||
{columnIndex === previousColumns.length && displayedError && <p id={errorId} role="alert" className="px-3 py-2 text-[11.5px] text-destructive">{displayedError}</p>}
|
||||
</div>)}
|
||||
</WorkspaceDirectoryColumn>)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex shrink-0 items-center justify-between gap-2 px-2 pt-1">
|
||||
|
||||
@@ -2486,30 +2486,24 @@
|
||||
"dialog": {
|
||||
"defaultProject": "Default workspace",
|
||||
"manual": "Paste path",
|
||||
"manualPlaceholder": "/Users/name/project",
|
||||
"usePath": "Use Path",
|
||||
"absolutePathRequired": "Enter an absolute folder path on this machine."
|
||||
},
|
||||
"picker": {
|
||||
"favorites": "Favorites",
|
||||
"recent": "Recent projects",
|
||||
"directories": "Folders",
|
||||
"pin": "Pin {{name}}",
|
||||
"unpin": "Unpin {{name}}",
|
||||
"description": "Search recent projects or choose a folder on the connected host.",
|
||||
"emptyProjects": "No matching projects",
|
||||
"search": "Enter a path or filter this folder…",
|
||||
"shortcuts": "Saved locations",
|
||||
"favoriteHint": "Use a folder’s star to add it here.",
|
||||
"native": "Use system folder picker…",
|
||||
"up": "Parent directory",
|
||||
"loading": "Loading folders…",
|
||||
"emptyDirectories": "No matching folders",
|
||||
"truncated": "Showing 500 folders. Continue typing the path to narrow the list.",
|
||||
"hidden": "Show hidden folders",
|
||||
"select": "Select",
|
||||
"switchDirectory": "Switch working directory",
|
||||
"selectDirectory": "Select this folder"
|
||||
"switchDirectory": "Switch working directory"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2287,30 +2287,24 @@
|
||||
"dialog": {
|
||||
"defaultProject": "Espacio de trabajo predeterminado",
|
||||
"manual": "Pegar ruta",
|
||||
"manualPlaceholder": "/Users/name/project",
|
||||
"usePath": "Usar ruta",
|
||||
"absolutePathRequired": "Introduce una ruta absoluta de carpeta en esta máquina."
|
||||
},
|
||||
"picker": {
|
||||
"favorites": "Favoritos",
|
||||
"recent": "Proyectos recientes",
|
||||
"directories": "Carpetas",
|
||||
"pin": "Fijar {{name}}",
|
||||
"unpin": "Desfijar {{name}}",
|
||||
"description": "Busca proyectos recientes o elige una carpeta en el equipo conectado.",
|
||||
"emptyProjects": "No hay proyectos coincidentes",
|
||||
"search": "Introduce una ruta o filtra esta carpeta…",
|
||||
"shortcuts": "Ubicaciones guardadas",
|
||||
"favoriteHint": "Pulsa la estrella de una carpeta para añadirla aquí.",
|
||||
"native": "Usar el selector de carpetas del sistema…",
|
||||
"up": "Carpeta superior",
|
||||
"loading": "Cargando carpetas…",
|
||||
"emptyDirectories": "No hay carpetas coincidentes",
|
||||
"truncated": "Se muestran 500 carpetas. Sigue escribiendo la ruta para reducir la lista.",
|
||||
"hidden": "Mostrar carpetas ocultas",
|
||||
"select": "Seleccionar",
|
||||
"switchDirectory": "Cambiar directorio de trabajo",
|
||||
"selectDirectory": "Seleccionar esta carpeta"
|
||||
"switchDirectory": "Cambiar directorio de trabajo"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2286,30 +2286,24 @@
|
||||
"dialog": {
|
||||
"defaultProject": "Espace de travail par défaut",
|
||||
"manual": "Coller un chemin",
|
||||
"manualPlaceholder": "/Users/name/project",
|
||||
"usePath": "Utiliser le chemin",
|
||||
"absolutePathRequired": "Saisissez un chemin absolu de dossier sur cette machine."
|
||||
},
|
||||
"picker": {
|
||||
"favorites": "Favoris",
|
||||
"recent": "Projets récents",
|
||||
"directories": "Dossiers",
|
||||
"pin": "Épingler {{name}}",
|
||||
"unpin": "Désépingler {{name}}",
|
||||
"description": "Recherchez un projet récent ou choisissez un dossier sur l’hôte connecté.",
|
||||
"emptyProjects": "Aucun projet correspondant",
|
||||
"search": "Saisir un chemin ou filtrer ce dossier…",
|
||||
"shortcuts": "Emplacements enregistrés",
|
||||
"favoriteHint": "Cliquez sur l’étoile d’un dossier pour l’ajouter ici.",
|
||||
"native": "Utiliser le sélecteur de dossiers du système…",
|
||||
"up": "Dossier parent",
|
||||
"loading": "Chargement des dossiers…",
|
||||
"emptyDirectories": "Aucun dossier correspondant",
|
||||
"truncated": "500 dossiers affichés. Continuez à saisir le chemin pour réduire la liste.",
|
||||
"hidden": "Afficher les dossiers cachés",
|
||||
"select": "Choisir",
|
||||
"switchDirectory": "Changer de dossier de travail",
|
||||
"selectDirectory": "Sélectionner ce dossier"
|
||||
"switchDirectory": "Changer de dossier de travail"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2286,30 +2286,24 @@
|
||||
"dialog": {
|
||||
"defaultProject": "Ruang kerja bawaan",
|
||||
"manual": "Tempel path",
|
||||
"manualPlaceholder": "/Users/name/project",
|
||||
"usePath": "Gunakan path",
|
||||
"absolutePathRequired": "Masukkan path folder absolut di mesin ini."
|
||||
},
|
||||
"picker": {
|
||||
"favorites": "Favorit",
|
||||
"recent": "Proyek terbaru",
|
||||
"directories": "Folder",
|
||||
"pin": "Sematkan {{name}}",
|
||||
"unpin": "Lepas {{name}}",
|
||||
"description": "Cari proyek terbaru atau pilih folder di host yang terhubung.",
|
||||
"emptyProjects": "Tidak ada proyek yang cocok",
|
||||
"search": "Masukkan jalur atau filter folder ini…",
|
||||
"shortcuts": "Lokasi tersimpan",
|
||||
"favoriteHint": "Klik bintang di samping folder untuk menambahkannya di sini.",
|
||||
"native": "Gunakan pemilih folder sistem…",
|
||||
"up": "Direktori induk",
|
||||
"loading": "Memuat folder…",
|
||||
"emptyDirectories": "Tidak ada folder yang cocok",
|
||||
"truncated": "Menampilkan 500 folder. Lanjutkan mengetik jalur untuk mempersempit daftar.",
|
||||
"hidden": "Tampilkan folder tersembunyi",
|
||||
"select": "Pilih",
|
||||
"switchDirectory": "Ganti direktori kerja",
|
||||
"selectDirectory": "Pilih folder ini"
|
||||
"switchDirectory": "Ganti direktori kerja"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2286,30 +2286,24 @@
|
||||
"dialog": {
|
||||
"defaultProject": "既定のワークスペース",
|
||||
"manual": "パスを貼り付け",
|
||||
"manualPlaceholder": "/Users/name/project",
|
||||
"usePath": "パスを使用",
|
||||
"absolutePathRequired": "このマシン上の絶対フォルダーパスを入力してください。"
|
||||
},
|
||||
"picker": {
|
||||
"favorites": "お気に入り",
|
||||
"recent": "最近のプロジェクト",
|
||||
"directories": "フォルダー",
|
||||
"pin": "{{name}} を固定",
|
||||
"unpin": "{{name}} の固定を解除",
|
||||
"description": "最近のプロジェクトを検索するか、接続先ホストのフォルダーを選択します。",
|
||||
"emptyProjects": "一致するプロジェクトはありません",
|
||||
"search": "パスを入力、または現在のフォルダを絞り込む…",
|
||||
"shortcuts": "保存した場所",
|
||||
"favoriteHint": "フォルダの星をクリックして追加します。",
|
||||
"native": "システムのフォルダー選択を使用…",
|
||||
"up": "親ディレクトリ",
|
||||
"loading": "フォルダーを読み込み中…",
|
||||
"emptyDirectories": "一致するフォルダーはありません",
|
||||
"truncated": "500 個のフォルダーを表示しています。パスの入力を続けて絞り込んでください。",
|
||||
"hidden": "隠しフォルダーを表示",
|
||||
"select": "選択",
|
||||
"switchDirectory": "作業ディレクトリを切り替える",
|
||||
"selectDirectory": "このフォルダーを選択"
|
||||
"switchDirectory": "作業ディレクトリを切り替える"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2286,30 +2286,24 @@
|
||||
"dialog": {
|
||||
"defaultProject": "기본 작업공간",
|
||||
"manual": "경로 붙여넣기",
|
||||
"manualPlaceholder": "/Users/name/project",
|
||||
"usePath": "경로 사용",
|
||||
"absolutePathRequired": "이 머신의 절대 폴더 경로를 입력하세요."
|
||||
},
|
||||
"picker": {
|
||||
"favorites": "즐겨찾기",
|
||||
"recent": "최근 프로젝트",
|
||||
"directories": "폴더",
|
||||
"pin": "{{name}} 고정",
|
||||
"unpin": "{{name}} 고정 해제",
|
||||
"description": "최근 프로젝트를 검색하거나 연결된 호스트의 폴더를 선택하세요.",
|
||||
"emptyProjects": "일치하는 프로젝트가 없습니다",
|
||||
"search": "경로 입력 또는 현재 폴더 필터링…",
|
||||
"shortcuts": "저장된 위치",
|
||||
"favoriteHint": "폴더 옆의 별을 눌러 즐겨찾기에 추가하세요.",
|
||||
"native": "시스템 폴더 선택기 사용…",
|
||||
"up": "상위 디렉터리",
|
||||
"loading": "폴더 불러오는 중…",
|
||||
"emptyDirectories": "일치하는 폴더가 없습니다",
|
||||
"truncated": "폴더 500개를 표시합니다. 경로를 계속 입력하여 목록을 좁히세요.",
|
||||
"hidden": "숨김 폴더 표시",
|
||||
"select": "선택",
|
||||
"switchDirectory": "작업 디렉터리 변경",
|
||||
"selectDirectory": "이 폴더 선택"
|
||||
"switchDirectory": "작업 디렉터리 변경"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2300,30 +2300,24 @@
|
||||
"dialog": {
|
||||
"defaultProject": "Espaço de trabalho padrão",
|
||||
"manual": "Colar caminho",
|
||||
"manualPlaceholder": "/Users/nome/projeto",
|
||||
"usePath": "Usar caminho",
|
||||
"absolutePathRequired": "Informe um caminho absoluto de pasta nesta máquina."
|
||||
},
|
||||
"picker": {
|
||||
"favorites": "Favoritos",
|
||||
"recent": "Projetos recentes",
|
||||
"directories": "Pastas",
|
||||
"pin": "Fixar {{name}}",
|
||||
"unpin": "Desafixar {{name}}",
|
||||
"description": "Pesquise projetos recentes ou escolha uma pasta no host conectado.",
|
||||
"emptyProjects": "Nenhum projeto correspondente",
|
||||
"search": "Digite um caminho ou filtre esta pasta…",
|
||||
"shortcuts": "Locais salvos",
|
||||
"favoriteHint": "Clique na estrela de uma pasta para adicioná-la aqui.",
|
||||
"native": "Usar o seletor de pastas do sistema…",
|
||||
"up": "Pasta superior",
|
||||
"loading": "Carregando pastas…",
|
||||
"emptyDirectories": "Nenhuma pasta correspondente",
|
||||
"truncated": "Exibindo 500 pastas. Continue digitando o caminho para reduzir a lista.",
|
||||
"hidden": "Mostrar pastas ocultas",
|
||||
"select": "Selecionar",
|
||||
"switchDirectory": "Alterar diretório de trabalho",
|
||||
"selectDirectory": "Selecionar esta pasta"
|
||||
"switchDirectory": "Alterar diretório de trabalho"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2286,30 +2286,24 @@
|
||||
"dialog": {
|
||||
"defaultProject": "Không gian làm việc mặc định",
|
||||
"manual": "Dán đường dẫn",
|
||||
"manualPlaceholder": "/Users/name/project",
|
||||
"usePath": "Dùng đường dẫn",
|
||||
"absolutePathRequired": "Nhập đường dẫn thư mục tuyệt đối trên máy này."
|
||||
},
|
||||
"picker": {
|
||||
"favorites": "Yêu thích",
|
||||
"recent": "Dự án gần đây",
|
||||
"directories": "Thư mục",
|
||||
"pin": "Ghim {{name}}",
|
||||
"unpin": "Bỏ ghim {{name}}",
|
||||
"description": "Tìm dự án gần đây hoặc chọn thư mục trên máy chủ đang kết nối.",
|
||||
"emptyProjects": "Không có dự án phù hợp",
|
||||
"search": "Nhập đường dẫn hoặc lọc thư mục này…",
|
||||
"shortcuts": "Vị trí đã lưu",
|
||||
"favoriteHint": "Nhấn ngôi sao bên cạnh thư mục để thêm vào đây.",
|
||||
"native": "Dùng bộ chọn thư mục hệ thống…",
|
||||
"up": "Thư mục cha",
|
||||
"loading": "Đang tải thư mục…",
|
||||
"emptyDirectories": "Không có thư mục phù hợp",
|
||||
"truncated": "Hiển thị 500 thư mục. Tiếp tục nhập đường dẫn để thu hẹp danh sách.",
|
||||
"hidden": "Hiện thư mục ẩn",
|
||||
"select": "Chọn",
|
||||
"switchDirectory": "Đổi thư mục làm việc",
|
||||
"selectDirectory": "Chọn thư mục này"
|
||||
"switchDirectory": "Đổi thư mục làm việc"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2486,30 +2486,24 @@
|
||||
"dialog": {
|
||||
"defaultProject": "默认工作区",
|
||||
"manual": "粘贴路径",
|
||||
"manualPlaceholder": "/Users/name/project",
|
||||
"usePath": "使用路径",
|
||||
"absolutePathRequired": "请输入这台机器上的绝对文件夹路径。"
|
||||
},
|
||||
"picker": {
|
||||
"favorites": "收藏",
|
||||
"recent": "最近项目",
|
||||
"directories": "文件夹",
|
||||
"pin": "收藏 {{name}}",
|
||||
"unpin": "取消收藏 {{name}}",
|
||||
"description": "搜索最近项目,或选择当前连接主机上的文件夹。",
|
||||
"emptyProjects": "没有匹配的项目",
|
||||
"search": "输入路径或筛选当前目录…",
|
||||
"shortcuts": "快捷位置",
|
||||
"favoriteHint": "点击文件夹旁的星标收藏。",
|
||||
"native": "使用系统文件夹选择器…",
|
||||
"up": "返回上级目录",
|
||||
"loading": "正在加载文件夹…",
|
||||
"emptyDirectories": "没有匹配的文件夹",
|
||||
"truncated": "已显示 500 个文件夹,继续输入路径以缩小范围。",
|
||||
"hidden": "显示隐藏文件夹",
|
||||
"select": "选择",
|
||||
"switchDirectory": "切换工作目录",
|
||||
"selectDirectory": "选择此文件夹"
|
||||
"switchDirectory": "切换工作目录"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2286,30 +2286,24 @@
|
||||
"dialog": {
|
||||
"defaultProject": "預設工作區",
|
||||
"manual": "貼上路徑",
|
||||
"manualPlaceholder": "/Users/name/project",
|
||||
"usePath": "使用路徑",
|
||||
"absolutePathRequired": "請輸入這台機器上的絕對資料夾路徑。"
|
||||
},
|
||||
"picker": {
|
||||
"favorites": "收藏",
|
||||
"recent": "最近專案",
|
||||
"directories": "資料夾",
|
||||
"pin": "收藏 {{name}}",
|
||||
"unpin": "取消收藏 {{name}}",
|
||||
"description": "搜尋最近專案,或選擇目前連線主機上的資料夾。",
|
||||
"emptyProjects": "沒有符合的專案",
|
||||
"search": "輸入路徑或篩選目前目錄…",
|
||||
"shortcuts": "快捷位置",
|
||||
"favoriteHint": "點擊資料夾旁的星號收藏。",
|
||||
"native": "使用系統資料夾選擇器…",
|
||||
"up": "返回上層目錄",
|
||||
"loading": "正在載入資料夾…",
|
||||
"emptyDirectories": "沒有符合的資料夾",
|
||||
"truncated": "已顯示 500 個資料夾,繼續輸入路徑以縮小範圍。",
|
||||
"hidden": "顯示隱藏資料夾",
|
||||
"select": "選擇",
|
||||
"switchDirectory": "切換工作目錄",
|
||||
"selectDirectory": "選擇此資料夾"
|
||||
"switchDirectory": "切換工作目錄"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { WorkspaceProjectPicker } from "@/components/thread/WorkspaceControls";
|
||||
import type { WorkspaceDirectoriesPayload, WorkspacesPayload } from "@/lib/types";
|
||||
import type { BrowseWorkspaceDirectories } from "@/lib/workspace";
|
||||
|
||||
const scope = { project_path: "/srv/workspace", access_mode: "restricted" as const };
|
||||
const catalog: WorkspacesPayload = {
|
||||
@@ -92,6 +93,33 @@ describe("Workspace project picker", () => {
|
||||
expect(viewport.scrollLeft).toBe(88);
|
||||
});
|
||||
|
||||
it("keeps a wide directory bounded while scrolling and completing an offscreen keyboard result", async () => {
|
||||
const user = userEvent.setup();
|
||||
const entries = Array.from({ length: 500 }, (_, index) => ({ name: `folder-${index}`, path: `/srv/workspace/folder-${index}` }));
|
||||
const onBrowse = vi.fn((rawPath: string) => {
|
||||
const path = rawPath.replace(/\/$/, "");
|
||||
return Promise.resolve({ ...directory, path, entries: path === scope.project_path ? entries : [{ name: "child", path: `${path}/child` }] });
|
||||
});
|
||||
render(<WorkspaceProjectPicker isHero scope={scope} defaultScope={scope} controls={catalog.controls} onBrowseDirectories={onBrowse} onChange={vi.fn()} />);
|
||||
await user.click(screen.getByRole("button", { name: "Switch working directory" }));
|
||||
const first = await screen.findByRole("option", { name: entries[0].path });
|
||||
expect(first).toHaveAttribute("aria-setsize", "500");
|
||||
expect(first).toHaveAttribute("aria-posinset", "1");
|
||||
const viewport = screen.getByRole("listbox");
|
||||
Object.defineProperty(viewport, "clientHeight", { configurable: true, value: 220 });
|
||||
expect(within(viewport).getAllByRole("option").length).toBeLessThan(20);
|
||||
viewport.scrollTop = 250 * 44;
|
||||
fireEvent.scroll(viewport);
|
||||
expect(await screen.findByRole("option", { name: entries[250].path })).toHaveAttribute("aria-posinset", "251");
|
||||
await user.keyboard("{ArrowUp}");
|
||||
const last = await screen.findByRole("option", { name: entries[499].path });
|
||||
expect(screen.getByRole("combobox")).toHaveAttribute("aria-activedescendant", last.id);
|
||||
expect(within(viewport).getAllByRole("option").length).toBeLessThan(20);
|
||||
await user.keyboard("{Tab}");
|
||||
expect(screen.getByRole("combobox")).toHaveValue(`${entries[499].path}/`);
|
||||
expect(await screen.findByRole("option", { name: `${entries[499].path}/child` })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("browses folders immediately, toggles hidden entries, and selects the resolved directory", async () => {
|
||||
const user = userEvent.setup();
|
||||
const onChange = vi.fn();
|
||||
@@ -248,7 +276,7 @@ describe("Workspace project picker", () => {
|
||||
it("ignores a Tab completion after the user changes the path", async () => {
|
||||
const user = userEvent.setup();
|
||||
let finish!: (value: WorkspaceDirectoriesPayload) => void;
|
||||
const onBrowse = vi.fn((_path: string, query: string) => query ? new Promise<WorkspaceDirectoriesPayload>(resolve => { finish = resolve; }) : Promise.resolve({ ...directory, entries: [] }));
|
||||
const onBrowse = vi.fn((path: string) => path === "/srv/al" ? new Promise<WorkspaceDirectoriesPayload>(resolve => { finish = resolve; }) : Promise.resolve({ ...directory, entries: [] }));
|
||||
render(<WorkspaceProjectPicker isHero scope={scope} defaultScope={scope} controls={catalog.controls} onBrowseDirectories={onBrowse} onChange={vi.fn()} />);
|
||||
await user.click(screen.getByRole("button", { name: "Switch working directory" }));
|
||||
const input = screen.getByRole("combobox");
|
||||
@@ -261,6 +289,25 @@ describe("Workspace project picker", () => {
|
||||
expect(input).toHaveFocus();
|
||||
});
|
||||
|
||||
it("reuses an in-flight partial-path listing when Tab completes it", async () => {
|
||||
const user = userEvent.setup();
|
||||
let finish!: (value: WorkspaceDirectoriesPayload) => void;
|
||||
const onBrowse = vi.fn<BrowseWorkspaceDirectories>((path: string) => path === "/srv/al"
|
||||
? new Promise<WorkspaceDirectoriesPayload>(resolve => { finish = resolve; })
|
||||
: Promise.resolve({ ...directory, path, entries: [] }));
|
||||
render(<WorkspaceProjectPicker isHero scope={scope} defaultScope={scope} controls={catalog.controls} onBrowseDirectories={onBrowse} onChange={vi.fn()} />);
|
||||
await user.click(screen.getByRole("button", { name: "Switch working directory" }));
|
||||
const input = screen.getByRole("combobox");
|
||||
await user.clear(input);
|
||||
await user.type(input, "/srv/al");
|
||||
await user.keyboard("{Tab}");
|
||||
await waitFor(() => expect(onBrowse).toHaveBeenCalledWith("/srv/al", "", false, true));
|
||||
await new Promise(resolve => setTimeout(resolve, 200));
|
||||
act(() => finish({ ...directory, path: "/srv", partial: true, entries: [{ name: "alpha", path: "/srv/alpha" }] }));
|
||||
await waitFor(() => expect(input).toHaveValue("/srv/alpha/"));
|
||||
expect(onBrowse.mock.calls.filter(call => call[0] === "/srv/al" || call[0] === "/srv/" && call[1] === "al")).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("updates folders while typing and ignores results from older paths", async () => {
|
||||
const user = userEvent.setup();
|
||||
let finishOld!: (value: WorkspaceDirectoriesPayload) => void;
|
||||
|
||||
Reference in new issue
Block a user