Open History to see the last commit
1import { THEME_COLOR_ROLES } from "./themePalettes.ts";
2
3const FETCHES_BY_STRING = /image-set\(|\bsrc\(/i;
4// Only CSS whitespace may come first. \s also matches U+00A0, which makes the address relative.
5const URL_NOT_LOCAL = /url\((?![ \t\n\f\r]*["']?(?:data:|#))/i;
6// Read tokens left to right, as CSS does: a url( or /* inside a string loads nothing, and a quote
7// in an unquoted url( or after a backslash is not a string. A quoted url() that is not data: or #id
8// keeps `url(` for the check.
9const ESCAPE = String.raw`\\(?:(?:[0-9a-fA-F]{6}|[0-9a-fA-F]{1,5}(?![0-9a-fA-F]))(?:\r\n|[\n\r\f])?|\r\n|[^0-9a-fA-F])`;
10const STRING = String.raw`"(?:${ESCAPE}|[^"\\\n\r\f])*"|'(?:${ESCAPE}|[^'\\\n\r\f])*'`;
11const URL_OR_STRING = String.raw`url\((?![ \t\n\f\r]*["'])([^)]*)|url\([ \t\n\f\r]*(${STRING})|${STRING}|${ESCAPE}`;
12const CSS_TOKENS = new RegExp(String.raw`\/\*[\s\S]*?\*\/|${URL_OR_STRING}`, "gi");
13
14/**
15 * The code with its strings and comments removed, keeping `url(` where a quoted url() can load a
16 * file. A declaration value keeps a comment or quoted url() that holds an escape. In a stylesheet
17 * an unquoted url() is judged by its address too.
18 */
19function withoutStrings(code: string, stylesheet: boolean): string {
20 return code.replace(CSS_TOKENS, (token, address?: string, urlString?: string) => {
21 const url = stylesheet ? (address ?? urlString) : urlString;
22 if (url !== undefined) {
23 if (!stylesheet && url.includes("\\")) return token;
24 return /^[ \t\n\f\r]*["']?(?:data:|#)/i.test(url) ? "" : "url(";
25 }
26 if (token.startsWith("/*")) {
27 if (stylesheet) return "";
28 return token.includes("\\") ? token : " ";
29 }
30 return /^["']/.test(token) ? "" : token;
31 });
32}
33
34function fetchesOutsideStrings(code: string): boolean {
35 return FETCHES_BY_STRING.test(code) || URL_NOT_LOCAL.test(code);
36}
37
38/**
39 * Whether one declaration value can load a remote file. Clients drop those declarations.
40 * Values with var() can keep escapes that spell `var` or `url`. Refuse escapes that survive
41 * removing plain strings, including escapes in URL addresses.
42 */
43export function themeCssValueFetches(value: string): boolean {
44 const code = withoutStrings(value, false);
45 return code.includes("\\") || fetchesOutsideStrings(code);
46}
47
48const WHITESPACE = String.raw`[ \t\n\f\r]`;
49const NAME_ESCAPE = String.raw`\\(?:[0-9a-fA-F]{1,6}(?:\r\n|${WHITESPACE})?|[^\n\r\f0-9a-fA-F])`;
50const NAME = String.raw`(?:${NAME_ESCAPE}|[-\w\u0080-\uffff])+`;
51const BLOCK_TOKENS = new RegExp(
52 String.raw`\/\*[\s\S]*?(?:\*\/|$)|${STRING}|(${NAME})(\()?|[()[\]{};]`,
53 "g",
54);
55// An unquoted url() is one token: quotes, comments and brackets inside it are part of the address.
56const UNQUOTED_URL = new RegExp(String.raw`(?!${WHITESPACE}*["'])(?:${NAME_ESCAPE}|[^)])*\)?`, "y");
57const NAME_ESCAPES = new RegExp(
58 String.raw`\\(?:([0-9a-fA-F]{1,6})(?:\r\n|${WHITESPACE})?|([^]))`,
59 "g",
60);
61const CLOSERS: Record<string, string> = { "(": ")", "[": "]", "{": "}" };
62
63const isUrlFunction = (name: string) =>
64 name
65 .replace(NAME_ESCAPES, (_, hex?: string, char?: string) =>
66 hex ? String.fromCodePoint(Math.min(Number.parseInt(hex, 16), 0x10ffff)) : (char ?? ""),
67 )
68 .toLowerCase() === "url";
69
70/**
71 * The CSS without the declarations that `drop` refuses, asked only for text that could load a
72 * remote file. A browser hides a var() shorthand's text once a later declaration overrides one of
73 * its longhands, so only the source has it. Brackets are tracked as the CSS parser does; an unsure
74 * split is left out, so one candidate can hold several declarations or rules.
75 */
76export function themeCssWithoutDeclarations(
77 css: string,
78 drop: (candidate: string) => boolean,
79): string {
80 let kept = "";
81 const open: string[] = [];
82 let start = 0;
83 const cut = (end: number) => {
84 const text = css.slice(start, end);
85 const candidate = text.includes("\\") || fetchesOutsideStrings(text);
86 kept += (candidate && drop(text) ? "" : text) + css.slice(end, end + 1);
87 start = end + 1;
88 };
89 BLOCK_TOKENS.lastIndex = 0;
90 for (let match = BLOCK_TOKENS.exec(css); match; match = BLOCK_TOKENS.exec(css)) {
91 const [token, name, paren] = match;
92 if (name !== undefined) {
93 if (!paren) continue;
94 UNQUOTED_URL.lastIndex = BLOCK_TOKENS.lastIndex;
95 const url = isUrlFunction(name) && UNQUOTED_URL.test(css);
96 if (url) BLOCK_TOKENS.lastIndex = UNQUOTED_URL.lastIndex;
97 else open.push(")");
98 } else if (token in CLOSERS && (token !== "{" || open.length > 0)) {
99 open.push(CLOSERS[token] ?? "");
100 } else if (token === open.at(-1)) {
101 open.pop();
102 } else if (open.length === 0 && (token === ";" || token === "{" || token === "}")) {
103 cut(match.index);
104 }
105 }
106 cut(css.length);
107 return kept;
108}
109
110/** A text check for early feedback. CSS escapes can dodge it; the client check is the guard. */
111export function themeCssLoadsRemoteFiles(css: string): boolean {
112 const code = withoutStrings(css, true);
113 return /@import/i.test(code) || fetchesOutsideStrings(code);
114}
115
116/**
117 * Selectors that theme CSS may rely on. Other class names are Tailwind utilities and change
118 * between releases. themeCss.test.ts in apps/web fails when one of these leaves the source.
119 */
120export const THEME_CSS_HOOKS = [
121 { selector: '[data-slot="sidebar"]', styles: "app sidebar" },
122 { selector: '[data-slot="sidebar-inner"]', styles: "sidebar surface" },
123 { selector: "[data-thread-item]", styles: "sidebar thread row" },
124 {
125 selector: '[data-slot="project-monogram"]',
126 styles: "project icon with letters; its svg holds the tile",
127 },
128 { selector: "[data-chat-header]", styles: "chat header" },
129 { selector: '[data-workspace-area="conversation"]', styles: "chat area, behind the messages" },
130 { selector: ".messages-timeline-scroll", styles: "chat scroller" },
131 { selector: "[data-timeline-row-kind]", styles: 'chat row, such as ="message" or ="work"' },
132 { selector: '[data-message-role="user"]', styles: "user message row" },
133 { selector: "[data-user-message-bubble]", styles: "user message bubble" },
134 { selector: '[data-message-role="assistant"]', styles: "assistant message row" },
135 { selector: ".chat-markdown", styles: "assistant text" },
136 { selector: ".chat-markdown-codeblock", styles: "code block" },
137 { selector: "[data-chat-composer-form]", styles: "composer" },
138 { selector: '[data-slot="composer-host"]', styles: "composer card" },
139 { selector: ".composer-tiptap", styles: "composer text" },
140 { selector: "[data-thread-details-card]", styles: "thread details card" },
141 { selector: "[data-thread-terminal-drawer]", styles: "terminal drawer" },
142 { selector: "[data-settings-page-scroll]", styles: "settings page" },
143 { selector: '[data-slot="button"]', styles: "button" },
144 { selector: '[data-slot="input"]', styles: "text input" },
145 { selector: '[data-slot="switch"]', styles: "switch" },
146 { selector: '[data-slot="select-trigger"]', styles: "select" },
147 { selector: '[data-slot="dialog-popup"]', styles: "dialog" },
148 { selector: '[data-slot="popover-popup"]', styles: "popover" },
149 { selector: '[data-slot="menu-popup"]', styles: "menu" },
150 { selector: '[data-slot="tooltip-popup"]', styles: "tooltip" },
151 { selector: '[data-slot="scroll-area-scrollbar"]', styles: "overlay scrollbar" },
152 { selector: '[data-slot="scroll-area-thumb"]', styles: "overlay scrollbar thumb" },
153] as const;
154
155/** What an agent needs to restyle the app. `t3_theme_read` returns it. */
156export const THEME_GUIDE = [
157 "Themes restyle T3 Code on web and desktop. Mobile does not use them.",
158 "",
159 "Colors: `canvas` and `accent` (hex) derive a full palette. `colors` overrides single roles, and `variants.light` or `variants.dark` does that for the other appearance. Prefer colors over CSS.",
160 `Roles: ${THEME_COLOR_ROLES.join(", ")}.`,
161 "",
162 "CSS: `css` applies after the app's styles. Use `.dark` or `:root:not(.dark)` for one appearance.",
163 "It cannot load files: no @import, no image-set(), and url() only with data: or #id.",
164 'For a background image, copy a JPEG, PNG, or WebP file of up to 16 MB to `<themesDir>/<themeId>.jpg` (or .png, .webp), beside the theme file. CSS shows it with `var(--theme-background-image)`, such as `[data-workspace-area="conversation"] { background: var(--theme-background-image) center / cover no-repeat; }`. Delete the file to remove it. Do not embed images in `css`: it holds 100,000 characters.',
165 "The app's own rules can be more specific. If a rule has no effect, add !important.",
166 "It cannot reach the terminal text, the file tree, or diff internals. Use color roles for those.",
167 "Native scrollbars take `::-webkit-scrollbar` and `::-webkit-scrollbar-thumb`.",
168 "Icons are `svg.lucide`. stroke-width, stroke-linecap, and stroke-linejoin restyle them.",
169 "",
170 "Stable selectors (other class names change between releases, so do not use them):",
171 ...THEME_CSS_HOOKS.map((hook) => `- ${hook.selector}: ${hook.styles}`),
172 "",
173 "You cannot see the result. Make small changes, then ask the user how it looks.",
174 "To undo, set `t3-code`, the stock T3 Code theme, or another built-in theme. An empty `current` means the stock theme or no environment theme.",
175].join("\n");