Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 19 additions & 1 deletion components/ui/theme-script.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,29 @@

export const THEME_STORAGE_KEY = "rt.theme";

const UNSAFE_SCRIPT_CHARS: Record<string, string> = {
"<": "\\u003C",
">": "\\u003E",
"/": "\\u002F",
"\u2028": "\\u2028",
"\u2029": "\\u2029",
};

/**
* Serialize a value as a JavaScript literal that is safe to embed inside an
* inline `<script>` element: JSON-encodes it, then escapes characters that
* could close the script tag (`<`, `>`, `/`) or break the JS string
* (U+2028/U+2029 line separators).
*/
export function toInlineScriptLiteral(value: unknown): string {
return JSON.stringify(value).replace(/[<>/\u2028\u2029]/g, (ch) => UNSAFE_SCRIPT_CHARS[ch] ?? ch);
}

/**
* Inline, render-blocking script for <head>: applies a saved light/dark
* choice before first paint. With nothing saved it leaves `data-theme`
* unset so `prefers-color-scheme` decides.
*/
export const THEME_INIT_SCRIPT = `(function(){try{var t=localStorage.getItem(${JSON.stringify(
export const THEME_INIT_SCRIPT = `(function(){try{var t=localStorage.getItem(${toInlineScriptLiteral(
THEME_STORAGE_KEY,
)});if(t==="light"||t==="dark"){document.documentElement.setAttribute("data-theme",t);}}catch(e){}})();`;
17 changes: 10 additions & 7 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -50,19 +50,22 @@
"prettier": "^3.8.1",
"tailwindcss": "^3.4.17",
"typescript": "^5.7.0",
"vitest": "^5.0.0"
"vitest": "^5.0.5"
},
"pnpm": {
"overrides": {
"nanoid@>=3 <4": "3.3.18",
"js-yaml@>=4": "4.3.2",
"postcss": "8.5.23",
"undici@>=7": "7.29.1",
"sharp": "0.35.4",
"vite@>=8 <8.0.16": "8.0.16",
"brace-expansion@>=1 <2": "1.1.16",
"brace-expansion@>=3 <5.0.7": "5.0.7",
"@babel/core": "7.29.6"
"undici@>=7": "7.30.1",
"sharp": "0.35.5",
"vite@>=8 <8.1.6": "8.1.6",
"brace-expansion@>=1 <2": "1.1.21",
"brace-expansion@>=3 <5.0.12": "5.0.12",
"@babel/core": "7.29.6",
"source-map-js@>=1 <1.2.2": "1.2.2",
"postcss-selector-parser@<6.1.5": "6.1.5",
"zod@<4.6.6": "4.6.7"
}
}
}
Loading
Loading