constant img height to reduce layout shift

This commit is contained in:
Martti Malmi 2023-08-12 12:57:36 +03:00
parent 1f3dbddb5c
commit 20f03b4437
2 changed files with 54 additions and 2 deletions

View File

@ -16,10 +16,10 @@ const Image: Embed = {
setShowModal(true);
};
return (
<div className="flex justify-center md:justify-start">
<div className="flex justify-center items-center md:justify-start h-96 my-2">
<SafeImg
onClick={onClick}
className="my-2 rounded max-h-[70vh] md:max-h-96 max-w-full cursor-pointer"
className="my-2 rounded md:max-h-96 max-w-full cursor-pointer"
src={match}
/>
<Show when={showModal}>

View File

@ -0,0 +1,52 @@
import { useEffect, useRef, useState } from 'preact/hooks';
const INCREASE_BY = 5;
type Props = { children: any; margin?: string; loadMore?: () => void };
// TODO save scroll position to history state
function InfiniteScroll({ children, margin = '2000px', loadMore }: Props) {
const [visibleCount, setVisibleCount] = useState(INCREASE_BY);
const observerRef = useRef<IntersectionObserver | null>(null);
const sentinelRef = useRef(null);
useEffect(() => {
if (sentinelRef.current && !observerRef.current) {
const options = {
root: null,
rootMargin: margin,
threshold: 0,
};
observerRef.current = new IntersectionObserver((entries) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
setVisibleCount((prev) => prev + INCREASE_BY);
if (loadMore && visibleCount >= children.length) {
loadMore?.();
}
}
});
}, options);
observerRef.current.observe(sentinelRef.current);
}
return () => {
if (observerRef.current) {
observerRef.current.disconnect();
observerRef.current = null;
}
};
}, [visibleCount, margin, loadMore, children.length]);
return (
<>
{children.slice(0, visibleCount)}
{visibleCount < children.length && <div ref={sentinelRef} />}
</>
);
}
export default InfiniteScroll;