Skip to content
← 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.

FollowFork

Files

content.ts

426 lines · 11.5 KB · TypeScript
import type { Gallery, Photo, SiteContent } from './types.ts'

export const maxGalleries = 200
export const maxPhotosPerGallery = 300

/** Turn a title into a URL slug: "Golden Hour!" → "golden-hour". */
export function slugify(value: string) {
	const slug = value
		.normalize('NFKD')
		.replace(/[\u0300-\u036f]/g, '')
		.toLowerCase()
		.replace(/&/g, ' and ')
		.replace(/[^a-z0-9]+/g, '-')
		.replace(/^-+|-+$/g, '')
		.slice(0, 60)
		.replace(/-+$/g, '')
	return slug || 'gallery'
}

export function isValidSlug(value: string) {
	return /^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(value) && value.length <= 60
}

/** Find a gallery by id or slug. */
export function findGallery(
	content: SiteContent,
	ref: string,
): Gallery | undefined {
	return content.galleries.find(
		(gallery) => gallery.id === ref || gallery.slug === ref,
	)
}

export function requireGallery(content: SiteContent, ref: string): Gallery {
	const gallery = findGallery(content, ref)
	if (!gallery) {
		const known = content.galleries.map((g) => g.slug).join(', ') || 'none yet'
		throw new Error(`No gallery "${ref}". Known galleries: ${known}.`)
	}
	return gallery
}

function assertSlugFree(content: SiteContent, slug: string, exceptId?: string) {
	const taken = content.galleries.some(
		(g) => g.slug === slug && g.id !== exceptId,
	)
	if (taken) throw new Error(`Another gallery already uses the slug "${slug}".`)
}

/** Pick a free slug: "portraits", then "portraits-2", "portraits-3", … */
export function uniqueSlug(content: SiteContent, base: string) {
	const taken = new Set(content.galleries.map((g) => g.slug))
	if (!taken.has(base)) return base
	for (let n = 2; ; n += 1) {
		const candidate = `${base}-${n}`
		if (!taken.has(candidate)) return candidate
	}
}

function touch(
	content: SiteContent,
	galleries: Array<Gallery>,
	now: string,
): SiteContent {
	return { ...content, galleries, updatedAt: now }
}

function replaceGallery(content: SiteContent, next: Gallery, now: string) {
	return touch(
		content,
		content.galleries.map((g) => (g.id === next.id ? next : g)),
		now,
	)
}

export type NewGallery = {
	id: string
	title: string
	slug?: string
	description?: string
	featured: boolean
	photos: Array<Photo>
	/** Index into `photos` for the cover. */
	cover: number
	position: 'start' | 'end'
}

export function addGallery(
	content: SiteContent,
	input: NewGallery,
	now: string,
) {
	if (content.galleries.length >= maxGalleries) {
		throw new Error(`A site can hold at most ${maxGalleries} galleries.`)
	}
	if (input.photos.length === 0)
		throw new Error('A gallery needs at least one photo.')
	if (input.photos.length > maxPhotosPerGallery) {
		throw new Error(`A gallery can hold at most ${maxPhotosPerGallery} photos.`)
	}
	const cover = input.photos[input.cover]
	if (!cover) {
		throw new Error(
			`cover must be an index between 0 and ${input.photos.length - 1}.`,
		)
	}
	let slug: string
	if (input.slug) {
		if (!isValidSlug(input.slug))
			throw new Error(
				`"${input.slug}" is not a valid slug (use lowercase-words-with-dashes).`,
			)
		assertSlugFree(content, input.slug)
		slug = input.slug
	} else {
		slug = uniqueSlug(content, slugify(input.title))
	}
	const gallery: Gallery = {
		id: input.id,
		slug,
		title: input.title.trim(),
		...(input.description?.trim()
			? { description: input.description.trim() }
			: {}),
		coverPhotoId: cover.id,
		featured: input.featured,
		photos: input.photos,
		createdAt: now,
		updatedAt: now,
	}
	const galleries =
		input.position === 'end'
			? [...content.galleries, gallery]
			: [gallery, ...content.galleries]
	return { content: touch(content, galleries, now), gallery }
}

export type GalleryPatch = {
	title?: string
	slug?: string
	description?: string | null
	featured?: boolean
	coverPhotoId?: string
	/** Photo ids in the new order. Listed photos move to the front; the rest keep their order after them. */
	photoOrder?: Array<string>
	/** Caption / alt edits keyed by photo id. `null` caption clears it. */
	photos?: Array<{ id: string; caption?: string | null; alt?: string }>
}

export function updateGallery(
	content: SiteContent,
	ref: string,
	patch: GalleryPatch,
	now: string,
) {
	const current = requireGallery(content, ref)
	const next: Gallery = { ...current, updatedAt: now }
	if (patch.title !== undefined) next.title = patch.title.trim()
	if (patch.slug !== undefined) {
		if (!isValidSlug(patch.slug))
			throw new Error(
				`"${patch.slug}" is not a valid slug (use lowercase-words-with-dashes).`,
			)
		assertSlugFree(content, patch.slug, current.id)
		next.slug = patch.slug
	}
	if (patch.description !== undefined) {
		const description = patch.description?.trim()
		if (description) next.description = description
		else delete next.description
	}
	if (patch.featured !== undefined) next.featured = patch.featured
	const byId = new Map(current.photos.map((photo) => [photo.id, photo]))
	if (patch.photos) {
		for (const edit of patch.photos) {
			const photo = byId.get(edit.id)
			if (!photo)
				throw new Error(`Gallery "${current.slug}" has no photo "${edit.id}".`)
			const edited: Photo = { ...photo }
			if (edit.alt !== undefined) edited.alt = edit.alt.trim()
			if (edit.caption !== undefined) {
				const caption = edit.caption?.trim()
				if (caption) edited.caption = caption
				else delete edited.caption
			}
			byId.set(edit.id, edited)
		}
	}
	let photos = current.photos.map((photo) => byId.get(photo.id) ?? photo)
	if (patch.photoOrder) {
		photos = reorderByIds(
			photos,
			patch.photoOrder,
			(photo) => [photo.id],
			'photo',
		)
	}
	next.photos = photos
	if (patch.coverPhotoId !== undefined) {
		if (!byId.has(patch.coverPhotoId)) {
			throw new Error(
				`Gallery "${current.slug}" has no photo "${patch.coverPhotoId}" to use as the cover.`,
			)
		}
		next.coverPhotoId = patch.coverPhotoId
	}
	return { content: replaceGallery(content, next, now), gallery: next }
}

export function removeGallery(content: SiteContent, ref: string, now: string) {
	const gallery = requireGallery(content, ref)
	return {
		content: touch(
			content,
			content.galleries.filter((g) => g.id !== gallery.id),
			now,
		),
		gallery,
	}
}

/**
 * Move the listed items to the front in the given order; unlisted items keep
 * their relative order after them. Unknown or duplicate refs throw.
 */
export function reorderByIds<item>(
	items: Array<item>,
	order: Array<string>,
	keysOf: (item: item) => Array<string>,
	noun: string,
) {
	const seen = new Set<item>()
	const front: Array<item> = []
	for (const ref of order) {
		const match = items.find((item) => keysOf(item).includes(ref))
		if (!match) throw new Error(`Unknown ${noun} "${ref}".`)
		if (seen.has(match))
			throw new Error(`The ${noun} "${ref}" is listed twice.`)
		seen.add(match)
		front.push(match)
	}
	return [...front, ...items.filter((item) => !seen.has(item))]
}

export function reorderGalleries(
	content: SiteContent,
	order: Array<string>,
	now: string,
) {
	const galleries = reorderByIds(
		content.galleries,
		order,
		(g) => [g.id, g.slug],
		'gallery',
	)
	return touch(content, galleries, now)
}

export function addPhotos(
	content: SiteContent,
	ref: string,
	photos: Array<Photo>,
	position: 'start' | 'end',
	now: string,
) {
	const current = requireGallery(content, ref)
	if (photos.length === 0) throw new Error('Pass at least one photo.')
	if (current.photos.length + photos.length > maxPhotosPerGallery) {
		throw new Error(`A gallery can hold at most ${maxPhotosPerGallery} photos.`)
	}
	const next: Gallery = {
		...current,
		photos:
			position === 'start'
				? [...photos, ...current.photos]
				: [...current.photos, ...photos],
		updatedAt: now,
	}
	return { content: replaceGallery(content, next, now), gallery: next }
}

export function removePhoto(
	content: SiteContent,
	ref: string,
	photoId: string,
	now: string,
) {
	const current = requireGallery(content, ref)
	const photo = current.photos.find((p) => p.id === photoId)
	if (!photo)
		throw new Error(`Gallery "${current.slug}" has no photo "${photoId}".`)
	if (current.photos.length === 1) {
		throw new Error(
			`"${current.slug}" would be empty. Use remove-gallery to remove the whole gallery instead.`,
		)
	}
	const photos = current.photos.filter((p) => p.id !== photoId)
	const next: Gallery = {
		...current,
		photos,
		coverPhotoId:
			current.coverPhotoId === photoId ? photos[0]!.id : current.coverPhotoId,
		updatedAt: now,
	}
	return { content: replaceGallery(content, next, now), gallery: next, photo }
}

export function coverOf(gallery: Gallery): Photo {
	return (
		gallery.photos.find((p) => p.id === gallery.coverPhotoId) ??
		gallery.photos[0]!
	)
}

/** Galleries shown on the home page: featured ones, or the first six when none are featured. */
export function featuredGalleries(content: SiteContent) {
	const featured = content.galleries.filter((g) => g.featured)
	return featured.length > 0 ? featured : content.galleries.slice(0, 6)
}

/** Every stored (not bundled) photo id the content points at, including the headshot. */
export function storedPhotoIds(content: SiteContent): Set<string> {
	const ids = new Set<string>()
	for (const gallery of content.galleries) {
		for (const photo of gallery.photos)
			if (photo.source === 'stored') ids.add(photo.id)
	}
	if (content.config.headshot?.source === 'stored')
		ids.add(content.config.headshot.id)
	return ids
}

export type GallerySummary = {
	id: string
	slug: string
	title: string
	description?: string
	featured: boolean
	photoCount: number
	coverPhotoId: string
	photos: Array<{
		id: string
		alt: string
		caption?: string
		width: number
		height: number
	}>
}

export function summarizeGallery(gallery: Gallery): GallerySummary {
	return {
		id: gallery.id,
		slug: gallery.slug,
		title: gallery.title,
		...(gallery.description ? { description: gallery.description } : {}),
		featured: gallery.featured,
		photoCount: gallery.photos.length,
		coverPhotoId: gallery.coverPhotoId,
		photos: gallery.photos.map((p) => ({
			id: p.id,
			alt: p.alt,
			...(p.caption ? { caption: p.caption } : {}),
			width: p.width,
			height: p.height,
		})),
	}
}

export type ContentDiff = {
	hasChanges: boolean
	configFields: Array<string>
	galleriesAdded: Array<string>
	galleriesRemoved: Array<string>
	galleriesChanged: Array<string>
	orderChanged: boolean
}

/** What would change if `next` replaced `current` (used for publish previews). */
export function diffContent(
	current: SiteContent,
	next: SiteContent,
): ContentDiff {
	const configFields = Object.keys({
		...current.config,
		...next.config,
	}).filter(
		(key) =>
			JSON.stringify((current.config as Record<string, unknown>)[key]) !==
			JSON.stringify((next.config as Record<string, unknown>)[key]),
	)
	const before = new Map(current.galleries.map((g) => [g.id, g]))
	const after = new Map(next.galleries.map((g) => [g.id, g]))
	const galleriesAdded = next.galleries
		.filter((g) => !before.has(g.id))
		.map((g) => g.slug)
	const galleriesRemoved = current.galleries
		.filter((g) => !after.has(g.id))
		.map((g) => g.slug)
	const galleriesChanged = next.galleries
		.filter(
			(g) =>
				before.has(g.id) &&
				JSON.stringify(before.get(g.id)) !== JSON.stringify(g),
		)
		.map((g) => g.slug)
	const sharedBefore = current.galleries
		.filter((g) => after.has(g.id))
		.map((g) => g.id)
	const sharedAfter = next.galleries
		.filter((g) => before.has(g.id))
		.map((g) => g.id)
	const orderChanged = sharedBefore.join() !== sharedAfter.join()
	return {
		hasChanges:
			configFields.length > 0 ||
			galleriesAdded.length > 0 ||
			galleriesRemoved.length > 0 ||
			galleriesChanged.length > 0 ||
			orderChanged,
		configFields,
		galleriesAdded,
		galleriesRemoved,
		galleriesChanged,
		orderChanged,
	}
}