From 842240021d7b6746bdc7a6e0318832c42348dfd7 Mon Sep 17 00:00:00 2001 From: Dermot Duffy Date: Sun, 14 Apr 2024 18:37:18 -0700 Subject: [PATCH] Fix media autoplay. --- .../auto-media-actions/auto-media-actions.ts | 18 +++++++++--------- .../auto-media-actions.test.ts | 2 +- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/src/utils/embla/plugins/auto-media-actions/auto-media-actions.ts b/src/utils/embla/plugins/auto-media-actions/auto-media-actions.ts index e31b10db..9086cf62 100644 --- a/src/utils/embla/plugins/auto-media-actions/auto-media-actions.ts +++ b/src/utils/embla/plugins/auto-media-actions/auto-media-actions.ts @@ -50,7 +50,7 @@ export function AutoMediaActions( let options: OptionsType; let emblaApi: EmblaCarouselType; let slides: HTMLElement[]; - let hadInitialIntersectionCall: boolean | null = false; + let containerIntersecting: boolean | null = null; const microphoneMuteTimer = new Timer(); const intersectionObserver: IntersectionObserver = new IntersectionObserver( @@ -184,15 +184,15 @@ export function AutoMediaActions( } function intersectionHandler(entries: IntersectionObserverEntry[]): void { - if (!hadInitialIntersectionCall) { - hadInitialIntersectionCall = true; - return; - } + const wasIntersecting = containerIntersecting; + containerIntersecting = entries.some((entry) => entry.isIntersecting); - // If the live view is preloaded (i.e. in the background) we may need to - // take media actions, e.g. muting a live stream that is now running in the - // background. - actOnVisibilityChange(entries.some((entry) => entry.isIntersecting)); + if (wasIntersecting !== null && wasIntersecting !== containerIntersecting) { + // If the live view is preloaded (i.e. in the background) we may need to + // take media actions, e.g. muting a live stream that is now running in + // the background, so we act even if the new state is hidden. + actOnVisibilityChange(containerIntersecting); + } } function getPlayer(slide: HTMLElement | undefined): FrigateCardMediaPlayer | null { diff --git a/tests/utils/embla/plugins/auto-media-actions/auto-media-actions.test.ts b/tests/utils/embla/plugins/auto-media-actions/auto-media-actions.test.ts index 4cbfea08..91cf31c8 100644 --- a/tests/utils/embla/plugins/auto-media-actions/auto-media-actions.test.ts +++ b/tests/utils/embla/plugins/auto-media-actions/auto-media-actions.test.ts @@ -315,7 +315,7 @@ describe('AutoMediaActions', () => { // Intersection observer always calls handler on creation (and we ignore // these first calls). - callIntersectionHandler(true); + callIntersectionHandler(false); callIntersectionHandler(true); expect(getPlayer(children[5], 'video')?.play).toBeCalled();