Skip to content

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

TypeScript

perf(codeblock): per-line tokens, skip default color, fix ::highlight selectors (#1369)

Cindy Zhangb2f51e4d922c
diff --git a/packages/core/src/CodeBlock/XDSCodeBlock.tsx b/packages/core/src/CodeBlock/XDSCodeBlock.tsx
index c9ffdc2148..16b41f5604 100644
--- a/packages/core/src/CodeBlock/XDSCodeBlock.tsx
+++ b/packages/core/src/CodeBlock/XDSCodeBlock.tsx
@@ -4,17 +4,11 @@
* @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/core/src/CodeBlock/index.ts (exports if types change)
- * - /packages/core/src/CodeBlock/tokenizer.ts (shared tokenizer)
- * - /packages/core/src/CodeBlock/highlightStyles.ts (::highlight rules)
*/
import {
useLayoutEffect,
useEffect,
- useId,
useRef,
useState,
useCallback,
@@ -38,8 +32,13 @@ import {
} from '../theme/tokens.stylex';
import {xdsClassName, mergeProps} from '../utils';
import {XDSIcon} from '../Icon';
-import {tokenize, tokenizeAsync, SYNC_TOKENIZE_THRESHOLD} from './tokenizer';
-import type {Token} from './tokenizer';
+import {
+ tokenize,
+ tokenizeAsync,
+ flatTokensToLines,
+ SYNC_TOKENIZE_THRESHOLD,
+} from './tokenizer';
+import type {Token, TokenLine} from './tokenizer';
import {ensureHighlightStyles} from './highlightStyles';
import {applyHighlightRangesChunked} from './highlightRanges';
@@ -94,7 +93,6 @@ const styles = stylex.create({
overflowX: 'auto',
overflowY: 'auto',
},
-
codeWrapper: {
display: 'flex',
minWidth: 'fit-content',
@@ -102,7 +100,6 @@ const styles = stylex.create({
codeWrapperCompact: {
marginBlockStart: `calc(-1 * ${spacingVars['--spacing-2']})`,
},
- // Collapse animation via grid-template-rows
collapseGrid: {
display: 'grid',
gridTemplateRows: '1fr',
@@ -215,30 +212,43 @@ const styles = stylex.create({
});
// ---------------------------------------------------------------------------
-// Line rendering (shared)
+// Line rendering
// ---------------------------------------------------------------------------
const LINE_CHUNK_SIZE = 20;
const LINE_CHUNK_THRESHOLD = 100;
/**
- * Memoized line component to avoid re-rendering unchanged lines.
+ * Memoized chunk component — cheaper than memoizing every individual line.
*/
-const CodeLine = React.memo(function CodeLine({
- lineIndex,
- isHighlighted,
- children,
+const CodeChunk = React.memo(function CodeChunk({
+ lines,
+ startIndex,
+ highlightSet,
+ renderLineContent,
}: {
- lineIndex: number;
- isHighlighted: boolean;
- children: React.ReactNode;
+ lines: string[];
+ startIndex: number;
+ highlightSet: Set<number> | null;
+ renderLineContent: (line: string, lineIndex: number) => React.ReactNode;
}) {
return (
- <div
- data-line={lineIndex + 1}
- {...stylex.props(styles.line, isHighlighted && styles.lineHighlighted)}>
- {children}
- </div>
+ <>
+ {lines.map((line, j) => {
+ const i = startIndex + j;
+ return (
+ <div
+ key={i}
+ data-line={i + 1}
+ {...stylex.props(
+ styles.line,
+ (highlightSet?.has(i + 1) ?? false) && styles.lineHighlighted,
+ )}>
+ {renderLineContent(line, i)}
+ </div>
+ );
+ })}
+ </>
);
});
@@ -250,17 +260,15 @@ function renderLines(
): React.ReactNode {
chunkSize = Math.max(1, Math.floor(chunkSize));
- const renderLine = (line: string, i: number) => (
- <CodeLine
- key={i}
- lineIndex={i}
- isHighlighted={highlightSet?.has(i + 1) ?? false}>
- {renderLineContent(line, i)}
- </CodeLine>
- );
-
if (lines.length < LINE_CHUNK_THRESHOLD) {
- return lines.map(renderLine);
+ return (
+ <CodeChunk
+ lines={lines}
+ startIndex={0}
+ highlightSet={highlightSet}
+ renderLineContent={renderLineContent}
+ />
+ );
}
const chunks: React.ReactNode[] = [];
@@ -274,7 +282,12 @@ function renderLines(
key={start}
{...stylex.props(styles.lineChunk)}
style={{containIntrinsicBlockSize: `auto ${estimatedHeight}`}}>
- {chunkLines.map((line, j) => renderLine(line, start + j))}
+ <CodeChunk
+ lines={chunkLines}
+ startIndex={start}
+ highlightSet={highlightSet}
+ renderLineContent={renderLineContent}
+ />
</div>,
);
}
@@ -297,32 +310,13 @@ export interface XDSCodeBlockProps extends XDSBaseProps<HTMLPreElement> {
onCopy?: () => void;
isWrapped?: boolean;
maxHeight?: number | string;
- /**
- * Allow collapsing the code body into just the header bar.
- * Starts expanded; the header becomes clickable to toggle.
- * Only shows the toggle when the code exceeds `collapsibleThreshold` lines.
- * @default false
- */
isCollapsible?: boolean;
- /**
- * Minimum number of lines before the collapse toggle appears.
- * Below this threshold the code block renders normally even when
- * `isCollapsible` is true.
- * @default 10
- */
collapsibleThreshold?: number;
size?: 'sm' | 'md';
tokenizer?: (
code: string,
language: string,
) => Array<{type: string; start: number; end: number}>;
- /**
- * Highlighting strategy.
- * - `'auto'` — uses CSS Custom Highlight API when available, falls back to spans
- * - `'ranges'` — force CSS Custom Highlight API (no-op if unsupported)
- * - `'spans'` — force span-based rendering
- * @default 'auto'
- */
highlightMode?: 'auto' | 'ranges' | 'spans';
}
@@ -338,136 +332,112 @@ function hasHighlightAPI(): boolean {
);
}
-// ---------------------------------------------------------------------------
-// Span-mode code element
-// ---------------------------------------------------------------------------
+/**
+ * Hook: per-line tokens with sync/async + custom tokenizer compat.
+ */
+function useTokenLines(
+ code: string,
+ language: string,
+ customTokenizer?: XDSCodeBlockProps['tokenizer'],
+): TokenLine[] {
+ const [asyncTokens, setAsyncTokens] = useState<TokenLine[] | null>(null);
-function findFirstTokenIndex(tokens: Token[], lineStart: number): number {
- let lo = 0;
- let hi = tokens.length;
- while (lo < hi) {
- const mid = (lo + hi) >>> 1;
- if (tokens[mid].end <= lineStart) {
- lo = mid + 1;
+ const syncTokens = useMemo(() => {
+ if (code.length >= SYNC_TOKENIZE_THRESHOLD) return null;
+ if (customTokenizer) {
+ return flatTokensToLines(customTokenizer(code, language), code);
+ }
+ return tokenize(code, language);
+ }, [code, language, customTokenizer]);
+
+ useEffect(() => {
+ if (code.length < SYNC_TOKENIZE_THRESHOLD) return;
+
+ const abortController = new AbortController();
+
+ if (customTokenizer) {
+ Promise.resolve().then(() => {
+ if (abortController.signal.aborted) return;
+ const flat = customTokenizer(code, language);
+ setAsyncTokens(flatTokensToLines(flat, code));
+ });
} else {
- hi = mid;
+ tokenizeAsync(code, language, abortController.signal).then(tokens => {
+ if (!abortController.signal.aborted) {
+ setAsyncTokens(tokens);
+ }
+ });
}
- }
- return lo;
+
+ return () => {
+ abortController.abort();
+ setAsyncTokens(null);
+ };
+ }, [code, language, customTokenizer]);
+
+ return syncTokens ?? asyncTokens ?? [];
}
+// ---------------------------------------------------------------------------
+// Span-mode code element
+// ---------------------------------------------------------------------------
+
function buildSpanLine(
lineText: string,
- lineStart: number,
tokens: Token[],
- searchStart: number,
): React.ReactNode {
if (tokens.length === 0) {
return lineText || '\u200b';
}
- const lineEnd = lineStart + lineText.length;
const parts: React.ReactNode[] = [];
- let cursor = lineStart;
- let hasTokens = false;
+ let cursor = 0;
- for (let i = searchStart; i < tokens.length; i++) {
- const token = tokens[i];
- if (token.start >= lineEnd) break;
- if (token.end <= lineStart) continue;
-
- hasTokens = true;
- const tStart = Math.max(token.start, lineStart);
- const tEnd = Math.min(token.end, lineEnd);
-
- if (tStart > cursor) {
- parts.push(lineText.slice(cursor - lineStart, tStart - lineStart));
+ for (const token of tokens) {
+ if (token.start > cursor) {
+ parts.push(lineText.slice(cursor, token.start));
}
+ const end = Math.min(token.end, lineText.length);
parts.push(
<span
- key={`${tStart}-${token.type}`}
+ key={`${token.start}-${token.type}`}
className={`xds-token-${token.type}`}>
- {lineText.slice(tStart - lineStart, tEnd - lineStart)}
+ {lineText.slice(token.start, end)}
</span>,
);
- cursor = tEnd;
+ cursor = end;
}
- if (!hasTokens) return lineText || '\u200b';
- if (cursor < lineEnd) parts.push(lineText.slice(cursor - lineStart));
+ if (cursor < lineText.length) {
+ parts.push(lineText.slice(cursor));
+ }
return parts.length > 0 ? parts : '\u200b';
}
-/**
- * Span-mode: tokenizes code and renders lines with <span> tokens.
- * Only mounts when highlightMode resolves to spans.
- */
function SpanCodeContent({
- code,
- language,
lines,
- lineOffsets,
+ tokenLines,
highlightSet,
isWrapped,
sizeStyle,
- customTokenizer,
}: {
- code: string;
- language: string;
lines: string[];
- lineOffsets: number[];
+ tokenLines: TokenLine[];
highlightSet: Set<number> | null;
isWrapped: boolean;
sizeStyle: stylex.StyleXStyles;
- customTokenizer?: XDSCodeBlockProps['tokenizer'];
}) {
- const [asyncTokens, setAsyncTokens] = useState<Token[] | null>(null);
-
useLayoutEffect(() => {
ensureHighlightStyles();
}, []);
- const syncTokens = useMemo(() => {
- if (code.length >= SYNC_TOKENIZE_THRESHOLD) return null;
- const tok = customTokenizer ?? tokenize;
- return tok(code, language);
- }, [code, language, customTokenizer]);
-
- useEffect(() => {
- if (code.length < SYNC_TOKENIZE_THRESHOLD) return;
-
- const abortController = new AbortController();
- tokenizeAsync(code, language, abortController.signal).then(tokens => {
- if (!abortController.signal.aborted) {
- setAsyncTokens(tokens);
- }
- });
-
- return () => {
- abortController.abort();
- setAsyncTokens(null);
- };
- }, [code, language, customTokenizer]);
-
- const spanTokens = syncTokens ?? asyncTokens ?? [];
-
- const tokenSearchStarts = useMemo(() => {
- if (spanTokens.length === 0) return null;
- const starts = new Array<number>(lines.length);
- for (let i = 0; i < lines.length; i++) {
- starts[i] = findFirstTokenIndex(spanTokens, lineOffsets[i]);
- }
- return starts;
- }, [spanTokens, lines.length, lineOffsets]);
-
- function renderLineContent(line: string, lineIndex: number): React.ReactNode {
- return buildSpanLine(
- line,
- lineOffsets[lineIndex],
- spanTokens,
- tokenSearchStarts?.[lineIndex] ?? 0,
- );
- }
+ const renderLineContent = useCallback(
+ (line: string, lineIndex: number): React.ReactNode => {
+ const tokens = tokenLines[lineIndex] ?? [];
+ return buildSpanLine(line, tokens);
+ },
+ [tokenLines],
+ );
return (
<code
@@ -485,66 +455,35 @@ function SpanCodeContent({
// Range-mode code element
// ---------------------------------------------------------------------------
-/**
- * Range-mode: renders plain text lines, applies CSS Custom Highlight API
- * ranges in a non-blocking effect. Only mounts when highlightMode
- * resolves to ranges.
- */
function RangeCodeContent({
- code,
- language,
lines,
+ tokenLines,
highlightSet,
isWrapped,
sizeStyle,
- customTokenizer,
}: {
- code: string;
- language: string;
lines: string[];
+ tokenLines: TokenLine[];
highlightSet: Set<number> | null;
isWrapped: boolean;
sizeStyle: stylex.StyleXStyles;
- customTokenizer?: XDSCodeBlockProps['tokenizer'];
}) {
const codeRef = useRef<HTMLElement>(null);
- const instanceId = useId();
- // Apply highlight ranges in a non-blocking effect so the code text
- // is visible and scrollable immediately. Colors appear a frame later.
useEffect(() => {
if (!hasHighlightAPI()) return;
-
ensureHighlightStyles();
const codeEl = codeRef.current;
- if (!codeEl) return;
+ if (!codeEl || tokenLines.length === 0) return;
- if (code.length < SYNC_TOKENIZE_THRESHOLD) {
- const tok = customTokenizer ?? tokenize;
- const tokens = tok(code, language);
- if (tokens.length === 0) return;
- return applyHighlightRangesChunked(codeEl, tokens);
- }
-
- const abortController = new AbortController();
- let cleanup: (() => void) | undefined;
+ return applyHighlightRangesChunked(codeEl, tokenLines);
+ }, [tokenLines]);
- tokenizeAsync(code, language, abortController.signal).then(tokens => {
- if (abortController.signal.aborted) return;
- if (tokens.length === 0) return;
- cleanup = applyHighlightRangesChunked(codeEl, tokens);
- });
-
- return () => {
- abortController.abort();
- cleanup?.();
- };
- }, [code, language, customTokenizer, instanceId]);
-
- function renderLineContent(line: string): React.ReactNode {
- return line || '\u200b';
- }
+ const renderLineContent = useCallback(
+ (line: string): React.ReactNode => line || '\u200b',
+ [],
+ );
return (
<code
@@ -554,9 +493,6 @@ function RangeCodeContent({
sizeStyle,
isWrapped && styles.codeWrapped,
)}>
- {/* No content-visibility chunking in range mode — TreeWalker
- can't see text nodes inside content-visibility: auto divs,
- so highlight ranges would be missing for off-screen lines. */}
{renderLines(lines, highlightSet, renderLineContent, Infinity)}
</code>
);
@@ -566,22 +502,6 @@ function RangeCodeContent({
// Main component
// ---------------------------------------------------------------------------
-/**
- * A read-only syntax-highlighted code block.
- *
- * Uses the CSS Custom Highlight API for zero-DOM-overhead syntax coloring.
- * Falls back to span-based rendering in browsers without support, or when
- * `highlightMode="spans"` is explicitly set.
- *
- * @example
- * ```
- * <XDSCodeBlock
- * code={`const x = 42;`}
- * language="typescript"
- * hasLineNumbers
- * />
- * ```
- */
export function XDSCodeBlock({
code,
language = 'plaintext',
@@ -610,20 +530,16 @@ export function XDSCodeBlock({
highlightMode === 'spans' ||
(highlightMode === 'auto' && !hasHighlightAPI());
- const {lines, lineOffsets} = useMemo(() => {
+ const lines = useMemo(() => {
const l = code.split('\n');
if (l.length > 1 && l[l.length - 1] === '') {
l.pop();
}
- const offsets = new Array<number>(l.length);
- let offset = 0;
- for (let i = 0; i < l.length; i++) {
- offsets[i] = offset;
- offset += l[i].length + 1;
- }
- return {lines: l, lineOffsets: offsets};
+ return l;
}, [code]);
+ const tokenLines = useTokenLines(code, language, customTokenizer);
+
const highlightSet = useMemo(
() => (highlightLines ? new Set(highlightLines) : null),
[highlightLines],
@@ -643,7 +559,6 @@ export function XDSCodeBlock({
hasLanguageLabel && language !== 'plaintext' ? language : null;
const showHeader = title != null || languageLabel != null;
- // Collapse state — starts expanded, user can collapse long blocks
const canCollapse = isCollapsible && lines.length >= collapsibleThreshold;
const [isCollapsed, setIsCollapsed] = useState(false);
@@ -653,62 +568,40 @@ export function XDSCodeBlock({
: undefined;
const copyIcon = copied ? (
- <svg
- width="1em"
- height="1em"
- viewBox="0 0 24 24"
- fill="none"
- stroke="currentColor"
- strokeWidth={1.5}
- strokeLinecap="round"
- strokeLinejoin="round">
+ <svg width="1em" height="1em" viewBox="0 0 24 24" fill="none"
+ stroke="currentColor" strokeWidth={1.5} strokeLinecap="round" strokeLinejoin="round">
<path d="M5 13l4 4L19 7" />
</svg>
) : (
- <svg
- width="1em"
- height="1em"
- viewBox="0 0 24 24"
- fill="none"
- stroke="currentColor"
- strokeWidth={1.5}
- strokeLinecap="round"
- strokeLinejoin="round">
+ <svg width="1em" height="1em" viewBox="0 0 24 24" fill="none"
+ stroke="currentColor" strokeWidth={1.5} strokeLinecap="round" strokeLinejoin="round">
<path d="M8 4v12a2 2 0 002 2h8a2 2 0 002-2V7.242a2 2 0 00-.602-1.43L16.083 2.57A2 2 0 0014.685 2H10a2 2 0 00-2 2z" />
<path d="M16 18v2a2 2 0 01-2 2H6a2 2 0 01-2-2V9a2 2 0 012-2h2" />
</svg>
);
const copyButtonEl = hasCopyButton ? (
- <button
- type="button"
- onClick={handleCopy}
+ <button type="button" onClick={handleCopy}
aria-label={copied ? 'Copied' : 'Copy code'}
- {...stylex.props(
- styles.copyButton,
- !showHeader && styles.copyButtonAbsolute,
- )}>
+ {...stylex.props(styles.copyButton, !showHeader && styles.copyButtonAbsolute)}>
{copyIcon}
</button>
) : null;
- // Header element — clickable when collapsible
const headerEl = showHeader ? (
<div
role={canCollapse ? 'button' : undefined}
tabIndex={canCollapse ? 0 : undefined}
aria-expanded={canCollapse ? !isCollapsed : undefined}
onClick={canCollapse ? () => setIsCollapsed(prev => !prev) : undefined}
- onKeyDown={
- canCollapse
- ? (e: React.KeyboardEvent) => {
- if (e.key === 'Enter' || e.key === ' ') {
- e.preventDefault();
- setIsCollapsed(prev => !prev);
- }
+ onKeyDown={canCollapse
+ ? (e: React.KeyboardEvent) => {
+ if (e.key === 'Enter' || e.key === ' ') {
+ e.preventDefault();
+ setIsCollapsed(prev => !prev);
}
- : undefined
- }
+ }
+ : undefined}
{...stylex.props(
styles.header,
hasLineNumbers ? styles.headerWithDivider : styles.headerCompact,
@@ -719,11 +612,10 @@ export function XDSCodeBlock({
{title && languageLabel ? ' — ' : ''}
{languageLabel}
{canCollapse && (
- <span
- {...stylex.props(
- styles.collapseChevron,
- isCollapsed && styles.collapseChevronCollapsed,
- )}>
+ <span {...stylex.props(
+ styles.collapseChevron,
+ isCollapsed && styles.collapseChevronCollapsed,
+ )}>
<XDSIcon icon="chevronDown" size="xsm" color="inherit" />
</span>
)}
@@ -732,48 +624,31 @@ export function XDSCodeBlock({
</div>
) : null;
- // Code body
const codeBody = (
- <div
- ref={scrollContainerRef}
- {...stylex.props(styles.scrollContainer)}
- style={scrollStyle}>
- <div
- {...stylex.props(
- styles.codeWrapper,
- showHeader && !hasLineNumbers && styles.codeWrapperCompact,
- )}>
+ <div ref={scrollContainerRef} {...stylex.props(styles.scrollContainer)} style={scrollStyle}>
+ <div {...stylex.props(styles.codeWrapper, showHeader && !hasLineNumbers && styles.codeWrapperCompact)}>
{hasLineNumbers && (
- <div
- {...stylex.props(styles.gutter, gutterSizeStyle)}
- aria-hidden="true">
+ <div {...stylex.props(styles.gutter, gutterSizeStyle)} aria-hidden="true">
{lines.map((_, i) => (
- <div key={i} {...stylex.props(styles.gutterLine)}>
- {i + 1}
- </div>
+ <div key={i} {...stylex.props(styles.gutterLine)}>{i + 1}</div>
))}
</div>
)}
{useSpans ? (
<SpanCodeContent
- code={code}
- language={language}
lines={lines}
- lineOffsets={lineOffsets}
+ tokenLines={tokenLines}
highlightSet={highlightSet}
isWrapped={isWrapped}
sizeStyle={sizeStyle}
- customTokenizer={customTokenizer}
/>
) : (
<RangeCodeContent
- code={code}
- language={language}
lines={lines}
+ tokenLines={tokenLines}
highlightSet={highlightSet}
isWrapped={isWrapped}
sizeStyle={sizeStyle}
- customTokenizer={customTokenizer}
/>
)}
</div>
@@ -783,20 +658,11 @@ export function XDSCodeBlock({
return (
<pre
ref={ref}
- {...mergeProps(
- xdsClassName('codeblock', {size, language}),
- stylex.props(styles.root, xstyle),
- className,
- style,
- )}
+ {...mergeProps(xdsClassName('codeblock', {size, language}), stylex.props(styles.root, xstyle), className, style)}
{...props}>
{headerEl}
{canCollapse ? (
- <div
- {...stylex.props(
- styles.collapseGrid,
- isCollapsed && styles.collapseGridCollapsed,
- )}>
+ <div {...stylex.props(styles.collapseGrid, isCollapsed && styles.collapseGridCollapsed)}>
<div {...stylex.props(styles.collapseInner)}>{codeBody}</div>
</div>
) : (
diff --git a/packages/core/src/CodeBlock/highlightRanges.test.ts b/packages/core/src/CodeBlock/highlightRanges.test.ts
index a40b49f420..72b5eeb2ff 100644
--- a/packages/core/src/CodeBlock/highlightRanges.test.ts
+++ b/packages/core/src/CodeBlock/highlightRanges.test.ts
@@ -1,203 +1,113 @@
-/**
- * @file highlightRanges.test.ts
- * Tests for binary search, text node mapping, and range application.
- */
-
-import {describe, it, expect, beforeEach, afterEach} from 'vitest';
-import {buildTextNodeMap, applyHighlightRanges} from './highlightRanges';
+import {describe, it, expect, vi, beforeEach, afterEach} from 'vitest';
+import {applyHighlightRangesChunked} from './highlightRanges';
+import type {TokenLine} from './tokenizer';
+
+// Mock CSS Highlight API
+class MockHighlight extends Set<Range> {}
+const mockHighlightsMap = new Map<string, MockHighlight>();
+
+beforeEach(() => {
+ mockHighlightsMap.clear();
+
+ // @ts-expect-error - mocking global CSS.highlights
+ globalThis.CSS = {
+ highlights: {
+ get: (name: string) => mockHighlightsMap.get(name),
+ set: (name: string, h: MockHighlight) => mockHighlightsMap.set(name, h),
+ },
+ };
+
+ // @ts-expect-error - mocking global Highlight
+ globalThis.Highlight = MockHighlight;
+
+ // Mock requestAnimationFrame
+ vi.stubGlobal('requestAnimationFrame', (fn: FrameRequestCallback) => {
+ fn(0);
+ return 0;
+ });
+ vi.stubGlobal('cancelAnimationFrame', () => {});
+});
-// ---------------------------------------------------------------------------
-// DOM helpers
-// ---------------------------------------------------------------------------
+afterEach(() => {
+ vi.restoreAllMocks();
+});
-function makeCodeEl(lines: string[]): HTMLElement {
+function createCodeElement(lines: string[]): HTMLElement {
const code = document.createElement('code');
- for (const line of lines) {
+ for (let i = 0; i < lines.length; i++) {
const div = document.createElement('div');
- div.textContent = line || '\u200b';
+ div.setAttribute('data-line', String(i + 1));
+ div.textContent = lines[i] || '\u200b';
code.appendChild(div);
}
- document.body.appendChild(code);
return code;
}
-afterEach(() => {
- document.body.innerHTML = '';
-});
-
-// ---------------------------------------------------------------------------
-// buildTextNodeMap
-// ---------------------------------------------------------------------------
-
-describe('buildTextNodeMap', () => {
- it('maps single-line code', () => {
- const el = makeCodeEl(['const x = 1;']);
- const nodes = buildTextNodeMap(el);
-
- expect(nodes).toHaveLength(1);
- expect(nodes[0].start).toBe(0);
- expect(nodes[0].node.textContent).toBe('const x = 1;');
- });
-
- it('maps multi-line code with correct offsets', () => {
- const el = makeCodeEl(['hello', 'world']);
- const nodes = buildTextNodeMap(el);
-
- expect(nodes).toHaveLength(2);
- expect(nodes[0].start).toBe(0);
- expect(nodes[1].start).toBe(6); // "hello"(5) + 1 for \n
- });
-
- it('handles empty lines (zero-width space)', () => {
- const el = makeCodeEl(['hello', '', 'world']);
- const nodes = buildTextNodeMap(el);
-
- // ZWSP nodes not included in array
- expect(nodes).toHaveLength(2);
- expect(nodes[0].start).toBe(0);
- expect(nodes[1].start).toBe(7); // "hello"(5) + \n(1) + ZWSP(1)
- });
-
- it('returns empty for empty element', () => {
- const el = document.createElement('code');
- document.body.appendChild(el);
- expect(buildTextNodeMap(el)).toHaveLength(0);
- });
-
- it('offset accounts for multiple consecutive empty lines', () => {
- const el = makeCodeEl(['a', '', '', 'b']);
- const nodes = buildTextNodeMap(el);
-
- expect(nodes).toHaveLength(2);
- expect(nodes[0].start).toBe(0); // "a"
- expect(nodes[1].start).toBe(4); // "a"(1) + \n(1) + ZWSP(1) + ZWSP(1)
- });
-});
-
-// ---------------------------------------------------------------------------
-// applyHighlightRanges
-// ---------------------------------------------------------------------------
-
-describe('applyHighlightRanges', () => {
- let mockHighlights: Map<string, Set<Range>>;
-
- beforeEach(() => {
- mockHighlights = new Map();
-
- if (typeof CSS === 'undefined') {
- (globalThis as Record<string, unknown>).CSS = {};
- }
- (CSS as Record<string, unknown>).highlights = {
- get(name: string) {
- return mockHighlights.get(name);
- },
- set(name: string, highlight: Set<Range>) {
- mockHighlights.set(name, highlight);
- },
- };
-
- (globalThis as Record<string, unknown>).Highlight =
- class MockHighlight extends Set<Range> {};
- });
-
- afterEach(() => {
- delete (CSS as Record<string, unknown>).highlights;
- delete (globalThis as Record<string, unknown>).Highlight;
- });
-
- it('creates ranges for tokens', () => {
- const el = makeCodeEl(['const x = 1;']);
- const tokens = [
- {type: 'keyword', start: 0, end: 5},
- {type: 'variable', start: 6, end: 7},
- {type: 'number', start: 10, end: 11},
+describe('applyHighlightRangesChunked', () => {
+ it('creates ranges for tokens on each line', () => {
+ const codeEl = createCodeElement(['const x = 1;', 'let y = 2;']);
+ const tokenLines: TokenLine[] = [
+ [{type: 'keyword', start: 0, end: 5}], // "const"
+ [{type: 'keyword', start: 0, end: 3}], // "let"
];
- const cleanupFn = applyHighlightRanges(el, tokens);
-
- expect(mockHighlights.has('xds-keyword')).toBe(true);
- expect(mockHighlights.has('xds-variable')).toBe(true);
- expect(mockHighlights.has('xds-number')).toBe(true);
- expect(mockHighlights.get('xds-keyword')!.size).toBe(1);
- expect(mockHighlights.get('xds-variable')!.size).toBe(1);
- expect(mockHighlights.get('xds-number')!.size).toBe(1);
-
- cleanupFn();
- });
+ // Need to inject the style element mock
+ const mockStyle = document.createElement('style');
+ mockStyle.setAttribute('data-xds-highlight-styles', '');
+ document.head.appendChild(mockStyle);
- it('handles multi-line tokens', () => {
- const el = makeCodeEl(['const x = 1;', 'let y = 2;']);
- const tokens = [
- {type: 'keyword', start: 0, end: 5},
- {type: 'keyword', start: 14, end: 17},
- ];
+ const cleanup = applyHighlightRangesChunked(codeEl, tokenLines);
- const cleanupFn = applyHighlightRanges(el, tokens);
- expect(mockHighlights.get('xds-keyword')!.size).toBe(2);
- cleanupFn();
- });
-
- it('skips tokens with out-of-bounds offsets', () => {
- const el = makeCodeEl(['hello']);
- const tokens = [
- {type: 'keyword', start: 0, end: 5},
- {type: 'keyword', start: 100, end: 105},
- ];
+ const kwHighlight = mockHighlightsMap.get('xds-keyword');
+ expect(kwHighlight).toBeDefined();
+ expect(kwHighlight!.size).toBe(2);
- const cleanupFn = applyHighlightRanges(el, tokens);
- expect(mockHighlights.get('xds-keyword')!.size).toBe(1);
- cleanupFn();
+ cleanup();
+ expect(kwHighlight!.size).toBe(0);
});
- it('cleanup removes all ranges', () => {
- const el = makeCodeEl(['const x = 1;']);
- const tokens = [
- {type: 'keyword', start: 0, end: 5},
- {type: 'number', start: 10, end: 11},
+ it('handles empty token lines', () => {
+ const codeEl = createCodeElement(['', 'const x = 1;']);
+ const tokenLines: TokenLine[] = [
+ [],
+ [{type: 'keyword', start: 0, end: 5}],
];
- const cleanupFn = applyHighlightRanges(el, tokens);
- expect(mockHighlights.get('xds-keyword')!.size).toBe(1);
- expect(mockHighlights.get('xds-number')!.size).toBe(1);
+ const mockStyle = document.createElement('style');
+ mockStyle.setAttribute('data-xds-highlight-styles', '');
+ document.head.appendChild(mockStyle);
- cleanupFn();
+ const cleanup = applyHighlightRangesChunked(codeEl, tokenLines);
- expect(mockHighlights.get('xds-keyword')!.size).toBe(0);
- expect(mockHighlights.get('xds-number')!.size).toBe(0);
- });
-
- it('returns no-op cleanup for empty tokens', () => {
- const el = makeCodeEl(['hello']);
- const cleanupFn = applyHighlightRanges(el, []);
-
- // No highlights created for unused types
- expect(mockHighlights.size).toBe(0);
+ const kwHighlight = mockHighlightsMap.get('xds-keyword');
+ expect(kwHighlight).toBeDefined();
+ expect(kwHighlight!.size).toBe(1);
- // Should not throw
- cleanupFn();
+ cleanup();
});
- it('handles tokens across empty lines', () => {
- // "if (x)\n\n return y;"
- const el = makeCodeEl(['if (x)', '', ' return y;']);
- const tokens = [
- {type: 'keyword', start: 0, end: 2},
- {type: 'keyword', start: 10, end: 16},
+ it('returns cleanup that removes all ranges', () => {
+ const codeEl = createCodeElement(['const x = 1;']);
+ const tokenLines: TokenLine[] = [
+ [
+ {type: 'keyword', start: 0, end: 5},
+ {type: 'number', start: 10, end: 11},
+ ],
];
- const cleanupFn = applyHighlightRanges(el, tokens);
- expect(mockHighlights.get('xds-keyword')!.size).toBe(2);
- cleanupFn();
- });
+ const mockStyle = document.createElement('style');
+ mockStyle.setAttribute('data-xds-highlight-styles', '');
+ document.head.appendChild(mockStyle);
+
+ const cleanup = applyHighlightRangesChunked(codeEl, tokenLines);
- it('registers highlights for arbitrary token types', () => {
- const el = makeCodeEl(['hello']);
- const tokens = [{type: 'made_up_type', start: 0, end: 5}];
+ const kwHighlight = mockHighlightsMap.get('xds-keyword');
+ const numHighlight = mockHighlightsMap.get('xds-number');
+ expect(kwHighlight!.size).toBe(1);
+ expect(numHighlight!.size).toBe(1);
- const cleanupFn = applyHighlightRanges(el, tokens);
- expect(mockHighlights.has('xds-made_up_type')).toBe(true);
- expect(mockHighlights.get('xds-made_up_type')!.size).toBe(1);
- cleanupFn();
- expect(mockHighlights.get('xds-made_up_type')!.size).toBe(0);
+ cleanup();
+ expect(kwHighlight!.size).toBe(0);
+ expect(numHighlight!.size).toBe(0);
});
});
diff --git a/packages/core/src/CodeBlock/highlightRanges.ts b/packages/core/src/CodeBlock/highlightRanges.ts
index 0196edbb33..68a1984dfa 100644
--- a/packages/core/src/CodeBlock/highlightRanges.ts
+++ b/packages/core/src/CodeBlock/highlightRanges.ts
@@ -1,110 +1,32 @@
/**
* @file highlightRanges.ts
- * @input Code element, tokens array, CSS Custom Highlight API
+ * @input Line divs, per-line token arrays, CSS Custom Highlight API
* @output Creates/removes highlight Range objects for syntax coloring
* @position Shared utility consumed by XDSCodeBlock (ranges mode)
- */
-
-import type {Token} from './tokenizer';
-import {ensureHighlightStyles} from './highlightStyles';
-
-// ---------------------------------------------------------------------------
-// Text node mapping
-// ---------------------------------------------------------------------------
-
-interface TextNodeEntry {
- node: Text;
- start: number;
-}
-
-/**
- * Walk a code element's text nodes and build a sorted map of
- * character offsets. Each entry maps a Text node to its starting
- * offset in the original code string.
*
- * Zero-width spaces (empty-line placeholders) count as 1 character
- * to stay aligned with the tokenizer's newline-separated offsets.
+ * Tokens are per-line with line-relative offsets, so we map directly
+ * from line div → text node → Range. No global text-node map, no
+ * binary search, no TreeWalker.
*/
-export function buildTextNodeMap(codeEl: HTMLElement): TextNodeEntry[] {
- const walker = document.createTreeWalker(codeEl, NodeFilter.SHOW_TEXT);
- const textNodes: TextNodeEntry[] = [];
- let charOffset = 0;
-
- let currentNode = walker.nextNode();
- while (currentNode) {
- const text = currentNode as Text;
- const content = text.textContent ?? '';
- if (content === '\u200b') {
- charOffset += 1;
- } else {
- textNodes.push({node: text, start: charOffset});
- charOffset += content.length + 1;
- }
- currentNode = walker.nextNode();
- }
- return textNodes;
-}
-
-// ---------------------------------------------------------------------------
-// Binary search
-// ---------------------------------------------------------------------------
-/**
- * Binary search for the Text node containing a character offset.
- * Returns the node and the local offset within that node, or null
- * if the offset falls outside any mapped node.
- */
-function findPosition(
- textNodes: TextNodeEntry[],
- offset: number,
-): {node: Text; offset: number} | null {
- let lo = 0;
- let hi = textNodes.length - 1;
-
- while (lo <= hi) {
- const mid = (lo + hi) >>> 1;
- const entry = textNodes[mid];
- if (offset < entry.start) {
- hi = mid - 1;
- } else if (
- mid + 1 < textNodes.length &&
- offset >= textNodes[mid + 1].start
- ) {
- lo = mid + 1;
- } else {
- const localOffset = offset - entry.start;
- if (localOffset <= (entry.node.textContent?.length ?? 0)) {
- return {node: entry.node, offset: localOffset};
- }
- return null;
- }
- }
- return null;
-}
+import type {Token, TokenLine} from './tokenizer';
+import {ensureHighlightStyles} from './highlightStyles';
// ---------------------------------------------------------------------------
// Dynamic ::highlight() style injection
// ---------------------------------------------------------------------------
-/**
- * Track which token types already have a ::highlight() CSS rule.
- * Known types are injected statically by ensureHighlightStyles();
- * unknown types (e.g. from a Shiki adapter) get rules injected lazily.
- */
const registeredHighlightTypes = new Set<string>();
let dynamicStyleSheet: CSSStyleSheet | null = null;
/**
* Ensure a ::highlight(xds-{type}) CSS rule exists for the given token type.
- * For the built-in types this is a no-op (static sheet covers them).
- * For unknown types, injects a rule that maps to a --color-syntax-{type}
- * custom property, falling back to currentColor.
+ * Static styles cover the built-in types; only injects for unknown ones.
*/
function ensureHighlightType(tokenType: string): void {
if (registeredHighlightTypes.has(tokenType)) return;
registeredHighlightTypes.add(tokenType);
- // Static styles cover the built-in types; only inject for unknown ones
ensureHighlightStyles();
if (typeof document === 'undefined') return;
@@ -118,159 +40,104 @@ function ensureHighlightType(tokenType: string): void {
const name = `xds-${tokenType}`;
const colorVar = `var(--color-syntax-${tokenType}, currentColor)`;
dynamicStyleSheet.insertRule(
- `.xds-codeblock ::highlight(${name}), .xds-codeeditor ::highlight(${name}) { color: ${colorVar}; }`,
+ `.xds-codeblock code::highlight(${name}), .xds-codeeditor code::highlight(${name}) { color: ${colorVar}; }`,
);
}
// ---------------------------------------------------------------------------
-// Range application
+// Per-type Highlight cache
// ---------------------------------------------------------------------------
-/**
- * Apply CSS Custom Highlight API ranges to a code element.
- *
- * Derives token types from the tokens themselves (not a hardcoded list),
- * so custom tokenizers (e.g. Shiki adapters) can produce arbitrary
- * scope names and they'll be registered automatically.
- *
- * Groups tokens by type, resolves each token's character offsets to
- * DOM Range objects via binary search over the text node map, and
- * registers them with the global CSS.highlights registry.
- *
- * Returns a cleanup function that removes all created ranges.
- */
-/**
- * Tokens per chunk when applying ranges progressively.
- * Smaller = more responsive, larger = fewer frames to full color.
- */
-const RANGE_CHUNK_SIZE = 200;
+function getOrCreateHighlight(tokenType: string): Highlight {
+ ensureHighlightType(tokenType);
+ const name = `xds-${tokenType}`;
+ let highlight = CSS.highlights.get(name);
+ if (!highlight) {
+ highlight = new Highlight();
+ CSS.highlights.set(name, highlight);
+ }
+ return highlight;
+}
+
+// ---------------------------------------------------------------------------
+// Range application — line-based
+// ---------------------------------------------------------------------------
+
+interface RangeEntry {
+ range: Range;
+ highlight: Highlight;
+}
/**
- * Resolve a flat list of tokens into Highlight entries, returning
- * the ranges and their associated Highlight objects for cleanup.
+ * Apply highlight ranges for a single line's tokens.
+ * The line div is expected to contain a single text node as its
+ * first child (or a zero-width space placeholder for empty lines).
*/
-function resolveTokenRanges(
+function applyLineRanges(
+ lineDiv: Element,
tokens: Token[],
- textNodes: TextNodeEntry[],
-): Array<{range: Range; highlight: Highlight}> {
- // 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]);
- }
- }
+ results: RangeEntry[],
+): void {
+ if (tokens.length === 0) return;
- const results: Array<{range: Range; highlight: Highlight}> = [];
+ // The text node is the first child of the line div.
+ // In range mode, lines render plain text so this is always a Text node.
+ const textNode = lineDiv.firstChild;
+ if (!textNode || textNode.nodeType !== Node.TEXT_NODE) return;
- for (const [tokenType, typedTokens] of tokensByType) {
- ensureHighlightType(tokenType);
+ const textLength = (textNode as Text).length;
- const name = `xds-${tokenType}`;
- let highlight = CSS.highlights.get(name);
- if (!highlight) {
- highlight = new Highlight();
- CSS.highlights.set(name, highlight);
- }
+ for (const token of tokens) {
+ if (token.start >= textLength || token.end <= 0) continue;
- for (const token of typedTokens) {
- const startPos = findPosition(textNodes, token.start);
- const endPos = findPosition(textNodes, 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);
- results.push({range, highlight});
- } catch {
- // Skip invalid ranges (detached nodes, out-of-bounds offsets)
- }
+ const start = Math.min(token.start, textLength);
+ const end = Math.min(token.end, textLength);
+
+ const highlight = getOrCreateHighlight(token.type);
+
+ try {
+ const range = new Range();
+ range.setStart(textNode, start);
+ range.setEnd(textNode, end);
+ highlight.add(range);
+ results.push({range, highlight});
+ } catch {
+ // Skip invalid ranges
}
}
-
- return results;
}
-function cleanupRanges(
- ranges: Array<{range: Range; highlight: Highlight}>,
-): void {
+function cleanupRanges(ranges: RangeEntry[]): void {
for (const {range, highlight} of ranges) {
highlight.delete(range);
}
}
-/**
- * Apply CSS Custom Highlight API ranges synchronously.
- * Best for small token sets (< RANGE_CHUNK_SIZE).
- * Returns a cleanup function that removes all created ranges.
- */
-export function applyHighlightRanges(
- codeEl: HTMLElement,
- tokens: Token[],
-): () => void {
- const textNodes = buildTextNodeMap(codeEl);
- const myRanges = resolveTokenRanges(tokens, textNodes);
+// ---------------------------------------------------------------------------
+// Chunked application
+// ---------------------------------------------------------------------------
- return function cleanup() {
- cleanupRanges(myRanges);
- };
-}
+const LINE_CHUNK_SIZE = 50;
/**
- * Apply CSS Custom Highlight API ranges in chunks, yielding to the
- * browser between batches via requestAnimationFrame. Colors appear
- * progressively over a few frames instead of blocking the main thread.
+ * Apply CSS Custom Highlight API ranges for all lines. Processes
+ * lines in chunks via requestAnimationFrame so colors appear
+ * progressively without blocking the main thread.
*
- * Returns a cleanup function that cancels pending work and removes
- * all ranges applied so far.
+ * @param codeEl - The <code> element containing line divs
+ * @param tokenLines - Per-line token arrays from the tokenizer
+ * @returns Cleanup function that cancels pending work and removes ranges
*/
export function applyHighlightRangesChunked(
codeEl: HTMLElement,
- tokens: Token[],
- chunkSize: number = RANGE_CHUNK_SIZE,
+ tokenLines: TokenLine[],
+ chunkSize: number = LINE_CHUNK_SIZE,
): () => void {
- // For small token sets, apply synchronously — no chunking overhead
- if (tokens.length <= chunkSize) {
- return applyHighlightRanges(codeEl, tokens);
- }
-
- const textNodes = buildTextNodeMap(codeEl);
-
- // Pre-group tokens by type and resolve highlights once
- const tokensByType = new Map<
- string,
- {tokens: Token[]; highlight: Highlight}
- >();
- for (const token of tokens) {
- let entry = tokensByType.get(token.type);
- if (!entry) {
- ensureHighlightType(token.type);
- const name = `xds-${token.type}`;
- let highlight = CSS.highlights.get(name);
- if (!highlight) {
- highlight = new Highlight();
- CSS.highlights.set(name, highlight);
- }
- entry = {tokens: [], highlight};
- tokensByType.set(token.type, entry);
- }
- entry.tokens.push(token);
- }
-
- // Flatten to a single ordered list for chunked iteration
- const allEntries: Array<{token: Token; highlight: Highlight}> = [];
- for (const {tokens: typedTokens, highlight} of tokensByType.values()) {
- for (const token of typedTokens) {
- allEntries.push({token, highlight});
- }
- }
+ ensureHighlightStyles();
- const myRanges: Array<{range: Range; highlight: Highlight}> = [];
+ // Collect all line divs with data-line attribute
+ const lineDivs = codeEl.querySelectorAll('[data-line]');
+ const myRanges: RangeEntry[] = [];
let cursor = 0;
let rafId = 0;
let cancelled = false;
@@ -278,31 +145,22 @@ export function applyHighlightRangesChunked(
function processChunk() {
if (cancelled) return;
- const end = Math.min(cursor + chunkSize, allEntries.length);
+ const end = Math.min(cursor + chunkSize, lineDivs.length);
for (let i = cursor; i < end; i++) {
- const {token, highlight} = allEntries[i];
- const startPos = findPosition(textNodes, token.start);
- const endPos = findPosition(textNodes, 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, highlight});
- } catch {
- // Skip invalid ranges
+ const lineDiv = lineDivs[i];
+ const tokens = tokenLines[i];
+ if (tokens && tokens.length > 0) {
+ applyLineRanges(lineDiv, tokens, myRanges);
}
}
cursor = end;
- if (cursor < allEntries.length) {
+ if (cursor < lineDivs.length) {
rafId = requestAnimationFrame(processChunk);
}
}
- // Start first chunk synchronously for immediate partial coloring
+ // First chunk synchronously for immediate partial coloring
processChunk();
return function cleanup() {
@@ -311,3 +169,37 @@ export function applyHighlightRangesChunked(
cleanupRanges(myRanges);
};
}
+
+/**
+ * Apply highlight ranges for a batch of lines starting at a given
+ * line index. Used by the streaming tokenizer to apply highlights
+ * progressively as tokens arrive.
+ */
+export function applyHighlightRangesBatch(
+ codeEl: HTMLElement,
+ tokenLines: TokenLine[],
+ startLine: number,
+): RangeEntry[] {
+ ensureHighlightStyles();
+
+ const lineDivs = codeEl.querySelectorAll('[data-line]');
+ const results: RangeEntry[] = [];
+
+ for (let i = 0; i < tokenLines.length; i++) {
+ const divIndex = startLine + i;
+ if (divIndex >= lineDivs.length) break;
+
+ const lineDiv = lineDivs[divIndex];
+ const tokens = tokenLines[i];
+ if (tokens && tokens.length > 0) {
+ applyLineRanges(lineDiv, tokens, results);
+ }
+ }
+
+ return results;
+}
+
+/**
+ * Cleanup a batch of ranges (returned from applyHighlightRangesBatch).
+ */
+export {cleanupRanges};
diff --git a/packages/core/src/CodeBlock/highlightStyles.ts b/packages/core/src/CodeBlock/highlightStyles.ts
index c27893e717..1024cebb37 100644
--- a/packages/core/src/CodeBlock/highlightStyles.ts
+++ b/packages/core/src/CodeBlock/highlightStyles.ts
@@ -20,39 +20,40 @@ const FALLBACK_TOKENS = `:root {\n${Object.entries(syntaxTokenDefaults)
.join('\n')}\n}`;
/**
- * Scoped ::highlight() rules — constrained to .xds-codeblock and .xds-codeeditor
- * so the browser only checks highlight ranges within code components, not the
- * entire document tree. See: Fabio's perf feedback on bare ::highlight() selectors.
+ * Scoped ::highlight() rules — attached to the `code` element so the
+ * browser only checks highlight ranges within code content, not the
+ * entire document tree. Using `code::highlight()` instead of bare
+ * `::highlight()` avoids expensive style recalc on every element.
*/
const HIGHLIGHT_STYLES = `
${FALLBACK_TOKENS}
-.xds-codeblock ::highlight(xds-keyword),
-.xds-codeeditor ::highlight(xds-keyword) { color: var(--color-syntax-keyword); }
-.xds-codeblock ::highlight(xds-string),
-.xds-codeeditor ::highlight(xds-string) { color: var(--color-syntax-string); }
-.xds-codeblock ::highlight(xds-comment),
-.xds-codeeditor ::highlight(xds-comment) { color: var(--color-syntax-comment); }
-.xds-codeblock ::highlight(xds-number),
-.xds-codeeditor ::highlight(xds-number) { color: var(--color-syntax-number); }
-.xds-codeblock ::highlight(xds-function),
-.xds-codeeditor ::highlight(xds-function) { color: var(--color-syntax-function); }
-.xds-codeblock ::highlight(xds-type),
-.xds-codeeditor ::highlight(xds-type) { color: var(--color-syntax-type); }
-.xds-codeblock ::highlight(xds-tag),
-.xds-codeeditor ::highlight(xds-tag) { color: var(--color-syntax-tag); }
-.xds-codeblock ::highlight(xds-attribute),
-.xds-codeeditor ::highlight(xds-attribute) { color: var(--color-syntax-attribute); }
-.xds-codeblock ::highlight(xds-property),
-.xds-codeeditor ::highlight(xds-property) { color: var(--color-syntax-property); }
-.xds-codeblock ::highlight(xds-operator),
-.xds-codeeditor ::highlight(xds-operator) { color: var(--color-syntax-operator); }
-.xds-codeblock ::highlight(xds-constant),
-.xds-codeeditor ::highlight(xds-constant) { color: var(--color-syntax-constant); }
-.xds-codeblock ::highlight(xds-punctuation),
-.xds-codeeditor ::highlight(xds-punctuation) { color: var(--color-syntax-punctuation); }
-.xds-codeblock ::highlight(xds-variable),
-.xds-codeeditor ::highlight(xds-variable) { color: var(--color-syntax-variable); }
+.xds-codeblock code::highlight(xds-keyword),
+.xds-codeeditor code::highlight(xds-keyword) { color: var(--color-syntax-keyword); }
+.xds-codeblock code::highlight(xds-string),
+.xds-codeeditor code::highlight(xds-string) { color: var(--color-syntax-string); }
+.xds-codeblock code::highlight(xds-comment),
+.xds-codeeditor code::highlight(xds-comment) { color: var(--color-syntax-comment); }
+.xds-codeblock code::highlight(xds-number),
+.xds-codeeditor code::highlight(xds-number) { color: var(--color-syntax-number); }
+.xds-codeblock code::highlight(xds-function),
+.xds-codeeditor code::highlight(xds-function) { color: var(--color-syntax-function); }
+.xds-codeblock code::highlight(xds-type),
+.xds-codeeditor code::highlight(xds-type) { color: var(--color-syntax-type); }
+.xds-codeblock code::highlight(xds-tag),
+.xds-codeeditor code::highlight(xds-tag) { color: var(--color-syntax-tag); }
+.xds-codeblock code::highlight(xds-attribute),
+.xds-codeeditor code::highlight(xds-attribute) { color: var(--color-syntax-attribute); }
+.xds-codeblock code::highlight(xds-property),
+.xds-codeeditor code::highlight(xds-property) { color: var(--color-syntax-property); }
+.xds-codeblock code::highlight(xds-operator),
+.xds-codeeditor code::highlight(xds-operator) { color: var(--color-syntax-operator); }
+.xds-codeblock code::highlight(xds-constant),
+.xds-codeeditor code::highlight(xds-constant) { color: var(--color-syntax-constant); }
+.xds-codeblock code::highlight(xds-punctuation),
+.xds-codeeditor code::highlight(xds-punctuation) { color: var(--color-syntax-punctuation); }
+.xds-codeblock code::highlight(xds-variable),
+.xds-codeeditor code::highlight(xds-variable) { color: var(--color-syntax-variable); }
/* Span-based fallback classes — used when highlightMode='spans' or
when the CSS Custom Highlight API is not available. */
diff --git a/packages/core/src/CodeBlock/index.ts b/packages/core/src/CodeBlock/index.ts
index 94d9332176..16322b2bdb 100644
--- a/packages/core/src/CodeBlock/index.ts
+++ b/packages/core/src/CodeBlock/index.ts
@@ -1,18 +1,17 @@
-'use client';
-
-/**
- * @file index.ts
- * @output Exports CodeBlock and Code components, tokenizer, and types
- * @position Component entry point; re-exported by /packages/core/src/index.ts
- */
-
export {XDSCodeBlock} from './XDSCodeBlock';
export type {XDSCodeBlockProps} from './XDSCodeBlock';
export {XDSCode} from './XDSCode';
export type {XDSCodeProps} from './XDSCode';
-export {tokenize, tokenizeAsync, SYNC_TOKENIZE_THRESHOLD} from './tokenizer';
-export type {Token} from './tokenizer';
+export {
+ tokenize,
+ tokenizeAsync,
+ tokenizeStreaming,
+ flatTokensToLines,
+ SYNC_TOKENIZE_THRESHOLD,
+} from './tokenizer';
+export type {Token, TokenLine} from './tokenizer';
+export {applyHighlightRangesChunked, applyHighlightRangesBatch, cleanupRanges} from './highlightRanges';
export {ensureHighlightStyles, TOKEN_TYPES} from './highlightStyles';
diff --git a/packages/core/src/CodeBlock/tokenizer.test.ts b/packages/core/src/CodeBlock/tokenizer.test.ts
index 377e1dd7c9..5c5f10ad6c 100644
--- a/packages/core/src/CodeBlock/tokenizer.test.ts
+++ b/packages/core/src/CodeBlock/tokenizer.test.ts
@@ -1,323 +1,159 @@
import {describe, it, expect} from 'vitest';
-import {tokenize, tokenizeAsync, SYNC_TOKENIZE_THRESHOLD} 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'});
- });
+import {tokenize, tokenizeAsync, tokenizeStreaming, flatTokensToLines} from './tokenizer';
+import type {TokenLine} from './tokenizer';
- it('tokenizes types (PascalCase)', () => {
- const tokens = tokenTypes('const x: MyType = {};', 'typescript');
- expect(tokens).toContainEqual({type: 'type', text: 'MyType'});
- });
+describe('tokenize', () => {
+ it('returns per-line tokens with line-relative offsets', () => {
+ const code = 'const x = 1;\nlet y = 2;';
+ const result = tokenize(code, 'typescript');
- 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');
- });
+ expect(result.length).toBe(2);
- 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'"});
- });
+ // Line 0: "const x = 1;"
+ const line0 = result[0];
+ const constToken = line0.find(t => t.type === 'keyword');
+ expect(constToken).toEqual({type: 'keyword', start: 0, end: 5});
- 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'});
- });
+ const numToken = line0.find(t => t.type === 'number');
+ expect(numToken).toEqual({type: 'number', start: 10, end: 11});
- 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);
- });
+ // Line 1: "let y = 2;"
+ const line1 = result[1];
+ const letToken = line1.find(t => t.type === 'keyword');
+ expect(letToken).toEqual({type: 'keyword', start: 0, end: 3});
});
- 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('omits default-type tokens (variable for JS)', () => {
+ const code = 'const foo = bar;';
+ const result = tokenize(code, 'typescript');
- 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');
- });
+ const line = result[0];
+ // "foo" would match as function (followed by no parens) then variable
+ // "bar" would match as variable — should be omitted
+ const variableTokens = line.filter(t => t.type === 'variable');
+ expect(variableTokens).toEqual([]);
});
- describe('python', () => {
- it('tokenizes keywords', () => {
- const tokens = tokenTypes('def hello():', 'python');
- expect(tokens).toContainEqual({type: 'keyword', text: 'def'});
- });
+ it('returns empty array for unknown languages', () => {
+ expect(tokenize('hello', 'unknown')).toEqual([]);
+ });
- it('tokenizes comments', () => {
- const tokens = tokenTypes('# this is a comment', 'python');
- expect(tokens).toContainEqual({
- type: 'comment',
- text: '# this is a comment',
- });
- });
+ it('tokenizes JSON correctly', () => {
+ const code = '{"key": "value", "num": 42}';
+ const result = tokenize(code, 'json');
- it('tokenizes decorators', () => {
- const tokens = tokenTypes('@dataclass', 'python');
- expect(tokens).toContainEqual({type: 'constant', text: '@dataclass'});
- });
+ expect(result.length).toBe(1);
+ const line = result[0];
- it('tokenizes triple-quote strings', () => {
- const tokens = tokenTypes('"""docstring"""', 'python');
- expect(tokens).toContainEqual({type: 'string', text: '"""docstring"""'});
- });
+ const prop = line.find(t => t.type === 'property');
+ expect(prop).toBeDefined();
+ expect(code.slice(prop!.start, prop!.end)).toBe('"key"');
- it('tokenizes f-strings', () => {
- const tokens = tokenTypes('f"hello {name}"', 'python');
- expect(tokens).toContainEqual({type: 'string', text: 'f"hello {name}"'});
- });
+ const str = line.find(t => t.type === 'string');
+ expect(str).toBeDefined();
- 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');
- });
+ const num = line.find(t => t.type === 'number');
+ expect(num).toBeDefined();
+ expect(code.slice(num!.start, num!.end)).toBe('42');
});
- 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('handles empty lines', () => {
+ const code = 'const a = 1;\n\nconst b = 2;';
+ const result = tokenize(code, 'typescript');
- it('tokenizes comments', () => {
- const tokens = tokenTypes('<!-- comment -->', 'html');
- expect(tokens).toContainEqual({
- type: 'comment',
- text: '<!-- comment -->',
- });
- });
+ expect(result.length).toBe(3);
+ expect(result[1]).toEqual([]); // empty line
});
- describe('css', () => {
- it('tokenizes properties', () => {
- const tokens = tokenTypes('display: flex;', 'css');
- expect(tokens).toContainEqual({type: 'property', text: 'display'});
- });
+ it('handles multi-line strings in Python', () => {
+ const code = 'x = """hello\nworld"""';
+ const result = tokenize(code, 'python');
+ // The multi-line string spans lines, but our line tokenizer works per-line
+ // so the first line gets the start of the string
+ expect(result.length).toBeGreaterThanOrEqual(1);
+ });
- it('tokenizes selectors', () => {
- const tokens = tokenTypes('.button { }', 'css');
- expect(tokens).toContainEqual({type: 'tag', text: '.button'});
- });
+ it('tokenizes CSS properties', () => {
+ const code = 'color: red;';
+ const result = tokenize(code, 'css');
- it('tokenizes custom properties', () => {
- const tokens = tokenTypes('--color-primary: blue;', 'css');
- expect(tokens).toContainEqual({
- type: 'variable',
- text: '--color-primary',
- });
- });
+ expect(result.length).toBe(1);
+ const line = result[0];
+ const prop = line.find(t => t.type === 'property');
+ expect(prop).toBeDefined();
+ });
- it('tokenizes numbers with units', () => {
- const tokens = tokenTypes('padding: 8px;', 'css');
- expect(tokens).toContainEqual({type: 'number', text: '8px'});
- });
+ it('handles trailing newline', () => {
+ const code = 'const x = 1;\n';
+ const result = tokenize(code, 'typescript');
+ // Should handle trailing newline (produces an empty last line)
+ expect(result.length).toBeGreaterThanOrEqual(1);
+ });
+});
- it('tokenizes hex colors', () => {
- const tokens = tokenTypes('color: #0064E0;', 'css');
- expect(tokens).toContainEqual({type: 'constant', text: '#0064E0'});
- });
+describe('tokenizeAsync', () => {
+ it('returns same result as sync tokenize', async () => {
+ const code = 'const x = 1;\nlet y = "hello";';
+ const sync = tokenize(code, 'typescript');
+ const async_ = await tokenizeAsync(code, 'typescript');
- it('tokenizes functions', () => {
- const tokens = tokenTypes('color: var(--x);', 'css');
- expect(tokens).toContainEqual({type: 'function', text: 'var'});
- });
+ expect(async_).toEqual(sync);
});
- 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('respects abort signal', async () => {
+ const code = 'const x = 1;'.repeat(100);
+ const controller = new AbortController();
+ controller.abort();
- it('tokenizes strings', () => {
- const tokens = tokenTypes('echo "hello"', 'bash');
- expect(tokens).toContainEqual({type: 'string', text: '"hello"'});
- });
+ const result = await tokenizeAsync(code, 'typescript', controller.signal);
+ // Should return partial/empty result
+ expect(result.length).toBeLessThanOrEqual(tokenize(code, 'typescript').length);
});
+});
- describe('edge cases', () => {
- it('returns empty for unknown language', () => {
- expect(tokenize('const x = 1;', 'brainfuck')).toEqual([]);
- });
+describe('tokenizeStreaming', () => {
+ it('calls onBatch with progressive results', async () => {
+ const lines = Array.from({length: 50}, (_, i) => `const x${i} = ${i};`);
+ const code = lines.join('\n');
+ const batches: Array<{lines: TokenLine[]; startLine: number}> = [];
- it('returns empty for plaintext', () => {
- expect(tokenize('hello world', 'plaintext')).toEqual([]);
+ await tokenizeStreaming(code, 'typescript', (batchLines, startLine) => {
+ batches.push({lines: batchLines, startLine});
});
- it('handles empty string', () => {
- expect(tokenize('', 'typescript')).toEqual([]);
- });
+ expect(batches.length).toBeGreaterThanOrEqual(1);
- 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();
- }
- });
+ // All lines should be covered
+ const totalLines = batches.reduce((sum, b) => sum + b.lines.length, 0);
+ expect(totalLines).toBe(50);
- 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);
- }
- });
+ // Start lines should be monotonically increasing
+ for (let i = 1; i < batches.length; i++) {
+ expect(batches[i].startLine).toBeGreaterThan(batches[i - 1].startLine);
+ }
});
+});
- describe('tokenizeAsync', () => {
- it('produces same results as sync tokenize for small code', async () => {
- const code = 'const x = 42;\nreturn "hello";';
- const syncTokens = tokenize(code, 'typescript');
- const asyncTokens = await tokenizeAsync(code, 'typescript');
- expect(asyncTokens).toEqual(syncTokens);
- });
+describe('flatTokensToLines', () => {
+ it('converts absolute offsets to line-relative', () => {
+ const code = 'const x = 1;\nlet y = 2;';
+ const flatTokens = [
+ {type: 'keyword', start: 0, end: 5}, // "const" in line 0
+ {type: 'number', start: 10, end: 11}, // "1" in line 0
+ {type: 'keyword', start: 13, end: 16}, // "let" in line 1
+ {type: 'number', start: 21, end: 22}, // "2" in line 1
+ ];
- it('produces same results for larger code', async () => {
- // Generate code larger than SYNC_TOKENIZE_THRESHOLD
- const line = 'const x = 42; // comment\n';
- const code = line.repeat(
- Math.ceil(SYNC_TOKENIZE_THRESHOLD / line.length) + 10,
- );
- const syncTokens = tokenize(code, 'typescript');
- const asyncTokens = await tokenizeAsync(code, 'typescript');
- expect(asyncTokens).toEqual(syncTokens);
- });
+ const result = flatTokensToLines(flatTokens, code);
- it('returns empty for unknown language', async () => {
- const tokens = await tokenizeAsync('const x = 1;', 'brainfuck');
- expect(tokens).toEqual([]);
- });
+ expect(result.length).toBe(2);
- it('respects abort signal', async () => {
- const controller = new AbortController();
- controller.abort();
- const tokens = await tokenizeAsync(
- 'const x = 42;',
- 'typescript',
- controller.signal,
- );
- // Aborted before processing — tokens may be empty or partial
- expect(Array.isArray(tokens)).toBe(true);
- });
+ // Line 0 tokens should have offsets relative to line start (0)
+ expect(result[0]).toContainEqual({type: 'keyword', start: 0, end: 5});
+ expect(result[0]).toContainEqual({type: 'number', start: 10, end: 11});
- it('exports SYNC_TOKENIZE_THRESHOLD as a number', () => {
- expect(typeof SYNC_TOKENIZE_THRESHOLD).toBe('number');
- expect(SYNC_TOKENIZE_THRESHOLD).toBe(2000);
- });
+ // Line 1 tokens should have offsets relative to line start (13)
+ expect(result[1]).toContainEqual({type: 'keyword', start: 0, end: 3});
+ expect(result[1]).toContainEqual({type: 'number', start: 8, end: 9});
});
});
diff --git a/packages/core/src/CodeBlock/tokenizer.ts b/packages/core/src/CodeBlock/tokenizer.ts
index a24188f232..e07d8a65a3 100644
--- a/packages/core/src/CodeBlock/tokenizer.ts
+++ b/packages/core/src/CodeBlock/tokenizer.ts
@@ -1,12 +1,12 @@
/**
* @file tokenizer.ts
* @input Code string and language identifier
- * @output Array of tokens with type, start, and end positions
+ * @output Array of per-line token arrays with line-relative offsets
* @position Shared utility; consumed by XDSCodeBlock and XDSCodeEditor
*
* SYNC: When modified, update:
- * - /packages/lab/src/CodeBlock/XDSCodeBlock.tsx
- * - /packages/lab/src/CodeEditor/XDSCodeEditor.tsx
+ * - /packages/core/src/CodeBlock/XDSCodeBlock.tsx
+ * - /packages/core/src/CodeBlock/highlightRanges.ts
*/
/**
@@ -17,12 +17,20 @@ declare const scheduler: {yield?: () => Promise<void>} | undefined;
export type Token = {type: string; start: number; end: number};
+/**
+ * Per-line token structure. Each line stores its own tokens with
+ * line-relative start/end offsets (0 = start of line).
+ */
+export type TokenLine = Token[];
+
// ---------------------------------------------------------------------------
// Language definitions
// ---------------------------------------------------------------------------
type LangDef = {
patterns: Array<{type: string; regex: RegExp; anchored: RegExp}>;
+ /** Token type that matches the element's default text color (skipped in output). */
+ defaultType: string;
};
/** Cache compiled language definitions to avoid re-creating regexes. */
@@ -58,9 +66,8 @@ function buildLanguageUncached(lang: string): LangDef | null {
const raw = buildLanguagePatterns(lang);
if (!raw) return null;
return {
+ defaultType: raw.defaultType,
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)};
}),
@@ -69,7 +76,7 @@ function buildLanguageUncached(lang: string): LangDef | null {
function buildLanguagePatterns(
lang: string,
-): {patterns: Array<{type: string; regex: RegExp}>} | null {
+): {patterns: Array<{type: string; regex: RegExp}>; defaultType: string} | null {
switch (lang) {
case 'typescript':
case 'javascript':
@@ -78,6 +85,7 @@ function buildLanguagePatterns(
case 'ts':
case 'js':
return {
+ defaultType: 'variable',
patterns: [
{type: 'comment', regex: /\/\*[\s\S]*?\*\//},
{type: 'comment', regex: /\/\/[^\n]*/},
@@ -101,6 +109,7 @@ function buildLanguagePatterns(
case 'json':
return {
+ defaultType: 'punctuation',
patterns: [
{type: 'property', regex: /"(?:[^"\\]|\\.)*"(?=\s*:)/},
{type: 'string', regex: /"(?:[^"\\]|\\.)*"/},
@@ -115,6 +124,7 @@ function buildLanguagePatterns(
case 'xml':
case 'svg':
return {
+ defaultType: 'variable',
patterns: [
{type: 'comment', regex: /<!--[\s\S]*?-->/},
{type: 'keyword', regex: /<!DOCTYPE[^>]*>/i},
@@ -132,6 +142,7 @@ function buildLanguagePatterns(
case 'scss':
case 'less':
return {
+ defaultType: 'variable',
patterns: [
{type: 'comment', regex: /\/\*[\s\S]*?\*\//},
{type: 'comment', regex: /\/\/[^\n]*/},
@@ -159,6 +170,7 @@ function buildLanguagePatterns(
case 'python':
case 'py':
return {
+ defaultType: 'variable',
patterns: [
{type: 'string', regex: /"""[\s\S]*?"""/},
{type: 'string', regex: /'''[\s\S]*?'''/},
@@ -187,6 +199,7 @@ function buildLanguagePatterns(
case 'zsh':
case 'shell':
return {
+ defaultType: 'variable',
patterns: [
{type: 'comment', regex: /#[^\n]*/},
{type: 'string', regex: /"(?:[^"\\]|\\.)*"/},
@@ -205,6 +218,7 @@ function buildLanguagePatterns(
case 'php':
return {
+ defaultType: 'variable',
patterns: [
{type: 'comment', regex: /\/\*[\s\S]*?\*\//},
{type: 'comment', regex: /\/\/[^\n]*/},
@@ -226,6 +240,7 @@ function buildLanguagePatterns(
case 'hack':
return {
+ defaultType: 'variable',
patterns: [
{type: 'comment', regex: /\/\*[\s\S]*?\*\//},
{type: 'comment', regex: /\/\/[^\n]*/},
@@ -248,6 +263,7 @@ function buildLanguagePatterns(
case 'yaml':
case 'yml':
return {
+ defaultType: 'variable',
patterns: [
{type: 'comment', regex: /#[^\n]*/},
{type: 'string', regex: /"(?:[^"\\]|\\.)*"/},
@@ -269,6 +285,7 @@ function buildLanguagePatterns(
case 'markdown':
case 'md':
return {
+ defaultType: 'variable',
patterns: [
{type: 'keyword', regex: /^```[\w]*$/m},
{type: 'keyword', regex: /^#{1,6}\s+.*/m},
@@ -297,7 +314,7 @@ function buildLanguagePatterns(
export const SYNC_TOKENIZE_THRESHOLD = 2000;
/** Characters to process per chunk in async tokenization. */
-const ASYNC_CHUNK_SIZE = 5000;
+const ASYNC_CHUNK_SIZE = 800;
/**
* Yield to the main thread. Uses `scheduler.yield()` when available,
@@ -314,19 +331,19 @@ function yieldToMain(): Promise<void> {
}
/**
- * Internal tokenization loop. Processes from `startPos` up to `endPos`
- * (or end of string), pushing tokens into the provided array.
- * Returns the final position.
+ * Tokenize a single line. Tokens whose type matches `defaultType`
+ * are omitted — the element's base color handles them.
+ * Returns tokens with line-relative offsets (0 = start of line).
*/
-function tokenizeRange(
+function tokenizeLine(
code: string,
langDef: LangDef,
- tokens: Token[],
- startPos: number,
- endPos: number,
-): number {
- let pos = startPos;
- const limit = Math.min(endPos, code.length);
+ lineStart: number,
+ lineEnd: number,
+): Token[] {
+ const tokens: Token[] = [];
+ let pos = lineStart;
+ const limit = Math.min(lineEnd, code.length);
while (pos < limit) {
let matched = false;
@@ -336,11 +353,13 @@ function tokenizeRange(
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,
- });
+ if (pattern.type !== langDef.defaultType) {
+ tokens.push({
+ type: pattern.type,
+ start: pos - lineStart,
+ end: pos - lineStart + match[0].length,
+ });
+ }
pos += match[0].length;
matched = true;
break;
@@ -352,67 +371,144 @@ function tokenizeRange(
}
}
- return pos;
+ return tokens;
}
/**
- * 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.
+ * Tokenizes a code string into per-line token arrays.
*
- * Best for small code strings (< 2000 chars). For large code, use
- * `tokenizeAsync()` which yields to the main thread between chunks.
+ * Each line's tokens use line-relative offsets. Tokens matching the
+ * language's default color type are omitted (~30% reduction).
*
* @param code - The source code string to tokenize
* @param language - Language identifier (e.g. 'typescript', 'python')
- * @returns Array of tokens sorted by start position
+ * @returns Array of token arrays, one per line
*/
-export function tokenize(code: string, language: string): Token[] {
+export function tokenize(code: string, language: string): TokenLine[] {
const langDef = buildLanguage(language);
if (!langDef) return [];
- const tokens: Token[] = [];
- tokenizeRange(code, langDef, tokens, 0, code.length);
- return tokens;
+ const result: TokenLine[] = [];
+ let lineStart = 0;
+
+ for (let i = 0; i <= code.length; i++) {
+ if (i === code.length || code[i] === '\n') {
+ result.push(tokenizeLine(code, langDef, lineStart, i));
+ lineStart = i + 1;
+ }
+ }
+
+ return result;
}
/**
- * Async streaming tokenizer that yields to the main thread between chunks.
- *
- * Processes ~5000 characters at a time, then yields via `scheduler.yield()`
- * (or `setTimeout`) to avoid blocking the main thread on large files.
- *
- * Supports cancellation via AbortSignal — returns tokens accumulated so far
- * if aborted (callers should discard the result).
- *
- * @param code - The source code string to tokenize
- * @param language - Language identifier (e.g. 'typescript', 'python')
- * @param signal - Optional AbortSignal for cancellation
- * @returns Promise resolving to array of tokens sorted by start position
+ * Async tokenizer that yields to the main thread between batches
+ * of lines (~800 chars per batch).
*/
export async function tokenizeAsync(
code: string,
language: string,
signal?: AbortSignal,
-): Promise<Token[]> {
+): Promise<TokenLine[]> {
const langDef = buildLanguage(language);
if (!langDef) return [];
- const tokens: Token[] = [];
- let pos = 0;
+ const result: TokenLine[] = [];
+ let lineStart = 0;
+ let charsInChunk = 0;
+
+ for (let i = 0; i <= code.length; i++) {
+ if (i === code.length || code[i] === '\n') {
+ result.push(tokenizeLine(code, langDef, lineStart, i));
+ charsInChunk += i - lineStart + 1;
+ lineStart = i + 1;
+
+ if (charsInChunk >= ASYNC_CHUNK_SIZE && i < code.length) {
+ if (signal?.aborted) return result;
+ charsInChunk = 0;
+ await yieldToMain();
+ }
+ }
+ }
+
+ return result;
+}
+
+/**
+ * Streaming tokenizer with per-batch callback. Tokenizes lines in
+ * batches and invokes `onBatch` after each so consumers can apply
+ * highlights progressively.
+ */
+export async function tokenizeStreaming(
+ code: string,
+ language: string,
+ onBatch: (lines: TokenLine[], startLine: number) => void,
+ signal?: AbortSignal,
+): Promise<void> {
+ const langDef = buildLanguage(language);
+ if (!langDef) return;
+
+ let lineStart = 0;
+ let lineIndex = 0;
+ let charsInChunk = 0;
+ let batch: TokenLine[] = [];
+ let batchStartLine = 0;
+
+ for (let i = 0; i <= code.length; i++) {
+ if (i === code.length || code[i] === '\n') {
+ batch.push(tokenizeLine(code, langDef, lineStart, i));
+ charsInChunk += i - lineStart + 1;
+ lineIndex++;
+ lineStart = i + 1;
+
+ if (charsInChunk >= ASYNC_CHUNK_SIZE && i < code.length) {
+ if (signal?.aborted) return;
+ onBatch(batch, batchStartLine);
+ batch = [];
+ batchStartLine = lineIndex;
+ charsInChunk = 0;
+ await yieldToMain();
+ }
+ }
+ }
- while (pos < code.length) {
- if (signal?.aborted) return tokens;
+ if (batch.length > 0) {
+ onBatch(batch, batchStartLine);
+ }
+}
- // Process one chunk
- pos = tokenizeRange(code, langDef, tokens, pos, pos + ASYNC_CHUNK_SIZE);
+/**
+ * Convert legacy flat tokens (absolute offsets) to per-line tokens
+ * (line-relative offsets). For backwards compatibility with custom
+ * tokenizers that return the old format.
+ */
+export function flatTokensToLines(
+ tokens: Array<{type: string; start: number; end: number}>,
+ code: string,
+): TokenLine[] {
+ const lineStarts: number[] = [0];
+ for (let i = 0; i < code.length; i++) {
+ if (code[i] === '\n') lineStarts.push(i + 1);
+ }
+
+ const result: TokenLine[] = Array.from({length: lineStarts.length}, () => []);
+ let lineIdx = 0;
- // Yield to main thread if there's more to process
- if (pos < code.length) {
- await yieldToMain();
+ for (const token of tokens) {
+ while (
+ lineIdx < lineStarts.length - 1 &&
+ token.start >= lineStarts[lineIdx + 1]
+ ) {
+ lineIdx++;
}
+
+ const lineStart = lineStarts[lineIdx];
+ result[lineIdx].push({
+ type: token.type,
+ start: token.start - lineStart,
+ end: token.end - lineStart,
+ });
}
- return tokens;
+ return result;
}
diff --git a/packages/lab/src/CodeEditor/XDSCodeEditor.tsx b/packages/lab/src/CodeEditor/XDSCodeEditor.tsx
index deddc9ff68..3d68bb9e47 100644
--- a/packages/lab/src/CodeEditor/XDSCodeEditor.tsx
+++ b/packages/lab/src/CodeEditor/XDSCodeEditor.tsx
@@ -37,8 +37,8 @@ import {
tokenizeAsync,
SYNC_TOKENIZE_THRESHOLD,
} from '@xds/core/CodeBlock';
-import type {Token} from '@xds/core/CodeBlock';
-import {ensureHighlightStyles, TOKEN_TYPES} from '@xds/core/CodeBlock';
+import type {Token, TokenLine} from '@xds/core/CodeBlock';
+import {ensureHighlightStyles, applyHighlightRangesChunked} from '@xds/core/CodeBlock';
// ---------------------------------------------------------------------------
// Styles
@@ -145,7 +145,7 @@ export interface XDSCodeEditorProps extends Omit<
tokenizer?: (
code: string,
language: string,
- ) => Array<{type: string; start: number; end: number}>;
+ ) => TokenLine[];
/**
* How to apply syntax highlighting.
* - 'css-highlight': Uses CSS Custom Highlight API (zero DOM overhead).
@@ -184,45 +184,39 @@ let editorInstanceCounter = 0;
// Span-based rendering helpers
// ---------------------------------------------------------------------------
+
/**
- * Build span-based highlighted line content from tokens.
+ * Build span-based highlighted line content from per-line tokens.
*/
function buildSpanLine(
lineText: string,
- lineStart: number,
tokens: Token[],
): React.ReactNode {
if (!lineText) return '\u200b';
-
- const lineEnd = lineStart + lineText.length;
- const lineTokens = tokens.filter(t => t.start < lineEnd && t.end > lineStart);
-
- if (lineTokens.length === 0) return lineText;
+ if (tokens.length === 0) return lineText;
const parts: React.ReactNode[] = [];
- let cursor = lineStart;
+ let cursor = 0;
- for (const token of lineTokens) {
- const tStart = Math.max(token.start, lineStart);
- const tEnd = Math.min(token.end, lineEnd);
-
- if (tStart > cursor) {
- parts.push(lineText.slice(cursor - lineStart, tStart - lineStart));
+ for (const token of tokens) {
+ if (token.start > cursor) {
+ parts.push(lineText.slice(cursor, token.start));
}
+ const end = Math.min(token.end, lineText.length);
parts.push(
<span
- key={`${tStart}-${token.type}`}
+ key={`${token.start}-${token.type}`}
className={`xds-token-${token.type}`}>
- {lineText.slice(tStart - lineStart, tEnd - lineStart)}
+ {lineText.slice(token.start, end)}
</span>,
);
- cursor = tEnd;
+ cursor = end;
}
- if (cursor < lineEnd) {
- parts.push(lineText.slice(cursor - lineStart));
+ if (cursor < lineText.length) {
+ parts.push(lineText.slice(cursor));
}
return parts.length > 0 ? parts : lineText;
@@ -231,104 +225,13 @@ function buildSpanLine(
/**
* Build span-based content for all lines.
*/
-function buildSpanContent(lines: string[], tokens: Token[]): React.ReactNode {
- return lines.map((line, i) => {
- let lineStart = 0;
- for (let j = 0; j < i; j++) {
- lineStart += lines[j].length + 1;
- }
- return (
- <div key={i}>
- {buildSpanLine(line, lineStart, tokens)}
- {i < lines.length - 1 ? '\n' : null}
- </div>
- );
- });
-}
-
-// ---------------------------------------------------------------------------
-// Shared highlight range application
-// ---------------------------------------------------------------------------
-
-function applyEditorHighlightRanges(
- el: HTMLElement,
- tokens: Token[],
-): () => void {
- 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]);
- }
- }
-
- 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);
- }
- }
- }
- };
+function buildSpanContent(lines: string[], tokenLines: TokenLine[]): React.ReactNode {
+ return lines.map((line, i) => (
+ <div key={i}>
+ {buildSpanLine(line, tokenLines[i] ?? [])}
+ {i < lines.length - 1 ? '\n' : null}
+ </div>
+ ));
}
// ---------------------------------------------------------------------------
@@ -380,7 +283,7 @@ export function XDSCodeEditor({
const useSpans = highlightModeProp === 'spans' || !hasHighlightAPI();
// Async tokens for span mode overlay
- const [asyncTokens, setAsyncTokens] = useState<Token[] | null>(null);
+ const [asyncTokens, setAsyncTokens] = useState<TokenLine[] | null>(null);
const lines = value.split('\n');
@@ -420,7 +323,7 @@ export function XDSCodeEditor({
};
}, [useSpans, value, language, customTokenizer]);
- const spanTokens = syncTokens ?? asyncTokens ?? [];
+ const spanTokens: TokenLine[] = syncTokens ?? asyncTokens ?? [];
// Ensure styles are always injected
useLayoutEffect(() => {
@@ -440,7 +343,7 @@ export function XDSCodeEditor({
const tokens = tok(value, language);
if (tokens.length === 0) return;
- return applyEditorHighlightRanges(el, tokens);
+ return applyHighlightRangesChunked(el, tokens);
}, [useSpans, value, language, customTokenizer, instanceId]);
// Apply CSS Custom Highlight API ranges — large code (async)
@@ -458,7 +361,7 @@ export function XDSCodeEditor({
tokenizeAsync(value, language, abortController.signal).then(tokens => {
if (abortController.signal.aborted) return;
if (tokens.length === 0) return;
- cleanup = applyEditorHighlightRanges(el, tokens);
+ cleanup = applyHighlightRangesChunked(el, tokens);
});
return () => {
@@ -581,7 +484,7 @@ export function XDSCodeEditor({
// is made transparent so the overlay provides the visual coloring while
// the contentEditable handles input/caret.
const spanOverlay =
- useSpans && spanTokens.length > 0 ? (
+ useSpans && spanTokens.some(line => line.length > 0) ? (
<div
aria-hidden="true"
style={{
@@ -645,7 +548,7 @@ export function XDSCodeEditor({
onCompositionEnd={handleCompositionEnd}
{...stylex.props(styles.editor, sizeStyle)}
style={
- useSpans && spanTokens.length > 0
+ useSpans && spanTokens.some(line => line.length > 0)
? {color: 'transparent', caretColor: 'inherit'}
: undefined
}