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.

When to Read This

The Code page covers everyday snippets, languages, headers and copy. This page is for extending that reader: syntax themes, folding rules, custom controls and delivery.

Syntax Themes and Typography

Keep the default, try a bundled palette, or derive syntax colors from your application's semantic tokens. Prism recognition, token groups and stylesheet ports are below.

Pick a Palette, Keep the Source

Choose from nine palettes with one prop. Keep the app-aware default, dusk, forest or monochromepalette, derive colors from your application with theme, or use okaidia, tomorrow, twilight or solarized-light for a dedicated Prism reading canvas. Every preset is included in the core stylesheet; no theme download, extra provider or different highlighter is needed. The selector below changes the real viewer, not a screenshot.

Usage PatternTypeScript
<Code code={source} language="tsx" syntaxTheme="okaidia" />
src/Welcome.tsx9 lines
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>;
}
PaletteReading characterA useful starting point
defaultFamiliar blue keywords and distinct token colors.Consistency with the rest of the documentation.
themePrimary and chart hues mixed with the current foreground.Source coloring that follows any of the eight application presets.
duskViolet declarations, teal strings and warm numeric values.Source that needs a different personality without a dark-only surface.
forestGreen keywords, olive strings and amber functions.A warmer, quieter alternative to blue-led syntax.
monochromeNeutral tokens, stronger keywords and italic comments.Readers who prefer structure and restrained emphasis over many colors.

The five Kamod palettes in this table follow the application appearance. The four Prism palettes below retain their own source background in either scheme: a dark Okaidia reader can sit inside a light page, and a cream Solarized reader can sit inside a dark page. The header and controls always follow the surrounding app. Changing a syntax palette never changes the source, clipboard text, grammar or reading preferences.

src/ThemeReader.tsx20 lines
import { Code, codeSyntaxThemes, type CodeSyntaxTheme } from "@kamod-ch/ui/code";
import { useState } from "preact/hooks";

export function ThemeReader({ source }: { source: string }) {
  const [syntaxTheme, setSyntaxTheme] = useState<CodeSyntaxTheme>("dusk");
  return (
    <section>
      <label>
        Syntax palette
        <select value={syntaxTheme}
          onChange={(event) => setSyntaxTheme(event.currentTarget.value as CodeSyntaxTheme)}>
          {codeSyntaxThemes.map((theme) => (
            <option key={theme} value={theme}>{theme}</option>
          ))}
        </select>
      </label>
      <Code code={source} language="tsx" syntaxTheme={syntaxTheme} />
    </section>
  );
}

codeSyntaxThemes provides the available IDs; CodeSyntaxTheme keeps your own selector typed. Persisting that choice is optional application state. A palette switch updates CSS variables only—it does not retokenize the same source.

Four Prism Palettes, One Familiar Reader

Compare the same source before choosing its colors. These studies use real Code components with identical tokens. Their palette families come from Prism 1.30's bundled themes. Kamod keeps the useful syntax distinctions and canvas colors, while preserving its own typography, spacing, rounded corners, controls and source links. The GitHub action on each study opens that palette's original stylesheet.

Okaidia

Prism Dark code canvas

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

// One clear action, one useful result.
export function Welcome() {
  const count = 3;
  return <Button disabled={false}>Open {count} items</Button>;
}

Cyan declarations, lime strings and warm function names on a charcoal canvas. A vivid Monokai-inspired starting point for JSX-heavy examples.

syntaxTheme="okaidia"

Tomorrow

Prism Dark code canvas

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

// One clear action, one useful result.
export function Welcome() {
  const count = 3;
  return <Button disabled={false}>Open {count} items</Button>;
}

Lavender keywords, peach functions and green strings on neutral gray. Tomorrow Night Eighties keeps a softer balance across long mixed-language files.

syntaxTheme="tomorrow"

Twilight

Prism Dark code canvas

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

// One clear action, one useful result.
export function Welcome() {
  const count = 3;
  return <Button disabled={false}>Open {count} items</Button>;
}

Cream declarations, muted olive strings and copper tags on an ink-dark canvas. A restrained TextMate-inspired palette with fewer competing accents.

syntaxTheme="twilight"

Solarized Light

Prism Light code canvas

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

// One clear action, one useful result.
export function Welcome() {
  const count = 3;
  return <Button disabled={false}>Open {count} items</Button>;
}

Blue properties, teal strings and olive keywords on warm cream. Its contrast-adjusted colors provide a light reading surface even inside a dark application.

syntaxTheme="solarized-light"

For a wider comparison, open the 24-theme Prism collection in the Theming guide. It includes original and community palettes, TSX/CSS/JSON samples, inspectable source colors, scoped CSS downloads and per-theme author credits.

The colors are scoped to an individual reader, so every palette can appear on the same page without overriding another. Some original small-text colors are strengthened for readability: Okaidia's pink, Twilight's comments and the Solarized Light token shades keep their color families with higher contrast. Tomorrow's inserted text uses its green string color. Decorative Prism shadows, font changes and plugin frames are deliberately omitted; the MIT attribution is preserved in the shipped stylesheet.

Keep the colors with their canvas

A pale lime string needs its dark Okaidia background. Importing several unscoped Prism stylesheets would also make their shared .token rules compete. Use syntaxTheme on Code to select the complete scoped palette instead. Choose an app-aware Kamod palette when the code surface should follow the page scheme automatically.

Code Prism Pipeline

Prism recognizes source; CSS gives the recognized pieces their appearance. These are independent stages. A TypeScript grammar identifies a declaration, string or punctuation. The selected syntax palette decides how those groups are painted. Your application theme supplies the surrounding surfaces and controls.

Kamod's Code keeps those responsibilities separated. It receives a literal source string, resolves a supported language, loads the shared highlighting implementation when needed, and presents highlighted markup. It preserves the original string for Copy even when the displayed imports are folded or the source wraps.

Follow One Line through the Reader

Usage PatternTypeScript
const message = "Hello";

A simplified highlighted result looks like this:

Markup StructureMarkup
<span class="token keyword">const</span> message <span class="token operator">=</span>
<span class="token string">"Hello"</span><span class="token punctuation">;</span>

The classes describe recognized groups. They are not color names, and their existence does not mean a stylesheet has been loaded. A palette can paint .token.keyword violet, cyan or a theme-derived tint without changing this markup. Unclassified text inherits the source foreground.

The viewer may add its own safe links and line markup around these tokens. That presentation is still separate from the string copied to the clipboard. A navigation link in displayed code does not insert an HTML anchor into the copied source.

Know When Each Stage Runs

Change Work that changes Work that stays reusable
Source string Language inference and highlighted source may change. The surrounding reader composition.
Language The grammar and resulting token classes may change. The original string.
syntaxTheme A root attribute and CSS colors. Highlighted token nodes, grammar and clipboard text.
App preset or scheme Inherited semantic values; app-aware syntax colors. Recognized source and reader state.
Import folding Which complete import lines are shown. Full source and highlighted content.
Wrapping Line layout and native overflow. Source characters and syntax classification.

Built-in palettes are shipped with the reader stylesheet. Selecting one is not a network request for a theme, and it does not import a second Prism instance. A source grammar can be deferred independently; plain text or highlight={false} has no colored token markup to restyle.

Prism's manual highlighting API describes the underlying string-to-markup operation. Kamod owns the reader lifecycle around it. Avoid calling Prism.highlightAll() after rendering Code: it does not know about the viewer's references, folded source, pending work or ownership of the DOM.

Keep Source Display Distinct from Execution

Neither choosing a grammar nor a palette runs the sample. Syntax highlighting is not validation, formatting, typechecking or a security review. A string containing a broken import can still receive sensible colors. A grammar can also classify an unfamiliar construct differently from what you expected.

For a language mismatch, use Language Selection. For unsafe external HTML, follow Safe Content Boundaries. Changing a keyword color cannot solve either problem.

Code Syntax Token Groups

Style the groups your grammar actually emits. A JavaScript string, a JSX attribute value and a CSS selector can take different paths through Prism, even when a palette intentionally gives them related colors. Inspect a highlighted element in browser tools rather than assuming its class from the word's appearance.

Map Prism Groups to Kamod Variables

Reader variable Common recognized groups What to verify
--kamod-code-keyword keyword, atrule, attr-value Declarations, at-rules and JSX values in your actual languages.
--kamod-code-string string, char, selector, attr-name, builtin, inserted Quoted text, CSS selectors, attributes and diff additions.
--kamod-code-function function, class-name Function calls and class/type-like identifiers recognized by the grammar.
--kamod-code-property property, tag, constant, symbol, deleted Object keys, markup tags and removed diff content.
--kamod-code-number number, boolean Numeric and boolean literals.
--kamod-code-variable variable, regex, important Regex literals and language-specific special emphasis.
--kamod-code-comment comment, prolog, doctype, cdata Small supporting text on the actual reading surface.
--kamod-code-punctuation punctuation Delimiters that should remain visible without dominating.
--kamod-code-operator operator, entity, url; some CSS strings Embedded languages, entities and operator symbols.

These are the reader's standard mappings, not a promise that every grammar emits all groups. The bundled Prism adaptations also retain useful exceptions: Tomorrow separates tags and function-name tokens; Okaidia groups some at-rules with functions; Solarized gives URLs its string treatment. A custom rule can refine one such exception without rewriting the entire viewer.

Preserve More than Keyword Color

A one-line .token.keyword rule is a useful experiment, but it is not a complete theme. Check ordinary unclassified text, strings, numbers, comments, punctuation, operators, selections, inserted/deleted content and long wrapped lines. A bright keyword can look excellent while the comment below it is unreadable.

src/source-colors.css11 lines
.product-source {
  --kamod-code-keyword: #6d28d9;
  --kamod-code-string: #0f766e;
  --kamod-code-comment: #526170;
}

.dark .product-source {
  --kamod-code-keyword: #c4b5fd;
  --kamod-code-string: #5eead4;
  --kamod-code-comment: #b5c1ce;
}

Put class="product-source" on the Code instance. These are illustrative starting colors for corresponding light/dark surfaces, not a universal contrast guarantee. The Theme Tokens palette is useful when you want a shared recipe instead of maintaining a second hand-authored pair.

Each standard token group also accepts -weight and -style suffixes. Use them sparingly. Grammar-specific bold, important and italic classes have their own emphasis; changing all code to semibold is usually less informative than preserving those distinctions.

Keep Linked Identifiers Readable as Code

Source navigation preserves token ink. Its dashed cue communicates that a component or package can be opened; it does not replace the source's syntax color with a normal link color. Check linked imports and their usages when tuning a palette, and retain a visible keyboard focus treatment.

The private documentation tooltips provide extra reference details lazily; that catalog is not part of Prism and does not determine token classification. In an application, the generic Source Link Resolver supplies navigation destinations independently of your color choices.

Code CSS Ownership

There are three boundaries to understand: the application's semantic tokens, the reader root, and the source itself. An override on the right boundary is easier to maintain than a long selector aimed at a token anywhere in the document.

Read the Reader's Structure

Markup StructureMarkup
<div class="kamod-code" data-syntax-theme="tomorrow">
  <!-- Optional metadata and reading controls use the application theme. -->
  <pre class="docs-code"><code class="language-typescript">…</code></pre>
</div>

The loading path can introduce a .kamod-code-content container around the source. Do not rely on a fixed child index or style the second div as if it were a public component slot. Prefer the documented variables on the Code root and use the existing source/header props for composition.

syntaxTheme is the supported typed palette selector. The actual root attribute is data-syntax-theme; an unrelated data-code-theme attribute from a generic Prism tutorial does not select Kamod's built-in palettes. Put an application-specific class on the reader to add a custom recipe without inventing a value outside CodeSyntaxTheme.

Let Each Instance Own Its Overrides

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

export function ProductSource({ source }: { source: string }) {
  return <Code code={source} language="tsx" class="product-source" />;
}

The core defaults reset token variables at each reader boundary. An inherited variable on a distant parent can therefore lose to a value declared on the reader. A class on the actual Code root makes the intended scope explicit and avoids recoloring unrelated snippets.

Core defaults use low-specificity :where(...) selectors. A focused product class can override them without !important. Still inspect cascade layers and the exact selector when another stylesheet wins: later source order only breaks ties between otherwise equally ranked rules.

Separate Source Paint from Panel Controls

Variable Affects
--kamod-code-surface The reader's shared panel surface.
--kamod-code-header The metadata/header surface.
--kamod-code-source-surface The source background, including a fixed Prism canvas.
--kamod-code-foreground Source foreground, before more specific token colors.
--kamod-code-font-family, -font-size, -line-height Source typography.

A named Prism palette supplies its own source background and base foreground so its colors remain coherent. It does not recolor the page, change the selected application preset or invert the application's scheme. Do not replace that background alone and assume every pastel token will remain readable.

Custom renderedContent is caller-owned markup. The syntax variables style highlighted source; they do not turn arbitrary JSX into a themed Markdown renderer. Ordinary inline code and a displayed Markdown string are also different things: the former is document content, the latter can be tokenized as source.

Code Prism Stylesheet Ports

Use a bundled palette first when it fits. Okaidia, Tomorrow, Twilight and Solarized Light are already included through the reader stylesheet, so using them requires no extra CSS package or Prism setup:

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

<Code code={'const result = "ready";'} language="typescript" syntaxTheme="tomorrow" />;

For more options, start with the official Prism stylesheets or the Prism Themes collection. Read the theme's actual file and license. Names shared with an editor theme do not guarantee that every port assigns the same color to the same token.

The Prism palette studies compare 24 saved original and community themes in this documentation, with shared language samples, exact source colors and scoped reader recipes. Each chapter links its pinned stylesheet and author; the source notes explain attribution and what the previews preserve.

Understand a Direct Stylesheet Import

A conventional standalone Prism host can load a stylesheet from its installed package:

Style RulesCSS
/* Standalone Prism markup, outside Kamod's multi-palette reader. */
@import "prismjs/themes/prism-tomorrow.css";

That example assumes the package is installed and your CSS pipeline resolves package imports. The stylesheet contains broad token and source rules. It is not scoped to one Kamod reader, and the theme file can also change fonts, padding, shadows or wrapping.

If you choose an additional collection, install it in the application that owns the CSS build:

Install PackagesTerminal
pnpm add -D prism-themes

For example, the collection provides prism-themes/themes/prism-dracula.css. Importing multiple raw theme files globally does not create a selector. Their shared .token rules compete in the normal cascade. For Kamod, convert the colors into a reader class, or carefully scope a complete stylesheet before importing the result.

Port a Palette through the Reader Variables

The following is a compact Dracula-family adaptation, not a new built-in palette ID. The source colors come from the Prism Themes port; the comment is strengthened for small text. Preserve its MIT license and attribution with any distributed adaptation.

src/code-dracula.css14 lines
/* Dracula-family adaptation of PrismJS/prism-themes (MIT). */
.source-dracula {
  --kamod-code-source-surface: #282a36;
  --kamod-code-foreground: #f8f8f2;
  --kamod-code-comment: #a5b0d3;
  --kamod-code-punctuation: #f8f8f2;
  --kamod-code-keyword: #8be9fd;
  --kamod-code-property: #ff79c6;
  --kamod-code-number: #bd93f9;
  --kamod-code-string: #50fa7b;
  --kamod-code-function: #f1fa8c;
  --kamod-code-operator: #f8f8f2;
  --kamod-code-variable: #ffb86c;
}
Usage PatternTypeScript
import { Code } from "@kamod-ch/ui/code";

export function DraculaSource({ source }: { source: string }) {
  return <Code code={source} language="tsx" class="source-dracula" />;
}

Load that local stylesheet after the chosen foundation and reader styles. The class is enough; syntaxTheme="dracula" is not a supported built-in ID. Add individual grammar exceptions only when your content needs them. Keep their selectors within that reader and inspect nested token spans before increasing specificity.

The variable recipe deliberately keeps Kamod's existing token grouping. A pixel-for-pixel upstream port also needs the upstream exceptions for attribute values, variables, URLs, at-rules, selections and emphasis. Decide whether exact historical fidelity is worth that extra policy; a consistent product adaptation is often easier to read and maintain.

Scope a Complete Third-Party File Deliberately

When a full CSS port is necessary, retain a reviewed vendor copy and its license, then scope every selector in every selector list to the intended reader. Handle code, pre, .token, .namespace, ::selection and nested language selectors; prefixing only .token.keyword leaves the rest global.

src/vendor/product-prism.css4 lines
/* A small, scoped exception after the variable-based palette. */
.source-dracula > :is(.docs-code, .kamod-code-content) .token.attr-value {
  color: #f1fa8c;
}

Do not blindly prefix @font-face, @keyframes or @import as though they were ordinary selectors. Review plugin-specific rules separately, and remove layout declarations you intend Code to own. A CSS parser is safer than a search-and-replace expression when automating a real vendor port.

Pin the chosen package or revision in your normal dependency workflow. Record deliberate contrast changes and retain the upstream license. Updating the highlighter grammar, updating a palette and updating a CSS scoping transform are separate maintenance tasks with different things to verify.

Code Palette Verification

Review a palette on the surfaces and languages where it will actually be used. A pleasing color wheel or a single JavaScript line cannot reveal every grouping, fallback or layout problem.

Build a Useful Verification Sample

Include comments, imports, linked package strings, numbers, booleans, punctuation, function calls and unclassified text. Add JSX attributes, CSS selectors/URLs, JSON properties and diff additions/removals if those languages matter to your product. Use long lines and a narrow container as well as a short example.

Check Why it matters
Small body text contrast Ordinary code and comments are usually normal-size text, so aim for at least 4.5:1 against the actual painted surface.
Text selection Selected source must remain readable even when browser default selection colors differ.
Plain text and loading Unclassified source should be readable before highlighting and when highlighting is disabled.
Source navigation A dashed cue and keyboard focus must remain distinguishable without changing syntax ink.
Header and controls A fixed dark source canvas can sit below light controls; check that deliberate boundary.
Neighboring readers Switching one palette should not recolor another or change its source.
Wrapping and copy Typography can change line layout; it must not change the copied string.
Zoom and narrow screens Color does not compensate for clipped controls or text that cannot scroll.

Diagnose the Correct Layer

If no token spans exist, check the language, highlight setting and highlighter readiness. If spans exist but all ink is inherited, check reader CSS loading and winning token declarations. If only one grammar group differs, inspect that group's actual class and a palette-specific exception. If the source surface is correct but the header looks wrong, inspect application tokens and header rules instead of editing Prism.

For a palette change, keep an existing highlighted node reference in a browser test and verify it is reused. Also check original text and Copy. For theme-derived colors, switch app presets and schemes, including a nested theme scope, and inspect the computed colors without expecting another grammar request.

Color is a reading aid. Users must still be able to select source, read it without syntax colors, discover links with a keyboard and copy the complete example. Keep those capabilities in the accessibility review when making the palette more expressive.

Code Theme Tokens

Preview only your page stays as it is
// Your app's palette, expressed as source.
export function greet(name = "Kamod") {
  const count = 3;
  return { message: name, ready: true, count };
}
Declarations
--primary
Functions
--chart-1
Strings
--chart-2
Properties
--chart-3
Numbers
--chart-4
Variables
--chart-5

Let the application palette give source its own voice. Set syntaxTheme="theme" to derive syntax colors from the semantic tokens already supplied by your theme. The preview above starts with Ocean, but its controls can compare all eight application presets in both appearances. Its selection is local: it does not change the navigation, your saved preferences or another reader.

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

export function ProductSource({ source }: { source: string }) {
  return <Code code={source} language="tsx" syntaxTheme="theme" />;
}

This is an opt-in syntax palette, not a second theme manager. The default remains syntaxTheme="default". There is no theme download, new provider or per-reader storage subscription. A preset change updates inherited CSS variables; Prism's existing token elements keep their identities. The reader's frame and controls continue using the same application roles as before.

Map Application Roles to Syntax Roles

The palette uses the primary accent for declarations and the chart family for related syntax distinctions. Chart tokens are useful here because a complete Kamod theme already defines several coordinated hues. They are inputs to the syntax palette, not a claim that functions are charts or that every brand color is suitable for small text on its own.

Source group Application input What the resulting color helps identify
--kamod-code-keyword --primary Declarations, imports and control flow.
--kamod-code-function --chart-1 Functions and class names.
--kamod-code-string --chart-2 Strings, selectors and attribute names.
--kamod-code-property --chart-3 Properties, tags, constants and deleted tokens.
--kamod-code-number --chart-4 Numbers and booleans.
--kamod-code-variable --chart-5 Variables, regular expressions and important tokens.
--kamod-code-comment --muted-foreground Comments and document declarations.
Punctuation and operators Existing reader defaults Delimiters and operators remain visually quieter.

Each chart lookup falls back to --primary when that chart variable is missing. A minimal theme therefore produces a coordinated accent rather than an invalid color. It still needs valid --primary, --foreground and --muted-foreground values. Use the Full Theme Foundation for the complete role contract, or define the required inputs yourself.

Mix for Small Text, Not Just Brand Recognition

A vivid swatch is not automatically a readable glyph. The palette blends 30% of each hue with 70% of the current foreground in the oklab color space. This keeps a recognizable relationship to the brand while moving thin source text toward the application's readable ink. The comment group instead mixes 40% muted foreground with 60% foreground, so comments remain secondary without fading as far as a large caption might.

Style RulesCSS
/* The keyword rule used by syntaxTheme="theme". */
:where(.kamod-code[data-syntax-theme="theme"]) {
  --kamod-code-keyword: color-mix(in oklab, var(--primary) 30%, var(--foreground));
  --kamod-code-string: color-mix(in oklab, var(--chart-2, var(--primary)) 30%, var(--foreground));
  --kamod-code-comment: color-mix(in oklab, var(--muted-foreground) 40%, var(--foreground));
}

These percentages are color weights, not opacity. A 30% hue mix does not make the code 30% visible and does not reveal a background through the letters. Its other 70% comes from foreground ink. In light mode that generally pulls bright colors toward darker text; in dark mode it pulls them toward lighter text. The actual result depends on the selected theme's endpoints.

Keep that distinction when tuning a custom palette: lowering an element's opacity would also fade its text, decorations and descendants. Changing a syntax variable affects only the assigned token group. If your product uses a colored or translucent code surface, verify the final composited background rather than assuming the mix guarantees contrast on every surface.

Follow the Nearest Theme Boundary

The reader uses inherited tokens from its closest scope. A page-wide preset, a nested preview or a dashboard with its own palette can each supply them. The complete theme stylesheet establishes scoped defaults on data-theme-scope; the preset attribute supplies the brand, and the local light or dark class selects its appearance.

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

export function LocalPalette({ source }: { source: string }) {
  return (
    <section data-theme-scope="" data-theme="watson" class="dark">
      <Code code={source} language="typescript" syntaxTheme="theme" />
    </section>
  );
}

Load the full theme foundation once before using this boundary. This example owns a local appearance; it does not toggle the document root. Put the boundary on a wrapper around Code so its variables are inherited by the reader. If a surrounding overlay uses a portal, place the intended theme boundary where that portal renders too. See Theme Scope and Inheritance for the general rules.

Because the palette reads the current roles, it works with Kamod, shadcn, Ocean, Sunset, Cursor warm, Voltage, Watson and Professional without eight separate syntax implementations. It also follows custom presets that supply the same semantic contract. Selecting a different application theme does not change the Code language, its source or the meaning of its token groups.

Code Product Palette

Start with the token palette, then refine the distinctions your source actually needs. This gives a product its own code coloring without maintaining a parallel copy of every theme. Use a class to keep exceptions local, and leave unmodified groups connected to the application palette.

Build a Small Brand Recipe

Suppose an API guide needs declarations to feel slightly more prominent and strings to keep a calmer hue. Give that reader a class, retain the semantic palette and override just those roles. The values below are an example recipe; compare them with real snippets before adopting them for your own backgrounds.

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

export function ApiSource({ source }: { source: string }) {
  return <Code code={source} language="typescript" syntaxTheme="theme" class="api-source" />;
}
Style RulesCSS
/* Load this after your shared theme and Code styles. */
.api-source {
  --kamod-code-keyword: color-mix(in oklab, var(--primary) 35%, var(--foreground));
  --kamod-code-string: color-mix(in oklab, var(--chart-2, var(--primary)) 25%, var(--foreground));
  --kamod-code-keyword-weight: 600;
  --kamod-code-comment-style: italic;
}

This recipe follows both appearances through the same foreground token; no dark selector is needed. Use a separate light/dark override only when the intended color relationship genuinely changes. Prefer a scoped semantic input when the whole product area should change, and a Code variable when only source presentation should change. Avoid changing --primary globally just to adjust a keyword.

Give a Product Theme a Stable Contract

A named application preset defines the values; Code consumes their roles. Keep custom values near the rest of that preset rather than embedding brand names in the component. The compact example below shows the relevant inputs, not a complete replacement for every theme token.

Style RulesCSS
/* Extend the installed theme; keep its other semantic roles. */
[data-theme-scope][data-theme="studio"] {
  --primary: oklch(0.48 0.16 275);
  --chart-1: oklch(0.48 0.14 280);
  --chart-2: oklch(0.46 0.1 175);
  --chart-3: oklch(0.48 0.12 335);
  --chart-4: oklch(0.48 0.1 70);
  --chart-5: oklch(0.48 0.13 235);
}

[data-theme-scope][data-theme="studio"].dark {
  --primary: oklch(0.78 0.12 275);
  --chart-1: oklch(0.78 0.1 280);
  --chart-2: oklch(0.78 0.09 175);
  --chart-3: oklch(0.78 0.1 335);
  --chart-4: oklch(0.78 0.1 70);
  --chart-5: oklch(0.78 0.1 235);
}

Use data-theme="studio" on the wrapper from the previous example to activate these CSS values. This CSS-only custom name is not automatically registered with ThemePresetId, the theme picker or a persistence API that accepts only the built-in IDs. Register application-level choices in your own model when you need them. The Code API still receives the supported syntaxTheme="theme"; it does not need a new syntax ID for every product brand.

Keep a Palette Maintainable

Review a change with a short, representative sample: one import, an ordinary function, a property, a string, a number, a boolean and a comment. Add JSX, CSS or Markdown when those are real parts of the product. Check plain source as well as highlighted source: punctuation and unclassified text need readable ink too. A successful theme preserves the structure of the example before showcasing its colors.

Use weight or italics sparingly. Heavier keywords can help scanning, but making every group bold removes hierarchy and may change the apparent density of a long example. Keep links and dashed reference cues distinguishable without overriding Prism's text colors. The Reference Layer adds navigation separately from syntax classification.

If you need a fixed dark or light editor palette rather than a brand-aware one, use a Bundled Prism Palette or follow the Stylesheet Porting Guide. If you need a different header, spacing or line treatment, continue with Typography and Composition. These choices can be combined, but each should have one clear owner.

Choose Once for Several Readers

Lift the preference to the component that owns the readers. The selector does not need to be repeated in every code header. Store one typed choice in the parent, then pass it to each Code instance. A single prop can also fix a palette for an article or example. Code has no hidden global preference, storage listener or browser-only theme initialization.

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

type Sources = { before: string; after: string };

export function CompareSources({ before, after }: Sources) {
  const [syntaxTheme, setSyntaxTheme] = useState<CodeSyntaxTheme>("tomorrow");
  return (
    <section>
      <button onClick={() => setSyntaxTheme("solarized-light")}>
        Read on a light canvas
      </button>
      <Code code={before} filePath="before.tsx" syntaxTheme={syntaxTheme} />
      <Code code={after} filePath="after.tsx" syntaxTheme={syntaxTheme} />
    </section>
  );
}

If a preference should survive navigation or reloads, own that decision above the page and validate a saved ID against codeSyntaxThemes. Follow Persisted Signals for an existing storage pattern. During server rendering, start with a consistent default and apply browser-only preferences after hydration. A palette switch changes CSS variables and token rules; it does not fetch a theme or run Prism again.

Three Choices, Three Separate Responsibilities

language decides which grammar recognizes the source. syntaxTheme decides how those recognized tokens look. variant decides how much framing the panel uses. A named Prism palette also supplies its source canvas; your app still owns the header, controls, borders and light/dark scheme. The default/subtle/outline variants remain most visible with app-aware palettes. With a Prism palette, its readable canvas stays constant while the surrounding frame adapts.

Usage PatternTypeScript
<Code
  code={source}
  language="typescript"
  syntaxTheme="forest"
  variant="outline"
/>
Syntax colors are not a page theme

The example uses TypeScript highlighting, Forest token colors and an outlined panel. Its header and controls continue to belong to your app. For broader changes, follow Theming; for only the frame, compare Surface Variants.

Plain text has no syntax tokens to recolor, although a Prism preset can still supply its source canvas and foreground. Likewise, highlight={false} skips token markup, and renderedContent supplies its own presentation. A palette cannot add missing grammar support. Start with Language Selection if recognized source is the part that needs changing.

Tune a Few Tokens before Designing a Whole Palette

Put a class on Code and override its --kamod-code-* variables in your stylesheet. Keep the class local to the panels you intend to change. The rules below build on Dusk; unmodified colors continue to come from that preset. Place your stylesheet after the shared theme import.

Usage PatternTypeScript
<Code code={source} language="tsx" syntaxTheme="dusk" class="product-source" />
src/product-source.css11 lines
.product-source {
  --kamod-code-keyword: #6d28d9;
  --kamod-code-string: #0f766e;
  --kamod-code-comment-style: italic;
  --kamod-code-keyword-weight: 600;
}

.dark .product-source {
  --kamod-code-keyword: #c4b5fd;
  --kamod-code-string: #5eead4;
}

The Syntax Token Reference lists each color variable and its grammar groups. Each group also accepts -weight and -style suffixes, such as --kamod-code-comment-style. Grammar-specific bold and italic tokens retain their own emphasis. The import control’s keyword shares --kamod-code-keyword with source keywords for app-aware palettes. Prism readers retain application foreground for that control so a pale source keyword is not placed on a light header. A Prism-specific token distinction—such as Tomorrow's separate tag color—can be refined with a locally scoped .token.tag rule when needed.

Token names describe highlighting groups, not a complete syntax tree. One language may emit nested tokens or classify a construct differently from another. Check your actual source in both schemes and every surface you use. Choose readable contrasts; a color should help recognition without becoming the only way to understand the code.

Make the Reading Rhythm Your Own

Typography variables affect the source area without enlarging its header or controls. Use --kamod-code-font-family, --kamod-code-font-size, --kamod-code-line-height and --kamod-code-foreground. Override--kamod-code-source-surface to change only the source background, including a Prism canvas; keep text and token colors readable on the replacement surface. A slightly roomier line height often does more for a long example than another color.

src/reading.css6 lines
.comfortable-source {
  --kamod-code-font-family: ui-monospace, "SFMono-Regular", Consolas, monospace;
  --kamod-code-font-size: 0.875rem;
  --kamod-code-line-height: 1.8;
  --kamod-code-comment-style: italic;
}
Usage PatternTypeScript
<Code
  code={source}
  filePath="src/Welcome.tsx"
  syntaxTheme="monochrome"
  class="comfortable-source"
  defaultWrapped
/>

Supply your own font only if it is already available or loaded by your application. Code does not fetch fonts. Keep a monospace fallback so indentation and wrapped continuation lines remain predictable. Use a regular style for most tokens and reserve italics or heavier weight for a few useful distinctions.

For a custom surface, the same root accepts --kamod-code-surface and --kamod-code-header. Review text and controls together when changing their backgrounds. Continue with Composition and Theming for layout, or Accessibility for keyboard and reading checks.

Reading Preferences

Import folding and line wrapping stay independent. Choose defaults, preserve the complete source, and decide whether preferences carry across file selections.

Collapse Declarations, Keep the Explanation

The import control counts statements, not imported names or lines. One multiline import with six names is one statement. Leading static JavaScript and TypeScript imports can be folded, including type-only imports. CSS @import rules also support URL targets, layers and media conditions. Comments and directives remain visible; dynamic import() calls and imports after executable code are not folded.

Folding removes the declarations from the displayed source and closes the whitespace at those joins. It does not leave an empty box for each hidden line. If the entire snippet only contains imports, a collapse control would hide the useful example, so it is omitted. Eligible import and wrap controls appear together when the complete source would overflow; long hidden imports still count, so you can always expand them again. Use showImportControl={false} when every declaration should stay visible.

src/styles/theme.css6 lines
@import "tailwindcss";
@import "@kamod-ch/themes/theme.css";

:root {
  --radius: 0.625rem;
}

Wrap for Reading, Preserve the Real Line

Wrapping operates on the presentation of each source line. Continuations receive readable indentation, and very deep indentation is constrained when space becomes scarce. A line that already fits should retain its original alignment. On narrow panels, long content can break rather than force the whole page to scroll sideways.

A wrapped continuation is not a new source line. Copy still returns the original line, not the visual layout. Use defaultWrapped for prose-like prompts and long attributes; leave it off when exact columns matter, such as an aligned text report. Wrapping works for every language, including commands, text and Markdown. Core readers use readingControls="overflow" by default; choose "always" to retain eligible controls at every width, or "imports" to show them only on snippets containing imports. Documentation readers use that last policy, so snippets without imports have neither control. Use showWrapControl={false} for a fixed reading mode.

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

Here, source is your source string. This composition starts wrapped and removes the control, which is useful when a containing layout has one fixed reading mode.

Choose What Resets When the File Changes

By default, the import and wrap controls own their state. The defaultWrapped and defaultImportsCollapsed props choose initial behavior; they are not controlled-state props. Changing the source resets import folding to its default. Wrap preference remains with the mounted instance so a reader can carry it across files.

For preferences shared across panels, supply wrapped and importsCollapsed with their change callbacks instead. Controlled values remain owned by your app when the file changes. See Own the Reading State for a live example.

When each file should start fresh, give Code a stable key based on the selected path. When the reader’s wrapping preference should carry over, leave that key off. File navigation itself belongs to your surrounding UI, using a Tree, Tabs or your own simple list.

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

type SourceFile = { path: string; source: string };

export function SelectedFile({ file }: { file: SourceFile }) {
  return (
    <Code
      key={file.path}
      code={file.source}
      filePath={file.path}
      defaultImportsCollapsed
      defaultWrapped
    />
  );
}

Build Your Own Reader

Choose which parts stay visible, connect shared preferences, or replace one action. The source stays in one place.

Choose How Much of the Reader to Show

Start with the source, then choose the surrounding tools. The earlier plain examples need no extra bar; a file viewer may benefit from a path, Copy and reading preferences. Try the switches below to compare those compositions and keep only the parts your interface needs.

Visible parts

Your reader, your choices. Switch a part off and see the panel adapt.

Header & actions

Give the source a little context.

A shared home for the file and actions.

Show the file name above the source.

Copy the full file, including folded imports.

Reading experience

Keep the details easy to explore.

Tuck setup away; keep the example in focus.

Let readers wrap long lines to fit the panel.

Make keywords and values easier to scan.

One shared header. File label and Copy appear inside it. Hide the header and your choices are kept for when it returns.

Your code panelChanges stay in this example
src/Welcome.tsx9 lines
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>;
}
Code visibility options and what remains available
Option / purposeWhat stays
showToolbar={false}A source-only, headerless panelReading controls stay above the source. The file label and Copy action disappear with the header.
showCopy={false}Remove the clipboard actionThe header and reading controls stay. Readers can still select the source themselves.
showImportControl={false}Keep every import visibleThe complete source stays visible. This also disables import folding; Copy continues to include every declaration.
showWrapControl={false}Keep the wrapping choice fixedYour wrapping choice still applies. Choose the layout with defaultWrapped or controlled wrapped.
highlight={false}Read the source without syntax colorsOnly the syntax colors change. Language metadata, reading controls, source selection and exact copying remain available.
Usage PatternTypeScript
<Code
  code={source}
  language="tsx"
  showToolbar={false}
  showImportControl={false}
  showWrapControl={false}
  defaultWrapped
/>

This expression assumes source is your string. Hiding a control never grants new capabilities: commands still omit the wrapping switch and unsupported import syntax remains visible. Read Reading Preferences for the eligibility rules.

Let the Reader Choose—or Share the Choice

For one independent example, use defaultWrapped and defaultImportsCollapsed. Code owns later changes. For a file browser, a preferences toolbar or several synchronized panels, provide wrapped and importsCollapsed with their change callbacks instead. Your state becomes the single source of truth.

Shared reading preferences
src/Welcome.tsx9 lines
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>;
}
src/SharedReader.tsx19 lines
import { Code } from "@kamod-ch/ui/code";
import { useState } from "preact/hooks";

const source = 'import { Button } from "@kamod-ch/ui/button";\n\nexport const Save = () => <Button>Save</Button>;';

export function SharedReader() {
  const [wrapped, setWrapped] = useState(true);
  const [importsCollapsed, setImportsCollapsed] = useState(false);
  return (
    <Code
      code={source}
      filePath="src/Save.tsx"
      wrapped={wrapped}
      onWrappedChange={setWrapped}
      importsCollapsed={importsCollapsed}
      onImportsCollapsedChange={setImportsCollapsed}
    />
  );
}

Click either the external checkbox or Code’s control: both update the same state. A controlled value changes only when your application supplies its next value; a callback is a request, not an automatic mutation. Supplying a value without a callback intentionally fixes that preference. Choose controlled or uncontrolled ownership when mounting and keep that choice stable.

Uncontrolled wrapping carries across source changes; uncontrolled import folding resets to its default for a different code string. Controlled preferences remain yours across files. Store preferences above the viewer if you want them to survive unmounting; Code does not read or write browser storage.

Replace One Control without Replacing Its Behavior

Use renderWrapControl, renderImportControl or renderCopyAction when a switch, menu or custom button fits your product better. Each callback receives the current state, the source ID, its action and defaultControl. Return your own element, wrap the default element, or return null to omit the visible control.

src/Welcome.tsx9 lines
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>;
}
src/CustomReader.tsx27 lines
import { Button } from "@kamod-ch/ui/button";
import { Code } from "@kamod-ch/ui/code";

export function CustomReader({ source }: { source: string }) {
  return (
    <Code
      code={source}
      language="tsx"
      renderWrapControl={({ codeId, wrapped, onWrappedChange }) => (
        <Button
          type="button"
          variant="outline"
          aria-controls={codeId}
          aria-pressed={wrapped}
          onClick={() => onWrappedChange(!wrapped)}
        >
          Wrap {wrapped ? "on" : "off"}
        </Button>
      )}
      renderCopyAction={({ defaultControl }) => (
        <span class="inline-flex" title="Copy the complete source, including folded imports">
          {defaultControl}
        </span>
      )}
    />
  );
}
Keep the behavior; own the presentation

The copy action still handles the complete source, clipboard failures and its live status announcement. Your button supplies its label, disabled state and keyboard interaction. Use aria-controls for the source, aria-pressed for a toggle and aria-expanded for import disclosure. A native Button keeps activation familiar.

Import and wrap callbacks run only when that control is eligible. Returning null from renderImportControl can hide its button while controlled folding still works; showImportControl={false} disables folding altogether. Copy renderers receive idle, copying, copied or error. Call the supplied copy() once; do not start a second clipboard write or add a second live region.

Build the Frame Around the Source

Use toolbarContent for a short purpose label and renderFilePath to replace the file presentation while retaining inference metadata. For a fully arranged header, renderToolbar receives the existing action group. Render it once wherever it belongs. Header Composition shows a complete example.

Usage PatternTypeScript
<Code
  code={source}
  filePath="src/Welcome.tsx"
  beforeCode={<p class="px-4 py-3 text-sm">Place this file beside your route.</p>}
  afterCode={<p class="px-4 py-3 text-sm">Adapt the action to your workspace.</p>}
/>

beforeCode sits after the reading controls; afterCode sits after the source or prepared document. Both accept Preact content and are excluded from Copy. Use them for a concise note or related link. To replace the entire source presentation with a document, use renderedContent. That mode omits code reading controls and highlighting while retaining the original string for copying.

Composition and Theming

Use surface variants, root layout classes and header composition before replacing control markup.

Choose a Surface before Adding Custom Styles

Use variant="default" for the familiar framed code surface, subtle when the snippet sits inside another quiet reading area, and outline when the surrounding background should remain visible. The Surface Comparison lets you inspect the same source in each variant.

Set class on the root for width, placement and layout. Use preClassName for the source area, such as a local height limit. className remains an alias for that source-area class; prefer the more explicit prop in new code so it cannot be mistaken for the root class.

Usage PatternTypeScript
<Code
  code={source}
  filePath="src/long-example.ts"
  variant="outline"
  class="w-full max-w-3xl"
  preClassName="max-h-96"
/>

This expression assumes source is a string. A height limit contains scrolling inside the source panel; it does not virtualize or reduce the amount of source rendered. For large inputs, follow Performance and Delivery.

Adapt the Header, Retain the Built-in Actions

For a short label or badge beside the existing actions, supply toolbarContent. A file path remains the most useful label when the snippet has a real destination. When your header needs a different arrangement, use renderToolbar and render the supplied actions exactly once.

The actions value can contain both wrapping and Copy, depending on the source and controls you enabled. It is not always only a copy button. The Custom Header example hides the wrap switch deliberately, then places the remaining action opposite a small contextual label. The separate import row, when present, continues to use the shared layout.

CodeFileHeader and CodeSnippetLabel are available for more involved compositions. Use CodeFileHeader when you need the shared file icon, path and optional line count inside a custom header. Do not put its content inside another interactive control.

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

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

export function NamedExample() {
  return (
    <Code
      code={source}
      language="typescript"
      renderToolbar={(actions) => (
        <div class="flex flex-wrap items-center justify-between gap-3 border-b border-border p-4">
          <CodeFileHeader path="src/status.ts" lineCount={1} />
          {actions}
        </div>
      )}
    />
  );
}

Let the Theme Carry the Visual Language

The component follows the shared semantic surface, foreground and border tokens, with syntax colors that remain legible in light and dark modes. Change the site theme to compare them in the examples. You do not need a separate code theme provider or a hard-coded dark background.

To give source tokens a different palette, use syntaxTheme. The Syntax Themes and Typography guide compares the available presets and documents local color, font and emphasis overrides. For replacing controls or adding content slots, continue to Build Your Own Reader.

Use the Theme Token Guide for application-wide changes, and Theme Toggle for an appearance control. Keep source text, filename labels, focus rings and disabled states readable together; a pleasing surface should still leave the code easy to scan.

Performance and Delivery

Load highlighting for the file a reader opens, avoid replacing stable strings, and keep large generated documents out of an ordinary example.

Start Readable, Highlight Near the Viewport

Code first renders the escaped source, then invokes the supplied highlighter near the visible area. Make the adapter dynamically import its syntax engine so that engine is not added to every route’s initial work. Language selection uses small bounded checks, and expensive derived display strings are reused until their inputs change.

The component disconnects visibility observers and ignores stale highlighting results when its source changes or it unmounts. Copy-feedback timers are also cleaned up. Avoid wrapping it in an effect that repeatedly replaces identical source, and keep your own file fetches cancellable so a slower previous selection cannot overwrite the current one.

Keep Examples Focused and File Viewers Selective

Code is a source viewer, not a virtualized editor. All displayed source is rendered and highlighted; a visual height limit does not change that. Prefer one focused excerpt in a guide and load a full file only when the reader opens it. For a file tree, mount the selected source rather than dozens of hidden Code instances.

For unusually large logs or generated files, consider a plain-text excerpt with inferLanguage={false}, a download link, or a specialized virtualized viewer. Keep the label honest about whether Copy copies the excerpt or the complete file. The component always copies exactly the code you pass.

Keep the First Render Deterministic

Source text and controls can render on the server without clipboard or layout access. Highlighting and browser clipboard work happen on the client. Send the same source, file metadata and default reading preferences to the server and the first client render to avoid an unnecessary content change during hydration.

A theme initialization strategy still belongs at your app entry. Follow Appearance Preferences to keep the first paint consistent; do not inspect browser storage inside every Code panel.

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.