perf(canvas): 画布渲染 - 降低大画布节点开销

This commit is contained in:
ddCat
2026-09-24 00:05:32 +08:00
parent 8822cb137c
commit 8a35a0ea98
17 changed files with 734 additions and 352 deletions

View File

@@ -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}

View File

@@ -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));
}

View File

@@ -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,
}}
>

View File

@@ -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 &&

View File

@@ -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;