Skip to content

The platform for continuously improving AI agents.

5.7 KB
Raw Blame
import { useEffect, useId, useMemo, useState } from "react";

import type { HighlightResult } from "@streamdown/code";

import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
import { Icon } from "@/components/ui/icons";
import { cn } from "@/lib/utils";

export function CodeCopyButton({ label, source }: { label: string; source: string }) {
  const [copyState, setCopyState] = useState("");
  useEffect(() => {
    if (!copyState) return;
    const timer = setTimeout(() => setCopyState(""), 1600);
    return () => clearTimeout(timer);
  }, [copyState]);

  return (
    <>
      <Button
        aria-label={`Copy ${label}`}
        onClick={async () => {
          try {
            await navigator.clipboard.writeText(source);
            setCopyState("Copied");
          } catch {
            setCopyState("Copy failed");
          }
        }}
        size="icon-xs"
        variant="ghost"
      >
        {copyState === "Copied" ? (
          <Icon.success aria-hidden />
        ) : copyState ? (
          <Icon.warning aria-hidden />
        ) : (
          <Icon.copy aria-hidden />
        )}
      </Button>
      <span aria-live="polite" className="sr-only">
        {copyState}
      </span>
    </>
  );
}

// File diff's source view: one gutter, with no change markers for unmodified code.
export function FileCode({
  source,
  language = "text",
  title = language,
}: {
  source: string;
  language?: string;
  title?: string;
}) {
  const [open, setOpen] = useState(true);
  const [all, setAll] = useState(false);
  const [highlighted, setHighlighted] = useState<{
    source: string;
    language: string;
    result: HighlightResult;
  } | null>(null);
  const id = useId();
  const lines = useMemo(() => source.split("\n"), [source]);
  const visible = all ? lines : lines.slice(0, 200);

  useEffect(() => {
    if (!open || source.length > 200_000 || language === "text") return;
    let active = true;
    void import("@/lib/code-highlighting")
      .then(({ workshopCode }) => {
        const supported = workshopCode.getSupportedLanguages().find((item) => item === language);
        if (!active || !supported) return;
        const apply = (result: HighlightResult) => {
          if (active) setHighlighted({ language, result, source });
        };
        const result = workshopCode.highlight(
          { code: source, language: supported, themes: ["github-dark", "github-dark"] },
          apply
        );
        if (result) apply(result);
      })
      .catch(() => undefined);
    return () => {
      active = false;
    };
  }, [language, open, source]);

  const tokens =
    highlighted?.source === source && highlighted.language === language
      ? highlighted.result.tokens
      : null;

  return (
    <Card aria-label={title} className="min-w-0 p-2" role="region">
      <div className="flex min-h-6 min-w-0 items-center gap-1.5 text-xs">
        <button
          aria-controls={id}
          aria-expanded={open}
          aria-label={`${open ? "Collapse" : "Expand"} ${title}`}
          className="flex min-w-0 flex-1 items-center gap-1.5 rounded-sm text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
          onClick={() => setOpen(!open)}
          type="button"
        >
          <Icon.chevronDown
            aria-hidden
            className={cn(
              "size-3 shrink-0 text-muted-foreground transition-transform duration-150 motion-reduce:transition-none",
              !open && "-rotate-90"
            )}
          />
          <span className="truncate font-medium">{title}</span>
        </button>
        {title !== language && language !== "text" && (
          <span className="text-muted-foreground">{language}</span>
        )}
        <CodeCopyButton label={title} source={source} />
      </div>
      <div
        aria-hidden={!open}
        className={cn(
          "grid transition-[grid-template-rows,opacity] duration-200 ease-out motion-reduce:transition-none",
          open ? "grid-rows-[1fr] opacity-100" : "grid-rows-[0fr] opacity-0"
        )}
        id={id}
        inert={!open}
      >
        <div className="min-h-0 overflow-hidden">
          <div
            className="mt-2 max-h-80 overflow-auto scroll-fade-y rounded-sm border border-border bg-background py-1 font-mono text-xs leading-5"
            tabIndex={open ? 0 : -1}
          >
            <div className="grid min-w-full w-max grid-cols-[2.5rem_minmax(max-content,1fr)]">
              <div
                aria-hidden
                className="sticky left-0 z-10 select-none bg-background pr-2 text-right tabular-nums text-muted-foreground"
              >
                {visible.map((_, index) => (
                  <div key={index}>{index + 1}</div>
                ))}
              </div>
              <pre className="m-0 whitespace-pre px-2 font-mono text-xs leading-5">
                <code>
                  {visible.map((line, index) => (
                    <span key={index}>
                      {tokens?.[index]?.map((token, tokenIndex) => (
                        <span
                          key={tokenIndex}
                          style={{ color: token.color ?? token.htmlStyle?.color }}
                        >
                          {token.content}
                        </span>
                      )) ?? line}
                      {index < visible.length - 1 ? "\n" : ""}
                    </span>
                  ))}
                </code>
              </pre>
            </div>
          </div>
          {lines.length > 200 && (
            <Button className="mt-1 w-full" onClick={() => setAll(!all)} size="xs" variant="ghost">
              {all ? "Show first 200 lines" : `Show all ${lines.length} lines`}
            </Button>
          )}
        </div>
      </div>
    </Card>
  );
}