Repository navigation
Expand file tree
/
Copy pathindex.html
More file actions
747 lines (665 loc) · 27.1 KB
/
Copy pathindex.html
File metadata and controls
747 lines (665 loc) · 27.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>codelight.js</title>
<meta name="description" content="Syntax highlighting that keeps up with live code. Each line highlighted once, no flicker, no dependencies. 19 languages, 8.4 KB.">
<link rel="icon" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'%3E%3Crect width='32' height='32' rx='7' fill='%2311141a'/%3E%3Cpath d='M9 11l-4 5 4 5M23 11l4 5-4 5' stroke='%23ff7aa8' stroke-width='2.6' fill='none' stroke-linecap='round' stroke-linejoin='round'/%3E%3Ccircle cx='16' cy='16' r='3.4' fill='%23ffb86b'/%3E%3C/svg%3E">
<link rel="stylesheet" href="styles/default.min.css">
<style>
:root{
--bg:#ffffff;--surface:#f6f8fa;--border:#d0d7de;--text:#1f2328;--muted:#59636e;--accent:#cf222e;--accent-2:#953800;
--user:#ddf4ff;--good:#1a7f37;--radius:12px;
font-family:ui-sans-serif,system-ui,-apple-system,"Segoe UI",Roboto,sans-serif;
}
@media (prefers-color-scheme:dark){:root:not([data-theme="light"]){
--bg:#010409;--surface:#0d1117;--border:#30363d;--text:#e6edf3;--muted:#9198a1;--accent:#ff7b72;--accent-2:#ffa657;--user:#0c2d6b;--good:#3fb950;
}}
:root[data-theme="dark"]{--bg:#010409;--surface:#0d1117;--border:#30363d;--text:#e6edf3;--muted:#9198a1;--accent:#ff7b72;--accent-2:#ffa657;--user:#0c2d6b;--good:#3fb950}
*{box-sizing:border-box}
body{margin:0;background:var(--bg);color:var(--text);line-height:1.55}
a{color:inherit}
.wrap{max-width:980px;margin:0 auto;padding:0 16px}
header{display:flex;align-items:center;justify-content:space-between;gap:12px;padding:18px 0}
.brand{display:flex;align-items:center;gap:10px;font-weight:700;font-size:20px;text-decoration:none}
.brand b{color:var(--accent)}
.brand svg{flex:none}
nav{display:flex;gap:8px;align-items:center}
.btn{display:inline-flex;align-items:center;gap:6px;border:1px solid var(--border);background:var(--surface);color:var(--text);border-radius:8px;padding:7px 12px;font:inherit;font-size:14px;cursor:pointer;text-decoration:none;white-space:nowrap}
.btn:hover{border-color:var(--muted)}
.btn.primary{background:var(--accent);border-color:var(--accent);color:#fff}
.hero{padding:28px 0 18px}
h1{font-size:clamp(28px,5vw,44px);line-height:1.15;margin:0 0 12px;letter-spacing:-.02em}
h1 span{color:var(--accent);white-space:nowrap}
.lead{font-size:18px;color:var(--muted);max-width:680px;margin:0}
.chat{border:1px solid var(--border);border-radius:var(--radius);background:var(--surface);overflow:hidden;margin-top:26px}
.bar{display:flex;flex-wrap:wrap;align-items:center;gap:8px;padding:10px 12px;border-bottom:1px solid var(--border)}
.bar label{font-size:13px;color:var(--muted);display:flex;align-items:center;gap:6px}
select,input[type=range]{font:inherit;font-size:14px}
select{border:1px solid var(--border);background:var(--bg);color:var(--text);border-radius:6px;padding:4px 6px}
.spacer{flex:1}
.messages{padding:18px;min-height:460px;max-height:620px;overflow:auto;background:var(--bg)}
.msg{max-width:100%;margin-bottom:14px}
.msg.user{margin-left:auto;width:fit-content;max-width:80%;background:var(--user);padding:10px 14px;border-radius:14px 14px 4px 14px}
.msg.bot p{margin:0 0 10px}
.msg.bot ul{margin:0 0 10px;padding-left:22px}
.msg.bot :not(pre)>code{background:var(--surface);border:1px solid var(--border);border-radius:5px;padding:1px 5px;font-size:.9em}
.block{border:1px solid var(--border);border-radius:10px;overflow:hidden;margin:0 0 12px}
.block-head{display:flex;justify-content:space-between;align-items:center;font-size:12px;color:var(--muted);padding:6px 12px;border-bottom:1px solid var(--border);background:var(--surface)}
.block pre{margin:0;font:13.5px/1.6 ui-monospace,SFMono-Regular,Menlo,Consolas,monospace}
.block pre code.cl{padding:12px 14px;min-height:46px}
.caret{display:inline-block;width:8px;height:1.05em;vertical-align:-2px;background:var(--accent);animation:blink 1s steps(1) infinite;margin-left:1px}
@keyframes blink{50%{opacity:0}}
.stats{display:grid;grid-template-columns:repeat(3,1fr);gap:1px;background:var(--border);border-top:1px solid var(--border)}
.stat{background:var(--surface);padding:12px 14px}
.stat b{display:block;font-size:22px;font-variant-numeric:tabular-nums}
.stat small{color:var(--muted);font-size:12.5px}
.stat.win b{color:var(--good)}
section{padding:34px 0 0}
h2{font-size:22px;margin:0 0 12px}
.grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:16px}
.card{min-width:0;border:1px solid var(--border);border-radius:var(--radius);background:var(--surface);padding:16px}
.card h3{margin:0 0 6px;font-size:16px}
.card p{margin:0;color:var(--muted);font-size:14.5px}
.snippet{margin:10px 0 0;border:1px solid var(--border);border-radius:10px;overflow:auto}
.snippet pre{margin:0;font:13px/1.6 ui-monospace,SFMono-Regular,Menlo,Consolas,monospace}
.snippet pre code.cl{padding:12px 14px}
.section-lead{color:var(--muted);margin:-4px 0 14px}
.langs{display:flex;flex-wrap:wrap;gap:6px;margin:0 0 12px}
.langs button{border:1px solid var(--border);border-radius:999px;padding:4px 11px;font:inherit;font-size:13px;background:var(--surface);color:var(--text);cursor:pointer}
.langs button:hover{border-color:var(--muted)}
.langs button[aria-pressed="true"]{background:var(--accent);border-color:var(--accent);color:#fff}
.example{border:1px solid var(--border);border-radius:var(--radius);overflow:hidden;background:var(--surface)}
.example pre{margin:0;font:13.5px/1.6 ui-monospace,SFMono-Regular,Menlo,Consolas,monospace}
.example pre code.cl{padding:14px 16px;min-height:330px}
.example textarea{display:none}
footer{color:var(--muted);font-size:13.5px;padding:40px 0 30px;text-align:center}
@media (max-width:720px){
.grid{grid-template-columns:minmax(0,1fr)}
.example pre code.cl{min-height:0}
.stats{grid-template-columns:1fr}
.msg.user{max-width:92%}
nav .hide-sm{display:none}
.messages{padding:12px;min-height:380px}
}
@media (max-width:380px){
nav .hide-xs{display:none}
}
</style>
</head>
<body>
<div class="wrap">
<header>
<a class="brand" href="./">
<svg width="30" height="30" viewBox="0 0 32 32" aria-hidden="true"><rect width="32" height="32" rx="7" fill="#11141a"/><path d="M9 11l-4 5 4 5M23 11l4 5-4 5" stroke="#ff7aa8" stroke-width="2.6" fill="none" stroke-linecap="round" stroke-linejoin="round"/><circle cx="16" cy="16" r="3.4" fill="#ffb86b"/></svg>
<span>codelight<b>.js</b></span>
</a>
<nav>
<button class="btn" id="theme" type="button" aria-label="Switch theme">◐ <span class="hide-sm" id="theme-label">Auto</span></button>
<a class="btn hide-xs" href="https://www.npmjs.com/package/codelight.js">npm</a>
<a class="btn primary" href="https://github.com/codelightjs/codelight.js">GitHub</a>
</nav>
</header>
<div class="hero">
<h1>Syntax highlighting that keeps up with <span>live code</span>.</h1>
<p class="lead">Very fast and lightweight. Each line is highlighted once, and only the line being written gets updated, so it stays fast even when the code is long. No flicker, no dependencies.</p>
</div>
<div class="chat">
<div class="bar">
<label>Reply
<select id="reply">
<option value="ts">TypeScript: retry a fetch</option>
<option value="py">Python: parse a CSV</option>
<option value="deploy">Bash + YAML: deploy</option>
<option value="web">HTML + CSS: a card</option>
</select>
</label>
<label>Speed
<input id="speed" type="range" min="1" max="10" value="5">
</label>
<span class="spacer"></span>
<button class="btn primary" id="play" type="button">▶ Replay</button>
</div>
<div class="messages" id="messages" aria-live="polite"></div>
<div class="stats">
<div class="stat win"><b id="s-cl">0</b><small>lines highlighted by codelight.js</small></div>
<div class="stat"><b id="s-naive">0</b><small>lines if every update re-highlighted the whole block</small></div>
<div class="stat"><b id="s-x">–</b><small>less work, and finished lines never change</small></div>
</div>
</div>
<section>
<h2>Use it</h2>
<div class="grid">
<div class="card">
<h3>Code already on the page</h3>
<p>Add two files and every <code><pre><code class="language-xxx"></code> block is highlighted. No build step. The code boxes on this page work this way.</p>
<div class="snippet"><pre><code class="language-html"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/codelight.js/build/styles/default.min.css">
<script src="https://cdn.jsdelivr.net/npm/codelight.js/build/codelight.min.js"></script>
<script>codelight.highlightAll();</script></code></pre></div>
</div>
<div class="card">
<h3>Code that's streaming in</h3>
<p>Mount a view once, then write each chunk as it arrives. Finished lines never change. The chat above works this way.</p>
<div class="snippet"><pre><code class="language-js">const view = codelight.mount(codeElement, { lang: "py" });
stream.on("data", (chunk) => view.write(chunk));</code></pre></div>
</div>
<div class="card">
<h3>React</h3>
<p><code>npm install codelight.js</code>, then pass the whole reply on every update. Only the new part is highlighted.</p>
<div class="snippet"><pre><code class="language-tsx">import { CodeLight } from "codelight.js/react";
import "codelight.js/styles/default.css";
<CodeLight code={partialCode} lang="ts" /></code></pre></div>
</div>
<div class="card">
<h3>Markdown replies</h3>
<p>Find code blocks in a reply that's still streaming, including a fence that hasn't closed yet.</p>
<div class="snippet"><pre><code class="language-js">import { splitFences } from "codelight.js";
for (const part of splitFences(replySoFar)) {
if (part.type === "code") views[i].set(part.code);
}</code></pre></div>
</div>
</div>
</section>
<section>
<h2>Languages</h2>
<p class="section-lead">19 languages, all in the one 8 KB file. Pick one to see it highlighted.</p>
<div class="langs" id="langs" role="toolbar" aria-label="Languages"></div>
<div class="example">
<div class="block-head"><span id="ex-name"></span><span id="ex-aliases"></span></div>
<pre><code id="ex-code"></code></pre>
<textarea data-lang="javascript">import { useState } from "react";
export function Counter({ start = 0 }) {
const [count, setCount] = useState(start);
// Each click adds one
return (
<button className="counter" onClick={() => setCount(count + 1)}>
Clicked {count} times
</button>
);
}</textarea>
<textarea data-lang="typescript">interface User {
id: number;
name: string;
email?: string;
}
/** Fetches a user, or null if there isn't one. */
export async function getUser(id: number): Promise<User | null> {
const res = await fetch(`/api/users/${id}`);
if (!res.ok) return null;
return (await res.json()) as User;
}</textarea>
<textarea data-lang="tsx">type Props = { items: string[]; onPick?: (item: string) => void };
export const List = ({ items, onPick }: Props) => (
<ul className="list">
{items.map((item) => (
<li key={item} onClick={() => onPick?.(item)}>
{item}
</li>
))}
</ul>
);</textarea>
<textarea data-lang="json">{
"name": "my-app",
"version": "1.4.0",
"private": true,
"scripts": {
"dev": "vite",
"build": "vite build"
},
"dependencies": { "codelight.js": "^1.0.0" },
"tags": ["demo", null, 42, false]
}</textarea>
<textarea data-lang="python">from dataclasses import dataclass
@dataclass
class Invoice:
"""An invoice with line items."""
customer: str
items: list[tuple[str, float]]
def total(self, tax: float = 0.18) -> float:
subtotal = sum(price for _, price in self.items)
return round(subtotal * (1 + tax), 2) # GST included
invoice = Invoice("Asha", [("Hosting", 499.0), ("Domain", 899.0)])
print(f"{invoice.customer} owes ₹{invoice.total():,.2f}")</textarea>
<textarea data-lang="bash">#!/usr/bin/env bash
set -euo pipefail
BACKUP_DIR="/var/backups/$(date +%F)"
mkdir -p "$BACKUP_DIR"
for db in users orders; do
echo "Backing up $db"
pg_dump --no-owner "$db" | gzip > "$BACKUP_DIR/$db.sql.gz"
done
echo "Done: ${BACKUP_DIR}" # keep 7 days</textarea>
<textarea data-lang="ruby">class Order < ApplicationRecord
belongs_to :customer
validates :total, numericality: { greater_than: 0 }
def paid?
status == :paid # set by the payment webhook
end
def self.recent(limit = 10)
order(created_at: :desc).limit(limit)
end
end</textarea>
<textarea data-lang="php"><?php
namespace App\Http;
final class Greeter
{
public function __construct(private string $name) {}
public function greet(int $times = 1): string
{
// Repeat the greeting
return str_repeat("Hello, {$this->name}! ", $times);
}
}</textarea>
<textarea data-lang="go">package main
import (
"fmt"
"net/http"
)
func handler(w http.ResponseWriter, r *http.Request) {
name := r.URL.Query().Get("name")
if name == "" {
name = "world"
}
fmt.Fprintf(w, "Hello, %s!", name)
}
func main() {
http.HandleFunc("/", handler)
http.ListenAndServe(":8080", nil)
}</textarea>
<textarea data-lang="rust">use std::collections::HashMap;
#[derive(Debug, Default)]
struct Inventory<'a> {
items: HashMap<&'a str, u32>,
}
impl<'a> Inventory<'a> {
fn add(&mut self, name: &'a str, qty: u32) {
*self.items.entry(name).or_insert(0) += qty;
}
}
fn main() {
let mut inv = Inventory::default();
inv.add("apple", 3);
println!("{:?}", inv);
}</textarea>
<textarea data-lang="java">import java.util.List;
public record Point(int x, int y) {
public double distance() {
return Math.sqrt(x * x + y * y);
}
@Override
public String toString() {
return "(" + x + ", " + y + ")";
}
public static void main(String[] args) {
List.of(new Point(3, 4)).forEach(System.out::println);
}
}</textarea>
<textarea data-lang="c">#include <stdio.h>
#include <string.h>
#define MAX_NAME 32
/* Reverses a string in place. */
void reverse(char *s) {
size_t n = strlen(s);
for (size_t i = 0; i < n / 2; i++) {
char t = s[i];
s[i] = s[n - 1 - i];
s[n - 1 - i] = t;
}
}
int main(void) {
char name[MAX_NAME] = "codelight";
reverse(name);
printf("%s\n", name);
return 0;
}</textarea>
<textarea data-lang="cpp">#include <iostream>
#include <vector>
template <typename T>
T sum(const std::vector<T>& values) {
T total{};
for (const auto& v : values) total += v;
return total;
}
int main() {
std::vector<int> nums{1, 2, 3, 4};
std::cout << "Sum: " << sum(nums) << std::endl;
return 0;
}</textarea>
<textarea data-lang="csharp">using System.Linq;
public record Product(string Name, decimal Price);
public static class Cart
{
// Ignores free items
public static decimal Total(IEnumerable<Product> items) =>
items.Where(p => p.Price > 0).Sum(p => p.Price);
public static string Label(Product p) => $"{p.Name}: {p.Price:C}";
}</textarea>
<textarea data-lang="sql">-- Top customers this year
SELECT c.name, COUNT(o.id) AS orders, SUM(o.total) AS revenue
FROM customers c
JOIN orders o ON o.customer_id = c.id
WHERE o.created_at >= '2026-01-01'
AND o.status <> 'cancelled'
GROUP BY c.name
HAVING SUM(o.total) > 1000
ORDER BY revenue DESC
LIMIT 10;</textarea>
<textarea data-lang="css">:root {
--brand: #6d28d9;
}
/* Primary button */
.button {
padding: 0.5rem 1rem;
border-radius: 8px;
background: var(--brand);
color: white;
transition: transform 150ms ease;
}
.button:hover {
transform: translateY(-1px);
}
@media (max-width: 600px) {
.button { width: 100%; }
}</textarea>
<textarea data-lang="yaml">name: CI
on:
push:
branches: [main]
jobs:
test:
runs-on: ubuntu-latest # Linux runner
strategy:
matrix:
node: [20, 22, 24]
steps:
- uses: actions/checkout@v5
- uses: actions/setup-node@v5
with:
node-version: ${{ matrix.node }}
- run: npm ci && npm test</textarea>
<textarea data-lang="xml"><!DOCTYPE html>
<html lang="en">
<head>
<title>Menu</title>
<style>
.title { font-family: system-ui; }
</style>
</head>
<body>
<!-- Today's special -->
<h1 class="title">Fish &amp; chips</h1>
<script>
document.querySelector(".title").textContent += "!";
</script>
</body>
</html></textarea>
<textarea data-lang="diff">--- a/src/config.ts
+++ b/src/config.ts
@@ -1,6 +1,6 @@
export const config = {
- retries: 3,
+ retries: 5,
timeout: 10_000,
- debug: true,
+ debug: false,
};</textarea>
</div>
</section>
<footer>
MIT licensed · Built by <a href="https://github.com/ckgiri">CK Giri</a> · <a href="https://github.com/codelightjs/codelight.js">Source on GitHub</a> · <a href="https://www.npmjs.com/package/codelight.js">npm</a>
</footer>
</div>
<!-- The replies the demo streams. Plain text, exactly as an LLM would send it. -->
<script type="text/plain" id="r-ts">
Here's a small helper that retries a request with exponential backoff:
```ts
type RetryOptions = { retries?: number; baseMs?: number };
/** Retries a fetch on network errors and 5xx responses. */
export async function fetchWithRetry(url: string, opts: RetryOptions = {}): Promise<Response> {
const { retries = 3, baseMs = 250 } = opts;
for (let attempt = 0; ; attempt++) {
try {
const res = await fetch(url);
if (res.status < 500 || attempt >= retries) return res;
} catch (err) {
if (attempt >= retries) throw err; // give up
}
const delay = baseMs * 2 ** attempt + Math.random() * 100;
await new Promise((resolve) => setTimeout(resolve, delay));
}
}
```
Use it like this:
```ts
const res = await fetchWithRetry("https://api.example.com/users", { retries: 5 });
console.log(await res.json());
```
The random **jitter** stops many clients retrying at exactly the same moment.
</script>
<script type="text/plain" id="r-py">
You can read the file with the standard library and total the amounts per customer:
```python
import csv
from collections import defaultdict
from decimal import Decimal
def totals(path: str) -> dict[str, Decimal]:
"""Sum the `amount` column for each customer."""
result: dict[str, Decimal] = defaultdict(Decimal)
with open(path, newline="", encoding="utf-8") as f:
for row in csv.DictReader(f):
if not row["amount"]: # skip blanks
continue
result[row["customer"]] += Decimal(row["amount"])
return dict(result)
if __name__ == "__main__":
for name, total in sorted(totals("orders.csv").items()):
print(f"{name:<20} {total:>10.2f}")
```
`Decimal` avoids the rounding errors you'd get with `float` for money.
</script>
<script type="text/plain" id="r-deploy">
Add a workflow that builds and deploys on every push to `main`:
```yaml
name: Deploy
on:
push:
branches: [main]
jobs:
deploy:
runs-on: ubuntu-latest
env:
NODE_ENV: production
steps:
- uses: actions/checkout@v5
- uses: actions/setup-node@v5
with:
node-version: 24
- run: npm ci && npm run build
- run: ./scripts/deploy.sh "$GITHUB_SHA"
```
And the deploy script it calls:
```bash
#!/usr/bin/env bash
set -euo pipefail
SHA="${1:?usage: deploy.sh <sha>}"
echo "Deploying ${SHA:0:7} to production"
rsync -az --delete dist/ deploy@app.example.com:/var/www/app/
ssh deploy@app.example.com "sudo systemctl reload nginx" # zero downtime
```
Remember to add the server's SSH key as a repository secret.
</script>
<script type="text/plain" id="r-web">
Here's a simple profile card:
```html
<article class="card">
<img src="avatar.png" alt="Asha Rao" width="64" height="64">
<h2>Asha Rao</h2>
<p>Platform engineer · Bengaluru</p>
<a class="button" href="/contact">Get in touch</a>
</article>
```
```css
.card {
--radius: 16px;
display: grid;
justify-items: center;
gap: 0.5rem;
padding: 1.5rem;
border-radius: var(--radius);
background: #ffffff;
box-shadow: 0 8px 24px rgb(0 0 0 / 12%);
}
.card img { border-radius: 50%; }
.button:hover {
background: #0969da;
color: white !important;
}
```
The card uses CSS grid, so everything stays centred without extra wrappers.
</script>
<script src="codelight.min.js"></script>
<script>
(() => {
const { mount, splitFences, listLanguages, createStream } = codelight;
const $ = (id) => document.getElementById(id);
const messages = $("messages");
const QUESTIONS = {
ts: "How do I retry a fetch request in TypeScript?",
py: "Sum a CSV of orders per customer in Python?",
deploy: "Deploy my Node app from GitHub Actions?",
web: "Make me a profile card in HTML and CSS.",
};
/* ── Theme toggle: auto → light → dark ── */
const modes = ["auto", "light", "dark"];
let mode = "auto";
try { mode = localStorage.getItem("cl-theme") || "auto"; } catch {}
const applyTheme = () => {
if (mode === "auto") document.documentElement.removeAttribute("data-theme");
else document.documentElement.setAttribute("data-theme", mode);
$("theme-label").textContent = mode[0].toUpperCase() + mode.slice(1);
};
$("theme").onclick = () => {
mode = modes[(modes.indexOf(mode) + 1) % modes.length];
try { localStorage.setItem("cl-theme", mode); } catch {}
applyTheme();
};
applyTheme();
/* ── Static snippets and the language list, highlighted by codelight itself ── */
codelight.highlightAll(document.querySelector("section"));
/* ── Language examples ── */
const NAMES = {
javascript: ["JavaScript", "js, jsx, mjs"], typescript: ["TypeScript", "ts, mts"], tsx: ["TSX", ""],
json: ["JSON", "jsonc, json5"], python: ["Python", "py"], bash: ["Bash", "sh, shell, zsh, console"],
ruby: ["Ruby", "rb"], php: ["PHP", ""], go: ["Go", "golang"], rust: ["Rust", "rs"], java: ["Java", ""],
c: ["C", "h"], cpp: ["C++", "c++, cc, hpp"], csharp: ["C#", "cs, c#"], sql: ["SQL", "postgres, mysql, sqlite"],
css: ["CSS", "scss, less"], yaml: ["YAML", "yml"], xml: ["HTML / XML", "html, svg, vue"], diff: ["Diff", "patch"],
};
const samples = {};
for (const t of document.querySelectorAll(".example textarea")) samples[t.dataset.lang] = t.value;
const langs = listLanguages().filter((l) => samples[l]);
const showLanguage = (lang) => {
const code = $("ex-code");
code.textContent = samples[lang];
codelight.highlightElement(code, lang);
$("ex-name").textContent = NAMES[lang]?.[0] ?? lang;
$("ex-aliases").textContent = NAMES[lang]?.[1] ? `lang="${lang}" · also ${NAMES[lang][1]}` : `lang="${lang}"`;
for (const b of $("langs").children) b.setAttribute("aria-pressed", String(b.dataset.lang === lang));
};
$("langs").innerHTML = langs.map((l) => `<button type="button" data-lang="${l}" aria-pressed="false">${NAMES[l]?.[0] ?? l}</button>`).join("");
$("langs").onclick = (e) => { const b = e.target.closest("button"); if (b) showLanguage(b.dataset.lang); };
showLanguage("python");
/* ── A tiny Markdown renderer for the text between code blocks ── */
const esc = (s) => s.replace(/[&<>"]/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """ })[c]);
const inline = (s) => esc(s).replace(/`([^`]+)`/g, "<code>$1</code>").replace(/\*\*([^*]+)\*\*/g, "<strong>$1</strong>");
function renderText(text) {
return text.trim().split(/\n{2,}/).filter(Boolean).map((para) => {
const lines = para.split("\n");
if (lines.every((l) => /^[-*] /.test(l))) return `<ul>${lines.map((l) => `<li>${inline(l.slice(2))}</li>`).join("")}</ul>`;
return `<p>${inline(para).replace(/\n/g, "<br>")}</p>`;
}).join("");
}
/* ── Streaming ── */
let timer = 0;
let run = 0;
function play() {
clearTimeout(timer);
const id = ++run;
const key = $("reply").value;
const reply = $("r-" + key).textContent.replace(/^\n/, "");
messages.innerHTML = `<div class="msg user"></div><div class="msg bot"></div>`;
messages.firstChild.textContent = QUESTIONS[key];
const bot = messages.lastChild;
// Each code block gets its own element and view, created once and then only written to.
const parts = []; // { el, view?, lang }
const caret = document.createElement("span");
caret.className = "caret";
let sent = 0;
let clLines = 0;
let naiveLines = 0;
const counters = new Map(); // block index -> stream used only for counting the work
function update(text, done) {
const segments = splitFences(text);
let codeIndex = 0;
segments.forEach((seg, i) => {
let part = parts[i];
if (!part || part.type !== seg.type) {
for (const old of parts.splice(i)) old.el.remove();
part = { type: seg.type, el: document.createElement("div") };
if (seg.type === "code") {
part.el.className = "block";
part.el.innerHTML = `<div class="block-head"><span></span><span>streaming…</span></div><pre><code></code></pre>`;
}
bot.append(part.el);
parts[i] = part;
}
if (seg.type === "text") {
part.el.innerHTML = renderText(seg.text);
return;
}
// A code block: create the view when the language is known, then only ever write to it.
if (!part.view || part.lang !== seg.lang) {
part.lang = seg.lang;
part.view = mount(part.el.querySelector("code"), { lang: seg.lang });
part.el.querySelector(".block-head span").textContent = seg.lang || "code";
counters.set(codeIndex, { stream: createStream(seg.lang), shown: "" });
}
part.view.set(seg.code);
part.el.querySelector(".block-head span:last-child").textContent = seg.closed || done ? "" : "streaming…";
// Count the work: codelight tokenizes the new finished lines plus the line being written;
// re-highlighting on every update would tokenize every line of the block again.
const c = counters.get(codeIndex);
if (seg.code !== c.shown && seg.code.startsWith(c.shown)) {
const u = c.stream.push(seg.code.slice(c.shown.length));
clLines += u.lines.length + 1;
naiveLines += seg.code.split("\n").length;
c.shown = seg.code;
}
codeIndex++;
});
for (const old of parts.splice(segments.length)) old.el.remove();
const last = parts[parts.length - 1];
if (!done && last) (last.type === "code" ? last.el.querySelector("code") : last.el.lastElementChild || last.el).append(caret);
else caret.remove();
$("s-cl").textContent = clLines.toLocaleString();
$("s-naive").textContent = naiveLines.toLocaleString();
$("s-x").textContent = clLines ? `${(naiveLines / clLines).toFixed(1)}×` : "–";
}
function tick() {
if (id !== run) return;
const speed = Number($("speed").value);
sent = Math.min(reply.length, sent + 1 + Math.floor(Math.random() * (2 + speed)));
update(reply.slice(0, sent), sent >= reply.length);
const nearBottom = messages.scrollHeight - messages.scrollTop - messages.clientHeight < 120;
if (nearBottom) messages.scrollTop = messages.scrollHeight;
if (sent < reply.length) timer = setTimeout(tick, 70 - speed * 6);
}
tick();
}
$("play").onclick = play;
$("reply").onchange = play;
play();
})();
</script>
</body>
</html>