// Reveal.js setup, matching the source deck (kcd-content personal-software-ecosystem) on a
// 1280x720 canvas, plus theme handling and the ladder / garden behaviour from that deck.
// ?static turns transitions and animations off; ?linear uses linear navigation; ?theme=light|dark
// forces a theme. T toggles the theme and remembers it in localStorage.
const params = new URLSearchParams(window.location.search)
const root = document.documentElement
const forcedTheme = params.get('theme')
const colorScheme = window.matchMedia('(prefers-color-scheme: light)')
const THEME_KEY = 'cf-connect-pse-theme'
const savedTheme = () => {
try {
const value = localStorage.getItem(THEME_KEY)
return value === 'light' || value === 'dark' ? value : null
} catch {
return null
}
}
const applyTheme = () => {
if (forcedTheme === 'light' || forcedTheme === 'dark') {
root.dataset.theme = forcedTheme
return
}
root.dataset.theme = savedTheme() ?? (colorScheme.matches ? 'light' : 'dark')
}
applyTheme()
colorScheme.addEventListener('change', applyTheme)
// T toggles light/dark (Reveal doesn't use T). Toggling back to the system theme clears the
// override, so the deck follows the system again.
const toggleTheme = () => {
const next = root.dataset.theme === 'light' ? 'dark' : 'light'
const system = colorScheme.matches ? 'light' : 'dark'
try {
if (next === system) localStorage.removeItem(THEME_KEY)
else localStorage.setItem(THEME_KEY, next)
} catch {}
root.dataset.theme = next
}
const staticDeck = params.has('static')
if (staticDeck) root.dataset.static = ''
// Tiny highlighters (no highlight.js): TypeScript, JSON and search markdown. Runs once on load.
const escapeHtml = (value) =>
value.replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>').replaceAll('"', '"')
const highlightTs = (source) => {
const slots = []
const parked = escapeHtml(source).replaceAll(
/(\/\*[\s\S]*?\*\/|\/\/.*|("|'|`)(?:\\.|(?!\2)[\s\S])*?\2)/g,
(match) => {
slots.push(``)
return `\u0000${slots.length - 1}\u0000`
},
)
const keywords = 'async|await|class|const|export|default|from|function|import|let|new|return|throw|type|if'
return parked
.replaceAll(new RegExp(`\\b(${keywords})\\b`, 'g'), '$1')
.replaceAll(/\u0000(\d+)\u0000/g, (_, i) => slots[Number(i)])
}
const highlightJson = (source) =>
escapeHtml(source).replaceAll(/("[^&]*?")(\s*:)?/g, (_, str, colon) =>
colon ? `${str}${colon}` : `${str}`,
)
const highlightMarkdown = (source) =>
escapeHtml(source)
.split('\n')
.map((line) => {
if (/^#{1,6} /.test(line)) return `${line}`
return line
.replace(/^(\d+\. )/, '$1')
.replaceAll(/`([^`]+)`/g, '`$1`')
.replaceAll(/\*\*([^*]+)\*\*/g, '**$1**')
})
.join('\n')
const highlightAll = () => {
const kinds = { typescript: highlightTs, json: highlightJson, markdown: highlightMarkdown }
for (const [lang, fn] of Object.entries(kinds)) {
document.querySelectorAll(`pre code.language-${lang}`).forEach((block) => {
const text = (block.textContent ?? '').replace(/^\n+|\s+$/g, '')
const indent = Math.min(...text.split('\n').filter((l) => l.trim()).map((l) => l.match(/^\t*/)[0].length))
const trimmed = text.split('\n').map((l) => l.slice(indent)).join('\n')
block.innerHTML = fn(trimmed)
block.classList.add('hljs')
})
}
}
highlightAll()
const deck = new Reveal({
hash: true,
// The source deck sets hashOneBasedIndex: true. Every slide here has an id (the hash is
// #/), and with that option on Reveal's speaker view opens one slide behind, so it's off.
controls: true,
controlsTutorial: true,
controlsLayout: 'bottom-right',
controlsBackArrows: 'faded',
progress: true,
slideNumber: 'c/t',
width: 1280,
height: 720,
margin: 0,
minScale: 0.2,
maxScale: 2,
display: 'flex',
transition: staticDeck ? 'none' : 'slide',
transitionSpeed: 'slow',
backgroundTransition: 'none',
viewDistance: 10,
mobileViewDistance: 10,
navigationMode: params.has('linear') ? 'linear' : 'default',
plugins: [RevealNotes],
})
// Vertical stacks (src/slides/groups.json), like the source deck: Down / Up move within a
// stack, Left / Right move between stacks, and Space / N walk every slide in order. Coming back
// to a stack with Left / Right lands on the slide you last saw there, not its top.
const lastVerticalByStack = new Map()
const stackSize = (horizontalIndex) => {
const stack = document.querySelectorAll('.reveal .slides > section')[horizontalIndex]
if (!stack) return 1
return Math.max(stack.querySelectorAll(':scope > section').length, 1)
}
const rememberVertical = (horizontalIndex, verticalIndex) => {
lastVerticalByStack.set(horizontalIndex, verticalIndex ?? 0)
}
const restoreVertical = (horizontalIndex) => {
const remembered = lastVerticalByStack.get(horizontalIndex)
if (remembered == null) return 0
return Math.min(remembered, stackSize(horizontalIndex) - 1)
}
// Only Left / Right (keys or the arrow controls) restore a stack's slide. Deep links, the
// speaker view and other explicit deck.slide(h, v) calls go exactly where they ask.
let horizontalIntent = false
const markHorizontal = () => {
horizontalIntent = true
setTimeout(() => {
horizontalIntent = false
})
}
const wireStackMemory = () => {
if (params.has('linear')) return
document.addEventListener(
'keydown',
(event) => {
if (['ArrowLeft', 'ArrowRight', 'h', 'H', 'l', 'L'].includes(event.key)) markHorizontal()
},
true,
)
document.querySelectorAll('.reveal .controls .navigate-left, .reveal .controls .navigate-right').forEach((button) => {
button.addEventListener('click', markHorizontal, true)
})
deck.on('beforeslidechange', (event) => {
if (!horizontalIntent) return
const current = deck.getIndices()
if (event.indexh === current.h) return
// Left / Right omit a target v, so Reveal copies the current one onto the event.
if (event.indexv !== current.v) return
const verticalIndex = restoreVertical(event.indexh)
if (verticalIndex === event.indexv) return
event.preventDefault()
horizontalIntent = false
deck.slide(event.indexh, verticalIndex)
})
}
deck.on('slidechanged', (event) => rememberVertical(event.indexh, event.indexv))
// Ladder: the rung buttons advance the deck, like the source deck.
const wireHotspots = () => {
document.querySelectorAll('[data-advance]').forEach((button) => {
button.addEventListener('click', (event) => {
event.preventDefault()
deck.next()
})
})
}
// Garden: hosts arrive in a random order and climb at random speeds (off with ?static).
const shuffleGardenLanes = () => {
if (staticDeck) return
const lanes = document.querySelector('.garden-lanes')
if (!lanes) return
const order = Array.from(lanes.children)
for (let i = order.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1))
;[order[i], order[j]] = [order[j], order[i]]
}
for (const lane of order) lanes.append(lane)
}
const wireGardenClimbers = () => {
if (staticDeck) return
document.querySelectorAll('.garden-climber').forEach((climber) => {
climber.style.setProperty('--climb-duration', `${((2.6 + Math.random() * 3.2) / 1.5).toFixed(2)}s`)
climber.style.setProperty('--climb-delay', `${(Math.random() * 4.4).toFixed(2)}s`)
})
}
document.addEventListener('keydown', (event) => {
if (event.metaKey || event.ctrlKey || event.altKey) return
if (event.target instanceof HTMLElement && event.target.closest('input, textarea, [contenteditable]')) return
if (event.key === 't' || event.key === 'T') toggleTheme()
})
// Below 435px wide (a phone in portrait) Reveal switches to its scroll view, which starts at the
// first slide and overwrites the hash, and its own slide(h, v) lands one page early with vertical
// stacks. Scroll straight to the requested slide's page instead.
const requestedSlide = decodeURIComponent(location.hash.replace(/^#\/?/, '').split('/')[0])
const restoreRequestedSlide = () => {
if (!deck.isScrollView?.() || !requestedSlide || /^\d/.test(requestedSlide)) return
const target = document.getElementById(requestedSlide)
if (!target || !target.closest('.reveal .slides') || target === deck.getCurrentSlide()) return
scrollToSlidePage(target)
}
function scrollToSlidePage(target) {
const page = target.closest('.scroll-page')
const viewport = document.querySelector('.reveal-viewport')
if (page && viewport) viewport.scrollTop = page.offsetTop
}
deck.on('ready', () => {
window.__deck = deck
setTimeout(restoreRequestedSlide)
// In the scroll view Reveal can land a hash change on the slide above; settle on the target.
addEventListener('hashchange', () => {
if (!deck.isScrollView?.()) return
const target = document.getElementById(decodeURIComponent(location.hash.replace(/^#\/?/, '').split('/')[0]))
if (!target || !target.closest('.reveal .slides') || target === deck.getCurrentSlide()) return
setTimeout(() => {
if (target !== deck.getCurrentSlide()) scrollToSlidePage(target)
}, 60)
})
wireStackMemory()
const start = deck.getIndices()
rememberVertical(start.h, start.v)
wireHotspots()
window.__widgets = window.initPrimitiveWidgets(deck, { staticDeck })
shuffleGardenLanes()
wireGardenClimbers()
})
deck.initialize()