feat: aspect-ratio instead of width measurer

This commit is contained in:
ner committed 2024-08-31 21:36:16 +03:00
1 parent 375ebf93d9
commit 279a61ddcd
15 files changed
+168 -313

No files matched your search

+65 -68
View File
@@ -1,70 +1,33 @@
'use client';
import { forwardRef, ReactNode, startTransition, useEffect, useLayoutEffect, useRef, useState } from 'react';
import { Virtuoso, VirtuosoHandle, VirtuosoProps } from 'react-virtuoso';
import { forwardRef, useEffect, useLayoutEffect, useRef } from 'react';
import { StateSnapshot, Virtuoso, VirtuosoHandle, VirtuosoProps } from 'react-virtuoso';
import Card from '@/components/Movie/Card';
import { cn } from '@/lib/utils';
const components: VirtuosoProps<Movie, number>['components'] = {
Item: (props) => <div {...props} className='shrink-0' style={{ ...props.style, width: props.context }} />,
List: forwardRef(function List(props, ref) {
return (
<div {...props} ref={ref} className='gap-2' style={{ ...props.style, display: 'flex', width: props.context }} />
);
}),
Scroller: forwardRef(function Scroller(props, ref) {
return <div {...props} ref={ref} className='overflow-hidden no-scrollbar snap-mandatory snap-x rounded-lg' />;
})
};
let snapshot: StateSnapshot;
export const Measurer = ({ children }: { children: (width: number) => ReactNode }) => {
const [ref, setRef] = useState<HTMLDivElement | null>(null);
const width = ref?.offsetWidth;
return (
<>
<div ref={setRef} />
{children(width || 0)}
</>
);
};
export const Carousel = ({
const Carousel = ({
index,
movies,
width: initialWidth,
onIndexChange
}: {
index: number;
movies?: Movie[];
width: number;
onIndexChange: (index: number) => void;
}) => {
const timeout = useRef<NodeJS.Timeout>();
const isMobile = matchMedia('(max-width: 500px)').matches;
const ref = useRef<VirtuosoHandle>(null);
const initialIndex = useRef(index);
const [snap, setSnap] = useState(true);
const width = isMobile ? initialWidth : 300;
const height = isMobile ? (width * 3) / 2 : 450;
useEffect(() => {
const virtuoso = ref.current;
useLayoutEffect(() => {
if (!ref.current) return;
if (!virtuoso) return;
ref.current.scrollIntoView({ index: initialIndex.current });
return () => virtuoso.getState((state) => (snapshot = state));
}, []);
useEffect(() => {
let pressed = false;
const scrollTo = ({ key }: globalThis.KeyboardEvent) => {
if (['ArrowLeft', 'ArrowRight'].includes(key)) {
pressed = true;
setSnap(false);
}
if (key === 'ArrowLeft') {
if (index <= 0) return;
ref.current?.scrollIntoView({ index: index - 1, behavior: 'smooth' });
@@ -80,32 +43,66 @@ export const Carousel = ({
return () => {
document.removeEventListener('keydown', scrollTo);
pressed && setTimeout(() => setSnap(true), 100);
};
}, [index, movies?.length]);
return (
<Virtuoso
ref={ref}
data={movies}
defaultItemHeight={height}
style={{ width, height, flexShrink: 0, margin: '0 auto' }}
totalCount={movies?.length}
horizontalDirection
context={width}
increaseViewportBy={154}
components={components}
itemContent={(index) => {
clearTimeout(timeout.current);
timeout.current = setTimeout(() => {
const currentIndex = index - 1;
startTransition(() => onIndexChange(currentIndex));
}, 50);
return <Card className={cn(snap && 'snap-start')} movie={movies?.[index]} />;
}}
/>
<div className='card-aspect-ratio mx-auto'>
<Virtuoso
ref={ref}
data={movies}
context={onIndexChange}
horizontalDirection
components={components}
skipAnimationFrameInResizeObserver
increaseViewportBy={1000}
restoreStateFrom={snapshot}
/>
</div>
);
};
const components: VirtuosoProps<Movie, (index: number) => void>['components'] = {
Item: ({ item, children, context: onIndexChange, ...props }) => {
const ref = useRef<HTMLDivElement>(null);
const index = props['data-index'];
useLayoutEffect(() => {
const container = ref.current;
if (!container) return;
const observer = new IntersectionObserver(
(entries) =>
entries.forEach((entry) => {
if (!entry.isIntersecting) return;
onIndexChange?.(index);
}),
{
threshold: 0.7
}
);
observer.observe(container);
return () => observer.disconnect();
}, [onIndexChange, index]);
return (
<div {...props} ref={ref} className='snap-start'>
<Card movie={item} />
</div>
);
},
List: forwardRef(function List({ context, ...props }, ref) {
return <div {...props} ref={ref} style={{ ...props.style, display: 'flex' }} className='gap-2' />;
}),
Scroller: forwardRef(function Scroller({ context, ...props }, ref) {
return (
<div {...props} ref={ref} className='overflow-hidden no-scrollbar snap-mandatory snap-x rounded-lg h-full' />
);
})
};
export default Carousel;