Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 13 additions & 2 deletions src/useOrientation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@ const useOrientation = (initialState: OrientationState = defaultState) => {

useEffect(() => {
const screen = window.screen;
const orientation = screen.orientation as
| (ScreenOrientation & EventTarget)
| undefined;
let mounted = true;

const onChange = () => {
Expand All @@ -36,12 +39,20 @@ const useOrientation = (initialState: OrientationState = defaultState) => {
}
};

on(window, 'orientationchange', onChange);
if (orientation?.addEventListener) {
on(orientation, 'change', onChange);
} else {
on(window, 'orientationchange', onChange);
}
onChange();

return () => {
mounted = false;
off(window, 'orientationchange', onChange);
if (orientation?.removeEventListener) {
off(orientation, 'change', onChange);
} else {
off(window, 'orientationchange', onChange);
}
};
}, []);

Expand Down
28 changes: 24 additions & 4 deletions tests/useOrientation.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,10 @@ describe('useOrientation', () => {
});

beforeEach(() => {
(window.screen.orientation as object) = {
(window.screen.orientation as unknown) = Object.assign(new EventTarget(), {
type: 'landscape-primary',
angle: 0,
};
});
(window.orientation as number) = 0;
});

Expand All @@ -32,10 +32,16 @@ describe('useOrientation', () => {
return renderHook(() => useOrientation(...args));
}

function triggerOrientation(type: string, angle: number) {
function triggerScreenOrientation(type: string, angle: number) {
(window.screen.orientation.type as string) = type;
(window.screen.orientation.angle as number) = angle;

(window.screen.orientation as EventTarget).dispatchEvent(new Event('change'));
}

function triggerWindowOrientation(angle: number) {
(window.orientation as number) = angle;

window.dispatchEvent(new Event('orientationchange'));
}

Expand All @@ -55,10 +61,24 @@ describe('useOrientation', () => {
});

it('should re-render after orientation change on closest RAF', () => {
(window.screen.orientation as unknown) = undefined;

const hook = getHook();

act(() => {
triggerWindowOrientation(180);
requestAnimationFrame.step();
});

expect(hook.result.current.type).toBe('');
expect(hook.result.current.angle).toBe(180);
});

it('should re-render after screen.orientation change', () => {
const hook = getHook();

act(() => {
triggerOrientation('portrait-secondary', 180);
triggerScreenOrientation('portrait-secondary', 180);
requestAnimationFrame.step();
});

Expand Down