About
Project files an assistant reads in every chat, indexed one at a time with progress, token counts and a context meter.
Built with React and Tailwind. Copy the prompt and paste it into Claude Code, Cursor or Lovable: your agent adds Knowledge Base to your project and fits it to your theme.
Code
How Knowledge Base is used: the demo's code. The component's own source comes with a free account.
Usage.tsx
"use client"
import * as React from "react"
import { KnowledgeBase, KnowledgeFile } from "@/components/ui/knowledge-base"
const reducedMotion = () => window.matchMedia("(prefers-reduced-motion: reduce)").matches
/** Already in the project when the tour starts. */
const READY: KnowledgeFile[] = [
{
id: "rfc",
name: "billing-migration-rfc.md",
size: 47_000,
status: "ready",
tokens: 12_400,
detail: "Added Oct 14 by Priya",
},
{
id: "runbook",
name: "on-call-runbook.pdf",
size: 1_900_000,
status: "ready",
tokens: 31_800,
detail: "Added Oct 14 by Priya",
},
]
/** Dropped in by the tour, then indexed one at a time. */
const ADDED: (KnowledgeFile & { final: number })[] = [
{ id: "funnel", name: "checkout-funnel-q3.csv", size: 793_000, status: "queued", final: 36_900 },
{ id: "schema", name: "schema.ts", size: 21_000, status: "queued", final: 5_200 },
{ id: "style", name: "api-style-guide.docx", size: 312_000, status: "queued", final: 18_300 },
]
const reducedMotion2 = () =>
typeof window !== "undefined" && window.matchMedia("(prefers-reduced-motion: reduce)").matches
const STOP = Symbol("stop")
/**
* Runs `script` in a loop with a `wait(ms)` that stops cleanly on unmount or once `active` turns
* false. Reduced motion never starts it.
*/
function useLoop(
script: (wait: (ms: number) => Promise<void>) => Promise<void>,
active = true,
) {
const ref = React.useRef(script)
ref.current = script
React.useEffect(() => {
if (!active || reducedMotion2()) return
let alive = true
const timers = new Set<number>()
const wait = (ms: number) =>
new Promise<void>((resolve, reject) => {
const id = window.setTimeout(() => {
timers.delete(id)
if (alive) resolve()
else reject(STOP)
}, ms)
timers.add(id)
})
;(async () => {
try {
while (alive) await ref.current(wait)
} catch (error) {
if (error !== STOP) throw error
}
})()
return () => {
alive = false
for (const id of timers) window.clearTimeout(id)
}
}, [active])
}
const FIT_CSS = "html,body{overflow:hidden}[data-fit-small] [data-fit-hide]{display:none!important}"
/**
* 21st shows a demo in a small frame: about 674 by 421 on a component page, 358 by 224 on a
* phone and 245 by 139 on a profile card. A demo taller than its frame gets scrollbars, which
* render white on dark pages. FitFrame fills the frame exactly instead.
*
* - "scale": the content shrinks until it fits, centered. For visuals such as orbs.
* - "crop": the content stays at full size from the top and fades out at the bottom. For text
* that streams in, where a changing scale would make the page breathe.
*
* `minWidth` lays out a wide demo (a table, a two column panel) at that width and scales it down
* to the frame, instead of letting it collapse to a narrow layout. The frame centers it, so it
* shrinks evenly on both sides.
*
* Anything marked `data-fit-hide` (state buttons, the chatcn.dev line) drops out in frames
* shorter than `hideBelow`, so a profile card shows the visual alone.
*/
function FitFrame({
children,
mode = "scale",
hideBelow = 360,
minWidth,
}: {
children: React.ReactNode
mode?: "scale" | "crop"
hideBelow?: number
minWidth?: string
}) {
const content = React.useRef<HTMLDivElement>(null)
const [cropped, setCropped] = React.useState(false)
React.useLayoutEffect(() => {
const el = content.current
if (!el) return
const measure = () => {
const vw = window.innerWidth
const vh = window.innerHeight
el.toggleAttribute("data-fit-small", vh < hideBelow)
// Layout sizes ignore the transform, so measuring never feeds back.
const w = Math.max(el.offsetWidth, el.scrollWidth)
const h = Math.max(el.offsetHeight, el.scrollHeight)
const scale = mode === "scale" ? Math.min(1, vw / w, vh / h) : 1
el.style.transform = scale < 1 ? `scale(${scale})` : ""
setCropped(mode === "crop" && h > vh + 1)
}
measure()
const observer = new ResizeObserver(measure)
observer.observe(el)
// Content that changes inside a fixed width box (a headline that cycles words) never resizes
// the box itself, so changes below it measure again on the next frame.
let frame = 0
const mutations = new MutationObserver(() => {
cancelAnimationFrame(frame)
frame = requestAnimationFrame(measure)
})
mutations.observe(el, { subtree: true, childList: true, characterData: true })
window.addEventListener("resize", measure)
return () => {
observer.disconnect()
mutations.disconnect()
cancelAnimationFrame(frame)
window.removeEventListener("resize", measure)
}
}, [mode, hideBelow])
const fade = "linear-gradient(to bottom, #000 calc(100% - 40px), transparent)"
return (
<div
className="flex w-full justify-center overflow-hidden"
style={{
height: "100dvh",
alignItems: mode === "crop" ? "flex-start" : "center",
maskImage: cropped ? fade : undefined,
WebkitMaskImage: cropped ? fade : undefined,
}}
>
<style>{FIT_CSS}</style>
<div
ref={content}
className="w-full shrink-0"
style={{ transformOrigin: mode === "crop" ? "top center" : "center", minWidth }}
>
{children}
</div>
</div>
)
}
/** The line under each 21st demo that points back to the kit. */
function MoreOn({ slug, children }: { slug: string; children: React.ReactNode }) {
return (
<p data-fit-hide className="text-[0.75rem]/[1rem] text-(color:--chatcn-fg-faint) text-center text-balance">
{children}{" "}
<a
href={`https://chatcn.dev/docs/components/${slug}`}
target="_blank"
rel="noopener"
className="text-(color:--chatcn-fg-subtle) hover:text-(color:--chatcn-fg) underline underline-offset-2"
>
chatcn.dev
</a>
</p>
)
}
/**
* A project's knowledge. Three files arrive and index in turn: each shows its progress, then
* lands as ready with its token count, and the meter at the top climbs with them. Then the new
* files are cleared and the tour starts over. Remove a file or Add files to try it yourself.
*/
export default function KnowledgeBasePreview() {
const [files, setFiles] = React.useState<KnowledgeFile[]>(() =>
typeof window !== "undefined" && reducedMotion()
? [...READY, ...ADDED.map(({ final, ...f }) => ({ ...f, status: "ready" as const, tokens: final, detail: "Added just now" }))]
: READY,
)
const [touring, setTouring] = React.useState(true)
useLoop(async (wait) => {
setFiles(READY)
await wait(1400)
setFiles([...READY, ...ADDED.map(({ final, ...f }) => f)])
await wait(700)
for (const file of ADDED) {
for (let p = 0; p <= 1.0001; p += 0.125) {
const progress = Math.min(1, p)
setFiles((prev) => prev.map((f) => (f.id === file.id ? { ...f, status: "indexing", progress } : f)))
await wait(150)
}
setFiles((prev) =>
prev.map((f) =>
f.id === file.id
? { ...f, status: "ready", progress: undefined, tokens: file.final, detail: "Added just now" }
: f,
),
)
await wait(450)
}
await wait(3400)
}, touring)
const stop = () => setTouring(false)
return (
<FitFrame minWidth="38rem">
<div className="flex w-full flex-col items-center justify-center gap-4 p-6">
{/* Room for all five rows, so the frame never rescales as files come and go. */}
<div className="h-[22.5rem] w-full max-w-2xl" onPointerDownCapture={stop}>
<KnowledgeBase
files={files}
capacity={200_000}
accept=".pdf,.md,.csv,.txt,.docx,.ts,.tsx,.json"
title="Project knowledge"
description="Files the assistant reads in every chat in this project."
onAdd={(list) =>
setFiles((prev) => [
...prev,
...list.map((file, i) => ({
id: `${file.name}-${Date.now()}-${i}`,
name: file.name,
size: file.size,
status: "ready" as const,
tokens: Math.max(400, Math.round(file.size / 22)),
detail: "Added just now",
})),
])
}
onRemove={(id) => setFiles((prev) => prev.filter((f) => f.id !== id))}
/>
</div>
<MoreOn slug="knowledge-base">Project files an assistant reads, indexed with token counts. On</MoreOn>
</div>
</FitFrame>
)
}
















