Merge claude/image-lightbox-15eabd: shared image lightbox
LightboxProvider / LightboxTrigger / LightboxDialog and lightboxImage from /client, RenderRichText lightbox, SiteProviders lightbox, opt-in Notifications labels (ipalKit lightbox: true), docs/lightbox.md and agent guide.
This commit is contained in:
@@ -38,6 +38,7 @@ API details — one file per module:
|
||||
| Integrations (`site-integrations` global, statuses, test email) | [integrations.md](./integrations.md) |
|
||||
| Links / CTA: buildLinkField, buildLinksField, resolveLinkHref, rowLabel | [links.md](./links.md) |
|
||||
| Media: collection, file names, optimization, placeholders, `mediaImageProps` | [media.md](./media.md) |
|
||||
| Image lightbox: enlarge a thumbnail, galleries, rich text images | [lightbox.md](./lightbox.md) |
|
||||
| Site MCP server | [mcp.md](./mcp.md) |
|
||||
| Form messages | [notifications.md](./notifications.md) |
|
||||
| System pages, 404, generateStaticParams | [pages.md](./pages.md) |
|
||||
|
||||
@@ -739,6 +739,11 @@ Skill: **ipal-nav**.
|
||||
`server-only`, secrets. Types are allowed (`import type`).
|
||||
6. Plugin hooks from `@intecion/ipal-kit/client` (`useForm`, `useConsentContext`…).
|
||||
7. a11y labels (`aria-label`, "Close", "Next slide") — from the panel, via props.
|
||||
8. **An enlarged image is never a hand-made modal** (no `useState(index)` + `div role="dialog"`,
|
||||
`glightbox`, `photoswipe`, a link to the raw file in a new tab) — `<LightboxTrigger>` around the
|
||||
thumbnail (a client component you render from a server block with plain `lightboxImage(…)` data),
|
||||
one `<SiteProviders lightbox>`, labels from Notifications → Lightbox (lightbox.md). `ipal-audit`
|
||||
warns about lightbox libraries and hand-made image dialogs.
|
||||
|
||||
### 6.10 Icons
|
||||
|
||||
@@ -893,6 +898,7 @@ project → **plugin gap**, not a copy.
|
||||
|---|---|---|
|
||||
| R2, file names, optimization, preview | `buildR2Storage`, `normalizeFilenameHook`, `buildOptimizeUploadHook`, `buildMediaPlaceholderHook` | storage.md |
|
||||
| Image / video in `<Media>` | `mediaImageProps`, `videoProps`, `MEDIA_SIZES` | storage.md |
|
||||
| Enlarge an image (card, gallery, product, rich text) | `<SiteProviders lightbox>` + `<LightboxTrigger group image={lightboxImage(media, { size })}>` (`/client`), `RenderRichText lightbox`, `useLightbox`; labels: `ipalKit({ lightbox: true })` → Notifications → Lightbox | lightbox.md |
|
||||
| YouTube without cookies before a click | `<YouTubeEmbed>` (`/client`) | storage.md |
|
||||
| `next.config` | `buildImagesConfig`, `buildSecurityHeaders`, `buildCsp`, `buildUploadSecurityHeaders` | storage.md, security.md |
|
||||
| Fluid typography and spacing | `fluid.css` / `fluid-wide.css` (`--ipal-*` variables) | PROGRAMISTA §2.5 |
|
||||
@@ -939,6 +945,7 @@ payloadTotp } })`, never `twoFactor: false` without a client decision). CSP: fir
|
||||
| Construction mode hides pages in Markdown, MCP | `markdown: { isPathVisible: () => true }`, `mcp: { isPathVisible: () => true }` | `isPathVisible`, `isPathVisibleIn(mode, path)`, `pathOf(url)`, type `PathVisibility` |
|
||||
| Construction mode filters the sitemap and llms.txt | `underConstructionSeo: false` | `include` / `getIncludedPaths` in the low-level builders |
|
||||
| `getSettings` at `depth: 1` | — | `createContentHelpers({ settingsDepth: 2 })` (every request pays) |
|
||||
| Image lightbox (off) | — (opt-in: `<SiteProviders lightbox>`, `LightboxTrigger`, `RenderRichText lightbox`, `ipalKit({ lightbox: true })` for panel labels) | `texts`, `classNames`, `unstyled`, `--ipal-lightbox-*` variables, `renderImage`, `renderDialog`, `loop`, `useLightbox`, `withLightboxUploads`, `lightboxImage` |
|
||||
| `RenderRichText` renders unsafe link URLs as `#` | `safeLinks={false}` (fully trusted content only) | your own `converters` |
|
||||
| Search & AI tab in Site Settings | `searchSettings: false` (top level, works without `seo`; `seo.searchSettings` still works) | `searchSettings: (fields) => fields`; `verificationFrom`, `robotsOptionsFrom` |
|
||||
| Verification `<meta>` from the panel | empty fields = no tag | `const { verification, ...meta } = await generatePageMetadata(…)` |
|
||||
@@ -1121,6 +1128,7 @@ Anything that needs a developer → move it to the panel.
|
||||
| SEO, metadata, sitemap, JSON-LD, llms.txt | [seo.md](../seo.md) |
|
||||
| Auto-slug | [slug.md](../slug.md) |
|
||||
| Media: collection, file names, optimization, placeholders | [media.md](../media.md) |
|
||||
| Image lightbox (enlarge, galleries, rich text images) | [lightbox.md](../lightbox.md) |
|
||||
| R2, `buildImagesConfig`, YouTube | [storage.md](../storage.md) |
|
||||
| Front end: `createContentHelpers` (`@/lib/content`), `createPageRoute`, `SiteProviders` | [frontend.md](../frontend.md) |
|
||||
| Integrations (the `site-integrations` global, statuses, email test) | [integrations.md](../integrations.md) |
|
||||
|
||||
@@ -312,6 +312,8 @@ report WARNING "<form> outside the form renderer" "§0b — panel forms render v
|
||||
# Project copies of what the plugin now ships (import instead of code)
|
||||
report WARNING "own form engine" "ipal-form §3 — <RenderForm> / useBuilderForm (steps, choices, Turnstile, honeypot; Emails tab never reaches the browser)" \
|
||||
"$(g 'buildValidator|useForm\(' src --include=*.tsx | grep -v 'useBuilderForm')"
|
||||
report WARNING "own image lightbox" "lightbox.md — <LightboxTrigger> + lightboxImage, one <SiteProviders lightbox>; labels from Notifications → Lightbox" \
|
||||
"$(g "['\"](glightbox|photoswipe|yet-another-react-lightbox|react-medium-image-zoom|fslightbox-react)['\"]" src --include=*.ts --include=*.tsx)"
|
||||
report WARNING "project copy of section fields / navigation" "blocks.md, links.md — buildSectionHeaderField, buildSectionSettingsField, resolveNav (lib/content)" \
|
||||
"$(ls src/fields/sectionHeader.ts src/fields/sectionSettings.ts src/lib/navigation.ts 2>/dev/null)"
|
||||
if [ -n "$UI" ]; then
|
||||
|
||||
@@ -39,6 +39,10 @@ File patterns (Hero, FeatureGrid + FeatureCard): `resources/section-code.md`.
|
||||
`<Section settings>` → `<SectionHeader header>` → content with `<Media>`, `<CMSLink>`,
|
||||
`items.map(<Card/>)`. No text, `href`, `<img>`, hex colors or inline SVG.
|
||||
3. Subcomponents go in the same folder; shared by 2+ sections → `src/components/ui/`.
|
||||
An image the visitor can enlarge (gallery, card, product, certificate) → wrap the `<Media>` in
|
||||
`<LightboxTrigger group={`<name>-${id}`} image={lightboxImage(item.image, { size: 'hero' })}>`
|
||||
(`@intecion/ipal-kit/client`; skip the trigger when `lightboxImage` returns `null`). No
|
||||
`useState` dialog, no `glightbox` — lightbox.md.
|
||||
4. Add `config.ts` to `layout` in `src/collections/Pages.ts`,
|
||||
and the component to `src/blocks/registry.ts` (key = slug).
|
||||
5. `pnpm generate:types`.
|
||||
|
||||
@@ -68,6 +68,7 @@ description: Complete map of everything @intecion/ipal-kit provides — every ip
|
||||
| `stats.collectionOverrides` | none | changes `stats-visits` like `consentLog.collectionOverrides`; its `access.read` also decides who sees the stats view and dashboard chart | object or function |
|
||||
| `stats.retentionDays` / `timeZone` / `dashboard` | 90 / `'Europe/Warsaw'` / `true` | retention, day boundary, `StatsWidget` | `dashboard: false` hides the chart |
|
||||
| `indexNow` | `false` | `afterChange` hook (publish → IndexNow, production + https only) in the `pages.slug ?? 'pages'` collection and each one from `content` | `true` + `indexnow-key.txt` route |
|
||||
| `lightbox` | `false` | **Lightbox** group in the Notifications global (image viewer labels: open, dialog, previous, next, close, counter — localized); read by `getNotificationTexts(...).lightbox` / `getSiteShell().lightboxTexts`. Postgres: `migrate:create` | omit = English fallbacks + the `texts` prop; `lightboxNotificationFields` for your own global; `globalOverrides.notifications` |
|
||||
| `siteSettingsFields` | none | **Custom** tab in Site Settings | `Field[]` |
|
||||
| `integrationsFields` | none | **Custom** tab in Site Integrations | `Field[]` |
|
||||
| `globalOverrides` | none | changes the plugin's globals (`site-settings`, `site-integrations`, `cookie-settings`, `notifications`): an object merges `access` / `admin` / `hooks` key by key (your keys win, your hooks run after the plugin's), other keys replace; a function `(global) => global` takes over | e.g. `{ notifications: { access: { update: authenticated } } }`; the way to change the plugin globals' access or hooks |
|
||||
@@ -142,6 +143,7 @@ Mandatory set: AGENT.md §0b, skill **ipal-setup**; checks: **ipal-audit**, **ip
|
||||
| Pages | `src/collections/Pages.ts` | `buildSlugField({ from: 'title' })`, `buildNoindexField()`, `buildSummaryField()`, `slugHistory` field + `trackSlugHistoryHook`, `buildRevalidateHook({ revalidatePath, config })` → `afterChange`/`afterDelete` | edit in the panel → the page refreshes without a deploy | slug.md, hooks.md, seo.md |
|
||||
| Pages — protection | as above | `beforeDelete: [buildPreventDeleteSystemPage({ settingsSlug: 'site-settings' })]`; `setPublishedAtHook`, `buildCrossLocaleFieldSync(...)` as needed | delete the homepage → error | hooks.md |
|
||||
| Media | `src/collections/Media.ts` | `upload: { focalPoint: true }`, `hooks.beforeOperation: [normalizeFilenameHook, buildOptimizeUploadHook(), buildMediaPlaceholderHook()]`, fields `buildOptimizeUploadField()`, `buildMediaPlaceholderField()`, `alt` | upload `Zdjęcie Ś.JPG` → `zdjecie-s.jpg`, placeholder in the document | media.md |
|
||||
| image lightbox (optional) | layout + blocks | `lightbox: true` in `ipalKit`; `<SiteProviders shell lightbox>`; `<LightboxTrigger group image={lightboxImage(media, { size: 'hero' })}>` around the thumbnail (`/client`); `<RenderRichText lightbox>` | keyboard: Tab to a thumbnail, Enter → dialog with focus on Close, ←/→, Esc → focus back; Network: a resized file on a phone | lightbox.md |
|
||||
| image on the frontend | `Media` primitive | `<Image {...mediaImageProps(media, { sizes })} />`, video `videoProps` | blur before load | media.md |
|
||||
| storage | `payload.config.ts` | `buildR2Storage(['media'], { s3Storage })` — always (without `R2_*` = local disk) | upload → URL from `R2_PUBLIC_URL` | storage.md |
|
||||
| e-mail | `payload.config.ts` | `email: mailAdapter()` (SMTP from the panel / Graph from env; also `panelSmtpAdapter`, `graphAdapter`, `sendEmail` from `/server`) | Site Integrations → SMTP → **Send test** | email.md |
|
||||
|
||||
@@ -194,11 +194,11 @@ Admin panel components from `@intecion/ipal-kit/admin` — the project does NOT
|
||||
| `createPageRoute(content, { blocks, notFound, permanentRedirect, redirect?, … })` | `@intecion/ipal-kit/rsc` | ready `[[...slug]]` catch-all page → `{ Page, generateMetadata, generateStaticParams }` (blocks, slug history redirects, JSON-LD, under-construction mode); does not paginate `?page=` |
|
||||
| `createNotFoundPage(content, { load } \| { blocks, fallback?, … })` | `@intecion/ipal-kit/rsc` | default export of `not-found.tsx` — the 404 page chosen in the panel or a fallback (the lazy `load` variant is recommended) |
|
||||
| `renderNotFoundView(content, { blocks, fallback?, blockProps?, layoutField? }, locale)` | `@intecion/ipal-kit/rsc` | 404 content in one language — called from a server action for the lazy `createNotFoundPage({ load })` (pages.md) |
|
||||
| `SiteProviders` | `@intecion/ipal-kit/rsc` | layout component: `shell={await getSiteShell(locale)}` mounts consent, cookie banner, analytics, Turnstile, site JSON-LD, theme script; does not mount `AlternateLinksProvider` |
|
||||
| `SiteProviders` | `@intecion/ipal-kit/rsc` | layout component: `shell={await getSiteShell(locale)}` mounts consent, cookie banner, analytics, Turnstile, site JSON-LD, theme script (and `lightbox` → `LightboxProvider`); does not mount `AlternateLinksProvider` |
|
||||
|
||||
Full option lists of `createContentHelpers` / `createPageRoute` / `SiteProviders` and the returned `@/lib/content` keys: `node_modules/@intecion/ipal-kit/docs/frontend.md`.
|
||||
|
||||
**Types:** `ContentHelpers` — `createContentHelpers` result; `SiteShell` — layout data from `getSiteShell` (consent, analytics, theme, jsonLd, settings, formTexts, turnstileSiteKey); `PageJsonLdOptions`, `EntryJsonLdContext` — `getPageJsonLd` options / your own JSON-LD nodes for entries (root); `PageRouteOptions`, `NotFoundPageOptions`, `NotFoundViewOptions`, `SiteProvidersProps` (`/rsc`) — options of `createPageRoute`, `createNotFoundPage`, `renderNotFoundView` and `SiteProviders` props.
|
||||
**Types:** `ContentHelpers` — `createContentHelpers` result; `SiteShell` — layout data from `getSiteShell` (consent, analytics, theme, jsonLd, settings, formTexts, lightboxTexts, turnstileSiteKey); `PageJsonLdOptions`, `EntryJsonLdContext` — `getPageJsonLd` options / your own JSON-LD nodes for entries (root); `PageRouteOptions`, `NotFoundPageOptions`, `NotFoundViewOptions`, `SiteProvidersProps` (`/rsc`) — options of `createPageRoute`, `createNotFoundPage`, `renderNotFoundView` and `SiteProviders` props.
|
||||
|
||||
## Health check (`health`) — details: `node_modules/@intecion/ipal-kit/docs/deployment.md`
|
||||
|
||||
@@ -355,6 +355,23 @@ The editor builds forms in the panel (Forms collection). The project does NOT wr
|
||||
|---|---|---|
|
||||
| `createMcpRoute({ getCachedPayload, config, baseUrl?, serverName?, … })` | `@intecion/ipal-kit` | Read-only MCP server for the site (JSON-RPC: `get_site_info`, `list_pages`, `search_content`, `get_page`) as a route handler → `{ GET, POST }` in `app/api/mcp/route.ts`; with a per-IP rate limit. Usually through `mcpGET`/`mcpPOST` from `lib/content` |
|
||||
|
||||
## Image lightbox (`lightbox`) — details: `node_modules/@intecion/ipal-kit/docs/lightbox.md`
|
||||
|
||||
| Export | Import from | What it does / when |
|
||||
|---|---|---|
|
||||
| `LightboxProvider({ texts?, classNames?, icons?, loop?, unstyled?, renderImage?, renderDialog? })` | `@intecion/ipal-kit/client` | One shared viewer for the site (or `<SiteProviders lightbox>`); renders nothing until an image is opened |
|
||||
| `LightboxTrigger({ image, group?, children, className?, style?, unstyled?, texts?, 'aria-label'? })` | `@intecion/ipal-kit/client` | `<button>` around any thumbnail that opens the large image; same `group` = one gallery in page order; works without a provider (own viewer) |
|
||||
| `useLightbox()` / `useOptionalLightbox()` | `@intecion/ipal-kit/client` | `open(images, index, returnFocus)`, `openGroup(group, start)`, `next`, `previous`, `close`, `isOpen`, `index`, `images`, `texts` — for your own controls; the optional one returns `null` outside a provider |
|
||||
| `LightboxDialog({ images, index, onClose, onIndexChange, … })` | `@intecion/ipal-kit/client` | The viewer itself, controlled (dialog role, focus trap and return, Esc, arrows, Home/End, swipe, counter, caption, scroll lock, reduced motion) |
|
||||
| `lightboxImage(media, { size?, sizes?, srcSet?, alt?, caption? })` | `@intecion/ipal-kit`, `@intecion/ipal-kit/client` | Payload media doc → `LightboxImage` (`src` from `size`, `srcSet` from every Payload size + original, alt, caption) or `null` (video, PDF, id) |
|
||||
| `withLightboxUploads(converters?, { group?, image?, triggerClassName? })` | `@intecion/ipal-kit/rsc` | Wraps rich text image uploads in `LightboxTrigger` on top of your converters (`RenderRichText lightbox` uses it) |
|
||||
| `LIGHTBOX_FALLBACK`, `resolveLightboxTexts(texts)` | `@intecion/ipal-kit`, `@intecion/ipal-kit/client` | English labels; partial texts → full set (empty → fallback) |
|
||||
| `lightboxIndex(index, delta, total, loop?)`, `formatLightboxCounter(template, current, total)` | `@intecion/ipal-kit`, `@intecion/ipal-kit/client` | Wrap / clamp a gallery index; "{current} / {total}" → "2 / 5" |
|
||||
| `prefersReducedMotion()` | `@intecion/ipal-kit/client` | OS reduced motion or the AccessibilityWidget switch (`data-a11y-motion="reduce"`) |
|
||||
| `lightboxNotificationFields` | `@intecion/ipal-kit` | The Notifications → Lightbox field group (added by `ipalKit({ lightbox: true })`) — to place in your own global |
|
||||
|
||||
**Types:** `LightboxImage`, `LightboxTexts`, `LightboxClassNames`, `LightboxRenderImage`, `LightboxImageOptions` (root and `/client`); `LightboxApi`, `LightboxProviderProps`, `LightboxTriggerProps`, `LightboxDialogProps` (`/client`); `RichTextLightboxOptions` (`/rsc`). Styling: `--ipal-lightbox-*` CSS variables, `data-ipal="lightbox…"` hooks.
|
||||
|
||||
## Media (`media`) — details: `node_modules/@intecion/ipal-kit/docs/media.md`
|
||||
|
||||
| Export | Import from | What it does / when |
|
||||
@@ -379,7 +396,7 @@ The editor builds forms in the panel (Forms collection). The project does NOT wr
|
||||
| `resolveFormMessage(result, texts)` | `@intecion/ipal-kit` | `SubmitFormResult` code → text from the panel (`{field}` filled in for `validation`, `error` without exception details); `createSubmitAction` calls it itself |
|
||||
| `NOTIFICATION_FALLBACK` | `@intecion/ipal-kit` | Constant: built-in English `form.*` texts used when a panel field is empty |
|
||||
|
||||
**Types:** `NotificationTexts`, `FormNotificationTexts` — resolved notification texts (`form` group).
|
||||
**Types:** `NotificationTexts`, `FormNotificationTexts` — resolved notification texts (`form` group; `lightbox` group = `LightboxTexts`, see Image lightbox).
|
||||
|
||||
## System pages (`pages`) — details: `node_modules/@intecion/ipal-kit/docs/pages.md`
|
||||
|
||||
@@ -410,7 +427,7 @@ The editor builds forms in the panel (Forms collection). The project does NOT wr
|
||||
|
||||
| Export | Import from | What it does / when |
|
||||
|---|---|---|
|
||||
| `RenderRichText({ data, converters?, className?, headingIds?, safeLinks? })` | `@intecion/ipal-kit/rsc` | Renders a richText (Lexical) field through Payload's official converter; your own classes via `converters`, `headingIds` adds anchors to headings (the same ids as `extractHeadings`). Unsafe link URLs (`javascript:`, `data:`…) render as `#`; `safeLinks={false}` turns that off (fully trusted content only). Instead of a hand-written renderer. |
|
||||
| `RenderRichText({ data, converters?, className?, headingIds?, lightbox?, safeLinks? })` | `@intecion/ipal-kit/rsc` | Renders a richText (Lexical) field through Payload's official converter; `lightbox` = click-to-enlarge images (lightbox.md); your own classes via `converters`, `headingIds` adds anchors to headings (the same ids as `extractHeadings`). Unsafe link URLs (`javascript:`, `data:`…) render as `#`; `safeLinks={false}` turns that off (fully trusted content only). Instead of a hand-written renderer. |
|
||||
| `extractHeadings(data, { levels? })` | `@intecion/ipal-kit`, `@intecion/ipal-kit/rsc` | List of headings `{ id, level, text }` (h2 by default) for a table of contents — ids match `RenderRichText headingIds`. |
|
||||
| `headingText(node)` | `@intecion/ipal-kit` | Plain text of a Lexical node (a heading with bold, links…). |
|
||||
| `buildTableOfContentsField({ name? })` | `@intecion/ipal-kit` | `tableOfContents` group field (show + localized label) for a text block/section — table of contents toggle in the panel. |
|
||||
|
||||
@@ -55,6 +55,11 @@ between phases. Before each phase, go through the "Anticipate" table in AGENT.md
|
||||
Order: Hero → recurring sections (FeatureGrid, CTA, FAQ…) → specific ones.
|
||||
Every block: schema from the field dictionary, composition of primitives, zero text in JSX
|
||||
(`ipal-audit --quick` after every block — fix errors right away).
|
||||
**Enlarged images** (gallery, cards, product photos, certificates, rich text): the shared lightbox,
|
||||
never a hand-made modal or a lightbox library — `ipalKit({ lightbox: true })` + migration,
|
||||
`<SiteProviders lightbox>` once, `<LightboxTrigger group={`gallery-${id}`} image={lightboxImage(media, { size })}>`
|
||||
around the thumbnail, `RenderRichText lightbox` for article images, Notifications → Lightbox labels
|
||||
in every language (lightbox.md). Check with the keyboard: Enter opens, ←/→ browse, Esc returns focus.
|
||||
|
||||
## Phase 5 — Forms → **ipal-form**
|
||||
Every form = a seed from `ipal-form/resources/seed-form.template.ts` (fields, confirmation, email to the
|
||||
|
||||
@@ -645,6 +645,7 @@ Do one item at a time, build, check. Order by importance:
|
||||
| 45 | **1.11.1** — format description in a form field label / time as text | the **Placeholder** field in the admin panel, the **Time** type; Postgres: `migrate:create` | forms.md |
|
||||
| 46 | **1.12.3** — own cookie settings window / cookie list in the banner written in the project | `<CookieBanner settings="detailed">` (list from Cookie Settings → Cookies, captions: Detail labels); delete your own version; Postgres: `migrate:create` | consent.md |
|
||||
| 47 | **1.13.0** — staff access, Search & AI, seed scripts, workarounds around plugin globals | without `access`: every logged-in account gets the staff features → `access` or `globalOverrides` / `formOverrides` / `formSubmissionOverrides` / `collectionOverrides`; with `access`: staff need `editor`/`admin`; Postgres: `migrate:create`; check `settingsDepth`, `sitemap()` throwing, 2FA slug, client IP; own seed code → `@intecion/ipal-kit/seed`; global hooks/access plugins → `revalidatePath` / `globalOverrides` | CHANGELOG 1.13.0, AGENT.md §7.1, seo.md, seeding.md |
|
||||
| 48 | **image lightbox** (release after 1.13.0) — own image modal (`useState(index)` + `div role="dialog"`), `glightbox` / other lightbox library, thumbnails linking to the raw file in a new tab | `ipalKit({ lightbox: true })` + Postgres `migrate:create`; `<SiteProviders lightbox>`; `<LightboxTrigger group image={lightboxImage(media, { size })}>` around the thumbnail; delete the old dialog and `pnpm remove glightbox`; old label fields → Notifications → Lightbox | lightbox.md → "Replacing a hand-made modal" |
|
||||
|
||||
After updating the package: `pnpm ipal:skills` (new skill versions), `pnpm payload generate:importmap`, `rm -rf .next`, restart dev, grep for the new symbol in
|
||||
`node_modules/@intecion/ipal-kit/dist`.
|
||||
|
||||
+3
-1
@@ -145,7 +145,7 @@ import { getSiteShell } from '@/lib/content'
|
||||
```
|
||||
|
||||
Renders: `<ThemeScript>` (when `theme`), `<MediaPreconnect>`, `<JsonLdGraph>` (site JSON-LD + `jsonLd`),
|
||||
`<ConsentProvider>` with `<TurnstileProvider>`, `<CookieBanner>`, `<CookieButton>`, `<Analytics>`, `<PageStats>`.
|
||||
`<ConsentProvider>` with `<TurnstileProvider>` (and `<LightboxProvider>` when `lightbox`), `<CookieBanner>`, `<CookieButton>`, `<Analytics>`, `<PageStats>`.
|
||||
It does not mount `AlternateLinksProvider` (i18n.md) — add it yourself if you use `LanguageSwitcher`.
|
||||
|
||||
| Prop | Default | What it does |
|
||||
@@ -157,6 +157,7 @@ It does not mount `AlternateLinksProvider` (i18n.md) — add it yourself if you
|
||||
| `analytics` | on | extra `<Analytics>` props or `false` = no tags |
|
||||
| `cookieMap` | — | extra cookies per category to clean up after consent is withdrawn |
|
||||
| `jsonLd` | `[]` | extra JSON-LD nodes |
|
||||
| `lightbox` | off | `true` / `{ texts, classNames, icons, loop, unstyled }` → one `<LightboxProvider>` for the site; texts from `shell.lightboxTexts` (Notifications → Lightbox) — lightbox.md |
|
||||
| `preconnect` | `true` | `<link rel=preconnect>` to the media origin |
|
||||
| `stats` | off | `true`/props → `<PageStats>` (stats.md) |
|
||||
| `theme` | `false` | `<ThemeScript>` before the first paint (theme.md) |
|
||||
@@ -168,6 +169,7 @@ It does not mount `AlternateLinksProvider` (i18n.md) — add it yourself if you
|
||||
- Any key from `createContentHelpers` can be left out of the destructuring or replaced with your own function
|
||||
of the same name in `src/lib/content.ts` (e.g. your own `generateStaticParams` with entries).
|
||||
- `createPageRoute`: your own view through `render`, your own 404/redirect through `onMissing`, extra block props through `blockProps`, JSON-LD through `jsonLd`.
|
||||
- `SiteProviders`: `lightbox` is off by default; for `renderImage` / `renderDialog` (functions) mount `<LightboxProvider>` yourself in a client component instead (lightbox.md).
|
||||
- `SiteProviders`: `banner`, `cookieButton`, `analytics` accept your own element or `false`; `analytics={{ consentMode: 'basic' }}` = no request to Google before consent (default `'advanced'`: the tag loads with every signal `denied`).
|
||||
- Search & AI from the panel: `robots` instead of `getRobots` ignores it; your own robots: `buildRobots({ ...robotsOptionsFrom(settings), … })`; drop the verification tags: `const { verification, ...meta } = await generatePageMetadata(…)`.
|
||||
- Construction filter in Markdown / MCP: `markdown: { isPathVisible: () => true }`, `mcp: { isPathVisible: () => true }`; in the sitemap and llms.txt: `underConstructionSeo: false`.
|
||||
|
||||
@@ -0,0 +1,215 @@
|
||||
# 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 **Lightbox** group to **Settings → 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` | `200ms` (fade; none with reduced motion) |
|
||||
|
||||
```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 |
|
||||
| Notifications → Lightbox labels | off | `ipalKit({ lightbox: true })`; `lightboxNotificationFields` for your own global; `globalOverrides.notifications` |
|
||||
| Texts | panel → `LIGHTBOX_FALLBACK` (English) | `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`, `LIGHTBOX_FALLBACK`, `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 **Settings → Notifications → Lightbox** 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`.
|
||||
@@ -148,5 +148,9 @@ props or `null` (video, PDF, a bare id, no `width`/`height`):
|
||||
- `'background'`: `autoPlay` (off with `reducedMotion: true`), `muted`, `loop`, `preload="metadata"`;
|
||||
- always `playsInline`; `poster` — a URL or a Media document.
|
||||
|
||||
**Enlarging an image** (card, gallery, product thumbnail): wrap the `<Media>` in `<LightboxTrigger
|
||||
image={lightboxImage(resource, { size: 'hero' })}>` — `lightboxImage` builds the large image with a
|
||||
`srcSet` from every Payload size. Do not build your own modal: [lightbox.md](./lightbox.md).
|
||||
|
||||
**`MEDIA_SIZES`** — starting points for `sizes`: `full` (`100vw`), `half`, `third`, `quarter`,
|
||||
`thumb` (`160px`). You can replace any value with your own string.
|
||||
|
||||
@@ -21,6 +21,12 @@ the texts in the panel (Notifications tab), grouped per context. Group `form`:
|
||||
exported from `@intecion/ipal-kit`).
|
||||
For forms: `getFormTexts(locale)` from `lib/content` = the `form` group in the given language.
|
||||
|
||||
Group `lightbox` (only with `ipalKit({ lightbox: true })` — adds columns, run a migration on Postgres):
|
||||
`open` ("Enlarge image"), `dialog` ("Image viewer"), `previous`, `next`, `close`, `counter`
|
||||
("{current} / {total}"). `getNotificationTexts(...).lightbox` always returns the full set (fallback
|
||||
`LIGHTBOX_FALLBACK`), and `getSiteShell(locale).lightboxTexts` carries it to `<SiteProviders lightbox>`.
|
||||
Details: [lightbox.md](./lightbox.md).
|
||||
|
||||
## Helper — getNotificationTexts
|
||||
|
||||
Reads the texts from the global per language, with a fallback per field. The counterpart of `getConsentTexts`:
|
||||
@@ -29,7 +35,7 @@ Reads the texts from the global per language, with a fallback per field. The cou
|
||||
import { getNotificationTexts } from '@intecion/ipal-kit'
|
||||
|
||||
const notifications = await getNotificationTexts({ payload, locale }) // in lib/content: getFormTexts(locale) = .form
|
||||
// notifications.form.error, notifications.form.success, ...
|
||||
// notifications.form.error, notifications.form.success, ..., notifications.lightbox.close
|
||||
```
|
||||
|
||||
## Mapping the result — resolveFormMessage
|
||||
@@ -74,7 +80,7 @@ users), so the frontend reads them without a session. Write: `editor+` (`adminOr
|
||||
|
||||
## Turn off, override, extend
|
||||
|
||||
- **Turn off:** none — the `notifications` global is currently always added (also without the `forms` option).
|
||||
- **Turn off:** none — the `notifications` global is currently always added (also without the `forms` option). The `lightbox` group is opt-in (`ipalKit({ lightbox: true })`); `lightboxNotificationFields` puts it in your own global instead.
|
||||
- **Override texts:** in the panel, per language; empty field → `NOTIFICATION_FALLBACK` (EN).
|
||||
The fallbacks cannot be swapped with a plugin option — apply your own default texts in the project
|
||||
on the result of `getNotificationTexts` (e.g. `texts.form.error ||= '…'`).
|
||||
|
||||
@@ -89,6 +89,18 @@ const items = block.tableOfContents?.show ? extractHeadings(block.content) : []
|
||||
- `buildTableOfContentsField({ name = 'tableOfContents' })` — a "Show table of contents" switch + a localized label (type `TableOfContentsSettings`).
|
||||
A new field in a block = a migration (`pnpm payload migrate:create`).
|
||||
|
||||
## Click-to-enlarge images (lightbox, opt-in)
|
||||
|
||||
```tsx
|
||||
<RenderRichText data={post.content} lightbox />
|
||||
<RenderRichText data={post.content} lightbox={{ group: 'post', image: { size: 'hero' }, triggerClassName: 'my-8' }} />
|
||||
```
|
||||
|
||||
Each image upload is wrapped in `<LightboxTrigger>` (`/client`); the images of the page browse as one
|
||||
gallery (default group `'richtext'`, `group: false` = each alone). Your own `upload` converter still
|
||||
renders the inline image. Your own renderer: `converters={withLightboxUploads(myConverters, options)}`
|
||||
(`/rsc`). Details, labels and styling: [lightbox.md](./lightbox.md).
|
||||
|
||||
## lexicalToMarkdown — richText → Markdown (for AI)
|
||||
|
||||
For readability by AI agents (Markdown per page, llms-full) you need
|
||||
@@ -127,6 +139,7 @@ project already has (it is the editor). No extra dependencies.
|
||||
|
||||
- The module has no option in `ipalKit()` — it adds nothing to the schema; you use the components and functions or you don't.
|
||||
- Override the look of nodes through `converters` (spread `defaultConverters`); heading ids through `headingIds` (`levels`, `className`).
|
||||
- Image lightbox: off by default; `lightbox` turns it on, `withLightboxUploads` is the building block (lightbox.md).
|
||||
- Link filtering: on by default; `safeLinks={false}` turns it off for fully trusted content.
|
||||
- `extractHeadings(data, { levels })` and `headingText(node)` — building blocks for your own table of contents; style `<TableOfContents>` with `classNames`, the active-section threshold with `offset`.
|
||||
- `lexicalToMarkdown` has no options (the handled nodes are fixed; unknown ones degrade to text) — another format needs your own converter.
|
||||
|
||||
@@ -76,6 +76,10 @@ export {
|
||||
switchLocalePath,
|
||||
} from '../modules/i18n/index.js'
|
||||
export type { I18nConfig, LocalizedSlugs } from '../modules/i18n/index.js'
|
||||
export { LightboxDialog, LightboxProvider, LightboxTrigger, prefersReducedMotion, useLightbox, useOptionalLightbox } from '../modules/lightbox/client.js'
|
||||
export type { LightboxApi, LightboxDialogProps, LightboxProviderProps, LightboxTriggerProps } from '../modules/lightbox/client.js'
|
||||
export { formatLightboxCounter, LIGHTBOX_FALLBACK, lightboxImage, lightboxIndex, resolveLightboxTexts } from '../modules/lightbox/index.js'
|
||||
export type { LightboxClassNames, LightboxImage, LightboxImageOptions, LightboxRenderImage, LightboxTexts } from '../modules/lightbox/index.js'
|
||||
export { LocaleView } from '../modules/pages/LocaleView.js'
|
||||
export { NotFoundLoader } from '../modules/pages/NotFoundLoader.js'
|
||||
export { TableOfContents } from '../modules/richtext/TableOfContents.js'
|
||||
|
||||
@@ -25,6 +25,8 @@ export type { SiteProvidersProps } from '../modules/frontend/SiteProviders.js'
|
||||
export { extractHeadings } from '../modules/richtext/headings.js'
|
||||
export { RenderRichText } from '../modules/richtext/index.js'
|
||||
export type { RenderRichTextProps } from '../modules/richtext/index.js'
|
||||
export { withLightboxUploads } from '../modules/richtext/withLightboxUploads.js'
|
||||
export type { RichTextLightboxOptions } from '../modules/richtext/withLightboxUploads.js'
|
||||
export { JsonLdGraph } from '../modules/seo/index.js'
|
||||
export { NoSnippet } from '../modules/seo/NoSnippet.js'
|
||||
export type { NoSnippetProps } from '../modules/seo/NoSnippet.js'
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import type { Field } from 'payload'
|
||||
|
||||
import { LIGHTBOX_FALLBACK } from '../../modules/lightbox/texts.js'
|
||||
|
||||
/**
|
||||
* Fields for the Notifications global — localized user-facing texts for action
|
||||
* results (form submission outcomes, and future contexts). Every text is
|
||||
@@ -96,3 +98,42 @@ export const notificationsFields: Field[] = [
|
||||
label: 'Form messages',
|
||||
},
|
||||
]
|
||||
|
||||
const lightboxText = (name: keyof typeof LIGHTBOX_FALLBACK, width: string, description?: string): Field => ({
|
||||
name,
|
||||
type: 'text',
|
||||
admin: { placeholder: LIGHTBOX_FALLBACK[name], width, ...(description ? { description } : {}) },
|
||||
localized: true,
|
||||
})
|
||||
|
||||
/**
|
||||
* The "Lightbox" group — labels of the image viewer (<LightboxProvider texts>).
|
||||
* Added by ipalKit `lightbox: true`; exported so a project can place it in its
|
||||
* own global instead.
|
||||
*/
|
||||
export const lightboxNotificationFields: Field = {
|
||||
name: 'lightbox',
|
||||
type: 'group',
|
||||
admin: {
|
||||
description: 'Labels of the enlarged-image viewer, read by screen readers. Leave a field empty to use the built-in default.',
|
||||
},
|
||||
fields: [
|
||||
{
|
||||
type: 'row',
|
||||
fields: [
|
||||
lightboxText('open', '50%', 'Button around a small image; its alt text follows after ": ".'),
|
||||
lightboxText('dialog', '50%', 'Name of the viewer window.'),
|
||||
],
|
||||
},
|
||||
{
|
||||
type: 'row',
|
||||
fields: [
|
||||
lightboxText('previous', '25%'),
|
||||
lightboxText('next', '25%'),
|
||||
lightboxText('close', '25%'),
|
||||
lightboxText('counter', '25%', '{current} and {total} are replaced.'),
|
||||
],
|
||||
},
|
||||
],
|
||||
label: 'Lightbox',
|
||||
}
|
||||
|
||||
@@ -1,14 +1,15 @@
|
||||
import type { GlobalConfig } from 'payload'
|
||||
|
||||
import { userMeetsRole } from '../../modules/access/index.js'
|
||||
import { notificationsFields } from './fields.js'
|
||||
import { lightboxNotificationFields, notificationsFields } from './fields.js'
|
||||
|
||||
/**
|
||||
* Builds the Notifications global — localized action-result texts. Readable by
|
||||
* any authenticated panel user; server-side helpers read it with overrideAccess
|
||||
* so the frontend can resolve texts without a session.
|
||||
* so the frontend can resolve texts without a session. `lightbox` adds the
|
||||
* image-viewer labels (ipalKit `lightbox: true`).
|
||||
*/
|
||||
export function buildNotifications(): GlobalConfig {
|
||||
export function buildNotifications({ lightbox = false }: { lightbox?: boolean } = {}): GlobalConfig {
|
||||
return {
|
||||
slug: 'notifications',
|
||||
access: {
|
||||
@@ -16,7 +17,7 @@ export function buildNotifications(): GlobalConfig {
|
||||
update: ({ req }) => userMeetsRole(req, 'editor'),
|
||||
},
|
||||
admin: { group: 'Settings' },
|
||||
fields: notificationsFields,
|
||||
fields: lightbox ? [...notificationsFields, lightboxNotificationFields] : notificationsFields,
|
||||
label: 'Notifications',
|
||||
}
|
||||
}
|
||||
|
||||
+5
-1
@@ -1,3 +1,4 @@
|
||||
export { lightboxNotificationFields } from './globals/Notifications/fields.js'
|
||||
export { applyGlobalOverrides } from './globals/overrides.js'
|
||||
export type { GlobalOverride, GlobalOverrides, IpalGlobalSlug } from './globals/overrides.js'
|
||||
export type { AccessOption, Role } from './modules/access/index.js'
|
||||
@@ -134,6 +135,9 @@ export { LOCALE_COOKIE_NAME, matchAcceptLanguage, negotiateLocale } from './modu
|
||||
export { resolveLocalized } from './modules/i18n/resolveLocalized.js'
|
||||
export { buildIntegrationStatusBanner, buildIntegrationStatusField, recordIntegrationStatus } from './modules/integrations/index.js'
|
||||
export type { IntegrationState, IntegrationStatus } from './modules/integrations/index.js'
|
||||
// Image lightbox — pure helpers (components live in /client).
|
||||
export { formatLightboxCounter, LIGHTBOX_FALLBACK, lightboxImage, lightboxIndex, resolveLightboxTexts } from './modules/lightbox/index.js'
|
||||
export type { LightboxClassNames, LightboxImage, LightboxImageOptions, LightboxRenderImage, LightboxTexts } from './modules/lightbox/index.js'
|
||||
export { buildLinkField, buildLinksField, homeSlugFrom, resolveLink, resolveLinkHref, resolveNav, resolveSystemLinks, safeHref } from './modules/links/index.js'
|
||||
export type {
|
||||
BuildLinkFieldOptions,
|
||||
@@ -174,7 +178,7 @@ export {
|
||||
export { buildTableOfContentsField, extractHeadings, headingText } from './modules/richtext/headings.js'
|
||||
export type { ExtractHeadingsOptions, HeadingItem, HeadingLevel } from './modules/richtext/headings.js'
|
||||
// Lexical → Markdown (pure, no React) — for AI-readable output.
|
||||
export { lexicalToMarkdown } from './modules/richtext/index.js'
|
||||
export { lexicalToMarkdown } from './modules/richtext/lexicalToMarkdown.js'
|
||||
export { buildSecurityHeaders, buildUploadSecurityHeaders } from './modules/security/index.js'
|
||||
export { buildCsp } from './modules/security/index.js'
|
||||
export type { BuildCspArgs } from './modules/security/index.js'
|
||||
|
||||
@@ -2,6 +2,7 @@ import type { ReactNode } from 'react'
|
||||
|
||||
import type { AnalyticsProps } from '../analytics/Analytics.js'
|
||||
import type { ConsentCookieMap } from '../consent/useConsent.js'
|
||||
import type { LightboxProviderProps } from '../lightbox/LightboxProvider.js'
|
||||
import type { PageStatsProps } from '../stats/PageStats.js'
|
||||
import type { SiteShell } from './createContentHelpers.js'
|
||||
|
||||
@@ -9,6 +10,7 @@ import { Analytics } from '../analytics/Analytics.js'
|
||||
import { ConsentProvider } from '../consent/ConsentContext.js'
|
||||
import { CookieBanner } from '../consent/CookieBanner.js'
|
||||
import { CookieButton } from '../consent/CookieButton.js'
|
||||
import { LightboxProvider } from '../lightbox/LightboxProvider.js'
|
||||
import { JsonLdGraph } from '../seo/JsonLdGraph.js'
|
||||
import { PageStats } from '../stats/PageStats.js'
|
||||
import { MediaPreconnect } from '../storage/MediaPreconnect.js'
|
||||
@@ -27,6 +29,14 @@ export type SiteProvidersProps = {
|
||||
cookieMap?: ConsentCookieMap
|
||||
/** More site-wide JSON-LD nodes next to shell.jsonLd (e.g. buildNavigationJsonLd). */
|
||||
jsonLd?: (null | Record<string, unknown> | undefined)[]
|
||||
/**
|
||||
* One shared image lightbox for the site: mounts <LightboxProvider> around the
|
||||
* page, so every <LightboxTrigger> and `RenderRichText lightbox` uses it.
|
||||
* `true` (texts from shell.lightboxTexts = Notifications → Lightbox) or
|
||||
* `{ texts, classNames, icons, loop, unstyled }`. Default off. For renderImage / renderDialog (functions) mount the provider
|
||||
* yourself in a client component.
|
||||
*/
|
||||
lightbox?: boolean | Omit<LightboxProviderProps, 'children' | 'renderDialog' | 'renderImage'>
|
||||
/** Consent log endpoint, e.g. '/api/ipal/consent' (ipalKit consentLog: true). */
|
||||
logEndpoint?: string
|
||||
/** <link rel=preconnect> to the media origin (R2_PUBLIC_URL). Default true. */
|
||||
@@ -69,6 +79,7 @@ export function SiteProviders({
|
||||
cookieButton,
|
||||
cookieMap,
|
||||
jsonLd = [],
|
||||
lightbox = false,
|
||||
logEndpoint,
|
||||
preconnect = true,
|
||||
shell,
|
||||
@@ -81,7 +92,15 @@ export function SiteProviders({
|
||||
{preconnect ? <MediaPreconnect /> : null}
|
||||
<JsonLdGraph schemas={[...shell.jsonLd, ...jsonLd]} />
|
||||
<ConsentProvider cookieMap={cookieMap} logEndpoint={logEndpoint} texts={shell.consent}>
|
||||
<TurnstileProvider siteKey={shell.turnstileSiteKey}>{children}</TurnstileProvider>
|
||||
<TurnstileProvider siteKey={shell.turnstileSiteKey}>
|
||||
{lightbox ? (
|
||||
<LightboxProvider texts={shell.lightboxTexts} {...(lightbox === true ? {} : lightbox)}>
|
||||
{children}
|
||||
</LightboxProvider>
|
||||
) : (
|
||||
children
|
||||
)}
|
||||
</TurnstileProvider>
|
||||
{banner === undefined ? <CookieBanner /> : banner || null}
|
||||
{cookieButton === undefined ? <CookieButton /> : cookieButton || null}
|
||||
{analytics === false ? null : <Analytics {...shell.analytics} {...analytics} />}
|
||||
|
||||
@@ -9,6 +9,7 @@ import type { ConstructionMode } from '../construction/types.js'
|
||||
import type { PathVisibility } from '../construction/visibility.js'
|
||||
import type { ArchiveEntries, ContentOption, ResolvedRoute } from '../content/index.js'
|
||||
import type { I18nConfig } from '../i18n/index.js'
|
||||
import type { LightboxTexts } from '../lightbox/types.js'
|
||||
import type { LinkValue, NavItem, ResolvedLink, ResolveLinkHrefOptions, SystemLink } from '../links/index.js'
|
||||
import type { CreateMcpRouteArgs } from '../mcp/createMcpRoute.js'
|
||||
import type { FormNotificationTexts } from '../notifications/types.js'
|
||||
@@ -795,23 +796,22 @@ export function createContentHelpers({
|
||||
|
||||
// ── Layout ────────────────────────────────────────────────────────────────
|
||||
/** Notifications → form texts in this locale (BuilderForm / RenderForm `texts`). */
|
||||
const getFormTexts = cache(async (locale: string): Promise<FormNotificationTexts> =>
|
||||
(await getNotificationTexts({ locale, payload: await getCachedPayload() })).form,
|
||||
)
|
||||
const getNotifications = cache(async (locale: string) => getNotificationTexts({ locale, payload: await getCachedPayload() }))
|
||||
const getFormTexts = cache(async (locale: string): Promise<FormNotificationTexts> => (await getNotifications(locale)).form)
|
||||
|
||||
/**
|
||||
* Everything the [locale] layout reads, in one cached call: consent texts,
|
||||
* analytics IDs, Turnstile site key, site JSON-LD, form texts and Site
|
||||
* analytics IDs, Turnstile site key, site JSON-LD, form and lightbox texts and Site
|
||||
* Settings. Feed it to <SiteProviders> (/rsc) — or use the pieces yourself.
|
||||
*/
|
||||
const getSiteShell = cache(async (locale: string): Promise<SiteShell> => {
|
||||
const payload = await getCachedPayload()
|
||||
const [consent, analytics, turnstile, settings, formTexts] = await Promise.all([
|
||||
const [consent, analytics, turnstile, settings, notifications] = await Promise.all([
|
||||
getConsentTexts({ config: needI18n('getSiteShell'), locale, payload, settingsSlug }),
|
||||
getAnalyticsConfig(payload),
|
||||
getTurnstileConfig(payload),
|
||||
getSettings(locale) as Promise<Record<string, unknown>>,
|
||||
getFormTexts(locale),
|
||||
getNotifications(locale),
|
||||
])
|
||||
let jsonLd: Record<string, unknown>[] = []
|
||||
if (typeof siteJsonLd === 'function') {
|
||||
@@ -828,8 +828,9 @@ export function createContentHelpers({
|
||||
return {
|
||||
analytics,
|
||||
consent,
|
||||
formTexts,
|
||||
formTexts: notifications.form,
|
||||
jsonLd: jsonLd.map(({ '@context': _context, ...node }) => node),
|
||||
lightboxTexts: notifications.lightbox,
|
||||
settings: settings ?? {},
|
||||
theme: themeConfigFrom(settings),
|
||||
turnstileSiteKey: turnstile.siteKey,
|
||||
@@ -910,6 +911,8 @@ export type SiteShell = {
|
||||
formTexts: FormNotificationTexts
|
||||
/** Site-wide nodes (WebSite, Organization…) for <JsonLdGraph>. */
|
||||
jsonLd: Record<string, unknown>[]
|
||||
/** Notifications → Lightbox (English fallbacks without ipalKit `lightbox`) — <SiteProviders lightbox> reads it. */
|
||||
lightboxTexts?: LightboxTexts
|
||||
settings: Record<string, unknown>
|
||||
/** Site Settings → Theme, for <ThemeScript> / <SiteProviders theme> and <ThemeSwitcher label>. */
|
||||
theme: ThemeConfig
|
||||
|
||||
@@ -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,
|
||||
)
|
||||
}
|
||||
@@ -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} />
|
||||
}
|
||||
@@ -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'
|
||||
@@ -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'
|
||||
@@ -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 } : {}),
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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
|
||||
@@ -1,5 +1,7 @@
|
||||
import type { NotificationTexts } from './types.js'
|
||||
|
||||
import { LIGHTBOX_FALLBACK } from '../lightbox/texts.js'
|
||||
|
||||
/**
|
||||
* Built-in English fallbacks, used per field when the Notifications global
|
||||
* leaves a text empty. Same philosophy as consent FALLBACK: the site works out
|
||||
@@ -18,4 +20,5 @@ export const NOTIFICATION_FALLBACK: NotificationTexts = {
|
||||
turnstile: 'Captcha verification failed. Please try again.',
|
||||
validation: 'Please check the {field} field and try again.',
|
||||
},
|
||||
lightbox: LIGHTBOX_FALLBACK,
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ import type { BasePayload } from 'payload'
|
||||
|
||||
import type { NotificationsData, NotificationTexts } from './types.js'
|
||||
|
||||
import { resolveLightboxTexts } from '../lightbox/texts.js'
|
||||
import { getGlobal } from '../payload/index.js'
|
||||
import { NOTIFICATION_FALLBACK } from './defaults.js'
|
||||
|
||||
@@ -39,5 +40,6 @@ export async function getNotificationTexts({
|
||||
turnstile: f.turnstile || fb.turnstile,
|
||||
validation: f.validation || fb.validation,
|
||||
},
|
||||
lightbox: resolveLightboxTexts(g.lightbox),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import type { LightboxTexts } from '../lightbox/types.js'
|
||||
|
||||
/**
|
||||
* Resolved notification texts, ready for the frontend. Grouped per context;
|
||||
* `form` maps submitForm result codes to user-facing messages.
|
||||
@@ -22,9 +24,12 @@ export type FormNotificationTexts = {
|
||||
|
||||
export type NotificationTexts = {
|
||||
form: FormNotificationTexts
|
||||
/** Image viewer labels — pass to <LightboxProvider texts>. Fallbacks when ipalKit `lightbox` is off. */
|
||||
lightbox: LightboxTexts
|
||||
}
|
||||
|
||||
/** Raw shape read from the Notifications global (all fields optional). */
|
||||
export type NotificationsData = {
|
||||
form?: Partial<FormNotificationTexts>
|
||||
lightbox?: null | Partial<Record<keyof LightboxTexts, null | string>>
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ import { cloneElement, isValidElement, type ReactElement, type ReactNode } from
|
||||
|
||||
import { headingIds as computeHeadingIds, type HeadingLevel } from './headings.js'
|
||||
import { sanitizeRichTextLinks } from './sanitizeLinks.js'
|
||||
import { type RichTextLightboxOptions, withLightboxUploads } from './withLightboxUploads.js'
|
||||
|
||||
export type RenderRichTextProps = {
|
||||
/** Wrapper class (e.g. Tailwind prose classes). */
|
||||
@@ -31,6 +32,14 @@ export type RenderRichTextProps = {
|
||||
* converter still renders the heading; the id is added to what it returns.
|
||||
*/
|
||||
headingIds?: { className?: string; levels?: readonly HeadingLevel[] } | boolean
|
||||
/**
|
||||
* Click-to-enlarge on image uploads (opt-in): each image becomes a
|
||||
* <LightboxTrigger>, and the images browse as one gallery. `true` or
|
||||
* `{ group, image: { size }, triggerClassName }`. Your own `upload` converter
|
||||
* still renders the inline image. Inside a <LightboxProvider> the site's
|
||||
* viewer and texts are used; without one each image brings its own.
|
||||
*/
|
||||
lightbox?: boolean | RichTextLightboxOptions
|
||||
/**
|
||||
* Links whose URL isn't a safe target (`javascript:`, `data:`…) render as
|
||||
* '#'. Default true; `false` renders stored URLs as they are (only for
|
||||
@@ -103,8 +112,9 @@ function withHeadingIds(
|
||||
* <TableOfContents items={extractHeadings(page.content)} label={toc.label} /> // /client
|
||||
* <RenderRichText data={page.content} headingIds={{ className: 'scroll-mt-24' }} />
|
||||
*/
|
||||
export function RenderRichText({ className, converters, data: raw, headingIds, safeLinks = true }: RenderRichTextProps) {
|
||||
export function RenderRichText({ className, converters: own, data: raw, headingIds, lightbox, safeLinks = true }: RenderRichTextProps) {
|
||||
if (!raw) {return null}
|
||||
const converters = lightbox ? withLightboxUploads(own, lightbox === true ? {} : lightbox) : own
|
||||
// javascript:/data: link URLs from stored content never reach an href
|
||||
const data = safeLinks ? sanitizeRichTextLinks(raw) : raw
|
||||
if (headingIds) {
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
import type { JSXConverters, JSXConvertersFunction } from '@payloadcms/richtext-lexical/react'
|
||||
import type { ReactNode } from 'react'
|
||||
|
||||
import type { LightboxImageOptions } from '../lightbox/lightboxImage.js'
|
||||
|
||||
import { lightboxImage } from '../lightbox/lightboxImage.js'
|
||||
import { LightboxTrigger } from '../lightbox/LightboxProvider.js'
|
||||
|
||||
export type RichTextLightboxOptions = {
|
||||
/**
|
||||
* Images of one rich text browse together under this group. Default
|
||||
* 'richtext' — every rich text on the page is one gallery; pass a different
|
||||
* group per field to keep them apart, or `false` to open each image alone.
|
||||
*/
|
||||
group?: false | string
|
||||
/** Passed to lightboxImage: `size` (src fallback), `sizes`, `srcSet`. */
|
||||
image?: Pick<LightboxImageOptions, 'size' | 'sizes' | 'srcSet'>
|
||||
/** Class on each trigger button (e.g. Tailwind `my-6 block`). */
|
||||
triggerClassName?: string
|
||||
}
|
||||
|
||||
type UploadNode = { fields?: { alt?: unknown; caption?: unknown } | null; value?: unknown }
|
||||
|
||||
/**
|
||||
* Wraps every image upload of a rich text in <LightboxTrigger>, on top of the
|
||||
* project's converters: your own `upload` converter still renders the inline
|
||||
* image (Payload's default otherwise); only the click-to-enlarge button is
|
||||
* added around it. Files that aren't images (PDF, video) are left as they are.
|
||||
*
|
||||
* <RenderRichText data={post.content} lightbox /> // the shortcut
|
||||
* <RichText data={…} converters={withLightboxUploads(myConverters)} /> // your own renderer
|
||||
*/
|
||||
export function withLightboxUploads(converters?: JSXConvertersFunction, options: RichTextLightboxOptions = {}): JSXConvertersFunction {
|
||||
const group = options.group === false ? undefined : (options.group ?? 'richtext')
|
||||
return (args) => {
|
||||
const base: JSXConverters = converters ? converters(args) : args.defaultConverters
|
||||
const inner = base.upload
|
||||
return {
|
||||
...base,
|
||||
upload: (props: { node: UploadNode }) => {
|
||||
const rendered = typeof inner === 'function' ? (inner as (p: typeof props) => ReactNode)(props) : null
|
||||
const { fields, value } = props.node
|
||||
const alt = typeof fields?.alt === 'string' && fields.alt ? fields.alt : undefined
|
||||
const caption = typeof fields?.caption === 'string' && fields.caption ? fields.caption : undefined
|
||||
const image = lightboxImage(value, { ...options.image, ...(alt ? { alt } : {}), ...(caption ? { caption } : {}) })
|
||||
if (!image || rendered === null || rendered === undefined) {return rendered}
|
||||
return (
|
||||
<LightboxTrigger className={options.triggerClassName} {...(group ? { group } : {})} image={image}>
|
||||
{rendered}
|
||||
</LightboxTrigger>
|
||||
)
|
||||
},
|
||||
} as JSXConverters
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -292,7 +292,7 @@ export const ipalKit = (options: IpalOptions): Plugin => {
|
||||
}),
|
||||
buildSiteIntegrations({ additionalFields: options.integrationsFields }),
|
||||
buildCookieSettings(),
|
||||
buildNotifications(),
|
||||
buildNotifications({ lightbox: options.lightbox === true }),
|
||||
]
|
||||
// A global feeds every page's layout — revalidate the site on save.
|
||||
const revalidateGlobal = options.revalidatePath ? buildGlobalRevalidateHook({ revalidatePath: options.revalidatePath }) : null
|
||||
|
||||
@@ -98,6 +98,16 @@ export type IpalOptions = {
|
||||
/** Additional fields injected into SiteIntegrations global */
|
||||
integrationsFields?: Field[]
|
||||
|
||||
/**
|
||||
* Image lightbox labels in the Notifications global (a "Lightbox" group:
|
||||
* close, previous, next, counter, dialog name, trigger name), localized per
|
||||
* language and read with getNotificationTexts(...).lightbox. Off by default —
|
||||
* the components work without it on English fallbacks and the `texts` prop;
|
||||
* turn it on so editors translate the labels. Adds columns: run a migration
|
||||
* on Postgres. See docs/lightbox.md.
|
||||
*/
|
||||
lightbox?: boolean
|
||||
|
||||
/**
|
||||
* System-page assignments (homepage, privacy, cookies) in SiteSettings.
|
||||
* Provide the slug of the client's Pages collection to enable.
|
||||
|
||||
@@ -225,6 +225,7 @@ describe('one-call helpers — layout, page, GEO routes', () => {
|
||||
expect(shell.turnstileSiteKey).toBeNull()
|
||||
expect(shell.consent.buttons.acceptAll).toEqual(expect.any(String))
|
||||
expect(shell.formTexts).toMatchObject({ next: 'Next', stepOf: 'Step {current} of {total}' })
|
||||
expect(shell.lightboxTexts).toMatchObject({ close: 'Close', counter: '{current} / {total}' })
|
||||
expect(shell.jsonLd.map((n) => n['@type'])).toEqual(['WebSite', 'Organization'])
|
||||
expect(shell.jsonLd.every((n) => !('@context' in n))).toBe(true)
|
||||
const custom = createContentHelpers({ baseUrl: 'https://acme.pl', config: configPromise, i18n, siteJsonLd: false })
|
||||
|
||||
@@ -0,0 +1,287 @@
|
||||
// @vitest-environment happy-dom
|
||||
import { act, createElement, type ReactElement } from 'react'
|
||||
import { createRoot, type Root } from 'react-dom/client'
|
||||
import { renderToStaticMarkup } from 'react-dom/server'
|
||||
import { afterEach, beforeEach, describe, expect, test } from 'vitest'
|
||||
|
||||
import { buildNotifications } from '../src/globals/Notifications/index.js'
|
||||
import { LightboxDialog } from '../src/modules/lightbox/LightboxDialog.js'
|
||||
import { lightboxImage } from '../src/modules/lightbox/lightboxImage.js'
|
||||
import { LightboxProvider, LightboxTrigger, useLightbox } from '../src/modules/lightbox/LightboxProvider.js'
|
||||
import { formatLightboxCounter, LIGHTBOX_FALLBACK, lightboxIndex, resolveLightboxTexts } from '../src/modules/lightbox/texts.js'
|
||||
import { RenderRichText } from '../src/modules/richtext/RenderRichText.js'
|
||||
|
||||
// Loosely typed createElement: children passed positionally, as JSX would.
|
||||
const h = createElement as unknown as (type: unknown, props?: null | object, ...children: unknown[]) => ReactElement
|
||||
|
||||
;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true
|
||||
|
||||
const photo = (n: number) => ({ alt: `Photo ${n}`, src: `/p${n}.jpg` })
|
||||
|
||||
let container: HTMLDivElement
|
||||
let root: Root
|
||||
|
||||
beforeEach(() => {
|
||||
container = document.createElement('div')
|
||||
document.body.appendChild(container)
|
||||
root = createRoot(container)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
act(() => root.unmount())
|
||||
container.remove()
|
||||
document.documentElement.removeAttribute('data-a11y-motion')
|
||||
})
|
||||
|
||||
const render = (node: React.ReactNode) => act(() => root.render(node))
|
||||
const dialog = () => document.querySelector<HTMLElement>('[role="dialog"]')
|
||||
const shown = () => dialog()?.querySelector('img')?.getAttribute('src')
|
||||
const counter = () => document.querySelector('[data-ipal="lightbox-counter"]')?.textContent
|
||||
const triggers = () => [...container.querySelectorAll<HTMLButtonElement>('[data-ipal="lightbox-trigger"]')]
|
||||
const key = (k: string, init: KeyboardEventInit = {}) =>
|
||||
act(() => {
|
||||
document.dispatchEvent(new KeyboardEvent('keydown', { bubbles: true, key: k, ...init }))
|
||||
})
|
||||
const click = (el: Element | null | undefined) =>
|
||||
act(() => {
|
||||
;(el as HTMLElement).click()
|
||||
})
|
||||
|
||||
const gallery = (props: Record<string, unknown> = {}) =>
|
||||
h(
|
||||
LightboxProvider,
|
||||
{ texts: { close: 'Zamknij', open: 'Powiększ' }, ...props },
|
||||
h(LightboxTrigger, { group: 'g', image: photo(1) }, h('img', { alt: '', src: '/t1.jpg' })),
|
||||
h(LightboxTrigger, { group: 'g', image: photo(2) }, h('img', { alt: '', src: '/t2.jpg' })),
|
||||
h(LightboxTrigger, { group: 'g', image: { ...photo(3), caption: 'Third' } }, h('img', { alt: '', src: '/t3.jpg' })),
|
||||
h(LightboxTrigger, { image: photo(9) }, h('img', { alt: '', src: '/t9.jpg' })),
|
||||
)
|
||||
|
||||
describe('lightbox helpers', () => {
|
||||
test('lightboxImage: srcSet from Payload sizes + original, size as src, caption, alt', () => {
|
||||
const doc = {
|
||||
alt: 'Sofa',
|
||||
caption: 'Living room',
|
||||
height: 2000,
|
||||
mimeType: 'image/jpeg',
|
||||
sizes: {
|
||||
card: { height: 512, url: '/card.jpg', width: 768 },
|
||||
empty: { height: null, url: null, width: null },
|
||||
hero: { height: 1080, url: '/hero.jpg', width: 1920 },
|
||||
},
|
||||
url: '/full.jpg',
|
||||
width: 3000,
|
||||
}
|
||||
expect(lightboxImage(doc, { size: 'hero' })).toEqual({
|
||||
alt: 'Sofa',
|
||||
caption: 'Living room',
|
||||
height: 1080,
|
||||
sizes: '100vw',
|
||||
src: '/hero.jpg',
|
||||
srcSet: '/card.jpg 768w, /hero.jpg 1920w, /full.jpg 3000w',
|
||||
width: 1920,
|
||||
})
|
||||
expect(lightboxImage(doc, { alt: 'Other', caption: false, srcSet: false })).toEqual({ alt: 'Other', height: 2000, src: '/full.jpg', width: 3000 })
|
||||
expect(lightboxImage({ mimeType: 'video/mp4', url: '/v.mp4' })).toBeNull()
|
||||
expect(lightboxImage({ mimeType: 'application/pdf', url: '/a.pdf' })).toBeNull()
|
||||
expect(lightboxImage(42)).toBeNull()
|
||||
})
|
||||
|
||||
test('index wraps or clamps, counter and texts fall back per field', () => {
|
||||
expect(lightboxIndex(2, 1, 3)).toBe(0)
|
||||
expect(lightboxIndex(0, -1, 3)).toBe(2)
|
||||
expect(lightboxIndex(2, 1, 3, false)).toBe(2)
|
||||
expect(lightboxIndex(0, -1, 3, false)).toBe(0)
|
||||
expect(formatLightboxCounter('{current} z {total}', 2, 5)).toBe('2 z 5')
|
||||
expect(resolveLightboxTexts({ close: 'Zamknij', next: ' ', previous: null })).toEqual({ ...LIGHTBOX_FALLBACK, close: 'Zamknij' })
|
||||
})
|
||||
|
||||
test('Notifications gets the Lightbox group only when asked', () => {
|
||||
const names = (g: ReturnType<typeof buildNotifications>) => g.fields.map((f) => ('name' in f ? f.name : null))
|
||||
expect(names(buildNotifications())).not.toContain('lightbox')
|
||||
expect(names(buildNotifications({ lightbox: true }))).toContain('lightbox')
|
||||
})
|
||||
})
|
||||
|
||||
describe('lightbox behaviour', () => {
|
||||
test('nothing in the DOM until opened; triggers are labelled buttons', () => {
|
||||
render(gallery())
|
||||
expect(dialog()).toBeNull()
|
||||
const [first] = triggers()
|
||||
expect(first.tagName).toBe('BUTTON')
|
||||
expect(first.getAttribute('aria-haspopup')).toBe('dialog')
|
||||
expect(first.getAttribute('aria-label')).toBe('Powiększ: Photo 1')
|
||||
})
|
||||
|
||||
test('open: accessible dialog at the clicked image, focus on Close, page scroll locked', () => {
|
||||
render(gallery())
|
||||
click(triggers()[1])
|
||||
const d = dialog()!
|
||||
expect(d.getAttribute('aria-modal')).toBe('true')
|
||||
expect(d.getAttribute('aria-label')).toBe(LIGHTBOX_FALLBACK.dialog)
|
||||
expect(shown()).toBe('/p2.jpg')
|
||||
expect(d.querySelector('img')?.getAttribute('alt')).toBe('Photo 2')
|
||||
expect(counter()).toBe('2 / 3')
|
||||
expect(document.activeElement?.getAttribute('aria-label')).toBe('Zamknij')
|
||||
expect(document.documentElement.style.overflow).toBe('hidden')
|
||||
})
|
||||
|
||||
test('keyboard: arrows browse the group with wrap-around, Home/End jump', () => {
|
||||
render(gallery())
|
||||
click(triggers()[1])
|
||||
key('ArrowRight')
|
||||
expect(shown()).toBe('/p3.jpg')
|
||||
expect(dialog()!.querySelector('figcaption')?.textContent).toBe('Third')
|
||||
key('ArrowRight')
|
||||
expect(shown()).toBe('/p1.jpg')
|
||||
key('ArrowLeft')
|
||||
expect(shown()).toBe('/p3.jpg')
|
||||
key('Home')
|
||||
expect(counter()).toBe('1 / 3')
|
||||
key('End')
|
||||
expect(counter()).toBe('3 / 3')
|
||||
})
|
||||
|
||||
test('buttons and swipe browse; loop={false} stops at the ends', () => {
|
||||
render(gallery({ loop: false }))
|
||||
click(triggers()[0])
|
||||
const prev = document.querySelector<HTMLButtonElement>('[data-ipal="lightbox-previous"]')!
|
||||
expect(prev.disabled).toBe(true)
|
||||
click(document.querySelector('[data-ipal="lightbox-next"]'))
|
||||
expect(shown()).toBe('/p2.jpg')
|
||||
const figure = document.querySelector('[data-ipal="lightbox-figure"]')!
|
||||
const swipe = (from: number, to: number) =>
|
||||
act(() => {
|
||||
figure.dispatchEvent(new MouseEvent('pointerdown', { bubbles: true, clientX: from, clientY: 100 }))
|
||||
figure.dispatchEvent(new MouseEvent('pointerup', { bubbles: true, clientX: to, clientY: 100 }))
|
||||
})
|
||||
swipe(300, 100) // swipe left → next
|
||||
expect(shown()).toBe('/p3.jpg')
|
||||
swipe(300, 100) // already last, no loop
|
||||
expect(shown()).toBe('/p3.jpg')
|
||||
swipe(100, 300) // swipe right → previous
|
||||
expect(shown()).toBe('/p2.jpg')
|
||||
swipe(100, 110) // too short
|
||||
expect(shown()).toBe('/p2.jpg')
|
||||
})
|
||||
|
||||
test('Esc closes, focus returns to the trigger, scroll restored', () => {
|
||||
render(gallery())
|
||||
const trigger = triggers()[2]
|
||||
click(trigger)
|
||||
key('Escape')
|
||||
expect(dialog()).toBeNull()
|
||||
expect(document.activeElement).toBe(trigger)
|
||||
expect(document.documentElement.style.overflow).toBe('')
|
||||
})
|
||||
|
||||
test('Close button and backdrop close it too', () => {
|
||||
render(gallery())
|
||||
click(triggers()[0])
|
||||
click(document.querySelector('[data-ipal="lightbox-close"]'))
|
||||
expect(dialog()).toBeNull()
|
||||
click(triggers()[0])
|
||||
click(document.querySelector('[data-ipal="lightbox-backdrop"]'))
|
||||
expect(dialog()).toBeNull()
|
||||
})
|
||||
|
||||
test('focus trap: Tab and Shift+Tab cycle inside the dialog', () => {
|
||||
render(gallery())
|
||||
click(triggers()[0])
|
||||
const close = document.querySelector<HTMLElement>('[data-ipal="lightbox-close"]')!
|
||||
const prev = document.querySelector<HTMLElement>('[data-ipal="lightbox-previous"]')!
|
||||
expect(document.activeElement).toBe(close)
|
||||
key('Tab')
|
||||
expect(document.activeElement).toBe(prev)
|
||||
key('Tab', { shiftKey: true })
|
||||
expect(document.activeElement).toBe(close)
|
||||
})
|
||||
|
||||
test('a trigger without a group opens alone — no counter, no arrows', () => {
|
||||
render(gallery())
|
||||
click(triggers()[3])
|
||||
expect(shown()).toBe('/p9.jpg')
|
||||
expect(counter()).toBeUndefined()
|
||||
expect(document.querySelector('[data-ipal="lightbox-next"]')).toBeNull()
|
||||
})
|
||||
|
||||
test('a standalone trigger brings its own viewer', () => {
|
||||
render(h(LightboxTrigger, { image: photo(5) }, h('img', { alt: '', src: '/t5.jpg' })))
|
||||
click(triggers()[0])
|
||||
expect(shown()).toBe('/p5.jpg')
|
||||
expect(document.activeElement?.getAttribute('aria-label')).toBe(LIGHTBOX_FALLBACK.close)
|
||||
})
|
||||
|
||||
test('useLightbox opens any list; renderImage and renderDialog replace the parts', () => {
|
||||
function Custom() {
|
||||
const box = useLightbox()
|
||||
return h('button', { id: 'all', onClick: () => box.open([photo(1), photo(2)], 1) }, 'all')
|
||||
}
|
||||
render(
|
||||
h(
|
||||
LightboxProvider,
|
||||
{ renderImage: ({ imgProps }: { imgProps: object }) => h('img', { ...imgProps, 'data-custom': 'yes' }) },
|
||||
h(Custom),
|
||||
),
|
||||
)
|
||||
click(container.querySelector('#all'))
|
||||
expect(dialog()!.querySelector('img')?.getAttribute('data-custom')).toBe('yes')
|
||||
expect(counter()).toBe('2 / 2')
|
||||
key('Escape')
|
||||
|
||||
render(h(LightboxProvider, { renderDialog: (p: { images: { alt: string }[]; index: number }) => h('div', { id: 'mine' }, p.images[p.index].alt) }, h(Custom)))
|
||||
click(container.querySelector('#all'))
|
||||
expect(container.querySelector('#mine')?.textContent).toBe('Photo 2')
|
||||
})
|
||||
|
||||
test('reduced motion: no transition; otherwise a fade', () => {
|
||||
const noop = () => {}
|
||||
render(h(LightboxDialog, { images: [photo(1)], index: 0, onClose: noop, onIndexChange: noop }))
|
||||
expect(dialog()!.style.transition).toContain('opacity')
|
||||
act(() => root.render(null))
|
||||
document.documentElement.setAttribute('data-a11y-motion', 'reduce')
|
||||
render(h(LightboxDialog, { images: [photo(1)], index: 0, onClose: noop, onIndexChange: noop }))
|
||||
expect(dialog()!.style.transition).toBe('')
|
||||
})
|
||||
|
||||
test('unstyled: no inline styles, classNames applied', () => {
|
||||
const noop = () => {}
|
||||
render(h(LightboxDialog, { classNames: { close: 'x', dialog: 'box' }, images: [photo(1)], index: 0, onClose: noop, onIndexChange: noop, unstyled: true }))
|
||||
expect(dialog()!.getAttribute('style')).toBeNull()
|
||||
expect(dialog()!.className).toBe('box')
|
||||
expect(document.querySelector('[data-ipal="lightbox-close"]')!.className).toBe('x')
|
||||
})
|
||||
})
|
||||
|
||||
describe('RenderRichText lightbox', () => {
|
||||
const upload = (value: object) => ({ type: 'upload', fields: null, format: '', relationTo: 'media', value, version: 3 })
|
||||
const data = {
|
||||
root: {
|
||||
type: 'root',
|
||||
children: [
|
||||
upload({ alt: 'Chart', height: 600, mimeType: 'image/png', url: '/chart.png', width: 800 }),
|
||||
upload({ filename: 'a.pdf', mimeType: 'application/pdf', url: '/a.pdf' }),
|
||||
],
|
||||
direction: 'ltr',
|
||||
format: '',
|
||||
indent: 0,
|
||||
version: 1,
|
||||
},
|
||||
} as never
|
||||
|
||||
test('off by default; `lightbox` wraps images only, project upload converter kept', () => {
|
||||
expect(renderToStaticMarkup(h(RenderRichText, { data }))).not.toContain('lightbox-trigger')
|
||||
const html = renderToStaticMarkup(
|
||||
h(RenderRichText, {
|
||||
converters: ({ defaultConverters }: { defaultConverters: object }) => ({
|
||||
...defaultConverters,
|
||||
upload: ({ node }: { node: { value: unknown } }) => h('img', { className: 'mine', src: (node.value as { url: string }).url }),
|
||||
}),
|
||||
data,
|
||||
lightbox: { group: 'post' },
|
||||
}),
|
||||
)
|
||||
expect(html).toMatch(/<button[^>]*aria-label="Enlarge image: Chart"[^>]*data-group="post"[^>]*data-ipal="lightbox-trigger"[^>]*><img class="mine" src="\/chart.png"\/><\/button>/)
|
||||
expect(html.match(/lightbox-trigger/g)).toHaveLength(1)
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user