4-10 树域 Rust 家族化
This commit is contained in:
@@ -12,6 +12,7 @@ export default async function AppLayout({ children }: { children: ReactNode }) {
|
||||
sidebarInitialData,
|
||||
} = await loadSidebarDataFromConvex({
|
||||
client,
|
||||
auth,
|
||||
fallbackName: auth.name ?? auth.email ?? "我的空间",
|
||||
});
|
||||
|
||||
|
||||
@@ -1,119 +1,83 @@
|
||||
import { randomUUID } from "crypto";
|
||||
import { NextResponse } from "next/server";
|
||||
import { isConvexEnabled } from "@/lib/convex/enabled";
|
||||
import { api } from "@/lib/convex/api";
|
||||
import { getAuthedConvexClient } from "@/lib/convex/route";
|
||||
import {
|
||||
buildDocumentBridgeContext,
|
||||
buildDocumentCommandEnvelope,
|
||||
documentBridgeErrorResponse,
|
||||
} from "@/lib/documents/bridge";
|
||||
import {
|
||||
executePageLifecycleBridgeCommand,
|
||||
type DocumentCreatePayload,
|
||||
} from "@/lib/documents/page-command-adapter";
|
||||
import { ensureDocumentScaffold } from "@/lib/documents/page-lifecycle-side-effects";
|
||||
|
||||
type TreeCreateResponse = {
|
||||
requestId?: string;
|
||||
traceId?: string;
|
||||
result?: {
|
||||
documentId?: string;
|
||||
parentId?: string | null;
|
||||
title?: string | null;
|
||||
sortOrder?: number | null;
|
||||
workspaceId?: string | null;
|
||||
execution?: {
|
||||
access_scope?: "private" | "shared" | "public";
|
||||
is_template?: boolean;
|
||||
created_at?: string | null;
|
||||
updated_at?: string | null;
|
||||
} | null;
|
||||
} | null;
|
||||
};
|
||||
|
||||
export async function POST(request: Request) {
|
||||
try {
|
||||
if (isConvexEnabled()) {
|
||||
return await handleCreateRequestConvex(request);
|
||||
}
|
||||
return await handleCreateRequest();
|
||||
} catch (error) {
|
||||
console.error("创建页面失败", error);
|
||||
const message = error instanceof Error ? error.message : "创建页面失败,请稍后再试";
|
||||
return NextResponse.json({ error: message }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
async function handleCreateRequestConvex(request: Request) {
|
||||
const { auth, client } = await getAuthedConvexClient();
|
||||
const { parentId }: { parentId?: string | null } = await request.json();
|
||||
|
||||
const workspaceBootstrap = await client.mutation(api.workspaces.ensureDefaultWorkspace, {
|
||||
fallbackName: auth.email ?? auth.name ?? "我的空间",
|
||||
workspaceIdIfCreate: randomUUID(),
|
||||
});
|
||||
|
||||
let workspaceId: string | null = null;
|
||||
let accessScope: "private" | "shared" | "public" = "private";
|
||||
|
||||
if (parentId) {
|
||||
const parentDoc = await client.query(api.documents.getMeta, {
|
||||
id: parentId,
|
||||
});
|
||||
|
||||
if (!parentDoc) {
|
||||
return NextResponse.json({ error: "父页面不存在或无权限" }, { status: 404 });
|
||||
}
|
||||
|
||||
workspaceId = parentDoc.workspace_id;
|
||||
accessScope = (parentDoc.access_scope ?? "private") as typeof accessScope;
|
||||
} else {
|
||||
workspaceId = workspaceBootstrap.activeWorkspaceId || null;
|
||||
}
|
||||
|
||||
if (!workspaceId) {
|
||||
return NextResponse.json({ error: "缺少目标工作空间" }, { status: 400 });
|
||||
if (!isConvexEnabled()) {
|
||||
return NextResponse.json({ error: "当前仅支持 Convex 模式" }, { status: 501 });
|
||||
}
|
||||
|
||||
try {
|
||||
const id = randomUUID();
|
||||
const normalizedWorkspaceId = workspaceId.trim();
|
||||
const bridgeContext = await buildDocumentBridgeContext({
|
||||
request,
|
||||
workspaceId: normalizedWorkspaceId,
|
||||
});
|
||||
const result = await executePageLifecycleBridgeCommand<
|
||||
DocumentCreatePayload,
|
||||
{
|
||||
id: string;
|
||||
title?: string | null;
|
||||
parent_id?: string | null;
|
||||
sort_order?: number | null;
|
||||
workspace_id?: string;
|
||||
access_scope?: "private" | "shared" | "public";
|
||||
is_template?: boolean;
|
||||
}
|
||||
>({
|
||||
context: bridgeContext,
|
||||
envelope: buildDocumentCommandEnvelope({
|
||||
name: "documents.create",
|
||||
payload: {
|
||||
documentId: id,
|
||||
workspaceId: normalizedWorkspaceId,
|
||||
parentId: parentId?.trim() || null,
|
||||
title: "无标题",
|
||||
accessScope,
|
||||
content: [],
|
||||
},
|
||||
context: bridgeContext,
|
||||
target: {
|
||||
workspaceId: normalizedWorkspaceId,
|
||||
pageId: id,
|
||||
},
|
||||
const { parentId }: { parentId?: string | null } = await request.json();
|
||||
const upstreamUrl = new URL("/api/tree/commands", request.url);
|
||||
const response = await fetch(upstreamUrl.toString(), {
|
||||
method: "POST",
|
||||
headers: new Headers({
|
||||
"content-type": "application/json",
|
||||
}),
|
||||
body: JSON.stringify({
|
||||
action: "create",
|
||||
parentId: typeof parentId === "string" ? parentId.trim() || null : null,
|
||||
}),
|
||||
});
|
||||
|
||||
await ensureDocumentScaffold(result.result.id, result.result.title ?? "无标题");
|
||||
const payload = (await response.json().catch(() => null)) as TreeCreateResponse | { error?: string } | null;
|
||||
if (!response.ok) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error:
|
||||
payload && typeof payload === "object" && "error" in payload && typeof payload.error === "string"
|
||||
? payload.error
|
||||
: "创建页面失败,请稍后再试",
|
||||
},
|
||||
{ status: response.status },
|
||||
);
|
||||
}
|
||||
|
||||
return NextResponse.json({
|
||||
...result.result,
|
||||
id: payload?.result?.documentId ?? "",
|
||||
title: payload?.result?.title ?? "无标题",
|
||||
parent_id: payload?.result?.parentId ?? null,
|
||||
sort_order: payload?.result?.sortOrder ?? null,
|
||||
workspace_id: payload?.result?.workspaceId ?? undefined,
|
||||
access_scope: payload?.result?.execution?.access_scope ?? "private",
|
||||
is_template: payload?.result?.execution?.is_template ?? false,
|
||||
created_at: payload?.result?.execution?.created_at ?? null,
|
||||
updated_at:
|
||||
payload?.result?.execution?.updated_at ??
|
||||
payload?.result?.execution?.created_at ??
|
||||
null,
|
||||
meta: {
|
||||
requestId: result.requestId,
|
||||
traceId: result.traceId,
|
||||
commandId: result.commandId,
|
||||
commandName: result.commandName,
|
||||
requestId: payload?.requestId,
|
||||
traceId: payload?.traceId,
|
||||
commandName: "tree.node.create",
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
return documentBridgeErrorResponse(error);
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: error instanceof Error ? error.message : "创建页面失败,请稍后再试",
|
||||
},
|
||||
{ status: 500 },
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleCreateRequest() {
|
||||
return NextResponse.json({ error: "当前仅支持 Convex 模式" }, { status: 501 });
|
||||
}
|
||||
|
||||
export const runtime = "nodejs";
|
||||
|
||||
@@ -1,67 +1,79 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { isConvexEnabled } from "@/lib/convex/enabled";
|
||||
import {
|
||||
assertDocumentId,
|
||||
buildDocumentBridgeContext,
|
||||
buildDocumentCommandEnvelope,
|
||||
documentBridgeErrorResponse,
|
||||
} from "@/lib/documents/bridge";
|
||||
import {
|
||||
executePageLifecycleBridgeCommand,
|
||||
type DocumentMovePayload,
|
||||
} from "@/lib/documents/page-command-adapter";
|
||||
|
||||
interface MovePayload {
|
||||
documentId: string;
|
||||
type TreeMoveResponse = {
|
||||
requestId?: string;
|
||||
traceId?: string;
|
||||
result?: {
|
||||
documentId?: string;
|
||||
parentId?: string | null;
|
||||
sortOrder?: number | null;
|
||||
} | null;
|
||||
};
|
||||
|
||||
type MovePayload = {
|
||||
documentId?: string | null;
|
||||
parentId?: string | null;
|
||||
position: number;
|
||||
position?: number | null;
|
||||
workspaceId?: string | null;
|
||||
}
|
||||
};
|
||||
|
||||
export async function POST(request: Request) {
|
||||
if (isConvexEnabled()) {
|
||||
try {
|
||||
const { documentId, parentId = null, position, workspaceId }: MovePayload = await request.json();
|
||||
const normalizedDocumentId = assertDocumentId(documentId);
|
||||
const normalizedWorkspaceId = workspaceId?.trim() || null;
|
||||
const sortOrder = Number.isFinite(position) ? Math.floor(position) : 0;
|
||||
const bridgeContext = await buildDocumentBridgeContext({
|
||||
request,
|
||||
workspaceId: normalizedWorkspaceId,
|
||||
});
|
||||
const result = await executePageLifecycleBridgeCommand<DocumentMovePayload, { ok: boolean }>({
|
||||
context: bridgeContext,
|
||||
envelope: buildDocumentCommandEnvelope({
|
||||
name: "documents.move",
|
||||
payload: {
|
||||
documentId: normalizedDocumentId,
|
||||
workspaceId: normalizedWorkspaceId,
|
||||
parentId: parentId?.trim() || null,
|
||||
sortOrder,
|
||||
},
|
||||
context: bridgeContext,
|
||||
target: {
|
||||
workspaceId: normalizedWorkspaceId,
|
||||
pageId: normalizedDocumentId,
|
||||
},
|
||||
}),
|
||||
});
|
||||
|
||||
return NextResponse.json({
|
||||
ok: true,
|
||||
meta: {
|
||||
requestId: result.requestId,
|
||||
traceId: result.traceId,
|
||||
commandId: result.commandId,
|
||||
commandName: result.commandName,
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
return documentBridgeErrorResponse(error);
|
||||
}
|
||||
if (!isConvexEnabled()) {
|
||||
return NextResponse.json({ error: "当前仅支持 Convex 模式" }, { status: 501 });
|
||||
}
|
||||
|
||||
return NextResponse.json({ error: "当前仅支持 Convex 模式" }, { status: 501 });
|
||||
try {
|
||||
const { documentId, parentId = null, position, workspaceId }: MovePayload = await request.json();
|
||||
const normalizedDocumentId = typeof documentId === "string" ? documentId.trim() : "";
|
||||
if (!normalizedDocumentId) {
|
||||
return NextResponse.json({ error: "缺少 documentId" }, { status: 400 });
|
||||
}
|
||||
|
||||
const upstreamUrl = new URL("/api/tree/commands", request.url);
|
||||
const response = await fetch(upstreamUrl.toString(), {
|
||||
method: "POST",
|
||||
headers: new Headers({
|
||||
"content-type": "application/json",
|
||||
}),
|
||||
body: JSON.stringify({
|
||||
action: "move",
|
||||
documentId: normalizedDocumentId,
|
||||
parentId: typeof parentId === "string" ? parentId.trim() || null : null,
|
||||
sortOrder: typeof position === "number" && Number.isFinite(position) ? Math.floor(position) : 0,
|
||||
workspaceId: typeof workspaceId === "string" ? workspaceId.trim() || null : null,
|
||||
}),
|
||||
});
|
||||
|
||||
const payload = (await response.json().catch(() => null)) as TreeMoveResponse | { error?: string } | null;
|
||||
if (!response.ok) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error:
|
||||
payload && typeof payload === "object" && "error" in payload && typeof payload.error === "string"
|
||||
? payload.error
|
||||
: "移动失败,请稍后再试",
|
||||
},
|
||||
{ status: response.status },
|
||||
);
|
||||
}
|
||||
|
||||
return NextResponse.json({
|
||||
ok: true,
|
||||
meta: {
|
||||
requestId: payload?.requestId,
|
||||
traceId: payload?.traceId,
|
||||
commandName: "tree.subtree.move",
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: error instanceof Error ? error.message : "移动失败,请稍后再试",
|
||||
},
|
||||
{ status: 500 },
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export const runtime = "nodejs";
|
||||
|
||||
@@ -79,6 +79,8 @@ import { POST as postPurge } from "@/app/api/documents/purge/route";
|
||||
import { POST as postTitle } from "@/app/api/documents/title/route";
|
||||
import { POST as postOptions } from "@/app/api/documents/options/route";
|
||||
import { POST as postSave } from "@/app/api/documents/save/route";
|
||||
import { POST as postCreate } from "@/app/api/documents/create/route";
|
||||
import { POST as postMove } from "@/app/api/documents/move/route";
|
||||
import { GET as getPage } from "@/app/api/documents/page/route";
|
||||
import {
|
||||
executeDocumentCreateChildBridgeCommand,
|
||||
@@ -91,6 +93,151 @@ import { executePageWriteBridgeCommand } from "@/lib/documents/page-write-comman
|
||||
import { loadPageAggregate } from "@/lib/documents/page-aggregate-loader";
|
||||
|
||||
describe("documents route adapters", () => {
|
||||
it("create route 作为 compat 壳委托 tree commands 主路径", async () => {
|
||||
const fetchMock = vi.spyOn(globalThis, "fetch").mockResolvedValue(
|
||||
new Response(
|
||||
JSON.stringify({
|
||||
requestId: "req_tree_create_1",
|
||||
traceId: "trace_tree_create_1",
|
||||
result: {
|
||||
action: "create",
|
||||
workspaceId: "ws_1",
|
||||
documentId: "doc_new",
|
||||
parentId: null,
|
||||
title: "无标题",
|
||||
sortOrder: 0,
|
||||
updatedAt: "2026-04-23T00:00:00Z",
|
||||
execution: {
|
||||
access_scope: "private",
|
||||
is_template: false,
|
||||
created_at: "2026-04-23T00:00:00Z",
|
||||
updated_at: "2026-04-23T00:00:00Z",
|
||||
},
|
||||
},
|
||||
}),
|
||||
{ status: 200, headers: { "content-type": "application/json" } },
|
||||
),
|
||||
);
|
||||
|
||||
const response = await postCreate(new Request("http://localhost/api/documents/create", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ parentId: null }),
|
||||
}));
|
||||
const payload = await response.json() as {
|
||||
id: string;
|
||||
workspace_id: string;
|
||||
meta: { commandName: string };
|
||||
};
|
||||
|
||||
expect(fetchMock).toHaveBeenCalledWith(
|
||||
"http://localhost/api/tree/commands",
|
||||
expect.objectContaining({
|
||||
method: "POST",
|
||||
headers: expect.any(Headers),
|
||||
body: JSON.stringify({
|
||||
action: "create",
|
||||
parentId: null,
|
||||
}),
|
||||
}),
|
||||
);
|
||||
expect(payload.id).toBe("doc_new");
|
||||
expect(payload.workspace_id).toBe("ws_1");
|
||||
expect(payload.meta.commandName).toBe("tree.node.create");
|
||||
});
|
||||
|
||||
it("move route 作为 compat 壳委托 tree commands 主路径", async () => {
|
||||
const fetchMock = vi.spyOn(globalThis, "fetch").mockResolvedValue(
|
||||
new Response(
|
||||
JSON.stringify({
|
||||
requestId: "req_tree_move_1",
|
||||
traceId: "trace_tree_move_1",
|
||||
result: {
|
||||
action: "move",
|
||||
workspaceId: "ws_1",
|
||||
documentId: "doc_1",
|
||||
parentId: "parent_1",
|
||||
sortOrder: 2,
|
||||
updatedAt: "2026-04-23T00:00:00Z",
|
||||
},
|
||||
}),
|
||||
{ status: 200, headers: { "content-type": "application/json" } },
|
||||
),
|
||||
);
|
||||
|
||||
const response = await postMove(new Request("http://localhost/api/documents/move", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ documentId: "doc_1", parentId: "parent_1", position: 2.7, workspaceId: "ws_1" }),
|
||||
}));
|
||||
const payload = await response.json() as {
|
||||
ok: boolean;
|
||||
meta: { commandName: string };
|
||||
};
|
||||
|
||||
expect(fetchMock).toHaveBeenCalledWith(
|
||||
"http://localhost/api/tree/commands",
|
||||
expect.objectContaining({
|
||||
method: "POST",
|
||||
headers: expect.any(Headers),
|
||||
body: JSON.stringify({
|
||||
action: "move",
|
||||
documentId: "doc_1",
|
||||
parentId: "parent_1",
|
||||
sortOrder: 2,
|
||||
workspaceId: "ws_1",
|
||||
}),
|
||||
}),
|
||||
);
|
||||
expect(payload.ok).toBe(true);
|
||||
expect(payload.meta.commandName).toBe("tree.subtree.move");
|
||||
});
|
||||
|
||||
it("title route 在树重命名兼容请求下委托 tree commands 主路径", async () => {
|
||||
const fetchMock = vi.spyOn(globalThis, "fetch").mockResolvedValue(
|
||||
new Response(
|
||||
JSON.stringify({
|
||||
requestId: "req_tree_rename_1",
|
||||
traceId: "trace_tree_rename_1",
|
||||
result: {
|
||||
action: "rename",
|
||||
workspaceId: "ws_1",
|
||||
documentId: "doc_1",
|
||||
title: "新标题",
|
||||
updatedAt: "2026-04-23T00:00:00Z",
|
||||
},
|
||||
}),
|
||||
{ status: 200, headers: { "content-type": "application/json" } },
|
||||
),
|
||||
);
|
||||
|
||||
const response = await postTitle(new Request("http://localhost/api/documents/title", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ documentId: "doc_1", workspaceId: "ws_1", title: "新标题" }),
|
||||
}));
|
||||
const payload = await response.json() as {
|
||||
ok: boolean;
|
||||
meta: { commandName: string };
|
||||
};
|
||||
|
||||
expect(fetchMock).toHaveBeenCalledWith(
|
||||
"http://localhost/api/tree/commands",
|
||||
expect.objectContaining({
|
||||
method: "POST",
|
||||
headers: expect.any(Headers),
|
||||
body: JSON.stringify({
|
||||
action: "rename",
|
||||
documentId: "doc_1",
|
||||
workspaceId: "ws_1",
|
||||
title: "新标题",
|
||||
}),
|
||||
}),
|
||||
);
|
||||
expect(payload.ok).toBe(true);
|
||||
expect(payload.meta.commandName).toBe("tree.node.rename");
|
||||
});
|
||||
|
||||
it("creates child route delegates to unified adapter", async () => {
|
||||
await postCreateChild(new Request("http://localhost/api/documents/create-child", {
|
||||
method: "POST",
|
||||
@@ -146,10 +293,15 @@ describe("documents route adapters", () => {
|
||||
expect(payload.meta.queryName).toBe("documents.page.get");
|
||||
});
|
||||
|
||||
it("title route delegates to unified page write adapter", async () => {
|
||||
it("title route 在 page head 请求下仍委托 unified page write adapter", async () => {
|
||||
await postTitle(new Request("http://localhost/api/documents/title", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ documentId: "doc_1", workspaceId: "ws_1", title: "新标题" }),
|
||||
body: JSON.stringify({
|
||||
documentId: "doc_1",
|
||||
workspaceId: "ws_1",
|
||||
title: "新标题",
|
||||
commandName: "page.head.updateTitle",
|
||||
}),
|
||||
}));
|
||||
|
||||
expect(executePageWriteBridgeCommand).toHaveBeenCalled();
|
||||
|
||||
@@ -17,15 +17,60 @@ interface RenamePayload {
|
||||
documentId: string;
|
||||
workspaceId?: string | null;
|
||||
title: string;
|
||||
commandName?: string | null;
|
||||
}
|
||||
|
||||
type TreeRenameResponse = {
|
||||
requestId?: string;
|
||||
traceId?: string;
|
||||
};
|
||||
|
||||
export async function POST(request: Request) {
|
||||
if (isConvexEnabled()) {
|
||||
try {
|
||||
const { documentId, workspaceId, title }: RenamePayload = await request.json();
|
||||
const { documentId, workspaceId, title, commandName }: RenamePayload = await request.json();
|
||||
const normalizedDocumentId = assertDocumentId(documentId);
|
||||
const normalizedTitle = assertTitle(title);
|
||||
const normalizedWorkspaceId = workspaceId?.trim() || null;
|
||||
|
||||
if (commandName !== PAGE_COMMAND_NAMES.updateTitle) {
|
||||
const upstreamUrl = new URL("/api/tree/commands", request.url);
|
||||
const response = await fetch(upstreamUrl.toString(), {
|
||||
method: "POST",
|
||||
headers: new Headers({
|
||||
"content-type": "application/json",
|
||||
}),
|
||||
body: JSON.stringify({
|
||||
action: "rename",
|
||||
documentId: normalizedDocumentId,
|
||||
workspaceId: normalizedWorkspaceId,
|
||||
title: normalizedTitle,
|
||||
}),
|
||||
});
|
||||
|
||||
const payload = (await response.json().catch(() => null)) as TreeRenameResponse | { error?: string } | null;
|
||||
if (!response.ok) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error:
|
||||
payload && typeof payload === "object" && "error" in payload && typeof payload.error === "string"
|
||||
? payload.error
|
||||
: "重命名失败,请稍后再试",
|
||||
},
|
||||
{ status: response.status },
|
||||
);
|
||||
}
|
||||
|
||||
return NextResponse.json({
|
||||
ok: true,
|
||||
meta: {
|
||||
requestId: payload?.requestId,
|
||||
traceId: payload?.traceId,
|
||||
commandName: "tree.node.rename",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const bridgeContext = await buildDocumentBridgeContext({ request, workspaceId: normalizedWorkspaceId });
|
||||
const envelope = buildDocumentCommandEnvelope({
|
||||
name: PAGE_COMMAND_NAMES.updateTitle,
|
||||
|
||||
@@ -5,6 +5,11 @@ const mockBuildDocumentBridgeContext = vi.fn();
|
||||
const mockBuildDocumentQueryEnvelope = vi.fn();
|
||||
const mockExecuteRustBridgeQueryTransport = vi.fn();
|
||||
const mockResolveRustBridgeQueryPlan = vi.fn();
|
||||
const mockResolveKernelFileTreeProjection = vi.fn();
|
||||
const mockAttachKernelFileTreeProjection = vi.fn((input: { dataset: unknown; projection: unknown }) => ({
|
||||
...(input.dataset as Record<string, unknown>),
|
||||
kernel_file_tree_projection: input.projection,
|
||||
}));
|
||||
const mockDocumentBridgeErrorResponse = vi.fn((error: unknown) =>
|
||||
Response.json(
|
||||
{
|
||||
@@ -29,6 +34,11 @@ vi.mock("@/lib/documents/rust-runtime", () => ({
|
||||
resolveRustBridgeQueryPlan: mockResolveRustBridgeQueryPlan,
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/server/kernel-file-tree", () => ({
|
||||
resolveKernelFileTreeProjection: (...args: unknown[]) => mockResolveKernelFileTreeProjection(...args),
|
||||
attachKernelFileTreeProjection: (...args: unknown[]) => mockAttachKernelFileTreeProjection(...args),
|
||||
}));
|
||||
|
||||
describe("/api/mnote-web/stream route", () => {
|
||||
beforeEach(() => {
|
||||
mockGetAuthedConvexClient.mockReset();
|
||||
@@ -36,11 +46,18 @@ describe("/api/mnote-web/stream route", () => {
|
||||
mockBuildDocumentQueryEnvelope.mockReset();
|
||||
mockExecuteRustBridgeQueryTransport.mockReset();
|
||||
mockResolveRustBridgeQueryPlan.mockReset();
|
||||
mockResolveKernelFileTreeProjection.mockReset();
|
||||
mockAttachKernelFileTreeProjection.mockClear();
|
||||
mockDocumentBridgeErrorResponse.mockClear();
|
||||
});
|
||||
|
||||
it("直接在 3000 内生成 snapshot SSE,不再回源 mnote-web", async () => {
|
||||
mockGetAuthedConvexClient.mockResolvedValue({
|
||||
auth: {
|
||||
userId: "user_1",
|
||||
email: "dev@example.com",
|
||||
name: "开发用户",
|
||||
},
|
||||
client: { query: vi.fn() },
|
||||
});
|
||||
mockBuildDocumentBridgeContext.mockResolvedValue({
|
||||
@@ -107,6 +124,13 @@ describe("/api/mnote-web/stream route", () => {
|
||||
has_more: false,
|
||||
generated_at: "2026-04-22T00:00:00Z",
|
||||
});
|
||||
mockResolveKernelFileTreeProjection.mockResolvedValue({
|
||||
projectionId: "kernel_projection:file_tree:root",
|
||||
projection: "file_tree",
|
||||
rootNodeId: null,
|
||||
items: [],
|
||||
edges: [],
|
||||
});
|
||||
|
||||
const { GET } = await import("./route");
|
||||
const response = await GET(
|
||||
@@ -124,7 +148,103 @@ describe("/api/mnote-web/stream route", () => {
|
||||
expect(text).toContain('"projection":"sidebar_tree"');
|
||||
expect(text).toContain('"workspaceId":"ws_1"');
|
||||
expect(text).toContain('"activeWorkspaceId":"ws_1"');
|
||||
expect(text).toContain('"kernelFileTreeProjection"');
|
||||
expect(mockResolveRustBridgeQueryPlan).toHaveBeenCalledTimes(2);
|
||||
expect(mockExecuteRustBridgeQueryTransport).toHaveBeenCalledTimes(2);
|
||||
expect(mockResolveKernelFileTreeProjection).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("应把请求 cursor 继续透传到 overview query 和 snapshot envelope", async () => {
|
||||
mockGetAuthedConvexClient.mockResolvedValue({
|
||||
auth: {
|
||||
userId: "user_1",
|
||||
email: "dev@example.com",
|
||||
name: "开发用户",
|
||||
},
|
||||
client: { query: vi.fn() },
|
||||
});
|
||||
mockBuildDocumentBridgeContext.mockResolvedValue({
|
||||
requestId: "req_stream_2",
|
||||
traceId: "trace_stream_2",
|
||||
workspaceId: "ws_1",
|
||||
});
|
||||
mockBuildDocumentQueryEnvelope
|
||||
.mockReturnValueOnce({
|
||||
name: "sidebar.dataset.list",
|
||||
payload: { workspaceId: "ws_1" },
|
||||
})
|
||||
.mockReturnValueOnce({
|
||||
name: "bridge.workspace.overview",
|
||||
payload: {
|
||||
workspaceId: "ws_1",
|
||||
limit: 20,
|
||||
cursor: "evt_9",
|
||||
commandStatus: null,
|
||||
eventStatus: null,
|
||||
targetPageId: null,
|
||||
targetBlockId: null,
|
||||
aggregateType: null,
|
||||
aggregateId: null,
|
||||
},
|
||||
});
|
||||
mockResolveRustBridgeQueryPlan
|
||||
.mockResolvedValueOnce({ kind: "query", functionName: "sidebar:datasetList", argsJson: { workspaceId: "ws_1" } })
|
||||
.mockResolvedValueOnce({
|
||||
kind: "query",
|
||||
functionName: "bridgeLogs:listWorkspaceOverview",
|
||||
argsJson: { workspaceId: "ws_1", cursor: "evt_9" },
|
||||
});
|
||||
mockExecuteRustBridgeQueryTransport
|
||||
.mockResolvedValueOnce({
|
||||
active_workspace_id: "ws_1",
|
||||
workspaces: [],
|
||||
documents: [],
|
||||
trashed_documents: [],
|
||||
media_assets: [],
|
||||
trashed_media_assets: [],
|
||||
mindmap_assets: [],
|
||||
trashed_mindmap_assets: [],
|
||||
table_assets: [],
|
||||
trashed_table_assets: [],
|
||||
mindmap_docs: [],
|
||||
mindmap_asset_children: {},
|
||||
})
|
||||
.mockResolvedValueOnce({
|
||||
workspace_id: "ws_1",
|
||||
command_logs: [],
|
||||
domain_events: [],
|
||||
counts: { command_logs: 0, domain_events: 0 },
|
||||
filters: null,
|
||||
next_cursor: "evt_10",
|
||||
has_more: true,
|
||||
generated_at: "2026-04-22T00:00:00Z",
|
||||
});
|
||||
mockResolveKernelFileTreeProjection.mockResolvedValue({
|
||||
projectionId: "kernel_projection:file_tree:root",
|
||||
projection: "file_tree",
|
||||
rootNodeId: null,
|
||||
items: [],
|
||||
edges: [],
|
||||
});
|
||||
|
||||
const { GET } = await import("./route");
|
||||
const response = await GET(
|
||||
new Request("http://127.0.0.1:3000/api/mnote-web/stream?workspaceId=ws_1&cursor=evt_9", {
|
||||
method: "GET",
|
||||
}),
|
||||
);
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
const text = await response.text();
|
||||
expect(text).toContain('"cursor":"evt_9"');
|
||||
expect(mockBuildDocumentQueryEnvelope).toHaveBeenNthCalledWith(
|
||||
2,
|
||||
expect.objectContaining({
|
||||
payload: expect.objectContaining({
|
||||
workspaceId: "ws_1",
|
||||
cursor: "evt_9",
|
||||
}),
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -9,6 +9,10 @@ import {
|
||||
resolveRustBridgeQueryPlan,
|
||||
} from "@/lib/documents/rust-runtime";
|
||||
import { mapSidebarDatasetListQueryResultToInitialData } from "@/lib/sidebar-data";
|
||||
import {
|
||||
attachKernelFileTreeProjection,
|
||||
resolveKernelFileTreeProjection,
|
||||
} from "@/lib/server/kernel-file-tree";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
@@ -26,7 +30,7 @@ export async function GET(request: Request) {
|
||||
return Response.json({ error: "缺少 workspaceId" }, { status: 400 });
|
||||
}
|
||||
|
||||
const { client } = await getAuthedConvexClient();
|
||||
const { auth, client } = await getAuthedConvexClient();
|
||||
const context = await buildDocumentBridgeContext({
|
||||
request,
|
||||
workspaceId,
|
||||
@@ -46,6 +50,20 @@ export async function GET(request: Request) {
|
||||
client,
|
||||
plan: sidebarPlan,
|
||||
});
|
||||
const sidebarDatasetWithFileTree = attachKernelFileTreeProjection({
|
||||
dataset: sidebarDataset,
|
||||
projection: await resolveKernelFileTreeProjection({
|
||||
client,
|
||||
request,
|
||||
workspaceId,
|
||||
actor: {
|
||||
actorType: "user",
|
||||
actorId: auth.userId,
|
||||
sessionId: null,
|
||||
},
|
||||
dataset: sidebarDataset,
|
||||
}),
|
||||
});
|
||||
|
||||
const overviewEnvelope = buildDocumentQueryEnvelope({
|
||||
name: "bridge.workspace.overview",
|
||||
@@ -79,10 +97,13 @@ export async function GET(request: Request) {
|
||||
cursor,
|
||||
requestId: context.requestId,
|
||||
traceId: context.traceId,
|
||||
data: mapSidebarDatasetListQueryResultToInitialData(sidebarDataset),
|
||||
data: mapSidebarDatasetListQueryResultToInitialData(sidebarDatasetWithFileTree),
|
||||
snapshot: {
|
||||
dataset: sidebarDataset,
|
||||
tree: sidebarDataset.kernel_sidebar_projection ?? sidebarDataset.kernelSidebarProjection ?? null,
|
||||
dataset: sidebarDatasetWithFileTree,
|
||||
tree:
|
||||
sidebarDatasetWithFileTree.kernel_sidebar_projection ??
|
||||
sidebarDatasetWithFileTree.kernelSidebarProjection ??
|
||||
null,
|
||||
},
|
||||
overview,
|
||||
};
|
||||
|
||||
@@ -16,6 +16,10 @@ import {
|
||||
mapSidebarDatasetListQueryResultToInitialData,
|
||||
type SidebarDatasetListQueryResult,
|
||||
} from "@/lib/sidebar-data";
|
||||
import {
|
||||
attachKernelFileTreeProjection,
|
||||
resolveKernelFileTreeProjection,
|
||||
} from "@/lib/server/kernel-file-tree";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
@@ -54,7 +58,21 @@ export async function GET(request: Request) {
|
||||
client,
|
||||
plan,
|
||||
});
|
||||
const result = mapSidebarDatasetListQueryResultToInitialData(sidebarDataset);
|
||||
const sidebarDatasetWithFileTree = attachKernelFileTreeProjection({
|
||||
dataset: sidebarDataset,
|
||||
projection: await resolveKernelFileTreeProjection({
|
||||
client,
|
||||
request,
|
||||
workspaceId: targetWorkspaceId,
|
||||
actor: {
|
||||
actorType: "user",
|
||||
actorId: auth.userId,
|
||||
sessionId: null,
|
||||
},
|
||||
dataset: sidebarDataset,
|
||||
}),
|
||||
});
|
||||
const result = mapSidebarDatasetListQueryResultToInitialData(sidebarDatasetWithFileTree);
|
||||
|
||||
return NextResponse.json({
|
||||
...result,
|
||||
|
||||
@@ -0,0 +1,374 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const mockIsConvexEnabled = vi.fn(() => true);
|
||||
const mockGetAuthedConvexClient = vi.fn();
|
||||
const mockBuildDocumentBridgeContext = vi.fn();
|
||||
const mockBuildDocumentCommandEnvelope = vi.fn();
|
||||
const mockResolveRustBridgeCommandPlan = vi.fn();
|
||||
const mockExecuteRustBridgeMutationTransport = vi.fn();
|
||||
const mockDocumentBridgeErrorResponse = vi.fn((error: unknown) =>
|
||||
Response.json(
|
||||
{
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
},
|
||||
{ status: 500 },
|
||||
),
|
||||
);
|
||||
const mockEnsureDocumentScaffold = vi.fn();
|
||||
|
||||
vi.mock("@/lib/convex/enabled", () => ({
|
||||
isConvexEnabled: () => mockIsConvexEnabled(),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/convex/api", () => ({
|
||||
api: {
|
||||
documents: {
|
||||
getMeta: "documents:getMeta",
|
||||
},
|
||||
workspaces: {
|
||||
ensureDefaultWorkspace: "workspaces:ensureDefaultWorkspace",
|
||||
},
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/convex/route", () => ({
|
||||
getAuthedConvexClient: mockGetAuthedConvexClient,
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/documents/bridge", () => ({
|
||||
assertDocumentId: (value: string | null | undefined) => {
|
||||
const normalized = typeof value === "string" ? value.trim() : "";
|
||||
if (!normalized) {
|
||||
throw new Error("缺少 documentId");
|
||||
}
|
||||
return normalized;
|
||||
},
|
||||
assertTitle: (value: string | null | undefined) => {
|
||||
const normalized = typeof value === "string" ? value.trim() : "";
|
||||
if (!normalized) {
|
||||
throw new Error("缺少标题");
|
||||
}
|
||||
return normalized;
|
||||
},
|
||||
buildDocumentBridgeContext: mockBuildDocumentBridgeContext,
|
||||
buildDocumentCommandEnvelope: mockBuildDocumentCommandEnvelope,
|
||||
documentBridgeErrorResponse: (...args: unknown[]) => mockDocumentBridgeErrorResponse(...args),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/documents/rust-runtime", () => ({
|
||||
resolveRustBridgeCommandPlan: (...args: unknown[]) => mockResolveRustBridgeCommandPlan(...args),
|
||||
executeRustBridgeMutationTransport: (...args: unknown[]) => mockExecuteRustBridgeMutationTransport(...args),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/documents/page-lifecycle-side-effects", () => ({
|
||||
ensureDocumentScaffold: (...args: unknown[]) => mockEnsureDocumentScaffold(...args),
|
||||
}));
|
||||
|
||||
describe("/api/tree/commands route", () => {
|
||||
beforeEach(() => {
|
||||
mockIsConvexEnabled.mockReturnValue(true);
|
||||
mockGetAuthedConvexClient.mockReset();
|
||||
mockBuildDocumentBridgeContext.mockReset();
|
||||
mockBuildDocumentCommandEnvelope.mockReset();
|
||||
mockResolveRustBridgeCommandPlan.mockReset();
|
||||
mockExecuteRustBridgeMutationTransport.mockReset();
|
||||
mockEnsureDocumentScaffold.mockReset();
|
||||
mockDocumentBridgeErrorResponse.mockClear();
|
||||
});
|
||||
|
||||
it("create action 走 tree.node.create,并保留本地 scaffold 副作用", async () => {
|
||||
const client = {
|
||||
mutation: vi.fn(async () => ({ activeWorkspaceId: "ws_root" })),
|
||||
query: vi.fn(),
|
||||
};
|
||||
mockGetAuthedConvexClient.mockResolvedValue({
|
||||
auth: {
|
||||
userId: "user_1",
|
||||
email: "dev@example.com",
|
||||
name: "开发用户",
|
||||
},
|
||||
client,
|
||||
});
|
||||
mockBuildDocumentBridgeContext.mockResolvedValue({
|
||||
requestId: "req_tree_1",
|
||||
traceId: "trace_tree_1",
|
||||
workspaceId: "ws_root",
|
||||
actor: {
|
||||
actorType: "user",
|
||||
actorId: "user_1",
|
||||
sessionId: null,
|
||||
},
|
||||
source: {
|
||||
channel: "next-route",
|
||||
client: "wolai-frontend",
|
||||
},
|
||||
tenantId: null,
|
||||
deploymentId: null,
|
||||
projectId: null,
|
||||
authToken: null,
|
||||
idempotencyKey: null,
|
||||
validateOnly: false,
|
||||
dryRun: false,
|
||||
});
|
||||
mockBuildDocumentCommandEnvelope.mockImplementation((input: unknown) => input);
|
||||
mockResolveRustBridgeCommandPlan.mockResolvedValue({
|
||||
kind: "command",
|
||||
commandName: "tree.node.create",
|
||||
commandId: "cmd_tree_create_1",
|
||||
functionName: "documents:createWithParentReference",
|
||||
workspaceId: "ws_root",
|
||||
requestId: "req_tree_1",
|
||||
traceId: "trace_tree_1",
|
||||
actorId: "user_1",
|
||||
idempotencyKey: null,
|
||||
payloadJson: "{}",
|
||||
argsJson: {},
|
||||
});
|
||||
mockExecuteRustBridgeMutationTransport.mockResolvedValue({
|
||||
id: "doc_new",
|
||||
title: "无标题",
|
||||
parent_id: null,
|
||||
sort_order: 0,
|
||||
workspace_id: "ws_root",
|
||||
access_scope: "private",
|
||||
is_template: false,
|
||||
created_at: "2026-04-23T00:00:00Z",
|
||||
updated_at: "2026-04-23T00:00:00Z",
|
||||
});
|
||||
|
||||
const { POST } = await import("./route");
|
||||
const response = await POST(
|
||||
new Request("http://127.0.0.1:3000/api/tree/commands", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
action: "create",
|
||||
parentId: null,
|
||||
}),
|
||||
}),
|
||||
);
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
const payload = await response.json() as {
|
||||
result: {
|
||||
action: string;
|
||||
documentId: string;
|
||||
workspaceId: string;
|
||||
title: string;
|
||||
};
|
||||
};
|
||||
expect(payload.result.action).toBe("create");
|
||||
expect(payload.result.documentId).toBe("doc_new");
|
||||
expect(payload.result.workspaceId).toBe("ws_root");
|
||||
expect(mockBuildDocumentCommandEnvelope).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
name: "tree.node.create",
|
||||
payload: expect.objectContaining({
|
||||
workspaceId: "ws_root",
|
||||
parentId: null,
|
||||
title: "无标题",
|
||||
accessScope: "private",
|
||||
}),
|
||||
}),
|
||||
);
|
||||
expect(mockEnsureDocumentScaffold).toHaveBeenCalledWith("doc_new", "无标题");
|
||||
});
|
||||
|
||||
it("move action 走 tree.subtree.move,并把 position 归一化为 sortOrder", async () => {
|
||||
const client = {
|
||||
mutation: vi.fn(),
|
||||
query: vi.fn(async () => ({
|
||||
id: "doc_1",
|
||||
workspace_id: "ws_1",
|
||||
})),
|
||||
};
|
||||
mockGetAuthedConvexClient.mockResolvedValue({
|
||||
auth: {
|
||||
userId: "user_1",
|
||||
email: "dev@example.com",
|
||||
name: "开发用户",
|
||||
},
|
||||
client,
|
||||
});
|
||||
mockBuildDocumentBridgeContext.mockResolvedValue({
|
||||
requestId: "req_tree_2",
|
||||
traceId: "trace_tree_2",
|
||||
workspaceId: "ws_1",
|
||||
actor: {
|
||||
actorType: "user",
|
||||
actorId: "user_1",
|
||||
sessionId: null,
|
||||
},
|
||||
source: {
|
||||
channel: "next-route",
|
||||
client: "wolai-frontend",
|
||||
},
|
||||
tenantId: null,
|
||||
deploymentId: null,
|
||||
projectId: null,
|
||||
authToken: null,
|
||||
idempotencyKey: null,
|
||||
validateOnly: false,
|
||||
dryRun: false,
|
||||
});
|
||||
mockBuildDocumentCommandEnvelope.mockImplementation((input: unknown) => input);
|
||||
mockResolveRustBridgeCommandPlan.mockResolvedValue({
|
||||
kind: "command",
|
||||
commandName: "tree.subtree.move",
|
||||
commandId: "cmd_tree_move_1",
|
||||
functionName: "documents:move",
|
||||
workspaceId: "ws_1",
|
||||
requestId: "req_tree_2",
|
||||
traceId: "trace_tree_2",
|
||||
actorId: "user_1",
|
||||
idempotencyKey: null,
|
||||
payloadJson: "{}",
|
||||
argsJson: {},
|
||||
});
|
||||
mockExecuteRustBridgeMutationTransport.mockResolvedValue({
|
||||
ok: true,
|
||||
updated_at: "2026-04-23T00:00:00Z",
|
||||
});
|
||||
|
||||
const { POST } = await import("./route");
|
||||
const response = await POST(
|
||||
new Request("http://127.0.0.1:3000/api/tree/commands", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
action: "move",
|
||||
documentId: "doc_1",
|
||||
parentId: "parent_1",
|
||||
sortOrder: 2.9,
|
||||
workspaceId: "ws_1",
|
||||
}),
|
||||
}),
|
||||
);
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
const payload = await response.json() as {
|
||||
result: {
|
||||
action: string;
|
||||
documentId: string;
|
||||
parentId: string | null;
|
||||
sortOrder: number | null;
|
||||
};
|
||||
};
|
||||
expect(payload.result).toMatchObject({
|
||||
action: "move",
|
||||
documentId: "doc_1",
|
||||
parentId: "parent_1",
|
||||
sortOrder: 2,
|
||||
workspaceId: "ws_1",
|
||||
});
|
||||
expect(mockBuildDocumentCommandEnvelope).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
name: "tree.subtree.move",
|
||||
payload: {
|
||||
documentId: "doc_1",
|
||||
parentId: "parent_1",
|
||||
sortOrder: 2,
|
||||
},
|
||||
}),
|
||||
);
|
||||
expect(mockEnsureDocumentScaffold).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rename action 走 tree.node.rename,并保留标题 payload", async () => {
|
||||
const client = {
|
||||
mutation: vi.fn(),
|
||||
query: vi.fn(async () => ({
|
||||
id: "doc_1",
|
||||
workspace_id: "ws_1",
|
||||
})),
|
||||
};
|
||||
mockGetAuthedConvexClient.mockResolvedValue({
|
||||
auth: {
|
||||
userId: "user_1",
|
||||
email: "dev@example.com",
|
||||
name: "开发用户",
|
||||
},
|
||||
client,
|
||||
});
|
||||
mockBuildDocumentBridgeContext.mockResolvedValue({
|
||||
requestId: "req_tree_3",
|
||||
traceId: "trace_tree_3",
|
||||
workspaceId: "ws_1",
|
||||
actor: {
|
||||
actorType: "user",
|
||||
actorId: "user_1",
|
||||
sessionId: null,
|
||||
},
|
||||
source: {
|
||||
channel: "next-route",
|
||||
client: "wolai-frontend",
|
||||
},
|
||||
tenantId: null,
|
||||
deploymentId: null,
|
||||
projectId: null,
|
||||
authToken: null,
|
||||
idempotencyKey: null,
|
||||
validateOnly: false,
|
||||
dryRun: false,
|
||||
});
|
||||
mockBuildDocumentCommandEnvelope.mockImplementation((input: unknown) => input);
|
||||
mockResolveRustBridgeCommandPlan.mockResolvedValue({
|
||||
kind: "command",
|
||||
commandName: "tree.node.rename",
|
||||
commandId: "cmd_tree_rename_1",
|
||||
functionName: "documents:updateTitle",
|
||||
workspaceId: "ws_1",
|
||||
requestId: "req_tree_3",
|
||||
traceId: "trace_tree_3",
|
||||
actorId: "user_1",
|
||||
idempotencyKey: null,
|
||||
payloadJson: "{}",
|
||||
argsJson: {},
|
||||
});
|
||||
mockExecuteRustBridgeMutationTransport.mockResolvedValue({
|
||||
ok: true,
|
||||
updated_at: "2026-04-23T00:00:00Z",
|
||||
});
|
||||
|
||||
const { POST } = await import("./route");
|
||||
const response = await POST(
|
||||
new Request("http://127.0.0.1:3000/api/tree/commands", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
action: "rename",
|
||||
documentId: "doc_1",
|
||||
workspaceId: "ws_1",
|
||||
title: "新标题",
|
||||
}),
|
||||
}),
|
||||
);
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
const payload = await response.json() as {
|
||||
result: {
|
||||
action: string;
|
||||
documentId: string;
|
||||
workspaceId: string;
|
||||
title: string;
|
||||
};
|
||||
};
|
||||
expect(payload.result).toMatchObject({
|
||||
action: "rename",
|
||||
documentId: "doc_1",
|
||||
workspaceId: "ws_1",
|
||||
title: "新标题",
|
||||
});
|
||||
expect(mockBuildDocumentCommandEnvelope).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
name: "tree.node.rename",
|
||||
payload: {
|
||||
documentId: "doc_1",
|
||||
workspaceId: "ws_1",
|
||||
title: "新标题",
|
||||
},
|
||||
}),
|
||||
);
|
||||
expect(mockEnsureDocumentScaffold).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,259 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { NextResponse } from "next/server";
|
||||
import { api } from "@/lib/convex/api";
|
||||
import { isConvexEnabled } from "@/lib/convex/enabled";
|
||||
import { getAuthedConvexClient } from "@/lib/convex/route";
|
||||
import {
|
||||
assertDocumentId,
|
||||
assertTitle,
|
||||
buildDocumentBridgeContext,
|
||||
buildDocumentCommandEnvelope,
|
||||
documentBridgeErrorResponse,
|
||||
} from "@/lib/documents/bridge";
|
||||
import { ensureDocumentScaffold } from "@/lib/documents/page-lifecycle-side-effects";
|
||||
import {
|
||||
executeRustBridgeMutationTransport,
|
||||
resolveRustBridgeCommandPlan,
|
||||
} from "@/lib/documents/rust-runtime";
|
||||
|
||||
type TreeCommandPayload = {
|
||||
action?: "create" | "move" | "rename";
|
||||
workspaceId?: string | null;
|
||||
documentId?: string | null;
|
||||
parentId?: string | null;
|
||||
title?: string | null;
|
||||
accessScope?: "private" | "shared" | "public" | null;
|
||||
content?: unknown;
|
||||
sortOrder?: number | null;
|
||||
};
|
||||
|
||||
function trimOrNull(value: unknown) {
|
||||
if (typeof value !== "string") return null;
|
||||
const trimmed = value.trim();
|
||||
return trimmed.length > 0 ? trimmed : null;
|
||||
}
|
||||
|
||||
function normalizeTitle(value: unknown) {
|
||||
const title = typeof value === "string" ? value.trim() : "";
|
||||
return title || "无标题";
|
||||
}
|
||||
|
||||
function normalizeSortOrder(value: unknown) {
|
||||
return typeof value === "number" && Number.isFinite(value) ? Math.max(0, Math.floor(value)) : 0;
|
||||
}
|
||||
|
||||
export async function POST(request: Request) {
|
||||
if (!isConvexEnabled()) {
|
||||
return NextResponse.json({ error: "当前仅支持 Convex 模式" }, { status: 501 });
|
||||
}
|
||||
|
||||
try {
|
||||
const payload = (await request.json()) as TreeCommandPayload;
|
||||
switch (payload.action) {
|
||||
case "create":
|
||||
return handleCreate(request, payload);
|
||||
case "move":
|
||||
return handleMove(request, payload);
|
||||
case "rename":
|
||||
return handleRename(request, payload);
|
||||
default:
|
||||
return NextResponse.json({ error: "不支持的 tree action" }, { status: 400 });
|
||||
}
|
||||
} catch (error) {
|
||||
return documentBridgeErrorResponse(error);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleCreate(request: Request, payload: TreeCommandPayload) {
|
||||
const { auth, client } = await getAuthedConvexClient();
|
||||
const parentId = trimOrNull(payload.parentId);
|
||||
const workspaceBootstrap = await client.mutation(api.workspaces.ensureDefaultWorkspace, {
|
||||
fallbackName: auth.email ?? auth.name ?? "我的空间",
|
||||
workspaceIdIfCreate: randomUUID(),
|
||||
});
|
||||
|
||||
let workspaceId: string | null = trimOrNull(payload.workspaceId);
|
||||
let accessScope: "private" | "shared" | "public" = "private";
|
||||
if (parentId) {
|
||||
const parentDoc = await client.query(api.documents.getMeta, { id: parentId });
|
||||
if (!parentDoc) {
|
||||
return NextResponse.json({ error: "父页面不存在或无权限" }, { status: 404 });
|
||||
}
|
||||
workspaceId = trimOrNull(parentDoc.workspace_id);
|
||||
accessScope = (parentDoc.access_scope ?? "private") as typeof accessScope;
|
||||
} else if (!workspaceId) {
|
||||
workspaceId = trimOrNull(workspaceBootstrap.activeWorkspaceId);
|
||||
}
|
||||
|
||||
if (!workspaceId) {
|
||||
return NextResponse.json({ error: "缺少目标工作空间" }, { status: 400 });
|
||||
}
|
||||
|
||||
const documentId = trimOrNull(payload.documentId) ?? randomUUID();
|
||||
const title = normalizeTitle(payload.title);
|
||||
const context = await buildDocumentBridgeContext({
|
||||
request,
|
||||
workspaceId,
|
||||
});
|
||||
const envelope = buildDocumentCommandEnvelope({
|
||||
name: "tree.node.create",
|
||||
payload: {
|
||||
documentId,
|
||||
workspaceId,
|
||||
parentId,
|
||||
title,
|
||||
accessScope: trimOrNull(payload.accessScope) ?? accessScope,
|
||||
content: Array.isArray(payload.content) ? payload.content : [],
|
||||
},
|
||||
context,
|
||||
target: {
|
||||
workspaceId,
|
||||
pageId: documentId,
|
||||
},
|
||||
reason: "tree-route create",
|
||||
refs: ["next-tree-route"],
|
||||
});
|
||||
const plan = await resolveRustBridgeCommandPlan({
|
||||
context,
|
||||
envelope,
|
||||
});
|
||||
const result = await executeRustBridgeMutationTransport<{
|
||||
id: string;
|
||||
title: string | null;
|
||||
parent_id: string | null;
|
||||
sort_order: number | null;
|
||||
workspace_id: string;
|
||||
access_scope: "private" | "shared" | "public";
|
||||
is_template: boolean;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}>({
|
||||
client,
|
||||
plan,
|
||||
});
|
||||
|
||||
await ensureDocumentScaffold(result.id, result.title ?? title);
|
||||
|
||||
return NextResponse.json({
|
||||
requestId: context.requestId,
|
||||
traceId: context.traceId,
|
||||
result: {
|
||||
action: "create",
|
||||
workspaceId,
|
||||
documentId: result.id,
|
||||
parentId: result.parent_id ?? parentId,
|
||||
title: result.title ?? title,
|
||||
sortOrder: result.sort_order ?? null,
|
||||
updatedAt: result.updated_at ?? null,
|
||||
execution: result,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async function handleMove(request: Request, payload: TreeCommandPayload) {
|
||||
const { client } = await getAuthedConvexClient();
|
||||
const documentId = assertDocumentId(payload.documentId ?? null);
|
||||
const sourceDoc = await client.query(api.documents.getMeta, { id: documentId });
|
||||
if (!sourceDoc) {
|
||||
return NextResponse.json({ error: "页面不存在或无权访问" }, { status: 404 });
|
||||
}
|
||||
|
||||
const workspaceId = trimOrNull(payload.workspaceId) ?? trimOrNull(sourceDoc.workspace_id);
|
||||
const parentId = trimOrNull(payload.parentId);
|
||||
const sortOrder = normalizeSortOrder(payload.sortOrder);
|
||||
const context = await buildDocumentBridgeContext({
|
||||
request,
|
||||
workspaceId,
|
||||
});
|
||||
const envelope = buildDocumentCommandEnvelope({
|
||||
name: "tree.subtree.move",
|
||||
payload: {
|
||||
documentId,
|
||||
parentId,
|
||||
sortOrder,
|
||||
},
|
||||
context,
|
||||
target: {
|
||||
workspaceId,
|
||||
pageId: documentId,
|
||||
},
|
||||
reason: "tree-route move",
|
||||
refs: ["next-tree-route"],
|
||||
});
|
||||
const plan = await resolveRustBridgeCommandPlan({
|
||||
context,
|
||||
envelope,
|
||||
});
|
||||
const result = await executeRustBridgeMutationTransport<{ ok?: boolean; updated_at?: string | null }>({
|
||||
client,
|
||||
plan,
|
||||
});
|
||||
|
||||
return NextResponse.json({
|
||||
requestId: context.requestId,
|
||||
traceId: context.traceId,
|
||||
result: {
|
||||
action: "move",
|
||||
workspaceId,
|
||||
documentId,
|
||||
parentId,
|
||||
sortOrder,
|
||||
updatedAt: result?.updated_at ?? null,
|
||||
execution: result ?? null,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async function handleRename(request: Request, payload: TreeCommandPayload) {
|
||||
const { client } = await getAuthedConvexClient();
|
||||
const documentId = assertDocumentId(payload.documentId ?? null);
|
||||
const sourceDoc = await client.query(api.documents.getMeta, { id: documentId });
|
||||
if (!sourceDoc) {
|
||||
return NextResponse.json({ error: "页面不存在或无权访问" }, { status: 404 });
|
||||
}
|
||||
|
||||
const workspaceId = trimOrNull(payload.workspaceId) ?? trimOrNull(sourceDoc.workspace_id);
|
||||
const title = assertTitle(payload.title ?? null);
|
||||
const context = await buildDocumentBridgeContext({
|
||||
request,
|
||||
workspaceId,
|
||||
});
|
||||
const envelope = buildDocumentCommandEnvelope({
|
||||
name: "tree.node.rename",
|
||||
payload: {
|
||||
documentId,
|
||||
workspaceId,
|
||||
title,
|
||||
},
|
||||
context,
|
||||
target: {
|
||||
workspaceId,
|
||||
pageId: documentId,
|
||||
},
|
||||
reason: "tree-route rename",
|
||||
refs: ["next-tree-route"],
|
||||
});
|
||||
const plan = await resolveRustBridgeCommandPlan({
|
||||
context,
|
||||
envelope,
|
||||
});
|
||||
const result = await executeRustBridgeMutationTransport<{ ok?: boolean; updated_at?: string | null }>({
|
||||
client,
|
||||
plan,
|
||||
});
|
||||
|
||||
return NextResponse.json({
|
||||
requestId: context.requestId,
|
||||
traceId: context.traceId,
|
||||
result: {
|
||||
action: "rename",
|
||||
workspaceId,
|
||||
documentId,
|
||||
title,
|
||||
updatedAt: result?.updated_at ?? null,
|
||||
execution: result ?? null,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export const runtime = "nodejs";
|
||||
@@ -0,0 +1,80 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const mockResolveMnoteWebInternalUrl = vi.fn();
|
||||
const mockBuildForwardHeaders = vi.fn();
|
||||
const mockFetch = vi.fn();
|
||||
|
||||
vi.mock("@/lib/mnote-web/internal-url", () => ({
|
||||
resolveMnoteWebInternalUrl: (...args: unknown[]) => mockResolveMnoteWebInternalUrl(...args),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/server/forward-headers", () => ({
|
||||
buildForwardHeaders: (...args: unknown[]) => mockBuildForwardHeaders(...args),
|
||||
}));
|
||||
|
||||
describe("/api/tree/shell route", () => {
|
||||
beforeEach(() => {
|
||||
mockResolveMnoteWebInternalUrl.mockReset();
|
||||
mockBuildForwardHeaders.mockReset();
|
||||
mockFetch.mockReset();
|
||||
vi.stubGlobal("fetch", mockFetch);
|
||||
});
|
||||
|
||||
it("通过 3000 同源代理回源 mnote-web tree shell,并移除不应透传的响应头", async () => {
|
||||
mockResolveMnoteWebInternalUrl.mockResolvedValue("http://127.0.0.1:3104");
|
||||
mockBuildForwardHeaders.mockResolvedValue(
|
||||
new Headers({
|
||||
cookie: "session=abc",
|
||||
authorization: "Bearer test-token",
|
||||
}),
|
||||
);
|
||||
mockFetch.mockResolvedValue(
|
||||
new Response("<!doctype html><html><body>tree shell</body></html>", {
|
||||
status: 200,
|
||||
headers: {
|
||||
"content-type": "text/html; charset=utf-8",
|
||||
"set-cookie": "debug=1",
|
||||
connection: "keep-alive",
|
||||
"x-upstream": "mnote-web-tree",
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
const { GET } = await import("./route");
|
||||
const response = await GET(
|
||||
new Request(
|
||||
"http://127.0.0.1:3000/api/tree/shell?workspaceId=ws_1&mode=page&activeDocumentId=doc_9",
|
||||
{
|
||||
method: "GET",
|
||||
headers: {
|
||||
cookie: "session=abc",
|
||||
},
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
expect(mockFetch).toHaveBeenCalledWith(
|
||||
"http://127.0.0.1:3104/tree?workspaceId=ws_1&mode=page&activeDocumentId=doc_9",
|
||||
expect.objectContaining({
|
||||
method: "GET",
|
||||
headers: expect.any(Headers),
|
||||
cache: "no-store",
|
||||
redirect: "manual",
|
||||
}),
|
||||
);
|
||||
|
||||
const fetchHeaders = mockFetch.mock.calls[0]?.[1]?.headers as Headers;
|
||||
expect(fetchHeaders.get("cookie")).toBe("session=abc");
|
||||
expect(fetchHeaders.get("authorization")).toBe("Bearer test-token");
|
||||
expect(fetchHeaders.get("accept")).toContain("text/html");
|
||||
expect(fetchHeaders.get("x-mnote-source-channel")).toBe("next_tree_shell_proxy");
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(response.headers.get("content-type")).toContain("text/html");
|
||||
expect(response.headers.get("cache-control")).toBe("no-store");
|
||||
expect(response.headers.get("set-cookie")).toBeNull();
|
||||
expect(response.headers.get("connection")).toBeNull();
|
||||
expect(response.headers.get("x-upstream")).toBe("mnote-web-tree");
|
||||
expect(await response.text()).toContain("tree shell");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,67 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { resolveMnoteWebInternalUrl } from "@/lib/mnote-web/internal-url";
|
||||
import { buildForwardHeaders } from "@/lib/server/forward-headers";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
export const runtime = "nodejs";
|
||||
|
||||
const stripHopByHopHeaders = (headers: Headers) => {
|
||||
// 说明:代理响应不应继续透传 hop-by-hop headers,避免浏览器拿到无效连接语义。
|
||||
const hopByHopHeaders = [
|
||||
"connection",
|
||||
"keep-alive",
|
||||
"proxy-authenticate",
|
||||
"proxy-authorization",
|
||||
"te",
|
||||
"trailer",
|
||||
"transfer-encoding",
|
||||
"upgrade",
|
||||
"content-length",
|
||||
];
|
||||
hopByHopHeaders.forEach((name) => headers.delete(name));
|
||||
};
|
||||
|
||||
export async function GET(request: Request) {
|
||||
try {
|
||||
const requestUrl = new URL(request.url);
|
||||
const internalBaseUrl = await resolveMnoteWebInternalUrl();
|
||||
const targetUrl = new URL("/tree", `${internalBaseUrl}/`);
|
||||
targetUrl.search = requestUrl.search;
|
||||
|
||||
const headers = await buildForwardHeaders(request);
|
||||
headers.set("accept", "text/html,application/xhtml+xml");
|
||||
headers.set("x-mnote-source-channel", "next_tree_shell_proxy");
|
||||
headers.set("x-mnote-source-client", "wolai-frontend");
|
||||
|
||||
const workspaceId = requestUrl.searchParams.get("workspaceId")?.trim();
|
||||
if (workspaceId && !headers.has("x-mnote-workspace-id")) {
|
||||
headers.set("x-mnote-workspace-id", workspaceId);
|
||||
}
|
||||
|
||||
const upstream = await fetch(targetUrl.toString(), {
|
||||
method: "GET",
|
||||
headers,
|
||||
cache: "no-store",
|
||||
redirect: "manual",
|
||||
});
|
||||
const body = await upstream.arrayBuffer();
|
||||
const responseHeaders = new Headers(upstream.headers);
|
||||
stripHopByHopHeaders(responseHeaders);
|
||||
responseHeaders.delete("set-cookie");
|
||||
responseHeaders.set("cache-control", "no-store");
|
||||
|
||||
return new NextResponse(body, {
|
||||
status: upstream.status,
|
||||
statusText: upstream.statusText,
|
||||
headers: responseHeaders,
|
||||
});
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : "tree shell 代理失败";
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: message,
|
||||
},
|
||||
{ status: 502 },
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -23,6 +23,7 @@ export function AppLayoutShell({ initialData, children }: AppLayoutShellProps) {
|
||||
initialData,
|
||||
sidebarQueryData: sidebarQuery.data,
|
||||
treeStreamData: treeStream.data,
|
||||
treeStreamStatus: treeStream.status,
|
||||
});
|
||||
|
||||
return (
|
||||
|
||||
@@ -39,12 +39,14 @@ vi.mock("@tanstack/react-query", () => ({
|
||||
},
|
||||
}));
|
||||
|
||||
const mockUseDocumentSearch = vi.fn(() => ({
|
||||
data: null,
|
||||
isLoading: false,
|
||||
error: null,
|
||||
}));
|
||||
|
||||
vi.mock("@/hooks/use-document-search", () => ({
|
||||
useDocumentSearch: () => ({
|
||||
data: null,
|
||||
isLoading: false,
|
||||
error: null,
|
||||
}),
|
||||
useDocumentSearch: (...args: unknown[]) => mockUseDocumentSearch(...args),
|
||||
}));
|
||||
|
||||
vi.mock("@/components/ui/dialog", () => ({
|
||||
@@ -100,6 +102,13 @@ describe("MoveEmbedPickerDialog", () => {
|
||||
});
|
||||
container.remove();
|
||||
vi.clearAllMocks();
|
||||
mockUseDocumentSearch.mockReset();
|
||||
mockUseDocumentSearch.mockReturnValue({
|
||||
data: null,
|
||||
isLoading: false,
|
||||
error: null,
|
||||
});
|
||||
delete window.__MNOTE_RUNTIME_CONFIG__;
|
||||
});
|
||||
|
||||
it("空查询时会使用统一 picker surface 并透传根目录选择", async () => {
|
||||
@@ -131,4 +140,130 @@ describe("MoveEmbedPickerDialog", () => {
|
||||
expect(onPick).toHaveBeenCalledWith("move", null);
|
||||
expect(onOpenChange).toHaveBeenCalledWith(false);
|
||||
});
|
||||
|
||||
it("搜索结果也应继续复用统一 picker surface", async () => {
|
||||
mockUseDocumentSearch.mockReturnValue({
|
||||
data: {
|
||||
results: [
|
||||
{
|
||||
id: "doc_target",
|
||||
title: "目标页面",
|
||||
matchField: "title",
|
||||
},
|
||||
],
|
||||
},
|
||||
isLoading: false,
|
||||
error: null,
|
||||
});
|
||||
|
||||
const onPick = vi.fn(async () => undefined);
|
||||
const onOpenChange = vi.fn();
|
||||
|
||||
await act(async () => {
|
||||
root.render(
|
||||
<MoveEmbedPickerDialog
|
||||
open
|
||||
onOpenChange={onOpenChange}
|
||||
workspaceId="ws_test"
|
||||
defaultMode="move"
|
||||
allowRoot
|
||||
excludeIds={[]}
|
||||
onPick={onPick}
|
||||
/>,
|
||||
);
|
||||
});
|
||||
|
||||
const input = container.querySelector("input");
|
||||
expect(input).not.toBeNull();
|
||||
|
||||
await act(async () => {
|
||||
input?.dispatchEvent(new Event("input", { bubbles: true }));
|
||||
Object.defineProperty(input as HTMLInputElement, "value", {
|
||||
configurable: true,
|
||||
value: "目标",
|
||||
});
|
||||
input?.dispatchEvent(new Event("change", { bubbles: true }));
|
||||
});
|
||||
|
||||
const pickerSurface = container.querySelector('[data-testid="tree-picker-surface"]');
|
||||
const pickerRows = container.querySelectorAll('[data-testid="tree-picker-row"]');
|
||||
expect(pickerSurface).not.toBeNull();
|
||||
expect(pickerRows).toHaveLength(1);
|
||||
|
||||
await act(async () => {
|
||||
pickerRows[0]?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
|
||||
});
|
||||
|
||||
expect(onPick).toHaveBeenCalledWith("move", "doc_target");
|
||||
expect(onOpenChange).toHaveBeenCalledWith(false);
|
||||
});
|
||||
|
||||
it("rust_family 配置下,picker 空态与结果态都应进入统一 host", async () => {
|
||||
window.__MNOTE_RUNTIME_CONFIG__ = {
|
||||
treeRendererFamily: "rust_family",
|
||||
};
|
||||
|
||||
const onPick = vi.fn(async () => undefined);
|
||||
const onOpenChange = vi.fn();
|
||||
|
||||
await act(async () => {
|
||||
root.render(
|
||||
<MoveEmbedPickerDialog
|
||||
open
|
||||
onOpenChange={onOpenChange}
|
||||
workspaceId="ws_test"
|
||||
defaultMode="move"
|
||||
allowRoot
|
||||
excludeIds={[]}
|
||||
onPick={onPick}
|
||||
/>,
|
||||
);
|
||||
});
|
||||
|
||||
const emptySurface = container.querySelector('[data-testid="tree-picker-surface"]');
|
||||
expect(emptySurface?.getAttribute("data-tree-host-kind")).toBe("rust_family");
|
||||
expect(emptySurface?.getAttribute("data-tree-host-implementation")).toBe("mnote_web_iframe_proxy");
|
||||
expect(
|
||||
container.querySelector('[data-testid="tree-picker-surface-rust-host"]'),
|
||||
).not.toBeNull();
|
||||
expect(
|
||||
container.querySelector('[data-testid="tree-picker-surface-rust-iframe"]'),
|
||||
).not.toBeNull();
|
||||
|
||||
mockUseDocumentSearch.mockReturnValue({
|
||||
data: {
|
||||
results: [
|
||||
{
|
||||
id: "doc_target",
|
||||
title: "目标页面",
|
||||
matchField: "title",
|
||||
},
|
||||
],
|
||||
},
|
||||
isLoading: false,
|
||||
error: null,
|
||||
});
|
||||
|
||||
const input = container.querySelector("input");
|
||||
expect(input).not.toBeNull();
|
||||
|
||||
await act(async () => {
|
||||
Object.defineProperty(input as HTMLInputElement, "value", {
|
||||
configurable: true,
|
||||
value: "目标",
|
||||
});
|
||||
input?.dispatchEvent(new Event("input", { bubbles: true }));
|
||||
input?.dispatchEvent(new Event("change", { bubbles: true }));
|
||||
});
|
||||
|
||||
const resultSurface = container.querySelector('[data-testid="tree-picker-surface"]');
|
||||
expect(resultSurface?.getAttribute("data-tree-host-kind")).toBe("rust_family");
|
||||
expect(resultSurface?.getAttribute("data-tree-host-implementation")).toBe("mnote_web_iframe_proxy");
|
||||
expect(
|
||||
container.querySelector('[data-testid="tree-picker-surface-rust-host"]'),
|
||||
).not.toBeNull();
|
||||
expect(
|
||||
container.querySelector('[data-testid="tree-picker-surface-rust-iframe"]'),
|
||||
).not.toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -8,8 +8,8 @@ import { Dialog, DialogContent, DialogTitle } from "@/components/ui/dialog";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
||||
import type { SidebarInitialData } from "@/components/sidebar/types";
|
||||
import { getMnoteRuntimeConfig } from "@/lib/runtime-config";
|
||||
import { buildPageTreeProjectionItems, buildPickerTreeItems } from "@/lib/tree-projection";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { useDocumentSearch } from "@/hooks/use-document-search";
|
||||
import type { DocumentSearchFilters, DocumentSearchResult } from "@/types/search";
|
||||
|
||||
@@ -106,6 +106,7 @@ function MoveEmbedPickerDialogBody({
|
||||
const [mode, setMode] = useState<MoveEmbedMode>(defaultMode);
|
||||
const [query, setQuery] = useState("");
|
||||
const [highlighted, setHighlighted] = useState(0);
|
||||
const treeRendererFamily = getMnoteRuntimeConfig().treeRendererFamily ?? "react";
|
||||
|
||||
const handleModeChange = useCallback((value: string) => {
|
||||
setMode(value as MoveEmbedMode);
|
||||
@@ -207,6 +208,11 @@ function MoveEmbedPickerDialogBody({
|
||||
<div className="p-4 text-sm text-gray-400">没有匹配结果</div>
|
||||
) : (
|
||||
<TreePickerSurface
|
||||
rendererFamily={treeRendererFamily}
|
||||
workspaceId={workspaceId}
|
||||
treeShellEnabled={isEmptyQuery}
|
||||
allowRootPick={allowRoot && mode === "move"}
|
||||
excludeIds={excludeIds}
|
||||
items={items}
|
||||
highlighted={highlighted}
|
||||
onHighlight={setHighlighted}
|
||||
@@ -278,28 +284,21 @@ function MoveEmbedPickerDialogBody({
|
||||
) : items.length === 0 ? (
|
||||
<div className="p-4 text-sm text-gray-400">没有匹配结果</div>
|
||||
) : (
|
||||
<div className="py-2">
|
||||
{items.map((item, idx) => (
|
||||
<button
|
||||
key={item.kind === "root" ? "root" : item.id}
|
||||
type="button"
|
||||
className={cn(
|
||||
"w-full px-4 py-3 text-left transition-colors hover:bg-[#eef2ff]",
|
||||
idx === highlighted && "bg-[#e3ecff]",
|
||||
)}
|
||||
onMouseEnter={() => setHighlighted(idx)}
|
||||
onClick={() => void handlePick(item.id)}
|
||||
>
|
||||
<div
|
||||
className="text-sm font-medium text-gray-900"
|
||||
style={item.kind === "doc" ? { paddingLeft: 12 * (item.depth ?? 0) } : undefined}
|
||||
>
|
||||
{item.title}
|
||||
</div>
|
||||
{item.subtitle && <div className="mt-1 text-xs text-gray-500">{item.subtitle}</div>}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<TreePickerSurface
|
||||
rendererFamily={treeRendererFamily}
|
||||
workspaceId={workspaceId}
|
||||
treeShellEnabled={Boolean(workspaceId)}
|
||||
allowRootPick={false}
|
||||
excludeIds={excludeIds}
|
||||
treeShellItems={items}
|
||||
items={items}
|
||||
highlighted={highlighted}
|
||||
className="py-2"
|
||||
onHighlight={setHighlighted}
|
||||
onPick={(targetId) => {
|
||||
void handlePick(targetId);
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { SidebarInitialData } from "@/components/sidebar/types";
|
||||
import type { SidebarTreeNode } from "@/lib/kernel-sidebar";
|
||||
import type { MediaAsset } from "@/types/media";
|
||||
import type { KernelFileTreeProjection } from "@/lib/kernel-file-tree";
|
||||
|
||||
type SidebarTreeSnapshot = {
|
||||
id: string;
|
||||
@@ -42,6 +43,20 @@ function toMillis(value: string | null | undefined): number {
|
||||
return Number.isFinite(parsed) ? parsed : 0;
|
||||
}
|
||||
|
||||
function normalizeKernelFileTreeProjection(
|
||||
projection: SidebarInitialData["kernelFileTreeProjection"] | undefined,
|
||||
): KernelFileTreeProjection {
|
||||
return (
|
||||
projection ?? {
|
||||
projectionId: "kernel_projection:file_tree:missing",
|
||||
projection: "file_tree",
|
||||
rootNodeId: null,
|
||||
items: [],
|
||||
edges: [],
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
export function buildSidebarTreeSyncKey(nodes: SidebarTreeNode[]): string {
|
||||
return JSON.stringify(toSidebarTreeSnapshot(nodes));
|
||||
}
|
||||
@@ -51,9 +66,31 @@ export function buildMediaAssetListSyncKey(assets: MediaAsset[]): string {
|
||||
}
|
||||
|
||||
export function buildSidebarDataSyncKey(data: SidebarInitialData): string {
|
||||
const fileTreeProjection = normalizeKernelFileTreeProjection(data.kernelFileTreeProjection);
|
||||
return JSON.stringify({
|
||||
activeWorkspaceId: data.activeWorkspaceId,
|
||||
tree: toSidebarTreeSnapshot(data.kernelSidebarTree),
|
||||
fileTree: {
|
||||
projectionId: fileTreeProjection.projectionId,
|
||||
rootNodeId: fileTreeProjection.rootNodeId,
|
||||
items: fileTreeProjection.items.map((item) => ({
|
||||
rowId: item.rowId,
|
||||
rowKind: item.rowKind,
|
||||
nodeId: item.nodeId,
|
||||
parentNodeId: item.parentNodeId,
|
||||
title: item.title,
|
||||
depth: item.depth,
|
||||
position: item.position,
|
||||
childCount: item.childCount,
|
||||
expandable: item.expandable,
|
||||
expandedByDefault: item.expandedByDefault,
|
||||
iconHint: item.iconHint ?? null,
|
||||
resourceKind: item.resourceMeta.resourceKind,
|
||||
documentId: item.resourceMeta.documentId ?? null,
|
||||
assetId: item.resourceMeta.assetId ?? null,
|
||||
assetKind: item.resourceMeta.assetKind ?? null,
|
||||
})),
|
||||
},
|
||||
mediaAssets: toMediaAssetSnapshot(data.mediaAssets ?? []),
|
||||
mindmapAssets: toMediaAssetSnapshot(data.mindmapAssets ?? []),
|
||||
tableAssets: toMediaAssetSnapshot(data.tableAssets ?? []),
|
||||
@@ -73,6 +110,8 @@ export function buildSidebarDataSyncKey(data: SidebarInitialData): string {
|
||||
export function getSidebarDataFreshness(data: SidebarInitialData): number {
|
||||
const documentTimes = data.documents.map((item) => toMillis(item.updated_at ?? item.created_at));
|
||||
const treeTimes = data.kernelSidebarTree.map((item) => toMillis(item.updated_at ?? item.created_at));
|
||||
const fileTreeProjection = normalizeKernelFileTreeProjection(data.kernelFileTreeProjection);
|
||||
const fileTreeTimes = fileTreeProjection.items.map((item) => item.position ?? 0);
|
||||
const assetTimes = [
|
||||
...(data.mediaAssets ?? []),
|
||||
...(data.mindmapAssets ?? []),
|
||||
@@ -87,6 +126,7 @@ export function getSidebarDataFreshness(data: SidebarInitialData): number {
|
||||
0,
|
||||
...documentTimes,
|
||||
...treeTimes,
|
||||
...fileTreeTimes,
|
||||
...assetTimes,
|
||||
...trashedDocumentTimes,
|
||||
);
|
||||
|
||||
@@ -199,6 +199,7 @@ function SidebarContent({ initialData, sidebarData: externalSidebarData, sidebar
|
||||
initialData,
|
||||
sidebarQueryData: sidebarQuery.data,
|
||||
treeStreamData: treeStream.data,
|
||||
treeStreamStatus: treeStream.status,
|
||||
});
|
||||
const sidebarData = externalSidebarData ?? preferredSidebarSnapshot.data;
|
||||
|
||||
@@ -211,6 +212,7 @@ function SidebarContent({ initialData, sidebarData: externalSidebarData, sidebar
|
||||
const { signOut } = useAuthActions();
|
||||
const activeId = segments?.[1] ?? "";
|
||||
const editorBridge = useEditorBridgeStore((state) => state.bridge);
|
||||
const treeRendererFamily = getMnoteRuntimeConfig().treeRendererFamily ?? "react";
|
||||
|
||||
const [tree, setTree] = useState<SidebarTreeNode[]>(() => sidebarData.kernelSidebarTree);
|
||||
const [filter, setFilter] = useState("");
|
||||
@@ -673,18 +675,28 @@ function SidebarContent({ initialData, sidebarData: externalSidebarData, sidebar
|
||||
const resourceRows = useMemo(
|
||||
() =>
|
||||
buildVisibleRows({
|
||||
fileTreeItems:
|
||||
filter.trim().length === 0
|
||||
? sidebarData.kernelFileTreeProjection.items
|
||||
: undefined,
|
||||
pageRows: visibleFilteredPrivatePageRows,
|
||||
expanded,
|
||||
assetsByDoc,
|
||||
assetChildrenByAssetId: mindmapChildrenSnapshot.childAssetsByMindmapId,
|
||||
expandedAssetFolderIds: expandedAssetFolders,
|
||||
nodeById,
|
||||
assetById,
|
||||
}),
|
||||
[
|
||||
assetById,
|
||||
assetsByDoc,
|
||||
expanded,
|
||||
expandedAssetFolders,
|
||||
mindmapChildrenSnapshot.childAssetsByMindmapId,
|
||||
nodeById,
|
||||
sidebarData.kernelFileTreeProjection.items,
|
||||
visibleFilteredPrivatePageRows,
|
||||
filter,
|
||||
],
|
||||
);
|
||||
|
||||
@@ -967,6 +979,118 @@ function SidebarContent({ initialData, sidebarData: externalSidebarData, sidebar
|
||||
[],
|
||||
);
|
||||
|
||||
const handlePageTreeShellNavigate = useCallback(
|
||||
(documentId: string) => {
|
||||
handleOpenDocument(documentId, "sidebar");
|
||||
},
|
||||
[handleOpenDocument],
|
||||
);
|
||||
|
||||
const handleFileTreeShellNavigate = useCallback(
|
||||
(documentId: string) => {
|
||||
handleOpenDocument(documentId, "main");
|
||||
},
|
||||
[handleOpenDocument],
|
||||
);
|
||||
|
||||
const handlePageTreeShellContextMenu = useCallback(
|
||||
(payload: { documentId: string; x: number; y: number }) => {
|
||||
const node = nodeById.get(payload.documentId);
|
||||
if (!node) {
|
||||
return;
|
||||
}
|
||||
setContextMenu({
|
||||
node,
|
||||
x: payload.x,
|
||||
y: payload.y,
|
||||
});
|
||||
},
|
||||
[nodeById],
|
||||
);
|
||||
|
||||
const handleFileTreeShellContextMenu = useCallback(
|
||||
(payload: {
|
||||
documentId: string | null;
|
||||
assetId: string | null;
|
||||
rowId: string | null;
|
||||
rowKind: string | null;
|
||||
x: number;
|
||||
y: number;
|
||||
}) => {
|
||||
if (payload.assetId) {
|
||||
const asset = assetById.get(payload.assetId);
|
||||
if (asset) {
|
||||
setAssetMenu({
|
||||
asset,
|
||||
x: payload.x,
|
||||
y: payload.y,
|
||||
});
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
const row = payload.rowId ? resourceRowById.get(payload.rowId) : null;
|
||||
const node =
|
||||
row && (row.kind === "doc" || row.kind === "index")
|
||||
? row.node
|
||||
: payload.documentId
|
||||
? nodeById.get(payload.documentId) ?? null
|
||||
: null;
|
||||
if (!node) {
|
||||
return;
|
||||
}
|
||||
setContextMenu({
|
||||
node,
|
||||
x: payload.x,
|
||||
y: payload.y,
|
||||
});
|
||||
},
|
||||
[assetById, nodeById, resourceRowById],
|
||||
);
|
||||
|
||||
const handleFileTreeShellSelectionChange = useCallback(
|
||||
(payload: {
|
||||
selectedRowIds: string[];
|
||||
anchorRowId: string | null;
|
||||
focusedRowId: string | null;
|
||||
}) => {
|
||||
const visibleRowIds = resourceRows.map((row) => row.rowId);
|
||||
const normalized = normalizeTreePaneSelectionForVisibleRows(
|
||||
{
|
||||
selectedRowIds: new Set(
|
||||
payload.selectedRowIds.filter((rowId) => resourceRowById.has(rowId)),
|
||||
),
|
||||
anchorRowId:
|
||||
payload.anchorRowId && resourceRowById.has(payload.anchorRowId)
|
||||
? payload.anchorRowId
|
||||
: null,
|
||||
focusedRowId:
|
||||
payload.focusedRowId && resourceRowById.has(payload.focusedRowId)
|
||||
? payload.focusedRowId
|
||||
: null,
|
||||
},
|
||||
visibleRowIds,
|
||||
);
|
||||
setResourceSelection(normalized);
|
||||
},
|
||||
[resourceRowById, resourceRows],
|
||||
);
|
||||
|
||||
const handleFileTreeShellAssetOpen = useCallback(
|
||||
(payload: { assetId: string; documentId: string | null }) => {
|
||||
const asset = assetById.get(payload.assetId);
|
||||
if (!asset) {
|
||||
return;
|
||||
}
|
||||
handleOpenAsset(asset);
|
||||
},
|
||||
[assetById, handleOpenAsset],
|
||||
);
|
||||
|
||||
const handleTreeShellMutation = useCallback(() => {
|
||||
void refreshTree();
|
||||
}, [refreshTree]);
|
||||
|
||||
useEffect(() => {
|
||||
const handler = async (event: KeyboardEvent) => {
|
||||
const isCopy =
|
||||
@@ -2593,6 +2717,9 @@ function SidebarContent({ initialData, sidebarData: externalSidebarData, sidebar
|
||||
<div className="flex-1 px-1 pb-2">
|
||||
<SidebarTreeSurface
|
||||
mode="page"
|
||||
rendererFamily={treeRendererFamily}
|
||||
workspaceId={sidebarData.activeWorkspaceId ?? null}
|
||||
treeShellEnabled={filter.trim().length === 0}
|
||||
className="h-full"
|
||||
rows={visibleFilteredPrivatePageRows}
|
||||
expanded={expanded}
|
||||
@@ -2601,6 +2728,9 @@ function SidebarContent({ initialData, sidebarData: externalSidebarData, sidebar
|
||||
onMove={handleMove}
|
||||
onCreateChild={handleCreate}
|
||||
onContextMenu={openContextMenu}
|
||||
onNavigate={handlePageTreeShellNavigate}
|
||||
onPageContextMenu={handlePageTreeShellContextMenu}
|
||||
onTreeMutation={handleTreeShellMutation}
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
@@ -2618,6 +2748,9 @@ function SidebarContent({ initialData, sidebarData: externalSidebarData, sidebar
|
||||
>
|
||||
<SidebarTreeSurface
|
||||
mode="filetree"
|
||||
rendererFamily={treeRendererFamily}
|
||||
workspaceId={sidebarData.activeWorkspaceId ?? null}
|
||||
treeShellEnabled={filter.trim().length === 0}
|
||||
className="h-full"
|
||||
rows={resourceRows}
|
||||
activeId={activeId}
|
||||
@@ -2635,6 +2768,11 @@ function SidebarContent({ initialData, sidebarData: externalSidebarData, sidebar
|
||||
onBlankMouseDown={handleResourcePaneBlankMouseDown}
|
||||
onDropFiles={handleResourcePaneDropFiles}
|
||||
onInternalDrop={handleResourcePaneInternalDrop}
|
||||
onNavigate={handleFileTreeShellNavigate}
|
||||
onFileTreeContextMenu={handleFileTreeShellContextMenu}
|
||||
onFileTreeSelectionChange={handleFileTreeShellSelectionChange}
|
||||
onAssetOpen={handleFileTreeShellAssetOpen}
|
||||
onTreeMutation={handleTreeShellMutation}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
"use client";
|
||||
|
||||
import type { ReactNode } from "react";
|
||||
import {
|
||||
TreeShellIframeHost,
|
||||
type TreeShellPickerItem,
|
||||
} from "@/components/sidebar/tree-shell-iframe-host";
|
||||
import type { FileTreeRow } from "@/lib/file-tree/types";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
export type TreeRendererFamily = "react" | "rust_family";
|
||||
|
||||
export type TreeShellHostMode = "page" | "filetree" | "picker";
|
||||
|
||||
type TreeShellHostProps = {
|
||||
mode: TreeShellHostMode;
|
||||
surfaceTestId: string;
|
||||
rendererFamily?: TreeRendererFamily;
|
||||
className?: string;
|
||||
treeShellEnabled?: boolean;
|
||||
workspaceId?: string | null;
|
||||
rootNodeId?: string | null;
|
||||
activeDocumentId?: string | null;
|
||||
allowRootPick?: boolean;
|
||||
excludeIds?: string[];
|
||||
pickerItems?: TreeShellPickerItem[];
|
||||
fileTreeRows?: FileTreeRow[];
|
||||
channel?: string;
|
||||
host?: string;
|
||||
onNavigate?: (documentId: string) => void;
|
||||
onPick?: (targetId: string | null) => void;
|
||||
onPageContextMenu?: (payload: { documentId: string; x: number; y: number }) => void;
|
||||
onFileTreeContextMenu?: (payload: {
|
||||
documentId: string | null;
|
||||
assetId: string | null;
|
||||
rowId: string | null;
|
||||
rowKind: string | null;
|
||||
x: number;
|
||||
y: number;
|
||||
}) => void;
|
||||
onFileTreeSelectionChange?: (payload: {
|
||||
selectedRowIds: string[];
|
||||
anchorRowId: string | null;
|
||||
focusedRowId: string | null;
|
||||
}) => void;
|
||||
onInternalDrop?: (args: { targetRow: FileTreeRow; rowIds: string[]; copy: boolean }) => void;
|
||||
onDropFiles?: (docId: string, files: FileList | File[], targetRow?: FileTreeRow) => void;
|
||||
onAssetOpen?: (payload: { assetId: string; documentId: string | null }) => void;
|
||||
onTreeMutation?: (payload: { type: string; documentId: string | null }) => void;
|
||||
children: ReactNode;
|
||||
};
|
||||
|
||||
export function TreeShellHost({
|
||||
mode,
|
||||
surfaceTestId,
|
||||
rendererFamily = "react",
|
||||
className,
|
||||
treeShellEnabled = true,
|
||||
workspaceId = null,
|
||||
rootNodeId = null,
|
||||
activeDocumentId = null,
|
||||
allowRootPick = false,
|
||||
excludeIds = [],
|
||||
pickerItems = [],
|
||||
fileTreeRows = [],
|
||||
channel,
|
||||
host,
|
||||
onNavigate,
|
||||
onPick,
|
||||
onPageContextMenu,
|
||||
onFileTreeContextMenu,
|
||||
onFileTreeSelectionChange,
|
||||
onInternalDrop,
|
||||
onDropFiles,
|
||||
onAssetOpen,
|
||||
onTreeMutation,
|
||||
children,
|
||||
}: TreeShellHostProps) {
|
||||
const useRustHost = rendererFamily === "rust_family";
|
||||
const useIframeHost = useRustHost && treeShellEnabled && Boolean(workspaceId?.trim());
|
||||
const hostKind = rendererFamily === "rust_family" ? "rust_family" : "react";
|
||||
const implementation = useIframeHost
|
||||
? "mnote_web_iframe_proxy"
|
||||
: rendererFamily === "rust_family"
|
||||
? "react_fallback"
|
||||
: "react_primary";
|
||||
|
||||
return (
|
||||
<div
|
||||
data-testid={surfaceTestId}
|
||||
data-shell-mode={mode}
|
||||
data-renderer-family={rendererFamily}
|
||||
data-tree-host-kind={hostKind}
|
||||
data-tree-host-implementation={implementation}
|
||||
className={cn(className)}
|
||||
>
|
||||
{useRustHost ? (
|
||||
<div
|
||||
data-testid={`${surfaceTestId}-rust-host`}
|
||||
data-tree-host-mode={mode}
|
||||
data-tree-host-kind="rust_family"
|
||||
data-tree-host-implementation={implementation}
|
||||
className="contents"
|
||||
>
|
||||
{useIframeHost && workspaceId ? (
|
||||
<TreeShellIframeHost
|
||||
mode={mode}
|
||||
surfaceTestId={surfaceTestId}
|
||||
workspaceId={workspaceId}
|
||||
rootNodeId={rootNodeId}
|
||||
activeDocumentId={activeDocumentId}
|
||||
allowRootPick={allowRootPick}
|
||||
excludeIds={excludeIds}
|
||||
pickerItems={pickerItems}
|
||||
fileTreeRows={fileTreeRows}
|
||||
channel={channel}
|
||||
host={host}
|
||||
onNavigate={onNavigate}
|
||||
onPick={onPick}
|
||||
onPageContextMenu={onPageContextMenu}
|
||||
onFileTreeContextMenu={onFileTreeContextMenu}
|
||||
onFileTreeSelectionChange={onFileTreeSelectionChange}
|
||||
onInternalDrop={onInternalDrop}
|
||||
onDropFiles={onDropFiles}
|
||||
onAssetOpen={onAssetOpen}
|
||||
onTreeMutation={onTreeMutation}
|
||||
/>
|
||||
) : (
|
||||
children
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
children
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,304 @@
|
||||
import { act } from "react";
|
||||
import { createRoot, type Root } from "react-dom/client";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import {
|
||||
TreeShellIframeHost,
|
||||
buildTreeShellIframeSrc,
|
||||
buildTreeShellInlinePickerItems,
|
||||
injectTreeShellInlineOverrides,
|
||||
} from "./tree-shell-iframe-host";
|
||||
|
||||
(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
|
||||
|
||||
describe("tree-shell-iframe-host", () => {
|
||||
let container: HTMLDivElement;
|
||||
let root: Root;
|
||||
|
||||
beforeEach(() => {
|
||||
container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
root = createRoot(container);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
act(() => {
|
||||
root.unmount();
|
||||
});
|
||||
container.remove();
|
||||
});
|
||||
|
||||
it("应构造同源 tree shell iframe 地址,并透传 picker 所需 query", () => {
|
||||
const src = buildTreeShellIframeSrc({
|
||||
mode: "picker",
|
||||
workspaceId: "ws_picker",
|
||||
activeDocumentId: "doc_active",
|
||||
allowRootPick: true,
|
||||
excludeIds: ["doc_hidden", "doc_other"],
|
||||
channel: "tree-picker-surface",
|
||||
host: "tree-picker-surface",
|
||||
});
|
||||
const url = new URL(src, "http://127.0.0.1:3000");
|
||||
|
||||
expect(url.pathname).toBe("/api/tree/shell");
|
||||
expect(url.searchParams.get("workspaceId")).toBe("ws_picker");
|
||||
expect(url.searchParams.get("mode")).toBe("picker");
|
||||
expect(url.searchParams.get("activeDocumentId")).toBe("doc_active");
|
||||
expect(url.searchParams.get("allowRootPick")).toBe("1");
|
||||
expect(url.searchParams.get("excludeIds")).toBe("doc_hidden,doc_other");
|
||||
expect(url.searchParams.get("channel")).toBe("tree-picker-surface");
|
||||
expect(url.searchParams.get("host")).toBe("tree-picker-surface");
|
||||
});
|
||||
|
||||
it("应能把 picker 搜索结果转换为 inline shell items 并注入到 HTML", () => {
|
||||
const pickerItems = buildTreeShellInlinePickerItems([
|
||||
{ kind: "doc", id: "doc_target", title: "目标页面", depth: 0 },
|
||||
{ kind: "doc", id: "doc_recent", title: "最近</script>打开", depth: 0 },
|
||||
]);
|
||||
|
||||
expect(pickerItems).toEqual([
|
||||
expect.objectContaining({
|
||||
nodeId: "doc_target",
|
||||
parentNodeId: null,
|
||||
title: "目标页面",
|
||||
depth: 0,
|
||||
childCount: 0,
|
||||
}),
|
||||
expect.objectContaining({
|
||||
nodeId: "doc_recent",
|
||||
parentNodeId: null,
|
||||
title: "最近</script>打开",
|
||||
depth: 0,
|
||||
childCount: 0,
|
||||
}),
|
||||
]);
|
||||
|
||||
const html = injectTreeShellInlineOverrides(
|
||||
'<!doctype html><html><body><script id="tree-shell-state" type="application/json">{}</script></body></html>',
|
||||
{ items: pickerItems },
|
||||
);
|
||||
|
||||
expect(html).toContain("__MNOTE_TREE_SHELL_OVERRIDE__");
|
||||
expect(html).toContain("\\u003c/script\\u003e");
|
||||
expect(html.indexOf("__MNOTE_TREE_SHELL_OVERRIDE__")).toBeGreaterThan(-1);
|
||||
expect(html.indexOf("__MNOTE_TREE_SHELL_OVERRIDE__")).toBeLessThan(
|
||||
html.indexOf('id="tree-shell-state"'),
|
||||
);
|
||||
});
|
||||
|
||||
it("应把 iframe postMessage 桥接回宿主回调,并忽略错误 channel", async () => {
|
||||
const onNavigate = vi.fn();
|
||||
const onPageContextMenu = vi.fn();
|
||||
const onPick = vi.fn();
|
||||
const onFileTreeContextMenu = vi.fn();
|
||||
const onFileTreeSelectionChange = vi.fn();
|
||||
const onAssetOpen = vi.fn();
|
||||
const onTreeMutation = vi.fn();
|
||||
const onInternalDrop = vi.fn();
|
||||
const onDropFiles = vi.fn();
|
||||
const targetRow = {
|
||||
kind: "doc",
|
||||
rowId: "doc:doc_target",
|
||||
depth: 0,
|
||||
docId: "doc_target",
|
||||
parentDocId: null,
|
||||
node: {
|
||||
_id: "doc_target",
|
||||
id: "doc_target",
|
||||
title: "目标页面",
|
||||
},
|
||||
hasChildren: false,
|
||||
isExpanded: false,
|
||||
};
|
||||
const droppedFile = new File(["hello"], "hello.txt", { type: "text/plain" });
|
||||
|
||||
await act(async () => {
|
||||
root.render(
|
||||
<TreeShellIframeHost
|
||||
mode="filetree"
|
||||
surfaceTestId="sidebar-file-tree-shell"
|
||||
workspaceId="ws_1"
|
||||
activeDocumentId="doc_1"
|
||||
channel="sidebar-file-tree-shell"
|
||||
host="sidebar-file-tree-shell"
|
||||
onNavigate={onNavigate}
|
||||
onPageContextMenu={onPageContextMenu}
|
||||
onPick={onPick}
|
||||
onFileTreeContextMenu={onFileTreeContextMenu}
|
||||
onFileTreeSelectionChange={onFileTreeSelectionChange}
|
||||
onAssetOpen={onAssetOpen}
|
||||
onTreeMutation={onTreeMutation}
|
||||
onInternalDrop={onInternalDrop}
|
||||
onDropFiles={onDropFiles}
|
||||
/>,
|
||||
);
|
||||
});
|
||||
|
||||
const iframe = container.querySelector("iframe");
|
||||
expect(iframe).not.toBeNull();
|
||||
Object.defineProperty(iframe, "contentWindow", {
|
||||
configurable: true,
|
||||
value: window,
|
||||
});
|
||||
|
||||
await act(async () => {
|
||||
window.dispatchEvent(
|
||||
new MessageEvent("message", {
|
||||
data: {
|
||||
channel: "wrong-channel",
|
||||
type: "tree.navigate",
|
||||
documentId: "doc_wrong",
|
||||
},
|
||||
source: window,
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
expect(onNavigate).not.toHaveBeenCalled();
|
||||
|
||||
await act(async () => {
|
||||
window.dispatchEvent(
|
||||
new MessageEvent("message", {
|
||||
data: {
|
||||
channel: "sidebar-file-tree-shell",
|
||||
type: "tree.navigate",
|
||||
documentId: "doc_2",
|
||||
},
|
||||
source: window,
|
||||
}),
|
||||
);
|
||||
window.dispatchEvent(
|
||||
new MessageEvent("message", {
|
||||
data: {
|
||||
channel: "sidebar-file-tree-shell",
|
||||
type: "tree.page.context-menu",
|
||||
documentId: "doc_2",
|
||||
x: 12,
|
||||
y: 34,
|
||||
},
|
||||
source: window,
|
||||
}),
|
||||
);
|
||||
window.dispatchEvent(
|
||||
new MessageEvent("message", {
|
||||
data: {
|
||||
channel: "sidebar-file-tree-shell",
|
||||
type: "tree.pick.root",
|
||||
documentId: null,
|
||||
},
|
||||
source: window,
|
||||
}),
|
||||
);
|
||||
window.dispatchEvent(
|
||||
new MessageEvent("message", {
|
||||
data: {
|
||||
channel: "sidebar-file-tree-shell",
|
||||
type: "tree.filetree.context-menu",
|
||||
documentId: "doc_2",
|
||||
assetId: "asset_2",
|
||||
rowId: "asset:asset_2",
|
||||
rowKind: "asset",
|
||||
x: 56,
|
||||
y: 78,
|
||||
},
|
||||
source: window,
|
||||
}),
|
||||
);
|
||||
window.dispatchEvent(
|
||||
new MessageEvent("message", {
|
||||
data: {
|
||||
channel: "sidebar-file-tree-shell",
|
||||
type: "tree.filetree.selection.changed",
|
||||
selectedRowIds: ["doc:doc_2", "index:doc_2"],
|
||||
anchorRowId: "doc:doc_2",
|
||||
focusedRowId: "index:doc_2",
|
||||
},
|
||||
source: window,
|
||||
}),
|
||||
);
|
||||
window.dispatchEvent(
|
||||
new MessageEvent("message", {
|
||||
data: {
|
||||
channel: "sidebar-file-tree-shell",
|
||||
type: "tree.asset.open",
|
||||
documentId: "doc_2",
|
||||
assetId: "asset_2",
|
||||
},
|
||||
source: window,
|
||||
}),
|
||||
);
|
||||
window.dispatchEvent(
|
||||
new MessageEvent("message", {
|
||||
data: {
|
||||
channel: "sidebar-file-tree-shell",
|
||||
type: "tree.node.renamed",
|
||||
documentId: "doc_2",
|
||||
},
|
||||
source: window,
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
expect(onNavigate).toHaveBeenCalledWith("doc_2");
|
||||
expect(onPageContextMenu).toHaveBeenCalledWith({
|
||||
documentId: "doc_2",
|
||||
x: 12,
|
||||
y: 34,
|
||||
});
|
||||
expect(onPick).toHaveBeenCalledWith(null);
|
||||
expect(onFileTreeContextMenu).toHaveBeenCalledWith({
|
||||
documentId: "doc_2",
|
||||
assetId: "asset_2",
|
||||
rowId: "asset:asset_2",
|
||||
rowKind: "asset",
|
||||
x: 56,
|
||||
y: 78,
|
||||
});
|
||||
expect(onFileTreeSelectionChange).toHaveBeenCalledWith({
|
||||
selectedRowIds: ["doc:doc_2", "index:doc_2"],
|
||||
anchorRowId: "doc:doc_2",
|
||||
focusedRowId: "index:doc_2",
|
||||
});
|
||||
expect(onAssetOpen).toHaveBeenCalledWith({
|
||||
documentId: "doc_2",
|
||||
assetId: "asset_2",
|
||||
});
|
||||
expect(onTreeMutation).toHaveBeenCalledWith({
|
||||
type: "tree.node.renamed",
|
||||
documentId: "doc_2",
|
||||
});
|
||||
|
||||
await act(async () => {
|
||||
window.dispatchEvent(
|
||||
new MessageEvent("message", {
|
||||
data: {
|
||||
channel: "sidebar-file-tree-shell",
|
||||
type: "tree.filetree.internal-drop",
|
||||
rowIds: ["doc:doc_source", "asset:asset_source"],
|
||||
copy: true,
|
||||
targetRow,
|
||||
},
|
||||
source: window,
|
||||
}),
|
||||
);
|
||||
window.dispatchEvent(
|
||||
new MessageEvent("message", {
|
||||
data: {
|
||||
channel: "sidebar-file-tree-shell",
|
||||
type: "tree.filetree.drop-files",
|
||||
documentId: "doc_target",
|
||||
targetRow,
|
||||
files: [droppedFile],
|
||||
},
|
||||
source: window,
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
expect(onInternalDrop).toHaveBeenCalledWith({
|
||||
targetRow,
|
||||
rowIds: ["doc:doc_source", "asset:asset_source"],
|
||||
copy: true,
|
||||
});
|
||||
expect(onDropFiles).toHaveBeenCalledWith("doc_target", [droppedFile], targetRow);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,559 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useMemo, useRef, useState } from "react";
|
||||
import type { TreeShellHostMode } from "@/components/sidebar/tree-shell-host";
|
||||
import type { FileTreeRow } from "@/lib/file-tree/types";
|
||||
|
||||
type TreeShellDocRow = Extract<FileTreeRow, { kind: "doc" }>;
|
||||
type TreeShellIndexRow = Extract<FileTreeRow, { kind: "index" }>;
|
||||
type TreeShellAssetFolderRow = Extract<FileTreeRow, { kind: "asset-folder" }>;
|
||||
type TreeShellAssetRow = Extract<FileTreeRow, { kind: "asset" }>;
|
||||
|
||||
type TreeShellBridgeContextMenuPayload = {
|
||||
documentId: string | null;
|
||||
assetId: string | null;
|
||||
rowId: string | null;
|
||||
rowKind: string | null;
|
||||
x: number;
|
||||
y: number;
|
||||
};
|
||||
|
||||
type TreeShellBridgeMutationPayload = {
|
||||
type: string;
|
||||
documentId: string | null;
|
||||
};
|
||||
|
||||
type TreeShellBridgeSelectionPayload = {
|
||||
selectedRowIds: string[];
|
||||
anchorRowId: string | null;
|
||||
focusedRowId: string | null;
|
||||
};
|
||||
|
||||
export type TreeShellPickerItem =
|
||||
| { kind: "root"; id: null; title: string; subtitle?: string; depth?: number }
|
||||
| { kind: "doc"; id: string; title: string; subtitle?: string; depth?: number };
|
||||
|
||||
type TreeShellInlineProjectionItem = {
|
||||
nodeId: string;
|
||||
parentNodeId: string | null;
|
||||
title: string;
|
||||
depth: number;
|
||||
childCount: number;
|
||||
position: number;
|
||||
expandedByDefault: boolean;
|
||||
};
|
||||
|
||||
export type TreeShellIframeHostProps = {
|
||||
mode: TreeShellHostMode;
|
||||
surfaceTestId: string;
|
||||
workspaceId: string;
|
||||
rootNodeId?: string | null;
|
||||
activeDocumentId?: string | null;
|
||||
allowRootPick?: boolean;
|
||||
excludeIds?: string[];
|
||||
pickerItems?: TreeShellPickerItem[];
|
||||
fileTreeRows?: FileTreeRow[];
|
||||
channel?: string;
|
||||
host?: string;
|
||||
onNavigate?: (documentId: string) => void;
|
||||
onPick?: (targetId: string | null) => void;
|
||||
onPageContextMenu?: (payload: { documentId: string; x: number; y: number }) => void;
|
||||
onFileTreeContextMenu?: (payload: TreeShellBridgeContextMenuPayload) => void;
|
||||
onFileTreeSelectionChange?: (payload: TreeShellBridgeSelectionPayload) => void;
|
||||
onInternalDrop?: (args: { targetRow: FileTreeRow; rowIds: string[]; copy: boolean }) => void;
|
||||
onDropFiles?: (docId: string, files: FileList | File[], targetRow?: FileTreeRow) => void;
|
||||
onAssetOpen?: (payload: { assetId: string; documentId: string | null }) => void;
|
||||
onTreeMutation?: (payload: TreeShellBridgeMutationPayload) => void;
|
||||
};
|
||||
|
||||
type TreeShellBridgeMessage = {
|
||||
channel: string;
|
||||
type: string;
|
||||
documentId: string | null;
|
||||
assetId: string | null;
|
||||
rowId: string | null;
|
||||
rowKind: string | null;
|
||||
x: number;
|
||||
y: number;
|
||||
selectedRowIds: string[];
|
||||
anchorRowId: string | null;
|
||||
focusedRowId: string | null;
|
||||
rowIds: string[];
|
||||
copy: boolean;
|
||||
targetRow: FileTreeRow | null;
|
||||
files: File[];
|
||||
};
|
||||
|
||||
const INLINE_TREE_SHELL_LOADING_HTML = [
|
||||
"<!doctype html>",
|
||||
'<html lang="zh-CN">',
|
||||
"<head>",
|
||||
' <meta charset="utf-8" />',
|
||||
' <meta name="viewport" content="width=device-width, initial-scale=1" />',
|
||||
" <title>Tree Shell Loading</title>",
|
||||
" <style>",
|
||||
" body { margin: 0; font-family: \"Noto Sans CJK SC\", \"Source Han Sans SC\", sans-serif; background: #f8fafc; color: #475569; }",
|
||||
" main { min-height: 100vh; display: grid; place-items: center; }",
|
||||
" p { margin: 0; font-size: 13px; }",
|
||||
" </style>",
|
||||
"</head>",
|
||||
"<body>",
|
||||
" <main><p>正在加载树结果…</p></main>",
|
||||
"</body>",
|
||||
"</html>",
|
||||
].join("");
|
||||
|
||||
const normalizeString = (value: unknown, fallback = "") => {
|
||||
if (typeof value !== "string") return fallback;
|
||||
const normalized = value.trim();
|
||||
return normalized || fallback;
|
||||
};
|
||||
|
||||
const readNullableString = (value: unknown) => {
|
||||
const normalized = normalizeString(value);
|
||||
return normalized || null;
|
||||
};
|
||||
|
||||
const readNumber = (value: unknown) => {
|
||||
return typeof value === "number" && Number.isFinite(value) ? value : 0;
|
||||
};
|
||||
|
||||
const readBoolean = (value: unknown) => value === true;
|
||||
|
||||
const isRecord = (value: unknown): value is Record<string, unknown> => {
|
||||
return Boolean(value) && typeof value === "object";
|
||||
};
|
||||
|
||||
const readStringArray = (value: unknown) => {
|
||||
if (!Array.isArray(value)) {
|
||||
return [];
|
||||
}
|
||||
return value
|
||||
.map((item) => normalizeString(item))
|
||||
.filter(Boolean);
|
||||
};
|
||||
|
||||
const readFiles = (value: unknown) => {
|
||||
if (typeof FileList !== "undefined" && value instanceof FileList) {
|
||||
return Array.from(value);
|
||||
}
|
||||
if (!Array.isArray(value)) {
|
||||
return [];
|
||||
}
|
||||
return value.filter((item): item is File => typeof File !== "undefined" && item instanceof File);
|
||||
};
|
||||
|
||||
const readFileTreeRow = (value: unknown): FileTreeRow | null => {
|
||||
if (!isRecord(value)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const kind = normalizeString(value.kind);
|
||||
const rowId = normalizeString(value.rowId);
|
||||
const docId = normalizeString(value.docId);
|
||||
const depth = Math.max(0, readNumber(value.depth));
|
||||
|
||||
if (!kind || !rowId || !docId) {
|
||||
return null;
|
||||
}
|
||||
|
||||
switch (kind) {
|
||||
case "doc":
|
||||
if (!isRecord(value.node)) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
kind: "doc",
|
||||
rowId: rowId as FileTreeRow["rowId"],
|
||||
depth,
|
||||
docId,
|
||||
parentDocId: readNullableString(value.parentDocId),
|
||||
node: value.node as TreeShellDocRow["node"],
|
||||
hasChildren: readBoolean(value.hasChildren),
|
||||
isExpanded: readBoolean(value.isExpanded),
|
||||
};
|
||||
case "index":
|
||||
if (!isRecord(value.node)) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
kind: "index",
|
||||
rowId: rowId as FileTreeRow["rowId"],
|
||||
depth,
|
||||
docId,
|
||||
parentDocId: readNullableString(value.parentDocId) ?? docId,
|
||||
node: value.node as TreeShellIndexRow["node"],
|
||||
};
|
||||
case "asset-folder":
|
||||
if (!isRecord(value.asset)) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
kind: "asset-folder",
|
||||
rowId: rowId as FileTreeRow["rowId"],
|
||||
depth,
|
||||
docId,
|
||||
parentDocId: readNullableString(value.parentDocId) ?? docId,
|
||||
asset: value.asset as TreeShellAssetFolderRow["asset"],
|
||||
hasChildren: readBoolean(value.hasChildren),
|
||||
isExpanded: readBoolean(value.isExpanded),
|
||||
};
|
||||
case "asset":
|
||||
if (!isRecord(value.asset)) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
kind: "asset",
|
||||
rowId: rowId as FileTreeRow["rowId"],
|
||||
depth,
|
||||
docId,
|
||||
parentDocId: readNullableString(value.parentDocId) ?? docId,
|
||||
asset: value.asset as TreeShellAssetRow["asset"],
|
||||
};
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
function parseTreeShellBridgeMessage(
|
||||
value: unknown,
|
||||
expectedChannel: string,
|
||||
): TreeShellBridgeMessage | null {
|
||||
if (!value || typeof value !== "object") {
|
||||
return null;
|
||||
}
|
||||
const payload = value as Record<string, unknown>;
|
||||
const channel = normalizeString(payload.channel);
|
||||
const type = normalizeString(payload.type);
|
||||
if (!channel || !type || channel !== expectedChannel) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
channel,
|
||||
type,
|
||||
documentId: readNullableString(payload.documentId ?? payload.docId),
|
||||
assetId: readNullableString(payload.assetId),
|
||||
rowId: readNullableString(payload.rowId ?? payload.targetRowId),
|
||||
rowKind: readNullableString(payload.rowKind ?? payload.targetRowKind),
|
||||
x: readNumber(payload.x),
|
||||
y: readNumber(payload.y),
|
||||
selectedRowIds: readStringArray(payload.selectedRowIds),
|
||||
anchorRowId: readNullableString(payload.anchorRowId),
|
||||
focusedRowId: readNullableString(payload.focusedRowId),
|
||||
rowIds: readStringArray(payload.rowIds),
|
||||
copy: readBoolean(payload.copy),
|
||||
targetRow: readFileTreeRow(payload.targetRow),
|
||||
files: readFiles(payload.files),
|
||||
};
|
||||
}
|
||||
|
||||
const escapeInlineScriptJson = (input: string) => {
|
||||
return input
|
||||
.replace(/&/g, "\\u0026")
|
||||
.replace(/</g, "\\u003c")
|
||||
.replace(/>/g, "\\u003e");
|
||||
};
|
||||
|
||||
export function buildTreeShellInlinePickerItems(
|
||||
items: TreeShellPickerItem[],
|
||||
): TreeShellInlineProjectionItem[] {
|
||||
return items
|
||||
.filter(
|
||||
(item): item is Extract<TreeShellPickerItem, { kind: "doc"; id: string }> =>
|
||||
item.kind === "doc" && Boolean(normalizeString(item.id)),
|
||||
)
|
||||
.map((item, index) => ({
|
||||
nodeId: normalizeString(item.id),
|
||||
parentNodeId: null,
|
||||
title: normalizeString(item.title, "无标题"),
|
||||
depth: typeof item.depth === "number" && Number.isFinite(item.depth) ? Math.max(0, item.depth) : 0,
|
||||
childCount: 0,
|
||||
position: index,
|
||||
expandedByDefault: false,
|
||||
}));
|
||||
}
|
||||
|
||||
export function injectTreeShellInlineOverrides(
|
||||
html: string,
|
||||
overrides: { items?: TreeShellInlineProjectionItem[] },
|
||||
) {
|
||||
const payloadJson = escapeInlineScriptJson(JSON.stringify(overrides));
|
||||
const scriptTag = `<script>window.__MNOTE_TREE_SHELL_OVERRIDE__ = ${payloadJson};</script>`;
|
||||
const anchor = '<script id="tree-shell-state"';
|
||||
if (html.includes(anchor)) {
|
||||
return html.replace(anchor, `${scriptTag}${anchor}`);
|
||||
}
|
||||
return `${scriptTag}${html}`;
|
||||
}
|
||||
|
||||
export function buildTreeShellIframeSrc(input: {
|
||||
mode: TreeShellHostMode;
|
||||
workspaceId: string;
|
||||
rootNodeId?: string | null;
|
||||
activeDocumentId?: string | null;
|
||||
allowRootPick?: boolean;
|
||||
excludeIds?: string[];
|
||||
channel: string;
|
||||
host: string;
|
||||
}) {
|
||||
const params = new URLSearchParams();
|
||||
params.set("workspaceId", input.workspaceId);
|
||||
params.set("mode", input.mode);
|
||||
params.set("channel", input.channel);
|
||||
params.set("host", input.host);
|
||||
|
||||
const rootNodeId = normalizeString(input.rootNodeId);
|
||||
if (rootNodeId) {
|
||||
params.set("rootNodeId", rootNodeId);
|
||||
}
|
||||
|
||||
const activeDocumentId = normalizeString(input.activeDocumentId);
|
||||
if (activeDocumentId) {
|
||||
params.set("activeDocumentId", activeDocumentId);
|
||||
}
|
||||
|
||||
if (input.allowRootPick) {
|
||||
params.set("allowRootPick", "1");
|
||||
}
|
||||
|
||||
const excludeIds = (input.excludeIds ?? [])
|
||||
.map((item) => normalizeString(item))
|
||||
.filter(Boolean);
|
||||
if (excludeIds.length > 0) {
|
||||
params.set("excludeIds", excludeIds.join(","));
|
||||
}
|
||||
|
||||
return `/api/tree/shell?${params.toString()}`;
|
||||
}
|
||||
|
||||
export function TreeShellIframeHost({
|
||||
mode,
|
||||
surfaceTestId,
|
||||
workspaceId,
|
||||
rootNodeId = null,
|
||||
activeDocumentId = null,
|
||||
allowRootPick = false,
|
||||
excludeIds = [],
|
||||
pickerItems = [],
|
||||
fileTreeRows = [],
|
||||
channel,
|
||||
host,
|
||||
onNavigate,
|
||||
onPick,
|
||||
onPageContextMenu,
|
||||
onFileTreeContextMenu,
|
||||
onFileTreeSelectionChange,
|
||||
onInternalDrop,
|
||||
onDropFiles,
|
||||
onAssetOpen,
|
||||
onTreeMutation,
|
||||
}: TreeShellIframeHostProps) {
|
||||
const iframeRef = useRef<HTMLIFrameElement | null>(null);
|
||||
const [inlineSrcDoc, setInlineSrcDoc] = useState<string | null>(null);
|
||||
const [inlineLoadFailed, setInlineLoadFailed] = useState(false);
|
||||
const resolvedChannel = channel?.trim() || surfaceTestId;
|
||||
const resolvedHost = host?.trim() || surfaceTestId;
|
||||
const fileTreeRowById = useMemo(
|
||||
() => new Map(fileTreeRows.map((row) => [row.rowId, row])),
|
||||
[fileTreeRows],
|
||||
);
|
||||
const inlinePickerItems = useMemo(
|
||||
() => (mode === "picker" ? buildTreeShellInlinePickerItems(pickerItems) : []),
|
||||
[mode, pickerItems],
|
||||
);
|
||||
const useInlinePickerOverride = inlinePickerItems.length > 0;
|
||||
const src = useMemo(
|
||||
() =>
|
||||
buildTreeShellIframeSrc({
|
||||
mode,
|
||||
workspaceId,
|
||||
rootNodeId,
|
||||
activeDocumentId,
|
||||
allowRootPick,
|
||||
excludeIds,
|
||||
channel: resolvedChannel,
|
||||
host: resolvedHost,
|
||||
}),
|
||||
[
|
||||
activeDocumentId,
|
||||
allowRootPick,
|
||||
excludeIds,
|
||||
mode,
|
||||
resolvedChannel,
|
||||
resolvedHost,
|
||||
rootNodeId,
|
||||
workspaceId,
|
||||
],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (!useInlinePickerOverride) {
|
||||
setInlineSrcDoc(null);
|
||||
setInlineLoadFailed(false);
|
||||
return;
|
||||
}
|
||||
|
||||
let disposed = false;
|
||||
setInlineLoadFailed(false);
|
||||
setInlineSrcDoc(null);
|
||||
|
||||
void (async () => {
|
||||
try {
|
||||
const response = await fetch(src, {
|
||||
method: "GET",
|
||||
credentials: "include",
|
||||
cache: "no-store",
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw new Error(`tree shell inline override fetch failed: ${response.status}`);
|
||||
}
|
||||
const html = await response.text();
|
||||
if (disposed) {
|
||||
return;
|
||||
}
|
||||
setInlineSrcDoc(
|
||||
injectTreeShellInlineOverrides(html, {
|
||||
items: inlinePickerItems,
|
||||
}),
|
||||
);
|
||||
} catch {
|
||||
if (disposed) {
|
||||
return;
|
||||
}
|
||||
setInlineLoadFailed(true);
|
||||
setInlineSrcDoc(null);
|
||||
}
|
||||
})();
|
||||
|
||||
return () => {
|
||||
disposed = true;
|
||||
};
|
||||
}, [inlinePickerItems, src, useInlinePickerOverride]);
|
||||
|
||||
useEffect(() => {
|
||||
const onMessage = (event: MessageEvent) => {
|
||||
if (event.source !== iframeRef.current?.contentWindow) {
|
||||
return;
|
||||
}
|
||||
const message = parseTreeShellBridgeMessage(event.data, resolvedChannel);
|
||||
if (!message) {
|
||||
return;
|
||||
}
|
||||
|
||||
switch (message.type) {
|
||||
case "tree.navigate":
|
||||
if (message.documentId) {
|
||||
onNavigate?.(message.documentId);
|
||||
}
|
||||
return;
|
||||
case "tree.pick":
|
||||
onPick?.(message.documentId);
|
||||
return;
|
||||
case "tree.pick.root":
|
||||
onPick?.(null);
|
||||
return;
|
||||
case "tree.page.context-menu":
|
||||
if (message.documentId) {
|
||||
onPageContextMenu?.({
|
||||
documentId: message.documentId,
|
||||
x: message.x,
|
||||
y: message.y,
|
||||
});
|
||||
}
|
||||
return;
|
||||
case "tree.filetree.context-menu":
|
||||
onFileTreeContextMenu?.({
|
||||
documentId: message.documentId,
|
||||
assetId: message.assetId,
|
||||
rowId: message.rowId,
|
||||
rowKind: message.rowKind,
|
||||
x: message.x,
|
||||
y: message.y,
|
||||
});
|
||||
return;
|
||||
case "tree.filetree.selection.changed":
|
||||
onFileTreeSelectionChange?.({
|
||||
selectedRowIds: message.selectedRowIds,
|
||||
anchorRowId: message.anchorRowId,
|
||||
focusedRowId: message.focusedRowId,
|
||||
});
|
||||
return;
|
||||
case "tree.filetree.internal-drop":
|
||||
if (message.rowIds.length > 0) {
|
||||
const targetRow =
|
||||
message.targetRow ??
|
||||
(message.rowId ? (fileTreeRowById.get(message.rowId) ?? null) : null);
|
||||
if (!targetRow) {
|
||||
return;
|
||||
}
|
||||
onInternalDrop?.({
|
||||
targetRow,
|
||||
rowIds: message.rowIds,
|
||||
copy: message.copy,
|
||||
});
|
||||
}
|
||||
return;
|
||||
case "tree.filetree.external-drop":
|
||||
case "tree.filetree.drop-files":
|
||||
if (message.files.length > 0) {
|
||||
const targetRow =
|
||||
message.targetRow ??
|
||||
(message.rowId ? (fileTreeRowById.get(message.rowId) ?? null) : null);
|
||||
const targetDocId = message.documentId ?? targetRow?.docId ?? null;
|
||||
if (!targetDocId) {
|
||||
return;
|
||||
}
|
||||
onDropFiles?.(targetDocId, message.files, targetRow ?? undefined);
|
||||
}
|
||||
return;
|
||||
case "tree.asset.open":
|
||||
if (message.assetId) {
|
||||
onAssetOpen?.({
|
||||
assetId: message.assetId,
|
||||
documentId: message.documentId,
|
||||
});
|
||||
}
|
||||
return;
|
||||
case "tree.node.created":
|
||||
case "tree.node.renamed":
|
||||
case "tree.subtree.moved":
|
||||
onTreeMutation?.({
|
||||
type: message.type,
|
||||
documentId: message.documentId,
|
||||
});
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener("message", onMessage);
|
||||
return () => {
|
||||
window.removeEventListener("message", onMessage);
|
||||
};
|
||||
}, [
|
||||
onAssetOpen,
|
||||
fileTreeRowById,
|
||||
onFileTreeContextMenu,
|
||||
onFileTreeSelectionChange,
|
||||
onInternalDrop,
|
||||
onDropFiles,
|
||||
onNavigate,
|
||||
onPageContextMenu,
|
||||
onPick,
|
||||
onTreeMutation,
|
||||
resolvedChannel,
|
||||
]);
|
||||
|
||||
return (
|
||||
<iframe
|
||||
ref={iframeRef}
|
||||
src={useInlinePickerOverride && !inlineLoadFailed ? undefined : src}
|
||||
srcDoc={useInlinePickerOverride && !inlineLoadFailed ? inlineSrcDoc ?? INLINE_TREE_SHELL_LOADING_HTML : undefined}
|
||||
title={`tree-shell-${mode}`}
|
||||
data-testid={`${surfaceTestId}-rust-iframe`}
|
||||
data-tree-shell-mode={mode}
|
||||
data-tree-shell-channel={resolvedChannel}
|
||||
data-tree-shell-inline={useInlinePickerOverride && !inlineLoadFailed ? "1" : "0"}
|
||||
className="h-full w-full border-0 bg-white"
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,266 @@
|
||||
import { act } from "react";
|
||||
import { createRoot, type Root } from "react-dom/client";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { SidebarTreeSurface, TreePickerSurface, type TreeRendererFamily } from "./tree-shell-surface";
|
||||
|
||||
(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
|
||||
|
||||
vi.mock("@/components/sidebar/private-tree", () => ({
|
||||
PrivateTree: () => <div data-testid="private-tree-fallback" />,
|
||||
}));
|
||||
|
||||
vi.mock("@/components/sidebar/file-tree", () => ({
|
||||
FileTree: () => <div data-testid="file-tree-fallback" />,
|
||||
}));
|
||||
|
||||
describe("tree-shell-surface", () => {
|
||||
let container: HTMLDivElement;
|
||||
let root: Root;
|
||||
|
||||
beforeEach(() => {
|
||||
container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
root = createRoot(container);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
act(() => {
|
||||
root.unmount();
|
||||
});
|
||||
container.remove();
|
||||
});
|
||||
|
||||
function renderPageSurface(rendererFamily: TreeRendererFamily) {
|
||||
act(() => {
|
||||
root.render(
|
||||
<SidebarTreeSurface
|
||||
mode="page"
|
||||
rendererFamily={rendererFamily}
|
||||
workspaceId="ws_1"
|
||||
treeShellEnabled
|
||||
rows={[]}
|
||||
expanded={new Set<string>()}
|
||||
activeId=""
|
||||
onToggleExpand={() => undefined}
|
||||
onMove={() => undefined}
|
||||
onCreateChild={() => undefined}
|
||||
onContextMenu={() => undefined}
|
||||
/>,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
it("page tree surface 在 rust_family 下可切到同源 iframe host", () => {
|
||||
renderPageSurface("rust_family");
|
||||
|
||||
const surface = container.querySelector('[data-testid="sidebar-page-tree-shell"]');
|
||||
const rustHost = container.querySelector(
|
||||
'[data-testid="sidebar-page-tree-shell-rust-host"]',
|
||||
);
|
||||
const iframe = container.querySelector('[data-testid="sidebar-page-tree-shell-rust-iframe"]');
|
||||
|
||||
expect(surface?.getAttribute("data-renderer-family")).toBe("rust_family");
|
||||
expect(surface?.getAttribute("data-tree-host-kind")).toBe("rust_family");
|
||||
expect(surface?.getAttribute("data-tree-host-implementation")).toBe("mnote_web_iframe_proxy");
|
||||
expect(rustHost).not.toBeNull();
|
||||
expect(iframe).not.toBeNull();
|
||||
expect(container.querySelector('[data-testid="private-tree-fallback"]')).toBeNull();
|
||||
});
|
||||
|
||||
it("page tree 在禁用 tree shell 时应安全回退到 React fallback", () => {
|
||||
act(() => {
|
||||
root.render(
|
||||
<SidebarTreeSurface
|
||||
mode="page"
|
||||
rendererFamily="rust_family"
|
||||
workspaceId="ws_1"
|
||||
treeShellEnabled={false}
|
||||
rows={[]}
|
||||
expanded={new Set<string>()}
|
||||
activeId=""
|
||||
onToggleExpand={() => undefined}
|
||||
onMove={() => undefined}
|
||||
onCreateChild={() => undefined}
|
||||
onContextMenu={() => undefined}
|
||||
/>,
|
||||
);
|
||||
});
|
||||
|
||||
const surface = container.querySelector('[data-testid="sidebar-page-tree-shell"]');
|
||||
expect(surface?.getAttribute("data-tree-host-implementation")).toBe("react_fallback");
|
||||
expect(container.querySelector('[data-testid="private-tree-fallback"]')).not.toBeNull();
|
||||
});
|
||||
|
||||
it("file tree surface 在 rust_family 下也应走同一 host 选择契约", () => {
|
||||
act(() => {
|
||||
root.render(
|
||||
<SidebarTreeSurface
|
||||
mode="filetree"
|
||||
rendererFamily="rust_family"
|
||||
workspaceId="ws_1"
|
||||
treeShellEnabled
|
||||
rows={[]}
|
||||
activeId=""
|
||||
selectedRowIds={new Set<string>()}
|
||||
onRowClick={() => undefined}
|
||||
onRowDoubleClick={() => undefined}
|
||||
onRowContextMenu={() => undefined}
|
||||
onToggleExpand={() => undefined}
|
||||
onCreateChild={() => undefined}
|
||||
/>,
|
||||
);
|
||||
});
|
||||
|
||||
const surface = container.querySelector('[data-testid="sidebar-file-tree-shell"]');
|
||||
const rustHost = container.querySelector(
|
||||
'[data-testid="sidebar-file-tree-shell-rust-host"]',
|
||||
);
|
||||
const iframe = container.querySelector('[data-testid="sidebar-file-tree-shell-rust-iframe"]');
|
||||
|
||||
expect(surface?.getAttribute("data-renderer-family")).toBe("rust_family");
|
||||
expect(surface?.getAttribute("data-tree-host-kind")).toBe("rust_family");
|
||||
expect(surface?.getAttribute("data-tree-host-implementation")).toBe("mnote_web_iframe_proxy");
|
||||
expect(rustHost).not.toBeNull();
|
||||
expect(iframe).not.toBeNull();
|
||||
expect(container.querySelector('[data-testid="file-tree-fallback"]')).toBeNull();
|
||||
});
|
||||
|
||||
it("file tree surface 应把 iframe 内部拖放与外部文件拖放桥接回宿主回调", async () => {
|
||||
const onInternalDrop = vi.fn();
|
||||
const onDropFiles = vi.fn();
|
||||
const targetRow = {
|
||||
kind: "doc",
|
||||
rowId: "doc:doc_target",
|
||||
depth: 0,
|
||||
docId: "doc_target",
|
||||
parentDocId: null,
|
||||
node: {
|
||||
_id: "doc_target",
|
||||
id: "doc_target",
|
||||
title: "目标页面",
|
||||
},
|
||||
hasChildren: false,
|
||||
isExpanded: false,
|
||||
};
|
||||
const droppedFile = new File(["bridge"], "bridge.txt", { type: "text/plain" });
|
||||
|
||||
await act(async () => {
|
||||
root.render(
|
||||
<SidebarTreeSurface
|
||||
mode="filetree"
|
||||
rendererFamily="rust_family"
|
||||
workspaceId="ws_1"
|
||||
treeShellEnabled
|
||||
rows={[targetRow]}
|
||||
activeId=""
|
||||
selectedRowIds={new Set<string>()}
|
||||
onRowClick={() => undefined}
|
||||
onRowDoubleClick={() => undefined}
|
||||
onRowContextMenu={() => undefined}
|
||||
onToggleExpand={() => undefined}
|
||||
onCreateChild={() => undefined}
|
||||
onInternalDrop={onInternalDrop}
|
||||
onDropFiles={onDropFiles}
|
||||
/>,
|
||||
);
|
||||
});
|
||||
|
||||
const iframe = container.querySelector(
|
||||
'[data-testid="sidebar-file-tree-shell-rust-iframe"]',
|
||||
);
|
||||
expect(iframe).not.toBeNull();
|
||||
Object.defineProperty(iframe, "contentWindow", {
|
||||
configurable: true,
|
||||
value: window,
|
||||
});
|
||||
|
||||
await act(async () => {
|
||||
window.dispatchEvent(
|
||||
new MessageEvent("message", {
|
||||
data: {
|
||||
channel: "sidebar-file-tree-shell",
|
||||
type: "tree.filetree.internal-drop",
|
||||
rowIds: ["doc:doc_source"],
|
||||
copy: false,
|
||||
targetRow,
|
||||
},
|
||||
source: window,
|
||||
}),
|
||||
);
|
||||
window.dispatchEvent(
|
||||
new MessageEvent("message", {
|
||||
data: {
|
||||
channel: "sidebar-file-tree-shell",
|
||||
type: "tree.filetree.external-drop",
|
||||
documentId: "doc_target",
|
||||
targetRow,
|
||||
files: [droppedFile],
|
||||
},
|
||||
source: window,
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
expect(onInternalDrop).toHaveBeenCalledWith({
|
||||
targetRow,
|
||||
rowIds: ["doc:doc_source"],
|
||||
copy: false,
|
||||
});
|
||||
expect(onDropFiles).toHaveBeenCalledWith("doc_target", [droppedFile], targetRow);
|
||||
});
|
||||
|
||||
it("picker surface 在 rust_family 下也应挂到同一 host 边界", async () => {
|
||||
const onPick = vi.fn();
|
||||
|
||||
await act(async () => {
|
||||
root.render(
|
||||
<TreePickerSurface
|
||||
rendererFamily="rust_family"
|
||||
workspaceId="ws_1"
|
||||
treeShellEnabled
|
||||
items={[{ kind: "doc", id: "doc_1", title: "页面 1", depth: 0 }]}
|
||||
highlighted={0}
|
||||
onHighlight={() => undefined}
|
||||
onPick={onPick}
|
||||
/>,
|
||||
);
|
||||
});
|
||||
|
||||
const surface = container.querySelector('[data-testid="tree-picker-surface"]');
|
||||
const rustHost = container.querySelector('[data-testid="tree-picker-surface-rust-host"]');
|
||||
const iframe = container.querySelector('[data-testid="tree-picker-surface-rust-iframe"]');
|
||||
|
||||
expect(surface?.getAttribute("data-renderer-family")).toBe("rust_family");
|
||||
expect(surface?.getAttribute("data-tree-host-kind")).toBe("rust_family");
|
||||
expect(surface?.getAttribute("data-tree-host-implementation")).toBe("mnote_web_iframe_proxy");
|
||||
expect(rustHost).not.toBeNull();
|
||||
expect(iframe).not.toBeNull();
|
||||
expect(onPick).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("picker 在 rust_family 但 tree shell 不可用时仍应保留 React fallback", () => {
|
||||
act(() => {
|
||||
root.render(
|
||||
<TreePickerSurface
|
||||
rendererFamily="rust_family"
|
||||
workspaceId="ws_1"
|
||||
treeShellEnabled={false}
|
||||
items={[{ kind: "doc", id: "doc_1", title: "页面 1", depth: 0 }]}
|
||||
highlighted={0}
|
||||
emptyText="没有匹配结果"
|
||||
onHighlight={() => undefined}
|
||||
onPick={vi.fn()}
|
||||
/>,
|
||||
);
|
||||
});
|
||||
|
||||
const surface = container.querySelector('[data-testid="tree-picker-surface"]');
|
||||
const rustHost = container.querySelector('[data-testid="tree-picker-surface-rust-host"]');
|
||||
const row = container.querySelector('[data-testid="tree-picker-row"]');
|
||||
|
||||
expect(surface?.getAttribute("data-tree-host-implementation")).toBe("react_fallback");
|
||||
expect(surface?.getAttribute("data-tree-host-kind")).toBe("rust_family");
|
||||
expect(rustHost).not.toBeNull();
|
||||
expect(row).not.toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -3,13 +3,19 @@
|
||||
import type { DragEvent, MouseEvent } from "react";
|
||||
import { FileTree } from "@/components/sidebar/file-tree";
|
||||
import { PrivateTree } from "@/components/sidebar/private-tree";
|
||||
import { TreeShellHost, type TreeRendererFamily } from "@/components/sidebar/tree-shell-host";
|
||||
import type { SidebarTreeNode } from "@/lib/kernel-sidebar";
|
||||
import type { FileTreeRow } from "@/lib/file-tree/types";
|
||||
import type { PageTreeProjectionItem } from "@/lib/tree-projection";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
export type { TreeRendererFamily } from "@/components/sidebar/tree-shell-host";
|
||||
|
||||
type SidebarPageTreeSurfaceProps = {
|
||||
mode: "page";
|
||||
rendererFamily?: TreeRendererFamily;
|
||||
workspaceId: string | null;
|
||||
treeShellEnabled?: boolean;
|
||||
rows: PageTreeProjectionItem[];
|
||||
expanded: Set<string>;
|
||||
activeId: string;
|
||||
@@ -18,10 +24,16 @@ type SidebarPageTreeSurfaceProps = {
|
||||
onMove: (nodeId: string, parentId: string | null, index: number) => void;
|
||||
onCreateChild: (parentId: string | null) => void;
|
||||
onContextMenu: (event: MouseEvent, node: SidebarTreeNode) => void;
|
||||
onNavigate?: (documentId: string) => void;
|
||||
onPageContextMenu?: (payload: { documentId: string; x: number; y: number }) => void;
|
||||
onTreeMutation?: (payload: { type: string; documentId: string | null }) => void;
|
||||
};
|
||||
|
||||
type SidebarFileTreeSurfaceProps = {
|
||||
mode: "filetree";
|
||||
rendererFamily?: TreeRendererFamily;
|
||||
workspaceId: string | null;
|
||||
treeShellEnabled?: boolean;
|
||||
rows: FileTreeRow[];
|
||||
activeId: string;
|
||||
selectedRowIds: Set<string>;
|
||||
@@ -34,8 +46,24 @@ type SidebarFileTreeSurfaceProps = {
|
||||
onToggleAssetFolderExpand?: (assetId: string) => void;
|
||||
onCreateChild: (parentId: string | null) => void;
|
||||
onBlankMouseDown?: (event: MouseEvent) => void;
|
||||
onDropFiles?: (docId: string, files: FileList, targetRow?: FileTreeRow) => void;
|
||||
onDropFiles?: (docId: string, files: FileList | File[], targetRow?: FileTreeRow) => void;
|
||||
onInternalDrop?: (args: { targetRow: FileTreeRow; rowIds: string[]; copy: boolean }) => void;
|
||||
onNavigate?: (documentId: string) => void;
|
||||
onFileTreeContextMenu?: (payload: {
|
||||
documentId: string | null;
|
||||
assetId: string | null;
|
||||
rowId: string | null;
|
||||
rowKind: string | null;
|
||||
x: number;
|
||||
y: number;
|
||||
}) => void;
|
||||
onFileTreeSelectionChange?: (payload: {
|
||||
selectedRowIds: string[];
|
||||
anchorRowId: string | null;
|
||||
focusedRowId: string | null;
|
||||
}) => void;
|
||||
onAssetOpen?: (payload: { assetId: string; documentId: string | null }) => void;
|
||||
onTreeMutation?: (payload: { type: string; documentId: string | null }) => void;
|
||||
};
|
||||
|
||||
export type SidebarTreeSurfaceProps =
|
||||
@@ -47,6 +75,13 @@ export type TreePickerSurfaceItem =
|
||||
| { kind: "doc"; id: string; title: string; subtitle?: string; depth?: number };
|
||||
|
||||
type TreePickerSurfaceProps = {
|
||||
rendererFamily?: TreeRendererFamily;
|
||||
workspaceId: string | null;
|
||||
treeShellEnabled?: boolean;
|
||||
activeDocumentId?: string | null;
|
||||
allowRootPick?: boolean;
|
||||
excludeIds?: string[];
|
||||
treeShellItems?: TreePickerSurfaceItem[];
|
||||
items: TreePickerSurfaceItem[];
|
||||
highlighted: number;
|
||||
className?: string;
|
||||
@@ -60,48 +95,71 @@ export function SidebarTreeSurface(props: SidebarTreeSurfaceProps) {
|
||||
props.mode === "page"
|
||||
? "sidebar-page-tree-shell"
|
||||
: "sidebar-file-tree-shell";
|
||||
const rendererFamily = props.rendererFamily ?? "react";
|
||||
const fallbackContent =
|
||||
props.mode === "page" ? (
|
||||
<PrivateTree
|
||||
rows={props.rows}
|
||||
expanded={props.expanded}
|
||||
activeId={props.activeId}
|
||||
onToggleExpand={props.onToggleExpand}
|
||||
onMove={props.onMove}
|
||||
onCreateChild={props.onCreateChild}
|
||||
onContextMenu={props.onContextMenu}
|
||||
/>
|
||||
) : (
|
||||
<FileTree
|
||||
rows={props.rows}
|
||||
activeId={props.activeId}
|
||||
selectedRowIds={props.selectedRowIds}
|
||||
onRowClick={props.onRowClick}
|
||||
onRowDoubleClick={props.onRowDoubleClick}
|
||||
onRowContextMenu={props.onRowContextMenu}
|
||||
onRowDragStart={props.onRowDragStart}
|
||||
onToggleExpand={props.onToggleExpand}
|
||||
onToggleAssetFolderExpand={props.onToggleAssetFolderExpand}
|
||||
onCreateChild={props.onCreateChild}
|
||||
onBlankMouseDown={props.onBlankMouseDown}
|
||||
onDropFiles={props.onDropFiles}
|
||||
onInternalDrop={props.onInternalDrop}
|
||||
/>
|
||||
);
|
||||
|
||||
return (
|
||||
<div
|
||||
data-testid={surfaceTestId}
|
||||
data-shell-mode={props.mode}
|
||||
<TreeShellHost
|
||||
mode={props.mode}
|
||||
surfaceTestId={surfaceTestId}
|
||||
rendererFamily={rendererFamily}
|
||||
treeShellEnabled={props.treeShellEnabled}
|
||||
workspaceId={props.workspaceId}
|
||||
activeDocumentId={props.activeId}
|
||||
fileTreeRows={props.mode === "filetree" ? props.rows : undefined}
|
||||
onNavigate={props.onNavigate}
|
||||
onPageContextMenu={props.mode === "page" ? props.onPageContextMenu : undefined}
|
||||
onFileTreeContextMenu={props.mode === "filetree" ? props.onFileTreeContextMenu : undefined}
|
||||
onFileTreeSelectionChange={props.mode === "filetree" ? props.onFileTreeSelectionChange : undefined}
|
||||
onInternalDrop={props.mode === "filetree" ? props.onInternalDrop : undefined}
|
||||
onDropFiles={props.mode === "filetree" ? props.onDropFiles : undefined}
|
||||
onAssetOpen={props.mode === "filetree" ? props.onAssetOpen : undefined}
|
||||
onTreeMutation={props.onTreeMutation}
|
||||
className={cn(
|
||||
"h-full w-full min-w-0 overflow-x-hidden rounded-md border border-[#eff2f6] bg-white",
|
||||
props.className,
|
||||
)}
|
||||
>
|
||||
{props.mode === "page" ? (
|
||||
<PrivateTree
|
||||
rows={props.rows}
|
||||
expanded={props.expanded}
|
||||
activeId={props.activeId}
|
||||
onToggleExpand={props.onToggleExpand}
|
||||
onMove={props.onMove}
|
||||
onCreateChild={props.onCreateChild}
|
||||
onContextMenu={props.onContextMenu}
|
||||
/>
|
||||
) : (
|
||||
<FileTree
|
||||
rows={props.rows}
|
||||
activeId={props.activeId}
|
||||
selectedRowIds={props.selectedRowIds}
|
||||
onRowClick={props.onRowClick}
|
||||
onRowDoubleClick={props.onRowDoubleClick}
|
||||
onRowContextMenu={props.onRowContextMenu}
|
||||
onRowDragStart={props.onRowDragStart}
|
||||
onToggleExpand={props.onToggleExpand}
|
||||
onToggleAssetFolderExpand={props.onToggleAssetFolderExpand}
|
||||
onCreateChild={props.onCreateChild}
|
||||
onBlankMouseDown={props.onBlankMouseDown}
|
||||
onDropFiles={props.onDropFiles}
|
||||
onInternalDrop={props.onInternalDrop}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
{fallbackContent}
|
||||
</TreeShellHost>
|
||||
);
|
||||
}
|
||||
|
||||
export function TreePickerSurface({
|
||||
rendererFamily = "react",
|
||||
workspaceId,
|
||||
treeShellEnabled = true,
|
||||
activeDocumentId = null,
|
||||
allowRootPick = false,
|
||||
excludeIds = [],
|
||||
treeShellItems,
|
||||
items,
|
||||
highlighted,
|
||||
className,
|
||||
@@ -109,42 +167,53 @@ export function TreePickerSurface({
|
||||
onHighlight,
|
||||
onPick,
|
||||
}: TreePickerSurfaceProps) {
|
||||
if (items.length === 0) {
|
||||
return <div className="p-4 text-sm text-gray-400">{emptyText}</div>;
|
||||
}
|
||||
const hasItems = items.length > 0;
|
||||
|
||||
return (
|
||||
<div
|
||||
data-testid="tree-picker-surface"
|
||||
className={cn("py-2", className)}
|
||||
<TreeShellHost
|
||||
mode="picker"
|
||||
surfaceTestId="tree-picker-surface"
|
||||
rendererFamily={rendererFamily}
|
||||
treeShellEnabled={treeShellEnabled}
|
||||
workspaceId={workspaceId}
|
||||
activeDocumentId={activeDocumentId}
|
||||
allowRootPick={allowRootPick}
|
||||
excludeIds={excludeIds}
|
||||
pickerItems={treeShellItems}
|
||||
onPick={onPick}
|
||||
className={cn(hasItems ? "py-2" : null, className)}
|
||||
>
|
||||
{items.map((item, index) => {
|
||||
const isRoot = item.kind === "root";
|
||||
return (
|
||||
<button
|
||||
key={isRoot ? "root" : item.id}
|
||||
data-testid={isRoot ? "tree-picker-root" : "tree-picker-row"}
|
||||
data-node-id={isRoot ? "" : item.id}
|
||||
type="button"
|
||||
className={cn(
|
||||
"w-full px-4 py-3 text-left transition-colors hover:bg-[#eef2ff]",
|
||||
index === highlighted && "bg-[#e3ecff]",
|
||||
)}
|
||||
onMouseEnter={() => onHighlight(index)}
|
||||
onClick={() => onPick(item.id)}
|
||||
>
|
||||
<div
|
||||
className="text-sm font-medium text-gray-900"
|
||||
style={!isRoot ? { paddingLeft: 12 * (item.depth ?? 0) } : undefined}
|
||||
{!hasItems ? (
|
||||
<div className="p-4 text-sm text-gray-400">{emptyText}</div>
|
||||
) : (
|
||||
items.map((item, index) => {
|
||||
const isRoot = item.kind === "root";
|
||||
return (
|
||||
<button
|
||||
key={isRoot ? "root" : item.id}
|
||||
data-testid={isRoot ? "tree-picker-root" : "tree-picker-row"}
|
||||
data-node-id={isRoot ? "" : item.id}
|
||||
type="button"
|
||||
className={cn(
|
||||
"w-full px-4 py-3 text-left transition-colors hover:bg-[#eef2ff]",
|
||||
index === highlighted && "bg-[#e3ecff]",
|
||||
)}
|
||||
onMouseEnter={() => onHighlight(index)}
|
||||
onClick={() => onPick(item.id)}
|
||||
>
|
||||
{item.title}
|
||||
</div>
|
||||
{item.subtitle ? (
|
||||
<div className="mt-1 text-xs text-gray-500">{item.subtitle}</div>
|
||||
) : null}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
<div
|
||||
className="text-sm font-medium text-gray-900"
|
||||
style={!isRoot ? { paddingLeft: 12 * (item.depth ?? 0) } : undefined}
|
||||
>
|
||||
{item.title}
|
||||
</div>
|
||||
{item.subtitle ? (
|
||||
<div className="mt-1 text-xs text-gray-500">{item.subtitle}</div>
|
||||
) : null}
|
||||
</button>
|
||||
);
|
||||
})
|
||||
)}
|
||||
</TreeShellHost>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { DocumentRecord } from "@/lib/documents";
|
||||
import type { KernelFileTreeProjection } from "@/lib/kernel-file-tree";
|
||||
import type { WorkspaceSummary } from "@/lib/workspaces";
|
||||
import type { MediaAsset } from "@/types/media";
|
||||
import type { KernelSidebarProjection, SidebarTreeNode } from "@/lib/kernel-sidebar";
|
||||
@@ -19,6 +20,7 @@ export interface SidebarInitialData {
|
||||
documents: DocumentRecord[];
|
||||
kernelSidebarProjection: KernelSidebarProjection;
|
||||
kernelSidebarTree: SidebarTreeNode[];
|
||||
kernelFileTreeProjection: KernelFileTreeProjection;
|
||||
trashedDocuments: TrashRecord[];
|
||||
trashedMediaAssets?: MediaAsset[];
|
||||
trashedMindmapAssets?: MediaAsset[];
|
||||
|
||||
@@ -39,6 +39,7 @@ function Harness(props: {
|
||||
initialData: SidebarInitialData;
|
||||
sidebarQueryData: SidebarInitialData;
|
||||
treeStreamData: SidebarInitialData | null;
|
||||
treeStreamStatus?: "idle" | "connecting" | "live" | "fallback";
|
||||
onState: (state: ReturnType<typeof usePreferredSidebarSnapshot>) => void;
|
||||
}) {
|
||||
const state = usePreferredSidebarSnapshot(props);
|
||||
@@ -71,7 +72,55 @@ describe("usePreferredSidebarSnapshot", () => {
|
||||
container.remove();
|
||||
});
|
||||
|
||||
it("tree stream 落后于 query refetch 时应优先使用更新后的 query 快照", async () => {
|
||||
it("tree stream live 时即使 query 更新也应继续优先使用 stream 快照", async () => {
|
||||
const initialData = buildSidebarData([buildDocument({ title: "标题 A" })]);
|
||||
const staleTreeStream = buildSidebarData([buildDocument({ title: "标题 A" })]);
|
||||
const refreshedQuery = buildSidebarData([
|
||||
buildDocument({
|
||||
title: "标题 B",
|
||||
updated_at: "2026-04-21T00:00:01.000Z",
|
||||
}),
|
||||
]);
|
||||
await act(async () => {
|
||||
root.render(
|
||||
<Harness
|
||||
initialData={initialData}
|
||||
sidebarQueryData={initialData}
|
||||
treeStreamData={staleTreeStream}
|
||||
treeStreamStatus="live"
|
||||
onState={onState}
|
||||
/>,
|
||||
);
|
||||
});
|
||||
|
||||
expect(onState.mock.lastCall?.[0]).toMatchObject({
|
||||
source: "tree_stream",
|
||||
data: expect.objectContaining({
|
||||
kernelSidebarTree: [expect.objectContaining({ title: "标题 A" })],
|
||||
}),
|
||||
});
|
||||
|
||||
await act(async () => {
|
||||
root.render(
|
||||
<Harness
|
||||
initialData={initialData}
|
||||
sidebarQueryData={refreshedQuery}
|
||||
treeStreamData={staleTreeStream}
|
||||
treeStreamStatus="live"
|
||||
onState={onState}
|
||||
/>,
|
||||
);
|
||||
});
|
||||
|
||||
expect(onState.mock.lastCall?.[0]).toMatchObject({
|
||||
source: "tree_stream",
|
||||
data: expect.objectContaining({
|
||||
kernelSidebarTree: [expect.objectContaining({ title: "标题 A" })],
|
||||
}),
|
||||
});
|
||||
});
|
||||
|
||||
it("tree stream 进入 fallback 后应回退到 query 快照", async () => {
|
||||
const initialData = buildSidebarData([buildDocument({ title: "标题 A" })]);
|
||||
const staleTreeStream = buildSidebarData([buildDocument({ title: "标题 A" })]);
|
||||
const refreshedQuery = buildSidebarData([
|
||||
@@ -87,30 +136,13 @@ describe("usePreferredSidebarSnapshot", () => {
|
||||
}),
|
||||
]);
|
||||
|
||||
await act(async () => {
|
||||
root.render(
|
||||
<Harness
|
||||
initialData={initialData}
|
||||
sidebarQueryData={initialData}
|
||||
treeStreamData={staleTreeStream}
|
||||
onState={onState}
|
||||
/>,
|
||||
);
|
||||
});
|
||||
|
||||
expect(onState.mock.lastCall?.[0]).toMatchObject({
|
||||
source: "tree_stream",
|
||||
data: expect.objectContaining({
|
||||
kernelSidebarTree: [expect.objectContaining({ title: "标题 A" })],
|
||||
}),
|
||||
});
|
||||
|
||||
await act(async () => {
|
||||
root.render(
|
||||
<Harness
|
||||
initialData={initialData}
|
||||
sidebarQueryData={refreshedQuery}
|
||||
treeStreamData={staleTreeStream}
|
||||
treeStreamStatus="fallback"
|
||||
onState={onState}
|
||||
/>,
|
||||
);
|
||||
@@ -129,6 +161,7 @@ describe("usePreferredSidebarSnapshot", () => {
|
||||
initialData={initialData}
|
||||
sidebarQueryData={refreshedQuery}
|
||||
treeStreamData={caughtUpTreeStream}
|
||||
treeStreamStatus="live"
|
||||
onState={onState}
|
||||
/>,
|
||||
);
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
import { useMemo } from "react";
|
||||
import type { SidebarInitialData } from "@/components/sidebar/types";
|
||||
import {
|
||||
buildSidebarDataSyncKey,
|
||||
getSidebarDataFreshness,
|
||||
} from "@/components/sidebar/sidebar-sync";
|
||||
import { buildSidebarDataSyncKey } from "@/components/sidebar/sidebar-sync";
|
||||
|
||||
export type PreferredSidebarSnapshotSource = "initial" | "query" | "tree_stream";
|
||||
|
||||
@@ -11,6 +8,7 @@ export function usePreferredSidebarSnapshot(input: {
|
||||
initialData: SidebarInitialData;
|
||||
sidebarQueryData: SidebarInitialData | null;
|
||||
treeStreamData: SidebarInitialData | null;
|
||||
treeStreamStatus?: "idle" | "connecting" | "live" | "fallback";
|
||||
}) {
|
||||
const querySyncKey = useMemo(
|
||||
() => (input.sidebarQueryData ? buildSidebarDataSyncKey(input.sidebarQueryData) : null),
|
||||
@@ -21,23 +19,10 @@ export function usePreferredSidebarSnapshot(input: {
|
||||
[input.treeStreamData],
|
||||
);
|
||||
const initialSyncKey = useMemo(() => buildSidebarDataSyncKey(input.initialData), [input.initialData]);
|
||||
const queryFreshness = useMemo(
|
||||
() => (input.sidebarQueryData ? getSidebarDataFreshness(input.sidebarQueryData) : Number.NEGATIVE_INFINITY),
|
||||
[input.sidebarQueryData],
|
||||
);
|
||||
const treeStreamFreshness = useMemo(
|
||||
() => (input.treeStreamData ? getSidebarDataFreshness(input.treeStreamData) : Number.NEGATIVE_INFINITY),
|
||||
[input.treeStreamData],
|
||||
);
|
||||
const streamIsPreferred = input.treeStreamStatus !== "fallback";
|
||||
|
||||
const source = useMemo<PreferredSidebarSnapshotSource>(() => {
|
||||
if (input.treeStreamData && input.sidebarQueryData) {
|
||||
if (treeStreamSyncKey === querySyncKey) {
|
||||
return "tree_stream";
|
||||
}
|
||||
return queryFreshness > treeStreamFreshness ? "query" : "tree_stream";
|
||||
}
|
||||
if (input.treeStreamData) {
|
||||
if (input.treeStreamData && streamIsPreferred) {
|
||||
return "tree_stream";
|
||||
}
|
||||
if (input.sidebarQueryData) {
|
||||
@@ -47,10 +32,7 @@ export function usePreferredSidebarSnapshot(input: {
|
||||
}, [
|
||||
input.sidebarQueryData,
|
||||
input.treeStreamData,
|
||||
queryFreshness,
|
||||
querySyncKey,
|
||||
treeStreamFreshness,
|
||||
treeStreamSyncKey,
|
||||
streamIsPreferred,
|
||||
]);
|
||||
|
||||
const data =
|
||||
@@ -61,7 +43,7 @@ export function usePreferredSidebarSnapshot(input: {
|
||||
: input.treeStreamData ?? input.sidebarQueryData ?? input.initialData;
|
||||
const syncKey =
|
||||
source === "tree_stream"
|
||||
? treeStreamSyncKey ?? initialSyncKey
|
||||
? treeStreamSyncKey ?? querySyncKey ?? initialSyncKey
|
||||
: source === "query"
|
||||
? querySyncKey ?? initialSyncKey
|
||||
: initialSyncKey;
|
||||
|
||||
@@ -3,6 +3,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { createRoot, type Root } from "react-dom/client";
|
||||
import { useSidebarData } from "./use-sidebar-data";
|
||||
import type { SidebarInitialData } from "@/components/sidebar/types";
|
||||
import { buildKernelFileTreeProjection } from "@/lib/kernel-file-tree";
|
||||
|
||||
const mockUseConvexSidebarData = vi.fn();
|
||||
const mockUseQuery = vi.fn();
|
||||
@@ -16,10 +17,18 @@ vi.mock("@tanstack/react-query", () => ({
|
||||
}));
|
||||
|
||||
function buildInitialData(): SidebarInitialData {
|
||||
const kernelFileTreeProjection = buildKernelFileTreeProjection({
|
||||
documents: [],
|
||||
mediaAssets: [],
|
||||
mindmapAssets: [],
|
||||
tableAssets: [],
|
||||
mindmapAssetChildren: {},
|
||||
});
|
||||
return {
|
||||
activeWorkspaceId: "ws_1",
|
||||
workspaces: [],
|
||||
documents: [],
|
||||
kernelFileTreeProjection,
|
||||
kernelSidebarProjection: {
|
||||
projectionId: "kernel_projection:sidebar_tree:workspace_root",
|
||||
projection: "sidebar_tree",
|
||||
@@ -169,4 +178,104 @@ describe("useSidebarData", () => {
|
||||
const refreshedState = onState.mock.lastCall?.[0] as ReturnType<typeof useSidebarData>;
|
||||
expect(refreshedState.data.documents[0]?.title).toBe("新标题");
|
||||
});
|
||||
|
||||
it("手动 refetch 只应临时覆盖主链,底层 live 数据变化后应回到新的 live snapshot", async () => {
|
||||
const initialData = buildInitialData();
|
||||
const manualSnapshot: SidebarInitialData = {
|
||||
...buildInitialData(),
|
||||
documents: [
|
||||
{
|
||||
access_scope: "private",
|
||||
id: "doc-1",
|
||||
workspace_id: "ws_1",
|
||||
title: "HTTP 标题",
|
||||
parent_id: null,
|
||||
sort_order: 0,
|
||||
is_starred: false,
|
||||
is_template: false,
|
||||
created_at: "2026-04-21T00:00:00.000Z",
|
||||
updated_at: "2026-04-21T00:00:02.000Z",
|
||||
},
|
||||
],
|
||||
kernelSidebarTree: [
|
||||
{
|
||||
id: "doc-1",
|
||||
workspace_id: "ws_1",
|
||||
title: "HTTP 标题",
|
||||
parent_id: null,
|
||||
sort_order: 0,
|
||||
access_scope: "private",
|
||||
is_starred: false,
|
||||
is_template: false,
|
||||
created_at: "2026-04-21T00:00:00.000Z",
|
||||
updated_at: "2026-04-21T00:00:02.000Z",
|
||||
children: [],
|
||||
},
|
||||
],
|
||||
};
|
||||
const nextLiveData: SidebarInitialData = {
|
||||
...buildInitialData(),
|
||||
documents: [
|
||||
{
|
||||
access_scope: "private",
|
||||
id: "doc-1",
|
||||
workspace_id: "ws_1",
|
||||
title: "Live 标题",
|
||||
parent_id: null,
|
||||
sort_order: 0,
|
||||
is_starred: false,
|
||||
is_template: false,
|
||||
created_at: "2026-04-21T00:00:00.000Z",
|
||||
updated_at: "2026-04-21T00:00:00.000Z",
|
||||
},
|
||||
],
|
||||
kernelSidebarTree: [
|
||||
{
|
||||
id: "doc-1",
|
||||
workspace_id: "ws_1",
|
||||
title: "Live 标题",
|
||||
parent_id: null,
|
||||
sort_order: 0,
|
||||
access_scope: "private",
|
||||
is_starred: false,
|
||||
is_template: false,
|
||||
created_at: "2026-04-21T00:00:00.000Z",
|
||||
updated_at: "2026-04-21T00:00:00.000Z",
|
||||
children: [],
|
||||
},
|
||||
],
|
||||
};
|
||||
let liveData = initialData;
|
||||
mockUseConvexSidebarData.mockImplementation(() => ({
|
||||
data: liveData,
|
||||
isLoading: false,
|
||||
isAuthLoading: false,
|
||||
isAuthenticated: true,
|
||||
hasLiveSubscription: true,
|
||||
canUseHttpFallback: false,
|
||||
error: null,
|
||||
refetch: stableRefetch,
|
||||
}));
|
||||
(global.fetch as unknown as ReturnType<typeof vi.fn>).mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => manualSnapshot,
|
||||
});
|
||||
|
||||
await act(async () => {
|
||||
root.render(<Harness initialData={initialData} onState={onState} />);
|
||||
});
|
||||
|
||||
const state = onState.mock.lastCall?.[0] as ReturnType<typeof useSidebarData>;
|
||||
await act(async () => {
|
||||
await state.refetch();
|
||||
});
|
||||
expect((onState.mock.lastCall?.[0] as ReturnType<typeof useSidebarData>).data.documents[0]?.title).toBe("HTTP 标题");
|
||||
|
||||
liveData = nextLiveData;
|
||||
await act(async () => {
|
||||
root.render(<Harness initialData={initialData} onState={onState} />);
|
||||
});
|
||||
|
||||
expect((onState.mock.lastCall?.[0] as ReturnType<typeof useSidebarData>).data.documents[0]?.title).toBe("Live 标题");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import {
|
||||
buildSidebarDataSyncKey,
|
||||
getSidebarDataFreshness,
|
||||
} from "@/components/sidebar/sidebar-sync";
|
||||
import { buildSidebarDataSyncKey } from "@/components/sidebar/sidebar-sync";
|
||||
import type { SidebarInitialData } from "@/components/sidebar/types";
|
||||
import { useConvexSidebarData } from "@/hooks/use-convex-sidebar-data";
|
||||
|
||||
@@ -56,9 +53,11 @@ export function useSidebarData(initialData: SidebarInitialData): SidebarDataResu
|
||||
const [manualSnapshotState, setManualSnapshotState] = useState<{
|
||||
workspaceId: string;
|
||||
data: SidebarInitialData | null;
|
||||
baseSyncKey: string | null;
|
||||
}>({
|
||||
workspaceId,
|
||||
data: null,
|
||||
baseSyncKey: null,
|
||||
});
|
||||
|
||||
const httpQuery = useQuery({
|
||||
@@ -73,40 +72,37 @@ export function useSidebarData(initialData: SidebarInitialData): SidebarDataResu
|
||||
manualSnapshotState.workspaceId === workspaceId
|
||||
? manualSnapshotState.data
|
||||
: null;
|
||||
const manualSnapshotBaseSyncKey =
|
||||
manualSnapshotState.workspaceId === workspaceId
|
||||
? manualSnapshotState.baseSyncKey
|
||||
: null;
|
||||
|
||||
const baseLiveData = convexSidebar.data ?? httpQuery.data ?? initialData;
|
||||
const baseLiveDataSyncKey = useMemo(
|
||||
() => buildSidebarDataSyncKey(baseLiveData),
|
||||
[baseLiveData],
|
||||
);
|
||||
const baseLiveDataFreshness = useMemo(
|
||||
() => getSidebarDataFreshness(baseLiveData),
|
||||
[baseLiveData],
|
||||
);
|
||||
const manualSnapshotSyncKey = useMemo(
|
||||
() => (manualSnapshot ? buildSidebarDataSyncKey(manualSnapshot) : null),
|
||||
[manualSnapshot],
|
||||
);
|
||||
const manualSnapshotFreshness = useMemo(
|
||||
() => (manualSnapshot ? getSidebarDataFreshness(manualSnapshot) : Number.NEGATIVE_INFINITY),
|
||||
[manualSnapshot],
|
||||
);
|
||||
const liveData = useMemo(() => {
|
||||
if (!manualSnapshot) {
|
||||
return baseLiveData;
|
||||
}
|
||||
if (manualSnapshotSyncKey === baseLiveDataSyncKey) {
|
||||
return baseLiveData;
|
||||
if (
|
||||
manualSnapshotBaseSyncKey === baseLiveDataSyncKey &&
|
||||
manualSnapshotSyncKey &&
|
||||
manualSnapshotSyncKey !== baseLiveDataSyncKey
|
||||
) {
|
||||
return manualSnapshot;
|
||||
}
|
||||
return manualSnapshotFreshness >= baseLiveDataFreshness
|
||||
? manualSnapshot
|
||||
: baseLiveData;
|
||||
return baseLiveData;
|
||||
}, [
|
||||
baseLiveData,
|
||||
baseLiveDataFreshness,
|
||||
baseLiveDataSyncKey,
|
||||
manualSnapshot,
|
||||
manualSnapshotFreshness,
|
||||
manualSnapshotBaseSyncKey,
|
||||
manualSnapshotSyncKey,
|
||||
]);
|
||||
const isLoading =
|
||||
@@ -145,6 +141,7 @@ export function useSidebarData(initialData: SidebarInitialData): SidebarDataResu
|
||||
setManualSnapshotState({
|
||||
workspaceId,
|
||||
data: refreshedSnapshot,
|
||||
baseSyncKey: buildSidebarDataSyncKey(liveDataRef.current),
|
||||
});
|
||||
return refreshedSnapshot;
|
||||
} catch {
|
||||
|
||||
@@ -20,7 +20,7 @@ describe("tree-command-client", () => {
|
||||
it("通过统一 client 发送 tree/document command 并返回结果", async () => {
|
||||
const fetchMock = vi.spyOn(globalThis, "fetch").mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({ ok: true, success: true, items: [] }),
|
||||
json: async () => ({ ok: true, success: true, items: [], id: "doc_created", documentId: "doc_created" }),
|
||||
} as Response);
|
||||
|
||||
await createDocumentCommand(null);
|
||||
@@ -41,9 +41,9 @@ describe("tree-command-client", () => {
|
||||
|
||||
expect(fetchMock).toHaveBeenCalledTimes(10);
|
||||
expect(fetchMock.mock.calls.map((call) => String(call[0]))).toEqual([
|
||||
"/api/documents/create",
|
||||
"/api/documents/title",
|
||||
"/api/documents/move",
|
||||
"/api/tree/commands",
|
||||
"/api/tree/commands",
|
||||
"/api/tree/commands",
|
||||
"/api/documents/delete",
|
||||
"/api/documents/restore",
|
||||
"/api/documents/purge",
|
||||
@@ -52,6 +52,24 @@ describe("tree-command-client", () => {
|
||||
"/api/documents/title",
|
||||
"/api/documents/options",
|
||||
]);
|
||||
|
||||
expect(JSON.parse(String(fetchMock.mock.calls[0]?.[1]?.body))).toEqual({
|
||||
action: "create",
|
||||
parentId: null,
|
||||
});
|
||||
expect(JSON.parse(String(fetchMock.mock.calls[1]?.[1]?.body))).toEqual({
|
||||
action: "rename",
|
||||
documentId: "doc_1",
|
||||
workspaceId: null,
|
||||
title: "新标题",
|
||||
});
|
||||
expect(JSON.parse(String(fetchMock.mock.calls[2]?.[1]?.body))).toEqual({
|
||||
action: "move",
|
||||
documentId: "doc_1",
|
||||
parentId: null,
|
||||
sortOrder: 0,
|
||||
workspaceId: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("在后端返回错误时抛出统一异常", async () => {
|
||||
|
||||
@@ -96,6 +96,8 @@ type MoveDocumentInput = {
|
||||
workspaceId?: string | null;
|
||||
};
|
||||
|
||||
type TreeCommandAction = "create" | "rename" | "move";
|
||||
|
||||
type DeleteDocumentInput = {
|
||||
documentId: string;
|
||||
workspaceId?: string | null;
|
||||
@@ -148,8 +150,56 @@ async function postDocumentCommand<TResult>(path: string, payload: unknown, fall
|
||||
return body as TResult;
|
||||
}
|
||||
|
||||
type TreeCommandResponse = {
|
||||
requestId?: string;
|
||||
traceId?: string;
|
||||
result?: {
|
||||
action?: TreeCommandAction;
|
||||
workspaceId?: string | null;
|
||||
documentId?: string;
|
||||
parentId?: string | null;
|
||||
title?: string | null;
|
||||
sortOrder?: number | null;
|
||||
updatedAt?: string | null;
|
||||
execution?: {
|
||||
access_scope?: "private" | "shared" | "public";
|
||||
is_template?: boolean;
|
||||
created_at?: string | null;
|
||||
updated_at?: string | null;
|
||||
} | null;
|
||||
} | null;
|
||||
};
|
||||
|
||||
async function postTreeCommand<TResult>(payload: unknown, fallbackMessage: string): Promise<TResult> {
|
||||
return postDocumentCommand<TResult>("/api/tree/commands", payload, fallbackMessage);
|
||||
}
|
||||
|
||||
export async function createDocumentCommand(parentId: string | null): Promise<DocumentCreateCommandResult> {
|
||||
return postDocumentCommand<DocumentCreateCommandResult>("/api/documents/create", { parentId }, "新建页面失败,请稍后再试");
|
||||
const response = await postTreeCommand<TreeCommandResponse>(
|
||||
{
|
||||
action: "create",
|
||||
parentId,
|
||||
},
|
||||
"新建页面失败,请稍后再试",
|
||||
);
|
||||
const result = response.result;
|
||||
|
||||
return {
|
||||
id: result?.documentId ?? "",
|
||||
title: result?.title ?? "无标题",
|
||||
parent_id: result?.parentId ?? parentId,
|
||||
sort_order: result?.sortOrder ?? null,
|
||||
workspace_id: result?.workspaceId ?? undefined,
|
||||
access_scope: result?.execution?.access_scope ?? "private",
|
||||
is_template: result?.execution?.is_template ?? false,
|
||||
created_at: result?.execution?.created_at ?? null,
|
||||
updated_at: result?.execution?.updated_at ?? result?.updatedAt ?? null,
|
||||
meta: {
|
||||
requestId: response.requestId,
|
||||
traceId: response.traceId,
|
||||
commandName: TREE_COMMAND_PROTOCOL.create.preferredCommandName,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export async function createChildDocumentCommand(
|
||||
@@ -163,15 +213,24 @@ export async function createChildDocumentCommand(
|
||||
}
|
||||
|
||||
export async function renameDocumentCommand(input: RenameDocumentInput): Promise<{ ok: true; meta?: DocumentCommandMeta }> {
|
||||
return postDocumentCommand<{ ok: true; meta?: DocumentCommandMeta }>(
|
||||
"/api/documents/title",
|
||||
const response = await postTreeCommand<TreeCommandResponse>(
|
||||
{
|
||||
action: "rename",
|
||||
documentId: input.documentId,
|
||||
workspaceId: input.workspaceId ?? null,
|
||||
title: input.title,
|
||||
},
|
||||
"重命名失败,请稍后再试",
|
||||
);
|
||||
|
||||
return {
|
||||
ok: true,
|
||||
meta: {
|
||||
requestId: response.requestId,
|
||||
traceId: response.traceId,
|
||||
commandName: TREE_COMMAND_PROTOCOL.rename.preferredCommandName,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export async function updatePageTitleCommand(
|
||||
@@ -192,16 +251,25 @@ export async function updatePageOptionsCommand(
|
||||
}
|
||||
|
||||
export async function moveDocumentCommand(input: MoveDocumentInput): Promise<{ ok: true; meta?: DocumentCommandMeta }> {
|
||||
return postDocumentCommand<{ ok: true; meta?: DocumentCommandMeta }>(
|
||||
"/api/documents/move",
|
||||
const response = await postTreeCommand<TreeCommandResponse>(
|
||||
{
|
||||
action: "move",
|
||||
documentId: input.documentId,
|
||||
parentId: input.parentId ?? null,
|
||||
position: input.position,
|
||||
sortOrder: Number.isFinite(input.position) ? Math.floor(input.position) : 0,
|
||||
workspaceId: input.workspaceId ?? null,
|
||||
},
|
||||
"移动失败,请稍后再试",
|
||||
);
|
||||
|
||||
return {
|
||||
ok: true,
|
||||
meta: {
|
||||
requestId: response.requestId,
|
||||
traceId: response.traceId,
|
||||
commandName: TREE_COMMAND_PROTOCOL.move.preferredCommandName,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export async function deleteDocumentCommand(
|
||||
|
||||
@@ -117,6 +117,172 @@ describe("buildVisibleRows", () => {
|
||||
expect(rows.filter((r) => r.rowId === "doc:a").length).toBe(1);
|
||||
expect(new Set(rows.map((r) => r.rowId)).size).toBe(rows.length);
|
||||
});
|
||||
|
||||
it("优先消费 Rust file_tree projection 并保留 index 与资源文件夹语义", () => {
|
||||
const rows = buildVisibleRows({
|
||||
fileTreeItems: [
|
||||
{
|
||||
rowId: "doc:page_root",
|
||||
rowKind: "document",
|
||||
nodeId: "page_root",
|
||||
parentNodeId: null,
|
||||
nodeType: "page",
|
||||
projectionKind: "file_tree",
|
||||
title: "根页面",
|
||||
depth: 0,
|
||||
position: 0,
|
||||
childCount: 4,
|
||||
expandable: true,
|
||||
expandedByDefault: true,
|
||||
capabilities: ["expand", "open", "select"],
|
||||
resourceMeta: {
|
||||
resourceKind: "document",
|
||||
documentId: "page_root",
|
||||
workspaceId: "ws_1",
|
||||
iconHint: "page",
|
||||
},
|
||||
iconHint: "page",
|
||||
},
|
||||
{
|
||||
rowId: "index:page_root",
|
||||
rowKind: "index",
|
||||
nodeId: "index:page_root",
|
||||
parentNodeId: "page_root",
|
||||
nodeType: "index",
|
||||
projectionKind: "file_tree",
|
||||
title: "index.md",
|
||||
depth: 1,
|
||||
position: 0,
|
||||
childCount: 0,
|
||||
expandable: false,
|
||||
expandedByDefault: false,
|
||||
capabilities: ["open", "select"],
|
||||
resourceMeta: {
|
||||
resourceKind: "index",
|
||||
documentId: "page_root",
|
||||
workspaceId: "ws_1",
|
||||
iconHint: "index",
|
||||
},
|
||||
iconHint: "index",
|
||||
},
|
||||
{
|
||||
rowId: "asset-folder:mind_1",
|
||||
rowKind: "asset_folder",
|
||||
nodeId: "asset-folder:mind_1",
|
||||
parentNodeId: "page_root",
|
||||
nodeType: "mindmap",
|
||||
projectionKind: "file_tree",
|
||||
title: "头脑风暴",
|
||||
depth: 1,
|
||||
position: 1,
|
||||
childCount: 1,
|
||||
expandable: true,
|
||||
expandedByDefault: false,
|
||||
capabilities: ["expand", "open-asset", "select"],
|
||||
resourceMeta: {
|
||||
resourceKind: "mindmap",
|
||||
documentId: "page_root",
|
||||
assetId: "mind_1",
|
||||
workspaceId: "ws_1",
|
||||
assetKind: "mindmap",
|
||||
iconHint: "mindmap",
|
||||
},
|
||||
iconHint: "mindmap",
|
||||
},
|
||||
{
|
||||
rowId: "asset:asset_child_1",
|
||||
rowKind: "asset",
|
||||
nodeId: "asset:asset_child_1",
|
||||
parentNodeId: "asset-folder:mind_1",
|
||||
nodeType: "asset",
|
||||
projectionKind: "file_tree",
|
||||
title: "节点图片.png",
|
||||
depth: 2,
|
||||
position: 0,
|
||||
childCount: 0,
|
||||
expandable: false,
|
||||
expandedByDefault: false,
|
||||
capabilities: ["open-asset", "select"],
|
||||
resourceMeta: {
|
||||
resourceKind: "asset",
|
||||
documentId: "page_root",
|
||||
assetId: "asset_child_1",
|
||||
workspaceId: "ws_1",
|
||||
assetKind: "image",
|
||||
iconHint: "image",
|
||||
},
|
||||
iconHint: "image",
|
||||
},
|
||||
{
|
||||
rowId: "asset:table_1",
|
||||
rowKind: "asset",
|
||||
nodeId: "asset:table_1",
|
||||
parentNodeId: "page_root",
|
||||
nodeType: "table",
|
||||
projectionKind: "file_tree",
|
||||
title: "预算.luckysheet",
|
||||
depth: 1,
|
||||
position: 2,
|
||||
childCount: 0,
|
||||
expandable: false,
|
||||
expandedByDefault: false,
|
||||
capabilities: ["open-asset", "select"],
|
||||
resourceMeta: {
|
||||
resourceKind: "table",
|
||||
documentId: "page_root",
|
||||
assetId: "table_1",
|
||||
workspaceId: "ws_1",
|
||||
assetKind: "table",
|
||||
iconHint: "table",
|
||||
},
|
||||
iconHint: "table",
|
||||
},
|
||||
],
|
||||
expanded: new Set(["page_root"]),
|
||||
expandedAssetFolderIds: new Set(["mind_1"]),
|
||||
});
|
||||
|
||||
expect(rows.map((row) => `${row.kind}:${row.depth}:${row.rowId}`)).toEqual([
|
||||
"doc:0:doc:page_root",
|
||||
"index:1:index:page_root",
|
||||
"asset-folder:1:asset-folder:mind_1",
|
||||
"asset:2:asset:asset_child_1",
|
||||
"asset:1:asset:table_1",
|
||||
]);
|
||||
expect(rows[0]).toMatchObject({
|
||||
kind: "doc",
|
||||
docId: "page_root",
|
||||
hasChildren: true,
|
||||
isExpanded: true,
|
||||
});
|
||||
expect(rows[2]).toMatchObject({
|
||||
kind: "asset-folder",
|
||||
docId: "page_root",
|
||||
asset: {
|
||||
id: "mind_1",
|
||||
asset_type: "mindmap",
|
||||
file_name: "头脑风暴",
|
||||
},
|
||||
hasChildren: true,
|
||||
isExpanded: true,
|
||||
});
|
||||
expect(rows[3]).toMatchObject({
|
||||
kind: "asset",
|
||||
asset: {
|
||||
id: "asset_child_1",
|
||||
asset_type: "image",
|
||||
file_name: "节点图片.png",
|
||||
},
|
||||
});
|
||||
expect(rows[4]).toMatchObject({
|
||||
kind: "asset",
|
||||
asset: {
|
||||
id: "table_1",
|
||||
asset_type: "luckysheet",
|
||||
file_name: "预算.luckysheet",
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("parseFileTreeRowId", () => {
|
||||
|
||||
@@ -1,28 +1,129 @@
|
||||
"use client";
|
||||
|
||||
import type { KernelFileTreeProjectionItem } from "@/lib/kernel-file-tree";
|
||||
import {
|
||||
getDocIdFromFileTreeItem,
|
||||
resolveFileTreeRowAsset,
|
||||
resolveFileTreeRowNode,
|
||||
} from "@/lib/kernel-file-tree";
|
||||
import type { SidebarTreeNode } from "@/lib/kernel-sidebar";
|
||||
import type { PageTreeProjectionItem } from "@/lib/tree-projection";
|
||||
import type { MediaAsset } from "@/types/media";
|
||||
import type { FileTreeRow } from "./types";
|
||||
import { makeAssetFolderRowId, makeAssetRowId, makeDocRowId, makeIndexRowId } from "./types";
|
||||
|
||||
function buildRowsFromKernelFileTreeProjection(input: {
|
||||
fileTreeItems: KernelFileTreeProjectionItem[];
|
||||
expanded: Set<string>;
|
||||
expandedAssetFolderIds?: Set<string>;
|
||||
nodeById?: Map<string, SidebarTreeNode>;
|
||||
assetById?: Map<string, MediaAsset>;
|
||||
}): FileTreeRow[] {
|
||||
const rows: FileTreeRow[] = [];
|
||||
const seen = new Set<string>();
|
||||
|
||||
input.fileTreeItems.forEach((item) => {
|
||||
if (!item?.rowId || seen.has(item.rowId)) {
|
||||
return;
|
||||
}
|
||||
seen.add(item.rowId);
|
||||
const docId = getDocIdFromFileTreeItem(item);
|
||||
|
||||
switch (item.rowKind) {
|
||||
case "document": {
|
||||
const node = resolveFileTreeRowNode(item, input.nodeById);
|
||||
rows.push({
|
||||
kind: "doc",
|
||||
rowId: makeDocRowId(docId),
|
||||
depth: item.depth,
|
||||
docId,
|
||||
parentDocId: item.parentNodeId,
|
||||
node,
|
||||
hasChildren: item.childCount > 0,
|
||||
isExpanded: input.expanded.has(docId),
|
||||
});
|
||||
return;
|
||||
}
|
||||
case "index": {
|
||||
const node = resolveFileTreeRowNode(item, input.nodeById);
|
||||
rows.push({
|
||||
kind: "index",
|
||||
rowId: makeIndexRowId(docId),
|
||||
depth: item.depth,
|
||||
docId,
|
||||
parentDocId: docId,
|
||||
node,
|
||||
});
|
||||
return;
|
||||
}
|
||||
case "asset_folder": {
|
||||
const asset = resolveFileTreeRowAsset(item, input.assetById);
|
||||
rows.push({
|
||||
kind: "asset-folder",
|
||||
rowId: makeAssetFolderRowId(asset.id),
|
||||
depth: item.depth,
|
||||
docId,
|
||||
parentDocId: docId,
|
||||
asset,
|
||||
hasChildren: item.childCount > 0,
|
||||
isExpanded: input.expandedAssetFolderIds?.has(asset.id) ?? false,
|
||||
});
|
||||
return;
|
||||
}
|
||||
case "asset": {
|
||||
const asset = resolveFileTreeRowAsset(item, input.assetById);
|
||||
rows.push({
|
||||
kind: "asset",
|
||||
rowId: makeAssetRowId(asset.id),
|
||||
depth: item.depth,
|
||||
docId,
|
||||
parentDocId: docId,
|
||||
asset,
|
||||
});
|
||||
return;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return rows;
|
||||
}
|
||||
|
||||
export function buildVisibleRows({
|
||||
fileTreeItems,
|
||||
pageRows,
|
||||
expanded,
|
||||
assetsByDoc,
|
||||
assetChildrenByAssetId,
|
||||
expandedAssetFolderIds,
|
||||
nodeById,
|
||||
assetById,
|
||||
}: {
|
||||
fileTreeItems?: KernelFileTreeProjectionItem[];
|
||||
// 只消费统一 page_tree projection;结构真相不再由文件树自行定义。
|
||||
pageRows: PageTreeProjectionItem[];
|
||||
pageRows?: PageTreeProjectionItem[];
|
||||
expanded: Set<string>;
|
||||
assetsByDoc: Record<string, MediaAsset[]>;
|
||||
assetsByDoc?: Record<string, MediaAsset[]>;
|
||||
assetChildrenByAssetId?: Record<string, MediaAsset[]>;
|
||||
expandedAssetFolderIds?: Set<string>;
|
||||
nodeById?: Map<string, SidebarTreeNode>;
|
||||
assetById?: Map<string, MediaAsset>;
|
||||
}): FileTreeRow[] {
|
||||
if (fileTreeItems && fileTreeItems.length > 0) {
|
||||
return buildRowsFromKernelFileTreeProjection({
|
||||
fileTreeItems,
|
||||
expanded,
|
||||
expandedAssetFolderIds,
|
||||
nodeById,
|
||||
assetById,
|
||||
});
|
||||
}
|
||||
|
||||
const safePageRows = pageRows ?? [];
|
||||
const safeAssetsByDoc = assetsByDoc ?? {};
|
||||
const rows: FileTreeRow[] = [];
|
||||
|
||||
pageRows.forEach((item) => {
|
||||
const assets = assetsByDoc[item.nodeId] ?? [];
|
||||
safePageRows.forEach((item) => {
|
||||
const assets = safeAssetsByDoc[item.nodeId] ?? [];
|
||||
const hasChildren = item.childCount > 0 || assets.length > 0;
|
||||
const isExpanded = expanded.has(item.nodeId);
|
||||
rows.push({
|
||||
|
||||
@@ -0,0 +1,578 @@
|
||||
import type { DocumentRecord } from "@/lib/documents";
|
||||
import type { SidebarTreeNode } from "@/lib/kernel-sidebar";
|
||||
import type {
|
||||
TreeProjectionAssetKind,
|
||||
TreeProjectionCapability,
|
||||
TreeProjectionItemBase,
|
||||
TreeProjectionNodeType,
|
||||
TreeProjectionResourceKind,
|
||||
} from "@/lib/tree-protocol";
|
||||
import type { MediaAsset } from "@/types/media";
|
||||
|
||||
export type KernelFileTreeProjectionRowKind =
|
||||
| "document"
|
||||
| "index"
|
||||
| "asset"
|
||||
| "asset_folder";
|
||||
|
||||
export type KernelFileTreeProjectionItem = TreeProjectionItemBase & {
|
||||
projectionKind: "file_tree";
|
||||
rowId: string;
|
||||
rowKind: KernelFileTreeProjectionRowKind;
|
||||
};
|
||||
|
||||
export type KernelFileTreeProjectionEdge = {
|
||||
id: string;
|
||||
edgeType: "parent_of";
|
||||
workspaceId: string | null;
|
||||
fromNodeId: string;
|
||||
toNodeId: string;
|
||||
};
|
||||
|
||||
export type KernelFileTreeProjection = {
|
||||
projectionId: string;
|
||||
projection: "file_tree";
|
||||
rootNodeId: string | null;
|
||||
items: KernelFileTreeProjectionItem[];
|
||||
edges: KernelFileTreeProjectionEdge[];
|
||||
};
|
||||
|
||||
type BuildKernelFileTreeProjectionInput = {
|
||||
documents: DocumentRecord[];
|
||||
mediaAssets?: MediaAsset[] | null;
|
||||
mindmapAssets?: MediaAsset[] | null;
|
||||
tableAssets?: MediaAsset[] | null;
|
||||
mindmapAssetChildren?: Record<string, string[]> | null;
|
||||
rootNodeId?: string | null;
|
||||
};
|
||||
|
||||
type NormalizedFileTreeAsset = {
|
||||
id: string;
|
||||
documentId: string;
|
||||
workspaceId: string | null;
|
||||
title: string;
|
||||
resourceKind: TreeProjectionResourceKind;
|
||||
assetKind: TreeProjectionAssetKind;
|
||||
iconHint: string;
|
||||
nodeType: TreeProjectionNodeType;
|
||||
};
|
||||
|
||||
function readRowId(value: unknown): string | null {
|
||||
return typeof value === "string" && value.trim() ? value.trim() : null;
|
||||
}
|
||||
|
||||
function toMillis(value: string | null | undefined): number {
|
||||
if (!value) return 0;
|
||||
const parsed = Date.parse(value);
|
||||
return Number.isFinite(parsed) ? parsed : 0;
|
||||
}
|
||||
|
||||
function sortDocuments(records: DocumentRecord[]) {
|
||||
return [...records].sort((a, b) => {
|
||||
const orderA = a.sort_order ?? Number.MAX_SAFE_INTEGER;
|
||||
const orderB = b.sort_order ?? Number.MAX_SAFE_INTEGER;
|
||||
if (orderA !== orderB) {
|
||||
return orderA - orderB;
|
||||
}
|
||||
return toMillis(a.created_at) - toMillis(b.created_at);
|
||||
});
|
||||
}
|
||||
|
||||
function dedupeDocuments(records: DocumentRecord[]) {
|
||||
const seen = new Set<string>();
|
||||
const unique: DocumentRecord[] = [];
|
||||
for (let index = records.length - 1; index >= 0; index -= 1) {
|
||||
const record = records[index]!;
|
||||
if (seen.has(record.id)) {
|
||||
continue;
|
||||
}
|
||||
seen.add(record.id);
|
||||
unique.push(record);
|
||||
}
|
||||
unique.reverse();
|
||||
return unique;
|
||||
}
|
||||
|
||||
function buildDocumentChildren(records: DocumentRecord[]) {
|
||||
const childrenByParentId = new Map<string | null, DocumentRecord[]>();
|
||||
const recordIds = new Set(records.map((record) => record.id));
|
||||
|
||||
for (const record of records) {
|
||||
const parentId =
|
||||
record.parent_id && recordIds.has(record.parent_id) ? record.parent_id : null;
|
||||
const bucket = childrenByParentId.get(parentId) ?? [];
|
||||
bucket.push(record);
|
||||
childrenByParentId.set(parentId, bucket);
|
||||
}
|
||||
|
||||
for (const [parentId, bucket] of childrenByParentId.entries()) {
|
||||
childrenByParentId.set(parentId, sortDocuments(bucket));
|
||||
}
|
||||
|
||||
return childrenByParentId;
|
||||
}
|
||||
|
||||
function makeProjectionEdge(
|
||||
fromNodeId: string,
|
||||
toNodeId: string,
|
||||
workspaceId: string | null,
|
||||
): KernelFileTreeProjectionEdge {
|
||||
return {
|
||||
id: `edge:${fromNodeId}:${toNodeId}:parent_of`,
|
||||
edgeType: "parent_of",
|
||||
workspaceId,
|
||||
fromNodeId,
|
||||
toNodeId,
|
||||
};
|
||||
}
|
||||
|
||||
function buildDocumentCapabilities(childCount: number): TreeProjectionCapability[] {
|
||||
const capabilities: TreeProjectionCapability[] = [
|
||||
"open",
|
||||
"drag",
|
||||
"drop",
|
||||
"select",
|
||||
"create-child",
|
||||
"rename",
|
||||
"archive",
|
||||
"restore",
|
||||
"context-menu",
|
||||
"reorder",
|
||||
];
|
||||
if (childCount > 0) {
|
||||
capabilities.unshift("expand");
|
||||
}
|
||||
return capabilities;
|
||||
}
|
||||
|
||||
function buildAssetFolderCapabilities(childCount: number): TreeProjectionCapability[] {
|
||||
const capabilities: TreeProjectionCapability[] = [
|
||||
"open-asset",
|
||||
"select",
|
||||
"context-menu",
|
||||
];
|
||||
if (childCount > 0) {
|
||||
capabilities.unshift("expand");
|
||||
}
|
||||
return capabilities;
|
||||
}
|
||||
|
||||
function buildLeafCapabilities(openAsset: boolean): TreeProjectionCapability[] {
|
||||
const capabilities: TreeProjectionCapability[] = ["select", "context-menu"];
|
||||
capabilities.unshift(openAsset ? "open-asset" : "open");
|
||||
return capabilities;
|
||||
}
|
||||
|
||||
function classifyGenericAssetKind(asset: MediaAsset): TreeProjectionAssetKind {
|
||||
const assetType = String(asset.asset_type ?? "").trim().toLowerCase();
|
||||
const name = String(asset.file_name ?? "").trim().toLowerCase();
|
||||
const mimeType = String(asset.mime_type ?? "").trim().toLowerCase();
|
||||
const ext = name.includes(".") ? name.split(".").pop() ?? "" : "";
|
||||
|
||||
if (assetType === "mindmap") return "mindmap";
|
||||
if (assetType === "luckysheet") return "table";
|
||||
if (ext === "pdf" || mimeType.includes("pdf")) return "pdf";
|
||||
if (ext === "epub" || mimeType.includes("epub")) return "book";
|
||||
if (mimeType.startsWith("image/")) return "image";
|
||||
if (mimeType.startsWith("video/")) return "video";
|
||||
if (mimeType.startsWith("audio/")) return "audio";
|
||||
return "file";
|
||||
}
|
||||
|
||||
function classifyResourceKind(assetKind: TreeProjectionAssetKind): TreeProjectionResourceKind {
|
||||
switch (assetKind) {
|
||||
case "mindmap":
|
||||
return "mindmap";
|
||||
case "table":
|
||||
return "table";
|
||||
case "book":
|
||||
return "book";
|
||||
case "pdf":
|
||||
return "pdf";
|
||||
default:
|
||||
return "asset";
|
||||
}
|
||||
}
|
||||
|
||||
function classifyNodeType(assetKind: TreeProjectionAssetKind): TreeProjectionNodeType {
|
||||
switch (assetKind) {
|
||||
case "mindmap":
|
||||
return "mindmap";
|
||||
case "table":
|
||||
return "table";
|
||||
case "book":
|
||||
return "book";
|
||||
case "pdf":
|
||||
return "pdf";
|
||||
default:
|
||||
return "asset";
|
||||
}
|
||||
}
|
||||
|
||||
function classifyIconHint(assetKind: TreeProjectionAssetKind): string {
|
||||
switch (assetKind) {
|
||||
case "mindmap":
|
||||
return "mindmap";
|
||||
case "table":
|
||||
return "table";
|
||||
case "book":
|
||||
return "book";
|
||||
case "pdf":
|
||||
return "pdf";
|
||||
case "image":
|
||||
return "image";
|
||||
case "video":
|
||||
return "video";
|
||||
case "audio":
|
||||
return "audio";
|
||||
default:
|
||||
return "file";
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeAsset(asset: MediaAsset): NormalizedFileTreeAsset {
|
||||
const assetKind = classifyGenericAssetKind(asset);
|
||||
return {
|
||||
id: asset.id,
|
||||
documentId: asset.document_id,
|
||||
workspaceId: asset.workspace_id ?? null,
|
||||
title: asset.file_name?.trim() || "附件",
|
||||
resourceKind: classifyResourceKind(assetKind),
|
||||
assetKind,
|
||||
iconHint: classifyIconHint(assetKind),
|
||||
nodeType: classifyNodeType(assetKind),
|
||||
};
|
||||
}
|
||||
|
||||
function buildAssetCollections(input: BuildKernelFileTreeProjectionInput) {
|
||||
const assetsByDoc = new Map<string, NormalizedFileTreeAsset[]>();
|
||||
const assetById = new Map<string, NormalizedFileTreeAsset>();
|
||||
const seen = new Set<string>();
|
||||
|
||||
for (const asset of [
|
||||
...(input.mediaAssets ?? []),
|
||||
...(input.mindmapAssets ?? []),
|
||||
...(input.tableAssets ?? []),
|
||||
]) {
|
||||
if (!asset?.id || seen.has(asset.id)) {
|
||||
continue;
|
||||
}
|
||||
seen.add(asset.id);
|
||||
const normalized = normalizeAsset(asset);
|
||||
const bucket = assetsByDoc.get(normalized.documentId) ?? [];
|
||||
bucket.push(normalized);
|
||||
assetsByDoc.set(normalized.documentId, bucket);
|
||||
assetById.set(normalized.id, normalized);
|
||||
}
|
||||
|
||||
const childAssetIdsByParentId = new Map<string, string[]>();
|
||||
Object.entries(input.mindmapAssetChildren ?? {}).forEach(([parentAssetId, childIds]) => {
|
||||
childAssetIdsByParentId.set(
|
||||
parentAssetId,
|
||||
(childIds ?? []).filter((childId) => typeof childId === "string" && childId.trim().length > 0),
|
||||
);
|
||||
});
|
||||
|
||||
return {
|
||||
assetsByDoc,
|
||||
assetById,
|
||||
childAssetIdsByParentId,
|
||||
};
|
||||
}
|
||||
|
||||
function makeFallbackNode(item: KernelFileTreeProjectionItem): SidebarTreeNode {
|
||||
const documentId =
|
||||
item.resourceMeta.documentId ??
|
||||
(item.rowKind === "document" ? item.nodeId : item.parentNodeId ?? item.nodeId);
|
||||
return {
|
||||
access_scope: "private",
|
||||
id: documentId,
|
||||
workspace_id: item.resourceMeta.workspaceId ?? "",
|
||||
title: item.title,
|
||||
parent_id: item.rowKind === "document" ? item.parentNodeId : documentId,
|
||||
sort_order: item.position,
|
||||
is_starred: false,
|
||||
is_template: false,
|
||||
created_at: "",
|
||||
updated_at: null,
|
||||
children: [],
|
||||
kernel: {
|
||||
nodeType: "page",
|
||||
depth: item.depth,
|
||||
position: item.position,
|
||||
childCount: item.childCount,
|
||||
expandedByDefault: item.expandedByDefault,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function makeFallbackAsset(item: KernelFileTreeProjectionItem): MediaAsset {
|
||||
const assetKind = item.resourceMeta.assetKind ?? "unknown";
|
||||
const resourceKind = item.resourceMeta.resourceKind;
|
||||
const assetType =
|
||||
assetKind === "mindmap"
|
||||
? "mindmap"
|
||||
: assetKind === "table" || resourceKind === "table"
|
||||
? "luckysheet"
|
||||
: assetKind;
|
||||
return {
|
||||
id: item.resourceMeta.assetId ?? item.nodeId,
|
||||
workspace_id: item.resourceMeta.workspaceId ?? "",
|
||||
document_id: item.resourceMeta.documentId ?? "",
|
||||
asset_type: assetType,
|
||||
file_url: null,
|
||||
thumbnail_url: null,
|
||||
bucket: null,
|
||||
storage_path: null,
|
||||
file_name: item.title,
|
||||
file_size: null,
|
||||
mime_type: null,
|
||||
ocr_payload: undefined,
|
||||
ocr_strategy: null,
|
||||
ocr_text: null,
|
||||
ocr_status: null,
|
||||
signed_url: null,
|
||||
created_at: "",
|
||||
updated_at: "",
|
||||
};
|
||||
}
|
||||
|
||||
export function getDocIdFromFileTreeItem(item: KernelFileTreeProjectionItem): string {
|
||||
if (item.resourceMeta.documentId) {
|
||||
return item.resourceMeta.documentId;
|
||||
}
|
||||
if (item.rowKind === "document") {
|
||||
return item.nodeId;
|
||||
}
|
||||
const rowId = readRowId(item.rowId);
|
||||
if (rowId?.startsWith("index:")) {
|
||||
return rowId.slice("index:".length);
|
||||
}
|
||||
return item.parentNodeId ?? item.nodeId;
|
||||
}
|
||||
|
||||
export function resolveFileTreeRowNode(
|
||||
item: KernelFileTreeProjectionItem,
|
||||
nodeById?: Map<string, SidebarTreeNode>,
|
||||
): SidebarTreeNode {
|
||||
const documentId = getDocIdFromFileTreeItem(item);
|
||||
return nodeById?.get(documentId) ?? makeFallbackNode(item);
|
||||
}
|
||||
|
||||
export function resolveFileTreeRowAsset(
|
||||
item: KernelFileTreeProjectionItem,
|
||||
assetById?: Map<string, MediaAsset>,
|
||||
): MediaAsset {
|
||||
const assetId = item.resourceMeta.assetId ?? item.nodeId;
|
||||
return assetById?.get(assetId) ?? makeFallbackAsset(item);
|
||||
}
|
||||
|
||||
export function isKernelFileTreeProjection(value: unknown): value is KernelFileTreeProjection {
|
||||
return (
|
||||
Boolean(value) &&
|
||||
typeof value === "object" &&
|
||||
(value as KernelFileTreeProjection).projection === "file_tree" &&
|
||||
Array.isArray((value as KernelFileTreeProjection).items) &&
|
||||
Array.isArray((value as KernelFileTreeProjection).edges)
|
||||
);
|
||||
}
|
||||
|
||||
export function buildKernelFileTreeProjection(
|
||||
input: BuildKernelFileTreeProjectionInput,
|
||||
): KernelFileTreeProjection {
|
||||
const uniqueDocuments = dedupeDocuments(input.documents);
|
||||
const documentById = new Map(uniqueDocuments.map((document) => [document.id, document]));
|
||||
const childrenByParentId = buildDocumentChildren(uniqueDocuments);
|
||||
const { assetsByDoc, assetById, childAssetIdsByParentId } = buildAssetCollections(input);
|
||||
const rootNodeId = input.rootNodeId?.trim() || null;
|
||||
const roots =
|
||||
rootNodeId && documentById.has(rootNodeId)
|
||||
? [rootNodeId]
|
||||
: sortDocuments(
|
||||
uniqueDocuments.filter((document) => {
|
||||
const parentId = document.parent_id?.trim() || null;
|
||||
return !parentId || !documentById.has(parentId);
|
||||
}),
|
||||
).map((document) => document.id);
|
||||
|
||||
const items: KernelFileTreeProjectionItem[] = [];
|
||||
const edges: KernelFileTreeProjectionEdge[] = [];
|
||||
|
||||
const walk = (documentId: string, depth: number) => {
|
||||
const document = documentById.get(documentId);
|
||||
if (!document) {
|
||||
return;
|
||||
}
|
||||
|
||||
const childDocuments = childrenByParentId.get(documentId) ?? [];
|
||||
const documentAssets = assetsByDoc.get(documentId) ?? [];
|
||||
const nestedChildIds = new Set<string>();
|
||||
documentAssets.forEach((asset) => {
|
||||
const childIds = childAssetIdsByParentId.get(asset.id) ?? [];
|
||||
childIds.forEach((childId) => nestedChildIds.add(childId));
|
||||
});
|
||||
const directAssets = documentAssets.filter((asset) => !nestedChildIds.has(asset.id));
|
||||
const childCount = 1 + directAssets.length + childDocuments.length;
|
||||
const parentNodeId = depth === 0 ? null : document.parent_id ?? null;
|
||||
const workspaceId = document.workspace_id ?? null;
|
||||
|
||||
items.push({
|
||||
rowId: `doc:${document.id}`,
|
||||
rowKind: "document",
|
||||
nodeId: document.id,
|
||||
parentNodeId,
|
||||
nodeType: "page",
|
||||
projectionKind: "file_tree",
|
||||
title: document.title ?? "无标题",
|
||||
depth,
|
||||
position: document.sort_order ?? null,
|
||||
childCount,
|
||||
expandable: childCount > 0,
|
||||
expandedByDefault: true,
|
||||
capabilities: buildDocumentCapabilities(childCount),
|
||||
resourceMeta: {
|
||||
resourceKind: "document",
|
||||
documentId: document.id,
|
||||
workspaceId,
|
||||
iconHint: "page",
|
||||
},
|
||||
iconHint: "page",
|
||||
});
|
||||
|
||||
const indexNodeId = `index:${document.id}`;
|
||||
items.push({
|
||||
rowId: indexNodeId,
|
||||
rowKind: "index",
|
||||
nodeId: indexNodeId,
|
||||
parentNodeId: document.id,
|
||||
nodeType: "index",
|
||||
projectionKind: "file_tree",
|
||||
title: "index.md",
|
||||
depth: depth + 1,
|
||||
position: 0,
|
||||
childCount: 0,
|
||||
expandable: false,
|
||||
expandedByDefault: false,
|
||||
capabilities: buildLeafCapabilities(false),
|
||||
resourceMeta: {
|
||||
resourceKind: "index",
|
||||
documentId: document.id,
|
||||
workspaceId,
|
||||
iconHint: "index",
|
||||
},
|
||||
iconHint: "index",
|
||||
});
|
||||
edges.push(makeProjectionEdge(document.id, indexNodeId, workspaceId));
|
||||
|
||||
let assetPosition = 1;
|
||||
directAssets.forEach((asset) => {
|
||||
const childIds = childAssetIdsByParentId.get(asset.id) ?? [];
|
||||
if (childIds.length > 0) {
|
||||
const folderNodeId = `asset-folder:${asset.id}`;
|
||||
items.push({
|
||||
rowId: folderNodeId,
|
||||
rowKind: "asset_folder",
|
||||
nodeId: folderNodeId,
|
||||
parentNodeId: document.id,
|
||||
nodeType: "mindmap",
|
||||
projectionKind: "file_tree",
|
||||
title: asset.title.replace(/\.json$/i, ""),
|
||||
depth: depth + 1,
|
||||
position: assetPosition,
|
||||
childCount: childIds.length,
|
||||
expandable: true,
|
||||
expandedByDefault: false,
|
||||
capabilities: buildAssetFolderCapabilities(childIds.length),
|
||||
resourceMeta: {
|
||||
resourceKind: asset.resourceKind,
|
||||
documentId: asset.documentId,
|
||||
assetId: asset.id,
|
||||
workspaceId: asset.workspaceId,
|
||||
assetKind: asset.assetKind,
|
||||
iconHint: "mindmap",
|
||||
},
|
||||
iconHint: "mindmap",
|
||||
});
|
||||
edges.push(makeProjectionEdge(document.id, folderNodeId, workspaceId));
|
||||
|
||||
childIds.forEach((childAssetId, index) => {
|
||||
const childAsset = assetById.get(childAssetId);
|
||||
if (!childAsset) {
|
||||
return;
|
||||
}
|
||||
const childNodeId = `asset:${childAsset.id}`;
|
||||
items.push({
|
||||
rowId: childNodeId,
|
||||
rowKind: "asset",
|
||||
nodeId: childNodeId,
|
||||
parentNodeId: folderNodeId,
|
||||
nodeType: childAsset.nodeType,
|
||||
projectionKind: "file_tree",
|
||||
title: childAsset.title,
|
||||
depth: depth + 2,
|
||||
position: index,
|
||||
childCount: 0,
|
||||
expandable: false,
|
||||
expandedByDefault: false,
|
||||
capabilities: buildLeafCapabilities(true),
|
||||
resourceMeta: {
|
||||
resourceKind: childAsset.resourceKind,
|
||||
documentId: childAsset.documentId,
|
||||
assetId: childAsset.id,
|
||||
workspaceId: childAsset.workspaceId,
|
||||
assetKind: childAsset.assetKind,
|
||||
iconHint: childAsset.iconHint,
|
||||
},
|
||||
iconHint: childAsset.iconHint,
|
||||
});
|
||||
edges.push(makeProjectionEdge(folderNodeId, childNodeId, workspaceId));
|
||||
});
|
||||
|
||||
assetPosition += 1;
|
||||
return;
|
||||
}
|
||||
|
||||
const assetNodeId = `asset:${asset.id}`;
|
||||
items.push({
|
||||
rowId: assetNodeId,
|
||||
rowKind: "asset",
|
||||
nodeId: assetNodeId,
|
||||
parentNodeId: document.id,
|
||||
nodeType: asset.nodeType,
|
||||
projectionKind: "file_tree",
|
||||
title: asset.title,
|
||||
depth: depth + 1,
|
||||
position: assetPosition,
|
||||
childCount: 0,
|
||||
expandable: false,
|
||||
expandedByDefault: false,
|
||||
capabilities: buildLeafCapabilities(true),
|
||||
resourceMeta: {
|
||||
resourceKind: asset.resourceKind,
|
||||
documentId: asset.documentId,
|
||||
assetId: asset.id,
|
||||
workspaceId: asset.workspaceId,
|
||||
assetKind: asset.assetKind,
|
||||
iconHint: asset.iconHint,
|
||||
},
|
||||
iconHint: asset.iconHint,
|
||||
});
|
||||
edges.push(makeProjectionEdge(document.id, assetNodeId, workspaceId));
|
||||
assetPosition += 1;
|
||||
});
|
||||
|
||||
childDocuments.forEach((childDocument) => {
|
||||
walk(childDocument.id, depth + 1);
|
||||
});
|
||||
};
|
||||
|
||||
roots.forEach((documentId) => walk(documentId, 0));
|
||||
|
||||
return {
|
||||
projectionId: `kernel_projection:file_tree:${rootNodeId ?? "root"}`,
|
||||
projection: "file_tree",
|
||||
rootNodeId,
|
||||
items,
|
||||
edges,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
import "server-only";
|
||||
|
||||
const DEFAULT_MNOTE_WEB_INTERNAL_URL = "http://127.0.0.1:3104";
|
||||
const DEFAULT_MNOTE_WEB_INTERNAL_URL_CANDIDATES = [
|
||||
DEFAULT_MNOTE_WEB_INTERNAL_URL,
|
||||
"http://localhost:3104",
|
||||
];
|
||||
const MNOTE_WEB_PROBE_PATH = "/health";
|
||||
const RESOLVE_CACHE_TTL_MS = 30_000;
|
||||
|
||||
let cachedMnoteWebInternalUrl = "";
|
||||
let cachedMnoteWebInternalUrlAt = 0;
|
||||
let pendingMnoteWebInternalUrl: Promise<string> | null = null;
|
||||
|
||||
const normalizeMnoteWebInternalUrl = (raw?: string | null) => {
|
||||
const value = String(raw || "").trim().replace(/\/+$/, "");
|
||||
if (!value) return "";
|
||||
try {
|
||||
const url = new URL(value);
|
||||
if (url.protocol !== "http:" && url.protocol !== "https:") {
|
||||
return "";
|
||||
}
|
||||
return url.toString().replace(/\/+$/, "");
|
||||
} catch {
|
||||
return "";
|
||||
}
|
||||
};
|
||||
|
||||
const getMnoteWebInternalUrlCandidates = () => {
|
||||
const candidates: string[] = [];
|
||||
const push = (value?: string | null) => {
|
||||
const normalized = normalizeMnoteWebInternalUrl(value);
|
||||
if (!normalized) return;
|
||||
if (!candidates.includes(normalized)) {
|
||||
candidates.push(normalized);
|
||||
}
|
||||
};
|
||||
|
||||
push(process.env.MNOTE_WEB_INTERNAL_URL);
|
||||
|
||||
for (const raw of String(process.env.MNOTE_WEB_INTERNAL_URL_CANDIDATES || "").split(",")) {
|
||||
push(raw);
|
||||
}
|
||||
|
||||
for (const candidate of DEFAULT_MNOTE_WEB_INTERNAL_URL_CANDIDATES) {
|
||||
push(candidate);
|
||||
}
|
||||
|
||||
return candidates.length > 0 ? candidates : [DEFAULT_MNOTE_WEB_INTERNAL_URL];
|
||||
};
|
||||
|
||||
const probeMnoteWebInternalUrl = async (candidate: string) => {
|
||||
try {
|
||||
const url = new URL(MNOTE_WEB_PROBE_PATH, `${candidate}/`);
|
||||
const response = await fetch(url, {
|
||||
method: "GET",
|
||||
redirect: "follow",
|
||||
cache: "no-store",
|
||||
signal: AbortSignal.timeout(2_500),
|
||||
});
|
||||
return response.ok;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
export const resolveMnoteWebInternalUrl = async () => {
|
||||
const now = Date.now();
|
||||
if (cachedMnoteWebInternalUrl && now - cachedMnoteWebInternalUrlAt < RESOLVE_CACHE_TTL_MS) {
|
||||
return cachedMnoteWebInternalUrl;
|
||||
}
|
||||
|
||||
if (pendingMnoteWebInternalUrl) {
|
||||
return pendingMnoteWebInternalUrl;
|
||||
}
|
||||
|
||||
pendingMnoteWebInternalUrl = (async () => {
|
||||
const candidates = getMnoteWebInternalUrlCandidates();
|
||||
for (const candidate of candidates) {
|
||||
if (await probeMnoteWebInternalUrl(candidate)) {
|
||||
return candidate;
|
||||
}
|
||||
}
|
||||
return candidates[0] || DEFAULT_MNOTE_WEB_INTERNAL_URL;
|
||||
})();
|
||||
|
||||
try {
|
||||
const resolved = await pendingMnoteWebInternalUrl;
|
||||
cachedMnoteWebInternalUrl = resolved;
|
||||
cachedMnoteWebInternalUrlAt = Date.now();
|
||||
return resolved;
|
||||
} finally {
|
||||
pendingMnoteWebInternalUrl = null;
|
||||
}
|
||||
};
|
||||
@@ -11,12 +11,41 @@ describe("runtime-config public projection", () => {
|
||||
expect("mnoteWebTreeShellEnabled" in (runtime as Record<string, unknown>)).toBe(false);
|
||||
});
|
||||
|
||||
it("允许通过新 runtime 配置显式选择树 renderer family", () => {
|
||||
window.__MNOTE_RUNTIME_CONFIG__ = {
|
||||
treeRendererFamily: "rust_family",
|
||||
};
|
||||
|
||||
const runtime = getMnoteRuntimeConfig();
|
||||
|
||||
expect(runtime.treeRendererFamily).toBe("rust_family");
|
||||
});
|
||||
|
||||
it("树 renderer family 别名应归一到 rust_family", () => {
|
||||
window.__MNOTE_RUNTIME_CONFIG__ = {
|
||||
treeRendererFamily: "tree_shell" as "rust_family",
|
||||
};
|
||||
|
||||
const runtime = getMnoteRuntimeConfig();
|
||||
|
||||
expect(runtime.treeRendererFamily).toBe("rust_family");
|
||||
});
|
||||
|
||||
it("树 renderer family 缺省时应回落到 react", () => {
|
||||
const runtime = getMnoteRuntimeConfig();
|
||||
|
||||
expect(runtime.treeRendererFamily).toBe("react");
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
delete process.env.NEXT_PUBLIC_MNOTE_WEB_BASE_URL;
|
||||
delete process.env.MNOTE_WEB_BASE_URL;
|
||||
delete process.env.NEXT_PUBLIC_MNOTE_WEB_TREE_SHELL_ENABLED;
|
||||
delete process.env.MNOTE_WEB_TREE_SHELL_ENABLED;
|
||||
delete process.env.NEXT_PUBLIC_TREE_RENDERER_FAMILY;
|
||||
delete process.env.TREE_RENDERER_FAMILY;
|
||||
delete window.__MNOTE_RUNTIME_CONFIG__;
|
||||
});
|
||||
|
||||
it("即使保留 legacy env 也不应回注 mnote-web runtime", () => {
|
||||
|
||||
@@ -35,6 +35,11 @@ export type MnoteRuntimeConfig = {
|
||||
* 说明:开启后,未显式传入 query host 的文档页会优先回退到 blocknote。
|
||||
*/
|
||||
documentEditorBlocknoteKillSwitch?: boolean;
|
||||
/**
|
||||
* 树域 renderer family 选择。
|
||||
* 说明:默认仍为 react;`rust_family` 只作为渐进切流开关,不代表已完全切主路径。
|
||||
*/
|
||||
treeRendererFamily?: "react" | "rust_family";
|
||||
/**
|
||||
* 是否为桌面端(Electron)运行。
|
||||
*/
|
||||
@@ -109,6 +114,25 @@ const parseDocumentEditorHost = (
|
||||
return undefined;
|
||||
};
|
||||
|
||||
const parseTreeRendererFamily = (
|
||||
value: unknown,
|
||||
): MnoteRuntimeConfig["treeRendererFamily"] | undefined => {
|
||||
if (typeof value !== "string") {
|
||||
return undefined;
|
||||
}
|
||||
const normalized = value.trim().toLowerCase();
|
||||
if (!normalized) {
|
||||
return undefined;
|
||||
}
|
||||
if (normalized === "rust_family" || normalized === "rust" || normalized === "tree_shell") {
|
||||
return "rust_family";
|
||||
}
|
||||
if (normalized === "react") {
|
||||
return "react";
|
||||
}
|
||||
return undefined;
|
||||
};
|
||||
|
||||
function getServerNodeBuiltin<T>(moduleName: string): T | null {
|
||||
if (typeof window !== "undefined") {
|
||||
return null;
|
||||
@@ -167,6 +191,17 @@ const readFromEnv = (): MnoteRuntimeConfig => ({
|
||||
),
|
||||
}
|
||||
: {}),
|
||||
...(parseTreeRendererFamily(
|
||||
process.env.NEXT_PUBLIC_TREE_RENDERER_FAMILY ??
|
||||
process.env.TREE_RENDERER_FAMILY,
|
||||
) !== undefined
|
||||
? {
|
||||
treeRendererFamily: parseTreeRendererFamily(
|
||||
process.env.NEXT_PUBLIC_TREE_RENDERER_FAMILY ??
|
||||
process.env.TREE_RENDERER_FAMILY,
|
||||
),
|
||||
}
|
||||
: {}),
|
||||
onlyofficeBaseUrl: process.env.NEXT_PUBLIC_ONLYOFFICE_BASE_URL,
|
||||
onlyofficeStorageHostOverride: process.env.NEXT_PUBLIC_ONLYOFFICE_STORAGE_HOST_OVERRIDE,
|
||||
onlyofficeProxyOrigin: process.env.NEXT_PUBLIC_ONLYOFFICE_PROXY_ORIGIN,
|
||||
@@ -256,12 +291,15 @@ const normalizeRuntimeConfig = (cfg: MnoteRuntimeConfig): MnoteRuntimeConfig =>
|
||||
parseDocumentEditorHost(cfg.documentEditorHost) ?? "leptos_tiptap_island";
|
||||
const documentEditorBlocknoteKillSwitch =
|
||||
parseRuntimeBoolean(cfg.documentEditorBlocknoteKillSwitch) ?? false;
|
||||
const treeRendererFamily =
|
||||
parseTreeRendererFamily(cfg.treeRendererFamily) ?? "react";
|
||||
|
||||
return {
|
||||
...cfg,
|
||||
isDesktop,
|
||||
documentEditorHost,
|
||||
documentEditorBlocknoteKillSwitch,
|
||||
treeRendererFamily,
|
||||
onlyofficeBaseUrl,
|
||||
onlyofficeStorageHostOverride,
|
||||
onlyofficeProxyOrigin,
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
import type { ConvexHttpClient } from "convex/browser";
|
||||
import type { SidebarDatasetListQueryResult } from "@/lib/sidebar-data";
|
||||
import type { KernelFileTreeProjection } from "@/lib/kernel-file-tree";
|
||||
import {
|
||||
buildDocumentBridgeContextWithActor,
|
||||
buildDocumentQueryEnvelope,
|
||||
type BridgeActor,
|
||||
} from "@/lib/documents/bridge";
|
||||
import { executeRustBridgeQuery } from "@/lib/documents/rust-runtime";
|
||||
|
||||
export async function resolveKernelFileTreeProjection(input: {
|
||||
client: ConvexHttpClient;
|
||||
request: Request;
|
||||
workspaceId: string;
|
||||
actor: BridgeActor;
|
||||
dataset: SidebarDatasetListQueryResult;
|
||||
rootNodeId?: string | null;
|
||||
depth?: number | null;
|
||||
}): Promise<KernelFileTreeProjection> {
|
||||
const context = buildDocumentBridgeContextWithActor({
|
||||
request: input.request,
|
||||
actor: input.actor,
|
||||
workspaceId: input.workspaceId,
|
||||
});
|
||||
|
||||
return executeRustBridgeQuery<KernelFileTreeProjection>({
|
||||
context,
|
||||
envelope: buildDocumentQueryEnvelope({
|
||||
name: "kernel.project_view",
|
||||
payload: {
|
||||
projection: "file_tree",
|
||||
workspaceId: input.workspaceId,
|
||||
rootNodeId: input.rootNodeId ?? null,
|
||||
depth: input.depth ?? null,
|
||||
includeEdges: true,
|
||||
includeContent: false,
|
||||
nodeTypes: ["page"],
|
||||
},
|
||||
}),
|
||||
data: input.dataset as unknown as Record<string, unknown>,
|
||||
});
|
||||
}
|
||||
|
||||
export function attachKernelFileTreeProjection<T extends SidebarDatasetListQueryResult>(input: {
|
||||
dataset: T;
|
||||
projection: KernelFileTreeProjection;
|
||||
}): T {
|
||||
return {
|
||||
...input.dataset,
|
||||
kernel_file_tree_projection: input.projection,
|
||||
};
|
||||
}
|
||||
@@ -9,9 +9,15 @@ import {
|
||||
type SidebarDatasetListQueryResult,
|
||||
} from "@/lib/sidebar-data";
|
||||
import type { WorkspaceSummary } from "@/lib/workspaces";
|
||||
import {
|
||||
attachKernelFileTreeProjection,
|
||||
resolveKernelFileTreeProjection,
|
||||
} from "@/lib/server/kernel-file-tree";
|
||||
import type { AuthContext } from "@/lib/auth/types";
|
||||
|
||||
type LoadSidebarDataFromConvexInput = {
|
||||
client: ConvexHttpClient;
|
||||
auth: AuthContext;
|
||||
fallbackName: string;
|
||||
requestedWorkspaceId?: string | null;
|
||||
};
|
||||
@@ -64,14 +70,29 @@ export async function loadSidebarDataFromConvex(
|
||||
const sidebarDataset = (await input.client.query(sidebarDatasetListQuery, {
|
||||
workspaceId: targetWorkspaceId,
|
||||
})) as SidebarDatasetListQueryResult;
|
||||
const normalizedDocuments = (sidebarDataset.documents ?? []) as DocumentRecord[];
|
||||
const syntheticRequest = new Request(`http://127.0.0.1:3000/api/sidebar?workspaceId=${targetWorkspaceId}`);
|
||||
const sidebarDatasetWithFileTree = attachKernelFileTreeProjection({
|
||||
dataset: sidebarDataset,
|
||||
projection: await resolveKernelFileTreeProjection({
|
||||
client: input.client,
|
||||
request: syntheticRequest,
|
||||
workspaceId: targetWorkspaceId,
|
||||
actor: {
|
||||
actorType: "user",
|
||||
actorId: input.auth.userId,
|
||||
sessionId: null,
|
||||
},
|
||||
dataset: sidebarDataset,
|
||||
}),
|
||||
});
|
||||
const normalizedDocuments = (sidebarDatasetWithFileTree.documents ?? []) as DocumentRecord[];
|
||||
|
||||
return {
|
||||
workspaces: sidebarDataset.workspaces ?? workspaces,
|
||||
workspaces: sidebarDatasetWithFileTree.workspaces ?? workspaces,
|
||||
activeWorkspaceId,
|
||||
targetWorkspaceId,
|
||||
sidebarDataset,
|
||||
sidebarInitialData: mapSidebarDatasetListQueryResultToInitialData(sidebarDataset),
|
||||
sidebarDataset: sidebarDatasetWithFileTree,
|
||||
sidebarInitialData: mapSidebarDatasetListQueryResultToInitialData(sidebarDatasetWithFileTree),
|
||||
documents: normalizedDocuments,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -137,6 +137,7 @@ describe("buildSidebarInitialData", () => {
|
||||
|
||||
expect(payload.activeWorkspaceId).toBe("ws_1");
|
||||
expect(payload.kernelSidebarProjection?.projection).toBe("sidebar_tree");
|
||||
expect(payload.kernelFileTreeProjection?.projection).toBe("file_tree");
|
||||
expect(payload.kernelSidebarTree?.map((item) => item.id)).toEqual(["doc_1"]);
|
||||
expect(payload.mindmapDocs).toEqual(["doc_1"]);
|
||||
expect(payload.mindmapAssetChildren).toEqual({
|
||||
@@ -251,6 +252,78 @@ describe("buildSidebarInitialData", () => {
|
||||
],
|
||||
edges: [],
|
||||
},
|
||||
kernel_file_tree_projection: {
|
||||
projectionId: "kernel_projection:file_tree:root",
|
||||
projection: "file_tree",
|
||||
rootNodeId: null,
|
||||
items: [
|
||||
{
|
||||
rowId: "doc:doc_1",
|
||||
rowKind: "document",
|
||||
nodeId: "doc_1",
|
||||
parentNodeId: null,
|
||||
nodeType: "page",
|
||||
projectionKind: "file_tree",
|
||||
title: "页面 1",
|
||||
depth: 0,
|
||||
position: 1,
|
||||
childCount: 1,
|
||||
expandable: true,
|
||||
expandedByDefault: true,
|
||||
capabilities: [
|
||||
"expand",
|
||||
"open",
|
||||
"drag",
|
||||
"drop",
|
||||
"select",
|
||||
"create-child",
|
||||
"rename",
|
||||
"archive",
|
||||
"restore",
|
||||
"context-menu",
|
||||
"reorder",
|
||||
],
|
||||
resourceMeta: {
|
||||
resourceKind: "document",
|
||||
documentId: "doc_1",
|
||||
workspaceId: "ws_1",
|
||||
iconHint: "page",
|
||||
},
|
||||
iconHint: "page",
|
||||
},
|
||||
{
|
||||
rowId: "index:doc_1",
|
||||
rowKind: "index",
|
||||
nodeId: "index:doc_1",
|
||||
parentNodeId: "doc_1",
|
||||
nodeType: "index",
|
||||
projectionKind: "file_tree",
|
||||
title: "index.md",
|
||||
depth: 1,
|
||||
position: 0,
|
||||
childCount: 0,
|
||||
expandable: false,
|
||||
expandedByDefault: false,
|
||||
capabilities: ["open", "select", "context-menu"],
|
||||
resourceMeta: {
|
||||
resourceKind: "index",
|
||||
documentId: "doc_1",
|
||||
workspaceId: "ws_1",
|
||||
iconHint: "index",
|
||||
},
|
||||
iconHint: "index",
|
||||
},
|
||||
],
|
||||
edges: [
|
||||
{
|
||||
id: "edge:doc_1:index:doc_1:parent_of",
|
||||
edgeType: "parent_of",
|
||||
workspaceId: "ws_1",
|
||||
fromNodeId: "doc_1",
|
||||
toNodeId: "index:doc_1",
|
||||
},
|
||||
],
|
||||
},
|
||||
trashed_documents: [],
|
||||
media_assets: [],
|
||||
trashed_media_assets: [],
|
||||
@@ -349,6 +422,78 @@ describe("buildSidebarInitialData", () => {
|
||||
},
|
||||
},
|
||||
],
|
||||
kernelFileTreeProjection: {
|
||||
projectionId: "kernel_projection:file_tree:root",
|
||||
projection: "file_tree",
|
||||
rootNodeId: null,
|
||||
items: [
|
||||
{
|
||||
rowId: "doc:doc_1",
|
||||
rowKind: "document",
|
||||
nodeId: "doc_1",
|
||||
parentNodeId: null,
|
||||
nodeType: "page",
|
||||
projectionKind: "file_tree",
|
||||
title: "页面 1",
|
||||
depth: 0,
|
||||
position: 1,
|
||||
childCount: 1,
|
||||
expandable: true,
|
||||
expandedByDefault: true,
|
||||
capabilities: [
|
||||
"expand",
|
||||
"open",
|
||||
"drag",
|
||||
"drop",
|
||||
"select",
|
||||
"create-child",
|
||||
"rename",
|
||||
"archive",
|
||||
"restore",
|
||||
"context-menu",
|
||||
"reorder",
|
||||
],
|
||||
resourceMeta: {
|
||||
resourceKind: "document",
|
||||
documentId: "doc_1",
|
||||
workspaceId: "ws_1",
|
||||
iconHint: "page",
|
||||
},
|
||||
iconHint: "page",
|
||||
},
|
||||
{
|
||||
rowId: "index:doc_1",
|
||||
rowKind: "index",
|
||||
nodeId: "index:doc_1",
|
||||
parentNodeId: "doc_1",
|
||||
nodeType: "index",
|
||||
projectionKind: "file_tree",
|
||||
title: "index.md",
|
||||
depth: 1,
|
||||
position: 0,
|
||||
childCount: 0,
|
||||
expandable: false,
|
||||
expandedByDefault: false,
|
||||
capabilities: ["open", "select", "context-menu"],
|
||||
resourceMeta: {
|
||||
resourceKind: "index",
|
||||
documentId: "doc_1",
|
||||
workspaceId: "ws_1",
|
||||
iconHint: "index",
|
||||
},
|
||||
iconHint: "index",
|
||||
},
|
||||
],
|
||||
edges: [
|
||||
{
|
||||
id: "edge:doc_1:index:doc_1:parent_of",
|
||||
edgeType: "parent_of",
|
||||
workspaceId: "ws_1",
|
||||
fromNodeId: "doc_1",
|
||||
toNodeId: "index:doc_1",
|
||||
},
|
||||
],
|
||||
},
|
||||
trashedDocuments: [],
|
||||
trashedMediaAssets: [],
|
||||
trashedMindmapAssets: [],
|
||||
|
||||
@@ -1,5 +1,10 @@
|
||||
import type { SidebarInitialData } from "@/components/sidebar/types";
|
||||
import type { DocumentRecord } from "@/lib/documents";
|
||||
import {
|
||||
buildKernelFileTreeProjection,
|
||||
isKernelFileTreeProjection,
|
||||
type KernelFileTreeProjection,
|
||||
} from "@/lib/kernel-file-tree";
|
||||
import {
|
||||
buildKernelSidebarProjection as buildProjectionContract,
|
||||
buildSidebarTreeFromKernelProjection,
|
||||
@@ -51,6 +56,8 @@ export type SidebarDatasetListQueryResult = {
|
||||
active_workspace_id: string;
|
||||
workspaces: WorkspaceSummary[];
|
||||
documents: DocumentRecord[];
|
||||
kernel_file_tree_projection?: KernelFileTreeProjection;
|
||||
kernelFileTreeProjection?: KernelFileTreeProjection;
|
||||
kernel_sidebar_projection?: KernelSidebarProjection;
|
||||
kernelSidebarProjection?: KernelSidebarProjection;
|
||||
trashed_documents: SidebarInitialData["trashedDocuments"];
|
||||
@@ -72,6 +79,14 @@ const EMPTY_KERNEL_SIDEBAR_PROJECTION: KernelSidebarProjection = {
|
||||
edges: [],
|
||||
};
|
||||
|
||||
const EMPTY_KERNEL_FILE_TREE_PROJECTION: KernelFileTreeProjection = {
|
||||
projectionId: "kernel_projection:file_tree:missing",
|
||||
projection: "file_tree",
|
||||
rootNodeId: null,
|
||||
items: [],
|
||||
edges: [],
|
||||
};
|
||||
|
||||
function isKernelSidebarProjection(value: unknown): value is KernelSidebarProjection {
|
||||
return (
|
||||
Boolean(value) &&
|
||||
@@ -105,6 +120,34 @@ function readKernelSidebarProjection(
|
||||
return EMPTY_KERNEL_SIDEBAR_PROJECTION;
|
||||
}
|
||||
|
||||
function readKernelFileTreeProjection(
|
||||
result: SidebarDatasetListQueryResult,
|
||||
): KernelFileTreeProjection {
|
||||
const snakeCaseProjection =
|
||||
"kernel_file_tree_projection" in result ? result.kernel_file_tree_projection : undefined;
|
||||
if (isKernelFileTreeProjection(snakeCaseProjection)) {
|
||||
return snakeCaseProjection;
|
||||
}
|
||||
|
||||
const camelCaseProjection =
|
||||
"kernelFileTreeProjection" in result ? result.kernelFileTreeProjection : undefined;
|
||||
if (isKernelFileTreeProjection(camelCaseProjection)) {
|
||||
return camelCaseProjection;
|
||||
}
|
||||
|
||||
if (Array.isArray(result.documents)) {
|
||||
return buildKernelFileTreeProjection({
|
||||
documents: result.documents,
|
||||
mediaAssets: result.media_assets,
|
||||
mindmapAssets: result.mindmap_assets,
|
||||
tableAssets: result.table_assets,
|
||||
mindmapAssetChildren: result.mindmap_asset_children,
|
||||
});
|
||||
}
|
||||
|
||||
return EMPTY_KERNEL_FILE_TREE_PROJECTION;
|
||||
}
|
||||
|
||||
function normalizeStringArray(values: Iterable<string>): string[] {
|
||||
return Array.from(new Set(values)).filter((value) => value.trim().length > 0);
|
||||
}
|
||||
@@ -262,11 +305,19 @@ export function buildSidebarDatasetListQueryResult(
|
||||
): SidebarDatasetListQueryResult {
|
||||
const derived = deriveSidebarDataset(input);
|
||||
const kernelSidebarProjection = buildProjectionContract(input.documents);
|
||||
const kernelFileTreeProjection = buildKernelFileTreeProjection({
|
||||
documents: input.documents,
|
||||
mediaAssets: input.mediaAssets,
|
||||
mindmapAssets: derived.mindmapAssets,
|
||||
tableAssets: derived.tableAssets,
|
||||
mindmapAssetChildren: derived.mindmapAssetChildren,
|
||||
});
|
||||
|
||||
return {
|
||||
active_workspace_id: input.activeWorkspaceId,
|
||||
workspaces: [...input.workspaces],
|
||||
documents: [...input.documents],
|
||||
kernel_file_tree_projection: kernelFileTreeProjection,
|
||||
kernel_sidebar_projection: kernelSidebarProjection,
|
||||
trashed_documents: [...input.trashedDocuments],
|
||||
media_assets: [...(input.mediaAssets ?? [])],
|
||||
@@ -284,6 +335,7 @@ export function mapSidebarDatasetListQueryResultToInitialData(
|
||||
result: SidebarDatasetListQueryResult,
|
||||
): SidebarInitialData {
|
||||
const kernelSidebarProjection = readKernelSidebarProjection(result);
|
||||
const kernelFileTreeProjection = readKernelFileTreeProjection(result);
|
||||
|
||||
return {
|
||||
activeWorkspaceId: result.active_workspace_id,
|
||||
@@ -294,6 +346,7 @@ export function mapSidebarDatasetListQueryResultToInitialData(
|
||||
records: result.documents,
|
||||
projection: kernelSidebarProjection,
|
||||
}),
|
||||
kernelFileTreeProjection,
|
||||
trashedDocuments: [...result.trashed_documents],
|
||||
trashedMediaAssets: [...result.trashed_media_assets],
|
||||
trashedMindmapAssets: [...result.trashed_mindmap_assets],
|
||||
|
||||
@@ -31,6 +31,58 @@ const baseSidebarData: SidebarInitialData = {
|
||||
updated_at: null,
|
||||
},
|
||||
],
|
||||
kernelFileTreeProjection: {
|
||||
projectionId: "kernel_projection:file_tree:root",
|
||||
projection: "file_tree",
|
||||
rootNodeId: null,
|
||||
items: [
|
||||
{
|
||||
rowId: "doc:root",
|
||||
rowKind: "document",
|
||||
nodeId: "root",
|
||||
parentNodeId: null,
|
||||
nodeType: "page",
|
||||
projectionKind: "file_tree",
|
||||
title: "Root",
|
||||
depth: 0,
|
||||
position: 0,
|
||||
childCount: 2,
|
||||
expandable: true,
|
||||
expandedByDefault: true,
|
||||
capabilities: ["expand", "open", "select"],
|
||||
resourceMeta: {
|
||||
resourceKind: "document",
|
||||
documentId: "root",
|
||||
workspaceId: "ws_1",
|
||||
iconHint: "page",
|
||||
},
|
||||
iconHint: "page",
|
||||
},
|
||||
{
|
||||
rowId: "index:root",
|
||||
rowKind: "index",
|
||||
nodeId: "index:root",
|
||||
parentNodeId: "root",
|
||||
nodeType: "index",
|
||||
projectionKind: "file_tree",
|
||||
title: "index.md",
|
||||
depth: 1,
|
||||
position: 0,
|
||||
childCount: 0,
|
||||
expandable: false,
|
||||
expandedByDefault: false,
|
||||
capabilities: ["open", "select"],
|
||||
resourceMeta: {
|
||||
resourceKind: "index",
|
||||
documentId: "root",
|
||||
workspaceId: "ws_1",
|
||||
iconHint: "index",
|
||||
},
|
||||
iconHint: "index",
|
||||
},
|
||||
],
|
||||
edges: [],
|
||||
},
|
||||
kernelSidebarProjection: {
|
||||
projectionId: "kernel_projection:sidebar_tree:workspace_root",
|
||||
projection: "sidebar_tree",
|
||||
@@ -172,6 +224,13 @@ describe("tree-stream/tree-delta", () => {
|
||||
items: [],
|
||||
edges: [],
|
||||
},
|
||||
kernelFileTreeProjection: {
|
||||
projectionId: "kernel_projection:file_tree:root",
|
||||
projection: "file_tree",
|
||||
rootNodeId: null,
|
||||
items: [],
|
||||
edges: [],
|
||||
},
|
||||
kernelSidebarTree: [],
|
||||
trashedDocuments: [],
|
||||
trashedMediaAssets: [],
|
||||
|
||||
@@ -28,6 +28,11 @@ function cloneSidebarData(data: SidebarInitialData): SidebarInitialData {
|
||||
...data,
|
||||
workspaces: [...data.workspaces],
|
||||
documents: [...data.documents],
|
||||
kernelFileTreeProjection: {
|
||||
...data.kernelFileTreeProjection,
|
||||
items: [...data.kernelFileTreeProjection.items],
|
||||
edges: [...data.kernelFileTreeProjection.edges],
|
||||
},
|
||||
kernelSidebarProjection: {
|
||||
...data.kernelSidebarProjection,
|
||||
items: [...data.kernelSidebarProjection.items],
|
||||
|
||||
@@ -51,6 +51,13 @@ describe("tree-stream/protocol", () => {
|
||||
active_workspace_id: "ws_1",
|
||||
workspaces: [],
|
||||
documents: [],
|
||||
kernel_file_tree_projection: {
|
||||
projectionId: "kernel_projection:file_tree:root",
|
||||
projection: "file_tree",
|
||||
rootNodeId: null,
|
||||
items: [],
|
||||
edges: [],
|
||||
},
|
||||
kernel_sidebar_projection: {
|
||||
projectionId: "kernel_projection:sidebar_tree:workspace_root",
|
||||
projection: "sidebar_tree",
|
||||
@@ -101,6 +108,13 @@ describe("tree-stream/protocol", () => {
|
||||
active_workspace_id: "ws_1",
|
||||
workspaces: [],
|
||||
documents: [],
|
||||
kernel_file_tree_projection: {
|
||||
projectionId: "kernel_projection:file_tree:root",
|
||||
projection: "file_tree",
|
||||
rootNodeId: null,
|
||||
items: [],
|
||||
edges: [],
|
||||
},
|
||||
kernel_sidebar_projection: {
|
||||
projectionId: "kernel_projection:sidebar_tree:workspace_root",
|
||||
projection: "sidebar_tree",
|
||||
@@ -121,6 +135,9 @@ describe("tree-stream/protocol", () => {
|
||||
|
||||
expect(snapshot).toMatchObject({
|
||||
activeWorkspaceId: "ws_1",
|
||||
kernelFileTreeProjection: {
|
||||
projection: "file_tree",
|
||||
},
|
||||
kernelSidebarProjection: {
|
||||
projection: "sidebar_tree",
|
||||
},
|
||||
|
||||
Reference in New Issue
Block a user