Files
ipal-kit/docs/lightbox.md
T
Radosław SmolińskiandClaude Opus 5.5 37592764b5 Docs: fix doc/code drift found against 1.16.3 (docs only)
Verified the IAWL summary's "Doc/code" notes against the code and swept
CLI flags, option names/defaults and env vars. Fixed in the docs:
admin groups (consent-records, cookie-review → Privacy; Form messages
global → Forms), tab labels (More, Spam protection, E-mail sending,
Search engines; Sending method), construction field labels, {field} =
label, globalOverrides instead of "a plugin after ipalKit", enabled:false
keeps globals, pages role labels en+pl, switchLocalePath prefix,
accessibility cookie (necessary), seeding summary() shape, prepublishOnly
chain, doctor --strict --offline in the starter, package files list,
ipal-skills --external in PROGRAMISTA, DATABASE_URI (not _URL),
uploadsCollection exists, SiteProviders nonce, buildLinksField labels,
MCP list_pages limit wording, IPAL_DOCTOR_TOKEN in the env table; shipped
seo-check message "Search engines". Reference skills copy refreshed.

Open questions (not changed): forms over-long text, PAYLOAD_SECRET
length, Site settings update access, doctor seen in CI, bare
`ipal-kit create --external`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-23 23:47:35 +01:00

217 lines
12 KiB
Markdown

# Image lightbox
One shared viewer for images that appear small — a card, a gallery grid, a product thumbnail, an
image inside rich text. The visitor clicks the thumbnail and sees the large version; images in the
same group browse with arrows, keys and swipe. Optional: nothing renders and nothing is added to the
schema until you use it.
- `<LightboxProvider>` (`/client`) — one per layout; owns the viewer.
- `<LightboxTrigger>` (`/client`) — a `<button>` around any thumbnail (`next/image`, `<img>`, your
`<Media>`). Works without a provider too (brings its own viewer).
- `lightboxImage(media, options)` (main entry and `/client`) — a Payload media doc → the large image,
with a `srcSet` from every Payload image size.
- `RenderRichText lightbox` (`/rsc`) — click-to-enlarge for images in rich text.
- `useLightbox()` (`/client`) — open, close, next, previous for your own controls.
- `<LightboxDialog>` (`/client`) — the viewer itself, controlled, for full control.
## What the visitor gets
- A full-screen dialog over the page (portal to `<body>`): `role="dialog"`, `aria-modal`, a name from
the texts, the caption linked with `aria-describedby`.
- Focus moves to Close, Tab and Shift+Tab stay inside the dialog, focus returns to the trigger on close.
- Esc closes, ← / → browse, Home / End jump to the first / last image; a click outside the image closes.
- Swipe left / right on touch screens (40 px threshold; vertical scrolling and pinch-zoom still work).
- Visible controls (44 px targets, the browser's focus ring kept), a live "2 / 5" counter, an
optional caption.
- The page does not scroll behind the dialog (scrollbar gap compensated).
- No animation when the visitor asked for reduced motion — the OS setting or the plugin's
AccessibilityWidget (`data-a11y-motion="reduce"`).
- The neighbouring images preload, so the next arrow press is instant.
- The browser picks the right file from `srcSet` (a phone does not download the 4K original).
## Setup
### 1. One provider for the site
```tsx
// app/(frontend)/[locale]/layout.tsx — Server Component
import { getNotificationTexts } from '@intecion/ipal-kit'
import { SiteProviders } from '@intecion/ipal-kit/rsc'
const payload = await getCachedPayload()
const { lightbox } = await getNotificationTexts({ payload, locale })
<SiteProviders shell={shell} lightbox={{ texts: lightbox }}>…</SiteProviders>
```
Without `SiteProviders`, mount it yourself: `<LightboxProvider texts={lightbox}>` from `/client`.
The provider renders nothing until an image is opened.
### 2. Labels in every language (the plugin's i18n)
```ts
// payload.config.ts
ipalKit({ …, lightbox: true })
```
Adds the **Image viewer** group (`lightbox`) to **Forms → Form messages** (`notifications`): trigger name ("Enlarge image"), dialog
name ("Image viewer"), Previous, Next, Close and the counter (`{current} / {total}`) — localized per
language. `getNotificationTexts(...).lightbox` reads them; an empty field falls back to English
(`LIGHTBOX_FALLBACK`). On Postgres this adds columns: run `pnpm payload migrate:create` and commit the
migration (Coolify runs `migrate` on deploy). Fill the labels in every language, or seed them.
Without `lightbox: true` the components still work: they use the `texts` you pass and English for the
rest. The field group is exported (`lightboxNotificationFields`) if you prefer it in your own global.
### 3. Wrap thumbnails
```tsx
import { lightboxImage, LightboxTrigger } from '@intecion/ipal-kit/client'
import { MEDIA_SIZES, mediaImageProps } from '@intecion/ipal-kit'
import Image from 'next/image'
// a gallery block — every image in one group, browsed in page order
{images.map(({ id, image }) => {
const thumb = mediaImageProps(image, { sizes: MEDIA_SIZES.third })
const large = lightboxImage(image, { size: 'hero' })
if (!thumb || !large) return null
return (
<LightboxTrigger key={id} group={`gallery-${blockId}`} image={large} className="group block overflow-hidden rounded-lg">
<Image {...thumb} className="transition group-hover:scale-105" />
</LightboxTrigger>
)
})}
```
- `group` — triggers with the same group form one gallery, in page order (whatever order they
mounted in). One group per block (`gallery-${id}`) keeps two galleries apart. No group = that image
alone.
- `image` — plain data (`{ src, srcSet?, sizes?, width?, height?, alt, caption? }`), so a Server
Component can render the trigger. `lightboxImage` builds it from a Payload doc; any other source works.
- `children` — the thumbnail, rendered as you like. With `next/image` `fill`, give the trigger a size
(`className="relative aspect-[4/3]"`).
- The button's accessible name is `texts.open + ": " + alt` ("Enlarge image: Red sofa"); pass
`aria-label` to change it.
### 4. Rich text images (opt-in)
```tsx
<RenderRichText data={post.content} lightbox />
<RenderRichText data={post.content} lightbox={{ group: 'post', image: { size: 'hero' }, triggerClassName: 'my-8' }} />
```
Every image upload becomes a trigger; PDFs and videos are left alone. Your own `upload` converter
still renders the inline image — the plugin only wraps what it returns. Default group: `'richtext'`
(every rich text on the page is one gallery); `group: false` opens each image alone. A caption or alt
from the upload node's fields wins over the document's. For your own renderer:
`converters={withLightboxUploads(myConverters, options)}` (`/rsc`).
### 5. Your own controls
```tsx
'use client'
import { useLightbox } from '@intecion/ipal-kit/client'
const box = useLightbox()
<button onClick={(e) => box.open(images, 0, e.currentTarget)}>{labels.viewAll}</button>
// box.openGroup('gallery-1', 2) · box.next() · box.previous() · box.close() · box.isOpen · box.index
```
A product page with a stage image: the stage can be the trigger, and the thumbnail strip keeps
choosing the stage image — `box.open(productImages, activeIndex, e.currentTarget)`.
## Media sizes
`lightboxImage(media, { size?, sizes?, srcSet?, alt?, caption? })`:
| option | default | effect |
|---|---|---|
| `size` | original file | the Payload image size used as `src` (fallback when the browser ignores `srcSet`), e.g. `'hero'` |
| `srcSet` | `true` | every generated size + the original as `url 768w, …`; `false` = `src` only |
| `sizes` | `'100vw'` | `sizes` of the large image |
| `alt` | the doc's `alt` | override |
| `caption` | the doc's `caption` when it is a string | override; `false` = none |
Returns `null` for a video, PDF or unpopulated id — render the thumbnail without a trigger.
A collection without `imageSizes` still works: the original file is the large image. For a phone-
friendly viewer add at least one large size (e.g. `hero` 1920 wide) to the Media collection.
## Styling
Out of the box the viewer is styled inline from CSS variables — override them on `:root` or any parent:
| variable | default |
|---|---|
| `--ipal-lightbox-backdrop` | `rgb(0 0 0 / 0.9)` |
| `--ipal-lightbox-color` | `#fff` |
| `--ipal-lightbox-padding` | `4rem 1rem` |
| `--ipal-lightbox-z-index` | `1000` |
| `--ipal-lightbox-image-max-height` | `calc(100dvh - 9rem)` |
| `--ipal-lightbox-control-bg` | `rgb(255 255 255 / 0.14)` |
| `--ipal-lightbox-control-color` | `inherit` |
| `--ipal-lightbox-control-size` | `2.75rem` |
| `--ipal-lightbox-control-radius` | `999px` |
| `--ipal-lightbox-inset` | `1rem` |
| `--ipal-lightbox-caption-color` | `inherit` |
| `--ipal-lightbox-caption-size` | `0.95rem` |
| `--ipal-lightbox-duration` | `var(--ipal-duration, 200ms)` (fade; none with reduced motion) |
| `--ipal-lightbox-easing` | `var(--ipal-ease-out, ease)` |
```css
:root { --ipal-lightbox-backdrop: rgb(15 23 42 / 0.95); --ipal-lightbox-control-bg: var(--color-brand); }
```
Full control: `unstyled` (on the provider — applies to triggers too — or on one trigger / dialog)
drops every inline style; style with `classNames` (`dialog`, `figure`, `image`, `caption`, `counter`,
`button`, `close`, `previous`, `next`) and the `data-ipal` hooks: `lightbox`, `lightbox-backdrop`,
`lightbox-figure`, `lightbox-caption`, `lightbox-counter`, `lightbox-previous`, `lightbox-next`,
`lightbox-close`, `lightbox-trigger` (+ `data-group`). Icons: `icons={{ close, previous, next }}`.
## Turn off, override, extend
| Feature | Default | Turn off / override |
|---|---|---|
| Whole feature | off — nothing renders without a trigger | don't use the components |
| Form messages → Image viewer labels | off | `ipalKit({ lightbox: true })`; `lightboxNotificationFields` for your own global; `globalOverrides.notifications` |
| Texts | panel → `lightboxFallback(locale)` (`LIGHTBOX_FALLBACK_PL` on `pl`, else `LIGHTBOX_FALLBACK`) | `texts` on the provider / trigger / dialog; `resolveLightboxTexts` |
| Provider in `SiteProviders` | off | `lightbox` prop; or your own `<LightboxProvider>` in a client component |
| Large image markup | `<img srcSet>` | `renderImage={({ image, imgProps, index }) => <Image … />}` (provider, client only) |
| The whole viewer | `LightboxDialog` | `renderDialog={(props) => <MyViewer {...props} />}` — same props, your markup |
| Wrap-around | on | `loop={false}` |
| Swipe threshold | 40 px | `swipeThreshold` on `LightboxDialog` |
| Rich text | off | `RenderRichText lightbox`; `withLightboxUploads(converters, options)` |
| Look | inline styles from `--ipal-lightbox-*` | CSS variables; `unstyled` + `classNames` + `data-ipal` |
Building blocks: `lightboxImage`, `lightboxIndex` (wrap / clamp), `formatLightboxCounter`,
`resolveLightboxTexts(texts, locale?)`, `LIGHTBOX_FALLBACK`, `LIGHTBOX_FALLBACK_PL`, `lightboxFallback`, `prefersReducedMotion`, `useOptionalLightbox` (null
outside a provider), `useLightbox`, `LightboxDialog`.
## Replacing a hand-made modal (migration)
Projects built before this feature open images in different ways: a `glightbox` wrapper, an inline
`div role="dialog"` with `next/image fill`, a link to the raw file in a new tab, or nothing. Move them
to the shared lightbox:
1. **Config:** `ipalKit({ lightbox: true })`, then `pnpm payload migrate:create` (Postgres) and commit
the migration. Fill **Forms → Form messages → Image viewer** in every language — copy the labels
from the old block fields (e.g. `closeLabel`, `prevLabel`, `nextLabel`) or seed them.
2. **Layout:** `<SiteProviders lightbox={{ texts: (await getNotificationTexts({ payload, locale })).lightbox }}>`.
3. **Gallery block:** replace the clickable `<div>` / custom `<button>` + `useState(index)` + dialog
with `<LightboxTrigger group={`gallery-${id}`} image={lightboxImage(image, { size: 'hero' })!}>`
around the existing thumbnail. Delete the dialog, its keydown listener, its scroll lock and its
`useState`. Keep the thumbnail markup and its hover effect (`ZoomIn` icon overlay can stay inside
the trigger as `aria-hidden`).
4. **glightbox:** remove the wrapper, the dynamic `import('glightbox')`, its CSS and the
`glightbox` dependency (`pnpm remove glightbox`).
5. **"Open in a new tab" links** (certificates, diplomas): swap `<a href={image.url} target="_blank">`
for a `LightboxTrigger` — the visitor stays on the page.
6. **Block label fields** for close / previous / next that only served the old modal: stop reading
them; remove them in a later release with a migration (skill **ipal-migrate-fields**) once the
panel texts are filled.
7. **Check:** keyboard only — Tab to a thumbnail, Enter opens, focus is on Close, ← / → browse, Tab
stays in the dialog, Esc closes and focus is back on the thumbnail; the page does not scroll behind
the dialog; on a phone, swipe browses; DevTools → Network shows a resized file, not the original,
on a narrow screen.
Source: `src/modules/lightbox/`, `src/modules/richtext/withLightboxUploads.tsx`. Tests:
`test/lightbox.test.ts`.