Command palette

@yasinsensoy/web

Web · Components

CodeBlock

Syntax-highlighted code block.

12 exports

Live example

Preview

app/counter.tsx
TSX
"use client";

import { Button, toast } from "@yasinsensoy/web";
import { useState } from "react";

/** A counter that goes up on each click. */
export function Counter({ start = 0 }: { start?: number }) {
  const [count, setCount] = useState<number>(start);
  const increment = () => setCount((c) => c + 1);

  return (
    <Button variant="soft" onClick={increment} disabled={count >= 10}>
      Increment: {count}
    </Button>
  );
}

Code

import { CodeBlock } from "@yasinsensoy/web";

<CodeBlock language="tsx" title="app/counter.tsx" lineNumbers highlightLines="8-9"
  code={code}
/>

Events

  1. Events appear here when you interact with the preview.

Comparing two codes: side by side (split), changed words highlighted

lib/api.ts
+7 −3TypeScript
interface User {interface User {
  id: number;  id: number;
  name: string;  name: string;
  role?: "admin" | "member";
}}

export async function userFetch(id: number) {const API_URL = "https://api.example.com";
  const response = await fetch("https://api.example.com/users/" + id);
  return response.json();export async function getUser(id: number): Promise<User> {
  const response = await fetch(`${API_URL}/users/${id}`);
  if (!response.ok) throw new Error(`Request failed: ${response.status}`);
  return (await response.json()) as User;
}}

Without a title: language name in the corner, copy button on hover (always on touch)

pnpm add @yasinsensoy/web

Added / removed lines (automatic in the diff language)

dialog.tsx
TSX
<Dialog
  open={open} onOpenChange={setOpen}
  title="Silinsin mi?"
  onConfirm={remove}
/>

Long code: collapsing with maxLines

cities.json
JSON
[
  {
    "plate": 1,
    "name": "Adana"
  },
  {
    "plate": 6,
    "name": "Ankara"
  },
  {
    "plate": 7,
    "name": "Antalya"
  },
  {
    "plate": 16,
    "name": "Bursa"
  },
  {
    "plate": 26,
    "name": "Eskişehir"
  },
  {
    "plate": 34,
    "name": "İstanbul"
  },
  {
    "plate": 35,
    "name": "İzmir"
  },
  {
    "plate": 42,
    "name": "Konya"
  }
]

Import

import { CodeBlock, loadLanguage, registerLanguage } from "@yasinsensoy/web";

CodeBlock

componentClient component

Syntax-highlighted code block. Colors come from the theme (--ui-code-* variables; separate for light and dark), so they fit custom themes too. The highlighter is the library's own, with no external dependency; each language is a separate chunk downloaded only when used on the page. Server-rendered pages get colored HTML ready.

When a title (title) or icon is given, a strip with the file name, language name and copy button appears on top; otherwise the copy button sits at the top right corner (appears on hover, always visible on touch). Long lines scroll horizontally with a scrollbar that takes no width; with wrap they wrap.

With original it shows the diff of two pieces of code (one column or side by side with diffView; long unchanged regions collapse).

Line numbers, highlighted / inserted / deleted lines, a maximum height and collapsing with "Show all" are given with props. Line numbers don't enter the selection or the copied text.

To change colors, define --ui-code-keyword, --ui-code-string, --ui-code-function… variables in the theme (full list in theme.css).

CodeBlock({ code, language, title, icon, lineNumbers: lineNumbersProp, startLine, highlightLines, addedLines, removedLines, wrap, maxHeight, maxLines, original, diffView, contextLines, copyable, onCopy, classNames, className, style, ...props }: CodeBlockProps): JSX.Element

Examples

<CodeBlock language="bash" code="pnpm add @yasinsensoy/web" />

<CodeBlock title="app/page.tsx" language="tsx" lineNumbers highlightLines="3-4"
  code={`export default function Page() {
  return (
    <Button onClick={save}>Save</Button>
  );
}`} />

<CodeBlock language="diff" code={diff} />

// Compare two pieces of code: one column or side by side
<CodeBlock language="ts" title="api.ts" original={oldCode} code={newCode} />
<CodeBlock language="ts" original={oldCode} code={newCode} diffView="split" />
<CodeBlock language="json" code={JSON.stringify(data, null, 2)} maxLines={15} />

loadLanguage

function

Loads a language's rules. The same language always gets the same Promise, marked the way React expects once resolved, so use() reads a loaded language right away without suspending. Resolves with null for an unknown language.

loadLanguage(language: CodeLanguage): Promise<CodeGrammar | null>

Adds your own language or replaces a built-in one. Rules are ordered; the first rule matching at a position wins. Call it once at app start.

registerLanguage(name: string, grammar: CodeGrammar, label?: string): void

Examples

registerLanguage("prisma", [
  { type: "comment", pattern: /\/\/.+/ },
  { type: "keyword", pattern: /\b(?:model|enum|datasource|generator)\b/ },
  { type: "type", pattern: /\b(?:String|Int|Boolean|DateTime)\b/ },
  { type: "meta", pattern: /@@?\w+/ },
], "Prisma");

Line selection: line numbers and ranges. An array ([1, [4, 6]]) or a string ("1,4-6"). Numbers are the line numbers shown on screen (relative to startLine).

type CodeLineSelection = string | readonly (number | readonly [number, number])[]

Classes that can be given to the inner parts of CodeBlock.

NameTypeDescription
header?stringTop strip holding the title, language name and copy button.
title?stringTitle text.
viewport?stringArea where the code scrolls (e.g. padding).
pre?stringThe <pre> element (e.g. font size: text-sm).
line?stringEach line.
copyButton?stringCopy button.

Props of the CodeBlock component.

Extends: Omit<ComponentProps<"div">, "title" | "children" | "onCopy">

NameTypeDefaultDescription
codestringCode to show. A single leading and trailing blank line is trimmed.
language?CodeLanguageHighlighting language: tsx, ts, js, json, html, css, bash, python, sql, md, yaml, diff, go, rust, java, kotlin, c, cpp, csharp, php, ruby, swift, graphql, dockerfile, toml… Each language loads only when used. An unknown name or "text" shows as plain text. For your own language see registerLanguage.
title?ReactNodeTitle shown in the top strip, usually a file name ("app/page.tsx").
icon?IconPropIcon left of the title: a name or an element. When given, the top strip is shown.
lineNumbers?booleanfalse`; `true` in diff mode (when `original` is given)Show line numbers. Numbers aren't selected or copied.
startLine?number1Number of the first line.
highlightLines?CodeLineSelectionLines to highlight: [3, [5, 7]] or "3,5-7". Ignored in diff mode.
addedLines?CodeLineSelectionLines shown as inserted (green). With language="diff" + lines are marked automatically.
removedLines?CodeLineSelectionLines shown as deleted (red). With language="diff" - lines are marked automatically.
wrap?booleanfalseWrap long lines instead of scrolling.
maxHeight?number | stringCode taller than this scrolls vertically (320, "50vh").
maxLines?numberIf the code is longer than this many lines only the first lines are shown, with a "Show all" button below. So long examples don't take over the page (especially on mobile).
original?stringOld code to compare with. When given the block switches to diff mode: code is the new state, deleted lines are red, inserted ones green, and changed words within a line are also highlighted. The diff is found with the library's own algorithm (Myers, the one git uses); the code is still highlighted with language. The header shows +inserted −deleted counts.
diffView?CodeDiffView"unified"Diff view: "unified" shows old and new lines stacked in one column, "split" shows old on the left and new on the right. "split" becomes "unified" automatically on narrow screens (below 640 px).
contextLines?number | false3Number of unchanged lines shown around changes in diff mode; longer unchanged regions collapse as "12 unchanged lines" and expand on click. false shows everything.
copyable?booleantrueShow the copy button.
onCopy?(code: string) => voidCalled with the copied text when the code is copied.
classNames?CodeBlockClassNamesClasses added to the inner parts.

Diff view: one column (unified) or side by side (split).

type CodeDiffView = "unified" | "split"

Canonical names of the languages built into the library.

type CodeLanguageName = keyof typeof loaders

The language prop of CodeBlock: a built-in language name or alias (ts, py, sh, yml…), a language added with registerLanguage, or plain text that is not colored ("text").

type CodeLanguage = CodeLanguageName | keyof typeof aliases | "text" | (string & {})

Highlighted token kinds. Each kind is colored by a --ui-code-* theme variable (e.g. keyword → --ui-code-keyword).

type CodeTokenType = "comment" | "keyword" | "string" | "number" | "constant" | "function" | "type" | "builtin" | "variable" | "property" | "operator" | "punctuation" | "tag" | "attr" | "regex" | "meta" | "inserted" | "deleted" | "heading" | "bold" | "italic" | "link"

CodeRule

interface

A language rule.

NameTypeDescription
type?CodeTokenTypeKind of the matched text; plain text when undefined. With inside, text the inner language cannot match gets this kind.
patternRegExpPattern to match. All rules combine into one expression with the gm flags (^ and $ are line start/end); the i flag is supported, others are ignored. Do not use back references (\1): numbers shift when combined; capture groups are fine.
inside?CodeGrammar | (() => CodeGrammar)Also highlight the matched text with this language (e.g. ${…} in a template string, <style> in HTML). A function is called on first use; it lets a language refer to itself.

Ordered rules of a language.

type CodeGrammar = readonly CodeRule[]