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

themeCss.ts

174 lines8.9 KB

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