Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

themeInspector.ts

490 lines17.4 KB

1import { THEME_COLOR_ROLES, getThemeColorVariable, type ThemeColorRole } from "../../themePalette";
2​
3export type ThemePaintKind = "background" | "border" | "foreground";
4​
5export type ThemePaintSnapshot = Readonly<Record<ThemePaintKind, string>>;
6export type ThemeElementInspection = Readonly<{
7 element: Element;
8 role: ThemeColorRole;
9}>;
10​
11const THEME_PAINT_KIND_ORDER: ReadonlyArray<ThemePaintKind> = [
12 "background",
13 "border",
14 "foreground",
15];
16​
17const THEME_INSPECTOR_MATCH_ATTRIBUTE = "data-theme-inspector-match";
18​
19const THEME_TOKEN_PROBE_ATTRIBUTE = "data-theme-token-probe";
20const THEME_TOKEN_PROBE_COLOR = "#01fea7";
21const THEME_TOKEN_ALTERNATE_PROBE_COLOR = "#fe01a7";
22const THEME_SPOTLIGHT_ID = "theme-inspector-spotlight";
23const THEME_SPOTLIGHT_MASK_ID = "theme-inspector-spotlight-mask";
24const THEME_SPOTLIGHT_GLOW_ID = "theme-inspector-spotlight-glow";
25const THEME_HOVER_ID = "theme-inspector-hover";
26const SVG_NAMESPACE = "http://www.w3.org/2000/svg";
27​
28const 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​
76const THEME_UTILITY_PREFIXES: Readonly<Record<ThemePaintKind, ReadonlyArray<string>>> = {
77 background: ["bg-"],
78 border: ["border-", "outline-", "ring-"],
79 foreground: ["text-", "caret-", "fill-", "stroke-"],
80};
81​
82function clearThemeInspectorAttribute(attribute: string): void {
83 document
84 .querySelectorAll(`[${attribute}]`)
85 .forEach((element) => element.removeAttribute(attribute));
87​
88export function clearThemeInspectorHighlights(): void {
89 clearThemeInspectorAttribute(THEME_INSPECTOR_MATCH_ATTRIBUTE);
90 document.getElementById(THEME_SPOTLIGHT_ID)?.remove();
92​
93export function clearThemeInspectorHover(): void {
94 document.getElementById(THEME_HOVER_ID)?.remove();
96​
97function svgElement<Name extends keyof SVGElementTagNameMap>(
98 name: Name,
99): SVGElementTagNameMap[Name] {
100 return document.createElementNS(SVG_NAMESPACE, name);
102​
103function 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 };
135​
136export 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;
163​
164function 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);
243​
244export function refreshThemeInspectorSpotlight(): void {
245 renderThemeInspectorSpotlight([
246 ...document.querySelectorAll(`[${THEME_INSPECTOR_MATCH_ATTRIBUTE}]`),
247 ]);
249​
250function 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 );
256​
257function 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 };
294​
295export function changedThemePaintKinds(
296 before: ThemePaintSnapshot,
297 after: ThemePaintSnapshot,
298): ReadonlyArray<ThemePaintKind> {
299 return THEME_PAINT_KIND_ORDER.filter((kind) => before[kind] !== after[kind]);
301​
302function 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 every restored token while transitions are still suppressed. The
310 // browser never gets a paint opportunity between the probe and restore.
311 void window.getComputedStyle(root).color;
312 if (!wasAlreadyProbing) root.removeAttribute(THEME_TOKEN_PROBE_ATTRIBUTE);
313 }
315​
316function applyThemeTokenProbe(role: ThemeColorRole): () => void {
317 const root = document.documentElement;
318 const variable = getThemeColorVariable(role);
319 const originalValue = root.style.getPropertyValue(variable);
320 const originalPriority = root.style.getPropertyPriority(variable);
321 const resolvedValue = originalValue.trim().toLowerCase();
322 const probeColor =
323 resolvedValue === THEME_TOKEN_PROBE_COLOR
324 ? THEME_TOKEN_ALTERNATE_PROBE_COLOR
325 : THEME_TOKEN_PROBE_COLOR;
326 root.style.setProperty(variable, probeColor, "important");
327​
328 return () => {
329 if (originalValue) {
330 root.style.setProperty(variable, originalValue, originalPriority);
331 } else {
332 root.style.removeProperty(variable);
333 }
334 };
336​
337function applyThemeTokenProbes(roles: ReadonlyArray<ThemeColorRole>): () => void {
338 const restores = roles.map(applyThemeTokenProbe);
339 return () => {
340 for (const restore of restores.toReversed()) restore();
341 };
343​
344function themeInspectorCandidates(): ReadonlyArray<Element> {
345 return [document.body, ...document.body.querySelectorAll("*")].filter(
346 (element) =>
347 !element.closest("[data-theme-editor-panel]") &&
348 !element.closest(`#${THEME_SPOTLIGHT_ID}, #${THEME_HOVER_ID}`),
349 );
351​
352export function themeRoleFromUtilityClass(
353 className: string,
354 kind: ThemePaintKind,
355): ThemeColorRole | null {
356 if (className.includes(":")) return null;
357 for (const prefix of THEME_UTILITY_PREFIXES[kind]) {
358 if (!className.startsWith(prefix)) continue;
359 const colorName = className.slice(prefix.length).split("/", 1)[0] ?? "";
360 return THEME_UTILITY_ROLES[colorName] ?? null;
361 }
362 return null;
364​
365function themeRoleFromUtilities(element: Element): ThemeColorRole | null {
366 for (const kind of THEME_PAINT_KIND_ORDER) {
367 for (const className of element.classList) {
368 const role = themeRoleFromUtilityClass(className, kind);
369 if (role) return role;
370 }
371 }
372 return null;
374​
375function themeInspectionCandidates(initialElement: Element): ReadonlyArray<Element> {
376 const candidates: Array<Element> = [];
377 let element: Element | null = initialElement;
378 while (element && element !== document.documentElement) {
379 if (!element.closest("[data-theme-editor-panel]")) candidates.push(element);
380 element = element.parentElement;
381 }
382 return candidates;
384​
385export function inspectThemeRoleFromUtilitiesAtElement(
386 initialElement: Element,
387): ThemeElementInspection | null {
388 if (initialElement.closest("[data-theme-editor-panel]")) return null;
389 for (const candidate of themeInspectionCandidates(initialElement)) {
390 const role = themeRoleFromUtilities(candidate);
391 if (role) return { element: candidate, role };
392 }
393 return null;
395​
396export function highlightThemeRoleUsage(roles: ReadonlyArray<ThemeColorRole>): number {
397 const startedAt = performance.now();
398 clearThemeInspectorAttribute(THEME_INSPECTOR_MATCH_ATTRIBUTE);
399 const candidates = themeInspectorCandidates();
400 const probeStartedAt = performance.now();
401 const matches = withThemeTokenProbeSession(() => {
402 const baseline = new Map<Element, ThemePaintSnapshot>();
403 for (const element of candidates) {
404 const snapshot = getThemePaintSnapshot(element);
405 if (snapshot) baseline.set(element, snapshot);
406 }
407​
408 const restore = applyThemeTokenProbes(roles);
409 const changed = new Set<Element>();
410 try {
411 for (const [element, before] of baseline) {
412 const after = getThemePaintSnapshot(element);
413 if (after && changedThemePaintKinds(before, after).length > 0) changed.add(element);
414 }
415 } finally {
416 restore();
417 }
418 return changed;
419 });
420 const probeDuration = performance.now() - probeStartedAt;
421​
422 const highlightedElements = new Set<Element>();
423 for (const element of matches) {
424 highlightedElements.add(
425 element instanceof SVGElement ? (element.closest("svg") ?? element) : element,
426 );
427 }
428 for (const element of highlightedElements) {
429 element.setAttribute(THEME_INSPECTOR_MATCH_ATTRIBUTE, "");
430 }
431 renderThemeInspectorSpotlight([...highlightedElements]);
432 if (import.meta.env.DEV) {
433 const spotlight = document.getElementById(THEME_SPOTLIGHT_ID);
434 if (spotlight) {
435 spotlight.dataset.themeInspectorCandidates = String(candidates.length);
436 spotlight.dataset.themeInspectorProbeMs = probeDuration.toFixed(2);
437 spotlight.dataset.themeInspectorTotalMs = (performance.now() - startedAt).toFixed(2);
438 }
439 }
440 return highlightedElements.size;
442​
443export function inspectThemeRoleAtElement(initialElement: Element): ThemeElementInspection | null {
444 if (initialElement.closest("[data-theme-editor-panel]")) return null;
445​
446 const candidates = themeInspectionCandidates(initialElement);
447​
448 // Most app paint comes from Tailwind's semantic color utilities. Those class
449 // names express the token dependency directly and avoid dozens of forced
450 // style recalculations on every pointer-down.
451 const utilityInspection = inspectThemeRoleFromUtilitiesAtElement(initialElement);
452 if (utilityInspection) return utilityInspection;
453​
454 const rolesByElement = withThemeTokenProbeSession(() => {
455 const baseline = new Map<Element, ThemePaintSnapshot>();
456 const roles = new Map<Element, Partial<Record<ThemePaintKind, ThemeColorRole>>>();
457 for (const candidate of candidates) {
458 const snapshot = getThemePaintSnapshot(candidate, { forHitTest: true });
459 if (snapshot) baseline.set(candidate, snapshot);
460 }
461​
462 for (const role of THEME_COLOR_ROLES) {
463 const restore = applyThemeTokenProbe(role);
464 try {
465 for (const [candidate, before] of baseline) {
466 const after = getThemePaintSnapshot(candidate, { forHitTest: true });
467 if (!after) continue;
468 const candidateRoles = roles.get(candidate) ?? {};
469 for (const kind of changedThemePaintKinds(before, after)) {
470 candidateRoles[kind] ??= role;
471 }
472 roles.set(candidate, candidateRoles);
473 }
474 } finally {
475 restore();
476 }
477 }
478 return roles;
479 });
480​
481 for (const candidate of candidates) {
482 const roles = rolesByElement.get(candidate);
483 if (!roles) continue;
484 for (const kind of THEME_PAINT_KIND_ORDER) {
485 const role = roles[kind];
486 if (role) return { element: candidate, role };
487 }
488 }
489 return null;