import { useEffect, useMemo, useRef, useState } from "react"; import { flushSync } from "react-dom"; import { BoundingBox, CaretDown, Check, CloudArrowUp, ClosedCaptioning, Crop, Diamond, DownloadSimple, MicrophoneStage, MusicNote, Pause, PersonSimpleRun, Scan, SelectionBackground, Target, Trash, Waveform, } from "@phosphor-icons/react"; import { EFFECT_OPTIONS, FILTER_OPTIONS, SAMPLE_IMAGE, STICKERS, STICKER_CATEGORIES, STICKER_PAGE_SIZE, TRANSITIONS, VOICES, } from "../config/editor.js"; import { APP_LANGUAGES } from "../i18n.js"; import { formatClock, formatTime, getSegmentStartTime } from "../lib/timeline.js"; import { hasVisualPropertyKeyframe, normalizeVisualKeyframes, resolveVisualTransform } from "../lib/visualEffects.js"; import { DEFAULT_VISUAL_ANIMATION_DURATION, normalizeVisualClipAnimation, VISUAL_CLIP_ANIMATION_OPTIONS } from "../lib/visualClipAnimations.js"; import { Popover } from "./ui.jsx"; export function LanguageIntro({ t, closing, onChoose }) { return (

{t("languageKicker")}

Choose interface language {t("languageTitle")}

Pick a language. This choice will be saved for next time. {t("languageSubtitle")}
{APP_LANGUAGES.map((language) => ( ))}
{t("languageSaved")}
); } export function MediaPanel({ t, mediaTab, setMediaTab, isDragging, setIsDragging, fileInputRef, handleFiles, selectedLibraryAssetId, builtInAssets, userAssets, deleteUserAsset, draggedAssetId, handleAssetPointerDown, handleAssetClick, }) { const assets = mediaTab === "library" ? builtInAssets : userAssets; const renderAssetList = (items, { deletable = false } = {}) => (
{items.length ? ( items.map((asset) => (
{deletable ? ( ) : null}
)) ) : (
{t("emptyAssets")}
)}
); return ( <>
{[ ["upload", t("uploadTab")], ["library", t("libraryTab")], ["mine", t("mineTab")], ].map(([id, label]) => ( ))}
{mediaTab === "upload" ? ( <> { handleFiles(event.target.files); event.target.value = ""; }} /> {renderAssetList(userAssets, { deletable: true })} ) : ( renderAssetList(assets, { deletable: mediaTab === "mine" }) )} ); } function AssetRow({ asset, selected, t }) { return (
{asset.type === "video" ? (
{asset.name} {asset.meta}
); } export function ToolPanel(props) { const { activeTool, uiLanguage, script, updateScript, segments, currentSegmentIndex, captionSegments, captionTargetDuration, selectedCaptionSegment, selectedSegmentId, setSelectedSegmentId, updateCaptionSegmentText, toggleCaptionSegmentHidden, deleteCaptionSegment, seekTo, estimatedDuration, captionPosition, setCaptionPosition, captionSize, setCaptionSize, captionStyle, setCaptionStyle, captionsEnabled, setCaptionsEnabled, selectedFilterId, setSelectedFilterId, selectedTransitionId, setSelectedTransitionId, selectedStickerId, setSelectedStickerId, handleStickerPointerDown, handleStickerClick, audioBlob, audioDuration, sourceAudioBlob, sourceAudioName, sourceAudioDuration, sourceAudioVolume, sourceAudioLinked, setSourceAudioVolume, clearSourceAudioTrack, generateCaptionsFromSourceAudio, isGeneratingCaptions, automaticCaptionProgress, separateSourceVocals, vocalSeparationJob, hasVisual, visualType, visionAnalysis, visionOptions, visionRunning, visionProgress, visionPhase, analyzeCurrentVisual, toggleVisionOption, clearVisionAnalysis, downloadVisionCutout, openAvatarPanel, musicBlob, musicName, musicDuration, musicVolume, setMusicVolume, clearMusicTrack, selectedVoice, setVoiceTab, downloadBlob, notify, t, trOption, selectedVisualSegment, visualLocalTime, updateSelectedVisualEffects, } = props; if (activeTool === "caption") { return (

{t("caption")}

{t("captionCanvasHint")}

{["top", "middle", "bottom"].map((position) => ( ))}
{captionSize}px
setCaptionSize(Number(event.target.value))} />
{t("captionStyle")}{t("captionStyleHint")}
{[['normal', t('captionPresetClassic')], ['neon', t('captionPresetNeon')]].map(([effect, label]) => ( ))}
{[['backgroundOpacity', t('captionOpacity'), 0, 1, 0.05, '%'], ['borderWidth', t('captionBorderWidth'), 0, 8, 1, 'px'], ['radius', t('captionRadius'), 0, 28, 1, 'px'], ['paddingX', t('captionPaddingX'), 0, 52, 1, 'px'], ['paddingY', t('captionPaddingY'), 0, 32, 1, 'px'], ['shadowOpacity', t('captionShadow'), 0, 1, 0.05, '%']].map(([key, label, min, max, step, unit]) => (
{unit === '%' ? `${Math.round(captionStyle[key] * 100)}%` : `${captionStyle[key]}${unit}`}
setCaptionStyle((style) => ({ ...style, [key]: Number(event.target.value) }))} />
))}
); } if (activeTool === "smart") { return ( ); } if (activeTool === "audio") { return (

{t("audioPanel")}

{t("currentVoice")} {selectedVoice.name}
{t("voiceDuration")} {formatTime(audioBlob ? audioDuration : 0)}
{t("sourceAudio")} {sourceAudioBlob ? sourceAudioName : t("notSeparated")}
{t("sourceDuration")} {formatTime(sourceAudioBlob ? sourceAudioDuration : 0)}
{t("bgm")} {musicBlob ? musicName : t("notAdded")}
{t("musicDuration")} {formatTime(musicBlob ? musicDuration : 0)}
{Math.round(sourceAudioVolume * 100)}%
setSourceAudioVolume(Number(event.currentTarget.value))} onChange={(event) => setSourceAudioVolume(Number(event.target.value))} />
{Math.round(musicVolume * 100)}%
setMusicVolume(Number(event.currentTarget.value))} onChange={(event) => setMusicVolume(Number(event.target.value))} />
); } if (activeTool === "transition") { return ( { setSelectedTransitionId(id); notify(t("transitionApplied")); }} /> ); } if (activeTool === "effects") { return ( { setSelectedFilterId(id); notify(t("effectApplied")); }} /> ); } if (activeTool === "stickers") { return ( { setSelectedStickerId(id); notify(t("stickerApplied")); }} /> ); } return ( { setSelectedFilterId(id); notify(t("filterApplied")); }} /> ); } export function VisualEffectsPanel({ t, segment, localTime, onChange, onSeek, onPreviewAnimation, selectedFilterId, trOption, onSelectFilter, contextMode = false, sourceAudioLinked = false }) { const [activeTab, setActiveTab] = useState("transform"); const [animationSection, setAnimationSection] = useState("in"); const [hoveredAnimation, setHoveredAnimation] = useState(null); const keyframes = normalizeVisualKeyframes(segment?.keyframes ?? []); const transform = resolveVisualTransform(keyframes, localTime); const mask = segment?.mask ?? { type: "none", feather: 0, inverted: false }; const hasMask = mask.type && mask.type !== "none"; const isCircleMask = mask.type === "circle"; const isVideo = segment?.type === "video"; const playbackRate = Math.max(0.25, Math.min(4, Number(segment?.playbackRate) || 1)); const clipAnimation = normalizeVisualClipAnimation(segment?.animation); const activeAnimation = clipAnimation[animationSection]; const sourceDuration = Math.max(0, Number(segment?.sourceDuration) || (Number(segment?.duration) || 0) * playbackRate); const updateTransform = (key, value) => onChange?.({ propertyKeyframe: { time: localTime, key, value } }); const tabs = [ ["transform", t("visualTabTransform")], ["mask", t("visualTabMask")], ["speed", t("visualTabSpeed")], ["effects", t("visualTabEffects")], ["animation", t("visualTabAnimation")], ]; useEffect(() => { if (!hoveredAnimation || !segment || !onPreviewAnimation) return undefined; let frame = 0; let lastPaint = 0; const startedAt = performance.now(); const paint = (now) => { if (now - lastPaint >= 32) { const phaseProgress = ((now - startedAt) % 1100) / 900; const progress = Math.min(1, phaseProgress); const previewAnimation = { ...clipAnimation, [hoveredAnimation.phase]: { id: hoveredAnimation.id, duration: DEFAULT_VISUAL_ANIMATION_DURATION, }, }; const previewLocalTime = hoveredAnimation.phase === "in" ? progress * DEFAULT_VISUAL_ANIMATION_DURATION : Math.max(0, Number(segment.duration) - DEFAULT_VISUAL_ANIMATION_DURATION + progress * DEFAULT_VISUAL_ANIMATION_DURATION); onPreviewAnimation({ segmentId: segment.id, animation: previewAnimation, localTime: previewLocalTime }); lastPaint = now; } frame = requestAnimationFrame(paint); }; frame = requestAnimationFrame(paint); return () => { cancelAnimationFrame(frame); onPreviewAnimation(null); }; }, [hoveredAnimation, onPreviewAnimation, segment?.id, segment?.duration]); return (
{!contextMode ?

{t("imageTrack")}

: null} {!segment ?
{t("visualSelectClip")}
: <>
{tabs.map(([id, label]) => )}
{activeTab === "transform" ?
{t("visualKeyframes")}{localTime.toFixed(2)}s · {keyframes.length} {t("visualFrames")}
{keyframes.length ?
{keyframes.map((frame) => )}
: null} {[['scale', t('visualScale'), 0.2, 3, 0.01, 100], ['x', t('visualPositionX'), -100, 100, 1, 1], ['y', t('visualPositionY'), -100, 100, 1, 1], ['rotation', t('visualRotation'), -180, 180, 1, 1], ['opacity', t('visualOpacity'), 0, 1, 0.01, 100]].map(([key, label, min, max, step, displayScale]) => { const keyed = hasVisualPropertyKeyframe(keyframes, localTime, key); const displayValue = Math.round(transform[key] * displayScale * 100) / 100; return
updateTransform(key, Number(event.target.value))} />
; })}
: null} {activeTab === "mask" ?
{t("visualMask")}{t("visualClipScoped")}
{[['none',t('visualMaskNone')],['rectangle',t('visualMaskRectangle')],['rounded',t('visualMaskRounded')],['circle',t('visualMaskCircle')]].map(([id,label]) => )}
{hasMask ? <>
{mask.feather || 0}%
onChange?.({ mask: { ...mask, feather: Number(event.target.value) } })} />
{[['centerX',t('visualHorizontal'),0,100,50],['centerY',t('visualVertical'),0,100,50]].map(([key,label,min,max,fallback]) =>
{Number.isFinite(mask[key]) ? Math.round(mask[key]) : fallback}%
onChange?.({ mask: { ...mask, [key]: Number(event.target.value) } })} />
)} {isCircleMask ?
{Number.isFinite(mask.size) ? Math.round(mask.size) : 72}%
onChange?.({ mask: { ...mask, size: Number(event.target.value) } })} />
: [['width',t('visualWidth'),8,100,80],['height',t('visualHeight'),8,100,80]].map(([key,label,min,max,fallback]) =>
{Number.isFinite(mask[key]) ? Math.round(mask[key]) : fallback}%
onChange?.({ mask: { ...mask, [key]: Number(event.target.value) } })} />
)} {mask.type === "rounded" ?
{Number.isFinite(mask.cornerRadius) ? Math.round(mask.cornerRadius) : 12}%
onChange?.({ mask: { ...mask, cornerRadius: Number(event.target.value) } })} />
: null} :

{t("visualMaskNoneHint")}

}
: null} {activeTab === "speed" ?
{t("visualSpeed")}{t("visualClipScoped")}
{isVideo ? <>
{[0.25, 0.5, 1, 1.5, 2, 3, 4].map((rate) => )}
{playbackRate.toFixed(playbackRate % 1 ? 2 : 0)}×
onChange?.({ playbackRate: Number(event.target.value) })} />
{t("visualSourceDuration")}{sourceDuration.toFixed(2)}s{t("visualTimelineDuration")}{Number(segment.duration).toFixed(2)}s

{sourceAudioLinked ? t("sourceAudioSynced") : t("visualSpeedVisualOnlyHint")}

:
{t("visualSpeedImageHint")}
}
: null} {activeTab === "effects" ? : null} {activeTab === "animation" ?
{t("visualAnimation")}{t("visualAnimationHoverHint")}
{[['in', t('visualAnimationIn')], ['out', t('visualAnimationOut')]].map(([id, label]) => )}
{VISUAL_CLIP_ANIMATION_OPTIONS.map((option) => )}
{activeAnimation.id !== "none" ?
{activeAnimation.duration.toFixed(1)}s
onChange?.({ animation: { ...clipAnimation, [animationSection]: { ...activeAnimation, duration: Number(event.target.value) } } })} />
: null}
: null} }
); } const SUBJECT_LABELS_ZH = { foreground: "前景主体", person: "人物", cat: "猫", dog: "狗", bird: "鸟", horse: "马", car: "汽车", motorcycle: "摩托车", bicycle: "自行车", bus: "公交车", truck: "卡车", bottle: "瓶子", cup: "杯子", chair: "椅子", laptop: "笔记本电脑", "cell phone": "手机", book: "书", }; function getDisplaySubjectLabel(label, language) { const normalized = String(label ?? "").trim(); if (!normalized) { return language === "zh" ? "前景主体" : "Foreground subject"; } return language === "zh" ? SUBJECT_LABELS_ZH[normalized.toLowerCase()] ?? normalized : normalized; } function SmartVisionPanel({ t, language = "zh", hasVisual, visualType, analysis, options = {}, running, progress = 0, phase = "", onAnalyze, onToggle, onClear, onDownloadCutout, onOpenAvatarPanel, }) { const subject = analysis?.subject ?? null; const detections = Array.isArray(analysis?.detections) ? analysis.detections : []; const canUseSubject = Boolean(subject?.box); const temporalSamples = Array.isArray(analysis?.samples) ? analysis.samples : []; const canUseMatting = Boolean(analysis?.cutoutUrl) || temporalSamples.some((sample) => sample.cutoutUrl); const canDownloadCutout = Boolean(analysis?.cutoutBlob) && visualType === "image"; const statusText = running ? t("smartVisionRunning") : analysis ? t("smartVisionReady") : t("smartVisionIdle"); const featureRows = [ { id: "showDetections", icon: BoundingBox, title: t("smartVisionDetection"), description: t("smartVisionDetectionDesc"), disabled: !detections.length, }, { id: "removeBackground", icon: SelectionBackground, title: t("smartVisionMatting"), description: t("smartVisionMattingDesc"), disabled: !canUseMatting, }, { id: "avoidCaptions", icon: ClosedCaptioning, title: t("smartVisionCaptionAvoidance"), description: t("smartVisionCaptionAvoidanceDesc"), disabled: !canUseSubject, }, { id: "smartCrop", icon: Crop, title: t("smartVisionCrop"), description: t("smartVisionCropDesc"), disabled: !canUseSubject, }, ]; return (
{t("smartVisionKicker")}

{t("smartVisionTitle")}

{statusText}
YOLOS tiny {t("smartVisionDetection")}
MODNet {t("smartVisionMatting")}
{!hasVisual ?
{t("smartVisionNoMedia")}
: null} {running ? (
{phase || t("smartVisionRunning")} {Math.max(0, Math.min(100, Math.round(progress)))}%
) : null} {analysis ? (
{subject ? ( <>
{t("smartVisionSubject")} {getDisplaySubjectLabel(subject.label, language)}
{t("smartVisionConfidence")} {Math.round((subject.score ?? 0) * 100)}%
{t("smartVisionObjects")} {detections.length}
) : (

{t("smartVisionNoSubject")}

)}
) : null} {visualType === "video" && temporalSamples.length ? (
{t("smartVisionVideoCoverage")} {temporalSamples.length} {t("smartVisionTemporalFrames")}
) : null}
{featureRows.map(({ id, icon: Icon, title, description, disabled }) => ( ))}

{t("smartVisionImageOnly")}

{t("avatarKicker")}{t("avatarTitle")}
{t("avatarWebPort")}

{t("avatarDescription")}

{t("avatarPortrait")} {t("avatarWebgpu")} {t("avatarAudio")}
{analysis ? (
) : null}
); } function VisualChoicePanel({ title, kind, options, selectedId, trOption = (name) => name, onSelect }) { return (

{title}

{options.map((option) => ( ))}
); } function ChoicePanel({ title, options, selectedId, trOption = (name) => name, onSelect }) { return (

{title}

{options.map((option) => ( ))}
); } function StickerPanel({ title, options, selectedId, trOption = (name) => name, onSelect, t, onStickerPointerDown, onStickerClick, }) { const [activeCategory, setActiveCategory] = useState("all"); const [visibleCount, setVisibleCount] = useState(STICKER_PAGE_SIZE); const loadMoreRef = useRef(null); const emptySticker = options.find((option) => option.id === "none") ?? { id: "none", name: "无贴纸" }; const stickerOptions = useMemo(() => options.filter((option) => option.id !== "none"), [options]); const filteredStickers = useMemo( () => activeCategory === "all" ? stickerOptions : stickerOptions.filter((option) => option.category === activeCategory), [activeCategory, stickerOptions], ); const visibleStickers = filteredStickers.slice(0, visibleCount); const hasMore = visibleCount < filteredStickers.length; useEffect(() => { setVisibleCount(STICKER_PAGE_SIZE); }, [activeCategory]); useEffect(() => { if (!hasMore || !loadMoreRef.current) { return undefined; } const observer = new IntersectionObserver( (entries) => { if (!entries.some((entry) => entry.isIntersecting)) { return; } setVisibleCount((count) => Math.min(count + STICKER_PAGE_SIZE, filteredStickers.length)); }, { root: null, rootMargin: "120px 0px" }, ); observer.observe(loadMoreRef.current); return () => observer.disconnect(); }, [filteredStickers.length, hasMore]); const loadMore = () => { setVisibleCount((count) => Math.min(count + STICKER_PAGE_SIZE, filteredStickers.length)); }; return (

{title}

{STICKER_CATEGORIES.map((category) => ( ))}
{visibleStickers.map((option) => { const dragAsset = { ...option, type: "sticker", meta: "贴纸", }; return ( ); })}
{hasMore ? ( ) : (
); } export function VoiceSynthesisPanel({ script, updateScript, selectedVoiceId, setSelectedVoiceId, selectedVoice, filteredVoices, voiceFilter, setVoiceFilter, showVoiceFilter, setShowVoiceFilter, speed, setSpeed, volume, setVolume, status, progressPercent, audioBlob, audioUrl, generateVoiceover, downloadBlob, favoriteVoiceIds, setFavoriteVoiceIds, t, }) { const voiceLanguages = useMemo(() => [...new Set(VOICES.map((voice) => voice.language))], []); const voiceSampleRef = useRef(null); const previousVoiceSampleIdRef = useRef(selectedVoiceId); const selectAndPlayVoiceSample = (voice) => { previousVoiceSampleIdRef.current = voice.id; flushSync(() => setSelectedVoiceId(voice.id)); const player = voiceSampleRef.current; if (!player) return; player.pause(); player.load(); delete player.dataset.autoplayStarted; delete player.dataset.autoplayError; player.play() .then(() => { player.dataset.autoplayStarted = "true"; }) .catch((error) => { player.dataset.autoplayError = error.name || "PlaybackError"; }); }; useEffect(() => { const player = voiceSampleRef.current; if (!player) return; if (previousVoiceSampleIdRef.current === selectedVoiceId) return; previousVoiceSampleIdRef.current = selectedVoiceId; player.pause(); player.load(); }, [selectedVoiceId]); return ( <>