feat(workspace): integrate persisted canvas, element editing and session renewal

This commit is contained in:
2026-11-06 12:50:43 +08:00
parent 45e78f2e43
commit 373582906d
36 changed files with 1028 additions and 193 deletions
+4
View File
@@ -49,6 +49,10 @@ export const errorText = (error: unknown) => {
version_conflict: "图谱已在别处修改,请再次保存以读取最新版本。",
invalid_profile: "请检查显示名称,以及用户名是否为 3–40 位小写字母、数字、下划线或连字符。",
forbidden: "你没有在此工作空间创建或编辑图谱的权限。",
invalid_canvas: "画布数据未通过服务端校验,请导出备份后检查节点内容。",
invalid_canvas_snapshot: "服务端画布数据格式无效,请重新读取或联系维护者。",
canvas_too_large: "画布超过 5 MiB,请减少图片或拆分画布后重试。",
body_too_large: "画布内容过大,请减少图片或拆分画布。",
invalid_material: "画布名称或内容不符合要求,请修改后重试。",
invalid_reference: "工作空间不存在或当前账户无权访问,请刷新空间列表。",
upstream_timeout: "连接服务超时,请稍后再试。",
+23 -3
View File
@@ -1,6 +1,7 @@
import type { Node, XYPosition } from "@xyflow/react";
export type ElementKind = "text" | "image" | "script" | "plain-text" | "icon";
export type ElementKind = "text" | "image" | "script" | "plain-text" | "icon" | "frame" | "plain-image";
export type FrameLabelMode = "hidden" | "fixed" | "scaled";
export type TextStyle = { color?: string; background?: string; bold?: boolean; italic?: boolean; underline?: boolean; align?: "left" | "center" | "right"; fontFamily?: "sans" | "serif" | "mono"; lineHeight?: number };
export type CanvasNodeData = {
kind: ElementKind;
@@ -11,8 +12,10 @@ export type CanvasNodeData = {
fontSize?: number;
textStyle?: TextStyle;
icon?: string;
frameId?: string;
labelMode?: FrameLabelMode;
};
export type CanvasNode = Node<CanvasNodeData, "material" | "plainText" | "icon">;
export type CanvasNode = Node<CanvasNodeData, "material" | "plainText" | "icon" | "frame" | "plainImage">;
export type ElementCapabilities = { resizable: boolean; rotatable: boolean; connectable: boolean; branchable: boolean };
/** Business inheritance only: React views reuse these capabilities by composition. */
@@ -57,7 +60,24 @@ export class IconElement extends CanvasElement {
override toNode(): CanvasNode { const node = super.toNode(); return { ...node, data: { ...node.data, icon: "Star" } }; }
}
export const elementClasses = { text: TextCardElement, image: ImageCardElement, script: ScriptCardElement, "plain-text": PlainTextElement, icon: IconElement };
export class FrameElement extends CanvasElement {
static override readonly capabilities: ElementCapabilities = { ...CanvasElement.capabilities, rotatable: false };
readonly kind = "frame"; readonly title = "未命名分区";
protected override readonly nodeType = "frame" as const;
protected override readonly size = { width: 640, height: 400 };
override toNode(): CanvasNode {
const node = super.toNode();
return { ...node, zIndex: -1, style: { ...node.style, pointerEvents: "none" }, data: { ...node.data, labelMode: "fixed" } };
}
}
export class PlainImageElement extends CanvasElement {
readonly kind = "plain-image"; readonly title = "图片";
protected override readonly nodeType = "plainImage" as const;
protected override readonly size = { width: 320, height: 240 };
}
export const elementClasses = { text: TextCardElement, image: ImageCardElement, script: ScriptCardElement, "plain-text": PlainTextElement, icon: IconElement, frame: FrameElement, "plain-image": PlainImageElement };
export function elementCapabilities(kind: ElementKind) { return elementClasses[kind].capabilities; }
export function createCanvasElement(kind: ElementKind, position: XYPosition, src?: string): CanvasNode {
return new elementClasses[kind](position, "", src).toNode();
+41
View File
@@ -0,0 +1,41 @@
import type { NodeChange } from "@xyflow/react";
import { applyNodeChanges } from "@xyflow/react";
import type { CanvasNode } from "./canvas-elements.ts";
import { nodeCenter, nodeSize } from "./canvas-geometry.ts";
/** Membership changes only on content drops, never on frame movement or resize. */
export function assignFrameMembership(nodes: CanvasNode[], droppedIds: string[]): CanvasNode[] {
const dropped = new Set(droppedIds);
const frames = nodes.filter((node) => node.data.kind === "frame");
return nodes.map((node) => {
if (!dropped.has(node.id) || node.data.kind === "frame") return node;
const center = nodeCenter(node);
const candidates = frames.filter((frame) => {
const { width, height } = nodeSize(frame);
return center.x >= frame.position.x && center.x <= frame.position.x + width && center.y >= frame.position.y && center.y <= frame.position.y + height;
}).sort((a, b) => nodeSize(a).width * nodeSize(a).height - nodeSize(b).width * nodeSize(b).height);
const frameId = candidates[0]?.id;
if (frameId === node.data.frameId) return node;
const { frameId: _old, ...data } = node.data;
return { ...node, data: { ...data, ...(frameId ? { frameId } : {}) } };
});
}
export function applyFrameNodeChanges(changes: NodeChange<CanvasNode>[], previous: CanvasNode[]) {
const nodes = applyNodeChanges(changes, previous);
const before = new Map(previous.map((node) => [node.id, node]));
const positioned = new Set(changes.flatMap((change) => change.type === "position" && change.position ? [change.id] : []));
const frames = new Map(nodes.filter((node) => node.data.kind === "frame").map((node) => [node.id, node]));
return nodes.map((node) => {
const frameId = node.data.frameId;
if (!frameId) return node;
const frame = frames.get(frameId);
if (!frame) {
const { frameId: _old, ...data } = node.data;
return { ...node, data };
}
const oldFrame = before.get(frameId);
if (!oldFrame || !positioned.has(frameId) || positioned.has(node.id)) return node;
return { ...node, position: { x: node.position.x + frame.position.x - oldFrame.position.x, y: node.position.y + frame.position.y - oldFrame.position.y } };
});
}
+21 -3
View File
@@ -5,8 +5,8 @@ export type ResizeDirection = "top" | "right" | "bottom" | "left" | "top-left" |
export type NodeTransform = { position?: XYPosition; width?: number; height?: number; rotation?: number; fontSize?: number };
export function nodeSize(node: CanvasNode) {
return {
width: node.width || Number(node.style?.width) || node.measured?.width || (node.data.kind === "icon" ? 80 : node.data.kind === "plain-text" ? 240 : 260),
height: node.height || Number(node.style?.height) || node.measured?.height || (node.data.kind === "icon" ? 80 : node.data.kind === "plain-text" ? 72 : 200),
width: node.width || Number(node.style?.width) || node.measured?.width || (node.data.kind === "frame" ? 640 : node.data.kind === "plain-image" ? 320 : node.data.kind === "icon" ? 80 : node.data.kind === "plain-text" ? 240 : 260),
height: node.height || Number(node.style?.height) || node.measured?.height || (node.data.kind === "frame" ? 400 : node.data.kind === "plain-image" ? 240 : node.data.kind === "icon" ? 80 : node.data.kind === "plain-text" ? 72 : 200),
};
}
export function normalizeRotation(angle: number) { return ((angle % 360) + 360) % 360; }
@@ -33,7 +33,7 @@ export function resizeFromPointer(node: CanvasNode, direction: ResizeDirection,
const horizontal = direction.includes("left") ? -1 : direction.includes("right") ? 1 : 0;
const vertical = direction.includes("top") ? -1 : direction.includes("bottom") ? 1 : 0;
const plain = node.data.kind === "plain-text";
const icon = node.data.kind === "icon";
const icon = node.data.kind === "icon" || node.data.kind === "plain-image";
let nextWidth = Math.max(plain ? 60 : 140, Math.min(3000, width + horizontal * local.x));
let nextHeight = Math.max(plain ? 24 : 100, Math.min(3000, height + vertical * local.y));
if (icon) {
@@ -51,3 +51,21 @@ export function resizeFromPointer(node: CanvasNode, direction: ResizeDirection,
width: nextWidth, height: nextHeight,
};
}
export type ConnectorSide = "top" | "right" | "bottom" | "left";
export type Connector = { point: XYPosition; normal: XYPosition };
/** Attach to the card border itself, independent of the handle's hit area. */
export function nodeConnector(node: CanvasNode, side: ConnectorSide): Connector {
const { width, height } = nodeSize(node);
const vectors = { top: { x: 0, y: -1 }, right: { x: 1, y: 0 }, bottom: { x: 0, y: 1 }, left: { x: -1, y: 0 } };
const local = vectors[side];
const angle = node.data.rotation || 0;
const normal = rotateVector(local, angle);
const offset = rotateVector({ x: local.x * width / 2, y: local.y * height / 2 }, angle);
const center = nodeCenter(node);
return { point: { x: center.x + offset.x, y: center.y + offset.y }, normal };
}
export function connectorBezier(from: Connector, to: Connector) {
const reach = Math.min(240, Math.max(40, Math.hypot(to.point.x - from.point.x, to.point.y - from.point.y) * 0.4));
return `M ${from.point.x},${from.point.y} C ${from.point.x + from.normal.x * reach},${from.point.y + from.normal.y * reach} ${to.point.x + to.normal.x * reach},${to.point.y + to.normal.y * reach} ${to.point.x},${to.point.y}`;
}
+9
View File
@@ -0,0 +1,9 @@
import { decodeSnapshot, type CanvasSnapshot, type CanvasRequest } from "./canvas-sync.ts";
import { matchesRef, type Board } from "./workspace.ts";
export async function loadBoardCanvas(request: CanvasRequest, workspaceRef: string, boardRef: string, signal?: AbortSignal) {
const path = `workspaces/${encodeURIComponent(workspaceRef)}/materials/${encodeURIComponent(boardRef)}`;
const [board, snapshot] = await Promise.all([request<Board>(path, { signal }), request<CanvasSnapshot>(path + "/canvas", { signal })]);
if (board.kind !== "board" || !matchesRef(board, boardRef) || typeof board.workspace_id !== "string" || !board.workspace_id) throw new Error("invalid_reference");
return { board, snapshot: decodeSnapshot(snapshot) };
}
+77
View File
@@ -0,0 +1,77 @@
import { decodeCanvas, type CanvasDocument } from "./canvas.ts";
export type CanvasSnapshot = { version: number; document: CanvasDocument };
export type CanvasRequest = <T>(path: string, options?: RequestInit) => Promise<T>;
export type SyncState = { status: "saved" | "saving" | "error"; version: number; error?: string };
export function canvasPath(workspace: string, board: string) {
return `workspaces/${encodeURIComponent(workspace)}/materials/${encodeURIComponent(board)}/canvas`;
}
export function canvasPayload(document: CanvasDocument) {
const clean = decodeCanvas(JSON.stringify(document));
return { ...clean, nodes: clean.nodes.map(({ id, type, position, width, height, data }) => ({ id, type, position, ...(width !== undefined ? { width, height } : {}), data })) };
}
export function canvasFingerprint(document: CanvasDocument) {
return JSON.stringify(canvasPayload(document), (_key, value) => value && typeof value === "object" && !Array.isArray(value) ? Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b))) : value);
}
export function decodeSnapshot(value: CanvasSnapshot): CanvasSnapshot {
if (!Number.isSafeInteger(value?.version) || value.version < 1) throw new Error("invalid_canvas_snapshot");
return { version: value.version, document: decodeCanvas(JSON.stringify(value.document)) };
}
/** One writer per board. Coalesce pending snapshots; stop on any rejected write. */
export class CanvasSync {
version: number;
saved: string;
error = "";
private pending: CanvasDocument | null = null;
private running: Promise<void> | null = null;
private request: CanvasRequest;
private path: string;
private notify: (state: SyncState) => void;
constructor(request: CanvasRequest, path: string, initial: CanvasSnapshot, notify: (state: SyncState) => void) {
this.request = request; this.path = path; this.version = initial.version;
this.saved = canvasFingerprint(initial.document); this.notify = notify;
}
enqueue(document: CanvasDocument): Promise<void> {
this.pending = document;
if (this.error) return Promise.resolve();
if (!this.running) this.running = Promise.resolve().then(() => this.drain()).finally(() => { this.running = null; if (this.pending && !this.error) void this.enqueue(this.pending); });
return this.running;
}
retry() { this.error = ""; return this.pending ? this.enqueue(this.pending) : Promise.resolve(); }
private async drain() {
while (this.pending) {
const document = this.pending; this.pending = null;
this.notify({ status: "saving", version: this.version });
try {
const fingerprint = canvasFingerprint(document);
if (fingerprint === this.saved) { this.notify({ status: "saved", version: this.version }); continue; }
const body = JSON.stringify({ document: canvasPayload(document) });
if (new TextEncoder().encode(body).length > 5 * 1024 * 1024) throw new Error("canvas_too_large");
const result = await this.request<{ version: number }>(this.path, { method: "PATCH", headers: { "If-Match": `"${this.version}"` }, body });
if (!Number.isSafeInteger(result?.version) || result.version !== this.version + 1) throw new Error("invalid_canvas_snapshot");
this.version = result.version; this.saved = fingerprint;
this.notify({ status: "saved", version: this.version });
} catch (error) {
this.pending ||= document;
this.error = error instanceof Error ? error.message : "request_failed";
this.notify({ status: "error", version: this.version, error: this.error });
return;
}
}
}
}
export function readLocalRecovery(storage: Pick<Storage, "getItem">, key: string, snapshot?: CanvasSnapshot): CanvasDocument | null {
const record = storage.getItem(key + ":recovery");
if (record) {
const value = JSON.parse(record);
const doc = decodeCanvas(JSON.stringify(value.document));
if (!snapshot || (value.dirty && canvasFingerprint(doc) !== canvasFingerprint(snapshot.document))) return doc;
return null;
}
const legacy = storage.getItem(key);
if (!legacy) return null;
const doc = decodeCanvas(legacy);
return !snapshot || canvasFingerprint(doc) !== canvasFingerprint(snapshot.document) ? doc : null;
}
+20 -7
View File
@@ -1,6 +1,7 @@
import { applyEdgeChanges, applyNodeChanges } from "@xyflow/react";
import { applyEdgeChanges } from "@xyflow/react";
import type { Edge, EdgeChange, NodeChange, Viewport, XYPosition } from "@xyflow/react";
import { applyFrameNodeChanges, assignFrameMembership } from "./canvas-frames.ts";
import { createCanvasElement, elementCapabilities, type CanvasNode } from "./canvas-elements.ts";
import { nodeSize, rotateVector, nodeCenter, type NodeTransform } from "./canvas-geometry.ts";
export type { CanvasNode } from "./canvas-elements.ts";
@@ -10,6 +11,9 @@ export type CanvasDocument = { schema_version: 1; nodes: CanvasNode[]; edges: Ed
export type CanvasHistory = { past: CanvasDocument[]; present: CanvasDocument; future: CanvasDocument[] };
export type CanvasAction =
| { type: "checkpoint" }
| { type: "drop"; ids: string[] }
| { type: "rename-node"; id: string; title: string }
| { type: "frame"; id: string; title?: string; labelMode?: import("./canvas-elements.ts").FrameLabelMode }
| { type: "replace"; document: CanvasDocument }
| { type: "nodes"; changes: NodeChange<CanvasNode>[] }
| { type: "edges"; changes: EdgeChange[] }
@@ -30,10 +34,13 @@ function recorded(state: CanvasHistory, present: CanvasDocument): CanvasHistory
}
export function canvasReducer(state: CanvasHistory, action: CanvasAction): CanvasHistory {
switch (action.type) {
case "drop": return { ...state, present: { ...state.present, nodes: assignFrameMembership(state.present.nodes, action.ids) } };
case "rename-node": return recorded(state, { ...state.present, nodes: state.present.nodes.map((node) => node.id === action.id ? { ...node, data: { ...node.data, title: action.title } } : node) });
case "frame": return recorded(state, { ...state.present, nodes: state.present.nodes.map((node) => node.id === action.id && node.data.kind === "frame" ? { ...node, data: { ...node.data, ...(action.title !== undefined ? { title: action.title } : {}), ...(action.labelMode ? { labelMode: action.labelMode } : {}) } } : node) });
case "checkpoint": return recorded(state, state.present);
case "replace": return recorded(state, action.document);
case "nodes": {
const nodes = applyNodeChanges(action.changes, state.present.nodes);
const nodes = applyFrameNodeChanges(action.changes, state.present.nodes);
const ids = new Set(nodes.map((node) => node.id));
const present = { ...state.present, nodes, edges: state.present.edges.filter((edge) => ids.has(edge.source) && ids.has(edge.target)) };
return action.changes.some((change) => change.type === "remove" || change.type === "add")
@@ -137,8 +144,8 @@ export function decodeCanvas(raw: string): CanvasDocument {
const nodes: CanvasNode[] = value.nodes.map((node: CanvasNode) => {
if (!node || typeof node.id !== "string" || !/^[\w-]{1,128}$/.test(node.id) || ids.has(node.id) || !node.position ||
![node.position.x, node.position.y].every((n) => Number.isFinite(n) && Math.abs(n) <= 1_000_000) ||
!node.data || !["text", "image", "script", "plain-text", "icon"].includes(node.data.kind) || typeof node.data.title !== "string" || node.data.title.length > 300 ||
typeof node.data.text !== "string" || node.data.text.length > 100_000 || (node.data.kind === "image" && !validImage(node.data.src)))
!node.data || !["text", "image", "script", "plain-text", "icon", "frame", "plain-image"].includes(node.data.kind) || typeof node.data.title !== "string" || node.data.title.length > 300 ||
typeof node.data.text !== "string" || node.data.text.length > 100_000 || (["image", "plain-image"].includes(node.data.kind) && !validImage(node.data.src)))
throw new Error("图谱节点格式无效。");
const width = node.width ?? node.style?.width;
const height = node.height ?? node.style?.height;
@@ -148,15 +155,21 @@ export function decodeCanvas(raw: string): CanvasDocument {
(node.data.fontSize !== undefined && (!Number.isFinite(node.data.fontSize) || node.data.fontSize < 8 || node.data.fontSize > 160)))
throw new Error("节点大小或旋转角度无效。");
if (node.data.kind === "icon" && (typeof node.data.icon !== "string" || !/^[A-Z][A-Za-z0-9]{0,63}$/.test(node.data.icon))) throw new Error("图标标识无效。");
if (node.data.frameId !== undefined && (node.data.kind === "frame" || typeof node.data.frameId !== "string" || !/^[\w-]{1,128}$/.test(node.data.frameId))) throw new Error("分区归属无效。");
if (node.data.kind === "frame" && ((node.data.labelMode !== undefined && !["hidden", "fixed", "scaled"].includes(node.data.labelMode)) || (node.data.rotation || 0) !== 0)) throw new Error("分区设置无效。");
const textStyle = decodeTextStyle(node.data.textStyle);
ids.add(node.id);
return { id: node.id, type: node.data.kind === "plain-text" ? "plainText" : node.data.kind === "icon" ? "icon" : "material",
...(width !== undefined && height !== undefined ? { width, height, style: { width, height } } : {}), position: { x: node.position.x, y: node.position.y }, data: {
return { id: node.id, type: node.data.kind === "plain-text" ? "plainText" : node.data.kind === "icon" ? "icon" : node.data.kind === "frame" ? "frame" : node.data.kind === "plain-image" ? "plainImage" : "material",
...(width !== undefined && height !== undefined ? { width, height, style: { width, height } } : {}), ...(node.data.kind === "frame" ? { zIndex: -1, style: { ...(width !== undefined ? { width, height } : {}), pointerEvents: "none" as const } } : {}),
position: { x: node.position.x, y: node.position.y }, data: {
...(node.data.frameId ? { frameId: node.data.frameId } : {}), ...(node.data.kind === "frame" ? { labelMode: node.data.labelMode || "fixed" } : {}),
...(textStyle ? { textStyle } : {}), ...(node.data.kind === "icon" ? { icon: node.data.icon } : {}),
kind: node.data.kind, title: node.data.title, text: node.data.text,
rotation: node.data.rotation || 0, fontSize: node.data.fontSize || (node.data.kind === "plain-text" ? 24 : 13), ...(node.data.kind === "image" ? { src: node.data.src } : {}),
rotation: node.data.rotation || 0, fontSize: node.data.fontSize || (node.data.kind === "plain-text" ? 24 : 13), ...(["image", "plain-image"].includes(node.data.kind) ? { src: node.data.src } : {}),
} };
});
const frameIds = new Set(nodes.filter((node) => node.data.kind === "frame").map((node) => node.id));
if (nodes.some((node) => node.data.frameId && !frameIds.has(node.data.frameId))) throw new Error("分区归属不存在。");
const nodeKinds = new Map(nodes.map((node) => [node.id, node.data.kind]));
const edgeIds = new Set<string>();
const edges: Edge[] = value.edges.map((edge: Edge) => {
+9
View File
@@ -0,0 +1,9 @@
export const SESSION_IDLE_SECONDS = 30 * 24 * 60 * 60;
export const SESSION_EXPIRY_HEADER = "X-Foundry-Session-Expires-In";
export function sessionMaxAge(value: unknown, fallback = SESSION_IDLE_SECONDS) {
const seconds = typeof value === "number" ? value : typeof value === "string" && /^\d+$/.test(value) ? Number(value) : NaN;
return Number.isSafeInteger(seconds) && seconds >= 0 ? Math.min(seconds, SESSION_IDLE_SECONDS) : fallback;
}
export function sessionCookie(value: string, maxAge: number, secure: boolean) {
return `foundry_session=${encodeURIComponent(value)}; HttpOnly; SameSite=Lax; Path=/; Max-Age=${sessionMaxAge(maxAge)}${secure ? "; Secure" : ""}`;
}
+5 -3
View File
@@ -1,15 +1,17 @@
import type { Profile } from "./api";
export type Workspace = { id: string; name: string; role?: "admin" | "editor" | "viewer" };
export type Workspace = { id: string; slug?: string; name: string; role?: "admin" | "editor" | "viewer" };
export type Board = {
id: string;
workspace_id: string;
slug?: string;
kind: "board";
title: string;
version: number;
content?: { schema_version: number };
description?: string;
};
export function matchesRef(item: { id: string; slug?: string } | null | undefined, ref: string | undefined) { return Boolean(item && ref && (item.id === ref || item.slug === ref)); }
export const DEFAULT_BOARD_TITLE = "未命名图谱";
export function boardHref(workspace: string, board: string, demo = false) {
@@ -47,7 +49,7 @@ export async function createBoard(
onWorkspaceCreated(workspace);
}
const name = title.trim() || DEFAULT_BOARD_TITLE;
const result = await request<{ id: string; workspace_id: string; kind: "board"; version: number }>("workspaces/" + id + "/materials", {
const result = await request<{ id: string; workspace_id: string; kind: "board"; version: number; slug?: string }>("workspaces/" + id + "/materials", {
method: "POST",
body: JSON.stringify({
kind: "board",
@@ -64,7 +66,7 @@ export async function renameBoard(request: Request, workspaceId: string, boardId
if (!name || new TextEncoder().encode(name).length > 300) throw new Error("invalid_title");
const path = `workspaces/${encodeURIComponent(workspaceId)}/materials/${encodeURIComponent(boardId)}`;
const current = await request<Board>(path);
if (current.kind !== "board" || current.id !== boardId || current.workspace_id !== workspaceId) throw new Error("invalid_reference");
if (current.kind !== "board" || !matchesRef(current, boardId) || current.workspace_id !== workspaceId) throw new Error("invalid_reference");
await request(path, {
method: "PATCH",
headers: { "If-Match": `"${current.version}"` },