Skip to content

Commit

Permalink
Add backwards support for MediaQueryList.addEventListener in older br…
Browse files Browse the repository at this point in the history
…owsers
  • Loading branch information
Nicolas Gasco committed Nov 9, 2023
1 parent 0ffd080 commit 480033f
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 8 deletions.
26 changes: 18 additions & 8 deletions ember-lottie/src/components/lottie.ts
Original file line number Diff line number Diff line change
Expand Up @@ -113,10 +113,15 @@ export default class LottieComponent extends Component<LottieSignature> {
const speed = Ember.testing ? 0 : this.args.speed || 1;
this.animation.setSpeed(speed);

this.mediaQuery?.addEventListener(
'change',
this.handleReducedMotionPreferenceChange,
);
if (this.mediaQuery?.addEventListener) {
this.mediaQuery?.addEventListener(
'change',
this.handleReducedMotionPreferenceChange
);
} else {
// For backwards compatibility with older browsers, e.g. Safari 13
this.mediaQuery?.addListener(this.handleReducedMotionPreferenceChange);
}
}

@action
Expand All @@ -130,10 +135,15 @@ export default class LottieComponent extends Component<LottieSignature> {
willDestroy(): void {
super.willDestroy();

this.mediaQuery?.removeEventListener(
'change',
this.handleReducedMotionPreferenceChange,
);
if (this.mediaQuery?.removeEventListener) {
this.mediaQuery?.removeEventListener(
'change',
this.handleReducedMotionPreferenceChange
);
} else {
// For backwards compatibility with older browsers, e.g. Safari 13
this.mediaQuery?.removeListener(this.handleReducedMotionPreferenceChange);
}

if (this.animation) {
this.animation.destroy();
Expand Down
26 changes: 26 additions & 0 deletions test-app/tests/integration/components/lottie-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,32 @@ module('Integration | Component | lottie', function (hooks) {
assert.dom('[data-test-autoplay=false]').exists();
});

test('it defaults to addListener and removeListener when addEventListener and removeEventListener is not available', async function (this: TestContext, assert) {
const addListener = sinon.spy();
const removeListener = sinon.spy();
window.matchMedia = (): MediaQueryList => {
return {
addListener,
removeListener,
addEventListener: undefined,
removeEventListener: undefined,
matches: true,
} as unknown as MediaQueryList;
};

await render<TestContext>(hbs`
<Lottie
@path="/data.json"
/>
`);

find('svg');
assert.true(addListener.calledOnce);

await clearRender();
assert.true(removeListener.calledOnce);
});

test('it does not autoplay the animation when autoplay is false', async function (this: TestContext, assert) {
window.matchMedia = (): MediaQueryList => {
return {
Expand Down

0 comments on commit 480033f

Please sign in to comment.