Context
How much of the context window is spent, as a meter with the breakdown on hover.
Installation
Copy and paste the following code into your project.
1'use client';23import { AnimatePresence, motion, useReducedMotion } from 'motion/react';4import * as React from 'react';5import { cn } from '../lib/cn';6import { springs } from '../lib/motion';7import { useLayer } from '../lib/overlay';8import { useControllableState } from '../lib/use-controllable-state';910const PANEL_INITIAL = { opacity: 0, y: 6, scale: 0.98 } as const;11const PANEL_ANIMATE = { opacity: 1, y: 0, scale: 1 } as const;12const PANEL_EXIT = { opacity: 0, y: 4, scale: 0.98 } as const;13const REDUCED_INITIAL = { opacity: 0 } as const;14const REDUCED_ANIMATE = { opacity: 1 } as const;15const REDUCED_TRANSITION = { duration: 0.1 } as const;1617const RADIUS = 7;18const CIRCUMFERENCE = 2 * Math.PI * RADIUS;1920function formatTokens(tokens: number): string {21 if (tokens < 1000) return String(tokens);22 if (tokens < 1_000_000) return `${(tokens / 1000).toFixed(tokens < 10_000 ? 1 : 0)}K`;23 return `${(tokens / 1_000_000).toFixed(1)}M`;24}2526interface ContextContextValue {27 maxTokens: number;28 usedTokens: number;29 percent: number;30 open: boolean;31 setOpen: (open: boolean) => void;32 toggle: () => void;33 id: string;34 contentRef: React.RefObject<HTMLDivElement | null>;35}3637const ContextContext = React.createContext<ContextContextValue | null>(null);3839const useContextMeter = (): ContextContextValue => {40 const context = React.use(ContextContext);41 if (!context) {42 throw new Error('Context components must be used within Context');43 }44 return context;45};4647interface ContextProps extends React.HTMLAttributes<HTMLDivElement> {48 maxTokens: number;49 usedTokens: number;50 open?: boolean;51 onOpenChange?: (open: boolean) => void;52}5354type ContextTriggerProps = React.ButtonHTMLAttributes<HTMLButtonElement>;5556type MotionSafeProps<T> = Omit<57 React.HTMLAttributes<T>,58 | 'onDrag'59 | 'onDragStart'60 | 'onDragEnd'61 | 'onAnimationStart'62 | 'onAnimationEnd'63 | 'onAnimationIteration'64>;6566interface ContextContentProps extends MotionSafeProps<HTMLDivElement> {67 side?: 'top' | 'bottom';68 align?: 'start' | 'center' | 'end';69}7071type ContextHeaderProps = React.HTMLAttributes<HTMLDivElement>;72type ContextBodyProps = React.HTMLAttributes<HTMLDivElement>;73type ContextFooterProps = React.HTMLAttributes<HTMLDivElement>;7475interface ContextUsageProps extends React.HTMLAttributes<HTMLDivElement> {76 label: React.ReactNode;77 tokens?: number;78 tone?: 'default' | 'muted' | 'success' | 'info' | 'warning';79}8081const TONE_DOT: Record<NonNullable<ContextUsageProps['tone']>, string> = {82 default: 'bg-foreground',83 muted: 'bg-muted-foreground',84 success: 'bg-success',85 info: 'bg-info',86 warning: 'bg-warning',87};8889const ContextRoot = ({90 className,91 maxTokens,92 usedTokens,93 open: controlledOpen,94 onOpenChange,95 onPointerEnter,96 onPointerLeave,97 onFocus,98 onBlur,99 children,100 ref,101 ...props102}: ContextProps & { ref?: React.Ref<HTMLDivElement> }) => {103 const [open, setOpen] = useControllableState({104 value: controlledOpen,105 defaultValue: false,106 onChange: onOpenChange,107 });108 const id = React.useId();109 const contentRef = React.useRef<HTMLDivElement | null>(null);110 const layer = useLayer(open, false, contentRef);111112 const transientRef = React.useRef(false);113114 const peek = () => {115 if (open) return;116 transientRef.current = true;117 setOpen(true);118 };119120 const dismiss = () => {121 transientRef.current = false;122 setOpen(false);123 };124125 const toggle = React.useCallback(() => {126 const pinned = open && !transientRef.current;127 transientRef.current = false;128 setOpen(!pinned);129 }, [open, setOpen]);130131 React.useEffect(() => {132 if (!open) return;133 const onKeyDown = (event: KeyboardEvent) => {134 if (event.key !== 'Escape' || event.defaultPrevented || !layer.isTopmost()) return;135 event.preventDefault();136 transientRef.current = false;137 setOpen(false);138 };139 document.addEventListener('keydown', onKeyDown);140 return () => document.removeEventListener('keydown', onKeyDown);141 }, [open, setOpen, layer]);142143 const safeMax = maxTokens > 0 ? maxTokens : 1;144 const percent = Math.min(Math.max(usedTokens / safeMax, 0), 1);145146 const value = React.useMemo<ContextContextValue>(147 () => ({ maxTokens, usedTokens, percent, open, setOpen, toggle, id, contentRef }),148 [maxTokens, usedTokens, percent, open, setOpen, toggle, id],149 );150151 return (152 <ContextContext value={value}>153 <div154 ref={ref}155 data-state={open ? 'open' : 'closed'}156 onPointerEnter={(event) => {157 onPointerEnter?.(event);158 if (event.pointerType === 'mouse') peek();159 }}160 onPointerLeave={(event) => {161 onPointerLeave?.(event);162 if (event.pointerType === 'mouse') dismiss();163 }}164 onFocus={(event) => {165 onFocus?.(event);166 peek();167 }}168 onBlur={(event) => {169 onBlur?.(event);170 if (!event.currentTarget.contains(event.relatedTarget as Node | null)) dismiss();171 }}172 className={cn('relative inline-flex', className)}173 {...props}174 >175 {children}176 </div>177 </ContextContext>178 );179};180181ContextRoot.displayName = 'Context';182183const ContextTrigger = ({184 className,185 children,186 onClick,187 ref,188 ...props189}: ContextTriggerProps & { ref?: React.Ref<HTMLButtonElement> }) => {190 const { percent, open, toggle, id, usedTokens, maxTokens } = useContextMeter();191 const rounded = Math.round(percent * 100);192193 return (194 <button195 ref={ref}196 type="button"197 id={`${id}-trigger`}198 aria-expanded={open}199 aria-controls={open ? `${id}-content` : undefined}200 aria-describedby={open ? `${id}-content` : undefined}201 aria-label={`${rounded}%, ${formatTokens(usedTokens)} of ${formatTokens(maxTokens)} tokens used`}202 onClick={(event) => {203 onClick?.(event);204 if (!event.defaultPrevented) toggle();205 }}206 className={cn(207 'bg-card text-muted-foreground hover:text-foreground focus-visible:ring-ring inline-flex h-8 items-center gap-1.5 rounded-full ps-1.5 pe-2.5 text-xs tabular-nums shadow-sm transition-colors focus-visible:ring-2 focus-visible:outline-none',208 className,209 )}210 {...props}211 >212 {children ?? (213 <>214 <svg width="18" height="18" viewBox="0 0 18 18" aria-hidden="true" className="shrink-0">215 <circle cx="9" cy="9" r={RADIUS} fill="none" stroke="var(--border)" strokeWidth="2.5" />216 <circle217 cx="9"218 cy="9"219 r={RADIUS}220 fill="none"221 stroke="currentColor"222 strokeWidth="2.5"223 strokeLinecap="round"224 strokeDasharray={CIRCUMFERENCE}225 strokeDashoffset={CIRCUMFERENCE * (1 - percent)}226 transform="rotate(-90 9 9)"227 />228 </svg>229 <span>{rounded}%</span>230 </>231 )}232 </button>233 );234};235236ContextTrigger.displayName = 'ContextTrigger';237238const ContextContent = ({239 className,240 side = 'bottom',241 align = 'start',242 children,243 ref,244 ...props245}: ContextContentProps & { ref?: React.Ref<HTMLDivElement> }) => {246 const { open, id, contentRef } = useContextMeter();247 const shouldReduceMotion = useReducedMotion();248249 const setRefs = React.useCallback(250 (node: HTMLDivElement | null) => {251 contentRef.current = node;252 if (typeof ref === 'function') ref(node);253 else if (ref) ref.current = node;254 },255 [contentRef, ref],256 );257258 return (259 <AnimatePresence>260 {open && (261 <motion.div262 ref={setRefs}263 id={`${id}-content`}264 initial={shouldReduceMotion ? REDUCED_INITIAL : PANEL_INITIAL}265 animate={shouldReduceMotion ? REDUCED_ANIMATE : PANEL_ANIMATE}266 exit={shouldReduceMotion ? REDUCED_INITIAL : PANEL_EXIT}267 transition={shouldReduceMotion ? REDUCED_TRANSITION : springs.smooth}268 className={cn(269 'bg-popover text-popover-foreground absolute z-50 w-64 rounded-md p-3 shadow-md',270 'before:absolute before:inset-x-0 before:h-2 before:content-[""]',271 side === 'bottom'272 ? 'top-full mt-2 before:bottom-full'273 : 'bottom-full mb-2 before:top-full',274 align === 'start' && 'start-0',275 align === 'center' && 'left-1/2 -translate-x-1/2',276 align === 'end' && 'end-0',277 className,278 )}279 {...props}280 >281 {children}282 </motion.div>283 )}284 </AnimatePresence>285 );286};287288ContextContent.displayName = 'ContextContent';289290const ContextHeader = ({291 className,292 children,293 ref,294 ...props295}: ContextHeaderProps & { ref?: React.Ref<HTMLDivElement> }) => {296 const { usedTokens, maxTokens, percent } = useContextMeter();297298 return (299 <div ref={ref} className={cn('flex flex-col gap-2', className)} {...props}>300 {children ?? (301 <>302 <div className="flex items-baseline justify-between gap-2">303 <span className="text-foreground text-xs font-medium">304 {Math.round(percent * 100)}% of context used305 </span>306 <span className="text-muted-foreground text-[11px] tabular-nums">307 {formatTokens(usedTokens)} / {formatTokens(maxTokens)}308 </span>309 </div>310 <div className="bg-muted h-1 w-full overflow-hidden rounded-full">311 <div312 className="bg-foreground h-full rounded-full"313 style={{ width: `${percent * 100}%` }}314 />315 </div>316 </>317 )}318 </div>319 );320};321322ContextHeader.displayName = 'ContextHeader';323324const ContextBody = ({325 className,326 ref,327 ...props328}: ContextBodyProps & { ref?: React.Ref<HTMLDivElement> }) => {329 return <div ref={ref} className={cn('mt-3 flex flex-col gap-1.5', className)} {...props} />;330};331332ContextBody.displayName = 'ContextBody';333334const ContextFooter = ({335 className,336 ref,337 ...props338}: ContextFooterProps & { ref?: React.Ref<HTMLDivElement> }) => {339 return (340 <div341 ref={ref}342 className={cn(343 'border-border text-muted-foreground mt-3 border-t pt-2 text-[11px]',344 className,345 )}346 {...props}347 />348 );349};350351ContextFooter.displayName = 'ContextFooter';352353const ContextUsage = ({354 className,355 label,356 tokens,357 tone = 'default',358 children,359 ref,360 ...props361}: ContextUsageProps & { ref?: React.Ref<HTMLDivElement> }) => {362 return (363 <div364 ref={ref}365 className={cn('flex items-center justify-between gap-2 text-xs', className)}366 {...props}367 >368 {children ?? (369 <>370 <span className="text-muted-foreground flex min-w-0 items-center gap-1.5">371 <span372 aria-hidden="true"373 className={cn('size-1.5 shrink-0 rounded-full', TONE_DOT[tone])}374 />375 <span className="truncate">{label}</span>376 </span>377 {tokens !== undefined && (378 <span className="text-foreground shrink-0 tabular-nums">{formatTokens(tokens)}</span>379 )}380 </>381 )}382 </div>383 );384};385386ContextUsage.displayName = 'ContextUsage';387388const Context = Object.assign(ContextRoot, {389 Trigger: ContextTrigger,390 Content: ContextContent,391 Header: ContextHeader,392 Body: ContextBody,393 Footer: ContextFooter,394 Usage: ContextUsage,395});396397export { Context, formatTokens, useContextMeter };398export type {399 ContextBodyProps,400 ContextContentProps,401 ContextFooterProps,402 ContextHeaderProps,403 ContextProps,404 ContextTriggerProps,405 ContextUsageProps,406};
Update the import paths to match your project structure.
Anatomy
1import { Context } from '@/ai/context';
1<Context maxTokens={200000} usedTokens={84320}>2 <Context.Trigger />3 <Context.Content>4 <Context.Header />5 <Context.Body>6 <Context.Usage label="Input" tokens={61200} />7 <Context.Usage label="Output" tokens={14100} tone="info" />8 </Context.Body>9 <Context.Footer>Estimated from your model pricing.</Context.Footer>10 </Context.Content>11</Context>
The trigger is a ring that fills as the window does, with the percentage beside it. The panel opens on hover and on focus, and clicking pins it open for keyboard and touch.
Composition
Use the following composition to build a
Context:Contextโโโ Context.Triggerโโโ Context.Contentโโโ Context.Headerโโโ Context.Bodyโ โโโ Context.Usageโโโ Context.Footer
Usage rows
Context.Usage is deliberately generic. It takes a label, an optional tokens count and a tone for the dot, so you name the buckets your provider reports rather than inheriting somebody else's. Input, output, reasoning and cached is a good default set.Both
Header and Usage render sensible content when you give them no children, and any children you do pass replace it completely.The panel opens on hover or focus, stays open while the pointer travels from the trigger to it, and closes on Escape. It is extra detail for the trigger rather than a dialog, so the trigger is described by it and its name starts with the same percentage you see.
API Reference
Context
| Prop | Type | Default | Description |
|---|---|---|---|
maxTokens | number | - | Size of the context window |
usedTokens | number | - | Tokens spent so far |
open | boolean | - | Controlled open state |
onOpenChange | (open: boolean) => void | - | Called when the open state changes |
className | string | - | Additional CSS classes |
Context.Content
| Prop | Type | Default | Description |
|---|---|---|---|
side | 'top' | 'bottom' | 'bottom' | Edge the panel opens from |
align | 'start' | 'center' | 'end' | 'start' | Horizontal anchor |
className | string | - | Additional CSS classes |
Context.Usage
| Prop | Type | Default | Description |
|---|---|---|---|
label | ReactNode | - | Name of the bucket |
tokens | number | - | Count shown on the right |
tone | 'default' | 'muted' | 'success' | 'info' | 'warning' | 'default' | Colour of the dot |
className | string | - | Additional CSS classes |
Context.Trigger / Context.Header / Context.Body / Context.Footer
| Prop | Type | Default | Description |
|---|---|---|---|
className | string | - | Additional CSS classes |
Found something to improve?
Notice a bug, typo, or missing detail on this page? Help us make the documentation better by opening a GitHub issue.