---
title: "Code Block"
description: "Display source code with syntax tokens, highlighted lines, diffs and useful file actions."
---

# Code Block

Display source code with syntax tokens, highlighted lines, diffs and useful file actions.

## Installation

Install the shared package once in your Exact app. This version is a beta.

```sh
bun add --exact @rightui/ui@0.4.0-beta.4
```

Or choose another package manager:

```sh
npm install --save-exact @rightui/ui@0.4.0-beta.4
pnpm add --save-exact @rightui/ui@0.4.0-beta.4
yarn add --exact @rightui/ui@0.4.0-beta.4
```

Exact compilation uses Bun 1.4.2. Register Geist and Newsreader, declare the font marker and add the root provider using [Installation](/docs/installation).

### Manual source setup

Install an editable copy of the complete package:

```sh
mkdir -p vendor/rightui vendor/rightui-ui
npm pack @rightui/ui@0.4.0-beta.4 --pack-destination vendor/rightui
tar -xzf ./vendor/rightui/rightui-ui-0.4.0-beta.4.tgz -C vendor/rightui-ui --strip-components=1
bun add file:./vendor/rightui-ui
```

Keep package.json, the Contract files, ui.tamber, assets and licenses together.

### Import

```contract
use CodeBlock, CodeBlockAdvanced, CodeToken, CodeLine from "@rightui/ui"
```

## Usage

CodeBlock keeps its existing props and adds a line-wrap toggle with clearer diff styling. Use CodeBlockAdvanced for tokenized content, highlighted or added/removed lines, a custom starting line, maximum height and optional file export. CodeToken contains text and tone; CodeLine contains tokens and variant. Supported tones are plain, keyword, string, function, number, comment, type and property. Line variants are default, highlighted, added and removed. Supply tokenized lines from your data or build tooling; language labels the code and does not run a parser. The example uses Shiki-generated tokens with light and dark theme colors. Copy and Download always use the original code string. Keep that string and the tokenized lines in sync. An empty lines array falls back to the code string. The export uses the platform save flow.

## Example

```contract
use FontWeights from "@rightui/ui"
use uiFontFamily, CodeBlock, CodeBlockAdvanced from "@rightui/ui"
use codeBlockDemoCode, codeBlockDemoLines from "./code-block-data.contract"

component Demo
  props
    width: number
    reduced: bool
  inject
    uiWeights: FontWeights
    uiFont: string
  view
    column gap="ui.space-28" min-width=0 width="100%" max-width="32rem" margin="ui.space-0 auto"
      CodeBlockAdvanced(id="content-codeblock", title="app/api/chat/route.ts", language="typescript", code=codeBlockDemoCode(), lines=codeBlockDemoLines(), numbers=true, startLine=1, showDownload=true, maxHeight=440, compact=false, variant="default")
      column gap="ui.space-12" min-width=0
        text "Diff" font-size="ui.text-sm" font-weight=uiWeights.medium font-family=uiFontFamily(uiFont) data-rightui-font="body"
        CodeBlock(id="code-diff", title="greeting.ts", language="typescript", code=" export function greeting(name: string) {\n-  return 'Hello, ' + name\n+  return `Hello, ${name}!`\n }", numbers=false, diff=true)

```

## Keyboard

Tab focuses Wrap lines, Download code when enabled, Copy code and the scrollable code region. Enter or Space activates the focused action. Wrap lines exposes its pressed state.

## API Reference

| Property | Type |
| --- | --- |
| CodeBlock.id | string |
| CodeBlock.title | string |
| CodeBlock.language | string |
| CodeBlock.code | string |
| CodeBlock.numbers | bool |
| CodeBlock.diff | bool |
| CodeBlockAdvanced.id | string |
| CodeBlockAdvanced.title | string |
| CodeBlockAdvanced.language | string |
| CodeBlockAdvanced.code | string |
| CodeBlockAdvanced.lines | CodeLine[] |
| CodeBlockAdvanced.numbers | bool |
| CodeBlockAdvanced.startLine | number |
| CodeBlockAdvanced.showDownload | bool |
| CodeBlockAdvanced.maxHeight | number |
| CodeBlockAdvanced.compact | bool |
| CodeBlockAdvanced.variant | string |

## Clipboard setup

Add this controller once to your app root. All CodeBlock variants share the last copied value and reset their confirmation after three seconds. Merge these providers with uiFont from Installation.

```contract
use defaultFontWeights from "@rightui/ui"
component App
  state copiedId = ""
  state copiedText = ""
  state copyVersion = 0
  provide
    uiFont = "theme"
    uiWeights = defaultFontWeights()
    uiCopiedId = copiedId
    uiCopiedText = copiedText
    uiCopyCode = copyCode
  action copyCode(id: string, text: string)
    copyText(text)
    copiedId = id
    copiedText = text
    copyVersion = copyVersion + 1
  action clearCopyFeedback
    copiedId = ""
    copiedText = ""
  task copiedFeedback when copiedId != "" key=copyVersion
    after(3000, clearCopyFeedback)
  view
    CodeBlock(id="example", title="hello.ts", language="ts", code="console.log('Hello')", numbers=false, diff=false)
```

## Source

File: packages/ui/code-block.contract

```contract
use FontWeights from "./typography-context.contract"
use uiFontFamily from "./typography-context.contract"
use Control from "./styles.contract"

shape CodeToken
  text: string
  tone: string

shape CodeLine
  tokens: CodeToken[]
  variant: string

fn codeTokenColor(tone: string): string = tone == "keyword" ? "ui.code-keyword" : tone == "string" ? "ui.code-string" : tone == "function" ? "ui.code-function" : tone == "number" ? "ui.code-number" : tone == "comment" ? "ui.code-comment" : tone == "type" ? "ui.code-type" : tone == "property" ? "ui.code-property" : "ui.code-foreground"
fn codeLineVariant(line: string, diff: bool): string = diff and line.startsWith("+") ? "added" : diff and line.startsWith("-") ? "removed" : "default"
fn codeLineText(line: string, diff: bool): string = diff and (line.startsWith("+") or line.startsWith("-") or line.startsWith(" ")) ? line.slice(1) : line

component CodeBlockFrame
  props
    id: string
    title: string
    language: string
    code: string
    numbers: bool
    diff: bool
    ai: bool
  view
    CodeBlockView(id=id, title=title, language=language, code=code, lines=[], numbers=numbers, diff=diff, ai=ai, startLine=1, showDownload=false, maxHeight=280, compact=ai, variant="default")

component CodeBlock
  props
    id: string
    title: string
    language: string
    code: string
    numbers: bool
    diff: bool
  view
    CodeBlockFrame(id=id, title=title, language=language, code=code, numbers=numbers, diff=diff, ai=false)

component CodeBlockAI
  props
    id: string
    title: string
    language: string
    code: string
    numbers: bool
    diff: bool
  view
    CodeBlockFrame(id=id, title=title, language=language, code=code, numbers=numbers, diff=diff, ai=true)

component CodeBlockAdvanced
  props
    id: string
    title: string
    language: string
    code: string
    lines: CodeLine[]
    numbers: bool
    startLine: number
    showDownload: bool
    maxHeight: number
    compact: bool
    variant: string
  view
    CodeBlockView(id=id, title=title, language=language, code=code, lines=lines, numbers=numbers, diff=false, ai=false, startLine=startLine, showDownload=showDownload, maxHeight=maxHeight, compact=compact, variant=variant)

component CodeBlockView
  props
    id: string
    title: string
    language: string
    code: string
    lines: CodeLine[]
    numbers: bool
    diff: bool
    ai: bool
    startLine: number
    showDownload: bool
    maxHeight: number
    compact: bool
    variant: string
  inject
    uiWeights: FontWeights
    uiFont: string
    uiCopiedId: string
    uiCopiedText: string
    uiCopyCode: action
  state wrapped = false
  derive copyConfirmed = uiCopiedId == id and uiCopiedText == code
  derive heading = title.trim() != "" ? title : language.trim() != "" ? language : "Code"
  derive filename = title.trim() != "" ? title.split("/").slice(-1).join("") : "code.txt"
  action copy
    uiCopyCode(id, code)
  action toggleWrap
    wrapped = not wrapped
  action download
    saveFile(id + "-file", text=code, suggestedName=filename)
  view
    CodeBlockSurface(id=id, compact=compact, variant=variant, ai=ai)
      CodeBlockHeader(compact=compact)
        row gap="ui.space-6" align-items="center" flex=1 min-width="0px"
          svg width=(compact ? "ui.space-14" : "ui.space-16") height=(compact ? "ui.space-14" : "ui.space-16") flex-shrink=0 viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="ui.stroke-detail" stroke-linecap="round" stroke-linejoin="round" aria-hidden=true
            if language == "sh" or language == "bash" or language == "shell" or language == "text"
              path d="m4 17 6-5-6-5M12 19h8"
            else
              path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8ZM14 2v6h6M10 12l-2 2 2 2M14 12l2 2-2 2"
          text heading testId=(id + "-title") min-width="0px" overflow="hidden" text-overflow="ellipsis" white-space="nowrap" font-size=(compact ? "ui.text-xs" : "ui.text-sm") line-height="ui.leading-normal" font-weight=uiWeights.medium color=(variant == "destructive" ? "ui.danger" : "ui.foreground") font-family=uiFontFamily(uiFont) data-rightui-font="body"
        row gap="ui.space-4" align-items="center" flex-shrink=0 margin="ui.space-negative-4 ui.space-negative-6 ui.space-negative-4 0px"
          button id=(id + "-wrap") testId=(id + "-wrap") class=Control font-weight=uiWeights.medium press=toggleWrap aria-label="Wrap lines" title="Wrap lines" aria-pressed=wrapped aria-controls=(id + "-content") display="flex" align-items="center" justify-content="center" width="ui.space-28" height="ui.space-28" min-height="ui.space-28" padding="0px" border="0" background-color=(wrapped ? "ui.code-highlight" : "transparent") color=(wrapped ? "ui.foreground" : "ui.muted-foreground")
            :hover
              background-color="ui.code-highlight"
            svg width="ui.space-14" height="ui.space-14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="ui.stroke-detail" stroke-linecap="round" stroke-linejoin="round" aria-hidden=true
              path d="M3 6h18M3 11h14a4 4 0 0 1 0 8h-4M3 16h4M13 16l-3 3 3 3"
          if showDownload
            button id=(id + "-download") testId=(id + "-download") class=Control font-weight=uiWeights.medium press=download aria-label="Download code" title="Download code" display="flex" align-items="center" justify-content="center" width="ui.space-28" height="ui.space-28" min-height="ui.space-28" padding="0px" border="0" background-color="transparent" color="ui.muted-foreground"
              :hover
                background-color="ui.code-highlight"
              svg width="ui.space-14" height="ui.space-14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="ui.stroke-detail" stroke-linecap="round" stroke-linejoin="round" aria-hidden=true
                path d="M12 3v12M7 10l5 5 5-5M5 16v3a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2v-3"
          button id=(id + "-copy") testId=(id + "-copy") class=Control font-weight=uiWeights.medium press=copy aria-label=(copyConfirmed ? "Copied" : "Copy code") title=(copyConfirmed ? "Copied" : "Copy code") display="flex" align-items="center" justify-content="center" width="ui.space-28" height="ui.space-28" min-height="ui.space-28" padding="0px" border="0" background-color="transparent" color="ui.muted-foreground"
            :hover
              background-color="ui.code-highlight"
            svg width="ui.space-14" height="ui.space-14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="ui.stroke-detail" stroke-linecap="round" stroke-linejoin="round" aria-hidden=true
              if copyConfirmed
                path d="m20 6-11 11-5-5"
              else
                rect x=8 y=8 width=12 height=12 rx=2
                path d="M16 8V4a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v10a2 2 0 0 0 2 2h4"
      text (copyConfirmed ? "Copied to clipboard" : "") testId=(id + "-copy-status") role="status" aria-live="polite" position="absolute" width="ui.space-1" height="ui.space-1" overflow="hidden" white-space="nowrap" font-family=uiFontFamily(uiFont) data-rightui-font="body"
      if showDownload
        input id=(id + "-file") display="none" aria-hidden=true font-family=uiFontFamily(uiFont) data-rightui-font="body"
      CodeBlockBody(id=id, heading=heading, code=code, lines=lines, numbers=numbers, diff=diff, startLine=startLine, maxHeight=maxHeight, compact=compact, variant=variant, wrapped=wrapped)

component CodeBlockSurface
  props
    id: string
    compact: bool
    variant: string
    ai: bool
  slot
  view
    column id=id testId=id min-width="0px" border-width="ui.border-width" border-style="solid" border-color="ui.border" border-radius=(compact ? "ui.radius-lg" : "ui.radius-2xl") overflow="hidden" background-color=(variant == "destructive" ? "ui.code-destructive-background" : ai ? "ui.background" : "ui.muted") color=(variant == "destructive" ? "ui.danger" : "ui.code-foreground")
      children

component CodeBlockHeader
  props
    compact: bool
  slot
  view
    row gap="ui.space-8" align-items="center" padding=(compact ? "ui.space-12 ui.space-12 0px" : "ui.space-16 ui.space-16 0px") min-width="0px"
      children

component CodeBlockBody
  props
    id: string
    heading: string
    code: string
    lines: CodeLine[]
    numbers: bool
    diff: bool
    startLine: number
    maxHeight: number
    compact: bool
    variant: string
    wrapped: bool
  derive plainCode = code.endsWith("\n") ? code.slice(0, -1) : code
  derive plainLines = plainCode.split("\n").map(line => CodeLine(tokens=[CodeToken(text=codeLineText(line, diff), tone="plain")], variant=codeLineVariant(line, diff)))
  derive displayLines = lines.length > 0 ? lines : plainLines
  derive lineStart = max(1, floor(startLine))
  derive numberWidth = max(2, (lineStart + displayLines.length - 1).toString().length).toString() + "ch"
  view
    scroll id=(id + "-content") testId=(id + "-content") tabindex=0 role="region" aria-label=(heading + " code") overflow="auto" min-width="0px" max-height=max(64, maxHeight) padding=(compact ? "ui.space-6 0px ui.space-12" : "ui.space-8 0px ui.space-16")
      :focus-visible
        box-shadow="ui.shadow-focus-inset"
      view display="grid" grid-template-columns=(wrapped ? "minmax(0, 1fr)" : "minmax(max-content, 1fr)") min-width="0px"
        for line, i in displayLines key=i
          row gap="ui.space-12" align-items="flex-start" position="relative" padding=(compact ? "0px ui.space-12" : "0px ui.space-16") min-width="0px" min-height=(compact ? "ui.space-20" : "ui.space-24") role="group" aria-label=("Line " + (lineStart + i).toString() + (line.variant == "added" ? ", added" : line.variant == "removed" ? ", removed" : line.variant == "highlighted" ? ", highlighted" : "")) background-color=(line.variant == "added" ? "ui.code-added-background" : line.variant == "removed" ? "ui.code-removed-background" : line.variant == "highlighted" ? "ui.code-highlight" : "transparent")
            if line.variant == "added" or line.variant == "removed"
              text (line.variant == "added" ? "+" : "−") position="absolute" left="ui.space-3" top="0px" aria-hidden=true user-select="none" font-family="ui.font-code" font-size=(compact ? "ui.text-xs" : "ui.text-sm") line-height="ui.leading-code" color=(line.variant == "removed" ? "ui.danger" : "ui.success")
            if numbers
              text (lineStart + i).toString() width=numberWidth flex-shrink=0 text-align="right" aria-hidden=true user-select="none" font-size=(compact ? "ui.text-xs" : "ui.text-sm") font-family="ui.font-code" line-height="ui.leading-code" color="ui.muted-foreground"
            text testId=(id + "-line-" + i.toString()) min-width="0px" flex=1 white-space=(wrapped ? "pre-wrap" : "pre") overflow-wrap=(wrapped ? "anywhere" : "normal") font-family="ui.font-code" font-size=(compact ? "ui.text-xs" : "ui.text-sm") line-height="ui.leading-code" min-height=(compact ? "ui.space-20" : "ui.space-24")
              if line.tokens.length == 0
                text "\n" font-family="ui.font-code"
              else
                for token, j in line.tokens key=j
                  text token.text color=(variant == "destructive" ? "ui.danger" : line.variant == "removed" and token.tone == "plain" ? "ui.danger" : codeTokenColor(token.tone)) font-family="ui.font-code"

```
