Files
AndreaSlopFotografie/web/src/components/Lightbox/Lightbox.tsx
T

375 lines
15 KiB
TypeScript

import {
useEffect,
useRef,
useState,
type KeyboardEvent,
type MouseEvent,
} from 'react';
import { Box, chakra, Dialog, Portal, Text, useRecipe } from '@chakra-ui/react';
import { Icon } from '@iconify/react/offline';
import closeOutlined from '@iconify-icons/ant-design/close-outlined';
import leftOutlined from '@iconify-icons/ant-design/left-outlined';
import rightOutlined from '@iconify-icons/ant-design/right-outlined';
import type { GalleryItem } from '@/content/types';
import useSwipe from '@/hooks/useSwipe';
import { t } from '@/i18n';
import { neighbourIndexes } from '@/lib/neighbourIndexes';
import { wrapIndex } from '@/lib/wrapIndex';
type LightboxProps = {
items: readonly GalleryItem[];
// The photo on screen, or null when closed
index: number | null;
onIndexChange: (index: number) => void;
onClose: () => void;
// Name of the dialog for assistive technology
label?: string;
// Where focus goes on close: the grid tile of the photo shown last
finalFocusEl?: () => HTMLElement | null;
};
// Large photos loaded ahead on each side of the one on screen (FD Q8 = B)
const PRELOAD_RADIUS = 2;
type LoadState = 'loading' | 'loaded' | 'failed';
// Shows one photo of a list large, in a modal dialog (design .lightbox).
// Chakra's Dialog traps focus, closes on Escape, makes the page behind it
// inert and stops it scrolling; this component adds browsing (buttons,
// arrow keys, Home/End, swipe), the counter, the caption and loading.
// Default export, so the page can load it lazily on first use.
export default function Lightbox({
items,
index,
onIndexChange,
onClose,
label = t('common.lightbox.label'),
finalFocusEl,
}: LightboxProps) {
const count = items.length;
const open = index !== null && count > 0;
const current = open ? wrapIndex(index, count) : 0;
const item = items[current];
const browsable = count > 1;
const closeButton = useRef<HTMLButtonElement>(null);
// Said after the visitor browses; not on opening (the dialog name and
// the focused close button are announced then)
const [announcement, setAnnouncement] = useState('');
// Clear the announcement when the dialog closes, so reopening is quiet.
// Adjusted during render, as React advises for state that follows a prop.
const [wasOpen, setWasOpen] = useState(open);
if (wasOpen !== open) {
setWasOpen(open);
if (!open) setAnnouncement('');
}
// Load the photos around this one, so browsing shows them at once
useEffect(() => {
if (!open) return;
for (const i of neighbourIndexes(current, count, PRELOAD_RADIUS)) {
const preload = new Image();
preload.src = items[i].full.src;
}
}, [open, current, count, items]);
const show = (to: number) => {
const next = wrapIndex(to, count);
onIndexChange(next);
const caption = items[next].caption;
const position = next + 1;
setAnnouncement(
caption
? t('common.lightbox.announcementWithCaption', {
position,
count,
caption,
})
: t('common.lightbox.announcement', { position, count }),
);
};
const swipe = useSwipe({
onPrev: () => show(current - 1),
onNext: () => show(current + 1),
enabled: browsable,
});
const handleKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
if (!browsable) return;
const target: Record<string, number> = {
ArrowRight: current + 1,
ArrowLeft: current - 1,
Home: 0,
End: count - 1,
};
if (event.key in target) {
event.preventDefault();
show(target[event.key]);
}
};
// A click on the dark area around the photo closes; on the photo itself
// it does nothing (FD Q3)
const closeOnBackground = (event: MouseEvent<HTMLElement>) => {
if (event.target === event.currentTarget) onClose();
};
return (
<Dialog.Root
unstyled
open={open}
onOpenChange={(details) => {
if (!details.open) onClose();
}}
initialFocusEl={() => closeButton.current}
finalFocusEl={finalFocusEl}
lazyMount
unmountOnExit
>
<Portal>
<Dialog.Backdrop
position="fixed"
inset={0}
zIndex="modal"
bg="rgba(20, 19, 18, 0.94)"
_open={{
animationName: 'fade-in',
animationDuration: 'swap',
}}
_closed={{
animationName: 'fade-out',
animationDuration: 'swap',
}}
_motionReduce={{ animation: 'none' }}
/>
<Dialog.Positioner position="fixed" inset={0} zIndex="modal">
{item && (
<Dialog.Content
data-testid="lightbox"
position="absolute"
inset={0}
display="flex"
alignItems="center"
justifyContent="center"
px={{ base: 3, md: 24 }}
pt={{ base: 16, md: 12 }}
pb={{ base: 24, md: 16 }}
color="white"
outline="none"
onKeyDown={handleKeyDown}
onClick={closeOnBackground}
_open={{
animationName: 'fade-in',
animationDuration: 'swap',
}}
_closed={{
animationName: 'fade-out',
animationDuration: 'swap',
}}
_motionReduce={{ animation: 'none' }}
>
<Dialog.Title srOnly>{label}</Dialog.Title>
{/* Keyed per photo: a new photo starts loading
from scratch */}
<Photo
key={`${current}-${item.full.src}`}
item={item}
swipe={swipe}
onBackground={closeOnBackground}
/>
<Dialog.CloseTrigger asChild>
<ControlButton
ref={closeButton}
aria-label={t('common.actions.close')}
data-testid="lightbox-close"
position="absolute"
top={{ base: 2, md: 4 }}
right={{ base: 2, md: 4 }}
>
<Icon icon={closeOutlined} aria-hidden />
</ControlButton>
</Dialog.CloseTrigger>
{browsable && (
// Phones: one bar at the bottom, within reach of
// the thumb and never over the photo (FD Q2).
// Larger screens: the bar dissolves and each
// control takes its place from the design.
<Box
display={{ base: 'flex', md: 'contents' }}
position="absolute"
insetX={0}
bottom={0}
px={2}
pb="max(0.5rem, env(safe-area-inset-bottom))"
alignItems="center"
justifyContent="space-between"
>
<ControlButton
aria-label={t(
'common.lightbox.previous',
)}
data-testid="lightbox-prev"
onClick={() => show(current - 1)}
position={{ md: 'absolute' }}
left={{ md: 4 }}
top={{ md: '50%' }}
transform={{ md: 'translateY(-50%)' }}
>
<Icon icon={leftOutlined} aria-hidden />
</ControlButton>
<Text
data-testid="lightbox-counter"
fontSize="sm"
letterSpacing="0.06em"
color="whiteAlpha.800"
fontVariantNumeric="tabular-nums"
position={{ md: 'absolute' }}
bottom={{ md: 5 }}
left={{ md: '50%' }}
transform={{ md: 'translateX(-50%)' }}
>
{current + 1} / {count}
</Text>
<ControlButton
aria-label={t('common.lightbox.next')}
data-testid="lightbox-next"
onClick={() => show(current + 1)}
position={{ md: 'absolute' }}
right={{ md: 4 }}
top={{ md: '50%' }}
transform={{ md: 'translateY(-50%)' }}
>
<Icon
icon={rightOutlined}
aria-hidden
/>
</ControlButton>
</Box>
)}
<chakra.p
srOnly
aria-live="polite"
data-testid="lightbox-announcement"
>
{announcement}
</chakra.p>
</Dialog.Content>
)}
</Dialog.Positioner>
</Portal>
</Dialog.Root>
);
}
type PhotoProps = {
item: GalleryItem;
swipe: ReturnType<typeof useSwipe>;
onBackground: (event: MouseEvent<HTMLElement>) => void;
};
// The photo with its caption. Until the large version has loaded, the grid
// version (already in the browser cache) stands in at the same size; if
// the large one fails, the grid version stays and a short note says so.
function Photo({ item, swipe, onBackground }: PhotoProps) {
const [load, setLoad] = useState<LoadState>('loading');
const onLoad = () => setLoad('loaded');
const onError = () => setLoad('failed');
const caption =
load === 'failed' ? t('common.lightbox.loadFailed') : item.caption;
return (
<chakra.figure
m={0}
display="flex"
flexDirection="column"
alignItems="center"
maxW="min(1100px, 100%)"
maxH="100%"
onClick={onBackground}
animationName="fade-in"
animationDuration="swap"
_motionReduce={{ animation: 'none' }}
{...swipe}
>
<Box position="relative" maxH="100%" minH={0}>
<chakra.img
src={item.thumb.src}
alt={load === 'loaded' ? '' : item.thumb.alt}
aria-hidden={load === 'loaded' ? true : undefined}
width={item.full.width}
height={item.full.height}
data-testid="lightbox-thumb"
display="block"
maxW="100%"
maxH={{ base: 'calc(100dvh - 10rem)', md: '80svh' }}
w="auto"
h="auto"
objectFit="contain"
/>
{load !== 'failed' && (
<chakra.img
src={item.full.src}
alt={load === 'loaded' ? item.thumb.alt : ''}
aria-hidden={load === 'loaded' ? undefined : true}
width={item.full.width}
height={item.full.height}
data-testid="lightbox-image"
decoding="async"
onLoad={onLoad}
onError={onError}
position="absolute"
inset={0}
w="100%"
h="100%"
objectFit="contain"
opacity={load === 'loaded' ? 1 : 0}
transitionProperty="opacity"
transitionDuration="swap"
_motionReduce={{ transition: 'none' }}
/>
)}
</Box>
{caption && (
<chakra.figcaption
data-testid="lightbox-caption"
aria-live={load === 'failed' ? 'polite' : undefined}
mt={4}
fontSize="sm"
letterSpacing="0.06em"
textAlign="center"
color="whiteAlpha.800"
>
{caption}
</chakra.figcaption>
)}
</chakra.figure>
);
}
type ControlButtonProps = React.ComponentProps<typeof chakra.button>;
// Buttons over the dark backdrop: the iconControl look (white, half
// transparent, full on hover/focus, white focus ring) with a hairline
// square around it as in the design (.lightbox__btn)
function ControlButton(props: ControlButtonProps) {
const iconControl = useRecipe({ key: 'iconControl' });
return (
<chakra.button
type="button"
css={iconControl()}
w="52px"
h="52px"
borderWidth="1px"
borderColor="whiteAlpha.400"
fontSize="1.1rem"
{...props}
/>
);
}