70160
Ce
cel-tui / files
cel-tui / examples / syntax-highlight.ts
12.5 KB
1/** 2 * cel-tui: SyntaxHighlight component demo 3 * 4 * This example is intentionally component-focused. 5 * It streams append-only chunks into one `createSyntaxHighlight()` instance 6 * and lets you switch samples and themes, without reaching into tokenizer internals. 7 * 8 * Run: bun run examples/syntax-highlight.ts 9 */ 10 11import { 12 createSyntaxHighlight, 13 Divider, 14 Spacer, 15 type SyntaxHighlightTheme, 16 VDivider, 17} from "@cel-tui/components"; 18import { cel, HStack, ProcessTerminal, Text, VStack } from "@cel-tui/core"; 19import { warningBox } from "./warning-box"; 20 21const MIN_COLS = 76; 22const MIN_ROWS = 20; 23const SIDE_BY_SIDE_MIN_COLS = 110; 24const TICK_MS = 70; 25 26interface DemoSample { 27 title: string; 28 language: string; 29 aliases: readonly string[]; 30 description: string; 31 chunkSize: number; 32 source: string; 33} 34 35const CUSTOM_THEME: SyntaxHighlightTheme = { 36 name: "syntax-highlight-demo-sunset", 37 type: "dark", 38 fg: "#f8f8f2", 39 bg: "#1f2335", 40 tokenColors: [ 41 { settings: { foreground: "#f8f8f2" } }, 42 { 43 scope: ["comment"], 44 settings: { foreground: "#7f849c", fontStyle: "italic" }, 45 }, 46 { 47 scope: ["keyword", "operator"], 48 settings: { foreground: "#ff79c6" }, 49 }, 50 { 51 scope: ["string"], 52 settings: { foreground: "#f1fa8c" }, 53 }, 54 { 55 scope: ["number", "escape"], 56 settings: { foreground: "#ffb86c" }, 57 }, 58 { 59 scope: ["command", "function"], 60 settings: { foreground: "#50fa7b" }, 61 }, 62 { 63 scope: ["type", "builtin", "meta", "markup.heading"], 64 settings: { foreground: "#8be9fd" }, 65 }, 66 { 67 scope: ["variable", "property"], 68 settings: { foreground: "#bd93f9" }, 69 }, 70 { 71 scope: ["link"], 72 settings: { foreground: "#8be9fd", fontStyle: "underline" }, 73 }, 74 { 75 scope: ["markup.list", "markup.quote"], 76 settings: { foreground: "#ffb86c" }, 77 }, 78 ], 79}; 80 81const THEME_OPTIONS: ReadonlyArray<{ 82 label: string; 83 help: string; 84 theme?: SyntaxHighlightTheme; 85}> = [ 86 { 87 label: "terminal ansi16", 88 help: "Default theme follows terminal defaults plus ANSI slot accents.", 89 }, 90 { 91 label: "dark-plus", 92 help: "Built-in preset with a VS Code-ish dark palette.", 93 theme: "dark-plus", 94 }, 95 { 96 label: "custom sunset", 97 help: "Custom token theme mapped onto cel's ANSI palette slots.", 98 theme: CUSTOM_THEME, 99 }, 100]; 101 102const SAMPLES: readonly DemoSample[] = [ 103 { 104 title: "TypeScript", 105 language: "typescript", 106 aliases: ["ts", "mts", "cts"], 107 description: 108 "Shows the current clew-backed path: keywords, strings, comments, and append-only updates.", 109 chunkSize: 4, 110 source: [ 111 "/**", 112 " * clew is stream-first.", 113 " */", 114 'type Phase = "idle" | "streaming" | "done";', 115 "", 116 "interface Chunk<T> {", 117 " id: number;", 118 " payload: T;", 119 "}", 120 "", 121 "function renderChunk<T extends string | number>(chunk: Chunk<T>): string {", 122 " return `${chunk.id}:${String(chunk.payload)}`;", 123 "}", 124 "", 125 'const preview: Chunk<string> = { id: 7, payload: "hello" };', 126 "renderChunk(preview);", 127 ].join("\n"), 128 }, 129 { 130 title: "JavaScript", 131 language: "javascript", 132 aliases: ["js", "mjs", "cjs"], 133 description: "Async code, destructuring, and a template literal.", 134 chunkSize: 5, 135 source: [ 136 "async function loadUsers(signal) {", 137 ' const response = await fetch("/api/users", { signal });', 138 " if (!response.ok) {", 139 " throw new Error(`HTTP ${response.status}`);", 140 " }", 141 " const users = await response.json();", 142 " return users.map(({ id, name }) => `${id}:${name}`).join(', ');", 143 "}", 144 ].join("\n"), 145 }, 146 { 147 title: "Python", 148 language: "python", 149 aliases: ["py"], 150 description: "Decorators, classes, builtins, and an f-string.", 151 chunkSize: 5, 152 source: [ 153 "from dataclasses import dataclass", 154 "", 155 "@dataclass", 156 "class Job:", 157 " name: str", 158 " retries: int = 0", 159 "", 160 " def render(self) -> str:", 161 ' return f"{self.name}:{self.retries}"', 162 "", 163 'print(Job("clew", 2).render())', 164 ].join("\n"), 165 }, 166 { 167 title: "Bash", 168 language: "bash", 169 aliases: ["bash"], 170 description: 171 "Bash-only support: builtins, variables, substitutions, and a heredoc.", 172 chunkSize: 5, 173 source: [ 174 "#!/usr/bin/env bash", 175 "set -euo pipefail", 176 "", 177 "name=${1:-stream}", 178 'printf "start %s\\n" "$name"', 179 "", 180 'if [[ "$name" == "stream" ]]; then', 181 " cat <<'EOF'", 182 "append-only shell chunks", 183 "EOF", 184 "fi", 185 ].join("\n"), 186 }, 187 { 188 title: "JSON", 189 language: "json", 190 aliases: ["json"], 191 description: 192 "Object keys, string values, booleans, null, numbers, and nested arrays.", 193 chunkSize: 6, 194 source: [ 195 "{", 196 ' "name": "clew",', 197 ' "stream": true,', 198 ' "stability": "eager",', 199 ' "retries": 2,', 200 ' "features": ["json", "markdown", null],', 201 ' "theme": { "name": "dark-plus", "enabled": true }', 202 "}", 203 ].join("\n"), 204 }, 205 { 206 title: "Markdown", 207 language: "markdown", 208 aliases: ["markdown"], 209 description: 210 "Headings, list markers, links, inline code, blockquotes, and fenced code.", 211 chunkSize: 5, 212 source: [ 213 "# clew notes", 214 "", 215 "- stream-first updates", 216 '- `SyntaxHighlight(content, "markdown")`', 217 "> Links stay atomic: [docs](https://example.com)", 218 "", 219 "```ts", 220 'const mode = "streaming";', 221 "```", 222 ].join("\n"), 223 }, 224]; 225 226let sampleIndex = 0; 227let themeIndex = 0; 228let content = ""; 229const highlightSource = createSyntaxHighlight(); 230let cursor = 0; 231let chunks = 0; 232let lastChunk = ""; 233let paused = false; 234let timer: ReturnType<typeof setTimeout> | null = null; 235 236function currentSample(): DemoSample { 237 return SAMPLES[sampleIndex] ?? SAMPLES[0]!; 238} 239 240function currentTheme() { 241 return THEME_OPTIONS[themeIndex] ?? THEME_OPTIONS[0]!; 242} 243 244function stopStreaming() { 245 if (timer) { 246 clearTimeout(timer); 247 timer = null; 248 } 249} 250 251function scheduleTick() { 252 stopStreaming(); 253 if (paused || cursor >= currentSample().source.length) { 254 return; 255 } 256 timer = setTimeout(tick, TICK_MS); 257} 258 259function resetCurrentSample() { 260 stopStreaming(); 261 content = ""; 262 cursor = 0; 263 chunks = 0; 264 lastChunk = ""; 265 paused = false; 266 scheduleTick(); 267 cel.render(); 268} 269 270function selectSample(delta: number) { 271 sampleIndex = (sampleIndex + delta + SAMPLES.length) % SAMPLES.length; 272 resetCurrentSample(); 273} 274 275function toggleTheme() { 276 themeIndex = (themeIndex + 1) % THEME_OPTIONS.length; 277 cel.render(); 278} 279 280function togglePause() { 281 paused = !paused; 282 scheduleTick(); 283 cel.render(); 284} 285 286function previewChunk(chunk: string, max = 24): string { 287 return chunk.length > max ? `${chunk.slice(0, max - 1)}…` : chunk; 288} 289 290function progressLine(sample: DemoSample): string { 291 return `${String(cursor).padStart(String(sample.source.length).length)}/${sample.source.length} chars`; 292} 293 294function tick() { 295 const sample = currentSample(); 296 if (cursor >= sample.source.length) { 297 stopStreaming(); 298 cel.render(); 299 return; 300 } 301 302 const nextCursor = Math.min(sample.source.length, cursor + sample.chunkSize); 303 lastChunk = sample.source.slice(cursor, nextCursor); 304 content += lastChunk; 305 cursor = nextCursor; 306 chunks += 1; 307 308 scheduleTick(); 309 cel.render(); 310} 311 312function quit() { 313 stopStreaming(); 314 cel.stop(); 315 process.exit(0); 316} 317 318function statusText(sample: DemoSample): string { 319 if (cursor >= sample.source.length) { 320 return "done"; 321 } 322 return paused ? "paused" : "streaming"; 323} 324 325function sampleChip(sample: DemoSample, index: number) { 326 const selected = index === sampleIndex; 327 return Text(` ${sample.language} `, { 328 fgColor: selected ? "color15" : "color08", 329 bgColor: selected ? "color06" : undefined, 330 bold: selected || undefined, 331 }); 332} 333 334function infoPane() { 335 const sample = currentSample(); 336 const theme = currentTheme(); 337 338 return VStack({ padding: { x: 1 }, gap: 1 }, [ 339 Text("SyntaxHighlight component demo", { 340 bold: true, 341 fgColor: "color06", 342 }), 343 Text("This example owns one createSyntaxHighlight() streaming instance.", { 344 fgColor: "color08", 345 italic: true, 346 }), 347 Text( 348 "Append-only chunks are streamed into the component; backend details stay internal.", 349 { 350 fgColor: "color08", 351 italic: true, 352 }, 353 ), 354 Divider({ fgColor: "color08" }), 355 Text(`${sample.title} (${sample.language})`, { 356 bold: true, 357 fgColor: "color03", 358 }), 359 Text(sample.description, { fgColor: "color08" }), 360 Text(`aliases: ${sample.aliases.join(", ")}`, { fgColor: "color08" }), 361 Text(`theme: ${theme.label}`, { fgColor: "color08" }), 362 Text(`status: ${statusText(sample)}`, { fgColor: "color08" }), 363 Text(`progress: ${progressLine(sample)} | ${chunks} chunks`, { 364 fgColor: "color08", 365 }), 366 Text(`last chunk: "${previewChunk(lastChunk)}"`, { fgColor: "color08" }), 367 Divider({ fgColor: "color08" }), 368 Text("Component call", { bold: true, fgColor: "color06" }), 369 Text(`highlightSource(content, "${sample.language}", {`, { 370 fgColor: "color07", 371 }), 372 Text( 373 ` theme: ${typeof theme.theme === "string" ? JSON.stringify(theme.theme) : theme.theme ? "<custom theme>" : "undefined"}`, 374 { fgColor: "color07" }, 375 ), 376 Text("})", { fgColor: "color07" }), 377 Divider({ fgColor: "color08" }), 378 Text("Controls", { bold: true, fgColor: "color06" }), 379 Text("Left/Right or Tab/Shift+Tab switch sample", { fgColor: "color08" }), 380 Text("Ctrl+T cycle theme", { fgColor: "color08" }), 381 Text("Space pause/resume stream", { 382 fgColor: "color08", 383 }), 384 Text("Ctrl+R restart current sample", { 385 fgColor: "color08", 386 }), 387 Text("Ctrl+Q quit", { fgColor: "color08" }), 388 ]); 389} 390 391function highlightPane() { 392 const sample = currentSample(); 393 const theme = currentTheme(); 394 395 return VStack({ flex: 1 }, [ 396 HStack({ padding: { x: 1 }, gap: 1 }, [ 397 Text(sample.title, { bold: true, fgColor: "color06" }), 398 Spacer(), 399 Text(theme.help, { fgColor: "color08" }), 400 ]), 401 Divider({ fgColor: "color08" }), 402 VStack( 403 { 404 flex: 1, 405 overflow: "scroll", 406 scrollbar: true, 407 padding: { x: 1 }, 408 }, 409 [highlightSource(content, sample.language, { theme: theme.theme })], 410 ), 411 ]); 412} 413 414function mainView(cols: number) { 415 const wide = cols >= SIDE_BY_SIDE_MIN_COLS; 416 417 if (wide) { 418 return HStack({ flex: 1 }, [ 419 VStack({ width: 42, overflow: "scroll", scrollbar: true }, [infoPane()]), 420 VDivider({ fgColor: "color08" }), 421 highlightPane(), 422 ]); 423 } 424 425 return VStack({ flex: 1 }, [ 426 infoPane(), 427 Divider({ fgColor: "color08" }), 428 highlightPane(), 429 ]); 430} 431 432cel.init(new ProcessTerminal()); 433cel.viewport(() => { 434 const cols = process.stdout.columns || 80; 435 const rows = process.stdout.rows || 24; 436 437 if (cols < MIN_COLS || rows < MIN_ROWS) { 438 return VStack( 439 { 440 height: "100%", 441 justifyContent: "center", 442 alignItems: "center", 443 onKeyPress: (key) => { 444 if (key === "ctrl+q" || key === "ctrl+c") { 445 quit(); 446 } 447 }, 448 }, 449 [ 450 ...warningBox([ 451 " Terminal too small :(", 452 "", 453 " Please resize to at", 454 ` least ${String(MIN_COLS).padStart(3)}×${String(MIN_ROWS).padStart(2)} chars.`, 455 "", 456 " Ctrl+Q to quit", 457 ]), 458 ], 459 ); 460 } 461 462 return VStack( 463 { 464 height: "100%", 465 overflow: "scroll", 466 onKeyPress: (key) => { 467 if (key === "ctrl+q" || key === "ctrl+c") { 468 quit(); 469 } 470 if (key === "ctrl+r") { 471 resetCurrentSample(); 472 } 473 if (key === "ctrl+t") { 474 toggleTheme(); 475 } 476 if (key === "space") { 477 togglePause(); 478 } 479 if (key === "left" || key === "shift+tab") { 480 selectSample(-1); 481 } 482 if (key === "right" || key === "tab") { 483 selectSample(1); 484 } 485 }, 486 }, 487 [ 488 HStack({ padding: { x: 1 }, gap: 2 }, [ 489 Text("SyntaxHighlight example", { bold: true, fgColor: "color06" }), 490 Spacer(), 491 Text(`theme: ${currentTheme().label}`, { fgColor: "color03" }), 492 ]), 493 Divider({ fgColor: "color08" }), 494 HStack({ padding: { x: 1 }, gap: 1, flexWrap: "wrap" }, [ 495 ...SAMPLES.map(sampleChip), 496 ]), 497 Divider({ fgColor: "color08" }), 498 mainView(cols), 499 ], 500 ); 501}); 502 503resetCurrentSample();