From d51593fdca42ed65b85851b5524991c8036c60da Mon Sep 17 00:00:00 2001 From: dazzatronus Date: Thu, 19 Nov 2026 02:38:08 +1100 Subject: [PATCH] feat: add a Duck control to the audio toolbar --- src/core/ui/composites/DuckPanel.ts | 287 ++++++++++++++++++++++++++++ src/core/ui/media-toolbar.ts | 63 +++++- src/styles/index.css | 1 + src/styles/ui/duck-panel.css | 80 ++++++++ src/styles/ui/media-toolbar.css | 6 + tests/media-toolbar-duck.test.ts | 239 ++++++++++++++++++++++- tests/media-toolbar.test.ts | 1 + tests/toolbar.test.ts | 1 + 8 files changed, 673 insertions(+), 5 deletions(-) create mode 100644 src/core/ui/composites/DuckPanel.ts create mode 100644 src/styles/ui/duck-panel.css diff --git a/src/core/ui/composites/DuckPanel.ts b/src/core/ui/composites/DuckPanel.ts new file mode 100644 index 00000000..675e29db --- /dev/null +++ b/src/core/ui/composites/DuckPanel.ts @@ -0,0 +1,287 @@ +import type { Edit } from "@core/edit-session"; +import { ensureClipAlias, findEligibleSourceClips } from "@core/shared/source-clip-finder"; +import type { AudioAsset, Duck, ResolvedClip } from "@schemas"; +import { DUCK_DEFAULT_VOLUME, findDuckIssues, planDuckMeasurements, scanDucking } from "@shotstack/shotstack-canvas/duck"; + +import { UIComponent } from "../primitives/UIComponent"; + +/** + * Copy for each `findDuckIssues` path below the asset. The last segment alone + * can't tell the clip's `volume` from `duck.volume`. + */ +const ISSUE_COPY: Readonly> = { + volume: "Ducking needs a constant volume.", + speed: "Ducking needs normal speed.", + "duck.volume": "Choose a level below the clip's volume.", + "duck.under": "A clip this ducks under no longer exists." +}; + +const UNKNOWN_ISSUE = "This setting can't be used with ducking."; + +/** + * The Duck popup's switch, the clips to duck under, and the level. Each change + * is written straight to the edit as one `updateClip`. Ducking under a clip that + * has no alias also writes the alias first, as an `updateClip` of its own. + * + * @example + * ```typescript + * const duck = new DuckPanel(edit); + * duck.mount(container); + * duck.setClip(trackIdx, clipIdx); + * duck.sync(); + * ``` + */ +export class DuckPanel extends UIComponent { + private trackIdx = -1; + private clipIdx = -1; + + private switchInput: HTMLInputElement | null = null; + private options: HTMLFieldSetElement | null = null; + private clipList: HTMLDivElement | null = null; + private levelSection: HTMLDivElement | null = null; + private levelButtons: NodeListOf | null = null; + private customRow: HTMLDivElement | null = null; + private slider: HTMLInputElement | null = null; + private readout: HTMLSpanElement | null = null; + private reasonNote: HTMLParagraphElement | null = null; + private errorNote: HTMLParagraphElement | null = null; + private hintNote: HTMLParagraphElement | null = null; + + constructor(private readonly edit: Edit) { + super(); + } + + render(): string { + return ` + +
+ Lower while these play +
+
+
Level
+
+ + +
+
+
+ + +
+
+
+
+

+ +

+ `; + } + + protected bindElements(): void { + const find = (name: string) => this.container?.querySelector(`[data-duck-${name}]`) ?? null; + this.switchInput = find("toggle"); + this.options = find("options"); + this.clipList = find("clips"); + this.levelSection = find("level"); + this.levelButtons = this.container?.querySelectorAll("[data-duck-level-option]") ?? null; + this.customRow = find("custom"); + this.slider = find("volume"); + this.readout = find("volume-value"); + this.reasonNote = find("reason"); + this.errorNote = find("error"); + this.hintNote = find("hint"); + } + + protected setupEvents(): void { + this.events.on(this.switchInput, "change", () => this.setDucking(this.switchInput?.checked ?? false)); + this.events.on(this.clipList, "change", e => { + const box = e.target as HTMLInputElement; + this.toggleClip(box.dataset["duckClip"] ?? "", box.checked); + }); + this.events.onAll(this.levelButtons, "click", (_, btn) => this.setLevel((btn as HTMLElement).dataset["duckLevelOption"] === "custom")); + + // Readout only while dragging, so a drag commits once, on release. + this.events.on(this.slider, "input", () => { + if (this.readout && this.slider) this.readout.textContent = `${this.slider.value}%`; + }); + this.events.on(this.slider, "change", () => this.setVolume(Number(this.slider?.value) / 100)); + } + + setClip(trackIdx: number, clipIdx: number): void { + this.trackIdx = trackIdx; + this.clipIdx = clipIdx; + } + + /** Why the selected clip can't duck, or "" when it can. */ + blocker(): string { + return this.issues(this.resolvedDuck() ?? { under: [] }).find(({ key }) => !key.startsWith("duck."))?.text ?? ""; + } + + sync(): void { + const clipId = this.edit.getClipId(this.trackIdx, this.clipIdx); + if (!this.container || !clipId) return; + + const duck = this.documentDuck(); + const issues = this.issues(this.resolvedDuck() ?? { under: [] }); + const blocker = issues.find(({ key }) => !key.startsWith("duck.")); + const custom = typeof duck?.volume === "number"; + const level = Math.round((typeof duck?.volume === "number" ? duck.volume : DUCK_DEFAULT_VOLUME) * 100); + + if (this.switchInput) { + this.switchInput.checked = Boolean(duck); + this.switchInput.disabled = Boolean(blocker) && !duck; + } + if (this.options) this.options.disabled = Boolean(blocker); + if (this.levelSection) this.levelSection.hidden = !duck; + this.levelButtons?.forEach(btn => { + const active = (btn.dataset["duckLevelOption"] === "custom") === custom; + btn.classList.toggle("active", active); + btn.setAttribute("aria-pressed", String(active)); + }); + if (this.customRow) this.customRow.hidden = !custom; + if (this.slider) this.slider.value = String(level); + if (this.readout) this.readout.textContent = `${level}%`; + // The Custom warning covers `duck.volume`; anything else this clip breaks is said here. + if (this.reasonNote) this.reasonNote.textContent = (blocker ?? issues.find(({ key }) => key === "duck.under"))?.text ?? ""; + if (this.errorNote) this.errorNote.textContent = ""; + this.renderClips(clipId, duck ? [duck.under].flat() : []); + this.updateHint(); + } + + private documentDuck(trackIdx = this.trackIdx, clipIdx = this.clipIdx): Duck | undefined { + return (this.edit.getDocumentClip(trackIdx, clipIdx)?.asset as AudioAsset | undefined)?.duck; + } + + private resolvedDuck(): Duck | undefined { + return (this.edit.getResolvedClip(this.trackIdx, this.clipIdx)?.asset as AudioAsset | undefined)?.duck; + } + + /** This clip's issues with `duck` as given, by the server's own rules, so Studio never writes what a render would reject. */ + private issues(duck: Partial) { + const { trackIdx, clipIdx } = this; + const { timeline } = this.edit.getResolvedEdit(); + const tracks = timeline.tracks.map((track, t) => + t !== trackIdx ? track : { ...track, clips: track.clips.map((clip, c) => (c !== clipIdx ? clip : { ...clip, asset: { ...clip.asset, duck } })) } + ); + // Paths run timeline.tracks[t].clips[c].asset.. + return findDuckIssues({ timeline: { tracks } }) + .filter(({ path }) => path[2] === trackIdx && path[4] === clipIdx) + .map(({ path }) => { + const key = path.slice(6).join("."); + return { key, text: ISSUE_COPY[key] ?? UNKNOWN_ISSUE }; + }); + } + + private renderClips(clipId: string, refs: string[]): void { + const list = this.clipList; + if (!list) return; + const focused = list.contains(document.activeElement) ? (document.activeElement as HTMLElement).dataset["duckClip"] : undefined; + const others = findEligibleSourceClips(this.edit).filter(info => info.clipId !== clipId); + + list.replaceChildren( + ...others.map(info => { + const box = document.createElement("input"); + box.type = "checkbox"; + box.dataset["duckClip"] = info.clipId; + box.checked = Boolean(info.currentAlias) && refs.includes(`alias://${info.currentAlias}`); + const text = document.createElement("span"); + // Labels carry user text such as speech scripts, so they never go through innerHTML. + text.textContent = info.displayLabel; + const label = document.createElement("label"); + label.className = "ss-duck-clip"; + label.append(box, text); + return label; + }) + ); + if (others.length === 0) list.innerHTML = `
No other audio or video clips
`; + + // Every write re-renders the list, which would otherwise drop a keyboard user's place. + list.querySelectorAll("[data-duck-clip]").forEach(box => { + if (box.dataset["duckClip"] === focused) box.focus(); + }); + } + + private async setDucking(on: boolean): Promise { + const { trackIdx, clipIdx } = this; + if (!on) { + this.write(trackIdx, clipIdx, undefined); + return; + } + + const clip = this.edit.getResolvedClip(trackIdx, clipIdx); + const clipId = this.edit.getClipId(trackIdx, clipIdx); + if (!clip) return; + const others = findEligibleSourceClips(this.edit).filter(info => info.clipId !== clipId); + const targets = others.filter(info => { + const other = info.assetType !== "video" && this.edit.getResolvedClip(info.trackIndex, info.clipIndex); + return other && other.start < clip.start + clip.length && clip.start < other.start + other.length; + }); + if (targets.length === 0) { + this.sync(); + if (this.errorNote) { + this.errorNote.textContent = + others.length > 0 ? "No audio plays over this clip. Tick the clips to duck under." : "There are no other clips to duck under."; + } + return; + } + + const aliases = await Promise.all(targets.map(info => ensureClipAlias(this.edit, info.trackIndex, info.clipIndex))); + this.write(trackIdx, clipIdx, { under: aliases.map(alias => `alias://${alias}`) }); + } + + private async toggleClip(targetId: string, ticked: boolean): Promise { + const { trackIdx, clipIdx } = this; + const target = findEligibleSourceClips(this.edit).find(info => info.clipId === targetId); + if (!target) return; + + const ref = `alias://${ticked ? await ensureClipAlias(this.edit, target.trackIndex, target.clipIndex) : target.currentAlias}`; + const duck = this.documentDuck(trackIdx, clipIdx); + const under = [duck?.under ?? []].flat().filter(existing => existing !== ref); + if (ticked) under.push(ref); + this.write(trackIdx, clipIdx, under.length > 0 ? { ...duck, under } : undefined); + } + + private setLevel(custom: boolean): void { + const duck = this.documentDuck(); + if (!duck || custom === (typeof duck.volume === "number")) return; + if (custom) this.setVolume(DUCK_DEFAULT_VOLUME); + else this.write(this.trackIdx, this.clipIdx, { ...duck, volume: undefined }); + } + + private setVolume(volume: number): void { + const duck = this.documentDuck(); + if (!duck) return; + const issue = this.issues({ ...this.resolvedDuck(), volume }).find(({ key }) => key === "duck.volume"); + if (issue) { + if (this.errorNote) this.errorNote.textContent = issue.text; + return; + } + this.write(this.trackIdx, this.clipIdx, { ...duck, volume }); + } + + private async updateHint(): Promise { + // A pending batch can take seconds, and the old hint may not apply to this clip or level. + if (this.hintNote) this.hintNote.textContent = ""; + const levels = this.edit.getDuckLevels(); + await levels.whenSettled(); + const clipId = this.edit.getClipId(this.trackIdx, this.clipIdx); + if (!this.container || !this.hintNote || !clipId) return; + + const { aliases, ducking } = scanDucking(this.edit.getResolvedEdit()); + const entry = ducking.find(({ clip }) => (clip as ResolvedClip).id === clipId); + const measured = levels.levelsFor(clipId); + // Only planned refs count: a ref that doesn't overlap the clip has no dip. + const unmeasured = entry ? planDuckMeasurements(entry.clip, aliases).some(({ ref }) => !measured?.has(ref)) : false; + this.hintNote.textContent = unmeasured ? "Couldn't measure some clips' loudness, so their dips use the default level." : ""; + } + + private write(trackIdx: number, clipIdx: number, duck: Duck | undefined): void { + this.edit.updateClip(trackIdx, clipIdx, { asset: { duck } } as Record); + } +} diff --git a/src/core/ui/media-toolbar.ts b/src/core/ui/media-toolbar.ts index beed8f9d..db868f24 100644 --- a/src/core/ui/media-toolbar.ts +++ b/src/core/ui/media-toolbar.ts @@ -17,6 +17,7 @@ import type { AudioAsset, Duck, ResolvedClip } from "@schemas"; import { injectShotstackStyles } from "@styles/inject"; import { BaseToolbar } from "./base-toolbar"; +import { DuckPanel } from "./composites/DuckPanel"; import { EffectPanel } from "./composites/EffectPanel"; import { TransitionPanel } from "./composites/TransitionPanel"; import { DragStateManager } from "./drag-state-manager"; @@ -120,6 +121,7 @@ export class MediaToolbar extends BaseToolbar { // ─── Composite UI Components ───────────────────────────────────────────────── private transitionPanel: TransitionPanel | null = null; private effectPanel: EffectPanel | null = null; + private duckPanel: DuckPanel | null = null; private opacitySlider: SliderControl | null = null; private scaleSlider: SliderControl | null = null; private mergeFieldManager: MergeFieldLabelManager | null = null; @@ -138,6 +140,7 @@ export class MediaToolbar extends BaseToolbar { private advancedBtn: HTMLButtonElement | null = null; private audioFadeBtn: HTMLButtonElement | null = null; private speedBtn: HTMLButtonElement | null = null; + private duckBtn: HTMLButtonElement | null = null; // ─── Popup Elements ────────────────────────────────────────────────────────── private fitPopup: HTMLDivElement | null = null; @@ -149,6 +152,7 @@ export class MediaToolbar extends BaseToolbar { private advancedPopup: HTMLDivElement | null = null; private audioFadePopup: HTMLDivElement | null = null; private speedPopup: HTMLDivElement | null = null; + private duckPopup: HTMLDivElement | null = null; // ─── Other Elements ────────────────────────────────────────────────────────── private fitLabel: HTMLSpanElement | null = null; @@ -158,6 +162,7 @@ export class MediaToolbar extends BaseToolbar { private volumeSection: HTMLDivElement | null = null; private visualSection: HTMLDivElement | null = null; private audioSection: HTMLDivElement | null = null; + private duckSection: HTMLDivElement | null = null; private speedSection: HTMLDivElement | null = null; private speedSlider: HTMLInputElement | null = null; private speedValue: HTMLSpanElement | null = null; @@ -360,6 +365,20 @@ export class MediaToolbar extends BaseToolbar { + + +
+
+
+ +
+
+
+
+
${ @@ -405,6 +424,7 @@ export class MediaToolbar extends BaseToolbar { this.advancedBtn = this.container.querySelector('[data-action="advanced"]'); this.audioFadeBtn = this.container.querySelector('[data-action="audio-fade"]'); this.speedBtn = this.container.querySelector('[data-action="speed"]'); + this.duckBtn = this.container.querySelector('[data-action="duck"]'); this.fitPopup = this.container.querySelector('[data-popup="fit"]'); this.opacityPopup = this.container.querySelector('[data-popup="opacity"]'); @@ -415,6 +435,7 @@ export class MediaToolbar extends BaseToolbar { this.advancedPopup = this.container.querySelector('[data-popup="advanced"]'); this.audioFadePopup = this.container.querySelector('[data-popup="audio-fade"]'); this.speedPopup = this.container.querySelector('[data-popup="speed"]'); + this.duckPopup = this.container.querySelector('[data-popup="duck"]'); this.fitLabel = this.container.querySelector("[data-fit-label]"); this.volumeValue = this.container.querySelector("[data-volume-value]"); @@ -423,6 +444,7 @@ export class MediaToolbar extends BaseToolbar { this.volumeSection = this.container.querySelector("[data-volume-section]"); this.visualSection = this.container.querySelector("[data-visual-section]"); this.audioSection = this.container.querySelector("[data-audio-section]"); + this.duckSection = this.container.querySelector("[data-duck-section]"); this.speedSection = this.container.querySelector("[data-speed-section]"); this.speedSlider = this.container.querySelector("[data-speed-slider]"); this.speedValue = this.container.querySelector("[data-speed-value]"); @@ -531,6 +553,12 @@ export class MediaToolbar extends BaseToolbar { this.effectPanel.onChange(() => this.applyEffect()); this.effectPanel.mount(effectMount as HTMLElement); } + + const duckMount = this.container?.querySelector("[data-duck-panel-mount]"); + if (duckMount) { + this.duckPanel = new DuckPanel(this.edit); + this.duckPanel.mount(duckMount as HTMLElement); + } } private setupEventListeners(): void { @@ -611,6 +639,15 @@ export class MediaToolbar extends BaseToolbar { }, { signal } ); + this.duckBtn?.addEventListener( + "click", + e => { + e.stopPropagation(); + this.duckPanel?.sync(); + this.togglePopupByName("duck"); + }, + { signal } + ); this.opacityPreviousKeyframeBtn?.addEventListener("click", () => this.navigateOpacityKeyframe(-1), { signal }); this.opacityKeyframeBtn?.addEventListener("click", () => this.toggleOpacityKeyframe(), { signal }); @@ -753,7 +790,9 @@ export class MediaToolbar extends BaseToolbar { this.syncState(); } - private togglePopupByName(popup: "fit" | "opacity" | "scale" | "volume" | "transition" | "effect" | "advanced" | "audio-fade" | "speed"): void { + private togglePopupByName( + popup: "fit" | "opacity" | "scale" | "volume" | "transition" | "effect" | "advanced" | "audio-fade" | "speed" | "duck" + ): void { const popupMap = { fit: { popup: this.fitPopup, btn: this.fitBtn }, opacity: { popup: this.opacityPopup, btn: this.opacityBtn }, @@ -763,7 +802,8 @@ export class MediaToolbar extends BaseToolbar { effect: { popup: this.effectPopup, btn: this.effectBtn }, advanced: { popup: this.advancedPopup, btn: this.advancedBtn }, "audio-fade": { popup: this.audioFadePopup, btn: this.audioFadeBtn }, - speed: { popup: this.speedPopup, btn: this.speedBtn } + speed: { popup: this.speedPopup, btn: this.speedBtn }, + duck: { popup: this.duckPopup, btn: this.duckBtn } }; const isCurrentlyOpen = popupMap[popup].popup?.classList.contains("visible"); @@ -788,6 +828,7 @@ export class MediaToolbar extends BaseToolbar { this.advancedBtn?.classList.remove("active"); this.audioFadeBtn?.classList.remove("active"); this.speedBtn?.classList.remove("active"); + this.duckBtn?.classList.remove("active"); } protected override getPopupList(): (HTMLElement | null)[] { @@ -800,7 +841,8 @@ export class MediaToolbar extends BaseToolbar { this.effectPopup, this.advancedPopup, this.audioFadePopup, - this.speedPopup + this.speedPopup, + this.duckPopup ]; } @@ -866,6 +908,8 @@ export class MediaToolbar extends BaseToolbar { if (this.audioSection) { this.audioSection.classList.toggle("hidden", !AUDIO_FADE_ASSET_TYPES.has(this.assetType)); } + // The API defines `duck` on audio assets only, so text-to-speech keeps Fade without it. + this.duckSection?.classList.toggle("hidden", this.assetType !== "audio"); // Show/hide speed section (only for types whose preview honours speed) if (this.speedSection) { @@ -1379,10 +1423,18 @@ export class MediaToolbar extends BaseToolbar { private syncDuckState(clip: ResolvedClip): void { const audio = this.assetType === "audio"; const ducking = audio && Boolean((clip.asset as AudioAsset).duck); + this.duckPanel?.setClip(this.selectedTrackIdx, this.selectedClipIdx); + const reason = audio ? (this.duckPanel?.blocker() ?? "") : ""; + if (this.duckBtn) { + // Left enabled while ducking, so an imported edit that breaks a rule can still be switched off. + this.duckBtn.disabled = Boolean(reason) && !ducking; + this.duckBtn.title = reason; + } if (this.speedBtn) { this.speedBtn.disabled = ducking; this.speedBtn.title = ducking ? "Turn off ducking to change speed" : ""; } + if (audio && this.isPopupOpen(this.duckPopup)) this.duckPanel?.sync(); } private applyClipUpdate(updates: Record): void { @@ -1605,6 +1657,7 @@ export class MediaToolbar extends BaseToolbar { // Dispose composite components this.transitionPanel?.dispose(); this.effectPanel?.dispose(); + this.duckPanel?.dispose(); this.opacitySlider?.dispose(); this.scaleSlider?.dispose(); @@ -1618,6 +1671,7 @@ export class MediaToolbar extends BaseToolbar { this.transitionPanel = null; this.effectPanel = null; + this.duckPanel = null; this.opacitySlider = null; this.scaleSlider = null; @@ -1633,6 +1687,7 @@ export class MediaToolbar extends BaseToolbar { this.advancedBtn = null; this.audioFadeBtn = null; this.speedBtn = null; + this.duckBtn = null; this.fitPopup = null; this.opacityPopup = null; @@ -1643,6 +1698,7 @@ export class MediaToolbar extends BaseToolbar { this.advancedPopup = null; this.audioFadePopup = null; this.speedPopup = null; + this.duckPopup = null; this.fitLabel = null; this.volumeSlider = null; @@ -1651,6 +1707,7 @@ export class MediaToolbar extends BaseToolbar { this.volumeSection = null; this.visualSection = null; this.audioSection = null; + this.duckSection = null; this.speedSection = null; this.speedSlider = null; this.speedValue = null; diff --git a/src/styles/index.css b/src/styles/index.css index e3b6ecf8..497d3a20 100644 --- a/src/styles/index.css +++ b/src/styles/index.css @@ -12,6 +12,7 @@ @import "./ui/rich-text-toolbar.css"; @import "./ui/svg-toolbar.css"; @import "./ui/media-toolbar.css"; +@import "./ui/duck-panel.css"; @import "./ui/generate-toolbar.css"; @import "./ui/text-to-image-toolbar.css"; @import "./ui/text-to-speech-toolbar.css"; diff --git a/src/styles/ui/duck-panel.css b/src/styles/ui/duck-panel.css new file mode 100644 index 00000000..21f99fe9 --- /dev/null +++ b/src/styles/ui/duck-panel.css @@ -0,0 +1,80 @@ +.ss-duck-options { + min-width: 0; + margin: 12px 0 0; + padding: 0; + border: 0; +} + +.ss-duck-options:disabled { + opacity: 0.5; +} + +.ss-duck-options legend { + padding: 0; +} + +/* Long timelines list many clips, so the list scrolls past a set height */ +.ss-duck-clips { + display: flex; + flex-direction: column; + gap: 2px; + max-height: 180px; + overflow-y: auto; + margin-bottom: 12px; +} + +.ss-duck-clip { + display: flex; + align-items: center; + gap: 8px; + padding: 6px 4px; + border-radius: 6px; + font-size: 12px; + color: rgba(255, 255, 255, 0.85); + cursor: pointer; +} + +.ss-duck-clip:hover { + background: rgba(255, 255, 255, 0.06); +} + +.ss-duck-clip input { + flex-shrink: 0; + margin: 0; + accent-color: rgba(99, 102, 241, 0.9); +} + +.ss-duck-clip span { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.ss-duck-empty { + padding: 4px; + font-size: 12px; + color: rgba(255, 255, 255, 0.5); +} + +.ss-duck-custom { + margin-top: 12px; +} + +.ss-duck-note { + margin: 10px 0 0; + font-size: 11px; + line-height: 1.4; + color: rgba(255, 255, 255, 0.6); +} + +.ss-duck-note:empty { + display: none; +} + +.ss-duck-note--error { + color: #f87171; +} + +.ss-duck-options .ss-media-toolbar-presets { + margin-top: 0; +} diff --git a/src/styles/ui/media-toolbar.css b/src/styles/ui/media-toolbar.css index 15e4cc5d..002cd41f 100644 --- a/src/styles/ui/media-toolbar.css +++ b/src/styles/ui/media-toolbar.css @@ -1092,3 +1092,9 @@ .ss-audio-fade-btn.active .ss-audio-fade-label { color: rgba(255, 255, 255, 0.9); } + +/* Duck popup */ +.ss-media-toolbar-popup--duck { + min-width: 260px; + padding: 12px; +} diff --git a/tests/media-toolbar-duck.test.ts b/tests/media-toolbar-duck.test.ts index 4a46f262..25b2b5ea 100644 --- a/tests/media-toolbar-duck.test.ts +++ b/tests/media-toolbar-duck.test.ts @@ -19,6 +19,7 @@ if (typeof structuredClone === "undefined") { type TestClip = Record & { id: string; start: number; length: number; asset: Record }; const MUSIC = 0; +const NARRATION = 2; /** Music on track 0 is the selected clip; everything else is a candidate to duck under. */ function createTracks(music: Record = {}, narration: Record = { alias: "narration" }): TestClip[][] { @@ -43,12 +44,17 @@ function createTracks(music: Record = {}, narration: Record void>>(); + const levels = new Map>(); + let settled: Promise = Promise.resolve(); const clipAt = (t: number, c: number) => tracks[t]?.[c] ?? null; const edit = { getClipId: jest.fn((t: number, c: number) => clipAt(t, c)?.id ?? null), getResolvedClip: jest.fn(clipAt), getDocumentClip: jest.fn(clipAt), + getDocument: () => ({ getTrackCount: () => tracks.length, getClipsInTrack: (t: number) => tracks[t] }), + getResolvedEdit: () => ({ timeline: { tracks: tracks.map(clips => ({ clips })) } }), + getDuckLevels: () => ({ levelsFor: (clipId: string) => levels.get(clipId), whenSettled: () => settled }), // Applied a tick later, like the command queue, so writes land after the handler that made them. updateClip: jest.fn((t: number, c: number, updates: Record) => Promise.resolve().then(() => { @@ -77,7 +83,13 @@ function createEdit(tracks: TestClip[][]) { size: { width: 1920, height: 1080 } }; - return { edit }; + return { + edit, + levels, + setSettled: (promise: Promise) => { + settled = promise; + } + }; } const flush = () => @@ -103,8 +115,11 @@ function mount(tracks: TestClip[][], selected: [number, number] = [MUSIC, 0]) { toolbar.show(...selected); const q = (selector: string) => parent.querySelector(selector) as T; + const duckButton = q('[data-action="duck"]'); + const open = () => duckButton.click(); + const box = (clipId: string) => q(`[data-duck-clip="${clipId}"]`); const music = () => tracks[MUSIC][0]; - return { ...mocked, toolbar, parent, q, music }; + return { ...mocked, toolbar, parent, q, duckButton, open, box, music }; } describe("MediaToolbar on a ducked clip", () => { @@ -185,3 +200,223 @@ describe("MediaToolbar on a ducked clip", () => { }); }); }); + +describe("MediaToolbar Duck control", () => { + afterEach(() => { + document.body.innerHTML = ""; + jest.clearAllMocks(); + }); + + it("shows for audio clips only", () => { + const tracks = createTracks(); + const speech = mount(tracks, [NARRATION, 0]); + expect(speech.q("[data-audio-section]").classList.contains("hidden")).toBe(false); + expect(speech.q("[data-duck-section]").classList.contains("hidden")).toBe(true); + speech.toolbar.dispose(); + + const music = mount(tracks); + expect(music.q("[data-duck-section]").classList.contains("hidden")).toBe(false); + music.toolbar.dispose(); + }); + + it("switching on ducks under the overlapping audio and speech clips, listing video unticked", async () => { + const { edit, toolbar, open, q, box, music } = mount(createTracks()); + open(); + q("[data-duck-toggle]").click(); + await flush(); + + expect(edit.updateClip).toHaveBeenCalledTimes(1); + expect(edit.updateClip).toHaveBeenCalledWith(MUSIC, 0, { asset: { duck: { under: ["alias://narration", "alias://voice"] } } }); + expect(music().asset["duck"]).toEqual({ under: ["alias://narration", "alias://voice"] }); + + expect(q("[data-duck-toggle]").checked).toBe(true); + expect(box("clip-voice-0000beef").checked).toBe(true); + expect(box("clip-speech-3f9a2c10").checked).toBe(true); + expect(box("clip-video-00c0ffee").checked).toBe(false); + expect(box("clip-video-00c0ffee").closest("label")?.textContent).toContain("broll"); + expect(box("clip-outro-0000cafe").checked).toBe(false); + expect(box("clip-music-a1b2c3d4")).toBeNull(); + toolbar.dispose(); + }); + + const [[bed], [, outro]] = createTracks(); + it.each([ + ["only clips that don't overlap", [[bed], [outro]], "No audio plays over this clip. Tick the clips to duck under."], + ["no other clips", [[bed]], "There are no other clips to duck under."] + ])("switching on with %s writes nothing and says why", async (_case, tracks, message) => { + const { edit, toolbar, open, q } = mount(tracks); + open(); + q("[data-duck-toggle]").click(); + await flush(); + + expect(edit.updateClip).not.toHaveBeenCalled(); + expect(q("[data-duck-error]").textContent).toBe(message); + toolbar.dispose(); + }); + + it("ticking a clip with no alias gives it one and writes alias://", async () => { + const tracks = createTracks({ duck: { under: ["alias://voice"] } }, {}); + const { edit, toolbar, open, box, music } = mount(tracks); + open(); + box("clip-speech-3f9a2c10").click(); + await flush(); + + expect(tracks[NARRATION][0]["alias"]).toBe("source_3f9a2c10"); + expect(edit.updateClip).toHaveBeenLastCalledWith(MUSIC, 0, { asset: { duck: { under: ["alias://voice", "alias://source_3f9a2c10"] } } }); + expect(music().asset["duck"]).toEqual({ under: ["alias://voice", "alias://source_3f9a2c10"] }); + toolbar.dispose(); + }); + + it("unticking the last clip removes duck", async () => { + const { edit, toolbar, open, box, music, q } = mount(createTracks({ duck: { under: ["alias://voice"], volume: 0.2 } })); + open(); + box("clip-voice-0000beef").click(); + await flush(); + + expect(edit.updateClip).toHaveBeenCalledTimes(1); + expect(music().asset["duck"]).toBeUndefined(); + expect(q("[data-duck-toggle]").checked).toBe(false); + toolbar.dispose(); + }); + + it("Custom writes duck.volume and Auto removes it", async () => { + const { toolbar, open, q, music } = mount(createTracks({ duck: { under: ["alias://voice"] } })); + open(); + const slider = q("[data-duck-volume]"); + expect(q("[data-duck-custom]").hidden).toBe(true); + + q('[data-duck-level-option="custom"]').click(); + await flush(); + expect(music().asset["duck"]).toEqual({ under: ["alias://voice"], volume: 0.05 }); + expect(q("[data-duck-custom]").hidden).toBe(false); + expect(slider.value).toBe("5"); + + slider.value = "20"; + slider.dispatchEvent(new Event("input", { bubbles: true })); + expect(q("[data-duck-volume-value]").textContent).toBe("20%"); + slider.dispatchEvent(new Event("change", { bubbles: true })); + await flush(); + expect(music().asset["duck"]).toEqual({ under: ["alias://voice"], volume: 0.2 }); + + q('[data-duck-level-option="auto"]').click(); + await flush(); + expect((music().asset["duck"] as { volume?: number }).volume).toBeUndefined(); + expect(q('[data-duck-level-option="auto"]').getAttribute("aria-pressed")).toBe("true"); + toolbar.dispose(); + }); + + it("warns about a Custom level at or above the clip's volume and writes nothing", async () => { + const { edit, toolbar, open, q, music } = mount(createTracks({ duck: { under: ["alias://voice"], volume: 0.3 } })); + open(); + const slider = q("[data-duck-volume]"); + slider.value = "80"; + slider.dispatchEvent(new Event("input", { bubbles: true })); + slider.dispatchEvent(new Event("change", { bubbles: true })); + await flush(); + + expect(edit.updateClip).not.toHaveBeenCalled(); + expect(q("[data-duck-error]").textContent).toBe("Choose a level below the clip's volume."); + expect(music().asset["duck"]).toEqual({ under: ["alias://voice"], volume: 0.3 }); + toolbar.dispose(); + }); + + it("writes a valid Custom level even with a dangling duck reference", async () => { + const { edit, toolbar, open, q, music } = mount(createTracks({ duck: { under: ["alias://voice", "alias://gone"], volume: 0.3 } })); + open(); + expect(q("[data-duck-reason]").textContent).toBe("A clip this ducks under no longer exists."); + const slider = q("[data-duck-volume]"); + slider.value = "20"; + slider.dispatchEvent(new Event("change", { bubbles: true })); + await flush(); + + expect(edit.updateClip).toHaveBeenCalledTimes(1); + expect(q("[data-duck-error]").textContent).toBe(""); + expect(music().asset["duck"]).toEqual({ under: ["alias://voice", "alias://gone"], volume: 0.2 }); + toolbar.dispose(); + }); + + it.each([ + ["the volume is an array", { volume: [{ from: 0, to: 1, start: 0, length: 1 }] }, "Ducking needs a constant volume."], + ["the speed is not 1", { speed: 2 }, "Ducking needs normal speed."] + ])("disables the control with a reason when %s", (_case, asset, reason) => { + const { toolbar, duckButton } = mount(createTracks(asset)); + expect(duckButton.disabled).toBe(true); + expect(duckButton.title).toBe(reason); + toolbar.dispose(); + }); + + it("makes every change one undo entry when the clips already have aliases", async () => { + const { edit, toolbar, open, q, box } = mount(createTracks()); + open(); + const oneEntry = async (step: string, act: () => void) => { + const before = edit.updateClip.mock.calls.length; + act(); + await flush(); + expect([step, edit.updateClip.mock.calls.length - before]).toEqual([step, 1]); + }; + + await oneEntry("switch on", () => q("[data-duck-toggle]").click()); + await oneEntry("untick", () => box("clip-voice-0000beef").click()); + await oneEntry("tick", () => box("clip-voice-0000beef").click()); + await oneEntry("custom", () => q('[data-duck-level-option="custom"]').click()); + await oneEntry("drag the level", () => drag(q("[data-duck-volume]"), ["10", "20", "30"])); + await oneEntry("auto", () => q('[data-duck-level-option="auto"]').click()); + await oneEntry("switch off", () => q("[data-duck-toggle]").click()); + expect(edit.updateClipInDocument).not.toHaveBeenCalled(); + expect(edit.commitClipUpdate).not.toHaveBeenCalled(); + toolbar.dispose(); + }); + + describe("measurement hint", () => { + const HINT = "Couldn't measure some clips' loudness, so their dips use the default level."; + + it("appears once measuring settles with a planned clip unmeasured", async () => { + const { toolbar, open, q, levels, setSettled } = mount(createTracks({ duck: { under: ["alias://voice", "alias://narration"] } })); + let settle!: () => void; + setSettled( + new Promise(resolve => { + settle = resolve; + }) + ); + open(); + await flush(); + expect(q("[data-duck-hint]").textContent).toBe(""); + + levels.set("clip-music-a1b2c3d4", new Map([["alias://voice", 0.12]])); + settle(); + await flush(); + expect(q("[data-duck-hint]").textContent).toBe(HINT); + toolbar.dispose(); + }); + + it("ignores clips that don't overlap, since they have no dip", async () => { + const { toolbar, open, q, levels } = mount(createTracks({ duck: { under: ["alias://voice", "alias://outro"] } })); + levels.set("clip-music-a1b2c3d4", new Map([["alias://voice", 0.12]])); + open(); + await flush(); + expect(q("[data-duck-hint]").textContent).toBe(""); + toolbar.dispose(); + }); + + it("stays hidden for a Custom level", async () => { + const { toolbar, open, q } = mount(createTracks({ duck: { under: ["alias://voice"], volume: 0.2 } })); + open(); + await flush(); + expect(q("[data-duck-hint]").textContent).toBe(""); + toolbar.dispose(); + }); + + it("clears as soon as the level changes, without waiting for measuring to settle", async () => { + const { toolbar, open, q, setSettled } = mount(createTracks({ duck: { under: ["alias://voice"] } })); + open(); + await flush(); + expect(q("[data-duck-hint]").textContent).toBe(HINT); + + setSettled(new Promise(() => {})); + q('[data-duck-level-option="custom"]').click(); + await flush(); + expect(q("[data-duck-hint]").textContent).toBe(""); + toolbar.dispose(); + }); + }); +}); diff --git a/tests/media-toolbar.test.ts b/tests/media-toolbar.test.ts index bd776793..c1e3ce75 100644 --- a/tests/media-toolbar.test.ts +++ b/tests/media-toolbar.test.ts @@ -57,6 +57,7 @@ function createMockEditSession() { getClipId: jest.fn().mockReturnValue("clip-1"), getResolvedClip: jest.fn(), getDocumentClip: jest.fn(), + getResolvedEdit: jest.fn(() => ({ timeline: { tracks: [] } })), updateClip: jest.fn(), updateClipInDocument: jest.fn(), resolveClip: jest.fn(), diff --git a/tests/toolbar.test.ts b/tests/toolbar.test.ts index 595033d5..f68f8b92 100644 --- a/tests/toolbar.test.ts +++ b/tests/toolbar.test.ts @@ -150,6 +150,7 @@ function createMockEdit(overrides: Record = {}) { getClipGenerationState: jest.fn(() => undefined), getResolvedClip: jest.fn(() => null), getResolvedClipById: jest.fn(() => null), + getResolvedEdit: jest.fn(() => ({ timeline: { tracks: [] } })), getDocumentClip: jest.fn(() => ({ start: 0, length: 1 })), getCurrentTime: jest.fn(() => 0), getEdit: jest.fn(() => ({