Skip to content

Commit

Permalink
chore: Use ownerDocument.defaultView for isMotionDisabled (#102)
Browse files Browse the repository at this point in the history
  • Loading branch information
abdhalees authored Oct 24, 2024
1 parent 8ef08a7 commit 9c4a87e
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 1 deletion.
17 changes: 17 additions & 0 deletions src/internal/visual-mode/__tests__/motion.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -69,4 +69,21 @@ describe('isMotionDisabled', () => {
const element = renderResult.container.querySelector('#test-element') as HTMLElement;
expect(isMotionDisabled(element)).toEqual(true);
});

test('should default to false when an error is thrown and a warning is logged', () => {
matchMedia.mockReturnValue(null);

const warnSpy = jest.spyOn(console, 'warn');

const renderResult = render(
<div>
<div id="test-element">Content</div>
</div>
);
const element = renderResult.container.querySelector('#test-element') as HTMLElement;

expect(isMotionDisabled(element)).toEqual(false);

expect(warnSpy).toHaveBeenCalled();
});
});
12 changes: 11 additions & 1 deletion src/internal/visual-mode/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,20 @@ import { isDevelopment } from '../is-development';
import { warnOnce } from '../logging';
import { awsuiVisualRefreshFlag, getGlobal } from '../global-flags';

function safeMatchMedia(element: HTMLElement, query: string) {
try {
const targetWindow = element.ownerDocument?.defaultView ?? window;
return targetWindow.matchMedia?.(query).matches ?? false;
} catch (error) {
console.warn(error);
return false;
}
}

export function isMotionDisabled(element: HTMLElement): boolean {
return (
!!findUpUntil(element, node => node.classList.contains('awsui-motion-disabled')) ||
(window.matchMedia?.('(prefers-reduced-motion: reduce)').matches ?? false)
safeMatchMedia(element, '(prefers-reduced-motion: reduce)')
);
}

Expand Down

0 comments on commit 9c4a87e

Please sign in to comment.