Skip to content

Commit a7a6648

Browse files
feat(player): add volume/mute controls (#651)
* feat(player): add volume/mute controls to the player Adds a mute toggle button and volume slider to the controls bar, positioned between the time display and speed selector. The slider expands on hover for a compact default footprint. - `volume` attribute/property (0–1, clamped) with `volumechange` event - `muted` attribute now syncs to the controls UI (icon updates) - Three volume icons: high, low, muted — updates reactively - Volume forwarded to parent-frame audio proxies and iframe runtime via `set-volume` postMessage control - 9 new tests covering volume clamping, events, controls rendering, mute toggle, and iframe message forwarding Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]> * fix(player): wire set-volume through runtime bridge + address review feedback Addresses the blocker from PR review: the iframe runtime now handles `set-volume` messages end-to-end (types → bridge → init → media sync). Runtime side: - Add `set-volume` to RuntimeBridgeControlAction union - Add `volume` field to RuntimeBridgeControlMessage - Handle `set-volume` in bridge.ts with [0,1] clamping - Store bridgeVolume in RuntimeState, apply to media elements - syncRuntimeMedia composes userVolume × clip author volume Player side: - Muted toggle now dispatches `volumechange` (HTML5 spec compliance) - Volume slider auto-unmutes when scrubbed above 0 while muted - Touch support on volume slider (touchstart/move/end) Tests: 5 new (3 bridge, 2 media) Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]> * fix(player): add ARIA keyboard controls, fix icon collision and clipVolume parity - Volume slider: role="slider", aria-label, aria-valuemin/max/now, tabindex=0, arrow key support (5% steps, auto-unmutes) - Volume=0 unmuted now shows low-volume icon instead of muted icon - Fix clipVolume divergence: init.ts uses Number.isFinite() matching media.ts semantics (preserves data-volume="0") - 3 new tests: ARIA attributes, volumechange on mute, icon collision Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]> --------- Co-authored-by: Claude Opus 4.6 (1M context) <[email protected]>
1 parent 614f764 commit a7a6648

11 files changed

Lines changed: 490 additions & 2 deletions

File tree

‎packages/core/src/runtime/bridge.test.ts‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ function createMockDeps() {
77
onPause: vi.fn(),
88
onSeek: vi.fn(),
99
onSetMuted: vi.fn(),
10+
onSetVolume: vi.fn(),
1011
onSetMediaOutputMuted: vi.fn(),
1112
onSetPlaybackRate: vi.fn(),
1213
onEnablePickMode: vi.fn(),
@@ -56,6 +57,29 @@ describe("installRuntimeControlBridge", () => {
5657
expect(deps.onSetMuted).toHaveBeenCalledWith(true);
5758
});
5859

60+
it("dispatches set-volume command", () => {
61+
const deps = createMockDeps();
62+
const handler = installRuntimeControlBridge(deps);
63+
handler(makeControlMessage("set-volume", { volume: 0.5 }));
64+
expect(deps.onSetVolume).toHaveBeenCalledWith(0.5);
65+
});
66+
67+
it("clamps set-volume to [0, 1]", () => {
68+
const deps = createMockDeps();
69+
const handler = installRuntimeControlBridge(deps);
70+
handler(makeControlMessage("set-volume", { volume: 1.5 }));
71+
expect(deps.onSetVolume).toHaveBeenCalledWith(1);
72+
handler(makeControlMessage("set-volume", { volume: -0.5 }));
73+
expect(deps.onSetVolume).toHaveBeenCalledWith(0);
74+
});
75+
76+
it("defaults volume to 1 when absent", () => {
77+
const deps = createMockDeps();
78+
const handler = installRuntimeControlBridge(deps);
79+
handler(makeControlMessage("set-volume"));
80+
expect(deps.onSetVolume).toHaveBeenCalledWith(1);
81+
});
82+
5983
it("dispatches set-media-output-muted command", () => {
6084
const deps = createMockDeps();
6185
const handler = installRuntimeControlBridge(deps);

‎packages/core/src/runtime/bridge.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ type BridgeDeps = {
55
onPause: () => void;
66
onSeek: (frame: number, seekMode: "drag" | "commit") => void;
77
onSetMuted: (muted: boolean) => void;
8+
onSetVolume: (volume: number) => void;
89
onSetMediaOutputMuted: (muted: boolean) => void;
910
onSetPlaybackRate: (rate: number) => void;
1011
onEnablePickMode: () => void;
@@ -40,6 +41,10 @@ export function installRuntimeControlBridge(deps: BridgeDeps): (event: MessageEv
4041
deps.onSetMuted(Boolean(data.muted));
4142
return;
4243
}
44+
if (action === "set-volume") {
45+
deps.onSetVolume(Math.max(0, Math.min(1, Number(data.volume ?? 1))));
46+
return;
47+
}
4348
if (action === "set-media-output-muted") {
4449
deps.onSetMediaOutputMuted(Boolean(data.muted));
4550
return;

‎packages/core/src/runtime/init.ts‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1296,6 +1296,7 @@ export function initSandboxRuntimeModular(): void {
12961296
playbackRate: state.playbackRate,
12971297
outputMuted: state.mediaOutputMuted,
12981298
userMuted: state.bridgeMuted,
1299+
userVolume: state.bridgeVolume,
12991300
onAutoplayBlocked: () => {
13001301
if (state.mediaAutoplayBlockedPosted) return;
13011302
state.mediaAutoplayBlockedPosted = true;
@@ -1555,6 +1556,16 @@ export function initSandboxRuntimeModular(): void {
15551556
el.muted = effective;
15561557
}
15571558
},
1559+
onSetVolume: (volume) => {
1560+
state.bridgeVolume = volume;
1561+
const mediaEls = document.querySelectorAll("video, audio");
1562+
for (const el of mediaEls) {
1563+
if (!(el instanceof HTMLMediaElement)) continue;
1564+
const parsed = parseFloat(el.dataset.volume ?? "");
1565+
const clipVolume = Number.isFinite(parsed) ? parsed : 1;
1566+
el.volume = clipVolume * volume;
1567+
}
1568+
},
15581569
onSetMediaOutputMuted: (muted) => {
15591570
state.mediaOutputMuted = muted;
15601571
const effective = muted || state.bridgeMuted;

‎packages/core/src/runtime/media.test.ts‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -319,6 +319,30 @@ describe("syncRuntimeMedia", () => {
319319
expect(clip.el.volume).toBe(0.7);
320320
});
321321

322+
it("applies userVolume as a multiplier on clip volume", () => {
323+
const clip = createMockClip({ start: 0, end: 10, volume: 0.8 });
324+
syncRuntimeMedia({
325+
clips: [clip],
326+
timeSeconds: 5,
327+
playing: false,
328+
playbackRate: 1,
329+
userVolume: 0.5,
330+
});
331+
expect(clip.el.volume).toBeCloseTo(0.4);
332+
});
333+
334+
it("applies userVolume to clips without explicit volume (default 1)", () => {
335+
const clip = createMockClip({ start: 0, end: 10 });
336+
syncRuntimeMedia({
337+
clips: [clip],
338+
timeSeconds: 5,
339+
playing: false,
340+
playbackRate: 1,
341+
userVolume: 0.3,
342+
});
343+
expect(clip.el.volume).toBeCloseTo(0.3);
344+
});
345+
322346
it("hard-syncs on the first active tick (sub-composition activation, mediaStart offsets)", () => {
323347
const clip = createMockClip({ start: 0, end: 10, mediaStart: 0 });
324348
Object.defineProperty(clip.el, "currentTime", { value: 0, writable: true });

‎packages/core/src/runtime/media.ts‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,11 @@ export function syncRuntimeMedia(params: {
118118
* before the next bridge message lands.
119119
*/
120120
userMuted?: boolean;
121+
/**
122+
* User's volume preference (0–1, set via `onSetVolume`). Multiplied with the
123+
* per-clip author volume so `data-volume="0.5"` at user volume 0.8 yields 0.4.
124+
*/
125+
userVolume?: number;
121126
/**
122127
* Invoked at most once when a media element's `play()` promise rejects with
123128
* `NotAllowedError`. The caller is expected to latch and post a single
@@ -142,7 +147,8 @@ export function syncRuntimeMedia(params: {
142147
relTime = clip.mediaStart + ((relTime - clip.mediaStart) % loopLength);
143148
}
144149
}
145-
if (clip.volume != null) el.volume = clip.volume;
150+
const userVol = params.userVolume ?? 1;
151+
el.volume = (clip.volume ?? 1) * userVol;
146152
if (shouldMute) el.muted = true;
147153
// Ensure full preload for every active media element. Streaming
148154
// formats (MP3) may arrive with preload="metadata", which only

‎packages/core/src/runtime/state.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ export type RuntimeState = {
1010
parityModeEnabled: boolean;
1111
canonicalFps: number;
1212
bridgeMuted: boolean;
13+
bridgeVolume: number;
1314
/**
1415
* Internal mute of audible media output, owned by the audio-ownership
1516
* protocol between the parent (`<hyperframes-player>`) and this runtime.
@@ -78,6 +79,7 @@ export function createRuntimeState(): RuntimeState {
7879
parityModeEnabled: true,
7980
canonicalFps: 30,
8081
bridgeMuted: false,
82+
bridgeVolume: 1,
8183
mediaOutputMuted: false,
8284
mediaAutoplayBlockedPosted: false,
8385
playbackRate: 1,

‎packages/core/src/runtime/types.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ export type RuntimeBridgeControlAction =
1111
| "pause"
1212
| "seek"
1313
| "set-muted"
14+
| "set-volume"
1415
| "set-media-output-muted"
1516
| "set-playback-rate"
1617
| "enable-pick-mode"
@@ -23,6 +24,7 @@ export type RuntimeBridgeControlMessage = {
2324
action: RuntimeBridgeControlAction;
2425
frame?: number;
2526
muted?: boolean;
27+
volume?: number;
2628
playbackRate?: number;
2729
seekMode?: "drag" | "commit";
2830
};

‎packages/player/src/controls.ts‎

Lines changed: 138 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,18 @@
1-
import { PLAY_ICON, PAUSE_ICON } from "./styles.js";
1+
import {
2+
PLAY_ICON,
3+
PAUSE_ICON,
4+
VOLUME_HIGH_ICON,
5+
VOLUME_LOW_ICON,
6+
VOLUME_MUTED_ICON,
7+
} from "./styles.js";
28

39
export interface ControlsCallbacks {
410
onPlay: () => void;
511
onPause: () => void;
612
onSeek: (fraction: number) => void;
713
onSpeedChange: (speed: number) => void;
14+
onMuteToggle: () => void;
15+
onVolumeChange: (volume: number) => void;
816
}
917

1018
/** Default logarithmic speed presets — each step roughly doubles/halves. */
@@ -38,6 +46,8 @@ export function createControls(
3846
updateTime: (current: number, duration: number) => void;
3947
updatePlaying: (playing: boolean) => void;
4048
updateSpeed: (speed: number) => void;
49+
updateMuted: (muted: boolean) => void;
50+
updateVolume: (volume: number) => void;
4151
show: () => void;
4252
hide: () => void;
4353
destroy: () => void;
@@ -94,23 +104,135 @@ export function createControls(
94104
speedWrap.appendChild(speedMenu);
95105
speedWrap.appendChild(speedBtn);
96106

107+
const volumeWrap = document.createElement("div");
108+
volumeWrap.className = "hfp-volume-wrap";
109+
110+
const muteBtn = document.createElement("button");
111+
muteBtn.className = "hfp-mute-btn";
112+
muteBtn.type = "button";
113+
muteBtn.innerHTML = VOLUME_HIGH_ICON;
114+
muteBtn.setAttribute("aria-label", "Mute");
115+
116+
const volumeSliderWrap = document.createElement("div");
117+
volumeSliderWrap.className = "hfp-volume-slider-wrap";
118+
119+
const volumeSlider = document.createElement("div");
120+
volumeSlider.className = "hfp-volume-slider";
121+
volumeSlider.setAttribute("role", "slider");
122+
volumeSlider.setAttribute("aria-label", "Volume");
123+
volumeSlider.setAttribute("aria-valuemin", "0");
124+
volumeSlider.setAttribute("aria-valuemax", "100");
125+
volumeSlider.setAttribute("aria-valuenow", "100");
126+
volumeSlider.tabIndex = 0;
127+
const volumeFill = document.createElement("div");
128+
volumeFill.className = "hfp-volume-fill";
129+
volumeFill.style.width = "100%";
130+
volumeSlider.appendChild(volumeFill);
131+
volumeSliderWrap.appendChild(volumeSlider);
132+
133+
volumeWrap.appendChild(volumeSliderWrap);
134+
volumeWrap.appendChild(muteBtn);
135+
97136
controls.appendChild(playBtn);
98137
controls.appendChild(scrubber);
99138
controls.appendChild(time);
139+
controls.appendChild(volumeWrap);
100140
controls.appendChild(speedWrap);
101141
parent.appendChild(controls);
102142

103143
let isPlaying = false;
144+
let isMuted = false;
145+
let currentVolume = 1;
104146
let hideTimeout: ReturnType<typeof setTimeout> | null = null;
105147
let speedIndex = presets.indexOf(1); // start at 1x
106148
if (speedIndex === -1) speedIndex = 0;
107149

150+
const getVolumeIcon = (muted: boolean, volume: number): string => {
151+
if (muted) return VOLUME_MUTED_ICON;
152+
if (volume === 0) return VOLUME_LOW_ICON;
153+
if (volume < 0.5) return VOLUME_LOW_ICON;
154+
return VOLUME_HIGH_ICON;
155+
};
156+
108157
playBtn.addEventListener("click", (e) => {
109158
e.stopPropagation();
110159
if (isPlaying) callbacks.onPause();
111160
else callbacks.onPlay();
112161
});
113162

163+
muteBtn.addEventListener("click", (e) => {
164+
e.stopPropagation();
165+
callbacks.onMuteToggle();
166+
});
167+
168+
let volumeScrubbing = false;
169+
170+
const handleVolumeAt = (clientX: number) => {
171+
const rect = volumeSlider.getBoundingClientRect();
172+
const fraction = Math.max(0, Math.min(1, (clientX - rect.left) / rect.width));
173+
currentVolume = fraction;
174+
volumeFill.style.width = `${fraction * 100}%`;
175+
volumeSlider.setAttribute("aria-valuenow", String(Math.round(fraction * 100)));
176+
if (isMuted && fraction > 0) callbacks.onMuteToggle();
177+
muteBtn.innerHTML = getVolumeIcon(isMuted, fraction);
178+
callbacks.onVolumeChange(fraction);
179+
};
180+
181+
volumeSlider.addEventListener("mousedown", (e) => {
182+
e.stopPropagation();
183+
volumeScrubbing = true;
184+
handleVolumeAt(e.clientX);
185+
});
186+
const onVolumeMouseMove = (e: MouseEvent) => {
187+
if (volumeScrubbing) handleVolumeAt(e.clientX);
188+
};
189+
const onVolumeMouseUp = () => {
190+
volumeScrubbing = false;
191+
};
192+
document.addEventListener("mousemove", onVolumeMouseMove);
193+
document.addEventListener("mouseup", onVolumeMouseUp);
194+
195+
volumeSlider.addEventListener(
196+
"touchstart",
197+
(e) => {
198+
volumeScrubbing = true;
199+
const touch = e.touches[0];
200+
if (touch) handleVolumeAt(touch.clientX);
201+
},
202+
{ passive: true },
203+
);
204+
const onVolumeTouchMove = (e: TouchEvent) => {
205+
if (volumeScrubbing) {
206+
const touch = e.touches[0];
207+
if (touch) handleVolumeAt(touch.clientX);
208+
}
209+
};
210+
const onVolumeTouchEnd = () => {
211+
volumeScrubbing = false;
212+
};
213+
document.addEventListener("touchmove", onVolumeTouchMove, { passive: true });
214+
document.addEventListener("touchend", onVolumeTouchEnd);
215+
216+
const VOLUME_STEP = 0.05;
217+
volumeSlider.addEventListener("keydown", (e) => {
218+
let newVol = currentVolume;
219+
if (e.key === "ArrowRight" || e.key === "ArrowUp") {
220+
newVol = Math.min(1, currentVolume + VOLUME_STEP);
221+
} else if (e.key === "ArrowLeft" || e.key === "ArrowDown") {
222+
newVol = Math.max(0, currentVolume - VOLUME_STEP);
223+
} else {
224+
return;
225+
}
226+
e.preventDefault();
227+
e.stopPropagation();
228+
currentVolume = newVol;
229+
volumeFill.style.width = `${newVol * 100}%`;
230+
volumeSlider.setAttribute("aria-valuenow", String(Math.round(newVol * 100)));
231+
if (isMuted && newVol > 0) callbacks.onMuteToggle();
232+
muteBtn.innerHTML = getVolumeIcon(isMuted, newVol);
233+
callbacks.onVolumeChange(newVol);
234+
});
235+
114236
const setActiveOption = (speed: number) => {
115237
for (const opt of speedMenu.querySelectorAll(".hfp-speed-option")) {
116238
opt.classList.toggle("hfp-active", (opt as HTMLElement).dataset.speed === String(speed));
@@ -221,6 +343,17 @@ export function createControls(
221343
speedBtn.textContent = formatSpeed(speed);
222344
setActiveOption(speed);
223345
},
346+
updateMuted(muted: boolean) {
347+
isMuted = muted;
348+
muteBtn.innerHTML = getVolumeIcon(muted, currentVolume);
349+
muteBtn.setAttribute("aria-label", muted ? "Unmute" : "Mute");
350+
},
351+
updateVolume(volume: number) {
352+
currentVolume = volume;
353+
volumeFill.style.width = `${volume * 100}%`;
354+
volumeSlider.setAttribute("aria-valuenow", String(Math.round(volume * 100)));
355+
muteBtn.innerHTML = getVolumeIcon(isMuted, volume);
356+
},
224357
show() {
225358
controls.style.display = "";
226359
},
@@ -232,6 +365,10 @@ export function createControls(
232365
document.removeEventListener("mouseup", onMouseUp);
233366
document.removeEventListener("touchmove", onTouchMove);
234367
document.removeEventListener("touchend", onTouchEnd);
368+
document.removeEventListener("mousemove", onVolumeMouseMove);
369+
document.removeEventListener("mouseup", onVolumeMouseUp);
370+
document.removeEventListener("touchmove", onVolumeTouchMove);
371+
document.removeEventListener("touchend", onVolumeTouchEnd);
235372
document.removeEventListener("click", onDocClick);
236373
if (hideTimeout) clearTimeout(hideTimeout);
237374
},

0 commit comments

Comments
 (0)