The open-source full-stack studio for Opus 5.5 motion video. Reverse engineering for any video. Code video with HTML: recreate, edit and render. BYOA + BYOK · Motion.md · Images, Video, Music & Voice.
TypeScript agent-skillsagentic-aiai-agentsai-videobyokclaude-codecodexdeepseek-harnessdsh-plugingenerative-ailocal-firstmcpmotionmotion-graphicsmultimodalopenmotionreverse-engineeringvideo-editingvideo-generationworkbuddy
import { Popover } from '@base-ui/react/popover';
import { useEffect, useRef, useState, type CSSProperties } from 'react';
import { useI18n } from '../../i18n/I18n';
import { RemixIcon } from '../../icons/RemixIcons';
import { useTimelineEditContextOptional } from '../../contexts/TimelineEditContext';
import { useStudioShellContextOptional } from '../../contexts/StudioContext';
import type { TimelineElement } from '../store/timelineElement';
import { usePlayerStore } from '../store/playerStore';
import { probeMediaUrl } from '../lib/mediaProbe';
import { authoredSrcPath, resolveMediaPreviewUrl } from './thumbnailUtils';
const buttonClass = 'flex h-6 w-6 shrink-0 items-center justify-center rounded text-text-3 hover:bg-hover hover:text-text-0 disabled:opacity-40';
/** Track-level controls write each audible clip through the native batch/undo path. */
export function TimelineTrackAudioControls({ elements, trackLabel, isAudioOnly, hidden, onUnhide }: {
elements: readonly TimelineElement[];
trackLabel: string;
isAudioOnly: boolean;
hidden: boolean;
onUnhide: () => void;
}) {
const { t } = useI18n();
const { onSetElementsAttributeQuiet } = useTimelineEditContextOptional();
const shell = useStudioShellContextOptional();
const projectId = usePlayerStore(state => state.timelineProjectId);
const sourceUrl = (el: TimelineElement) => el.src
? projectId ? resolveMediaPreviewUrl(authoredSrcPath(el.src), projectId, window.location.origin) : el.src
: undefined;
const sources = JSON.stringify([...new Set(elements.filter(el => el.tag === 'video').map(sourceUrl).filter((src): src is string => !!src))]);
const [sourceAudio, setSourceAudio] = useState<Record<string, boolean>>({});
useEffect(() => {
let active = true;
void Promise.all((JSON.parse(sources) as string[]).map(async src => {
const metadata = await probeMediaUrl(src);
return metadata ? [src, metadata.hasAudio] as const : null;
})).then(results => {
if (active) setSourceAudio(Object.fromEntries(results.filter(result => result !== null)));
});
return () => { active = false; };
}, [sources]);
// Source audio capability is independent of current mute/gain. Runtime manifests
// can omit hasAudio after unmuting; keep unknown video controls until a probe
// positively identifies a silent source. Reuse the shared bounded probe cache.
const clips = elements.filter(el => el.tag === 'audio' ||
(el.tag === 'video' && (sourceAudio[sourceUrl(el) ?? ''] ?? el.hasAudio) !== false));
const signature = clips.map(el => `${el.key ?? el.id}:${el.volume ?? 1}:${!!el.muted}`).join('|');
const volume = Math.round((clips[0]?.volume ?? 1) * 100);
const sliderVolume = Math.min(100, Math.max(0, volume));
const mixed = clips.some(el => Math.round((el.volume ?? 1) * 100) !== volume);
const muted = clips.length > 0 && clips.every(el => el.muted === true);
const silent = muted || (isAudioOnly && hidden);
const [open, setOpen] = useState(false);
const [draft, setDraft] = useState(sliderVolume);
const [dirty, setDirty] = useState(false);
const [busy, setBusy] = useState(false);
const running = useRef(false);
useEffect(() => { setDraft(sliderVolume); setDirty(false); }, [signature, open]);
const disabled = busy || !onSetElementsAttributeQuiet || !!shell?.writeBlockedReason || !!shell?.renderQueue?.isRendering;
if (!clips.length) return null;
const save = async (attr: string, value: string | null, label: string) => {
if (disabled || running.current || !onSetElementsAttributeQuiet) return;
running.current = true; setBusy(true);
try {
const result = await onSetElementsAttributeQuiet(clips.map(element => ({ element, value })), attr, label);
return !result || result.status === 'saved';
} catch (error) {
shell?.showToast(error instanceof Error ? error.message : 'Changes could not be saved.', 'error');
return false;
} finally { running.current = false; setBusy(false); }
};
const shownVolume = silent && !dirty ? 0 : draft;
const commitVolume = async () => {
if (!dirty) return;
const saved = await save('data-volume', String(draft / 100), 'Change volume');
if (saved && draft > 0 && silent) {
const unmuted = !muted || await save('muted', null, 'Unmute audio');
if (unmuted && isAudioOnly && hidden) onUnhide();
}
if (!saved) setDraft(sliderVolume);
setDirty(false);
};
const muteLabel = t(silent ? 'Unmute audio' : 'Mute audio');
return <div className="ml-2 flex shrink-0 items-center" onPointerDown={e => e.stopPropagation()} onClick={e => e.stopPropagation()}>
<Popover.Root open={open} onOpenChange={(nextOpen, details) => {
// Pressing the speaker changes mute only; hover/focus owns the slider.
if (details.reason === 'trigger-press') { details.cancel(); return; }
setOpen(nextOpen);
}}>
<Popover.Trigger openOnHover delay={150} closeDelay={250}
className={buttonClass} aria-label={`${muteLabel} · ${trackLabel}`} aria-pressed={silent} disabled={disabled}
onFocus={() => setOpen(true)}
onClick={() => void (async () => {
const saved = await save('muted', silent ? null : 'true', silent ? 'Unmute audio' : 'Mute audio');
if (saved && silent && isAudioOnly && hidden) onUnhide();
})()}>
<RemixIcon name={silent ? 'volume-mute-line' : 'volume-up-line'} size={16} />
</Popover.Trigger>
<Popover.Portal><Popover.Positioner side="top" align="center" sideOffset={6} collisionPadding={12} className="z-150">
<Popover.Popup initialFocus={false} finalFocus={false} aria-label={t('Volume')} className="hf-floating-motion flex flex-col items-center gap-2 rounded-lg bg-surface p-3 text-text-1 shadow-menu outline-none">
<span className="font-mono text-[11px] tabular-nums">{mixed && !dirty && !silent ? t('Mixed') : `${shownVolume}%`}</span>
<input type="range" min={0} max={100} step={1} value={shownVolume} disabled={disabled}
aria-label={t('Volume')} aria-orientation="vertical" aria-valuetext={`${shownVolume}%`} className="hf-volume-vertical-range" style={{ "--volume-progress": `${shownVolume}%` } as CSSProperties}
onChange={e => { setDraft(Number(e.currentTarget.value)); setDirty(true); }}
onPointerUp={() => void commitVolume()} onKeyUp={() => void commitVolume()} onBlur={() => void commitVolume()} />
</Popover.Popup>
</Popover.Positioner></Popover.Portal>
</Popover.Root>
</div>;
}