About
A segmented switch between Chat, Work and Code with a pill that slides between modes and locked modes that say why.
Built with React and Tailwind. Copy the prompt and paste it into Claude Code, Cursor or Lovable: your agent adds App Mode Switcher to your project and fits it to your theme.
Code
How App Mode Switcher 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 { cn } from "@/lib/utils"
import { Tooltip as TooltipPrimitive } from "@base-ui/react/tooltip"
import { AppModeSwitcher, Icon, IconNode, createIcon } from "@/components/ui/app-mode-switcher"
interface GhostState {
x: number
y: number
shown: boolean
down: boolean
}
/**
* A pointer that walks a demo through its clicks, so a preview shows what each control does.
* `stage` is the positioned box the pointer moves in; targets are found inside it. Sizes come
* from layout boxes, so a scaled FitFrame never throws the aim off.
*/
function useGhost(stage: React.RefObject<HTMLElement | null>) {
const [ghost, setGhost] = React.useState<GhostState>({ x: 0, y: 0, shown: false, down: false })
const find = React.useCallback(
(target: string | HTMLElement) =>
typeof target === "string"
? stage.current?.querySelector<HTMLElement>(target) ?? null
: target,
[stage],
)
const moveTo = React.useCallback(
(target: string | HTMLElement, dx = 0.5, dy = 0.6) => {
const root = stage.current
const el = find(target)
if (!root || !el) return null
const rr = root.getBoundingClientRect()
const scale = root.offsetWidth ? rr.width / root.offsetWidth : 1
const er = el.getBoundingClientRect()
const x = (er.left - rr.left + er.width * dx) / scale
const y = (er.top - rr.top + er.height * dy) / scale
// A hidden pointer fades in a short way off its first target instead of flying in from
// wherever it was last.
setGhost((g) => (g.shown ? { x, y, shown: true, down: false } : { x: x + 70, y: y + 46, shown: false, down: false }))
window.requestAnimationFrame(() =>
window.requestAnimationFrame(() => setGhost({ x, y, shown: true, down: false })),
)
return el
},
[stage, find],
)
const press = React.useCallback((down: boolean) => setGhost((g) => ({ ...g, down })), [])
const hide = React.useCallback(() => setGhost((g) => ({ ...g, shown: false, down: false })), [])
return { ghost, moveTo, press, hide, find }
}
/**
* The switcher sizes its pill from on-screen boxes, which come out small when FitFrame scales the
* demo down (the phone frame). Each time it sets the pill, set it again from layout offsets,
* which ignore the scale. The transition still runs, between the corrected values.
*/
function useUnscaledPill(root: React.RefObject<HTMLElement | null>, value: string) {
React.useLayoutEffect(() => {
const group = root.current?.querySelector<HTMLElement>('[data-slot="app-mode-switcher"]')
const layer = group?.querySelector<HTMLElement>('[data-slot="app-mode-indicator"]')
if (!group || !layer) return
const fix = () => {
const button = group.querySelector<HTMLElement>('[role="radio"][aria-checked="true"]')
if (!button) return
const left = button.offsetLeft - layer.parentElement!.offsetLeft
const right = layer.offsetWidth - left - button.offsetWidth
const clip = `inset(0 ${right}px 0 ${left}px round var(--chatcn-radius-sm, 6px))`
if (layer.style.clipPath !== clip) {
layer.style.clipPath = clip
layer.style.setProperty("-webkit-clip-path", clip)
}
}
fix()
const observer = new MutationObserver(fix)
observer.observe(layer, { attributes: true, attributeFilter: ["style"] })
return () => observer.disconnect()
}, [root, value])
}
const reducedMotion = () =>
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 || reducedMotion()) 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])
}
function Chat() {
return (
<div className="flex flex-col gap-4">
<div className="flex justify-end">
<p className="bg-(color:--chatcn-fill) rounded-(--chatcn-radius-xl) text-[0.875rem]/[1.25rem] tracking-[-0.003em] text-(color:--chatcn-fg) max-w-[80%] px-3.5 py-2">
Turn these interview notes into three themes for Friday.
</p>
</div>
<div className="text-[0.875rem]/[1.25rem] tracking-[-0.003em] text-(color:--chatcn-fg) flex flex-col gap-2">
<p>Three themes came up in most of the eight interviews:</p>
<ol className="text-(color:--chatcn-fg-muted) flex list-decimal flex-col gap-1 ps-5">
<li>Setup takes longer than people expect, mostly the import step.</li>
<li>Teams want shared views before they want more charts.</li>
<li>Weekly email digests are read more than the dashboard.</li>
</ol>
</div>
</div>
)
}
const TASKS = [
{ title: "Draft the Friday research readout", meta: "Docs, 12 min", state: "done" },
{ title: "Tag 214 support tickets by theme", meta: "Spreadsheet, 168 of 214", state: "running" },
{ title: "Book three follow up interviews", meta: "Calendar, waiting on replies", state: "running" },
{ title: "Summarize the pricing survey", meta: "Starts after tagging", state: "queued" },
] as const
const iconNode: IconNode = [
["path", {"d":"m4.5 12.75 3.23 3.23a2.5 2.5 0 0 0 3.54 0l8.48-8.48"}],
]
const CheckIcon: Icon = /* @__PURE__ */ createIcon("check", iconNode)
const iconNode2: IconNode = [
["path", {"d":"M12 3a9 9 0 1 1-9 9"}],
]
const LoaderCircleIcon: Icon = /* @__PURE__ */ createIcon("loader-circle", iconNode2)
function Work() {
return (
<div className="flex flex-col gap-1">
<p className="text-[0.8125rem]/[1.25rem] text-(color:--chatcn-fg-subtle) mb-1">Running on their own</p>
{TASKS.map((t) => (
<div key={t.title} className="rounded-(--chatcn-radius-md) flex items-center gap-3 px-1 py-2">
<span
className={cn(
"grid size-5 shrink-0 place-items-center rounded-full [&_svg]:size-3.5",
t.state === "done" && "bg-(color:--chatcn-green)/15 text-(color:--chatcn-green)",
t.state === "running" && "text-(color:--chatcn-fg-muted)",
t.state === "queued" && "shadow-[inset_0_0_0_1.5px_var(--chatcn-alpha-300)]",
)}
>
{t.state === "done" ? <CheckIcon /> : t.state === "running" ? <LoaderCircleIcon className="animate-spin" /> : null}
</span>
<span className="flex min-w-0 flex-1 flex-col">
<span className="text-[0.875rem]/[1.25rem] tracking-[-0.003em] text-(color:--chatcn-fg) truncate">{t.title}</span>
<span className="text-[0.75rem]/[1rem] text-(color:--chatcn-fg-subtle)">{t.meta}</span>
</span>
</div>
))}
</div>
)
}
const iconNode3: IconNode = [
["path", {"d":"M6 2.75V15"}],
["path", {"d":"M3 18a3 3 0 1 0 6 0 3 3 0 1 0-6 0"}],
["path", {"d":"M15 6a3 3 0 1 0 6 0 3 3 0 1 0-6 0"}],
["path", {"d":"M15 6a9 9 0 0 0-9 9"}],
]
const GitBranchIcon: Icon = /* @__PURE__ */ createIcon("git-branch", iconNode3)
const FILES = [
{ path: "src/app/runs/page.tsx", add: 24, del: 6 },
{ path: "src/lib/pagination.ts", add: 41, del: 0 },
{ path: "src/lib/pagination.test.ts", add: 58, del: 0 },
]
const iconNode4: IconNode = [
["path", {"d":"M7 2.5h5.88a1.5 1.5 0 0 1 1.06.44l5.12 5.12a1.5 1.5 0 0 1 .44 1.06V19a2.5 2.5 0 0 1-2.5 2.5H7A2.5 2.5 0 0 1 4.5 19V5A2.5 2.5 0 0 1 7 2.5"}],
["path", {"d":"M13.5 3.25v3.5a1.75 1.75 0 0 0 1.75 1.75h3.5"}],
["path", {"d":"m10 12-1.5 1.88a1 1 0 0 0 0 1.24L10 17"}],
["path", {"d":"m14 12 1.5 1.88a1 1 0 0 1 0 1.24L14 17"}],
]
const FileCodeIcon: Icon = /* @__PURE__ */ createIcon("file-code", iconNode4)
function Code() {
return (
<div className="flex flex-col gap-3">
<div className="text-[0.8125rem]/[1.25rem] text-(color:--chatcn-fg-muted) flex items-center gap-2">
<span className="font-mono">quarry/web</span>
<span className="text-(color:--chatcn-fg-faint)">/</span>
<span className="flex items-center gap-1 font-mono [&_svg]:size-3.5">
<GitBranchIcon />
fix/runs-pagination
</span>
</div>
<p className="text-[0.875rem]/[1.25rem] tracking-[-0.003em] text-(color:--chatcn-fg)">
Switched the runs list to cursor pagination, so rows no longer repeat while runs finish.
Tests pass.
</p>
<div className="rounded-(--chatcn-radius-lg) shadow-(--chatcn-shadow-border) flex flex-col">
{FILES.map((f, i) => (
<div
key={f.path}
className={cn("flex items-center gap-2.5 px-3 py-2", i > 0 && "border-(color:--chatcn-border) border-t")}
>
<FileCodeIcon className="text-(color:--chatcn-fg-subtle) size-4 shrink-0" />
<span className="text-[0.8125rem]/[1.25rem] text-(color:--chatcn-fg) flex-1 truncate font-mono">{f.path}</span>
<span className="text-[0.75rem]/[1rem] text-(color:--chatcn-green) font-mono tabular-nums">+{f.add}</span>
<span className="text-[0.75rem]/[1rem] text-(color:--chatcn-red) w-6 font-mono tabular-nums">
{f.del ? `-${f.del}` : ""}
</span>
</div>
))}
</div>
</div>
)
}
const VIEWS: Record<string, { title: string; body: React.ReactNode }> = {
chat: { title: "Interview themes", body: <Chat /> },
work: { title: "Tasks", body: <Work /> },
code: { title: "Runs pagination", body: <Code /> },
}
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>
)
}
/**
* Wrap the app once. After the first tooltip opens, the next ones open instantly, the way
* native toolbars behave.
*/
function TooltipProvider({
delay = 500,
...props
}: React.ComponentProps<typeof TooltipPrimitive.Provider>) {
return <TooltipPrimitive.Provider delay={delay} closeDelay={0} {...props} />
}
/** The pointer itself. Put it last inside the stage, which must be `relative`. */
function Ghost({ ghost }: { ghost: GhostState }) {
return (
<div
aria-hidden
className="pointer-events-none absolute top-0 left-0 z-20"
style={{
transform: `translate(${ghost.x}px, ${ghost.y}px)`,
opacity: ghost.shown ? 1 : 0,
// Hidden, it jumps; shown, it glides.
transition: ghost.shown
? "transform 620ms cubic-bezier(0.4, 0, 0.2, 1), opacity 220ms ease-out"
: "opacity 220ms ease-out",
}}
>
<svg
width="18"
height="20"
viewBox="0 0 18 20"
className="drop-shadow-[0_1px_2px_rgb(0_0_0/0.25)]"
style={{
transform: ghost.down ? "scale(0.86)" : "scale(1)",
transformOrigin: "2px 2px",
transition: "transform 120ms ease-out",
}}
>
<path
d="M2 1.5 L2 16 L5.9 12.4 L8.6 18.3 L11.2 17.1 L8.6 11.3 L13.9 11.1 Z"
className="fill-[oklch(0.2_0_0)] stroke-white dark:fill-white dark:stroke-[oklch(0.2_0_0)]"
strokeWidth="1.3"
strokeLinejoin="round"
/>
</svg>
</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 desktop assistant with Chat, Work and Code. The pointer switches modes and the pill slides
* across while the window below changes: a conversation, tasks running on their own, then an
* agent's change in a repository. Loops. Click a mode to stop the tour and switch yourself.
*/
export default function AppModeSwitcherPreview() {
const stage = React.useRef<HTMLDivElement>(null)
const g = useGhost(stage)
const [mode, setMode] = React.useState("chat")
const [touring, setTouring] = React.useState(true)
const scripted = React.useRef(false)
useUnscaledPill(stage, mode)
useLoop(async (wait) => {
await wait(1400)
for (const next of ["work", "code", "chat"]) {
const el = stage.current?.querySelector<HTMLElement>(`[role="radio"][data-mode="${next}"]`)
if (!el) return
g.moveTo(el)
await wait(700)
g.press(true)
await wait(120)
scripted.current = true
el.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true, detail: 1 }))
scripted.current = false
g.press(false)
await wait(400)
g.hide()
await wait(2600)
}
}, touring)
// The segments carry no mode id of their own; tag them so the tour can find each one.
React.useLayoutEffect(() => {
const radios = stage.current?.querySelectorAll<HTMLElement>('[data-slot="app-mode-switcher"] [role="radio"]')
radios?.forEach((el, i) => el.setAttribute("data-mode", ["chat", "work", "code"][i] ?? ""))
}, [])
const view = VIEWS[mode]!
return (
<FitFrame minWidth="38rem">
<div className="flex w-full flex-col items-center justify-center gap-4 p-6">
<TooltipProvider>
<div
ref={stage}
className="rounded-(--chatcn-radius-xl) shadow-(--chatcn-shadow-border) bg-(color:--chatcn-bg) relative flex h-[19.5rem] w-full max-w-xl flex-col overflow-hidden"
onPointerDownCapture={() => {
if (scripted.current || !touring) return
setTouring(false)
g.hide()
}}
>
<div className="border-(color:--chatcn-border) bg-(color:--chatcn-bg-subtle) grid h-12 shrink-0 grid-cols-[1fr_auto_1fr] items-center border-b px-4">
<span className="text-[0.8125rem]/[1.25rem] text-(color:--chatcn-fg-muted) truncate">{view.title}</span>
<AppModeSwitcher value={mode} onValueChange={setMode} />
<span />
</div>
<div key={mode} className="flex-1 overflow-hidden px-6 py-5 transition-opacity duration-300 starting:opacity-0">
{view.body}
</div>
<Ghost ghost={g.ghost} />
</div>
</TooltipProvider>
<MoreOn slug="app-mode-switcher">Switch an assistant between chat, tasks and code. On</MoreOn>
</div>
</FitFrame>
)
}
















