Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

feat(kb): design overhaul (#51565)

Anthony Liod9faba5a2cc5
diff --git a/apps/docs/components/AiTools.tsx b/apps/docs/components/AiTools.tsx
index 8864b10822d..c1def0dd818 100644
--- a/apps/docs/components/AiTools.tsx
+++ b/apps/docs/components/AiTools.tsx
@@ -1,13 +1,9 @@
'use client'
import { useSendTelemetryEvent } from '~/lib/telemetry'
-import { askAiUrls, useCopyMarkdownFromUrl } from 'common'
import { type MarkdownAffordancePageType } from 'common/telemetry-constants'
-import { Chatgpt, Claude, Google } from 'icons'
-import { Check, Copy, Sparkles } from 'lucide-react'
-import Link from 'next/link'
import { usePathname } from 'next/navigation'
-import { cn } from 'ui'
+import { AiTools as SharedAiTools, type AiAgent } from 'ui-patterns/AiTools'
function AiTools({
pageType,
@@ -24,108 +20,47 @@ function AiTools({
}) {
const path = usePathname()
const sendTelemetryEvent = useSendTelemetryEvent()
- const { copied, copyMarkdown } = useCopyMarkdownFromUrl()
- const urls = askAiUrls(`https://supabase.com/docs${path}`)
function handleAgentSetupClick() {
sendTelemetryEvent({ action: 'agent_setup_clicked' })
}
- async function handleCopy() {
- const ok = await copyMarkdown(`/docs${path}.md`, {
- fallback: () => document.getElementById(articleId)?.innerHTML ?? '',
- })
- if (ok) {
- sendTelemetryEvent({ action: 'copy_as_markdown_clicked', properties: { pageType } })
- }
+ function handleMarkdownCopy() {
+ sendTelemetryEvent({ action: 'copy_as_markdown_clicked', properties: { pageType } })
+ }
+
+ function handlePreferredSourceClick() {
+ sendTelemetryEvent({ action: 'preferred_source_clicked', properties: { pageType } })
+ }
+
+ function handleAskAiClick(agent: AiAgent) {
+ sendTelemetryEvent({ action: 'ask_ai_clicked', properties: { agent, pageType } })
+ }
+
+ function getArticleHtml() {
+ return document.getElementById(articleId)?.innerHTML ?? ''
}
return (
- <section className={className} aria-labelledby="ai-tools-title">
- <h2
- id="ai-tools-title"
- className={cn(
- 'mb-3',
- pageType === 'troubleshooting'
- ? 'text-sm text-foreground-lighter'
- : 'block font-mono uppercase text-xs text-foreground-light'
- )}
- >
- AI tools
- </h2>
- <div className="flex flex-col gap-2">
- {showAgentSetup && (
- <Link
- href="/guides/ai-tools"
- onClick={handleAgentSetupClick}
- className="flex items-center gap-1.5 text-xs text-foreground-lighter hover:text-foreground transition-colors"
- >
- <Sparkles size={14} strokeWidth={1.5} />
- Connect your AI agent
- </Link>
- )}
- <button
- tabIndex={0}
- onClick={handleCopy}
- className="flex cursor-pointer items-center gap-1.5 text-xs text-foreground-lighter hover:text-foreground text-left transition-colors"
- >
- {copied ? (
- <Check size={14} strokeWidth={1.5} className="text-primary" aria-hidden />
- ) : (
- <Copy size={14} strokeWidth={1.5} aria-hidden />
- )}
- {copied ? 'Copied!' : 'Copy as Markdown'}
- </button>
- <span className="sr-only" role="status">
- {copied ? 'Copied to clipboard' : ''}
- </span>
- <a
- href={urls.chatgpt}
- target="_blank"
- onClick={() =>
- sendTelemetryEvent({
- action: 'ask_ai_clicked',
- properties: { agent: 'chatgpt', pageType },
- })
- }
- rel="noreferrer noopener"
- className="flex items-center gap-1.5 text-xs text-foreground-lighter hover:text-foreground transition-colors"
- >
- <Chatgpt size={14} aria-hidden />
- Ask ChatGPT
- </a>
- <a
- href={urls.claude}
- target="_blank"
- onClick={() =>
- sendTelemetryEvent({
- action: 'ask_ai_clicked',
- properties: { agent: 'claude', pageType },
- })
- }
- rel="noreferrer noopener"
- className="flex items-center gap-1.5 text-xs text-foreground-lighter hover:text-foreground transition-colors"
- >
- <Claude size={14} aria-hidden />
- Ask Claude
- </a>
- {showPreferredSource && (
- <a
- href="https://www.google.com/preferences/source?q=supabase.com"
- target="_blank"
- title="Add Supabase as a preferred source on Google"
- rel="noreferrer noopener"
- onClick={() =>
- sendTelemetryEvent({ action: 'preferred_source_clicked', properties: { pageType } })
- }
- className="flex items-center gap-1.5 text-xs text-foreground-lighter hover:text-foreground transition-colors"
- >
- <Google size={14} aria-hidden />
- Prefer on Google
- </a>
- )}
- </div>
- </section>
+ <SharedAiTools
+ pageUrl={`https://supabase.com/docs${path}`}
+ markdownUrl={`/docs${path}.md`}
+ markdownFallback={getArticleHtml}
+ agentSetupHref={showAgentSetup ? '/docs/guides/ai-tools' : undefined}
+ preferredSourceHref={
+ showPreferredSource ? 'https://www.google.com/preferences/source?q=supabase.com' : undefined
+ }
+ onAgentSetupClick={handleAgentSetupClick}
+ onPreferredSourceClick={handlePreferredSourceClick}
+ onMarkdownCopy={handleMarkdownCopy}
+ onAskAiClick={handleAskAiClick}
+ titleClassName={
+ pageType === 'troubleshooting'
+ ? 'font-sans text-sm normal-case text-foreground-lighter'
+ : undefined
+ }
+ className={className}
+ />
)
}
diff --git a/apps/docs/components/GuidesSidebar.tsx b/apps/docs/components/GuidesSidebar.tsx
index 175d333ede0..ade9fee5550 100644
--- a/apps/docs/components/GuidesSidebar.tsx
+++ b/apps/docs/components/GuidesSidebar.tsx
@@ -6,7 +6,7 @@ import { isFeatureEnabled } from 'common'
import { usePathname } from 'next/navigation'
import { cn } from 'ui'
import { ExpandableVideo } from 'ui-patterns/ExpandableVideo'
-import { Toc, TOCItems, TOCScrollArea } from 'ui-patterns/Toc'
+import { TocSection } from 'ui-patterns/Toc'
import { useTocAnchors } from '../features/docs/GuidesMdx.state'
@@ -55,16 +55,7 @@ const GuidesSidebar = ({
showPreferredSource
/>
</div>
- {!hideToc && toc.length !== 0 && (
- <Toc className="-ml-[calc(0.25rem+6px)]">
- <h3 className="inline-flex items-center gap-1.5 font-mono text-xs uppercase text-foreground pl-[calc(1.5rem+6px)]">
- On this page
- </h3>
- <TOCScrollArea>
- <TOCItems items={toc} />
- </TOCScrollArea>
- </Toc>
- )}
+ {!hideToc && toc.length !== 0 && <TocSection items={toc} />}
</div>
</div>
)
diff --git a/apps/docs/components/Navigation/NavigationMenu/NavigationMenu.constants.ts b/apps/docs/components/Navigation/NavigationMenu/NavigationMenu.constants.ts
index 61ee0ae53bc..1315f3c57cf 100644
--- a/apps/docs/components/Navigation/NavigationMenu/NavigationMenu.constants.ts
+++ b/apps/docs/components/Navigation/NavigationMenu/NavigationMenu.constants.ts
@@ -342,6 +342,11 @@ export const GLOBAL_MENU_ITEMS: GlobalMenuItems = [
href: '/guides/troubleshooting' as `/${string}`,
level: 'troubleshooting',
},
+ {
+ label: 'Knowledge base',
+ icon: 'resources',
+ href: 'https://supabase.com/kb',
+ },
],
],
},
diff --git a/apps/docs/features/directives/CodeSample.client.tsx b/apps/docs/features/directives/CodeSample.client.tsx
index e609d3236ca..15d1360d455 100644
--- a/apps/docs/features/directives/CodeSample.client.tsx
+++ b/apps/docs/features/directives/CodeSample.client.tsx
@@ -11,6 +11,7 @@ import {
IconGitHubSolid,
} from 'ui'
import { Admonition } from 'ui-patterns/Admonition'
+import { getNotchFocusRing, getNotchMask, getNotchOutline } from 'ui-patterns/Notch'
interface CodeSampleWrapperProps {
source: string | URL | (string | URL)[]
@@ -37,17 +38,6 @@ export const SOURCE_FOOTER_CLASSES = cn(
const DEFAULT_NOTCH_WIDTH = 117
-const getNotchOutline = (width: number): string =>
- `M0 39.5A7.5 7.5 0 0 0 7.5 32V16A8.5 8.5 0 0 1 16 7.5H${width}A7.5 7.5 0 0 0 ${width + 7.5} 0`
-
-const getNotchFocusRing = (width: number): string =>
- `M0 41A9 9 0 0 0 9 32V16A7 7 0 0 1 16 9H${width}A9 9 0 0 0 ${width + 9} 0`
-
-const getNotchMask = (width: number): string =>
- `url("data:image/svg+xml,${encodeURIComponent(
- `<svg xmlns='http://www.w3.org/2000/svg' width='${width + 10}' height='42'><path d='M0 40A8 8 0 0 0 8 32V16A8 8 0 0 1 16 8H${width}A8 8 0 0 0 ${width + 8} 0H${width + 10}V42H0Z'/></svg>`
- )}")`
-
const getSourcePath = (source: string | URL): string => {
const [, org, repo, , , ...path] = new URL(source).pathname.split('/')
return `${org}/${repo}/${path.join('/')}`
diff --git a/apps/kb/scripts/generate-markdown.mjs b/apps/kb/scripts/generate-markdown.mjs
index 1fa5d27e7e0..fb133e2c4c9 100644
--- a/apps/kb/scripts/generate-markdown.mjs
+++ b/apps/kb/scripts/generate-markdown.mjs
@@ -15,7 +15,7 @@ import { visit } from 'unist-util-visit'
import YAML from 'yaml'
import { BASE_PATH } from '../src/lib/constants.ts'
-import { TOPICS, topicToSlug } from '../src/lib/topics.ts'
+import { isInTopic, TOPICS, topicToSlug } from '../src/lib/topics.ts'
const SCRIPT_DIR = path.dirname(fileURLToPath(import.meta.url))
const CONTENT_DIR = path.join(SCRIPT_DIR, '..', 'src', 'content')
@@ -28,9 +28,8 @@ const SITE_ORIGIN = 'https://supabase.com'
// Single processor reused for every file: parses GFM markdown to an mdast
// tree and serializes it back, same extensions on both ends so nothing
// (tables, strikethrough, alert blockquotes) gets mangled in the round trip.
-// `emphasis`/`rule` match the markers content already uses (see
-// src/content/guides/sample-guide.mdx) so the round trip doesn't normalize
-// authors' `_italic_`/`---` into the serializer's own `*italic*`/`***`.
+// `emphasis`/`rule` match the markers content already uses, so the round trip
+// doesn't normalize authors' `_italic_`/`---` into the serializer's own `*italic*`/`***`.
const processor = unified()
.use(remarkParse)
.use(remarkGfm)
@@ -166,8 +165,6 @@ async function writeFileEnsuringDir(outputPath, contents) {
async function main() {
const files = await findContentFiles(CONTENT_DIR)
- // Only entries with a `topics` array (currently just the `guides`
- // collection) feed the per-topic index pages below.
const guidesByTopic = new Map(TOPICS.map((topic) => [topic.name, []]))
await Promise.all(
@@ -180,10 +177,12 @@ async function main() {
const outputPath = path.join(OUTPUT_DIR, toMdExtension(relativePath))
await writeFileEnsuringDir(outputPath, markdown)
- if (!Array.isArray(data.topics)) return
+ // the first folder under src/content is the collection, e.g. guides or troubleshooting
+ const collection = relativePath.split(path.sep)[0]
+ const topics = Array.isArray(data.topics) ? data.topics : []
const guide = { title: data.title, url: toGuideUrl(relativePath) }
- for (const topicName of data.topics) {
- guidesByTopic.get(topicName)?.push(guide)
+ for (const { name } of TOPICS) {
+ if (isInTopic({ collection, topics, topic: name })) guidesByTopic.get(name).push(guide)
}
})
)
diff --git a/apps/kb/src/assets/grain.webp b/apps/kb/src/assets/grain.webp
new file mode 100644
index 00000000000..0f9d5ef1ecc
Binary files /dev/null and b/apps/kb/src/assets/grain.webp differ
diff --git a/apps/kb/src/components/AsciiCanvas.tsx b/apps/kb/src/components/AsciiCanvas.tsx
new file mode 100644
index 00000000000..13447e0c97a
--- /dev/null
+++ b/apps/kb/src/components/AsciiCanvas.tsx
@@ -0,0 +1,370 @@
+import { useCallback, type RefObject } from 'react'
+import { cn } from 'ui'
+
+import {
+ BLOCK_GLYPHS,
+ buildMask,
+ cellRange,
+ createRng,
+ decayEnergy,
+ drawStep,
+ GLYPH_PITCH,
+ glyphRun,
+ latticeSize,
+ phase,
+ snapRect,
+ type Lattice,
+ type PixelRect,
+} from '../lib/ascii/field'
+import { loadGrain, punchGrain } from '../lib/ascii/grain'
+import { sizeLayers } from '../lib/ascii/layer'
+import { easeOutCubic } from '../lib/ascii/warp'
+import { ColorProbes, observeTheme, readProbeColor } from './ColorProbes'
+
+export interface CanvasSize {
+ width: number
+ height: number
+}
+
+interface FieldParams {
+ lattice: Lattice
+ seed: number
+ mask: Uint8Array
+}
+
+export interface AsciiCanvasProps {
+ getLattice: (size: CanvasSize) => Lattice
+ getField: (params: FieldParams) => Float32Array
+ keepOutRefs?: RefObject<HTMLElement | null>[]
+ keepOutMargin?: number
+ words?: string[]
+ decay?: number
+ className?: string
+}
+
+interface RunParams {
+ index: number
+ quantized: number
+ capacity: number
+}
+
+interface IngestedWord {
+ word: string
+ startedAt: number
+}
+
+interface VisibleLettersParams {
+ ingest: IngestedWord
+ now: number
+}
+
+interface Palette {
+ background: string
+ grid: string
+ muted: string
+ hot: string
+}
+
+const CELL_PADDING = 8
+const DENSITY_STEPS = 8
+const TYPE_SPAN = 0.2
+const LETTER_STEP_MS = 90
+const LETTER_SCRAMBLE_MS = 240
+
+const PROBES = {
+ grid: 'text-border-muted',
+ muted: 'text-foreground-muted',
+ hot: 'text-foreground-lighter',
+ background: 'text-background',
+} as const
+
+// knuth hash gives each cell a stable random start, capped so the last cell finishes with the reveal
+const revealOrder = (index: number) =>
+ ((Math.imul(index + 1, 2654435761) >>> 0) / 2 ** 32) * (1 - TYPE_SPAN)
+
+const visibleLetters = ({ ingest, now }: VisibleLettersParams) => {
+ const { word, startedAt } = ingest
+ const heldUntil = word.length * LETTER_STEP_MS + LETTER_SCRAMBLE_MS + 900
+ return word.length - Math.max(0, Math.floor((now - startedAt - heldUntil) / LETTER_STEP_MS))
+}
+
+const readPalette = (probeRoot: HTMLElement, host: HTMLElement): Palette => {
+ const hostBackground = getComputedStyle(host).backgroundColor
+ const read = (role: keyof typeof PROBES) => readProbeColor(probeRoot, role)
+ return {
+ background:
+ hostBackground === 'transparent' || hostBackground.endsWith(', 0)')
+ ? read('background')
+ : hostBackground,
+ grid: read('grid'),
+ muted: read('muted'),
+ hot: read('hot'),
+ }
+}
+
+const relativeRect = (element: HTMLElement, origin: DOMRect): PixelRect => {
+ const rect = element.getBoundingClientRect()
+ return {
+ left: rect.left - origin.left,
+ top: rect.top - origin.top,
+ right: rect.right - origin.left,
+ bottom: rect.bottom - origin.top,
+ }
+}
+
+export const AsciiCanvas = ({
+ getLattice,
+ getField,
+ keepOutRefs = [],
+ keepOutMargin = 1,
+ words = [],
+ decay = 0.92,
+ className,
+}: AsciiCanvasProps) => {
+ const setupCanvas = useCallback((canvas: HTMLCanvasElement | null) => {
+ const host = canvas?.parentElement
+ const ctx = canvas?.getContext('2d')
+ if (!canvas || !host || !ctx) return
+
+ const isReducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches
+ const seed = Math.floor(Math.random() * 2 ** 31)
+ const probeRoot = canvas.nextElementSibling
+ if (!(probeRoot instanceof HTMLElement)) return
+
+ let grain: CanvasPattern | null = null
+ loadGrain(ctx).then((pattern) => {
+ grain = pattern
+ draw()
+ })
+ let palette = readPalette(probeRoot, host)
+ let lattice: Lattice = { xs: [0], ys: [0] }
+ let base: Float32Array = new Float32Array(0)
+ let energy: Float32Array = new Float32Array(0)
+ let mask: Uint8Array = new Uint8Array(0)
+ let cutouts: PixelRect[] = []
+ let measuredKey = ''
+ let isDisposed = false
+ const runs = new Map<number, string>()
+ const ingested = new Map<number, IngestedWord>()
+ let isVisible = false
+ let frame = 0
+ const observed = new Set<HTMLElement>()
+ const revealStartedAt = performance.now()
+
+ const isRunning = () => isVisible && document.visibilityState === 'visible'
+
+ const revealProgress = () =>
+ isReducedMotion ? 1 : Math.min(1, (performance.now() - revealStartedAt) / 1000)
+
+ const keepOutCell = (rect: PixelRect, margin: number) =>
+ snapRect({ lattice, rect: { ...rect, top: rect.top - 1 }, margin })
+
+ const capacityAt = (c: number) =>
+ Math.max(1, Math.floor((lattice.xs[c + 1] - lattice.xs[c] - CELL_PADDING * 2) / GLYPH_PITCH))
+
+ const getRun = ({ index, quantized, capacity }: RunParams) => {
+ const runKey = index * (DENSITY_STEPS + 1) + quantized
+ const cached = runs.get(runKey)
+ if (cached !== undefined) return cached
+ const run = glyphRun({
+ density: quantized / DENSITY_STEPS,
+ capacity,
+ rand: createRng(seed + index * 97 + quantized),
+ })
+ runs.set(runKey, run)
+ return run
+ }
+
+ const draw = () => {
+ const { cols, rows } = latticeSize(lattice)
+ const { xs, ys } = lattice
+ const width = canvas.clientWidth
+ const height = canvas.clientHeight
+ const t = revealProgress()
+ const across = drawStep(phase({ t, start: 0, length: 0.5 }))
+ const down = drawStep(phase({ t, start: 0.25, length: 0.5 }))
+ const reveal = easeOutCubic(phase({ t, start: 0.4, length: 0.6 }))
+ ctx.clearRect(0, 0, width, height)
+
+ ctx.strokeStyle = palette.grid
+ ctx.lineWidth = 1
+ ctx.beginPath()
+ for (let i = 1; i < lattice.xs.length - 1; i++) {
+ ctx.moveTo(Math.round(lattice.xs[i]) + 0.5, 0)
+ ctx.lineTo(Math.round(lattice.xs[i]) + 0.5, height * down)
+ }
+ for (let i = 1; i < lattice.ys.length - 1; i++) {
+ ctx.moveTo(0, Math.round(lattice.ys[i]) + 0.5)
+ ctx.lineTo(width * across, Math.round(lattice.ys[i]) + 0.5)
+ }
+ ctx.stroke()
+ if (grain) {
+ punchGrain({ ctx, pattern: grain, width, height })
+ }
+
+ ctx.fillStyle = palette.background
+ for (const rect of cutouts) {
+ const cell = keepOutCell(rect, 0)
+ if (!cell) continue
+ const left = Math.round(cell.left) + 1
+ const top = Math.round(cell.top) + 1
+ ctx.fillRect(left, top, Math.round(cell.right) - left, Math.round(cell.bottom) - top)
+ }
+
+ ctx.font = '12px ui-monospace, SFMono-Regular, Menlo, monospace'
+ ctx.textAlign = 'center'
+ ctx.textBaseline = 'middle'
+ const now = performance.now()
+ for (let r = 0; r < rows; r++) {
+ const cy = (ys[r] + ys[r + 1]) / 2
+ for (let c = 0; c < cols; c++) {
+ const index = r * cols + c
+ if (mask[index] || revealOrder(index) > reveal) continue
+ const density = Math.min(1, base[index] + energy[index])
+ const ingest = ingested.get(index)
+ if (density <= 0 && !ingest) continue
+ const cellWidth = xs[c + 1] - xs[c]
+ const capacity = capacityAt(c)
+ const run = getRun({ index, quantized: Math.round(density * DENSITY_STEPS), capacity })
+ const typed = Math.ceil(
+ Math.min(1, (reveal - revealOrder(index)) / TYPE_SPAN) * run.length
+ )
+ const runStart =
+ capacity === 1 ? xs[c] + cellWidth / 2 : xs[c] + CELL_PADDING + GLYPH_PITCH / 2
+ const runColor = energy[index] > 0.15 ? palette.hot : palette.muted
+ const shown = ingest ? visibleLetters({ ingest, now }) : 0
+ if (ingest && shown <= 0) ingested.delete(index)
+ if (ingest && shown > 0) {
+ const elapsed = now - ingest.startedAt
+ const wordStart = xs[c] + CELL_PADDING + GLYPH_PITCH / 2
+ ctx.fillStyle = palette.hot
+ for (let i = 0; i < shown; i++) {
+ const since = elapsed - i * LETTER_STEP_MS
+ if (since < 0) break
+ const char =
+ since < LETTER_SCRAMBLE_MS
+ ? BLOCK_GLYPHS[Math.floor(since / 70) % BLOCK_GLYPHS.length]
+ : ingest.word[i]
+ ctx.fillText(char, wordStart + i * GLYPH_PITCH, cy)
+ }
+ if (shown < ingest.word.length) {
+ ctx.fillStyle = runColor
+ for (let i = shown; i < typed; i++) {
+ ctx.fillText(run[i], runStart + i * GLYPH_PITCH, cy)
+ }
+ }
+ continue
+ }
+ ctx.fillStyle = runColor
+ for (let i = 0; i < typed; i++) ctx.fillText(run[i], runStart + i * GLYPH_PITCH, cy)
+ }
+ }
+ }
+
+ const tick = () => {
+ frame = 0
+ draw()
+ const isHot = decayEnergy({ energy, factor: decay })
+ if ((isHot || ingested.size > 0 || revealProgress() < 1) && isRunning()) {
+ frame = requestAnimationFrame(tick)
+ }
+ }
+
+ const wake = () => {
+ if (!frame && isRunning() && !isReducedMotion) frame = requestAnimationFrame(tick)
+ }
+
+ const measure = () => {
+ if (isDisposed) return
+ const width = host.clientWidth
+ const height = host.clientHeight
+ const dpr = window.devicePixelRatio || 1
+ const origin = canvas.getBoundingClientRect()
+ const keepOuts = keepOutRefs.flatMap((ref) => (ref.current ? [ref.current] : []))
+ for (const element of keepOuts) {
+ if (observed.has(element)) continue
+ observed.add(element)
+ resizeObserver.observe(element)
+ }
+ const nextCutouts = keepOuts.map((element) => relativeRect(element, origin))
+ const key = JSON.stringify([width, height, dpr, nextCutouts])
+ if (key === measuredKey) return
+ measuredKey = key
+
+ sizeLayers({ contexts: [ctx], width, height })
+ lattice = getLattice({ width, height })
+ cutouts = nextCutouts
+ runs.clear()
+ ingested.clear()
+ const safeAreas = cutouts.flatMap((rect) => keepOutCell(rect, keepOutMargin) ?? [])
+ mask = buildMask({ lattice, rects: safeAreas, margin: 0 })
+ base = getField({ lattice, seed, mask })
+ energy = new Float32Array(base.length)
+ draw()
+ }
+
+ const typeWordAt = (event: PointerEvent) => {
+ if (isReducedMotion || energy.length === 0) return
+ const origin = canvas.getBoundingClientRect()
+ const x = event.clientX - origin.left
+ const y = event.clientY - origin.top
+ const point = { left: x, right: x + 1, top: y, bottom: y + 1 }
+ const cell = cellRange({ lattice, rect: point, margin: 0 })
+ if (!cell) return
+ const index = cell.r0 * latticeSize(lattice).cols + cell.c0
+ if (mask[index]) return
+ energy[index] = 0.9
+ const shownWords = new Set([...ingested.values()].map(({ word }) => word))
+ const fitting = words.filter((word) => word.length <= capacityAt(cell.c0))
+ const unseen = fitting.filter((word) => !shownWords.has(word))
+ const pool = unseen.length > 0 ? unseen : fitting
+ if (pool.length > 0) {
+ const word = pool[Math.floor(Math.random() * pool.length)]
+ ingested.set(index, { word, startedAt: performance.now() })
+ } else {
+ ingested.delete(index)
+ }
+ wake()
+ }
+
+ const resizeObserver = new ResizeObserver(measure)
+ resizeObserver.observe(host)
+
+ const intersectionObserver = new IntersectionObserver(([entry]) => {
+ isVisible = entry.isIntersecting
+ wake()
+ })
+ intersectionObserver.observe(canvas)
+
+ const unobserveTheme = observeTheme(() => {
+ palette = readPalette(probeRoot, host)
+ draw()
+ })
+
+ host.addEventListener('pointerdown', typeWordAt)
+ document.addEventListener('visibilitychange', wake)
+ document.fonts?.ready.then(measure)
+ if (!isReducedMotion) wake()
+
+ return () => {
+ isDisposed = true
+ cancelAnimationFrame(frame)
+ resizeObserver.disconnect()
+ intersectionObserver.disconnect()
+ unobserveTheme()
+ host.removeEventListener('pointerdown', typeWordAt)
+ document.removeEventListener('visibilitychange', wake)
+ }
+ }, [])
+
+ return (
+ <>
+ <canvas
+ ref={setupCanvas}
+ aria-hidden
+ className={cn('pointer-events-none absolute inset-0 size-full', className)}
+ />
+ <ColorProbes probes={PROBES} />
+ </>
+ )
+}
diff --git a/apps/kb/src/components/AsciiHoverText.tsx b/apps/kb/src/components/AsciiHoverText.tsx
new file mode 100644
index 00000000000..b81df986b54
--- /dev/null
+++ b/apps/kb/src/components/AsciiHoverText.tsx
@@ -0,0 +1,47 @@
+import { cn } from 'ui'
+
+import { hash, RAMP } from '../lib/ascii/field'
+
+export interface AsciiHoverTextProps {
+ text: string
+ glyphClassName: string
+ className?: string
+}
+
+export const ASCII_HOVER_CLASS = cn(
+ 'relative',
+ 'after:pointer-events-none after:absolute after:inset-0 after:flex after:items-center after:justify-center',
+ 'after:font-mono after:text-[0.72em] after:leading-none after:opacity-0',
+ 'after:content-[attr(data-glyph)]',
+ 'hover:text-transparent hover:after:opacity-100',
+ '[:hover+&]:text-transparent [:hover+&]:after:opacity-60 [:hover+&]:after:content-["░"]',
+ '[&:has(+:hover)]:text-transparent [&:has(+:hover)]:after:opacity-60 [&:has(+:hover)]:after:content-["░"]'
+)
+
+export const hoverGlyph = (position: number, char: string): string =>
+ RAMP[1 + Math.floor(hash(position, char.charCodeAt(0)) * (RAMP.length - 1))]
+
+export const AsciiHoverText = ({ text, glyphClassName, className }: AsciiHoverTextProps) => {
+ const characters = Array.from(text).map((char, position) => ({
+ id: `${position}:${char}`,
+ char,
+ glyph: hoverGlyph(position, char),
+ }))
+
+ return (
+ <span className={className}>
+ <span className="sr-only">{text}</span>
+ <span aria-hidden>
+ {characters.map(({ id, char, glyph }) =>
+ char === ' ' ? (
+ ' '
+ ) : (
+ <span key={id} data-glyph={glyph} className={cn(ASCII_HOVER_CLASS, glyphClassName)}>
+ {char}
+ </span>
+ )
+ )}
+ </span>
+ </span>
+ )
+}
diff --git a/apps/kb/src/components/Card.astro b/apps/kb/src/components/Card.astro
deleted file mode 100644
index 8784427734e..00000000000
--- a/apps/kb/src/components/Card.astro
+++ /dev/null
@@ -1,45 +0,0 @@
----
-// Small "glass panel" card, adapted from apps/docs' GlassPanel
-// (packages/ui-patterns/src/GlassPanel/index.tsx) — same surface treatment
-// (bg-surface-75, hover:border-strong), trimmed to what kb needs: no
-// logo/icon-picker machinery, which pulled in next/image and next-themes
-// that don't apply to a plain Astro app.
-//
-// Unlike GlassPanel (always a plain <div>, link-agnostic — every call site
-// in docs wraps it in a Next.js <Link>), this renders as an <a> itself when
-// `href` is given. That's only safe because `topics` render as plain,
-// non-linked badges — nothing inside the card is itself a link, so there's
-// no nested-<a> problem.
-import { Badge } from 'ui'
-
-interface Props {
- href?: string
- title: string
- description?: string
- topics?: string[]
- class?: string
-}
-
-const { href, title, description, topics = [], class: className } = Astro.props
-const Tag = href ? 'a' : 'div'
----
-
-<Tag
- href={href}
- class:list={[
- 'relative flex h-full flex-col gap-2 rounded-lg border border-default bg-surface-75 p-5 text-left transition hover:border-strong',
- className,
- ]}
->
- <h2 class="m-0 text-base font-medium text-foreground">{title}</h2>
- {description && <p class="m-0 text-sm text-foreground-light">{description}</p>}
- {
- topics.length > 0 && (
- <div class="mt-2 flex flex-wrap gap-2">
- {topics.map((topic) => (
- <Badge>{topic}</Badge>
- ))}
- </div>
- )
- }
-</Tag>
diff --git a/apps/kb/src/components/ColorProbes.tsx b/apps/kb/src/components/ColorProbes.tsx
new file mode 100644
index 00000000000..502c066b16d
--- /dev/null
+++ b/apps/kb/src/components/ColorProbes.tsx
@@ -0,0 +1,23 @@
+export interface ColorProbesProps {
+ probes: Record<string, string>
+}
+
+export const readProbeColor = (probeRoot: HTMLElement, role: string): string => {
+ const probe = probeRoot.querySelector<HTMLElement>(`[data-probe="${role}"]`)
+ return probe ? getComputedStyle(probe).color : 'transparent'
+}
+
+// the probes' colors change with the theme, so a canvas reads them again and redraws
+export const observeTheme = (onChange: () => void): (() => void) => {
+ const observer = new MutationObserver(onChange)
+ observer.observe(document.documentElement, { attributes: true, attributeFilter: ['data-theme'] })
+ return () => observer.disconnect()
+}
+
+export const ColorProbes = ({ probes }: ColorProbesProps) => (
+ <span aria-hidden className="hidden">
+ {Object.entries(probes).map(([role, probeClass]) => (
+ <span key={role} data-probe={role} className={probeClass} />
+ ))}
+ </span>
+)
diff --git a/apps/kb/src/components/CoverCanvas.tsx b/apps/kb/src/components/CoverCanvas.tsx
new file mode 100644
index 00000000000..904ea04b1ac
--- /dev/null
+++ b/apps/kb/src/components/CoverCanvas.tsx
@@ -0,0 +1,400 @@
+import { useCallback, type RefObject } from 'react'
+import { cn } from 'ui'
+
+import { CELL_HEIGHT, CELL_WIDTH, clamp, fitEdges, uniformEdges } from '../lib/ascii/field'
+import { drawFluid, FLUID_RISE_MS } from '../lib/ascii/fluid'
+import { loadGrain, punchGrain } from '../lib/ascii/grain'
+import { createLayer, sizeLayers, tracePolygon } from '../lib/ascii/layer'
+import { easeInOutCubic } from '../lib/ascii/warp'
+import {
+ compositionBounds,
+ convexHull,
+ paintOrder,
+ projectShape,
+ ringBounds,
+ VIEW_POINTS,
+ type IsoBox,
+ type IsoPoint,
+ type IsoRing,
+ type IsoView,
+} from '../lib/iso-shapes'
+import { ColorProbes, observeTheme, readProbeColor } from './ColorProbes'
+
+export interface CoverCanvasProps {
+ boxes: IsoBox[]
+ view?: IsoView
+ rings?: IsoRing[]
+ fillBoxes?: IsoBox[]
+ nudgeY?: number
+ zoom?: number
+ keepOutRef?: RefObject<HTMLElement | null>
+ className?: string
+}
+
+interface Point {
+ x: number
+ y: number
+}
+
+interface Palette {
+ line: string
+ fluid: string
+ beam: string
+}
+
+const PROBES = {
+ line: 'text-border-muted',
+ fluid: 'text-foreground-muted',
+ beam: 'text-brand',
+} as const
+
+const LIFT = 0.5
+const LIFT_MS = 700
+const CARD_HOVER_MS = 500
+// stable default so the canvas setup isn't redone on every render
+const NO_RINGS: IsoRing[] = []
+
+// a box lifts together with every box stacked on its footprint, lowest first
+const stackFrom = (boxes: IsoBox[], index: number): number[] => {
+ const base = boxes[index]
+ return boxes
+ .map((box, i) => ({ box, i }))
+ .filter(
+ ({ box, i }) =>
+ i === index ||
+ (box.z >= base.z + base.h - 0.01 &&
+ box.x < base.x + base.w &&
+ box.x + box.w > base.x &&
+ box.y < base.y + base.d &&
+ box.y + box.d > base.y)
+ )
+ .sort((a, b) => a.box.z - b.box.z)
+ .map(({ i }) => i)
+}
+
+const isInside = ({ x, y }: Point, polygon: IsoPoint[]) => {
+ let isIn = false
+ for (let i = 0, j = polygon.length - 1; i < polygon.length; j = i++) {
+ const [xi, yi] = polygon[i]
+ const [xj, yj] = polygon[j]
+ if (yi > y !== yj > y && x < ((xj - xi) * (y - yi)) / (yj - yi) + xi) isIn = !isIn
+ }
+ return isIn
+}
+
+const clearPath = (ctx: CanvasRenderingContext2D) => {
+ ctx.save()
+ ctx.globalCompositeOperation = 'destination-out'
+ ctx.fillStyle = '#000'
+ ctx.fill()
+ ctx.restore()
+}
+
+const readPalette = (probeRoot: HTMLElement): Palette => {
+ const read = (role: keyof typeof PROBES) => readProbeColor(probeRoot, role)
+ return {
+ line: read('line'),
+ fluid: read('fluid'),
+ beam: read('beam'),
+ }
+}
+
+const easeOutQuart = (t: number) => 1 - (1 - t) ** 4
+
+export const CoverCanvas = ({
+ boxes,
+ view = 'iso',
+ rings = NO_RINGS,
+ fillBoxes = boxes,
+ nudgeY = 0,
+ zoom = 1,
+ keepOutRef,
+ className,
+}: CoverCanvasProps) => {
+ const setupCanvas = useCallback(
+ (canvas: HTMLCanvasElement | null) => {
+ const host = canvas?.parentElement
+ const ctx = canvas?.getContext('2d')
+ const probeRoot = canvas?.nextElementSibling
+ if (!canvas || !host || !ctx || !(probeRoot instanceof HTMLElement)) return
+
+ const isReducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches
+ const sorted = paintOrder(boxes)
+ const lifts = sorted.map(() => ({ from: 0, to: 0, startedAt: 0, delay: 0 }))
+ let grain: CanvasPattern | null = null
+ loadGrain(ctx).then((pattern) => {
+ grain = pattern
+ draw()
+ })
+ // the fluid paints after the grain so the grain's holes stay on the lines only
+ const fluidLayer = createLayer()
+ let palette = readPalette(probeRoot)
+ let fit = { scale: 1, x: 0, y: 0 }
+ let hovered = -1
+ const filled = fillBoxes.map((box) => sorted.indexOf(box))
+ let fill = { from: 0, to: 0, startedAt: 0 }
+ let cardHover = { from: 0, to: 0, startedAt: 0 }
+ const hasOrbit = rings.some((ring) => ring.isDashed)
+ let table = { xs: [0], ys: [0] }
+ let tableBottom = 0
+ let frame = 0
+ let wasAnimating = false
+ let drawnFluidStep = -1
+
+ const groundZ = Math.min(...sorted.map((box) => box.z))
+ const toPixel = ([x, y]: IsoPoint): IsoPoint => [x * fit.scale + fit.x, y * fit.scale + fit.y]
+ const liftAt = (index: number, now: number) => {
+ const { from, to, startedAt, delay } = lifts[index]
+ const t = isReducedMotion ? 1 : clamp((now - startedAt - delay) / LIFT_MS, 0, 1)
+ return from + (to - from) * easeOutQuart(t)
+ }
+ const fillAt = (now: number) => {
+ const t = isReducedMotion ? 1 : clamp((now - fill.startedAt) / LIFT_MS, 0, 1)
+ return fill.from + (fill.to - fill.from) * easeOutQuart(t)
+ }
+ const cardHoverAt = (now: number) => {
+ const t = isReducedMotion ? 1 : clamp((now - cardHover.startedAt) / CARD_HOVER_MS, 0, 1)
+ return cardHover.from + (cardHover.to - cardHover.from) * easeInOutCubic(t)
+ }
+ const isLifting = (now: number) =>
+ lifts.some(
+ ({ from, to, startedAt, delay }) => from !== to && now - startedAt - delay < LIFT_MS
+ )
+
+ const draw = () => {
+ const now = performance.now()
+ const width = canvas.clientWidth
+ const height = canvas.clientHeight
+ ctx.clearRect(0, 0, width, height)
+ fluidLayer?.ctx.clearRect(0, 0, width, height)
+ ctx.strokeStyle = palette.line
+ ctx.lineWidth = 1
+ ctx.beginPath()
+ for (const x of table.xs.slice(1, -1)) {
+ ctx.moveTo(Math.round(x) + 0.5, 0)
+ ctx.lineTo(Math.round(x) + 0.5, Math.round(tableBottom) + 0.5)
+ }
+ for (const y of table.ys.slice(1, -1).filter((row) => row <= tableBottom)) {
+ ctx.moveTo(0, Math.round(y) + 0.5)
+ ctx.lineTo(width, Math.round(y) + 0.5)
+ }
+ ctx.stroke()
+ // solid rings clear the canvas inside them, so they cover the dashed orbit
+ const point = VIEW_POINTS[view]
+ const orbitProgress = cardHoverAt(now)
+ const circleOf = (ring: IsoRing) => {
+ const [cx, cy] = toPixel(point(ring.x, ring.y, ring.z))
+ return { cx, cy, radius: ring.radius * fit.scale - 2 }
+ }
+ ctx.lineWidth = 1
+ ctx.strokeStyle = palette.line
+ for (const ring of orbitProgress > 0 ? rings.filter((ring) => ring.isDashed) : []) {
+ const { cx, cy, radius } = circleOf(ring)
+ ctx.save()
+ ctx.setLineDash([3.6, 3.6])
+ ctx.beginPath()
+ ctx.arc(cx, cy, radius, -Math.PI / 2, -Math.PI / 2 + orbitProgress * Math.PI * 2)
+ ctx.stroke()
+ ctx.restore()
+ }
+ for (const ring of rings.filter((ring) => !ring.isDashed)) {
+ const { cx, cy, radius } = circleOf(ring)
+ ctx.beginPath()
+ ctx.arc(cx, cy, radius, 0, Math.PI * 2)
+ clearPath(ctx)
+ ctx.stroke()
+ }
+ sorted.forEach((box, index) => {
+ const lift = liftAt(index, now)
+ const {
+ faces,
+ insets,
+ posts,
+ fill: fillArea,
+ } = projectShape({
+ box: { ...box, z: box.z + lift },
+ view,
+ })
+ const polygons = [...faces, ...insets].map((polygon) => polygon.map(toPixel))
+ for (const polygon of polygons) {
+ tracePolygon(ctx, polygon)
+ clearPath(ctx)
+ ctx.stroke()
+ }
+ if (fluidLayer) {
+ const silhouette = convexHull(faces.flat()).map(toPixel)
+ // a box in front erases the fluid behind it, then draws its own fluid
+ const fluid = fluidLayer.ctx
+ fluid.save()
+ fluid.globalCompositeOperation = 'destination-out'
+ tracePolygon(fluid, silhouette)
+ fluid.fill()
+ fluid.restore()
+ drawFluid({
+ ctx: fluid,
+ area: fillArea.map(toPixel),
+ level: filled.includes(index) ? fillAt(now) : 0,
+ // reduced motion keeps the fill but stills the bubbles
+ now: isReducedMotion ? 0 : now,
+ color: palette.fluid,
+ beam: palette.beam,
+ flow: box.fillFlow ?? 'up',
+ })
+ }
+ if (lift <= 0) return
+ ctx.save()
+ ctx.setLineDash([1, 3])
+ ctx.beginPath()
+ for (const [px, py] of posts) {
+ const [fromX, fromY] = toPixel(point(px, py, box.z))
+ const [toX, toY] = toPixel(point(px, py, box.z + lift))
+ ctx.moveTo(fromX, fromY)
+ ctx.lineTo(toX, toY)
+ }
+ ctx.stroke()
+ ctx.restore()
+ })
+ if (grain) punchGrain({ ctx, pattern: grain, width, height })
+ if (fluidLayer) ctx.drawImage(fluidLayer.canvas, 0, 0, width, height)
+ }
+
+ const tick = () => {
+ frame = 0
+ const now = performance.now()
+ const isEasing =
+ cardHover.from !== cardHover.to && now - cardHover.startedAt < CARD_HOVER_MS
+ const isFilling = fill.from !== fill.to && now - fill.startedAt < LIFT_MS
+ const isAnimating = isLifting(now) || isEasing || isFilling
+ const isBubbling = !isReducedMotion && fill.to > 0
+ // a resting fill changes only when it rises a row. the frame after an animation draws its end state
+ const fluidStep = Math.floor(now / FLUID_RISE_MS)
+ if (isAnimating || wasAnimating || fluidStep !== drawnFluidStep) {
+ drawnFluidStep = fluidStep
+ draw()
+ }
+ wasAnimating = isAnimating
+ if (isAnimating || isBubbling) frame = requestAnimationFrame(tick)
+ }
+
+ const wake = () => {
+ if (!frame) frame = requestAnimationFrame(tick)
+ }
+
+ const measure = () => {
+ const width = host.clientWidth
+ const height = host.clientHeight
+ sizeLayers({ contexts: fluidLayer ? [ctx, fluidLayer.ctx] : [ctx], width, height })
+ table = {
+ xs: fitEdges({ size: width, target: CELL_WIDTH }),
+ ys: uniformEdges({ size: height, step: CELL_HEIGHT }),
+ }
+ const keepOut = keepOutRef?.current
+ const areaBottom = keepOut
+ ? keepOut.getBoundingClientRect().top - canvas.getBoundingClientRect().top
+ : height
+ tableBottom = table.ys.filter((row) => row < areaBottom - 1).at(-1) ?? areaBottom
+ // fit the lifted pose too so a raised box never clips the top edge
+ const poses = sorted
+ .flatMap((box) => [box, { ...box, z: box.z + LIFT }])
+ .map((box) => projectShape({ box, view }))
+ // rings frame the scene themselves, so they need less padding than bare boxes
+ const bounds = compositionBounds(
+ [...poses, ...ringBounds({ rings, view })],
+ rings.length > 0 ? 0.06 : 0.25
+ )
+ const scale = zoom * Math.max(0, Math.min(width / bounds.width, areaBottom / bounds.height))
+ fit = {
+ scale,
+ x: (width - bounds.width * scale) / 2 - bounds.x * scale,
+ y: (areaBottom - bounds.height * scale) / 2 - bounds.y * scale - CELL_HEIGHT + nudgeY,
+ }
+ draw()
+ }
+
+ // hit-tests the resting pose, so a box that lifts away from the pointer stays hovered
+ const boxAt = (point: Point) => {
+ for (let index = sorted.length - 1; index >= 0; index--) {
+ const { faces } = projectShape({ box: sorted[index], view })
+ if (faces.some((face) => isInside(point, face.map(toPixel)))) return index
+ }
+ return -1
+ }
+
+ const hover = (next: number) => {
+ if (next === hovered) return
+ hovered = next
+ const now = performance.now()
+ // a scene with an orbit does not lift. its hover effect is the orbit
+ const stack = next < 0 || hasOrbit ? [] : stackFrom(sorted, next)
+ // the ground box of a stack does not lift. if it did, the full stack would move
+ if (stack.length > 1 && sorted[next].z <= groundZ) stack.length = 0
+ if (stack.length > 0)
+ stack.push(...(sorted[next].alsoLifts ?? []).map((box) => sorted.indexOf(box)))
+ lifts.forEach((lift, index) => {
+ const depth = stack.indexOf(index)
+ const to = depth < 0 ? 0 : LIFT
+ if (to === lift.to) return
+ Object.assign(lift, {
+ from: liftAt(index, now),
+ to,
+ startedAt: now,
+ delay: depth < 0 ? 0 : depth * 50,
+ })
+ })
+ wake()
+ }
+
+ const hoverCard = (to: number) => {
+ if (cardHover.to === to) return
+ const now = performance.now()
+ cardHover = { from: cardHoverAt(now), to, startedAt: now }
+ fill = { from: fillAt(now), to, startedAt: now }
+ wake()
+ }
+
+ const handlePointerMove = (event: PointerEvent) => {
+ const origin = canvas.getBoundingClientRect()
+ const point = { x: event.clientX - origin.left, y: event.clientY - origin.top }
+ hover(boxAt(point))
+ hoverCard(1)
+ }
+
+ const handlePointerLeave = () => {
+ hover(-1)
+ hoverCard(0)
+ }
+
+ const resizeObserver = new ResizeObserver(measure)
+ resizeObserver.observe(host)
+ if (keepOutRef?.current) resizeObserver.observe(keepOutRef.current)
+
+ const unobserveTheme = observeTheme(() => {
+ palette = readPalette(probeRoot)
+ draw()
+ })
+
+ host.addEventListener('pointermove', handlePointerMove)
+ host.addEventListener('pointerleave', handlePointerLeave)
+
+ return () => {
+ cancelAnimationFrame(frame)
+ resizeObserver.disconnect()
+ unobserveTheme()
+ host.removeEventListener('pointermove', handlePointerMove)
+ host.removeEventListener('pointerleave', handlePointerLeave)
+ }
+ },
+ [boxes, view, rings, fillBoxes, nudgeY, zoom, keepOutRef]
+ )
+
+ return (
+ <>
+ <canvas
+ ref={setupCanvas}
+ aria-hidden
+ className={cn('pointer-events-none absolute inset-0 size-full', className)}
+ />
+ <ColorProbes probes={PROBES} />
+ </>
+ )
+}
diff --git a/apps/kb/src/components/FeaturedSection.tsx b/apps/kb/src/components/FeaturedSection.tsx
new file mode 100644
index 00000000000..20b1f2db86e
--- /dev/null
+++ b/apps/kb/src/components/FeaturedSection.tsx
@@ -0,0 +1,110 @@
+import { ArrowRight } from 'lucide-react'
+import { useId, type CSSProperties } from 'react'
+import { cn } from 'ui'
+import { getNotchMask, getNotchOutline } from 'ui-patterns/Notch'
+
+import type { FeaturedItem } from '../lib/guides'
+import { bindRevealOnce, REVEAL_GROUP_CLASS, REVEAL_ITEM_CLASS, revealStyle } from '../lib/reveal'
+import { AsciiHoverText } from './AsciiHoverText'
+import { TopicCover } from './TopicCover'
+
+export interface FeaturedSectionProps {
+ title: string
+ items: FeaturedItem[]
+ className?: string
+}
+
+interface FeaturedCoverProps {
+ item: FeaturedItem
+ hasDates: boolean
+}
+
+type NotchStyle = CSSProperties & { '--notch-width': string; '--notch-mask': string }
+
+const NOTCH_WIDTH = 40
+
+const NOTCH_STYLE: NotchStyle = {
+ '--notch-width': `${NOTCH_WIDTH}px`,
+ '--notch-mask': getNotchMask(NOTCH_WIDTH),
+}
+
+export const FeaturedSection = ({ title, items, className }: FeaturedSectionProps) => {
+ const headingId = useId()
+ const hasDates = items.some((item) => item.date)
+ if (items.length === 0) return null
+
+ return (
+ <section aria-labelledby={headingId} className={cn('flex flex-col gap-8', className)}>
+ <header
+ ref={bindRevealOnce}
+ className={cn('mx-auto flex w-full max-w-6xl px-6', REVEAL_GROUP_CLASS)}
+ >
+ <h2
+ id={headingId}
+ style={revealStyle(0)}
+ className={cn(
+ 'm-0 font-sans! text-xl font-medium! tracking-title text-foreground',
+ REVEAL_ITEM_CLASS
+ )}
+ >
+ <AsciiHoverText text={title} glyphClassName="after:text-foreground" />
+ </h2>
+ </header>
+ <ul
+ ref={bindRevealOnce}
+ className={cn(
+ 'mx-auto grid w-full max-w-6xl list-none gap-6 px-6 sm:grid-cols-[repeat(auto-fill,minmax(18rem,1fr))]',
+ REVEAL_GROUP_CLASS
+ )}
+ >
+ {items.map((item, index) => (
+ <li key={item.slot} style={revealStyle(index + 1)} className={REVEAL_ITEM_CLASS}>
+ <FeaturedCover item={item} hasDates={hasDates} />
+ </li>
+ ))}
+ </ul>
+ </section>
+ )
+}
+
+const FeaturedCover = ({ item, hasDates }: FeaturedCoverProps) => (
+ <a
+ href={item.href}
+ style={NOTCH_STYLE}
+ className="group/cover relative block rounded-lg focus-ring"
+ >
+ <div className="drop-shadow-raised">
+ <TopicCover
+ title={item.title}
+ description={item.description}
+ topics={item.topics}
+ date={hasDates ? (item.date ?? '') : undefined}
+ className={cn('cover-notch', hasDates ? 'h-115.5' : 'h-107.5')}
+ />
+ </div>
+ <svg
+ aria-hidden
+ width={NOTCH_WIDTH + 8}
+ height="40"
+ viewBox={`0 0 ${NOTCH_WIDTH + 8} 40`}
+ fill="none"
+ className="pointer-events-none absolute right-0 bottom-0 z-20 overflow-visible"
+ >
+ <path d={getNotchOutline(NOTCH_WIDTH)} className="stroke-(--background-surface-75)" />
+ <path d={getNotchOutline(NOTCH_WIDTH)} className="stroke-border" />
+ </svg>
+ <span
+ aria-hidden
+ className="pointer-events-none absolute right-0 bottom-0 z-20 flex h-8 w-(--notch-width) items-center justify-center overflow-hidden"
+ >
+ <ArrowRight
+ strokeWidth={2.25}
+ className={cn(
+ 'size-3.5 -translate-x-7 text-foreground-light',
+ 'transition-transform duration-200 ease-out-strong motion-reduce:transition-none',
+ 'group-hover/cover:translate-x-px group-focus-visible/cover:translate-x-px'
+ )}
+ />
+ </span>
+ </a>
+)
diff --git a/apps/kb/src/components/Footer.astro b/apps/kb/src/components/Footer.astro
index 2e9ff17bba6..2e707026d1d 100644
--- a/apps/kb/src/components/Footer.astro
+++ b/apps/kb/src/components/Footer.astro
@@ -30,7 +30,7 @@ const secondaryLinks = [
]
---
-<footer role="contentinfo" aria-label="footer" class="max-w-6xl px-6 mx-auto pt-12 pb-6">
+<footer role="contentinfo" aria-label="footer" class="section-container pt-12 pb-6">
<ul class="flex flex-col gap-2">
{
primaryLinks.map(({ Icon, text, ctaLabel, url }) => (
diff --git a/apps/kb/src/components/GuideBrowser.tsx b/apps/kb/src/components/GuideBrowser.tsx
new file mode 100644
index 00000000000..173328d2d4d
--- /dev/null
+++ b/apps/kb/src/components/GuideBrowser.tsx
@@ -0,0 +1,313 @@
+import { ChevronDown } from 'lucide-react'
+import { Fragment, useId, useState, useSyncExternalStore } from 'react'
+import {
+ cn,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuRadioGroup,
+ DropdownMenuRadioItem,
+ DropdownMenuTrigger,
+ Tabs,
+ TabsContent,
+ TabsIndicator,
+ TabsList,
+ TabsTrigger,
+} from 'ui'
+
+import {
+ emptyStateFor,
+ filterGuides,
+ parseTopicParam,
+ withTopicParam,
+ type GuideSummary,
+} from '../lib/guides'
+import { bindRevealOnce, REVEAL_GROUP_CLASS, REVEAL_ITEM_CLASS, revealStyle } from '../lib/reveal'
+import { FORMAT_TOPICS, isKnownTopic, TOPICS, type Topic } from '../lib/topics'
+import { AsciiHoverText } from './AsciiHoverText'
+
+export interface GuideBrowserProps {
+ title: string
+ guides: GuideSummary[]
+ // url search param for the active topic. each browser on a page needs its own
+ param?: string
+ className?: string
+}
+
+interface TopicTabsProps {
+ topics: Topic[]
+ activeTopic: Topic | null
+ onTopicSelect: (topic: Topic | null) => void
+ className?: string
+}
+
+interface TopicTabProps {
+ topic: Topic | null
+}
+
+interface GuideListProps {
+ guides: GuideSummary[]
+ activeTopic: Topic | null
+ onTopicClear: () => void
+}
+
+const TOPIC_CHANGE_EVENT = 'kb:topicchange'
+const PAGE_SIZE = 16
+const INLINE_TOPIC_COUNT = 7
+
+// css can't animate between two auto heights. the panel copies the measured content height into an explicit height
+const bindPanelHeight = (content: HTMLDivElement | null) => {
+ const panel = content?.parentElement
+ if (!content || !panel) return
+ const observer = new ResizeObserver(([entry]) => {
+ panel.style.height = `${entry.contentRect.height}px`
+ })
+ observer.observe(content)
+ return () => observer.disconnect()
+}
+
+const toTabValue = (topic: Topic | null) => topic ?? 'all'
+
+const subscribeToTopic = (onChange: () => void) => {
+ window.addEventListener('popstate', onChange)
+ window.addEventListener(TOPIC_CHANGE_EVENT, onChange)
+ return () => {
+ window.removeEventListener('popstate', onChange)
+ window.removeEventListener(TOPIC_CHANGE_EVENT, onChange)
+ }
+}
+
+const getTopicOnServer = () => null
+
+export const GuideBrowser = ({ title, guides, param = 'topic', className }: GuideBrowserProps) => {
+ const headingId = useId()
+ const getTopicFromUrl = () =>
+ parseTopicParam(new URLSearchParams(window.location.search).get(param))
+ const activeTopic = useSyncExternalStore(subscribeToTopic, getTopicFromUrl, getTopicOnServer)
+ const visibleGuides = filterGuides({ guides, topic: activeTopic })
+ const filterKey = activeTopic ?? ''
+ const [paging, setPaging] = useState({ filterKey, count: PAGE_SIZE })
+ const shownCount = paging.filterKey === filterKey ? paging.count : PAGE_SIZE
+ const shownGuides = visibleGuides.slice(0, shownCount)
+ const hasMore = visibleGuides.length > shownCount
+
+ const setTopicInUrl = (topic: Topic | null) => {
+ const { pathname, search, hash } = window.location
+ const nextSearch = withTopicParam({ search, topic, param })
+ window.history.replaceState(null, '', `${pathname}${nextSearch}${hash}`)
+ window.dispatchEvent(new Event(TOPIC_CHANGE_EVENT))
+ }
+ const handleTabChange = (value: string) => setTopicInUrl(isKnownTopic(value) ? value : null)
+ const handleLoadMore = () => setPaging({ filterKey, count: shownCount + PAGE_SIZE })
+ const handleTopicClear = () => setTopicInUrl(null)
+ const filterTopics = TOPICS.filter(
+ (topic) =>
+ topic.visible &&
+ guides.some((guide) => guide.topics.includes(topic.name)) &&
+ // a topic that every guide has would list the same guides as all
+ !guides.every((guide) => guide.topics.includes(topic.name))
+ ).map((topic) => topic.name)
+
+ return (
+ <section
+ aria-labelledby={headingId}
+ className={cn('mx-auto flex w-full max-w-6xl flex-col gap-8 px-6', className)}
+ >
+ <h2
+ id={headingId}
+ className="m-0 font-sans! text-xl font-medium! tracking-title text-foreground"
+ >
+ <AsciiHoverText text={title} glyphClassName="after:text-foreground" />
+ </h2>
+ <Tabs
+ value={toTabValue(activeTopic)}
+ onValueChange={handleTabChange}
+ className="group/topic-tabs tab-flares flex flex-col"
+ >
+ <div className="relative flex items-end">
+ <TopicTabs
+ topics={filterTopics}
+ activeTopic={activeTopic}
+ onTopicSelect={setTopicInUrl}
+ className="flex-1"
+ />
+ </div>
+ <span aria-hidden className="relative z-1 block h-0">
+ <span
+ className={cn(
+ 'absolute left-0 top-0 size-2 border-l border-default bg-200 opacity-0',
+ 'transition-opacity duration-150 ease-move motion-reduce:transition-none',
+ 'group-has-[[role=tab]:first-child[data-state=active]]/topic-tabs:opacity-100',
+ 'group-has-[[role=tab]:first-child[data-state=active]]/topic-tabs:duration-400'
+ )}
+ />
+ </span>
+ <TabsContent
+ value={toTabValue(activeTopic)}
+ className={cn(
+ 'mt-0 box-content overflow-hidden rounded-lg border border-default bg-200 px-6 py-2',
+ 'transition-[height] duration-300 ease-move motion-reduce:transition-none'
+ )}
+ >
+ <div ref={bindPanelHeight}>
+ <p aria-live="polite" className="sr-only">
+ {`${shownGuides.length} of ${visibleGuides.length} ${visibleGuides.length === 1 ? 'guide' : 'guides'} shown`}
+ </p>
+ <GuideList
+ guides={shownGuides}
+ activeTopic={activeTopic}
+ onTopicClear={handleTopicClear}
+ />
+ {hasMore ? (
+ <div className="flex justify-center py-6">
+ <button
+ type="button"
+ onClick={handleLoadMore}
+ className={cn(
+ 'inline-flex cursor-pointer items-center gap-1.5 rounded-full py-1 pl-2.5 pr-3 text-xs text-foreground',
+ 'bg-surface-200/90 shadow-sm ring-1 ring-foreground/10 backdrop-blur-sm',
+ 'transition duration-200 ease-out',
+ 'hover:bg-surface-300 active:scale-[0.96] focus-ring'
+ )}
+ >
+ <ChevronDown aria-hidden className="size-3.5" />
+ Load more
+ </button>
+ </div>
+ ) : null}
+ </div>
+ </TabsContent>
+ </Tabs>
+ </section>
+ )
+}
+
+const TopicTabs = ({ topics, activeTopic, onTopicSelect, className }: TopicTabsProps) => {
+ const inlineTopics = topics.slice(0, INLINE_TOPIC_COUNT)
+ const moreTopics = topics.slice(INLINE_TOPIC_COUNT)
+ const activeMoreTopic = moreTopics.find((topic) => topic === activeTopic) ?? null
+ const tabTopics = [null, ...inlineTopics, ...(activeMoreTopic ? [activeMoreTopic] : [])]
+ const firstProductIndex = tabTopics.findIndex(
+ (topic) => topic !== null && !FORMAT_TOPICS.includes(topic)
+ )
+ const handleMoreSelect = (value: string) =>
+ onTopicSelect(moreTopics.find((topic) => topic === value) ?? null)
+
+ return (
+ <TabsList
+ aria-label="Topics"
+ className={cn(
+ 'relative z-1 -mb-px min-w-0 border-b-0 overflow-x-auto no-scrollbar has-focus-visible:z-2',
+ 'has-[[data-tab-indicator]]:after:hidden',
+ className
+ )}
+ >
+ {tabTopics.map((topic, index) => (
+ <Fragment key={toTabValue(topic)}>
+ {index === firstProductIndex && index > 1 ? (
+ <span aria-hidden className="mx-1 h-4 w-px shrink-0 self-center bg-border" />
+ ) : null}
+ <TopicTab topic={topic} />
+ </Fragment>
+ ))}
+ {moreTopics.length > 0 ? (
+ <DropdownMenu>
+ <DropdownMenuTrigger
+ className={cn(
+ 'shrink-0 whitespace-nowrap rounded-md py-2 text-sm tracking-body transition-colors focus-inset',
+ 'text-foreground-lighter hover:text-foreground'
+ )}
+ >
+ <span className="flex items-center gap-1 px-3">
+ More
+ <ChevronDown aria-hidden className="size-3.5" strokeWidth={2.25} />
+ </span>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="start" className="w-48">
+ <DropdownMenuRadioGroup value={activeMoreTopic ?? ''} onValueChange={handleMoreSelect}>
+ {moreTopics.map((topic) => (
+ <DropdownMenuRadioItem key={topic} value={topic}>
+ {topic}
+ </DropdownMenuRadioItem>
+ ))}
+ </DropdownMenuRadioGroup>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ ) : null}
+ <TabsIndicator
+ className={cn(
+ 'top-0 h-auto rounded-t-lg border border-b-0 border-default bg-200',
+ 'before:absolute before:bottom-0 before:-left-2 before:size-2',
+ 'before:transition-opacity before:duration-150 before:ease-move motion-reduce:before:transition-none',
+ 'group-has-[[role=tab]:first-child[data-state=active]]/topic-tabs:before:opacity-0',
+ 'before:bg-(image:--tab-flare-left)',
+ 'after:absolute after:bottom-0 after:-right-2 after:size-2',
+ 'after:bg-(image:--tab-flare-right)'
+ )}
+ />
+ </TabsList>
+ )
+}
+
+const TopicTab = ({ topic }: TopicTabProps) => (
+ <TabsTrigger
+ value={toTabValue(topic)}
+ className={cn(
+ 'shrink-0 whitespace-nowrap rounded-md py-2 text-sm tracking-body transition-colors focus-inset',
+ 'relative z-1 data-[state=active]:shadow-none'
+ )}
+ >
+ <span className="block px-3">{topic ?? 'All'}</span>
+ </TabsTrigger>
+)
+
+const GuideList = ({ guides, activeTopic, onTopicClear }: GuideListProps) => {
+ if (guides.length === 0) {
+ const emptyState = emptyStateFor({ topic: activeTopic })
+ return (
+ <div className="flex flex-col items-start gap-3 py-8">
+ <p className="m-0 text-sm text-foreground-light">{emptyState.message}</p>
+ <button
+ type="button"
+ onClick={onTopicClear}
+ className="text-sm text-foreground underline underline-offset-4 focus-ring rounded-sm"
+ >
+ {emptyState.action}
+ </button>
+ </div>
+ )
+ }
+
+ return (
+ <ul ref={bindRevealOnce} className={cn('m-0 flex list-none flex-col p-0', REVEAL_GROUP_CLASS)}>
+ {guides.map((guide, index) => (
+ <li
+ // guide and troubleshooting slugs can be the same. hrefs are unique
+ key={guide.href}
+ style={revealStyle(index % PAGE_SIZE)}
+ className={cn(
+ 'border-b border-dashed border-muted last:border-b-0 transition-colors',
+ 'hover:border-transparent has-[+li:hover]:border-transparent',
+ 'has-[:focus-visible]:border-transparent has-[+li_:focus-visible]:border-transparent',
+ REVEAL_ITEM_CLASS
+ )}
+ >
+ <a
+ href={guide.href}
+ className={cn(
+ 'group -mx-4 flex min-h-14 flex-col gap-1 rounded-md px-4 py-3 transition-colors',
+ 'hover:bg-surface-200 focus-visible:bg-surface-200 focus-visible:outline-hidden',
+ 'sm:flex-row sm:items-center sm:gap-8 sm:py-0'
+ )}
+ >
+ <span className="min-w-0 flex-1 text-sm font-medium tracking-body text-foreground">
+ {guide.title}
+ </span>
+ <span className="text-sm tracking-body text-foreground-lighter sm:max-w-1/2 sm:shrink-0 sm:truncate sm:text-right">
+ {guide.topics.join(', ')}
+ </span>
+ </a>
+ </li>
+ ))}
+ </ul>
+ )
+}
diff --git a/apps/kb/src/components/GuideSearchDialog.tsx b/apps/kb/src/components/GuideSearchDialog.tsx
new file mode 100644
index 00000000000..86b68d9b3f3
--- /dev/null
+++ b/apps/kb/src/components/GuideSearchDialog.tsx
@@ -0,0 +1,75 @@
+import {
+ cn,
+ Command,
+ CommandEmpty,
+ CommandInput,
+ CommandItem,
+ CommandList,
+ Dialog,
+ DialogContent,
+ DialogTitle,
+} from 'ui'
+
+import type { GuideSummary } from '../lib/guides'
+
+export interface GuideSearchDialogProps {
+ guides: GuideSummary[]
+ isOpen: boolean
+ onOpenChange: (isOpen: boolean) => void
+}
+
+interface GuideResultProps {
+ guide: GuideSummary
+ onGuideSelect: (href: string) => void
+}
+
+export const GuideSearchDialog = ({ guides, isOpen, onOpenChange }: GuideSearchDialogProps) => {
+ const handleGuideSelect = (href: string) => window.location.assign(href)
+
+ return (
+ <Dialog open={isOpen} onOpenChange={onOpenChange}>
+ <DialogContent
+ hideClose
+ centered={false}
+ aria-describedby={undefined}
+ className="mx-auto overflow-hidden p-0 shadow-raised"
+ >
+ <DialogTitle className="sr-only">Search guides</DialogTitle>
+ <Command
+ className={cn(
+ '**:[[cmdk-input]]:h-12 **:[[cmdk-item]]:px-3 **:[[cmdk-item]]:py-2.5',
+ '**:[[cmdk-list]]:max-h-[min(420px,60vh)] **:[[cmdk-list]]:overflow-y-auto **:[[cmdk-list]]:p-1.5',
+ '**:[[cmdk-list]]:box-content **:[[cmdk-list]]:h-(--cmdk-list-height) **:[[cmdk-list]]:transition-[height]',
+ '**:[[cmdk-list]]:duration-200 **:[[cmdk-list]]:ease-out-strong',
+ 'motion-reduce:**:[[cmdk-list]]:transition-none'
+ )}
+ >
+ <CommandInput placeholder="Search guides" />
+ <CommandList>
+ <CommandEmpty className="px-3 py-6 text-center text-sm text-foreground-lighter">
+ No guide titles match your search. Try a shorter or different term.
+ </CommandEmpty>
+ {guides.map((guide) => (
+ <GuideResult key={guide.id} guide={guide} onGuideSelect={handleGuideSelect} />
+ ))}
+ </CommandList>
+ </Command>
+ </DialogContent>
+ </Dialog>
+ )
+}
+
+const GuideResult = ({ guide, onGuideSelect }: GuideResultProps) => {
+ const handleSelect = () => onGuideSelect(guide.href)
+
+ return (
+ <CommandItem
+ value={guide.title}
+ onSelect={handleSelect}
+ className="flex items-center justify-between gap-4 rounded-md text-sm text-foreground"
+ >
+ <span className="truncate">{guide.title}</span>
+ <span className="shrink-0 text-xs text-foreground-lighter">{guide.topics.join(', ')}</span>
+ </CommandItem>
+ )
+}
diff --git a/apps/kb/src/components/GuideSidebar.tsx b/apps/kb/src/components/GuideSidebar.tsx
new file mode 100644
index 00000000000..5deae508264
--- /dev/null
+++ b/apps/kb/src/components/GuideSidebar.tsx
@@ -0,0 +1,28 @@
+import { cn } from 'ui'
+import { AiTools } from 'ui-patterns/AiTools'
+import { AnchorProvider, TocSection } from 'ui-patterns/Toc'
+import type { TOCItemType } from 'ui-patterns/Toc/types'
+
+export interface GuideSidebarProps {
+ items: TOCItemType[]
+ pageUrl: string
+ markdownUrl: string
+ className?: string
+}
+
+const getArticleHtml = () => document.querySelector('article')?.innerHTML ?? ''
+
+export const GuideSidebar = ({ items, pageUrl, markdownUrl, className }: GuideSidebarProps) => (
+ <AnchorProvider toc={items} single={false}>
+ <div className={cn('flex flex-col gap-8 border-l px-2', className)}>
+ <AiTools
+ pageUrl={pageUrl}
+ markdownUrl={markdownUrl}
+ markdownFallback={getArticleHtml}
+ agentSetupHref="https://supabase.com/docs/guides/ai-tools"
+ className="pl-5"
+ />
+ {items.length > 0 ? <TocSection items={items} /> : null}
+ </div>
+ </AnchorProvider>
+)
diff --git a/apps/kb/src/components/Header.tsx b/apps/kb/src/components/Header.tsx
index 14b7ce68bbe..641ae007a74 100644
--- a/apps/kb/src/components/Header.tsx
+++ b/apps/kb/src/components/Header.tsx
@@ -1,20 +1,76 @@
+import { Menu } from 'lucide-react'
+import { useRef, useState } from 'react'
+import { Button, buttonVariants, cn } from 'ui'
+
+import { getNavMenus, SIGN_UP_URL } from '../lib/nav'
+import type { Topic } from '../lib/topics'
+import { HeaderMenu } from './HeaderMenu'
import { Logo } from './Logo'
+import { MobileMenu } from './MobileMenu'
import { Nav } from './Nav'
-import { ThemeToggle } from './ThemeToggle'
-// Bare-bones port of apps/docs' TopNavBar — logo, nav, and theme toggle, each
-// split into their own component (Logo.tsx, Nav.tsx, ThemeToggle.tsx). No
-// search, no user menu, no dashboard link — kb doesn't have any of that yet.
-function Header() {
+const MOBILE_MENU_ID = 'mobile-menu'
+
+export interface HeaderProps {
+ topics: Topic[]
+}
+
+export const Header = ({ topics }: HeaderProps) => {
+ const menus = getNavMenus(topics)
+ const [isMenuOpen, setIsMenuOpen] = useState(false)
+ const menuButtonRef = useRef<HTMLButtonElement>(null)
+
+ const setMenuOpen = (isOpen: boolean) => {
+ setIsMenuOpen(isOpen)
+ document.documentElement.toggleAttribute('data-mobile-menu-open', isOpen)
+ }
+ const handleMenuOpen = () => setMenuOpen(true)
+ const handleMenuClose = () => {
+ setMenuOpen(false)
+ menuButtonRef.current?.focus()
+ }
+
return (
- <header className="relative z-50 backdrop-blur-sm backdrop-filter bg-default/75 border-b border-default w-full px-5 lg:pl-10 items-center flex h-(--header-height) gap-3">
- <div className="flex basis-full h-full items-center justify-center gap-2">
- <Logo />
- <Nav />
- </div>
- <ThemeToggle />
- </header>
+ <>
+ <nav className="relative h-(--header-height) border-b border-default bg-background/90 backdrop-blur-xs dark:bg-background/95">
+ <div className="section-container flex h-full items-center justify-between">
+ <div className="flex h-full items-center">
+ <div className="lg:w-[calc(var(--nav-inset)-0.625rem-1px)]">
+ <Logo />
+ </div>
+ <Nav menus={menus} className="hidden lg:flex" />
+ </div>
+ <div className="flex items-center gap-2">
+ <Button variant="primary" asChild className="hidden h-7.5 lg:inline-flex">
+ <a href={SIGN_UP_URL}>Start your project</a>
+ </Button>
+ <HeaderMenu className="hidden lg:inline-flex" />
+ <button
+ ref={menuButtonRef}
+ type="button"
+ aria-expanded={isMenuOpen}
+ aria-controls={MOBILE_MENU_ID}
+ onClick={handleMenuOpen}
+ className={cn(
+ buttonVariants({ variant: 'default' }),
+ 'size-7.5 min-w-7.5 border-default bg-surface-100/75 px-0',
+ 'text-foreground-light lg:hidden'
+ )}
+ >
+ <span className="sr-only">Open main menu</span>
+ <Menu aria-hidden className="size-4.5" strokeWidth={1} />
+ </button>
+ </div>
+ </div>
+ </nav>
+ {isMenuOpen ? (
+ <MobileMenu
+ id={MOBILE_MENU_ID}
+ menus={menus}
+ onClose={handleMenuClose}
+ className="lg:hidden"
+ />
+ ) : null}
+ </>
)
}
-
-export { Header }
diff --git a/apps/kb/src/components/HeaderMenu.tsx b/apps/kb/src/components/HeaderMenu.tsx
new file mode 100644
index 00000000000..d993fb09b30
--- /dev/null
+++ b/apps/kb/src/components/HeaderMenu.tsx
@@ -0,0 +1,116 @@
+import { House, LifeBuoy, Menu } from 'lucide-react'
+import { useState } from 'react'
+import {
+ buttonVariants,
+ cn,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuGroup,
+ DropdownMenuItem,
+ DropdownMenuLabel,
+ DropdownMenuRadioGroup,
+ DropdownMenuRadioItem,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+ GithubIcon,
+ singleThemes,
+} from 'ui'
+
+export interface HeaderMenuProps {
+ className?: string
+}
+
+type ThemeChoice = 'system' | 'dark' | 'light'
+
+export const EXTERNAL_LINKS = [
+ { label: 'Supabase.com', href: 'https://supabase.com', Icon: House },
+ { label: 'GitHub', href: 'https://github.com/supabase/supabase', Icon: GithubIcon },
+ { label: 'Support', href: 'https://supabase.com/support', Icon: LifeBuoy },
+]
+
+const isThemeChoice = (value: string | null): value is ThemeChoice =>
+ value === 'system' || value === 'dark' || value === 'light'
+
+const readStoredChoice = (): ThemeChoice => {
+ try {
+ const stored = localStorage.getItem('theme')
+ return isThemeChoice(stored) ? stored : 'dark'
+ } catch {
+ return 'dark'
+ }
+}
+
+// writes the same `data-theme` attribute and `theme` key the no-flash script in Layout.astro reads
+const applyTheme = (choice: ThemeChoice) => {
+ const isSystemDark = window.matchMedia('(prefers-color-scheme: dark)').matches
+ const resolved = choice === 'system' ? (isSystemDark ? 'dark' : 'light') : choice
+ // without this, transition-colors elements fade between themes while the rest change at once
+ const freeze = document.createElement('style')
+ freeze.textContent = '*,*::before,*::after{transition:none!important}'
+ document.head.appendChild(freeze)
+ document.documentElement.setAttribute('data-theme', resolved)
+ // reading a property forces the style flush while transitions are frozen
+ void window.getComputedStyle(document.body).opacity
+ window.setTimeout(() => freeze.remove(), 1)
+ try {
+ localStorage.setItem('theme', choice)
+ } catch {
+ // private browsing can block localStorage, so the choice does not persist
+ }
+}
+
+export const useThemeChoice = () => {
+ const [choice, setChoice] = useState(readStoredChoice)
+
+ const handleChoiceChange = (value: string) => {
+ if (!isThemeChoice(value)) return
+ setChoice(value)
+ applyTheme(value)
+ }
+
+ return { choice, onChoiceChange: handleChoiceChange }
+}
+
+export const HeaderMenu = ({ className }: HeaderMenuProps) => {
+ const { choice, onChoiceChange } = useThemeChoice()
+
+ return (
+ <DropdownMenu modal={false}>
+ <DropdownMenuTrigger asChild>
+ <button
+ type="button"
+ className={cn(
+ buttonVariants({ variant: 'default' }),
+ 'size-7.5 min-w-7.5 space-x-0 border-default bg-transparent px-0 text-foreground-light',
+ 'hover:border-strong hover:bg-overlay-hover/50! data-open:border-stronger data-open:bg-overlay-hover/30',
+ className
+ )}
+ >
+ <Menu aria-hidden className="size-4.5" strokeWidth={1} />
+ <span className="sr-only">Open menu</span>
+ </button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent side="bottom" align="end" className="w-52">
+ {EXTERNAL_LINKS.map(({ label, href, Icon }) => (
+ <DropdownMenuItem key={href} asChild className="gap-2">
+ <a href={href} target="_blank" rel="noreferrer noopener">
+ <Icon aria-hidden className="size-4 text-foreground-lighter" strokeWidth={1.5} />
+ {label}
+ </a>
+ </DropdownMenuItem>
+ ))}
+ <DropdownMenuSeparator />
+ <DropdownMenuGroup>
+ <DropdownMenuLabel>Theme</DropdownMenuLabel>
+ <DropdownMenuRadioGroup value={choice} onValueChange={onChoiceChange}>
+ {singleThemes.map((theme) => (
+ <DropdownMenuRadioItem key={theme.value} value={theme.value}>
+ {theme.name}
+ </DropdownMenuRadioItem>
+ ))}
+ </DropdownMenuRadioGroup>
+ </DropdownMenuGroup>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ )
+}
diff --git a/apps/kb/src/components/Hero.tsx b/apps/kb/src/components/Hero.tsx
index 779eac3e08b..3bcaecbba1d 100644
--- a/apps/kb/src/components/Hero.tsx
+++ b/apps/kb/src/components/Hero.tsx
@@ -1,17 +1,314 @@
-// Ported from apps/docs/components/HomePageCover.tsx — just the title + intro
-// copy (rebranded for kb), without the animated logo or the CLI/AI setup
-// prompt panel (docs-specific, feature-flagged, and not something kb has yet).
-function Hero() {
+import { Search } from 'lucide-react'
+import { useCallback, useRef, useState, useSyncExternalStore, type ReactNode } from 'react'
+import { cn, KeyboardShortcut } from 'ui'
+
+import {
+ alignedEdges,
+ CELL_HEIGHT,
+ CELL_WIDTH,
+ heroField,
+ uniformEdges,
+ type Lattice,
+} from '../lib/ascii/field'
+import type { GuideSummary } from '../lib/guides'
+import type { Topic } from '../lib/topics'
+import { useQueryVariant } from '../lib/use-query-variant'
+import { AsciiCanvas, type CanvasSize } from './AsciiCanvas'
+import { AsciiHoverText } from './AsciiHoverText'
+import { GuideSearchDialog } from './GuideSearchDialog'
+import { HeroGrid } from './HeroGrid'
+import { InfallText } from './InfallText'
+import { TopicShape } from './TopicShape'
+import { WarpCanvas } from './WarpCanvas'
+
+export interface HeroProps {
+ title: string
+ description: string
+ guides: GuideSummary[]
+ breadcrumb?: ReactNode
+ variant?: 'grid' | 'warp' | 'construction'
+ topic?: Topic
+ children?: ReactNode
+ className?: string
+}
+
+export interface TopicHeroProps {
+ topic: Topic
+ description: string
+ guides: GuideSummary[]
+ breadcrumb?: ReactNode
+ className?: string
+}
+
+interface CopyFrameProps {
+ lines: { id: string; className: string }[]
+}
+
+interface HeroFlanksProps {
+ topic: Topic
+}
+
+export interface HomeHeroProps {
+ guides: GuideSummary[]
+ className?: string
+}
+
+interface HeroSearchProps {
+ guides: GuideSummary[]
+}
+
+// hidden for launch. preview with ?search=on, flip the fallback to ship it
+const SEARCH_FLAG = ['off', 'on'] as const
+
+const DRAW_OUT = 'motion-safe:animate-draw-out'
+
+const FLANK_BOX = cn(
+ 'grain-mask-flank absolute -top-[100vh] h-[calc(100%+200vh)] w-[50vw]',
+ 'pointer-events-none py-[100vh] pl-12 pr-92 max-lg:hidden'
+)
+
+const ACROSS = 'left-1/2 h-px w-screen -translate-x-1/2 bg-border'
+const UPRIGHT =
+ 'inset-y-0 w-px origin-top bg-linear-to-b from-border via-border via-70% to-transparent'
+
+const getHeroLattice = ({ width, height }: CanvasSize): Lattice => {
+ const contentLeft = Math.max(0, (width - 1152) / 2) + 24
+ return {
+ xs: alignedEdges({
+ size: width,
+ start: contentLeft,
+ end: width - contentLeft,
+ target: CELL_WIDTH,
+ }),
+ ys: uniformEdges({ size: height, step: CELL_HEIGHT }),
+ }
+}
+
+const subscribeToNothing = () => () => {}
+
+const getIsMac = () => /Mac|iPhone|iPad/.test(navigator.userAgent)
+
+const getIsMacOnServer = () => false
+
+export const Hero = ({
+ title,
+ description,
+ guides,
+ breadcrumb,
+ variant = 'warp',
+ topic,
+ children,
+ className,
+}: HeroProps) => {
+ const isWarp = variant === 'warp'
+ const isGrid = variant === 'grid'
+ const copyRef = useRef<HTMLDivElement>(null)
+ const ingestWords = [
+ ...new Set(
+ guides.flatMap((guide) =>
+ guide.title
+ .toLowerCase()
+ .split(/[^a-z0-9]+/)
+ .filter((word) => word.length >= 5)
+ )
+ ),
+ ]
+
return (
- <div className="w-full border-b border-default bg-muted/10">
- <div className="mx-auto max-w-7xl px-6 py-16">
- <h1 className="m-0 text-3xl text-foreground sm:text-4xl">Supabase Knowledge Base</h1>
- <p className="m-0 mt-2 text-base leading-7 text-foreground-light sm:mt-3 sm:text-xl">
- In-depth guides, tutorials, and explainers for best practices for Supabase databases.
- </p>
+ <section
+ className={cn(
+ 'relative isolate flex justify-center',
+ isWarp ? 'pt-39 pb-60' : 'pt-32.5 pb-26 max-sm:pt-19.5 max-sm:pb-19.5 lg:pb-40',
+ 'overflow-hidden bg-background',
+ className
+ )}
+ >
+ {isWarp ? <WarpCanvas anchorRef={copyRef} /> : null}
+ {variant === 'construction' ? (
+ <CopyFrame
+ lines={[
+ { id: 'left', className: cn('right-[calc(50%+20rem)]', UPRIGHT, DRAW_OUT) },
+ { id: 'right', className: cn('left-[calc(50%+20rem)]', UPRIGHT, DRAW_OUT) },
+ ]}
+ />
+ ) : null}
+ {isGrid ? (
+ <AsciiCanvas
+ getLattice={getHeroLattice}
+ getField={heroField}
+ keepOutRefs={[copyRef]}
+ keepOutMargin={0}
+ words={ingestWords}
+ decay={0.985}
+ />
+ ) : null}
+ <div className="relative z-10 w-full max-w-6xl px-6">
+ {isWarp ? (
+ <div
+ aria-hidden
+ className={cn(
+ 'pointer-events-none absolute left-1/2 top-1/2 -z-10 h-100 w-205 max-w-screen',
+ '-translate-x-1/2 -translate-y-1/2',
+ 'bg-radial-[closest-side] from-background/95 via-background/80 via-65% to-transparent'
+ )}
+ />
+ ) : null}
+ <div
+ ref={copyRef}
+ className={cn(
+ 'relative flex flex-col items-center gap-5 text-center',
+ isWarp ? 'py-16' : 'pt-12 pb-9.5'
+ )}
+ >
+ {breadcrumb}
+ <h1 className="m-0 text-5xl tracking-display text-foreground sm:text-6xl">
+ {isWarp ? (
+ <InfallText text={title} hoverGlyphClassName="after:text-foreground" />
+ ) : (
+ <AsciiHoverText text={title} glyphClassName="after:text-foreground" />
+ )}
+ </h1>
+ <p className="m-0 min-h-[2lh] max-w-145 text-balance text-lg leading-7 text-foreground-light">
+ {isWarp ? <InfallText text={description} /> : description}
+ </p>
+ {children}
+ {variant === 'construction' && topic ? <HeroFlanks topic={topic} /> : null}
+ </div>
</div>
- </div>
+ {isGrid ? (
+ <div
+ aria-hidden
+ className="pointer-events-none absolute inset-x-0 bottom-0 h-1/3 bg-linear-to-b from-transparent to-background"
+ />
+ ) : null}
+ </section>
)
}
-export { Hero }
+export const HomeHero = ({ guides, className }: HomeHeroProps) => {
+ const isSearchEnabled =
+ useQueryVariant({ key: 'search', options: SEARCH_FLAG, fallback: 'off' }) === 'on'
+
+ return (
+ <Hero
+ title="Knowledge base"
+ description="In-depth guides, tutorials, troubleshooting, and explainers for best practices for Supabase"
+ guides={guides}
+ className={className}
+ >
+ {isSearchEnabled ? <HeroSearch guides={guides} /> : null}
+ </Hero>
+ )
+}
+
+export const TopicHero = ({
+ topic,
+ description,
+ guides,
+ breadcrumb,
+ className,
+}: TopicHeroProps) => {
+ // grid hero stays reachable with ?hero=grid, in case we go back to it
+ const variant = useQueryVariant({
+ key: 'hero',
+ options: ['construction', 'grid'],
+ fallback: 'construction',
+ })
+
+ return (
+ <Hero
+ variant={variant}
+ topic={topic}
+ title={topic}
+ description={description}
+ guides={guides}
+ breadcrumb={breadcrumb}
+ className={className}
+ />
+ )
+}
+
+const HeroFlanks = ({ topic }: HeroFlanksProps) => (
+ <>
+ <HeroGrid axis="rows" className={cn('right-1/2', FLANK_BOX)} />
+ <HeroGrid axis="rows" className={cn('left-1/2 -scale-x-100', FLANK_BOX)} />
+ <HeroGrid
+ axis="columns"
+ className={cn('right-1/2 [--flank-span:calc(100%_-_20rem)]', FLANK_BOX)}
+ />
+ <HeroGrid
+ axis="columns"
+ className={cn('left-1/2 -scale-x-100 [--flank-span:calc(100%_-_20rem)]', FLANK_BOX)}
+ />
+ <TopicShape topic={topic} className={cn('right-1/2', FLANK_BOX)} />
+ <TopicShape topic={topic} className={cn('left-1/2 -scale-x-100', FLANK_BOX)} />
+ <CopyFrame
+ lines={[
+ { id: 'top', className: cn('top-0', ACROSS, DRAW_OUT) },
+ { id: 'band', className: cn('-top-[calc(var(--spacing)*32.5/2)]', ACROSS, DRAW_OUT) },
+ { id: 'bottom', className: cn('bottom-0', ACROSS, DRAW_OUT) },
+ {
+ id: 'stem',
+ className: cn('bottom-full left-1/2 h-screen w-px origin-bottom bg-border', DRAW_OUT),
+ },
+ {
+ id: 'tail',
+ className: cn(
+ 'top-full left-1/2 h-40 w-px origin-top bg-linear-to-b from-border to-transparent',
+ DRAW_OUT
+ ),
+ },
+ ]}
+ />
+ </>
+)
+
+const CopyFrame = ({ lines }: CopyFrameProps) =>
+ lines.map(({ id, className }) => (
+ <span
+ key={id}
+ aria-hidden
+ className={cn('grain-mask pointer-events-none absolute max-lg:hidden', className)}
+ />
+ ))
+
+const HeroSearch = ({ guides }: HeroSearchProps) => {
+ const [isSearchOpen, setIsSearchOpen] = useState(false)
+ const isMac = useSyncExternalStore(subscribeToNothing, getIsMac, getIsMacOnServer)
+
+ const bindSearchShortcut = useCallback((trigger: HTMLButtonElement | null) => {
+ if (!trigger) return
+ const handleKeyDown = (event: KeyboardEvent) => {
+ if (event.repeat || event.key?.toLowerCase() !== 'k') return
+ if (!(event.metaKey || event.ctrlKey)) return
+ event.preventDefault()
+ setIsSearchOpen((isOpen) => !isOpen)
+ }
+ window.addEventListener('keydown', handleKeyDown)
+ return () => window.removeEventListener('keydown', handleKeyDown)
+ }, [])
+
+ const handleSearchOpen = () => setIsSearchOpen(true)
+
+ return (
+ <>
+ <button
+ ref={bindSearchShortcut}
+ type="button"
+ data-warp-throat
+ aria-keyshortcuts="Meta+K Control+K"
+ onClick={handleSearchOpen}
+ className={cn(
+ 'relative mt-2 flex h-12 w-full max-w-85 items-center gap-2.5 rounded-lg pl-3 pr-4 sm:max-w-107',
+ 'border border-default bg-surface-75 text-left text-base text-foreground-lighter shadow-raised',
+ 'transition-colors hover:border-strong hover:text-foreground-light focus-ring'
+ )}
+ >
+ <Search aria-hidden className="size-4.5 shrink-0" strokeWidth={2.25} />
+ <span className="flex-1 truncate">Search guides</span>
+ <KeyboardShortcut keys={[isMac ? '⌘' : 'Ctrl', 'K']} />
+ </button>
+ <GuideSearchDialog guides={guides} isOpen={isSearchOpen} onOpenChange={setIsSearchOpen} />
+ </>
+ )
+}
diff --git a/apps/kb/src/components/HeroGrid.tsx b/apps/kb/src/components/HeroGrid.tsx
new file mode 100644
index 00000000000..be7a006a61c
--- /dev/null
+++ b/apps/kb/src/components/HeroGrid.tsx
@@ -0,0 +1,60 @@
+import { cn } from 'ui'
+
+import { CELL_HEIGHT, CELL_WIDTH } from '../lib/ascii/field'
+
+export interface HeroGridProps {
+ // rows and columns are separate layers, so the hero can mask each one differently
+ axis: 'rows' | 'columns'
+ className?: string
+}
+
+// the same height as a topic shape, so a cell lines up with the shape at any size
+const GRID_HEIGHT = 320
+// a line runs this far from its middle, in viewBox units. it must pass every border it can meet
+const GRID_REACH = 2400
+
+export const HeroGrid = ({ axis, className }: HeroGridProps) => {
+ const lines =
+ axis === 'columns'
+ ? // the grid hero's cells. 12 columns go past the page middle. there is no middle column, because it would cut the shape
+ [-6, -5, -4, -3, -2, -1, 1, 2, 3, 4, 5, 6].map((step) => ({
+ x: step * CELL_WIDTH,
+ y: GRID_HEIGHT / 2,
+ dx: 0,
+ dy: 1,
+ }))
+ : // 6 rows of 4 cells, from one row above the copy
+ [-1, 0, 1, 2, 3, 4].map((step) => ({
+ x: 0,
+ y: GRID_HEIGHT / 2 + step * CELL_HEIGHT * 4,
+ dx: 1,
+ dy: 0,
+ }))
+
+ return (
+ <svg
+ aria-hidden
+ // the classes size it. until the css loads, a zero size keeps it from flashing
+ width={0}
+ height={0}
+ // 1 unit wide, so the height always sets the scale, as it does for a topic shape
+ viewBox={`-0.5 0 1 ${GRID_HEIGHT}`}
+ className={cn('overflow-visible fill-none stroke-current text-border', className)}
+ >
+ {lines.flatMap(({ x, y, dx, dy }, index) =>
+ [1, -1].map((side) => (
+ <line
+ key={`${x}:${y}:${side}`}
+ x1={x}
+ y1={y}
+ x2={x + dx * side * GRID_REACH}
+ y2={y + dy * side * GRID_REACH}
+ pathLength={1}
+ style={{ animationDelay: `${index * 22}ms` }}
+ className="[stroke-dasharray:1] motion-safe:animate-draw-line"
+ />
+ ))
+ )}
+ </svg>
+ )
+}
diff --git a/apps/kb/src/components/InfallText.tsx b/apps/kb/src/components/InfallText.tsx
new file mode 100644
index 00000000000..c546b7be7fb
--- /dev/null
+++ b/apps/kb/src/components/InfallText.tsx
@@ -0,0 +1,61 @@
+import { Fragment } from 'react'
+import { cn } from 'ui'
+
+import { ASCII_HOVER_CLASS, hoverGlyph } from './AsciiHoverText'
+
+export interface InfallTextProps {
+ text: string
+ hoverGlyphClassName?: string
+ className?: string
+}
+
+export const InfallText = ({ text, hoverGlyphClassName, className }: InfallTextProps) => {
+ const words = text.split(' ').map((word, position) => ({
+ id: `${position}:${word}`,
+ isFirst: position === 0,
+ characters: Array.from(word).map((char, index) => ({
+ id: `${index}:${char}`,
+ char,
+ // the word index times 64 gives each character its own glyph seed
+ glyph: hoverGlyph(position * 64 + index, char),
+ })),
+ }))
+
+ return (
+ <span className={className}>
+ <span className="sr-only">{text}</span>
+ <span aria-hidden>
+ {words.map(({ id, isFirst, characters }) => (
+ <Fragment key={id}>
+ {isFirst ? null : ' '}
+ <span className="whitespace-nowrap">
+ {characters.map((character) => (
+ <span
+ key={character.id}
+ data-infall
+ data-glyph={hoverGlyphClassName === undefined ? undefined : character.glyph}
+ className={cn(
+ 'relative inline-block',
+ hoverGlyphClassName === undefined
+ ? null
+ : [ASCII_HOVER_CLASS, hoverGlyphClassName]
+ )}
+ >
+ <span>{character.char}</span>
+ <span
+ className={cn(
+ 'absolute inset-0 flex items-center justify-center',
+ 'scale-60 font-mono leading-none opacity-0'
+ )}
+ >
+ ▒
+ </span>
+ </span>
+ ))}
+ </span>
+ </Fragment>
+ ))}
+ </span>
+ </span>
+ )
+}
diff --git a/apps/kb/src/components/MobileMenu.tsx b/apps/kb/src/components/MobileMenu.tsx
new file mode 100644
index 00000000000..e07ea499e62
--- /dev/null
+++ b/apps/kb/src/components/MobileMenu.tsx
@@ -0,0 +1,171 @@
+import { X } from 'lucide-react'
+import { type KeyboardEvent } from 'react'
+import {
+ Accordion,
+ AccordionContent,
+ AccordionItem,
+ AccordionTrigger,
+ Button,
+ cn,
+ singleThemes,
+ ToggleGroup,
+ ToggleGroupItem,
+} from 'ui'
+
+import { SIGN_UP_URL, type NavMenu } from '../lib/nav'
+import { revealStyle } from '../lib/reveal'
+import { EXTERNAL_LINKS, useThemeChoice } from './HeaderMenu'
+import { Logo } from './Logo'
+
+export interface MobileMenuProps {
+ id: string
+ menus: NavMenu[]
+ onClose: () => void
+ className?: string
+}
+
+export const MobileMenu = ({ id, menus, onClose, className }: MobileMenuProps) => {
+ const { choice, onChoiceChange } = useThemeChoice()
+
+ const handleKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
+ if (event.key === 'Escape') onClose()
+ if (event.key !== 'Tab') return
+ // aria-modal doesn't stop Tab, so wrap focus between the first and last focusable element
+ const focusable = event.currentTarget.querySelectorAll<HTMLElement>('a[href], button')
+ const first = focusable[0]
+ const last = focusable[focusable.length - 1]
+ if (event.shiftKey && document.activeElement === first) {
+ event.preventDefault()
+ last.focus()
+ } else if (!event.shiftKey && document.activeElement === last) {
+ event.preventDefault()
+ first.focus()
+ }
+ }
+
+ // the menu only exists below lg, so close it once the viewport grows past that
+ const bindDesktopClose = (dialog: HTMLDivElement | null) => {
+ if (!dialog) return
+ const desktop = window.matchMedia('(width >= 64rem)')
+ const handleDesktopChange = (event: MediaQueryListEvent) => {
+ if (event.matches) onClose()
+ }
+ desktop.addEventListener('change', handleDesktopChange)
+ return () => desktop.removeEventListener('change', handleDesktopChange)
+ }
+
+ return (
+ <div
+ ref={bindDesktopClose}
+ id={id}
+ role="dialog"
+ aria-modal="true"
+ aria-label="Menu"
+ onKeyDown={handleKeyDown}
+ className={cn(
+ 'fixed inset-0 z-50 flex h-svh flex-col bg-overlay',
+ 'transition-opacity duration-150 starting:opacity-0 motion-reduce:transition-none',
+ className
+ )}
+ >
+ <div className="flex h-(--header-height) shrink-0 items-center justify-between border-b border-transparent px-6">
+ <Logo />
+ <button
+ type="button"
+ autoFocus
+ onClick={onClose}
+ className="inline-flex items-center justify-center rounded-md p-2 text-foreground-lighter hover:text-foreground-light focus-ring"
+ >
+ <span className="sr-only">Close menu</span>
+ <X aria-hidden className="size-6" strokeWidth={2} />
+ </button>
+ </div>
+ <div className="flex flex-1 flex-col overflow-y-auto px-4 pb-8 pt-4">
+ <Accordion type="multiple">
+ {menus.map((menu, index) => (
+ <AccordionItem
+ key={menu.label}
+ value={menu.label}
+ style={revealStyle(index)}
+ className={cn(
+ 'border-b transition duration-250 ease-out',
+ 'delay-[calc(var(--reveal-index)*50ms)] motion-reduce:transition-none',
+ 'starting:translate-y-2.5 starting:opacity-0'
+ )}
+ >
+ <AccordionTrigger className="py-2 pl-2 pr-4 text-base font-medium text-foreground hover:bg-surface-200">
+ {menu.label}
+ </AccordionTrigger>
+ <AccordionContent className="p-0">
+ <div className="flex flex-col gap-5 px-3 pb-4">
+ {menu.groups.map((group) => (
+ <div key={group.label} className="flex flex-col gap-3">
+ {menu.groups.length > 1 ? (
+ <span className="font-mono text-xs uppercase tracking-widest text-foreground-lighter">
+ {group.label}
+ </span>
+ ) : null}
+ <ul className="flex flex-col gap-3">
+ {group.links.map((link) => (
+ <li key={link.href}>
+ <a
+ href={link.href}
+ className="rounded-sm text-sm text-foreground-light hover:text-foreground focus-ring"
+ >
+ {link.label}
+ </a>
+ </li>
+ ))}
+ </ul>
+ </div>
+ ))}
+ </div>
+ </AccordionContent>
+ </AccordionItem>
+ ))}
+ </Accordion>
+ <ul className="mt-auto flex flex-col gap-3 px-2 pt-6">
+ {EXTERNAL_LINKS.map(({ label, href, Icon }) => (
+ <li key={href}>
+ <a
+ href={href}
+ target="_blank"
+ rel="noreferrer noopener"
+ className="flex items-center gap-2 rounded-sm text-sm text-foreground-light hover:text-foreground focus-ring"
+ >
+ <Icon aria-hidden className="size-4 text-foreground-lighter" strokeWidth={1.5} />
+ {label}
+ </a>
+ </li>
+ ))}
+ </ul>
+ <div className="px-2 pt-6">
+ <ToggleGroup
+ type="single"
+ variant="segmented"
+ tone="outline"
+ size="sm"
+ allowDeselect={false}
+ value={choice}
+ onValueChange={onChoiceChange}
+ aria-label="Theme"
+ className="w-full"
+ >
+ {singleThemes.map((theme) => (
+ <ToggleGroupItem key={theme.value} value={theme.value} className="flex-1">
+ {theme.name}
+ </ToggleGroupItem>
+ ))}
+ </ToggleGroup>
+ </div>
+ </div>
+ <div className="flex shrink-0 bg-alternative p-4">
+ <Button variant="primary" block asChild>
+ <a href={SIGN_UP_URL} className="h-10 py-4">
+ Start your project
+ </a>
+ </Button>
+ </div>
+ </div>
+ )
+}
diff --git a/apps/kb/src/components/Nav.tsx b/apps/kb/src/components/Nav.tsx
index aeda0f8fe38..c210a398069 100644
--- a/apps/kb/src/components/Nav.tsx
+++ b/apps/kb/src/components/Nav.tsx
@@ -1,4 +1,7 @@
+import { ChevronRight } from 'lucide-react'
+import { useState } from 'react'
import {
+ buttonVariants,
cn,
NavigationMenu,
NavigationMenuContent,
@@ -6,74 +9,128 @@ import {
NavigationMenuLink,
NavigationMenuList,
NavigationMenuTrigger,
- navigationMenuTriggerStyle,
+ NavigationMenuViewport,
} from 'ui'
-import { TOPICS, topicToSlug } from '../lib/topics'
+import type { NavMenu } from '../lib/nav'
-const visibleTopics = TOPICS.filter((topic) => topic.visible).map((topic) => ({
- label: topic.name,
- href: `${import.meta.env.BASE_URL}/topics/${topicToSlug(topic.name)}`,
-}))
+export interface NavProps {
+ menus: NavMenu[]
+ className?: string
+}
+
+interface MenuPanelProps {
+ menu: NavMenu
+}
-/**
- * Hard-codding links in here for now until we have actual content. Might be worth putting these arrays in their on data file too.
- */
-const resources = [
- { label: 'Status', href: 'https://status.supabase.com' },
- { label: 'Changelog', href: 'https://supabase.com/changelog' },
- { label: 'Docs', href: 'https://supabase.com/docs' },
-]
+export const Nav = ({ menus, className }: NavProps) => {
+ const menuLabels = menus.map((menu) => menu.label)
+ const [activeMenu, setActiveMenu] = useState('')
+ const [visibleMenu, setVisibleMenu] = useState('')
+ const [isSwitching, setIsSwitching] = useState(false)
-const menus = [
- { label: 'Topics', items: visibleTopics },
- { label: 'Resources', items: resources },
-]
+ const handleMenuChange = (value: string) => {
+ setIsSwitching(value !== '' && activeMenu !== '')
+ setActiveMenu(value)
+ if (value !== '') setVisibleMenu(value)
+ }
-const triggerClass =
- 'h-(--header-height) p-2 bg-transparent border-transparent font-normal rounded-none text-foreground-light hover:text-foreground data-open:text-foreground! border-0 focus-ring focus-visible:text-foreground h-full focus-visible:rounded-sm shadow-none!'
-// docs gates this at `md:absolute` (its own base component class) because its
-// nav is hidden entirely below `lg` in favor of a separate mobile menu. kb
-// doesn't have that split — the nav is always visible — so `absolute` is
-// unconditional here; without it, an open menu pushes its siblings around
-// below the `md` breakpoint instead of overlaying them.
-const contentClass =
- 'absolute top-[calc(100%+4px)]! z-50 min-w-56 max-h-[calc(100vh-4rem)] border-y w-screen md:w-64 overflow-hidden overflow-y-auto rounded-none md:rounded-md md:border border-overlay bg-overlay text-foreground-light shadow-md duration-0!'
-const itemClass =
- 'w-full flex h-8 items-center text-foreground-light text-sm hover:text-foreground select-none rounded-md p-2 leading-none no-underline focus-ring focus-visible:text-foreground'
+ const sideOf = (label: string) => {
+ if (label === visibleMenu) return 'active'
+ return menuLabels.indexOf(label) < menuLabels.indexOf(visibleMenu) ? 'start' : 'end'
+ }
-function Nav() {
return (
- <div className="flex relative gap-2 justify-start items-end w-full h-full">
- <NavigationMenu
- delayDuration={0}
- skipDelayDuration={0}
- className="w-full flex justify-start h-full"
- renderViewport={false}
- >
- <NavigationMenuList className="px-6 space-x-2 h-(--header-height)">
- {menus.map((menu) => (
- <NavigationMenuItem key={menu.label} className="text-sm relative h-full m-0">
- <NavigationMenuTrigger className={cn(navigationMenuTriggerStyle(), triggerClass)}>
- {menu.label}
- </NavigationMenuTrigger>
- <NavigationMenuContent className={contentClass}>
- <div className="p-3 md:p-1">
- {menu.items.map((item) => (
- <NavigationMenuLink key={item.label} asChild>
- <a href={item.href} className={itemClass}>
- {item.label}
- </a>
- </NavigationMenuLink>
- ))}
- </div>
- </NavigationMenuContent>
- </NavigationMenuItem>
- ))}
- </NavigationMenuList>
- </NavigationMenu>
- </div>
+ <NavigationMenu
+ delayDuration={0}
+ value={activeMenu}
+ onValueChange={handleMenuChange}
+ renderViewport={false}
+ className={cn('relative h-full items-stretch', className)}
+ >
+ <NavigationMenuList className="h-full items-stretch space-x-0">
+ {menus.map((menu) => (
+ <NavigationMenuItem key={menu.label} value={menu.label} className="text-sm font-medium">
+ <NavigationMenuTrigger
+ className={cn(
+ buttonVariants({ variant: 'text', size: 'small' }),
+ 'h-full bg-transparent! px-2.5 hover:text-primary data-open:text-primary!',
+ 'focus-ring focus-visible:text-foreground'
+ )}
+ >
+ {menu.label}
+ </NavigationMenuTrigger>
+ <NavigationMenuContent
+ forceMount
+ inert={visibleMenu !== menu.label}
+ data-active={visibleMenu === menu.label}
+ data-side={sideOf(menu.label)}
+ className={cn(
+ 'data-[motion^=from-]:animate-none! data-[motion^=to-]:animate-none!',
+ 'data-[active=false]:pointer-events-none data-[active=false]:opacity-0',
+ 'data-[side=start]:-translate-x-4 data-[side=end]:translate-x-4',
+ 'motion-safe:group-data-[switching=true]/viewport:transition',
+ 'motion-safe:group-data-[switching=true]/viewport:duration-250',
+ 'motion-safe:group-data-[switching=true]/viewport:ease-in-out'
+ )}
+ >
+ <MenuPanel menu={menu} />
+ </NavigationMenuContent>
+ </NavigationMenuItem>
+ ))}
+ </NavigationMenuList>
+ <NavigationMenuViewport
+ forceMount
+ data-open={activeMenu !== ''}
+ data-switching={isSwitching}
+ containerProps={{ className: '-left-3.5 justify-start pointer-events-none' }}
+ className={cn(
+ 'group/viewport pointer-events-auto origin-top-left scale-100 rounded-xl bg-surface-75',
+ 'data-[state=open]:animate-none! data-[state=closed]:animate-none!',
+ 'data-[state=open]:duration-200 data-[state=open]:ease-out data-[state=closed]:duration-200',
+ 'data-[open=false]:pointer-events-none data-[open=false]:invisible',
+ 'data-[open=false]:scale-[0.97] data-[open=false]:opacity-0',
+ 'motion-safe:transition-[opacity,scale,visibility]',
+ 'motion-safe:data-[switching=true]:transition-[width,height,opacity,scale,visibility]',
+ 'motion-reduce:transition-none'
+ )}
+ />
+ </NavigationMenu>
)
}
-export { Nav }
+const MenuPanel = ({ menu }: MenuPanelProps) => (
+ <div className="flex gap-12 px-6 py-5">
+ {menu.groups.map((group) => (
+ <div key={group.label} className="flex w-44 flex-col gap-6">
+ <span className="font-mono text-xs uppercase tracking-widest text-foreground-lighter">
+ {group.label}
+ </span>
+ <ul className="flex flex-col gap-4">
+ {group.links.map((link) => (
+ <li key={link.href}>
+ <NavigationMenuLink asChild>
+ <a
+ href={link.href}
+ className={cn(
+ 'group flex items-center gap-2 rounded-sm text-sm text-foreground-light',
+ 'hover:text-foreground focus-ring focus-visible:text-foreground'
+ )}
+ >
+ {link.label}
+ <ChevronRight
+ strokeWidth={2}
+ className={cn(
+ '-ml-1 w-3 -translate-x-1 opacity-0 transition-all',
+ 'group-hover:translate-x-0 group-hover:opacity-100'
+ )}
+ />
+ </a>
+ </NavigationMenuLink>
+ </li>
+ ))}
+ </ul>
+ </div>
+ ))}
+ </div>
+)
diff --git a/apps/kb/src/components/ThemeToggle.tsx b/apps/kb/src/components/ThemeToggle.tsx
deleted file mode 100644
index a09b8163bda..00000000000
--- a/apps/kb/src/components/ThemeToggle.tsx
+++ /dev/null
@@ -1,65 +0,0 @@
-// Same sun/moon icon apps/docs' mobile menu ThemeToggle uses (ui-patterns/ThemeToggle),
-// but a plain binary light/dark switch — no system option, no dropdown, no next-themes.
-function toggleTheme() {
- const isDark = document.documentElement.getAttribute('data-theme') !== 'light'
- const next = isDark ? 'light' : 'dark'
- document.documentElement.setAttribute('data-theme', next)
- try {
- localStorage.setItem('theme', next)
- } catch {
- // localStorage unavailable (e.g. private browsing) — theme just won't persist.
- }
-}
-
-// Theme is read/written as the `data-theme` attribute on <html> (matching
-// next-themes' default `attribute="data-theme"`, which is what the shared
-// theme CSS and Tailwind's `dark:` variant key off — see
-// packages/config/css/variants.css). The no-flash script in Layout.astro sets
-// the initial attribute before paint; this just flips it on click. The icons
-// themselves don't need React state — which one is visible is driven purely
-// by the `dark:` CSS variant, so there's no hydration-mismatch risk to guard
-// against here.
-function ThemeToggle() {
- return (
- <button
- type="button"
- aria-label="Toggle theme"
- onClick={toggleTheme}
- className="cursor-pointer flex h-7 w-7 items-center justify-center rounded-md text-foreground-light hover:text-foreground"
- >
- <svg
- className="hidden dark:block h-5 w-5 rotate-0 transition-transform"
- viewBox="0 0 24 24"
- fill="none"
- stroke="currentColor"
- strokeWidth={2}
- strokeLinecap="round"
- strokeLinejoin="round"
- >
- <path d="M20.985 12.486a9 9 0 1 1-9.473-9.472c.405-.022.617.46.402.803a6 6 0 0 0 8.268 8.268c.344-.215.825-.004.803.401" />
- </svg>
- <svg
- className="block dark:hidden h-5 w-5 rotate-0 transition-transform"
- viewBox="0 0 24 24"
- fill="none"
- stroke="currentColor"
- strokeWidth={2}
- strokeLinecap="round"
- strokeLinejoin="round"
- >
- <circle cx="12" cy="12" r="4" />
- <path d="M12 2v2" />
- <path d="M12 20v2" />
- <path d="m4.93 4.93 1.41 1.41" />
- <path d="m17.66 17.66 1.41 1.41" />
- <path d="M2 12h2" />
- <path d="M20 12h2" />
- <path d="m6.34 17.66-1.41 1.41" />
- <path d="m19.07 4.93-1.41 1.41" />
- </svg>
- <span className="sr-only">Toggle theme</span>
- </button>
- )
-}
-
-export { ThemeToggle }
diff --git a/apps/kb/src/components/TopicCover.tsx b/apps/kb/src/components/TopicCover.tsx
new file mode 100644
index 00000000000..dbf82abe440
--- /dev/null
+++ b/apps/kb/src/components/TopicCover.tsx
@@ -0,0 +1,54 @@
+import { useRef } from 'react'
+import { cn } from 'ui'
+
+import { FALLBACK_COMPOSITION, ISO_COMPOSITIONS } from '../lib/cover-compositions'
+import { pickCoverTopic, type Topic } from '../lib/topics'
+import { CoverCanvas } from './CoverCanvas'
+
+export interface TopicCoverProps {
+ title: string
+ description: string
+ topics: Topic[]
+ date?: string
+ className?: string
+}
+
+export const TopicCover = ({ title, description, topics, date, className }: TopicCoverProps) => {
+ const textRef = useRef<HTMLDivElement>(null)
+ const topic = pickCoverTopic(topics)
+ const composition = topic ? ISO_COMPOSITIONS[topic] : FALLBACK_COMPOSITION
+
+ return (
+ <article
+ className={cn(
+ 'relative overflow-hidden rounded-lg bg-surface-75 shadow-raised',
+ "after:pointer-events-none after:absolute after:inset-0 after:z-10 after:rounded-lg after:border after:border-default after:content-['']",
+ className
+ )}
+ >
+ <CoverCanvas
+ boxes={composition.boxes}
+ view={composition.view}
+ rings={composition.rings}
+ fillBoxes={composition.fillBoxes}
+ nudgeY={composition.nudgeY}
+ zoom={composition.zoom}
+ keepOutRef={textRef}
+ />
+ <div
+ ref={textRef}
+ className="absolute inset-x-0 bottom-0 flex flex-col gap-3 bg-surface-75 px-6 pb-6"
+ >
+ <h3 className="m-0 grid min-h-[2lh] content-end font-sans! text-3xl font-medium! leading-8 tracking-tight text-foreground">
+ <span className="line-clamp-2">{title}</span>
+ </h3>
+ <p className="m-0 line-clamp-2 min-h-[2lh] max-w-100 pr-8 text-sm leading-5.5 text-foreground-light">
+ {description}
+ </p>
+ {date !== undefined ? (
+ <p className="m-0 min-h-5 text-xs leading-5 text-foreground-lighter">{date}</p>
+ ) : null}
+ </div>
+ </article>
+ )
+}
diff --git a/apps/kb/src/components/TopicShape.tsx b/apps/kb/src/components/TopicShape.tsx
new file mode 100644
index 00000000000..84c337ffdce
--- /dev/null
+++ b/apps/kb/src/components/TopicShape.tsx
@@ -0,0 +1,99 @@
+import { cn } from 'ui'
+
+import { HERO_PADDING, HERO_RINGS, HERO_SHAPES } from '../lib/hero-shapes'
+import {
+ compositionBounds,
+ paintOrder,
+ projectShape,
+ ringBounds,
+ VIEW_POINTS,
+ type IsoPoint,
+} from '../lib/iso-shapes'
+import type { Topic } from '../lib/topics'
+
+export interface TopicShapeProps {
+ topic: Topic
+ className?: string
+}
+
+const PIECE_DELAY_MS = 105
+const GUIDES_LEAD_MS = 340
+
+// faces paint back to front and fill with the page color, so a near face hides the lines behind it
+export const TopicShape = ({ topic, className }: TopicShapeProps) => {
+ const boxes = paintOrder(HERO_SHAPES[topic])
+ const pieces = boxes.map((box) => projectShape({ box }))
+ const rings = (HERO_RINGS[topic] ?? []).map((ring) => {
+ const [cx, cy] = VIEW_POINTS.iso(ring.x, ring.y, ring.z)
+ return { ...ring, cx, cy }
+ })
+ const solidRings = rings.filter((ring) => !ring.isDashed)
+ const bounds = compositionBounds([...pieces, ...ringBounds({ rings })], HERO_PADDING[topic] ?? 0)
+ // the long side is 320 viewBox units. that is near its rendered size, so a 1 unit stroke stays near 1px
+ const scale = 320 / Math.max(bounds.width, bounds.height)
+ const toView = ([x, y]: IsoPoint): IsoPoint => [(x - bounds.x) * scale, (y - bounds.y) * scale]
+ const toPoints = (polygon: IsoPoint[]) =>
+ polygon.map((point) => toView(point).join(',')).join(' ')
+
+ return (
+ <svg
+ aria-hidden
+ // the classes size it. until the css lands, a zero size keeps an unstyled shape from flashing
+ width={0}
+ height={0}
+ viewBox={`0 0 ${bounds.width * scale} ${bounds.height * scale}`}
+ className={cn(
+ 'overflow-visible fill-background stroke-current text-border-stronger',
+ className
+ )}
+ >
+ {rings
+ .filter((ring) => ring.isDashed)
+ .map(({ cx, cy, radius }) => {
+ const [x, y] = toView([cx, cy])
+ return (
+ <circle
+ key={`${cx}:${cy}`}
+ cx={x}
+ cy={y}
+ r={radius * scale}
+ fill="none"
+ strokeDasharray="3.6 3.6"
+ style={{
+ animationDelay: `${GUIDES_LEAD_MS + (solidRings.length + pieces.length) * PIECE_DELAY_MS}ms`,
+ }}
+ className="motion-safe:animate-fade-in"
+ />
+ )
+ })}
+ {solidRings.map(({ cx, cy, radius }, index) => {
+ const [x, y] = toView([cx, cy])
+ return (
+ <circle
+ key={`${cx}:${cy}`}
+ cx={x}
+ cy={y}
+ r={radius * scale}
+ pathLength={1}
+ style={{ animationDelay: `${GUIDES_LEAD_MS + index * PIECE_DELAY_MS}ms` }}
+ className="[stroke-dasharray:1] motion-safe:animate-draw-line-fast"
+ />
+ )
+ })}
+ {pieces.flatMap((piece, index) =>
+ [...piece.faces, ...piece.insets].map((polygon) => (
+ <polygon
+ key={toPoints(polygon)}
+ points={toPoints(polygon)}
+ pathLength={1}
+ strokeLinejoin="round"
+ style={{
+ animationDelay: `${GUIDES_LEAD_MS + (solidRings.length + index) * PIECE_DELAY_MS}ms`,
+ }}
+ className="[stroke-dasharray:1] motion-safe:animate-draw-line-fast"
+ />
+ ))
+ )}
+ </svg>
+ )
+}
diff --git a/apps/kb/src/components/WarpCanvas.tsx b/apps/kb/src/components/WarpCanvas.tsx
new file mode 100644
index 00000000000..58b66c35e01
--- /dev/null
+++ b/apps/kb/src/components/WarpCanvas.tsx
@@ -0,0 +1,550 @@
+import { useCallback, type RefObject } from 'react'
+import { cn } from 'ui'
+
+import {
+ BEAM_ALPHA,
+ clamp,
+ drawStep,
+ GLYPH_PITCH,
+ hash,
+ isBeamAt,
+ phase,
+ rampGlyph,
+ type PixelRect,
+} from '../lib/ascii/field'
+import { loadGrain, punchGrain } from '../lib/ascii/grain'
+import { createInfall } from '../lib/ascii/infall'
+import { createLayer, sizeLayers } from '../lib/ascii/layer'
+import {
+ easeInOutCubic,
+ easeOutCubic,
+ frontRadius,
+ isBehindWall,
+ locateCell,
+ projectWarp,
+ ringRadii,
+ type WarpCell,
+ type WarpPoint,
+ type WarpShape,
+} from '../lib/ascii/warp'
+import { ColorProbes, observeTheme, readProbeColor } from './ColorProbes'
+
+export interface WarpCanvasProps {
+ anchorRef: RefObject<HTMLElement | null>
+ className?: string
+}
+
+interface StrokePolylineParams {
+ ctx: CanvasRenderingContext2D
+ points: WarpPoint[]
+ visible: boolean[]
+ isClosed: boolean
+}
+
+interface CellShownParams {
+ ring: number
+ spoke: number
+ radii: number[]
+ ringVisible: boolean[][]
+}
+
+interface CellOutlineParams extends CellShownParams {
+ project: (r: number, angle: number) => WarpPoint
+}
+
+interface CellGlyphsParams {
+ ring: number
+ spoke: number
+ strength: number
+ radii: number[]
+ project: (r: number, angle: number) => WarpPoint
+}
+
+interface PlacedGlyph extends WarpPoint {
+ glyph: string
+ isBeam: boolean
+}
+
+interface Pulse {
+ spoke: number
+ start: number
+ ringPos: number
+ age: number
+}
+
+interface Palette {
+ line: string
+ glyph: string
+ beam: string
+}
+
+const PROBES = {
+ line: 'text-border-muted',
+ glyph: 'text-foreground-lighter',
+ beam: 'text-brand',
+} as const
+
+const THROAT_RADIUS = 150
+const ANCHOR_MARGIN = 24
+const BOTTOM_FADE = 200
+const THROAT_DROP = 90
+const RING_ANGLES = Array.from({ length: 160 }, (_, k) => (k / 160) * Math.PI * 2)
+const SPOKE_ANGLES = Array.from({ length: 32 }, (_, s) => (s / 32) * Math.PI * 2)
+const SAMPLES_PER_CELL = RING_ANGLES.length / SPOKE_ANGLES.length
+const SPOKE_STEPS = 6
+const MAX_FLATTEN = 0.15
+const EXPAND_STEPS = 60
+const FRONT_ARC_ANGLES = Array.from({ length: 81 }, (_, k) => (k / 80) * Math.PI)
+
+const SPAWN_MIN_RING = 5
+const FADE_IN_S = 0.3
+const CELL_PADDING = 0.18
+
+const subdivide = (radii: number[]) =>
+ radii.flatMap((r, i) => {
+ const next = radii[i + 1]
+ if (next === undefined) return [r]
+ return Array.from({ length: SPOKE_STEPS }, (_, step) => r + ((next - r) * step) / SPOKE_STEPS)
+ })
+
+const strokePolyline = ({ ctx, points, visible, isClosed }: StrokePolylineParams) => {
+ const count = isClosed ? points.length : points.length - 1
+ for (let i = 0; i < count; i++) {
+ const next = (i + 1) % points.length
+ if (!visible[i] || !visible[next]) continue
+ ctx.moveTo(points[i].x, points[i].y)
+ ctx.lineTo(points[next].x, points[next].y)
+ }
+}
+
+const cellSamples = (spoke: number) =>
+ Array.from(
+ { length: SAMPLES_PER_CELL + 1 },
+ (_, step) => (spoke * SAMPLES_PER_CELL + step) % RING_ANGLES.length
+ )
+
+const isCellShown = ({ ring, spoke, radii, ringVisible }: CellShownParams) =>
+ ring >= 0 &&
+ ring + 1 < radii.length &&
+ cellSamples(spoke).every((k) => ringVisible[ring][k] && ringVisible[ring + 1][k])
+
+const cellOutline = ({
+ ring,
+ spoke,
+ radii,
+ ringVisible,
+ project,
+}: CellOutlineParams): WarpPoint[] | null => {
+ if (!isCellShown({ ring, spoke, radii, ringVisible })) return null
+ const samples = cellSamples(spoke)
+ const inner = samples.map((k) => project(radii[ring], RING_ANGLES[k]))
+ const outer = samples.map((k) => project(radii[ring + 1], RING_ANGLES[k]))
+ return [...inner, ...outer.reverse()]
+}
+
+const cellGlyphs = ({ ring, spoke, strength, radii, project }: CellGlyphsParams): PlacedGlyph[] => {
+ const spokeWidth = (Math.PI * 2) / SPOKE_ANGLES.length
+ const rInner = radii[ring] + (radii[ring + 1] - radii[ring]) * CELL_PADDING
+ const rOuter = radii[ring + 1] - (radii[ring + 1] - radii[ring]) * CELL_PADDING
+ const aStart = SPOKE_ANGLES[spoke] + spokeWidth * CELL_PADDING
+ const aEnd = SPOKE_ANGLES[spoke] + spokeWidth * (1 - CELL_PADDING)
+ const rMid = (rInner + rOuter) / 2
+ const aMid = (aStart + aEnd) / 2
+ const width = distance(project(rMid, aStart), project(rMid, aEnd))
+ const height = distance(project(rInner, aMid), project(rOuter, aMid))
+ const cols = Math.max(1, Math.floor(width / GLYPH_PITCH))
+ const rows = Math.max(1, Math.floor(height / 14))
+
+ const glyphs: PlacedGlyph[] = []
+ for (let row = 0; row < rows; row++) {
+ for (let col = 0; col < cols; col++) {
+ const cellCol = spoke * cols + col
+ const cellRow = ring * rows + row
+ const glyph = rampGlyph(strength * hash(cellCol, cellRow))
+ if (glyph === ' ') continue
+ const r = rInner + ((rOuter - rInner) * (row + 0.5)) / rows
+ const angle = aStart + ((aEnd - aStart) * (col + 0.5)) / cols
+ const isBeam = isBeamAt({ col: cellCol, row: cellRow })
+ glyphs.push({ glyph, isBeam, ...project(r, angle) })
+ }
+ }
+ return glyphs
+}
+
+const distance = (a: WarpPoint, b: WarpPoint) => Math.hypot(a.x - b.x, a.y - b.y)
+
+const readPalette = (probeRoot: HTMLElement): Palette => {
+ const read = (role: keyof typeof PROBES) => readProbeColor(probeRoot, role)
+ return {
+ line: read('line'),
+ glyph: read('glyph'),
+ beam: read('beam'),
+ }
+}
+
+export const WarpCanvas = ({ anchorRef, className }: WarpCanvasProps) => {
+ const setupCanvas = useCallback((canvas: HTMLCanvasElement | null) => {
+ const host = canvas?.parentElement
+ const ctx = canvas?.getContext('2d')
+ const probeRoot = canvas?.nextElementSibling
+ const gridLayer = createLayer()
+ if (!canvas || !host || !ctx || !gridLayer || !(probeRoot instanceof HTMLElement)) return
+ const grid = gridLayer.ctx
+
+ const isReducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches
+ const revealStartedAt = performance.now()
+ const revealAt = (now: number) =>
+ isReducedMotion ? 1 : Math.min(1, (now - revealStartedAt) / 600)
+ let grain: CanvasPattern | null = null
+ loadGrain(grid).then((pattern) => {
+ grain = pattern
+ draw()
+ })
+ let palette = readPalette(probeRoot)
+ let baseShape: WarpShape = { cx: 0, rimY: 0, throatY: 0, r0: THROAT_RADIUS }
+ let baseRadii: number[] = []
+ let expandStep = -1
+ let shape = baseShape
+ let radii: number[] = []
+ let spokeRadii: number[] = []
+ let ringVisible: boolean[][] = []
+ let spokeVisible: boolean[][] = []
+ let anchorBox: PixelRect | null = null
+ let boundaryRing = -1
+ let boundaryY = 0
+ let pulses: Pulse[] = []
+ let hovered: WarpCell | null = null
+ let isVisible = false
+ let frame = 0
+ let lastTime = 0
+ let lastSpawn = 0
+ let isAnchorObserved = false
+ const infall = createInfall({ getAnchor: () => anchorRef.current })
+ let ringdownWave = -1
+ // the rings and spokes change only with scroll, size and theme, so frames reuse this layer
+ let gridKey = ''
+
+ const isRunning = () => isVisible && document.visibilityState === 'visible'
+
+ const getScrollProgress = () => {
+ const rect = host.getBoundingClientRect()
+ return clamp(-rect.top / rect.height, 0, 1)
+ }
+
+ const draw = () => {
+ const width = canvas.clientWidth
+ const height = canvas.clientHeight
+ const progress = getScrollProgress()
+ const step = Math.round(easeOutCubic(progress) * EXPAND_STEPS)
+ if (step !== expandStep) {
+ expandStep = step
+ const grow = (THROAT_RADIUS * 0.65 * step) / EXPAND_STEPS
+ shape = { ...baseShape, r0: baseShape.r0 + grow }
+ const edge = baseRadii[boundaryRing]
+ const edgeGrow = boundaryRing > 0 ? frontRadius({ shape, y: boundaryY }) - edge : grow
+ radii = baseRadii.map((r, i) =>
+ i < boundaryRing
+ ? r + grow + ((edgeGrow - grow) * (r - THROAT_RADIUS)) / (edge - THROAT_RADIUS)
+ : r + edgeGrow
+ )
+ spokeRadii = subdivide(radii)
+ const isShown = (r: number, angle: number) => !isBehindWall({ shape, radii, r, angle })
+ ringVisible = radii.map((r) => RING_ANGLES.map((angle) => isShown(r, angle)))
+ spokeVisible = SPOKE_ANGLES.map((angle) => spokeRadii.map((r) => isShown(r, angle)))
+ }
+ const flatten = MAX_FLATTEN * easeInOutCubic(progress)
+ const lineY = height - 1.5
+ const project = (r: number, angle: number) => projectWarp({ shape, r, angle, flatten, lineY })
+ const clipToBoundary = (target: CanvasRenderingContext2D) => {
+ if (boundaryRing < 0) return
+ const span = Math.max(width, height) * 4
+ target.beginPath()
+ target.moveTo(-span, -span)
+ target.lineTo(span, -span)
+ for (const angle of FRONT_ARC_ANGLES) {
+ const { x, y } = project(radii[boundaryRing], angle)
+ target.lineTo(x, y + 1)
+ }
+ target.closePath()
+ target.clip()
+ }
+
+ const t = revealAt(performance.now())
+ // bending pulls the rings past the boundary up to it, so they would show inside the slack
+ const ringCount = boundaryRing < 0 ? radii.length : boundaryRing + 1
+ // rings that fit inside the copy are hidden behind its fade, so they show at once
+ const copyHalfWidth = anchorBox ? (anchorBox.right - anchorBox.left) / 2 : 0
+ const firstSweptRing = Math.max(
+ 0,
+ radii.findIndex((r) => r > copyHalfWidth)
+ )
+ const shownRings =
+ firstSweptRing +
+ Math.ceil((ringCount - firstSweptRing) * phase({ t, start: 0, length: 0.6 }))
+ const down = drawStep(phase({ t, start: 0.35, length: 0.65 }))
+ if (gridKey !== `${expandStep}:${flatten}:${shownRings}:${down}`) {
+ gridKey = `${expandStep}:${flatten}:${shownRings}:${down}`
+ grid.clearRect(0, 0, width, height)
+ grid.save()
+ clipToBoundary(grid)
+ grid.lineWidth = 1
+ grid.strokeStyle = palette.line
+ grid.beginPath()
+ radii.slice(0, shownRings).forEach((r, i) => {
+ const points = RING_ANGLES.map((angle) => project(r, angle))
+ strokePolyline({ ctx: grid, points, visible: ringVisible[i], isClosed: true })
+ })
+ grid.stroke()
+ grid.beginPath()
+ SPOKE_ANGLES.forEach((angle, s) => {
+ const points = spokeRadii
+ .slice(0, Math.round(((ringCount - 1) * SPOKE_STEPS + 1) * down))
+ .map((r) => project(r, angle))
+ strokePolyline({ ctx: grid, points, visible: spokeVisible[s], isClosed: false })
+ })
+ grid.stroke()
+ if (grain) {
+ punchGrain({ ctx: grid, pattern: grain, width, height })
+ }
+ grid.restore()
+ }
+ ctx.clearRect(0, 0, width, height)
+ ctx.drawImage(gridLayer.canvas, 0, 0, width, height)
+ if (!isReducedMotion && infall.paint({ shape, flatten, lineY, progress })) {
+ // the wave owns the grid while it runs, so pulses stop and no new ones spawn
+ ringdownWave = 0
+ pulses = []
+ }
+
+ ctx.save()
+ clipToBoundary(ctx)
+ ctx.font = '11px ui-monospace, SFMono-Regular, Menlo, monospace'
+ ctx.textAlign = 'center'
+ ctx.textBaseline = 'middle'
+ const paintCell = (cell: WarpCell, strength: number) => {
+ if (!isCellShown({ ...cell, radii, ringVisible })) return
+ const alpha = Math.min(1, strength) * (1 - flatten)
+ for (const { glyph, isBeam, x, y } of cellGlyphs({ ...cell, strength, radii, project })) {
+ ctx.fillStyle = isBeam ? palette.beam : palette.glyph
+ ctx.globalAlpha = alpha * (isBeam ? BEAM_ALPHA : 1)
+ ctx.fillText(glyph, x, y)
+ }
+ }
+ for (const pulse of pulses) {
+ const fadeIn = Math.min(1, pulse.age / FADE_IN_S)
+ const head = Math.floor(pulse.ringPos)
+ for (const [offset, strength] of [1, 0.45, 0.18].entries()) {
+ const ring = head + offset
+ if (ring <= pulse.start) paintCell({ ring, spoke: pulse.spoke }, strength * fadeIn)
+ }
+ }
+ if (ringdownWave >= 0) {
+ const head = Math.floor(ringdownWave)
+ const fade = 1 - (ringdownWave / ringCount) ** 2
+ SPOKE_ANGLES.forEach((_, spoke) => {
+ for (const [offset, strength] of [1, 0.7, 0.4].entries()) {
+ const ring = head - offset
+ if (ring >= 0 && hash(spoke, ring) > 0.15) paintCell({ ring, spoke }, strength * fade)
+ }
+ })
+ }
+ if (hovered && ringdownWave < 0) paintCell(hovered, 1)
+ ctx.restore()
+
+ const bottomFade = ctx.createLinearGradient(0, height - BOTTOM_FADE, 0, height)
+ bottomFade.addColorStop(0, 'rgb(0 0 0 / 0)')
+ bottomFade.addColorStop(1, 'rgb(0 0 0 / 1)')
+ ctx.globalCompositeOperation = 'destination-out'
+ ctx.globalAlpha = 1
+ ctx.fillStyle = bottomFade
+ ctx.fillRect(0, height - BOTTOM_FADE, width, BOTTOM_FADE)
+ ctx.globalCompositeOperation = 'source-over'
+ }
+
+ const isPaintable = ({ ring, spoke }: WarpCell, canBeUnderCopy = false) => {
+ const outline = cellOutline({
+ ring,
+ spoke,
+ radii,
+ ringVisible,
+ project: (r, angle) => projectWarp({ shape, r, angle, flatten: 0, lineY: 0 }),
+ })
+ if (!outline) return false
+ const { x, y } = outline[Math.floor(outline.length / 4)]
+ const isOffCanvas = x < 0 || x > canvas.clientWidth || y < 0 || y > canvas.clientHeight
+ const isUnderCopy =
+ anchorBox !== null &&
+ x >= anchorBox.left &&
+ x <= anchorBox.right &&
+ y >= anchorBox.top &&
+ y <= anchorBox.bottom
+ return !isOffCanvas && (canBeUnderCopy || !isUnderCopy)
+ }
+
+ const launch = ({ ring, spoke }: WarpCell, age = 0) => {
+ pulses.push({ spoke, start: ring, ringPos: ring + 0.999, age })
+ }
+
+ const spawn = () => {
+ for (let attempt = 0; attempt < 8; attempt++) {
+ const cell = {
+ ring: SPAWN_MIN_RING + Math.floor(Math.random() * (radii.length - 1 - SPAWN_MIN_RING)),
+ spoke: Math.floor(Math.random() * SPOKE_ANGLES.length),
+ }
+ if (isPaintable(cell)) return launch(cell)
+ }
+ }
+
+ const handlePointerMove = (event: PointerEvent) => {
+ const origin = canvas.getBoundingClientRect()
+ const cell = locateCell({
+ shape,
+ radii,
+ spokeCount: SPOKE_ANGLES.length,
+ x: event.clientX - origin.left,
+ y: event.clientY - origin.top,
+ flatten: MAX_FLATTEN * easeInOutCubic(getScrollProgress()),
+ lineY: canvas.clientHeight - 0.5,
+ })
+ hovered = cell && isPaintable(cell, true) ? cell : null
+ requestDraw()
+ }
+
+ const handlePointerLeave = () => {
+ hovered = null
+ requestDraw()
+ }
+
+ const handleClick = () => {
+ if (!hovered || isReducedMotion) return
+ launch(hovered, FADE_IN_S)
+ }
+
+ const tick = (time: number) => {
+ frame = 0
+ if (!isRunning()) return
+ const dt = lastTime ? Math.min(0.05, (time - lastTime) / 1000) : 0
+ lastTime = time
+ if (revealAt(time) >= 1 && ringdownWave < 0 && time - lastSpawn > 450 && pulses.length < 10) {
+ lastSpawn = time
+ spawn()
+ }
+ infall.advance(dt)
+ if (ringdownWave >= 0) {
+ ringdownWave += 14 * dt
+ // past the last drawn ring the fade turns negative, which has no ramp glyph
+ if (ringdownWave >= (boundaryRing < 0 ? radii.length : boundaryRing + 1)) ringdownWave = -1
+ }
+ pulses = pulses.flatMap((pulse) => {
+ const speed = 2.5 * (1 + 0.25 * (pulse.start - pulse.ringPos))
+ const ringPos = pulse.ringPos - speed * dt
+ if (ringPos < 0) return []
+ return [{ ...pulse, ringPos, age: pulse.age + dt }]
+ })
+ draw()
+ frame = requestAnimationFrame(tick)
+ }
+
+ const wake = () => {
+ if (isReducedMotion || frame || !isRunning()) return
+ lastTime = 0
+ frame = requestAnimationFrame(tick)
+ }
+
+ const requestDraw = () => {
+ if (!isReducedMotion || frame) return
+ frame = requestAnimationFrame(() => {
+ frame = 0
+ draw()
+ })
+ }
+
+ const measure = () => {
+ const width = host.clientWidth
+ const height = host.clientHeight
+ sizeLayers({ contexts: [ctx, grid], width, height })
+ gridKey = ''
+
+ if (anchorRef.current && !isAnchorObserved) {
+ isAnchorObserved = true
+ resizeObserver.observe(anchorRef.current)
+ }
+ const origin = host.getBoundingClientRect()
+ const covered = [...(anchorRef.current?.children ?? [])].map((child) =>
+ child.getBoundingClientRect()
+ )
+ anchorBox =
+ covered.length > 0
+ ? {
+ left: Math.min(...covered.map((rect) => rect.left)) - origin.left - ANCHOR_MARGIN,
+ top: Math.min(...covered.map((rect) => rect.top)) - origin.top - ANCHOR_MARGIN,
+ right: Math.max(...covered.map((rect) => rect.right)) - origin.left + ANCHOR_MARGIN,
+ bottom: Math.max(...covered.map((rect) => rect.bottom)) - origin.top + ANCHOR_MARGIN,
+ }
+ : null
+ const throatTarget = anchorRef.current
+ ?.querySelector('[data-warp-throat]')
+ ?.getBoundingClientRect()
+ const throatBox = throatTarget ?? anchorRef.current?.getBoundingClientRect()
+ const throatY = throatBox
+ ? (throatBox.top + throatBox.bottom) / 2 -
+ origin.top +
+ (throatTarget ? infall.getLift() : THROAT_DROP)
+ : height / 2
+ baseShape = { cx: width / 2, rimY: throatY - 190, throatY, r0: THROAT_RADIUS }
+ infall.measure({ origin, throat: { x: width / 2, y: throatY } })
+ baseRadii = ringRadii({ r0: THROAT_RADIUS, maxRadius: Math.hypot(width, height * 3) })
+ const frontYs = baseRadii.map(
+ (r) => projectWarp({ shape: baseShape, r, angle: Math.PI / 2, flatten: 0, lineY: 0 }).y
+ )
+ boundaryRing = frontYs.findLastIndex((y) => y <= height - 2)
+ boundaryY = frontYs[boundaryRing] ?? 0
+ expandStep = -1
+ draw()
+ }
+
+ const resizeObserver = new ResizeObserver(measure)
+ resizeObserver.observe(host)
+
+ const intersectionObserver = new IntersectionObserver(([entry]) => {
+ isVisible = entry.isIntersecting
+ wake()
+ })
+ intersectionObserver.observe(canvas)
+
+ const unobserveTheme = observeTheme(() => {
+ palette = readPalette(probeRoot)
+ gridKey = ''
+ draw()
+ })
+
+ window.addEventListener('scroll', requestDraw, { passive: true })
+ host.addEventListener('pointermove', handlePointerMove)
+ host.addEventListener('pointerleave', handlePointerLeave)
+ host.addEventListener('click', handleClick)
+ document.addEventListener('visibilitychange', wake)
+
+ return () => {
+ cancelAnimationFrame(frame)
+ resizeObserver.disconnect()
+ intersectionObserver.disconnect()
+ unobserveTheme()
+ window.removeEventListener('scroll', requestDraw)
+ host.removeEventListener('pointermove', handlePointerMove)
+ host.removeEventListener('pointerleave', handlePointerLeave)
+ host.removeEventListener('click', handleClick)
+ document.removeEventListener('visibilitychange', wake)
+ }
+ }, [])
+
+ return (
+ <>
+ <canvas
+ ref={setupCanvas}
+ aria-hidden
+ className={cn('pointer-events-none absolute inset-0 size-full', className)}
+ />
+ <ColorProbes probes={PROBES} />
+ </>
+ )
+}
diff --git a/apps/kb/src/content.config.ts b/apps/kb/src/content.config.ts
index 7f62410d221..7d154553738 100644
--- a/apps/kb/src/content.config.ts
+++ b/apps/kb/src/content.config.ts
@@ -4,7 +4,7 @@ import { z } from 'astro/zod'
import { TOPIC_NAMES } from './lib/topics'
-// Format date as "26 SEPTEMBER 2026"
+// Format date as "September 26, 2026"
const formatDate = (date: Date): string => {
// Adjust for timezone offset to preserve the intended date
const adjusted = new Date(date.getTime() + date.getTimezoneOffset() * 60000)
@@ -12,9 +12,7 @@ const formatDate = (date: Date): string => {
year: 'numeric',
month: 'long',
day: 'numeric',
- })
- .format(adjusted)
- .toUpperCase()
+ }).format(adjusted)
}
// Every entry here is rendered through GuideLayout by
diff --git a/apps/kb/src/content/guides/sample-guide.mdx b/apps/kb/src/content/guides/sample-guide.mdx
deleted file mode 100644
index c420dd19eea..00000000000
--- a/apps/kb/src/content/guides/sample-guide.mdx
+++ /dev/null
@@ -1,100 +0,0 @@
----
-title: 'Markdown elements sample'
-description: 'A lorem ipsum sample guide exercising every base Markdown element supported by the guide layout.'
-topics: ['Tutorial', 'Database']
-pinned: true
-github_url: 'https://github.com/supabase/supabase/discussions/0000000'
-date: 2026-10-05
----
-
-Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor
-incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis
-nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
-
-## Heading level 2
-
-Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore
-eu fugiat nulla pariatur. This paragraph mixes **bold text**, _italic text_,
-**_bold italic text_**, ~~strikethrough text~~, and `inline code`.
-
-### Heading level 3
-
-Here's a [link to the Astro docs](https://docs.astro.build/en/basics/layouts/),
-followed by an unordered list with a nested list:
-
-- Excepteur sint occaecat cupidatat non proident
-- Sunt in culpa qui officia deserunt mollit anim id est laborum
- - Nested item one
- - Nested item two
-- Curabitur blandit tempus porttitor
-
-#### Heading level 4
-
-And an ordered list with a nested list:
-
-1. Lorem ipsum dolor sit amet
-2. Consectetur adipiscing elit
- 1. Nested step one
- 2. Nested step two
-3. Sed do eiusmod tempor incididunt
-
-##### Heading level 5
-
-> Neque porro quisquam est qui dolorem ipsum quia dolor sit amet,
-> consectetur, adipisci velit.
->
-> > Nested blockquote: at vero eos et accusamus et iusto odio dignissimos.
-
-GitHub-style alert blockquotes, rendered through the `Admonition` component:
-
-> [!NOTE]
-> Useful information that users should know, even when skimming content.
-
-> [!TIP]
-> Helpful advice for doing things better or more easily.
-
-> [!IMPORTANT]
-> Key information users need to know to achieve their goal.
-
-> [!WARNING]
-> Urgent info that needs immediate attention to avoid problems.
-
-> [!CAUTION]
-> Advises about risks or negative outcomes of certain actions.
-
-###### Heading level 6
-
-A fenced code block with a language tag:
-
-```js
-function add(a, b) {
- return a + b
-}
-
-console.log(add(2, 3))
-```
-
-And another in a different language:
-
-```bash
-npm install
-npm run dev
-```
-
-A table:
-
-| Element | Supported | Notes |
-| -------- | --------- | ---------------------------- |
-| Headings | Yes | h2 through h6 |
-| Tables | Yes | via GitHub-flavored Markdown |
-| Images | Yes | see below |
-
-An image:
-
-![Placeholder image](https://placehold.co/800x400?text=Placeholder+Image)
-
----
-
-Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium
-doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore
-veritatis et quasi architecto beatae vitae dicta sunt explicabo.
diff --git a/apps/kb/src/layouts/ArticleLayout.astro b/apps/kb/src/layouts/ArticleLayout.astro
index e8cb9479bd7..08f2239c4b6 100644
--- a/apps/kb/src/layouts/ArticleLayout.astro
+++ b/apps/kb/src/layouts/ArticleLayout.astro
@@ -1,9 +1,13 @@
---
import { ExternalLink } from 'lucide-react'
-import { Badge, GithubIcon } from 'ui'
+import { Breadcrumb, BreadcrumbItem, BreadcrumbLink, BreadcrumbList, BreadcrumbSeparator, GithubIcon } from 'ui'
+import type { TOCItemType } from 'ui-patterns/Toc/types'
+import { FeaturedSection } from '../components/FeaturedSection'
+import { GuideSidebar } from '../components/GuideSidebar'
+import type { RelatedGuides } from '../lib/guides'
import Layout from './Layout.astro'
-import { getTopicDescription, type Topic, TOPIC_NAMES, topicToSlug } from '../lib/topics'
+import { getTopicDescription, isKnownTopic, topicToSlug } from '../lib/topics'
interface Props {
title: string
@@ -15,62 +19,118 @@ interface Props {
github_url?: string
viewGitHubLink?: string
date?: string
+ toc?: TOCItemType[]
jsonLd?: Record<string, unknown> | Record<string, unknown>[]
+ related?: RelatedGuides | null
}
-const { title, description, topics = [], github_url, viewGitHubLink, date, jsonLd } = Astro.props
-
-function isKnownTopic(topic: string): topic is Topic {
- return (TOPIC_NAMES as readonly string[]).includes(topic)
-}
+const {
+ title,
+ description,
+ topics = [],
+ github_url,
+ viewGitHubLink,
+ date,
+ toc = [],
+ jsonLd,
+ related,
+} = Astro.props
+const pagePath = Astro.url.pathname.replace(/\/$/, '')
+// the `<page>.md` redirect only exists on vercel (vercel.json), so fetch the generated file directly
+const markdownUrl = `${pagePath.replace(import.meta.env.BASE_URL, `${import.meta.env.BASE_URL}/markdown`)}.md`
---
<Layout title={title} description={description} jsonLd={jsonLd}>
- <article class="prose max-w-3xl mx-auto px-6 py-16">
- <h1>{title}</h1>
- {date && <p class="text-sm pb-4">{date}</p>}
- {description && <p class="lead">{description}</p>}
- {
- topics.length > 0 && (
- <div class="flex flex-wrap gap-2">
- {topics.map((topic) =>
- isKnownTopic(topic) ? (
- <a
- href={`${import.meta.env.BASE_URL}/topics/${topicToSlug(topic)}`}
- title={getTopicDescription(topic)}
- >
- <Badge>{topic}</Badge>
- </a>
- ) : (
- <Badge>{topic}</Badge>
+ <div class="section-container lg:grid lg:grid-cols-3 lg:gap-6">
+ <article class="prose prose-img:rounded-lg max-w-none min-w-0 py-16 lg:col-span-2">
+ <Breadcrumb className="not-prose mb-6">
+ <BreadcrumbList>
+ <BreadcrumbItem>
+ <BreadcrumbLink href={import.meta.env.BASE_URL}>Knowledge base</BreadcrumbLink>
+ </BreadcrumbItem>
+ {
+ topics.length > 0 && (
+ <>
+ <BreadcrumbSeparator />
+ {/* a guide can sit in several topics, so they share one level instead of nesting */}
+ <BreadcrumbItem>
+ {topics.map((topic, index) => (
+ <span>
+ {isKnownTopic(topic) ? (
+ <BreadcrumbLink
+ href={`${import.meta.env.BASE_URL}/topics/${topicToSlug(topic)}`}
+ title={getTopicDescription(topic)}
+ >
+ {topic}
+ </BreadcrumbLink>
+ ) : (
+ topic
+ )}
+ {index < topics.length - 1 && ','}
+ </span>
+ ))}
+ </BreadcrumbItem>
+ </>
)
- )}
- </div>
- )
- }
- <slot />
- {
- github_url && (
- <p>
- <a href={github_url} target="_blank" rel="noreferrer" class="inline-flex items-center gap-1.5">
- <GithubIcon size={16} /> Go to the GitHub discussion
- </a>
- </p>
- )
- }
- {
- viewGitHubLink && (
- <footer class="mt-16 not-prose">
- <a
- href={viewGitHubLink}
- target="_blank"
- rel="noreferrer noopener edit"
- class="w-fit inline-flex items-center gap-1 text-sm text-foreground-light hover:text-foreground"
- >
- View this page on GitHub <ExternalLink size={14} strokeWidth={1.5} />
- </a>
- </footer>
- )
- }
- </article>
+ }
+ </BreadcrumbList>
+ </Breadcrumb>
+ <header class="mb-8">
+ <h1 class="mt-0 mb-0 text-balance">{title}</h1>
+ {description && <p class="not-prose mt-3 text-xl leading-7 text-foreground-light">{description}</p>}
+ </header>
+ <slot />
+ <div class="not-prose mt-12 -ml-5 lg:hidden">
+ <GuideSidebar
+ client:visible
+ items={[]}
+ pageUrl={new URL(pagePath, Astro.site).href}
+ markdownUrl={markdownUrl}
+ className="border-l-0 px-0"
+ />
+ </div>
+ {
+ github_url && (
+ <p>
+ <a href={github_url} target="_blank" rel="noreferrer" class="inline-flex items-center gap-1.5">
+ <GithubIcon size={16} /> Go to the GitHub discussion
+ </a>
+ </p>
+ )
+ }
+ {
+ viewGitHubLink && (
+ <footer class="mt-16 not-prose flex items-center justify-between gap-4">
+ <a
+ href={viewGitHubLink}
+ target="_blank"
+ rel="noreferrer noopener edit"
+ class="w-fit inline-flex items-center gap-1 text-sm text-foreground-light hover:text-foreground"
+ >
+ View this page on GitHub <ExternalLink size={14} strokeWidth={1.5} />
+ </a>
+ {date && <p class="m-0 text-sm text-foreground-lighter">{date}</p>}
+ </footer>
+ )
+ }
+ </article>
+ <aside class="sticky top-(--header-height) hidden justify-self-end max-h-[calc(100vh-var(--header-height))] w-60 self-start overflow-y-auto py-16 lg:block">
+ <GuideSidebar
+ client:load
+ items={toc}
+ pageUrl={new URL(pagePath, Astro.site).href}
+ markdownUrl={markdownUrl}
+ />
+ </aside>
+ </div>
+ {
+ related && (
+ <FeaturedSection
+ client:load
+ title={`More ${related.topic} guides`}
+ items={related.guides.map((guide) => ({ ...guide, slot: guide.id }))}
+ className="pb-24 pt-16"
+ />
+ )
+ }
</Layout>
diff --git a/apps/kb/src/layouts/Layout.astro b/apps/kb/src/layouts/Layout.astro
index 0140669e673..0e72af6fd3b 100644
--- a/apps/kb/src/layouts/Layout.astro
+++ b/apps/kb/src/layouts/Layout.astro
@@ -1,17 +1,25 @@
---
+import { getCollection } from 'astro:content'
import { genFaviconLinks } from 'common/MetaFavicons/icons'
import Footer from '../components/Footer.astro'
import { Header } from '../components/Header'
+import { toSummary, toTroubleshootingSummary } from '../lib/guides'
+import { getListedTopics } from '../lib/topics'
import '../styles/globals.css'
import { serializeJsonLd } from '../lib/json-ld'
interface Props {
- title: string
+ title?: string
description?: string
jsonLd?: Record<string, unknown> | Record<string, unknown>[]
}
const { title, description, jsonLd } = Astro.props
+// the nav lists only topics with entries
+const navTopics = getListedTopics({
+ guides: (await getCollection('guides')).map(toSummary),
+ troubleshooting: (await getCollection('troubleshooting')).map(toTroubleshootingSummary),
+}).map((topic) => topic.name)
const faviconRoute = import.meta.env.DEV ? '/favicon/local' : '/favicon'
---
@@ -24,13 +32,19 @@ const faviconRoute = import.meta.env.DEV ? '/favicon/local' : '/favicon'
{description && <meta name="description" content={description} />}
<script is:inline>
// Set data-theme on <html> before first paint, so the page doesn't flash
- // the wrong theme while this loads. Defaults to dark (no system-preference
- // check — the toggle in components/ThemeToggle.tsx is light/dark only).
+ // the wrong theme while this loads. Defaults to dark, and "system" follows the
+ // OS preference, including changes mid-session (choices come from components/HeaderMenu.tsx).
;(function () {
- try {
- var stored = localStorage.getItem('theme')
- document.documentElement.setAttribute('data-theme', stored === 'light' ? 'light' : 'dark')
- } catch (_) {}
+ var systemDark = window.matchMedia('(prefers-color-scheme: dark)')
+ var applyTheme = function () {
+ try {
+ var stored = localStorage.getItem('theme')
+ var theme = stored === 'system' ? (systemDark.matches ? 'dark' : 'light') : stored === 'light' ? 'light' : 'dark'
+ document.documentElement.setAttribute('data-theme', theme)
+ } catch (_) {}
+ }
+ applyTheme()
+ systemDark.addEventListener('change', applyTheme)
})()
</script>
{genFaviconLinks(import.meta.env.BASE_URL, faviconRoute).map((link) => <link {...link} />)}
@@ -45,12 +59,14 @@ const faviconRoute = import.meta.env.DEV ? '/favicon/local' : '/favicon'
href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=Manrope:wght@400;500;600;700;800&display=swap"
/>
<link rel="sitemap" href={`${import.meta.env.BASE_URL}/sitemap-index.xml`} />
- <title>{title} | Supabase Knowledge Base</title>
+ <title>{title ? `${title} | Supabase Knowledge Base` : 'Supabase Knowledge Base'}</title>
{jsonLd && <script type="application/ld+json" is:inline set:html={serializeJsonLd(jsonLd)} />}
</head>
- <body>
- <Header client:load />
- <main>
+ <body class="flex min-h-dvh flex-col">
+ <div class="sticky top-0 z-40">
+ <Header client:load topics={navTopics} />
+ </div>
+ <main class="grow">
<slot />
</main>
<Footer />
@@ -61,10 +77,12 @@ const faviconRoute = import.meta.env.DEV ? '/favicon/local' : '/favicon'
:root {
--header-height: 50px;
+ --nav-inset: 10rem;
}
html {
scroll-behavior: smooth;
+ scroll-padding-top: var(--header-height);
font-weight: 500;
}
@@ -75,7 +93,8 @@ html[data-theme*='dark'] {
body {
margin: 0;
width: 100%;
- height: 100%;
+ min-height: 100%;
+ overscroll-behavior-y: none;
}
body {
diff --git a/apps/kb/src/lib/ascii/field.ts b/apps/kb/src/lib/ascii/field.ts
new file mode 100644
index 00000000000..e04f5b94eae
--- /dev/null
+++ b/apps/kb/src/lib/ascii/field.ts
@@ -0,0 +1,219 @@
+export interface Lattice {
+ xs: number[]
+ ys: number[]
+}
+
+export interface PixelRect {
+ left: number
+ top: number
+ right: number
+ bottom: number
+}
+
+interface CellRange {
+ c0: number
+ c1: number
+ r0: number
+ r1: number
+}
+
+interface CellRangeParams {
+ lattice: Lattice
+ rect: PixelRect
+ margin: number
+}
+
+interface BuildMaskParams {
+ lattice: Lattice
+ rects: PixelRect[]
+ margin?: number
+}
+
+interface AlignedEdgesParams {
+ size: number
+ start: number
+ end: number
+ target: number
+}
+
+interface GlyphRunParams {
+ density: number
+ capacity: number
+ rand: () => number
+}
+
+interface HeroFieldParams {
+ lattice: Lattice
+ seed: number
+}
+
+interface PhaseParams {
+ t: number
+ start: number
+ length: number
+}
+
+interface BeamParams {
+ col: number
+ row: number
+ now?: number
+}
+
+export const RAMP = [' ', '·', '░', '▒', '▓'] as const
+export const BLOCK_GLYPHS = ['▓', '▒', '░'] as const
+
+export const CELL_WIDTH = 120
+export const CELL_HEIGHT = 26
+export const GLYPH_PITCH = 12
+
+const ENERGY_EPSILON = 0.01
+const MIN_COLUMN = 60
+export const BEAM_ALPHA = 0.7
+
+export const hash = (a: number, b: number) => {
+ const n = Math.sin(a * 127.1 + b * 311.7) * 43758.5453
+ return n - Math.floor(n)
+}
+
+export const rampGlyph = (density: number) =>
+ RAMP[Math.min(RAMP.length - 1, Math.floor(density * RAMP.length))]
+
+export const isBeamAt = ({ col, row, now = 0 }: BeamParams) =>
+ hash(col + row * 31, Math.floor(now / 600 + hash(row, col))) < 0.04
+
+export const createRng = (seed: number): (() => number) => {
+ let state = seed >>> 0
+ return () => {
+ state = (state + 0x6d2b79f5) >>> 0
+ const mixed = Math.imul(state ^ (state >>> 15), state | 1)
+ const remixed = mixed ^ (mixed + Math.imul(mixed ^ (mixed >>> 7), mixed | 61))
+ return ((remixed ^ (remixed >>> 14)) >>> 0) / 4294967296
+ }
+}
+
+export const uniformEdges = ({ size, step }: { size: number; step: number }): number[] =>
+ Array.from({ length: Math.ceil(Math.max(0, size) / step) + 1 }, (_, i) => i * step)
+
+const roundEdge = (value: number) => Math.round(value * 100) / 100
+
+export const alignedEdges = ({ size, start, end, target }: AlignedEdgesParams): number[] => {
+ const span = end - start
+ if (size <= 0 || span <= 0) return uniformEdges({ size, step: target })
+ const count = Math.max(1, Math.round(span / target))
+ const step = span / count
+ const inner = Array.from({ length: count + 1 }, (_, i) => roundEdge(start + i * step))
+
+ if (inner[0] < MIN_COLUMN) inner.shift()
+ if (size - inner[inner.length - 1] < MIN_COLUMN) inner.pop()
+ return [0, ...inner, size]
+}
+
+export const fitEdges = ({ size, target }: { size: number; target: number }): number[] => {
+ const count = size > 0 ? Math.max(1, Math.round(size / target)) : 0
+ return Array.from({ length: count + 1 }, (_, i) => roundEdge((i * size) / count || 0))
+}
+
+export const latticeSize = ({ xs, ys }: Lattice) => ({
+ cols: Math.max(0, xs.length - 1),
+ rows: Math.max(0, ys.length - 1),
+})
+
+export const clamp = (value: number, min: number, max: number) =>
+ Math.min(max, Math.max(min, value))
+
+export const phase = ({ t, start, length }: PhaseParams) => clamp((t - start) / length, 0, 1)
+
+export const drawStep = (progress: number) => Math.floor(progress * 8) / 8
+
+const firstIndexAtOrBefore = (edges: number[], value: number) => {
+ let index = 0
+ while (index < edges.length - 2 && edges[index + 1] <= value) index++
+ return index
+}
+
+const lastIndexAtOrAfter = (edges: number[], value: number) => {
+ let index = edges.length - 2
+ while (index > 0 && edges[index] >= value) index--
+ return index
+}
+
+export const cellRange = ({ lattice, rect, margin }: CellRangeParams): CellRange | null => {
+ const { xs, ys } = lattice
+ const { cols, rows } = latticeSize(lattice)
+ if (cols === 0 || rows === 0) return null
+ if (rect.right <= rect.left || rect.bottom <= rect.top) return null
+ if (
+ rect.right <= xs[0] ||
+ rect.left >= xs[cols] ||
+ rect.bottom <= ys[0] ||
+ rect.top >= ys[rows]
+ ) {
+ return null
+ }
+
+ return {
+ c0: clamp(firstIndexAtOrBefore(xs, rect.left) - margin, 0, cols - 1),
+ c1: clamp(lastIndexAtOrAfter(xs, rect.right) + margin, 0, cols - 1),
+ r0: clamp(firstIndexAtOrBefore(ys, rect.top) - margin, 0, rows - 1),
+ r1: clamp(lastIndexAtOrAfter(ys, rect.bottom) + margin, 0, rows - 1),
+ }
+}
+
+export const snapRect = ({ lattice, rect, margin }: CellRangeParams): PixelRect | null => {
+ const range = cellRange({ lattice, rect, margin })
+ if (!range) return null
+ return {
+ left: lattice.xs[range.c0],
+ top: lattice.ys[range.r0],
+ right: lattice.xs[range.c1 + 1],
+ bottom: lattice.ys[range.r1 + 1],
+ }
+}
+
+export const buildMask = ({ lattice, rects, margin = 1 }: BuildMaskParams): Uint8Array => {
+ const { cols, rows } = latticeSize(lattice)
+ const mask = new Uint8Array(cols * rows)
+ for (const rect of rects) {
+ const range = cellRange({ lattice, rect, margin })
+ if (!range) continue
+ for (let r = range.r0; r <= range.r1; r++) {
+ for (let c = range.c0; c <= range.c1; c++) mask[r * cols + c] = 1
+ }
+ }
+ return mask
+}
+
+export const glyphRun = ({ density, capacity, rand }: GlyphRunParams): string => {
+ if (density <= 0 || capacity <= 0) return ''
+ const length = clamp(Math.round(capacity * density), 1, capacity)
+ return Array.from(
+ { length },
+ () =>
+ RAMP[Math.ceil(clamp(density + (rand() - 0.5) * 0.3, ENERGY_EPSILON, 1) * (RAMP.length - 1))]
+ ).join('')
+}
+
+export const decayEnergy = ({ energy, factor }: { energy: Float32Array; factor: number }) => {
+ let isHot = false
+ for (let i = 0; i < energy.length; i++) {
+ if (energy[i] === 0) continue
+ energy[i] = energy[i] * factor < ENERGY_EPSILON ? 0 : energy[i] * factor
+ if (energy[i] > 0) isHot = true
+ }
+ return isHot
+}
+
+export const heroField = ({ lattice, seed }: HeroFieldParams): Float32Array => {
+ const { cols, rows } = latticeSize(lattice)
+ const rand = createRng(seed)
+ const field = new Float32Array(cols * rows)
+ for (let c = 0; c < cols; c++) {
+ const level = rand()
+ const fillChance = (0.1 + 0.5 * level) / 10
+ for (let r = 0; r < rows; r++) {
+ if (rand() > fillChance) continue
+ field[r * cols + c] = clamp(level * 0.7 + rand() * 0.3, 0.1, 1)
+ }
+ }
+ return field
+}
diff --git a/apps/kb/src/lib/ascii/fluid.ts b/apps/kb/src/lib/ascii/fluid.ts
new file mode 100644
index 00000000000..213a9fa0d97
--- /dev/null
+++ b/apps/kb/src/lib/ascii/fluid.ts
@@ -0,0 +1,50 @@
+import type { IsoPoint } from '../iso-shapes'
+import { BEAM_ALPHA, hash, isBeamAt, rampGlyph } from './field'
+import { tracePolygon } from './layer'
+
+interface DrawFluidParams {
+ ctx: CanvasRenderingContext2D
+ area: IsoPoint[]
+ level: number
+ now: number
+ color: string
+ beam: string
+ flow: 'up' | 'down'
+}
+
+const FLUID_COLUMN = 8
+const FLUID_ROW = 10
+export const FLUID_RISE_MS = 200
+
+export const drawFluid = ({ ctx, area, level, now, color, beam, flow }: DrawFluidParams) => {
+ if (level <= 0) return
+ const ys = area.map(([, y]) => y)
+ const xs = area.map(([x]) => x)
+ const left = Math.min(...xs)
+ const right = Math.max(...xs)
+ const edge = flow === 'down' ? Math.min(...ys) : Math.max(...ys)
+ const step = flow === 'down' ? FLUID_ROW : -FLUID_ROW
+ const reach = (Math.max(...ys) - Math.min(...ys)) * level
+ const drift = Math.floor(now / FLUID_RISE_MS)
+ ctx.save()
+ tracePolygon(ctx, area)
+ ctx.clip()
+ ctx.font = '12px ui-monospace, SFMono-Regular, Menlo, monospace'
+ ctx.textAlign = 'center'
+ ctx.textBaseline = 'middle'
+ for (let row = 0; row * FLUID_ROW < reach; row++) {
+ const y = edge + row * step
+ const depth = 1 - (row * FLUID_ROW) / Math.max(1, reach)
+ for (let col = 0; left + col * FLUID_COLUMN < right; col++) {
+ const cell = row - drift
+ const density = hash(col, cell) * (0.35 + 0.65 * depth)
+ const glyph = rampGlyph(density)
+ if (glyph === ' ') continue
+ const isBeam = isBeamAt({ col, row: cell, now })
+ ctx.fillStyle = isBeam ? beam : color
+ ctx.globalAlpha = isBeam ? BEAM_ALPHA : 1
+ ctx.fillText(glyph, left + col * FLUID_COLUMN, y)
+ }
+ }
+ ctx.restore()
+}
diff --git a/apps/kb/src/lib/ascii/grain.ts b/apps/kb/src/lib/ascii/grain.ts
new file mode 100644
index 00000000000..210a0c2f656
--- /dev/null
+++ b/apps/kb/src/lib/ascii/grain.ts
@@ -0,0 +1,32 @@
+import grainImage from '../../assets/grain.webp'
+
+interface PunchGrainParams {
+ ctx: CanvasRenderingContext2D
+ pattern: CanvasPattern
+ width: number
+ height: number
+}
+
+let grain: Promise<HTMLImageElement | null> | undefined
+
+export const loadGrain = async (ctx: CanvasRenderingContext2D): Promise<CanvasPattern | null> => {
+ if (!grain) {
+ const image = new Image()
+ image.src = grainImage.src
+ grain = image.decode().then(
+ () => image,
+ () => null
+ )
+ }
+ const image = await grain
+ return image ? ctx.createPattern(image, 'repeat') : null
+}
+
+export const punchGrain = ({ ctx, pattern, width, height }: PunchGrainParams) => {
+ ctx.save()
+ ctx.globalCompositeOperation = 'destination-in'
+ ctx.globalAlpha = 1
+ ctx.fillStyle = pattern
+ ctx.fillRect(0, 0, width, height)
+ ctx.restore()
+}
diff --git a/apps/kb/src/lib/ascii/infall.ts b/apps/kb/src/lib/ascii/infall.ts
new file mode 100644
index 00000000000..27a4c254e28
--- /dev/null
+++ b/apps/kb/src/lib/ascii/infall.ts
@@ -0,0 +1,217 @@
+import { hash, phase, RAMP } from './field'
+import { invertWarp, projectWarp, tangentAngle, type WarpPoint, type WarpShape } from './warp'
+
+interface InfallGlyph {
+ root: HTMLElement
+ char: HTMLElement
+ glyph: HTMLElement
+ rest: WarpPoint
+ delay: number
+}
+
+interface MeasureInfallParams {
+ container: HTMLElement
+ origin: DOMRect
+ throat: WarpPoint
+}
+
+interface PaintSettleParams {
+ glyphs: InfallGlyph[]
+ at: number
+}
+
+interface CreateInfallParams {
+ getAnchor: () => HTMLElement | null
+}
+
+interface InfallMeasureParams {
+ origin: DOMRect
+ throat: WarpPoint
+}
+
+interface InfallFrameParams {
+ shape: WarpShape
+ flatten: number
+ lineY: number
+ progress: number
+}
+
+interface Infall {
+ getLift: () => number
+ measure: (params: InfallMeasureParams) => void
+ advance: (dt: number) => void
+ paint: (params: InfallFrameParams) => boolean
+}
+
+interface PaintInfallParams {
+ throat: WarpPoint
+ glyphs: InfallGlyph[]
+ shape: WarpShape
+ flatten: number
+ lineY: number
+ progress: number
+}
+
+const measureInfall = ({ container, origin, throat }: MeasureInfallParams): InfallGlyph[] => {
+ const roots = [...container.querySelectorAll<HTMLElement>('[data-infall]')]
+ // the rest position must not include the transform of the last frame
+ for (const root of roots) root.style.transform = ''
+ const glyphs = roots.flatMap((root) => {
+ const [char, glyph] = root.children
+ if (!(char instanceof HTMLElement) || !(glyph instanceof HTMLElement)) return []
+ const rect = root.getBoundingClientRect()
+ const rest = {
+ x: (rect.left + rect.right) / 2 - origin.left,
+ y: (rect.top + rect.bottom) / 2 - origin.top,
+ }
+ return [{ root, char, glyph, rest, delay: 0 }]
+ })
+ const farthest = Math.max(
+ 1,
+ ...glyphs.map(({ rest }) => Math.hypot(rest.x - throat.x, rest.y - throat.y))
+ )
+ // glyphs near the throat go first, so the line of text bends into the warp
+ return glyphs.map((glyph, index) => ({
+ ...glyph,
+ delay:
+ (0.1 * Math.hypot(glyph.rest.x - throat.x, glyph.rest.y - throat.y)) / farthest +
+ 0.03 * hash(index, 7),
+ }))
+}
+
+const paintInfall = ({
+ glyphs,
+ throat,
+ shape,
+ flatten,
+ lineY,
+ progress,
+}: PaintInfallParams): number => {
+ let remaining = 0
+ for (const { root, char, glyph, rest, delay } of glyphs) {
+ const fall = phase({ t: progress, start: delay, length: 0.2 })
+ // the rings end at the throat rim, so the last stretch drops the glyph into the hole
+ const drop = phase({ t: fall, start: 0.65, length: 0.35 })
+ remaining += (1 - drop) / glyphs.length
+ const morph = phase({ t: fall, start: 0.7, length: 0.12 })
+ char.style.opacity = `${1 - morph}`
+ glyph.style.opacity = `${morph}`
+ const nextGlyph = RAMP[Math.max(1, 3 - Math.floor(drop * 3))]
+ if (glyph.textContent !== nextGlyph) glyph.textContent = nextGlyph
+ if (fall === 0) {
+ root.style.transform = ''
+ root.style.filter = ''
+ root.style.opacity = ''
+ continue
+ }
+
+ const eased = fall * fall
+ const start = invertWarp({
+ shape,
+ x: rest.x,
+ y: lineY + (rest.y - lineY) / (1 - flatten),
+ })
+ // the angle stays fixed, so each glyph slides down its own spoke and both sides bend in
+ const r = shape.r0 + (start.r - shape.r0) * (1 - eased)
+ const from = projectWarp({ shape, ...start, flatten, lineY })
+ const rim = projectWarp({ shape, r, angle: start.angle, flatten, lineY })
+ const to = { x: rim.x + (throat.x - rim.x) * drop, y: rim.y + (throat.y - rim.y) * drop }
+ const turn = tangentAngle({ shape, r, angle: start.angle }) - tangentAngle({ shape, ...start })
+ const shrink = (1 - 0.5 * eased) * (1 - drop)
+ root.style.transform = [
+ `translate(${to.x - from.x}px, ${to.y - from.y}px)`,
+ `rotate(${turn}rad)`,
+ `scale(${shrink * (1 + 1.2 * eased)}, ${shrink * (1 - 0.5 * eased)})`,
+ ].join(' ')
+ root.style.filter = `blur(${eased + 2 * drop}px)`
+ root.style.opacity = `${1 - phase({ t: drop, start: 0.5, length: 0.5 })}`
+ }
+ return remaining
+}
+
+const paintSettle = ({ glyphs, at }: PaintSettleParams) => {
+ for (const { root, char, glyph, delay } of glyphs) {
+ const settled = 1 - (1 - phase({ t: at, start: delay * 2, length: 0.6 })) ** 3
+ char.style.opacity = '1'
+ glyph.style.opacity = '0'
+ root.style.opacity = `${settled}`
+ root.style.transform = settled < 1 ? `translateY(${(1 - settled) * 6}px)` : ''
+ root.style.filter = settled < 1 ? `blur(${(1 - settled) * 3}px)` : ''
+ }
+}
+
+export const createInfall = ({ getAnchor }: CreateInfallParams): Infall => {
+ let glyphs: InfallGlyph[] = []
+ let frameKey = ''
+ let isConsumed = false
+ let lift = 0
+ let fallAt = 0
+ let fallTarget = 0
+ let settleAt = 1
+ const getSearch = () => getAnchor()?.querySelector<HTMLElement>('[data-warp-throat]') ?? null
+
+ return {
+ // a risen search must not move the throat, so the canvas adds the lift back when it measures
+ getLift: () => (isConsumed ? lift : 0),
+ measure: ({ origin, throat }) => {
+ const anchor = getAnchor()
+ glyphs = anchor ? measureInfall({ container: anchor, origin, throat }) : []
+ const copy = [...(anchor?.children ?? [])]
+ .filter((child) => !child.matches('[data-warp-throat]'))
+ .map((child) => child.getBoundingClientRect())
+ // the search rises 60% of the way to the copy's center
+ lift =
+ getSearch() && copy.length > 0
+ ? 0.6 *
+ (throat.y -
+ (Math.min(...copy.map((rect) => rect.top)) +
+ Math.max(...copy.map((rect) => rect.bottom))) /
+ 2 +
+ origin.top)
+ : 0
+ frameKey = ''
+ },
+ advance: (dt) => {
+ if (fallTarget === 1 && fallAt < 1) fallAt = Math.min(1, fallAt + dt)
+ if (settleAt < 1) settleAt = Math.min(1, settleAt + dt / 0.6)
+ },
+ // true on the frame the last glyph goes in
+ paint: ({ shape, flatten, lineY, progress }) => {
+ // two thresholds, so a scroll that stops near one does not start and stop the infall
+ if (progress > 0.03) {
+ fallTarget = 1
+ settleAt = 1
+ } else if (progress < 0.01 && fallTarget === 1) {
+ fallTarget = 0
+ fallAt = 0
+ settleAt = 0
+ }
+ // frames repeat while the page is still, so the glyph styles change only when they move
+ if (frameKey === `${fallAt}:${settleAt}:${progress}`) return false
+ frameKey = `${fallAt}:${settleAt}:${progress}`
+ if (settleAt < 1) paintSettle({ glyphs, at: settleAt })
+ const remaining =
+ settleAt < 1
+ ? 1
+ : paintInfall({
+ glyphs,
+ throat: { x: shape.cx, y: lineY + (shape.throatY - lineY) * (1 - flatten) },
+ shape,
+ flatten,
+ lineY,
+ // the glyph timeline ends near 0.34, so the clock maps onto it
+ progress: fallAt * 0.34,
+ })
+ const isGone = glyphs.length > 0 && remaining === 0
+ if (isGone !== isConsumed) {
+ getSearch()?.animate(
+ { translate: isGone ? `0 ${-lift}px` : '0 0' },
+ { duration: 700, easing: 'cubic-bezier(0.23, 1, 0.32, 1)', fill: 'forwards' }
+ )
+ }
+ const isJustConsumed = isGone && !isConsumed
+ isConsumed = isGone
+ return isJustConsumed
+ },
+ }
+}
diff --git a/apps/kb/src/lib/ascii/layer.ts b/apps/kb/src/lib/ascii/layer.ts
new file mode 100644
index 00000000000..1549a4c6794
--- /dev/null
+++ b/apps/kb/src/lib/ascii/layer.ts
@@ -0,0 +1,34 @@
+import type { IsoPoint } from '../iso-shapes'
+
+interface CanvasLayer {
+ canvas: HTMLCanvasElement
+ ctx: CanvasRenderingContext2D
+}
+
+interface SizeLayersParams {
+ contexts: CanvasRenderingContext2D[]
+ width: number
+ height: number
+}
+
+export const createLayer = (): CanvasLayer | null => {
+ const canvas = document.createElement('canvas')
+ const ctx = canvas.getContext('2d')
+ return ctx ? { canvas, ctx } : null
+}
+
+// each layer gets device pixels, while drawing stays in css pixels
+export const sizeLayers = ({ contexts, width, height }: SizeLayersParams) => {
+ const dpr = window.devicePixelRatio || 1
+ for (const ctx of contexts) {
+ ctx.canvas.width = Math.round(width * dpr)
+ ctx.canvas.height = Math.round(height * dpr)
+ ctx.setTransform(dpr, 0, 0, dpr, 0, 0)
+ }
+}
+
+export const tracePolygon = (ctx: CanvasRenderingContext2D, polygon: IsoPoint[]) => {
+ ctx.beginPath()
+ for (const [x, y] of polygon) ctx.lineTo(x, y)
+ ctx.closePath()
+}
diff --git a/apps/kb/src/lib/ascii/warp.ts b/apps/kb/src/lib/ascii/warp.ts
new file mode 100644
index 00000000000..82f2ff138a6
--- /dev/null
+++ b/apps/kb/src/lib/ascii/warp.ts
@@ -0,0 +1,157 @@
+export interface WarpShape {
+ cx: number
+ rimY: number
+ throatY: number
+ r0: number
+}
+
+export interface WarpPoint {
+ x: number
+ y: number
+}
+
+interface ProjectParams {
+ shape: WarpShape
+ r: number
+ angle: number
+ flatten: number
+ lineY: number
+}
+
+interface IsBehindWallParams {
+ shape: WarpShape
+ radii: number[]
+ r: number
+ angle: number
+}
+
+interface LocateCellParams {
+ shape: WarpShape
+ radii: number[]
+ spokeCount: number
+ x: number
+ y: number
+ flatten: number
+ lineY: number
+}
+
+export interface WarpCell {
+ ring: number
+ spoke: number
+}
+
+interface FrontRadiusParams {
+ shape: WarpShape
+ y: number
+}
+
+interface RingRadiiParams {
+ r0: number
+ maxRadius: number
+}
+
+interface InvertWarpParams {
+ shape: WarpShape
+ x: number
+ y: number
+}
+
+interface TangentAngleParams {
+ shape: WarpShape
+ r: number
+ angle: number
+}
+
+interface WarpPolar {
+ r: number
+ angle: number
+}
+
+const TILT = 0.42
+const THROAT_FLATTENING = 0.6
+
+export const ringRadii = ({ r0, maxRadius }: RingRadiiParams): number[] => {
+ const radii: number[] = []
+ for (let i = 0; ; i++) {
+ const r = r0 * (1 + 0.1 * i + 0.012 * i * i)
+ radii.push(r)
+ if (r > maxRadius) return radii
+ }
+}
+
+const ringEllipse = ({ rimY, throatY, r0 }: WarpShape, r: number) => ({
+ centerY: rimY + (throatY - rimY) * (r0 / r),
+ ry: TILT * (r - THROAT_FLATTENING * r0),
+})
+
+export const frontRadius = ({ shape: { rimY, throatY, r0 }, y }: FrontRadiusParams): number => {
+ const b = rimY - TILT * THROAT_FLATTENING * r0 - y
+ return (-b + Math.sqrt(b * b - 4 * TILT * (throatY - rimY) * r0)) / (2 * TILT)
+}
+
+export const projectWarp = ({ shape, r, angle, flatten, lineY }: ProjectParams): WarpPoint => {
+ const { centerY, ry } = ringEllipse(shape, r)
+ const y = centerY + ry * Math.sin(angle)
+ return { x: shape.cx + r * Math.cos(angle), y: lineY + (y - lineY) * (1 - flatten) }
+}
+
+export const isBehindWall = ({ shape, radii, r, angle }: IsBehindWallParams): boolean => {
+ if (Math.sin(angle) <= 0) return false
+ const { x, y } = projectWarp({ shape, r, angle, flatten: 0, lineY: 0 })
+ const dx = x - shape.cx
+ return radii.some((inner) => {
+ if (inner >= r || Math.abs(dx) >= inner) return false
+ const { centerY, ry } = ringEllipse(shape, inner)
+ return centerY + ry * Math.sqrt(1 - (dx / inner) ** 2) > y + 0.5
+ })
+}
+
+export const locateCell = ({
+ shape,
+ radii,
+ spokeCount,
+ x,
+ y,
+ flatten,
+ lineY,
+}: LocateCellParams): WarpCell | null => {
+ if (flatten >= 1) return null
+ const unflattenedY = lineY + (y - lineY) / (1 - flatten)
+ const dx = x - shape.cx
+ const outer = radii.findIndex((r) => {
+ const { centerY, ry } = ringEllipse(shape, r)
+ return (dx / r) ** 2 + ((unflattenedY - centerY) / ry) ** 2 <= 1
+ })
+ if (outer <= 0) return null
+ const { centerY, ry } = ringEllipse(shape, radii[outer])
+ const angle = Math.atan2((unflattenedY - centerY) / ry, dx / radii[outer])
+ const turn = (angle + Math.PI * 2) % (Math.PI * 2)
+ return { ring: outer - 1, spoke: Math.floor((turn / (Math.PI * 2)) * spokeCount) % spokeCount }
+}
+
+// bisects for the ring that passes through the point. points inside the throat stay on the throat ring
+export const invertWarp = ({ shape, x, y }: InvertWarpParams): WarpPolar => {
+ const dx = x - shape.cx
+ const isOutside = (r: number) => {
+ const { centerY, ry } = ringEllipse(shape, r)
+ return (dx / r) ** 2 + ((y - centerY) / ry) ** 2 > 1
+ }
+ let inner = shape.r0
+ let outer = isOutside(inner) ? shape.r0 * 64 : inner
+ while (outer - inner > 0.01) {
+ const mid = (inner + outer) / 2
+ if (isOutside(mid)) inner = mid
+ else outer = mid
+ }
+ const { centerY, ry } = ringEllipse(shape, outer)
+ return { r: outer, angle: Math.atan2((y - centerY) / ry, dx / outer) }
+}
+
+export const tangentAngle = ({ shape, r, angle }: TangentAngleParams): number => {
+ const { ry } = ringEllipse(shape, r)
+ return Math.atan2(ry * Math.cos(angle), -r * Math.sin(angle))
+}
+
+export const easeInOutCubic = (t: number) => (t < 0.5 ? 4 * t * t * t : 1 - (-2 * t + 2) ** 3 / 2)
+
+export const easeOutCubic = (t: number) => 1 - (1 - t) ** 3
diff --git a/apps/kb/src/lib/cover-compositions.ts b/apps/kb/src/lib/cover-compositions.ts
new file mode 100644
index 00000000000..8f432a35ccf
--- /dev/null
+++ b/apps/kb/src/lib/cover-compositions.ts
@@ -0,0 +1,164 @@
+import { cube, type IsoBox, type IsoRing, type IsoView } from './iso-shapes'
+import type { Topic } from './topics'
+
+interface IsoComposition {
+ boxes: IsoBox[]
+ titleAt: 'top' | 'bottom'
+ view?: IsoView
+ rings?: IsoRing[]
+ fillBoxes?: IsoBox[]
+ nudgeY?: number
+ zoom?: number
+}
+
+const LOCK_BODY: IsoBox = { x: 0, y: 0, z: 0, w: 0.8, d: 1.8, h: 1.3, inset: 'front' }
+
+const DATABASE_DISKS: IsoBox[] = [0, 0.5, 1.026].map((z) => ({
+ x: 0,
+ y: 0,
+ z,
+ w: 2,
+ d: 2,
+ h: 0.38,
+ shape: 'cylinder',
+}))
+
+const REALTIME_SCREEN: IsoBox = { ...cube(0, 0, 0, 2), inset: 'front' }
+
+const EDGE_NODES: IsoBox[] = [
+ { ...cube(2.35, 0.2, 0, 0.4), fillFace: 'left' },
+ { ...cube(0.2, 2.35, 0, 0.4), fillFace: 'right' },
+ { ...cube(-1.75, 0.4, 0, 0.4), fillFace: 'right' },
+ { ...cube(0.4, -1.75, 0, 0.4), fillFace: 'left' },
+]
+
+const QUEUE_CUBES: IsoBox[] = [0, 1, 2, 3, 4].map((i) => ({
+ ...cube(i * 0.95, 0, 0, 0.7),
+ fillFace: 'right',
+}))
+
+const MIGRATION_SOURCE: IsoBox = { ...cube(0, 0, 0, 1), fillFace: 'right', fillFlow: 'down' }
+const MIGRATION_TARGET: IsoBox = { ...cube(2.3, -2.3, 0, 1), fillFace: 'left' }
+
+const COMPARISON_TALL: IsoBox = { ...cube(0, 0, 0, 0.9), h: 2.2, fillFace: 'right' }
+
+const RUNDOWN_BARS: IsoBox[] = [1.6, 2.2, 1, 1.8].map((h, i) => ({
+ ...cube(i * 1.1, 0, 0, 0.8),
+ h,
+ fillFace: 'right',
+}))
+
+const TROUBLESHOOTING_SLABS: IsoBox[] = [
+ cube(-0.1, 0.1, 0, 1),
+ cube(0.274, -0.174, 0.8, 1.14),
+ cube(-0.1, 0.1, 1.6, 1),
+].map((slab) => ({ ...slab, h: 0.8, fillFace: 'top' }))
+
+const TUTORIAL_STEPS: IsoBox[][] = [0, 1, 2, 3].map((step) =>
+ Array.from({ length: step + 1 }, (_, i) => ({
+ x: step,
+ y: 0,
+ z: i * 0.56,
+ w: 0.88,
+ d: 0.88,
+ h: 0.5,
+ fillFace: 'top',
+ }))
+)
+
+const PLATFORM_LAYERS: IsoBox[] = [0, 1, 2].map((i) => ({
+ x: 0,
+ y: 0,
+ z: i * 0.55,
+ w: 2.2,
+ d: 2.2,
+ h: 0.18,
+ fillFace: 'top',
+}))
+
+export const ISO_COMPOSITIONS: Record<Topic, IsoComposition> = {
+ Auth: {
+ titleAt: 'bottom',
+ boxes: [
+ LOCK_BODY,
+ { x: 0.3, y: 0.3, z: 1.3, w: 0.2, d: 0.2, h: 0.6 },
+ { x: 0.3, y: 1.3, z: 1.3, w: 0.2, d: 0.2, h: 0.6 },
+ { x: 0.3, y: 0.3, z: 1.9, w: 0.2, d: 1.2, h: 0.2 },
+ ],
+ fillBoxes: [LOCK_BODY],
+ },
+ Database: {
+ titleAt: 'top',
+ view: 'front',
+ boxes: DATABASE_DISKS,
+ fillBoxes: DATABASE_DISKS.slice(0, 2),
+ nudgeY: -4,
+ zoom: 0.805,
+ },
+ Realtime: {
+ titleAt: 'top',
+ boxes: [REALTIME_SCREEN, { ...cube(2.3, 1.2, 0, 0.7), alsoLifts: [REALTIME_SCREEN] }],
+ fillBoxes: [REALTIME_SCREEN],
+ zoom: 0.88,
+ },
+ Storage: {
+ titleAt: 'top',
+ boxes: [
+ [0.048, -0.048],
+ [0, 1.35],
+ [-0.012, 2.712],
+ ].map(([x, y]) => ({ ...cube(x, y, 0, 1.1), h: 0.8, inset: 'top' })),
+ },
+ 'Edge Functions': {
+ titleAt: 'top',
+ boxes: [cube(0.112, 0.088, 0, 1.34), ...EDGE_NODES],
+ fillBoxes: EDGE_NODES,
+ nudgeY: 7,
+ },
+ Queues: {
+ titleAt: 'top',
+ boxes: QUEUE_CUBES,
+ fillBoxes: QUEUE_CUBES.slice(0, -1),
+ },
+ Migration: {
+ titleAt: 'top',
+ boxes: [MIGRATION_SOURCE, MIGRATION_TARGET],
+ fillBoxes: [MIGRATION_SOURCE, MIGRATION_TARGET],
+ nudgeY: 13,
+ rings: [
+ { x: 0.5, y: 0.5, z: 0.5, radius: 1.5 },
+ { x: 1.65, y: -0.65, z: 0.5, radius: 1.78, isDashed: true },
+ { x: 2.8, y: -1.8, z: 0.5, radius: 1.5 },
+ ],
+ },
+ Comparison: {
+ titleAt: 'bottom',
+ boxes: [COMPARISON_TALL, { ...cube(1.4, 0, 0, 0.9), h: 1.4 }],
+ fillBoxes: [COMPARISON_TALL],
+ },
+ Rundowns: {
+ titleAt: 'bottom',
+ boxes: RUNDOWN_BARS,
+ fillBoxes: RUNDOWN_BARS.slice(0, -1),
+ },
+ Troubleshooting: {
+ titleAt: 'bottom',
+ boxes: TROUBLESHOOTING_SLABS,
+ fillBoxes: TROUBLESHOOTING_SLABS.slice(1, 2),
+ },
+ Tutorials: {
+ titleAt: 'top',
+ view: 'front',
+ boxes: TUTORIAL_STEPS.flat(),
+ fillBoxes: TUTORIAL_STEPS.flatMap((column) => column.slice(0, -1)),
+ },
+ Platform: {
+ titleAt: 'top',
+ boxes: PLATFORM_LAYERS,
+ fillBoxes: PLATFORM_LAYERS.slice(1, 2),
+ nudgeY: 13,
+ zoom: 0.645,
+ },
+}
+
+export const FALLBACK_COMPOSITION: IsoComposition = { titleAt: 'top', boxes: [cube(0, 0, 0, 1)] }
diff --git a/apps/kb/src/lib/guides.test.ts b/apps/kb/src/lib/guides.test.ts
new file mode 100644
index 00000000000..cf7bc7c93d7
--- /dev/null
+++ b/apps/kb/src/lib/guides.test.ts
@@ -0,0 +1,151 @@
+import { describe, expect, it } from 'vitest'
+
+import {
+ filterGuides,
+ padFeatured,
+ parseTopicParam,
+ relatedGuides,
+ withTopicParam,
+ type GuideSummary,
+} from './guides'
+import { isInTopic, TOPICS, topicToSlug, type Topic } from './topics'
+
+const guide = (id: string, title: string, topics: Topic[]): GuideSummary => ({
+ id,
+ title,
+ description: `${title} description, mentions Postgres replication`,
+ topics,
+ href: `/kb/guides/${id}`,
+})
+
+const GUIDES = [
+ guide('rds', 'Migrate from Amazon RDS to Supabase', ['Migration', 'Database']),
+ guide('auth0', 'Migrate from Auth0 to Supabase Auth', ['Migration', 'Auth']),
+ guide('firebase-auth', 'Migrate from Firebase Auth to Supabase', ['Migration', 'Auth']),
+ guide('firebase-storage', 'Migrate from Firebase Storage to Supabase', ['Migration', 'Storage']),
+ guide('firestore', 'Migrate from Firebase Firestore to Supabase', ['Migration', 'Database']),
+ guide('heroku', 'Migrate from Heroku to Supabase', ['Migration', 'Database']),
+ guide('mysql', 'Migrate from MySQL to Supabase', ['Migration', 'Database']),
+ guide('sample', 'Markdown elements sample', ['Tutorials', 'Database']),
+]
+
+const ids = (guides: GuideSummary[]) => guides.map((g) => g.id)
+
+describe('filterGuides', () => {
+ it('filters by topic', () => {
+ expect(ids(filterGuides({ guides: GUIDES, topic: 'Auth' }))).toEqual(['auth0', 'firebase-auth'])
+ })
+
+ it('returns every guide without a topic', () => {
+ expect(filterGuides({ guides: GUIDES, topic: null })).toBe(GUIDES)
+ })
+})
+
+describe('padFeatured', () => {
+ it('repeats a single featured guide into 3 unique slots', () => {
+ const result = padFeatured({ featured: [GUIDES[7]], fallback: GUIDES })
+ expect(ids(result)).toEqual(['sample', 'sample', 'sample'])
+ expect(new Set(result.map((g) => g.slot)).size).toBe(3)
+ })
+
+ it('cycles two featured guides to fill 3 slots', () => {
+ const result = padFeatured({ featured: GUIDES.slice(0, 2), fallback: GUIDES })
+ expect(ids(result)).toEqual(['rds', 'auth0', 'rds'])
+ expect(new Set(result.map((g) => g.slot)).size).toBe(3)
+ })
+
+ it('keeps the first 3 when more are featured', () => {
+ const result = padFeatured({ featured: GUIDES.slice(0, 4), fallback: GUIDES })
+ expect(ids(result)).toEqual(['rds', 'auth0', 'firebase-auth'])
+ })
+
+ it('falls back to the first guides when nothing is featured', () => {
+ expect(ids(padFeatured({ featured: [], fallback: GUIDES }))).toEqual([
+ 'rds',
+ 'auth0',
+ 'firebase-auth',
+ ])
+ })
+
+ it('returns nothing without any guides', () => {
+ expect(padFeatured({ featured: [], fallback: [] })).toEqual([])
+ })
+})
+
+describe('topic url param', () => {
+ it('parses known slugs', () => {
+ expect(parseTopicParam('edge-functions')).toBe('Edge Functions')
+ expect(parseTopicParam('auth')).toBe('Auth')
+ })
+
+ it('round-trips every topic slug', () => {
+ for (const { name } of TOPICS) expect(parseTopicParam(topicToSlug(name))).toBe(name)
+ })
+
+ it('ignores unknown or missing slugs', () => {
+ expect(parseTopicParam('nope')).toBeNull()
+ expect(parseTopicParam(null)).toBeNull()
+ })
+
+ it('sets and clears the topic while keeping other params', () => {
+ expect(withTopicParam({ search: '?ref=x', topic: 'Edge Functions' })).toBe(
+ '?ref=x&topic=edge-functions'
+ )
+ expect(withTopicParam({ search: '?topic=auth&ref=x', topic: null })).toBe('?ref=x')
+ expect(withTopicParam({ search: '?topic=auth', topic: null })).toBe('')
+ })
+})
+
+describe('relatedGuides', () => {
+ const firebaseAuth = guide('firebase-auth', 'Migrate from Firebase Auth to Supabase', [
+ 'Migration',
+ 'Auth',
+ ])
+
+ it('prefers the subject topic over the format topic', () => {
+ const related = relatedGuides({ guide: firebaseAuth, guides: GUIDES })
+ expect(related?.topic).toBe('Auth')
+ expect(related?.guides.map((guide) => guide.id)).toEqual(['auth0'])
+ })
+
+ it('ranks guides sharing more topics first', () => {
+ const rds = guide('rds', 'Migrate from Amazon RDS to Supabase', ['Migration', 'Database'])
+ expect(relatedGuides({ guide: rds, guides: GUIDES })?.guides.map((guide) => guide.id)).toEqual([
+ 'firestore',
+ 'heroku',
+ 'mysql',
+ ])
+ })
+
+ it('falls back to the format topic when no other guide shares the subject', () => {
+ const storage = guide('firebase-storage', 'Migrate from Firebase Storage to Supabase', [
+ 'Migration',
+ 'Storage',
+ ])
+ expect(relatedGuides({ guide: storage, guides: GUIDES })?.topic).toBe('Migration')
+ })
+
+ it('returns null when no other guide shares a topic', () => {
+ expect(relatedGuides({ guide: firebaseAuth, guides: [firebaseAuth] })).toBeNull()
+ })
+})
+
+describe('isInTopic', () => {
+ it('lists guides under the topics they carry', () => {
+ const topics = ['Migration', 'Database']
+ expect(isInTopic({ collection: 'guides', topics, topic: 'Migration' })).toBe(true)
+ expect(isInTopic({ collection: 'guides', topics, topic: 'Troubleshooting' })).toBe(false)
+ })
+
+ it('lists every troubleshooting entry under Troubleshooting, tagged or not', () => {
+ expect(isInTopic({ collection: 'troubleshooting', topics: [], topic: 'Troubleshooting' })).toBe(
+ true
+ )
+ })
+
+ it('lists troubleshooting under feature topics, never under other type topics', () => {
+ const topics = ['Migration', 'Platform']
+ expect(isInTopic({ collection: 'troubleshooting', topics, topic: 'Platform' })).toBe(true)
+ expect(isInTopic({ collection: 'troubleshooting', topics, topic: 'Migration' })).toBe(false)
+ })
+})
diff --git a/apps/kb/src/lib/guides.ts b/apps/kb/src/lib/guides.ts
new file mode 100644
index 00000000000..aaef63969c2
--- /dev/null
+++ b/apps/kb/src/lib/guides.ts
@@ -0,0 +1,130 @@
+import type { CollectionEntry } from 'astro:content'
+
+import { FORMAT_TOPICS, isKnownTopic, TOPICS, topicToSlug, type Topic } from './topics'
+
+export interface GuideSummary {
+ id: string
+ title: string
+ description: string
+ topics: Topic[]
+ href: string
+ date?: string
+}
+
+export interface FeaturedItem extends GuideSummary {
+ slot: string
+}
+
+interface FilterGuidesParams {
+ guides: GuideSummary[]
+ topic: Topic | null
+}
+
+interface PadFeaturedParams {
+ featured: Omit<FeaturedItem, 'slot'>[]
+ fallback: Omit<FeaturedItem, 'slot'>[]
+ count?: number
+}
+
+interface EmptyStateParams {
+ topic: Topic | null
+}
+
+export interface EmptyState {
+ message: string
+ action: string
+}
+
+interface RelatedGuidesParams {
+ guide: GuideSummary
+ guides: GuideSummary[]
+}
+
+export interface RelatedGuides {
+ topic: Topic
+ guides: GuideSummary[]
+}
+
+export const toSummary = (guide: CollectionEntry<'guides'>): GuideSummary => ({
+ id: guide.id,
+ title: guide.data.title,
+ description: guide.data.description,
+ topics: guide.data.topics,
+ href: `${import.meta.env.BASE_URL}/guides/${guide.id}`,
+ date: guide.data.date,
+})
+
+export const toTroubleshootingSummary = (
+ entry: CollectionEntry<'troubleshooting'>
+): GuideSummary => ({
+ id: entry.id,
+ title: entry.data.title,
+ description: entry.data.description ?? '',
+ // troubleshooting is a content type, so it keeps only product topics
+ topics: entry.data.topics.filter(
+ (topic): topic is Topic => isKnownTopic(topic) && !FORMAT_TOPICS.includes(topic)
+ ),
+ href: `${import.meta.env.BASE_URL}/troubleshooting/${entry.id}`,
+})
+
+export const filterGuides = ({ guides, topic }: FilterGuidesParams): GuideSummary[] =>
+ topic ? guides.filter((guide) => guide.topics.includes(topic)) : guides
+
+export const padFeatured = ({
+ featured,
+ fallback,
+ count = 3,
+}: PadFeaturedParams): FeaturedItem[] => {
+ const source = featured.length > 0 ? featured : fallback
+ if (source.length === 0) return []
+
+ return Array.from({ length: count }, (_, slotIndex) => {
+ const guide = source[slotIndex % source.length]
+ return { ...guide, slot: `${guide.id}-${slotIndex}` }
+ })
+}
+
+export const parseTopicParam = (slug: string | null): Topic | null =>
+ TOPICS.find((topic) => topicToSlug(topic.name) === slug)?.name ?? null
+
+export const withTopicParam = ({
+ search,
+ topic,
+ param = 'topic',
+}: {
+ search: string
+ topic: Topic | null
+ param?: string
+}): string => {
+ const params = new URLSearchParams(search)
+ if (topic) params.set(param, topicToSlug(topic))
+ else params.delete(param)
+ const next = params.toString()
+ return next ? `?${next}` : ''
+}
+
+export const emptyStateFor = ({ topic }: EmptyStateParams): EmptyState => {
+ const topicLabel = topic ? `${topic} ` : ''
+ return {
+ message: `There are no ${topicLabel}guides yet.`,
+ action: 'Show all guides',
+ }
+}
+
+export const relatedGuides = ({ guide, guides }: RelatedGuidesParams): RelatedGuides | null => {
+ const sharedTopics = (other: GuideSummary) =>
+ other.topics.filter((topic) => guide.topics.includes(topic)).length
+ // readers want more on the same subject, not more of the same kind of guide
+ const subjectFirst = guide.topics.toSorted(
+ (a, b) => Number(FORMAT_TOPICS.includes(a)) - Number(FORMAT_TOPICS.includes(b))
+ )
+ for (const topic of subjectFirst) {
+ // hidden topics target crawlers, not readers, so they never name the section
+ if (!TOPICS.find(({ name }) => name === topic)?.visible) continue
+ const others = guides.filter((other) => other.id !== guide.id && other.topics.includes(topic))
+ if (others.length === 0) continue
+ const ranked = others.toSorted((a, b) => sharedTopics(b) - sharedTopics(a))
+ return { topic, guides: ranked.slice(0, 3) }
+ }
+ return null
+}
diff --git a/apps/kb/src/lib/hero-shapes.ts b/apps/kb/src/lib/hero-shapes.ts
new file mode 100644
index 00000000000..c07d88b5f4b
--- /dev/null
+++ b/apps/kb/src/lib/hero-shapes.ts
@@ -0,0 +1,51 @@
+import { cube, type IsoBox, type IsoRing } from './iso-shapes'
+import type { Topic } from './topics'
+
+const SHACKLE_LIFT = 2
+
+export const HERO_SHAPES: Record<Topic, IsoBox[]> = {
+ Auth: [
+ { x: 0, y: 0, z: 0, w: 0.8, d: 1.8, h: 1.3, inset: 'front' },
+ { x: 0.3, y: 0.3, z: SHACKLE_LIFT, w: 0.2, d: 0.2, h: 0.8 },
+ { x: 0.3, y: 1.3, z: SHACKLE_LIFT, w: 0.2, d: 0.2, h: 0.8 },
+ { x: 0.3, y: 0.3, z: SHACKLE_LIFT + 0.8, w: 0.2, d: 1.2, h: 0.2 },
+ ],
+ Database: [0, 0.9, 1.8].map((z) => ({ x: 0, y: 0, z, w: 2, d: 2, h: 0.38, shape: 'cylinder' })),
+ Realtime: [{ ...cube(0, 0, 0, 2), inset: 'front' }, cube(2.9, -0.9, 1.5, 0.7)],
+ Storage: [{ ...cube(0, 0, 0, 1.1), h: 0.8, inset: 'top' }],
+ 'Edge Functions': [
+ cube(0, 0, 0.3, 1.34),
+ cube(3, 0.47, 0.9, 0.4),
+ cube(0.47, 3, 0, 0.4),
+ cube(-2.4, 0.47, 0.6, 0.4),
+ cube(0.47, -2.4, 1.2, 0.4),
+ ],
+ Queues: [0, 1, 2, 3].map((i) => cube(i * 1.35, 0, 0, 0.8)),
+ Migration: [cube(0, 0, 0, 1), cube(2.3, -2.3, 1.2, 1)],
+ Comparison: [
+ { ...cube(0, 0, 0, 0.9), h: 2.4 },
+ { ...cube(1.8, 0, 0, 0.9), h: 1.4 },
+ ],
+ Rundowns: [1.6, 2.2, 1, 1.8].map((h, i) => ({ ...cube(i * 1.3, 0, 0, 0.8), h })),
+ Troubleshooting: [
+ { ...cube(-0.1, 0.1, 0, 1), h: 0.7 },
+ { ...cube(0.45, -0.35, 0.94, 1.105), h: 0.7 },
+ { ...cube(-0.1, 0.1, 1.88, 1), h: 0.7 },
+ ],
+ Tutorials: [0, 1, 2].map((i) => ({ ...cube(0, -i * 1.4, i * 0.85, 1.1), h: 0.6 })),
+ Platform: [0, 1, 2].map((i) => ({ x: 0, y: 0, z: i * 0.9, w: 2.2, d: 2.2, h: 0.18 })),
+}
+
+// a share of the shape's long side added on each edge, so a lone shape does not fill the flank.
+// storage's sides then sit on the grid columns
+export const HERO_PADDING: Partial<Record<Topic, number>> = {
+ Storage: 1 / 6,
+}
+
+export const HERO_RINGS: Partial<Record<Topic, IsoRing[]>> = {
+ Migration: [
+ { x: 0.5, y: 0.5, z: 0.5, radius: 1.5 },
+ { x: 1.65, y: -0.65, z: 1.1, radius: 1.85, isDashed: true },
+ { x: 2.8, y: -1.8, z: 1.7, radius: 1.5 },
+ ],
+}
diff --git a/apps/kb/src/lib/iso-shapes.ts b/apps/kb/src/lib/iso-shapes.ts
new file mode 100644
index 00000000000..30238181468
--- /dev/null
+++ b/apps/kb/src/lib/iso-shapes.ts
@@ -0,0 +1,252 @@
+export type IsoPoint = [number, number]
+
+export interface IsoBox {
+ x: number
+ y: number
+ z: number
+ w: number
+ d: number
+ h: number
+ inset?: 'front' | 'top'
+ fillFace?: IsoFace
+ fillFlow?: 'up' | 'down'
+ // a cylinder fills the box footprint, so keep w equal to d
+ shape?: 'box' | 'cylinder'
+ alsoLifts?: IsoBox[]
+}
+
+export type IsoView = 'iso' | 'front'
+
+type IsoFace = 'right' | 'left' | 'top'
+
+export interface IsoRing {
+ x: number
+ y: number
+ z: number
+ radius: number
+ isDashed?: boolean
+}
+
+interface ProjectedShape extends ProjectedBox {
+ // plan positions of the visible vertical edges, for guides drawn when a shape lifts
+ posts: [number, number][]
+ fill: IsoPoint[]
+}
+
+interface ProjectShapeParams {
+ box: IsoBox
+ view?: IsoView
+}
+
+interface RecessParams {
+ opening: IsoPoint[]
+ floor: IsoPoint[]
+ inset: NonNullable<IsoBox['inset']>
+}
+
+interface RingBoundsParams {
+ rings: IsoRing[]
+ view?: IsoView
+}
+
+interface ProjectedBox {
+ key: string
+ faces: IsoPoint[][]
+ hiddenEdges: [IsoPoint, IsoPoint][]
+ insets: IsoPoint[][]
+ guides: [IsoPoint, IsoPoint][]
+}
+
+const COS = Math.cos(Math.PI / 6)
+const GUIDE_REACH = 1.6
+const INSET_MARGIN = 0.18
+const FRONT_TURN_COS = Math.cos(Math.PI / 9)
+const FRONT_TURN_SIN = Math.sin(Math.PI / 9)
+const CYLINDER_SEGMENTS = 48
+
+const isoPoint = (x: number, y: number, z: number): IsoPoint => [(x - y) * COS, (x + y) * 0.5 - z]
+
+export const VIEW_POINTS: Record<IsoView, (x: number, y: number, z: number) => IsoPoint> = {
+ iso: isoPoint,
+ // turned a little, so boxes show a narrow side face. circles look the same at all angles
+ front: (x, y, z) => [
+ x * FRONT_TURN_COS - y * FRONT_TURN_SIN,
+ (x * FRONT_TURN_SIN + y * FRONT_TURN_COS) * 0.35 - z,
+ ],
+}
+
+export const cube = (x: number, y: number, z: number, size: number): IsoBox => ({
+ x,
+ y,
+ z,
+ w: size,
+ d: size,
+ h: size,
+})
+
+export const paintOrder = (boxes: IsoBox[]): IsoBox[] =>
+ [...boxes].sort(
+ (a, b) => a.x + a.w / 2 + a.y + a.d / 2 + a.z - (b.x + b.w / 2 + b.y + b.d / 2 + b.z)
+ )
+
+const projectBox = (box: IsoBox, p = isoPoint): ProjectedBox => {
+ const { x, y, z, w, d, h, inset } = box
+ const right = [p(x + w, y, z), p(x + w, y + d, z), p(x + w, y + d, z + h), p(x + w, y, z + h)]
+ const left = [p(x, y + d, z), p(x + w, y + d, z), p(x + w, y + d, z + h), p(x, y + d, z + h)]
+ const top = [p(x, y, z + h), p(x + w, y, z + h), p(x + w, y + d, z + h), p(x, y + d, z + h)]
+ const back = p(x, y, z)
+ const mw = w * INSET_MARGIN
+ const md = d * INSET_MARGIN
+ const mh = h * INSET_MARGIN
+
+ const frontInset = (depth: number) => [
+ p(x + w - depth, y + md, z + mh),
+ p(x + w - depth, y + d - md, z + mh),
+ p(x + w - depth, y + d - md, z + h - mh),
+ p(x + w - depth, y + md, z + h - mh),
+ ]
+ const topInset = (depth: number) => [
+ p(x + mw, y + md, z + h - depth),
+ p(x + w - mw, y + md, z + h - depth),
+ p(x + w - mw, y + d - md, z + h - depth),
+ p(x + mw, y + d - md, z + h - depth),
+ ]
+ const insetFace = { front: frontInset, top: topInset }
+
+ return {
+ key: `${x}:${y}:${z}`,
+ faces: [right, left, top],
+ hiddenEdges: [
+ [back, p(x + w, y, z)],
+ [back, p(x, y + d, z)],
+ [back, p(x, y, z + h)],
+ ],
+ insets: inset
+ ? recess({ opening: insetFace[inset](0), floor: insetFace[inset](w * 0.12), inset })
+ : [],
+ guides: [
+ [p(x - GUIDE_REACH, y + d, z), p(x + w + GUIDE_REACH, y + d, z)],
+ [p(x + w, y - GUIDE_REACH, z), p(x + w, y + d + GUIDE_REACH, z)],
+ ],
+ }
+}
+
+export const projectShape = ({ box, view = 'iso' }: ProjectShapeParams): ProjectedShape => {
+ const { x, y, z, w, d, h } = box
+ if (box.shape !== 'cylinder') {
+ const projected = projectBox(box, VIEW_POINTS[view])
+ return {
+ ...projected,
+ posts: [
+ [x + w, y],
+ [x + w, y + d],
+ [x, y + d],
+ ],
+ fill: box.fillFace
+ ? // projectBox returns faces in this order
+ projected.faces[{ right: 0, left: 1, top: 2 }[box.fillFace]]
+ : (projected.insets.at(-1) ?? convexHull(projected.faces.flat())),
+ }
+ }
+ const point = VIEW_POINTS[view]
+ const radius = w / 2
+ const plan = Array.from({ length: CYLINDER_SEGMENTS }, (_, i): [number, number] => {
+ const angle = (i / CYLINDER_SEGMENTS) * Math.PI * 2
+ return [x + radius + Math.cos(angle) * radius, y + radius + Math.sin(angle) * radius]
+ })
+ const base = plan.map(([px, py]) => point(px, py, z))
+ const top = plan.map(([px, py]) => point(px, py, z + h))
+ const pick = (score: (p: IsoPoint) => number) =>
+ plan[base.reduce((best, p, i) => (score(p) > score(base[best]) ? i : best), 0)]
+ return {
+ key: `${x}:${y}:${z}`,
+ // the hull of both rims is the side outline. the top rim covers its far half
+ faces: [convexHull([...base, ...top]), top],
+ hiddenEdges: [],
+ insets: [],
+ guides: [],
+ posts: [pick(([px]) => -px), pick(([, py]) => py), pick(([px]) => px)],
+ fill: top,
+ }
+}
+
+// the last polygon is the floor, because projectShape takes it as the fill area
+const recess = ({ opening, floor, inset }: RecessParams): IsoPoint[][] => {
+ const visibleFloor = clipPolygon(floor, opening)
+ if (inset === 'top') {
+ const [, right, front, left] = opening
+ const [, floorRight, floorFront, floorLeft] = floor
+ return [opening, [right, front, left, floorLeft, floorFront, floorRight], visibleFloor]
+ }
+ // a floor corner that clipping keeps is inside the opening, so its depth edge shows
+ const depthEdges = floor.flatMap((corner, i) =>
+ visibleFloor.includes(corner) ? [[opening[i], corner]] : []
+ )
+ return [opening, ...depthEdges, visibleFloor]
+}
+
+const cross = (o: IsoPoint, a: IsoPoint, b: IsoPoint) =>
+ (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0])
+
+// sutherland-hodgman. the clip polygon must be convex
+const clipPolygon = (subject: IsoPoint[], clip: IsoPoint[]): IsoPoint[] => {
+ const turn = Math.sign(cross(clip[0], clip[1], clip[2]))
+ return clip.reduce((output, a, i) => {
+ const b = clip[(i + 1) % clip.length]
+ const side = (p: IsoPoint) => turn * cross(a, b, p)
+ const crossing = (p: IsoPoint, q: IsoPoint): IsoPoint => {
+ const t = side(p) / (side(p) - side(q))
+ return [p[0] + (q[0] - p[0]) * t, p[1] + (q[1] - p[1]) * t]
+ }
+ return output.flatMap((q, j) => {
+ const p = output[(j + output.length - 1) % output.length]
+ if (side(q) >= 0) return side(p) >= 0 ? [q] : [crossing(p, q), q]
+ return side(p) >= 0 ? [crossing(p, q)] : []
+ })
+ }, subject)
+}
+
+// monotone chain
+export const convexHull = (points: IsoPoint[]): IsoPoint[] => {
+ const sorted = [...points].sort(([ax, ay], [bx, by]) => ax - bx || ay - by)
+ const half = (list: IsoPoint[]) =>
+ list.reduce<IsoPoint[]>((hull, p) => {
+ while (hull.length >= 2 && cross(hull[hull.length - 2], hull[hull.length - 1], p) <= 0) {
+ hull.pop()
+ }
+ hull.push(p)
+ return hull
+ }, [])
+ const lower = half(sorted)
+ const upper = half([...sorted].reverse())
+ return [...lower.slice(0, -1), ...upper.slice(0, -1)]
+}
+
+export const compositionBounds = (boxes: Pick<ProjectedBox, 'faces'>[], padding = 0.25) => {
+ const points = boxes.flatMap((box) => box.faces.flat())
+ const xs = points.map(([px]) => px)
+ const ys = points.map(([, py]) => py)
+ const minX = Math.min(...xs)
+ const minY = Math.min(...ys)
+ const width = Math.max(...xs) - minX
+ const height = Math.max(...ys) - minY
+ const pad = Math.max(width, height) * padding
+ return { x: minX - pad, y: minY - pad, width: width + pad * 2, height: height + pad * 2 }
+}
+
+// a ring's square, so compositionBounds fits rings like boxes
+export const ringBounds = ({
+ rings,
+ view = 'iso',
+}: RingBoundsParams): Pick<ProjectedBox, 'faces'>[] =>
+ rings.map((ring) => {
+ const [cx, cy] = VIEW_POINTS[view](ring.x, ring.y, ring.z)
+ return {
+ faces: [
+ [
+ [cx - ring.radius, cy - ring.radius],
+ [cx + ring.radius, cy + ring.radius],
+ ],
+ ],
+ }
+ })
diff --git a/apps/kb/src/lib/nav.ts b/apps/kb/src/lib/nav.ts
new file mode 100644
index 00000000000..59a60cdfca1
--- /dev/null
+++ b/apps/kb/src/lib/nav.ts
@@ -0,0 +1,53 @@
+import { FORMAT_TOPICS, topicToSlug, type Topic } from './topics'
+
+interface NavLink {
+ label: string
+ href: string
+}
+
+interface NavLinkGroup {
+ label: string
+ links: NavLink[]
+}
+
+export interface NavMenu {
+ label: string
+ groups: NavLinkGroup[]
+}
+
+export const SIGN_UP_URL = 'https://supabase.com/dashboard/sign-up'
+
+const toTopicLink = (topic: Topic): NavLink => ({
+ label: topic,
+ href: `${import.meta.env.BASE_URL}/topics/${topicToSlug(topic)}`,
+})
+
+// topics come from getListedTopics, so the menu only links to topics with entries
+export const getNavMenus = (topics: Topic[]): NavMenu[] => [
+ {
+ label: 'Topics',
+ groups: [
+ {
+ label: 'By category',
+ links: topics.filter((topic) => FORMAT_TOPICS.includes(topic)).map(toTopicLink),
+ },
+ {
+ label: 'By feature',
+ links: topics.filter((topic) => !FORMAT_TOPICS.includes(topic)).map(toTopicLink),
+ },
+ ].filter((group) => group.links.length > 0),
+ },
+ {
+ label: 'Resources',
+ groups: [
+ {
+ label: 'Resources',
+ links: [
+ { label: 'Status', href: 'https://status.supabase.com' },
+ { label: 'Changelog', href: 'https://supabase.com/changelog' },
+ { label: 'Docs', href: 'https://supabase.com/docs' },
+ ],
+ },
+ ],
+ },
+]
diff --git a/apps/kb/src/lib/reveal.ts b/apps/kb/src/lib/reveal.ts
new file mode 100644
index 00000000000..8e2d858cdf4
--- /dev/null
+++ b/apps/kb/src/lib/reveal.ts
@@ -0,0 +1,43 @@
+import type { CSSProperties } from 'react'
+
+type RevealStyle = CSSProperties & { '--reveal-index': number }
+
+export const REVEAL_GROUP_CLASS = 'group/reveal'
+
+export const REVEAL_ITEM_CLASS = [
+ 'motion-safe:opacity-0 motion-safe:group-data-revealed/reveal:opacity-100',
+ 'motion-safe:group-data-[revealed=true]/reveal:animate-[reveal-up_500ms_var(--ease-out-strong)_calc(var(--reveal-offset,0ms)_+_min(var(--reveal-index),8)*60ms)_both]',
+].join(' ')
+
+export const bindRevealOnce = (element: HTMLElement | null) => {
+ if (!element) return
+ // the last item has the longest delay, so its end means the whole stagger is done
+ const settle = (event: Event) => {
+ if (event.target !== element.lastElementChild) return
+ element.dataset.revealed = 'settled'
+ }
+ element.addEventListener('animationend', settle)
+ element.addEventListener('animationcancel', settle)
+ let isFirstCheck = true
+ const observer = new IntersectionObserver(
+ ([entry]) => {
+ const isOnScreenAtLoad = isFirstCheck
+ isFirstCheck = false
+ if (!entry?.isIntersecting) return
+ // groups already in view on load wait for the hero instead of beating it in
+ // the offset lets the hero canvas start drawing before on-screen groups reveal
+ if (isOnScreenAtLoad) element.style.setProperty('--reveal-offset', '300ms')
+ element.dataset.revealed = 'true'
+ observer.disconnect()
+ },
+ { rootMargin: '0px 0px -10% 0px' }
+ )
+ observer.observe(element)
+ return () => {
+ observer.disconnect()
+ element.removeEventListener('animationend', settle)
+ element.removeEventListener('animationcancel', settle)
+ }
+}
+
+export const revealStyle = (index: number): RevealStyle => ({ '--reveal-index': index })
diff --git a/apps/kb/src/lib/topics.ts b/apps/kb/src/lib/topics.ts
index 828fd6682e2..1c8d024f794 100644
--- a/apps/kb/src/lib/topics.ts
+++ b/apps/kb/src/lib/topics.ts
@@ -36,7 +36,7 @@ export const TOPICS = [
visible: true,
},
{
- name: 'Tutorial',
+ name: 'Tutorials',
description: 'Step-by-step walkthroughs for building with Supabase.',
pinned: true,
visible: true,
@@ -78,7 +78,7 @@ export const TOPICS = [
visible: true,
},
{
- name: 'Supabase Platform',
+ name: 'Platform',
description: 'Project settings, billing, and infrastructure.',
pinned: false,
visible: true,
@@ -87,10 +87,60 @@ export const TOPICS = [
export type Topic = (typeof TOPICS)[number]['name']
+type ContentCollection = 'guides' | 'troubleshooting'
+
+interface ListedTopicsParams {
+ guides: { topics: readonly string[] }[]
+ troubleshooting: { topics: readonly string[] }[]
+}
+
+interface IsInTopicParams {
+ collection: ContentCollection
+ topics: readonly string[]
+ topic: Topic
+}
+
// zod's `enum()` needs a literal non-empty tuple of strings, which `.map()`
// can't preserve on its own — this cast is safe because TOPICS is `as const`.
export const TOPIC_NAMES = TOPICS.map((topic) => topic.name) as [Topic, ...Topic[]]
+export const FORMAT_TOPICS: Topic[] = [
+ 'Migration',
+ 'Comparison',
+ 'Rundowns',
+ 'Troubleshooting',
+ 'Tutorials',
+]
+
+// the kind of guide picks the cover before its subject does
+export const pickCoverTopic = (topics: Topic[]): Topic | null =>
+ topics.find((topic) => FORMAT_TOPICS.includes(topic)) ?? topics[0] ?? null
+
+// the topic pages and scripts/generate-markdown.mjs both use this, so they list the same entries
+export const isInTopic = ({ collection, topics, topic }: IsInTopicParams): boolean => {
+ if (collection !== 'troubleshooting') return topics.includes(topic)
+ // troubleshooting is a content type. other type topics never list it
+ if (topic === 'Troubleshooting') return true
+ return !FORMAT_TOPICS.includes(topic) && topics.includes(topic)
+}
+
+// visible topics with at least one entry. the nav and the homepage only link to these
+export const getListedTopics = ({ guides, troubleshooting }: ListedTopicsParams) =>
+ TOPICS.filter(
+ (topic) =>
+ topic.visible &&
+ (guides.some((guide) =>
+ isInTopic({ collection: 'guides', topics: guide.topics, topic: topic.name })
+ ) ||
+ troubleshooting.some((entry) =>
+ isInTopic({ collection: 'troubleshooting', topics: entry.topics, topic: topic.name })
+ ))
+ )
+
+// federated collections tag with their own vocabulary, which may not match kb's topics
+export const isKnownTopic = (topic: string): topic is Topic =>
+ TOPIC_NAMES.some((name) => name === topic)
+
export function getTopicDescription(topic: Topic): string {
return TOPICS.find((t) => t.name === topic)!.description
}
diff --git a/apps/kb/src/lib/use-query-variant.ts b/apps/kb/src/lib/use-query-variant.ts
new file mode 100644
index 00000000000..23a4074f182
--- /dev/null
+++ b/apps/kb/src/lib/use-query-variant.ts
@@ -0,0 +1,25 @@
+import { useSyncExternalStore } from 'react'
+
+interface UseQueryVariantParams<T extends string> {
+ key: string
+ options: readonly T[]
+ fallback: T
+}
+
+const subscribeToHistory = (onChange: () => void) => {
+ window.addEventListener('popstate', onChange)
+ return () => window.removeEventListener('popstate', onChange)
+}
+
+export const useQueryVariant = <T extends string>({
+ key,
+ options,
+ fallback,
+}: UseQueryVariantParams<T>): T => {
+ const value = useSyncExternalStore(
+ subscribeToHistory,
+ () => new URLSearchParams(window.location.search).get(key),
+ () => null
+ )
+ return options.find((option) => option === value) ?? fallback
+}
diff --git a/apps/kb/src/pages/guides/[...slug].astro b/apps/kb/src/pages/guides/[...slug].astro
index 8b630013c1d..902e13d253d 100644
--- a/apps/kb/src/pages/guides/[...slug].astro
+++ b/apps/kb/src/pages/guides/[...slug].astro
@@ -3,19 +3,24 @@ import { getCollection, render } from 'astro:content'
import { Admonition } from 'ui-patterns/Admonition'
import ArticleLayout from '../../layouts/ArticleLayout.astro'
+import { relatedGuides, toSummary } from '../../lib/guides'
import { breadcrumbListSchema, KB_BASE_URL, techArticleSchema } from '../../lib/json-ld'
export async function getStaticPaths() {
const guides = await getCollection('guides')
+ const summaries = guides.map(toSummary)
return guides.map((guide) => ({
params: { slug: guide.id },
- props: { guide },
+ props: { guide, related: relatedGuides({ guide: toSummary(guide), guides: summaries }) },
}))
}
-const { guide } = Astro.props
+const { guide, related } = Astro.props
const { title, description, topics, github_url, date } = guide.data
-const { Content } = await render(guide)
+const { Content, headings } = await render(guide)
+const toc = headings
+ .filter((heading) => heading.depth === 2 || heading.depth === 3)
+ .map((heading) => ({ title: heading.text, url: `#${heading.slug}`, depth: heading.depth }))
// guide.filePath is relative to the kb app root, e.g. "src/content/guides/foo.mdx"
const viewGitHubLink = `https://github.com/supabase/supabase/blob/master/apps/kb/${guide.filePath}`
@@ -38,6 +43,8 @@ const jsonLd = [
viewGitHubLink={viewGitHubLink}
date={date}
jsonLd={jsonLd}
+ toc={toc}
+ related={related}
>
<Content components={{ Admonition }} />
</ArticleLayout>
diff --git a/apps/kb/src/pages/index.astro b/apps/kb/src/pages/index.astro
index 1d458621676..e8d0d14557b 100644
--- a/apps/kb/src/pages/index.astro
+++ b/apps/kb/src/pages/index.astro
@@ -1,80 +1,44 @@
---
import { getCollection } from 'astro:content'
-import Card from '../components/Card.astro'
-import { Hero } from '../components/Hero'
+import { FeaturedSection } from '../components/FeaturedSection'
+import { GuideBrowser } from '../components/GuideBrowser'
+import { HomeHero } from '../components/Hero'
import Layout from '../layouts/Layout.astro'
-import { TOPICS, topicToSlug } from '../lib/topics'
+import { padFeatured, toSummary, toTroubleshootingSummary, type FeaturedItem } from '../lib/guides'
+import { getListedTopics, topicToSlug } from '../lib/topics'
const guides = await getCollection('guides')
-const visibleTopics = TOPICS.filter((topic) => topic.visible)
-const pinnedTopics = visibleTopics.filter((topic) => topic.pinned)
-const featuredGuides = guides.filter((guide) => guide.data.pinned)
+const summaries = guides.map(toSummary)
+const troubleshooting = (await getCollection('troubleshooting')).map(toTroubleshootingSummary)
+const listedTopics = getListedTopics({ guides: summaries, troubleshooting })
+const pinnedTopics = listedTopics.filter((topic) => topic.pinned)
+const featuredTopics: FeaturedItem[] = (pinnedTopics.length > 0 ? pinnedTopics : listedTopics.slice(0, 3)).map(
+ (topic) => ({
+ id: `topic-${topicToSlug(topic.name)}`,
+ slot: `topic-${topicToSlug(topic.name)}`,
+ title: topic.name,
+ description: topic.description,
+ topics: [topic.name],
+ href: `${import.meta.env.BASE_URL}/topics/${topicToSlug(topic.name)}`,
+ })
+)
+const featuredGuides = padFeatured({
+ featured: guides.filter((guide) => guide.data.pinned).map(toSummary),
+ fallback: summaries,
+})
---
-<Layout title="Home" description="In-depth guides, tutorials, and explainers for best practices for Supabase databases.">
- <Hero />
-
- <div class="mx-auto flex max-w-7xl flex-col gap-16 px-6 py-16">
- {
- pinnedTopics.length > 0 && (
- <section class="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3">
- {pinnedTopics.map((topic) => (
- <Card
- href={`${import.meta.env.BASE_URL}/topics/${topicToSlug(topic.name)}`}
- title={topic.name}
- description={topic.description}
- />
- ))}
- </section>
- )
- }
-
+<Layout description="In-depth guides, tutorials, troubleshooting, and explainers for best practices for Supabase">
+ <HomeHero client:load guides={[...summaries, ...troubleshooting]} />
+ <div class="flex flex-col gap-20 pb-24 pt-16 sm:gap-24 sm:pt-20">
+ <FeaturedSection client:load title="Featured topics" items={featuredTopics} />
+ <FeaturedSection client:load title="Featured guides" items={featuredGuides} />
{
- featuredGuides.length > 0 && (
- <section>
- <h2 class="mb-6 text-2xl font-medium text-foreground">Featured Guides</h2>
- <div class="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3">
- {featuredGuides.map((guide) => (
- <Card
- href={`${import.meta.env.BASE_URL}/guides/${guide.id}`}
- title={guide.data.title}
- description={guide.data.description}
- topics={guide.data.topics}
- />
- ))}
- </div>
- </section>
- )
+ troubleshooting.length > 0 ? (
+ <GuideBrowser client:load title="Troubleshooting" guides={troubleshooting} param="troubleshooting" />
+ ) : null
}
-
- <section>
- <h2 class="mb-6 text-2xl font-medium text-foreground">All Guides</h2>
- <ul class="flex flex-col gap-2">
- {guides.map((guide) => (
- <li>
- <a href={`${import.meta.env.BASE_URL}/guides/${guide.id}`} class="text-brand-link hover:underline">
- {guide.data.title}
- </a>
- </li>
- ))}
- </ul>
- </section>
-
- <section>
- <h2 class="mb-6 text-2xl font-medium text-foreground">All Topics</h2>
- <ul class="flex flex-col gap-2">
- {visibleTopics.map((topic) => (
- <li>
- <a
- href={`${import.meta.env.BASE_URL}/topics/${topicToSlug(topic.name)}`}
- class="text-brand-link hover:underline"
- >
- {topic.name}
- </a>
- </li>
- ))}
- </ul>
- </section>
+ <GuideBrowser client:load title="All guides" guides={summaries} />
</div>
</Layout>
diff --git a/apps/kb/src/pages/topics/[topic].astro b/apps/kb/src/pages/topics/[topic].astro
index ddb7a703156..932e0935036 100644
--- a/apps/kb/src/pages/topics/[topic].astro
+++ b/apps/kb/src/pages/topics/[topic].astro
@@ -1,17 +1,17 @@
---
import { getCollection } from 'astro:content'
+import { Breadcrumb, BreadcrumbItem, BreadcrumbLink, BreadcrumbList } from 'ui'
+import { GuideBrowser } from '../../components/GuideBrowser'
+import { TopicHero } from '../../components/Hero'
import Layout from '../../layouts/Layout.astro'
+import { toSummary, toTroubleshootingSummary } from '../../lib/guides'
import { breadcrumbListSchema, KB_BASE_URL } from '../../lib/json-ld'
-import { TOPICS, topicToSlug } from '../../lib/topics'
+import { isInTopic, TOPICS, topicToSlug } from '../../lib/topics'
export async function getStaticPaths() {
- const guides = await getCollection('guides')
- const troubleshooting = await getCollection('troubleshooting')
- const entries = [
- ...guides.map((guide) => ({ data: guide.data, href: `/guides/${guide.id}` })),
- ...troubleshooting.map((entry) => ({ data: entry.data, href: `/troubleshooting/${entry.id}` })),
- ]
+ const guides = (await getCollection('guides')).map(toSummary)
+ const troubleshooting = (await getCollection('troubleshooting')).map(toTroubleshootingSummary)
// One page per topic in TOPICS — not just topics a guide already uses —
// so every link on the "Topics" nav resolves instead of 404ing.
@@ -20,12 +20,17 @@ export async function getStaticPaths() {
props: {
topic: topic.name,
description: topic.description,
- guides: entries.filter((entry) => entry.data.topics?.includes(topic.name)),
+ guides: guides.filter((guide) =>
+ isInTopic({ collection: 'guides', topics: guide.topics, topic: topic.name })
+ ),
+ troubleshooting: troubleshooting.filter((entry) =>
+ isInTopic({ collection: 'troubleshooting', topics: entry.topics, topic: topic.name })
+ ),
},
}))
}
-const { topic, description, guides } = Astro.props
+const { topic, description, guides, troubleshooting } = Astro.props
const url = `${KB_BASE_URL}/topics/${topicToSlug(topic)}`
const jsonLd = breadcrumbListSchema([
{ name: 'Knowledge Base', url: KB_BASE_URL },
@@ -34,21 +39,26 @@ const jsonLd = breadcrumbListSchema([
---
<Layout title={topic} description={description} jsonLd={jsonLd}>
- <article class="prose max-w-3xl mx-auto px-6 py-16">
- <h1>{topic}</h1>
- <p class="lead">{description}</p>
+ <TopicHero client:load topic={topic} description={description} guides={[...guides, ...troubleshooting]}>
+ <Breadcrumb slot="breadcrumb">
+ <BreadcrumbList>
+ <BreadcrumbItem>
+ <BreadcrumbLink href={import.meta.env.BASE_URL} className="no-underline">Knowledge base</BreadcrumbLink>
+ </BreadcrumbItem>
+ </BreadcrumbList>
+ </Breadcrumb>
+ </TopicHero>
+ <div class="flex flex-col gap-20 pb-24 pt-16 sm:gap-24 sm:pt-20">
{
- guides.length === 0 ? (
- <p>No guides for this topic</p>
- ) : (
- <ul>
- {guides.map((guide) => (
- <li>
- <a href={`${import.meta.env.BASE_URL}${guide.href}`}>{guide.data.title}</a>
- </li>
- ))}
- </ul>
- )
+ guides.length === 0 && troubleshooting.length === 0 ? (
+ <p class="mx-auto max-w-6xl px-6 text-sm text-foreground-light">No guides for this topic yet.</p>
+ ) : null
}
- </article>
+ {guides.length > 0 ? <GuideBrowser client:load title="Guides" guides={guides} /> : null}
+ {
+ troubleshooting.length > 0 ? (
+ <GuideBrowser client:load title="Troubleshooting" guides={troubleshooting} param="troubleshooting" />
+ ) : null
+ }
+ </div>
</Layout>
diff --git a/apps/kb/src/styles/globals.css b/apps/kb/src/styles/globals.css
index 6fccde73f71..e8ddbff7e51 100644
--- a/apps/kb/src/styles/globals.css
+++ b/apps/kb/src/styles/globals.css
@@ -1,4 +1,6 @@
@import 'config/tailwind.config.css';
+@import './utilities.css';
+@import './keyframes.css';
@source '../pages/**/*.astro';
@source '../components/**/*.{astro,tsx}';
@@ -23,6 +25,26 @@
--font-mono: 'Source Code Pro', ui-monospace, Menlo, monospace;
}
+@theme {
+ --ease-out-strong: cubic-bezier(0.23, 1, 0.32, 1);
+ --animate-draw-out: draw-out 700ms cubic-bezier(0.65, 0, 0.35, 1) both;
+ --animate-draw-line: draw-line 1.8s linear both;
+ --animate-draw-line-fast: draw-line 850ms cubic-bezier(0.65, 0, 0.35, 1) both;
+ --animate-fade-in: fade-in 450ms ease-out both;
+}
+
+@theme {
+ --tracking-display: -0.03em;
+ --tracking-title: -0.015em;
+ --tracking-body: -0.012em;
+ --tracking-label: 0.08em;
+}
+
+@theme inline {
+ --shadow-raised: var(--raised-shadow, 0 0 #0000);
+ --drop-shadow-raised: var(--raised-drop-shadow, 0 0 #0000);
+}
+
/* Same type scale as apps/docs/styles/globals.css — without this, utilities
* like `text-sm` resolve to Tailwind's default 0.875rem instead of docs'
* 0.8125rem, so text using the same class names still renders at different
@@ -65,12 +87,14 @@ h6:not(.font-mono),
@apply font-heading font-semibold;
}
-*,
-::after,
-::before,
-::backdrop,
-::file-selector-button {
- border-color: var(--border-default, currentColor);
+@layer base {
+ *,
+ ::after,
+ ::before,
+ ::backdrop,
+ ::file-selector-button {
+ border-color: var(--border-default, currentColor);
+ }
}
/* Code block theme colors for use with Supabase Theme */
@@ -88,6 +112,9 @@ h6:not(.font-mono),
--code-token-number: #ffffff;
--code-token-property: #3ecf8e;
--code-highlight-color: #232323;
+ --raised-shadow:
+ 0 0 0 0 var(--border-default), 0 1px 2px 0 rgba(0, 0, 0, 0.3), 0 1px 3px 0 rgba(0, 0, 0, 0.3);
+ --raised-drop-shadow: 0 1px 1px rgba(0, 0, 0, 0.5);
}
[data-theme='light'] {
@@ -109,3 +136,9 @@ h6:not(.font-mono),
.prose [role='alert'] {
margin: 1.25rem 0;
}
+
+@media (width < 64rem) {
+ html[data-mobile-menu-open] {
+ overflow: hidden;
+ }
+}
diff --git a/apps/kb/src/styles/keyframes.css b/apps/kb/src/styles/keyframes.css
new file mode 100644
index 00000000000..4d1e12f7fb0
--- /dev/null
+++ b/apps/kb/src/styles/keyframes.css
@@ -0,0 +1,24 @@
+@keyframes reveal-up {
+ from {
+ opacity: 0;
+ translate: 0 12px;
+ }
+}
+
+@keyframes draw-line {
+ from {
+ stroke-dashoffset: 1;
+ }
+}
+
+@keyframes fade-in {
+ from {
+ opacity: 0;
+ }
+}
+
+@keyframes draw-out {
+ from {
+ scale: 0;
+ }
+}
diff --git a/apps/kb/src/styles/utilities.css b/apps/kb/src/styles/utilities.css
new file mode 100644
index 00000000000..30b8576e46c
--- /dev/null
+++ b/apps/kb/src/styles/utilities.css
@@ -0,0 +1,40 @@
+.cover-notch {
+ mask:
+ linear-gradient(#000 0 0),
+ var(--notch-mask) right -2px bottom -2px / calc(var(--notch-width) + 10px) 42px no-repeat;
+ mask-composite: exclude;
+ mask-clip: no-clip;
+ box-shadow: none;
+}
+
+@utility section-container {
+ @apply w-full mx-auto max-w-6xl px-6;
+}
+
+.tab-flares {
+ --tab-flare-ring:
+ transparent 6.75px, var(--border-color-default) 7.25px, var(--border-color-default) 7.75px,
+ transparent 8.25px;
+ --tab-flare-fill: transparent 6.75px, var(--background-color-200) 7.25px;
+ --tab-flare-left:
+ radial-gradient(circle at 0 0, var(--tab-flare-ring)),
+ radial-gradient(circle at 0 0, var(--tab-flare-fill));
+ --tab-flare-right:
+ radial-gradient(circle at 100% 0, var(--tab-flare-ring)),
+ radial-gradient(circle at 100% 0, var(--tab-flare-fill));
+}
+
+@utility grain-mask {
+ mask: url('../assets/grain.webp') 0 0 / 132px 132px;
+}
+
+/* --flank-span is how wide the bands above and below the copy show.
+ the grid columns pass calc(100% - 20rem), so they stop at the copy frame */
+@utility grain-mask-flank {
+ mask:
+ url('../assets/grain.webp') 0 0 / 132px 132px,
+ linear-gradient(#000 0 0) top left / var(--flank-span, 100%) 100vh no-repeat,
+ linear-gradient(#000, transparent 10rem) bottom left / var(--flank-span, 100%) 100vh no-repeat,
+ linear-gradient(#000 0 0) top left / calc(100% - 20rem) calc(100% - 100vh) no-repeat;
+ mask-composite: intersect, add, add, add;
+}
diff --git a/packages/ui-patterns/package.json b/packages/ui-patterns/package.json
index 840d87000f1..9bae29ade1d 100644
--- a/packages/ui-patterns/package.json
+++ b/packages/ui-patterns/package.json
@@ -34,6 +34,10 @@
"import": "./src/Admonition/index.tsx",
"types": "./src/Admonition/index.tsx"
},
+ "./AiTools": {
+ "import": "./src/AiTools/index.tsx",
+ "types": "./src/AiTools/index.tsx"
+ },
"./AssistantChat/AssistantChatForm": {
"import": "./src/AssistantChat/AssistantChatForm.tsx",
"types": "./src/AssistantChat/AssistantChatForm.tsx"
@@ -518,6 +522,10 @@
"import": "./src/MultipleCodeBlock/index.tsx",
"types": "./src/MultipleCodeBlock/index.tsx"
},
+ "./Notch": {
+ "import": "./src/Notch/index.ts",
+ "types": "./src/Notch/index.ts"
+ },
"./PageBreadcrumbs": {
"import": "./src/PageBreadcrumbs/index.tsx",
"types": "./src/PageBreadcrumbs/index.tsx"
diff --git a/packages/ui-patterns/src/AiTools/index.tsx b/packages/ui-patterns/src/AiTools/index.tsx
new file mode 100644
index 00000000000..65887d49672
--- /dev/null
+++ b/packages/ui-patterns/src/AiTools/index.tsx
@@ -0,0 +1,122 @@
+'use client'
+
+import { useCopyMarkdownFromUrl } from 'common/hooks/useCopyMarkdownFromUrl'
+import { askAiUrls } from 'common/markdown-affordance'
+import { Chatgpt, Claude, Google } from 'icons'
+import { Check, Copy, Sparkles } from 'lucide-react'
+import { useId } from 'react'
+import { cn } from 'ui'
+
+export type AiAgent = 'chatgpt' | 'claude'
+
+export interface AiToolsProps {
+ pageUrl: string
+ markdownUrl: string
+ markdownFallback?: () => string
+ agentSetupHref?: string
+ preferredSourceHref?: string
+ onAgentSetupClick?: () => void
+ onPreferredSourceClick?: () => void
+ onMarkdownCopy?: () => void
+ onAskAiClick?: (agent: AiAgent) => void
+ titleClassName?: string
+ className?: string
+}
+
+const ITEM_CLASS =
+ 'flex items-center gap-1.5 text-xs text-foreground-lighter transition-colors hover:text-foreground'
+
+export const AiTools = ({
+ pageUrl,
+ markdownUrl,
+ markdownFallback,
+ agentSetupHref,
+ preferredSourceHref,
+ onAgentSetupClick,
+ onPreferredSourceClick,
+ onMarkdownCopy,
+ onAskAiClick,
+ titleClassName,
+ className,
+}: AiToolsProps) => {
+ const { copied, copyMarkdown } = useCopyMarkdownFromUrl()
+ const titleId = useId()
+ const urls = askAiUrls(pageUrl)
+
+ const handleCopy = async () => {
+ const isCopied = await copyMarkdown(markdownUrl, { fallback: markdownFallback })
+ if (isCopied) onMarkdownCopy?.()
+ }
+ const handleChatgptClick = () => onAskAiClick?.('chatgpt')
+ const handleClaudeClick = () => onAskAiClick?.('claude')
+
+ return (
+ <section className={className} aria-labelledby={titleId}>
+ <h2
+ id={titleId}
+ className={cn(
+ 'mb-3 block font-mono text-xs uppercase text-foreground-light',
+ titleClassName
+ )}
+ >
+ AI tools
+ </h2>
+ <div className="flex flex-col gap-2">
+ {agentSetupHref ? (
+ <a href={agentSetupHref} onClick={onAgentSetupClick} className={ITEM_CLASS}>
+ <Sparkles aria-hidden className="size-3.5" strokeWidth={1.5} />
+ Connect your AI agent
+ </a>
+ ) : null}
+ <button
+ type="button"
+ onClick={handleCopy}
+ className={cn(ITEM_CLASS, 'cursor-pointer text-left')}
+ >
+ {copied ? (
+ <Check aria-hidden className="size-3.5 text-primary" strokeWidth={1.5} />
+ ) : (
+ <Copy aria-hidden className="size-3.5" strokeWidth={1.5} />
+ )}
+ {copied ? 'Copied!' : 'Copy as Markdown'}
+ </button>
+ <span className="sr-only" role="status">
+ {copied ? 'Copied to clipboard' : ''}
+ </span>
+ <a
+ href={urls.chatgpt}
+ target="_blank"
+ rel="noreferrer noopener"
+ onClick={handleChatgptClick}
+ className={ITEM_CLASS}
+ >
+ <Chatgpt aria-hidden className="size-3.5" />
+ Ask ChatGPT
+ </a>
+ <a
+ href={urls.claude}
+ target="_blank"
+ rel="noreferrer noopener"
+ onClick={handleClaudeClick}
+ className={ITEM_CLASS}
+ >
+ <Claude aria-hidden className="size-3.5" />
+ Ask Claude
+ </a>
+ {preferredSourceHref ? (
+ <a
+ href={preferredSourceHref}
+ target="_blank"
+ title="Add Supabase as a preferred source on Google"
+ rel="noreferrer noopener"
+ onClick={onPreferredSourceClick}
+ className={ITEM_CLASS}
+ >
+ <Google aria-hidden className="size-3.5" />
+ Prefer on Google
+ </a>
+ ) : null}
+ </div>
+ </section>
+ )
+}
diff --git a/packages/ui-patterns/src/Notch/index.ts b/packages/ui-patterns/src/Notch/index.ts
new file mode 100644
index 00000000000..c3e8ba65494
--- /dev/null
+++ b/packages/ui-patterns/src/Notch/index.ts
@@ -0,0 +1,10 @@
+export const getNotchOutline = (width: number): string =>
+ `M0 39.5A7.5 7.5 0 0 0 7.5 32V16A8.5 8.5 0 0 1 16 7.5H${width}A7.5 7.5 0 0 0 ${width + 7.5} 0`
+
+export const getNotchFocusRing = (width: number): string =>
+ `M0 41A9 9 0 0 0 9 32V16A7 7 0 0 1 16 9H${width}A9 9 0 0 0 ${width + 9} 0`
+
+export const getNotchMask = (width: number): string =>
+ `url("data:image/svg+xml,${encodeURIComponent(
+ `<svg xmlns='http://www.w3.org/2000/svg' width='${width + 10}' height='42'><path d='M0 40A8 8 0 0 0 8 32V16A8 8 0 0 1 16 8H${width}A8 8 0 0 0 ${width + 8} 0H${width + 10}V42H0Z'/></svg>`
+ )}")`
diff --git a/packages/ui-patterns/src/Toc/index.ts b/packages/ui-patterns/src/Toc/index.ts
index 4f476ea8f58..986f503bc3e 100644
--- a/packages/ui-patterns/src/Toc/index.ts
+++ b/packages/ui-patterns/src/Toc/index.ts
@@ -1,4 +1,4 @@
-import { Toc, TOCItems, TOCScrollArea } from './toc'
+import { Toc, TOCItems, TOCScrollArea, TocSection } from './toc'
import * as TocPrimitive from './toc-primitive'
import { AnchorProvider, ScrollProvider, TOCItem, type AnchorProviderProps } from './toc-primitive'
import { TocThumb, type TOCThumb } from './toc-thumb'
@@ -10,6 +10,7 @@ export {
TocThumb,
TOCItem,
TOCScrollArea,
+ TocSection,
TOCItems,
ScrollProvider,
}
diff --git a/packages/ui-patterns/src/Toc/toc-primitive.tsx b/packages/ui-patterns/src/Toc/toc-primitive.tsx
index 03cb5a5acb6..4c06d63351c 100644
--- a/packages/ui-patterns/src/Toc/toc-primitive.tsx
+++ b/packages/ui-patterns/src/Toc/toc-primitive.tsx
@@ -1,6 +1,8 @@
'use client'
-import { mergeRefs, useAnchorObserver, useOnChange } from 'common'
+import { mergeRefs } from 'common/helpers'
+import { useAnchorObserver } from 'common/hooks/useAnchorObserver'
+import { useOnChange } from 'common/hooks/useOnChange'
import { createContext, forwardRef, useContext, useMemo, useRef } from 'react'
import type { AnchorHTMLAttributes, ReactNode, RefObject } from 'react'
import scrollIntoView from 'scroll-into-view-if-needed'
diff --git a/packages/ui-patterns/src/Toc/toc-thumb.tsx b/packages/ui-patterns/src/Toc/toc-thumb.tsx
index 38499c87d94..40a75487bab 100644
--- a/packages/ui-patterns/src/Toc/toc-thumb.tsx
+++ b/packages/ui-patterns/src/Toc/toc-thumb.tsx
@@ -1,6 +1,7 @@
'use client'
-import { useEffectEvent, useOnChange } from 'common'
+import { useEffectEvent } from 'common/hooks/useEffectEvent'
+import { useOnChange } from 'common/hooks/useOnChange'
import { useEffect, useRef, type HTMLAttributes, type RefObject } from 'react'
import * as Primitive from './toc-primitive'
diff --git a/packages/ui-patterns/src/Toc/toc.tsx b/packages/ui-patterns/src/Toc/toc.tsx
index d8c2322eb98..658e05d5fe0 100644
--- a/packages/ui-patterns/src/Toc/toc.tsx
+++ b/packages/ui-patterns/src/Toc/toc.tsx
@@ -58,6 +58,19 @@ export function TOCScrollArea({
)
}
+export function TocSection({ items, className }: { items: TOCItemType[]; className?: string }) {
+ return (
+ <Toc className={cn('-ml-[calc(0.25rem+6px)]', className)}>
+ <h3 className="inline-flex items-center gap-1.5 font-mono text-xs uppercase text-foreground pl-7.5">
+ On this page
+ </h3>
+ <TOCScrollArea>
+ <TOCItems items={items} />
+ </TOCScrollArea>
+ </Toc>
+ )
+}
+
export function TOCItems({
items,
showTrack = false,