Files
ipal-kit/docs/media.md
T
Radosław SmolińskiandClaude Opus 5.5 2d9f3e15d4 Docs in English (part 1), seeding guide, Coolify deployment
- Translate to English every doc the code branches did not touch: AGENT.md,
  developer guide, vibe, CHANGELOG, docs index, module pages, all skills
  except ipal-seo-check (14 pages follow after the security/SEO merge).
  Placeholder marker is now [TO FILL: …]; skill resources renamed to
  section-code.md / nav-code.md. AGENT.md and the ipal-skills pointer
  block say the docs are in English.
- docs/seeding.md: create-only, natural keys, never delete, no users or
  secrets, empty-field globals, fallbackLocale: false, dry run, backup and
  restore, production update guard, seeds vs migrations, Coolify Terminal.
  Seed templates gain --dry-run, the SEED_UPDATE production guard
  (IPAL_SEED_ALLOW_PROD_UPDATE), skip of edited records and a summary.
  "Seeding on production" rule block in AGENT.md.
- Coolify is the single deployment path (deployment, env, developer guide,
  ipal-setup): build vs runtime env, migrations on container start
  (prodMigrations), health check and rolling updates, rollback, backups and
  restore, DNS/Let's Encrypt/CAA. R2: custom domain needs a Cloudflare zone;
  default is media served by the app (R2_PUBLIC_URL empty).
- docsConsistency: no Polish prose outside code/quoted data (pending pages
  listed); IPAL_* names may also be read by shipped skill templates.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-22 17:39:03 +02:00

7.7 KiB
Raw Blame History

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 (R2, buildImagesConfig, MediaPreconnect, YouTubeEmbed), 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

// 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.

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:

// 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.

MEDIA_SIZES — starting points for sizes: full (100vw), half, third, quarter, thumb (160px). You can replace any value with your own string.