Search documentation

Search pages, components, blocks, styles and colours.

Get started
Skip to content

Syntax Highlight

PreviousNext

Code coloured by the foundations' syntax tokens, in over 30 languages.

components/ui/badge.tsx
import { cn } from "@/lib/utils"
// Every look lives in the style map; the source only names it.export function Badge({  className,  variant = "default",  ...props}: React.ComponentProps<"span"> & { variant?: "default" | "outline" }) {  return (    <span      data-slot="badge"      data-variant={variant}      className={cn("cn-badge inline-flex items-center", className)}      {...props}    />  )}

Give it the code and a language, or just a file name, and it colours the code with the syntax colours: six hues that follow the colour roles and two neutrals, contrast-checked on every surface in light and dark. A title bar shows the file and a Copy button; the code can number its lines, mark lines, show what was added and removed, and wrap.

Syntax Highlight is part of the Fabricator style. It's built on plain HTML, so the same component ships for every base, and the same tokenizer runs in the React Native version.

Installation

bunx --bun fabricator-ui@latest add syntax-highlight

Usage

import {
  SyntaxHighlight,
  SyntaxHighlightContent,
  SyntaxHighlightCopy,
  SyntaxHighlightHeader,
  SyntaxHighlightIcon,
  SyntaxHighlightTitle,
} from "@/components/ui/syntax-highlight"
<SyntaxHighlight code={code} filename="app/page.tsx">
  <SyntaxHighlightHeader>
    <SyntaxHighlightIcon />
    <SyntaxHighlightTitle />
    <SyntaxHighlightCopy />
  </SyntaxHighlightHeader>
  <SyntaxHighlightContent showLineNumbers />
</SyntaxHighlight>

With no children it renders just the code:

<SyntaxHighlight code="bun add refractor" language="bash" />

Composition

SyntaxHighlight              the code, its language and its tokens
├── SyntaxHighlightHeader    the title bar
│   ├── SyntaxHighlightIcon      a file, or a terminal for shell code
│   ├── SyntaxHighlightTitle     the file name, else the language's name
│   ├── SyntaxHighlightLanguage  the language's name
│   └── SyntaxHighlightCopy      copies the code
└── SyntaxHighlightContent   the lines: numbers, marks, diff, wrapping

Every part reads the root through context, so they can sit anywhere inside it. For parts of your own, useSyntaxHighlight() returns the code, the language, the filename and the tokenized lines.

Examples

Languages

The language comes from language, a name or an alias (ts, sh, yml, html), or from the extension of filename when language is left out. Dockerfile, Makefile, .gitignore and .env files are read by their name.

package.jsonJSON
{  "name": "acme-dashboard",  "private": true,  "scripts": { "dev": "next dev", "build": "next build" },  "dependencies": { "fabricator-ui": "^0.6.0" }}
app/globals.cssCSS
@import "tailwindcss";
:root {  --radius: 0.5rem;}
.card:hover {  background-color: var(--surface-3);}
scripts/release.shBash
#!/usr/bin/env bashset -euo pipefail
# Ship only from a clean main.VERSION=$(node -p "require('./package.json').version")git tag "v$VERSION" && git push --tagsecho "Released v$VERSION"
seed.pyPython
from dataclasses import dataclass
@dataclassclass Member:    email: str    is_admin: bool = False
def seed() -> list[Member]:    return [Member("gabs@fabricator.dev", is_admin=True)]
.github/workflows/ci.ymlYAML
name: CIon: [push]jobs:  test:    runs-on: ubuntu-latest    steps:      - uses: actions/checkout@v4      - run: bun install && bun run test
README.mdMarkdown
# Acme Dashboard
Built with **Fabricator UI**. Run `bun dev` and open[localhost:3000](http://localhost:3000).
- Light and dark themes- _Every_ component from the registry

Line numbers

showLineNumbers numbers the lines, and startLine sets the first number, for an excerpt. The numbers can't be selected, so copying the code leaves them out.

export function getInitials(name: string) {  return name    .split(" ")    .map((part) => part[0]?.toUpperCase() ?? "")    .slice(0, 2)    .join("")}

Highlighted lines

highlightLines takes line numbers and inclusive ranges: [2, [6, 7]].

save-button.tsx
import { Button } from "@/components/ui/button"import { Spinner } from "@/components/ui/spinner"
export function SaveButton({ isSaving }: { isSaving: boolean }) {  return (    <Button disabled={isSaving}>      {isSaving ? <Spinner data-icon="inline-start" /> : null}      Save changes    </Button>  )}

Diff

A diff or a .patch marks its added and removed lines on its own. Give a diff the filename of the file it changes and its lines keep that file's colours; language="diff-json" does the same without one. To show a change without a diff, mark lines with insertedLines and deletedLines.

package.json
@@ -1,5 +1,5 @@ {   "name": "acme-dashboard",-  "version": "0.5.1",+  "version": "0.6.0",   "private": true }
greeting.tsx
export function Greeting({ name }: { name: string }) {  return <p>Hello, {name}</p>  return <p className="text-muted-foreground">Welcome back, {name}</p>}

Wrapping

wrap wraps long lines at the panel's edge instead of scrolling sideways.

const url = "https://fabricator-ui.vercel.app/r/fabricator/base-nova/syntax-highlight.json?icons=fabricator"const message = "Long lines wrap at the panel's edge instead of scrolling sideways, and a hanging line keeps its number."

Long code

Give SyntaxHighlightContent a maximum height and it scrolls, fading at the top and bottom edges while there is more.

members.ts
export const members = [  { id: 1, email: "member1@fabricator.dev", role: "admin" },  { id: 2, email: "member2@fabricator.dev", role: "member" },  { id: 3, email: "member3@fabricator.dev", role: "member" },  { id: 4, email: "member4@fabricator.dev", role: "member" },  { id: 5, email: "member5@fabricator.dev", role: "admin" },  { id: 6, email: "member6@fabricator.dev", role: "member" },  { id: 7, email: "member7@fabricator.dev", role: "member" },  { id: 8, email: "member8@fabricator.dev", role: "member" },  { id: 9, email: "member9@fabricator.dev", role: "admin" },  { id: 10, email: "member10@fabricator.dev", role: "member" },  { id: 11, email: "member11@fabricator.dev", role: "member" },  { id: 12, email: "member12@fabricator.dev", role: "member" },  { id: 13, email: "member13@fabricator.dev", role: "admin" },  { id: 14, email: "member14@fabricator.dev", role: "member" },  { id: 15, email: "member15@fabricator.dev", role: "member" },  { id: 16, email: "member16@fabricator.dev", role: "member" },  { id: 17, email: "member17@fabricator.dev", role: "admin" },  { id: 18, email: "member18@fabricator.dev", role: "member" },  { id: 19, email: "member19@fabricator.dev", role: "member" },  { id: 20, email: "member20@fabricator.dev", role: "member" },  { id: 21, email: "member21@fabricator.dev", role: "admin" },  { id: 22, email: "member22@fabricator.dev", role: "member" },  { id: 23, email: "member23@fabricator.dev", role: "member" },  { id: 24, email: "member24@fabricator.dev", role: "member" },  { id: 25, email: "member25@fabricator.dev", role: "admin" },  { id: 26, email: "member26@fabricator.dev", role: "member" },  { id: 27, email: "member27@fabricator.dev", role: "member" },  { id: 28, email: "member28@fabricator.dev", role: "member" },  { id: 29, email: "member29@fabricator.dev", role: "admin" },  { id: 30, email: "member30@fabricator.dev", role: "member" },  { id: 31, email: "member31@fabricator.dev", role: "member" },  { id: 32, email: "member32@fabricator.dev", role: "member" },  { id: 33, email: "member33@fabricator.dev", role: "admin" },  { id: 34, email: "member34@fabricator.dev", role: "member" },  { id: 35, email: "member35@fabricator.dev", role: "member" },  { id: 36, email: "member36@fabricator.dev", role: "member" },  { id: 37, email: "member37@fabricator.dev", role: "admin" },  { id: 38, email: "member38@fabricator.dev", role: "member" },  { id: 39, email: "member39@fabricator.dev", role: "member" },  { id: 40, email: "member40@fabricator.dev", role: "member" },]

Command

Copy can sit anywhere inside the root, here beside a one-line command.

npx fabricator-ui@latest add syntax-highlight

Colours

Each token kind takes one of eight foundation tokens, installed with every Fabricator component (bg-syntax-keyword, text-syntax-string, …):

TokenFollowsColours
--syntax-keywordits own hue and chromakeywords, at-rules, markdown headings
--syntax-functionthe info rolefunctions, methods, properties and keys, links
--syntax-stringthe success rolestrings, characters, attribute values
--syntax-constantthe warning rolenumbers, booleans, constants, attribute names
--syntax-typeits own hue and chromatypes, classes, built-ins, regular expressions
--syntax-tagthe destructive roletags, selectors, variables
--syntax-commentthe surface tintcomments, line numbers
--syntax-punctuationthe surface tintpunctuation and operators

Retint a role and its tokens turn with it; set a role to strength 0 and they turn to the foreground colour. Keyword and type have no role, so they take their own variables:

:root {
  --syntax-keyword-hue: 315;
  --syntax-keyword-chroma: 0.16;
  --syntax-type-hue: 195;
  --syntax-type-chroma: 0.08;
}

Every colour is the same lightness at any hue, so no token outshouts another, and every one keeps 4.5:1 against the first four surfaces, tinted or not, for any role setting. Added and removed lines use the success and destructive roles.

Languages

These languages are bundled: Bash, C, C++, C#, CSS, Diff, Dockerfile, Go, GraphQL, HTML, XML and SVG, Ignore files, INI, Java, JavaScript, JSON, JSX, Kotlin, Lua, Makefile, Markdown, PHP, Python, Ruby, Rust, SCSS, SQL, Swift, TOML, TSX, TypeScript and YAML. Anything else renders as plain text.

refractor has grammars for around 300 more. Register one once, anywhere before it renders:

import elixir from "refractor/elixir"
 
import { registerLanguage } from "@/lib/syntax-highlight-model"
 
registerLanguage(elixir)

To trim the bundle, remove languages from BUNDLED_LANGUAGES in lib/syntax-highlight-model.ts. The tokenizer is plain data with no DOM: highlightCode(code, language) returns the lines and their tokens, for a renderer of your own.

API Reference

SyntaxHighlight

All other props go to the root <div>.

PropTypeDefault
codestringrequired
languagestringread from filename, else plain text
filenamestring-
childrenReactNode<SyntaxHighlightContent />

SyntaxHighlightContent

All other props go to the <pre>.

PropTypeDefault
showLineNumbersbooleanfalse
startLinenumber1
highlightLinesArray<number | [number, number]>-
insertedLinesArray<number | [number, number]>-
deletedLinesArray<number | [number, number]>-
wrapbooleanfalse

SyntaxHighlightCopy

All other props go to the <button>. A handler that calls event.preventDefault() stops the copy.

PropTypeDefault
valuestringthe code
onCopied(value: string) => void-

SyntaxHighlightTitle, SyntaxHighlightLanguage

Children replace the text: the file name or the language's name.

Data attributes

AttributeElementPresent when
data-slot="syntax-highlight"rootalways
data-languagerootalways: the language read, or text
data-slot="syntax-highlight-content"the <pre>always
data-wrapthe <pre>wrap is true
data-slot="syntax-highlight-line"a linealways
data-highlighteda lineits number is in highlightLines
data-diff="inserted" | "deleted"a lineadded or removed
data-slot="syntax-highlight-line-number"a line's numbershowLineNumbers
data-tokena tokenthe token's kind (keyword, …)
data-copiedCopyfor two seconds after a copy

Accessibility

  • The code is a <pre> that takes focus, so a keyboard can scroll it sideways and down with the arrow keys.
  • Line numbers are hidden from screen readers and can't be selected, so neither reading nor copying the code includes them.
  • Copy is a button named "Copy code". After a copy it's named "Copied", and a polite live region says "Copied to clipboard". When the page has no clipboard (an insecure page, a denied permission), it stays as it was.
  • Every token colour, comments included, keeps 4.5:1 contrast against the code's surface in light and dark. Added and removed lines also carry a coloured edge, and a diff keeps its + and -, so the change doesn't rest on colour alone.