HextaUI

Code blocks for AI answers. Highlighting keeps up with streaming, diffs can be accepted or rejected, and commands run in a terminal.

Category
AI
Components used
7
Files
12
Usage examples
4
Access
HextaUI Pro (55 blocks)
Source updated
Open in new tab

Part of HextaUI Pro, all 55 blocks, $79 one-time, Compare plans

Code in an AI answer arrives a few characters at a time, often as a diff someone has to approve. Code Block highlights while it streams, follows new lines unless the reader has scrolled up, and keeps copy, download and wrap out of the way until the code is complete.

Highlighting uses Shiki with GitHub’s light and dark themes, loaded per language on demand. Only new lines are tokenized as text arrives, so long files stay fast, and both themes render at once so switching color scheme never flashes. Blocks longer than 16 lines fold behind “Show all”.

Pass a unified diff and you get old and new line numbers, a change count and tinted rows; copying gives the new version, not the diff. Add a review and the reader can accept or reject the change, with ⌘↵ and ⌘⌫ while the block has focus. CodeFence plugs the same block into Streamdown, and CodeTerminal shows commands with their output and exit code.

CodeTerminal reads the ANSI codes that test runners and package managers print: bold, dim, italic, underline, the 16 colours mapped to theme tokens that read well in light and dark, 256 colours and truecolor. Carriage returns overwrite the line, so progress bars and spinners settle on their last state, OSC 8 links become real links, and a code split across two chunks never flashes on screen. Copy gives plain text, and long output folds behind “Show all”.

  1. Get HextaUI Pro

    One payment unlocks every block, including future ones. See pricing.

  2. Add the Pro registry to components.json

    components.json
    {
      "registries": {
        "@hextaui-pro": {
          "url": "https://hextaui.com/r/pro/{name}.json",
          "headers": {
            "Authorization": "Bearer ${HEXTAUI_PRO_TOKEN}"
          }
        }
      }
    }
  3. Add your token

    Create a token on your account page and put it in .env.local as HEXTAUI_PRO_TOKEN.

  4. Add the block

    pnpm dlx shadcn@latest add @hextaui-pro/code-block

In Markdown with Streamdown

Register CodeFence as a renderer. It reads the language and fence settings like title="app/page.tsx", {2,4-6} and showLineNumbers, and keeps highlighting while the fence is still streaming.

"use client"

import { Streamdown } from "streamdown"

import { CodeFence, codeFenceLanguages } from "@/components/blocks/code-block/code-fence"

export function Answer({
  markdown,
  streaming,
}: {
  markdown: string
  streaming: boolean
}) {
  return (
    <Streamdown
      mode="streaming"
      isAnimating={streaming}
      plugins={{
        renderers: [{ language: codeFenceLanguages, component: CodeFence }],
      }}
    >
      {markdown}
    </Streamdown>
  )
}

Reviewing a change

Show a proposed edit as a diff and let the reader accept or reject it, with ⌘↵ and ⌘⌫ while the block has focus.

"use client"

import * as React from "react"

import { CodeBlock, type ReviewStatus } from "@/components/blocks/code-block/code-block"

export function ProposedEdit({
  patch,
  onAccept,
  onReject,
}: {
  patch: string
  onAccept: () => Promise<void>
  onReject: () => void
}) {
  const [status, setStatus] = React.useState<ReviewStatus>("pending")

  return (
    <CodeBlock
      code={patch}
      language="tsx"
      filename="components/search.tsx"
      diff
      review={{
        status,
        onAccept: async () => {
          await onAccept()
          setStatus("accepted")
        },
        onReject: () => {
          onReject()
          setStatus("rejected")
        },
      }}
    />
  )
}

Streaming a command with the AI SDK

Write the command’s output as a data-terminal part keyed by the tool call id, so each write replaces the last and the terminal follows along. Pass onClear to add a Clear action.

"use client"

import { useChat } from "@ai-sdk/react"
import type { UIMessage } from "ai"

import { CodeTerminal } from "@/components/blocks/code-block/code-terminal"

type TerminalRun = {
  command: string
  output: string
  exitCode?: number
}

type ChatMessage = UIMessage<unknown, { terminal: TerminalRun }>

export function CommandRuns() {
  const { messages, setMessages } = useChat<ChatMessage>()

  const clear = (messageId: string, partId?: string) =>
    setMessages((list) =>
      list.map((message) =>
        message.id !== messageId
          ? message
          : {
              ...message,
              parts: message.parts.map((part) =>
                part.type === "data-terminal" && part.id === partId
                  ? { ...part, data: { ...part.data, output: "" } }
                  : part
              ),
            }
      )
    )

  return messages.flatMap((message) =>
    message.parts.map((part, index) =>
      part.type === "data-terminal" ? (
        <CodeTerminal
          key={part.id ?? `${message.id}-${index}`}
          command={part.data.command}
          output={part.data.output}
          running={part.data.exitCode === undefined}
          exitCode={part.data.exitCode}
          onClear={() => clear(message.id, part.id)}
        />
      ) : null
    )
  )
}

On its own

Pass the code and language directly, for example when a tool call returns file contents.

import { CodeBlock } from "@/components/blocks/code-block/code-block"

export function FileContents({ path, contents }: { path: string; contents: string }) {
  return (
    <CodeBlock
      code={contents}
      language={path.split(".").pop()}
      filename={path}
      lineNumbers
      highlight={[3, 4]}
    />
  )
}

Anatomy

The parts you compose, from the outside in.

PartDescription
CodeBlockThe block itself: header, actions, code and the optional review bar.
CodeFenceA Streamdown renderer that turns fenced code into a CodeBlock.
CodeTerminalA command with its streaming output and exit status.
parseAnsi, stripAnsiTurn terminal output into styled lines, or into the plain text it shows.
CopyButton, DownloadButton, WrapToggleThe header actions, exported for your own headers.
LanguageIconThe language mark used in the header.
PropTypeDefault
codeThe source, or a unified diff when diff is set.
string–
languageShiki language id or alias, such as tsx, py or bash. Unknown ids render as plain text.
string–
filenameShown in the header and used for downloads.
string–
streamingKeeps highlighting incremental, follows new lines and disables the actions.
booleanfalse
diffTreat code as a unified diff.
booleanfalse
lineNumbersShow line numbers. Diffs show them unless set to false.
boolean–
startLineNumber of the first line.
number1
highlightLine numbers to mark.
number[][]
defaultWrapStart with long lines wrapped.
booleanfalse
collapseAfterCollapse when longer than this many lines. 0 never collapses.
number16
actionsExtra controls in the header, before the built-in ones.
ReactNode–
onApplyShows an Apply button that confirms with “Applied”.
() => unknown–
reviewShows the review bar while pending, and a badge once accepted or rejected.
CodeBlockReview–
PropTypeDefault
statusThe current decision.
"pending" | "accepted" | "rejected"–
onAcceptCalled from Accept or ⌘↵.
() => void–
onRejectCalled from Reject or ⌘⌫.
() => void–

CodeFence

Register with Streamdown: plugins={{ renderers: [{ language: codeFenceLanguages, component: CodeFence }] }}.

PropTypeDefault
codeFence contents, from Streamdown.
string–
languageFence language, from Streamdown.
string–
metaEverything after the language: title="…", {1,3-5}, showLineNumbers, startLine=10.
string–
isIncompleteTrue while the fence is still open.
boolean–
PropTypeDefault
commandThe command that ran.
string–
outputOutput so far, ANSI codes included. Append as it streams.
string""
runningShows Running in the header and follows new output unless the reader has scrolled up.
booleanfalse
exitCodeShown in the header when finished. Anything but 0 is marked as failed.
number–
titleHeader label.
string"Terminal"
collapseAfterFold behind “Show all” when longer than this many lines. 0 never folds.
number12
onClearShows a Clear action. Empty output in your own state.
() => void–
KeyAction
TabMoves through the header actions, the code area and Show all.
⌘↵Accepts a pending review while focus is inside the block.
⌘⌫Rejects a pending review while focus is inside the block.
←→Scrolls long lines when the code area has focus.
  • The code area is a focusable region named after the file, for example “app/page.tsx code”, so keyboard users can scroll it.
  • Changed lines don’t rely on color. The + and − markers are visual only, and screen readers hear “added” or “removed” before each changed line instead.
  • Copy announces “Copied” and every icon button has a label and a tooltip.
  • Review shortcuts are ignored while typing in a field, so they never steal keystrokes.
  • In CodeTerminal the header status is announced, “Running” and then “Exited with code 1”, links from the output say they open in a new tab, and colours from the output are theme tokens with readable contrast in light and dark.

Built with

The free HextaUI components Code Block is made from. Each one installs on its own.

Code

12 files, added to components/blocks/code-block.