merge: 解决与 master 的冲突,保留双方改动
This commit is contained in:
@@ -100,14 +100,14 @@ function AssetsPage({ isAuthenticated, onOpenLogin }: AssetsPageProps) {
|
||||
setContextMenu({ x: e.clientX, y: e.clientY, asset });
|
||||
}, []);
|
||||
|
||||
const handleDeleteAsset = useCallback(async () => {
|
||||
if (!contextMenu) return;
|
||||
const { asset } = contextMenu;
|
||||
const handleDeleteAsset = useCallback(async (asset?: LibraryAssetItem) => {
|
||||
const target = asset || contextMenu?.asset;
|
||||
if (!target) return;
|
||||
setContextMenu(null);
|
||||
try {
|
||||
await assetClient.delete(asset.id);
|
||||
setServerAssets((prev) => prev.filter((a) => a.id !== asset.id));
|
||||
setServerNotice(`已删除 ${asset.name}`);
|
||||
await assetClient.delete(target.id);
|
||||
setServerAssets((prev) => prev.filter((a) => a.id !== target.id));
|
||||
setServerNotice(`已删除 ${target.name}`);
|
||||
} catch (err) {
|
||||
setServerNotice(err instanceof Error ? err.message : "删除失败");
|
||||
}
|
||||
@@ -287,32 +287,42 @@ function AssetsPage({ isAuthenticated, onOpenLogin }: AssetsPageProps) {
|
||||
{visibleAssets.length ? (
|
||||
<div className="asset-grid asset-grid--desktop motion-stagger">
|
||||
{visibleAssets.map((asset) => (
|
||||
<button
|
||||
key={asset.id}
|
||||
type="button"
|
||||
className="asset-card asset-card--desktop"
|
||||
onClick={() => setPreviewAsset(asset)}
|
||||
onContextMenu={(e) => handleContextMenu(e, asset)}
|
||||
aria-label={`预览素材 ${asset.name}`}
|
||||
>
|
||||
<div className={`asset-card__thumb ${asset.thumbClass}`}>
|
||||
{asset.imageUrl ? <OptimizedImage src={asset.imageUrl} alt={asset.name} /> : null}
|
||||
</div>
|
||||
<div className="asset-card__body">
|
||||
<div className="asset-card__head">
|
||||
<strong>{asset.name}</strong>
|
||||
<span className={`studio-status-bar__badge ${statusBadgeClass[asset.status]}`}>
|
||||
{statusLabel[asset.status]}
|
||||
</span>
|
||||
<div key={asset.id} className="asset-card-wrapper">
|
||||
<button
|
||||
type="button"
|
||||
className="asset-card asset-card--desktop"
|
||||
onClick={() => setPreviewAsset(asset)}
|
||||
onContextMenu={(e) => handleContextMenu(e, asset)}
|
||||
aria-label={`预览素材 ${asset.name}`}
|
||||
>
|
||||
<div className={`asset-card__thumb ${asset.thumbClass}`}>
|
||||
{asset.imageUrl ? <OptimizedImage src={asset.imageUrl} alt={asset.name} /> : null}
|
||||
</div>
|
||||
<p className="asset-card__desc">{asset.description}</p>
|
||||
<div className="asset-card__tags">
|
||||
{asset.tags.slice(0, 2).map((tag) => (
|
||||
<span key={tag}>{tag}</span>
|
||||
))}
|
||||
<div className="asset-card__body">
|
||||
<div className="asset-card__head">
|
||||
<strong>{asset.name}</strong>
|
||||
<span className={`studio-status-bar__badge ${statusBadgeClass[asset.status]}`}>
|
||||
{statusLabel[asset.status]}
|
||||
</span>
|
||||
</div>
|
||||
<p className="asset-card__desc">{asset.description}</p>
|
||||
<div className="asset-card__tags">
|
||||
{asset.tags.slice(0, 2).map((tag) => (
|
||||
<span key={tag}>{tag}</span>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</button>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="asset-card__delete"
|
||||
title="删除素材"
|
||||
onClick={(e) => { e.stopPropagation(); void handleDeleteAsset(asset); }}
|
||||
aria-label={`删除 ${asset.name}`}
|
||||
>
|
||||
<DeleteOutlined />
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
) : isLoading ? (
|
||||
|
||||
@@ -3717,6 +3717,9 @@ function CanvasPage({
|
||||
<ReactFlow
|
||||
nodes={[]}
|
||||
edges={[]}
|
||||
nodesDraggable={false}
|
||||
nodesConnectable={false}
|
||||
elementsSelectable={false}
|
||||
minZoom={0.3}
|
||||
maxZoom={1.6}
|
||||
panOnDrag={false}
|
||||
@@ -5531,6 +5534,11 @@ function CanvasPage({
|
||||
role="menu"
|
||||
onClick={(event) => event.stopPropagation()}
|
||||
onContextMenu={(event) => event.preventDefault()}
|
||||
onMouseMove={(event) => {
|
||||
if (pendingLinkPort) {
|
||||
setPendingLinkPreviewPoint(getCanvasWorldPointFromClient(event.clientX, event.clientY));
|
||||
}
|
||||
}}
|
||||
>
|
||||
<div className="studio-canvas-add-node-menu__title">新建节点并连接</div>
|
||||
<button
|
||||
@@ -5542,8 +5550,6 @@ function CanvasPage({
|
||||
const pos = getTextNodePositionFromClient(connectionDropMenu.originLeft, connectionDropMenu.originTop);
|
||||
pendingAutoConnectRef.current = connectionDropMenu.sourcePort;
|
||||
addTextNode(undefined, pos);
|
||||
setPendingLinkPort(null);
|
||||
setPendingLinkPreviewPoint(null);
|
||||
setConnectionDropMenu(null);
|
||||
}}
|
||||
>
|
||||
@@ -5559,8 +5565,6 @@ function CanvasPage({
|
||||
const pos = getTextNodePositionFromClient(connectionDropMenu.originLeft, connectionDropMenu.originTop);
|
||||
pendingAutoConnectRef.current = connectionDropMenu.sourcePort;
|
||||
addImageNode("", "图片节点", pos);
|
||||
setPendingLinkPort(null);
|
||||
setPendingLinkPreviewPoint(null);
|
||||
setConnectionDropMenu(null);
|
||||
}}
|
||||
>
|
||||
@@ -5576,8 +5580,6 @@ function CanvasPage({
|
||||
const pos = getTextNodePositionFromClient(connectionDropMenu.originLeft, connectionDropMenu.originTop);
|
||||
pendingAutoConnectRef.current = connectionDropMenu.sourcePort;
|
||||
addVideoNode(pos);
|
||||
setPendingLinkPort(null);
|
||||
setPendingLinkPreviewPoint(null);
|
||||
setConnectionDropMenu(null);
|
||||
}}
|
||||
>
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,4 +1,4 @@
|
||||
import { Fragment, useCallback, useEffect, useRef, useState } from "react";
|
||||
import { Fragment, useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import {
|
||||
CopyOutlined,
|
||||
DownloadOutlined,
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
PLAN_STEPS_DISPLAY,
|
||||
type EcommerceVideoStage,
|
||||
type EcommerceVideoSceneTask,
|
||||
type EcommerceVideoPlanProgress,
|
||||
type EcommerceVideoPlanResult,
|
||||
type PlanStep,
|
||||
} from "./ecommerceVideoTypes";
|
||||
@@ -22,6 +23,7 @@ import type { AdVideoUserConfig } from "../../api/adVideoPlanClient";
|
||||
import { ServerRequestError } from "../../api/serverConnection";
|
||||
import { saveToolResultToLocal, addToolResultToAssetLibrary } from "../workbench/toolResultActions";
|
||||
import { useAppStore } from "../../stores";
|
||||
import { useGenerationTasks } from "../../hooks/useGenerationTasks";
|
||||
import {
|
||||
saveEcommerceVideoState,
|
||||
loadEcommerceVideoState,
|
||||
@@ -44,10 +46,51 @@ const ALL_STEPS: PlanStep[] = [
|
||||
"creative", "storyboard", "prompts", "compliance",
|
||||
];
|
||||
|
||||
function hashString(value: string): string {
|
||||
let hash = 2166136261;
|
||||
for (let index = 0; index < value.length; index += 1) {
|
||||
hash ^= value.charCodeAt(index);
|
||||
hash = Math.imul(hash, 16777619);
|
||||
}
|
||||
return (hash >>> 0).toString(36);
|
||||
}
|
||||
|
||||
function buildInputFingerprint(input: {
|
||||
productImageDataUrls: string[];
|
||||
requirement: string;
|
||||
platform: string;
|
||||
aspectRatio: string;
|
||||
durationSeconds: number;
|
||||
resolution: string;
|
||||
}): string {
|
||||
const imageCount = input.productImageDataUrls.length;
|
||||
return hashString([
|
||||
String(imageCount),
|
||||
input.requirement.trim(),
|
||||
input.platform,
|
||||
input.aspectRatio,
|
||||
input.durationSeconds,
|
||||
input.resolution,
|
||||
].join("::"));
|
||||
}
|
||||
|
||||
function mapResolutionToQuality(res: string): "720P" | "1080P" {
|
||||
return res.includes("720") ? "720P" : "1080P";
|
||||
}
|
||||
|
||||
function stepCompletedFromProgress(step: PlanStep, p: EcommerceVideoPlanProgress): boolean {
|
||||
switch (step) {
|
||||
case "upload": return Boolean(p.imageUrls?.length);
|
||||
case "analyze": return p.imageDescription !== undefined;
|
||||
case "summary": return Boolean(p.summary);
|
||||
case "selling": return Boolean(p.selling);
|
||||
case "creative": return Boolean(p.creatives?.length);
|
||||
case "storyboard": return Boolean(p.storyboard);
|
||||
case "prompts": return Boolean(p.videoPrompts);
|
||||
case "compliance": return Boolean(p.compliance);
|
||||
}
|
||||
}
|
||||
|
||||
export default function EcommerceVideoWorkspace({
|
||||
isAuthenticated,
|
||||
productImageDataUrls,
|
||||
@@ -60,38 +103,67 @@ export default function EcommerceVideoWorkspace({
|
||||
}: EcommerceVideoWorkspaceProps) {
|
||||
const [stage, setStage] = useState<EcommerceVideoStage>("idle");
|
||||
const [planResult, setPlanResult] = useState<EcommerceVideoPlanResult | null>(null);
|
||||
const [planProgress, setPlanProgress] = useState<EcommerceVideoPlanProgress | null>(null);
|
||||
const [scenes, setScenes] = useState<EcommerceVideoSceneTask[]>([]);
|
||||
const [completedSteps, setCompletedSteps] = useState<PlanStep[]>([]);
|
||||
const [sourceImageUrls, setSourceImageUrls] = useState<string[]>([]);
|
||||
const [currentStep, setCurrentStep] = useState<PlanStep | null>(null);
|
||||
const [failedStep, setFailedStep] = useState<PlanStep | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [actionNotice, setActionNotice] = useState<string | null>(null);
|
||||
const abortControllerRef = useRef<AbortController | null>(null);
|
||||
const renderAbortRef = useRef({ current: false });
|
||||
const setView = useAppStore((s) => s.setView);
|
||||
const keepaliveRestoredRef = useRef(false);
|
||||
const keepaliveRestoredFingerprintRef = useRef<string | null>(null);
|
||||
const keepalivePollingStartedRef = useRef(false);
|
||||
const generation = useGenerationTasks({ sourceView: "ecommerce" });
|
||||
const sceneStoreIdMap = useRef<Map<number, string>>(new Map());
|
||||
const inputFingerprint = useMemo(
|
||||
() => buildInputFingerprint({ productImageDataUrls, requirement, platform, aspectRatio, durationSeconds, resolution }),
|
||||
[productImageDataUrls, requirement, platform, aspectRatio, durationSeconds, resolution],
|
||||
);
|
||||
|
||||
// ── Keep-alive: restore saved state on mount ─────────────
|
||||
useEffect(() => {
|
||||
if (keepaliveRestoredRef.current) return;
|
||||
keepaliveRestoredRef.current = true;
|
||||
const saved = loadEcommerceVideoState();
|
||||
if (keepaliveRestoredFingerprintRef.current === inputFingerprint) return;
|
||||
keepaliveRestoredFingerprintRef.current = inputFingerprint;
|
||||
const saved = loadEcommerceVideoState(inputFingerprint);
|
||||
if (!saved) return;
|
||||
if (saved.stage === "idle" || saved.stage === "cancelled") return;
|
||||
// Restore completed / in-progress states — results persist across page switches
|
||||
setStage(saved.stage);
|
||||
setCompletedSteps(saved.completedSteps || []);
|
||||
setPlanResult(saved.planResult);
|
||||
setPlanProgress((saved as { planProgress?: EcommerceVideoPlanProgress | null }).planProgress || null);
|
||||
setScenes(saved.scenes || []);
|
||||
setSourceImageUrls(saved.sourceImageUrls || saved.planResult?.imageUrls || []);
|
||||
}, []);
|
||||
}, [inputFingerprint]);
|
||||
|
||||
// ── Keep-alive: save state on changes ───────────────────
|
||||
useEffect(() => {
|
||||
if (stage === "idle" || stage === "cancelled") return;
|
||||
saveEcommerceVideoState({ stage, completedSteps, planResult, scenes, sourceImageUrls });
|
||||
}, [stage, completedSteps, planResult, scenes, sourceImageUrls]);
|
||||
saveEcommerceVideoState({ inputFingerprint, stage, completedSteps, planResult, planProgress, scenes, sourceImageUrls });
|
||||
}, [inputFingerprint, stage, completedSteps, planResult, planProgress, scenes, sourceImageUrls]);
|
||||
|
||||
// ── Auto-advance: skip manual "next step" clicks ─────────
|
||||
const autoAdvanceTriggeredRef = useRef(false);
|
||||
useEffect(() => {
|
||||
if (autoAdvanceTriggeredRef.current) return;
|
||||
const delay = 600;
|
||||
if (stage === "planned" && planResult && scenes.length > 0) {
|
||||
autoAdvanceTriggeredRef.current = true;
|
||||
const timer = setTimeout(() => { void handleGenerateImages(); }, delay);
|
||||
return () => clearTimeout(timer);
|
||||
}
|
||||
if (stage === "imaged" && scenes.every((s) => s.imageUrl)) {
|
||||
autoAdvanceTriggeredRef.current = true;
|
||||
const timer = setTimeout(() => { void handleRenderVideos(); }, delay);
|
||||
return () => clearTimeout(timer);
|
||||
}
|
||||
if (stage === "idle" || stage === "cancelled") {
|
||||
autoAdvanceTriggeredRef.current = false;
|
||||
}
|
||||
}, [stage, scenes, planResult]);
|
||||
|
||||
// ── Keep-alive: resume polling for running tasks ──────────
|
||||
useEffect(() => {
|
||||
@@ -253,40 +325,89 @@ export default function EcommerceVideoWorkspace({
|
||||
|
||||
// ── Phase 1: Planning ──────────────────────────────────────
|
||||
|
||||
const handlePlan = async () => {
|
||||
if (!isAuthenticated) { onRequestLogin?.(); return; }
|
||||
if (!productImageDataUrls.length && !requirement.trim()) {
|
||||
setError("请先上传产品图片或填写商品说明"); return;
|
||||
}
|
||||
const runPlanFlow = async (resume: EcommerceVideoPlanProgress | null) => {
|
||||
abortControllerRef.current?.abort();
|
||||
const controller = new AbortController();
|
||||
abortControllerRef.current = controller;
|
||||
setStage("planning"); setError(null);
|
||||
setCompletedSteps([]); setCurrentStep(null);
|
||||
setPlanResult(null); setScenes([]); setSourceImageUrls([]);
|
||||
setStage("planning"); setError(null); setFailedStep(null);
|
||||
if (!resume) {
|
||||
setCompletedSteps([]); setPlanResult(null); setScenes([]); setSourceImageUrls([]); setPlanProgress(null);
|
||||
}
|
||||
setCurrentStep(null);
|
||||
// Mutable snapshot — async handlers must persist to localStorage directly since the component may unmount
|
||||
let livePlanProgress: EcommerceVideoPlanProgress = resume ? { ...resume } : {};
|
||||
let liveCompletedSteps: PlanStep[] = resume
|
||||
? ALL_STEPS.filter((s) => stepCompletedFromProgress(s, resume))
|
||||
: [];
|
||||
const persist = (stageNow: EcommerceVideoStage) => {
|
||||
saveEcommerceVideoState({
|
||||
inputFingerprint,
|
||||
stage: stageNow,
|
||||
completedSteps: liveCompletedSteps,
|
||||
planResult: null,
|
||||
planProgress: livePlanProgress,
|
||||
scenes: [],
|
||||
sourceImageUrls: livePlanProgress.imageUrls || [],
|
||||
});
|
||||
};
|
||||
try {
|
||||
const result = await runVideoPlan(
|
||||
productImageDataUrls, requirement, buildConfig(),
|
||||
{
|
||||
onStepStart: (step) => setCurrentStep(step),
|
||||
onStepDone: (step) => setCompletedSteps((prev) => [...prev, step]),
|
||||
onImagesUploaded: (urls) => { setSourceImageUrls(urls); saveEcommerceVideoState({ stage: "planning", completedSteps: ["upload"], planResult: null, scenes: [], sourceImageUrls: urls }); },
|
||||
onStepDone: (step) => {
|
||||
liveCompletedSteps = [...liveCompletedSteps, step];
|
||||
setCompletedSteps((prev) => [...prev, step]);
|
||||
},
|
||||
onImagesUploaded: (urls) => {
|
||||
setSourceImageUrls(urls);
|
||||
livePlanProgress = { ...livePlanProgress, imageUrls: urls };
|
||||
persist("planning");
|
||||
},
|
||||
onUploadRejected: (messages) => {
|
||||
if (messages.length) showNotice(`已跳过 ${messages.length} 张上传失败的图片`);
|
||||
},
|
||||
onPartialProgress: (progress) => {
|
||||
livePlanProgress = progress;
|
||||
setPlanProgress(progress);
|
||||
persist("planning");
|
||||
},
|
||||
resumeFrom: resume || undefined,
|
||||
signal: controller.signal,
|
||||
},
|
||||
);
|
||||
const builtScenes = buildSceneTasks(result);
|
||||
setPlanResult(result);
|
||||
setPlanProgress(null);
|
||||
setScenes(builtScenes);
|
||||
setStage("planned");
|
||||
// Persist immediately — component may be unmounted by the time React re-renders
|
||||
saveEcommerceVideoState({ stage: "planned", completedSteps: [...ALL_STEPS], planResult: result, scenes: builtScenes, sourceImageUrls: result.imageUrls });
|
||||
saveEcommerceVideoState({ inputFingerprint, stage: "planned", completedSteps: [...ALL_STEPS], planResult: result, planProgress: null, scenes: builtScenes, sourceImageUrls: result.imageUrls });
|
||||
} catch (err) {
|
||||
if ((err as Error).name === "AbortError") return;
|
||||
setError(err instanceof Error ? err.message : "策划失败");
|
||||
if ((err as Error).name === "AbortError" && controller.signal.aborted) return;
|
||||
const message = err instanceof Error ? err.message : "策划失败";
|
||||
setError(message);
|
||||
// Mark the step that was in-progress as failed so user can resume
|
||||
setFailedStep((prev) => prev || currentStep);
|
||||
setStage("idle");
|
||||
// Persist partial progress so the user can resume after a page switch
|
||||
persist("idle");
|
||||
} finally { setCurrentStep(null); }
|
||||
};
|
||||
|
||||
const handlePlan = async () => {
|
||||
if (!isAuthenticated) { onRequestLogin?.(); return; }
|
||||
if (!productImageDataUrls.length && !requirement.trim()) {
|
||||
setError("请先上传产品图片或填写商品说明"); return;
|
||||
}
|
||||
await runPlanFlow(null);
|
||||
};
|
||||
|
||||
const handleResumePlan = async () => {
|
||||
if (!isAuthenticated) { onRequestLogin?.(); return; }
|
||||
if (!planProgress) { void handlePlan(); return; }
|
||||
await runPlanFlow(planProgress);
|
||||
};
|
||||
|
||||
// ── Phase 2: Image generation per scene ──────────────────────
|
||||
|
||||
const handleGenerateImages = async () => {
|
||||
@@ -300,19 +421,34 @@ export default function EcommerceVideoWorkspace({
|
||||
const persistScenes = (next: EcommerceVideoSceneTask[]) => {
|
||||
currentScenes = next;
|
||||
setScenes(next);
|
||||
saveEcommerceVideoState({ stage: "imaging", completedSteps, planResult, scenes: next, sourceImageUrls });
|
||||
saveEcommerceVideoState({ inputFingerprint, stage: "imaging", completedSteps, planResult, scenes: next, sourceImageUrls });
|
||||
};
|
||||
for (const scene of currentScenes) {
|
||||
// Only redo scenes missing imageUrl — preserves successfully generated images on partial retry
|
||||
const scenesToProcess = currentScenes.filter((s) => !s.imageUrl);
|
||||
if (!scenesToProcess.length) { setStage("imaged"); return; }
|
||||
for (const scene of scenesToProcess) {
|
||||
if (renderAbortRef.current.current) break;
|
||||
persistScenes(currentScenes.map((s) => s.sceneId === scene.sceneId ? { ...s, status: "pending" } : s));
|
||||
persistScenes(currentScenes.map((s) => s.sceneId === scene.sceneId ? { ...s, status: "pending", error: undefined } : s));
|
||||
try {
|
||||
await renderSceneImage(
|
||||
{ sceneId: scene.sceneId, prompt: scene.prompt, aspectRatio: ratio },
|
||||
{
|
||||
onSceneImageSubmitted: (id, taskId) => persistScenes(currentScenes.map((s) => s.sceneId === id ? { ...s, imageTaskId: taskId, status: "running" } : s)),
|
||||
onSceneImageSubmitted: (id, taskId) => {
|
||||
persistScenes(currentScenes.map((s) => s.sceneId === id ? { ...s, imageTaskId: taskId, status: "running" } : s));
|
||||
const storeId = generation.submitTask({ title: `分镜${id}图片`, type: "image", status: "running", progress: 0, prompt: scene.prompt, sourceView: "ecommerce", taskId, params: { sceneId: id, phase: "imaging" } });
|
||||
sceneStoreIdMap.current.set(id, storeId);
|
||||
},
|
||||
onSceneImageProgress: (id, progress) => persistScenes(currentScenes.map((s) => s.sceneId === id ? { ...s, progress } : s)),
|
||||
onSceneImageCompleted: (id, url) => persistScenes(currentScenes.map((s) => s.sceneId === id ? { ...s, status: "idle", progress: 100, imageUrl: url } : s)),
|
||||
onSceneImageFailed: (id, err2) => persistScenes(currentScenes.map((s) => s.sceneId === id ? { ...s, status: "idle", error: err2 } : s)),
|
||||
onSceneImageCompleted: (id, url) => {
|
||||
persistScenes(currentScenes.map((s) => s.sceneId === id ? { ...s, status: "idle", progress: 100, imageUrl: url } : s));
|
||||
const sid = sceneStoreIdMap.current.get(id);
|
||||
if (sid) generation.markCompleted(sid, url);
|
||||
},
|
||||
onSceneImageFailed: (id, err2) => {
|
||||
persistScenes(currentScenes.map((s) => s.sceneId === id ? { ...s, status: "idle", error: err2 } : s));
|
||||
const sid = sceneStoreIdMap.current.get(id);
|
||||
if (sid) generation.markFailed(sid, err2);
|
||||
},
|
||||
},
|
||||
renderAbortRef.current,
|
||||
);
|
||||
@@ -324,15 +460,14 @@ export default function EcommerceVideoWorkspace({
|
||||
const allHaveImages = currentScenes.every((s) => s.imageUrl);
|
||||
const finalStage = allHaveImages ? "imaged" as const : "partial_failed" as const;
|
||||
setStage(finalStage);
|
||||
saveEcommerceVideoState({ stage: finalStage, completedSteps, planResult, scenes: currentScenes, sourceImageUrls });
|
||||
saveEcommerceVideoState({ inputFingerprint, stage: finalStage, completedSteps, planResult, scenes: currentScenes, sourceImageUrls });
|
||||
};
|
||||
|
||||
// ── Phase 3: Video rendering from generated images ──────────
|
||||
|
||||
const handleRenderVideos = async () => {
|
||||
if (!scenes.length) return;
|
||||
const firstImage = scenes[0]?.imageUrl;
|
||||
if (!firstImage) { setError("请先生成分镜图片"); return; }
|
||||
if (!scenes.some((s) => s.imageUrl)) { setError("请先生成分镜图片"); return; }
|
||||
setStage("rendering"); setError(null);
|
||||
renderAbortRef.current = { current: false };
|
||||
const quality = mapResolutionToQuality(resolution);
|
||||
@@ -340,20 +475,35 @@ export default function EcommerceVideoWorkspace({
|
||||
const persistScenes = (next: EcommerceVideoSceneTask[]) => {
|
||||
currentScenes = next;
|
||||
setScenes(next);
|
||||
saveEcommerceVideoState({ stage: "rendering", completedSteps, planResult, scenes: next, sourceImageUrls });
|
||||
saveEcommerceVideoState({ inputFingerprint, stage: "rendering", completedSteps, planResult, scenes: next, sourceImageUrls });
|
||||
};
|
||||
for (const scene of currentScenes) {
|
||||
// Only render scenes that haven't completed yet — preserves successful videos on partial retry
|
||||
const scenesToProcess = currentScenes.filter((s) => s.imageUrl && s.status !== "completed");
|
||||
if (!scenesToProcess.length) { setStage(currentScenes.every((s) => s.status === "completed") ? "completed" : "partial_failed"); return; }
|
||||
for (const scene of scenesToProcess) {
|
||||
if (renderAbortRef.current.current) break;
|
||||
if (!scene.imageUrl) continue;
|
||||
persistScenes(currentScenes.map((s) => s.sceneId === scene.sceneId ? { ...s, status: "pending" } : s));
|
||||
persistScenes(currentScenes.map((s) => s.sceneId === scene.sceneId ? { ...s, status: "pending", error: undefined } : s));
|
||||
try {
|
||||
await renderScene(
|
||||
{ sceneId: scene.sceneId, prompt: scene.prompt, durationSeconds: scene.durationSeconds, imageUrl: scene.imageUrl, aspectRatio, resolution: quality },
|
||||
{
|
||||
onSceneSubmitted: (id, taskId) => persistScenes(currentScenes.map((s) => s.sceneId === id ? { ...s, taskId, status: "running" } : s)),
|
||||
onSceneSubmitted: (id, taskId) => {
|
||||
persistScenes(currentScenes.map((s) => s.sceneId === id ? { ...s, taskId, status: "running" } : s));
|
||||
const storeId = generation.submitTask({ title: `分镜${id}视频`, type: "video", status: "running", progress: 0, prompt: scene.prompt, sourceView: "ecommerce", taskId, params: { sceneId: id, phase: "rendering" } });
|
||||
sceneStoreIdMap.current.set(id, storeId);
|
||||
},
|
||||
onSceneProgress: (id, progress) => persistScenes(currentScenes.map((s) => s.sceneId === id ? { ...s, progress } : s)),
|
||||
onSceneCompleted: (id, url) => persistScenes(currentScenes.map((s) => s.sceneId === id ? { ...s, status: "completed", progress: 100, resultUrl: url } : s)),
|
||||
onSceneFailed: (id, err2) => persistScenes(currentScenes.map((s) => s.sceneId === id ? { ...s, status: "failed", error: err2 } : s)),
|
||||
onSceneCompleted: (id, url) => {
|
||||
persistScenes(currentScenes.map((s) => s.sceneId === id ? { ...s, status: "completed", progress: 100, resultUrl: url } : s));
|
||||
const sid = sceneStoreIdMap.current.get(id);
|
||||
if (sid) generation.markCompleted(sid, url);
|
||||
},
|
||||
onSceneFailed: (id, err2) => {
|
||||
persistScenes(currentScenes.map((s) => s.sceneId === id ? { ...s, status: "failed", error: err2 } : s));
|
||||
const sid = sceneStoreIdMap.current.get(id);
|
||||
if (sid) generation.markFailed(sid, err2);
|
||||
},
|
||||
},
|
||||
renderAbortRef.current,
|
||||
);
|
||||
@@ -369,7 +519,7 @@ export default function EcommerceVideoWorkspace({
|
||||
const finalStage = allDone ? (hasFailed ? "partial_failed" as const : "completed" as const) : "rendering" as const;
|
||||
setScenes(currentScenes);
|
||||
setStage(finalStage);
|
||||
saveEcommerceVideoState({ stage: finalStage, completedSteps, planResult, scenes: currentScenes, sourceImageUrls });
|
||||
saveEcommerceVideoState({ inputFingerprint, stage: finalStage, completedSteps, planResult, scenes: currentScenes, sourceImageUrls });
|
||||
};
|
||||
|
||||
const handleCancel = () => { abortControllerRef.current?.abort(); renderAbortRef.current.current = true; setStage("cancelled"); };
|
||||
@@ -424,26 +574,32 @@ export default function EcommerceVideoWorkspace({
|
||||
|
||||
<div className="ecom-video-flowbar__actions">
|
||||
{error ? <span className="ecom-video-flowbar__error" role="alert">{error}</span> : null}
|
||||
{stage === "idle" && planProgress && (planProgress.summary || planProgress.creatives || planProgress.storyboard) ? (
|
||||
<button type="button" className="ecom-video-flow-action ecom-video-flow-action--ghost"
|
||||
onClick={() => void handleResumePlan()} title={`从「${failedStep ? PLAN_STEP_LABELS[failedStep] : "已中断处"}」继续策划`}>
|
||||
<ReloadOutlined /> 继续
|
||||
</button>
|
||||
) : null}
|
||||
{stage !== "planning" && stage !== "imaging" && stage !== "rendering" ? (
|
||||
<button type="button" className="ecom-video-flow-action"
|
||||
onClick={() => void handlePlan()} title="一键策划">
|
||||
onClick={() => void handlePlan()} title={planProgress ? "从头重新策划" : "一键策划"}>
|
||||
<PlayCircleOutlined />
|
||||
</button>
|
||||
) : null}
|
||||
{stage === "planned" ? (
|
||||
{stage === "planned" || stage === "imaged" ? (
|
||||
<button type="button" className="ecom-video-flow-action ecom-video-flow-action--ghost"
|
||||
onClick={() => void handleGenerateImages()} title="生成图片">
|
||||
<SendOutlined />
|
||||
onClick={() => void handleGenerateImages()} title={stage === "imaged" ? "重新生成分镜图" : "生成图片"}>
|
||||
{stage === "imaged" ? <ReloadOutlined /> : <SendOutlined />}
|
||||
</button>
|
||||
) : null}
|
||||
{stage === "imaged" ? (
|
||||
{stage === "imaged" || (stage === "partial_failed" && imagedScenes.length > 0) ? (
|
||||
<button type="button" className="ecom-video-flow-action ecom-video-flow-action--ghost"
|
||||
onClick={() => void handleRenderVideos()} title="生成视频">
|
||||
onClick={() => void handleRenderVideos()} title={stage === "partial_failed" ? "重新生成失败的视频" : "生成视频"}>
|
||||
<SendOutlined />
|
||||
</button>
|
||||
) : null}
|
||||
{stage === "planning" ? (
|
||||
<span className="ecom-video-flowbar__stage-label"><LoadingOutlined /> 策划中</span>
|
||||
<span className="ecom-video-flowbar__stage-label"><LoadingOutlined /> {currentStep ? PLAN_STEP_LABELS[currentStep] : "策划中"}</span>
|
||||
) : null}
|
||||
{stage === "imaging" ? (
|
||||
<span className="ecom-video-flowbar__stage-label"><LoadingOutlined /> 生成图片中</span>
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import type {
|
||||
EcommerceVideoStage,
|
||||
EcommerceVideoSceneTask,
|
||||
EcommerceVideoPlanProgress,
|
||||
EcommerceVideoPlanResult,
|
||||
PlanStep,
|
||||
} from "./ecommerceVideoTypes";
|
||||
@@ -8,18 +9,22 @@ import type {
|
||||
const KEEPALIVE_KEY = "omniai:ecommerce-video-workspace";
|
||||
|
||||
interface EcommerceVideoKeepalive {
|
||||
inputFingerprint: string;
|
||||
stage: EcommerceVideoStage;
|
||||
completedSteps: PlanStep[];
|
||||
planResult: EcommerceVideoPlanResult | null;
|
||||
planProgress?: EcommerceVideoPlanProgress | null;
|
||||
scenes: EcommerceVideoSceneTask[];
|
||||
sourceImageUrls: string[];
|
||||
savedAt: number;
|
||||
}
|
||||
|
||||
export function saveEcommerceVideoState(state: {
|
||||
inputFingerprint: string;
|
||||
stage: EcommerceVideoStage;
|
||||
completedSteps: PlanStep[];
|
||||
planResult: EcommerceVideoPlanResult | null;
|
||||
planProgress?: EcommerceVideoPlanProgress | null;
|
||||
scenes: EcommerceVideoSceneTask[];
|
||||
sourceImageUrls?: string[];
|
||||
}): void {
|
||||
@@ -35,7 +40,7 @@ export function saveEcommerceVideoState(state: {
|
||||
}
|
||||
}
|
||||
|
||||
export function loadEcommerceVideoState(): EcommerceVideoKeepalive | null {
|
||||
export function loadEcommerceVideoState(inputFingerprint: string): EcommerceVideoKeepalive | null {
|
||||
try {
|
||||
const raw = window.localStorage.getItem(KEEPALIVE_KEY);
|
||||
if (!raw) return null;
|
||||
@@ -45,6 +50,7 @@ export function loadEcommerceVideoState(): EcommerceVideoKeepalive | null {
|
||||
clearEcommerceVideoState();
|
||||
return null;
|
||||
}
|
||||
if (parsed.inputFingerprint !== inputFingerprint) return null;
|
||||
return parsed;
|
||||
} catch {
|
||||
return null;
|
||||
|
||||
@@ -11,7 +11,9 @@ import {
|
||||
import { aiGenerationClient } from "../../api/aiGenerationClient";
|
||||
import { waitForTask } from "../../api/taskSubscription";
|
||||
import { resolveVideoRequestModel } from "../../utils/resolveVideoModel";
|
||||
import { normalizeEcommerceImageMime } from "./ecommerceImageValidation";
|
||||
import type {
|
||||
EcommerceVideoPlanProgress,
|
||||
EcommerceVideoPlanResult,
|
||||
EcommerceVideoSceneTask,
|
||||
PlanStep,
|
||||
@@ -21,66 +23,129 @@ export interface PlanCallbacks {
|
||||
onStepStart: (step: PlanStep) => void;
|
||||
onStepDone: (step: PlanStep) => void;
|
||||
onImagesUploaded?: (urls: string[]) => void;
|
||||
onUploadRejected?: (messages: string[]) => void;
|
||||
onPartialProgress?: (progress: EcommerceVideoPlanProgress) => void;
|
||||
signal?: AbortSignal;
|
||||
/** Partial state from a previous run; steps with existing data are skipped. */
|
||||
resumeFrom?: EcommerceVideoPlanProgress;
|
||||
}
|
||||
|
||||
/**
|
||||
* Run the full ad video planning pipeline.
|
||||
* Supports resumption: if `resumeFrom` contains data for a step, that step is skipped.
|
||||
* After each step, `onPartialProgress` fires so callers can persist intermediate state.
|
||||
*/
|
||||
export async function runVideoPlan(
|
||||
imageDataUrls: string[],
|
||||
manualText: string,
|
||||
config: AdVideoUserConfig,
|
||||
callbacks: PlanCallbacks,
|
||||
): Promise<EcommerceVideoPlanResult> {
|
||||
const { onStepStart, onStepDone, signal } = callbacks;
|
||||
const { onStepStart, onStepDone, signal, resumeFrom = {} } = callbacks;
|
||||
const progress: EcommerceVideoPlanProgress = { ...resumeFrom };
|
||||
const emit = () => callbacks.onPartialProgress?.({ ...progress });
|
||||
|
||||
onStepStart("upload");
|
||||
const imageUrls: string[] = [];
|
||||
const SUPPORTED_IMAGE_TYPES = new Set(["image/jpeg", "image/png", "image/webp", "image/gif"]);
|
||||
for (const srcUrl of imageDataUrls) {
|
||||
try {
|
||||
const resp = await fetch(srcUrl);
|
||||
const rawBlob = await resp.blob();
|
||||
const mimeType = SUPPORTED_IMAGE_TYPES.has(rawBlob.type) ? rawBlob.type : "image/png";
|
||||
const blob = rawBlob.type === mimeType ? rawBlob : new Blob([rawBlob], { type: mimeType });
|
||||
const result = await aiGenerationClient.uploadAssetBinary(blob, { mimeType, scope: "ecommerce-product" });
|
||||
imageUrls.push(result.url);
|
||||
} catch {
|
||||
// skip images that fail to upload
|
||||
// ── Step: upload ──────────────────────────────────────
|
||||
if (!progress.imageUrls?.length) {
|
||||
onStepStart("upload");
|
||||
const imageUrls: string[] = [];
|
||||
const rejected: string[] = [];
|
||||
for (const srcUrl of imageDataUrls) {
|
||||
try {
|
||||
const resp = await fetch(srcUrl);
|
||||
const rawBlob = await resp.blob();
|
||||
const mimeType = normalizeEcommerceImageMime(rawBlob.type);
|
||||
const blob = rawBlob.type === mimeType ? rawBlob : new Blob([rawBlob], { type: mimeType });
|
||||
const dataUrl = await new Promise<string>((resolve, reject) => {
|
||||
const reader = new FileReader();
|
||||
reader.onload = () => resolve(String(reader.result || ""));
|
||||
reader.onerror = () => reject(reader.error || new Error("文件读取失败"));
|
||||
reader.readAsDataURL(blob);
|
||||
});
|
||||
const result = await aiGenerationClient.uploadAsset({ dataUrl, mimeType, scope: "ecommerce-product" });
|
||||
imageUrls.push(result.url);
|
||||
} catch (err) {
|
||||
rejected.push(err instanceof Error ? err.message : "图片上传失败");
|
||||
}
|
||||
}
|
||||
if (rejected.length) {
|
||||
progress.uploadWarnings = rejected;
|
||||
callbacks.onUploadRejected?.(rejected);
|
||||
}
|
||||
if (!imageUrls.length) throw new Error("图片上传失败,请检查图片格式或网络后重试");
|
||||
progress.imageUrls = imageUrls;
|
||||
onStepDone("upload");
|
||||
callbacks.onImagesUploaded?.(imageUrls);
|
||||
emit();
|
||||
}
|
||||
if (!imageUrls.length) throw new Error("图片上传失败,请检查图片格式或网络后重试");
|
||||
onStepDone("upload");
|
||||
callbacks.onImagesUploaded?.(imageUrls);
|
||||
|
||||
onStepStart("analyze");
|
||||
const imageDesc = await analyzeProductImages(imageUrls, signal);
|
||||
onStepDone("analyze");
|
||||
// ── Step: analyze ─────────────────────────────────────
|
||||
if (progress.imageDescription === undefined) {
|
||||
onStepStart("analyze");
|
||||
progress.imageDescription = await analyzeProductImages(progress.imageUrls!, signal);
|
||||
onStepDone("analyze");
|
||||
emit();
|
||||
}
|
||||
|
||||
onStepStart("summary");
|
||||
const summary = await buildProductSummary(imageDesc, manualText, signal);
|
||||
onStepDone("summary");
|
||||
// ── Step: summary ─────────────────────────────────────
|
||||
if (!progress.summary) {
|
||||
onStepStart("summary");
|
||||
progress.summary = await buildProductSummary(progress.imageDescription || "", manualText, signal);
|
||||
onStepDone("summary");
|
||||
emit();
|
||||
}
|
||||
|
||||
onStepStart("selling");
|
||||
const selling = await extractSellingPoints(summary, signal);
|
||||
onStepDone("selling");
|
||||
// ── Step: selling ─────────────────────────────────────
|
||||
if (!progress.selling) {
|
||||
onStepStart("selling");
|
||||
progress.selling = await extractSellingPoints(progress.summary, signal);
|
||||
onStepDone("selling");
|
||||
emit();
|
||||
}
|
||||
|
||||
onStepStart("creative");
|
||||
const creatives = await generateCreativeOptions(selling, config, signal);
|
||||
if (!creatives.length) throw new Error("未能生成有效的广告创意");
|
||||
onStepDone("creative");
|
||||
// ── Step: creative ────────────────────────────────────
|
||||
if (!progress.creatives?.length) {
|
||||
onStepStart("creative");
|
||||
progress.creatives = await generateCreativeOptions(progress.selling, config, signal);
|
||||
if (!progress.creatives.length) throw new Error("未能生成有效的广告创意");
|
||||
onStepDone("creative");
|
||||
emit();
|
||||
}
|
||||
|
||||
onStepStart("storyboard");
|
||||
const storyboard = await generateStoryboard(creatives[0], summary, config, signal);
|
||||
onStepDone("storyboard");
|
||||
// ── Step: storyboard ──────────────────────────────────
|
||||
if (!progress.storyboard) {
|
||||
onStepStart("storyboard");
|
||||
progress.storyboard = await generateStoryboard(progress.creatives[0], progress.summary, config, signal);
|
||||
onStepDone("storyboard");
|
||||
emit();
|
||||
}
|
||||
|
||||
onStepStart("prompts");
|
||||
const videoPrompts = await generateVideoPrompts(storyboard, summary, signal);
|
||||
onStepDone("prompts");
|
||||
// ── Step: prompts ─────────────────────────────────────
|
||||
if (!progress.videoPrompts) {
|
||||
onStepStart("prompts");
|
||||
progress.videoPrompts = await generateVideoPrompts(progress.storyboard, progress.summary, signal);
|
||||
onStepDone("prompts");
|
||||
emit();
|
||||
}
|
||||
|
||||
onStepStart("compliance");
|
||||
const compliance = await checkCompliance(summary, selling, storyboard, signal);
|
||||
onStepDone("compliance");
|
||||
// ── Step: compliance ──────────────────────────────────
|
||||
if (!progress.compliance) {
|
||||
onStepStart("compliance");
|
||||
progress.compliance = await checkCompliance(progress.summary, progress.selling, progress.storyboard, signal);
|
||||
onStepDone("compliance");
|
||||
emit();
|
||||
}
|
||||
|
||||
return { imageUrls, summary, selling, creatives, storyboard, videoPrompts, compliance };
|
||||
return {
|
||||
imageUrls: progress.imageUrls!,
|
||||
imageDescription: progress.imageDescription,
|
||||
summary: progress.summary!,
|
||||
selling: progress.selling!,
|
||||
creatives: progress.creatives!,
|
||||
storyboard: progress.storyboard!,
|
||||
videoPrompts: progress.videoPrompts!,
|
||||
compliance: progress.compliance!,
|
||||
};
|
||||
}
|
||||
|
||||
export interface RenderSceneImageInput {
|
||||
|
||||
@@ -36,6 +36,7 @@ export interface EcommerceVideoSceneTask {
|
||||
|
||||
export interface EcommerceVideoPlanResult {
|
||||
imageUrls: string[];
|
||||
imageDescription?: string;
|
||||
summary: ProductSummary;
|
||||
selling: SellingPointResult;
|
||||
creatives: CreativeOption[];
|
||||
@@ -44,6 +45,19 @@ export interface EcommerceVideoPlanResult {
|
||||
compliance: ComplianceCheck;
|
||||
}
|
||||
|
||||
/** Partial plan state — used as resume input when an earlier run failed mid-flow. */
|
||||
export interface EcommerceVideoPlanProgress {
|
||||
imageUrls?: string[];
|
||||
imageDescription?: string;
|
||||
uploadWarnings?: string[];
|
||||
summary?: ProductSummary;
|
||||
selling?: SellingPointResult;
|
||||
creatives?: CreativeOption[];
|
||||
storyboard?: Storyboard;
|
||||
videoPrompts?: VideoPrompt[];
|
||||
compliance?: ComplianceCheck;
|
||||
}
|
||||
|
||||
export interface EcommerceVideoDelivery {
|
||||
planResult: EcommerceVideoPlanResult | null;
|
||||
scenes: EcommerceVideoSceneTask[];
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
import {
|
||||
CameraOutlined,
|
||||
CheckOutlined,
|
||||
CheckCircleFilled,
|
||||
CloseOutlined,
|
||||
DeleteOutlined,
|
||||
EditOutlined,
|
||||
LockOutlined,
|
||||
MailOutlined,
|
||||
MobileOutlined,
|
||||
@@ -134,6 +137,48 @@ function mapAssetToSavedItem(asset: Awaited<ReturnType<typeof assetClient.list>>
|
||||
};
|
||||
}
|
||||
|
||||
function formatProfileDate(value: string | null | undefined): string {
|
||||
if (!value) return "刚刚";
|
||||
const date = new Date(value);
|
||||
if (Number.isNaN(date.getTime())) return value;
|
||||
|
||||
return new Intl.DateTimeFormat("zh-CN", {
|
||||
month: "numeric",
|
||||
day: "numeric",
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
}).format(date);
|
||||
}
|
||||
|
||||
function formatTaskType(type: WebGenerationPreviewTask["type"]): string {
|
||||
const labels: Record<WebGenerationPreviewTask["type"], string> = {
|
||||
image: "图像",
|
||||
video: "视频",
|
||||
agent: "智能体",
|
||||
"digital-human": "数字人",
|
||||
"character-mix": "角色融合",
|
||||
};
|
||||
return labels[type] || type;
|
||||
}
|
||||
|
||||
function formatTaskStatus(status: WebGenerationPreviewTask["status"]): string {
|
||||
const labels: Record<WebGenerationPreviewTask["status"], string> = {
|
||||
queued: "排队中",
|
||||
running: "生成中",
|
||||
completed: "已完成",
|
||||
failed: "失败",
|
||||
};
|
||||
return labels[status] || status;
|
||||
}
|
||||
|
||||
function formatAssetStatus(status: string | undefined): string {
|
||||
const normalized = String(status || "").toLowerCase();
|
||||
if (normalized === "completed" || normalized === "ready" || normalized === "success") return "可用";
|
||||
if (normalized === "running" || normalized === "processing") return "处理中";
|
||||
if (normalized === "failed" || normalized === "error") return "失败";
|
||||
return status || "资产";
|
||||
}
|
||||
|
||||
function ProfilePage({
|
||||
session,
|
||||
usage,
|
||||
@@ -169,6 +214,14 @@ function ProfilePage({
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
const [smsCooldown, setSmsCooldown] = useState(0);
|
||||
const [isSendingSms, setIsSendingSms] = useState(false);
|
||||
const [emailCode, setEmailCode] = useState("");
|
||||
const [emailCooldown, setEmailCooldown] = useState(0);
|
||||
const [isSendingEmail, setIsSendingEmail] = useState(false);
|
||||
const [showForgotPassword, setShowForgotPassword] = useState(false);
|
||||
const [forgotStep, setForgotStep] = useState<"email" | "code" | "newPassword">("email");
|
||||
const [forgotEmail, setForgotEmail] = useState("");
|
||||
const [forgotCode, setForgotCode] = useState("");
|
||||
const [forgotPassword, setForgotPassword] = useState("");
|
||||
|
||||
const [activePanel, setActivePanel] = useState<ProfilePanel>("works");
|
||||
const [accountPanel, setAccountPanel] = useState<AccountPanel>("credits");
|
||||
@@ -179,6 +232,9 @@ function ProfilePage({
|
||||
const [profileNotice, setProfileNotice] = useState<string | null>(null);
|
||||
const [localAvatarUrl, setLocalAvatarUrl] = useState(() => session?.user.avatarUrl || readLocalProfileValue(userId, "avatar"));
|
||||
const [profileBio, setProfileBio] = useState(() => session?.user.bio || readLocalProfileValue(userId, "bio"));
|
||||
const [isBioEditing, setIsBioEditing] = useState(false);
|
||||
const [bioEditBackup, setBioEditBackup] = useState("");
|
||||
const [bioStatusNotice, setBioStatusNotice] = useState<string | null>(null);
|
||||
const [bannerUrl, setBannerUrl] = useState(() => session?.user.backgroundUrl || readLocalProfileValue(userId, "background"));
|
||||
|
||||
const completedTasks = tasks.filter((task) => task.status === "completed");
|
||||
@@ -187,6 +243,9 @@ function ProfilePage({
|
||||
const packageLabel = session?.user.activePackages?.[0]?.name || "按量积分";
|
||||
const avatarUrl = session?.user.avatarUrl || localAvatarUrl || null;
|
||||
const displayedBio = profileBio.trim() || "这个人还没有填写个性签名";
|
||||
const emailLooksValid = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email.trim());
|
||||
const phoneLooksValid = /^1[3-9]\d{9}$/.test(phone.trim());
|
||||
const passwordLooksReady = password.length >= (mode === "register" ? 6 : 1);
|
||||
|
||||
useEffect(() => {
|
||||
setLocalAvatarUrl(session?.user.avatarUrl || readLocalProfileValue(userId, "avatar"));
|
||||
@@ -245,6 +304,70 @@ function ProfilePage({
|
||||
return () => window.clearInterval(timer);
|
||||
}, [smsCooldown]);
|
||||
|
||||
useEffect(() => {
|
||||
if (emailCooldown <= 0) return;
|
||||
const timer = window.setInterval(() => {
|
||||
setEmailCooldown((current) => Math.max(0, current - 1));
|
||||
}, 1000);
|
||||
return () => window.clearInterval(timer);
|
||||
}, [emailCooldown]);
|
||||
|
||||
const handleSendEmailCode = async (purpose: "register" | "login" | "reset" = "register") => {
|
||||
const targetEmail = purpose === "reset" ? forgotEmail : email;
|
||||
if (emailCooldown > 0 || !targetEmail.trim() || isSendingEmail) return;
|
||||
if (purpose === "register" && !betaCode.trim()) {
|
||||
setNotice("请输入企业邀请码 / 内测码后再获取验证码");
|
||||
return;
|
||||
}
|
||||
setIsSendingEmail(true);
|
||||
setNotice(null);
|
||||
try {
|
||||
const result = await keyServerClient.sendEmailCode(targetEmail, purpose, betaCode);
|
||||
setEmailCooldown(result.cooldownSeconds || 60);
|
||||
if (result.devCode) {
|
||||
setNotice(`验证码已发送(开发模式: ${result.devCode})`);
|
||||
} else {
|
||||
setNotice("验证码已发送,请查收邮件");
|
||||
}
|
||||
} catch (error) {
|
||||
setNotice(error instanceof Error ? error.message : "验证码发送失败");
|
||||
} finally {
|
||||
setIsSendingEmail(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleForgotPassword = async () => {
|
||||
if (forgotStep === "email") {
|
||||
if (!forgotEmail.trim()) { setNotice("请输入邮箱"); return; }
|
||||
try {
|
||||
await keyServerClient.forgotPassword({ email: forgotEmail });
|
||||
setForgotStep("code");
|
||||
setNotice("重置验证码已发送到您的邮箱");
|
||||
await handleSendEmailCode("reset");
|
||||
} catch (error) {
|
||||
setNotice(error instanceof Error ? error.message : "发送失败");
|
||||
}
|
||||
} else if (forgotStep === "code") {
|
||||
if (!forgotCode.trim()) { setNotice("请输入验证码"); return; }
|
||||
setForgotStep("newPassword");
|
||||
setNotice(null);
|
||||
} else {
|
||||
if (forgotPassword.length < 6) { setNotice("密码至少 6 位"); return; }
|
||||
try {
|
||||
const result = await keyServerClient.resetPassword({ email: forgotEmail, code: forgotCode, newPassword: forgotPassword });
|
||||
setNotice(result.message || "密码重置成功,请重新登录");
|
||||
setShowForgotPassword(false);
|
||||
setForgotStep("email");
|
||||
setForgotEmail("");
|
||||
setForgotCode("");
|
||||
setForgotPassword("");
|
||||
setMode("login");
|
||||
} catch (error) {
|
||||
setNotice(error instanceof Error ? error.message : "重置失败");
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const handleSendSms = async () => {
|
||||
if (smsCooldown > 0 || !phone.trim() || isSendingSms) return;
|
||||
if (mode === "register" && !betaCode.trim()) {
|
||||
@@ -289,6 +412,10 @@ function ProfilePage({
|
||||
if (!value.trim()) return "请输入验证码";
|
||||
if (value.length !== 6) return "验证码为 6 位数字";
|
||||
return "";
|
||||
case "emailCode":
|
||||
if (!value.trim()) return "请输入邮箱验证码";
|
||||
if (value.length !== 6) return "验证码为 6 位数字";
|
||||
return "";
|
||||
default:
|
||||
return "";
|
||||
}
|
||||
@@ -328,6 +455,10 @@ function ProfilePage({
|
||||
if (emailErr) errors.email = emailErr;
|
||||
const pwErr = validateField("password", password);
|
||||
if (pwErr) errors.password = pwErr;
|
||||
if (mode === "register") {
|
||||
const codeErr = validateField("emailCode", emailCode);
|
||||
if (codeErr) errors.emailCode = codeErr;
|
||||
}
|
||||
} else {
|
||||
const userErr = validateField("username", username);
|
||||
if (userErr) errors.username = userErr;
|
||||
@@ -354,7 +485,7 @@ function ProfilePage({
|
||||
const nextSession =
|
||||
mode === "login"
|
||||
? await keyServerClient.loginEmail({ email, password })
|
||||
: await keyServerClient.registerEmail({ email, password, username: username.trim() || undefined, betaCode });
|
||||
: await keyServerClient.registerEmail({ email, password, code: emailCode, username: username.trim() || undefined, betaCode });
|
||||
await onAuthComplete?.(nextSession);
|
||||
} else if (mode === "login") {
|
||||
await onLogin(username.trim(), password);
|
||||
@@ -445,8 +576,29 @@ function ProfilePage({
|
||||
void syncProfilePatch({ bio: nextBio || null });
|
||||
};
|
||||
|
||||
const startBioEdit = () => {
|
||||
setBioEditBackup(profileBio);
|
||||
setBioStatusNotice(null);
|
||||
setIsBioEditing(true);
|
||||
};
|
||||
|
||||
const confirmBioEdit = () => {
|
||||
handleBioBlur();
|
||||
setIsBioEditing(false);
|
||||
setBioStatusNotice("个性签名已保存");
|
||||
};
|
||||
|
||||
const cancelBioEdit = () => {
|
||||
setProfileBio(bioEditBackup);
|
||||
setIsBioEditing(false);
|
||||
setBioStatusNotice(null);
|
||||
};
|
||||
|
||||
const renderEmptyState = (text: string, actionLabel: string, action: () => void) => (
|
||||
<div className="profile-page__empty-state">
|
||||
<span className="profile-page__empty-mark" aria-hidden="true">
|
||||
<PlusOutlined />
|
||||
</span>
|
||||
<p className="profile-page__empty-text">{text}</p>
|
||||
<button type="button" className="profile-page__empty-btn" onClick={action}>
|
||||
<PlusOutlined />
|
||||
@@ -464,12 +616,12 @@ function ProfilePage({
|
||||
<article key={task.id} className="profile-page__list-card">
|
||||
<div className="profile-page__list-card-head">
|
||||
<strong>{task.title}</strong>
|
||||
<span>{task.type}</span>
|
||||
<span>{formatTaskType(task.type)}</span>
|
||||
</div>
|
||||
<p>{task.prompt}</p>
|
||||
<div className="profile-page__list-card-meta">
|
||||
<span>{task.status}</span>
|
||||
<span>{task.createdAt}</span>
|
||||
<span>{formatTaskStatus(task.status)}</span>
|
||||
<span>{formatProfileDate(task.createdAt)}</span>
|
||||
</div>
|
||||
</article>
|
||||
))}
|
||||
@@ -487,7 +639,7 @@ function ProfilePage({
|
||||
<article key={project.id} className="profile-page__list-card">
|
||||
<div className="profile-page__list-card-head">
|
||||
<strong>{project.name}</strong>
|
||||
<span>{project.updatedAt}</span>
|
||||
<span>{formatProfileDate(project.updatedAt)}</span>
|
||||
{onDeleteProject ? (
|
||||
<button
|
||||
type="button"
|
||||
@@ -519,12 +671,12 @@ function ProfilePage({
|
||||
<article key={asset.id} className="profile-page__list-card">
|
||||
<div className="profile-page__list-card-head">
|
||||
<strong>{asset.name}</strong>
|
||||
<span>{asset.status}</span>
|
||||
<span>{formatAssetStatus(asset.status)}</span>
|
||||
</div>
|
||||
<p>{asset.description}</p>
|
||||
<div className="profile-page__list-card-meta">
|
||||
<span>{asset.type}</span>
|
||||
<span>{asset.updatedAt}</span>
|
||||
<span>{formatProfileDate(asset.updatedAt)}</span>
|
||||
</div>
|
||||
</article>
|
||||
))}
|
||||
@@ -587,15 +739,39 @@ function ProfilePage({
|
||||
</span>
|
||||
</div>
|
||||
<strong className="profile-page__username">{displayName}</strong>
|
||||
<textarea
|
||||
className="profile-page__bio"
|
||||
value={profileBio}
|
||||
onChange={(event) => setProfileBio(event.target.value)}
|
||||
onBlur={handleBioBlur}
|
||||
placeholder={displayedBio}
|
||||
rows={2}
|
||||
maxLength={80}
|
||||
/>
|
||||
{isBioEditing ? (
|
||||
<div className="profile-page__bio-editor">
|
||||
<textarea
|
||||
className="profile-page__bio"
|
||||
value={profileBio}
|
||||
onChange={(event) => setProfileBio(event.target.value)}
|
||||
placeholder="填写一句个人签名"
|
||||
rows={2}
|
||||
maxLength={80}
|
||||
autoFocus
|
||||
/>
|
||||
<div className="profile-page__bio-actions">
|
||||
<button type="button" className="profile-page__bio-action profile-page__bio-action--save" onClick={confirmBioEdit}>
|
||||
<CheckOutlined />
|
||||
保存
|
||||
</button>
|
||||
<button type="button" className="profile-page__bio-action" onClick={cancelBioEdit}>
|
||||
<CloseOutlined />
|
||||
取消
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<button
|
||||
type="button"
|
||||
className={`profile-page__bio-display${profileBio.trim() ? "" : " is-empty"}`}
|
||||
onClick={startBioEdit}
|
||||
>
|
||||
<span>{displayedBio}</span>
|
||||
<EditOutlined className="profile-page__bio-edit-icon" />
|
||||
</button>
|
||||
)}
|
||||
{bioStatusNotice ? <span className="profile-page__bio-status">{bioStatusNotice}</span> : null}
|
||||
{profileNotice ? <span className="profile-page__sync-notice">{profileNotice}</span> : null}
|
||||
</div>
|
||||
|
||||
@@ -614,18 +790,21 @@ function ProfilePage({
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<button type="button" className="profile-page__share-btn">
|
||||
<button type="button" className="profile-page__share-btn profile-page__share-btn--plan">
|
||||
<ShareAltOutlined />
|
||||
{packageLabel}
|
||||
</button>
|
||||
|
||||
<button type="button" className="profile-page__share-btn" onClick={onOpenWorkbench}>
|
||||
<button type="button" className="profile-page__share-btn profile-page__share-btn--primary" onClick={onOpenWorkbench}>
|
||||
<PlusOutlined />
|
||||
进入工作台
|
||||
</button>
|
||||
<button type="button" className="profile-page__share-btn" onClick={onOpenCommunity}>
|
||||
<button type="button" className="profile-page__share-btn profile-page__share-btn--secondary" onClick={onOpenCommunity}>
|
||||
<ShareAltOutlined />
|
||||
打开社区
|
||||
</button>
|
||||
<button type="button" className="profile-page__share-btn" onClick={onLogout}>
|
||||
<button type="button" className="profile-page__share-btn profile-page__share-btn--danger" onClick={onLogout}>
|
||||
<LockOutlined />
|
||||
退出登录
|
||||
</button>
|
||||
</aside>
|
||||
@@ -681,13 +860,25 @@ function ProfilePage({
|
||||
<div className="profile-page__upload-card profile-page__upload-card--meta">
|
||||
{accountPanel === "credits" ? (
|
||||
<>
|
||||
<span>当前账号:{displayName}</span>
|
||||
<span>积分剩余:{(usage.balanceCents / 100).toFixed(2)}</span>
|
||||
<span className="profile-page__meta-item">
|
||||
<small>当前账号</small>
|
||||
<strong>{displayName}</strong>
|
||||
</span>
|
||||
<span className="profile-page__meta-item">
|
||||
<small>积分剩余</small>
|
||||
<strong>{(usage.balanceCents / 100).toFixed(2)}</strong>
|
||||
</span>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<span>任务总数:{tasks.length}</span>
|
||||
<span>已完成:{completedTasks.length}</span>
|
||||
<span className="profile-page__meta-item">
|
||||
<small>任务总数</small>
|
||||
<strong>{tasks.length}</strong>
|
||||
</span>
|
||||
<span className="profile-page__meta-item">
|
||||
<small>已完成</small>
|
||||
<strong>{completedTasks.length}</strong>
|
||||
</span>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
@@ -706,12 +897,30 @@ function ProfilePage({
|
||||
<source src={AUTH_SHOWCASE_VIDEO_URL} type="video/mp4" />
|
||||
</video>
|
||||
<div className="auth-page__video-overlay">
|
||||
<h1 className="auth-page__brand">OmniAI</h1>
|
||||
<p className="auth-page__tagline">一句话,从创意到成片</p>
|
||||
<div className="auth-page__features">
|
||||
<span>AI 视频生成</span>
|
||||
<span>AI 图片创作</span>
|
||||
<span>AI 电商素材</span>
|
||||
<div className="auth-page__showcase-content">
|
||||
<div className="auth-page__brand-row">
|
||||
<h1 className="auth-page__brand">OmniAI</h1>
|
||||
</div>
|
||||
<p className="auth-page__tagline">一句话,从创意到成片</p>
|
||||
<div className="auth-page__features">
|
||||
<span>AI 视频生成</span>
|
||||
<span>AI 图片创作</span>
|
||||
<span>AI 电商素材</span>
|
||||
</div>
|
||||
<div className="auth-page__showcase-stats" aria-label="平台能力">
|
||||
<span>
|
||||
<strong>Studio</strong>
|
||||
创作工作台
|
||||
</span>
|
||||
<span>
|
||||
<strong>Assets</strong>
|
||||
资产沉淀
|
||||
</span>
|
||||
<span>
|
||||
<strong>Team</strong>
|
||||
团队协作
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -762,7 +971,8 @@ function ProfilePage({
|
||||
<MailOutlined /> 邮箱
|
||||
</button>
|
||||
<button type="button" className={authTab === "phone" ? "is-active" : ""} onClick={() => { setAuthTab("phone"); setFieldErrors({}); }}>
|
||||
<MobileOutlined /> 手机验证码
|
||||
<MobileOutlined />
|
||||
<span className="auth-page__tab-label-short">手机</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
@@ -790,7 +1000,31 @@ function ProfilePage({
|
||||
</label>
|
||||
) : null}
|
||||
|
||||
{authTab === "password" ? (
|
||||
{showForgotPassword ? (
|
||||
<div className="auth-page__forgot-box">
|
||||
<p className="auth-page__forgot-title">重置密码</p>
|
||||
{forgotStep === "email" ? (
|
||||
<input value={forgotEmail} onChange={(e) => setForgotEmail(e.target.value)} placeholder="输入注册邮箱" type="email" className="auth-page__forgot-input" />
|
||||
) : forgotStep === "code" ? (
|
||||
<div className="auth-page__sms-row">
|
||||
<input value={forgotCode} onChange={(e) => setForgotCode(e.target.value)} placeholder="输入验证码" maxLength={6} />
|
||||
<button type="button" className="auth-page__sms-btn" disabled={emailCooldown > 0 || isSendingEmail} onClick={() => void handleSendEmailCode("reset")}>
|
||||
{isSendingEmail ? "发送中" : emailCooldown > 0 ? `${emailCooldown}s` : "重新发送"}
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<input type="password" value={forgotPassword} onChange={(e) => setForgotPassword(e.target.value)} placeholder="输入新密码(至少 6 位)" className="auth-page__forgot-input" />
|
||||
)}
|
||||
<div className="auth-page__forgot-actions">
|
||||
<button type="button" className="auth-page__forgot-cancel" onClick={() => { setShowForgotPassword(false); setForgotStep("email"); setForgotEmail(""); setForgotCode(""); setForgotPassword(""); setNotice(null); }}>取消</button>
|
||||
<button type="button" className="auth-page__forgot-confirm" onClick={() => void handleForgotPassword()}>
|
||||
{forgotStep === "newPassword" ? "重置密码" : "下一步"}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{!showForgotPassword && authTab === "password" ? (
|
||||
<>
|
||||
<label className={`auth-page__field${fieldErrors.username ? " auth-page__field--error" : ""}`}>
|
||||
<span>
|
||||
@@ -818,16 +1052,21 @@ function ProfilePage({
|
||||
autoComplete={mode === "login" ? "current-password" : "new-password"}
|
||||
/>
|
||||
{fieldErrors.password ? <span className="auth-page__field-error">{fieldErrors.password}</span> : null}
|
||||
{mode === "register" && passwordLooksReady && !fieldErrors.password ? (
|
||||
<span className="auth-page__field-hint">
|
||||
<CheckCircleFilled /> 密码长度符合要求
|
||||
</span>
|
||||
) : null}
|
||||
</label>
|
||||
{mode === "login" ? (
|
||||
<div className="auth-page__forgot">
|
||||
<button type="button">忘记密码?</button>
|
||||
<button type="button" onClick={() => { setShowForgotPassword(true); setForgotStep("email"); }}>忘记密码?</button>
|
||||
</div>
|
||||
) : null}
|
||||
</>
|
||||
) : null}
|
||||
|
||||
{authTab === "email" ? (
|
||||
{!showForgotPassword && authTab === "email" ? (
|
||||
<>
|
||||
{mode === "register" ? (
|
||||
<label className="auth-page__field">
|
||||
@@ -855,6 +1094,11 @@ function ProfilePage({
|
||||
autoComplete="email"
|
||||
/>
|
||||
{fieldErrors.email ? <span className="auth-page__field-error">{fieldErrors.email}</span> : null}
|
||||
{emailLooksValid && !fieldErrors.email ? (
|
||||
<span className="auth-page__field-hint">
|
||||
<CheckCircleFilled /> 邮箱格式正确
|
||||
</span>
|
||||
) : null}
|
||||
</label>
|
||||
<label className={`auth-page__field${fieldErrors.password ? " auth-page__field--error" : ""}`}>
|
||||
<span>
|
||||
@@ -869,11 +1113,16 @@ function ProfilePage({
|
||||
autoComplete={mode === "login" ? "current-password" : "new-password"}
|
||||
/>
|
||||
{fieldErrors.password ? <span className="auth-page__field-error">{fieldErrors.password}</span> : null}
|
||||
{mode === "register" && passwordLooksReady && !fieldErrors.password ? (
|
||||
<span className="auth-page__field-hint">
|
||||
<CheckCircleFilled /> 密码长度符合要求
|
||||
</span>
|
||||
) : null}
|
||||
</label>
|
||||
</>
|
||||
) : null}
|
||||
|
||||
{authTab === "phone" ? (
|
||||
{!showForgotPassword && authTab === "phone" ? (
|
||||
<>
|
||||
<label className={`auth-page__field${fieldErrors.phone ? " auth-page__field--error" : ""}`}>
|
||||
<span>
|
||||
@@ -884,6 +1133,11 @@ function ProfilePage({
|
||||
<input type="tel" value={phone} onChange={(event) => { setPhone(event.target.value); clearFieldError("phone"); }} onBlur={() => handleFieldBlur("phone", phone)} placeholder="输入手机号" autoComplete="tel" />
|
||||
</div>
|
||||
{fieldErrors.phone ? <span className="auth-page__field-error">{fieldErrors.phone}</span> : null}
|
||||
{phoneLooksValid && !fieldErrors.phone ? (
|
||||
<span className="auth-page__field-hint">
|
||||
<CheckCircleFilled /> 手机号格式正确
|
||||
</span>
|
||||
) : null}
|
||||
</label>
|
||||
<label className={`auth-page__field${fieldErrors.smsCode ? " auth-page__field--error" : ""}`}>
|
||||
<span>
|
||||
@@ -909,14 +1163,21 @@ function ProfilePage({
|
||||
</span>
|
||||
<input type="password" value={password} onChange={(event) => { setPassword(event.target.value); clearFieldError("password"); }} onBlur={() => handleFieldBlur("password", password)} placeholder="至少 6 位" autoComplete="new-password" />
|
||||
{fieldErrors.password ? <span className="auth-page__field-error">{fieldErrors.password}</span> : null}
|
||||
{passwordLooksReady && !fieldErrors.password ? (
|
||||
<span className="auth-page__field-hint">
|
||||
<CheckCircleFilled /> 密码长度符合要求
|
||||
</span>
|
||||
) : null}
|
||||
</label>
|
||||
) : null}
|
||||
</>
|
||||
) : null}
|
||||
|
||||
{notice ? <p className="auth-page__notice">{notice}</p> : null}
|
||||
{!showForgotPassword ? (
|
||||
<>
|
||||
{notice ? <p className="auth-page__notice">{notice}</p> : null}
|
||||
|
||||
<button type="submit" className="auth-page__submit" disabled={isSubmitting}>
|
||||
<button type="submit" className="auth-page__submit" disabled={isSubmitting}>
|
||||
{isSubmitting ? "处理中..." : mode === "login" ? "登录" : "注册"}
|
||||
</button>
|
||||
|
||||
@@ -936,6 +1197,8 @@ function ProfilePage({
|
||||
<MobileOutlined />
|
||||
</button>
|
||||
</div>
|
||||
</>
|
||||
) : null}
|
||||
</form>
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
import {
|
||||
BarChartOutlined,
|
||||
CheckCircleFilled,
|
||||
CopyOutlined,
|
||||
DownloadOutlined,
|
||||
FileTextOutlined,
|
||||
LoadingOutlined,
|
||||
ThunderboltOutlined,
|
||||
UploadOutlined,
|
||||
} from "@ant-design/icons";
|
||||
import { useEffect, useRef, useState, type ChangeEvent, type KeyboardEvent } from "react";
|
||||
@@ -33,6 +36,8 @@ interface HistoryEntry {
|
||||
timestamp: number;
|
||||
score: number;
|
||||
grade: string;
|
||||
script?: string;
|
||||
result?: EvalResult;
|
||||
}
|
||||
|
||||
function getGrade(score: number): string {
|
||||
@@ -54,6 +59,8 @@ const TEXT_FILE_EXTENSIONS = [
|
||||
".fountain",
|
||||
".fdx",
|
||||
".rtf",
|
||||
".docx",
|
||||
".doc",
|
||||
".csv",
|
||||
".tsv",
|
||||
".json",
|
||||
@@ -99,7 +106,7 @@ const TEXT_FILE_EXTENSIONS = [
|
||||
] as const;
|
||||
const TEXT_FILE_EXTENSION_SET = new Set<string>(TEXT_FILE_EXTENSIONS);
|
||||
const TEXT_FILE_ACCEPT = TEXT_FILE_EXTENSIONS.join(",");
|
||||
const TEXT_FILE_HINT = "支持常见文本格式:TXT / MD / Fountain / FDX / RTF / JSON / CSV / XML / HTML / YAML / LOG / 字幕等";
|
||||
const TEXT_FILE_HINT = "支持常见文本格式:TXT / MD / DOCX / Fountain / FDX / RTF / JSON / CSV / XML / HTML / YAML / LOG / 字幕等";
|
||||
|
||||
function loadHistory(): HistoryEntry[] {
|
||||
try {
|
||||
@@ -168,6 +175,68 @@ function normalizeUploadedText(raw: string, ext: string): string {
|
||||
return raw;
|
||||
}
|
||||
|
||||
async function extractDocxText(bytes: Uint8Array): Promise<string> {
|
||||
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
||||
const entries: Array<{ name: string; offset: number; size: number; compressed: boolean }> = [];
|
||||
let pos = 0;
|
||||
while (pos < bytes.length - 30) {
|
||||
if (view.getUint32(pos, true) !== 0x04034b50) break;
|
||||
const compressed = view.getUint16(pos + 10, true) !== 0;
|
||||
const compressedSize = view.getUint32(pos + 18, true);
|
||||
const fileNameLen = view.getUint16(pos + 26, true);
|
||||
const extraLen = view.getUint16(pos + 28, true);
|
||||
const name = new TextDecoder().decode(bytes.slice(pos + 30, pos + 30 + fileNameLen));
|
||||
const dataStart = pos + 30 + fileNameLen + extraLen;
|
||||
entries.push({ name, offset: dataStart, size: compressedSize, compressed });
|
||||
pos = dataStart + compressedSize;
|
||||
}
|
||||
const docEntry = entries.find((e) => e.name === "word/document.xml");
|
||||
if (!docEntry) return "";
|
||||
const xmlBytes = bytes.slice(docEntry.offset, docEntry.offset + docEntry.size);
|
||||
let xmlText: string;
|
||||
if (docEntry.compressed) {
|
||||
try {
|
||||
const ds = new DecompressionStream("deflate-raw");
|
||||
const writer = ds.writable.getWriter();
|
||||
writer.write(xmlBytes);
|
||||
writer.close();
|
||||
const reader = ds.readable.getReader();
|
||||
const chunks: Uint8Array[] = [];
|
||||
while (true) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
chunks.push(value);
|
||||
}
|
||||
const totalLen = chunks.reduce((s, c) => s + c.length, 0);
|
||||
const combined = new Uint8Array(totalLen);
|
||||
let offset = 0;
|
||||
for (const c of chunks) { combined.set(c, offset); offset += c.length; }
|
||||
xmlText = new TextDecoder().decode(combined);
|
||||
} catch {
|
||||
xmlText = new TextDecoder().decode(xmlBytes);
|
||||
}
|
||||
} else {
|
||||
xmlText = new TextDecoder().decode(xmlBytes);
|
||||
}
|
||||
const textMatches = xmlText.match(/<w:t[^>]*>([\s\S]*?)<\/w:t>/g);
|
||||
if (!textMatches) return "";
|
||||
const paraMatches = xmlText.match(/<w:p[ >][\s\S]*?<\/w:p>/g);
|
||||
if (paraMatches) {
|
||||
return paraMatches.map((p) => {
|
||||
const tMatches = p.match(/<w:t[^>]*>([\s\S]*?)<\/w:t>/g);
|
||||
if (!tMatches) return "";
|
||||
return tMatches.map((m) => m.replace(/<[^>]+>/g, "").replace(/</g, "<").replace(/>/g, ">").replace(/&/g, "&").replace(/"/g, "\"")).join("");
|
||||
}).filter(Boolean).join("\n").trim();
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
function formatFileSize(size: number): string {
|
||||
if (size < 1024) return `${size} B`;
|
||||
if (size < 1024 * 1024) return `${(size / 1024).toFixed(1)} KB`;
|
||||
return `${(size / 1024 / 1024).toFixed(1)} MB`;
|
||||
}
|
||||
|
||||
const SCORE_DIMENSIONS: ScoreDimension[] = [
|
||||
{ key: "hook", label: "钩子设计", maxScore: 20, hint: "开篇吸引力·悬念设置·黄金三秒", detail: "开篇即抛出高概念钩子,悬念设置紧凑有力。" },
|
||||
{ key: "character", label: "角色塑造", maxScore: 15, hint: "人物立体度·动机合理性·弧光设计", detail: "主角动机有铺垫,配角功能性较强,人物弧光尚可进一步深化。" },
|
||||
@@ -222,6 +291,7 @@ function ScriptTokensPage() {
|
||||
const [copied, setCopied] = useState(false);
|
||||
const [activeDim, setActiveDim] = useState<number | null>(null);
|
||||
const [animatedScore, setAnimatedScore] = useState(0);
|
||||
const [activeHistoryIndex, setActiveHistoryIndex] = useState<number>(0);
|
||||
const [history, setHistory] = useState<HistoryEntry[]>(loadHistory);
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
const scoreFrameRef = useRef<number | null>(null);
|
||||
@@ -251,7 +321,23 @@ function ScriptTokensPage() {
|
||||
const ext = getFileExtension(file.name);
|
||||
const readable = isReadableTextFile(file, ext);
|
||||
setUploadedFile({ name: file.name, size: file.size });
|
||||
if (readable) {
|
||||
if (ext === ".docx") {
|
||||
try {
|
||||
const bytes = new Uint8Array(await file.arrayBuffer());
|
||||
const text = await extractDocxText(bytes);
|
||||
if (text) {
|
||||
setScript(text);
|
||||
} else {
|
||||
setScript(`[已上传文件:${file.name}]\n\n无法从 DOCX 文件中提取文本,请尝试另存为 TXT 格式后重新上传。`);
|
||||
}
|
||||
} catch {
|
||||
setScript(`[已上传文件:${file.name}]\n\n解析 DOCX 文件失败,请尝试另存为 TXT 格式后重新上传。`);
|
||||
}
|
||||
} else if (ext === ".doc") {
|
||||
const text = await decodeTextFile(file);
|
||||
const cleaned = text.replace(/[\x00-\x08\x0b\x0c\x0e-\x1f]/g, "").replace(/\s{3,}/g, "\n\n").trim();
|
||||
setScript(cleaned || `[已上传文件:${file.name}]\n\n无法从 .doc 文件中提取文本,请另存为 .docx 或 .txt 格式。`);
|
||||
} else if (readable) {
|
||||
const text = normalizeUploadedText(await decodeTextFile(file), ext);
|
||||
setScript(text);
|
||||
} else {
|
||||
@@ -277,6 +363,8 @@ function ScriptTokensPage() {
|
||||
timestamp: Date.now(),
|
||||
score: aiResult.totalScore,
|
||||
grade: g,
|
||||
script,
|
||||
result: aiResult,
|
||||
};
|
||||
const updated = [entry, ...loadHistory().filter((h) => h.name !== entry.name || h.score !== entry.score)].sort(
|
||||
(a, b) => b.timestamp - a.timestamp,
|
||||
@@ -289,6 +377,20 @@ function ScriptTokensPage() {
|
||||
setLoading(false);
|
||||
};
|
||||
|
||||
const handleHistoryClick = (item: HistoryEntry, index: number) => {
|
||||
setActiveHistoryIndex(index);
|
||||
if (item.script) {
|
||||
setScript(item.script);
|
||||
setUploadedFile({ name: `${item.name}.txt`, size: item.script.length });
|
||||
}
|
||||
if (item.result) {
|
||||
setResult(item.result);
|
||||
} else {
|
||||
setResult(null);
|
||||
}
|
||||
setEvalError(null);
|
||||
};
|
||||
|
||||
const handleReset = () => {
|
||||
setScript("");
|
||||
setResult(null);
|
||||
@@ -346,9 +448,10 @@ function ScriptTokensPage() {
|
||||
const compactTitle = uploadedFile?.name?.replace(/\.[^.]+$/, "") ?? "剧本评测";
|
||||
const scriptMinutes = Math.max(8, Math.round(script.length / 460));
|
||||
const reportDate = new Date().toLocaleDateString("zh-CN", { month: "2-digit", day: "2-digit" });
|
||||
const statusClass = loading ? "is-loading" : result ? "is-complete" : hasContent ? "is-ready" : "is-idle";
|
||||
|
||||
return (
|
||||
<section className="script-eval-v5 page-motion">
|
||||
<section className={`script-eval-v5 page-motion ${statusClass}`}>
|
||||
<div className="script-eval-v5-page">
|
||||
{/* Left Panel */}
|
||||
<aside className="script-eval-v5-left">
|
||||
@@ -364,7 +467,10 @@ function ScriptTokensPage() {
|
||||
{uploadedFile ? (
|
||||
<div className="script-eval-v5-upload-done is-show">
|
||||
<CheckCircleFilled />
|
||||
<span className="script-eval-v5-uf-name">{uploadedFile.name}</span>
|
||||
<span className="script-eval-v5-uf-meta">
|
||||
<span className="script-eval-v5-uf-name">{uploadedFile.name}</span>
|
||||
<span className="script-eval-v5-uf-size">{formatFileSize(uploadedFile.size)}</span>
|
||||
</span>
|
||||
<span className="script-eval-v5-uf-re" onClick={(e) => { e.stopPropagation(); handleReset(); }}>
|
||||
重新上传
|
||||
</span>
|
||||
@@ -374,7 +480,7 @@ function ScriptTokensPage() {
|
||||
<div className="script-eval-v5-upload-icon"><UploadOutlined /></div>
|
||||
<div className="script-eval-v5-upload-text">拖拽或点击上传</div>
|
||||
<button type="button" className="script-eval-v5-upload-btn" onClick={(e) => { e.stopPropagation(); fileInputRef.current?.click(); }}>
|
||||
+ 上传剧本
|
||||
<UploadOutlined /> 选择剧本
|
||||
</button>
|
||||
<div className="script-eval-v5-upload-hint">{TEXT_FILE_HINT}</div>
|
||||
</>
|
||||
@@ -420,7 +526,9 @@ function ScriptTokensPage() {
|
||||
<div className="script-eval-v5-history-empty">暂无评测记录</div>
|
||||
) : (
|
||||
history.map((item, i) => (
|
||||
<div key={i} className={`script-eval-v5-history-item${i === 0 ? " is-active" : ""}`}>
|
||||
<div key={i} className={`script-eval-v5-history-item${i === activeHistoryIndex ? " is-active" : ""}`}
|
||||
onClick={() => handleHistoryClick(item, i)} role="button" tabIndex={0}
|
||||
onKeyDown={(e) => { if ((e as React.KeyboardEvent).key === "Enter") handleHistoryClick(item, i); }}>
|
||||
<div className="script-eval-v5-hi-left">
|
||||
<div className="script-eval-v5-hi-name">{item.name}</div>
|
||||
<div className="script-eval-v5-hi-date">{item.date}</div>
|
||||
@@ -445,10 +553,12 @@ function ScriptTokensPage() {
|
||||
disabled={loading || !hasContent}
|
||||
onClick={() => void handleEvaluate()}
|
||||
>
|
||||
{loading ? "◆ 评测中..." : "◆ 开始评测"}
|
||||
{loading ? <LoadingOutlined /> : <ThunderboltOutlined />}
|
||||
<span>{loading ? "评测中..." : "开始评测"}</span>
|
||||
</button>
|
||||
<button type="button" className="script-eval-v5-export-btn" disabled={!result} onClick={handleExportMarkdown}>
|
||||
导出评测报告
|
||||
<DownloadOutlined />
|
||||
<span>导出评测报告</span>
|
||||
</button>
|
||||
</div>
|
||||
</aside>
|
||||
@@ -482,6 +592,11 @@ function ScriptTokensPage() {
|
||||
<div className="page-loading-spinner" />
|
||||
<strong>AI 正在分析剧本...</strong>
|
||||
<p>正在调用模型进行六维评分,预计需要 15-30 秒</p>
|
||||
<div className="script-eval-v5-loading-steps" aria-hidden="true">
|
||||
<span>结构识别</span>
|
||||
<span>冲突评估</span>
|
||||
<span>商业潜力</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -568,13 +683,23 @@ function ScriptTokensPage() {
|
||||
<span>0%</span>
|
||||
</div>
|
||||
<div className="script-eval-report__chart-grid">
|
||||
{SCORE_DIMENSIONS.map((dim) => {
|
||||
{SCORE_DIMENSIONS.map((dim, dimIndex) => {
|
||||
const score = result.dimensionScores[dim.key] ?? 0;
|
||||
const pct = Math.max(0, Math.min(1, score / dim.maxScore));
|
||||
const lossPct = 1 - pct;
|
||||
const isPerfect = score === dim.maxScore;
|
||||
const isActive = activeDim === null || activeDim === dimIndex;
|
||||
return (
|
||||
<button key={dim.key} type="button" className="script-eval-report__bar-col">
|
||||
<button
|
||||
key={dim.key}
|
||||
type="button"
|
||||
className={`script-eval-report__bar-col${isActive ? "" : " is-dimmed"}`}
|
||||
onMouseEnter={() => setActiveDim(dimIndex)}
|
||||
onFocus={() => setActiveDim(dimIndex)}
|
||||
onMouseLeave={() => setActiveDim(null)}
|
||||
onBlur={() => setActiveDim(null)}
|
||||
aria-label={`${dim.label} ${score}/${dim.maxScore},${dim.hint}`}
|
||||
>
|
||||
<div className="script-eval-report__bar-score">
|
||||
<b>{score}</b><small>/{dim.maxScore}</small>{isPerfect ? <em>*</em> : null}
|
||||
</div>
|
||||
@@ -589,6 +714,14 @@ function ScriptTokensPage() {
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
<div className="script-eval-report__chart-note">
|
||||
<BarChartOutlined />
|
||||
<span>
|
||||
{activeDim === null
|
||||
? "悬停维度可查看当前分项表现,优先从低分项制定改稿计划。"
|
||||
: `${SCORE_DIMENSIONS[activeDim].label}:${SCORE_DIMENSIONS[activeDim].detail}`}
|
||||
</span>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<div className="script-eval-report__findings">
|
||||
|
||||
@@ -6,7 +6,6 @@ import {
|
||||
LineChartOutlined,
|
||||
ReloadOutlined,
|
||||
RightOutlined,
|
||||
SettingOutlined,
|
||||
TeamOutlined,
|
||||
UserOutlined,
|
||||
WarningOutlined,
|
||||
@@ -143,29 +142,22 @@ function TokenUsagePage({
|
||||
onSelectView,
|
||||
}: TokenUsagePageProps) {
|
||||
const [enterpriseUsage, setEnterpriseUsage] = useState<WebEnterpriseUsageSummary | null>(null);
|
||||
const [enterpriseUsageLoading, setEnterpriseUsageLoading] = useState(false);
|
||||
const [enterpriseUsageError, setEnterpriseUsageError] = useState<string | null>(null);
|
||||
const isEnterpriseAdmin = session?.user.enterpriseRole === "admin";
|
||||
const isEnterpriseAccount = Boolean(session?.user.enterpriseId || session?.user.accountType === "enterprise");
|
||||
|
||||
const refreshEnterpriseUsage = useCallback(async () => {
|
||||
if (!session) return;
|
||||
const loader = isEnterpriseAdmin ? loadEnterpriseUsage : loadPersonalUsage;
|
||||
if (!loader) {
|
||||
setEnterpriseUsage(null);
|
||||
setEnterpriseUsageError(null);
|
||||
return;
|
||||
}
|
||||
setEnterpriseUsageLoading(true);
|
||||
setEnterpriseUsageError(null);
|
||||
try {
|
||||
setEnterpriseUsage(await loader());
|
||||
} catch (error) {
|
||||
setEnterpriseUsage(null);
|
||||
setEnterpriseUsageError(error instanceof Error ? error.message : "用量数据暂时不可用");
|
||||
} finally {
|
||||
setEnterpriseUsageLoading(false);
|
||||
}
|
||||
}, [isEnterpriseAdmin, loadEnterpriseUsage, loadPersonalUsage]);
|
||||
}, [session, isEnterpriseAdmin, loadEnterpriseUsage, loadPersonalUsage]);
|
||||
|
||||
useEffect(() => {
|
||||
void refreshEnterpriseUsage();
|
||||
@@ -230,45 +222,51 @@ function TokenUsagePage({
|
||||
{ label: "账户类型", value: isEnterpriseAccount ? "企业账户" : "个人账户", tone: "good" },
|
||||
{ label: "企业空间", value: enterpriseUsage?.enterpriseName || session?.user.enterpriseName || "-" },
|
||||
];
|
||||
const pageStatusClass = enterpriseUsageLoading
|
||||
? "is-syncing"
|
||||
: enterpriseUsageError
|
||||
? "has-sync-error"
|
||||
: isLowBalance
|
||||
? "has-low-balance"
|
||||
: "is-healthy";
|
||||
|
||||
return (
|
||||
<section className="script-token-page token-usage-page management-center-page" aria-label="管理中心">
|
||||
<section className={`script-token-page token-usage-page management-center-page ${pageStatusClass}`} aria-label="管理中心">
|
||||
<main className="management-center-shell">
|
||||
<header className="management-center-toolbar" aria-label="管理中心操作">
|
||||
<div className="management-center-toolbar__title">
|
||||
<button type="button" className="management-center-toolbar__back" aria-label="返回工具盒" onClick={onOpenMore}>
|
||||
<ArrowLeftOutlined />
|
||||
</button>
|
||||
<strong>管理中心</strong>
|
||||
<span>
|
||||
<strong>管理中心</strong>
|
||||
<small>用量、成员与模型调用监控</small>
|
||||
</span>
|
||||
</div>
|
||||
<span className="management-center-status-pill">
|
||||
<span className={`management-center-status-pill ${enterpriseUsageError ? "is-error" : enterpriseUsageLoading ? "is-loading" : "is-online"}`}>
|
||||
{enterpriseUsageLoading ? "正在同步企业用量" : enterpriseUsageError || "服务器已连接"}
|
||||
</span>
|
||||
<button type="button" onClick={refreshEnterpriseUsage}>
|
||||
<button type="button" onClick={refreshEnterpriseUsage} disabled={enterpriseUsageLoading}>
|
||||
<ReloadOutlined />
|
||||
刷新数据
|
||||
</button>
|
||||
<button type="button">
|
||||
<button type="button" className="is-muted-action">
|
||||
<UserOutlined />
|
||||
成员管理
|
||||
</button>
|
||||
<button type="button" className="is-primary" onClick={() => onSelectView?.("settings")}>
|
||||
<SettingOutlined />
|
||||
服务设置
|
||||
</button>
|
||||
</header>
|
||||
|
||||
{isLowBalance ? (
|
||||
<div className="management-balance-alert" role="alert">
|
||||
<WarningOutlined />
|
||||
<span>当前余额 {formatCredits(availableBalanceCents)},可能不足以完成下一次生成,请及时充值。</span>
|
||||
<button type="button" onClick={() => onSelectView?.("settings")}>去充值</button>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<section className="management-metric-cards" aria-label="关键指标">
|
||||
{metricCards.map((card) => (
|
||||
{metricCards.map((card, index) => (
|
||||
<article key={card.key} className={`management-metric-card is-${card.tone}`}>
|
||||
<span className="management-metric-card__index">{String(index + 1).padStart(2, "0")}</span>
|
||||
<span className="management-metric-card__label">{card.label}</span>
|
||||
<strong className="management-metric-card__value">{card.value}</strong>
|
||||
<span className="management-metric-card__hint">{card.hint}</span>
|
||||
@@ -283,7 +281,7 @@ function TokenUsagePage({
|
||||
<BarChartOutlined />
|
||||
模型消耗分布
|
||||
</h2>
|
||||
<span>{modelBreakdown.length ? `${modelBreakdown.length} 个模型` : "LIVE"}</span>
|
||||
<span>{enterpriseUsageLoading ? "SYNC" : modelBreakdown.length ? `${modelBreakdown.length} 个模型` : "LIVE"}</span>
|
||||
</div>
|
||||
{modelBreakdown.length ? (
|
||||
<div className="management-model-list">
|
||||
@@ -310,7 +308,10 @@ function TokenUsagePage({
|
||||
|
||||
<article className="management-card management-status-card">
|
||||
<div className="management-card__head">
|
||||
<h2>系统状态</h2>
|
||||
<h2>
|
||||
<LineChartOutlined />
|
||||
系统状态
|
||||
</h2>
|
||||
</div>
|
||||
<dl>
|
||||
{systemStatus.map((item) => (
|
||||
@@ -364,7 +365,10 @@ function TokenUsagePage({
|
||||
|
||||
<section className="management-card management-records">
|
||||
<div className="management-card__head">
|
||||
<h2>调用记录</h2>
|
||||
<h2>
|
||||
<BarChartOutlined />
|
||||
调用记录
|
||||
</h2>
|
||||
<span>{records.length} 条记录</span>
|
||||
</div>
|
||||
<div className="management-record-table" role="table" aria-label="调用记录">
|
||||
|
||||
@@ -41,6 +41,7 @@ import { preUploadReference, resolvePreUploadedUrl } from "../../api/referenceUp
|
||||
import { assetClient } from "../../api/assetClient";
|
||||
import { communityClient } from "../../api/communityClient";
|
||||
import { RechargeModal } from "../../components/RechargeModal/RechargeModal";
|
||||
import { useGenerationTasks } from "../../hooks/useGenerationTasks";
|
||||
|
||||
import { conversationClient, type ConversationSummary } from "../../api/conversationClient";
|
||||
import { modelCapabilitiesClient } from "../../api/modelCapabilitiesClient";
|
||||
@@ -236,8 +237,10 @@ function WorkbenchPage({
|
||||
const keepaliveTasksRef = useRef<Record<string, WorkbenchKeepaliveTask>>(readStoredKeepaliveTasks());
|
||||
const taskAbortControllersRef = useRef<Map<string, AbortController>>(new Map());
|
||||
const lastScrollTopRef = useRef(0);
|
||||
const scrollActionsHideTimerRef = useRef<number | null>(null);
|
||||
const shouldFollowNewMessagesRef = useRef(true);
|
||||
const pendingScrollToLatestRef = useRef(true);
|
||||
const genTracker = useGenerationTasks({ sourceView: "workbench" });
|
||||
const renderedMessageIdsRef = useRef<string[]>([]);
|
||||
const hasHandledInitialMessagesRef = useRef(false);
|
||||
|
||||
@@ -273,6 +276,8 @@ function WorkbenchPage({
|
||||
const [promptSelectionRange, setPromptSelectionRange] = useState({ start: 0, end: 0 });
|
||||
const [mentionActiveIndex, setMentionActiveIndex] = useState(0);
|
||||
const [composerHidden, setComposerHidden] = useState(false);
|
||||
const [scrollActionsVisible, setScrollActionsVisible] = useState(false);
|
||||
const [scrollActionDirection, setScrollActionDirection] = useState<"top" | "bottom" | null>(null);
|
||||
const [workspaceStarted, setWorkspaceStarted] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -441,6 +446,27 @@ function WorkbenchPage({
|
||||
"--accent-glow": `0 0 24px rgba(${accentRgb}, 0.22)`,
|
||||
} as CSSProperties;
|
||||
|
||||
const revealScrollActionsTemporarily = useCallback((direction: "top" | "bottom") => {
|
||||
setScrollActionDirection(direction);
|
||||
setScrollActionsVisible(true);
|
||||
if (scrollActionsHideTimerRef.current !== null) {
|
||||
window.clearTimeout(scrollActionsHideTimerRef.current);
|
||||
}
|
||||
scrollActionsHideTimerRef.current = window.setTimeout(() => {
|
||||
setScrollActionsVisible(false);
|
||||
setScrollActionDirection(null);
|
||||
scrollActionsHideTimerRef.current = null;
|
||||
}, 950);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
if (scrollActionsHideTimerRef.current !== null) {
|
||||
window.clearTimeout(scrollActionsHideTimerRef.current);
|
||||
}
|
||||
};
|
||||
}, []);
|
||||
|
||||
const scrollMessagesToLatest = useCallback((behavior: ScrollBehavior = "smooth") => {
|
||||
const scroll = () => {
|
||||
const surface = messagesSurfaceRef.current;
|
||||
@@ -451,6 +477,7 @@ function WorkbenchPage({
|
||||
|
||||
setComposerHidden(false);
|
||||
shouldFollowNewMessagesRef.current = true;
|
||||
revealScrollActionsTemporarily("bottom");
|
||||
surface.scrollTo({ top: surface.scrollHeight, behavior });
|
||||
lastScrollTopRef.current = surface.scrollTop;
|
||||
};
|
||||
@@ -459,7 +486,7 @@ function WorkbenchPage({
|
||||
scroll();
|
||||
window.setTimeout(scroll, 80);
|
||||
});
|
||||
}, []);
|
||||
}, [revealScrollActionsTemporarily]);
|
||||
|
||||
const imageSettingGroups = useMemo<WorkbenchFieldGroup[]>(
|
||||
() => [
|
||||
@@ -1373,6 +1400,9 @@ function WorkbenchPage({
|
||||
const delta = top - lastScrollTopRef.current;
|
||||
const atTop = top <= edgeThreshold;
|
||||
const atBottom = top + surface.clientHeight >= surface.scrollHeight - edgeThreshold;
|
||||
if (surface.scrollHeight > surface.clientHeight + edgeThreshold && Math.abs(delta) > 1) {
|
||||
revealScrollActionsTemporarily(delta > 0 ? "bottom" : "top");
|
||||
}
|
||||
shouldFollowNewMessagesRef.current = atBottom;
|
||||
if (atTop || atBottom) {
|
||||
setComposerHidden(false);
|
||||
@@ -1384,7 +1414,7 @@ function WorkbenchPage({
|
||||
|
||||
surface.addEventListener("scroll", handleScroll, { passive: true });
|
||||
return () => surface.removeEventListener("scroll", handleScroll);
|
||||
}, [hasActivatedWorkspace]);
|
||||
}, [hasActivatedWorkspace, revealScrollActionsTemporarily]);
|
||||
|
||||
const scrollMessagesSurface = useCallback((direction: "top" | "bottom") => {
|
||||
const surface = messagesSurfaceRef.current;
|
||||
@@ -1392,8 +1422,9 @@ function WorkbenchPage({
|
||||
|
||||
const top = direction === "top" ? 0 : surface.scrollHeight;
|
||||
setComposerHidden(false);
|
||||
revealScrollActionsTemporarily(direction);
|
||||
surface.scrollTo({ top, behavior: "smooth" });
|
||||
}, []);
|
||||
}, [revealScrollActionsTemporarily]);
|
||||
|
||||
const closeToolbarMenus = () => setToolbarMenuId(null);
|
||||
const toggleToolbarMenu = (menuId: Exclude<ToolbarMenuId, null>) => {
|
||||
@@ -1851,6 +1882,7 @@ function WorkbenchPage({
|
||||
referenceUrls: refUrls.length ? refUrls : undefined,
|
||||
});
|
||||
taskId = result.taskId;
|
||||
genTracker.submitTask({ title: trimmedPrompt.slice(0, 60), type: "image", status: "running", progress: 5, prompt: trimmedPrompt, sourceView: "workbench", taskId });
|
||||
} else {
|
||||
let requestModel = resolveVideoRequestModel({
|
||||
model: taskInput.params?.model || ENTERPRISE_DEFAULT_VIDEO_MODEL,
|
||||
@@ -1870,6 +1902,7 @@ function WorkbenchPage({
|
||||
hasReferenceVideo: requestReferenceItems.some((item) => item.kind === "video"),
|
||||
});
|
||||
taskId = result.taskId;
|
||||
genTracker.submitTask({ title: trimmedPrompt.slice(0, 60), type: "video", status: "running", progress: 5, prompt: trimmedPrompt, sourceView: "workbench", taskId });
|
||||
}
|
||||
|
||||
onRefreshUsage?.();
|
||||
@@ -3022,10 +3055,13 @@ function WorkbenchPage({
|
||||
{renderComposerToolbar(false, isGenerating)}
|
||||
</div>
|
||||
</section>
|
||||
<div className="wb-chat-scroll-actions" aria-label="聊天滚动">
|
||||
<div
|
||||
className={`wb-chat-scroll-actions${scrollActionsVisible ? " is-visible" : ""}${scrollActionDirection ? ` is-${scrollActionDirection}` : ""}`}
|
||||
aria-label="聊天滚动"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
className="wb-chat-scroll-actions__button"
|
||||
className="wb-chat-scroll-actions__button wb-chat-scroll-actions__button--top"
|
||||
title="返回聊天顶部"
|
||||
aria-label="返回聊天顶部"
|
||||
onClick={() => scrollMessagesSurface("top")}
|
||||
@@ -3034,7 +3070,7 @@ function WorkbenchPage({
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="wb-chat-scroll-actions__button"
|
||||
className="wb-chat-scroll-actions__button wb-chat-scroll-actions__button--bottom"
|
||||
title="到达聊天底部"
|
||||
aria-label="到达聊天底部"
|
||||
onClick={() => scrollMessagesSurface("bottom")}
|
||||
|
||||
Reference in New Issue
Block a user