Skip to content

Commit

Permalink
Merge pull request #917 from prezly/feature/care-5201-allow-to-keep-t…
Browse files Browse the repository at this point in the history
…he-scroll-location

[CARE-5201] Feature - Allow communication between the theme and the parent
  • Loading branch information
kudlajz authored Jun 5, 2024
2 parents 3e02538 + 5813e12 commit fdadcee
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 fdadcee

Please sign in to comment.