Media performance tools: image/video props, upload placeholders, images preset, YouTube facade

Headless helpers for the project's own <Media> (look stays in the project):
- mediaImageProps: dimensions from the doc (no CLS), lazy by default, LCP image
  gets preload + fetchPriority=high + eager (Next 16 replaced 'priority'),
  focal point → object-position, blur placeholder + dominant colour.
- MEDIA_SIZES suggestions for 'sizes' (any string still works).
- videoProps: 'background' (muted loop, respects reduced motion) or 'player'
  (controls, preload=none, poster).
- buildMediaPlaceholderHook/Field: tiny WebP blur + dominant colour at upload
  via the configured sharp (no new dependency).
- buildImagesConfig: AVIF/WebP, R2 remotePatterns, 31-day cache.
- <YouTubeEmbed> (/client): poster + button, youtube-nocookie iframe on click.
- buildCsp youtube allows the i.ytimg.com poster. kod-sekcji Media template
  uses the helpers.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
2026-10-16 03:19:38 +02:00
co-authored by Claude Opus 5.5
parent f7466cf77f
commit 55fc27a13f
13 changed files with 414 additions and 25 deletions
+1
View File
@@ -62,6 +62,7 @@ export {
export type { AlternateLinks, LanguageSwitcherClassNames } from '../modules/i18n/index.js'
export { IntegrationStatusBanner } from '../modules/integrations/IntegrationStatusBanner.js'
export { LocaleView } from '../modules/pages/LocaleView.js'
export { YouTubeEmbed } from '../modules/storage/YouTubeEmbed.js'
export { Turnstile } from '../modules/turnstile/client.js'
export { TurnstileProvider, useTurnstile } from '../modules/turnstile/client.js'
export type { TurnstileProps } from '../modules/turnstile/client.js'
+11 -1
View File
@@ -138,6 +138,14 @@ export type {
export { createMcpRoute } from './modules/mcp/index.js'
export { buildOptimizeUploadField, buildOptimizeUploadHook, normalizeFilename, normalizeFilenameHook } from './modules/media/index.js'
export type { OptimizeUploadOptions } from './modules/media/index.js'
export {
buildMediaPlaceholderField,
buildMediaPlaceholderHook,
MEDIA_SIZES,
mediaImageProps,
videoProps,
} from './modules/media/index.js'
export type { MediaImageOptions, MediaImageProps, VideoMode, VideoProps } from './modules/media/index.js'
export { getNotificationTexts, NOTIFICATION_FALLBACK, resolveFormMessage } from './modules/notifications/index.js'
export type { FormNotificationTexts, NotificationTexts } from './modules/notifications/index.js'
export type { PagesOption, SystemPageRole } from './modules/pages/index.js'
@@ -150,10 +158,10 @@ export {
SITE_INTEGRATIONS_SLUG,
SITE_SETTINGS_SLUG,
} from './modules/payload/index.js'
// Lexical → Markdown (pure, no React) — for AI-readable output.
export { lexicalToMarkdown } from './modules/richtext/index.js'
export { buildSecurityHeaders, buildUploadSecurityHeaders } from './modules/security/index.js'
export { buildCsp } from './modules/security/index.js'
export type { BuildCspArgs } from './modules/security/index.js'
export type { BuildSecurityHeadersArgs, SecurityHeader } from './modules/security/index.js'
@@ -203,6 +211,8 @@ export type { SitemapRouteOptions, SitemapStyleOptions } from './modules/seo/ind
export { clientIp, setRateLimitStore } from './modules/shared/rateLimit.js'
export type { ClientIpOptions, RateLimitStore } from './modules/shared/rateLimit.js'
export { buildSlugField, toSlug } from './modules/slug/index.js'
export { buildImagesConfig } from './modules/storage/buildImagesConfig.js'
export type { ImagesConfig } from './modules/storage/buildImagesConfig.js'
export { buildR2Storage } from './modules/storage/index.js'
// Imported from the file, not the turnstile barrel — that one re-exports verify,
// which imports 'server-only'.
+3
View File
@@ -1,3 +1,6 @@
export { MEDIA_SIZES, mediaImageProps, videoProps } from './mediaProps.js'
export type { MediaImageOptions, MediaImageProps, VideoMode, VideoProps } from './mediaProps.js'
export { normalizeFilename, normalizeFilenameHook } from './normalizeFilename.js'
export { buildOptimizeUploadField, buildOptimizeUploadHook } from './optimizeUpload.js'
export type { OptimizeUploadOptions } from './optimizeUpload.js'
export { buildMediaPlaceholderField, buildMediaPlaceholderHook } from './placeholder.js'
+136
View File
@@ -0,0 +1,136 @@
/**
* Props for the project's own <Media> — the plugin computes the performance
* details, the project keeps the markup and the look. Nothing here renders,
* styles or limits anything: every value can be overridden by the caller.
*
* // src/components/ui/Media.tsx
* 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} />
*/
type MediaDoc = {
alt?: null | string
focalX?: null | number
focalY?: null | number
height?: null | number
mimeType?: null | string
placeholder?: { blurDataURL?: null | string; color?: null | string } | null
url?: null | string
width?: null | number
}
/**
* Starting points for `sizes` — how wide the image is ON SCREEN at each
* breakpoint, so the browser downloads the right file instead of a full-width
* one. Suggestions only: pass any string that matches the actual layout.
*/
export const MEDIA_SIZES = {
/** Full-bleed hero / background. */
full: '100vw',
/** Half the container from md up (two-column hero, image + text). */
half: '(min-width: 768px) 50vw, 100vw',
/** Card in a 3-column grid from lg, 2 from md. */
third: '(min-width: 1024px) 33vw, (min-width: 768px) 50vw, 100vw',
/** Card in a 4-column grid. */
quarter: '(min-width: 1024px) 25vw, (min-width: 640px) 50vw, 100vw',
/** Thumbnail / avatar / logo up to ~160 px. */
thumb: '160px',
} as const
export type MediaImageOptions = {
/** Alt override (decorative images: ''). Default: the document's alt. */
alt?: string
/**
* The LCP image (first visible image — usually the hero): loads eagerly with
* fetchPriority="high". Exactly one per page; everything else is lazy.
*/
priority?: boolean
/** How wide it is on screen. Required in practice — see MEDIA_SIZES. Default '100vw'. */
sizes?: string
}
export type MediaImageProps = {
alt: string
blurDataURL?: string
fetchPriority?: 'high'
height: number
loading: 'eager' | 'lazy'
placeholder?: 'blur' | 'empty'
/** Next 16: <link rel=preload> for the LCP image (replaces the deprecated `priority`). */
preload?: boolean
sizes: string
src: string
style?: { backgroundColor?: string; objectPosition?: string }
width: number
}
const asDoc = (resource: unknown): MediaDoc | null =>
resource && typeof resource === 'object' && typeof (resource as MediaDoc).url === 'string' ? (resource as MediaDoc) : null
/**
* next/image props for an image upload, or null for anything else (video, PDF,
* a bare id). Width/height always come from the document — no layout shift.
* Focal point (upload `focalPoint: true`) becomes object-position, so a cropped
* image keeps its subject; a placeholder (buildMediaPlaceholderHook) becomes a
* blur-up and background colour.
*/
export function mediaImageProps(resource: unknown, { alt, priority = false, sizes = '100vw' }: MediaImageOptions = {}): MediaImageProps | null {
const doc = asDoc(resource)
if (!doc || doc.mimeType?.startsWith('video/')) {return null}
if (!doc.width || !doc.height) {return null} // PDF or other non-image file — link it instead
const blur = doc.placeholder?.blurDataURL ?? undefined
const color = doc.placeholder?.color ?? undefined
const hasFocal = typeof doc.focalX === 'number' && typeof doc.focalY === 'number' && !(doc.focalX === 50 && doc.focalY === 50)
const style = {
...(hasFocal ? { objectPosition: `${doc.focalX}% ${doc.focalY}%` } : {}),
...(color ? { backgroundColor: color } : {}),
}
return {
alt: alt ?? doc.alt ?? '',
height: doc.height,
sizes,
src: doc.url!,
width: doc.width,
...(priority
? { fetchPriority: 'high' as const, loading: 'eager' as const, preload: true }
: { loading: 'lazy' as const }),
...(blur ? { blurDataURL: blur, placeholder: 'blur' as const } : {}),
...(Object.keys(style).length ? { style } : {}),
}
}
export type VideoMode = 'background' | 'player'
export type VideoProps = {
autoPlay?: boolean
controls?: boolean
loop?: boolean
muted?: boolean
playsInline: true
poster?: string
preload: 'metadata' | 'none'
src: string
}
/**
* <video> attributes for a video upload, or null when it isn't one.
* - 'background': silent loop for heroes/ambience — autoplay, muted, loop, no
* controls. Pass `reducedMotion` (from a client hook) to not autoplay for
* visitors who asked for less motion.
* - 'player': a real video — controls, nothing downloaded until play
* (preload="none"), poster shown meanwhile. Default.
*/
export function videoProps(
resource: unknown,
{ mode = 'player', poster, reducedMotion = false }: { mode?: VideoMode; poster?: unknown; reducedMotion?: boolean } = {},
): null | VideoProps {
const doc = asDoc(resource)
if (!doc || !doc.mimeType?.startsWith('video/')) {return null}
const posterUrl = typeof poster === 'string' ? poster : asDoc(poster)?.url ?? undefined
const base = { playsInline: true as const, src: doc.url!, ...(posterUrl ? { poster: posterUrl } : {}) }
return mode === 'background'
? { ...base, autoPlay: !reducedMotion, loop: true, muted: true, preload: 'metadata' }
: { ...base, controls: true, preload: 'none' }
}
+62
View File
@@ -0,0 +1,62 @@
import type { CollectionBeforeOperationHook, Field } from 'payload'
import { readFile } from 'node:fs/promises'
/**
* Image placeholders computed once, at upload: a ~16 px blurred preview
* (base64 WebP, ~150–400 bytes) and the dominant colour. The page shows them
* while the real image loads — no empty box, no layout "pop" — and Next's
* `placeholder="blur"` needs exactly this. Opt-in, two pieces in the project's
* Media collection:
*
* hooks: { beforeOperation: [buildOptimizeUploadHook(), buildMediaPlaceholderHook()] },
* fields: [ …, buildMediaPlaceholderField() ],
*
* Uses the `sharp` passed to buildConfig({ sharp }) — no extra dependency.
* Existing images get placeholders when re-saved with a new file; without one
* mediaImageProps simply renders no placeholder.
*/
const FIELD = 'placeholder'
/** Hidden group holding the placeholder (read by mediaImageProps). */
export function buildMediaPlaceholderField(name: string = FIELD): Field {
return {
name,
type: 'group',
admin: { hidden: true },
fields: [
{ name: 'blurDataURL', type: 'text' },
{ name: 'color', type: 'text' },
],
}
}
type UploadFile = { data?: Buffer; mimetype: string; tempFilePath?: string }
const RASTER = new Set(['image/avif', 'image/gif', 'image/jpeg', 'image/png', 'image/webp'])
export function buildMediaPlaceholderHook({ field = FIELD, size = 16 }: { field?: string; size?: number } = {}): CollectionBeforeOperationHook {
return async ({ args, operation, req }) => {
if (operation !== 'create' && operation !== 'update') {return}
const file = req.file as undefined | UploadFile
const sharp = req.payload.config.sharp
if (!file || !sharp || !RASTER.has(file.mimetype)) {return}
const data = (args as { data?: Record<string, unknown> }).data
if (!data) {return}
try {
const buffer = file.data && file.data.length > 0 ? file.data : file.tempFilePath ? await readFile(file.tempFilePath) : undefined
if (!buffer) {return}
const tiny = await sharp(buffer).rotate().resize(size, size, { fit: 'inside' }).webp({ quality: 40 }).toBuffer()
const { dominant } = await sharp(buffer).stats()
const hex = (n: number) => Math.round(n).toString(16).padStart(2, '0')
data[field] = {
blurDataURL: `data:image/webp;base64,${tiny.toString('base64')}`,
color: `#${hex(dominant.r)}${hex(dominant.g)}${hex(dominant.b)}`,
}
} catch (err) {
// A placeholder is a nicety — never block the upload.
req.payload.logger.warn(`[ipal] media placeholder skipped: ${err instanceof Error ? err.message : String(err)}`)
}
}
}
+1
View File
@@ -93,6 +93,7 @@ export function buildCsp(args: BuildCspArgs = {}): { key: string; value: string
if (youtube) {
src['frame-src'].push('https://www.youtube.com', 'https://www.youtube-nocookie.com')
src['img-src'].push('https://i.ytimg.com') // YouTubeEmbed poster
}
if (googleMaps) {
+1 -1
View File
@@ -1,4 +1,3 @@
import { isSiteNoindex } from './siteNoindex.js'
import type { I18nConfig, LocalizedSlugs } from '../i18n/index.js'
import type { TitleOrder } from './composeTitle.js'
import type { SeoMeta } from './types.js'
@@ -6,6 +5,7 @@ import type { SeoMeta } from './types.js'
import { buildLocalizedPath } from '../i18n/index.js'
import { composeTitle } from './composeTitle.js'
import { buildHreflangAlternates } from './hreflang.js'
import { isSiteNoindex } from './siteNoindex.js'
/**
* Subset of Next.js `Metadata` this helper produces. Kept local so the plugin
+55
View File
@@ -0,0 +1,55 @@
'use client'
import { useState } from 'react'
type YouTubeEmbedProps = {
/** Classes per element; nothing is styled by default (keep the aspect ratio in your CSS). */
classNames?: Partial<Record<'button' | 'frame' | 'note' | 'poster' | 'root', string>>
/** Short text under the play button, from the panel — e.g. that playing loads YouTube. */
note?: string
/** Accessible name of the play button, from the panel ("Play: <title>"). */
playLabel: string
/**
* Poster URL — your own upload (no request to Google until play) or omit to
* use YouTube's thumbnail (i.ytimg.com, no cookies).
*/
poster?: string
/** Video title, from the panel — iframe title for screen readers. */
title: string
/** YouTube video id (the part after watch?v=). */
videoId: string
}
/**
* Lightweight YouTube: a poster and a play button until the visitor clicks —
* no ~1 MB of player JavaScript and no YouTube cookies on page load (better
* LCP, no consent problem before interaction). On click it loads the
* privacy-enhanced youtube-nocookie.com player with autoplay. Unstyled.
*/
export function YouTubeEmbed({ classNames = {}, note, playLabel, poster, title, videoId }: YouTubeEmbedProps) {
const [playing, setPlaying] = useState(false)
const id = /^[\w-]{6,20}$/.test(videoId) ? videoId : ''
if (!id) {return null}
if (playing) {
return (
<iframe
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
allowFullScreen
className={classNames.frame}
// What the YouTube player needs, nothing more (no top navigation, no forms).
sandbox="allow-scripts allow-same-origin allow-presentation allow-popups allow-popups-to-escape-sandbox"
src={`https://www.youtube-nocookie.com/embed/${id}?autoplay=1`}
title={title}
/>
)
}
return (
<div className={classNames.root}>
<img alt="" className={classNames.poster} decoding="async" loading="lazy" src={poster ?? `https://i.ytimg.com/vi/${id}/hqdefault.jpg`} />
<button aria-label={playLabel} className={classNames.button} onClick={() => setPlaying(true)} type="button">
▶
</button>
{note ? <p className={classNames.note}>{note}</p> : null}
</div>
)
}
+35
View File
@@ -0,0 +1,35 @@
type RemotePattern = { hostname: string; pathname?: string; port?: string; protocol?: 'http' | 'https' }
export type ImagesConfig = {
formats: ('image/avif' | 'image/webp')[]
minimumCacheTTL: number
remotePatterns: RemotePattern[]
}
/**
* Defaults for `next.config.ts → images`, to merge or override:
* - AVIF first, WebP fallback — ~20–50 % smaller than JPEG at the same quality;
* - remotePatterns for the media domain (R2_PUBLIC_URL) so next/image may
* optimize R2 files — otherwise it refuses them;
* - optimized images cached for 31 days (uploads get new names when replaced).
*
* import { buildImagesConfig } from '@intecion/ipal-kit'
* export default withPayload({ images: { ...buildImagesConfig(), /* your overrides *\/ } })
*/
export function buildImagesConfig({
extraHosts = [],
publicUrl = process.env.R2_PUBLIC_URL,
}: { extraHosts?: string[]; publicUrl?: string } = {}): ImagesConfig {
const remotePatterns: RemotePattern[] = []
if (publicUrl && /^https?:\/\//i.test(publicUrl)) {
const u = new URL(publicUrl)
remotePatterns.push({
hostname: u.hostname,
protocol: u.protocol.replace(':', '') as 'http' | 'https',
...(u.port ? { port: u.port } : {}),
pathname: `${u.pathname.replace(/\/$/, '')}/**`,
})
}
for (const host of extraHosts) {remotePatterns.push({ hostname: host, protocol: 'https' })}
return { formats: ['image/avif', 'image/webp'], minimumCacheTTL: 60 * 60 * 24 * 31, remotePatterns }
}
+2
View File
@@ -1,2 +1,4 @@
export { buildImagesConfig } from './buildImagesConfig.js'
export type { ImagesConfig } from './buildImagesConfig.js'
export { buildR2Storage } from './buildR2Storage.js'
export type { BuildR2StorageDeps, S3StorageFactory } from './buildR2Storage.js'