Skip to content

Commit 9c4a87e

Browse files
authored
chore: Use ownerDocument.defaultView for isMotionDisabled (#102)
1 parent 8ef08a7 commit 9c4a87e

File tree

2 files changed

+28
-1
lines changed

2 files changed

+28
-1
lines changed

src/internal/visual-mode/__tests__/motion.test.tsx

+17
Original file line numberDiff line numberDiff line change
@@ -69,4 +69,21 @@ describe('isMotionDisabled', () => {
6969
const element = renderResult.container.querySelector('#test-element') as HTMLElement;
7070
expect(isMotionDisabled(element)).toEqual(true);
7171
});
72+
73+
test('should default to false when an error is thrown and a warning is logged', () => {
74+
matchMedia.mockReturnValue(null);
75+
76+
const warnSpy = jest.spyOn(console, 'warn');
77+
78+
const renderResult = render(
79+
<div>
80+
<div id="test-element">Content</div>
81+
</div>
82+
);
83+
const element = renderResult.container.querySelector('#test-element') as HTMLElement;
84+
85+
expect(isMotionDisabled(element)).toEqual(false);
86+
87+
expect(warnSpy).toHaveBeenCalled();
88+
});
7289
});

src/internal/visual-mode/index.ts

+11-1
Original file line numberDiff line numberDiff line change
@@ -9,10 +9,20 @@ import { isDevelopment } from '../is-development';
99
import { warnOnce } from '../logging';
1010
import { awsuiVisualRefreshFlag, getGlobal } from '../global-flags';
1111

12+
function safeMatchMedia(element: HTMLElement, query: string) {
13+
try {
14+
const targetWindow = element.ownerDocument?.defaultView ?? window;
15+
return targetWindow.matchMedia?.(query).matches ?? false;
16+
} catch (error) {
17+
console.warn(error);
18+
return false;
19+
}
20+
}
21+
1222
export function isMotionDisabled(element: HTMLElement): boolean {
1323
return (
1424
!!findUpUntil(element, node => node.classList.contains('awsui-motion-disabled')) ||
15-
(window.matchMedia?.('(prefers-reduced-motion: reduce)').matches ?? false)
25+
safeMatchMedia(element, '(prefers-reduced-motion: reduce)')
1626
);
1727
}
1828

0 commit comments

Comments
 (0)