Files
ipal-kit/src/modules/media/mediaProps.ts
T

156 lines
6.2 KiB
TypeScript

/**
* 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
/**
* Above the fold but not the LCP image (a header logo): loads at once (`loading="eager"`) WITHOUT
* fetchPriority="high" or a preload, so it does not compete with the one `priority` image. Ignored with `priority`.
*/
eager?: boolean
/**
* Dominant colour as the <img> background while it loads. The style stays after
* load, so it would show through transparent pixels (white logo on a black box).
* 'auto' (default): only for JPEG, which has no alpha channel. true: always
* (opaque PNG/WebP photos). false: never.
*/
placeholderColor?: 'auto' | boolean
/**
* 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
}
/** Formats that cannot be transparent — a background colour never shows through. */
const NO_ALPHA = new Set(['image/jpeg', 'image/jpg', 'image/pjpeg'])
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 — for JPEG only, see `placeholderColor` — a background colour.
*/
export function mediaImageProps(
resource: unknown,
{ alt, eager = false, placeholderColor = 'auto', 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 useColor = placeholderColor === 'auto' ? NO_ALPHA.has(doc.mimeType ?? '') : placeholderColor
const color = useColor ? (doc.placeholder?.color ?? undefined) : 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: eager ? ('eager' as const) : ('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' }
}