Skip to content
← Public packages

@kentcdodds/the-last-software-engineer

The Last Software Engineer: Kent C. Dodds's React Summit US 2026 talk deck. Judgment and product engineering in an AI era.

FollowForkOpen app

Files

deck.js

230 lines · 9.8 KB · JavaScript
// Reveal.js setup, theme handling, the click-step engine and entry motion.
// Theme: follows the OS (prefers-color-scheme) by default and switches live when the OS does.
// ?theme=light|dark forces a theme; ?theme=system clears any remembered pick. T flips the theme
// and remembers it in this browser (the speaker view follows live); flipping back to what the OS
// says forgets the pick, so the deck follows the OS again. ?static turns all motion off; ?soft
// uses gentle fades. Keep the inline head script in src/deck.html in step with this.
const params = new URLSearchParams(window.location.search)
const root = document.documentElement
const THEME_KEY = 'last-swe-deck-theme'
const forcedTheme = params.get('theme')
const systemDark = window.matchMedia('(prefers-color-scheme: dark)')
const systemTheme = () => (systemDark.matches ? 'dark' : 'light')
if (forcedTheme === 'system') {
	try {
		localStorage.removeItem(THEME_KEY)
	} catch {}
}

const savedTheme = () => {
	try {
		const value = localStorage.getItem(THEME_KEY)
		return value === 'light' || value === 'dark' ? value : null
	} catch {
		return null
	}
}
const applyTheme = () => {
	root.dataset.theme = forcedTheme === 'light' || forcedTheme === 'dark' ? forcedTheme : savedTheme() ?? systemTheme()
}
applyTheme()
systemDark.addEventListener('change', applyTheme)
// The speaker view (and its preview iframes) share localStorage, so a T press in either window
// switches both.
window.addEventListener('storage', (event) => {
	if (event.key === THEME_KEY) applyTheme()
})
const toggleTheme = () => {
	const next = root.dataset.theme === 'light' ? 'dark' : 'light'
	try {
		if (next === systemTheme()) localStorage.removeItem(THEME_KEY)
		else localStorage.setItem(THEME_KEY, next)
	} catch {}
	root.dataset.theme = next
}

const reduce = window.matchMedia('(prefers-reduced-motion: reduce)')
const setMotion = () => {
	root.dataset.motion = params.has('static') ? 'off' : reduce.matches || params.has('soft') ? 'soft' : 'full'
}
setMotion()
reduce.addEventListener('change', setMotion)

// Click steps. A section with data-steps="N" gets N hidden Reveal fragments, so Reveal owns the
// beat order (and the speaker view's fragment count). The current step is mirrored on the section
// as data-step and classes s1..sN; [data-at="k"] elements show from step k and [data-until="k"]
// elements hide from step k.
const sections = [...document.querySelectorAll('.reveal .slides section')]
for (const section of sections) {
	const n = Number(section.dataset.steps ?? 0)
	for (let i = 0; i < n; i++) {
		const marker = document.createElement('span')
		marker.className = 'fragment step-marker'
		marker.dataset.fragmentIndex = String(i)
		marker.setAttribute('aria-hidden', 'true')
		section.append(marker)
	}
	for (const el of section.querySelectorAll('[data-at], [data-until]')) el.classList.add('stepped')
	for (const el of section.querySelectorAll('[data-d]')) el.style.setProperty('--d', `${el.dataset.d}ms`)
	// Rewind order for going backward: the last element in leaves first.
	const ds = [...section.querySelectorAll('[data-m]')].map((el) => Number(el.dataset.d ?? 0))
	const maxD = Math.max(0, ...ds)
	for (const el of section.querySelectorAll('[data-m]')) el.style.setProperty('--rd', `${Math.round((maxD - Number(el.dataset.d ?? 0)) * 0.3)}ms`)
	for (const el of section.querySelectorAll('[data-td]')) el.style.setProperty('--td', `${el.dataset.td}ms`)
}
function syncSteps(section) {
	if (!section) return
	const n = Number(section.dataset.steps ?? 0)
	const step = section.querySelectorAll('.step-marker.visible').length
	const changed = section.dataset.step !== String(step)
	section.dataset.step = String(step)
	// Widgets (the physics plank) follow beats through this event.
	if (changed) section.dispatchEvent(new CustomEvent('stepchange', { detail: { step } }))
	for (let i = 1; i <= Math.max(n, 8); i++) section.classList.toggle(`s${i}`, i <= step)
	for (const el of section.querySelectorAll('.stepped')) {
		const at = Number(el.dataset.at ?? 0)
		const until = el.dataset.until == null ? Infinity : Number(el.dataset.until)
		el.classList.toggle('is-shown', step >= at && step < until)
		el.classList.toggle('is-gone', step >= until)
	}
	for (const el of section.querySelectorAll('path[data-morph]')) morphTo(el, step >= Number(el.dataset.morph) ? 1 : 0, section)
}

// Path morphs: <path data-morph="k" data-from="..." data-to="..."> interpolates every number of
// its d attribute from data-from to data-to when the slide reaches step k (and back when it
// leaves it). Both paths must use the same commands. Animated only on the current slide with
// full motion; otherwise it jumps to the end state, so ?static shows each beat's final shape.
const MORPH_MS = 1300
const easeInOut = (x) => (x < 0.5 ? 4 * x * x * x : 1 - (-2 * x + 2) ** 3 / 2)
function morphTo(el, target, section) {
	if (!el.__morph) {
		const nums = (s) => (s.match(/-?\d*\.?\d+/g) ?? []).map(Number)
		const from = nums(el.dataset.from)
		const to = nums(el.dataset.to)
		if (from.length !== to.length) throw new Error(`morph paths differ in shape: ${el.dataset.from} / ${el.dataset.to}`)
		const parts = el.dataset.from.split(/-?\d*\.?\d+/)
		el.__morph = { from, to, parts, p: 0, raf: 0 }
	}
	const m = el.__morph
	const render = (p) => {
		m.p = p
		const e = easeInOut(p)
		el.setAttribute('d', m.parts.map((part, i) => (i < m.from.length ? part + (m.from[i] + (m.to[i] - m.from[i]) * e).toFixed(2) : part)).join(''))
	}
	cancelAnimationFrame(m.raf)
	const live = window.__deck?.getCurrentSlide?.() === section && root.dataset.motion === 'full' && !section.classList.contains('m-instant')
	if (!live || m.p === target) return render(target)
	const start = performance.now()
	const p0 = m.p
	const tick = (now) => {
		const x = Math.min(1, (now - start) / (MORPH_MS * Math.abs(target - p0)))
		render(p0 + (target - p0) * x)
		if (x < 1) m.raf = requestAnimationFrame(tick)
	}
	m.raf = requestAnimationFrame(tick)
}
for (const section of sections) syncSteps(section)

// Entry motion. Going forward, the new slide's [data-m] elements play in (m-go) and later beats
// animate (m-beat). Going backward, the slide you land on appears in its final state at once
// (m-instant: no entry animation, no beats replaying), and the slide you leave rewinds its entry
// animation as it fades out (m-rev).
function play(section) {
	for (const s of document.querySelectorAll('.reveal .slides section.m-go, .reveal .slides section.m-beat')) s.classList.remove('m-go', 'm-beat')
	if (!section || root.dataset.motion === 'off') return
	section.classList.remove('m-rev')
	void section.offsetWidth
	section.classList.add('m-go', 'm-beat')
}
function arriveBack(section, left) {
	for (const s of document.querySelectorAll('.reveal .slides section.m-go, .reveal .slides section.m-beat, .reveal .slides section.m-rev')) {
		if (s !== left) s.classList.remove('m-go', 'm-beat', 'm-rev')
	}
	if (left && root.dataset.motion === 'full') {
		left.classList.remove('m-go', 'm-beat')
		void left.offsetWidth
		left.classList.add('m-rev')
	}
	if (!section) return
	section.classList.add('m-instant')
	syncSteps(section)
	void section.offsetWidth
	requestAnimationFrame(() => requestAnimationFrame(() => section.classList.remove('m-instant')))
}
const slideIndex = (s) => (s ? Array.prototype.indexOf.call(document.querySelectorAll('.reveal .slides > section'), s) : -1)

const deck = new Reveal({
	hash: true,
	controls: false,
	progress: true,
	slideNumber: false,
	width: 1920,
	height: 1080,
	margin: 0,
	minScale: 0.2,
	maxScale: 2,
	display: 'flex',
	center: false,
	transition: params.has('static') ? 'none' : 'fade',
	transitionSpeed: 'default',
	backgroundTransition: 'none',
	viewDistance: 4,
	navigationMode: 'linear',
	plugins: [RevealNotes],
})
deck.addKeyBinding({ keyCode: 84, key: 'T', description: 'Toggle light / dark theme' }, toggleTheme)
deck.on('ready', (event) => {
	for (const section of sections) syncSteps(section)
	play(event.currentSlide)
})
deck.on('slidechanged', (event) => {
	const back = event.previousSlide && slideIndex(event.currentSlide) < slideIndex(event.previousSlide)
	if (event.previousSlide) syncSteps(event.previousSlide)
	if (back) arriveBack(event.currentSlide, event.previousSlide)
	else {
		syncSteps(event.currentSlide)
		play(event.currentSlide)
	}
})
// A beat on a slide you arrived at backward animates like any other beat (m-beat), without
// replaying the slide's entry animation.
const onFragment = (event) => {
	const section = event.fragment.closest('section')
	syncSteps(section)
	if (root.dataset.motion !== 'off') section.classList.add('m-beat')
}
deck.on('fragmentshown', onFragment)
deck.on('fragmenthidden', onFragment)
deck.initialize()
window.__deck = deck

// Offline (PWA): when the deck is served over http(s), register the service worker (it caches
// this page, which holds every asset) and link the web app manifest so it can be installed.
// Opening dist/index.html from disk needs none of this: it is already fully self-contained.
window.__pwa = { state: 'off' }
if (/^https?:$/.test(location.protocol) && 'serviceWorker' in navigator) {
	const base = location.pathname.endsWith('/') ? location.pathname : `${location.pathname}/`
	const manifest = document.createElement('link')
	manifest.rel = 'manifest'
	manifest.href = `${base}manifest.webmanifest`
	document.head.append(manifest)
	const register = async () => {
		try {
			// Scope /<mount> (no trailing slash) also covers the URL without a trailing slash.
			return await navigator.serviceWorker.register(`${base}sw.js`, { scope: base.replace(/\/$/, '') || '/' })
		} catch {
			return navigator.serviceWorker.register(`${base}sw.js`, { scope: base })
		}
	}
	window.__pwa.state = 'registering'
	register()
		.then(async (registration) => {
			window.__pwa.scope = registration.scope
			await navigator.serviceWorker.ready
			window.__pwa.state = 'ready'
		})
		.catch((error) => {
			window.__pwa.state = 'error'
			window.__pwa.error = String(error)
		})
}