Shared image lightbox: LightboxProvider, LightboxTrigger, LightboxDialog, lightboxImage

Opt-in click-to-enlarge for small images (cards, galleries, rich text):
- /client: LightboxProvider (one viewer per site), LightboxTrigger (button
  around any thumbnail, works without a provider), LightboxDialog
  (controlled viewer), useLightbox / useOptionalLightbox
- accessible dialog: aria-modal, focus trap and return, Esc, arrows,
  Home/End, swipe, counter, caption, scroll lock, reduced motion
- lightboxImage builds src + srcSet from Payload image sizes
- labels: ipalKit({ lightbox: true }) adds Notifications -> Lightbox;
  getNotificationTexts().lightbox and getSiteShell().lightboxTexts,
  English fallbacks otherwise
- RenderRichText lightbox / withLightboxUploads wrap image uploads
- SiteProviders lightbox mounts the provider
- styling from --ipal-lightbox-* variables; unstyled + classNames,
  renderImage, renderDialog, icons, loop overrides
- tests with happy-dom (vitest's pinned optional peer)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-10-27 14:49:38 +01:00
co-authored by Claude Opus 5.5
parent e53d09b720
commit 476c3ac1df
23 changed files with 1203 additions and 15 deletions
+302
View File
@@ -0,0 +1,302 @@
'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', '200ms')} 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,
)
}
+247
View File
@@ -0,0 +1,247 @@
'use client'
import type { CSSProperties, ReactNode } from 'react'
import { createContext, use, useCallback, useId, useMemo, useRef, useState } from 'react'
import type { LightboxDialogProps } from './LightboxDialog.js'
import type { LightboxClassNames, LightboxImage, LightboxRenderImage, LightboxTexts } from './types.js'
import { LightboxDialog } from './LightboxDialog.js'
import { lightboxIndex, resolveLightboxTexts } from './texts.js'
type Entry = { el: { current: HTMLElement | null }; group?: string; image: { current: LightboxImage } }
type OpenState = { images: readonly LightboxImage[]; index: number; returnFocus: HTMLElement | null }
export type LightboxApi = {
close: () => void
/** Images of the open gallery ([] when closed). */
images: readonly LightboxImage[]
/** Index in the open gallery, or -1 when closed. */
index: number
isOpen: boolean
next: () => void
/** Open any list of images — for a custom trigger ("View all photos") or a product stage. */
open: (images: readonly LightboxImage[], index?: number, returnFocus?: HTMLElement | null) => void
/** Open the triggers of `group` in page order, starting at an index or at a trigger element. */
openGroup: (group: string, start?: HTMLElement | number, returnFocus?: HTMLElement | null) => void
previous: () => void
/** @internal — LightboxTrigger registers itself here. */
register: (key: string, entry: Entry) => () => void
texts: LightboxTexts
}
const LightboxContext = createContext<LightboxApi | null>(null)
/** The lightbox API, or null outside a <LightboxProvider>. */
export const useOptionalLightbox = () => use(LightboxContext)
/** open / close / next / previous for custom triggers. Needs a <LightboxProvider> above. */
export function useLightbox(): LightboxApi {
const api = use(LightboxContext)
if (!api) {throw new Error('useLightbox: wrap the tree in <LightboxProvider> (from @intecion/ipal-kit/client).')}
return api
}
export type LightboxProviderProps = {
children: ReactNode
classNames?: LightboxClassNames
icons?: LightboxDialogProps['icons']
/** Wrap around at the ends. Default true. */
loop?: boolean
/** Swap the whole viewer (e.g. a project's own dialog) — gets the same props as LightboxDialog. */
renderDialog?: (props: LightboxDialogProps) => ReactNode
/** next/image or a <picture> for the large image. Client-only (a function). */
renderImage?: LightboxRenderImage
/** Pass getNotificationTexts({ payload, locale }).lightbox. Missing texts → English. */
texts?: null | Partial<Record<keyof LightboxTexts, null | string>>
/** No inline styles — style with classNames / [data-ipal^="lightbox"]. Also applies to triggers. */
unstyled?: boolean
}
/** What a trigger needs — stable while the viewer browses, so triggers don't re-render on every step. */
type TriggerApi = { unstyled: boolean } & Pick<LightboxApi, 'open' | 'openGroup' | 'register' | 'texts'>
const TriggerContext = createContext<null | TriggerApi>(null)
/**
* One shared lightbox for a page or the whole site: put it once in the layout
* (or <SiteProviders lightbox>), then wrap thumbnails in <LightboxTrigger>.
* Triggers with the same `group` browse together, in page order. Renders
* nothing until an image is opened.
*/
export function LightboxProvider({ children, classNames, icons, loop = true, renderDialog, renderImage, texts, unstyled = false }: LightboxProviderProps) {
const entries = useRef(new Map<string, Entry>())
const [state, setState] = useState<null | OpenState>(null)
const resolved = useMemo(() => resolveLightboxTexts(texts), [texts])
const open = useCallback((images: readonly LightboxImage[], index = 0, returnFocus: HTMLElement | null = null) => {
if (images.length === 0) {return}
const focus = returnFocus ?? (typeof document === 'undefined' ? null : (document.activeElement as HTMLElement | null))
setState({ images, index: Math.min(Math.max(index, 0), images.length - 1), returnFocus: focus })
}, [])
const groupEntries = useCallback((group: string) => {
const list = [...entries.current.values()].filter((e) => e.group === group && e.el.current)
// Page order, whatever order the triggers mounted in.
return list.sort((a, b) => (a.el.current!.compareDocumentPosition(b.el.current!) & 4 ? -1 : 1))
}, [])
const openGroup = useCallback(
(group: string, start: HTMLElement | number = 0, returnFocus: HTMLElement | null = null) => {
const list = groupEntries(group)
const index = typeof start === 'number' ? start : Math.max(list.findIndex((e) => e.el.current === start), 0)
open(list.map((e) => e.image.current), index, returnFocus)
},
[groupEntries, open],
)
const register = useCallback((key: string, entry: Entry) => {
entries.current.set(key, entry)
return () => {
entries.current.delete(key)
}
}, [])
const close = useCallback(() => setState(null), [])
const move = useCallback(
(delta: number) =>
setState((s) => {
if (!s) {return s}
return { ...s, index: lightboxIndex(s.index, delta, s.images.length, loop) }
}),
[loop],
)
const api = useMemo<LightboxApi>(
() => ({
close,
images: state?.images ?? [],
index: state ? state.index : -1,
isOpen: !!state,
next: () => move(1),
open,
openGroup,
previous: () => move(-1),
register,
texts: resolved,
}),
[close, move, open, openGroup, register, resolved, state],
)
const triggerApi = useMemo<TriggerApi>(() => ({ open, openGroup, register, texts: resolved, unstyled }), [open, openGroup, register, resolved, unstyled])
const dialogProps: LightboxDialogProps | null = state
? {
...(classNames ? { classNames } : {}),
...(icons ? { icons } : {}),
images: state.images,
index: state.index,
loop,
onClose: close,
onIndexChange: (index) => setState((s) => (s ? { ...s, index } : s)),
...(renderImage ? { renderImage } : {}),
returnFocus: state.returnFocus,
texts: resolved,
unstyled,
}
: null
return (
<LightboxContext value={api}>
<TriggerContext value={triggerApi}>
{children}
{dialogProps ? (renderDialog ? renderDialog(dialogProps) : <LightboxDialog {...dialogProps} />) : null}
</TriggerContext>
</LightboxContext>
)
}
export type LightboxTriggerProps = {
/** Accessible name. Default: texts.open + ": " + image alt. */
'aria-label'?: string
/** The thumbnail: next/image, <img>, a <Media> — anything. */
children: ReactNode
className?: string
/** Triggers sharing a group browse together (arrows, swipe). None = this image alone. */
group?: string
/** The large image — lightboxImage(mediaDoc) or your own object. */
image: LightboxImage
style?: CSSProperties
/** Texts when there is no provider above (standalone trigger). */
texts?: null | Partial<Record<keyof LightboxTexts, null | string>>
/** No inline reset styles on the button. Default: the provider's `unstyled`. */
unstyled?: boolean
}
const TRIGGER_STYLE: CSSProperties = {
background: 'none',
border: 0,
color: 'inherit',
cursor: 'zoom-in',
display: 'block',
font: 'inherit',
padding: 0,
position: 'relative',
textAlign: 'inherit',
width: '100%',
}
function Trigger({ api, children, className, group, image, style, unstyled, ...rest }: { api: TriggerApi } & Omit<LightboxTriggerProps, 'texts'>) {
const key = useId()
const el = useRef<HTMLButtonElement | null>(null)
const imageRef = useRef(image)
imageRef.current = image
const registered = useRef<(() => void) | null>(null)
const setRef = useCallback(
(node: HTMLButtonElement | null) => {
el.current = node
registered.current?.()
registered.current = node ? api.register(key, { el, ...(group ? { group } : {}), image: imageRef }) : null
},
[api, group, key],
)
const plain = unstyled ?? api.unstyled
const label = rest['aria-label'] ?? (image.alt ? `${api.texts.open}: ${image.alt}` : api.texts.open)
return (
<button
aria-haspopup="dialog"
aria-label={label}
className={className}
data-group={group}
data-ipal="lightbox-trigger"
onClick={(e) => {
if (group) {api.openGroup(group, e.currentTarget, e.currentTarget)}
else {api.open([imageRef.current], 0, e.currentTarget)}
}}
ref={setRef}
style={plain ? style : { ...TRIGGER_STYLE, ...style }}
type="button"
>
{children}
</button>
)
}
/**
* A button around a thumbnail that opens the large image. Inside a
* <LightboxProvider> it shares the site's viewer (and `group` gallery); alone it
* brings its own, so a single card image needs no setup.
*
* <LightboxTrigger image={lightboxImage(photo, { size: 'hero' })!} group="gallery-1">
* <Image {...mediaImageProps(photo, { sizes: MEDIA_SIZES.third })!} />
* </LightboxTrigger>
*/
export function LightboxTrigger({ texts, ...props }: LightboxTriggerProps) {
const api = use(TriggerContext)
if (!api) {
return (
<LightboxProvider {...(texts ? { texts } : {})}>
<LightboxTrigger {...props} />
</LightboxProvider>
)
}
return <Trigger api={api} {...props} />
}
+5
View File
@@ -0,0 +1,5 @@
'use client'
export { LightboxDialog, prefersReducedMotion } from './LightboxDialog.js'
export type { LightboxDialogProps } from './LightboxDialog.js'
export { LightboxProvider, LightboxTrigger, useLightbox, useOptionalLightbox } from './LightboxProvider.js'
export type { LightboxApi, LightboxProviderProps, LightboxTriggerProps } from './LightboxProvider.js'
+5
View File
@@ -0,0 +1,5 @@
// Server-safe: pure helpers and types (no React state, no DOM).
export { lightboxImage } from './lightboxImage.js'
export type { LightboxImageOptions } from './lightboxImage.js'
export { formatLightboxCounter, LIGHTBOX_FALLBACK, lightboxIndex, resolveLightboxTexts } from './texts.js'
export type { LightboxClassNames, LightboxImage, LightboxRenderImage, LightboxTexts } from './types.js'
+70
View File
@@ -0,0 +1,70 @@
import type { LightboxImage } from './types.js'
type SizeDoc = { height?: null | number; url?: null | string; width?: null | number }
type MediaDoc = {
alt?: null | string
caption?: unknown
height?: null | number
mimeType?: null | string
sizes?: null | Record<string, null | SizeDoc | undefined>
url?: null | string
width?: null | number
}
export type LightboxImageOptions = {
/** Alt override. Default: the document's alt. */
alt?: null | string
/** Caption override; `false` = none. Default: the document's `caption` when it is a string. */
caption?: false | null | string
/**
* Name of the Payload image size used as `src` (the fallback when the browser
* ignores srcSet), e.g. 'hero'. Default: the original file.
*/
size?: string
/** `sizes` attribute of the large image. Default '100vw'. */
sizes?: string
/** `false` = no srcSet, only `src`. Default true: every Payload size plus the original. */
srcSet?: boolean
}
/**
* A Payload media doc → the image the lightbox shows, or null when it isn't a
* populated image (video, PDF, a bare id). srcSet lists every generated size
* plus the original, so a phone gets a small file and a 4K screen the original.
*
* <LightboxTrigger image={lightboxImage(photo, { size: 'hero' })!} group="gallery">
* <Image {...mediaImageProps(photo, { sizes: MEDIA_SIZES.third })!} />
* </LightboxTrigger>
*/
export function lightboxImage(resource: unknown, options: LightboxImageOptions = {}): LightboxImage | null {
if (!resource || typeof resource !== 'object') {return null}
const doc = resource as MediaDoc
if (typeof doc.url !== 'string' || !doc.url) {return null}
if (doc.mimeType && !doc.mimeType.startsWith('image/')) {return null}
const sizes = Object.values(doc.sizes ?? {}).filter(
(s): s is { height?: null | number; url: string; width: number } => !!s && typeof s.url === 'string' && !!s.url && typeof s.width === 'number' && s.width > 0,
)
const picked = options.size ? doc.sizes?.[options.size] : undefined
const main = picked && typeof picked.url === 'string' && picked.url ? picked : doc
const candidates = [...sizes.map((s) => ({ url: s.url, width: s.width }))]
if (doc.width) {candidates.push({ url: doc.url, width: doc.width })}
const byWidth = new Map<number, string>()
for (const c of candidates) {byWidth.set(c.width, c.url)}
const srcSet =
options.srcSet !== false && byWidth.size > 1
? [...byWidth.entries()].sort((a, b) => a[0] - b[0]).map(([w, url]) => `${url} ${w}w`).join(', ')
: undefined
const caption = options.caption === false ? undefined : (options.caption ?? (typeof doc.caption === 'string' ? doc.caption : undefined))
return {
alt: options.alt ?? doc.alt ?? '',
src: main.url as string,
...(caption?.trim() ? { caption } : {}),
...(main.width ? { width: main.width } : {}),
...(main.height ? { height: main.height } : {}),
...(srcSet ? { sizes: options.sizes ?? '100vw', srcSet } : {}),
}
}
+39
View File
@@ -0,0 +1,39 @@
import type { LightboxTexts } from './types.js'
/**
* English fallbacks, per field — the same philosophy as NOTIFICATION_FALLBACK.
* Editors translate them in Notifications → Lightbox (ipalKit `lightbox: true`).
*/
export const LIGHTBOX_FALLBACK: LightboxTexts = {
close: 'Close',
counter: '{current} / {total}',
dialog: 'Image viewer',
next: 'Next image',
open: 'Enlarge image',
previous: 'Previous image',
}
/** Merges partial texts over the fallback; empty strings fall back too. */
export function resolveLightboxTexts(texts?: null | Partial<Record<keyof LightboxTexts, null | string>>): LightboxTexts {
const out = { ...LIGHTBOX_FALLBACK }
for (const key of Object.keys(out) as (keyof LightboxTexts)[]) {
const value = texts?.[key]
if (typeof value === 'string' && value.trim()) {out[key] = value}
}
return out
}
/** "{current} / {total}" → "2 / 5". */
export const formatLightboxCounter = (template: string, current: number, total: number): string =>
template.replace('{current}', String(current)).replace('{total}', String(total))
/**
* The index after a step of `delta`. `loop` wraps around the ends; without it
* the index stops at the first and last image.
*/
export function lightboxIndex(index: number, delta: number, total: number, loop = true): number {
if (total <= 0) {return 0}
const next = index + delta
if (loop) {return ((next % total) + total) % total}
return Math.min(Math.max(next, 0), total - 1)
}
+73
View File
@@ -0,0 +1,73 @@
import type { ReactNode } from 'react'
/**
* One image as the lightbox shows it. Plain data (strings and numbers), so a
* Server Component can pass it to the client trigger. Build it from a Payload
* media doc with lightboxImage(), or by hand for any other source.
*/
export type LightboxImage = {
/** Alt text of the large image. '' only for a decorative image. */
alt: string
/** Shown under the image and read by screen readers. */
caption?: string
height?: number
/** `sizes` for the large image. Default '100vw'. */
sizes?: string
/** The large image — fallback when the browser ignores srcSet. */
src: string
/** Every width the browser may pick for the viewer, e.g. from Payload `sizes`. */
srcSet?: string
width?: number
}
/**
* Labels of the viewer. The plugin's i18n: the Notifications global → Lightbox
* (ipalKit `lightbox: true`), read with getNotificationTexts(...).lightbox.
* Every missing text falls back to LIGHTBOX_FALLBACK (English).
*/
export type LightboxTexts = {
/** Close button. */
close: string
/** Position in a gallery, with {current} and {total}. */
counter: string
/** Accessible name of the dialog. */
dialog: string
/** Next-image button. */
next: string
/** Accessible name of the trigger; the image alt is appended after ": ". */
open: string
/** Previous-image button. */
previous: string
}
/** Classes per part. Combine with `unstyled` to style everything yourself. */
export type LightboxClassNames = {
/** Every control (close, previous, next). */
button?: string
caption?: string
close?: string
counter?: string
/** The dialog — full-screen overlay and backdrop. */
dialog?: string
figure?: string
image?: string
next?: string
previous?: string
}
/** The image the viewer renders — pass `renderImage` to use next/image or a <picture>. */
export type LightboxRenderImage = (args: {
image: LightboxImage
/** Ready-made props for <img>: src, srcSet, sizes, alt, width, height, className, style. */
imgProps: {
alt: string
className?: string
height?: number
sizes?: string
src: string
srcSet?: string
style?: Record<string, string>
width?: number
}
index: number
}) => ReactNode