Skip to content

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

TypeScript

feat(codeeditor): perf/theme stories + remove span fallback (#1470)

Cindy Zhang0bdbcbbd2449
diff --git a/apps/storybook/stories/CodeEditorPerf.stories.tsx b/apps/storybook/stories/CodeEditorPerf.stories.tsx
new file mode 100644
index 0000000000..584532223e
--- /dev/null
+++ b/apps/storybook/stories/CodeEditorPerf.stories.tsx
@@ -0,0 +1,212 @@
+import type {Meta, StoryObj} from '@storybook/react';
+import {useState, useRef, useEffect, useCallback} from 'react';
+import {XDSCodeEditor} from '@xds/lab';
+
+const meta: Meta<typeof XDSCodeEditor> = {
+ title: 'Lab/XDSCodeEditor/Performance',
+ component: XDSCodeEditor,
+ parameters: {layout: 'fullscreen'},
+};
+
+export default meta;
+type Story = StoryObj<typeof XDSCodeEditor>;
+
+// ---------------------------------------------------------------------------
+// Helpers
+// ---------------------------------------------------------------------------
+
+function generateCode(lineCount: number): string {
+ const lines: string[] = [];
+ for (let i = 0; i < lineCount; i++) {
+ const mod = i % 6;
+ if (mod === 0) lines.push(`import {Component${i}} from './module${i}';`);
+ else if (mod === 1) lines.push(`const value${i} = ${i} + Math.random();`);
+ else if (mod === 2) lines.push(`function compute${i}(x: number): number {`);
+ else if (mod === 3)
+ lines.push(` return x * ${i} + value${Math.max(0, i - 2)};`);
+ else if (mod === 4) lines.push(`}`);
+ else lines.push(`// Line ${i + 1}: performance test`);
+ }
+ return lines.join('\n');
+}
+
+function Metric({label, value}: {label: string; value: string | number}) {
+ return (
+ <div
+ style={{
+ display: 'inline-flex',
+ gap: 4,
+ padding: '2px 8px',
+ borderRadius: 4,
+ background: '#f0f0f0',
+ fontSize: 12,
+ fontFamily: 'monospace',
+ }}>
+ <span style={{color: '#666'}}>{label}:</span>
+ <strong>{value}</strong>
+ </div>
+ );
+}
+
+// ---------------------------------------------------------------------------
+// Stress Test — single editor, configurable line count
+// ---------------------------------------------------------------------------
+
+function StressTestImpl() {
+ const [lineCount, setLineCount] = useState(500);
+ const [code, setCode] = useState(() => generateCode(500));
+ const [mountTime, setMountTime] = useState<number | null>(null);
+ const mountStart = useRef(0);
+
+ useEffect(() => {
+ mountStart.current = performance.now();
+ }, [code]);
+
+ useEffect(() => {
+ const frame = requestAnimationFrame(() => {
+ setMountTime(performance.now() - mountStart.current);
+ });
+ return () => cancelAnimationFrame(frame);
+ }, [code]);
+
+ const regenerate = useCallback((count: number) => {
+ setLineCount(count);
+ setCode(generateCode(count));
+ }, []);
+
+ return (
+ <div
+ style={{
+ padding: 16,
+ display: 'flex',
+ flexDirection: 'column',
+ gap: 12,
+ }}>
+ <div
+ style={{
+ display: 'flex',
+ gap: 8,
+ alignItems: 'center',
+ flexWrap: 'wrap',
+ }}>
+ <span style={{fontSize: 13, fontWeight: 600}}>Lines:</span>
+ {[100, 500, 1000, 2000, 5000].map(n => (
+ <button
+ key={n}
+ onClick={() => regenerate(n)}
+ style={{
+ padding: '4px 10px',
+ borderRadius: 4,
+ border: lineCount === n ? '2px solid #0066cc' : '1px solid #ccc',
+ background: lineCount === n ? '#e6f0ff' : 'white',
+ cursor: 'pointer',
+ fontSize: 12,
+ }}>
+ {n}
+ </button>
+ ))}
+ {mountTime != null && (
+ <Metric label="Mount" value={`${mountTime.toFixed(1)}ms`} />
+ )}
+ </div>
+ <XDSCodeEditor
+ value={code}
+ onChange={setCode}
+ language="typescript"
+ hasLineNumbers
+ maxHeight={600}
+ />
+ </div>
+ );
+}
+
+export const StressTest: Story = {
+ render: () => <StressTestImpl />,
+};
+
+// ---------------------------------------------------------------------------
+// Typing Latency — measure input responsiveness
+// ---------------------------------------------------------------------------
+
+function TypingLatencyImpl() {
+ const [lineCount, setLineCount] = useState(500);
+ const [code, setCode] = useState(() => generateCode(500));
+ const [latencies, setLatencies] = useState<number[]>([]);
+ const lastInput = useRef(0);
+
+ const handleChange = useCallback((val: string) => {
+ const now = performance.now();
+ if (lastInput.current > 0) {
+ const dt = now - lastInput.current;
+ if (dt < 500) {
+ setLatencies(prev => [...prev.slice(-49), dt]);
+ }
+ }
+ lastInput.current = now;
+ setCode(val);
+ }, []);
+
+ const avgLatency =
+ latencies.length > 0
+ ? latencies.reduce((a, b) => a + b, 0) / latencies.length
+ : 0;
+ const maxLatency = latencies.length > 0 ? Math.max(...latencies) : 0;
+
+ const regenerate = useCallback((count: number) => {
+ setLineCount(count);
+ setCode(generateCode(count));
+ setLatencies([]);
+ }, []);
+
+ return (
+ <div
+ style={{
+ padding: 16,
+ display: 'flex',
+ flexDirection: 'column',
+ gap: 12,
+ }}>
+ <div
+ style={{
+ display: 'flex',
+ gap: 8,
+ alignItems: 'center',
+ flexWrap: 'wrap',
+ }}>
+ <span style={{fontSize: 13, fontWeight: 600}}>Lines:</span>
+ {[100, 500, 1000, 2000].map(n => (
+ <button
+ key={n}
+ onClick={() => regenerate(n)}
+ style={{
+ padding: '4px 10px',
+ borderRadius: 4,
+ border: lineCount === n ? '2px solid #0066cc' : '1px solid #ccc',
+ background: lineCount === n ? '#e6f0ff' : 'white',
+ cursor: 'pointer',
+ fontSize: 12,
+ }}>
+ {n}
+ </button>
+ ))}
+ <Metric label="Avg" value={`${avgLatency.toFixed(1)}ms`} />
+ <Metric label="Max" value={`${maxLatency.toFixed(1)}ms`} />
+ <Metric label="Samples" value={latencies.length} />
+ <span style={{fontSize: 11, color: '#888'}}>
+ Type in the editor to measure input latency
+ </span>
+ </div>
+ <XDSCodeEditor
+ value={code}
+ onChange={handleChange}
+ language="typescript"
+ hasLineNumbers
+ maxHeight={600}
+ />
+ </div>
+ );
+}
+
+export const TypingLatency: Story = {
+ render: () => <TypingLatencyImpl />,
+};
diff --git a/apps/storybook/stories/CodeEditorTheme.stories.tsx b/apps/storybook/stories/CodeEditorTheme.stories.tsx
new file mode 100644
index 0000000000..2ad31fe44d
--- /dev/null
+++ b/apps/storybook/stories/CodeEditorTheme.stories.tsx
@@ -0,0 +1,239 @@
+import type {Meta, StoryObj} from '@storybook/react';
+import {useState} from 'react';
+import {XDSCodeEditor} from '@xds/lab';
+import {
+ XDSSyntaxTheme as SyntaxThemeProvider,
+ defineSyntaxTheme,
+} from '@xds/core/theme/syntax';
+import {
+ oneDarkPro,
+ dracula,
+ monokai,
+ nord,
+ tokyoNight,
+ catppuccinMocha,
+ githubDark,
+ githubLight,
+ solarizedLight,
+ oneLight,
+ catppuccinLatte,
+ tokyoNightLight,
+ allSyntaxPresets,
+} from '@xds/core/theme/syntax';
+
+const sampleCode = [
+ "import {useState, useEffect} from 'react';",
+ '',
+ 'interface User {',
+ ' id: string;',
+ ' name: string;',
+ ' roles: string[];',
+ '}',
+ '',
+ 'const API_URL = "https://api.example.com";',
+ 'const MAX_RETRIES = 3;',
+ '',
+ '// Fetch user data with retry logic',
+ 'async function fetchUser(id: string): Promise<User> {',
+ ' const response = await fetch(`${API_URL}/users/${id}`);',
+ ' if (!response.ok) {',
+ ' throw new Error(`HTTP ${response.status}`);',
+ ' }',
+ ' return response.json();',
+ '}',
+ '',
+ 'export function UserCard({id}: {id: string}) {',
+ ' const [user, setUser] = useState<User | null>(null);',
+ '',
+ ' useEffect(() => {',
+ ' fetchUser(id).then(setUser);',
+ ' }, [id]);',
+ '',
+ ' if (!user) return <div>Loading...</div>;',
+ '',
+ ' return (',
+ ' <div className="card">',
+ ' <h2>{user.name}</h2>',
+ ' <span>{user.roles.length} roles</span>',
+ ' </div>',
+ ' );',
+ '}',
+].join('\n');
+
+function ThemedEditor({
+ theme,
+ title,
+ initialCode = sampleCode,
+}: {
+ theme: Parameters<typeof SyntaxThemeProvider>[0]['theme'];
+ title?: string;
+ initialCode?: string;
+}) {
+ const [value, setValue] = useState(initialCode);
+ return (
+ <SyntaxThemeProvider theme={theme}>
+ <XDSCodeEditor
+ value={value}
+ onChange={setValue}
+ language="typescript"
+ hasLineNumbers
+ />
+ </SyntaxThemeProvider>
+ );
+}
+
+const meta: Meta = {
+ title: 'Lab/XDSCodeEditor Themes',
+ parameters: {
+ docs: {
+ description: {
+ component:
+ 'Syntax theme showcase for XDSCodeEditor. All themes from XDSSyntaxTheme ' +
+ 'work identically on both CodeBlock and CodeEditor.',
+ },
+ },
+ },
+};
+
+export default meta;
+
+// ---------------------------------------------------------------------------
+// Individual theme stories
+// ---------------------------------------------------------------------------
+
+export const OneDarkPro: StoryObj = {
+ render: () => <ThemedEditor theme={oneDarkPro} />,
+};
+
+export const Dracula: StoryObj = {
+ render: () => <ThemedEditor theme={dracula} />,
+};
+
+export const Monokai: StoryObj = {
+ render: () => <ThemedEditor theme={monokai} />,
+};
+
+export const Nord: StoryObj = {
+ render: () => <ThemedEditor theme={nord} />,
+};
+
+export const TokyoNight: StoryObj = {
+ render: () => <ThemedEditor theme={tokyoNight} />,
+};
+
+export const CatppuccinMocha: StoryObj = {
+ render: () => <ThemedEditor theme={catppuccinMocha} />,
+};
+
+export const GitHubLight: StoryObj = {
+ render: () => <ThemedEditor theme={githubLight} />,
+};
+
+export const GitHubDark: StoryObj = {
+ render: () => <ThemedEditor theme={githubDark} />,
+};
+
+export const SolarizedLight: StoryObj = {
+ render: () => <ThemedEditor theme={solarizedLight} />,
+};
+
+export const OneLight: StoryObj = {
+ render: () => <ThemedEditor theme={oneLight} />,
+};
+
+export const CatppuccinLatte: StoryObj = {
+ render: () => <ThemedEditor theme={catppuccinLatte} />,
+};
+
+export const TokyoNightLight: StoryObj = {
+ render: () => <ThemedEditor theme={tokyoNightLight} />,
+};
+
+// ---------------------------------------------------------------------------
+// Gallery — all themes side by side
+// ---------------------------------------------------------------------------
+
+const shortCode = [
+ 'const greet = (name: string) => {',
+ ' // Say hello',
+ ' return `Hello, ${name}!`;',
+ '};',
+ '',
+ 'const result = greet("World");',
+ 'console.log(result); // Hello, World!',
+].join('\n');
+
+function GalleryEditor({
+ theme,
+}: {
+ theme: Parameters<typeof SyntaxThemeProvider>[0]['theme'];
+}) {
+ const [value, setValue] = useState(shortCode);
+ return (
+ <SyntaxThemeProvider theme={theme}>
+ <div>
+ <div
+ style={{
+ fontSize: 11,
+ fontWeight: 600,
+ color: '#888',
+ marginBottom: 4,
+ fontFamily: 'monospace',
+ }}>
+ {theme.name}
+ </div>
+ <XDSCodeEditor
+ value={value}
+ onChange={setValue}
+ language="typescript"
+ hasLineNumbers
+ />
+ </div>
+ </SyntaxThemeProvider>
+ );
+}
+
+export const AllThemesGallery: StoryObj = {
+ render: () => (
+ <div
+ style={{
+ display: 'grid',
+ gridTemplateColumns: '1fr 1fr',
+ gap: 16,
+ padding: 16,
+ }}>
+ {allSyntaxPresets.map(theme => (
+ <GalleryEditor key={theme.name} theme={theme} />
+ ))}
+ </div>
+ ),
+ parameters: {layout: 'fullscreen'},
+};
+
+// ---------------------------------------------------------------------------
+// Custom syntax theme
+// ---------------------------------------------------------------------------
+
+const cyberpunk = defineSyntaxTheme({
+ name: 'cyberpunk',
+ tokens: {
+ keyword: '#ff2a6d',
+ string: '#05d9e8',
+ comment: '#4a5568',
+ number: '#d1f7ff',
+ function: '#ff6ac1',
+ type: '#7efff5',
+ variable: '#e2e8f0',
+ operator: '#ff9e64',
+ constant: '#d1f7ff',
+ tag: '#ff2a6d',
+ attribute: '#7efff5',
+ property: '#05d9e8',
+ punctuation: '#718096',
+ background: '#0d0221',
+ },
+});
+
+export const CustomTheme: StoryObj = {
+ render: () => <ThemedEditor theme={cyberpunk} />,
+};
diff --git a/packages/core/src/CodeBlock/highlightRanges.ts b/packages/core/src/CodeBlock/highlightRanges.ts
index e8ed72bbea..ed186e11cb 100644
--- a/packages/core/src/CodeBlock/highlightRanges.ts
+++ b/packages/core/src/CodeBlock/highlightRanges.ts
@@ -338,6 +338,92 @@ export function applyHighlightRangesBatch(
return results;
}
+// ---------------------------------------------------------------------------
+// Flat text-node application (for contentEditable elements)
+// ---------------------------------------------------------------------------
+
+/**
+ * Apply CSS Custom Highlight API ranges to a flat element (no [data-line]
+ * structure). Works with contentEditable="plaintext-only" where all text
+ * may be a single Text node with embedded newlines.
+ *
+ * @param el - The element containing text (e.g. contentEditable code element)
+ * @param tokenLines - Per-line token arrays from the tokenizer
+ * @returns Cleanup function that removes all ranges
+ */
+export function applyHighlightRangesFlat(
+ el: HTMLElement,
+ tokenLines: TokenLine[],
+): () => void {
+ ensureHighlightStyles();
+
+ const resolve = createHighlightResolver();
+ const myRanges: RangeEntry[] = [];
+
+ // Collect text nodes with absolute offsets
+ const walker = document.createTreeWalker(el, NodeFilter.SHOW_TEXT);
+ const textNodes: Array<{node: Text; start: number; length: number}> = [];
+ let totalOffset = 0;
+ let current = walker.nextNode();
+ while (current) {
+ const text = current as Text;
+ textNodes.push({node: text, start: totalOffset, length: text.length});
+ totalOffset += text.length;
+ current = walker.nextNode();
+ }
+
+ if (textNodes.length === 0) return () => cleanupRanges(myRanges);
+
+ // Convert per-line tokens to absolute offsets.
+ // The source code string has lines joined by \n, so each line starts
+ // at the cumulative offset of all previous lines + their \n separators.
+ const fullText = el.textContent ?? '';
+ let lineOffset = 0;
+ for (let lineIdx = 0; lineIdx < tokenLines.length; lineIdx++) {
+ const lineTokens = tokenLines[lineIdx];
+ if (lineTokens) {
+ for (const token of lineTokens) {
+ const absStart = lineOffset + token.start;
+ const absEnd = lineOffset + token.end;
+
+ const startPos = resolveOffset(textNodes, absStart);
+ const endPos = resolveOffset(textNodes, absEnd);
+ if (!startPos || !endPos) continue;
+
+ const highlight = resolve(token.type);
+ 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
+ }
+ }
+ }
+
+ // Advance past this line + \n separator
+ const nlPos = fullText.indexOf('\n', lineOffset);
+ lineOffset = nlPos === -1 ? fullText.length : nlPos + 1;
+ }
+
+ return () => cleanupRanges(myRanges);
+}
+
+function resolveOffset(
+ textNodes: Array<{node: Text; start: number; length: number}>,
+ absOffset: number,
+): {node: Text; offset: number} | null {
+ for (const entry of textNodes) {
+ const end = entry.start + entry.length;
+ if (absOffset >= entry.start && absOffset <= end) {
+ return {node: entry.node, offset: absOffset - entry.start};
+ }
+ }
+ return null;
+}
+
/**
* Cleanup a batch of ranges (returned from applyHighlightRangesBatch).
*/
diff --git a/packages/core/src/CodeBlock/index.ts b/packages/core/src/CodeBlock/index.ts
index 16322b2bdb..5b855ded46 100644
--- a/packages/core/src/CodeBlock/index.ts
+++ b/packages/core/src/CodeBlock/index.ts
@@ -13,5 +13,10 @@ export {
} from './tokenizer';
export type {Token, TokenLine} from './tokenizer';
-export {applyHighlightRangesChunked, applyHighlightRangesBatch, cleanupRanges} from './highlightRanges';
+export {
+ applyHighlightRangesChunked,
+ applyHighlightRangesBatch,
+ applyHighlightRangesFlat,
+ cleanupRanges,
+} from './highlightRanges';
export {ensureHighlightStyles, TOKEN_TYPES} from './highlightStyles';
diff --git a/packages/lab/src/CodeEditor/XDSCodeEditor.tsx b/packages/lab/src/CodeEditor/XDSCodeEditor.tsx
index 3d68bb9e47..7cb815af81 100644
--- a/packages/lab/src/CodeEditor/XDSCodeEditor.tsx
+++ b/packages/lab/src/CodeEditor/XDSCodeEditor.tsx
@@ -12,14 +12,7 @@
'use client';
-import {
- useEffect,
- useLayoutEffect,
- useRef,
- useCallback,
- useState,
- useMemo,
-} from 'react';
+import {useEffect, useLayoutEffect, useRef, useCallback, useState} from 'react';
import type {XDSBaseProps} from '@xds/core/XDSBaseProps';
import * as stylex from '@stylexjs/stylex';
import {
@@ -37,8 +30,11 @@ import {
tokenizeAsync,
SYNC_TOKENIZE_THRESHOLD,
} from '@xds/core/CodeBlock';
-import type {Token, TokenLine} from '@xds/core/CodeBlock';
-import {ensureHighlightStyles, applyHighlightRangesChunked} from '@xds/core/CodeBlock';
+import type {TokenLine} from '@xds/core/CodeBlock';
+import {
+ ensureHighlightStyles,
+ applyHighlightRangesFlat,
+} from '@xds/core/CodeBlock';
// ---------------------------------------------------------------------------
// Styles
@@ -72,6 +68,7 @@ const styles = stylex.create({
lineHeight: typeScaleVars['--text-code-leading'],
},
editorContainer: {
+ display: 'flex',
flex: 1,
overflow: 'auto',
},
@@ -142,19 +139,7 @@ export interface XDSCodeEditorProps extends Omit<
/** Text size. @default "md" */
size?: 'sm' | 'md';
/** Custom tokenizer */
- tokenizer?: (
- code: string,
- language: string,
- ) => TokenLine[];
- /**
- * How to apply syntax highlighting.
- * - 'css-highlight': Uses CSS Custom Highlight API (zero DOM overhead).
- * Falls back to 'spans' if the API is not available.
- * - 'spans': Renders `<span>` elements with CSS classes per token.
- * In the editor, uses a transparent-text overlay approach.
- * @default 'css-highlight'
- */
- highlightMode?: 'css-highlight' | 'spans';
+ tokenizer?: (code: string, language: string) => TokenLine[];
}
// ---------------------------------------------------------------------------
@@ -180,60 +165,6 @@ const AUTO_CLOSE_PAIRS: Record<string, string> = {
let editorInstanceCounter = 0;
-// ---------------------------------------------------------------------------
-// Span-based rendering helpers
-// ---------------------------------------------------------------------------
-
-
-/**
- * Build span-based highlighted line content from per-line tokens.
- */
-function buildSpanLine(
- lineText: string,
- tokens: Token[],
-): React.ReactNode {
- if (!lineText) return '\u200b';
- if (tokens.length === 0) return lineText;
-
- const parts: React.ReactNode[] = [];
- let cursor = 0;
-
- 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={`${token.start}-${token.type}`}
- className={`xds-token-${token.type}`}>
- {lineText.slice(token.start, end)}
- </span>,
- );
-
- cursor = end;
- }
-
- if (cursor < lineText.length) {
- parts.push(lineText.slice(cursor));
- }
-
- return parts.length > 0 ? parts : lineText;
-}
-
-/**
- * Build span-based content for all lines.
- */
-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>
- ));
-}
-
// ---------------------------------------------------------------------------
// Component
// ---------------------------------------------------------------------------
@@ -243,8 +174,6 @@ function buildSpanContent(lines: string[], tokenLines: TokenLine[]): React.React
*
* Uses CSS Custom Highlight API for syntax coloring. Supports
* auto-indent, tab insertion, and bracket auto-closing.
- * Falls back to span-based rendering when the API is unavailable
- * or `highlightMode="spans"` is set.
*
* @example
* ```tsx
@@ -267,24 +196,17 @@ export function XDSCodeEditor({
maxHeight,
size = 'md',
tokenizer: customTokenizer,
- highlightMode: highlightModeProp = 'css-highlight',
xstyle,
className,
style,
ref,
...props
}: XDSCodeEditorProps) {
- const editorRef = useRef<HTMLDivElement>(null);
+ const editorRef = useRef<HTMLElement>(null);
const [instanceId] = useState(() => ++editorInstanceCounter);
const [focused, setFocused] = useState(false);
const isComposingRef = useRef(false);
- // Resolve effective highlight mode
- const useSpans = highlightModeProp === 'spans' || !hasHighlightAPI();
-
- // Async tokens for span mode overlay
- const [asyncTokens, setAsyncTokens] = useState<TokenLine[] | null>(null);
-
const lines = value.split('\n');
// Sync textContent with controlled value
@@ -296,35 +218,6 @@ export function XDSCodeEditor({
}
}, [value]);
- // Compute sync tokens for span mode (small code)
- const syncTokens = useMemo(() => {
- if (!useSpans) return null;
- if (value.length >= SYNC_TOKENIZE_THRESHOLD) return null;
- const tok = customTokenizer ?? tokenize;
- return tok(value, language);
- }, [useSpans, value, language, customTokenizer]);
-
- // Async tokenization for span mode with large code
- useEffect(() => {
- if (!useSpans) return;
- if (value.length < SYNC_TOKENIZE_THRESHOLD) return;
-
- const abortController = new AbortController();
-
- tokenizeAsync(value, language, abortController.signal).then(tokens => {
- if (!abortController.signal.aborted) {
- setAsyncTokens(tokens);
- }
- });
-
- return () => {
- abortController.abort();
- setAsyncTokens(null);
- };
- }, [useSpans, value, language, customTokenizer]);
-
- const spanTokens: TokenLine[] = syncTokens ?? asyncTokens ?? [];
-
// Ensure styles are always injected
useLayoutEffect(() => {
ensureHighlightStyles();
@@ -332,7 +225,6 @@ export function XDSCodeEditor({
// Apply CSS Custom Highlight API ranges — small code
useLayoutEffect(() => {
- if (useSpans) return;
if (value.length >= SYNC_TOKENIZE_THRESHOLD) return;
if (!hasHighlightAPI()) return;
@@ -343,12 +235,11 @@ export function XDSCodeEditor({
const tokens = tok(value, language);
if (tokens.length === 0) return;
- return applyHighlightRangesChunked(el, tokens);
- }, [useSpans, value, language, customTokenizer, instanceId]);
+ return applyHighlightRangesFlat(el, tokens);
+ }, [value, language, customTokenizer, instanceId]);
// Apply CSS Custom Highlight API ranges — large code (async)
useEffect(() => {
- if (useSpans) return;
if (value.length < SYNC_TOKENIZE_THRESHOLD) return;
if (!hasHighlightAPI()) return;
@@ -361,14 +252,14 @@ export function XDSCodeEditor({
tokenizeAsync(value, language, abortController.signal).then(tokens => {
if (abortController.signal.aborted) return;
if (tokens.length === 0) return;
- cleanup = applyHighlightRangesChunked(el, tokens);
+ cleanup = applyHighlightRangesFlat(el, tokens);
});
return () => {
abortController.abort();
cleanup?.();
};
- }, [useSpans, value, language, customTokenizer, instanceId]);
+ }, [value, language, customTokenizer, instanceId]);
const handleInput = useCallback(() => {
if (isComposingRef.current) return;
@@ -479,30 +370,6 @@ export function XDSCodeEditor({
? {maxHeight: typeof maxHeight === 'number' ? `${maxHeight}px` : maxHeight}
: undefined;
- // For span mode in the editor, we render a non-interactive overlay with
- // colored spans on top of the contentEditable. The contentEditable text
- // is made transparent so the overlay provides the visual coloring while
- // the contentEditable handles input/caret.
- const spanOverlay =
- useSpans && spanTokens.some(line => line.length > 0) ? (
- <div
- aria-hidden="true"
- style={{
- position: 'absolute',
- top: 0,
- left: 0,
- right: 0,
- bottom: 0,
- pointerEvents: 'none',
- whiteSpace: 'pre',
- wordBreak: 'normal',
- overflowWrap: 'normal',
- }}
- {...stylex.props(styles.editor, sizeStyle)}>
- {buildSpanContent(lines, spanTokens)}
- </div>
- ) : null;
-
return (
<div
ref={ref}
@@ -513,47 +380,41 @@ export function XDSCodeEditor({
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, position: 'relative'}}>
- {showPlaceholder && (
- <div {...stylex.props(styles.placeholder, sizeStyle)}>
- {placeholder}
+ <div {...stylex.props(styles.editorContainer)} style={containerStyle}>
+ {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
- 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)}
- style={
- useSpans && spanTokens.some(line => line.length > 0)
- ? {color: 'transparent', caretColor: 'inherit'}
- : undefined
- }
- />
- {spanOverlay}
+ <div style={{position: 'relative', flex: 1}}>
+ {showPlaceholder && (
+ <div {...stylex.props(styles.placeholder, sizeStyle)}>
+ {placeholder}
+ </div>
+ )}
+ <code
+ 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>
</div>
);