@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 474 lines 16.7 KB
Raw
1 import { THEME_COLOR_ROLES, getThemeColorVariable, type ThemeColorRole } from "../../themePalette";
2
3 export type ThemePaintKind = "background" | "border" | "foreground";
4
5 export type ThemePaintSnapshot = Readonly<Record<ThemePaintKind, string>>;
6 export type ThemeElementInspection = Readonly<{
7 element: Element;
8 role: ThemeColorRole;
9 }>;
10
11 const THEME_PAINT_KIND_ORDER: ReadonlyArray<ThemePaintKind> = [
12 "background",
13 "border",
14 "foreground",
15 ];
16
17 const THEME_INSPECTOR_MATCH_ATTRIBUTE = "data-theme-inspector-match";
18
19 const THEME_TOKEN_PROBE_ATTRIBUTE = "data-theme-token-probe";
20 const THEME_TOKEN_PROBE_COLOR = "#01fea7";
21 const THEME_TOKEN_ALTERNATE_PROBE_COLOR = "#fe01a7";
22 const THEME_SPOTLIGHT_ID = "theme-inspector-spotlight";
23 const THEME_SPOTLIGHT_MASK_ID = "theme-inspector-spotlight-mask";
24 const THEME_SPOTLIGHT_GLOW_ID = "theme-inspector-spotlight-glow";
25 const THEME_HOVER_ID = "theme-inspector-hover";
26 const SVG_NAMESPACE = "http://www.w3.org/2000/svg";
27
28 const THEME_UTILITY_ROLES: Readonly<Partial<Record<string, ThemeColorRole>>> = {
29 background: "canvas",
30 foreground: "text",
31 card: "surface",
32 "card-foreground": "text",
33 popover: "surfaceOverlay",
34 "popover-foreground": "text",
35 "surface-raised": "surfaceRaised",
36 primary: "messageAction",
37 "primary-foreground": "messageActionForeground",
38 secondary: "secondary",
39 "secondary-foreground": "secondaryForeground",
40 muted: "muted",
41 "muted-foreground": "mutedForeground",
42 placeholder: "placeholder",
43 "secondary-label": "secondaryLabel",
44 "icon-muted": "iconMuted",
45 accent: "accentSurface",
46 "accent-foreground": "accentSurfaceForeground",
47 destructive: "error",
48 "destructive-foreground": "errorForeground",
49 error: "error",
50 "error-foreground": "errorForeground",
51 "error-surface": "errorSurface",
52 warning: "warning",
53 "warning-foreground": "warningForeground",
54 "warning-surface": "warningSurface",
55 update: "update",
56 "update-foreground": "updateForeground",
57 "update-surface": "updateSurface",
58 message: "messageSurface",
59 "message-foreground": "messageForeground",
60 "message-action": "messageAction",
61 "message-action-foreground": "messageActionForeground",
62 "message-action-hover": "messageActionHover",
63 sidebar: "sidebar",
64 "sidebar-foreground": "sidebarForeground",
65 "sidebar-muted-foreground": "sidebarMutedForeground",
66 "sidebar-control-surface": "sidebarControlSurface",
67 "sidebar-row-hover": "sidebarRowHover",
68 "sidebar-row-active": "sidebarRowActive",
69 "sidebar-row-selected": "sidebarRowSelected",
70 "sidebar-border": "sidebarBorder",
71 border: "border",
72 input: "input",
73 ring: "focus",
74 };
75
76 const THEME_UTILITY_PREFIXES: Readonly<Record<ThemePaintKind, ReadonlyArray<string>>> = {
77 background: ["bg-"],
78 border: ["border-", "outline-", "ring-"],
79 foreground: ["text-", "caret-", "fill-", "stroke-"],
80 };
81
82 function clearThemeInspectorAttribute(attribute: string): void {
83 document
84 .querySelectorAll(`[${attribute}]`)
85 .forEach((element) => element.removeAttribute(attribute));
86 }
87
88 export function clearThemeInspectorHighlights(): void {
89 clearThemeInspectorAttribute(THEME_INSPECTOR_MATCH_ATTRIBUTE);
90 document.getElementById(THEME_SPOTLIGHT_ID)?.remove();
91 }
92
93 export function clearThemeInspectorHover(): void {
94 document.getElementById(THEME_HOVER_ID)?.remove();
95 }
96
97 function svgElement<Name extends keyof SVGElementTagNameMap>(
98 name: Name,
99 ): SVGElementTagNameMap[Name] {
100 return document.createElementNS(SVG_NAMESPACE, name);
101 }
102
103 function spotlightRect(element: Element): {
104 x: number;
105 y: number;
106 width: number;
107 height: number;
108 radius: number;
109 } | null {
110 const bounds = element.getBoundingClientRect();
111 if (
112 bounds.width <= 0 ||
113 bounds.height <= 0 ||
114 bounds.right < 0 ||
115 bounds.bottom < 0 ||
116 bounds.left > window.innerWidth ||
117 bounds.top > window.innerHeight
118 ) {
119 return null;
120 }
121
122 const padding = 5;
123 const x = bounds.left - padding;
124 const y = bounds.top - padding;
125 const elementRadius =
126 Number.parseFloat(window.getComputedStyle(element).borderTopLeftRadius) || 0;
127 return {
128 x,
129 y,
130 width: bounds.width + padding * 2,
131 height: bounds.height + padding * 2,
132 radius: Math.min(18, Math.max(7, elementRadius + padding)),
133 };
134 }
135
136 export function showThemeInspectorHover(inspection: ThemeElementInspection, label: string): void {
137 const rectangle = spotlightRect(inspection.element);
138 if (!rectangle) {
139 clearThemeInspectorHover();
140 return;
141 }
142
143 let hover = document.getElementById(THEME_HOVER_ID);
144 if (!hover) {
145 hover = document.createElement("div");
146 hover.id = THEME_HOVER_ID;
147 hover.setAttribute("aria-hidden", "true");
148 const tokenLabel = document.createElement("span");
149 tokenLabel.dataset.themeInspectorHoverLabel = "";
150 hover.append(tokenLabel);
151 document.body.append(hover);
152 }
153
154 hover.style.left = `${rectangle.x}px`;
155 hover.style.top = `${rectangle.y}px`;
156 hover.style.width = `${rectangle.width}px`;
157 hover.style.height = `${rectangle.height}px`;
158 hover.style.borderRadius = `${rectangle.radius}px`;
159 hover.dataset.placement = rectangle.y < 32 ? "below" : "above";
160 const tokenLabel = hover.querySelector<HTMLElement>("[data-theme-inspector-hover-label]");
161 if (tokenLabel) tokenLabel.textContent = label;
162 }
163
164 function renderThemeInspectorSpotlight(elements: ReadonlyArray<Element>): void {
165 const rectangles = new Map<string, NonNullable<ReturnType<typeof spotlightRect>>>();
166 for (const element of elements) {
167 const rectangle = spotlightRect(element);
168 if (!rectangle) continue;
169 const key = [rectangle.x, rectangle.y, rectangle.width, rectangle.height]
170 .map((value) => Math.round(value))
171 .join(":");
172 rectangles.set(key, rectangle);
173 }
174
175 if (rectangles.size === 0) {
176 document.getElementById(THEME_SPOTLIGHT_ID)?.remove();
177 return;
178 }
179
180 let spotlight = document.getElementById(THEME_SPOTLIGHT_ID) as SVGSVGElement | null;
181 if (!spotlight) {
182 spotlight = svgElement("svg");
183 spotlight.id = THEME_SPOTLIGHT_ID;
184 spotlight.setAttribute("aria-hidden", "true");
185 spotlight.setAttribute("focusable", "false");
186 document.body.append(spotlight);
187 }
188 spotlight.setAttribute("viewBox", `0 0 ${window.innerWidth} ${window.innerHeight}`);
189
190 const definitions = svgElement("defs");
191 const mask = svgElement("mask");
192 mask.id = THEME_SPOTLIGHT_MASK_ID;
193 mask.setAttribute("maskUnits", "userSpaceOnUse");
194 const maskSurface = svgElement("rect");
195 maskSurface.setAttribute("width", String(window.innerWidth));
196 maskSurface.setAttribute("height", String(window.innerHeight));
197 maskSurface.setAttribute("fill", "white");
198 mask.append(maskSurface);
199
200 const glowFilter = svgElement("filter");
201 glowFilter.id = THEME_SPOTLIGHT_GLOW_ID;
202 glowFilter.setAttribute("x", "-50%");
203 glowFilter.setAttribute("y", "-50%");
204 glowFilter.setAttribute("width", "200%");
205 glowFilter.setAttribute("height", "200%");
206 const blur = svgElement("feGaussianBlur");
207 blur.setAttribute("stdDeviation", "5");
208 blur.setAttribute("result", "blur");
209 const merge = svgElement("feMerge");
210 const blurredGlow = svgElement("feMergeNode");
211 blurredGlow.setAttribute("in", "blur");
212 const crispGlow = svgElement("feMergeNode");
213 crispGlow.setAttribute("in", "SourceGraphic");
214 merge.append(blurredGlow, crispGlow);
215 glowFilter.append(blur, merge);
216 definitions.append(mask, glowFilter);
217
218 const glowGroup = svgElement("g");
219 for (const rectangle of rectangles.values()) {
220 const hole = svgElement("rect");
221 hole.setAttribute("x", String(rectangle.x));
222 hole.setAttribute("y", String(rectangle.y));
223 hole.setAttribute("width", String(rectangle.width));
224 hole.setAttribute("height", String(rectangle.height));
225 hole.setAttribute("rx", String(rectangle.radius));
226 hole.setAttribute("fill", "black");
227 mask.append(hole);
228
229 const glow = hole.cloneNode(false) as SVGRectElement;
230 glow.removeAttribute("fill");
231 glow.setAttribute("class", "theme-inspector-spotlight-glow");
232 glow.setAttribute("filter", `url(#${THEME_SPOTLIGHT_GLOW_ID})`);
233 glowGroup.append(glow);
234 }
235
236 const dimmer = svgElement("rect");
237 dimmer.setAttribute("class", "theme-inspector-spotlight-dimmer");
238 dimmer.setAttribute("width", String(window.innerWidth));
239 dimmer.setAttribute("height", String(window.innerHeight));
240 dimmer.setAttribute("mask", `url(#${THEME_SPOTLIGHT_MASK_ID})`);
241 spotlight.replaceChildren(definitions, dimmer, glowGroup);
242 }
243
244 export function refreshThemeInspectorSpotlight(): void {
245 renderThemeInspectorSpotlight([
246 ...document.querySelectorAll(`[${THEME_INSPECTOR_MATCH_ATTRIBUTE}]`),
247 ]);
248 }
249
250 function elementHasVisibleText(element: Element): boolean {
251 if (element.matches("input, textarea, select, option")) return true;
252 return Array.from(element.childNodes).some(
253 (node) => node.nodeType === Node.TEXT_NODE && Boolean(node.textContent?.trim()),
254 );
255 }
256
257 function getThemePaintSnapshot(
258 element: Element,
259 { forHitTest = false }: { forHitTest?: boolean } = {},
260 ): ThemePaintSnapshot | null {
261 const style = window.getComputedStyle(element);
262 if (style.display === "none" || style.visibility === "hidden" || Number(style.opacity) === 0) {
263 return null;
264 }
265
266 const borderPaints: Array<string> = [];
267 for (const [color, borderStyle, width] of [
268 [style.borderTopColor, style.borderTopStyle, style.borderTopWidth],
269 [style.borderRightColor, style.borderRightStyle, style.borderRightWidth],
270 [style.borderBottomColor, style.borderBottomStyle, style.borderBottomWidth],
271 [style.borderLeftColor, style.borderLeftStyle, style.borderLeftWidth],
272 ] as const) {
273 if (borderStyle !== "none" && Number.parseFloat(width) > 0) borderPaints.push(color);
274 }
275 if (style.outlineStyle !== "none" && Number.parseFloat(style.outlineWidth) > 0) {
276 borderPaints.push(style.outlineColor);
277 }
278 if (style.borderImageSource !== "none") borderPaints.push(style.borderImageSource);
279 if (style.boxShadow !== "none") borderPaints.push(style.boxShadow);
280
281 const foregroundPaints: Array<string> = [];
282 if (forHitTest || elementHasVisibleText(element)) foregroundPaints.push(style.color);
283 if (element instanceof SVGElement) foregroundPaints.push(style.fill, style.stroke);
284 if (element.matches("input, textarea")) foregroundPaints.push(style.caretColor);
285 if (style.textDecorationLine !== "none") foregroundPaints.push(style.textDecorationColor);
286 if (style.textShadow !== "none") foregroundPaints.push(style.textShadow);
287
288 return {
289 background: [style.backgroundColor, style.backgroundImage].join("\n"),
290 border: borderPaints.join("\n"),
291 foreground: foregroundPaints.join("\n"),
292 };
293 }
294
295 function changedThemePaintKinds(
296 before: ThemePaintSnapshot,
297 after: ThemePaintSnapshot,
298 ): ReadonlyArray<ThemePaintKind> {
299 return THEME_PAINT_KIND_ORDER.filter((kind) => before[kind] !== after[kind]);
300 }
301
302 function withThemeTokenProbeSession<Result>(run: () => Result): Result {
303 const root = document.documentElement;
304 const wasAlreadyProbing = root.hasAttribute(THEME_TOKEN_PROBE_ATTRIBUTE);
305 if (!wasAlreadyProbing) root.setAttribute(THEME_TOKEN_PROBE_ATTRIBUTE, "");
306 try {
307 return run();
308 } finally {
309 // Flush restored tokens before re-enabling transitions; no paint may occur during probing.
310 void window.getComputedStyle(root).color;
311 if (!wasAlreadyProbing) root.removeAttribute(THEME_TOKEN_PROBE_ATTRIBUTE);
312 }
313 }
314
315 function applyThemeTokenProbe(role: ThemeColorRole): () => void {
316 const root = document.documentElement;
317 const variable = getThemeColorVariable(role);
318 const originalValue = root.style.getPropertyValue(variable);
319 const originalPriority = root.style.getPropertyPriority(variable);
320 const resolvedValue = originalValue.trim().toLowerCase();
321 const probeColor =
322 resolvedValue === THEME_TOKEN_PROBE_COLOR
323 ? THEME_TOKEN_ALTERNATE_PROBE_COLOR
324 : THEME_TOKEN_PROBE_COLOR;
325 root.style.setProperty(variable, probeColor, "important");
326
327 return () => {
328 if (originalValue) {
329 root.style.setProperty(variable, originalValue, originalPriority);
330 } else {
331 root.style.removeProperty(variable);
332 }
333 };
334 }
335
336 function applyThemeTokenProbes(roles: ReadonlyArray<ThemeColorRole>): () => void {
337 const restores = roles.map(applyThemeTokenProbe);
338 return () => {
339 for (const restore of restores.toReversed()) restore();
340 };
341 }
342
343 function themeInspectorCandidates(): ReadonlyArray<Element> {
344 return [document.body, ...document.body.querySelectorAll("*")].filter(
345 (element) =>
346 !element.closest("[data-theme-editor-panel]") &&
347 !element.closest(`#${THEME_SPOTLIGHT_ID}, #${THEME_HOVER_ID}`),
348 );
349 }
350
351 function themeRoleFromUtilityClass(className: string, kind: ThemePaintKind): ThemeColorRole | null {
352 if (className.includes(":")) return null;
353 for (const prefix of THEME_UTILITY_PREFIXES[kind]) {
354 if (!className.startsWith(prefix)) continue;
355 const colorName = className.slice(prefix.length).split("/", 1)[0] ?? "";
356 return THEME_UTILITY_ROLES[colorName] ?? null;
357 }
358 return null;
359 }
360
361 function themeRoleFromUtilities(element: Element): ThemeColorRole | null {
362 for (const kind of THEME_PAINT_KIND_ORDER) {
363 for (const className of element.classList) {
364 const role = themeRoleFromUtilityClass(className, kind);
365 if (role) return role;
366 }
367 }
368 return null;
369 }
370
371 function themeInspectionCandidates(initialElement: Element): ReadonlyArray<Element> {
372 const candidates: Array<Element> = [];
373 let element: Element | null = initialElement;
374 while (element && element !== document.documentElement) {
375 if (!element.closest("[data-theme-editor-panel]")) candidates.push(element);
376 element = element.parentElement;
377 }
378 return candidates;
379 }
380
381 export function inspectThemeRoleFromUtilitiesAtElement(
382 initialElement: Element,
383 ): ThemeElementInspection | null {
384 if (initialElement.closest("[data-theme-editor-panel]")) return null;
385 for (const candidate of themeInspectionCandidates(initialElement)) {
386 const role = themeRoleFromUtilities(candidate);
387 if (role) return { element: candidate, role };
388 }
389 return null;
390 }
391
392 export function highlightThemeRoleUsage(roles: ReadonlyArray<ThemeColorRole>): number {
393 clearThemeInspectorAttribute(THEME_INSPECTOR_MATCH_ATTRIBUTE);
394 const candidates = themeInspectorCandidates();
395 const matches = withThemeTokenProbeSession(() => {
396 const baseline = new Map<Element, ThemePaintSnapshot>();
397 for (const element of candidates) {
398 const snapshot = getThemePaintSnapshot(element);
399 if (snapshot) baseline.set(element, snapshot);
400 }
401
402 const restore = applyThemeTokenProbes(roles);
403 const changed = new Set<Element>();
404 try {
405 for (const [element, before] of baseline) {
406 const after = getThemePaintSnapshot(element);
407 if (after && changedThemePaintKinds(before, after).length > 0) changed.add(element);
408 }
409 } finally {
410 restore();
411 }
412 return changed;
413 });
414
415 const highlightedElements = new Set<Element>();
416 for (const element of matches) {
417 highlightedElements.add(
418 element instanceof SVGElement ? (element.closest("svg") ?? element) : element,
419 );
420 }
421 for (const element of highlightedElements) {
422 element.setAttribute(THEME_INSPECTOR_MATCH_ATTRIBUTE, "");
423 }
424 renderThemeInspectorSpotlight([...highlightedElements]);
425 return highlightedElements.size;
426 }
427
428 export function inspectThemeRoleAtElement(initialElement: Element): ThemeElementInspection | null {
429 if (initialElement.closest("[data-theme-editor-panel]")) return null;
430
431 const candidates = themeInspectionCandidates(initialElement);
432
433 // Semantic Tailwind utilities reveal token dependencies without forced style recalculations per
434 // pointerdown.
435 const utilityInspection = inspectThemeRoleFromUtilitiesAtElement(initialElement);
436 if (utilityInspection) return utilityInspection;
437
438 const rolesByElement = withThemeTokenProbeSession(() => {
439 const baseline = new Map<Element, ThemePaintSnapshot>();
440 const roles = new Map<Element, Partial<Record<ThemePaintKind, ThemeColorRole>>>();
441 for (const candidate of candidates) {
442 const snapshot = getThemePaintSnapshot(candidate, { forHitTest: true });
443 if (snapshot) baseline.set(candidate, snapshot);
444 }
445
446 for (const role of THEME_COLOR_ROLES) {
447 const restore = applyThemeTokenProbe(role);
448 try {
449 for (const [candidate, before] of baseline) {
450 const after = getThemePaintSnapshot(candidate, { forHitTest: true });
451 if (!after) continue;
452 const candidateRoles = roles.get(candidate) ?? {};
453 for (const kind of changedThemePaintKinds(before, after)) {
454 candidateRoles[kind] ??= role;
455 }
456 roles.set(candidate, candidateRoles);
457 }
458 } finally {
459 restore();
460 }
461 }
462 return roles;
463 });
464
465 for (const candidate of candidates) {
466 const roles = rolesByElement.get(candidate);
467 if (!roles) continue;
468 for (const kind of THEME_PAINT_KIND_ORDER) {
469 const role = roles[kind];
470 if (role) return { element: candidate, role };
471 }
472 }
473 return null;
474 }