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:
@@ -137,40 +137,40 @@ export function buttonClass(appearance: LinkAppearance): string {
|
||||
}
|
||||
```
|
||||
|
||||
`src/components/ui/Media.tsx` — **każdy** obraz/wideo z panelu:
|
||||
`src/components/ui/Media.tsx` — **każdy** obraz/wideo z panelu. Szybkość liczy plugin
|
||||
(`mediaImageProps`, `videoProps`), wygląd zostaje tutaj:
|
||||
|
||||
```tsx
|
||||
import Image from 'next/image'
|
||||
import { mediaImageProps, MEDIA_SIZES, videoProps, type VideoMode } from '@intecion/ipal-kit'
|
||||
import type { Media as MediaDoc } from '@/payload-types'
|
||||
|
||||
type Props = {
|
||||
resource: MediaDoc | string | number | null | undefined
|
||||
/** Szerokość NA EKRANIE — MEDIA_SIZES.half / .third / własny string. Bez tego pobiera się pełna szerokość. */
|
||||
sizes?: string
|
||||
/** Tylko pierwszy widoczny obraz strony (hero, LCP). Reszta ładuje się leniwie. */
|
||||
priority?: boolean
|
||||
className?: string
|
||||
/** Poster image URL for videos (shown before playback). */
|
||||
poster?: string
|
||||
/** Wideo: 'background' (pętla bez dźwięku) albo 'player' (kontrolki, ładowanie po kliknięciu). */
|
||||
videoMode?: VideoMode
|
||||
/** Plakat wideo — upload z panelu. */
|
||||
poster?: MediaDoc | string | number | null
|
||||
}
|
||||
|
||||
export function Media({ resource, sizes = '100vw', priority = false, className, poster }: Props) {
|
||||
if (!resource || typeof resource !== 'object' || !resource.url) return null
|
||||
const { url, alt, width, height, mimeType } = resource
|
||||
|
||||
if (mimeType?.startsWith('video/')) {
|
||||
// preload="metadata": the browser fetches only headers until playback, not the whole file
|
||||
return (
|
||||
<video src={url} className={className} poster={poster} preload="metadata" autoPlay muted loop playsInline />
|
||||
)
|
||||
}
|
||||
if (!width || !height) return null // non-image file (PDF) — use CMSLink type 'file'
|
||||
|
||||
return (
|
||||
<Image src={url} alt={alt ?? ''} width={width} height={height}
|
||||
sizes={sizes} priority={priority} className={className} />
|
||||
)
|
||||
export function Media({ resource, sizes = MEDIA_SIZES.full, priority = false, className, videoMode = 'player', poster }: Props) {
|
||||
const video = videoProps(resource, { mode: videoMode, poster })
|
||||
if (video) return <video {...video} className={className} />
|
||||
const img = mediaImageProps(resource, { priority, sizes })
|
||||
if (!img) return null // PDF / plik — link typu 'file' (CMSLink), nie <Media>
|
||||
return <Image {...img} className={className} />
|
||||
}
|
||||
```
|
||||
|
||||
Media w kolekcji: `upload: { focalPoint: true, … }` (punkt ostrości → `object-position`) oraz
|
||||
placeholder z pluginu: `hooks.beforeOperation: [buildOptimizeUploadHook(), buildMediaPlaceholderHook()]`,
|
||||
pole `buildMediaPlaceholderField()` (rozmyty podgląd + kolor podczas ładowania).
|
||||
|
||||
`Section.tsx` i `SectionHeader.tsx`:
|
||||
|
||||
```tsx
|
||||
|
||||
@@ -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
@@ -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'.
|
||||
|
||||
@@ -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)}`)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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,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
|
||||
|
||||
@@ -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>
|
||||
)
|
||||
}
|
||||
@@ -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 }
|
||||
}
|
||||
@@ -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'
|
||||
|
||||
+4
-4
@@ -79,11 +79,11 @@ describe('archive listing', () => {
|
||||
|
||||
describe('noindex protection', () => {
|
||||
test('the homepage cannot be set to noindex; an ordinary page can', async () => {
|
||||
const home = await payload.create({ collection: 'pages' as never, data: { _status: 'published', slug: 'start', title: 'Start' } as never })
|
||||
const other = await payload.create({ collection: 'pages' as never, data: { _status: 'published', slug: 'dziekujemy', title: 'Dziękujemy' } as never })
|
||||
const home = await payload.create({ collection: 'pages' as never, data: { slug: 'start', _status: 'published', title: 'Start' } as never })
|
||||
const other = await payload.create({ collection: 'pages' as never, data: { slug: 'dziekujemy', _status: 'published', title: 'Dziękujemy' } as never })
|
||||
await payload.updateGlobal({ slug: 'site-settings' as never, data: { homepage: home.id, siteName: 'Acme' } as never })
|
||||
await expect(payload.update({ collection: 'pages' as never, data: { noindex: true } as never, id: home.id })).rejects.toThrow(/Exclude from indexing/)
|
||||
const updated = (await payload.update({ collection: 'pages' as never, data: { noindex: true } as never, id: other.id })) as { noindex?: boolean }
|
||||
await expect(payload.update({ id: home.id, collection: 'pages' as never, data: { noindex: true } as never })).rejects.toThrow(/Exclude from indexing/)
|
||||
const updated = (await payload.update({ id: other.id, collection: 'pages' as never, data: { noindex: true } as never })) as { noindex?: boolean }
|
||||
expect(updated.noindex).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
import sharp from 'sharp'
|
||||
import { describe, expect, test, vi } from 'vitest'
|
||||
|
||||
import { MEDIA_SIZES, mediaImageProps, videoProps } from '../src/modules/media/mediaProps.js'
|
||||
import { buildMediaPlaceholderHook } from '../src/modules/media/placeholder.js'
|
||||
import { buildImagesConfig } from '../src/modules/storage/buildImagesConfig.js'
|
||||
|
||||
const image = { alt: 'Ekipa przy pracy', height: 800, mimeType: 'image/webp', url: '/media/a.webp', width: 1200 }
|
||||
|
||||
describe('mediaImageProps', () => {
|
||||
test('lazy by default, dimensions from the document', () => {
|
||||
expect(mediaImageProps(image, { sizes: MEDIA_SIZES.half })).toEqual({
|
||||
alt: 'Ekipa przy pracy',
|
||||
height: 800,
|
||||
loading: 'lazy',
|
||||
sizes: '(min-width: 768px) 50vw, 100vw',
|
||||
src: '/media/a.webp',
|
||||
width: 1200,
|
||||
})
|
||||
})
|
||||
|
||||
test('LCP image: preload + high priority + eager', () => {
|
||||
expect(mediaImageProps(image, { priority: true })).toMatchObject({ fetchPriority: 'high', loading: 'eager', preload: true })
|
||||
})
|
||||
|
||||
test('placeholder and focal point', () => {
|
||||
const p = mediaImageProps({ ...image, focalX: 30, focalY: 70, placeholder: { blurDataURL: 'data:x', color: '#123456' } })
|
||||
expect(p).toMatchObject({ blurDataURL: 'data:x', placeholder: 'blur', style: { backgroundColor: '#123456', objectPosition: '30% 70%' } })
|
||||
expect(mediaImageProps({ ...image, focalX: 50, focalY: 50 })?.style).toBeUndefined()
|
||||
})
|
||||
|
||||
test('video, PDF and bare ids give null; decorative alt override', () => {
|
||||
expect(mediaImageProps({ ...image, mimeType: 'video/mp4' })).toBeNull()
|
||||
expect(mediaImageProps({ mimeType: 'application/pdf', url: '/x.pdf' })).toBeNull()
|
||||
expect(mediaImageProps(42)).toBeNull()
|
||||
expect(mediaImageProps(image, { alt: '' })?.alt).toBe('')
|
||||
})
|
||||
})
|
||||
|
||||
describe('videoProps', () => {
|
||||
const video = { mimeType: 'video/mp4', url: '/media/v.mp4' }
|
||||
test('player: controls, nothing downloaded before play', () => {
|
||||
expect(videoProps(video, { poster: { url: '/media/p.webp' } })).toEqual({
|
||||
controls: true,
|
||||
playsInline: true,
|
||||
poster: '/media/p.webp',
|
||||
preload: 'none',
|
||||
src: '/media/v.mp4',
|
||||
})
|
||||
})
|
||||
test('background: muted loop, no autoplay with reduced motion', () => {
|
||||
expect(videoProps(video, { mode: 'background' })).toMatchObject({ autoPlay: true, loop: true, muted: true })
|
||||
expect(videoProps(video, { mode: 'background', reducedMotion: true })?.autoPlay).toBe(false)
|
||||
expect(videoProps(image)).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('buildImagesConfig', () => {
|
||||
test('AVIF/WebP and the R2 domain', () => {
|
||||
expect(buildImagesConfig({ publicUrl: 'https://media.acme.pl/' })).toEqual({
|
||||
formats: ['image/avif', 'image/webp'],
|
||||
minimumCacheTTL: 2678400,
|
||||
remotePatterns: [{ hostname: 'media.acme.pl', pathname: '/**', protocol: 'https' }],
|
||||
})
|
||||
expect(buildImagesConfig({ publicUrl: '/media' }).remotePatterns).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe('buildMediaPlaceholderHook', () => {
|
||||
test('stores a tiny blur image and the dominant colour; skips non-raster files', async () => {
|
||||
const png = await sharp({ create: { background: { b: 40, g: 120, r: 200 }, channels: 3, height: 300, width: 400 } }).png().toBuffer()
|
||||
const data: Record<string, unknown> = {}
|
||||
const req = { file: { data: png, mimetype: 'image/png' }, payload: { config: { sharp }, logger: { warn: vi.fn() } } }
|
||||
await buildMediaPlaceholderHook()({ args: { data }, operation: 'create', req } as never)
|
||||
const ph = data.placeholder as { blurDataURL: string; color: string }
|
||||
expect(ph.blurDataURL).toMatch(/^data:image\/webp;base64,/)
|
||||
expect(ph.blurDataURL.length).toBeLessThan(600)
|
||||
expect(ph.color).toBe('#c87828')
|
||||
|
||||
const svgData: Record<string, unknown> = {}
|
||||
await buildMediaPlaceholderHook()({ args: { data: svgData }, operation: 'create', req: { ...req, file: { data: png, mimetype: 'image/svg+xml' } } } as never)
|
||||
expect(svgData.placeholder).toBeUndefined()
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user