Command palette

@yasinsensoy/native

React Native · Components

CodeBlock

Syntax-highlighted code block.

10 exports

Live example

The preview runs in the browser with the web component; the native component takes the same props and looks the same on iOS and Android.

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/native";

<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/native";

CodeBlock

component

Syntax-highlighted code block. The same highlighter, languages and theme colors (theme.code) as web's CodeBlock; looks the same on iOS and Android.

Supports line numbers, highlighted / added / removed lines, horizontal scrolling or wrapping (wrap) for long lines, collapsing long code (maxLines), a diff between two pieces of code (original) and copying to the clipboard.

CodeBlock({ ref, code: rawCode, language, title, icon, header, lineNumbers, startLine, highlightLines, addedLines, removedLines, wrap, maxHeight, maxLines, original, contextLines, copyable, onCopy, fontSize, style, codeStyle, }: CodeBlockProps): JSX.Element

Examples

<CodeBlock language="tsx" title="App.tsx" lineNumbers highlightLines="2" code={`
export function App() {
  return <Text>Hello</Text>;
}
`} />

<CodeBlock language="ts" original={before} code={after} />

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. Can be 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])[]

Props of CodeBlock.

NameTypeDefaultDescription
ref?Ref<ViewRef>Ref of the underlying native element.
codestringCode to show. A single leading and trailing empty 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… The same highlighter and languages as web. An unknown name or "text" is shown as plain text. For your own language use registerLanguage.
title?ReactNodeTitle shown in the top bar, usually a file name ("app/page.tsx").
icon?IconPropIcon to the left of the title: a name or an element.
header?booleanShow the top bar (title, language name, copy). @defaultValue true if there is a title, icon, language name or copy button
lineNumbers?booleanfalse`; `true` in diff mode (when `original` is given)Show line numbers.
startLine?number1Number of the first line.
highlightLines?CodeLineSelectionLines to highlight: [3, [5, 7]] or "3,5-7". Ignored in diff mode.
addedLines?CodeLineSelectionLines to show as added (green). With language="diff", + lines are marked automatically.
removedLines?CodeLineSelectionLines to show as removed (red). With language="diff", - lines are marked automatically.
wrap?booleanfalseWrap long lines instead of scrolling horizontally.
maxHeight?numberCode taller than this height (pixels) scrolls vertically.
maxLines?numberIf the code is longer than this many lines, only the first lines are shown with a "Show all" button below. Ignored in diff mode.
original?stringOld code to compare against. When given the block switches to diff mode: code is the new version, removed lines show in red, added ones in green, and words changed within a line are highlighted separately (the same Myers algorithm as web). The header shows +added −removed counts. It is a single-column view for phone screens (web's "unified").
contextLines?number | false3Number of unchanged lines shown around changes in diff mode; longer unchanged regions are folded and expand on press. false shows all.
copyable?booleantrueShow the copy button. If the app has no clipboard module (Clipboard) the button does not appear.
onCopy?(code: string) => voidCalled with the copied text when the code is copied.
fontSize?number13Font size (pixels).
style?StyleProp<ViewStyle>Container style.
codeStyle?StyleProp<TextStyle>Style of the code text (e.g. font).

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.

Canonical names of the languages built into the library.

type CodeLanguageName = keyof typeof loaders

Ordered rules of a language.

type CodeGrammar = readonly CodeRule[]

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 & {})