Файли
openidea/src/ui/tokenSpans.tsx
T
Qingтаqtvbwfn 78a3768ec1 feat(ui): syntax-highlight the read-only source previews (#1284)
The read-only previews beside Problems, Show Usages and TODO results are syntax-coloured from one whole-file parse (capped for very large files), so a line inside a block comment or a multi-line string is coloured as such; the pane renders plain first and recolours when the parse lands. SourcePreview takes the colouring as a colorize prop (the editor's previewColors), keeping src/ui free of editor imports, and the tok-* colours live once in global.css instead of a copy per view, with the theme's comment style.

Co-authored-by: qtvbwfn <[email protected]>
2026-11-05 00:55:03 +08:00

40 рядки
992 B
TypeScript

import type { ReactNode } from "react";
/** A syntax-coloured span of a text: `[from, to)` with its `tok-*` class names. */
export interface SourceToken {
from: number;
to: number;
cls: string;
}
/**
* `text` between `from` and `to` as spans with the tokens' `tok-*` classes
* (styled in global.css); `key` prefixes the React keys.
*/
export function tokenSpans(
text: string,
from: number,
to: number,
tokens: readonly SourceToken[] | null,
key = "",
): ReactNode[] {
if (!tokens?.length) return [text.slice(from, to)];
const out: ReactNode[] = [];
let pos = from;
for (const t of tokens) {
if (t.to <= pos) continue;
if (t.from >= to) break;
const s = Math.max(t.from, pos);
const e = Math.min(t.to, to);
if (s > pos) out.push(text.slice(pos, s));
out.push(
<span key={`${key}${s}`} className={t.cls}>
{text.slice(s, e)}
</span>,
);
pos = e;
}
if (pos < to) out.push(text.slice(pos, to));
return out;
}