The best way to control Claude Code, Codex and more from any computer or phone

main
tsx 401 lines 13.9 KB
Raw
1 /** @jsxRuntime automatic */
2 /** @jsxImportSource @alchemy.run/sigil */
3 /**
4 * The yantra logo, rasterized at runtime. Geometry mirrors
5 * website/src/brand/yantra.ts (the brand's source of truth): a downward
6 * equilateral triangle inscribed in a circle, bindu at the center. The
7 * shapes are signed distance functions in the brand's 24-unit viewBox,
8 * sampled at the on-screen positions of a braille dot grid (2x4 dots per
9 * cell), so stroke weight scales with the logo exactly as the SVG does.
10 */
11 import { useMemo } from "@alchemy.run/sigil/react";
12 import type { JSX } from "react";
13 import { theme } from "../../../Util/Theme.ts";
14 import { Box, Text } from "../ui/index.ts";
15
16 const VIEWBOX = 24;
17 const CENTER = 12;
18 const CIRCLE_R = 9.5;
19 const BINDU_R = 1.3;
20 const STROKE_W = 1.5;
21 // Strokes scale with the logo, but are snapped to whole braille dots so every
22 // line renders at an even weight, and floored so small logos never break up.
23 const MIN_STROKE_DOTS = 2;
24 // Supersamples per braille dot along each axis; a dot is raised when at least
25 // half of its cell is covered.
26 const SAMPLES = 4;
27 const COVERAGE_THRESHOLD = 0.5;
28 // Terminals space braille dots evenly within a cell, but leave extra leading
29 // between cells: a cell is 2 dot pitches wide and ~4.25 tall (3 pitches between
30 // its 4 rows, plus a 1.25-pitch gap to the next cell). Sampling at those real
31 // positions keeps circles round on screen instead of ~6% tall and lumpy at
32 // every cell seam.
33 const CELL_W_PITCHES = 2;
34 const CELL_H_PITCHES = 4.25;
35
36 type Point = readonly [number, number];
37
38 /**
39 * Where each braille dot actually lands, in viewBox units, addressed by global
40 * dot column `i` (0..cols*2) and dot row `j` (0..rows*4). The logo is centered
41 * on the grid's midpoint, which is always a point of symmetry (a cell center or
42 * the middle of an inter-cell gap), so symmetric shapes rasterize
43 * symmetrically.
44 */
45 interface DotGrid {
46 cols: number;
47 rows: number;
48 /** viewBox units per dot pitch */
49 scale: number;
50 dot: (i: number, j: number) => Point;
51 }
52
53 const makeGrid = (cols: number): DotGrid => {
54 const width = cols * CELL_W_PITCHES; // logo width in dot pitches
55 const rows = Math.ceil(width / CELL_H_PITCHES);
56 const scale = VIEWBOX / width;
57 const offsetY = (rows * CELL_H_PITCHES - width) / 2;
58 const padY = (CELL_H_PITCHES - 4) / 2;
59 return {
60 cols,
61 rows,
62 scale,
63 dot: (i, j) => [
64 (Math.floor(i / 2) * CELL_W_PITCHES + (i % 2) + 0.5) * scale,
65 (Math.floor(j / 4) * CELL_H_PITCHES + padY + (j % 4) + 0.5 - offsetY) * scale,
66 ],
67 };
68 };
69
70 /** Per-dot coverage in [0, 1] for one shape on one grid. */
71 type Coverage = (i: number, j: number) => number;
72
73 /** A shape that knows how to rasterize itself onto a dot grid. */
74 interface Shape {
75 color: string;
76 compile: (grid: DotGrid) => Coverage;
77 }
78
79 /**
80 * Supersample a signed distance field over each dot's footprint (one pitch
81 * square). Best for thin diagonal strokes.
82 */
83 const areaSampled =
84 (sd: (x: number, y: number) => number) =>
85 (grid: DotGrid): Coverage => {
86 const step = grid.scale / SAMPLES;
87 return (i, j) => {
88 const [x, y] = grid.dot(i, j);
89 const x0 = x - grid.scale / 2;
90 const y0 = y - grid.scale / 2;
91 let hits = 0;
92 for (let b = 0; b < SAMPLES; b++) {
93 for (let a = 0; a < SAMPLES; a++) {
94 if (sd(x0 + (a + 0.5) * step, y0 + (b + 0.5) * step) <= 0) hits++;
95 }
96 }
97 return hits / (SAMPLES * SAMPLES);
98 };
99 };
100
101 const sdSegment = (px: number, py: number, [ax, ay]: Point, [bx, by]: Point) => {
102 const abx = bx - ax;
103 const aby = by - ay;
104 const apx = px - ax;
105 const apy = py - ay;
106 const t = Math.max(0, Math.min(1, (apx * abx + apy * aby) / (abx * abx + aby * aby)));
107 return Math.hypot(apx - t * abx, apy - t * aby);
108 };
109
110 /**
111 * Pull `inner` (per-line innermost dot index, measured outward from the
112 * center) toward the center until it moves at most one dot between adjacent
113 * lines. Each change only thickens the stroke, and the fixpoint is
114 * order-independent, so symmetry is preserved.
115 */
116 const smoothInnerEdge = (inner: Array<number | undefined>) => {
117 for (let changed = true; changed;) {
118 changed = false;
119 for (let k = 0; k < inner.length; k++) {
120 const q = inner[k];
121 if (q === undefined) continue;
122 for (const n of [inner[k - 1], inner[k + 1]]) {
123 if (n !== undefined && q > n + 1) {
124 inner[k] = n + 1;
125 changed = true;
126 }
127 }
128 }
129 }
130 };
131
132 /**
133 * Stroked circle outline. Rasterizing the annulus directly (by area or by dot
134 * center) rounds the outer and inner edges independently, so where their
135 * stair-steps fall out of phase the stroke flickers a dot thicker and thinner
136 * line to line. Instead, only the outer edge is snapped to the grid and the
137 * stroke is filled inward from it by a whole-dot count derived from the true
138 * thickness across that row (on the sides) or column (on the caps); that count
139 * changes monotonically around the circle. The inner edge is then smoothed so
140 * it never jumps two dots where the outer edge and the count step together.
141 */
142 const ring = (cx: number, cy: number, r: number, strokeW: number, color: string): Shape => ({
143 color,
144 compile: (grid) => {
145 const W = grid.cols * 2;
146 const H = grid.rows * 4;
147 const ro = r + strokeW / 2;
148 const ri = r - strokeW / 2;
149 const at = (i: number, j: number): Point => {
150 const [x, y] = grid.dot(i, j);
151 return [x - cx, y - cy];
152 };
153 /** Outer edge and whole-dot stroke count across a chord at `offset`. */
154 const chord = (offset: number) => {
155 const outer = Math.sqrt(ro * ro - offset * offset);
156 const inner = Math.abs(offset) < ri ? Math.sqrt(ri * ri - offset * offset) : 0;
157 return { outer, count: Math.max(1, Math.round((outer - inner) / grid.scale)) };
158 };
159 const on = Array.from({ length: H }, () => new Uint8Array(W));
160
161 // sides (|x| >= |y|): per dot row, dots are indexed n = 0, 1, … outward
162 // from the vertical center line
163 const rowEdge: Array<number | undefined> = [];
164 const rowInner: Array<number | undefined> = [];
165 for (let j = 0; j < H; j++) {
166 const [, y] = at(0, j);
167 if (Math.abs(y) >= ro) continue;
168 const { outer, count } = chord(y);
169 rowEdge[j] = Math.floor(outer / grid.scale - 0.5);
170 rowInner[j] = rowEdge[j]! - count + 1;
171 }
172 // only rows whose inner edge is still on the side (past 45° the caps own
173 // it) take part in smoothing, or the caps' short chords would drag it in
174 const sideInner = rowInner.map((q, j) =>
175 q !== undefined && (q + 0.5) * grid.scale >= Math.abs(at(0, j)[1]) ? q : undefined,
176 );
177 smoothInnerEdge(sideInner);
178 sideInner.forEach((q, j) => q !== undefined && (rowInner[j] = q));
179 for (let j = 0; j < H; j++) {
180 const edge = rowEdge[j];
181 if (edge === undefined) continue;
182 const [, y] = at(0, j);
183 for (let i = 0; i < W; i++) {
184 const [x] = at(i, j);
185 if (Math.abs(x) < Math.abs(y)) continue;
186 const n = Math.round(Math.abs(x) / grid.scale - 0.5);
187 if (n <= edge && n >= rowInner[j]!) on[j][i] = 1;
188 }
189 }
190
191 // caps (|y| > |x|): per dot column, dots are indexed k = 0, 1, … inward
192 // from the top. Rows are unevenly spaced (cell gaps), so walk the actual
193 // dots; the bottom cap mirrors the top since the grid is symmetric.
194 const colEdge: Array<number | undefined> = [];
195 const colInner: Array<number | undefined> = [];
196 for (let i = 0; i < W; i++) {
197 const [x] = at(i, 0);
198 if (Math.abs(x) >= ro) continue;
199 const { outer, count } = chord(x);
200 let top = 0;
201 while (top < H / 2 && Math.abs(at(i, top)[1]) > outer) top++;
202 colEdge[i] = top;
203 colInner[i] = top + count - 1;
204 }
205 // smooth in "distance from center" terms, where inner edges move outward
206 const half = H / 2;
207 const fromCenter = colInner.map((k) => (k === undefined ? undefined : half - 1 - k));
208 const capInner = fromCenter.map((q, i) =>
209 q !== undefined && Math.abs(at(i, half - 1 - q)[1]) > Math.abs(at(i, 0)[0]) ? q : undefined,
210 );
211 smoothInnerEdge(capInner);
212 capInner.forEach((q, i) => q !== undefined && (fromCenter[i] = q));
213 for (let i = 0; i < W; i++) {
214 const top = colEdge[i];
215 if (top === undefined) continue;
216 const innerK = half - 1 - fromCenter[i]!;
217 const [x] = at(i, 0);
218 for (let k = top; k <= innerK && k < half; k++) {
219 for (const j of [k, H - 1 - k]) {
220 if (Math.abs(at(i, j)[1]) > Math.abs(x)) on[j][i] = 1;
221 }
222 }
223 }
224 return (i, j) => on[j][i];
225 },
226 });
227
228 /** Stroked closed polygon with round joins (stroke-linejoin="round"). */
229 const polygon = (pts: ReadonlyArray<Point>, strokeW: number, color: string): Shape => ({
230 color,
231 compile: areaSampled((x, y) => {
232 let d = Infinity;
233 for (let k = 0; k < pts.length; k++) {
234 d = Math.min(d, sdSegment(x, y, pts[k], pts[(k + 1) % pts.length]));
235 }
236 return d - strokeW / 2;
237 }),
238 });
239
240 /**
241 * Filled circle, sampled at dot centers (area sampling leaves bumps on solid
242 * fills). Some radii leave a narrow nub on the cap row or column, so the radius
243 * is nudged by up to half a dot pitch to the closest one whose caps are at
244 * least 40% of the widest span on both axes.
245 */
246 const disc = (cx: number, cy: number, r: number, color: string): Shape => ({
247 color,
248 compile: (grid) => {
249 const W = grid.cols * 2;
250 const H = grid.rows * 4;
251 const inside = (radius: number) => (i: number, j: number) => {
252 const [x, y] = grid.dot(i, j);
253 return Math.hypot(x - cx, y - cy) <= radius;
254 };
255 const capsOk = (radius: number) => {
256 const test = inside(radius);
257 const rowW = new Map<number, number>();
258 const colH = new Map<number, number>();
259 for (let j = 0; j < H; j++) {
260 for (let i = 0; i < W; i++) {
261 if (!test(i, j)) continue;
262 rowW.set(j, (rowW.get(j) ?? 0) + 1);
263 colH.set(i, (colH.get(i) ?? 0) + 1);
264 }
265 }
266 const capRatio = (spans: Map<number, number>) => {
267 if (spans.size === 0) return 0;
268 const keys = [...spans.keys()].sort((a, b) => a - b);
269 const widest = Math.max(...spans.values());
270 return Math.min(spans.get(keys[0])!, spans.get(keys[keys.length - 1])!) / widest;
271 };
272 return capRatio(rowW) >= 0.4 && capRatio(colH) >= 0.4;
273 };
274 const step = grid.scale * 0.05;
275 let radius = r;
276 for (let k = 0; k <= 9; k++) {
277 if (capsOk(r - k * step)) {
278 radius = r - k * step;
279 break;
280 }
281 if (capsOk(r + k * step)) {
282 radius = r + k * step;
283 break;
284 }
285 }
286 const test = inside(radius);
287 return (i, j) => (test(i, j) ? 1 : 0);
288 },
289 });
290
291 /**
292 * The yantra, mirroring yantra.ts: the triangle's circumradius is pulled in by
293 * a quarter stroke so its tips merge into the ring.
294 */
295 const yantra = (strokeW: number): Shape[] => {
296 const triR = CIRCLE_R - strokeW / 4;
297 const dx = triR * Math.cos(Math.PI / 6);
298 const topY = CENTER - triR * Math.sin(Math.PI / 6);
299 return [
300 ring(CENTER, CENTER, CIRCLE_R, strokeW, theme.color.accent),
301 polygon(
302 [
303 [CENTER, CENTER + triR],
304 [CENTER - dx, topY],
305 [CENTER + dx, topY],
306 ],
307 strokeW,
308 theme.color.accent,
309 ),
310 disc(CENTER, CENTER, BINDU_R, theme.color.brand),
311 ];
312 };
313
314 // braille dot bit per (row 0-3, column 0-1) subpixel
315 const BRAILLE_BITS = [
316 [0x01, 0x08],
317 [0x02, 0x10],
318 [0x04, 0x20],
319 [0x40, 0x80],
320 ] as const;
321
322 interface LogoRun {
323 text: string;
324 color?: string;
325 }
326
327 const rasterizeLogo = (cols: number): LogoRun[][] => {
328 const grid = makeGrid(cols);
329 const strokeW = Math.max(MIN_STROKE_DOTS, Math.round(STROKE_W / grid.scale)) * grid.scale;
330 const layers = yantra(strokeW).map((shape) => ({
331 color: shape.color,
332 coverage: shape.compile(grid),
333 }));
334
335 const lines: LogoRun[][] = [];
336 for (let r = 0; r < grid.rows; r++) {
337 const runs: LogoRun[] = [];
338 const push = (text: string, color?: string) => {
339 const last = runs[runs.length - 1];
340 if (last && last.color === color) last.text += text;
341 else runs.push({ text, color });
342 };
343 for (let c = 0; c < cols; c++) {
344 let bits = 0;
345 // the cell's color is whichever shape covers the most of its raised dots
346 const weight = new Map<string, number>();
347 for (let sy = 0; sy < 4; sy++) {
348 for (let sx = 0; sx < 2; sx++) {
349 let union = 0;
350 for (const layer of layers) {
351 const cov = layer.coverage(c * 2 + sx, r * 4 + sy);
352 if (cov === 0) continue;
353 union = Math.max(union, cov);
354 weight.set(layer.color, (weight.get(layer.color) ?? 0) + cov);
355 }
356 if (union >= COVERAGE_THRESHOLD) bits |= BRAILLE_BITS[sy][sx];
357 }
358 }
359 if (bits === 0) push(" ");
360 else {
361 let color: string | undefined;
362 let best = 0;
363 for (const [k, w] of weight) if (w > best) [color, best] = [k, w];
364 push(String.fromCharCode(0x2800 + bits), color);
365 }
366 }
367 // drop trailing whitespace runs
368 while (runs.length > 0) {
369 const last = runs[runs.length - 1];
370 if (last.color !== undefined || last.text.trim() !== "") break;
371 runs.pop();
372 }
373 lines.push(runs);
374 }
375 while (lines.length > 0 && lines[0].length === 0) lines.shift();
376 while (lines.length > 0 && lines[lines.length - 1].length === 0) lines.pop();
377 return lines;
378 };
379
380 // Braille rasterization is mojibake on non-Unicode terminals — the help
381 // formatter skips mounting the logo entirely when Unicode is unavailable.
382 type LogoProps = { cols: number };
383
384 export function Logo({ cols }: LogoProps): JSX.Element | null {
385 const lines = useMemo(() => rasterizeLogo(cols), [cols]);
386 return (
387 <Box flexDirection="column" flexShrink={0}>
388 {lines.map((runs, i) => (
389 <Text key={i}>
390 {runs.length === 0
391 ? " "
392 : runs.map((run, j) => (
393 <Text key={j} color={run.color}>
394 {run.text}
395 </Text>
396 ))}
397 </Text>
398 ))}
399 </Box>
400 );
401 }