API snippet

An interactive code sample panel for API docs. Language tabs (cURL, JavaScript, Python, Go or your own) with a sliding underline sit above the code, which crossfades when you switch. A small parameter form beside the code, or behind a 'Parameters' disclosure in narrow containers, edits values that are templated into every language live; changed lines get a left accent bar and the changed tokens flash briefly, with a screen-reader note that the line was updated. A built-in tokenizer colours strings, numbers, keywords, keys and comments from the chart tokens, so it follows the theme without a highlighting dependency. An optional Response tab shows a templated sample body with a status pill. Copy morphs its icon into a check and announces 'Copied', the chosen language can be remembered in localStorage, and the tabs are a proper keyboard tablist.

Tables & dataComponentTailwind v4

Source

import * as React from "react";
import { Check, ChevronDown, Copy } from "lucide-react";
import { cn } from "@/lib/utils";

export type SnippetParams = Record<string, string>;
export type SnippetParam = {
  name: string;
  label: string;
  type: "text" | "number" | "select";
  options?: string[];
  default: string | number;
};

export type ApiSnippetProps = {
  /** One template per language, called with the current parameter values. */
  snippets: Record<string, (params: SnippetParams) => string>;
  params?: SnippetParam[];
  /** A sample response body, templated like the snippets. */
  response?: (params: SnippetParams) => string;
  /** e.g. "201 Created". */
  responseStatus?: string;
  /** Tab names; defaults cover curl, javascript, python and go. */
  labels?: Record<string, string>;
  defaultLang?: string;
  /** localStorage key that remembers the chosen language across pages. */
  persistLang?: string;
  title?: string;
  method?: string;
  path?: string;
  /** Controlled parameter values. */
  values?: SnippetParams;
  onValuesChange?: (values: SnippetParams) => void;
  className?: string;
};

const LABELS: Record<string, string> = { curl: "cURL", javascript: "JavaScript", js: "JavaScript", python: "Python", go: "Go", ruby: "Ruby", php: "PHP" };
const RESPONSE = "__response";
const FLASH_MS = 1800;
const ring = "outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-card";

/* ---------- a small tokenizer: enough colour to read, nothing more ---------- */
type TokenType = "comment" | "string" | "key" | "number" | "keyword" | "flag" | "text";
type Token = { type: TokenType; text: string };
const KEYWORDS = new Set(
  "const let var await async function return import from export def print package func if else nil None True False true false null new for in range type struct with as try catch curl".split(" "),
);
const RULES: [TokenType, RegExp][] = [
  ["comment", /^(\/\/.*|#.*)/],
  ["string", /^("(?:\\.|[^"\\])*"?|'(?:\\.|[^'\\])*'?|`(?:\\.|[^`\\])*`?)/],
  ["number", /^-?\d+(?:\.\d+)?\b/],
  ["flag", /^--?[A-Za-z][\w-]*/],
  ["text", /^[A-Za-z_$][\w$.]*/],
  ["text", /^\s+/],
  ["text", /^[^\sA-Za-z_$"'`#/\d-]+|^./],
];

function tokenize(line: string): Token[] {
  const tokens: Token[] = [];
  let rest = line;
  while (rest) {
    for (const [type, rule] of RULES) {
      const match = rule.exec(rest);
      if (!match) continue;
      let kind = type;
      const text = match[0];
      if (type === "text" && KEYWORDS.has(text)) kind = "keyword";
      if (type === "string" && /^\s*:/.test(rest.slice(text.length))) kind = "key";
      tokens.push({ type: kind, text });
      rest = rest.slice(text.length);
      break;
    }
  }
  return tokens;
}

const COLORS: Record<TokenType, React.CSSProperties | undefined> = {
  comment: { color: "var(--muted-foreground)", fontStyle: "italic" },
  string: { color: "color-mix(in oklab, var(--chart-2) 78%, var(--foreground))" },
  key: { color: "var(--foreground)", fontWeight: 500 },
  number: { color: "color-mix(in oklab, var(--chart-1) 80%, var(--foreground))" },
  keyword: { color: "color-mix(in oklab, var(--chart-4) 62%, var(--foreground))", fontWeight: 500 },
  flag: { color: "color-mix(in oklab, var(--chart-5) 70%, var(--foreground))" },
  text: undefined,
};

type Flash = { tab: string; at: number; lines: Map<number, Set<number>> };

/* Marks lines that differ, and inside them the tokens that differ. */
function diff(before: string, after: string) {
  const a = before.split("\n");
  const b = after.split("\n");
  const lines = new Map<number, Set<number>>();
  b.forEach((line, index) => {
    if (a[index] === line) return;
    const left = tokenize(a[index] || "");
    const right = tokenize(line);
    const marks = new Set<number>();
    right.forEach((token, t) => {
      if (left[t]?.text !== token.text && token.text.trim()) marks.add(t);
    });
    lines.set(index, marks);
  });
  return lines;
}

function read(key?: string) {
  if (!key) return null;
  try {
    return window.localStorage.getItem(key);
  } catch {
    return null;
  }
}
function write(key: string | undefined, value: string) {
  if (!key) return;
  try {
    window.localStorage.setItem(key, value);
  } catch {
    /* storage can be blocked; the choice just is not remembered */
  }
}

export function ApiSnippet({
  snippets,
  params = [],
  response,
  responseStatus = "200 OK",
  labels,
  defaultLang,
  persistLang,
  title,
  method,
  path,
  values: controlled,
  onValuesChange,
  className,
}: ApiSnippetProps) {
  const langs = Object.keys(snippets);
  const tabs = response ? [...langs, RESPONSE] : langs;
  const [tab, setTab] = React.useState(defaultLang && langs.includes(defaultLang) ? defaultLang : langs[0]);
  const [inner, setInner] = React.useState<SnippetParams>(() => Object.fromEntries(params.map((param) => [param.name, String(param.default)])));
  const values = controlled || inner;
  const [flash, setFlash] = React.useState<Flash | null>(null);
  const [copied, setCopied] = React.useState(false);
  const [paramsOpen, setParamsOpen] = React.useState(false);
  const [switched, setSwitched] = React.useState(false);
  const [bar, setBar] = React.useState({ left: 0, width: 0 });
  const previous = React.useRef(values);
  const tabRefs = React.useRef(new Map<string, HTMLButtonElement>());
  const listRef = React.useRef<HTMLDivElement>(null);
  const id = React.useId();

  React.useEffect(() => {
    const saved = read(persistLang);
    if (saved && langs.includes(saved)) setTab(saved);
  }, [persistLang]);

  const source = (which: string, params: SnippetParams) => (which === RESPONSE ? response?.(params) ?? "" : snippets[which]?.(params) ?? "");
  const code = source(tab, values);

  /* When a parameter changes, flash what changed in the visible tab. */
  React.useEffect(() => {
    const before = previous.current;
    previous.current = values;
    if (before === values) return;
    const lines = diff(source(tab, before), source(tab, values));
    if (!lines.size) return;
    const at = Date.now();
    setFlash({ tab, at, lines });
    const timer = setTimeout(() => setFlash((current) => (current?.at === at ? null : current)), FLASH_MS);
    return () => clearTimeout(timer);
  }, [values]);

  /* Sliding underline under the active tab. */
  React.useLayoutEffect(() => {
    const measure = () => {
      const element = tabRefs.current.get(tab);
      if (element) setBar({ left: element.offsetLeft, width: element.offsetWidth });
    };
    measure();
    const observer = new ResizeObserver(measure);
    if (listRef.current) observer.observe(listRef.current);
    return () => observer.disconnect();
  }, [tab, tabs.length]);

  const choose = (next: string) => {
    setTab(next);
    setSwitched(true);
    setFlash(null);
    setCopied(false);
    if (next !== RESPONSE) write(persistLang, next);
  };

  const update = (name: string, value: string) => {
    const next = { ...values, [name]: value };
    if (!controlled) setInner(next);
    onValuesChange?.(next);
  };

  const copy = async () => {
    try {
      await navigator.clipboard.writeText(code);
      setCopied(true);
      setTimeout(() => setCopied(false), 1600);
    } catch {
      setCopied(false);
    }
  };

  const onTabKey = (event: React.KeyboardEvent) => {
    const index = tabs.indexOf(tab);
    const map: Record<string, number> = { ArrowRight: index + 1, ArrowLeft: index - 1, Home: 0, End: tabs.length - 1 };
    if (!(event.key in map)) return;
    event.preventDefault();
    const next = tabs[(map[event.key] + tabs.length) % tabs.length];
    choose(next);
    tabRefs.current.get(next)?.focus();
  };

  const label = (key: string) => (key === RESPONSE ? "Response" : labels?.[key] || LABELS[key] || key);
  const lines = code.split("\n");
  const activeFlash = flash?.tab === tab ? flash : null;

  const form = params.length > 0 && (
    <div className="space-y-3.5">
      {params.map((param) => {
        const fieldId = `${id}-${param.name}`;
        const field = "h-9 w-full rounded-md border border-input bg-background px-2.5 text-sm text-foreground shadow-xs outline-none transition-colors focus-visible:border-ring focus-visible:ring-2 focus-visible:ring-ring/40";
        return (
          <div key={param.name}>
            <label htmlFor={fieldId} className="flex items-baseline justify-between gap-2 text-[13px] font-medium">
              {param.label}
              <code className="font-mono text-[11px] font-normal text-muted-foreground">{param.name}</code>
            </label>
            {param.type === "select" ? (
              <div className="relative mt-1.5">
                <select id={fieldId} value={values[param.name]} onChange={(event) => update(param.name, event.target.value)} className={cn(field, "appearance-none pr-8")}>
                  {param.options?.map((option) => <option key={option} value={option}>{option}</option>)}
                </select>
                <ChevronDown className="pointer-events-none absolute right-2.5 top-1/2 size-4 -translate-y-1/2 text-muted-foreground" aria-hidden="true" />
              </div>
            ) : (
              <input
                id={fieldId}
                type={param.type === "number" ? "number" : "text"}
                inputMode={param.type === "number" ? "decimal" : undefined}
                value={values[param.name]}
                onChange={(event) => update(param.name, event.target.value)}
                spellCheck={false}
                className={cn(field, "mt-1.5", param.type === "number" ? "tabular-nums" : "font-mono text-[13px]")}
              />
            )}
          </div>
        );
      })}
    </div>
  );

  return (
    <section className={cn("@container overflow-hidden rounded-xl border border-border bg-card text-card-foreground shadow-sm", className)} aria-label={title || "Code sample"}>
      <style href="chm-api-snippet" precedence="default">{`@keyframes chm-as-in{from{opacity:0}to{opacity:1}}@keyframes chm-as-line{from{background:color-mix(in oklab,var(--chart-2) 16%,transparent)}to{background:color-mix(in oklab,var(--chart-2) 5%,transparent)}}@keyframes chm-as-tok{0%,40%{background:color-mix(in oklab,var(--chart-2) 32%,transparent)}to{background:transparent}}`}</style>
      {(title || path) && (
        <header className="flex flex-wrap items-center gap-x-3 gap-y-1 border-b border-border px-4 py-3">
          {method && <span className="rounded-md bg-[color-mix(in_oklab,var(--chart-2)_16%,transparent)] px-1.5 py-0.5 font-mono text-[11px] font-semibold text-[color-mix(in_oklab,var(--chart-2)_70%,var(--foreground))]">{method}</span>}
          {path && <code className="font-mono text-[13px]">{path}</code>}
          {title && <h3 className="ml-auto text-sm text-muted-foreground">{title}</h3>}
        </header>
      )}

      <div className="grid @2xl:grid-cols-[15rem_minmax(0,1fr)]">
        {params.length > 0 && (
          <div className="border-b border-border bg-muted/30 @2xl:border-b-0 @2xl:border-r">
            <button
              type="button"
              aria-expanded={paramsOpen}
              aria-controls={`${id}-form`}
              onClick={() => setParamsOpen((open) => !open)}
              className={cn("flex w-full items-center justify-between px-4 py-2.5 text-[13px] font-medium @2xl:hidden", ring)}
            >
              <span>
                Parameters <span className="ml-1 font-normal text-muted-foreground">{params.length}</span>
              </span>
              <ChevronDown className={cn("size-4 text-muted-foreground transition-transform", paramsOpen && "rotate-180")} aria-hidden="true" />
            </button>
            <div id={`${id}-form`} className={cn("px-4 pb-4 @2xl:block @2xl:pt-4", paramsOpen ? "block" : "hidden")}>
              <p className="mb-3 hidden text-[11px] font-medium uppercase tracking-wide text-muted-foreground @2xl:block">Parameters</p>
              {form}
            </div>
          </div>
        )}

        <div className="flex min-w-0 flex-col">
          <div className="flex items-center gap-2 border-b border-border pr-2">
            <div ref={listRef} role="tablist" aria-label="Language" onKeyDown={onTabKey} className="relative flex min-w-0 flex-1 overflow-x-auto px-2 [scrollbar-width:none]">
              {tabs.map((key) => (
                <button
                  key={key}
                  ref={(element) => {
                    if (element) tabRefs.current.set(key, element);
                    else tabRefs.current.delete(key);
                  }}
                  id={`${id}-tab-${key}`}
                  type="button"
                  role="tab"
                  aria-selected={tab === key}
                  aria-controls={`${id}-panel`}
                  tabIndex={tab === key ? 0 : -1}
                  onClick={() => choose(key)}
                  className={cn(
                    "relative shrink-0 whitespace-nowrap rounded-md px-2.5 py-3 text-[13px] @md:px-3 transition-colors",
                    tab === key ? "font-medium text-foreground" : "text-muted-foreground hover:text-foreground",
                    key === RESPONSE && "ml-auto",
                    "outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring",
                  )}
                >
                  {label(key)}
                </button>
              ))}
              <span
                aria-hidden="true"
                className="absolute bottom-0 h-0.5 rounded-full bg-foreground motion-safe:transition-[left,width] motion-safe:duration-300 motion-safe:ease-[cubic-bezier(.3,.9,.3,1)]"
                style={{ left: bar.left + 8, width: Math.max(bar.width - 16, 0) }}
              />
            </div>
            {tab === RESPONSE && (
              <span className="shrink-0 rounded-full bg-emerald-500/12 px-2 py-0.5 font-mono text-[11px] font-medium text-emerald-700 dark:text-emerald-300">{responseStatus}</span>
            )}
            <button
              type="button"
              onClick={copy}
              aria-label={copied ? "Copied" : `Copy ${label(tab)}`}
              className={cn("relative grid size-8 shrink-0 place-items-center rounded-md text-muted-foreground hover:bg-accent hover:text-foreground", ring)}
            >
              <Copy className={cn("absolute size-4 transition-all duration-200 motion-reduce:transition-none", copied ? "rotate-[-30deg] scale-50 opacity-0" : "opacity-100")} aria-hidden="true" />
              <Check className={cn("absolute size-4 text-emerald-600 transition-all duration-200 motion-reduce:transition-none dark:text-emerald-400", copied ? "scale-100 opacity-100" : "rotate-[30deg] scale-50 opacity-0")} aria-hidden="true" />
            </button>
          </div>

          <div id={`${id}-panel`} role="tabpanel" aria-labelledby={`${id}-tab-${tab}`} className="flex-1 bg-muted/25">
            <pre
              key={tab}
              aria-label={`${label(tab)} ${tab === RESPONSE ? "example response" : "code sample"}`}
              tabIndex={0}
              className={cn("max-h-[26rem] overflow-auto py-3 font-mono text-[12.5px] leading-6 outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring", switched && "motion-safe:animate-[chm-as-in_.22s_ease-out]")}
            >
              <code className="block min-w-max">
                {lines.map((line, index) => {
                  const marks = activeFlash?.lines.get(index);
                  return (
                    <span
                      key={`${index}-${activeFlash && marks ? activeFlash.at : 0}`}
                      className={cn(
                        "flex border-l-2 pr-4",
                        marks ? "border-[color-mix(in_oklab,var(--chart-2)_80%,var(--foreground))] motion-safe:animate-[chm-as-line_1.8s_ease-out_forwards] motion-reduce:bg-[color-mix(in_oklab,var(--chart-2)_8%,transparent)]" : "border-transparent",
                      )}
                    >
                      <span className="w-10 shrink-0 select-none pr-3 text-right text-muted-foreground/50 tabular-nums" aria-hidden="true">{index + 1}</span>
                      <span className="whitespace-pre">
                        {tokenize(line).map((token, t) => (
                          <span
                            key={t}
                            style={COLORS[token.type]}
                            className={cn(marks?.has(t) && "rounded-sm motion-safe:animate-[chm-as-tok_1.8s_ease-out_forwards] motion-reduce:underline motion-reduce:decoration-[var(--chart-2)] motion-reduce:underline-offset-4")}
                          >
                            {token.text}
                          </span>
                        ))}
                        {line === "" && " "}
                        {marks && <span className="sr-only"> (line updated)</span>}
                      </span>
                    </span>
                  );
                })}
              </code>
            </pre>
          </div>
        </div>
      </div>
      <p className="sr-only" role="status" aria-live="polite">{copied ? "Copied" : ""}</p>
    </section>
  );
}