Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 5 additions & 5 deletions src/factory/createHTMLMediaHook.ts
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ export default function createHTMLMediaHook<T extends HTMLAudioElement | HTMLVid
// if one tries to execute another `.play()` or `.pause()` while that
// promise is resolving. So we prevent that with this lock.
// See: https://bugs.chromium.org/p/chromium/issues/detail?id=593273
let lockPlay: boolean = false;
const lockPlay = useRef<boolean>(false);

const controls = {
play: () => {
Expand All @@ -148,14 +148,14 @@ export default function createHTMLMediaHook<T extends HTMLAudioElement | HTMLVid
return undefined;
}

if (!lockPlay) {
if (!lockPlay.current) {
const promise = el.play();
const isPromise = typeof promise === 'object';

if (isPromise) {
lockPlay = true;
lockPlay.current = true;
const resetLock = () => {
lockPlay = false;
lockPlay.current = false;
};
promise.then(resetLock, resetLock);
}
Expand All @@ -166,7 +166,7 @@ export default function createHTMLMediaHook<T extends HTMLAudioElement | HTMLVid
},
pause: () => {
const el = ref.current;
if (el && !lockPlay) {
if (el && !lockPlay.current) {
return el.pause();
}
},
Expand Down
22 changes: 22 additions & 0 deletions tests/useAudio.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,3 +41,25 @@ it('should init audio and utils', () => {
controls.volume(0.5);
expect(ref.current.volume).toBe(0.5);
});

it('should keep play lock across rerenders', () => {
const { result, rerender } = setUp();
const [, , controls, ref] = result.current;
const audio = document.createElement('audio');
const play = jest.fn(() => new Promise<void>(() => {}));
const pause = jest.fn();

Object.defineProperties(audio, {
play: { value: play },
pause: { value: pause },
});

ref.current = audio;
controls.play();

rerender();
result.current[2].pause();

expect(play).toHaveBeenCalledTimes(1);
expect(pause).not.toHaveBeenCalled();
});