- bin ipal-tokens: src/design/tokens.ts → src/design/tokens.css, --check, WCAG contrast report (fails on AA errors; --report, --warn-only) - CookieBanner / CookieButton read the single --ipal-* roles; the fallback follows color-scheme via light-dark() and still honours the legacy -dark variables - lightbox fade reads --ipal-duration / --ipal-ease-out - DESIGN.md and tokens.ts templates in ipal-setup/resources Co-Authored-By: Claude Opus 5.5 <[email protected]>
303 lines
12 KiB
TypeScript
303 lines
12 KiB
TypeScript
'use client'
|
|
|
|
import type { CSSProperties, ReactNode } from 'react'
|
|
|
|
import { ChevronLeft, ChevronRight, X } from 'lucide-react'
|
|
import { useEffect, useRef, useState } from 'react'
|
|
import { createPortal } from 'react-dom'
|
|
|
|
import type { LightboxClassNames, LightboxImage, LightboxRenderImage, LightboxTexts } from './types.js'
|
|
|
|
import { formatLightboxCounter, lightboxIndex, resolveLightboxTexts } from './texts.js'
|
|
|
|
export type LightboxDialogProps = {
|
|
classNames?: LightboxClassNames
|
|
/** Replace the default icons (lucide X / ChevronLeft / ChevronRight). */
|
|
icons?: { close?: ReactNode; next?: ReactNode; previous?: ReactNode }
|
|
images: readonly LightboxImage[]
|
|
/** Position in `images`. */
|
|
index: number
|
|
/** Wrap around at the ends. Default true. */
|
|
loop?: boolean
|
|
onClose: () => void
|
|
onIndexChange: (index: number) => void
|
|
/** Use next/image, a <picture> or anything else for the large image. Default: <img srcSet>. */
|
|
renderImage?: LightboxRenderImage
|
|
/** Gets focus back on close — usually the trigger. Default: whatever had focus on open. */
|
|
returnFocus?: HTMLElement | null
|
|
/** Swipe distance (px) that changes the image. Default 40. */
|
|
swipeThreshold?: number
|
|
texts?: null | Partial<Record<keyof LightboxTexts, null | string>>
|
|
/** No inline styles — style everything with classNames and [data-ipal^="lightbox"]. */
|
|
unstyled?: boolean
|
|
}
|
|
|
|
const FOCUSABLE = 'a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])'
|
|
|
|
/** OS "reduce motion", or the plugin's AccessibilityWidget switch on <html>. */
|
|
export function prefersReducedMotion(): boolean {
|
|
if (typeof window === 'undefined') {return false}
|
|
if (document.documentElement.getAttribute('data-a11y-motion') === 'reduce') {return true}
|
|
return typeof window.matchMedia === 'function' && window.matchMedia('(prefers-reduced-motion: reduce)').matches
|
|
}
|
|
|
|
const v = (name: string, fallback: string) => `var(--ipal-lightbox-${name}, ${fallback})`
|
|
|
|
const STYLES = {
|
|
button: {
|
|
alignItems: 'center',
|
|
background: v('control-bg', 'rgb(255 255 255 / 0.14)'),
|
|
border: 0,
|
|
borderRadius: v('control-radius', '999px'),
|
|
color: v('control-color', 'inherit'),
|
|
cursor: 'pointer',
|
|
display: 'inline-flex',
|
|
height: v('control-size', '2.75rem'),
|
|
justifyContent: 'center',
|
|
padding: 0,
|
|
position: 'absolute',
|
|
width: v('control-size', '2.75rem'),
|
|
},
|
|
caption: { color: v('caption-color', 'inherit'), fontSize: v('caption-size', '0.95rem'), margin: '0.75rem auto 0', maxWidth: '60ch', textAlign: 'center' },
|
|
close: { right: v('inset', '1rem'), top: v('inset', '1rem') },
|
|
counter: { fontSize: '0.875rem', left: v('inset', '1rem'), margin: 0, position: 'absolute', top: v('inset', '1rem') },
|
|
dialog: {
|
|
alignItems: 'center',
|
|
background: v('backdrop', 'rgb(0 0 0 / 0.9)'),
|
|
color: v('color', '#fff'),
|
|
display: 'flex',
|
|
inset: 0,
|
|
justifyContent: 'center',
|
|
padding: v('padding', '4rem 1rem'),
|
|
position: 'fixed',
|
|
zIndex: v('z-index', '1000') as unknown as number,
|
|
},
|
|
figure: { margin: 0, maxHeight: '100%', maxWidth: '100%', position: 'relative', touchAction: 'pan-y pinch-zoom' },
|
|
image: {
|
|
display: 'block',
|
|
height: 'auto',
|
|
margin: '0 auto',
|
|
maxHeight: v('image-max-height', 'calc(100dvh - 9rem)'),
|
|
maxWidth: '100%',
|
|
objectFit: 'contain',
|
|
width: 'auto',
|
|
},
|
|
next: { right: v('inset', '1rem'), top: '50%', transform: 'translateY(-50%)' },
|
|
previous: { left: v('inset', '1rem'), top: '50%', transform: 'translateY(-50%)' },
|
|
} satisfies Record<string, CSSProperties>
|
|
|
|
const cx = (...parts: (string | undefined)[]) => parts.filter(Boolean).join(' ') || undefined
|
|
|
|
/**
|
|
* The viewer itself, controlled: full-screen dialog over the page (portal to
|
|
* <body>), arrows, swipe, counter, caption. Accessible: role="dialog" +
|
|
* aria-modal, focus moves to Close and stays inside (Tab cycles), Esc closes,
|
|
* ←/→/Home/End browse, focus returns to the trigger on close, the page does not
|
|
* scroll behind it, no animation when the visitor asked for reduced motion.
|
|
*
|
|
* Usually rendered by <LightboxProvider>; use it directly for full control.
|
|
*/
|
|
export function LightboxDialog({
|
|
classNames: cn = {},
|
|
icons = {},
|
|
images,
|
|
index,
|
|
loop = true,
|
|
onClose,
|
|
onIndexChange,
|
|
renderImage,
|
|
returnFocus,
|
|
swipeThreshold = 40,
|
|
texts,
|
|
unstyled = false,
|
|
}: LightboxDialogProps) {
|
|
const t = resolveLightboxTexts(texts)
|
|
const ref = useRef<HTMLDivElement>(null)
|
|
const closeRef = useRef<HTMLButtonElement>(null)
|
|
const swipe = useRef<{ x: number; y: number } | null>(null)
|
|
const [visible, setVisible] = useState(false)
|
|
const total = images.length
|
|
const current = Math.min(Math.max(index, 0), Math.max(total - 1, 0))
|
|
const image = images[current]
|
|
|
|
// Latest handlers for the document listener, without re-subscribing per render.
|
|
const live = useRef({ current, loop, onClose, onIndexChange, total })
|
|
live.current = { current, loop, onClose, onIndexChange, total }
|
|
|
|
// Focus in, scroll lock, focus back — once per open.
|
|
useEffect(() => {
|
|
const previous = returnFocus ?? (document.activeElement as HTMLElement | null)
|
|
const root = document.documentElement
|
|
const saved = { overflow: root.style.overflow, paddingRight: root.style.paddingRight }
|
|
const gap = window.innerWidth - root.clientWidth
|
|
root.style.overflow = 'hidden'
|
|
if (gap > 0) {root.style.paddingRight = `${gap}px`}
|
|
closeRef.current?.focus()
|
|
const frame = typeof requestAnimationFrame === 'function' ? requestAnimationFrame(() => setVisible(true)) : undefined
|
|
return () => {
|
|
if (frame !== undefined) {cancelAnimationFrame(frame)}
|
|
root.style.overflow = saved.overflow
|
|
root.style.paddingRight = saved.paddingRight
|
|
if (previous && previous.isConnected) {previous.focus()}
|
|
}
|
|
}, [returnFocus])
|
|
|
|
useEffect(() => {
|
|
const onKey = (e: KeyboardEvent) => {
|
|
const s = live.current
|
|
const go = (to: number) => {
|
|
e.preventDefault()
|
|
if (to !== s.current) {s.onIndexChange(to)}
|
|
}
|
|
if (e.key === 'Escape') {
|
|
e.preventDefault()
|
|
s.onClose()
|
|
} else if (e.key === 'ArrowRight' && s.total > 1) {go(lightboxIndex(s.current, 1, s.total, s.loop))}
|
|
else if (e.key === 'ArrowLeft' && s.total > 1) {go(lightboxIndex(s.current, -1, s.total, s.loop))}
|
|
else if (e.key === 'Home' && s.total > 1) {go(0)}
|
|
else if (e.key === 'End' && s.total > 1) {go(s.total - 1)}
|
|
else if (e.key === 'Tab' && ref.current) {
|
|
const items = [...ref.current.querySelectorAll<HTMLElement>(FOCUSABLE)]
|
|
if (items.length === 0) {return}
|
|
const first = items[0]
|
|
const last = items[items.length - 1]
|
|
const active = document.activeElement
|
|
if (e.shiftKey && (active === first || !ref.current.contains(active))) {
|
|
e.preventDefault()
|
|
last.focus()
|
|
} else if (!e.shiftKey && (active === last || !ref.current.contains(active))) {
|
|
e.preventDefault()
|
|
first.focus()
|
|
}
|
|
}
|
|
}
|
|
document.addEventListener('keydown', onKey)
|
|
return () => document.removeEventListener('keydown', onKey)
|
|
}, [])
|
|
|
|
// Warm the neighbours so the next arrow press shows the image at once.
|
|
useEffect(() => {
|
|
if (total < 2 || typeof window.Image !== 'function') {return}
|
|
for (const i of new Set([lightboxIndex(current, -1, total, loop), lightboxIndex(current, 1, total, loop)])) {
|
|
const n = images[i]
|
|
if (!n || i === current) {continue}
|
|
const img = new window.Image()
|
|
if (n.srcSet) {
|
|
img.sizes = n.sizes ?? '100vw'
|
|
img.srcset = n.srcSet
|
|
}
|
|
img.src = n.src
|
|
}
|
|
}, [current, images, loop, total])
|
|
|
|
if (!image || typeof document === 'undefined') {return null}
|
|
|
|
const style = (key: keyof typeof STYLES, extra?: CSSProperties): CSSProperties | undefined =>
|
|
unstyled ? undefined : { ...(key === 'close' || key === 'next' || key === 'previous' ? STYLES.button : {}), ...STYLES[key], ...extra }
|
|
const motion = prefersReducedMotion()
|
|
const dialogStyle = style('dialog', motion ? undefined : { opacity: visible ? 1 : 0, transition: `opacity ${v('duration', 'var(--ipal-duration, 200ms)')} ${v('easing', 'var(--ipal-ease-out, ease)')}` })
|
|
const canPrev = loop || current > 0
|
|
const canNext = loop || current < total - 1
|
|
const step = (delta: number) => onIndexChange(lightboxIndex(current, delta, total, loop))
|
|
const imgProps = {
|
|
alt: image.alt,
|
|
className: cn.image,
|
|
...(image.width ? { width: image.width } : {}),
|
|
...(image.height ? { height: image.height } : {}),
|
|
...(image.srcSet ? { sizes: image.sizes ?? '100vw', srcSet: image.srcSet } : {}),
|
|
src: image.src,
|
|
...(unstyled ? {} : { style: STYLES.image as Record<string, string> }),
|
|
}
|
|
const captionId = image.caption ? 'ipal-lightbox-caption' : undefined
|
|
|
|
return createPortal(
|
|
<div
|
|
aria-describedby={captionId}
|
|
aria-label={t.dialog}
|
|
aria-modal="true"
|
|
className={cn.dialog}
|
|
data-ipal="lightbox"
|
|
ref={ref}
|
|
role="dialog"
|
|
style={dialogStyle}
|
|
>
|
|
{/* Click outside the image closes; keyboard users have Esc and the Close button. */}
|
|
<div aria-hidden data-ipal="lightbox-backdrop" onClick={onClose} style={unstyled ? undefined : { inset: 0, position: 'absolute' }} />
|
|
<figure
|
|
className={cn.figure}
|
|
data-ipal="lightbox-figure"
|
|
onPointerCancel={() => {
|
|
swipe.current = null
|
|
}}
|
|
onPointerDown={(e) => {
|
|
swipe.current = { x: e.clientX, y: e.clientY }
|
|
}}
|
|
onPointerUp={(e) => {
|
|
const start = swipe.current
|
|
swipe.current = null
|
|
if (!start || total < 2) {return}
|
|
const dx = e.clientX - start.x
|
|
const dy = e.clientY - start.y
|
|
if (Math.abs(dx) < swipeThreshold || Math.abs(dx) < Math.abs(dy)) {return}
|
|
if (dx < 0 ? canNext : canPrev) {step(dx < 0 ? 1 : -1)}
|
|
}}
|
|
style={style('figure')}
|
|
>
|
|
{renderImage ? (
|
|
renderImage({ image, imgProps, index: current })
|
|
) : (
|
|
<img {...imgProps} alt={imgProps.alt} draggable={false} />
|
|
)}
|
|
{image.caption ? (
|
|
<figcaption className={cn.caption} data-ipal="lightbox-caption" id={captionId} style={style('caption')}>
|
|
{image.caption}
|
|
</figcaption>
|
|
) : null}
|
|
</figure>
|
|
{total > 1 ? (
|
|
<p aria-live="polite" className={cn.counter} data-ipal="lightbox-counter" style={style('counter')}>
|
|
{formatLightboxCounter(t.counter, current + 1, total)}
|
|
</p>
|
|
) : null}
|
|
{total > 1 ? (
|
|
<button
|
|
aria-label={t.previous}
|
|
className={cx(cn.button, cn.previous)}
|
|
data-ipal="lightbox-previous"
|
|
disabled={!canPrev}
|
|
onClick={() => step(-1)}
|
|
style={style('previous')}
|
|
type="button"
|
|
>
|
|
{icons.previous ?? <ChevronLeft aria-hidden size={28} />}
|
|
</button>
|
|
) : null}
|
|
{total > 1 ? (
|
|
<button
|
|
aria-label={t.next}
|
|
className={cx(cn.button, cn.next)}
|
|
data-ipal="lightbox-next"
|
|
disabled={!canNext}
|
|
onClick={() => step(1)}
|
|
style={style('next')}
|
|
type="button"
|
|
>
|
|
{icons.next ?? <ChevronRight aria-hidden size={28} />}
|
|
</button>
|
|
) : null}
|
|
<button
|
|
aria-label={t.close}
|
|
className={cx(cn.button, cn.close)}
|
|
data-ipal="lightbox-close"
|
|
onClick={onClose}
|
|
ref={closeRef}
|
|
style={style('close')}
|
|
type="button"
|
|
>
|
|
{icons.close ?? <X aria-hidden size={24} />}
|
|
</button>
|
|
</div>,
|
|
document.body,
|
|
)
|
|
}
|