import {
CheckCircle,
ClosedCaptioning,
Eye,
EyeSlash,
ImageSquare,
Link,
LinkBreak,
ListBullets,
PersonSimpleRun,
Plus,
Scissors,
Sparkle,
Trash,
UploadSimple,
Waveform,
X,
} from "@phosphor-icons/react";
import { useEffect, useRef, useState } from "react";
import { createPortal } from "react-dom";
import { formatTime, getSegmentStartTime } from "../lib/timeline.js";
import { LIVE_PORTRAIT_WEB_MODEL } from "../config/livePortrait.js";
import { probeLivePortraitWebEnvironment } from "../lib/livePortraitWeb.js";
import { getCaptionVoiceSegment } from "../lib/captionVoice.js";
import { findCaptionAudioLinkTarget } from "../lib/captionEditingActions.js";
import { normalizeVisualKeyframes } from "../lib/visualEffects.js";
import { MAX_SRT_FILE_BYTES, parseSrt } from "../lib/subtitles.js";
import { AiMusicGenerator, HistoryPanel, MyVoicesPanel, SmartVisionPanel, VisualEffectsPanel, VoiceSynthesisPanel } from "./panels.jsx";
function AutoEditReviewDialog({ t, autoEdit }) {
const { review, job } = autoEdit || {};
if (!review?.open || typeof document === "undefined") return null;
const complete = !job.running && review.captions.length > 0;
return createPortal(
{t("smartAutoEdit")}
{t("autoEditReviewTitle")}
{review.error ? t("autoEditReviewFailed") : complete ? t("autoEditReviewReady") : job.phase}
01{t("autoEditCandidateTitle")}
{review.candidates.length} {t("autoEditFramesUnit")}
{t("autoEditCandidateHint")}
{review.candidates.length ? {review.candidates.map((candidate, index) => (
#{String(index + 1).padStart(2, "0")}{candidate.aspectRatio}
))}
: {t("autoEditFindingScenes")}
}
02{t("autoEditModelResultTitle")}
{review.captions.length} {t("captionSegmentsUnit")}
{t("autoEditModelResultHint")}
{review.error ? {t("autoEditReviewFailed")}{review.error}
: review.segments.length ? {review.segments.map((segment) => {
const segmentCaptions = review.captions.filter((caption) => caption.visualSegmentId === segment.id);
const preview = review.candidates.find((candidate) => candidate.segmentId === segment.id);
return
{segment.error ? {segment.error}
: segmentCaptions.length ? <>{segmentCaptions.map((caption, index) => (
{String(index + 1).padStart(2, "0")}{caption.text}
))}
{segment.status === "running" ? {t("autoEditWindowProgress").replace("{current}", segment.windowIndex || 0).replace("{total}", segment.totalWindows || 0)}
: null}> : {segment.status === "running" ? : null}{segment.status === "running" && segment.totalWindows ? t("autoEditWindowProgress").replace("{current}", segment.windowIndex || 0).replace("{total}", segment.totalWindows) : t(`autoEditSegmentHint_${segment.status}`)}
}
;
})}
: {job.running ? job.phase : t("autoEditWaitingForModel")}
}
, document.body,
);
}
function AutoEditPanel({ t, hasVisual, autoEdit }) {
const availability = autoEdit?.support?.availability || "unknown";
const ready = availability === "available" || availability === "downloadable" || availability === "downloading";
const downloadProgress = Math.max(0, Math.min(100, Number(autoEdit?.support?.progress) || 0));
const isPreparingSupport = availability === "downloading" && Number.isFinite(autoEdit?.support?.progress);
const supportActionLabel = availability === "downloading"
? `${t("autoEditDownloadingModel")}${downloadProgress ? ` ${downloadProgress}%` : ""}`
: availability === "downloadable" ? t("autoEditDownloadModel") : t("autoEditCheckSupport");
return (<>
{t("autoEditCreateTitle")}{t("autoEditCreateDesc")}
{t("autoEditBrowserModel")}{t(`autoEditStatus_${availability}`)}
{t("autoEditPrivacyHint")}
{isPreparingSupport ? : null}
1{t("autoEditStepScenes")}{t("autoEditStepScenesHint")}
2{t("autoEditStepCaptions")}{t("autoEditStepCaptionsHint")}
3{t("autoEditStepTimeline")}{t("autoEditStepTimelineHint")}
{autoEdit?.job?.running ?
{autoEdit.job.phase}{autoEdit.job.progress}%
: null}
>);
}
function CaptionContextPanel({
t,
captionSegments,
selectedCaptionSegment,
selectedSegmentId,
setSelectedSegmentId,
currentSegmentIndex,
captionTargetDuration,
updateCaptionSegmentText,
toggleCaptionSegmentHidden,
deleteCaptionSegment,
seekTo,
sourceAudioBlob,
generateCaptionsFromSourceAudio,
isGeneratingCaptions,
automaticCaptionProgress,
importCaptionSegments,
addCaptionSegment,
alignCaptionToAudio,
linkCaptionAudio,
unlinkCaptionAudio,
audioSegments,
}) {
const srtInputRef = useRef(null);
const focusNewCaptionRef = useRef(false);
const [pendingSrt, setPendingSrt] = useState(null);
const selectedIndex = Math.max(
0,
captionSegments.findIndex((segment) => segment.id === selectedCaptionSegment?.id),
);
const selectedStart = captionSegments.length
? getSegmentStartTime(captionSegments, selectedIndex, captionTargetDuration)
: 0;
const linkedAudioSegment = audioSegments.find((segment) => segment.id === selectedCaptionSegment?.audioSegmentId);
const relinkTarget = findCaptionAudioLinkTarget(selectedCaptionSegment, audioSegments);
useEffect(() => {
if (!focusNewCaptionRef.current || !selectedCaptionSegment) return;
focusNewCaptionRef.current = false;
const frame = requestAnimationFrame(() => document.getElementById("caption-context-input")?.focus());
return () => cancelAnimationFrame(frame);
}, [selectedCaptionSegment]);
function handleAddCaption() {
focusNewCaptionRef.current = true;
addCaptionSegment();
}
async function handleSrtFile(file) {
if (!file) return;
try {
if (file.size > MAX_SRT_FILE_BYTES) throw new Error(t("srtFileTooLarge"));
const result = parseSrt(await file.text());
if (!result.captions.length) throw new Error(t("srtNoValidCaptions"));
if (captionSegments.length) setPendingSrt(result);
else importCaptionSegments(result.captions, "replace", result.skipped);
} catch (error) {
window.alert(error instanceof Error ? error.message : t("srtImportFailed"));
}
}
function applyPendingSrt(mode) {
if (!pendingSrt) return;
importCaptionSegments(pendingSrt.captions, mode, pendingSrt.skipped);
setPendingSrt(null);
}
return (
{selectedCaptionSegment ? (
) : (
{t("noCaptionSegments")}
{t("captionEmptyHint", "字幕片段可拖动到字幕轨道,并在这里同步编辑。")}
)}
{selectedCaptionSegment ? (
{linkedAudioSegment ? : }
{linkedAudioSegment ? t("captionLinkedAudio") : t("captionAudioNotLinked")}
{linkedAudioSegment
? `${linkedAudioSegment.name || t("audioClip")} · ${formatTime(linkedAudioSegment.duration)}`
: relinkTarget ? t("captionAudioRelinkHint") : t("captionAudioUnavailable")}
{linkedAudioSegment ? <>
> : (
)}
) : null}
{!captionSegments.length ? (
) : null}
{t("captionList", "字幕列表")}
{captionSegments.length ? (
<>
>
) : null}
{
handleSrtFile(event.target.files?.[0]);
event.target.value = "";
}}
/>
{pendingSrt ? createPortal(
{t("srtConflictTitle")}
{t("srtConflictDescription").replace("{count}", pendingSrt.captions.length)}
, document.body,
) : null}
{captionSegments.length ? (
captionSegments.map((segment, index) => (
))
) : (
{t("noCaptionSegments")}
)}
);
}
function AudioClipContextPanel({ t, segment, updateAudioSegment, toggleAudioSegmentReverse, deleteAudioSegment, downloadBlob }) {
const isVoiceClip = segment.track === "audio";
const trackLabel = segment.track === "music" ? t("musicTrack") : segment.track === "source" ? t("sourceTrack") : t("voiceTrack");
return (
);
}
function StickerContextPanel({ t, segment, updateStickerSegment, deleteStickerSegment }) {
if (!segment) return null;
const round = (value) => Math.round(value * 100) / 100;
const updateNumber = (key, value, min, max) => updateStickerSegment({
[key]: round(Math.max(min, Math.min(max, Number(value) || 0))),
});
const fields = [
["x", t("stickerHorizontalPosition"), 0, 100, "%"],
["y", t("stickerVerticalPosition"), 0, 100, "%"],
["scale", t("stickerScale"), 0.2, 3, "x"],
["rotation", t("stickerRotation"), -180, 180, "°"],
];
return (
{fields.map(([key, label, min, max, unit]) => (
))}
);
}
function AvatarContextPanel({ t, hasVisual, visualType, audioBlob, audioDuration, captionSegments, selectedVoice, avatarJob, generateAvatarAcceptanceFrame }) {
const hasPortrait = hasVisual && visualType === "image";
const [probeState, setProbeState] = useState("idle");
const [probeResult, setProbeResult] = useState(null);
const [avatarQuality, setAvatarQuality] = useState("preview");
const runProbe = async () => {
setProbeState("running");
try {
setProbeResult(await probeLivePortraitWebEnvironment());
setProbeState("done");
} catch (error) {
setProbeResult({ readyForPorting: false, checks: [{ id: "runtime", state: "failed", detail: error instanceof Error ? error.message : String(error) }] });
setProbeState("done");
}
};
return (
{t("avatarKicker")}{t("avatarLipSyncTitle")}{t("avatarLipSyncDescription")}
{t("avatarPortrait")}{hasPortrait ? t("avatarCurrentPortrait") : t("avatarNeedsPortrait")}
{t("avatarAudio")}{audioBlob ? `${selectedVoice?.name ?? "AI"} · ${audioDuration.toFixed(1)}s` : t("avatarNeedsAudio")}
{t("avatarLipSyncSource")}{captionSegments.length ? `${captionSegments.length} ${t("captionSegmentsUnit")} · ${t("avatarCaptionSync")}` : t("avatarNeedsCaptions")}
{t("avatarModelSource")}{LIVE_PORTRAIT_WEB_MODEL.id}
{t("avatarGenerationNote")}
1{t("avatarStagePinned")}
2{t("avatarStageGrid")}
3{t("avatarStageAudio")}
{probeResult ? (
{probeResult.checks.map((check) =>
{check.detail}
)}
) : null}
{avatarJob?.running || avatarJob?.progress > 0 || avatarJob?.phase ? (
{avatarJob.phase || t("avatarGenerating")}{avatarJob.progress}%
) : null}
);
}
export function VoicePanel({
t,
activeTool,
captionVoiceFocusRequest = 0,
status,
statusText,
voiceTab,
setVoiceTab,
script,
updateScript,
selectedVoiceId,
setSelectedVoiceId,
selectedVoice,
filteredVoices,
voiceFilter,
setVoiceFilter,
showVoiceFilter,
setShowVoiceFilter,
speed,
setSpeed,
volume,
setVolume,
progressPercent,
audioBlob,
generateVoiceover,
downloadBlob,
favoriteVoiceIds,
setFavoriteVoiceIds,
recordedVoices,
recordingState,
recordingElapsed,
startVoiceRecording,
stopVoiceRecording,
useRecordedVoice,
historyItems,
useHistoryItem,
setHistoryItems,
notify,
audioUrl,
audioRef,
audioSegments,
audioSegmentRefs,
sourceAudioRef,
musicRef,
sourceAudioUrl,
musicUrl,
captionSegments,
selectedCaptionSegment,
selectedSegmentId,
setSelectedSegmentId,
currentSegmentIndex,
captionTargetDuration,
updateCaptionSegmentText,
toggleCaptionSegmentHidden,
deleteCaptionSegment,
importCaptionSegments,
addCaptionSegment,
seekTo,
sourceAudioBlob,
sourceAudioLinked,
generateCaptionsFromSourceAudio,
isGeneratingCaptions,
automaticCaptionProgress,
avatarPanelOpen,
smartMode = "auto-edit",
aiMusic,
autoEdit,
uiLanguage,
visionAnalysis,
visionOptions,
visionRunning,
visionProgress,
visionPhase,
analyzeCurrentVisual,
toggleVisionOption,
clearVisionAnalysis,
downloadVisionCutout,
hasVisual,
visualType,
audioDuration,
avatarJob,
generateAvatarAcceptanceFrame,
selectedTrack,
selectedAudioSegment,
selectedTrackAudioSegment,
audioClipInspectorOpen = false,
updateSelectedTrackAudioSegment,
deleteSelectedTrackAudioSegment,
updateAudioSegment,
toggleAudioSegmentReverse,
deleteAudioSegment,
selectedVisualSegment,
selectedStickerSegment,
updateStickerSegment,
deleteStickerSegment,
visualLocalTime,
visualTimelineStart = 0,
updateSelectedVisualEffects,
onPreviewAnimation,
selectedFilterId,
setSelectedFilterId,
trOption,
selectedVisualOverlay,
updateVisualOverlaySegment,
deleteVisualOverlay,
applyVisualOverlayPreset,
alignCaptionToAudio,
linkCaptionAudio,
unlinkCaptionAudio,
}) {
const [captionPanelTab, setCaptionPanelTab] = useState("caption");
const panelRef = useRef(null);
const isCaptionContext = activeTool === "caption";
const isSmartContext = activeTool === "smart";
const isAvatarContext = isSmartContext && smartMode === "avatar" && avatarPanelOpen;
const isSmartAutoContext = isSmartContext && smartMode === "auto-edit";
const isSmartFrameContext = isSmartContext && smartMode === "smart-frame";
const isAiMusicContext = isSmartContext && smartMode === "ai-music";
const audioPropertySegment = selectedTrack === "audio" ? selectedAudioSegment : selectedTrackAudioSegment;
const isAudioClipContext = Boolean(selectedTrack === "audio" && selectedAudioSegment)
|| Boolean(audioClipInspectorOpen && ["source", "music"].includes(selectedTrack) && audioPropertySegment);
const isVisualContext = !isSmartContext && selectedTrack === "image";
const isStickerContext = selectedTrack === "sticker" && Boolean(selectedStickerSegment);
const isOverlayContext = selectedTrack === "overlay" && Boolean(selectedVisualOverlay);
const selectedCaptionAudioSegment = getCaptionVoiceSegment(audioSegments, selectedCaptionSegment);
const localizedStatusText = statusText?.startsWith?.("tts") ? t(statusText) : statusText;
const title = isAiMusicContext ? (uiLanguage === "zh" ? "AI 音乐" : "AI music") : isSmartAutoContext ? t("smartAutoEdit") : isSmartFrameContext ? t("smartFrame") : isAvatarContext ? t("avatarTitle") : isOverlayContext ? t("pictureInPicture", "画中画") : isStickerContext ? t("stickerProperties") : isVisualContext ? t("visualPanelTitle") : isCaptionContext ? t("caption") : isAudioClipContext ? t("audioClipProperties") : t("aiVoice");
const panelStatusText = isAiMusicContext ? (aiMusic?.job?.state === "running" ? `${Math.round((aiMusic.job.progress || 0) * 100)}%` : aiMusic?.job?.state === "complete" ? t("complete") : t("modelReady")) : isSmartAutoContext ? t(`autoEditStatus_${autoEdit?.support?.availability || "unknown"}`) : isSmartFrameContext ? (hasVisual ? t("smartVisualReady") : t("smartWaitingVisual")) : isCaptionContext
? captionSegments.length
? `${captionSegments.length} ${t("captionSegmentsUnit", "条字幕")}`
: t("noCaptionSegments")
: isStickerContext
? `${selectedStickerSegment.start.toFixed(2)}s · ${selectedStickerSegment.duration.toFixed(2)}s`
: isOverlayContext
? `${selectedVisualOverlay.start.toFixed(2)}s · ${selectedVisualOverlay.duration.toFixed(2)}s · L${selectedVisualOverlay.layer || 1}`
: isVisualContext
? selectedVisualSegment
? `${visualLocalTime.toFixed(2)}s · ${normalizeVisualKeyframes(selectedVisualSegment.keyframes).length} ${t("visualFrames")}`
: t("visualSelectClip")
: isAvatarContext
? t("avatarPortingStatus")
: isAudioClipContext
? `${formatTime(audioPropertySegment.duration)} · ${audioPropertySegment.start.toFixed(1)}s`
: statusText === "模型待命"
? t("modelReady")
: localizedStatusText;
useEffect(() => {
if (!captionVoiceFocusRequest || !isCaptionContext) return;
setCaptionPanelTab("voice");
const frame = requestAnimationFrame(() => {
requestAnimationFrame(() => {
panelRef.current?.querySelector(".voice-header")?.scrollIntoView({ block: "start", behavior: "smooth" });
});
});
return () => cancelAnimationFrame(frame);
}, [captionVoiceFocusRequest, isCaptionContext]);
useEffect(() => {
panelRef.current?.querySelector(".voice-tab-body")?.scrollTo({ top: 0 });
}, [activeTool, smartMode]);
return (
);
}