Files
model-platform/frontend/app/features/platform/WorkspaceTree.tsx
T
tao.chenandtao.chen a337804700 feat(scripts/data-resources): merge tree + add parent_path filter
- Backend: GET /api/v1/data-resources accepts parent_path; LIKE
  '{ws_id}/%/{escaped}/%' AND NOT LIKE '{ws_id}/%/{escaped}/%/%' on
  StorageObjects.object_key (workspace-wide, escapes _ and %, mirrors
  list_scripts parent_path semantics). 13 new tests in
  test_resources.py (helper unit / SQL compile / SQLite behavioral).
- Frontend: listResources gains parentPath arg, propagated through
  WorkspaceBoundApi + AuthContext binding. WorkspaceTreeGroup title
  count and ScriptExplorer header count now include dataResources.
  memberScriptGroups backfills data-only owners so users with only
  data resources still render a group. loadDataResources accepts an
  optional parentPath, default empty preserves prior behavior.
2026-09-02 10:10:41 +08:00

331 lines
9.8 KiB
TypeScript

import { type MouseEvent as ReactMouseEvent, useEffect, useMemo } from "react";
import Icon from "../../components/common/Icon";
import type {
ScriptItem,
WorkspaceDirectory,
ResourceItem,
} from "~/services/api";
export type WorkspaceTreeTarget = {
kind: "root" | "directory" | "file";
path: string;
script?: ScriptItem;
};
type WorkspaceTreeProps = {
title: string;
scripts: ScriptItem[];
directories: WorkspaceDirectory[];
selectedId: string | null;
onSelect: (id: string) => void;
onContextMenu?: (
event: ReactMouseEvent,
target: WorkspaceTreeTarget,
) => void;
readOnly?: boolean;
dataResources?: ResourceItem[];
onCopyResourcePath?: (jupyterPath: string) => void;
// 唯一标识此 group(通常 `__group__<owner_user_id>`),让多个 owner 的 group 各自独立展开。
groupKey: string;
expandedPaths: Set<string>;
onToggle: (path: string, loadPath?: string) => void;
loadingChildrenPaths: Set<string>;
};
type WorkspaceTreeItemsProps = Omit<WorkspaceTreeProps, "title" | "readOnly"> & {
path: string;
depth: number;
onCopyResourcePath?: (jupyterPath: string) => void;
};
function formatTime(value: string) {
return new Intl.DateTimeFormat("zh-CN", {
month: "2-digit",
day: "2-digit",
hour: "2-digit",
minute: "2-digit",
hour12: false,
}).format(new Date(value));
}
export function scriptIcon(item: ScriptItem) {
return item.script_type === "notebook" ? "notebook" : "python";
}
function ownedScriptPath(item: ScriptItem) {
// 数据资源的 relative_path 已经是 jupyter 路径(无 ULID 前缀);脚本相对路径形如
// `{ulid}/{ws_id}/{user_id}/...`,需要剥前两层。
if (item.script_id.startsWith("data:")) {
return item.relative_path.replaceAll("\\", "/");
}
return item.relative_path.replaceAll("\\", "/").split("/").slice(2).join("/");
}
function parentOf(path: string) {
const parts = path.split("/");
parts.pop();
return parts.join("/");
}
export function WorkspaceTreeGroup({
title,
scripts,
directories,
selectedId,
onSelect,
onContextMenu,
readOnly = false,
dataResources,
onCopyResourcePath,
groupKey,
expandedPaths,
onToggle,
loadingChildrenPaths,
}: WorkspaceTreeProps) {
const open = expandedPaths.has(groupKey);
const dataResourceScripts = useMemo(() => {
if (!dataResources) return [];
return dataResources.map((r) => ({
script_id: `data:${r.resource_id}`,
workspace_id: r.workspace_id,
current_object_id: r.storage_object_id,
owner_user_id: r.owner_user_id,
owner_display_name: null,
script_name: r.resource_name,
script_type: "python" as const,
visibility: r.visibility,
status: r.status,
is_locked: false,
// relative_path 直接是 jupyter 路径(与 Python/Notebook 同层渲染,不再带虚拟前缀)
relative_path: r.jupyter_accessible_path,
jupyter_path: r.jupyter_accessible_path,
content_hash: r.file.content_hash ?? "",
size_bytes: r.file.size_bytes,
created_at: r.created_at,
updated_at: r.updated_at,
} as unknown as ScriptItem));
}, [dataResources]);
const dataResourceDirectories = useMemo(() => {
if (!dataResources) return [];
const dirSet = new Set<string>();
for (const r of dataResources) {
const parts = r.jupyter_accessible_path.split("/");
parts.pop();
let acc = "";
for (const p of parts) {
acc = acc ? `${acc}/${p}` : p;
dirSet.add(acc);
}
}
return [...dirSet].map((path) => ({
path,
name: path.split("/").pop() ?? path,
parent_path: path.includes("/")
? path.split("/").slice(0, -1).join("/")
: "",
}));
}, [dataResources]);
// 首次挂载自动展开(保留原本 useState(true) 的默认展开行为)。
// toggleExpanded 内识别 `__group__` 前缀,不会触发 loadChildren。
useEffect(() => {
if (!expandedPaths.has(groupKey)) {
void onToggle(groupKey);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [groupKey]);
return (
<div className="tree-group">
<button
className={`tree-group__title${open ? " is-open" : ""}`}
type="button"
aria-expanded={open}
onClick={() => onToggle(groupKey)}
onContextMenu={onContextMenu
? (event) => onContextMenu(event, { kind: "root", path: "" })
: undefined}
>
<Icon name="chevron" size={14} />
<Icon name="folder" size={17} />
<span>{title}</span>
<em>{scripts.length + (dataResources ?? []).length}</em>
</button>
{open && (
<div className="tree-group__items">
<WorkspaceTreeItems
groupKey={groupKey}
path=""
depth={0}
scripts={[...scripts, ...dataResourceScripts]}
// 数据资源目录与真实/推断目录按 path 去重
directories={[
...new Map(
[...directories, ...dataResourceDirectories].map((d) => [d.path, d]),
).values(),
]}
selectedId={selectedId}
onSelect={onSelect}
onContextMenu={onContextMenu}
expandedPaths={expandedPaths}
onToggle={onToggle}
loadingChildrenPaths={loadingChildrenPaths}
onCopyResourcePath={onCopyResourcePath}
/>
{scripts.length === 0 && directories.length === 0 && dataResourceScripts.length === 0 && (
<p className="tree-group__empty">
{readOnly ? "暂无文件" : "右键此目录即可新建或上传"}
</p>
)}
</div>
)}
</div>
);
}
function WorkspaceTreeItems({
groupKey,
path,
depth,
scripts,
directories,
selectedId,
onSelect,
onContextMenu,
onCopyResourcePath,
expandedPaths,
onToggle,
loadingChildrenPaths,
}: WorkspaceTreeItemsProps) {
const childDirectories = directories.filter(
(item) => item.parent_path === path,
);
const childScripts = scripts.filter(
(item) => parentOf(ownedScriptPath(item)) === path,
);
return (
<>
{childDirectories.map((directory) => (
<DirectoryBranch
key={directory.path}
groupKey={groupKey}
directory={directory}
depth={depth}
scripts={scripts}
directories={directories}
selectedId={selectedId}
onSelect={onSelect}
onContextMenu={onContextMenu}
expandedPaths={expandedPaths}
onToggle={onToggle}
loadingChildrenPaths={loadingChildrenPaths}
onCopyResourcePath={onCopyResourcePath}
/>
))}
{childScripts.map((item) => (
<button
className={`script-row${
selectedId === item.script_id ? " script-row--active" : ""
}`}
style={{ paddingLeft: 20 + depth * 16 }}
key={item.script_id}
type="button"
onClick={() => {
if (item.script_id.startsWith("data:") && onCopyResourcePath) {
onCopyResourcePath(item.relative_path);
} else {
onSelect(item.script_id);
}
}}
onContextMenu={onContextMenu
? (event) => onContextMenu(event, {
kind: "file",
path: ownedScriptPath(item),
script: item,
})
: undefined}
>
<span className={`file-icon file-icon--${
item.script_id.startsWith("data:") ? "data" : item.script_type
}`}>
<Icon name={item.script_id.startsWith("data:") ? "database" : scriptIcon(item)} size={17} />
</span>
<span className="script-row__copy">
<strong title={item.script_name}>{item.script_name}</strong>
<small>{formatTime(item.updated_at)}</small>
</span>
{item.is_locked && (
<span className="lock-badge" title="已锁定">
<Icon name="lock" size={12} />
</span>
)}
{item.visibility !== "private" && (
<span className="visibility-dot" title="Workspace 可见" />
)}
</button>
))}
</>
);
}
function DirectoryBranch({
groupKey,
directory,
depth,
scripts,
directories,
selectedId,
onSelect,
onContextMenu,
onCopyResourcePath,
expandedPaths,
onToggle,
loadingChildrenPaths,
}: Omit<WorkspaceTreeItemsProps, "path"> & {
directory: WorkspaceDirectory;
}) {
const expandKey = `${groupKey}/${directory.path}`;
const open = expandedPaths.has(expandKey);
const childrenLoading = loadingChildrenPaths.has(directory.path);
return (
<div className="directory-branch">
<button
className="directory-row"
style={{ paddingLeft: 10 + depth * 16 }}
type="button"
onClick={() => onToggle(expandKey, directory.path)}
onContextMenu={onContextMenu
? (event) => onContextMenu(event, {
kind: "directory",
path: directory.path,
})
: undefined}
>
<span className={`directory-row__chevron${open ? " is-open" : ""}`}>
<Icon name="chevron" size={13} />
</span>
<Icon name="folder" size={17} />
<strong title={directory.path}>{directory.name}</strong>
{childrenLoading && <span className="loading-spinner" />}
</button>
{open && (
<WorkspaceTreeItems
groupKey={groupKey}
path={directory.path}
depth={depth + 1}
scripts={scripts}
directories={directories}
selectedId={selectedId}
onSelect={onSelect}
onContextMenu={onContextMenu}
expandedPaths={expandedPaths}
onToggle={onToggle}
loadingChildrenPaths={loadingChildrenPaths}
onCopyResourcePath={onCopyResourcePath}
/>
)}
</div>
);
}