Lab 08Study
A life in weeks, one tab stop
About 4,160 weeks as one tab stop, on Vercel’s UI SDK grid focus. Only the focused row exists as real cells over the WebGL canvas, and the camera zooms 3.5× to follow the arrows.
Your life as about 4,160 dots, a row per year, each starting on your birthday. It’s one WebGL draw, not 4,160 elements, so the whole grid can move as one: the weeks fill from your first to this one in about a second, at an even pace because every week is the same length, and the weeks ahead fade toward a horizon instead of stopping at a wall.
With a keyboard it’s one tab stop. Tab lands on this week and the camera zooms in, ← → move a week, ↑ ↓ a year, Page Up and Page Down ten years, and End brings you back. The focus comes from Vercel’s UI SDK (createGridFocus): only the row you’re on exists as real cells over the canvas, so a screen reader hears each week’s dates and its place in the grid.
Move the pointer over it and a lens swells the weeks underneath, or press and hold on a phone. Press this week and the camera zooms in on it the same way Tab does, ring and all, so the arrows carry on from there. A click or Esc pulls back. What you do once you’re inside is at wy.vaunb.lu.
"use client"
import { useRouter } from "next/navigation"
import { useEffect, useEffectEvent, useMemo, useRef, useState, useSyncExternalStore } from "react"
import { useBirthDate } from "../../_lib/use-birth-date"
import { useReducedMotion } from "../../_lib/use-reduced-motion"
import { useThoughts } from "../../_lib/use-thoughts"
import { CARD_CLOSE_MS, DEMO_BIRTH, describeWeek, DIVE, DIVE_KEY, SEED_KEY, drawInOf, formatCount, indexOfDay, isoOf, lifeOf, MAX_THOUGHT, SEEN_KEY, today, WEEKS } from "../../_lib/whats-yours"
import { VERSION, WhatsYoursAbout } from "./nested/about"
import { WhatsYoursBackup } from "./nested/backup"
import { WhatsYoursBirthField } from "./nested/birth-field"
import { WhatsYoursCard } from "./nested/card"
import { WhatsYoursGrid } from "./nested/grid"
import { WhatsYoursThought } from "./nested/thought"
/* Today on this device; null on the server, which can't know your calendar. Rechecked when the tab comes back. */
const subscribeDay = (onChange: () => void) => {
document.addEventListener("visibilitychange", onChange)
return () => document.removeEventListener("visibilitychange", onChange)
}
/** The grid's exit into a week page: the last 360ms of the dive, blurring 8px as it fades. */
const LEAVE = { ms: 360, blurPx: 8 }
const useToday = () => useSyncExternalStore(subscribeDay, today, () => null)
/**
* The week you were last here in, read once per page load (so saving this visit doesn't change
* how this visit draws in). Tied to the birth date it was for.
*/
let seenAtLoad: { birth: string; lived: number } | null | undefined
function lastSeen() {
if (seenAtLoad !== undefined) return seenAtLoad
try {
const data = JSON.parse(window.localStorage.getItem(SEEN_KEY) ?? "null") as { birth?: unknown; lived?: unknown } | null
seenAtLoad = data && typeof data.birth === "string" && typeof data.lived === "number" ? { birth: data.birth, lived: data.lived } : null
} catch {
seenAtLoad = null
}
return seenAtLoad
}
/** Where typing shouldn't open the card: fields, lists and anything already open. */
const TYPING_ELSEWHERE = "input, textarea, select, [contenteditable], [role=listbox], [role=dialog], [data-no-type]"
/**
* Your life in weeks. A sample life until you add your birth date, then yours: lived weeks
* filled, the future empty, this week glowing. Open this week (or just start typing) to write
* down what's on your mind and sort it: what's yours sets into the week's dot.
*/
interface WhatsYoursProps {
/** The About and credits under the grid. Off in the Lab 08 entry, which has its own write-up. */
about?: boolean
/** On /weeks: if a dive led here (back from a week page), start inside this week and pull back out to the whole grid. */
fromIntro?: boolean
/**
* How a week opens. "zoom": the keyboard's zoom (3.5×, the ring, arrows move), a click, Esc or
* "All weeks" pulls back, with no input or sorting (the Lab 08 demo). "card": a popover over the grid. "page": dive in, then go
* to /week (or /week/<n> for a past week), carrying anything typed during the dive.
*/
opens?: "card" | "page" | "zoom"
}
/** The dive hand-off flag (sessionStorage, this tab only). Read once; cleared after mount. */
function cameFromDive() {
try {
return typeof window !== "undefined" && window.sessionStorage.getItem(DIVE_KEY) === "out"
} catch {
return false
}
}
function WhatsYours({ about = true, fromIntro = false, opens = "card" }: WhatsYoursProps) {
const router = useRouter()
const reduced = useReducedMotion()
const day = useToday()
const [birth, setBirth] = useBirthDate()
const thoughts = useThoughts()
const [shown, setShown] = useState<number | null>(null)
const [active, setActive] = useState<number | null>(null)
const [openWeek, setOpenWeek] = useState<number | null>(null)
/** The last week opened, kept while the card closes. */
const [cardWeek, setCardWeek] = useState(0)
const [seed, setSeed] = useState("")
const [settle, setSettle] = useState(0)
const [aboutOpen, setAboutOpen] = useState(false)
/** The week the camera is in. Set first; the card opens partway through the dive. */
const [dive, setDive] = useState<number | null>(null)
/** Zoom-only demo: the camera is zoomed in on a week (by a press or the keyboard). */
const [zoomed, setZoomed] = useState(false)
/** Arriving from the intro: hold the camera inside this week for a beat, then pull back. */
const [introHold, setIntroHold] = useState(() => fromIntro && cameFromDive())
/** Diving into a week page: the grid blurs and fades out over the dive's second half, so the page comes in on a clean slate. */
const [leaving, setLeaving] = useState(false)
const timer = useRef(0)
const button = useRef<HTMLElement>(null)
/* Memoized: the grid's draw-in effect keys on these objects, so a hover mustn't make new ones. */
const life = useMemo(() => (day === null ? null : (lifeOf(birth ?? DEMO_BIRTH, day) ?? lifeOf(DEMO_BIRTH, day))), [birth, day])
const kept = useMemo(() => {
const counts = new Map<number, number>()
if (!life) return counts
for (const each of thoughts.kept) {
const index = indexOfDay(life, each.day)
if (index !== null) counts.set(index, (counts.get(index) ?? 0) + 1)
}
return counts
}, [life, thoughts.kept])
/* This visit: the whole life on a first visit or a new birth date, otherwise only the weeks that passed since. */
const lifeKey = birth ?? "demo"
const drawIn = useMemo(() => {
if (!life) return null
const seen = lastSeen()
return drawInOf(life, seen?.birth === lifeKey ? seen.lived : null)
}, [life, lifeKey])
useEffect(() => {
if (!life) return
try {
window.localStorage.setItem(SEEN_KEY, JSON.stringify({ birth: lifeKey, lived: life.lived }))
} catch {
/* Not remembered: next visit plays the whole draw-in. */
}
}, [life, lifeKey])
/* A new life starts the keyboard back on this week. */
const [lastBirth, setLastBirth] = useState(birth)
if (lastBirth !== birth) {
setLastBirth(birth)
setActive(null)
}
useEffect(() => {
try {
window.sessionStorage.removeItem(DIVE_KEY)
} catch {
/* Nothing to clear. */
}
}, [])
useEffect(() => {
if (!introHold) return
const id = window.setTimeout(() => setIntroHold(false), 160)
return () => window.clearTimeout(id)
}, [introHold])
/** Opens a week: dive in first (full motion), then the card at 55% of the way. */
const seedRef = useRef("")
const openAt = (index: number, typed = "") => {
setSeed(typed)
seedRef.current = typed
setCardWeek(index)
window.clearTimeout(timer.current)
if (opens === "zoom") {
if (!reduced) setDive((current) => (current === index ? null : index))
return
}
if (opens === "page") {
/* Dive all the way in, then the week's own page. */
const go = () => {
try {
if (seedRef.current) window.sessionStorage.setItem(SEED_KEY, seedRef.current)
} catch {
/* The typed text stays behind. */
}
router.push(index === life?.lived ? "/week" : `/week/${index + 1}`)
}
if (reduced) return go()
setDive(index)
timer.current = window.setTimeout(() => {
setLeaving(true)
timer.current = window.setTimeout(go, LEAVE.ms)
}, DIVE.openMs - LEAVE.ms)
return
}
if (reduced) return setOpenWeek(index)
setDive(index)
timer.current = window.setTimeout(() => setOpenWeek(index), DIVE.openMs * DIVE.cardAt)
}
/* Arriving with ?thought= (Today's “Add to this week”): open this week with it in the field, once. Read after mount, when the URL has settled. */
const used = useRef(false)
useEffect(() => {
if (!life || used.current) return
const incoming = new URLSearchParams(window.location.search).get("thought")?.slice(0, MAX_THOUGHT)
if (!incoming) return
const id = window.setTimeout(() => {
used.current = true
window.history.replaceState(null, "", window.location.pathname)
openAt(life.lived, incoming)
}, 500)
return () => window.clearTimeout(id)
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [life])
/** Closes it: the card shrinks first, then the camera pulls back. */
const close = () => {
setOpenWeek(null)
window.clearTimeout(timer.current)
timer.current = window.setTimeout(() => setDive(null), CARD_CLOSE_MS * 0.6)
}
/* Type anywhere: a letter typed on the page opens this week with it in the field. */
const onType = useEffectEvent((event: KeyboardEvent) => {
if (!life) return
/* Zoom only: Esc pulls back out, and typing does nothing. */
if (opens === "zoom") {
if (event.key === "Escape" && dive !== null) setDive(null)
return
}
if (event.defaultPrevented || event.isComposing || event.metaKey || event.ctrlKey || event.altKey) return
if (event.key.length !== 1) return
if ((event.target as Element | null)?.closest?.(TYPING_ELSEWHERE)) return
const opening = (openWeek ?? dive) === life.lived
/* Space only counts once the card is on its way (it scrolls the page otherwise). */
if (event.key === " " && !opening) return
event.preventDefault()
if (opening) {
seedRef.current = (seedRef.current + event.key).slice(0, MAX_THOUGHT)
setSeed((each) => (each + event.key).slice(0, MAX_THOUGHT))
return
}
setActive(null)
openAt(life.lived, event.key)
})
useEffect(() => {
const onKey = (event: KeyboardEvent) => onType(event)
document.addEventListener("keydown", onKey)
return () => document.removeEventListener("keydown", onKey)
}, [])
const readout = (() => {
if (!life) return " "
if (shown !== null) {
const week = describeWeek(life, shown)
return `${week.range} · ${week.age} · ${week.state}`
}
if (drawIn?.passed) return `${formatCount(drawIn.passed)} ${drawIn.passed === 1 ? "week" : "weeks"} since you were here`
return `Week ${formatCount(life.lived + 1)} of ${formatCount(life.rows * WEEKS)}`
})()
const hasData = !!birth || thoughts.open.length > 0 || thoughts.kept.length > 0
const aboutShown = about && aboutOpen
return (
<div
className="flex w-full max-w-[28rem] flex-col items-center gap-6"
style={
leaving
? { opacity: 0, filter: `blur(${LEAVE.blurPx}px)`, transition: `opacity ${LEAVE.ms}ms ease-in, filter ${LEAVE.ms}ms ease-in` }
: undefined
}
>
{opens === "zoom" && zoomed ? (
/* Zoomed in (demo): the readout becomes the way back out. Focus leaving the grid pulls the camera back (Safari keeps it on the cell when a button is clicked, so blur it). */
<button
type="button"
onClick={() => (document.activeElement as HTMLElement | null)?.blur()}
className="-my-3.5 flex min-h-11 items-center gap-1.5 rounded-md px-2 font-mono text-xs text-ink transition-colors duration-150 can-hover:text-ink-muted focus-visible:outline-2 focus-visible:outline-teal"
>
<span aria-hidden>←</span> All weeks <span className="text-ink-faint pointer-coarse:hidden">· Esc</span>
</button>
) : (
<p className="flex h-4 items-center gap-2 font-mono text-xs whitespace-nowrap text-ink-muted tabular-nums" aria-hidden={shown !== null}>
{readout}
</p>
)}
<div className="flex w-full justify-center">
{life ? (
<WhatsYoursGrid
life={life}
reduced={reduced}
replay={lifeKey}
drawIn={drawIn ?? undefined}
kept={kept}
active={active}
onActiveChange={setActive}
buttonRef={button}
settle={settle}
dive={introHold ? life.lived : dive}
onShow={setShown}
onOpen={(index) => openAt(index)}
pressZooms={opens === "zoom"}
onZoomChange={opens === "zoom" ? setZoomed : undefined}
/>
) : (
<div className="w-full" style={{ aspectRatio: `${WEEKS} / 86` }} />
)}
</div>
{life && day !== null && (
<>
{opens === "card" && (
<WhatsYoursCard
life={life}
week={cardWeek}
open={openWeek !== null}
onClose={close}
anchor={button}
today={day}
thoughts={thoughts}
actions={thoughts}
seed={seed}
onKept={() => setSettle((each) => each + 1)}
reduced={reduced}
/>
)}
{/* Under the grid, centered: your birth date, then About. The zoom-only demo has the date alone. */}
{opens === "zoom" && (
<div data-no-type className="flex w-full justify-center">
<WhatsYoursBirthField value={birth} max={isoOf(day)} onChange={setBirth} />
</div>
)}
{opens !== "zoom" && (
<div className="flex w-full flex-col items-center gap-1">
<div data-no-type>
<WhatsYoursBirthField value={birth} max={isoOf(day)} onChange={setBirth} />
</div>
{about ? (
<button
type="button"
aria-expanded={aboutShown}
aria-controls="whats-yours-about"
onClick={() => setAboutOpen(!aboutShown)}
className="flex min-h-11 items-center gap-1.5 rounded-md px-2 text-xs text-ink-faint transition-colors duration-150 can-hover:text-ink focus-visible:outline-2 focus-visible:outline-teal aria-expanded:text-ink"
>
About <span className="font-mono tabular-nums">v{VERSION}</span>
</button>
) : null}
</div>
)}
{aboutShown && opens !== "zoom" && (
<WhatsYoursAbout id="whats-yours-about">
{hasData && (
<WhatsYoursBackup
birth={birth}
store={thoughts}
onImport={(backupBirth, store) => {
/* A backup's birth date only fills in a missing one: it never replaces yours. */
if (backupBirth && !birth) setBirth(backupBirth)
return thoughts.merge(store)
}}
/>
)}
</WhatsYoursAbout>
)}
</>
)}
</div>
)
}
WhatsYours.Grid = WhatsYoursGrid
WhatsYours.Card = WhatsYoursCard
WhatsYours.Thought = WhatsYoursThought
WhatsYours.BirthField = WhatsYoursBirthField
WhatsYours.About = WhatsYoursAbout
WhatsYours.Backup = WhatsYoursBackup
export { WhatsYours }