Skip to content

CodeSnippet

A read-only block of highlighted code with a copy button.

<CodeSnippet language="json" code={'{ "enabled": true }'} />
{
  "name": "rover",
  "speed": 3,
  "ready": true,
  "error": null
}
  • Highlighting is done by prism, synchronously, so the colored code is in the first render. Eight grammars are bundled: bash, dart, go, javascript, json, python, rust, and typescript.
  • The copy button writes code to the clipboard and reads Copied for two seconds, or Copy failed when the browser refuses the write.
  • Token colors come from the code color tokens, which change in dark mode, so dark mode needs nothing extra.
  • Long lines scroll sideways by default. Set wrapLines to wrap them instead.
{
  "name": "rover",
  "speed": 3,
  "ready": true
}
Code
Basic.svelte
<script lang="ts">
import { CodeSnippet } from "@viamrobotics/prime-ui";
const code = '{\n "name": "rover",\n "speed": 3,\n "ready": true\n}';
</script>
<div class="not-content">
<CodeSnippet {code} language="json" />
</div>

Pass a caption snippet as a direct child to show a label beneath the code.

{
  "name": "rover",
  "speed": 3,
  "ready": true
}
rover.json
Code
Captioned.svelte
<script lang="ts">
import { CodeSnippet } from "@viamrobotics/prime-ui";
const code = '{\n "name": "rover",\n "speed": 3,\n "ready": true\n}';
</script>
<div class="not-content">
<CodeSnippet {code} language="json">
{#snippet caption()}
rover.json
{/snippet}
</CodeSnippet>
</div>

wrapLines wraps a long line at the edge of the block.

curl --request POST --header "Content-Type: application/json" --data '{"name": "rover", "speed": 3}' https://example.com/api/robots
Code
WrapLines.svelte
<script lang="ts">
import { CodeSnippet } from "@viamrobotics/prime-ui";
const code =
'curl --request POST --header "Content-Type: application/json" --data \'{"name": "rover", "speed": 3}\' https://example.com/api/robots';
</script>
<div class="not-content max-w-md">
<CodeSnippet {code} language="bash" wrapLines />
</div>

One snippet for each language in codeSnippetLanguages.

bash

# Drive the rover a fixed distance.
ROVER="rover"
SPEED=3

drive() {
  local meters=$1
  echo "$ROVER is moving $meters meters at $SPEED"
  if [ "$meters" -gt 0 ]; then
    return 0
  fi
  false
}

drive 12

dart

// Drive the rover a fixed distance.
class Rover {
  final String name;
  int speed = 3;
  bool parked = false;

  Rover(this.name);

  bool drive(double meters) {
    print("$name is moving");
    return meters > 0 && !parked;
  }
}

go

// Drive the rover a fixed distance.
package main

import "fmt"

type Rover struct {
	Name  string
	Speed int
}

func (r Rover) Drive(meters int) bool {
	parked := false
	fmt.Println(r.Name, "is moving")
	return meters > 0 && !parked
}

javascript

// Drive the rover a fixed distance.
const rover = { name: "rover", speed: 3, parked: false };

function drive(meters) {
  console.log(`${rover.name} is moving`);
  return meters > 0 ? rover.speed : null;
}

json

{
  "name": "rover",
  "speed": 3,
  "ready": true,
  "error": null
}

python

# Drive the rover a fixed distance.
class Rover:
    def __init__(self, name: str, speed: int = 3):
        self.name = name
        self.speed = speed

    def drive(self, meters: float) -> bool:
        print(f"{self.name} is moving")
        return meters > 0 and self.speed is not None

rust

// Drive the rover a fixed distance.
struct Rover {
    name: String,
    speed: u32,
}

impl Rover {
    fn drive(&self, meters: f64) -> bool {
        let parked = false;
        println!("{} is moving", self.name);
        meters > 0.0 && !parked
    }
}

typescript

// Drive the rover a fixed distance.
interface Rover {
  name: string;
  speed: number;
  parked: boolean;
}

function drive(rover: Rover, meters: number): boolean {
  console.log(`${rover.name} is moving`);
  return meters > 0 && rover.parked === false;
}

class and any other attributes land on the <figure> root. The <pre> wears text-code and bg-light. Every standard prism token class maps to one code token, grouped as below, so a grammar added later is colored with no new rules. Operators, punctuation, variables, and parameters inherit the text color.

Prism classes Color token
comment, prolog, doctype, cdata, shebang, hashbang --color-code-comment
keyword, atrule, important --color-code-keyword
builtin, class-name, type-definition, generic, namespace, lifetime-annotation --color-code-type
function, function-name, function-definition, macro, decorator, annotation --color-code-function
string, char, template-string, triple-quoted-string, string-literal, attr-value, regex, url --color-code-string
number, constant, symbol --color-code-number
boolean --color-code-boolean
null --color-code-null
property, attr-name, tag, selector --color-code-property-keys

CodeSnippet is native, so it sets no data attributes.

The copy button is a native button, so Tab reaches it and Enter or Space copies.

A snippet whose code overflows horizontally is a keyboard scroll stop: Tab reaches the code and the arrow keys scroll it. It is a region named by its caption, or “Code” when there is none. A snippet that fits, or one that uses wrapLines, is not a tab stop.

PropTypeDefaultDescription
codestringThe code to render, verbatim.
languageCodeSnippetLanguageThe grammar code is highlighted with.
wrapLinesbooleanfalseWraps long lines instead of scrolling them horizontally.
captionSnippetA caption rendered beneath the code.

Plus everything in HTMLAttributes<HTMLElement>, spread onto the element.