Skip to content

Commit

Permalink
Post message to parent when scrolling happens and allow page scrollin…
Browse files Browse the repository at this point in the history
…g via message as well
  • Loading branch information
kudlajz committed Jun 4, 2024
1 parent 3e02538 commit 5813e12
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 0 deletions.
43 changes: 43 additions & 0 deletions components/WindowScrollListener/WindowScrollListener.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { useEffect } from 'react';

type OnScrollMessage = {
type: 'onScroll';
value: number;
};

type ScrollToMessage = {
type: 'scrollTo';
value: number;
};

export function WindowScrollListener() {
useEffect(() => {
function onScroll() {
window.parent.postMessage(
{
type: 'onScroll',
value: window.scrollY,
} satisfies OnScrollMessage,
'*',
);
}

window.addEventListener('scroll', onScroll);

return () => window.removeEventListener('scroll', onScroll);
}, []);

useEffect(() => {
function onMessage(event: MessageEvent<ScrollToMessage>) {
if (event.data.type === 'scrollTo') {
window.scrollTo({ top: event.data.value });
}
}

window.addEventListener('message', onMessage);

return () => window.removeEventListener('message', onMessage);
}, []);

return null;
}
1 change: 1 addition & 0 deletions components/WindowScrollListener/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { WindowScrollListener } from './WindowScrollListener';
2 changes: 2 additions & 0 deletions modules/Layout/Layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import { useEffect, useMemo, useState } from 'react';

import { CategoriesBar, NotificationsBar } from '@/components';
import { PreviewPageMask } from '@/components/PreviewPageMask';
import { WindowScrollListener } from '@/components/WindowScrollListener';
import { LoadingBar, ScrollToTopButton } from '@/ui';

import Boilerplate from './Boilerplate';
Expand Down Expand Up @@ -125,6 +126,7 @@ function Layout({ children, description, imageUrl, title, hasError }: PropsWithC
{/* hide scroll to top on story page */}
{!STORY_PAGE_PATHS.includes(pathname) && <ScrollToTopButton />}
<PreviewPageMask />
<WindowScrollListener />
</>
);
}
Expand Down

0 comments on commit 5813e12

Please sign in to comment.