iterate.com / ui

git clone https://git.iterate.com/repos/ui

ui / src / components / code-block.tsxmain at d68d7e1

import { Suspense, lazy } from "react";
import { cn } from "cn";
import type { SerializedObjectCodeBlockProps } from "./code-block.client.tsx";
import type { SourceCodeBlockProps } from "./source-code-block.client.tsx";
import { Spinner } from "#/components/ui/spinner.tsx";

// Keep CodeMirror (languages, theme, search) out of the server bundle: the
// worker script has a 10 MiB upload limit and the editor only mounts in the
// browser anyway. The type-only imports leave no runtime edge.
const LazyCodeBlock = import.meta.env.SSR
  ? () => null
  : // The grammars load with CodeBlock alone, in source-code-block.client.tsx: markdown brings html,
    // css and javascript, which serialized data's chunk (yaml, json) would otherwise carry to the
    // dash's event inspector.
    lazy(async () => ({
      default: (await import("./source-code-block.client.tsx")).SourceCodeBlock,
    }));
const LazySerializedBlock = import.meta.env.SSR
  ? () => null
  : lazy(async () => ({
      default: (await import("./code-block.client.tsx")).SerializedObjectCodeBlock,
    }));

/** Read-only code with search, folding and a copy button (code-block.client.tsx). */
export function CodeBlock(props: SourceCodeBlockProps) {
  return (
    <Suspense fallback={<CodeBlockFallback className={props.className} />}>
      <LazyCodeBlock {...props} />
    </Suspense>
  );
}

/** Any value as YAML or JSON, with a button to copy each (code-block.client.tsx). */
export function SerializedObjectCodeBlock(props: SerializedObjectCodeBlockProps) {
  return (
    <Suspense fallback={<CodeBlockFallback className={props.className} />}>
      <LazySerializedBlock {...props} />
    </Suspense>
  );
}

function CodeBlockFallback({ className }: { className?: string }) {
  return (
    <div className={cn("relative flex min-h-0 flex-col", className)} data-spinner="true">
      <div className="flex min-h-16 items-center gap-2 rounded border px-3 py-2 text-xs text-muted-foreground">
        <Spinner className="size-3.5" />
        <span>Loading code block...</span>
      </div>
    </div>
  );
}