Your next page is taking shape...

Opening Your Next Page…

Loading the guide and preparing its examples for you to explore. The page will appear here automatically when it’s ready, so you can keep this view open without refreshing.

Made for Preact. Built to be yours.

Source & Documentation

Code — Readable Snippets for Any Interface

Display source strings as selectable code with syntax highlighting and theme-aware surfaces. Start with a small snippet, choose its language, and add optional file context or reading tools when your interface needs them. Help readers understand a real source example, reveal its imports when needed and take an exact copy into their project. Keep reading preferences separate from the source itself. Import it from @kamod-ch/ui/code.

Source · API reference · Theming · Styles


Interactive Live Preview
Try it. Make it yours.
Setting the scene...

Interactive preview

Live Preact example Local preview theme · Responsive styles follow the preview widthFull width

Installation

Start with a Readable Snippet. Code is a Preact component exported by @kamod-ch/ui. Pass a source string and use the shared stylesheet for its typography, surfaces and syntax colors. Set it up once, then use the same component in a help article, API response, settings screen or working example.

Install PackagesTerminal
pnpm add @kamod-ch/ui

These examples use the published exports from @kamod-ch/ui. Install the package once, then import the component directly. Connect The Global Theme CSS and Tailwind Source Detection before your first render.

1. Add the UI Package

Use the same Preact and theme foundation as your other Kamod components. In a new project, install the UI package and its peers together. In an existing app, add only the packages that are missing; the Getting Started Guide walks through the complete application setup.

Install PackagesTerminal
pnpm add @kamod-ch/ui preact @preact/signals @kamod-ch/themes

@kamod-ch/ui does not install a syntax engine. Code renders safe, escaped source by default; applications that want token colors supply a highlighter adapter. This documentation keeps Prism in its own package and passes that adapter to Code. Use the focused @kamod-ch/ui/code entrypoint when your file only needs this component.

Usage PatternTypeScript
import { Code } from "@kamod-ch/ui/code";

// The root export is available too:
// import { Code } from "@kamod-ch/ui";

2. Connect the Shared Stylesheet

Import the theme once, at the application entry. Code’s surfaces, source typography and syntax colors are included in the shared theme stylesheet. Keep your overrides after these imports so the same design decisions apply to Button, Switch and the rest of your interface.

src/styles.css2 lines
@import "tailwindcss";
@import "@kamod-ch/ui/theme.css";

If your application already uses the full @kamod-ch/themes/theme.css foundation, keep it and add the component-only @kamod-ch/ui/code/styles.css entry instead of importing a second set of token defaults. This includes Code's layout, syntax palettes and CopyButton feedback. The UI theme above already includes those styles.

Style RulesCSS
/* Alternative: your existing full theme foundation. */
@import "tailwindcss";
@import "@kamod-ch/themes/theme.css";
@import "@kamod-ch/ui/code/styles.css";

Use your existing Tailwind CSS v4 integration. If utility classes are missing in a production build, check Source Detection and CSS Setup; adding more language labels will not fix missing styles.

3. Render One Useful Example

Pass the source as a string through code. It remains selectable and readable before the highlighter loads. Choose a language when you know it; the example below keeps the presentation plain so it can sit beside a paragraph, response value or small demo.

src/GettingStartedExample.tsx14 lines
import { Code } from "@kamod-ch/ui/code";

const source = 'const greeting = "Hello";';

export function GettingStartedExample() {
  return (
    <Code
      code={source}
      language="typescript"
      showToolbar={false}
      showWrapControl={false}
    />
  );
}

Usage

Put the Source First. Begin with a small string and the language that matches it. Keep the presentation plain, preserve its original spacing and give it a short explanation in your surrounding page. The first examples below cover ordinary commands, data, styles and literal output; optional headers and reading tools follow later.

Import SetupTypeScript
import { Code } from "@kamod-ch/ui/code";
Usage PatternTypeScript
<Code
  code={'const greeting = "Hello";'}
  language="typescript"
  showToolbar={false}
  showWrapControl={false}
/>

Display the String Your Application Supplies

The code string is the source of truth. Syntax colors help a reader recognize tokens; spaces, indentation and newlines come from your string. A snippet can be a short expression, a configuration value or a complete function. Code displays it; it does not execute or format it. Prepare an object's JSON or an excerpt from a log before passing it to the component.

Start with the source and its language. The early examples use a plain presentation:showToolbar={false} removes the optional top bar, and showWrapControl={false} keeps long lines in the native horizontal scroll area. The later Optional File Header and Reading Preferences sections explain when extra context and interactive tools become useful.

A code surface that fits your interface

Your application provides the source and its purpose. Use Code beside an API response, in a help article or beneath a working example. Its surface and syntax colors follow the same shared stylesheet as the rest of your interface. Add a short explanation outside the snippet so readers know what they are looking at.

Prefer the Information You Already Have

Use language="typescript" for typed source, language="json" for serialized values and language="bash" for commands. For generated output that should remain literal, pair language="text" with inferLanguage={false}.

Usage PatternTypeScript
<Code code={source} language="typescript" showToolbar={false} showWrapControl={false} />
<Code code={response} language="json" showToolbar={false} showWrapControl={false} />
<Code code={report} language="text" inferLanguage={false} showToolbar={false} />

These are alternative render expressions; source, response and report are strings supplied by your app. Choose the matching grammar, then use the Language Selection Guide when the source arrives without metadata.

Component Examples & Variants

Explore Code in Different Contexts, from the starting pattern to the compositions below. Begin with Terminal Command, then compare the examples that match your content, state and layout. These are working patterns to adapt, not a list of interchangeable variant values: check the API Reference before using a prop or combining behaviors. Look at the surrounding labels, supporting text and spacing as well as the component itself.

Read the Result and Its Implementation Together. Use each showcase’s Code view to inspect imports and composition, or its Prompt view to prepare a setup or adaptation brief. Try the narrow preview and local theme controls before connecting real data, and use Reset to return an example to its initial state. Keep layout changes in class utilities where appropriate; follow the Component Styles Guide for hierarchy and the Theming Guide for shared surfaces and colors. The Accessibility Notes explain what to preserve when making those changes.

Terminal Command

Show a Command, Ready to Reuse. Choose language="bash" for shell commands and pass the command itself, without a decorative $ prompt. Code highlights the text; it does not run it. A short command can sit directly beside the explanation of when to use it.

This example displays pnpm build as a simple source surface. Longer commands retain native horizontal scrolling, and the string stays exactly as supplied. For package setup, follow the Getting Started Guide; for a later copyable command with a purpose label, see Optional File Header and Copy and Content.

Interactive Live Preview
Try it. Make it yours.
Setting the scene...

Interactive preview

Live Preact example Local preview theme · Responsive styles follow the preview widthFull width

Structured Data

Keep Structured Values Easy to Scan. Pass a serialized string and choose language="json" to distinguish keys, strings, booleans and punctuation. The plain example below preserves the original indentation without a filename or an additional header.

This works well beside an API response or a settings explanation. Code does not serialize objects, validate values or turn them into an interactive tree; prepare the string before rendering. See Language Selection for JSON aliases, YAML and other supported formats.

Interactive Live Preview
Try it. Make it yours.
Setting the scene...

Interactive preview

Live Preact example Local preview theme · Responsive styles follow the preview widthFull width

CSS Snippet

Give Styles the Same Readable Surface. Choose language="css" for a stylesheet excerpt and keep the explanation outside the code. The example below uses semantic color, border and focus tokens in a small workspace rule; Code displays the original selectors and declarations.

An explicit language is enough for syntax colors. No file label or extra controls are needed to explain a class. Follow Theme Tokens when adapting the rule to your own interface, or compare Surface Variants to style the viewer itself.

Interactive Live Preview
Try it. Make it yours.
Setting the scene...

Interactive preview

Live Preact example Local preview theme · Responsive styles follow the preview widthFull width

Literal Output

Keep Plain Output Plain. Logs, build reports and generated text can contain code-like fragments without being source files. Pair language="text" with inferLanguage={false} to preserve a deliberately unhighlighted presentation, including the JSX-looking text in this report.

The example uses the same plain surface as the earlier snippets. Whitespace, punctuation and line endings remain yours; nothing is stripped or normalized. This is also a useful fallback for a language or custom DSL that has no supported grammar.

Interactive Live Preview
Try it. Make it yours.
Setting the scene...

Interactive preview

Live Preact example Local preview theme · Responsive styles follow the preview widthFull width

Surface Variants

Fit the Snippet into Its Surroundings. Choose default, subtle or outline to adjust the code surface without changing its source or syntax highlighting. The examples share one short string and keep their labels outside Code, so the difference in the surfaces is easy to compare.

Use the default for a distinct reading area, subtle for a quiet inset, or outline when an existing parent already provides the surrounding surface. Syntax colors, Prism palettes and reader extensions are on the Code internals page.

Interactive Live Preview
Try it. Make it yours.
Setting the scene...

Interactive preview

Live Preact example Local preview theme · Responsive styles follow the preview widthFull width

Optional File Header

Add File Context When It Helps. The preceding examples use showToolbar={false} for a plain source surface. Code’s header is enabled by default: omit that setting when a label and copy action are useful, then supply filePath for an actual file or suggested destination.

The header separates the path from the filename, includes a file-type icon and shows a line count when space allows. Its .tsx extension also selects TypeScript with JSX here. The path is descriptive metadata; Code does not fetch or write the file. This example keeps extra reading controls out of the way so you can focus on the header. Compare Custom Header when a purpose is more useful than a path.

Interactive Live Preview
Try it. Make it yours.
Setting the scene...

Interactive preview

Live Preact example Local preview theme · Responsive styles follow the preview widthFull width

Custom Header

Use the Header to Explain Why This Source Matters. A destination path is not always the most useful label. renderToolbar lets you introduce a short purpose, state or piece of context while retaining the component’s own actions. The example places workspace defaults on the left and the supplied Copy action on the right.

This composition disables the wrap switch because the source is short. In a general source viewer, the supplied actions may include wrapping too, so render that value rather than rebuilding its buttons. Use toolbarContent for a smaller addition and reserve the full render function for an actual layout change.

Interactive Live Preview
Try it. Make it yours.
Setting the scene...

Interactive preview

Live Preact example Local preview theme · Responsive styles follow the preview widthFull width

Rendered Document

Let People Read a Document and Copy Its Source. Supply renderedContent when the visible presentation should be prepared Preact content, while code remains the original Markdown. This is useful for an implementation brief, a setup prompt or a short reference that reads better with real headings and paragraphs.

The viewer omits code-only import and wrapping controls in this mode. The preview below is hand-authored JSX, not an automatic Markdown parser; its Copy action still returns the Markdown string. If the document comes from another source, review Safe Content Boundaries before rendering it.

Interactive Live Preview
Try it. Make it yours.
Setting the scene...

Interactive preview

Live Preact example Local preview theme · Responsive styles follow the preview widthFull width

Collapsible Imports

Add Folding to a Larger Source Example. After choosing the source, its language and any useful header, consider hiding familiar setup declarations with defaultImportsCollapsed. The control counts complete import statements: the multiline Card import below is one statement even though it imports several parts. Introductory comments remain visible.

Expand the imports to inspect the dependencies, then collapse them to compare the implementation. Hidden declarations leave no blank stack of lines, and Copy includes every declaration. Folding rules are on the Code internals page.

Interactive Live Preview
Try it. Make it yours.
Setting the scene...

Interactive preview

Live Preact example Local preview theme · Responsive styles follow the preview widthFull width

Readable Wrapping

Offer a Reading Choice for Long Lines. Once a source viewer needs more than the plain snippets above, use defaultWrapped to start long attributes or messages inside the reading area. The wrap switch changes their visual layout while preserving useful indentation.

Compare the example at a narrow preview width, then turn wrapping off to use native horizontal scrolling. A visual continuation never adds a newline to the original source or copied text. Wrapping rules are on the Code internals page.

Interactive Live Preview
Try it. Make it yours.
Setting the scene...

Interactive preview

Live Preact example Local preview theme · Responsive styles follow the preview widthFull width

Language Selection

Choose the Grammar That Matches Your Source. A language selects syntax highlighting, not a formatter that rewrites your code. Start with an explicit language or filename, explore the supported grammars, then offer a selector when your reader needs a choice. Automatic inference and plain-text mode cover the cases where metadata is missing or colors are unnecessary.

Choose a Language with the Metadata You Trust

Pass language when you know what the source contains. A file browser can use its file type, a Markdown renderer can pass the fence label, and a settings screen can declare json directly. This selects syntax highlighting; it does not translate, validate or format the string.

Usage PatternTypeScript
<Code code={componentSource} language="tsx" />
<Code code={responseSource} language="json" />
<Code code="pnpm build" language="bash" />

These independent expressions assume your app supplies componentSource and responseSource as strings. With inference enabled, a recognized explicit language takes precedence over the extension in filePath. If neither gives a useful hint, bounded syntax checks look for common source patterns. JavaScript and TypeScript hints can be promoted to JSX and TSX when recognizable JSX is present.

For a strict override, set inferLanguage={false}. Code then uses only the normalized language value: file metadata, content guessing and JSX promotion are skipped. Your explicit selector can therefore choose TypeScript, JSX or plain text without another hint overriding that choice.

Usage PatternTypeScript
<Code
  code={source}
  filePath="src/example.tsx"
  language="javascript"
  inferLanguage={false}
/>
Highlighting leaves the source alone

Selecting JSON does not serialize an object. Selecting TypeScript does not add types. Indentation, newlines, import order and copied text still come from code. If your app needs formatted source, prepare it before passing the string to Code.

Change the Language at Runtime

Choose any grammar below to inspect the same TSX source. The selector treats named languages as strict choices. Its Automatic option restores inference from the filename and source. Try text, then tsx: the same string switches between plain text and syntax highlighting, with no extra reading controls.

Selected grammar: tsx. The source stays the same.

import { Button } from "@kamod-ch/ui/button";
import type { ComponentChildren } from "preact";

type WelcomeProps = { name: string; children?: ComponentChildren };

// Keep a clear next step within reach.
export function Welcome({ name, children }: WelcomeProps) {
  return <Button aria-label={`Open the shared workspace for ${name} and review the latest updates`}>{children ?? "Open workspace"}</Button>;
}

Use the exported codeLanguages catalog to build a selector without maintaining a second list. Its values are the supported canonical grammar names, including text. The matching CodeLanguage type is useful for application state; the public language prop also accepts aliases and file hints as strings.

src/LanguageSelector.tsx31 lines
import { Code, codeLanguages, type CodeLanguage } from "@kamod-ch/ui/code";
import { useState } from "preact/hooks";

const source = 'export const ready: boolean = true;';

export function LanguageSelector() {
  const [language, setLanguage] = useState<CodeLanguage>("typescript");

  return (
    <section>
      <label>
        Highlighting language
        <select
          value={language}
          onChange={(event) => setLanguage(event.currentTarget.value as CodeLanguage)}
        >
          {codeLanguages.map((value) => (
            <option key={value} value={value}>{value}</option>
          ))}
        </select>
      </label>
      <Code
        code={source}
        language={language}
        inferLanguage={false}
        showToolbar={false}
        showWrapControl={false}
      />
    </section>
  );
}

Keep the source string stable while changing the preference. Code updates highlighting when language changes and ignores results from an older highlighting request. A selector can change presentation immediately without fetching or rebuilding the source. The later Reading Preferences section covers optional tools for larger source viewers.

Supported Languages, Aliases and File Hints

The built-in catalog covers these families. Canonical names and aliases are case-insensitive; labels such as language-tsx and path hints such as src/Welcome.tsx are normalized too. JSONC uses the JSON grammar and Zsh uses Bash highlighting; an alias is not an additional parser.

Canonical languageAccepted short names and aliasesFilename hints
typescriptts, mts, cts.ts, .mts, .cts
javascriptjs, mjs, cjs.js, .mjs, .cjs
tsx / jsxtsx / jsx.tsx / .jsx
jsonjson, jsonc.json, .jsonc
yamlyaml, yml.yaml, .yml
csscss.css
markuphtml, htm, xml, svg.html, .htm, .xml, .svg
markdownmd, markdown.md, .markdown
bashsh, bash, zsh, shell, shellscript, console, terminal, shellsession.sh, .bash, .zsh
diffdiff, patch.diff, .patch
texttext, txt, plain, plaintext, none, autoUnrecognized extensions

Inference inspects a bounded part of the source rather than trying every grammar. Short expressions and ambiguous text can remain plain. An unsupported label, such as python or sql, does not load a new grammar; with inference enabled, another file or content hint can still be used. Choose literal mode when that would be misleading.

Keep Plain Source Deliberately Plain

Generic labels such as text, plain and autonormalize to plain text, but still allow inference by default. Pair language="text" with inferLanguage={false} to make a log, unknown language or report literal even when its contents look like code.

Usage PatternTypeScript
<Code
  code="SELECT name FROM workspaces;"
  language="text"
  inferLanguage={false}
/>

To keep known language metadata and eligible reading controls while disabling colors, use highlight={false} instead. This skips the highlighter for that instance. Both approaches preserve selection and exact copying; neither removes source characters or applies formatting.

Usage PatternTypeScript
<Code code={source} language="tsx" highlight={false} />

Reuse Language Decisions Outside the Viewer

Code resolves its own language. Use the exported helpers only when surrounding UI needs the same metadata, such as a file inventory or language badge. Each returns a canonical CodeLanguage value and leaves source handling to your app.

Usage PatternTypeScript
import {
  codeLanguageForFile,
  normalizeCodeLanguage,
  resolveCodeLanguage,
} from "@kamod-ch/ui/code";

codeLanguageForFile("src/Welcome.tsx"); // "tsx"
normalizeCodeLanguage("language-yml"); // "yaml"
resolveCodeLanguage("export const ready = true;", undefined, "src/status.ts"); // "typescript"

normalizeCodeLanguage normalizes one label without inspecting source. codeLanguageForFile uses the final extension, ignoring query, hash and source-position suffixes. resolveCodeLanguage applies the inference order above; it does not implement strict mode. For a strict external selection, normalize the chosen label directly.

Copy and Content

Make Copy Predictable. A reader should receive the source they came for, regardless of which imports are hidden or how the text fits on screen. Build on that contract with honest success feedback, a useful failure path and a clear boundary between source strings and prepared document content.

Copy the Source the Reader Expects

Copy writes the exact code string to the clipboard. File labels, custom headers, syntax tokens and line-wrap controls are excluded. Hidden imports are included. In document mode, the visible JSX can be a friendly rendering while Copy still provides the original Markdown.

Save the same source as a file. Download beside Copy preserves the full source, including folded imports and original whitespace. These documentation panels compose that action through renderCopyAction; the public component retains its existing API.

Author source that can stand on its own. Use real imports, include required setup nearby and avoid a copied command that contains a decorative prompt character. If your example needs a secret or account-specific identifier, pass an explicit placeholder rather than a real credential.

React to Success and Recover from Failure

The built-in button reports successful copying and announces its status. onCopy receives the original string after the clipboard write succeeds. onCopyError lets your app provide a helpful next step if clipboard access is unavailable or denied. Do not report success before the browser confirms it.

src/CopyableCommand.tsx17 lines
import { Code } from "@kamod-ch/ui/code";
import { useState } from "preact/hooks";

export function CopyableCommand() {
  const [message, setMessage] = useState("");
  return (
    <section>
      <Code
        code="pnpm build"
        language="bash"
        onCopy={() => setMessage("Command copied. Run it in your project.")}
        onCopyError={() => setMessage("Copy was blocked. Select the command and copy it manually.")}
      />
      <p class="mt-2 text-sm text-muted-foreground">{message}</p>
    </section>
  );
}

Use the same action outside a code panel. Import CopyButtonfrom @kamod-ch/ui/copy-button and pass the exact value to copy. Set label for visible text, subject for status announcements, or iconOnly for a compact action with an accessible name. The shared button uses the theme’s success color, keeps its width stable during feedback, and respects reduced motion. Pending results and feedback timers are discarded when the value changes or the action unmounts.

src/InstallAction.tsx9 lines
import { CopyButton } from "@kamod-ch/ui/copy-button";

export const InstallAction = () => (
  <CopyButton
    value="pnpm add @kamod-ch/ui"
    label="Copy command"
    subject="install command"
  />
);

The paragraph adds persistent guidance; the component already owns the live announcement. Clipboard writing depends on browser permission and a secure context. When it fails, the source remains selectable. A legacy browser fallback cleans up its temporary field and restores focus; every copy action shares the same lifecycle.

Treat Rendered Content as Application Content

Source supplied through code is displayed as text before highlighting; markup-like source does not become a live element. The optional renderedContent prop accepts Preact children that your application has already prepared. Code does not parse Markdown or sanitize arbitrary HTML for that slot.

For content from an untrusted source, keep it as the source string or use your application’s reviewed Markdown and sanitization pipeline before rendering. For a hand-authored guide, normal JSX elements are a straightforward way to build the document view shown in Rendered Document.

API reference

Props and Data

Configure Code using the contracts below. Read the documented options alongside the Source Definitions to understand which values your application supplies and which details the component owns. Start with a prop or helper, then follow its type link to inspect the declaration without leaving the page.

The tables group source, reading and composition options by responsibility. The source definitions below are generated from this checkout. Code also accepts root HTML attributes, excluding its own source and clipboard-specific contracts; children are supplied through the named composition slots.

API reference
Your API, from source

Type cards are extracted from this checkout’s TypeScript source at build time. Props inherited through HTMLAttributes, Omit or variant helpers remain references in those declarations; their fields are not flattened here. Match the reference to your installed version, and check a package’s exports before writing an import type. A type exported by a source file is not necessarily re-exported by @kamod-ch/ui.

Component Props

Read each option with its owning component. The
marker identifies required fields verified in that declaration. A ? means a field can be omitted; it does not promise a fallback value. Existing documented defaults remain alongside the descriptions. For callbacks, check the argument and return types before connecting your own state or services.

Code

Source and appearance: start with a string, then describe what the reader is looking at.

Code documented props
Prop / typeDescription
code
stringCodeProps

The original source. Displayed as text and copied unchanged, including hidden imports and original whitespace.

Usage requirement
Required
language
stringCodeProps

A supported language or alias. Recognized values take precedence over the file extension; use inferLanguage={false} to disable inference.

Default
Inferred
filePath
stringCodeProps

Adds a file header with an appropriate icon and supplies the extension for language selection. It is a label, not a request to load that file.

Default
—
inferLanguage
booleanCodeProps

Resolve a language from an explicit hint, file extension or recognizable source. When false, only the normalized language prop is used.

Default
true
variant
"default" | "subtle" | "outline"CodeProps

Choose the surrounding code surface. Every variant retains the same source handling, keyboard controls and copy behavior.

Default
"default"
class
stringCodeProps

Classes on the outer container. Use for overall width, placement and layout.

Default
—
preClassName
stringCodeProps

Classes on the source pre element. Useful for a local maximum height; it does not apply to rendered document content.

Default
—
className
stringCodeProps

Compatibility alias for the source-area class. Prefer preClassName in new code; use class for the outer container.

Default
—

Code

Reading preferences: defaults initialize local state; optional controlled props let your application own later changes.

Code documented props
Prop / typeDescription
defaultWrapped
booleanCodeProps

Start with readable soft wrapping. This is an initial preference, not a controlled-state value.

Default
false
readingControls
"overflow" | "always" | "imports"CodeProps

Use overflow-driven controls, always show eligible controls, or show controls only for snippets with leading imports. The latter policies avoid width observers. Documentation readers default to "imports".

Default
"overflow"
showWrapControl
booleanCodeProps

Allow wrapping in any supported language or plain text. Visibility follows readingControls; false hides the switch while controlled or default wrapping still works.

Default
true
defaultImportsCollapsed
booleanCodeProps

Start eligible imports folded. A different source string resets import folding to this default.

Default
false
showImportControl
booleanCodeProps

Allow eligible leading static imports to be folded. If disabled, the declarations remain visible even when the collapsed default is set. The control appears alongside wrapping only when complete source would overflow; hidden imports still count.

Default
true

Code

Composition and copying: adapt the surrounding content without duplicating the source or clipboard logic.

Code documented props
Prop / typeDescription
toolbarContent
ComponentChildrenCodeProps

Content beside the standard actions. Replaces the automatic purpose label; an explicit file path can still be shown.

Default
—
renderToolbar
(actions: ComponentChildren) => ComponentChildrenCodeProps

Render a custom header and place the supplied actions once. Depending on the layout, the actions may include wrapping as well as Copy.

Default
Built-in header
renderLanguage
(language: CodeLanguage, label: string) => ComponentChildrenCodeProps

Replace the language label in an unnamed snippet’s automatic header, for example with a linked inline-code reference. Receives the resolved grammar and its readable label; does not change highlighting or override a file path or custom toolbar.

Default
Plain language label
renderFilePath
(filePath: string) => ComponentChildrenCodeProps

Replace only the file label while retaining filePath as language metadata. Useful when your application needs its own file links inside the standard header.

Default
CodeFileHeader
renderedContent
ComponentChildrenCodeProps

A prepared Preact document view in place of the source area. Copy retains the original source; syntax highlighting and code reading controls are omitted.

Default
—
showCopy
booleanCodeProps

Show the built-in clipboard action. Hiding it does not prevent normal text selection.

Default
true
onCopy
(code: string) => voidCodeProps

Called with the original source after clipboard writing succeeds. Use for persistent context or application feedback.

Default
—
onCopyError
(error: unknown) => voidCodeProps

Called when clipboard writing fails or is unavailable. Provide a recovery step such as selecting the text manually.

Default
—

Code

Modularity: hide presentation, share state or replace individual controls.

Code documented props
Prop / typeDescription
resolveReference
CodeReferenceResolver | nullCodeProps

Resolve imported names and module strings to verified local or HTTP(S) destinations. Return undefined for unknown references; null disables links for this panel. Aliases retain the original export name. Copy still uses the unchanged source. See Source Reference Links.

Default
Inherited provider or no links
showToolbar
booleanCodeProps

Show the header, file label and Copy action. When false, eligible reading controls remain in their own row. renderToolbar is not called.

Default
true
highlighter
CodeHighlighterCodeProps

Supply the application’s syntax engine as a synchronous or asynchronous adapter. Core ships without one and otherwise displays escaped source. Returned HTML must already be escaped and safe to insert.

Default
—
highlight
booleanCodeProps

Allow deferred syntax highlighting when a highlighter is supplied. False preserves escaped source, selected language, copying and reading behavior without invoking the adapter for this instance.

Default
true
syntaxTheme
CodeSyntaxThemeCodeProps

Choose an ID in codeSyntaxThemes. The theme palette derives syntax colors from your application's semantic tokens. Other Kamod palettes follow the application scheme; Okaidia, Tomorrow, Twilight and Solarized Light also select a fixed source canvas. The header, controls and application appearance remain independent. See Prism Palette Studies.

Default
"default"
wrapped
booleanCodeProps

Control wrapping externally. Takes precedence over defaultWrapped; works even with the wrap control hidden.

Default
Uncontrolled
onWrappedChange
(wrapped: boolean) => voidCodeProps

Receives a requested wrap change in either ownership mode. In controlled mode, update wrapped to apply it.

Default
—
importsCollapsed
booleanCodeProps

Control eligible import folding externally. Takes precedence over its default and survives source changes. showImportControl=false disables folding.

Default
Uncontrolled
onImportsCollapsedChange
(collapsed: boolean) => voidCodeProps

Receives a requested folding change. Automatic uncontrolled resets on source changes do not call it.

Default
—
renderImportControl
(context: CodeImportControlContext) => ComponentChildrenCodeProps

Replace or decorate an eligible import control. Return null to hide the button while retaining controlled folding.

Default
Standard import button
renderWrapControl
(context: CodeWrapControlContext) => ComponentChildrenCodeProps

Replace or decorate an eligible wrap control. Return null to omit its presentation without changing the preference.

Default
Standard wrap switch
renderCopyAction
(context: CodeCopyActionContext) => ComponentChildrenCodeProps

Replace the clipboard button while retaining Code’s clipboard lifecycle and live status region. Requires both showCopy and showToolbar.

Default
Standard copy button
beforeCode / afterCode
ComponentChildrenCodeProps

Prepared Preact content around the source or rendered document. The before slot follows the reading controls. Slot content is never copied.

Default
—

Code

Renderer contexts: use the supplied action once and preserve accessible labels.

Code documented props
Prop / typeDescription
codeId
stringCodeProps

Source element ID available to every renderer. Use it for aria-controls in source views.

Default
Generated per instance
defaultControl
ComponentChildrenCodeProps

Render the default button or switch once to add surrounding context without rebuilding it. Do not nest it inside another interactive control.

Default
Built-in control
collapsed / count / onCollapsedChange
CodeImportControlContextCodeProps

Current collapsed preference, complete statement count and change action. Use aria-expanded={!collapsed} on a replacement disclosure.

Default
Current import state
wrapped / onWrappedChange
CodeWrapControlContextCodeProps

Current preference and change action. A custom toggle button should expose aria-pressed.

Default
Current wrap state
status / statusId / copy
CodeCopyActionContextCodeProps

Copy status is idle | copying | copied | error. Call copy(): Promise<void> to use the existing clipboard flow. statusId identifies its retained live region.

Default
"idle"

CodeFileHeader

Optional file-label composition for custom headers; ordinary examples can simply pass filePath to Code.

CodeFileHeader documented props
Prop / typeDescription
path
stringCodeFileHeaderProps

The display path, including its filename and extension. The file icon exposes its type.

Usage requirement
Required
code
stringCodeFileHeaderProps

Complete source for automatic line counting. Counts include hidden imports and exclude trailing blank space; wrapping does not change the total.

Default
—
lineCount
numberCodeFileHeaderProps

An explicit line total for a custom file viewer, overriding the count from code. Code's standard filename header calculates its total automatically. The count hides when the snippet container is 640px wide or narrower.

Default
—
children
ComponentChildrenCodeFileHeaderProps

Custom path content, retaining the shared separator and line-count styling.

Default
File path and icon
class
stringCodeFileHeaderProps

Additional classes for the file-label container.

Default
—

CodeSnippetLabel

Optional automatic purpose label for snippets without a meaningful file path.

CodeSnippetLabel documented props
Prop / typeDescription
code
string

The source used to distinguish a command from an installation command.

Usage requirement
Required
language
CodeLanguage

The resolved language. Use resolveCodeLanguage when your surrounding code does not already have this value.

Usage requirement
Required
renderLanguage
(language: CodeLanguage, label: string) => ComponentChildren

Decorate the language with the same optional renderer supported by Code.

Default
Plain language label
importsOnly
boolean

Whether the snippet consists only of imports, allowing the label to describe that purpose.

Usage requirement
Required

Data Type Reference

Expand a card to inspect and copy the exact declaration. The code header identifies its repository file; follow imported or inherited types in the Implementation Source when you need the complete dependency chain. Required-field summaries cover fields declared directly in that type. Source-only helpers and inferred schema outputs describe the local implementation, not additional props you can pass to every component.

CodeFileHeader Props

5 declared fields
CodeFileHeaderProps
Exported Source Declaration from CodeFileHeader.tsx. Referenced types retain their original names; inspect that file for imports and supporting definitions. Inspect the Complete Definition of CodeFileHeaderProps before adapting it.
Required fields
path

CodeIcon Props

1 declared field
CodeIconProps
Local Source Declaration from code-icons.tsx. Referenced types retain their original names; inspect that file for imports and supporting definitions. Inspect the Complete Definition of CodeIconProps before adapting it.

CodeLanguage

Declaration
CodeLanguage
Exported Source Declaration from code-language.ts. Referenced types retain their original names; inspect that file for imports and supporting definitions. Inspect the Complete Definition of CodeLanguage before adapting it.

CodeSourcePart

Declaration
CodeSourcePart
Retained source offsets, with literal whitespace for joins created by import folding. Inspect the Complete Definition of CodeSourcePart before adapting it.

ReferenceToken

4 declared fields
ReferenceToken
Source offsets, not a compiler AST. Literal content never becomes an identifier. Inspect the Complete Definition of ReferenceToken before adapting it.
Required fields
text, start, end, kind
CodeReferenceResolver
Resolve only destinations the host application actually owns or can verify. Inspect the Complete Definition of CodeReferenceResolver before adapting it.

CodeReference

7 declared fields
CodeReference
Source context lets hosts explain a link without reparsing or changing its copied text. Inspect the Complete Definition of CodeReference before adapting it.
Required fields
start, end, href

CodeSyntaxTheme

Declaration
CodeSyntaxTheme
`default` preserves the standard Code syntax colors. Inspect the Complete Definition of CodeSyntaxTheme before adapting it.

CodeHighlighter

Declaration
CodeHighlighter
Optional syntax-coloring adapter. Returned HTML must be escaped and safe to insert. Inspect the Complete Definition of CodeHighlighter before adapting it.

CodeImportControlContext

5 declared fields
CodeImportControlContext
State and behavior supplied to a replacement import-folding control. Inspect the Complete Definition of CodeImportControlContext before adapting it.
Required fields
codeId, collapsed, count, onCollapsedChange, defaultControl

CodeWrapControlContext

4 declared fields
CodeWrapControlContext
State and behavior supplied to a replacement line-wrap control. Inspect the Complete Definition of CodeWrapControlContext before adapting it.
Required fields
codeId, wrapped, onWrappedChange, defaultControl

CodeCopyStatus

Declaration
CodeCopyStatus
Exported Source Declaration from code-types.ts. Referenced types retain their original names; inspect that file for imports and supporting definitions. Inspect the Complete Definition of CodeCopyStatus before adapting it.

CodeCopyActionContext

5 declared fields
CodeCopyActionContext
Clipboard state stays local to the action; replacing it never duplicates clipboard work. Inspect the Complete Definition of CodeCopyActionContext before adapting it.
Required fields
codeId, statusId, status, copy, defaultControl

Code Props

36 declared fields
CodeProps
A read-only source viewer. Display preferences never modify `code` or clipboard text. Inspect the Complete Definition of CodeProps before adapting it.
Required fields
code

Accessibility

Code renders native pre and code elements. Its source viewport is keyboard focusable, imports use a button with aria-expanded and aria-controls, and wrapping uses a named switch. Syntax colors supplement the source text; the escaped plain-text fallback remains readable before highlighting loads.

Troubleshooting and Next Steps

Check the Smallest Missing Piece First. A missing stylesheet, ambiguous language or intentionally omitted control usually explains an unexpected result. Use the questions below to distinguish setup from presentation, then return to the smallest example that demonstrates the behavior you need. Prism themes, folding rules and performance notes are on the Code internals page.

Why Does This Snippet Look Like Plain Text?

First check that a highlighter adapter is supplied and that the shared theme CSS is loaded. Then check the source’s language or extension. Inference is intentionally conservative, so a single expression such as workspace.name may need language="typescript". A language outside the supported families remains readable but does not gain a grammar just because its name is supplied.

If colors appear shortly after the source enters view, that is the lazy adapter arriving. If they never arrive, inspect failed script requests, the adapter and the selected language. A failed highlighter load should leave the complete source visible. See Supported Languages and Stylesheet Setup.

Why Is the Import or Wrapping Control Absent?

Import folding requires recognizable leading static imports and visible content after them. A snippet containing only imports, a Bash command or a document view will not get an import control. CSS @import rules are supported too. Check showImportControl and readingControls: the core default "overflow" measures complete source; "always" retains eligible controls without measuring; "imports" limits the controls to snippets with imports. Wrapping itself supports every language. Documentation uses "imports" by default. Custom renderedContent skips both controls; showWrapControl={false} explicitly hides the switch.

On very narrow panels, control labels simplify to preserve room for the icons and switch. Their accessible names still describe the action. Widen the containing panel to see the fuller descriptions.

Why Are Indentation and Copied Text Unchanged?

That is intentional. Syntax highlighting changes presentation; it does not format source. Format the string before passing it to Code if your product promises formatted output. Wrapping and folded imports make reading easier while preserving the copy contract. If you need an editor, diagnostics, line selection or virtualized documents, compose a tool designed for those responsibilities.

For small UI demonstrations, pair Code with a real Button, Input or Alert. For a complete multi-file composition, explore Blocks. The most useful example is the smallest one that explains the next step.

Take the Next Useful Step

You have the pieces. Put them into one real interaction, keep its state in one place, and check the result with the content your application will actually show.

Connect the Foundation

Return to Choose and Compose Components to connect this reference to a working screen. Keep global CSS in one entrypoint and import only the components that screen needs.

Build the Surrounding Screen

Find a neighboring interaction in the Component Library, or start with a complete Block. Replace sample content and destinations before refining the layout; a local class change can stay with the composition.

Make the Result Hold Up

Use shared theme roles for changes that belong everywhere. Then review the whole journey: keyboard focus, long labels, narrow screens and a clear way to recover when something fails.

Keep a link to the source and note your intentional changes. Your next edit should begin with a clear decision, not another search.