- docs/lightbox.md: setup, sizes, styling, overrides, migration from a hand-made modal or glightbox - AGENT.md (§6.9, §7 catalog, §7.1, §12), ipal-reference (option, wiring, api.md section), ipal-site and ipal-block steps, PROGRAMISTA §6 row 48 - ipal-audit warns about lightbox libraries - notifications.md, richtext.md, media.md, frontend.md, README index Co-Authored-By: Claude Opus 5.5 <[email protected]>
157 lines
8.0 KiB
Markdown
157 lines
8.0 KiB
Markdown
# media — the Media collection: file names, oversized uploads, placeholders, `<Media>` props
|
||
|
||
Building blocks for the project's upload collection (usually `media`) and for your own `<Media>` component.
|
||
The plugin **does not add** a Media collection or a component — the project assembles them from these parts. Everything
|
||
comes from the main entry `@intecion/ipal-kit`.
|
||
|
||
Related: [storage.md](./storage.md) (R2, `buildImagesConfig`, `MediaPreconnect`, `YouTubeEmbed`),
|
||
[security.md](./security.md) (`buildUploadSecurityHeaders`).
|
||
|
||
| Export | What it is | Where |
|
||
|---|---|---|
|
||
| `normalizeFilenameHook` | `beforeOperation` — cleans the file name | `hooks.beforeOperation` |
|
||
| `normalizeFilename(name)` | the same function, without the hook | anywhere |
|
||
| `buildOptimizeUploadHook(options?)` | `beforeOperation` — safety net for oversized files | `hooks.beforeOperation` |
|
||
| `buildOptimizeUploadField(name?)` | consent checkbox "Optimize this upload" | `fields` |
|
||
| `buildMediaPlaceholderHook({ field?, size? })` | `beforeOperation` — blur + dominant color | `hooks.beforeOperation` |
|
||
| `buildMediaPlaceholderField(name?)` | hidden `placeholder` group | `fields` |
|
||
| `mediaImageProps(resource, options?)` | `next/image` props | `<Media>` component |
|
||
| `videoProps(resource, options?)` | `<video>` attributes | `<Media>` component |
|
||
| `MEDIA_SIZES` | ready `sizes` values | `<Media>` component |
|
||
|
||
Types: `OptimizeUploadOptions`, `MediaImageOptions`, `MediaImageProps`, `VideoMode`, `VideoProps`.
|
||
|
||
## Full collection
|
||
|
||
```ts
|
||
// collections/Media.ts
|
||
import type { CollectionConfig } from 'payload'
|
||
import {
|
||
buildMediaPlaceholderField,
|
||
buildMediaPlaceholderHook,
|
||
buildOptimizeUploadField,
|
||
buildOptimizeUploadHook,
|
||
normalizeFilenameHook,
|
||
} from '@intecion/ipal-kit'
|
||
|
||
export const Media: CollectionConfig = {
|
||
slug: 'media',
|
||
access: { read: () => true }, // public files; required when media are served by the app (/api/media/file/…)
|
||
upload: { focalPoint: true, mimeTypes: ['image/*', 'application/pdf', 'video/mp4', 'video/webm'] },
|
||
hooks: {
|
||
// order: name first, then any conversion, the placeholder last from the final file
|
||
beforeOperation: [normalizeFilenameHook, buildOptimizeUploadHook(), buildMediaPlaceholderHook()],
|
||
},
|
||
fields: [
|
||
{ name: 'alt', type: 'text', required: true, localized: true },
|
||
buildOptimizeUploadField(), // checkbox in the sidebar
|
||
buildMediaPlaceholderField(), // hidden: placeholder.blurDataURL, placeholder.color
|
||
],
|
||
}
|
||
```
|
||
|
||
`buildOptimizeUploadHook` and `buildMediaPlaceholderHook` use the `sharp` passed to
|
||
`buildConfig({ sharp })` — the plugin does not import it. Postgres with migrations: new fields →
|
||
`pnpm payload migrate:create`.
|
||
|
||
**Turn off / override:** every part is opt-in and independent — if you don't wire a hook, nothing happens.
|
||
Change field names with a parameter (`consentField`, `field`, `name`), thresholds with options; instead of the hook you can
|
||
use the bare function (`normalizeFilename`) in your own hook.
|
||
|
||
## File names — `normalizeFilenameHook`
|
||
|
||
Slugifies the name (diacritics, spaces, letter case), keeps the extension (lowercase):
|
||
|
||
```
|
||
"Zdjęcie jeden nad morzem.jpg" → "zdjecie-jeden-nad-morzem.jpg"
|
||
"Faktura #12 (2024).PDF" → "faktura-12-2024.pdf"
|
||
"###.png" → "plik.png" (empty name → "plik")
|
||
```
|
||
|
||
Runs on `create` and on `update` with a file. It runs BEFORE the storage layer, so the clean name goes
|
||
both to the database and to disk / R2. Result: clean, portable URLs without `%20` and characters that break caching.
|
||
|
||
## Oversized files — `buildOptimizeUploadHook` (with consent)
|
||
|
||
**The developer / editor prepares the files.** The hook only catches mistakes (an 8 MB phone photo,
|
||
a 300 MB raw video) and **changes nothing without consent**:
|
||
|
||
1. JPG/PNG over the limit → save stopped (400), message e.g. "Image is 9.3 MB (limit 1.5 MB),
|
||
4000 px wide (limit 2560 px). Tick *Optimize this upload*…".
|
||
2. The editor ticks the checkbox and saves again → **WebP**, width ≤ `maxImageWidth`, rotated by
|
||
EXIF, **metadata (EXIF/GPS) removed**; extension → `.webp`. The checkbox goes back to "unticked".
|
||
When conversion did not make the file smaller and the width was fine — the original stays.
|
||
3. Video over the limit → stopped with export instructions (MP4 H.264, 720p–1080p, 2–4 Mbit/s, fast
|
||
start). **Video is never converted.**
|
||
|
||
| Type | Behavior |
|
||
|---|---|
|
||
| JPG, PNG within the limit | unchanged |
|
||
| JPG, PNG over the limit | stop → with consent WebP + resize + no metadata |
|
||
| GIF, SVG, WebP, AVIF, PDF, animated PNG | always unchanged |
|
||
| video over the limit | stop with instructions (no conversion) |
|
||
|
||
| Option | Default |
|
||
|---|---|
|
||
| `maxImageBytes` | 1.5 MB |
|
||
| `maxImageWidth` | 2560 px (also the target width) |
|
||
| `quality` | 82 (lossy WebP: JPG, PNG with `png: 'lossy'`) |
|
||
| `png` | `'lossless'` (screenshots, logos); `'lossy'` = smaller, risk of blurry text |
|
||
| `maxVideoBytes` | 20 MB; `false` = no limit |
|
||
| `consentField` | `'optimizeOnUpload'` — must match `buildOptimizeUploadField(name)` |
|
||
|
||
Without `sharp` in the config: the width is not checked (only the size), and consenting to conversion ends
|
||
with a 500 error "Image optimization needs sharp". The collection must allow `image/webp`
|
||
(`image/*` allows it).
|
||
|
||
## Placeholders — `buildMediaPlaceholderHook` + `buildMediaPlaceholderField`
|
||
|
||
On upload of a raster image (AVIF, GIF, JPEG, PNG, WebP) it computes a ~16 px preview (base64 WebP,
|
||
a few hundred bytes) and the dominant color. It saves them in the hidden `placeholder` group
|
||
(`blurDataURL`, `color`); images with transparency get `color: null`. An error never blocks the
|
||
upload (warning in the log). Without `sharp` — nothing. Existing images get a placeholder only after
|
||
being saved again with a new file.
|
||
|
||
Hook options: `field` (default `'placeholder'`), `size` (default 16 px).
|
||
|
||
## `<Media>` in the project — `mediaImageProps`, `videoProps`, `MEDIA_SIZES`
|
||
|
||
The plugin computes the performance details; the project keeps the markup and the look:
|
||
|
||
```tsx
|
||
// src/components/ui/Media.tsx
|
||
import Image from 'next/image'
|
||
import { MEDIA_SIZES, mediaImageProps, videoProps } from '@intecion/ipal-kit'
|
||
|
||
export function Media({ resource, priority, className }: Props) {
|
||
const img = mediaImageProps(resource, { sizes: MEDIA_SIZES.half, priority })
|
||
if (img) return <Image {...img} className={className} />
|
||
const video = videoProps(resource, { mode: 'background' })
|
||
if (video) return <video {...video} className={className} />
|
||
return null
|
||
}
|
||
```
|
||
|
||
**`mediaImageProps(resource, { alt?, sizes?, priority?, placeholderColor? })`** → `next/image`
|
||
props or `null` (video, PDF, a bare id, no `width`/`height`):
|
||
- `width`/`height` from the document (no layout shift), `alt` from the document (override: `alt`, `''` for decoration);
|
||
- `sizes` defaults to `'100vw'` — give the real width (`MEDIA_SIZES`);
|
||
- `priority: true` (one LCP image per page) → `loading="eager"`, `fetchPriority="high"`, `preload`
|
||
(Next 16); otherwise `loading="lazy"`;
|
||
- focal point (≠ 50/50) → `style.objectPosition`;
|
||
- `placeholder.blurDataURL` → `placeholder="blur"`;
|
||
- `placeholder.color` → `style.backgroundColor` per `placeholderColor`: `'auto'` (default — JPEG only,
|
||
because the color stays under transparent pixels), `true` (always), `false` (never).
|
||
|
||
**`videoProps(resource, { mode?, poster?, reducedMotion? })`** → `<video>` attributes or `null`:
|
||
- `'player'` (default): `controls`, `preload="none"`, `poster`;
|
||
- `'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.
|