Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

feat: XDSCodeBlock + XDSCodeEditor — native CSS Highlight API (#741)

Cindy Zhang862d1c835dc7
diff --git a/apps/storybook/stories/CodeBlock.stories.tsx b/apps/storybook/stories/CodeBlock.stories.tsx
new file mode 100644
index 0000000000..19cc9f5cff
--- /dev/null
+++ b/apps/storybook/stories/CodeBlock.stories.tsx
@@ -0,0 +1,280 @@
+import type {Meta, StoryObj} from '@storybook/react';
+import {XDSCodeBlock} from '@xds/lab';
+
+const meta: Meta<typeof XDSCodeBlock> = {
+ title: 'Lab/XDSCodeBlock',
+ component: XDSCodeBlock,
+ tags: ['autodocs'],
+ argTypes: {
+ language: {
+ control: 'select',
+ options: [
+ 'typescript',
+ 'javascript',
+ 'json',
+ 'html',
+ 'css',
+ 'python',
+ 'bash',
+ 'php',
+ 'hack',
+ 'yaml',
+ 'markdown',
+ 'plaintext',
+ ],
+ description: 'Language for syntax highlighting',
+ },
+ size: {
+ control: 'select',
+ options: ['sm', 'md'],
+ description: 'Text size',
+ },
+ hasLineNumbers: {control: 'boolean'},
+ hasCopyButton: {control: 'boolean'},
+ isWrapped: {control: 'boolean'},
+ },
+};
+
+export default meta;
+type Story = StoryObj<typeof XDSCodeBlock>;
+
+const tsExample = `import {useState, useEffect} from 'react';
+
+interface User {
+ id: string;
+ name: string;
+ email: string;
+}
+
+async function fetchUser(id: string): Promise<User> {
+ const response = await fetch(\`/api/users/\${id}\`);
+ if (!response.ok) {
+ throw new Error(\`HTTP \${response.status}\`);
+ }
+ return response.json();
+}
+
+export function useUser(id: string) {
+ const [user, setUser] = useState<User | null>(null);
+
+ useEffect(() => {
+ fetchUser(id).then(setUser);
+ }, [id]);
+
+ return user;
+}`;
+
+export const Default: Story = {
+ args: {
+ code: tsExample,
+ language: 'typescript',
+ title: 'useUser.ts',
+ hasLineNumbers: true,
+ hasCopyButton: true,
+ },
+};
+
+export const WithHighlightedLines: Story = {
+ args: {
+ code: tsExample,
+ language: 'typescript',
+ title: 'useUser.ts',
+ hasLineNumbers: true,
+ highlightLines: [9, 10, 11, 12, 13],
+ },
+};
+
+export const JSON: Story = {
+ args: {
+ code: `{
+ "name": "@xds/core",
+ "version": "0.0.5",
+ "dependencies": {
+ "@stylexjs/stylex": "^0.17.5",
+ "react": "^19.0.0"
+ },
+ "scripts": {
+ "build": "tsup",
+ "test": "vitest"
+ }
+}`,
+ language: 'json',
+ title: 'package.json',
+ hasLineNumbers: true,
+ },
+};
+
+export const Python: Story = {
+ args: {
+ code: `#!/usr/bin/env python3
+"""Data processing pipeline."""
+
+from dataclasses import dataclass
+from typing import List, Optional
+
+@dataclass
+class Config:
+ input_path: str
+ output_path: str
+ batch_size: int = 100
+
+def process(config: Config) -> None:
+ """Process data according to config."""
+ print(f"Processing {config.input_path}")
+ # TODO: implement pipeline
+ pass
+
+if __name__ == "__main__":
+ cfg = Config("input.csv", "output.csv")
+ process(cfg)`,
+ language: 'python',
+ title: 'pipeline.py',
+ hasLineNumbers: true,
+ highlightLines: [7, 8, 9, 10, 11],
+ },
+};
+
+export const HTML: Story = {
+ args: {
+ code: `<!DOCTYPE html>
+<html lang="en">
+ <head>
+ <meta charset="utf-8" />
+ <title>Hello World</title>
+ <link rel="stylesheet" href="styles.css" />
+ </head>
+ <body>
+ <main id="app">
+ <h1>Hello, World!</h1>
+ <p class="subtitle">Welcome to XDS.</p>
+ </main>
+ <script src="app.js"></script>
+ </body>
+</html>`,
+ language: 'html',
+ title: 'index.html',
+ hasLineNumbers: true,
+ },
+};
+
+export const CSS: Story = {
+ args: {
+ code: `:root {
+ --color-primary: #0064E0;
+ --radius: 8px;
+}
+
+.button {
+ display: inline-flex;
+ align-items: center;
+ padding: 8px 16px;
+ border-radius: var(--radius);
+ background-color: var(--color-primary);
+ color: white;
+ font-weight: 600;
+ transition: opacity 0.15s ease;
+}
+
+.button:hover {
+ opacity: 0.9;
+}
+
+@media (prefers-color-scheme: dark) {
+ :root {
+ --color-primary: #2694FE;
+ }
+}`,
+ language: 'css',
+ title: 'button.css',
+ hasLineNumbers: true,
+ },
+};
+
+export const Bash: Story = {
+ args: {
+ code: `#!/bin/bash
+# Deploy script for production
+
+set -euo pipefail
+
+DEPLOY_DIR="/opt/app"
+VERSION=$(git describe --tags --always)
+
+echo "Deploying version $VERSION..."
+
+if [ ! -d "$DEPLOY_DIR" ]; then
+ mkdir -p "$DEPLOY_DIR"
+fi
+
+yarn build
+cp -r dist/* "$DEPLOY_DIR/"
+
+echo "Deploy complete: $VERSION"`,
+ language: 'bash',
+ title: 'deploy.sh',
+ hasLineNumbers: true,
+ },
+};
+
+export const SingleLine: Story = {
+ args: {
+ code: 'npm install @xds/core',
+ language: 'bash',
+ hasCopyButton: true,
+ },
+};
+
+export const Wrapped: Story = {
+ args: {
+ code: `// This is a very long line that demonstrates the word wrapping behavior of the code block component when isWrapped is set to true, which causes long lines to wrap instead of scrolling horizontally
+const result = someVeryLongFunctionName(parameterOne, parameterTwo, parameterThree, parameterFour, parameterFive);`,
+ language: 'typescript',
+ isWrapped: true,
+ hasLineNumbers: true,
+ },
+};
+
+export const WithMaxHeight: Story = {
+ args: {
+ code: Array.from(
+ {length: 50},
+ (_, i) => `const line${i + 1} = ${i + 1};`,
+ ).join('\n'),
+ language: 'typescript',
+ title: 'many-lines.ts',
+ hasLineNumbers: true,
+ maxHeight: 200,
+ },
+};
+
+export const SmallSize: Story = {
+ args: {
+ code: tsExample,
+ language: 'typescript',
+ title: 'useUser.ts',
+ hasLineNumbers: true,
+ size: 'sm',
+ },
+};
+
+export const NoHeader: Story = {
+ args: {
+ code: `const greeting = "Hello, world!";
+console.log(greeting);`,
+ language: 'typescript',
+ hasCopyButton: true,
+ },
+};
+
+export const Plaintext: Story = {
+ args: {
+ code: `This is plain text without any syntax highlighting.
+It preserves whitespace and line breaks.
+
+ Indentation is maintained.
+ Nested indentation too.`,
+ language: 'plaintext',
+ title: 'notes.txt',
+ hasLineNumbers: true,
+ },
+};
diff --git a/apps/storybook/stories/CodeEditor.stories.tsx b/apps/storybook/stories/CodeEditor.stories.tsx
new file mode 100644
index 0000000000..a38601f9aa
--- /dev/null
+++ b/apps/storybook/stories/CodeEditor.stories.tsx
@@ -0,0 +1,111 @@
+import type {Meta, StoryObj} from '@storybook/react';
+import {useState} from 'react';
+import {XDSCodeEditor} from '@xds/lab';
+
+const meta: Meta<typeof XDSCodeEditor> = {
+ title: 'Lab/XDSCodeEditor',
+ component: XDSCodeEditor,
+ tags: ['autodocs'],
+ argTypes: {
+ language: {
+ control: 'select',
+ options: [
+ 'typescript',
+ 'javascript',
+ 'json',
+ 'html',
+ 'css',
+ 'python',
+ 'bash',
+ 'php',
+ 'hack',
+ 'yaml',
+ 'markdown',
+ 'plaintext',
+ ],
+ },
+ size: {control: 'select', options: ['sm', 'md']},
+ hasLineNumbers: {control: 'boolean'},
+ isReadOnly: {control: 'boolean'},
+ },
+};
+
+export default meta;
+type Story = StoryObj<typeof XDSCodeEditor>;
+
+const defaultCode = `function greet(name: string): string {
+ const message = \`Hello, \${name}!\`;
+ console.log(message);
+ return message;
+}`;
+
+function ControlledEditor(
+ props: Partial<React.ComponentProps<typeof XDSCodeEditor>>,
+) {
+ const [value, setValue] = useState(props.value ?? defaultCode);
+ return (
+ <XDSCodeEditor
+ language="typescript"
+ hasLineNumbers
+ {...props}
+ value={value}
+ onChange={setValue}
+ />
+ );
+}
+
+export const Default: Story = {
+ render: () => <ControlledEditor />,
+};
+
+export const JSONEditor: Story = {
+ render: () => (
+ <ControlledEditor
+ value={`{\n "name": "my-app",\n "version": "1.0.0",\n "settings": {\n "port": 3000,\n "debug": false\n }\n}`}
+ language="json"
+ hasLineNumbers
+ />
+ ),
+};
+
+export const PythonEditor: Story = {
+ render: () => (
+ <ControlledEditor
+ value={`def fibonacci(n: int) -> list[int]:\n """Generate Fibonacci sequence."""\n if n <= 0:\n return []\n fib = [0, 1]\n for i in range(2, n):\n fib.append(fib[-1] + fib[-2])\n return fib[:n]\n\nresult = fibonacci(10)\nprint(result)`}
+ language="python"
+ hasLineNumbers
+ />
+ ),
+};
+
+export const WithPlaceholder: Story = {
+ render: () => (
+ <ControlledEditor
+ value=""
+ placeholder="Type your code here..."
+ language="typescript"
+ />
+ ),
+};
+
+export const ReadOnly: Story = {
+ render: () => <ControlledEditor isReadOnly hasLineNumbers />,
+};
+
+export const WithMaxHeight: Story = {
+ render: () => (
+ <ControlledEditor
+ value={Array.from(
+ {length: 30},
+ (_, i) => `const line${i + 1} = ${i + 1};`,
+ ).join('\n')}
+ language="typescript"
+ hasLineNumbers
+ maxHeight={200}
+ />
+ ),
+};
+
+export const SmallSize: Story = {
+ render: () => <ControlledEditor size="sm" hasLineNumbers />,
+};
diff --git a/packages/core/src/theme/defineTheme.test.ts b/packages/core/src/theme/defineTheme.test.ts
index 5f09bacf3c..afda940b69 100644
--- a/packages/core/src/theme/defineTheme.test.ts
+++ b/packages/core/src/theme/defineTheme.test.ts
@@ -55,18 +55,19 @@ describe('defineTheme', () => {
expect(theme.tokens['--font-heading']).toBe('"Georgia", serif');
});
- it('warns on unknown token names', () => {
+ it('accepts unknown token names without warning (types provide guardrails)', () => {
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
- defineTheme({
- name: 'bad',
+ const theme = defineTheme({
+ name: 'custom',
tokens: {
// @ts-expect-error testing unknown token
'--color-does-not-exist': '#FF0000',
},
});
- expect(warn).toHaveBeenCalledWith(
- expect.stringContaining('unknown token "--color-does-not-exist"'),
- );
+ // No runtime warning — TypeScript catches typos at compile time
+ expect(warn).not.toHaveBeenCalled();
+ // But the token is still set (themes are just CSS custom properties)
+ expect(theme.tokens['--color-does-not-exist']).toBe('#FF0000');
warn.mockRestore();
});
diff --git a/packages/core/src/theme/defineTheme.ts b/packages/core/src/theme/defineTheme.ts
index b563498275..108909ce59 100644
--- a/packages/core/src/theme/defineTheme.ts
+++ b/packages/core/src/theme/defineTheme.ts
@@ -59,12 +59,15 @@ import {
type XDSRadiusScaleConfig,
} from './expandRadiusScale';
+import type {DomainTokenName} from './domainTokens';
+import {domainTokenDefaults} from './domainTokens';
+
// =============================================================================
// Types
// =============================================================================
-/** All valid XDS token names */
-export type XDSTokenName =
+/** All valid XDS core token names */
+export type XDSCoreTokenName =
| keyof typeof colorDefaults
| keyof typeof spacingDefaults
| keyof typeof sizeDefaults
@@ -79,6 +82,9 @@ export type XDSTokenName =
| keyof typeof fontWeightDefaults
| keyof typeof typeScaleDefaults;
+/** All valid XDS token names — core + domain tokens */
+export type XDSTokenName = XDSCoreTokenName | DomainTokenName;
+
/**
* Token value — either a single string or a [light, dark] tuple.
* Tuples are converted to CSS light-dark() at theme creation time.
@@ -244,6 +250,7 @@ export const xdsTokenDefaults: Record<string, string> = {
...lineHeightDefaults,
...fontWeightDefaults,
...typeScaleDefaults,
+ ...domainTokenDefaults,
};
// =============================================================================
@@ -340,12 +347,6 @@ export function defineTheme(input: XDSDefineThemeInput): XDSDefinedTheme {
if (input.tokens) {
for (const [key, value] of Object.entries(input.tokens)) {
if (value !== undefined) {
- if (!(key in xdsTokenDefaults)) {
- console.warn(
- `[XDS] defineTheme("${input.name}"): unknown token "${key}". ` +
- `Run "npx xds docs tokens" to see valid token names.`,
- );
- }
tokens[key] = resolveTokenValue(value);
}
}
diff --git a/packages/core/src/theme/domainTokens.ts b/packages/core/src/theme/domainTokens.ts
new file mode 100644
index 0000000000..da11e3e7c3
--- /dev/null
+++ b/packages/core/src/theme/domainTokens.ts
@@ -0,0 +1,79 @@
+/**
+ * @file domainTokens.ts
+ * @input None (pure token definitions)
+ * @output Exports domain token defaults and types for syntax, dataviz, etc.
+ * @position Token definitions; consumed by defineTheme for validation + autocomplete
+ *
+ * Domain tokens are color tokens owned by specific feature areas (code
+ * highlighting, data visualization, etc.) that don't belong in the core
+ * color palette but still need to be theme-overridable.
+ *
+ * These are in a SEPARATE file from tokens.stylex.ts so they're
+ * tree-shakeable — importing core components doesn't pull these in.
+ * Only defineTheme and domain components reference this file.
+ *
+ * SYNC: When adding a new domain, update:
+ * - This file (add defaults + type)
+ * - /packages/core/src/theme/defineTheme.ts (add to XDSTokenName union)
+ * - /packages/core/src/theme/index.ts (re-export)
+ */
+
+// =============================================================================
+// Syntax Highlighting
+// =============================================================================
+
+export const syntaxTokenDefaults = {
+ // keyword → accent (primary emphasis, control flow)
+ '--color-syntax-keyword': 'light-dark(#0064E0, #2694FE)',
+ // string → green-text
+ '--color-syntax-string': 'light-dark(#09441F, #A5F690)',
+ // comment → text-secondary (de-emphasized)
+ '--color-syntax-comment': 'light-dark(#4E606F, #AAAFB5)',
+ // number → orange-text (warm tone for constants)
+ '--color-syntax-number': 'light-dark(#6B2203, #FDB876)',
+ // function → blue-text (structural landmarks)
+ '--color-syntax-function': 'light-dark(#042F97, #AFD7FF)',
+ // type → purple-text (type system, interfaces)
+ '--color-syntax-type': 'light-dark(#3E0697, #B3B0FE)',
+ // variable → text-primary (neutral body text)
+ '--color-syntax-variable': 'light-dark(#0A1317, #DFE2E5)',
+ // operator → text-secondary
+ '--color-syntax-operator': 'light-dark(#4E606F, #AAAFB5)',
+ // constant → orange-text (true/false/null, same family as numbers)
+ '--color-syntax-constant': 'light-dark(#6B2203, #FDB876)',
+ // tag → red-text (HTML/JSX tags)
+ '--color-syntax-tag': 'light-dark(#7B0210, #FFB2B8)',
+ // attribute → orange-text (HTML/JSX attributes)
+ '--color-syntax-attribute': 'light-dark(#6B2203, #FDB876)',
+ // property → cyan-text (object properties, distinct from functions)
+ '--color-syntax-property': 'light-dark(#006064, #B2EBF2)',
+ // punctuation → text-disabled (most de-emphasized)
+ '--color-syntax-punctuation': 'light-dark(#A4B0BC, #6F747C)',
+} as const;
+
+export type SyntaxTokenName = keyof typeof syntaxTokenDefaults;
+
+// =============================================================================
+// Data Visualization (planned)
+// =============================================================================
+
+// export const datavizTokenDefaults = {
+// '--color-dataviz-primary': 'light-dark(#0064E0, #2694FE)',
+// '--color-dataviz-secondary': 'light-dark(#50a14f, #98c379)',
+// // ...
+// } as const;
+//
+// export type DatavizTokenName = keyof typeof datavizTokenDefaults;
+
+// =============================================================================
+// Aggregate
+// =============================================================================
+
+/** All domain token defaults merged — used by defineTheme for validation */
+export const domainTokenDefaults: Record<string, string> = {
+ ...syntaxTokenDefaults,
+ // ...datavizTokenDefaults, // uncomment when added
+};
+
+/** Union of all domain token names */
+export type DomainTokenName = SyntaxTokenName; // | DatavizTokenName
diff --git a/packages/core/src/theme/index.ts b/packages/core/src/theme/index.ts
index 0bc8000b4d..1445cea128 100644
--- a/packages/core/src/theme/index.ts
+++ b/packages/core/src/theme/index.ts
@@ -22,12 +22,23 @@ export {
export type {
XDSDefineThemeInput,
XDSDefinedTheme,
+ XDSCoreTokenName,
XDSTokenName,
XDSTokenValue,
XDSComponentStyleMap,
XDSStyleOverrides,
} from './defineTheme';
+export type {
+ SyntaxTokenName,
+ DomainTokenName,
+} from './domainTokens';
+
+export {
+ syntaxTokenDefaults,
+ domainTokenDefaults,
+} from './domainTokens';
+
export {expandTypeScale, generateTypeScaleComponents} from './expandTypeScale';
export type {XDSTypeScaleConfig, TypeScaleTokens} from './expandTypeScale';
diff --git a/packages/core/src/theme/tokens.stylex.ts b/packages/core/src/theme/tokens.stylex.ts
index cc13b36e4f..d29e539734 100644
--- a/packages/core/src/theme/tokens.stylex.ts
+++ b/packages/core/src/theme/tokens.stylex.ts
@@ -128,6 +128,8 @@ export const colorDefaults = {
'--color-yellow-border': 'light-dark(#FFEB3B, #FFF176)',
'--color-yellow-icon': 'light-dark(#FBC02D, #FFEE58)',
'--color-yellow-text': 'light-dark(#753F07, #FBCE03)',
+
+ // Syntax highlighting
} as const;
/** @deprecated Use colorDefaults */
diff --git a/packages/lab/src/CodeBlock/XDSCodeBlock.tsx b/packages/lab/src/CodeBlock/XDSCodeBlock.tsx
new file mode 100644
index 0000000000..bb1493671b
--- /dev/null
+++ b/packages/lab/src/CodeBlock/XDSCodeBlock.tsx
@@ -0,0 +1,446 @@
+/**
+ * @file XDSCodeBlock.tsx
+ * @input Uses React, StyleX, theme tokens, CSS Custom Highlight API
+ * @output Exports XDSCodeBlock component and XDSCodeBlockProps
+ * @position Core implementation; read-only syntax-highlighted code display
+ *
+ * SYNC: When modified, update:
+ * - /packages/lab/src/CodeBlock/index.ts (exports if types change)
+ * - /packages/lab/src/CodeBlock/tokenizer.ts (shared tokenizer)
+ * - /packages/lab/src/CodeBlock/highlightStyles.ts (::highlight rules)
+ */
+
+'use client';
+
+import {useLayoutEffect, useRef, useState, useCallback} from 'react';
+import type {XDSBaseProps} from '@xds/core/XDSBaseProps';
+import * as stylex from '@stylexjs/stylex';
+import {
+ colorVars,
+ spacingVars,
+ radiusVars,
+ textSizeVars,
+ typographyVars,
+ fontWeightVars,
+ lineHeightVars,
+} from '@xds/core/theme/tokens.stylex';
+import {xdsClassName, mergeProps} from '@xds/core/utils';
+import {tokenize} from './tokenizer';
+import type {Token} from './tokenizer';
+import {ensureHighlightStyles, TOKEN_TYPES} from './highlightStyles';
+
+// ---------------------------------------------------------------------------
+// Styles
+// ---------------------------------------------------------------------------
+
+const styles = stylex.create({
+ root: {
+ position: 'relative',
+ margin: 0,
+ borderRadius: radiusVars['--radius-2'],
+ backgroundColor: colorVars['--color-wash'],
+ border: `1px solid ${colorVars['--color-border']}`,
+ overflow: 'hidden',
+ },
+ header: {
+ display: 'flex',
+ alignItems: 'center',
+ justifyContent: 'space-between',
+ paddingBlock: spacingVars['--spacing-2'],
+ paddingInline: spacingVars['--spacing-4'],
+ borderBottom: `1px solid ${colorVars['--color-border']}`,
+ backgroundColor: colorVars['--color-surface'],
+ },
+ headerTitle: {
+ fontSize: textSizeVars['--text-sm'],
+ fontFamily: typographyVars['--font-code'],
+ fontWeight: fontWeightVars['--font-weight-medium'],
+ color: colorVars['--color-text-secondary'],
+ margin: 0,
+ lineHeight: lineHeightVars['--leading-snug'],
+ },
+ scrollContainer: {
+ overflowX: 'auto',
+ overflowY: 'auto',
+ },
+ codeWrapper: {
+ display: 'flex',
+ minWidth: 'fit-content',
+ },
+ gutter: {
+ flexShrink: 0,
+ paddingBlock: spacingVars['--spacing-3'],
+ paddingInlineStart: spacingVars['--spacing-4'],
+ paddingInlineEnd: spacingVars['--spacing-3'],
+ textAlign: 'end',
+ userSelect: 'none',
+ color: colorVars['--color-text-disabled'],
+ borderRight: `1px solid ${colorVars['--color-border']}`,
+ },
+ gutterLine: {
+ fontFamily: typographyVars['--font-code'],
+ lineHeight: lineHeightVars['--leading-normal'],
+ },
+ code: {
+ display: 'block',
+ flex: 1,
+ paddingBlock: spacingVars['--spacing-3'],
+ paddingInline: spacingVars['--spacing-4'],
+ margin: 0,
+ fontFamily: typographyVars['--font-code'],
+ color: colorVars['--color-text-primary'],
+ tabSize: 2,
+ whiteSpace: 'pre',
+ wordBreak: 'normal',
+ overflowWrap: 'normal',
+ },
+ codeWrapped: {
+ whiteSpace: 'pre-wrap',
+ wordBreak: 'break-all',
+ overflowWrap: 'break-word',
+ },
+ line: {
+ lineHeight: lineHeightVars['--leading-normal'],
+ contentVisibility: 'auto',
+ containIntrinsicBlockSize: 'auto 1lh',
+ },
+ lineHighlighted: {
+ backgroundColor: colorVars['--color-accent-muted'],
+ marginInline: `calc(-1 * ${spacingVars['--spacing-4']})`,
+ paddingInline: spacingVars['--spacing-4'],
+ borderLeft: `2px solid ${colorVars['--color-accent']}`,
+ },
+ sizeSm: {
+ fontSize: textSizeVars['--text-sm'],
+ },
+ sizeMd: {
+ fontSize: textSizeVars['--text-base'],
+ },
+ gutterSm: {
+ fontSize: textSizeVars['--text-sm'],
+ },
+ gutterMd: {
+ fontSize: textSizeVars['--text-base'],
+ },
+ copyButton: {
+ display: 'inline-flex',
+ alignItems: 'center',
+ justifyContent: 'center',
+ padding: spacingVars['--spacing-1'],
+ border: 'none',
+ borderRadius: radiusVars['--radius-1'],
+ backgroundColor: 'transparent',
+ color: colorVars['--color-text-secondary'],
+ cursor: 'pointer',
+ fontFamily: typographyVars['--font-code'],
+ fontSize: textSizeVars['--text-sm'],
+ lineHeight: '1',
+ transition: 'background-color 0.15s ease, color 0.15s ease',
+ },
+ copyButtonAbsolute: {
+ position: 'absolute',
+ top: spacingVars['--spacing-2'],
+ right: spacingVars['--spacing-2'],
+ },
+});
+
+// ---------------------------------------------------------------------------
+// Props
+// ---------------------------------------------------------------------------
+
+export interface XDSCodeBlockProps extends XDSBaseProps<HTMLPreElement> {
+ /** Ref forwarded to the root <pre> element */
+ ref?: React.Ref<HTMLPreElement>;
+ /** The code string to display */
+ code: string;
+ /** Language for syntax highlighting. @default "plaintext" */
+ language?: string;
+ /** Filename/label in header bar */
+ title?: string;
+ /** Show line number gutter. @default false */
+ hasLineNumbers?: boolean;
+ /** 1-indexed lines to highlight. */
+ highlightLines?: number[];
+ /** Show copy-to-clipboard button. @default true */
+ hasCopyButton?: boolean;
+ /** Callback after copy */
+ onCopy?: () => void;
+ /** Wrap long lines vs horizontal scroll. @default false */
+ isWrapped?: boolean;
+ /** Max height before scrolling */
+ maxHeight?: number | string;
+ /** Text size. @default "md" */
+ size?: 'sm' | 'md';
+ /** Custom tokenizer override */
+ tokenizer?: (
+ code: string,
+ language: string,
+ ) => Array<{type: string; start: number; end: number}>;
+}
+
+// ---------------------------------------------------------------------------
+// Helpers
+// ---------------------------------------------------------------------------
+
+/**
+ * Check if CSS Custom Highlight API is available.
+ */
+function hasHighlightAPI(): boolean {
+ return (
+ typeof CSS !== 'undefined' &&
+ 'highlights' in CSS &&
+ typeof Highlight !== 'undefined'
+ );
+}
+
+/**
+ * Unique instance counter to namespace highlights when multiple
+ * code blocks are on the same page.
+ */
+let instanceCounter = 0;
+
+// ---------------------------------------------------------------------------
+// Component
+// ---------------------------------------------------------------------------
+
+/**
+ * A read-only syntax-highlighted code block.
+ *
+ * Uses the CSS Custom Highlight API for zero-DOM-overhead syntax coloring.
+ * Falls back to plain text display in browsers without support.
+ *
+ * @example
+ * ```tsx
+ * <XDSCodeBlock
+ * code={`const x = 42;`}
+ * language="typescript"
+ * hasLineNumbers
+ * />
+ * ```
+ */
+export function XDSCodeBlock({
+ code,
+ language = 'plaintext',
+ title,
+ hasLineNumbers = false,
+ highlightLines,
+ hasCopyButton = true,
+ onCopy,
+ isWrapped = false,
+ maxHeight,
+ size = 'md',
+ tokenizer: customTokenizer,
+ xstyle,
+ className,
+ style,
+ ref,
+ ...props
+}: XDSCodeBlockProps) {
+ const codeRef = useRef<HTMLElement>(null);
+ const [instanceId] = useState(() => ++instanceCounter);
+ const [copied, setCopied] = useState(false);
+
+ const lines = code.split('\n');
+ // Remove trailing empty line from code that ends with newline
+ if (lines.length > 1 && lines[lines.length - 1] === '') {
+ lines.pop();
+ }
+
+ const highlightSet = highlightLines ? new Set(highlightLines) : null;
+
+ const handleCopy = useCallback(() => {
+ navigator.clipboard.writeText(code).then(() => {
+ setCopied(true);
+ onCopy?.();
+ setTimeout(() => setCopied(false), 2000);
+ });
+ }, [code, onCopy]);
+
+ // Apply CSS Custom Highlight API ranges
+ useLayoutEffect(() => {
+ if (!hasHighlightAPI()) return;
+
+ ensureHighlightStyles();
+
+ const codeEl = codeRef.current;
+ if (!codeEl) return;
+
+ const tok = customTokenizer ?? tokenize;
+ const tokens = tok(code, language);
+ if (tokens.length === 0) return;
+
+ // Group tokens by type
+ const tokensByType = new Map<string, Token[]>();
+ for (const token of tokens) {
+ const existing = tokensByType.get(token.type);
+ if (existing) {
+ existing.push(token);
+ } else {
+ tokensByType.set(token.type, [token]);
+ }
+ }
+
+ // Build text node mapping using TreeWalker — same approach as CodeEditor.
+ // Finds all text nodes and maps code offsets to DOM positions.
+ // Code string has \n between lines; DOM has separate text nodes per line
+ // with no \n, so we add 1 after each line's text node to stay in sync.
+ const walker = document.createTreeWalker(codeEl, NodeFilter.SHOW_TEXT);
+ const textNodes: Array<{node: Text; start: number}> = [];
+ let charOffset = 0;
+
+ let currentNode = walker.nextNode();
+ while (currentNode) {
+ const text = currentNode as Text;
+ const content = text.textContent ?? '';
+ // Skip zero-width space placeholders for empty lines
+ if (content === '\u200b') {
+ // Empty line — still accounts for the \n in the code string
+ charOffset += 1; // just the \n
+ } else {
+ textNodes.push({node: text, start: charOffset});
+ charOffset += content.length + 1; // +1 for the \n after this line
+ }
+ currentNode = walker.nextNode();
+ }
+
+ /**
+ * Find the text node and local offset for a given code offset.
+ */
+ function findPosition(offset: number): {node: Text; offset: number} | null {
+ for (let i = textNodes.length - 1; i >= 0; i--) {
+ const entry = textNodes[i];
+ if (offset >= entry.start) {
+ const localOffset = offset - entry.start;
+ if (localOffset <= (entry.node.textContent?.length ?? 0)) {
+ return {node: entry.node, offset: localOffset};
+ }
+ return null;
+ }
+ }
+ return null;
+ }
+
+ // Create highlight ranges for each token type.
+ // Multiple CodeBlock instances share the same highlight names —
+ // we add our ranges to the existing Highlight (or create a new one).
+ // On cleanup, we remove only our ranges.
+ const myRanges: Range[] = [];
+
+ for (const tokenType of TOKEN_TYPES) {
+ const typedTokens = tokensByType.get(tokenType);
+ if (!typedTokens || typedTokens.length === 0) continue;
+
+ const name = `xds-${tokenType}`;
+ let highlight = CSS.highlights.get(name);
+ if (!highlight) {
+ highlight = new Highlight();
+ CSS.highlights.set(name, highlight);
+ }
+
+ for (const token of typedTokens) {
+ const startPos = findPosition(token.start);
+ const endPos = findPosition(token.end);
+ if (!startPos || !endPos) continue;
+
+ try {
+ const range = new Range();
+ range.setStart(startPos.node, startPos.offset);
+ range.setEnd(endPos.node, endPos.offset);
+ highlight.add(range);
+ myRanges.push(range);
+ } catch {
+ // Skip invalid ranges
+ }
+ }
+ }
+
+ return () => {
+ // Remove only this instance's ranges from the shared highlights
+ for (const range of myRanges) {
+ for (const tokenType of TOKEN_TYPES) {
+ const highlight = CSS.highlights.get(`xds-${tokenType}`);
+ if (highlight) {
+ highlight.delete(range);
+ }
+ }
+ }
+ };
+ }, [code, language, customTokenizer, instanceId]);
+
+ const sizeStyle = size === 'sm' ? styles.sizeSm : styles.sizeMd;
+ const gutterSizeStyle = size === 'sm' ? styles.gutterSm : styles.gutterMd;
+ const showHeader = title != null;
+
+ const scrollStyle: React.CSSProperties | undefined = maxHeight
+ ? {maxHeight: typeof maxHeight === 'number' ? `${maxHeight}px` : maxHeight}
+ : undefined;
+
+ const copyButtonEl = hasCopyButton ? (
+ <button
+ type="button"
+ onClick={handleCopy}
+ aria-label={copied ? 'Copied' : 'Copy code'}
+ {...stylex.props(
+ styles.copyButton,
+ !showHeader && styles.copyButtonAbsolute,
+ )}>
+ {copied ? '✓' : '⎘'}
+ </button>
+ ) : null;
+
+ return (
+ <pre
+ ref={ref}
+ {...mergeProps(
+ xdsClassName('codeblock', {size, language}),
+ stylex.props(styles.root, xstyle),
+ className,
+ style,
+ )}
+ {...props}>
+ {showHeader && (
+ <div {...stylex.props(styles.header)}>
+ <span {...stylex.props(styles.headerTitle)}>{title}</span>
+ {copyButtonEl}
+ </div>
+ )}
+ <div {...stylex.props(styles.scrollContainer)} style={scrollStyle}>
+ <div {...stylex.props(styles.codeWrapper)}>
+ {hasLineNumbers && (
+ <div
+ {...stylex.props(styles.gutter, gutterSizeStyle)}
+ aria-hidden="true">
+ {lines.map((_, i) => (
+ <div key={i} {...stylex.props(styles.gutterLine)}>
+ {i + 1}
+ </div>
+ ))}
+ </div>
+ )}
+ <code
+ ref={codeRef}
+ {...stylex.props(
+ styles.code,
+ sizeStyle,
+ isWrapped && styles.codeWrapped,
+ )}>
+ {lines.map((line, i) => (
+ <div
+ key={i}
+ data-line={i + 1}
+ {...stylex.props(
+ styles.line,
+ highlightSet?.has(i + 1) && styles.lineHighlighted,
+ )}>
+ {line || '\u200b'}
+ </div>
+ ))}
+ </code>
+ </div>
+ </div>
+ {!showHeader && copyButtonEl}
+ </pre>
+ );
+}
+
+XDSCodeBlock.displayName = 'XDSCodeBlock';
diff --git a/packages/lab/src/CodeBlock/highlightStyles.ts b/packages/lab/src/CodeBlock/highlightStyles.ts
new file mode 100644
index 0000000000..41ed990751
--- /dev/null
+++ b/packages/lab/src/CodeBlock/highlightStyles.ts
@@ -0,0 +1,75 @@
+/**
+ * @file highlightStyles.ts
+ * @input Syntax token defaults from domainTokens
+ * @output Injects ::highlight() CSS rules + fallback token values into the document head
+ * @position Shared utility; consumed by XDSCodeBlock and XDSCodeEditor
+ *
+ * SYNC: When modified, update:
+ * - /packages/core/src/theme/domainTokens.ts (syntax color token names/defaults)
+ */
+
+import {syntaxTokenDefaults} from '@xds/core/theme';
+
+/**
+ * Build the fallback CSS custom properties from the syntax token defaults.
+ * These provide colors when no theme explicitly sets --color-syntax-* tokens.
+ * Themes override these via higher-specificity [data-xds-theme] selectors.
+ */
+const FALLBACK_TOKENS = `:root {\n${Object.entries(syntaxTokenDefaults)
+ .map(([name, value]) => ` ${name}: ${value};`)
+ .join('\n')}\n}`;
+
+const HIGHLIGHT_STYLES = `
+${FALLBACK_TOKENS}
+
+::highlight(xds-keyword) { color: var(--color-syntax-keyword); }
+::highlight(xds-string) { color: var(--color-syntax-string); }
+::highlight(xds-comment) { color: var(--color-syntax-comment); }
+::highlight(xds-number) { color: var(--color-syntax-number); }
+::highlight(xds-function) { color: var(--color-syntax-function); }
+::highlight(xds-type) { color: var(--color-syntax-type); }
+::highlight(xds-tag) { color: var(--color-syntax-tag); }
+::highlight(xds-attribute) { color: var(--color-syntax-attribute); }
+::highlight(xds-property) { color: var(--color-syntax-property); }
+::highlight(xds-operator) { color: var(--color-syntax-operator); }
+::highlight(xds-constant) { color: var(--color-syntax-constant); }
+::highlight(xds-punctuation) { color: var(--color-syntax-punctuation); }
+::highlight(xds-variable) { color: var(--color-syntax-variable); }
+`;
+
+let inserted = false;
+
+/**
+ * Injects the ::highlight() CSS rules into the document <head>.
+ * Safe to call multiple times — only injects once.
+ */
+export function ensureHighlightStyles(): void {
+ if (inserted) return;
+ if (typeof document === 'undefined') return;
+
+ const style = document.createElement('style');
+ style.setAttribute('data-xds-highlight-styles', '');
+ style.textContent = HIGHLIGHT_STYLES;
+ document.head.appendChild(style);
+ inserted = true;
+}
+
+/**
+ * Token types that map to highlight names.
+ * Used to create CSS.highlights entries with `xds-` prefix.
+ */
+export const TOKEN_TYPES = [
+ 'keyword',
+ 'string',
+ 'comment',
+ 'number',
+ 'function',
+ 'type',
+ 'tag',
+ 'attribute',
+ 'property',
+ 'operator',
+ 'constant',
+ 'punctuation',
+ 'variable',
+] as const;
diff --git a/packages/lab/src/CodeBlock/index.ts b/packages/lab/src/CodeBlock/index.ts
new file mode 100644
index 0000000000..16d0672eb8
--- /dev/null
+++ b/packages/lab/src/CodeBlock/index.ts
@@ -0,0 +1,6 @@
+/**
+ * @file CodeBlock component barrel export
+ */
+
+export {XDSCodeBlock} from './XDSCodeBlock';
+export type {XDSCodeBlockProps} from './XDSCodeBlock';
diff --git a/packages/lab/src/CodeBlock/tokenizer.test.ts b/packages/lab/src/CodeBlock/tokenizer.test.ts
new file mode 100644
index 0000000000..4c396dd4b9
--- /dev/null
+++ b/packages/lab/src/CodeBlock/tokenizer.test.ts
@@ -0,0 +1,281 @@
+import {describe, it, expect} from 'vitest';
+import {tokenize} from './tokenizer';
+
+function tokenTypes(code: string, lang: string) {
+ return tokenize(code, lang).map(t => ({
+ type: t.type,
+ text: code.slice(t.start, t.end),
+ }));
+}
+
+function hasType(code: string, lang: string, type: string) {
+ return tokenize(code, lang).some(t => t.type === type);
+}
+
+describe('tokenizer', () => {
+ describe('typescript', () => {
+ it('tokenizes keywords', () => {
+ const tokens = tokenTypes('const x = 42;', 'typescript');
+ expect(tokens).toContainEqual({type: 'keyword', text: 'const'});
+ });
+
+ it('tokenizes strings', () => {
+ const tokens = tokenTypes('const s = "hello";', 'typescript');
+ expect(tokens).toContainEqual({type: 'string', text: '"hello"'});
+ });
+
+ it('tokenizes single-quote strings', () => {
+ const tokens = tokenTypes("const s = 'hello';", 'typescript');
+ expect(tokens).toContainEqual({type: 'string', text: "'hello'"});
+ });
+
+ it('tokenizes template literals', () => {
+ const tokens = tokenTypes('const s = `hello ${name}`;', 'typescript');
+ expect(tokens).toContainEqual({type: 'string', text: '`hello ${name}`'});
+ });
+
+ it('tokenizes numbers', () => {
+ const tokens = tokenTypes('const x = 42;', 'typescript');
+ expect(tokens).toContainEqual({type: 'number', text: '42'});
+ });
+
+ it('tokenizes line comments', () => {
+ const tokens = tokenTypes('// this is a comment', 'typescript');
+ expect(tokens).toContainEqual({
+ type: 'comment',
+ text: '// this is a comment',
+ });
+ });
+
+ it('tokenizes block comments', () => {
+ const tokens = tokenTypes('/* block comment */', 'typescript');
+ expect(tokens).toContainEqual({
+ type: 'comment',
+ text: '/* block comment */',
+ });
+ });
+
+ it('tokenizes function calls', () => {
+ const tokens = tokenTypes('console.log("hi")', 'typescript');
+ expect(tokens).toContainEqual({type: 'function', text: 'log'});
+ });
+
+ it('tokenizes types (PascalCase)', () => {
+ const tokens = tokenTypes('const x: MyType = {};', 'typescript');
+ expect(tokens).toContainEqual({type: 'type', text: 'MyType'});
+ });
+
+ it('tokenizes multiple keywords', () => {
+ const tokens = tokenTypes('if (true) { return false; }', 'typescript');
+ const kws = tokens.filter(t => t.type === 'keyword').map(t => t.text);
+ expect(kws).toContain('if');
+ expect(kws).toContain('true');
+ expect(kws).toContain('return');
+ expect(kws).toContain('false');
+ });
+
+ it('tokenizes import statement', () => {
+ const tokens = tokenTypes(
+ "import {useState} from 'react';",
+ 'typescript',
+ );
+ const kws = tokens.filter(t => t.type === 'keyword').map(t => t.text);
+ expect(kws).toContain('import');
+ expect(kws).toContain('from');
+ expect(tokens).toContainEqual({type: 'string', text: "'react'"});
+ });
+
+ it('tokenizes multi-line code', () => {
+ const code = `const x = 1;
+const y = "hello";
+// comment`;
+ const tokens = tokenTypes(code, 'typescript');
+ const kws = tokens.filter(t => t.type === 'keyword');
+ expect(kws.length).toBe(2); // two 'const'
+ expect(tokens).toContainEqual({type: 'string', text: '"hello"'});
+ expect(tokens).toContainEqual({type: 'comment', text: '// comment'});
+ });
+
+ it('produces non-zero tokens for typical code', () => {
+ const code = `function greet(name: string): string {
+ const greeting = \`Hello, \${name}!\`;
+ console.log(greeting);
+ return greeting;
+}`;
+ const tokens = tokenize(code, 'typescript');
+ expect(tokens.length).toBeGreaterThan(5);
+ });
+ });
+
+ describe('json', () => {
+ it('tokenizes keys and values', () => {
+ const tokens = tokenTypes('{"name": "value"}', 'json');
+ expect(tokens).toContainEqual({type: 'property', text: '"name"'});
+ expect(tokens).toContainEqual({type: 'string', text: '"value"'});
+ });
+
+ it('tokenizes numbers', () => {
+ const tokens = tokenTypes('{"count": 42}', 'json');
+ expect(tokens).toContainEqual({type: 'number', text: '42'});
+ });
+
+ it('tokenizes booleans and null', () => {
+ const tokens = tokenTypes('{"a": true, "b": false, "c": null}', 'json');
+ const constants = tokens
+ .filter(t => t.type === 'constant')
+ .map(t => t.text);
+ expect(constants).toContain('true');
+ expect(constants).toContain('false');
+ expect(constants).toContain('null');
+ });
+ });
+
+ describe('python', () => {
+ it('tokenizes keywords', () => {
+ const tokens = tokenTypes('def hello():', 'python');
+ expect(tokens).toContainEqual({type: 'keyword', text: 'def'});
+ });
+
+ it('tokenizes comments', () => {
+ const tokens = tokenTypes('# this is a comment', 'python');
+ expect(tokens).toContainEqual({
+ type: 'comment',
+ text: '# this is a comment',
+ });
+ });
+
+ it('tokenizes decorators', () => {
+ const tokens = tokenTypes('@dataclass', 'python');
+ expect(tokens).toContainEqual({type: 'constant', text: '@dataclass'});
+ });
+
+ it('tokenizes triple-quote strings', () => {
+ const tokens = tokenTypes('"""docstring"""', 'python');
+ expect(tokens).toContainEqual({type: 'string', text: '"""docstring"""'});
+ });
+
+ it('tokenizes f-strings', () => {
+ const tokens = tokenTypes('f"hello {name}"', 'python');
+ expect(tokens).toContainEqual({type: 'string', text: 'f"hello {name}"'});
+ });
+
+ it('produces tokens for a real function', () => {
+ const code = `def process(config):
+ print(f"Processing {config}")
+ return True`;
+ const tokens = tokenize(code, 'python');
+ expect(tokens.length).toBeGreaterThan(5);
+ const kws = tokenTypes(code, 'python')
+ .filter(t => t.type === 'keyword')
+ .map(t => t.text);
+ expect(kws).toContain('def');
+ expect(kws).toContain('return');
+ expect(kws).toContain('True');
+ });
+ });
+
+ describe('html', () => {
+ it('tokenizes tags', () => {
+ const tokens = tokenTypes('<div class="x">hello</div>', 'html');
+ expect(tokens.some(t => t.type === 'tag')).toBe(true);
+ });
+
+ it('tokenizes attributes', () => {
+ const tokens = tokenTypes('<div class="x">hello</div>', 'html');
+ expect(tokens).toContainEqual({type: 'attribute', text: 'class'});
+ });
+
+ it('tokenizes comments', () => {
+ const tokens = tokenTypes('<!-- comment -->', 'html');
+ expect(tokens).toContainEqual({
+ type: 'comment',
+ text: '<!-- comment -->',
+ });
+ });
+ });
+
+ describe('css', () => {
+ it('tokenizes properties', () => {
+ const tokens = tokenTypes('display: flex;', 'css');
+ expect(tokens).toContainEqual({type: 'property', text: 'display'});
+ });
+
+ it('tokenizes selectors', () => {
+ const tokens = tokenTypes('.button { }', 'css');
+ expect(tokens).toContainEqual({type: 'tag', text: '.button'});
+ });
+
+ it('tokenizes custom properties', () => {
+ const tokens = tokenTypes('--color-primary: blue;', 'css');
+ expect(tokens).toContainEqual({
+ type: 'variable',
+ text: '--color-primary',
+ });
+ });
+
+ it('tokenizes numbers with units', () => {
+ const tokens = tokenTypes('padding: 8px;', 'css');
+ expect(tokens).toContainEqual({type: 'number', text: '8px'});
+ });
+
+ it('tokenizes hex colors', () => {
+ const tokens = tokenTypes('color: #0064E0;', 'css');
+ expect(tokens).toContainEqual({type: 'constant', text: '#0064E0'});
+ });
+
+ it('tokenizes functions', () => {
+ const tokens = tokenTypes('color: var(--x);', 'css');
+ expect(tokens).toContainEqual({type: 'function', text: 'var'});
+ });
+ });
+
+ describe('bash', () => {
+ it('tokenizes comments', () => {
+ const tokens = tokenTypes('# comment', 'bash');
+ expect(tokens).toContainEqual({type: 'comment', text: '# comment'});
+ });
+
+ it('tokenizes variables', () => {
+ const tokens = tokenTypes('echo $HOME', 'bash');
+ expect(tokens).toContainEqual({type: 'variable', text: '$HOME'});
+ });
+
+ it('tokenizes strings', () => {
+ const tokens = tokenTypes('echo "hello"', 'bash');
+ expect(tokens).toContainEqual({type: 'string', text: '"hello"'});
+ });
+ });
+
+ describe('edge cases', () => {
+ it('returns empty for unknown language', () => {
+ expect(tokenize('const x = 1;', 'brainfuck')).toEqual([]);
+ });
+
+ it('returns empty for plaintext', () => {
+ expect(tokenize('hello world', 'plaintext')).toEqual([]);
+ });
+
+ it('handles empty string', () => {
+ expect(tokenize('', 'typescript')).toEqual([]);
+ });
+
+ it('tokens have valid ranges', () => {
+ const code = 'const x = 42;';
+ const tokens = tokenize(code, 'typescript');
+ for (const t of tokens) {
+ expect(t.start).toBeGreaterThanOrEqual(0);
+ expect(t.end).toBeGreaterThan(t.start);
+ expect(t.end).toBeLessThanOrEqual(code.length);
+ expect(code.slice(t.start, t.end)).toBeTruthy();
+ }
+ });
+
+ it('tokens do not overlap', () => {
+ const code = 'const greeting = "hello"; // comment\nreturn 42;';
+ const tokens = tokenize(code, 'typescript');
+ for (let i = 1; i < tokens.length; i++) {
+ expect(tokens[i].start).toBeGreaterThanOrEqual(tokens[i - 1].end);
+ }
+ });
+ });
+});
diff --git a/packages/lab/src/CodeBlock/tokenizer.ts b/packages/lab/src/CodeBlock/tokenizer.ts
new file mode 100644
index 0000000000..9305691d7b
--- /dev/null
+++ b/packages/lab/src/CodeBlock/tokenizer.ts
@@ -0,0 +1,332 @@
+/**
+ * @file tokenizer.ts
+ * @input Code string and language identifier
+ * @output Array of tokens with type, start, and end positions
+ * @position Shared utility; consumed by XDSCodeBlock and XDSCodeEditor
+ *
+ * SYNC: When modified, update:
+ * - /packages/lab/src/CodeBlock/XDSCodeBlock.tsx
+ * - /packages/lab/src/CodeEditor/XDSCodeEditor.tsx
+ */
+
+export type Token = {type: string; start: number; end: number};
+
+// ---------------------------------------------------------------------------
+// Language definitions
+// ---------------------------------------------------------------------------
+
+type LangDef = {
+ patterns: Array<{type: string; regex: RegExp; anchored: RegExp}>;
+};
+
+/** Cache compiled language definitions to avoid re-creating regexes. */
+const langCache = new Map<string, LangDef | null>();
+
+const JS_KEYWORDS =
+ /\b(const|let|var|function|class|if|else|for|while|return|import|export|from|default|async|await|try|catch|throw|new|typeof|instanceof|interface|type|enum|extends|implements|switch|case|break|continue|do|in|of|void|null|undefined|true|false|this|super|yield|delete|static|public|private|protected|readonly|abstract|as|is|keyof|declare|module|namespace|require)\b/;
+
+const PYTHON_KEYWORDS =
+ /\b(def|class|if|elif|else|for|while|return|import|from|as|with|try|except|raise|True|False|None|and|or|not|in|is|lambda|yield|async|await|pass|break|continue|del|global|nonlocal|assert|finally|print|self|cls)\b/;
+
+const BASH_KEYWORDS =
+ /\b(if|then|else|elif|fi|for|do|done|while|until|case|esac|function|in|select|return|exit|local|export|source|alias|unalias|readonly|shift|eval|exec|set|unset|trap|wait|read|echo|printf|test|true|false)\b/;
+
+const CSS_KEYWORDS = /\b(important|inherit|initial|unset|revert|auto|none)\b/;
+
+const PHP_KEYWORDS =
+ /\b(function|class|if|else|elseif|for|foreach|while|return|echo|public|private|protected|static|new|try|catch|throw|namespace|use|require|require_once|include|include_once|extends|implements|interface|abstract|final|const|var|true|false|null|array|isset|unset|empty|list|match|enum|switch|case|break|continue|do|yield|fn)\b/;
+
+const HACK_KEYWORDS =
+ /\b(function|class|if|else|for|foreach|while|return|echo|public|private|protected|static|new|try|catch|throw|namespace|use|require|include|extends|implements|interface|abstract|final|const|shape|vec|dict|keyset|async|await|concurrent|enum|type|newtype|tuple|inout)\b/;
+
+function buildLanguage(lang: string): LangDef | null {
+ const cached = langCache.get(lang);
+ if (cached !== undefined) return cached;
+
+ const def = buildLanguageUncached(lang);
+ langCache.set(lang, def);
+ return def;
+}
+
+function buildLanguageUncached(lang: string): LangDef | null {
+ const raw = buildLanguagePatterns(lang);
+ if (!raw) return null;
+ return {
+ patterns: raw.patterns.map(p => {
+ // Use sticky flag (y) to anchor match at lastIndex position.
+ // This avoids code.slice() on every attempt — much faster.
+ const flags = p.regex.flags.replace(/[gy]/g, '') + 'y';
+ return {...p, anchored: new RegExp(p.regex.source, flags)};
+ }),
+ };
+}
+
+function buildLanguagePatterns(
+ lang: string,
+): {patterns: Array<{type: string; regex: RegExp}>} | null {
+ switch (lang) {
+ case 'typescript':
+ case 'javascript':
+ case 'tsx':
+ case 'jsx':
+ case 'ts':
+ case 'js':
+ return {
+ patterns: [
+ {type: 'comment', regex: /\/\*[\s\S]*?\*\//},
+ {type: 'comment', regex: /\/\/[^\n]*/},
+ {type: 'string', regex: /`(?:[^`\\]|\\.)*`/},
+ {type: 'string', regex: /"(?:[^"\\]|\\.)*"/},
+ {type: 'string', regex: /'(?:[^'\\]|\\.)*'/},
+ {type: 'constant', regex: /@[\w]+/},
+ {type: 'number', regex: /\b0[xX][0-9a-fA-F_]+\b/},
+ {type: 'number', regex: /\b0[bB][01_]+\b/},
+ {type: 'number', regex: /\b0[oO][0-7_]+\b/},
+ {type: 'number', regex: /\b\d[\d_]*\.?[\d_]*(?:[eE][+-]?\d+)?\b/},
+ {type: 'keyword', regex: JS_KEYWORDS},
+ {type: 'function', regex: /\b[a-zA-Z_$][\w$]*(?=\s*\()/},
+ {type: 'type', regex: /\b[A-Z][a-zA-Z0-9_]*\b/},
+ {type: 'operator', regex: /[+\-*/%=!<>&|^~?:]+/},
+ // eslint-disable-next-line no-useless-escape
+ {type: 'punctuation', regex: /[{}()\[\];,.]/},
+ {type: 'variable', regex: /\b[a-zA-Z_$][\w$]*\b/},
+ ],
+ };
+
+ case 'json':
+ return {
+ patterns: [
+ {type: 'property', regex: /"(?:[^"\\]|\\.)*"(?=\s*:)/},
+ {type: 'string', regex: /"(?:[^"\\]|\\.)*"/},
+ {type: 'number', regex: /-?\b\d+\.?\d*(?:[eE][+-]?\d+)?\b/},
+ {type: 'constant', regex: /\b(true|false|null)\b/},
+ // eslint-disable-next-line no-useless-escape
+ {type: 'punctuation', regex: /[{}()\[\]:,]/},
+ ],
+ };
+
+ case 'html':
+ case 'xml':
+ case 'svg':
+ return {
+ patterns: [
+ {type: 'comment', regex: /<!--[\s\S]*?-->/},
+ {type: 'keyword', regex: /<!DOCTYPE[^>]*>/i},
+ {type: 'tag', regex: /<\/[a-zA-Z][\w-]*\s*>/},
+ {type: 'tag', regex: /<[a-zA-Z][\w-]*/},
+ {type: 'tag', regex: /\/?>/},
+ {type: 'string', regex: /"(?:[^"\\]|\\.)*"/},
+ {type: 'string', regex: /'(?:[^'\\]|\\.)*'/},
+ {type: 'attribute', regex: /\b[a-zA-Z_:][\w:.-]*(?=\s*=)/},
+ {type: 'operator', regex: /=/},
+ ],
+ };
+
+ case 'css':
+ case 'scss':
+ case 'less':
+ return {
+ patterns: [
+ {type: 'comment', regex: /\/\*[\s\S]*?\*\//},
+ {type: 'comment', regex: /\/\/[^\n]*/},
+ {type: 'string', regex: /"(?:[^"\\]|\\.)*"/},
+ {type: 'string', regex: /'(?:[^'\\]|\\.)*'/},
+ {type: 'variable', regex: /--[a-zA-Z_-][\w-]*/},
+ {
+ type: 'number',
+ regex:
+ /-?\b\d+\.?\d*(?:px|em|rem|%|vh|vw|vmin|vmax|ch|ex|deg|rad|turn|s|ms|fr)?\b/,
+ },
+ {type: 'constant', regex: /#[0-9a-fA-F]{3,8}\b/},
+ {type: 'keyword', regex: CSS_KEYWORDS},
+ {type: 'keyword', regex: /@[a-zA-Z][\w-]*/},
+ {type: 'tag', regex: /[.#][a-zA-Z_-][\w-]*/},
+ {type: 'keyword', regex: /::?[a-zA-Z][\w-]*/},
+ {type: 'function', regex: /\b[a-zA-Z_-][\w-]*(?=\s*\()/},
+ {type: 'property', regex: /[a-zA-Z_-][\w-]*(?=\s*:)/},
+ // eslint-disable-next-line no-useless-escape
+ {type: 'punctuation', regex: /[{}()\[\];:,]/},
+ {type: 'operator', regex: /[+~>*=|^$]/},
+ ],
+ };
+
+ case 'python':
+ case 'py':
+ return {
+ patterns: [
+ {type: 'string', regex: /"""[\s\S]*?"""/},
+ {type: 'string', regex: /'''[\s\S]*?'''/},
+ {type: 'string', regex: /f"(?:[^"\\]|\\.)*"/},
+ {type: 'string', regex: /f'(?:[^'\\]|\\.)*'/},
+ {type: 'comment', regex: /#[^\n]*/},
+ {type: 'string', regex: /"(?:[^"\\]|\\.)*"/},
+ {type: 'string', regex: /'(?:[^'\\]|\\.)*'/},
+ {type: 'constant', regex: /@[\w.]+/},
+ {type: 'number', regex: /\b0[xX][0-9a-fA-F_]+\b/},
+ {type: 'number', regex: /\b0[bB][01_]+\b/},
+ {type: 'number', regex: /\b0[oO][0-7_]+\b/},
+ {type: 'number', regex: /\b\d[\d_]*\.?[\d_]*(?:[eE][+-]?\d+)?j?\b/},
+ {type: 'keyword', regex: PYTHON_KEYWORDS},
+ {type: 'function', regex: /\b[a-zA-Z_][\w]*(?=\s*\()/},
+ {type: 'type', regex: /\b[A-Z][a-zA-Z0-9_]*\b/},
+ {type: 'operator', regex: /[+\-*/%=!<>&|^~@:]+/},
+ // eslint-disable-next-line no-useless-escape
+ {type: 'punctuation', regex: /[{}()\[\];,.]/},
+ {type: 'variable', regex: /\b[a-zA-Z_][\w]*\b/},
+ ],
+ };
+
+ case 'bash':
+ case 'sh':
+ case 'zsh':
+ case 'shell':
+ return {
+ patterns: [
+ {type: 'comment', regex: /#[^\n]*/},
+ {type: 'string', regex: /"(?:[^"\\]|\\.)*"/},
+ {type: 'string', regex: /'[^']*'/},
+ {type: 'variable', regex: /\$\{[^}]+\}/},
+ {type: 'variable', regex: /\$[a-zA-Z_][\w]*/},
+ {type: 'variable', regex: /\$[0-9@#?*!$-]/},
+ {type: 'number', regex: /\b\d+\b/},
+ {type: 'keyword', regex: BASH_KEYWORDS},
+ {type: 'function', regex: /\b[a-zA-Z_][\w]*(?=\s*\()/},
+ {type: 'operator', regex: /[|&<>;!]+/},
+ // eslint-disable-next-line no-useless-escape
+ {type: 'punctuation', regex: /[{}()\[\]]/},
+ ],
+ };
+
+ case 'php':
+ return {
+ patterns: [
+ {type: 'comment', regex: /\/\*[\s\S]*?\*\//},
+ {type: 'comment', regex: /\/\/[^\n]*/},
+ {type: 'comment', regex: /#[^\n]*/},
+ {type: 'string', regex: /"(?:[^"\\]|\\.)*"/},
+ {type: 'string', regex: /'(?:[^'\\]|\\.)*'/},
+ {type: 'variable', regex: /\$[a-zA-Z_][\w]*/},
+ {type: 'number', regex: /\b0[xX][0-9a-fA-F]+\b/},
+ {type: 'number', regex: /\b\d+\.?\d*(?:[eE][+-]?\d+)?\b/},
+ {type: 'keyword', regex: PHP_KEYWORDS},
+ {type: 'function', regex: /\b[a-zA-Z_][\w]*(?=\s*\()/},
+ {type: 'type', regex: /\b[A-Z][a-zA-Z0-9_]*\b/},
+ {type: 'operator', regex: /[+\-*/%=!<>&|^~?:.]+/},
+ {type: 'constant', regex: /@[\w]+/},
+ // eslint-disable-next-line no-useless-escape
+ {type: 'punctuation', regex: /[{}()\[\];,.]/},
+ ],
+ };
+
+ case 'hack':
+ return {
+ patterns: [
+ {type: 'comment', regex: /\/\*[\s\S]*?\*\//},
+ {type: 'comment', regex: /\/\/[^\n]*/},
+ {type: 'string', regex: /"(?:[^"\\]|\\.)*"/},
+ {type: 'string', regex: /'(?:[^'\\]|\\.)*'/},
+ {type: 'variable', regex: /\$[a-zA-Z_][\w]*/},
+ {type: 'number', regex: /\b0[xX][0-9a-fA-F]+\b/},
+ {type: 'number', regex: /\b\d+\.?\d*(?:[eE][+-]?\d+)?\b/},
+ {type: 'keyword', regex: HACK_KEYWORDS},
+ {type: 'type', regex: /\b[A-Z][a-zA-Z0-9_]*\b/},
+ {type: 'function', regex: /\b[a-zA-Z_][\w]*(?=\s*\()/},
+ {type: 'property', regex: /(?<=->|::)\b[a-zA-Z_][\w]*\b/},
+ {type: 'operator', regex: /[+\-*/%=!<>&|^~?:.]+/},
+ {type: 'constant', regex: /<<[\w]+/},
+ // eslint-disable-next-line no-useless-escape
+ {type: 'punctuation', regex: /[{}()\[\];,.]/},
+ ],
+ };
+
+ case 'yaml':
+ case 'yml':
+ return {
+ patterns: [
+ {type: 'comment', regex: /#[^\n]*/},
+ {type: 'string', regex: /"(?:[^"\\]|\\.)*"/},
+ {type: 'string', regex: /'(?:[^'\\]|\\.)*'/},
+ {type: 'constant', regex: /\b(true|false|yes|no|on|off|null|~)\b/i},
+ {type: 'variable', regex: /[&*][\w]+/},
+ {type: 'type', regex: /!!\w+/},
+ {type: 'number', regex: /\b-?\d+\.?\d*(?:[eE][+-]?\d+)?\b/},
+ {type: 'property', regex: /^[ \t]*[\w][\w ./-]*(?=\s*:)/m},
+ {type: 'keyword', regex: /---/},
+ {type: 'keyword', regex: /\.\.\./},
+ {type: 'operator', regex: /[:|>\-?]/},
+ // eslint-disable-next-line no-useless-escape
+ {type: 'punctuation', regex: /[{}()\[\],]/},
+ {type: 'variable', regex: /\b[a-zA-Z_][\w]*\b/},
+ ],
+ };
+
+ case 'markdown':
+ case 'md':
+ return {
+ patterns: [
+ {type: 'keyword', regex: /^```[\w]*$/m},
+ {type: 'keyword', regex: /^#{1,6}\s+.*/m},
+ {type: 'keyword', regex: /^---$/m},
+ {type: 'keyword', regex: /^\*\*\*$/m},
+ {type: 'string', regex: /\*\*(?:[^*]|\*(?!\*))+\*\*/},
+ {type: 'string', regex: /\*(?:[^*])+\*/},
+ {type: 'constant', regex: /`[^`]+`/},
+ {type: 'function', regex: /\[(?:[^\]])+\]\([^)]+\)/},
+ {type: 'comment', regex: /^>\s+.*/m},
+ {type: 'operator', regex: /^\s*[-*+]\s/m},
+ {type: 'number', regex: /^\s*\d+\.\s/m},
+ ],
+ };
+
+ default:
+ return null;
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Core tokenizer
+// ---------------------------------------------------------------------------
+
+/**
+ * Tokenizes a code string into an array of typed tokens with character offsets.
+ *
+ * Uses a greedy first-match strategy: at each position, try all patterns in
+ * order and emit the first match. Skips characters that don't match any pattern.
+ *
+ * @param code - The source code string to tokenize
+ * @param language - Language identifier (e.g. 'typescript', 'python')
+ * @returns Array of tokens sorted by start position
+ */
+export function tokenize(code: string, language: string): Token[] {
+ const langDef = buildLanguage(language);
+ if (!langDef) return [];
+
+ const tokens: Token[] = [];
+ let pos = 0;
+
+ while (pos < code.length) {
+ let matched = false;
+
+ for (const pattern of langDef.patterns) {
+ pattern.anchored.lastIndex = pos;
+ const match = pattern.anchored.exec(code);
+
+ if (match && match.index === pos && match[0].length > 0) {
+ tokens.push({
+ type: pattern.type,
+ start: pos,
+ end: pos + match[0].length,
+ });
+ pos += match[0].length;
+ matched = true;
+ break;
+ }
+ }
+
+ if (!matched) {
+ pos++;
+ }
+ }
+
+ return tokens;
+}
diff --git a/packages/lab/src/CodeEditor/XDSCodeEditor.tsx b/packages/lab/src/CodeEditor/XDSCodeEditor.tsx
new file mode 100644
index 0000000000..3a4e6cebec
--- /dev/null
+++ b/packages/lab/src/CodeEditor/XDSCodeEditor.tsx
@@ -0,0 +1,465 @@
+/**
+ * @file XDSCodeEditor.tsx
+ * @input Uses React, StyleX, theme tokens, CSS Custom Highlight API
+ * @output Exports XDSCodeEditor component and XDSCodeEditorProps
+ * @position Core implementation; editable code input (lab/experimental)
+ *
+ * SYNC: When modified, update:
+ * - /packages/lab/src/CodeEditor/index.ts (exports if types change)
+ * - /packages/lab/src/CodeBlock/tokenizer.ts (shared tokenizer)
+ * - /packages/lab/src/CodeBlock/highlightStyles.ts (::highlight rules)
+ */
+
+'use client';
+
+import {useEffect, useLayoutEffect, useRef, useCallback, useState} from 'react';
+import type {XDSBaseProps} from '@xds/core/XDSBaseProps';
+import * as stylex from '@stylexjs/stylex';
+import {
+ colorVars,
+ spacingVars,
+ radiusVars,
+ textSizeVars,
+ typographyVars,
+ lineHeightVars,
+} from '@xds/core/theme/tokens.stylex';
+import {xdsClassName, mergeProps} from '@xds/core/utils';
+import {tokenize} from '../CodeBlock/tokenizer';
+import type {Token} from '../CodeBlock/tokenizer';
+import {ensureHighlightStyles, TOKEN_TYPES} from '../CodeBlock/highlightStyles';
+
+// ---------------------------------------------------------------------------
+// Styles
+// ---------------------------------------------------------------------------
+
+const styles = stylex.create({
+ root: {
+ position: 'relative',
+ display: 'flex',
+ borderRadius: radiusVars['--radius-2'],
+ backgroundColor: colorVars['--color-wash'],
+ border: `1px solid ${colorVars['--color-border']}`,
+ overflow: 'hidden',
+ },
+ rootFocused: {
+ borderColor: colorVars['--color-ring-focus'],
+ boxShadow: `0 0 0 1px ${colorVars['--color-ring-focus']}`,
+ },
+ gutter: {
+ flexShrink: 0,
+ paddingBlock: spacingVars['--spacing-3'],
+ paddingInlineStart: spacingVars['--spacing-4'],
+ paddingInlineEnd: spacingVars['--spacing-3'],
+ textAlign: 'end',
+ userSelect: 'none',
+ color: colorVars['--color-text-disabled'],
+ borderRight: `1px solid ${colorVars['--color-border']}`,
+ },
+ gutterLine: {
+ fontFamily: typographyVars['--font-code'],
+ lineHeight: lineHeightVars['--leading-normal'],
+ },
+ editorContainer: {
+ flex: 1,
+ overflow: 'auto',
+ },
+ editor: {
+ display: 'block',
+ minHeight: '3em',
+ paddingBlock: spacingVars['--spacing-3'],
+ paddingInline: spacingVars['--spacing-4'],
+ margin: 0,
+ fontFamily: typographyVars['--font-code'],
+ color: colorVars['--color-text-primary'],
+ tabSize: 2,
+ whiteSpace: 'pre',
+ wordBreak: 'normal',
+ overflowWrap: 'normal',
+ outline: 'none',
+ caretColor: colorVars['--color-text-primary'],
+ lineHeight: lineHeightVars['--leading-normal'],
+ },
+ placeholder: {
+ position: 'absolute',
+ top: spacingVars['--spacing-3'],
+ left: spacingVars['--spacing-4'],
+ color: colorVars['--color-text-disabled'],
+ fontFamily: typographyVars['--font-code'],
+ lineHeight: lineHeightVars['--leading-normal'],
+ pointerEvents: 'none',
+ userSelect: 'none',
+ },
+ sizeSm: {
+ fontSize: textSizeVars['--text-sm'],
+ },
+ sizeMd: {
+ fontSize: textSizeVars['--text-base'],
+ },
+ gutterSm: {
+ fontSize: textSizeVars['--text-sm'],
+ },
+ gutterMd: {
+ fontSize: textSizeVars['--text-base'],
+ },
+});
+
+// ---------------------------------------------------------------------------
+// Props
+// ---------------------------------------------------------------------------
+
+export interface XDSCodeEditorProps extends Omit<
+ XDSBaseProps<HTMLDivElement>,
+ 'onChange'
+> {
+ /** Ref forwarded to the root element */
+ ref?: React.Ref<HTMLDivElement>;
+ /** Controlled value */
+ value: string;
+ /** Change handler */
+ onChange: (value: string) => void;
+ /** Language for highlighting. @default "plaintext" */
+ language?: string;
+ /** Show line numbers. @default false */
+ hasLineNumbers?: boolean;
+ /** Read-only mode. @default false */
+ isReadOnly?: boolean;
+ /** Placeholder when empty */
+ placeholder?: string;
+ /** Max height before scrolling */
+ maxHeight?: number | string;
+ /** Text size. @default "md" */
+ size?: 'sm' | 'md';
+ /** Custom tokenizer */
+ tokenizer?: (
+ code: string,
+ language: string,
+ ) => Array<{type: string; start: number; end: number}>;
+}
+
+// ---------------------------------------------------------------------------
+// Helpers
+// ---------------------------------------------------------------------------
+
+function hasHighlightAPI(): boolean {
+ return (
+ typeof CSS !== 'undefined' &&
+ 'highlights' in CSS &&
+ typeof Highlight !== 'undefined'
+ );
+}
+
+const AUTO_CLOSE_PAIRS: Record<string, string> = {
+ '(': ')',
+ '[': ']',
+ '{': '}',
+ '"': '"',
+ "'": "'",
+ '`': '`',
+};
+
+let editorInstanceCounter = 0;
+
+// ---------------------------------------------------------------------------
+// Component
+// ---------------------------------------------------------------------------
+
+/**
+ * An editable code input using contentEditable="plaintext-only".
+ *
+ * Uses CSS Custom Highlight API for syntax coloring. Supports
+ * auto-indent, tab insertion, and bracket auto-closing.
+ *
+ * @example
+ * ```tsx
+ * const [code, setCode] = useState('');
+ * <XDSCodeEditor
+ * value={code}
+ * onChange={setCode}
+ * language="typescript"
+ * hasLineNumbers
+ * />
+ * ```
+ */
+export function XDSCodeEditor({
+ value,
+ onChange,
+ language = 'plaintext',
+ hasLineNumbers = false,
+ isReadOnly = false,
+ placeholder,
+ maxHeight,
+ size = 'md',
+ tokenizer: customTokenizer,
+ xstyle,
+ className,
+ style,
+ ref,
+ ...props
+}: XDSCodeEditorProps) {
+ const editorRef = useRef<HTMLDivElement>(null);
+ const [instanceId] = useState(() => ++editorInstanceCounter);
+ const [focused, setFocused] = useState(false);
+ const isComposingRef = useRef(false);
+
+ const lines = value.split('\n');
+
+ // Sync textContent with controlled value
+ useLayoutEffect(() => {
+ const el = editorRef.current;
+ if (!el) return;
+ // Only update DOM if it differs (avoids clobbering cursor)
+ if (el.textContent !== value) {
+ el.textContent = value;
+ }
+ }, [value]);
+
+ // Apply CSS Custom Highlight API ranges
+ useEffect(() => {
+ if (!hasHighlightAPI()) return;
+
+ ensureHighlightStyles();
+
+ const el = editorRef.current;
+ if (!el) return;
+
+ const tok = customTokenizer ?? tokenize;
+ const tokens = tok(value, language);
+ if (tokens.length === 0) return;
+
+ // Group tokens by type
+ const tokensByType = new Map<string, Token[]>();
+ for (const token of tokens) {
+ const existing = tokensByType.get(token.type);
+ if (existing) {
+ existing.push(token);
+ } else {
+ tokensByType.set(token.type, [token]);
+ }
+ }
+
+ // Build text node mapping from the contenteditable element
+ const walker = document.createTreeWalker(el, NodeFilter.SHOW_TEXT);
+ const textNodes: Array<{node: Text; start: number}> = [];
+ let totalOffset = 0;
+
+ let node = walker.nextNode();
+ while (node) {
+ textNodes.push({node: node as Text, start: totalOffset});
+ totalOffset += (node as Text).length;
+ node = walker.nextNode();
+ }
+
+ function findPosition(offset: number): {node: Text; offset: number} | null {
+ for (let i = textNodes.length - 1; i >= 0; i--) {
+ const entry = textNodes[i];
+ if (offset >= entry.start) {
+ const localOffset = offset - entry.start;
+ if (localOffset <= entry.node.length) {
+ return {node: entry.node, offset: localOffset};
+ }
+ return null;
+ }
+ }
+ return null;
+ }
+
+ const myRanges: Range[] = [];
+
+ for (const tokenType of TOKEN_TYPES) {
+ const typedTokens = tokensByType.get(tokenType);
+ if (!typedTokens || typedTokens.length === 0) continue;
+
+ const name = `xds-${tokenType}`;
+ let highlight = CSS.highlights.get(name);
+ if (!highlight) {
+ highlight = new Highlight();
+ CSS.highlights.set(name, highlight);
+ }
+
+ for (const token of typedTokens) {
+ const startPos = findPosition(token.start);
+ const endPos = findPosition(token.end);
+ if (!startPos || !endPos) continue;
+
+ try {
+ const range = new Range();
+ range.setStart(startPos.node, startPos.offset);
+ range.setEnd(endPos.node, endPos.offset);
+ highlight.add(range);
+ myRanges.push(range);
+ } catch {
+ // Skip invalid ranges
+ }
+ }
+ }
+
+ return () => {
+ for (const range of myRanges) {
+ for (const tokenType of TOKEN_TYPES) {
+ const highlight = CSS.highlights.get(`xds-${tokenType}`);
+ if (highlight) {
+ highlight.delete(range);
+ }
+ }
+ }
+ };
+ }, [value, language, customTokenizer, instanceId]);
+
+ const handleInput = useCallback(() => {
+ if (isComposingRef.current) return;
+ const el = editorRef.current;
+ if (!el) return;
+ const newValue = el.textContent ?? '';
+ onChange(newValue);
+ }, [onChange]);
+
+ const handleKeyDown = useCallback(
+ (e: React.KeyboardEvent<HTMLDivElement>) => {
+ if (isReadOnly) return;
+
+ // Tab key: insert 2 spaces
+ if (e.key === 'Tab') {
+ e.preventDefault();
+ const sel = window.getSelection();
+ if (!sel || sel.rangeCount === 0) return;
+ const range = sel.getRangeAt(0);
+ range.deleteContents();
+ const textNode = document.createTextNode(' ');
+ range.insertNode(textNode);
+ range.setStartAfter(textNode);
+ range.setEndAfter(textNode);
+ sel.removeAllRanges();
+ sel.addRange(range);
+ const el = editorRef.current;
+ if (el) onChange(el.textContent ?? '');
+ return;
+ }
+
+ // Enter key: preserve indentation
+ if (e.key === 'Enter') {
+ e.preventDefault();
+ const sel = window.getSelection();
+ if (!sel || sel.rangeCount === 0) return;
+
+ const el = editorRef.current;
+ if (!el) return;
+ const fullText = el.textContent ?? '';
+
+ // Find cursor offset
+ const range = sel.getRangeAt(0);
+ const preCaretRange = range.cloneRange();
+ preCaretRange.selectNodeContents(el);
+ preCaretRange.setEnd(range.startContainer, range.startOffset);
+ const cursorOffset = preCaretRange.toString().length;
+
+ // Find current line and its indentation
+ const beforeCursor = fullText.slice(0, cursorOffset);
+ const lastNewline = beforeCursor.lastIndexOf('\n');
+ const currentLine = beforeCursor.slice(lastNewline + 1);
+ const indent = currentLine.match(/^(\s*)/)?.[1] ?? '';
+
+ // Insert newline + indent
+ const insertText = '\n' + indent;
+ range.deleteContents();
+ const textNode = document.createTextNode(insertText);
+ range.insertNode(textNode);
+ range.setStartAfter(textNode);
+ range.setEndAfter(textNode);
+ sel.removeAllRanges();
+ sel.addRange(range);
+ onChange(el.textContent ?? '');
+ return;
+ }
+
+ // Auto-close brackets and quotes
+ const closeChar = AUTO_CLOSE_PAIRS[e.key];
+ if (closeChar) {
+ const sel = window.getSelection();
+ if (!sel || sel.rangeCount === 0) return;
+ const range = sel.getRangeAt(0);
+
+ // Only auto-close if no text is selected
+ if (!range.collapsed) return;
+
+ e.preventDefault();
+ const textNode = document.createTextNode(e.key + closeChar);
+ range.deleteContents();
+ range.insertNode(textNode);
+ // Place cursor between the pair
+ range.setStart(textNode, 1);
+ range.setEnd(textNode, 1);
+ sel.removeAllRanges();
+ sel.addRange(range);
+ const el = editorRef.current;
+ if (el) onChange(el.textContent ?? '');
+ }
+ },
+ [isReadOnly, onChange],
+ );
+
+ const handleCompositionStart = useCallback(() => {
+ isComposingRef.current = true;
+ }, []);
+
+ const handleCompositionEnd = useCallback(() => {
+ isComposingRef.current = false;
+ handleInput();
+ }, [handleInput]);
+
+ const sizeStyle = size === 'sm' ? styles.sizeSm : styles.sizeMd;
+ const gutterSizeStyle = size === 'sm' ? styles.gutterSm : styles.gutterMd;
+ const showPlaceholder = placeholder && value === '';
+
+ const containerStyle: React.CSSProperties | undefined = maxHeight
+ ? {maxHeight: typeof maxHeight === 'number' ? `${maxHeight}px` : maxHeight}
+ : undefined;
+
+ return (
+ <div
+ ref={ref}
+ {...mergeProps(
+ xdsClassName('codeeditor', {size, language}),
+ stylex.props(styles.root, focused && styles.rootFocused, xstyle),
+ className,
+ style,
+ )}
+ {...props}>
+ {hasLineNumbers && (
+ <div
+ {...stylex.props(styles.gutter, gutterSizeStyle)}
+ aria-hidden="true">
+ {lines.map((_, i) => (
+ <div key={i} {...stylex.props(styles.gutterLine)}>
+ {i + 1}
+ </div>
+ ))}
+ </div>
+ )}
+ <div {...stylex.props(styles.editorContainer)} style={containerStyle}>
+ {showPlaceholder && (
+ <div {...stylex.props(styles.placeholder, sizeStyle)}>
+ {placeholder}
+ </div>
+ )}
+ <div
+ ref={editorRef}
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ contentEditable={isReadOnly ? false : ('plaintext-only' as any)}
+ role="textbox"
+ aria-multiline="true"
+ aria-readonly={isReadOnly}
+ spellCheck={false}
+ onInput={handleInput}
+ onKeyDown={handleKeyDown}
+ onFocus={() => setFocused(true)}
+ onBlur={() => setFocused(false)}
+ onCompositionStart={handleCompositionStart}
+ onCompositionEnd={handleCompositionEnd}
+ {...stylex.props(styles.editor, sizeStyle)}
+ />
+ </div>
+ </div>
+ );
+}
+
+XDSCodeEditor.displayName = 'XDSCodeEditor';
diff --git a/packages/lab/src/CodeEditor/index.ts b/packages/lab/src/CodeEditor/index.ts
new file mode 100644
index 0000000000..c3a22b20b0
--- /dev/null
+++ b/packages/lab/src/CodeEditor/index.ts
@@ -0,0 +1,6 @@
+/**
+ * @file CodeEditor component barrel export
+ */
+
+export {XDSCodeEditor} from './XDSCodeEditor';
+export type {XDSCodeEditorProps} from './XDSCodeEditor';
diff --git a/packages/lab/src/index.ts b/packages/lab/src/index.ts
index b79b44deee..41d71addb9 100644
--- a/packages/lab/src/index.ts
+++ b/packages/lab/src/index.ts
@@ -26,3 +26,8 @@ export {
defaultFilter,
type CommandPaletteFilterFn,
} from './CommandPalette';
+
+// Code components — syntax highlighting domain
+export {XDSCodeBlock, type XDSCodeBlockProps} from './CodeBlock';
+export {XDSCodeEditor, type XDSCodeEditorProps} from './CodeEditor';
+export {tokenize, type Token} from './CodeBlock/tokenizer';