diff --git a/packages/taro-h5/__tests__/media/audio-listeners.test.ts b/packages/taro-h5/__tests__/media/audio-listeners.test.ts new file mode 100644 index 000000000000..f6d9de94aef9 --- /dev/null +++ b/packages/taro-h5/__tests__/media/audio-listeners.test.ts @@ -0,0 +1,166 @@ +import Taro from '@tarojs/api' + +import { createInnerAudioContext } from '../../src/api/media/audio' +import { InnerAudioContext } from '../../src/api/media/audio/InnerAudioContext' + +const events = [ + ['Canplay', 'canplay'], + ['Play', 'play'], + ['Pause', 'pause'], + ['Stop', 'stop'], + ['Ended', 'ended'], + ['TimeUpdate', 'timeupdate'], + ['Error', 'error'], + ['Waiting', 'waiting'], + ['Seeking', 'seeking'], + ['Seeked', 'seeked'] +] as const + +describe('InnerAudioContext listener removal', () => { + let contexts: InnerAudioContext[] + + beforeEach(() => { + contexts = [] + jest.spyOn(HTMLMediaElement.prototype, 'pause').mockImplementation(() => {}) + }) + + afterEach(() => { + contexts.forEach(context => context.destroy()) + jest.restoreAllMocks() + }) + + function create () { + const context = createInnerAudioContext() as InnerAudioContext + contexts.push(context) + return context + } + + function emit (context: InnerAudioContext, event: string) { + if (event === 'stop') context.stop() + else context.Instance!.dispatchEvent(new Event(event)) + } + + describe.each(events)('off%s', (suffix, event) => { + test('without a callback removes all user listeners and allows subscribing again', () => { + const context = create() + const first = jest.fn() + const second = jest.fn() + context[`on${suffix}`](first) + context[`on${suffix}`](second) + context[`off${suffix}`]() + emit(context, event) + expect(first).not.toHaveBeenCalled() + expect(second).not.toHaveBeenCalled() + + context[`on${suffix}`](second) + emit(context, event) + expect(first).not.toHaveBeenCalled() + expect(second).toHaveBeenCalledTimes(1) + }) + + test('explicit undefined and repeated removal also clear all listeners', () => { + const context = create() + const listener = jest.fn() + context[`off${suffix}`]() + context[`on${suffix}`](listener) + context[`off${suffix}`](undefined) + context[`off${suffix}`]() + emit(context, event) + expect(listener).not.toHaveBeenCalled() + }) + + test('a callback removes only that listener and an unknown callback removes none', () => { + const context = create() + const first = jest.fn() + const second = jest.fn() + context[`on${suffix}`](first) + context[`on${suffix}`](second) + context[`off${suffix}`](jest.fn()) + emit(context, event) + expect(first).toHaveBeenCalledTimes(1) + expect(second).toHaveBeenCalledTimes(1) + context[`off${suffix}`](first) + emit(context, event) + expect(first).toHaveBeenCalledTimes(1) + expect(second).toHaveBeenCalledTimes(2) + }) + }) + + test('offPlay preserves the internal first-play startTime handling', () => { + const context = create() + context.startTime = 12 + const listener = jest.fn() + context.onPlay(listener) + context.offPlay() + emit(context, 'play') + expect(listener).not.toHaveBeenCalled() + expect(context.currentTime).toBe(12) + context.seek(3) + emit(context, 'play') + expect(context.currentTime).toBe(3) + }) + + test('removal is isolated by event and audio context', () => { + const first = create() + const second = create() + const play = jest.fn() + const pause = jest.fn() + const otherPlay = jest.fn() + first.onPlay(play) + first.onPause(pause) + second.onPlay(otherPlay) + first.offPlay() + emit(first, 'play') + emit(first, 'pause') + emit(second, 'play') + expect(play).not.toHaveBeenCalled() + expect(pause).toHaveBeenCalledTimes(1) + expect(otherPlay).toHaveBeenCalledTimes(1) + }) + + test('DOM callbacks retain their event, this and native duplicate-registration behavior', () => { + const context = create() + const audio = context.Instance! + const listener = jest.fn(function (this: HTMLAudioElement, event: Event) { + expect(this).toBe(audio) + expect(event.target).toBe(audio) + }) + context.onPlay(listener) + context.onPlay(listener) + emit(context, 'play') + expect(listener).toHaveBeenCalledTimes(1) + context.offPlay(listener) + emit(context, 'play') + expect(listener).toHaveBeenCalledTimes(1) + }) + + test('offPlay during dispatch keeps native removal semantics for later listeners', () => { + const context = create() + const second = jest.fn() + context.onPlay(() => context.offPlay()) + context.onPlay(second) + emit(context, 'play') + expect(second).not.toHaveBeenCalled() + }) + + test('destroy detaches listeners from the retained audio element and remains idempotent', () => { + const context = create() + const audio = context.Instance! + const play = jest.fn() + const error = jest.fn() + context.onPlay(play) + context.onError(error) + context.destroy() + audio.dispatchEvent(new Event('play')) + audio.dispatchEvent(new Event('error')) + Taro.eventCenter.trigger('__taroRouterChange') + expect(play).not.toHaveBeenCalled() + expect(error).not.toHaveBeenCalled() + expect(context.errorStack.count()).toBe(0) + expect(context.stopStack.count()).toBe(0) + expect(() => context.destroy()).not.toThrow() + for (const [suffix] of events) { + expect(() => context[`off${suffix}`]()).not.toThrow() + } + }) +}) diff --git a/packages/taro-h5/__tests__/media/audio.test.ts b/packages/taro-h5/__tests__/media/audio.test.ts index 1d9a37c3cc52..15b29c111239 100644 --- a/packages/taro-h5/__tests__/media/audio.test.ts +++ b/packages/taro-h5/__tests__/media/audio.test.ts @@ -8,6 +8,7 @@ describe('InnerAudioContext', () => { test('removes the router listener and callbacks when destroyed', () => { const audio = { addEventListener: jest.fn(), + removeEventListener: jest.fn(), pause: jest.fn(), removeAttribute: jest.fn(), currentTime: 0, diff --git a/packages/taro-h5/src/api/media/audio/InnerAudioContext.ts b/packages/taro-h5/src/api/media/audio/InnerAudioContext.ts index c7a41d497245..9002faa0020d 100644 --- a/packages/taro-h5/src/api/media/audio/InnerAudioContext.ts +++ b/packages/taro-h5/src/api/media/audio/InnerAudioContext.ts @@ -9,7 +9,14 @@ export class InnerAudioContext implements Taro.InnerAudioContext { stopStack: CallbackManager __startTime = 0 __isFirstPlay = true + private readonly listeners = new Map>() private readonly onRouterChange = () => this.stop() + private readonly onFirstPlay = () => { + if (this.__isFirstPlay) { + this.__isFirstPlay = false + this.seek(this.startTime) + } + } constructor () { this.Instance = new Audio() @@ -18,12 +25,8 @@ export class InnerAudioContext implements Taro.InnerAudioContext { this.Instance.onerror = this.errorStack.trigger Taro.eventCenter.on('__taroRouterChange', this.onRouterChange) - this.onPlay(() => { - if (this.__isFirstPlay) { - this.__isFirstPlay = false - this.seek(this.startTime) - } - }) + // Keep internal playback handling separate from removable user listeners. + this.Instance.addEventListener('play', this.onFirstPlay) } set autoplay (e) { this.setProperty('autoplay', e) } @@ -65,6 +68,29 @@ export class InnerAudioContext implements Taro.InnerAudioContext { } } + private addListener (type: string, callback: EventListener) { + if (!this.Instance) return + let callbacks = this.listeners.get(type) + if (!callbacks) { + callbacks = new Set() + this.listeners.set(type, callbacks) + } + callbacks.add(callback) + this.Instance.addEventListener(type, callback) + } + + private removeListener (type: string, callback?: EventListener) { + const callbacks = this.listeners.get(type) + if (callback) { + this.Instance?.removeEventListener(type, callback) + callbacks?.delete(callback) + } else { + callbacks?.forEach(listener => this.Instance?.removeEventListener(type, listener)) + callbacks?.clear() + } + if (!callbacks?.size) this.listeners.delete(type) + } + play = () => this.Instance?.play() pause = () => this.Instance?.pause() @@ -86,6 +112,8 @@ export class InnerAudioContext implements Taro.InnerAudioContext { this.stop() Taro.eventCenter.off('__taroRouterChange', this.onRouterChange) + this.listeners.forEach((_, type) => this.removeListener(type)) + this.Instance.removeEventListener('play', this.onFirstPlay) this.Instance.onerror = null this.Instance.removeAttribute('src') this.errorStack.clear() @@ -93,24 +121,24 @@ export class InnerAudioContext implements Taro.InnerAudioContext { this.Instance = undefined } - onCanplay = (callback: Taro.InnerAudioContext.OnCanplayCallback = () => {}) => this.Instance?.addEventListener('canplay', callback as any) - onPlay = (callback: Taro.InnerAudioContext.OnPlayCallback = () => {}) => this.Instance?.addEventListener('play', callback as any) - onPause = (callback: Taro.InnerAudioContext.OnPauseCallback = () => {}) => this.Instance?.addEventListener('pause', callback as any) + onCanplay = (callback: Taro.InnerAudioContext.OnCanplayCallback = () => {}) => this.addListener('canplay', callback as any) + onPlay = (callback: Taro.InnerAudioContext.OnPlayCallback = () => {}) => this.addListener('play', callback as any) + onPause = (callback: Taro.InnerAudioContext.OnPauseCallback = () => {}) => this.addListener('pause', callback as any) onStop = (callback: Taro.InnerAudioContext.OnStopCallback = () => {}) => this.stopStack.add(callback) - onEnded = (callback: Taro.InnerAudioContext.OnEndedCallback = () => {}) => this.Instance?.addEventListener('ended', callback as any) - onTimeUpdate = (callback: Taro.InnerAudioContext.OnTimeUpdateCallback = () => {}) => this.Instance?.addEventListener('timeupdate', callback as any) + onEnded = (callback: Taro.InnerAudioContext.OnEndedCallback = () => {}) => this.addListener('ended', callback as any) + onTimeUpdate = (callback: Taro.InnerAudioContext.OnTimeUpdateCallback = () => {}) => this.addListener('timeupdate', callback as any) onError = (callback: Taro.InnerAudioContext.OnErrorCallback) => this.errorStack.add(callback) - onWaiting = (callback: Taro.InnerAudioContext.OnWaitingCallback = () => {}) => this.Instance?.addEventListener('waiting', callback as any) - onSeeking = (callback: Taro.InnerAudioContext.OnSeekingCallback = () => {}) => this.Instance?.addEventListener('seeking', callback as any) - onSeeked = (callback: Taro.InnerAudioContext.OnSeekedCallback = () => {}) => this.Instance?.addEventListener('seeked', callback as any) - offCanplay = (callback: Taro.InnerAudioContext.OnCanplayCallback = () => {}) => this.Instance?.removeEventListener('canplay', callback as any) - offPlay = (callback: Taro.InnerAudioContext.OnPlayCallback = () => {}) => this.Instance?.removeEventListener('play', callback as any) - offPause = (callback: Taro.InnerAudioContext.OnPauseCallback = () => {}) => this.Instance?.removeEventListener('pause', callback as any) - offStop = (callback: Taro.InnerAudioContext.OnStopCallback = () => {}) => this.stopStack.remove(callback) - offEnded = (callback: Taro.InnerAudioContext.OnEndedCallback = () => {}) => this.Instance?.removeEventListener('ended', callback as any) - offTimeUpdate = (callback: Taro.InnerAudioContext.OnTimeUpdateCallback = () => {}) => this.Instance?.removeEventListener('timeupdate', callback as any) - offError = (callback: Taro.InnerAudioContext.OnErrorCallback = () => {}) => this.errorStack.remove(callback) - offWaiting = (callback: Taro.InnerAudioContext.OnWaitingCallback = () => {}) => this.Instance?.removeEventListener('waiting', callback as any) - offSeeking = (callback: Taro.InnerAudioContext.OnSeekingCallback = () => {}) => this.Instance?.removeEventListener('seeking', callback as any) - offSeeked = (callback: Taro.InnerAudioContext.OnSeekedCallback = () => {}) => this.Instance?.removeEventListener('seeked', callback as any) + onWaiting = (callback: Taro.InnerAudioContext.OnWaitingCallback = () => {}) => this.addListener('waiting', callback as any) + onSeeking = (callback: Taro.InnerAudioContext.OnSeekingCallback = () => {}) => this.addListener('seeking', callback as any) + onSeeked = (callback: Taro.InnerAudioContext.OnSeekedCallback = () => {}) => this.addListener('seeked', callback as any) + offCanplay = (callback?: Taro.InnerAudioContext.OnCanplayCallback) => this.removeListener('canplay', callback as any) + offPlay = (callback?: Taro.InnerAudioContext.OnPlayCallback) => this.removeListener('play', callback as any) + offPause = (callback?: Taro.InnerAudioContext.OnPauseCallback) => this.removeListener('pause', callback as any) + offStop = (callback?: Taro.InnerAudioContext.OnStopCallback) => this.stopStack.remove(callback) + offEnded = (callback?: Taro.InnerAudioContext.OnEndedCallback) => this.removeListener('ended', callback as any) + offTimeUpdate = (callback?: Taro.InnerAudioContext.OnTimeUpdateCallback) => this.removeListener('timeupdate', callback as any) + offError = (callback?: Taro.InnerAudioContext.OnErrorCallback) => this.errorStack.remove(callback) + offWaiting = (callback?: Taro.InnerAudioContext.OnWaitingCallback) => this.removeListener('waiting', callback as any) + offSeeking = (callback?: Taro.InnerAudioContext.OnSeekingCallback) => this.removeListener('seeking', callback as any) + offSeeked = (callback?: Taro.InnerAudioContext.OnSeekedCallback) => this.removeListener('seeked', callback as any) }