perf(canvas): 画布渲染 - 降低大画布节点开销
This commit is contained in:
@@ -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,
|
||||
}}
|
||||
>
|
||||
|
||||
Reference in New Issue
Block a user