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

entry.ts

185 lines · 5.3 KB · TypeScript
import type { LightboxPhoto } from '../controllers/gallery.tsx'

/**
 * Progressive-enhancement lightbox for gallery pages. Without JavaScript every
 * thumbnail links to its own photo page; with it, the same links open a
 * full-screen <dialog> with arrow keys, Escape, swipe, and shareable URLs.
 * Plain DOM code (no framework) keeps the only client script tiny.
 */

function readPhotos(grid: HTMLElement): Array<LightboxPhoto> {
	const data = document.getElementById(grid.dataset.lightbox ?? '')
	return data?.textContent
		? (JSON.parse(data.textContent) as Array<LightboxPhoto>)
		: []
}

function element<tag extends keyof HTMLElementTagNameMap>(
	tag: tag,
	props: Partial<HTMLElementTagNameMap[tag]> = {},
	...children: Array<Node>
) {
	const node = Object.assign(document.createElement(tag), props)
	node.append(...children)
	return node
}

function preload(photo: LightboxPhoto | undefined) {
	if (!photo) return
	const img = new Image()
	img.sizes = '100vw'
	img.srcset = photo.webpSrcset || photo.srcset
}

function setUpLightbox(grid: HTMLElement) {
	const photos = readPhotos(grid)
	if (photos.length === 0) return

	const source = element('source', { type: 'image/webp' })
	const img = element('img', { alt: '', decoding: 'async' })
	img.sizes = '100vw'
	const frame = element('picture', { className: 'lightbox-photo' }, source, img)
	const caption = element('p', { className: 'lightbox-caption' })
	const counter = element('p', { className: 'lightbox-counter' })
	const prev = element('button', {
		type: 'button',
		className: 'lightbox-nav prev',
		ariaLabel: 'Previous photo',
		textContent: '‹',
	})
	const next = element('button', {
		type: 'button',
		className: 'lightbox-nav next',
		ariaLabel: 'Next photo',
		textContent: '›',
	})
	const close = element('button', {
		type: 'button',
		className: 'lightbox-close',
		ariaLabel: 'Close',
		textContent: '×',
	})
	const dialog = element(
		'dialog',
		{ className: 'lightbox' },
		close,
		prev,
		frame,
		next,
		element('div', { className: 'lightbox-meta' }, caption, counter),
	)
	dialog.setAttribute('aria-label', 'Photo viewer')
	document.body.append(dialog)

	let current = 0
	let opener: HTMLElement | null = null

	function show(index: number, history: 'push' | 'replace' | 'none') {
		current = (index + photos.length) % photos.length
		const photo = photos[current]!
		frame.style.aspectRatio = `${photo.width} / ${photo.height}`
		frame.style.backgroundImage = `url("${photo.lqip}")`
		source.srcset = photo.webpSrcset
		img.srcset = photo.srcset
		img.src = photo.src
		img.alt = photo.alt
		img.width = photo.width
		img.height = photo.height
		caption.textContent = [photo.caption, photo.details]
			.filter(Boolean)
			.join(' · ')
		counter.textContent = `${current + 1} / ${photos.length}`
		prev.hidden = next.hidden = photos.length < 2
		if (history === 'push')
			window.history.pushState({ lightbox: current }, '', photo.href)
		if (history === 'replace')
			window.history.replaceState({ lightbox: current }, '', photo.href)
		preload(photos[current + 1])
		preload(photos[current - 1])
	}

	function open(index: number, from: HTMLElement) {
		opener = from
		show(index, 'push')
		dialog.showModal()
	}

	function closeViewer() {
		if (!dialog.open) return
		dialog.close()
	}

	dialog.addEventListener('close', () => {
		// Closing with the button, Escape, or a tap outside steps back to the gallery URL.
		if (typeof window.history.state?.lightbox === 'number')
			window.history.back()
		opener?.focus()
	})

	grid.addEventListener('click', (event) => {
		if (
			event.defaultPrevented ||
			event.button !== 0 ||
			event.metaKey ||
			event.ctrlKey ||
			event.shiftKey ||
			event.altKey
		)
			return
		const link = (event.target as Element).closest<HTMLAnchorElement>(
			'a[data-index]',
		)
		if (!link) return
		event.preventDefault()
		open(Number(link.dataset.index), link)
	})

	prev.addEventListener('click', () => show(current - 1, 'replace'))
	next.addEventListener('click', () => show(current + 1, 'replace'))
	close.addEventListener('click', closeViewer)
	dialog.addEventListener('click', (event) => {
		if (event.target === dialog) closeViewer()
	})
	dialog.addEventListener('keydown', (event) => {
		if (event.key === 'ArrowRight') show(current + 1, 'replace')
		else if (event.key === 'ArrowLeft') show(current - 1, 'replace')
		else return
		event.preventDefault()
	})

	let touchStart: { x: number; y: number } | null = null
	dialog.addEventListener(
		'touchstart',
		(event) => {
			const touch = event.touches[0]
			touchStart =
				event.touches.length === 1 && touch
					? { x: touch.clientX, y: touch.clientY }
					: null
		},
		{ passive: true },
	)
	dialog.addEventListener('touchend', (event) => {
		const touch = event.changedTouches[0]
		if (!touchStart || !touch) return
		const dx = touch.clientX - touchStart.x
		const dy = touch.clientY - touchStart.y
		touchStart = null
		if (Math.abs(dx) > 50 && Math.abs(dx) > Math.abs(dy) * 1.5)
			show(current + (dx < 0 ? 1 : -1), 'replace')
		else if (dy > 90 && Math.abs(dy) > Math.abs(dx) * 1.5) closeViewer()
	})

	window.addEventListener('popstate', (event) => {
		const index = event.state?.lightbox
		if (typeof index !== 'number') {
			if (dialog.open) dialog.close()
			return
		}
		show(index, 'none')
		if (!dialog.open) dialog.showModal()
	})
}

for (const grid of document.querySelectorAll<HTMLElement>('[data-lightbox]'))
	setUpLightbox(grid)