← Public packages
@kentcdodds/photo-portfolio
A fast, photo-first portfolio site you update by chatting with your agent: galleries, about, contact, and one-step rollback.
Files
import type { ImageFormat, Photo, PhotoVariant } from './types.ts'
/** Target widths for responsive images. */
export const variantWidths = [480, 960, 1600, 2400] as const
/** No variant's long edge exceeds this, so tall portraits don't balloon. */
export const maxLongEdge = 2400
export const variantFormats: ReadonlyArray<ImageFormat> = ['webp', 'jpeg']
/** Largest source we decode inside a Worker isolate (memory bound). */
export const maxSourceMegapixels = 12
export type PlannedSize = { width: number; height: number }
/**
* Pick the output sizes for a source image (already in display orientation):
* every standard width that fits, plus the largest size the source allows when
* it falls between standard widths. Never upscales.
*/
export function planVariantSizes(
sourceWidth: number,
sourceHeight: number,
): Array<PlannedSize> {
if (sourceWidth < 1 || sourceHeight < 1)
throw new Error('Image has no pixels.')
const megapixels = (sourceWidth * sourceHeight) / 1_000_000
if (megapixels > maxSourceMegapixels) {
throw new Error(
`Image is ${sourceWidth}×${sourceHeight} (${megapixels.toFixed(1)} MP). Send a web export of at most ${maxSourceMegapixels} MP (for example 4200×2800 or smaller).`,
)
}
const scaleForLongEdge = maxLongEdge / Math.max(sourceWidth, sourceHeight)
const largestWidth = Math.min(
sourceWidth,
Math.floor(sourceWidth * Math.min(1, scaleForLongEdge)),
)
const widths: Array<number> = variantWidths.filter((w) => w < largestWidth)
widths.push(largestWidth)
return widths.map((width) => ({
width,
height: Math.max(1, Math.round((sourceHeight * width) / sourceWidth)),
}))
}
export function variantFileName(
variant: Pick<PhotoVariant, 'width' | 'format'>,
) {
return `${variant.width}.${variant.format === 'jpeg' ? 'jpg' : 'webp'}`
}
export const contentTypes: Record<ImageFormat, string> = {
webp: 'image/webp',
jpeg: 'image/jpeg',
}
/** `srcset` for one format, given a URL builder for a variant. */
export function buildSrcset(
photo: Photo,
format: ImageFormat,
urlFor: (photo: Photo, variant: PhotoVariant) => string,
) {
return photo.variants
.filter((v) => v.format === format)
.sort((a, b) => a.width - b.width)
.map((v) => `${urlFor(photo, v)} ${v.width}w`)
.join(', ')
}
/** The variant of `format` closest to (and at least) `targetWidth`, else the largest. */
export function pickVariant(
photo: Photo,
format: ImageFormat,
targetWidth: number,
) {
const candidates = photo.variants
.filter((v) => v.format === format)
.sort((a, b) => a.width - b.width)
return (
candidates.find((v) => v.width >= targetWidth) ??
candidates[candidates.length - 1]
)
}