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:
@@ -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'
|
||||
|
||||
@@ -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' }
|
||||
}
|
||||
@@ -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)}`)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user