perf(canvas): 画布渲染 - 降低大画布节点开销
This commit is contained in:
@@ -6,6 +6,7 @@ import { CometCard } from "@/components/ui/aceternity/comet-card";
|
||||
import { CanvasFolderPreview } from "@/components/canvas/canvas-folder-preview";
|
||||
import { CanvasVideoPreviewImage } from "@/components/canvas/canvas-video-preview-image";
|
||||
import { FRAME_HEADER_HEIGHT, FRAME_PADDING, isCanvasFolderNode } from "@/lib/canvas/canvas-frame";
|
||||
import type { CanvasNodeRenderLOD } from "@/lib/canvas/canvas-node-lod";
|
||||
import { canvasThemes, type CanvasTheme } from "@/lib/canvas-theme";
|
||||
import { useActiveTheme } from "@/stores/canvas/use-canvas-theme-store";
|
||||
import { CanvasNodeType, type CanvasFolderStyle, type CanvasFolderTheme, type CanvasNodeData, type Position } from "@/types/canvas";
|
||||
@@ -14,6 +15,7 @@ type ResizeCorner = "top-left" | "top-right" | "bottom-left" | "bottom-right";
|
||||
|
||||
export const CanvasFrameNode = React.memo(function CanvasFrameNode({
|
||||
data,
|
||||
renderLOD = "full",
|
||||
dragOffset,
|
||||
childNodes,
|
||||
scale,
|
||||
@@ -33,6 +35,7 @@ export const CanvasFrameNode = React.memo(function CanvasFrameNode({
|
||||
data: CanvasNodeData;
|
||||
dragOffset?: Position;
|
||||
childNodes: CanvasNodeData[];
|
||||
renderLOD?: CanvasNodeRenderLOD;
|
||||
scale: number;
|
||||
isSelected: boolean;
|
||||
isDropTarget: boolean;
|
||||
@@ -51,6 +54,7 @@ export const CanvasFrameNode = React.memo(function CanvasFrameNode({
|
||||
const collapsed = Boolean(data.metadata?.frame?.collapsed);
|
||||
const folder = isCanvasFolderNode(data);
|
||||
const [editing, setEditing] = useState(false);
|
||||
const [hovered, setHovered] = useState(false);
|
||||
const [title, setTitle] = useState(data.title);
|
||||
const resizeRef = useRef({
|
||||
active: false,
|
||||
@@ -148,10 +152,12 @@ export const CanvasFrameNode = React.memo(function CanvasFrameNode({
|
||||
|
||||
const active = isSelected || isDropTarget;
|
||||
const linkedFolder = Boolean(data.metadata?.folder?.assetFolderId);
|
||||
const fullDetail = renderLOD === "full" || hovered || editing;
|
||||
|
||||
return (
|
||||
<div
|
||||
data-node-id={data.id}
|
||||
data-node-lod={fullDetail ? "full" : renderLOD}
|
||||
role={folder && collapsed ? "group" : undefined}
|
||||
tabIndex={folder && collapsed ? 0 : undefined}
|
||||
aria-label={folder && collapsed ? `${data.title},文件夹,${childNodes.length} 项内容。按回车打开` : undefined}
|
||||
@@ -170,8 +176,8 @@ export const CanvasFrameNode = React.memo(function CanvasFrameNode({
|
||||
event.preventDefault();
|
||||
onToggleCollapsed(data.id);
|
||||
}}
|
||||
onMouseEnter={() => onHoverStart?.(data.id)}
|
||||
onMouseLeave={() => onHoverEnd?.(data.id)}
|
||||
onMouseEnter={() => { setHovered(true); onHoverStart?.(data.id); }}
|
||||
onMouseLeave={() => { setHovered(false); onHoverEnd?.(data.id); }}
|
||||
>
|
||||
{/* 帧节点同样禁用指针跟随 3D 位移,hover 使用 CSS 静态抬升 */}
|
||||
<CometCard
|
||||
@@ -183,10 +189,14 @@ export const CanvasFrameNode = React.memo(function CanvasFrameNode({
|
||||
background: folder && collapsed ? "transparent" : active ? theme.frame.activeFill : theme.frame.fill,
|
||||
borderColor: folder && collapsed ? "transparent" : active ? theme.frame.activeStroke : theme.frame.stroke,
|
||||
borderWidth: folder && collapsed ? 0 : 1 / Math.max(scale, 0.05),
|
||||
boxShadow: folder && collapsed ? "none" : isSelected ? `0 0 0 ${1 / Math.max(scale, 0.05)}px ${theme.frame.activeStroke}33, 0 24px 72px ${theme.spatial.shadow}` : `0 18px 54px ${theme.spatial.shadow}`,
|
||||
boxShadow: !fullDetail || (folder && collapsed) ? "none" : isSelected ? `0 0 0 ${1 / Math.max(scale, 0.05)}px ${theme.frame.activeStroke}33, 0 24px 72px ${theme.spatial.shadow}` : `0 18px 54px ${theme.spatial.shadow}`,
|
||||
}}
|
||||
>
|
||||
{folder && collapsed ? (
|
||||
{!fullDetail ? (
|
||||
<div className="flex h-full items-center justify-center rounded-[var(--node-radius)]" style={{ background: theme.frame.fill, color: theme.node.text }}>
|
||||
{data.title} · {childNodes.length}
|
||||
</div>
|
||||
) : folder && collapsed ? (
|
||||
// 素材库目录是单一事实源;画布节点只负责浏览和调用,避免本地改名后被同步结果覆盖。
|
||||
<CanvasFolderPreview
|
||||
data={data}
|
||||
|
||||
@@ -1,133 +1,87 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState, type RefObject } from "react";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState, type PointerEvent as ReactPointerEvent, type RefObject } from "react";
|
||||
|
||||
import { CachedResourceImage } from "@/components/cached-resource-image";
|
||||
import { canvasThemes } from "@/lib/canvas-theme";
|
||||
import { isFrameNode, isNodeHiddenByCollapsedFrame } from "@/lib/canvas/canvas-frame";
|
||||
import { buildLibTVImagePreviewUrl } from "@/lib/canvas/libtv-import";
|
||||
import { getNodeLabel } from "@/lib/canvas/node-registry/node-registry";
|
||||
import { subscribeCanvasViewportPreview } from "@/lib/canvas/canvas-live-viewport";
|
||||
import { useActiveTheme } from "@/stores/canvas/use-canvas-theme-store";
|
||||
import { CanvasNodeType, type CanvasNodeData, type ViewportTransform } from "@/types/canvas";
|
||||
|
||||
const MINIMAP_WIDTH = 240;
|
||||
const MINIMAP_HEIGHT = 160;
|
||||
const MINIMAP_IMAGE_PREVIEW_LIMIT = 24;
|
||||
|
||||
export function Minimap({ nodes, viewport, viewportSize, canvasContainerRef, onViewportPreviewChange, onViewportChange }: { nodes: CanvasNodeData[]; viewport: ViewportTransform; viewportSize: { width: number; height: number }; canvasContainerRef?: RefObject<HTMLDivElement | null>; onViewportPreviewChange?: (viewport: ViewportTransform) => void; onViewportChange: (viewport: ViewportTransform) => void }) {
|
||||
type MinimapProps = {
|
||||
nodes: CanvasNodeData[];
|
||||
viewport: ViewportTransform;
|
||||
viewportSize: { width: number; height: number };
|
||||
canvasContainerRef?: RefObject<HTMLDivElement | null>;
|
||||
onViewportPreviewChange?: (viewport: ViewportTransform) => void;
|
||||
onViewportChange: (viewport: ViewportTransform) => void;
|
||||
};
|
||||
|
||||
export function Minimap({ nodes, viewport, viewportSize, canvasContainerRef, onViewportPreviewChange, onViewportChange }: MinimapProps) {
|
||||
const theme = canvasThemes[useActiveTheme()];
|
||||
const containerRef = useRef<HTMLDivElement>(null);
|
||||
const viewportRectRef = useRef<HTMLDivElement>(null);
|
||||
const canvasRef = useRef<HTMLCanvasElement>(null);
|
||||
const liveViewportRef = useRef(viewport);
|
||||
const [isDragging, setIsDragging] = useState(false);
|
||||
const width = MINIMAP_WIDTH;
|
||||
const height = MINIMAP_HEIGHT;
|
||||
const displayNodes = useMemo(() => nodes.filter((node) => !isNodeHiddenByCollapsedFrame(node, nodes)), [nodes]);
|
||||
const showImagePreviews = useMemo(() => displayNodes.filter((node) => node.type === CanvasNodeType.Image && Boolean(getImagePreviewSource(node) || node.metadata?.storageKey)).length <= MINIMAP_IMAGE_PREVIEW_LIMIT, [displayNodes]);
|
||||
|
||||
const { worldBounds, scale, offset } = useMemo(() => {
|
||||
if (!displayNodes.length) {
|
||||
return { worldBounds: { x: -500, y: -500, w: 1000, h: 1000 }, scale: 0.16, offset: { x: 40, y: 0 } };
|
||||
}
|
||||
|
||||
if (!displayNodes.length) return { worldBounds: { x: -500, y: -500, w: 1000, h: 1000 }, scale: 0.16, offset: { x: 40, y: 0 } };
|
||||
let minX = Infinity;
|
||||
let minY = Infinity;
|
||||
let maxX = -Infinity;
|
||||
let maxY = -Infinity;
|
||||
|
||||
displayNodes.forEach((node) => {
|
||||
minX = Math.min(minX, node.position.x);
|
||||
minY = Math.min(minY, node.position.y);
|
||||
maxX = Math.max(maxX, node.position.x + node.width);
|
||||
maxY = Math.max(maxY, node.position.y + node.height);
|
||||
});
|
||||
|
||||
minX -= 500;
|
||||
minY -= 500;
|
||||
maxX += 500;
|
||||
maxY += 500;
|
||||
|
||||
const boundsWidth = maxX - minX;
|
||||
const boundsHeight = maxY - minY;
|
||||
const boundsWidth = Math.max(maxX - minX, 1);
|
||||
const boundsHeight = Math.max(maxY - minY, 1);
|
||||
const nextScale = Math.min(width / boundsWidth, height / boundsHeight);
|
||||
const mapContentW = boundsWidth * nextScale;
|
||||
const mapContentH = boundsHeight * nextScale;
|
||||
|
||||
return {
|
||||
worldBounds: { x: minX, y: minY, w: boundsWidth, h: boundsHeight },
|
||||
scale: nextScale,
|
||||
offset: { x: (width - mapContentW) / 2, y: (height - mapContentH) / 2 },
|
||||
offset: { x: (width - boundsWidth * nextScale) / 2, y: (height - boundsHeight * nextScale) / 2 },
|
||||
};
|
||||
}, [displayNodes]);
|
||||
|
||||
const toMinimap = useCallback(
|
||||
(worldX: number, worldY: number) => {
|
||||
return {
|
||||
x: (worldX - worldBounds.x) * scale + offset.x,
|
||||
y: (worldY - worldBounds.y) * scale + offset.y,
|
||||
};
|
||||
},
|
||||
[offset.x, offset.y, scale, worldBounds.x, worldBounds.y],
|
||||
);
|
||||
|
||||
const toWorld = useCallback(
|
||||
(minimapX: number, minimapY: number) => {
|
||||
return {
|
||||
x: (minimapX - offset.x) / scale + worldBounds.x,
|
||||
y: (minimapY - offset.y) / scale + worldBounds.y,
|
||||
};
|
||||
},
|
||||
[offset.x, offset.y, scale, worldBounds.x, worldBounds.y],
|
||||
);
|
||||
|
||||
}, [displayNodes, height, width]);
|
||||
const toMinimap = useCallback((worldX: number, worldY: number) => ({ x: (worldX - worldBounds.x) * scale + offset.x, y: (worldY - worldBounds.y) * scale + offset.y }), [offset.x, offset.y, scale, worldBounds.x, worldBounds.y]);
|
||||
const toWorld = useCallback((minimapX: number, minimapY: number) => ({ x: (minimapX - offset.x) / scale + worldBounds.x, y: (minimapY - offset.y) / scale + worldBounds.y }), [offset.x, offset.y, scale, worldBounds.x, worldBounds.y]);
|
||||
const viewportRect = useMemo(() => {
|
||||
const vx = -viewport.x / viewport.k;
|
||||
const vy = -viewport.y / viewport.k;
|
||||
const vw = viewportSize.width / viewport.k;
|
||||
const vh = viewportSize.height / viewport.k;
|
||||
const p1 = toMinimap(vx, vy);
|
||||
const p2 = toMinimap(vx + vw, vy + vh);
|
||||
|
||||
return {
|
||||
x: p1.x,
|
||||
y: p1.y,
|
||||
w: Math.max(p2.x - p1.x, 4),
|
||||
h: Math.max(p2.y - p1.y, 4),
|
||||
};
|
||||
const p2 = toMinimap(vx + viewportSize.width / viewport.k, vy + viewportSize.height / viewport.k);
|
||||
return { x: p1.x, y: p1.y, w: Math.max(p2.x - p1.x, 4), h: Math.max(p2.y - p1.y, 4) };
|
||||
}, [toMinimap, viewport.k, viewport.x, viewport.y, viewportSize.height, viewportSize.width]);
|
||||
|
||||
const updateViewportRect = useCallback((nextViewport: ViewportTransform) => {
|
||||
liveViewportRef.current = nextViewport;
|
||||
const element = viewportRectRef.current;
|
||||
if (!element) return;
|
||||
const vx = -nextViewport.x / nextViewport.k;
|
||||
const vy = -nextViewport.y / nextViewport.k;
|
||||
const p1 = toMinimap(vx, vy);
|
||||
const p2 = toMinimap(vx + viewportSize.width / nextViewport.k, vy + viewportSize.height / nextViewport.k);
|
||||
element.style.left = `${p1.x}px`;
|
||||
element.style.top = `${p1.y}px`;
|
||||
element.style.width = `${Math.max(p2.x - p1.x, 4)}px`;
|
||||
element.style.height = `${Math.max(p2.y - p1.y, 4)}px`;
|
||||
}, [toMinimap, viewportSize.height, viewportSize.width]);
|
||||
drawMinimap(canvasRef.current, displayNodes, toMinimap, nextViewport, viewportSize, theme);
|
||||
}, [displayNodes, theme, toMinimap, viewportSize]);
|
||||
|
||||
useEffect(() => {
|
||||
drawMinimap(canvasRef.current, displayNodes, toMinimap, viewport, viewportSize, theme);
|
||||
}, [displayNodes, theme, toMinimap, viewport, viewportSize]);
|
||||
useEffect(() => updateViewportRect(viewport), [updateViewportRect, viewport]);
|
||||
|
||||
useEffect(() => {
|
||||
const canvasContainer = canvasContainerRef?.current;
|
||||
if (!canvasContainer) return;
|
||||
return subscribeCanvasViewportPreview(canvasContainer, updateViewportRect);
|
||||
}, [canvasContainerRef, updateViewportRect]);
|
||||
|
||||
const updateViewportFromEvent = (event: React.PointerEvent) => {
|
||||
const updateViewportFromEvent = (event: ReactPointerEvent) => {
|
||||
const rect = containerRef.current?.getBoundingClientRect();
|
||||
if (!rect) return;
|
||||
|
||||
const world = toWorld(event.clientX - rect.left, event.clientY - rect.top);
|
||||
const scale = liveViewportRef.current.k;
|
||||
const next = {
|
||||
x: viewportSize.width / 2 - world.x * scale,
|
||||
y: viewportSize.height / 2 - world.y * scale,
|
||||
k: scale,
|
||||
};
|
||||
const current = liveViewportRef.current;
|
||||
const next = { x: viewportSize.width / 2 - world.x * current.k, y: viewportSize.height / 2 - world.y * current.k, k: current.k };
|
||||
liveViewportRef.current = next;
|
||||
onViewportPreviewChange?.(next);
|
||||
};
|
||||
@@ -155,59 +109,37 @@ export function Minimap({ nodes, viewport, viewportSize, canvasContainerRef, onV
|
||||
onViewportChange(liveViewportRef.current);
|
||||
}}
|
||||
>
|
||||
{displayNodes.map((node) => {
|
||||
const pos = toMinimap(node.position.x, node.position.y);
|
||||
const frame = isFrameNode(node);
|
||||
const color = node.type === CanvasNodeType.Image ? "#10b981" : node.type === CanvasNodeType.Video ? "#f97316" : node.type === CanvasNodeType.Audio ? "#a855f7" : node.type === CanvasNodeType.Config ? "#60a5fa" : node.type === CanvasNodeType.Skill ? "#818cf8" : frame ? theme.frame.stroke : theme.node.muted;
|
||||
const imagePreviewSource = showImagePreviews && node.type === CanvasNodeType.Image ? getImagePreviewSource(node) : "";
|
||||
const nodeLabel = node.title?.trim() || getNodeLabel(node.type);
|
||||
return (
|
||||
<div
|
||||
key={node.id}
|
||||
className="absolute rounded-[1px]"
|
||||
style={{
|
||||
left: pos.x,
|
||||
top: pos.y,
|
||||
width: Math.max(node.width * scale, 2),
|
||||
height: Math.max(node.height * scale, 2),
|
||||
backgroundColor: frame ? (node.metadata?.frame?.collapsed ? theme.frame.preview : "transparent") : color,
|
||||
border: frame ? `1px solid ${color}` : undefined,
|
||||
opacity: frame ? 0.95 : 0.8,
|
||||
}}
|
||||
>
|
||||
<div className="absolute inset-0 overflow-hidden rounded-[1px]">
|
||||
{imagePreviewSource || (showImagePreviews && node.type === CanvasNodeType.Image && node.metadata?.storageKey) ? (
|
||||
<CachedResourceImage
|
||||
storageKey={node.metadata?.storageKey}
|
||||
src={imagePreviewSource}
|
||||
alt=""
|
||||
loading="lazy"
|
||||
decoding="async"
|
||||
draggable={false}
|
||||
className="size-full object-cover"
|
||||
fallback={null}
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
<span
|
||||
title={nodeLabel}
|
||||
aria-label={nodeLabel}
|
||||
className="pointer-events-none absolute left-0 top-0 z-[1] max-w-[7.5rem] -translate-y-1/2 truncate whitespace-nowrap rounded-[2px] border px-1 py-px text-[9px] font-medium leading-[1.15] shadow-sm"
|
||||
style={{ color: theme.node.text, background: theme.toolbar.panel, borderColor: theme.toolbar.border }}
|
||||
>
|
||||
{nodeLabel}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
<div ref={viewportRectRef} className="pointer-events-none absolute rounded-[var(--r-xs)]" style={{ left: viewportRect.x, top: viewportRect.y, width: viewportRect.w, height: viewportRect.h, background: `${theme.node.activeStroke}12`, boxShadow: `inset 0 0 0 1px ${theme.node.activeStroke}66` }} />
|
||||
<canvas ref={canvasRef} width={width} height={height} className="pointer-events-none block size-full" aria-label="画布小地图" />
|
||||
<div className="pointer-events-none absolute rounded-[var(--r-xs)]" style={{ left: viewportRect.x, top: viewportRect.y, width: viewportRect.w, height: viewportRect.h, background: `${theme.node.activeStroke}12`, boxShadow: `inset 0 0 0 1px ${theme.node.activeStroke}66` }} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function getImagePreviewSource(node: CanvasNodeData) {
|
||||
if (node.type !== CanvasNodeType.Image) return "";
|
||||
const content = node.metadata?.content || "";
|
||||
return node.metadata?.previewContent || (node.metadata?.importSource?.provider === "libtv" ? buildLibTVImagePreviewUrl(content) : content);
|
||||
function drawMinimap(canvas: HTMLCanvasElement | null, nodes: CanvasNodeData[], toMinimap: (x: number, y: number) => { x: number; y: number }, viewport: ViewportTransform, viewportSize: { width: number; height: number }, theme: (typeof canvasThemes)[keyof typeof canvasThemes]) {
|
||||
if (!canvas) return;
|
||||
const context = canvas.getContext("2d");
|
||||
if (!context) return;
|
||||
context.clearRect(0, 0, canvas.width, canvas.height);
|
||||
for (const node of nodes) {
|
||||
const pos = toMinimap(node.position.x, node.position.y);
|
||||
const frame = isFrameNode(node);
|
||||
const color = node.type === CanvasNodeType.Image ? "#10b981" : node.type === CanvasNodeType.Video ? "#f97316" : node.type === CanvasNodeType.Audio ? "#a855f7" : node.type === CanvasNodeType.Config ? "#60a5fa" : node.type === CanvasNodeType.Skill ? "#818cf8" : frame ? theme.frame.stroke : theme.node.muted;
|
||||
const p2 = toMinimap(node.position.x + node.width, node.position.y + node.height);
|
||||
const rectWidth = Math.max(p2.x - pos.x, 2);
|
||||
const rectHeight = Math.max(p2.y - pos.y, 2);
|
||||
context.globalAlpha = frame ? 0.95 : 0.8;
|
||||
context.fillStyle = frame && !node.metadata?.frame?.collapsed ? "transparent" : color;
|
||||
context.strokeStyle = color;
|
||||
context.lineWidth = frame ? 1 : 0;
|
||||
if (context.fillStyle !== "transparent") context.fillRect(pos.x, pos.y, rectWidth, rectHeight);
|
||||
if (frame) context.strokeRect(pos.x, pos.y, rectWidth, rectHeight);
|
||||
}
|
||||
const vx = -viewport.x / viewport.k;
|
||||
const vy = -viewport.y / viewport.k;
|
||||
const p1 = toMinimap(vx, vy);
|
||||
const p2 = toMinimap(vx + viewportSize.width / viewport.k, vy + viewportSize.height / viewport.k);
|
||||
context.globalAlpha = 1;
|
||||
context.strokeStyle = theme.node.activeStroke;
|
||||
context.strokeRect(p1.x, p1.y, Math.max(p2.x - p1.x, 4), Math.max(p2.y - p1.y, 4));
|
||||
}
|
||||
|
||||
@@ -1,9 +1,12 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState, type CSSProperties, type ReactNode, type RefObject } from "react";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore, type CSSProperties, type ReactNode, type RefObject } from "react";
|
||||
import { idleTaskTickerSubscribe, subscribeTaskTicker, taskTickerSnapshot } from "@/lib/canvas/task-ticker";
|
||||
import { AlertCircle, BookOpenCheck, Clock3, Download, FileText, Image as ImageIcon, LoaderCircle, Music2, Pencil, Play, RefreshCw, Video } from "lucide-react";
|
||||
|
||||
import { VideoPlayer } from "@/components/video-player";
|
||||
import { CONTENT_MODERATION_ERROR_CODE, generationErrorMessage, isContentModerationError } from "@/lib/generation-error";
|
||||
import { generationTaskShowsProgress, generationTaskStageLabel, generationTaskStatusLabel, isGenerationTaskSubmissionUncertain } from "@/lib/generation-task-display";
|
||||
import type { CanvasNodeRenderLOD } from "@/lib/canvas/canvas-node-lod";
|
||||
import { CachedResourceImage } from "@/components/cached-resource-image";
|
||||
import { canvasRichTextHTML } from "@/lib/canvas/canvas-rich-text";
|
||||
import { fitNodeSize } from "@/lib/canvas/canvas-node-size";
|
||||
import { canvasTextFontSize } from "@/lib/canvas/canvas-text-scale";
|
||||
@@ -15,7 +18,6 @@ import type { CanvasResourceReference } from "@/lib/canvas/canvas-resource-refer
|
||||
import type { CanvasTheme } from "@/lib/canvas-theme";
|
||||
import { formatBytes } from "@/lib/image-utils";
|
||||
import type { GenerationTask } from "@/services/api/task-center";
|
||||
import { scheduleResourceBlobCache } from "@/services/resource-blob-cache";
|
||||
import { resolveMediaUrl } from "@/services/file-storage";
|
||||
import { hydrateCanvasVideoPreview } from "@/services/canvas-video-preview";
|
||||
import { CanvasNodeType, type CanvasNodeData } from "@/types/canvas";
|
||||
@@ -42,6 +44,7 @@ import { MEDIA_CONVERSION_NODE_TYPE } from "@/lib/media-conversion/contracts";
|
||||
export type CanvasNodeContentProps = {
|
||||
node: CanvasNodeData;
|
||||
theme: CanvasTheme;
|
||||
renderLOD?: CanvasNodeRenderLOD;
|
||||
isEditingContent: boolean;
|
||||
textareaRef: RefObject<HTMLTextAreaElement | null>;
|
||||
isBatchRoot: boolean;
|
||||
@@ -65,14 +68,17 @@ export type CanvasNodeContentProps = {
|
||||
};
|
||||
|
||||
export function CanvasNodeContent(props: CanvasNodeContentProps) {
|
||||
if (props.renderLOD === "shell") return <CanvasNodeShellContent node={props.node} theme={props.theme} />;
|
||||
if (props.renderLOD === "preview") return <CanvasNodePreviewContent node={props.node} theme={props.theme} />;
|
||||
if (props.node.metadata?.fileUpload) return <CanvasFileUploadContent node={props.node} theme={props.theme} reduceMotion={props.reduceMediaEffects} />;
|
||||
const hasCustomContent = props.node.type === CanvasNodeType.Config
|
||||
|| props.node.type === CanvasNodeType.Script
|
||||
|| props.node.type === CanvasNodeType.BatchTable
|
||||
|| Boolean(props.node.metadata?.directorSceneId)
|
||||
|| (props.node.metadata?.workflowKind === "character" && Boolean(props.node.metadata.characterAssetId))
|
||||
|| (props.node.metadata?.workflowKind === "story_input" && !props.isEditingContent)
|
||||
|| (props.node.metadata?.workflowKind === "styleboard" && !props.node.metadata.content);
|
||||
const hasCustomContent =
|
||||
props.node.type === CanvasNodeType.Config ||
|
||||
props.node.type === CanvasNodeType.Script ||
|
||||
props.node.type === CanvasNodeType.BatchTable ||
|
||||
Boolean(props.node.metadata?.directorSceneId) ||
|
||||
(props.node.metadata?.workflowKind === "character" && Boolean(props.node.metadata.characterAssetId)) ||
|
||||
(props.node.metadata?.workflowKind === "story_input" && !props.isEditingContent) ||
|
||||
(props.node.metadata?.workflowKind === "styleboard" && !props.node.metadata.content);
|
||||
if (hasCustomContent && props.renderNodeContent) return props.renderNodeContent(props.node);
|
||||
if (props.node.type === ART_CRITIQUE_NODE_TYPE) return <ArtCritiqueNodeContent node={props.node} />;
|
||||
if (props.node.type === MEDIA_CONVERSION_NODE_TYPE) return <MediaConversionNodeContent node={props.node} theme={props.theme} />;
|
||||
@@ -86,20 +92,50 @@ export function CanvasNodeContent(props: CanvasNodeContentProps) {
|
||||
return Renderer ? <Renderer {...props} /> : <UnknownNodeContent theme={props.theme} />;
|
||||
}
|
||||
|
||||
function CanvasNodeShellContent({ node, theme }: { node: CanvasNodeData; theme: CanvasTheme }) {
|
||||
const Icon = node.type === CanvasNodeType.Video ? Video : node.type === CanvasNodeType.Audio ? Music2 : node.type === CanvasNodeType.Image ? ImageIcon : FileText;
|
||||
return (
|
||||
<div className="flex size-full flex-col items-center justify-center gap-2 rounded-[var(--node-radius)] px-3 text-center" style={{ background: theme.node.fill, color: theme.node.muted }}>
|
||||
<Icon className="size-6 opacity-40" />
|
||||
<span className="max-w-full truncate text-xs font-medium" title={node.title}>{node.title || "画布节点"}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function CanvasNodePreviewContent({ node, theme }: { node: CanvasNodeData; theme: CanvasTheme }) {
|
||||
if (node.type === CanvasNodeType.Image && (node.metadata?.content || node.metadata?.storageKey)) {
|
||||
return <CachedResourceImage storageKey={node.metadata?.storageKey} src={node.metadata?.previewContent || node.metadata?.content} alt={node.title} loading="lazy" decoding="async" draggable={false} className="pointer-events-none block size-full select-none object-contain" fallback={<CanvasNodeShellContent node={node} theme={theme} />} />;
|
||||
}
|
||||
if (node.type === CanvasNodeType.Video && (node.metadata?.content || node.metadata?.storageKey)) {
|
||||
return <CanvasVideoPreviewImage node={node} alt={node.title} loading="lazy" decoding="async" draggable={false} className="pointer-events-none block size-full select-none object-contain" fallback={<CanvasNodeShellContent node={node} theme={theme} />} />;
|
||||
}
|
||||
return <CanvasNodeShellContent node={node} theme={theme} />;
|
||||
}
|
||||
|
||||
function PluginCanvasNodeContent({ node, theme, renderer, schema }: CanvasNodeContentProps & { renderer: "declarative" | "sandbox"; schema: Record<string, unknown> }) {
|
||||
if (renderer === "sandbox") {
|
||||
return <div className="flex h-full w-full items-center justify-center p-4 text-center text-xs" style={{ color: theme.node.placeholder }}>
|
||||
插件节点等待隔离运行时
|
||||
</div>;
|
||||
return (
|
||||
<div className="flex h-full w-full items-center justify-center p-4 text-center text-xs" style={{ color: theme.node.placeholder }}>
|
||||
插件节点等待隔离运行时
|
||||
</div>
|
||||
);
|
||||
}
|
||||
const data = node.metadata?.pluginData || {};
|
||||
const fields = Object.keys(schema.properties && typeof schema.properties === "object" ? schema.properties as Record<string, unknown> : schema);
|
||||
return <div className="flex h-full w-full flex-col gap-3 overflow-auto p-4 pt-10 text-xs" style={{ color: theme.node.text }}>
|
||||
{fields.length ? fields.map((field) => <div key={field} className="flex flex-col gap-1">
|
||||
<span className="font-medium opacity-60">{field}</span>
|
||||
<span className="whitespace-pre-wrap break-words opacity-90">{formatPluginValue(data[field] ?? (field === "content" ? node.metadata?.content : undefined))}</span>
|
||||
</div>) : <span className="whitespace-pre-wrap break-words">{node.metadata?.content || "插件节点"}</span>}
|
||||
</div>;
|
||||
const fields = Object.keys(schema.properties && typeof schema.properties === "object" ? (schema.properties as Record<string, unknown>) : schema);
|
||||
return (
|
||||
<div className="flex h-full w-full flex-col gap-3 overflow-auto p-4 pt-10 text-xs" style={{ color: theme.node.text }}>
|
||||
{fields.length ? (
|
||||
fields.map((field) => (
|
||||
<div key={field} className="flex flex-col gap-1">
|
||||
<span className="font-medium opacity-60">{field}</span>
|
||||
<span className="whitespace-pre-wrap break-words opacity-90">{formatPluginValue(data[field] ?? (field === "content" ? node.metadata?.content : undefined))}</span>
|
||||
</div>
|
||||
))
|
||||
) : (
|
||||
<span className="whitespace-pre-wrap break-words">{node.metadata?.content || "插件节点"}</span>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function formatPluginValue(value: unknown) {
|
||||
@@ -138,15 +174,17 @@ function DrawingContent({ node, theme, drawingProjectId }: CanvasNodeContentProp
|
||||
if (!drawingProjectId || !drawingId) return;
|
||||
let active = true;
|
||||
let objectUrl = "";
|
||||
void loadCanvasDrawingPreview(drawingProjectId, drawingId).then((preview) => {
|
||||
if (!active) return;
|
||||
if (!preview) {
|
||||
setPreviewUrl(fallbackPreview);
|
||||
return;
|
||||
}
|
||||
objectUrl = URL.createObjectURL(preview);
|
||||
setPreviewUrl(objectUrl);
|
||||
}).catch((error) => console.warn("读取绘图节点预览失败", error));
|
||||
void loadCanvasDrawingPreview(drawingProjectId, drawingId)
|
||||
.then((preview) => {
|
||||
if (!active) return;
|
||||
if (!preview) {
|
||||
setPreviewUrl(fallbackPreview);
|
||||
return;
|
||||
}
|
||||
objectUrl = URL.createObjectURL(preview);
|
||||
setPreviewUrl(objectUrl);
|
||||
})
|
||||
.catch((error) => console.warn("读取绘图节点预览失败", error));
|
||||
return () => {
|
||||
active = false;
|
||||
if (objectUrl) URL.revokeObjectURL(objectUrl);
|
||||
@@ -169,8 +207,12 @@ function DrawingContent({ node, theme, drawingProjectId }: CanvasNodeContentProp
|
||||
)}
|
||||
<div className="pointer-events-none absolute inset-x-0 bottom-0 flex items-end justify-between gap-3 px-4 pb-3 pt-12" style={{ background: `linear-gradient(to top, ${theme.node.fill}, ${theme.node.fill}e6 55%, transparent)` }}>
|
||||
<div className="min-w-0">
|
||||
<div className="truncate text-xs font-semibold" title={node.title || "绘图"}>{node.title || "绘图"}</div>
|
||||
<div className="mt-0.5 text-[var(--fs-tiny)]" style={{ color: theme.node.muted }}>{shapeCount} 个图形 · {pageCount} 个页面</div>
|
||||
<div className="truncate text-xs font-semibold" title={node.title || "绘图"}>
|
||||
{node.title || "绘图"}
|
||||
</div>
|
||||
<div className="mt-0.5 text-[var(--fs-tiny)]" style={{ color: theme.node.muted }}>
|
||||
{shapeCount} 个图形 · {pageCount} 个页面
|
||||
</div>
|
||||
</div>
|
||||
<Pencil className="size-3.5 shrink-0" style={{ color: theme.accent.primary }} />
|
||||
</div>
|
||||
@@ -210,10 +252,23 @@ function LoadingContent({ node, theme, onOpenTaskDetails }: Pick<CanvasNodeConte
|
||||
</div>
|
||||
) : null}
|
||||
<div className="max-w-full truncate text-[var(--fs-tiny)] tabular-nums" style={{ color: theme.node.muted }}>
|
||||
<Clock3 className="mr-1 inline size-3" />{elapsed} · {shortTaskId(taskId)}
|
||||
<Clock3 className="mr-1 inline size-3" />
|
||||
{elapsed} · {shortTaskId(taskId)}
|
||||
</div>
|
||||
<div className="mt-0.5 flex items-center gap-1.5">
|
||||
<button type="button" className="inline-flex h-7 items-center gap-1 rounded-[var(--r-sm)] px-2 text-[var(--fs-tiny)] font-medium transition-colors" style={{ background: theme.toolbar.itemHover, color: theme.node.text }} onMouseDown={(event) => event.stopPropagation()} onClick={(event) => { event.stopPropagation(); onOpenTaskDetails?.(node); }}><FileText className="size-3" />详情</button>
|
||||
<button
|
||||
type="button"
|
||||
className="inline-flex h-7 items-center gap-1 rounded-[var(--r-sm)] px-2 text-[var(--fs-tiny)] font-medium transition-colors"
|
||||
style={{ background: theme.toolbar.itemHover, color: theme.node.text }}
|
||||
onMouseDown={(event) => event.stopPropagation()}
|
||||
onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
onOpenTaskDetails?.(node);
|
||||
}}
|
||||
>
|
||||
<FileText className="size-3" />
|
||||
详情
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
@@ -222,14 +277,11 @@ function LoadingContent({ node, theme, onOpenTaskDetails }: Pick<CanvasNodeConte
|
||||
}
|
||||
|
||||
function useTaskElapsed(createdAt?: string) {
|
||||
const [, setTick] = useState(0);
|
||||
useEffect(() => {
|
||||
if (!createdAt) return;
|
||||
const timer = window.setInterval(() => setTick((value) => value + 1), 1000);
|
||||
return () => window.clearInterval(timer);
|
||||
}, [createdAt]);
|
||||
const now = useSyncExternalStore(createdAt ? subscribeTaskTicker : idleTaskTickerSubscribe, taskTickerSnapshot, taskTickerSnapshot);
|
||||
if (!createdAt) return "刚刚";
|
||||
const seconds = Math.max(0, Math.floor((Date.now() - new Date(createdAt).getTime()) / 1000));
|
||||
const started = new Date(createdAt).getTime();
|
||||
if (!Number.isFinite(started)) return "刚刚";
|
||||
const seconds = Math.max(0, Math.floor((now - started) / 1000));
|
||||
if (seconds < 60) return `${seconds}秒`;
|
||||
const minutes = Math.floor(seconds / 60);
|
||||
return minutes < 60 ? `${minutes}分${seconds % 60}秒` : `${Math.floor(minutes / 60)}时${minutes % 60}分`;
|
||||
@@ -253,7 +305,9 @@ function ErrorContent({ node, theme, onRetry, onReloadResource }: Pick<CanvasNod
|
||||
const submissionUncertain = isGenerationTaskSubmissionUncertain(errorDisplayTask);
|
||||
return (
|
||||
<div className="flex max-w-[260px] flex-col items-center gap-3 px-5 text-center">
|
||||
<div className="text-xs leading-5" style={{ color: submissionUncertain ? theme.node.text : theme.accent.danger }}>{submissionUncertain ? generationTaskStatusLabel(errorDisplayTask) : generationErrorMessage(node.metadata?.errorDetails)}</div>
|
||||
<div className="text-xs leading-5" style={{ color: submissionUncertain ? theme.node.text : theme.accent.danger }}>
|
||||
{submissionUncertain ? generationTaskStatusLabel(errorDisplayTask) : generationErrorMessage(node.metadata?.errorDetails)}
|
||||
</div>
|
||||
{submissionUncertain ? (
|
||||
<div className="rounded-[var(--r-sm)] px-3 py-2 text-[var(--fs-label)] leading-4" style={{ background: theme.toolbar.itemHover, color: theme.node.muted }}>
|
||||
{generationTaskStageLabel(errorDisplayTask)}
|
||||
@@ -268,7 +322,10 @@ function ErrorContent({ node, theme, onRetry, onReloadResource }: Pick<CanvasNod
|
||||
type="button"
|
||||
className="inline-flex h-8 items-center gap-1.5 rounded-[var(--r-md)] px-3 text-xs font-medium transition-colors"
|
||||
style={{ background: theme.accent.primary, color: theme.accent.onPrimary }}
|
||||
onClick={(event) => { event.stopPropagation(); onReloadResource?.(node); }}
|
||||
onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
onReloadResource?.(node);
|
||||
}}
|
||||
onMouseDown={(event) => event.stopPropagation()}
|
||||
>
|
||||
<Download className="size-3.5" />
|
||||
@@ -278,7 +335,10 @@ function ErrorContent({ node, theme, onRetry, onReloadResource }: Pick<CanvasNod
|
||||
type="button"
|
||||
className="inline-flex h-8 items-center gap-1.5 rounded-[var(--r-md)] px-3 text-xs font-medium transition-colors"
|
||||
style={{ background: theme.toolbar.itemHover, color: theme.node.text }}
|
||||
onClick={(event) => { event.stopPropagation(); onRetry?.(node); }}
|
||||
onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
onRetry?.(node);
|
||||
}}
|
||||
onMouseDown={(event) => event.stopPropagation()}
|
||||
>
|
||||
<RefreshCw className="size-3.5" />
|
||||
@@ -305,7 +365,11 @@ function ErrorContent({ node, theme, onRetry, onReloadResource }: Pick<CanvasNod
|
||||
}
|
||||
|
||||
function UnknownNodeContent({ theme }: Pick<CanvasNodeContentProps, "theme">) {
|
||||
return <div className="flex h-full w-full items-center justify-center text-sm" style={{ color: theme.node.placeholder }}>未知节点</div>;
|
||||
return (
|
||||
<div className="flex h-full w-full items-center justify-center text-sm" style={{ color: theme.node.placeholder }}>
|
||||
未知节点
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function TextContent({ node, theme, isEditingContent, textareaRef, mentionReferences, onContentChange, onStopEditing }: CanvasNodeContentProps) {
|
||||
@@ -362,22 +426,45 @@ function SkillContent({ node, theme }: CanvasNodeContentProps) {
|
||||
<BookOpenCheck className="size-4" />
|
||||
</span>
|
||||
<div className="min-w-0">
|
||||
<div className="truncate text-sm font-semibold" title={skill?.name || node.title || "技能"}>{skill?.name || node.title || "技能"}</div>
|
||||
<div className="truncate text-sm font-semibold" title={skill?.name || node.title || "技能"}>
|
||||
{skill?.name || node.title || "技能"}
|
||||
</div>
|
||||
<div className="mt-0.5 flex items-center gap-1.5 text-[var(--fs-label)]" style={{ color: theme.node.muted }}>
|
||||
<span>{skillCategoryLabel(skill?.category)}</span><span>·</span><span>{skillOutputModeLabel(skill?.outputMode)}</span>
|
||||
{skill?.version ? <><span>·</span><span>v{skill.version}</span></> : null}
|
||||
<span>{skillCategoryLabel(skill?.category)}</span>
|
||||
<span>·</span>
|
||||
<span>{skillOutputModeLabel(skill?.outputMode)}</span>
|
||||
{skill?.version ? (
|
||||
<>
|
||||
<span>·</span>
|
||||
<span>v{skill.version}</span>
|
||||
</>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{skill?.description ? <div className="mt-3 line-clamp-2 text-xs leading-5" style={{ color: theme.node.muted }}>{skill.description}</div> : null}
|
||||
{skill?.description ? (
|
||||
<div className="mt-3 line-clamp-2 text-xs leading-5" style={{ color: theme.node.muted }}>
|
||||
{skill.description}
|
||||
</div>
|
||||
) : null}
|
||||
<div className="thin-scrollbar mt-3 min-h-0 flex-1 overflow-hidden rounded-[var(--r-md)] px-3 py-2 text-xs leading-5" style={{ background: theme.node.panel, color: theme.node.text }}>
|
||||
<div className="mb-1 font-semibold opacity-55">模板</div>
|
||||
<div className="line-clamp-4 whitespace-pre-wrap break-words">{template || "未配置技能模板"}</div>
|
||||
</div>
|
||||
<div className="mt-3 flex flex-wrap gap-1.5">
|
||||
{tags.length ? tags.map((tag) => <span key={tag} className="rounded-[var(--r-sm)] bg-black/5 px-1.5 py-0.5 text-[var(--fs-tiny)] dark:bg-white/6" style={{ color: theme.node.muted }}>{tag}</span>) : <span className="text-[var(--fs-label)]" style={{ color: theme.node.muted }}>连接到图片、视频、音频或文本节点后生效</span>}
|
||||
{tags.length ? (
|
||||
tags.map((tag) => (
|
||||
<span key={tag} className="rounded-[var(--r-sm)] bg-black/5 px-1.5 py-0.5 text-[var(--fs-tiny)] dark:bg-white/6" style={{ color: theme.node.muted }}>
|
||||
{tag}
|
||||
</span>
|
||||
))
|
||||
) : (
|
||||
<span className="text-[var(--fs-label)]" style={{ color: theme.node.muted }}>
|
||||
连接到图片、视频、音频或文本节点后生效
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
@@ -400,31 +487,69 @@ function skillOutputModeLabel(mode?: string) {
|
||||
|
||||
function ImageNodeContent(props: CanvasNodeContentProps) {
|
||||
if (!props.node.metadata?.content && props.isBatchRoot) {
|
||||
const content = props.node.metadata?.status === "loading"
|
||||
? <LoadingContent node={props.node} theme={props.theme} />
|
||||
: props.node.metadata?.status === "error"
|
||||
? <ErrorContent node={props.node} theme={props.theme} onRetry={props.onRetry} onReloadResource={props.onReloadResource} />
|
||||
: <EmptyImageContent {...props} isBatchRoot={false} />;
|
||||
return <BatchFrame batchPreviewNodes={props.batchPreviewNodes} batchCount={props.batchCount} batchExpanded={props.batchExpanded} batchOpening={props.batchOpening} batchRecovering={props.batchRecovering} theme={props.theme} onToggleBatch={props.onToggleBatch}>{content}</BatchFrame>;
|
||||
const content =
|
||||
props.node.metadata?.status === "loading" ? (
|
||||
<LoadingContent node={props.node} theme={props.theme} />
|
||||
) : props.node.metadata?.status === "error" ? (
|
||||
<ErrorContent node={props.node} theme={props.theme} onRetry={props.onRetry} onReloadResource={props.onReloadResource} />
|
||||
) : (
|
||||
<EmptyImageContent {...props} isBatchRoot={false} />
|
||||
);
|
||||
return (
|
||||
<BatchFrame
|
||||
batchPreviewNodes={props.batchPreviewNodes}
|
||||
batchCount={props.batchCount}
|
||||
batchExpanded={props.batchExpanded}
|
||||
batchOpening={props.batchOpening}
|
||||
batchRecovering={props.batchRecovering}
|
||||
theme={props.theme}
|
||||
onToggleBatch={props.onToggleBatch}
|
||||
>
|
||||
{content}
|
||||
</BatchFrame>
|
||||
);
|
||||
}
|
||||
if (!props.node.metadata?.content) return <EmptyImageContent {...props} />;
|
||||
return <ImageContent batchPreviewNodes={props.batchPreviewNodes} node={props.node} theme={props.theme} isBatchRoot={props.isBatchRoot} batchCount={props.batchCount} batchExpanded={props.batchExpanded} batchOpening={props.batchOpening} batchRecovering={props.batchRecovering} onToggleBatch={props.onToggleBatch} />;
|
||||
return (
|
||||
<ImageContent
|
||||
batchPreviewNodes={props.batchPreviewNodes}
|
||||
node={props.node}
|
||||
theme={props.theme}
|
||||
isBatchRoot={props.isBatchRoot}
|
||||
batchCount={props.batchCount}
|
||||
batchExpanded={props.batchExpanded}
|
||||
batchOpening={props.batchOpening}
|
||||
batchRecovering={props.batchRecovering}
|
||||
onToggleBatch={props.onToggleBatch}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function EmptyImageContent({ node, theme, isBatchRoot, batchCount, batchPreviewNodes, batchExpanded, batchOpening, batchRecovering, onToggleBatch }: CanvasNodeContentProps) {
|
||||
const isCharacterReference = node.metadata?.workflowKind === "character" && node.metadata?.characterView === "multi";
|
||||
const content = (
|
||||
<div className="flex h-full w-full flex-col items-center justify-center gap-3" style={{ color: theme.node.placeholder }}>
|
||||
<div className="flex size-14 items-center justify-center rounded-[var(--r-lg)]" style={{ background: theme.toolbar.activeBg }}><ImageIcon className="size-6 opacity-30" /></div>
|
||||
<div className="flex size-14 items-center justify-center rounded-[var(--r-lg)]" style={{ background: theme.toolbar.activeBg }}>
|
||||
<ImageIcon className="size-6 opacity-30" />
|
||||
</div>
|
||||
{isCharacterReference ? (
|
||||
<div className="max-w-[80%] text-center">
|
||||
<div className="truncate text-xs font-medium" title={node.metadata?.characterName || node.title} style={{ color: theme.node.muted }}>{node.metadata?.characterName || node.title}</div>
|
||||
<div className="truncate text-xs font-medium" title={node.metadata?.characterName || node.title} style={{ color: theme.node.muted }}>
|
||||
{node.metadata?.characterName || node.title}
|
||||
</div>
|
||||
<div className="mt-1 text-[var(--fs-tiny)] tracking-[0.12em] opacity-50">多视角参考 · 待生成</div>
|
||||
</div>
|
||||
) : <span className="text-[var(--fs-tiny)] tracking-[0.18em] opacity-50">空图片节点</span>}
|
||||
) : (
|
||||
<span className="text-[var(--fs-tiny)] tracking-[0.18em] opacity-50">空图片节点</span>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
if (isBatchRoot) return <BatchFrame batchPreviewNodes={batchPreviewNodes} batchCount={batchCount} batchExpanded={batchExpanded} batchOpening={batchOpening} batchRecovering={batchRecovering} theme={theme} onToggleBatch={onToggleBatch}>{content}</BatchFrame>;
|
||||
if (isBatchRoot)
|
||||
return (
|
||||
<BatchFrame batchPreviewNodes={batchPreviewNodes} batchCount={batchCount} batchExpanded={batchExpanded} batchOpening={batchOpening} batchRecovering={batchRecovering} theme={theme} onToggleBatch={onToggleBatch}>
|
||||
{content}
|
||||
</BatchFrame>
|
||||
);
|
||||
return content;
|
||||
}
|
||||
|
||||
@@ -432,10 +557,16 @@ function VideoNodeContent({ node, theme, mediaActive = false, onMediaPlayRequest
|
||||
const playerBoxRef = useRef<HTMLDivElement>(null);
|
||||
const { updateMediaNode } = useCanvasNodeActions();
|
||||
const { url, loading } = useVideoPlaybackUrl(node, mediaActive);
|
||||
const preview = canvasNodeVideoPreviewReference(node);
|
||||
const subtitleEntries = node.metadata?.subtitleEntries || [];
|
||||
const subtitleStyle = node.metadata?.subtitleStyle || createDefaultSubtitleStyle();
|
||||
const [currentTimeMs, setCurrentTimeMs] = useState(0);
|
||||
const [videoSize, setVideoSize] = useState<{ width: number; height: number } | null>(null);
|
||||
const [videoReady, setVideoReady] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
setVideoReady(false);
|
||||
}, [url]);
|
||||
|
||||
useEffect(() => {
|
||||
const box = playerBoxRef.current;
|
||||
@@ -461,7 +592,6 @@ function VideoNodeContent({ node, theme, mediaActive = false, onMediaPlayRequest
|
||||
|
||||
if (!node.metadata?.content && !node.metadata?.storageKey) return <EmptyMediaContent icon={<Video className="size-7 opacity-35" />} label="空视频节点" color={theme.node.placeholder} />;
|
||||
if (!mediaActive) return <InactiveVideoPreview node={node} theme={theme} onPlay={() => onMediaPlayRequest?.(node.id)} />;
|
||||
if (!url) return <MediaLoadingState icon={<LoaderCircle className="size-5 animate-spin" />} label={loading ? "正在加载视频" : "视频资源不可用"} />;
|
||||
|
||||
const sourceRatio = (videoSize?.width || node.metadata?.naturalWidth || node.width) / Math.max(1, videoSize?.height || node.metadata?.naturalHeight || node.height);
|
||||
const fitHeight = Math.min(node.height, node.width / Math.max(0.01, sourceRatio));
|
||||
@@ -471,10 +601,38 @@ function VideoNodeContent({ node, theme, mediaActive = false, onMediaPlayRequest
|
||||
|
||||
return (
|
||||
<div ref={playerBoxRef} className="relative flex h-full w-full items-center justify-center overflow-hidden rounded-[var(--node-radius)] bg-black">
|
||||
<div className="relative" style={{ width: fitWidth, height: Math.round(fitHeight) }}>
|
||||
<VideoPlayer src={url} mimeType={node.metadata?.mimeType} title={node.title || "视频"} hasAudio={inferVideoHasAudio(node.metadata)} autoPlay preload="metadata" brandColor={theme.accent.primary} className="h-full w-full rounded-[var(--node-radius)] bg-black" dataCanvasNoZoom compactControls onPlay={() => scheduleResourceBlobCache(node.metadata?.storageKey || "")} />
|
||||
{activeEntry && activeEntry.text.trim() ? <CanvasSubtitleOverlay text={activeEntry.text} highlight={activeHighlight} style={subtitleStyle} /> : null}
|
||||
</div>
|
||||
{preview ? (
|
||||
<CanvasVideoPreviewImage
|
||||
node={node}
|
||||
alt={`${node.title || "视频"} 静态预览`}
|
||||
loading="eager"
|
||||
decoding="async"
|
||||
draggable={false}
|
||||
className={`absolute inset-0 size-full select-none object-contain transition-opacity duration-150 ${videoReady ? "opacity-0" : "opacity-100"}`}
|
||||
loadingFallback={<LoaderCircle className="size-5 animate-spin text-white/55" />}
|
||||
fallback={<Video className="size-7 text-white/40" />}
|
||||
/>
|
||||
) : !url || loading ? (
|
||||
<MediaLoadingState icon={<LoaderCircle className="size-5 animate-spin" />} label={loading ? "正在加载视频" : "视频资源不可用"} />
|
||||
) : null}
|
||||
{url ? (
|
||||
<div className={`relative z-[1] transition-opacity duration-150 ${videoReady ? "opacity-100" : "opacity-0"}`} style={{ width: fitWidth, height: Math.round(fitHeight) }}>
|
||||
<VideoPlayer
|
||||
src={url}
|
||||
mimeType={node.metadata?.mimeType}
|
||||
title={node.title || "视频"}
|
||||
hasAudio={inferVideoHasAudio(node.metadata)}
|
||||
autoPlay
|
||||
preload="metadata"
|
||||
brandColor={theme.accent.primary}
|
||||
className="h-full w-full rounded-[var(--node-radius)] bg-black"
|
||||
dataCanvasNoZoom
|
||||
compactControls
|
||||
onCanPlay={() => setVideoReady(true)}
|
||||
/>
|
||||
{activeEntry && activeEntry.text.trim() ? <CanvasSubtitleOverlay text={activeEntry.text} highlight={activeHighlight} style={subtitleStyle} /> : null}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -507,8 +665,6 @@ function InactiveVideoPreview({ node, theme, onPlay }: Pick<CanvasNodeContentPro
|
||||
const [hydrating, setHydrating] = useState(false);
|
||||
const [localPreviewUrl, setLocalPreviewUrl] = useState("");
|
||||
const localPreviewUrlRef = useRef("");
|
||||
const [passiveVideoUrl, setPassiveVideoUrl] = useState("");
|
||||
const [passiveVideoReady, setPassiveVideoReady] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
const element = previewRef.current;
|
||||
@@ -522,33 +678,12 @@ function InactiveVideoPreview({ node, theme, onPlay }: Pick<CanvasNodeContentPro
|
||||
updateMetadataRef.current = updateMetadata;
|
||||
}, [updateMetadata]);
|
||||
|
||||
useEffect(() => () => {
|
||||
if (localPreviewUrlRef.current) URL.revokeObjectURL(localPreviewUrlRef.current);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (hasPersistedPreview || localPreviewUrl || !nearViewport || (!node.metadata?.content && !node.metadata?.storageKey)) {
|
||||
setPassiveVideoUrl("");
|
||||
setPassiveVideoReady(false);
|
||||
return;
|
||||
}
|
||||
let cancelled = false;
|
||||
const content = node.metadata?.content || "";
|
||||
const fallback = node.metadata?.importSource?.provider === "libtv" ? buildLibTVVideoSourceUrl(content) : content;
|
||||
setPassiveVideoUrl("");
|
||||
setPassiveVideoReady(false);
|
||||
// This is a real <video> fallback rather than canvas extraction. It can
|
||||
// paint the first decoded frame even when OSS allows media playback but
|
||||
// does not expose the CORS headers required by drawImage/toBlob.
|
||||
void resolveMediaUrl(node.metadata?.storageKey, fallback)
|
||||
.then((url) => {
|
||||
if (!cancelled) setPassiveVideoUrl(url);
|
||||
})
|
||||
.catch(() => undefined);
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [hasPersistedPreview, localPreviewUrl, nearViewport, node.metadata?.content, node.metadata?.storageKey, node.metadata?.importSource?.provider]);
|
||||
useEffect(
|
||||
() => () => {
|
||||
if (localPreviewUrlRef.current) URL.revokeObjectURL(localPreviewUrlRef.current);
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (hasPersistedPreview || !nearViewport || (!node.metadata?.content && !node.metadata?.storageKey) || !updateMetadataRef.current) {
|
||||
@@ -589,73 +724,52 @@ function InactiveVideoPreview({ node, theme, onPlay }: Pick<CanvasNodeContentPro
|
||||
};
|
||||
}, [hasPersistedPreview, nearViewport, node.id, node.metadata?.content, node.metadata?.storageKey, persistedPreviewSource, persistedPreviewStorageKey]);
|
||||
|
||||
if (hasPersistedPreview || localPreviewUrl || passiveVideoUrl) {
|
||||
return <div ref={previewRef} className="group/video-preview relative size-full overflow-hidden rounded-[var(--node-radius)] bg-black">
|
||||
{hasPersistedPreview ? (
|
||||
<CanvasVideoPreviewImage
|
||||
node={node}
|
||||
alt={`${node.title || "视频"} 静态预览`}
|
||||
loading="lazy"
|
||||
decoding="async"
|
||||
draggable={false}
|
||||
className="pointer-events-none size-full select-none object-contain"
|
||||
loadingFallback={<LoaderCircle className="size-5 animate-spin text-white/55" />}
|
||||
fallback={<Video className="size-7 text-white/40" />}
|
||||
/>
|
||||
) : localPreviewUrl ? (
|
||||
<img src={localPreviewUrl} alt={`${node.title || "视频"} 静态预览`} loading="lazy" decoding="async" draggable={false} className="pointer-events-none size-full select-none object-contain" />
|
||||
) : (
|
||||
<>
|
||||
<video
|
||||
src={passiveVideoUrl}
|
||||
aria-hidden="true"
|
||||
tabIndex={-1}
|
||||
muted
|
||||
playsInline
|
||||
preload="auto"
|
||||
if (hasPersistedPreview || localPreviewUrl) {
|
||||
return (
|
||||
<div ref={previewRef} className="group/video-preview relative size-full overflow-hidden rounded-[var(--node-radius)] bg-black">
|
||||
{hasPersistedPreview ? (
|
||||
<CanvasVideoPreviewImage
|
||||
node={node}
|
||||
alt={`${node.title || "视频"} 静态预览`}
|
||||
loading="lazy"
|
||||
decoding="async"
|
||||
draggable={false}
|
||||
className={`pointer-events-none size-full select-none object-contain transition-opacity ${passiveVideoReady ? "opacity-100" : "opacity-0"}`}
|
||||
onLoadedMetadata={(event) => {
|
||||
const video = event.currentTarget;
|
||||
if (video.readyState >= 2) {
|
||||
setPassiveVideoReady(true);
|
||||
return;
|
||||
}
|
||||
// Some browsers stop at metadata when the element is muted and
|
||||
// offscreen. A tiny seek forces an actual frame decode without
|
||||
// starting playback or requiring canvas/CORS access.
|
||||
if (Number.isFinite(video.duration) && video.duration > 0) {
|
||||
try {
|
||||
video.currentTime = Math.min(0.001, video.duration / 2);
|
||||
} catch {
|
||||
// loadeddata/canplay will still reveal the frame if seeking is unavailable.
|
||||
}
|
||||
}
|
||||
}}
|
||||
onLoadedData={() => setPassiveVideoReady(true)}
|
||||
onCanPlay={() => setPassiveVideoReady(true)}
|
||||
onSeeked={(event) => {
|
||||
if (event.currentTarget.readyState >= 2) setPassiveVideoReady(true);
|
||||
}}
|
||||
onError={() => {
|
||||
setPassiveVideoReady(false);
|
||||
setPassiveVideoUrl("");
|
||||
}}
|
||||
className="pointer-events-none size-full select-none object-contain"
|
||||
loadingFallback={<LoaderCircle className="size-5 animate-spin text-white/55" />}
|
||||
fallback={<Video className="size-7 text-white/40" />}
|
||||
/>
|
||||
{!passiveVideoReady ? <div className="absolute inset-0"><InactiveMediaCard icon={<Video className="size-7" />} title={node.title || "视频"} hint={hydrating ? "正在生成首帧" : "正在读取首帧"} theme={theme} /></div> : null}
|
||||
</>
|
||||
)}
|
||||
<VideoPreviewPlayButton title={node.title || "视频"} onPlay={onPlay} />
|
||||
</div>;
|
||||
) : (
|
||||
<img src={localPreviewUrl} alt={`${node.title || "视频"} 静态预览`} loading="lazy" decoding="async" draggable={false} className="pointer-events-none size-full select-none object-contain" />
|
||||
)}
|
||||
<VideoPreviewPlayButton title={node.title || "视频"} onPlay={onPlay} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return <div ref={previewRef} className="group/video-preview relative size-full">
|
||||
<InactiveMediaCard icon={<Video className="size-7" />} title={node.title || "视频"} hint={hydrating ? "正在生成首帧" : nearViewport ? "点击播放视频" : "进入视口后加载首帧"} theme={theme} />
|
||||
<VideoPreviewPlayButton title={node.title || "视频"} onPlay={onPlay} />
|
||||
</div>;
|
||||
return (
|
||||
<div ref={previewRef} className="group/video-preview relative size-full">
|
||||
<InactiveMediaCard icon={<Video className="size-7" />} title={node.title || "视频"} hint={hydrating ? "正在生成首帧" : nearViewport ? "点击播放视频" : "进入视口后加载首帧"} theme={theme} />
|
||||
<VideoPreviewPlayButton title={node.title || "视频"} onPlay={onPlay} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function VideoPreviewPlayButton({ title, onPlay }: { title: string; onPlay: () => void }) {
|
||||
return <button type="button" className="absolute left-1/2 top-1/2 z-[var(--node-z-overlay)] grid size-11 -translate-x-1/2 -translate-y-1/2 place-items-center rounded-full bg-black/62 text-white shadow-lg backdrop-blur transition-[transform,background-color,opacity] hover:scale-105 hover:bg-black/78 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-white" aria-label={`播放 ${title}`} title="播放视频" onPointerDown={(event) => event.stopPropagation()} onMouseDown={(event) => event.stopPropagation()} onClick={(event) => { event.stopPropagation(); onPlay(); }}><Play className="ml-0.5 size-5 fill-current" /></button>;
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
className="absolute left-1/2 top-1/2 z-[var(--node-z-overlay)] grid size-11 -translate-x-1/2 -translate-y-1/2 place-items-center rounded-full bg-black/62 text-white shadow-lg backdrop-blur transition-[transform,background-color,opacity] hover:scale-105 hover:bg-black/78 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-white"
|
||||
aria-label={`播放 ${title}`}
|
||||
title="播放视频"
|
||||
onPointerDown={(event) => event.stopPropagation()}
|
||||
onMouseDown={(event) => event.stopPropagation()}
|
||||
onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
onPlay();
|
||||
}}
|
||||
>
|
||||
<Play className="ml-0.5 size-5 fill-current" />
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
function useVideoPlaybackUrl(node: CanvasNodeData, active: boolean) {
|
||||
@@ -674,28 +788,64 @@ function useVideoPlaybackUrl(node: CanvasNodeData, active: boolean) {
|
||||
}
|
||||
setLoading(true);
|
||||
void resolveMediaUrl(storageKey, fallback)
|
||||
.then((resolved) => { if (!cancelled) setUrl(resolved); })
|
||||
.catch(() => { if (!cancelled) setUrl(fallback); })
|
||||
.finally(() => { if (!cancelled) setLoading(false); });
|
||||
return () => { cancelled = true; };
|
||||
.then((resolved) => {
|
||||
if (!cancelled) setUrl(resolved);
|
||||
})
|
||||
.catch(() => {
|
||||
if (!cancelled) setUrl(fallback);
|
||||
})
|
||||
.finally(() => {
|
||||
if (!cancelled) setLoading(false);
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [active, fallback, storageKey]);
|
||||
|
||||
return { url, loading };
|
||||
}
|
||||
|
||||
function InactiveMediaCard({ icon, title, hint, theme }: { icon: ReactNode; title: string; hint: string; theme: CanvasTheme }) {
|
||||
return <div className="flex size-full flex-col items-center justify-center gap-2 rounded-[var(--node-radius)] px-4 text-center" style={{ background: theme.node.fill, color: theme.node.muted }}><span className="opacity-40">{icon}</span><span className="max-w-full truncate text-xs font-medium" title={title}>{title}</span><span className="text-[var(--fs-tiny)] opacity-50">{hint}</span></div>;
|
||||
return (
|
||||
<div className="flex size-full flex-col items-center justify-center gap-2 rounded-[var(--node-radius)] px-4 text-center" style={{ background: theme.node.fill, color: theme.node.muted }}>
|
||||
<span className="opacity-40">{icon}</span>
|
||||
<span className="max-w-full truncate text-xs font-medium" title={title}>
|
||||
{title}
|
||||
</span>
|
||||
<span className="text-[var(--fs-tiny)] opacity-50">{hint}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function MediaLoadingState({ icon, label }: { icon: ReactNode; label: string }) {
|
||||
return <div role="status" className="flex size-full flex-col items-center justify-center gap-2 rounded-[var(--node-radius)] bg-black text-white/75"><span className="grid size-10 place-items-center rounded-full bg-white/10">{icon}</span><span className="text-xs font-medium">{label}</span></div>;
|
||||
return (
|
||||
<div role="status" className="flex size-full flex-col items-center justify-center gap-2 rounded-[var(--node-radius)] bg-black text-white/75">
|
||||
<span className="grid size-10 place-items-center rounded-full bg-white/10">{icon}</span>
|
||||
<span className="text-xs font-medium">{label}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function EmptyMediaContent({ icon, label, color }: { icon: ReactNode; label: string; color: string }) {
|
||||
return <div className="flex h-full w-full flex-col items-center justify-center gap-3" style={{ color }}>{icon}<span className="text-sm">{label}</span></div>;
|
||||
return (
|
||||
<div className="flex h-full w-full flex-col items-center justify-center gap-3" style={{ color }}>
|
||||
{icon}
|
||||
<span className="text-sm">{label}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ImageContent({ node, theme, isBatchRoot, batchCount, batchPreviewNodes, batchExpanded, batchOpening, batchRecovering, onToggleBatch }: Pick<CanvasNodeContentProps, "node" | "theme" | "isBatchRoot" | "batchCount" | "batchPreviewNodes" | "batchExpanded" | "batchOpening" | "batchRecovering" | "onToggleBatch">) {
|
||||
function ImageContent({
|
||||
node,
|
||||
theme,
|
||||
isBatchRoot,
|
||||
batchCount,
|
||||
batchPreviewNodes,
|
||||
batchExpanded,
|
||||
batchOpening,
|
||||
batchRecovering,
|
||||
onToggleBatch,
|
||||
}: Pick<CanvasNodeContentProps, "node" | "theme" | "isBatchRoot" | "batchCount" | "batchPreviewNodes" | "batchExpanded" | "batchOpening" | "batchRecovering" | "onToggleBatch">) {
|
||||
const imageContainerRef = useRef<HTMLDivElement>(null);
|
||||
const nearViewport = useNearViewport(imageContainerRef);
|
||||
const { url, loading } = useNodeResourceUrl(node, nearViewport);
|
||||
@@ -741,7 +891,22 @@ function ImageContent({ node, theme, isBatchRoot, batchCount, batchPreviewNodes,
|
||||
return (
|
||||
<BatchFrame batchPreviewNodes={batchPreviewNodes} batchCount={isBatchRoot ? batchCount : 0} batchExpanded={batchExpanded} batchOpening={batchOpening} batchRecovering={batchRecovering} theme={theme} onToggleBatch={onToggleBatch}>
|
||||
<div ref={imageContainerRef} className="h-full w-full overflow-hidden rounded-[var(--node-radius)]">
|
||||
{url ? <img src={url} alt={node.title} loading="lazy" decoding="async" draggable={false} onDragStart={(event) => event.preventDefault()} onLoad={(event) => fitToImage(event.currentTarget)} className={`pointer-events-none block h-full w-full select-none ${node.metadata?.freeResize ? "object-fill" : "object-contain"}`} /> : <div className="grid size-full place-items-center" style={{ color: theme.node.muted }}>{loading ? <LoaderCircle className="size-5 animate-spin" /> : <ImageIcon className="size-5 opacity-45" />}</div>}
|
||||
{url ? (
|
||||
<img
|
||||
src={url}
|
||||
alt={node.title}
|
||||
loading="lazy"
|
||||
decoding="async"
|
||||
draggable={false}
|
||||
onDragStart={(event) => event.preventDefault()}
|
||||
onLoad={(event) => fitToImage(event.currentTarget)}
|
||||
className={`pointer-events-none block h-full w-full select-none ${node.metadata?.freeResize ? "object-fill" : "object-contain"}`}
|
||||
/>
|
||||
) : (
|
||||
<div className="grid size-full place-items-center" style={{ color: theme.node.muted }}>
|
||||
{loading ? <LoaderCircle className="size-5 animate-spin" /> : <ImageIcon className="size-5 opacity-45" />}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</BatchFrame>
|
||||
);
|
||||
@@ -750,23 +915,21 @@ function ImageContent({ node, theme, isBatchRoot, batchCount, batchPreviewNodes,
|
||||
function useNodeResourceUrl(node: CanvasNodeData, eager: boolean) {
|
||||
const storageKey = node.metadata?.storageKey || "";
|
||||
const rawContent = node.metadata?.content || "";
|
||||
const content = node.type === CanvasNodeType.Video && node.metadata?.importSource?.provider === "libtv"
|
||||
? buildLibTVVideoSourceUrl(rawContent)
|
||||
: rawContent;
|
||||
const content = node.type === CanvasNodeType.Video && node.metadata?.importSource?.provider === "libtv" ? buildLibTVVideoSourceUrl(rawContent) : rawContent;
|
||||
// `previewContent` is intentionally passive-only. When a media node is
|
||||
// activated, VideoPlayer/Audio must receive the playable asset, never the
|
||||
// LibTV OSS snapshot URL stored for the thumbnail.
|
||||
const fallback = node.type === CanvasNodeType.Video || node.type === CanvasNodeType.Audio
|
||||
? content
|
||||
: node.metadata?.previewContent
|
||||
|| (node.type === CanvasNodeType.Image && node.metadata?.importSource?.provider === "libtv" ? buildLibTVImagePreviewUrl(content) : content);
|
||||
const fallback =
|
||||
node.type === CanvasNodeType.Video || node.type === CanvasNodeType.Audio
|
||||
? content
|
||||
: node.metadata?.previewContent || (node.type === CanvasNodeType.Image && node.metadata?.importSource?.provider === "libtv" ? buildLibTVImagePreviewUrl(content) : content);
|
||||
const isRemoteResource = storageKey.startsWith("resource:");
|
||||
// Inline data URLs are already local, but decoding thousands of them is
|
||||
// still expensive. Images must wait for the same viewport gate as remote
|
||||
// resources; otherwise DOM virtualization does not reduce image work.
|
||||
const isLazyVisual = node.type === CanvasNodeType.Image;
|
||||
const isHttpUrl = Boolean(fallback && !fallback.startsWith("data:"));
|
||||
const initialUrl = eager && !isRemoteResource && isLazyVisual && isHttpUrl ? fallback : (isRemoteResource || isLazyVisual ? "" : fallback);
|
||||
const initialUrl = eager && !isRemoteResource && isLazyVisual && isHttpUrl ? fallback : isRemoteResource || isLazyVisual ? "" : fallback;
|
||||
const [url, setUrl] = useState(() => initialUrl);
|
||||
const [loading, setLoading] = useState(() => !initialUrl && isRemoteResource && eager);
|
||||
|
||||
@@ -810,12 +973,15 @@ function useNearViewport(ref: RefObject<Element | null>) {
|
||||
setNearViewport(true);
|
||||
return;
|
||||
}
|
||||
const observer = new IntersectionObserver((entries) => {
|
||||
if (entries.some((entry) => entry.isIntersecting)) {
|
||||
setNearViewport(true);
|
||||
observer.disconnect();
|
||||
}
|
||||
}, { rootMargin: "600px" });
|
||||
const observer = new IntersectionObserver(
|
||||
(entries) => {
|
||||
if (entries.some((entry) => entry.isIntersecting)) {
|
||||
setNearViewport(true);
|
||||
observer.disconnect();
|
||||
}
|
||||
},
|
||||
{ rootMargin: "600px" },
|
||||
);
|
||||
observer.observe(element);
|
||||
return () => observer.disconnect();
|
||||
}, [ref]);
|
||||
@@ -826,20 +992,57 @@ export function CanvasNodeImageInfo({ node }: { node: CanvasNodeData }) {
|
||||
const width = Math.round(node.metadata?.naturalWidth || node.width);
|
||||
const height = Math.round(node.metadata?.naturalHeight || node.height);
|
||||
const size = formatBytes(node.metadata?.bytes || 0);
|
||||
return <span className="ml-auto max-w-full shrink-0 truncate rounded-[var(--r-sm)] bg-black/55 px-2 py-1 text-[var(--fs-label)] font-medium leading-none text-white backdrop-blur-sm">{width} x {height}{size ? ` · ${size}` : ""}</span>;
|
||||
return (
|
||||
<span className="ml-auto max-w-full shrink-0 truncate rounded-[var(--r-sm)] bg-black/55 px-2 py-1 text-[var(--fs-label)] font-medium leading-none text-white backdrop-blur-sm">
|
||||
{width} x {height}
|
||||
{size ? ` · ${size}` : ""}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function BatchPreviewImage({ node }: { node: CanvasNodeData }) {
|
||||
const ref = useRef<HTMLDivElement>(null);
|
||||
const nearViewport = useNearViewport(ref);
|
||||
const { url } = useNodeResourceUrl(node, nearViewport);
|
||||
return <div ref={ref} className="h-full w-full overflow-hidden rounded-[inherit]">{url ? <img src={url} alt={`子图预览:${node.title}`} className="h-full w-full object-contain" draggable={false} /> : null}</div>;
|
||||
return (
|
||||
<div ref={ref} className="h-full w-full overflow-hidden rounded-[inherit]">
|
||||
{url ? <img src={url} alt={`子图预览:${node.title}`} className="h-full w-full object-contain" draggable={false} /> : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function BatchFrame({ batchCount, batchPreviewNodes, batchExpanded, batchOpening, batchRecovering, theme, onToggleBatch, children }: { batchCount: number; batchPreviewNodes?: CanvasNodeData[]; batchExpanded: boolean; batchOpening: boolean; batchRecovering: boolean; theme: CanvasTheme; onToggleBatch?: () => void; children: ReactNode }) {
|
||||
function BatchFrame({
|
||||
batchCount,
|
||||
batchPreviewNodes,
|
||||
batchExpanded,
|
||||
batchOpening,
|
||||
batchRecovering,
|
||||
theme,
|
||||
onToggleBatch,
|
||||
children,
|
||||
}: {
|
||||
batchCount: number;
|
||||
batchPreviewNodes?: CanvasNodeData[];
|
||||
batchExpanded: boolean;
|
||||
batchOpening: boolean;
|
||||
batchRecovering: boolean;
|
||||
theme: CanvasTheme;
|
||||
onToggleBatch?: () => void;
|
||||
children: ReactNode;
|
||||
}) {
|
||||
const isBatchRoot = batchCount > 1;
|
||||
return (
|
||||
<div className="group/batch relative h-full w-full overflow-visible" onDoubleClick={isBatchRoot ? (event) => { event.stopPropagation(); onToggleBatch?.(); } : undefined}>
|
||||
<div
|
||||
className="group/batch relative h-full w-full overflow-visible"
|
||||
onDoubleClick={
|
||||
isBatchRoot
|
||||
? (event) => {
|
||||
event.stopPropagation();
|
||||
onToggleBatch?.();
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
>
|
||||
{isBatchRoot ? (
|
||||
<div className="pointer-events-none absolute inset-0 overflow-visible">
|
||||
{Array.from({ length: Math.min(batchCount - 1, 5) }).map((_, index) => (
|
||||
@@ -851,7 +1054,8 @@ function BatchFrame({ batchCount, batchPreviewNodes, batchExpanded, batchOpening
|
||||
background: theme.node.panel,
|
||||
boxShadow: `inset 0 0 0 1px ${theme.node.stroke}`,
|
||||
opacity: batchExpanded && !batchOpening ? 0.34 : 1,
|
||||
transform: batchOpening || batchRecovering ? `translate(${54 + index * 22}px, ${20 + index * 12}px) rotate(${8 + index * 5}deg) scale(.98)` : `translate(${34 + index * 18}px, ${14 + index * 10}px) rotate(${6 + index * 4}deg)`,
|
||||
transform:
|
||||
batchOpening || batchRecovering ? `translate(${54 + index * 22}px, ${20 + index * 12}px) rotate(${8 + index * 5}deg) scale(.98)` : `translate(${34 + index * 18}px, ${14 + index * 10}px) rotate(${6 + index * 4}deg)`,
|
||||
zIndex: -index - 1,
|
||||
}}
|
||||
>
|
||||
|
||||
@@ -5,6 +5,7 @@ import { AlertCircle, BookOpenCheck, CheckCircle2, ChevronRight, Clapperboard, C
|
||||
import { useCanvasNodeActions } from "./canvas-node-action-context";
|
||||
|
||||
import { canvasThemes } from "@/lib/canvas-theme";
|
||||
import type { CanvasNodeRenderLOD } from "@/lib/canvas/canvas-node-lod";
|
||||
import { canvasConnectionTilt } from "@/lib/canvas/canvas-connection-tilt";
|
||||
import { storyboardMinNodeHeight } from "@/lib/canvas/canvas-storyboard-layout";
|
||||
import { resourceStorageLabel, resourceStorageLocation, resourceStorageTitle } from "@/lib/canvas/resource-storage-status";
|
||||
@@ -20,6 +21,7 @@ type CanvasTheme = (typeof canvasThemes)[keyof typeof canvasThemes];
|
||||
|
||||
type CanvasNodeProps = {
|
||||
data: CanvasNodeData;
|
||||
renderLOD?: CanvasNodeRenderLOD;
|
||||
dragOffset?: Position;
|
||||
scale: number;
|
||||
isSelected: boolean;
|
||||
@@ -68,6 +70,7 @@ type CanvasNodeProps = {
|
||||
|
||||
export const CanvasNode = React.memo(function CanvasNode({
|
||||
data,
|
||||
renderLOD = "full",
|
||||
dragOffset,
|
||||
scale,
|
||||
isSelected,
|
||||
@@ -128,6 +131,8 @@ export const CanvasNode = React.memo(function CanvasNode({
|
||||
const isBatchChild = data.type === CanvasNodeType.Image && Boolean(data.metadata?.batchRootId);
|
||||
const showStatusTrack = Boolean(resourceLabel || data.metadata?.locked || isBatchRoot || (isBatchChild && !readOnly) || (hasMediaContent && !readOnly));
|
||||
const isActive = isConnectionTarget || isSelected || isFocusRelated;
|
||||
const effectiveRenderLOD: CanvasNodeRenderLOD = renderLOD === "full" || hovered || isEditingContent || isEditingTitle || mediaActive ? "full" : renderLOD;
|
||||
const showChrome = effectiveRenderLOD === "full";
|
||||
const nodeState = isFocusRelated ? "focus" : isConnectionTarget ? "target" : isSelected ? "selected" : isRelated && !isBatchChild ? "related" : "idle";
|
||||
const showOutputConnection = getNodeDefinition(data.type)?.showOutputConnection !== false;
|
||||
const assetTags = data.metadata?.assetTags?.filter((tag) => tag.trim()) || [];
|
||||
@@ -272,6 +277,7 @@ export const CanvasNode = React.memo(function CanvasNode({
|
||||
return (
|
||||
<div
|
||||
data-node-id={data.id}
|
||||
data-node-lod={effectiveRenderLOD}
|
||||
className={`node-element absolute flex select-none flex-col ${dragOffset ? "cursor-grabbing" : data.type === CanvasNodeType.Drawing ? "cursor-pointer" : "cursor-default"} ${isSelected && data.type === CanvasNodeType.Video ? "z-[var(--z-node-toolbar)]" : isSelected || isFocusRelated || isConnectionTarget ? "z-[var(--z-node-active)]" : "z-[var(--z-node)]"}`}
|
||||
style={{
|
||||
transform: `translate(${data.position.x + (dragOffset?.x || 0)}px, ${data.position.y + (dragOffset?.y || 0)}px)`,
|
||||
@@ -289,7 +295,7 @@ export const CanvasNode = React.memo(function CanvasNode({
|
||||
}}
|
||||
onContextMenu={(event) => onContextMenu(event, data.id)}
|
||||
>
|
||||
<NodeExternalHeader
|
||||
{showChrome ? <NodeExternalHeader
|
||||
node={data}
|
||||
scale={scale}
|
||||
dimensionLabel={mediaDimensionLabel}
|
||||
@@ -303,7 +309,7 @@ export const CanvasNode = React.memo(function CanvasNode({
|
||||
onEdit={() => setIsEditingTitle(true)}
|
||||
onCommit={commitTitle}
|
||||
onCancel={() => { setTitleDraft(data.title); setIsEditingTitle(false); }}
|
||||
/>
|
||||
/> : null}
|
||||
<div
|
||||
className="canvas-node-shell relative h-full w-full overflow-visible rounded-[var(--node-radius)]"
|
||||
data-node-state={nodeState}
|
||||
@@ -313,7 +319,8 @@ export const CanvasNode = React.memo(function CanvasNode({
|
||||
background: hasImageContent || hasVideoContent ? "transparent" : theme.node.fill,
|
||||
// 固定占位但不绘制描边,避免聚焦切换时边框宽度变化造成白边跳动。
|
||||
border: isComposerNode ? "0" : "1px solid transparent",
|
||||
boxShadow: isComposerNode ? "none" : isSelected || isFocusRelated ? theme.node.hoverShadow : theme.node.shadow,
|
||||
boxShadow: isComposerNode || !showChrome ? "none" : isSelected || isFocusRelated ? theme.node.hoverShadow : theme.node.shadow,
|
||||
outline: !showChrome && isActive ? `1px solid ${theme.node.activeStroke}` : undefined,
|
||||
"--connection-tilt-x": `${connectionTilt?.rotateX || 0}deg`,
|
||||
"--connection-tilt-y": `${connectionTilt?.rotateY || 0}deg`,
|
||||
transformOrigin: connectionTilt?.origin,
|
||||
@@ -364,12 +371,13 @@ export const CanvasNode = React.memo(function CanvasNode({
|
||||
}
|
||||
>
|
||||
{/* 节点状态徽章(对应 #97 决策2:左上角 loading/success/error,近距离确认信号)*/}
|
||||
{data.metadata?.status && data.metadata.status !== "idle" && data.type !== CanvasNodeType.Frame ? (
|
||||
{showChrome && data.metadata?.status && data.metadata.status !== "idle" && data.type !== CanvasNodeType.Frame ? (
|
||||
<NodeStatusBadge status={data.metadata.status} />
|
||||
) : null}
|
||||
<CanvasNodeContent
|
||||
node={data}
|
||||
theme={theme}
|
||||
renderLOD={effectiveRenderLOD}
|
||||
isEditingContent={isEditingContent}
|
||||
textareaRef={textareaRef}
|
||||
isBatchRoot={isBatchRoot}
|
||||
@@ -393,7 +401,7 @@ export const CanvasNode = React.memo(function CanvasNode({
|
||||
/>
|
||||
</div>
|
||||
|
||||
{data.type === CanvasNodeType.Text && data.metadata?.workflowKind !== "character" && !readOnly ? (
|
||||
{showChrome && data.type === CanvasNodeType.Text && data.metadata?.workflowKind !== "character" && !readOnly ? (
|
||||
<div
|
||||
className={`absolute bottom-[10%] left-1/2 z-[var(--node-z-overlay)] -translate-x-1/2 motion-safe:transition motion-safe:duration-200 ${isSelected ? "translate-y-0 opacity-100" : "pointer-events-none translate-y-3 opacity-0"}`}
|
||||
onMouseDown={(event) => event.stopPropagation()}
|
||||
@@ -412,7 +420,7 @@ export const CanvasNode = React.memo(function CanvasNode({
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{data.metadata?.versionLabel ? (
|
||||
{showChrome && data.metadata?.versionLabel ? (
|
||||
<button
|
||||
type="button"
|
||||
className="absolute left-3 top-3 z-[var(--node-z-overlay)] grid size-7 place-items-center rounded-[var(--r-full)] border p-0.5 text-[var(--node-badge-fs)] font-semibold leading-none backdrop-blur-md transition-[transform,background,border-color,box-shadow] hover:-translate-y-px focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 motion-reduce:hover:translate-y-0"
|
||||
@@ -430,7 +438,7 @@ export const CanvasNode = React.memo(function CanvasNode({
|
||||
{data.metadata.versionLabel}
|
||||
</button>
|
||||
) : null}
|
||||
{showStatusTrack ? (
|
||||
{showChrome && showStatusTrack ? (
|
||||
<div className={`absolute right-3 top-3 z-[var(--node-z-overlay)] flex min-w-0 items-center justify-end gap-1 ${data.metadata?.versionLabel ? "max-w-[calc(100%-104px)]" : "max-w-[calc(100%-24px)]"}`}>
|
||||
{resourceLabel && data.type !== CanvasNodeType.Image ? <ResourceLabelBadge reference={resourceLabel} theme={theme} /> : null}
|
||||
{hasMediaContent && !readOnly ? <ResourceStorageBadge storageKey={data.metadata?.storageKey} active={isActive} theme={theme} /> : null}
|
||||
@@ -440,7 +448,7 @@ export const CanvasNode = React.memo(function CanvasNode({
|
||||
</div>
|
||||
) : null}
|
||||
{/* 批次子图操作条:成功子项提供下载/副本/设为主图,失败子项提供重试/删除 */}
|
||||
{isBatchChild && !readOnly && (hasImageContent || data.metadata?.status === "error") && (hovered || isSelected) ? (
|
||||
{showChrome && isBatchChild && !readOnly && (hasImageContent || data.metadata?.status === "error") && (hovered || isSelected) ? (
|
||||
<div
|
||||
className="absolute inset-x-0 bottom-2 z-[var(--node-z-overlay)] flex justify-center"
|
||||
onMouseDown={(event) => event.stopPropagation()}
|
||||
@@ -459,19 +467,19 @@ export const CanvasNode = React.memo(function CanvasNode({
|
||||
</div>
|
||||
) : null}
|
||||
{/* 批次主图位(折叠根节点封面)常驻下载按钮 */}
|
||||
{isBatchRoot && hasImageContent && !readOnly ? (
|
||||
{showChrome && isBatchRoot && hasImageContent && !readOnly ? (
|
||||
<div className="absolute bottom-2 right-2 z-[var(--node-z-overlay)]" onMouseDown={(event) => event.stopPropagation()} onPointerDown={(event) => event.stopPropagation()}>
|
||||
<BatchChildActionButton theme={theme} label="下载主图" icon={<Download className="size-3.5" />} onClick={() => downloadNode?.(data)} />
|
||||
</div>
|
||||
) : null}
|
||||
{assetTags.length || (showImageInfo && hasImageContent) ? (
|
||||
{showChrome && (assetTags.length || (showImageInfo && hasImageContent)) ? (
|
||||
<div className="pointer-events-none absolute inset-x-3 bottom-3 z-[var(--node-z-overlay)] flex items-end justify-between gap-2">
|
||||
{assetTags.length ? <AssetTagBadges tags={assetTags} theme={theme} /> : null}
|
||||
{showImageInfo && hasImageContent ? <CanvasNodeImageInfo node={data} /> : null}
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{!readOnly && !data.metadata?.locked && (isSelected || hovered) ? <>
|
||||
{showChrome && !readOnly && !data.metadata?.locked && (isSelected || hovered) ? <>
|
||||
<ResizeHandle corner="top-left" onMouseDown={handleResizeMouseDown} />
|
||||
<ResizeHandle corner="top-right" onMouseDown={handleResizeMouseDown} />
|
||||
<ResizeHandle corner="bottom-left" onMouseDown={handleResizeMouseDown} />
|
||||
@@ -479,8 +487,8 @@ export const CanvasNode = React.memo(function CanvasNode({
|
||||
</> : null}
|
||||
</div>
|
||||
|
||||
{!readOnly && data.type !== CanvasNodeType.Script && data.type !== CanvasNodeType.BatchTable ? <ConnectionSideRail side="left" scale={scale} theme={theme} visible={hovered || forceInputVisible} onPointerDown={(event, anchorRatio) => onConnectStart(event, data.id, "target", undefined, anchorRatio)} /> : null}
|
||||
{!readOnly && data.type !== CanvasNodeType.Script && data.type !== CanvasNodeType.Config && showOutputConnection ? <ConnectionSideRail side="right" scale={scale} theme={theme} visible={hovered} onPointerDown={(event, anchorRatio) => onConnectStart(event, data.id, "source", undefined, anchorRatio)} /> : null}
|
||||
{(showChrome || forceInputVisible) && !readOnly && data.type !== CanvasNodeType.Script && data.type !== CanvasNodeType.BatchTable ? <ConnectionSideRail side="left" scale={scale} theme={theme} visible={hovered || forceInputVisible} onPointerDown={(event, anchorRatio) => onConnectStart(event, data.id, "target", undefined, anchorRatio)} /> : null}
|
||||
{showChrome && !readOnly && data.type !== CanvasNodeType.Script && data.type !== CanvasNodeType.Config && showOutputConnection ? <ConnectionSideRail side="right" scale={scale} theme={theme} visible={hovered} onPointerDown={(event, anchorRatio) => onConnectStart(event, data.id, "source", undefined, anchorRatio)} /> : null}
|
||||
|
||||
</div>
|
||||
);
|
||||
@@ -489,6 +497,7 @@ export const CanvasNode = React.memo(function CanvasNode({
|
||||
function areCanvasNodePropsEqual(previous: CanvasNodeProps, next: CanvasNodeProps) {
|
||||
return (
|
||||
previous.data === next.data &&
|
||||
previous.renderLOD === next.renderLOD &&
|
||||
previous.dragOffset?.x === next.dragOffset?.x &&
|
||||
previous.dragOffset?.y === next.dragOffset?.y &&
|
||||
previous.scale === next.scale &&
|
||||
|
||||
@@ -128,8 +128,7 @@ export function InfiniteCanvas({ interactive = true, containerRef, viewport, app
|
||||
const container = containerRef.current;
|
||||
if (container) container.dataset.canvasViewportInteracting = "true";
|
||||
nextViewportRef.current = next;
|
||||
if (frameRef.current) return;
|
||||
frameRef.current = requestAnimationFrame((now) => {
|
||||
if (!frameRef.current) frameRef.current = requestAnimationFrame((now) => {
|
||||
frameRef.current = null;
|
||||
const pending = nextViewportRef.current;
|
||||
if (!pending) return;
|
||||
|
||||
@@ -15,8 +15,30 @@ export function sameCanvasContent(left: CanvasProject | undefined, right: Canvas
|
||||
return [...new Set([...Object.keys(a), ...Object.keys(b)])].every((key) => a[key] === b[key] || canonicalize(a[key]) === canonicalize(b[key]));
|
||||
}
|
||||
|
||||
export async function canvasContentHash(project: CanvasProject) {
|
||||
const serialized = canonicalize(canvasContentSnapshot(project));
|
||||
type ContentSnapshot = ReturnType<typeof canvasContentSnapshot>;
|
||||
const contentHashes = new WeakMap<CanvasProject["nodes"], { content: ContentSnapshot; hash: Promise<string> }>();
|
||||
|
||||
// Store updates are immutable. Reuse a hash across viewport/revision-only copies;
|
||||
// any content field/reference change invalidates it. Weak keys bound its lifetime.
|
||||
export function canvasContentHash(project: CanvasProject): Promise<string> {
|
||||
const content = canvasContentSnapshot(project);
|
||||
const cached = contentHashes.get(project.nodes);
|
||||
if (cached && sameContentReferences(cached.content, content)) return cached.hash;
|
||||
const hash = hashContent(content);
|
||||
contentHashes.set(project.nodes, { content, hash });
|
||||
void hash.catch(() => {
|
||||
if (contentHashes.get(project.nodes)?.hash === hash) contentHashes.delete(project.nodes);
|
||||
});
|
||||
return hash;
|
||||
}
|
||||
|
||||
function sameContentReferences(a: ContentSnapshot, b: ContentSnapshot) {
|
||||
const keys = Object.keys(a) as (keyof ContentSnapshot)[];
|
||||
return keys.length === Object.keys(b).length && keys.every((key) => a[key] === b[key]);
|
||||
}
|
||||
|
||||
async function hashContent(content: ContentSnapshot) {
|
||||
const serialized = canonicalize(content);
|
||||
// LAN HTTP deployments may lack Web Crypto. Keep an exact baseline there;
|
||||
// a lossy checksum could incorrectly discard an unsaved draft during login.
|
||||
if (!globalThis.crypto?.subtle) return `json:${serialized}`;
|
||||
|
||||
12
web/src/lib/canvas/canvas-node-lod.ts
Normal file
12
web/src/lib/canvas/canvas-node-lod.ts
Normal file
@@ -0,0 +1,12 @@
|
||||
export type CanvasNodeRenderLOD = "shell" | "preview" | "full";
|
||||
|
||||
// Hysteresis prevents mounting/unmounting editors around the overview boundary.
|
||||
export function canvasOverviewMode(scale: number, previous: boolean) {
|
||||
return previous ? scale < 0.27 : scale < 0.23;
|
||||
}
|
||||
|
||||
export function resolveCanvasNodeLOD(overview: boolean, inView: boolean, inEntry: boolean, editing: boolean): CanvasNodeRenderLOD {
|
||||
if (editing) return "full";
|
||||
if (inView) return overview ? "preview" : "full";
|
||||
return inEntry ? "preview" : "shell";
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
import { canvasNodeBounds, type CanvasSpatialBounds, type CanvasSpatialIndex } from "@/lib/canvas/canvas-spatial-index";
|
||||
import type { CanvasNodeData } from "@/types/canvas";
|
||||
|
||||
const intersects = (a: CanvasSpatialBounds, b: CanvasSpatialBounds) => a.right > b.left && a.left < b.right && a.bottom > b.top && a.top < b.bottom;
|
||||
export const intersectsCanvasBounds = (a: CanvasSpatialBounds, b: CanvasSpatialBounds) => a.right > b.left && a.left < b.right && a.bottom > b.top && a.top < b.bottom;
|
||||
|
||||
/** 预算只能裁减屏外预加载,不能裁掉屏内节点或正在交互的节点。 */
|
||||
export function selectCanvasVisibleNodes({
|
||||
@@ -25,8 +25,8 @@ export function selectCanvasVisibleNodes({
|
||||
const node = nodeById.get(id);
|
||||
if (!node || hiddenIds.has(id)) continue;
|
||||
const bounds = canvasNodeBounds(node);
|
||||
if (forcedIds.has(id) || intersects(bounds, view)) visible.push(node);
|
||||
else if (retainedIds.has(id) || intersects(bounds, enter)) overscan.push(node);
|
||||
if (forcedIds.has(id) || intersectsCanvasBounds(bounds, view)) visible.push(node);
|
||||
else if (retainedIds.has(id) || intersectsCanvasBounds(bounds, enter)) overscan.push(node);
|
||||
}
|
||||
return [...visible, ...overscan.slice(0, Math.max(0, budget - visible.length))];
|
||||
}
|
||||
|
||||
37
web/src/lib/canvas/task-ticker.ts
Normal file
37
web/src/lib/canvas/task-ticker.ts
Normal file
@@ -0,0 +1,37 @@
|
||||
// One clock per canvas runtime, not one timer per loading node. No work while
|
||||
// hidden or when the final loading node unmounts.
|
||||
const listeners = new Set<() => void>();
|
||||
let now = Date.now();
|
||||
let timer: ReturnType<typeof setInterval> | undefined;
|
||||
|
||||
export const taskTickerSnapshot = () => now;
|
||||
export const idleTaskTickerSubscribe = () => () => {};
|
||||
|
||||
function tick() {
|
||||
now = Date.now();
|
||||
for (const listener of listeners) listener();
|
||||
}
|
||||
|
||||
function reconcileTimer() {
|
||||
if (timer !== undefined) clearInterval(timer);
|
||||
timer = undefined;
|
||||
if (listeners.size && (typeof document === "undefined" || !document.hidden)) {
|
||||
tick();
|
||||
timer = setInterval(tick, 1000);
|
||||
}
|
||||
}
|
||||
|
||||
export function subscribeTaskTicker(listener: () => void) {
|
||||
listeners.add(listener);
|
||||
if (listeners.size === 1) {
|
||||
if (typeof document !== "undefined") document.addEventListener("visibilitychange", reconcileTimer);
|
||||
reconcileTimer();
|
||||
}
|
||||
return () => {
|
||||
listeners.delete(listener);
|
||||
if (!listeners.size) {
|
||||
if (typeof document !== "undefined") document.removeEventListener("visibilitychange", reconcileTimer);
|
||||
reconcileTimer();
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import type { CanvasBatchConnectionPreview } from "@/lib/canvas/canvas-batch-con
|
||||
import { sortCanvasNodesByStackOrder, type CanvasNodeStackOrder } from "@/lib/canvas/canvas-node-stack-order";
|
||||
import type { CanvasResourceReference } from "@/lib/canvas/canvas-resource-references";
|
||||
import { isFrameNode } from "@/lib/canvas/canvas-frame";
|
||||
import type { CanvasNodeRenderLOD } from "@/lib/canvas/canvas-node-lod";
|
||||
import type { CanvasDisplayConnection, CanvasFolderStyle, CanvasFolderTheme, CanvasNodeData, ConnectionHandle, Position, SelectionBox } from "@/types/canvas";
|
||||
|
||||
type DragPreview = { x: number; y: number; nodeIds: Set<string> } | null;
|
||||
@@ -28,6 +29,7 @@ type CanvasProjectWorldLayersProps = {
|
||||
connectionApproach: CanvasConnectionApproach;
|
||||
nodeById: Map<string, CanvasNodeData>;
|
||||
visibleNodes: CanvasNodeData[];
|
||||
nodeRenderLODById: Map<string, CanvasNodeRenderLOD>;
|
||||
nodeStackOrder: CanvasNodeStackOrder;
|
||||
frameChildrenById: Map<string, CanvasNodeData[]>;
|
||||
linkedFolderPreviewNodesById: Map<string, CanvasNodeData[]>;
|
||||
@@ -136,6 +138,7 @@ export const CanvasProjectWorldLayers = memo(function CanvasProjectWorldLayers(p
|
||||
<CanvasFrameNode
|
||||
key={node.id}
|
||||
data={node}
|
||||
renderLOD={props.nodeRenderLODById.get(node.id) || "full"}
|
||||
dragOffset={props.dragPreview?.nodeIds.has(node.id) ? props.dragPreview : undefined}
|
||||
childNodes={framePreviewNodes(node)}
|
||||
scale={viewportScale}
|
||||
@@ -153,6 +156,7 @@ export const CanvasProjectWorldLayers = memo(function CanvasProjectWorldLayers(p
|
||||
<CanvasNode
|
||||
key={node.id}
|
||||
data={node}
|
||||
renderLOD={props.nodeRenderLODById.get(node.id) || "full"}
|
||||
dragOffset={props.dragPreview?.nodeIds.has(node.id) ? props.dragPreview : undefined}
|
||||
scale={viewportScale}
|
||||
isSelected={props.selectedNodeIds.has(node.id)}
|
||||
|
||||
@@ -1409,6 +1409,7 @@ function InfiniteCanvasPage() {
|
||||
imageEditNode,
|
||||
mentionReferencesByNodeId,
|
||||
nodeById,
|
||||
nodeRenderLODById,
|
||||
previewNode,
|
||||
reduceMediaEffects,
|
||||
relatedHighlight,
|
||||
@@ -2692,6 +2693,7 @@ function InfiniteCanvasPage() {
|
||||
connectionTargetNodeId={connectionTargetNodeId}
|
||||
nodeById={nodeById}
|
||||
visibleNodes={visibleNodes}
|
||||
nodeRenderLODById={nodeRenderLODById}
|
||||
nodeStackOrder={nodeStackOrder}
|
||||
frameChildrenById={frameChildrenById}
|
||||
linkedFolderPreviewNodesById={linkedFolderPreviewNodesById}
|
||||
|
||||
@@ -1,20 +1,39 @@
|
||||
import { useEffect } from "react";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
|
||||
import { listGenerationTasks, type GenerationTask } from "@/services/api/task-center";
|
||||
import { listGenerationTasks, subscribeGenerationTasks, type GenerationTask } from "@/services/api/task-center";
|
||||
|
||||
export function useCanvasActiveTasks(projectId: string, enabled: boolean) {
|
||||
const queryClient = useQueryClient();
|
||||
const query = useQuery<GenerationTask[]>({
|
||||
queryKey: ["canvas-active-tasks", projectId],
|
||||
// Agent 的持久化执行仍复用任务队列/计费生命周期,但不应占据画布右上角的“生成任务”浮层。
|
||||
// 多取一页再过滤,避免 Agent 排在前面时把真正的画布生成任务挤掉。
|
||||
queryFn: () => listGenerationTasks(30, { projectId, activeOnly: true }).then((tasks) => tasks.filter((task) => !isInternalAgentTask(task)).slice(0, 5)),
|
||||
queryFn: ({ signal }) => listGenerationTasks(30, { projectId, activeOnly: true }, undefined, signal).then((tasks) => tasks.filter((task) => !isInternalAgentTask(task)).slice(0, 5)),
|
||||
enabled: enabled && Boolean(projectId),
|
||||
refetchInterval: (current) => (current.state.data?.length ? 2_000 : 10_000),
|
||||
// Shared task observers provide live updates. Lists only discover missed/new tasks.
|
||||
refetchInterval: 10_000,
|
||||
refetchIntervalInBackground: false,
|
||||
refetchOnWindowFocus: true,
|
||||
});
|
||||
|
||||
const taskIds = JSON.stringify((query.data || []).map((task) => task.id).sort());
|
||||
useEffect(() => {
|
||||
if (!enabled || !projectId) return;
|
||||
return subscribeGenerationTasks(JSON.parse(taskIds) as string[], (task) => {
|
||||
if (task.projectId !== projectId || isInternalAgentTask(task)) return;
|
||||
queryClient.setQueryData<GenerationTask[]>(["canvas-active-tasks", projectId], (current) => {
|
||||
if (!current) return current;
|
||||
const previous = current.find((item) => item.id === task.id);
|
||||
if (!previous || previous.updatedAt > task.updatedAt) return current;
|
||||
if (task.status !== "queued" && task.status !== "running") return current.filter((item) => item.id !== task.id);
|
||||
return current.map((item) => item.id === task.id ? task : item);
|
||||
});
|
||||
});
|
||||
}, [enabled, projectId, queryClient, taskIds]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!enabled || !projectId) return;
|
||||
const handleTaskChanged = (event: Event) => {
|
||||
const task = (event as CustomEvent<{ task?: GenerationTask }>).detail?.task;
|
||||
if (task?.projectId === projectId) void query.refetch();
|
||||
@@ -25,7 +44,7 @@ export function useCanvasActiveTasks(projectId: string, enabled: boolean) {
|
||||
window.removeEventListener("canvas:task-created", handleTaskChanged);
|
||||
window.removeEventListener("canvas:task-cancelled", handleTaskChanged);
|
||||
};
|
||||
}, [projectId, query.refetch]);
|
||||
}, [enabled, projectId, query.refetch]);
|
||||
|
||||
return {
|
||||
tasks: query.data || [],
|
||||
|
||||
@@ -254,12 +254,12 @@ export function useCanvasProjectLifecycle({
|
||||
useEffect(() => {
|
||||
if (!projectLoaded || historyPausedRef.current) return;
|
||||
const snapshot = { nodes, connections, chatSessions, activeChatId, canvasAppearance, backgroundMode, showImageInfo };
|
||||
if (!observedContentRef.current || JSON.stringify(observedContentRef.current) === JSON.stringify(snapshot)) return;
|
||||
if (!observedContentRef.current || sameCanvasHistorySnapshot(observedContentRef.current, snapshot)) return;
|
||||
observedContentRef.current = snapshot;
|
||||
const patch = { nodes, connections, chatSessions, activeChatId, appearance: canvasAppearance, backgroundMode, showImageInfo };
|
||||
const stored = useCanvasStore.getState().projects.find((project) => project.id === projectId);
|
||||
// 远端结果投影到编辑器不是一次本地编辑,避免改写时间戳并触发反向保存。
|
||||
if (stored && Object.entries(patch).every(([key, value]) => JSON.stringify(stored[key as keyof CanvasProject]) === JSON.stringify(value))) return;
|
||||
if (stored && sameCanvasPatch(stored, patch)) return;
|
||||
updateProject(projectId, patch);
|
||||
}, [activeChatId, backgroundMode, canvasAppearance, chatSessions, connections, historyPausedRef, nodes, projectId, projectLoaded, showImageInfo, updateProject]);
|
||||
|
||||
@@ -317,7 +317,7 @@ export function useCanvasProjectLifecycle({
|
||||
|
||||
const persistLocalEdits = useCallback(async () => {
|
||||
const snapshot = { nodes: nodesRef.current, connections: connectionsRef.current, chatSessions, activeChatId, canvasAppearance, backgroundMode, showImageInfo };
|
||||
if (observedContentRef.current && JSON.stringify(observedContentRef.current) !== JSON.stringify(snapshot)) {
|
||||
if (observedContentRef.current && !sameCanvasHistorySnapshot(observedContentRef.current, snapshot)) {
|
||||
updateProject(projectId, {
|
||||
nodes: nodesRef.current,
|
||||
connections: connectionsRef.current,
|
||||
@@ -407,6 +407,26 @@ export function useCanvasProjectLifecycle({
|
||||
}
|
||||
|
||||
|
||||
function sameCanvasHistorySnapshot(left: CanvasHistorySnapshot, right: CanvasHistorySnapshot) {
|
||||
return left.nodes === right.nodes
|
||||
&& left.connections === right.connections
|
||||
&& left.chatSessions === right.chatSessions
|
||||
&& left.activeChatId === right.activeChatId
|
||||
&& left.canvasAppearance === right.canvasAppearance
|
||||
&& left.backgroundMode === right.backgroundMode
|
||||
&& left.showImageInfo === right.showImageInfo;
|
||||
}
|
||||
|
||||
function sameCanvasPatch(project: CanvasProject, patch: Pick<CanvasProject, "nodes" | "connections" | "chatSessions" | "activeChatId" | "backgroundMode" | "showImageInfo"> & { appearance: CanvasProject["appearance"] }) {
|
||||
return project.nodes === patch.nodes
|
||||
&& project.connections === patch.connections
|
||||
&& project.chatSessions === patch.chatSessions
|
||||
&& project.activeChatId === patch.activeChatId
|
||||
&& project.appearance === patch.appearance
|
||||
&& project.backgroundMode === patch.backgroundMode
|
||||
&& project.showImageInfo === patch.showImageInfo;
|
||||
}
|
||||
|
||||
function mergeHydratedSessions(currentSessions: CanvasAssistantSession[], hydratedSessions: CanvasAssistantSession[]) {
|
||||
const hydratedById = new Map(hydratedSessions.map((session) => [session.id, session]));
|
||||
return currentSessions.map((session) => {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useEffect, useMemo, useRef } from "react";
|
||||
import { useEffect, useMemo, useRef, useState } from "react";
|
||||
|
||||
import { buildNodeGenerationInputs, type NodeGenerationInput } from "@/components/canvas/canvas-node-generation";
|
||||
import { isFrameNode } from "@/lib/canvas/canvas-frame";
|
||||
@@ -7,7 +7,8 @@ import { canvasNodeRenderBudget, canvasNodeRenderPadding, CANVAS_MAX_RENDERED_CO
|
||||
import { buildCanvasNodeMentionReferenceMap, buildCanvasResourceReferences, buildToolMentionReference, parseToolMentionTokens } from "@/lib/canvas/canvas-resource-references";
|
||||
import { buildSkillMentionReferences } from "@/lib/canvas/canvas-skill-mentions";
|
||||
import { buildCanvasSpatialIndex, canvasNodeBounds, type CanvasSpatialIndex, type CanvasSpatialIndexEntry } from "@/lib/canvas/canvas-spatial-index";
|
||||
import { selectCanvasVisibleNodes } from "@/lib/canvas/canvas-node-visibility";
|
||||
import { canvasOverviewMode, resolveCanvasNodeLOD, type CanvasNodeRenderLOD } from "@/lib/canvas/canvas-node-lod";
|
||||
import { intersectsCanvasBounds, selectCanvasVisibleNodes } from "@/lib/canvas/canvas-node-visibility";
|
||||
import type { Skill } from "@/services/api/skills";
|
||||
import type { Asset, ImageAsset } from "@/stores/use-asset-store";
|
||||
import type { DirectorScene } from "@/types/director";
|
||||
@@ -176,7 +177,8 @@ export function useCanvasRenderModel({
|
||||
return index;
|
||||
}, [nodes]);
|
||||
const renderedNodeIdsRef = useRef<Set<string>>(new Set());
|
||||
const visibleNodes = useMemo(() => {
|
||||
const forcedRenderNodeIds = useMemo(() => new Set([...selectedNodeIds, ...(dragPreview?.nodeIds || [])]), [dragPreview, selectedNodeIds]);
|
||||
const candidateNodes = useMemo(() => {
|
||||
const frames: CanvasNodeData[] = [];
|
||||
const regular: CanvasNodeData[] = [];
|
||||
selectCanvasVisibleNodes({
|
||||
@@ -185,13 +187,74 @@ export function useCanvasRenderModel({
|
||||
...renderBounds,
|
||||
hiddenIds: renderHiddenNodeIds,
|
||||
retainedIds: renderedNodeIdsRef.current,
|
||||
forcedIds: new Set([...selectedNodeIds, ...(dragPreview?.nodeIds || [])]),
|
||||
forcedIds: forcedRenderNodeIds,
|
||||
budget: canvasNodeRenderBudget(viewport.k),
|
||||
}).forEach((node) => {
|
||||
(isFrameNode(node) ? frames : regular).push(node);
|
||||
});
|
||||
return [...frames, ...regular];
|
||||
}, [dragPreview, nodeById, nodeSpatialIndex, renderBounds, renderHiddenNodeIds, selectedNodeIds, viewport.k]);
|
||||
}, [forcedRenderNodeIds, nodeById, nodeSpatialIndex, renderBounds, renderHiddenNodeIds, viewport.k]);
|
||||
const immediateRenderNodeIds = useMemo(() => {
|
||||
const ids = new Set(forcedRenderNodeIds);
|
||||
candidateNodes.forEach((node) => {
|
||||
if (ids.has(node.id) || intersectsCanvasBounds(canvasNodeBounds(node), renderBounds.view)) ids.add(node.id);
|
||||
});
|
||||
return ids;
|
||||
}, [candidateNodes, forcedRenderNodeIds, renderBounds.view]);
|
||||
const [mountedNodeIds, setMountedNodeIds] = useState<Set<string>>(() => new Set());
|
||||
useEffect(() => {
|
||||
const candidateIds = new Set(candidateNodes.map((node) => node.id));
|
||||
setMountedNodeIds((current) => {
|
||||
const next = new Set<string>();
|
||||
current.forEach((id) => {
|
||||
if (candidateIds.has(id)) next.add(id);
|
||||
});
|
||||
immediateRenderNodeIds.forEach((id) => next.add(id));
|
||||
return next.size === current.size && [...next].every((id) => current.has(id)) ? current : next;
|
||||
});
|
||||
const queue = candidateNodes
|
||||
.filter((node) => !immediateRenderNodeIds.has(node.id))
|
||||
.sort((left, right) => {
|
||||
const leftDistance = distanceToBounds(canvasNodeBounds(left), renderBounds.view);
|
||||
const rightDistance = distanceToBounds(canvasNodeBounds(right), renderBounds.view);
|
||||
return leftDistance - rightDistance;
|
||||
});
|
||||
let cursor = 0;
|
||||
let frameId = 0;
|
||||
const schedule = () => {
|
||||
frameId = requestAnimationFrame(() => {
|
||||
const startedAt = performance.now();
|
||||
const additions: string[] = [];
|
||||
while (cursor < queue.length && additions.length < 12 && performance.now() - startedAt < 4) additions.push(queue[cursor++].id);
|
||||
if (additions.length) {
|
||||
setMountedNodeIds((current) => {
|
||||
if (additions.every((id) => current.has(id))) return current;
|
||||
const next = new Set(current);
|
||||
additions.forEach((id) => next.add(id));
|
||||
return next;
|
||||
});
|
||||
}
|
||||
if (cursor < queue.length) schedule();
|
||||
});
|
||||
};
|
||||
if (queue.length && typeof window !== "undefined") schedule();
|
||||
return () => cancelAnimationFrame(frameId);
|
||||
}, [candidateNodes, immediateRenderNodeIds, renderBounds.view]);
|
||||
const visibleNodes = useMemo(() => candidateNodes.filter((node) => immediateRenderNodeIds.has(node.id) || mountedNodeIds.has(node.id)), [candidateNodes, immediateRenderNodeIds, mountedNodeIds]);
|
||||
const overviewRef = useRef(false);
|
||||
const overview = canvasOverviewMode(viewport.k, overviewRef.current);
|
||||
useEffect(() => { overviewRef.current = overview; }, [overview]);
|
||||
const nodeRenderLODById = useMemo(() => {
|
||||
const result = new Map<string, CanvasNodeRenderLOD>();
|
||||
for (const node of visibleNodes) {
|
||||
// Selection/drag keeps every node visible, not every editor mounted.
|
||||
const editing = selectedNodeIds.size === 1 && selectedNodeIds.has(node.id);
|
||||
const inView = intersectsCanvasBounds(canvasNodeBounds(node), renderBounds.view);
|
||||
const inEntry = intersectsCanvasBounds(canvasNodeBounds(node), renderBounds.enter);
|
||||
result.set(node.id, resolveCanvasNodeLOD(overview, inView, inEntry, editing));
|
||||
}
|
||||
return result;
|
||||
}, [overview, selectedNodeIds, renderBounds.enter, renderBounds.view, visibleNodes]);
|
||||
useEffect(() => {
|
||||
renderedNodeIdsRef.current = new Set(visibleNodes.map((node) => node.id));
|
||||
}, [visibleNodes]);
|
||||
@@ -397,6 +460,7 @@ export function useCanvasRenderModel({
|
||||
imageEditNode,
|
||||
mentionReferencesByNodeId,
|
||||
nodeById,
|
||||
nodeRenderLODById,
|
||||
previewNode,
|
||||
reduceMediaEffects,
|
||||
relatedHighlight,
|
||||
@@ -413,3 +477,9 @@ export function useCanvasRenderModel({
|
||||
visibleNodes,
|
||||
};
|
||||
}
|
||||
|
||||
function distanceToBounds(node: { left: number; top: number; right: number; bottom: number }, bounds: { left: number; top: number; right: number; bottom: number }) {
|
||||
const dx = node.right < bounds.left ? bounds.left - node.right : node.left > bounds.right ? node.left - bounds.right : 0;
|
||||
const dy = node.bottom < bounds.top ? bounds.top - node.bottom : node.top > bounds.bottom ? node.top - bounds.bottom : 0;
|
||||
return Math.hypot(dx, dy);
|
||||
}
|
||||
|
||||
@@ -15,7 +15,7 @@ import type { CanvasProject } from "@/stores/canvas/use-canvas-store";
|
||||
import { flushCanvasStorePersistence, useCanvasStore } from "@/stores/canvas/use-canvas-store";
|
||||
import { useSyncProgressStore } from "@/stores/use-sync-progress-store";
|
||||
import { useCanvasHistoryStore } from "@/stores/canvas/use-canvas-history-store";
|
||||
import { repairMissingCanvasAssets, collectCanvasMediaAssetIds, rebindInconsistentCanvasAssets, type CanvasAssetRebindResult } from "@/services/canvas-asset-repair";
|
||||
import { repairMissingCanvasAssets, repairMissingCanvasVideoPreviews, collectCanvasMediaAssetIds, rebindInconsistentCanvasAssets, type CanvasAssetRebindResult } from "@/services/canvas-asset-repair";
|
||||
import { canvasNodeToAsset } from "@/lib/canvas/canvas-node-asset";
|
||||
import { applyAgentCanvasPatch, type AgentCanvasPatch } from "@/lib/canvas/agent-canvas-patch";
|
||||
|
||||
@@ -412,6 +412,9 @@ export function scheduleRemoteUserDataSync() {
|
||||
|
||||
export function formatLocalSavedRemotePending(localAction: string, error: unknown): string {
|
||||
const detail = error instanceof Error && error.message.trim() ? error.message.trim() : "未知错误";
|
||||
if (error instanceof ApiError && error.reason === "canvas_history_resources_missing") {
|
||||
return `${localAction},云端同步已暂停:${detail}。请修复缺失素材或从有效历史版本恢复。`;
|
||||
}
|
||||
if (error instanceof ApiError && (error.status === 409 || error.status === 428)) {
|
||||
return `${localAction},云端同步已暂停:${detail}。请保留草稿并加载最新版本。`;
|
||||
}
|
||||
@@ -583,9 +586,9 @@ export async function deleteCanvasProjectsWithRemoteSync(ids: string[]) {
|
||||
});
|
||||
}
|
||||
|
||||
export async function saveRemoteUserDataNow(input?: string | readonly string[] | { force?: boolean }) {
|
||||
export async function saveRemoteUserDataNow(input?: string | readonly string[] | { force?: boolean; repairMissingResources?: boolean }) {
|
||||
const projectId = typeof input === "string" || Array.isArray(input) ? input as string | readonly string[] : undefined;
|
||||
const options = input && typeof input === "object" && !Array.isArray(input) ? input as { force?: boolean } : {};
|
||||
const options = input && typeof input === "object" && !Array.isArray(input) ? input as { force?: boolean; repairMissingResources?: boolean } : {};
|
||||
const epoch = sessionEpoch;
|
||||
if (!activeRemoteUserId) throw new Error("尚未建立云端同步会话,本地内容尚未保存到云端");
|
||||
requireRemoteUserDataBaseline();
|
||||
@@ -602,6 +605,11 @@ export async function saveRemoteUserDataNow(input?: string | readonly string[] |
|
||||
syncQueued = true;
|
||||
await syncPromise;
|
||||
assertNoConflict();
|
||||
// The in-flight drain may have started before this explicit repair/force
|
||||
// request. Re-enter after it settles so the user's intent is not lost.
|
||||
if (options.force || options.repairMissingResources) {
|
||||
return saveRemoteUserDataNow(input);
|
||||
}
|
||||
return;
|
||||
}
|
||||
syncPromise = withRemoteUserDataSyncExclusive(async () => {
|
||||
@@ -630,6 +638,8 @@ export async function forceOverwriteRemoteCanvasSync(): Promise<CanvasAssetRebin
|
||||
const rebind = await withRemoteUserDataSyncExclusive(async () => {
|
||||
if (epoch !== sessionEpoch) throw new Error("账号已切换,已停止修复保存");
|
||||
requireRemoteUserDataBaseline();
|
||||
await repairMissingCanvasVideoPreviews();
|
||||
if (epoch !== sessionEpoch) throw new Error("账号已切换,已停止修复保存");
|
||||
const projects = useCanvasStore.getState().projects;
|
||||
// 服务端素材记录是 guard 实际校验的事实;本地缓存可能落后,须先取回再判定绑定一致性。
|
||||
const claimedIds = [...collectCanvasMediaAssetIds(projects)];
|
||||
@@ -638,17 +648,18 @@ export async function forceOverwriteRemoteCanvasSync(): Promise<CanvasAssetRebin
|
||||
const { assets } = await getRemoteAssetsByIds(claimedIds.slice(offset, offset + 100));
|
||||
remoteAssets.push(...assets);
|
||||
}
|
||||
if (epoch !== sessionEpoch) throw new Error("账号已切换,已停止修复保存");
|
||||
const remoteById = new Map(remoteAssets.map((asset) => [asset.id, asset]));
|
||||
const merged = [...remoteAssets, ...useAssetStore.getState().assets.filter((asset) => !remoteById.has(asset.id))];
|
||||
const result = rebindInconsistentCanvasAssets(parseAssetRecordList(merged));
|
||||
await Promise.all([flushCanvasStorePersistence(), flushAssetStorePersistence()]);
|
||||
return result;
|
||||
});
|
||||
await saveRemoteUserDataNow({ force: true });
|
||||
await saveRemoteUserDataNow({ force: true, repairMissingResources: true });
|
||||
return rebind;
|
||||
}
|
||||
|
||||
async function drainRemoteUserDataChanges(options: { force?: boolean } = {}) {
|
||||
async function drainRemoteUserDataChanges(options: { force?: boolean; repairMissingResources?: boolean } = {}) {
|
||||
const uploaded = new Map<string, string>();
|
||||
do {
|
||||
syncQueued = false;
|
||||
@@ -656,7 +667,7 @@ async function drainRemoteUserDataChanges(options: { force?: boolean } = {}) {
|
||||
} while (syncQueued);
|
||||
}
|
||||
|
||||
async function saveRemoteUserDataBatch(uploaded: Map<string, string>, options: { force?: boolean } = {}) {
|
||||
async function saveRemoteUserDataBatch(uploaded: Map<string, string>, options: { force?: boolean; repairMissingResources?: boolean } = {}) {
|
||||
// 中央兜底:任何调用方只要把持久媒体写进画布,提交前都会先补齐素材记录与 assetId。
|
||||
// 页面级入口仍主动入库,以便立即反馈;这里负责阻止遗漏入口形成远端幽灵资源。
|
||||
const changedProjectIds = new Set(useCanvasStore.getState().projects.filter((project) => !sameCanvasContent(acknowledgedProjects.get(project.id), project)).map((project) => project.id));
|
||||
@@ -719,7 +730,7 @@ async function saveRemoteUserDataBatch(uploaded: Map<string, string>, options: {
|
||||
message: "正在保存画布结构",
|
||||
});
|
||||
}
|
||||
const { project: saved } = await upsertRemoteCanvasProject(sanitizeCanvasProjectForRemoteSync(remotePayload));
|
||||
const { project: saved } = await upsertRemoteCanvasProject(sanitizeCanvasProjectForRemoteSync(remotePayload), { repairMissingResources: options.repairMissingResources === true });
|
||||
if (!Number.isSafeInteger(saved.revision) || saved.revision !== source.revision! + 1) {
|
||||
throw new ApiError("服务端未返回有效画布版本,请加载云端最新版本", { status: 409 });
|
||||
}
|
||||
@@ -739,7 +750,7 @@ async function saveRemoteUserDataBatch(uploaded: Map<string, string>, options: {
|
||||
useSyncProgressStore.getState().setProjectProgress(source.id, { phase: pending ? "pending" : "done", message: pending ? "有新修改等待保存" : "已保存到云端" });
|
||||
if (pending) syncQueued = true;
|
||||
} catch (error) {
|
||||
const conflict = error instanceof ApiError && (error.status === 409 || error.status === 428);
|
||||
const conflict = error instanceof ApiError && error.reason !== "canvas_history_resources_missing" && (error.status === 409 || error.status === 428);
|
||||
useSyncProgressStore.getState().setProjectProgress(source.id, {
|
||||
phase: conflict ? "conflict" : "error",
|
||||
message: error instanceof Error ? error.message : "云端同步失败,等待重试",
|
||||
|
||||
@@ -512,6 +512,10 @@ export const useCanvasStore = create<CanvasStore>()(
|
||||
const current = state.projects.find((project) => project.id === id);
|
||||
if (!current) return state;
|
||||
const next = { ...current, ...patch };
|
||||
if (Object.keys(patch).every((key) => key === "viewport")) {
|
||||
if (samePersistenceValue(current.viewport, next.viewport)) return state;
|
||||
return { projects: state.projects.map((project) => project === current ? next : project) };
|
||||
}
|
||||
const contentChanged = !sameCanvasContent(current, next);
|
||||
if (!contentChanged && samePersistenceValue(current.viewport, next.viewport)) return state;
|
||||
if (contentChanged) next.updatedAt = new Date().toISOString();
|
||||
|
||||
27
web/test/canvas-node-lod.test.ts
Normal file
27
web/test/canvas-node-lod.test.ts
Normal file
@@ -0,0 +1,27 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { canvasOverviewMode, resolveCanvasNodeLOD } from "../src/lib/canvas/canvas-node-lod";
|
||||
|
||||
describe("canvas overview rendering", () => {
|
||||
test("uses hysteresis without retaining full editors at 5%", () => {
|
||||
expect(canvasOverviewMode(0.05, false)).toBe(true);
|
||||
expect(canvasOverviewMode(0.24, false)).toBe(false);
|
||||
expect(canvasOverviewMode(0.24, true)).toBe(true);
|
||||
expect(canvasOverviewMode(0.27, true)).toBe(false);
|
||||
});
|
||||
test("keeps 5000 visible representations without 5000 business editors", () => {
|
||||
const levels = Array.from({ length: 5000 }, (_, i) => resolveCanvasNodeLOD(true, true, true, i === 23));
|
||||
expect(levels.filter((level) => level === "full")).toHaveLength(1);
|
||||
expect(levels.filter((level) => level === "preview")).toHaveLength(4999);
|
||||
expect(resolveCanvasNodeLOD(false, true, true, false)).toBe("full");
|
||||
expect(resolveCanvasNodeLOD(true, false, false, false)).toBe("shell");
|
||||
expect(resolveCanvasNodeLOD(true, false, false, true)).toBe("full");
|
||||
});
|
||||
test("wires LOD into both node kinds and the memo comparator", () => {
|
||||
const world = readFileSync(new URL("../src/pages/canvas/canvas-project-world-layers.tsx", import.meta.url), "utf8");
|
||||
const node = readFileSync(new URL("../src/components/canvas/canvas-node.tsx", import.meta.url), "utf8");
|
||||
expect(world.match(/renderLOD=\{props.nodeRenderLODById/g)).toHaveLength(2);
|
||||
expect(node).toContain("previous.renderLOD === next.renderLOD");
|
||||
expect(node).not.toContain('|| isSelected || Boolean(dragOffset) ? "full"');
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user