@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 435 lines 15.2 KB
Raw
1 import {
2 ExpressiveCodeTheme,
3 type AnnotationRenderOptions,
4 type ExpressiveCodePlugin,
5 } from "@astrojs/starlight/expressive-code";
6
7 /**
8 * Alchemy "walnut sunrise" Expressive Code theme.
9 *
10 * Dark walnut bg (#2a2620) + sunrise syntax tokens that match the design
11 * system's `--alc-code-*` variables. Designed for legibility on cream
12 * parchment pages where every other surface is light.
13 */
14 export const alchemyWalnutTheme = new ExpressiveCodeTheme({
15 name: "alchemy-walnut-sunrise",
16 type: "dark",
17 semanticHighlighting: true,
18 colors: {
19 "editor.background": "#2a2620",
20 "editor.foreground": "#faf5e3",
21 "editor.lineHighlightBackground": "#36302280",
22 "editor.selectionBackground": "#5c7a3e66",
23 "editorLineNumber.foreground": "#85714f",
24 "editorLineNumber.activeForeground": "#faf5e3",
25 "editorIndentGuide.background": "#4e402c",
26 "editorIndentGuide.activeBackground": "#68573c",
27 "editorBracketMatch.background": "#5c7a3e33",
28 "editorBracketMatch.border": "#5c7a3e",
29 "editorWidget.background": "#363022",
30 "editorWidget.border": "#4e402c",
31 "editorHoverWidget.background": "#363022",
32 "editorHoverWidget.border": "#4e402c",
33 "editorGroupHeader.tabsBackground": "#1a1813",
34 "tab.activeBackground": "#2a2620",
35 "tab.inactiveBackground": "#1a1813",
36 "tab.activeForeground": "#faf5e3",
37 "tab.inactiveForeground": "#a89572",
38 "tab.border": "#4e402c",
39 focusBorder: "#5c7a3e",
40 "scrollbarSlider.background": "#4e402c80",
41 "scrollbarSlider.hoverBackground": "#68573c80",
42 "scrollbarSlider.activeBackground": "#85714f80",
43 "diffEditor.insertedTextBackground": "#5c7a3e26",
44 "diffEditor.removedTextBackground": "#b3462e26",
45 },
46 tokenColors: [
47 {
48 scope: ["comment", "punctuation.definition.comment", "string.comment"],
49 settings: { foreground: "#b3a27a", fontStyle: "italic" },
50 },
51 {
52 scope: [
53 "keyword",
54 "storage",
55 "storage.type",
56 "storage.modifier",
57 "keyword.control",
58 "keyword.operator.new",
59 "keyword.operator.expression",
60 "keyword.other",
61 ],
62 settings: { foreground: "#d4f26a" },
63 },
64 {
65 scope: ["keyword.operator", "punctuation.separator", "punctuation.terminator"],
66 settings: { foreground: "#c7b795" },
67 },
68 {
69 scope: ["string", "string.quoted", "punctuation.definition.string"],
70 settings: { foreground: "#ffe38a" },
71 },
72 {
73 scope: ["string.template", "punctuation.definition.template-expression"],
74 settings: { foreground: "#ffe38a" },
75 },
76 {
77 scope: ["constant.numeric", "constant.language", "constant.character"],
78 settings: { foreground: "#ff9a6b" },
79 },
80 {
81 scope: ["constant.language.boolean", "constant.language.null", "constant.language.undefined"],
82 settings: { foreground: "#ff9a6b" },
83 },
84 {
85 scope: [
86 "entity.name.function",
87 "support.function",
88 "meta.function-call entity.name.function",
89 "meta.function-call.method entity.name.function",
90 "variable.function",
91 "meta.definition.method entity.name.function",
92 ],
93 settings: { foreground: "#7ddfff" },
94 },
95 {
96 scope: [
97 "entity.name.type",
98 "entity.name.class",
99 "entity.name.interface",
100 "entity.name.namespace",
101 "support.type",
102 "support.class",
103 "support.other.namespace",
104 "support.module",
105 "meta.type",
106 ],
107 settings: { foreground: "#7ddfff" },
108 },
109 {
110 scope: [
111 "variable.other.object",
112 "variable.other.readwrite.alias",
113 "meta.import variable.other.readwrite",
114 "meta.export variable.other.readwrite",
115 "meta.object-literal.key support.type.object",
116 ],
117 settings: { foreground: "#7ddfff" },
118 },
119 {
120 scope: ["entity.name.tag", "meta.tag entity.name.tag"],
121 settings: { foreground: "#ffb968" },
122 },
123 {
124 scope: ["entity.other.attribute-name"],
125 settings: { foreground: "#d4f26a", fontStyle: "italic" },
126 },
127 {
128 scope: [
129 "variable",
130 "variable.other",
131 "variable.parameter",
132 "meta.definition.variable variable.other",
133 ],
134 settings: { foreground: "#faf5e3" },
135 },
136 {
137 scope: ["variable.other.constant"],
138 settings: { foreground: "#7ddfff" },
139 },
140 {
141 scope: ["variable.other.enummember"],
142 settings: { foreground: "#ff9a6b" },
143 },
144 {
145 scope: ["variable.other.property", "meta.object.member"],
146 settings: { foreground: "#faf5e3" },
147 },
148 {
149 scope: ["support.variable", "support.constant"],
150 settings: { foreground: "#7ddfff" },
151 },
152 {
153 scope: ["punctuation.section.embedded", "meta.embedded"],
154 settings: { foreground: "#faf5e3" },
155 },
156 {
157 scope: ["markup.heading", "markup.bold"],
158 settings: { foreground: "#faf5e3", fontStyle: "bold" },
159 },
160 {
161 scope: ["markup.italic"],
162 settings: { foreground: "#faf5e3", fontStyle: "italic" },
163 },
164 {
165 scope: ["markup.inserted", "markup.inserted.diff"],
166 settings: { foreground: "#8fb15e" },
167 },
168 {
169 scope: ["markup.deleted", "markup.deleted.diff"],
170 settings: { foreground: "#e07a5f" },
171 },
172 {
173 scope: ["invalid", "invalid.illegal"],
174 settings: { foreground: "#e07a5f" },
175 },
176 ],
177 });
178
179 import { InlineStyleAnnotation } from "@astrojs/starlight/expressive-code";
180
181 const TARGET_LANGS = new Set(["ts", "tsx", "typescript", "js", "jsx", "javascript", "mts", "cts"]);
182
183 const CAP_IDENT_RE = /\b[A-Z][A-Za-z0-9_]*\b/g;
184
185 const CYAN = "#7ddfff";
186 const STRING_COLOR = "#ffe38a";
187 const COMMENT_COLOR = "#b3a27a";
188
189 const eq = (a: string, b: string) => (a || "").toLowerCase() === b.toLowerCase();
190
191 /**
192 * Expressive Code plugin that paints every bare capitalized identifier
193 * in TS/JS code blocks with the "type cyan" used by the marketing
194 * highlighter (`src/components/marketing/highlightTS.ts`).
195 *
196 * Why: the TextMate TS grammar shipped with shiki does NOT tokenize
197 * namespace references in expression position — `Alchemy` and `Effect`
198 * inside `Alchemy.Stack(...)` and `Effect.gen(...)` come out as plain
199 * untokenized text and fall back to the editor foreground. The
200 * marketing landing page colors every capitalized identifier cyan,
201 * giving snippets a distinct "type-y" rhythm. This plugin re-applies
202 * that same rule to docs code blocks so syntax matches across the
203 * whole site.
204 *
205 * The plugin runs AFTER syntax highlighting (which adds its own
206 * `InlineStyleAnnotation`s with the walnut-sunrise colors), and skips
207 * matches that overlap an existing string or comment annotation so
208 * we don't recolor things like `"MyApp"` inside a string literal.
209 */
210 export function capitalizedIdentifierColor(): ExpressiveCodePlugin {
211 return {
212 name: "capitalized-identifier-color",
213 hooks: {
214 postprocessAnalyzedCode({ codeBlock }) {
215 if (!TARGET_LANGS.has(codeBlock.language)) return;
216
217 for (const line of codeBlock.getLines()) {
218 // Snapshot column ranges that already belong to strings or
219 // comments — we don't want to recolor characters inside them
220 // (e.g. the `MyApp` in `Alchemy.Stack("MyApp", ...)`).
221 const skipRanges = [];
222 for (const ann of line.getAnnotations()) {
223 if (!ann.inlineRange) continue;
224 // @ts-expect-error verify
225 const c = ann.color;
226 if (eq(c, STRING_COLOR) || eq(c, COMMENT_COLOR)) {
227 skipRanges.push(ann.inlineRange);
228 }
229 }
230
231 const text = line.text;
232 CAP_IDENT_RE.lastIndex = 0;
233 let m;
234 while ((m = CAP_IDENT_RE.exec(text)) !== null) {
235 const columnStart = m.index;
236 const columnEnd = columnStart + m[0].length;
237 const overlapsSkip = skipRanges.some(
238 (r) => columnStart < r.columnEnd && columnEnd > r.columnStart,
239 );
240 if (overlapsSkip) continue;
241
242 line.addAnnotation(
243 new InlineStyleAnnotation({
244 color: CYAN,
245 inlineRange: { columnStart, columnEnd },
246 // `normal` phase: runs after syntax highlighting
247 // (`earliest`), so the cyan wraps and overrides any
248 // walnut-sunrise color the tokenizer applied.
249 renderPhase: "normal",
250 }),
251 );
252 }
253 }
254 },
255 },
256 };
257 }
258
259 import { ExpressiveCodeAnnotation } from "@astrojs/starlight/expressive-code";
260 import { getClassNames, h } from "@astrojs/starlight/expressive-code/hast";
261
262 /** Matches `// @error: <text>`, tolerating a leading diff marker. */
263 const ERROR_COMMENT = /^(?:[+-](?=[\s/]))?\s*\/\/ @error: ?(.*)$/;
264
265 /** Extracts an optional `ts(NNNN)` code from the start of the message. */
266 const TS_CODE = /^ts\((\d+)\):?\s*/;
267
268 /** The line's token container (`.code` child), or the node itself. */
269 function codeContainer(node: any) {
270 return (
271 node.children?.find((c: any) => c.type === "element" && getClassNames(c).includes("code")) ??
272 node
273 );
274 }
275
276 class ErrorUnderlineAnnotation extends ExpressiveCodeAnnotation {
277 render({ nodesToTransform }: AnnotationRenderOptions) {
278 return nodesToTransform.map((node) => {
279 if (node.type !== "element") return node;
280 // Wrap the line's tokens in a squiggle span rather than classing the
281 // container: the error box is appended to the same container below,
282 // and `text-decoration` propagates to descendants (it can't be
283 // cancelled from inside), so the box must be a sibling of the
284 // underlined span, not its child.
285 const code = codeContainer(node);
286 code.children = [h("span.twoslash.twoslash-error-underline", code.children ?? [])];
287 return node;
288 });
289 }
290 }
291
292 class ErrorBoxAnnotation extends ExpressiveCodeAnnotation {
293 title?: string;
294 message: string;
295
296 constructor(title: string | undefined, message: string) {
297 super({ renderPhase: "latest" });
298 this.title = title;
299 this.message = message;
300 }
301 render({ nodesToTransform }: AnnotationRenderOptions) {
302 return nodesToTransform.map((node) => {
303 if (node.type !== "element") return node;
304 // Append inside `.code` (a block container): a block-level flex box
305 // after inline token content renders on its own line below the code,
306 // exactly like twoslash's markup did. Appending to the `.ec-line`
307 // instead puts the box on the same flex row as the code.
308 codeContainer(node).children.push(
309 h("div.twoslash-error-box.twoslash-error-level-error", [
310 h("span.twoslash-error-box-icon"),
311 h("span.twoslash-error-box-content", [
312 ...(this.title ? [h("span.twoslash-error-box-content-title", this.title)] : []),
313 h("span.twoslash-error-box-content-message", this.message),
314 ]),
315 ]),
316 );
317 return node;
318 });
319 }
320 }
321
322 /**
323 * Compiler-free type-error annotations for code blocks.
324 *
325 * Replaces expressive-code-twoslash's error rendering (the part of twoslash
326 * we actually rely on) without spinning up a TypeScript program per block.
327 * Docs author errors as plain comments inside any fenced code block, so the
328 * MDX source stays readable as code — agents ingesting the raw markdown see
329 * a normal comment stating that (and why) the code fails to compile:
330 *
331 * ```typescript
332 * const providers: Layer<Providers> = Layer.empty;
333 * // @error: ts(2322) Type 'Layer<never, never, never>' is not assignable
334 * // @error: to type 'Layer<NoInfer<Providers>, never, StackServices>'.
335 * ```
336 *
337 * Rules:
338 * - A `// @error:` comment group annotates the nearest preceding code line:
339 * that line gets a red squiggle and the error box renders directly below
340 * it (exactly where the comment sits in the source).
341 * - Consecutive `// @error:` lines merge into one message. Line breaks
342 * collapse when the box renders (white-space: normal), so wrapping long
343 * messages across several comment lines is purely cosmetic in the source.
344 * - A leading `ts(NNNN)` on the first line becomes the box title
345 * ("Error ts(NNNN) ― "), matching the twoslash UI.
346 * - Works inside ```diff lang="typescript" blocks: a leading `+`/`-`/space
347 * diff marker before the comment is tolerated (the comment itself should
348 * be an unchanged/context line).
349 *
350 * The rendered markup and CSS replicate expressive-code-twoslash's error UI
351 * (`.twoslash-error-underline` squiggle + `.twoslash-error-box`), so the
352 * visual output is identical to what the compiler-backed plugin produced.
353 */
354 export function errorAnnotations(): ExpressiveCodePlugin {
355 return {
356 name: "error-annotations",
357 baseStyles: `
358 .twoslash-error-underline {
359 text-decoration-line: spelling-error;
360 position: relative;
361 }
362 .twoslash-error-box {
363 display: flex;
364 z-index: 10;
365 padding: 0.1rem 0.3rem;
366 font-style: italic;
367 border: 1px solid rgba(from var(--al-error-col, #cd3131) r g b / 0.25);
368 border-radius: 4px;
369 font-size: 90%;
370 white-space: normal;
371 word-break: normal;
372 overflow-wrap: normal;
373 flex: 0 1 100%;
374 color: var(--al-error-col, #cd3131);
375 background: rgba(from var(--al-error-col, #cd3131) r g b / 0.1);
376 }
377 .twoslash-error-box .twoslash-error-box-icon {
378 display: inline-block;
379 vertical-align: middle;
380 }
381 .twoslash-error-box .twoslash-error-box-content {
382 display: inline-block;
383 vertical-align: middle;
384 flex: 0 1 100%;
385 }
386 .twoslash-error-box-content-message {
387 white-space: normal;
388 }
389 `,
390 hooks: {
391 preprocessCode({ codeBlock }) {
392 const lines = codeBlock.getLines();
393 /** @type {{ target: number, deletions: number[], parts: string[] }[]} */
394 const groups = [];
395 let current;
396 for (let i = 0; i < lines.length; i++) {
397 const match = lines[i].text.match(ERROR_COMMENT);
398 if (!match) {
399 current = undefined;
400 continue;
401 }
402 if (current) {
403 current.deletions.push(i);
404 current.parts.push(match[1]);
405 } else if (i > 0) {
406 current = { target: i - 1, deletions: [i], parts: [match[1]] };
407 groups.push(current);
408 }
409 }
410 if (groups.length === 0) return;
411
412 // Delete the comment lines (bottom-up so indices stay valid), then
413 // annotate each group's target line. Targets never move: a group's
414 // target always precedes its own deletions, and later groups'
415 // deletions never precede an earlier group's target.
416 const deleted = groups.flatMap((g) => g.deletions);
417 codeBlock.deleteLines(deleted);
418 for (const group of groups) {
419 const shift = deleted.filter((d) => d < group.target).length;
420 const line = codeBlock.getLine(group.target - shift);
421 if (!line) continue;
422 let message = group.parts.join("\n");
423 let title;
424 const code = message.match(TS_CODE);
425 if (code) {
426 title = `Error ts(${code[1]}) ― `;
427 message = message.slice(code[0].length);
428 }
429 line.addAnnotation(new ErrorUnderlineAnnotation({}));
430 line.addAnnotation(new ErrorBoxAnnotation(title, message));
431 }
432 },
433 },
434 };
435 }