Skip to content
Open
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
2 changes: 1 addition & 1 deletion src/generators/web/template.html
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
href="https://fonts.googleapis.com/css2?family=IBM+Plex+Mono&family=Open+Sans:ital,wght@0,300..800;1,300..800" />

<!-- Apply theme before paint to avoid Flash of Unstyled Content -->
<script>document.documentElement.setAttribute("data-theme", document.documentElement.style.colorScheme = localStorage.getItem("theme") || (matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light"));</script>
<script>${themeScript}</script>
<script type="importmap">${importMap}</script>
<script type="speculationrules">${speculationRules}</script>
</head>
Expand Down
25 changes: 25 additions & 0 deletions src/generators/web/ui/theme-script.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
'use strict';

/**
* This script is designed to be inlined in the <head> of the HTML template.
* It must execute BEFORE the body renders to prevent a Flash of Unstyled Content (FOUC).
*/

export default `(function initializeTheme() {
const THEME_STORAGE_KEY = 'theme';
const THEME_DATA_ATTRIBUTE = 'data-theme';
const DARK_QUERY = '(prefers-color-scheme: dark)';

const savedUserPreference = localStorage.getItem(THEME_STORAGE_KEY);
const systemSupportsDarkMode = window.matchMedia(DARK_QUERY).matches;

const shouldApplyDark =
savedUserPreference === 'dark' ||
(savedUserPreference === 'system' && systemSupportsDarkMode) ||
(!savedUserPreference && systemSupportsDarkMode);

const themeToApply = shouldApplyDark ? 'dark' : 'light';

document.documentElement.setAttribute(THEME_DATA_ATTRIBUTE, themeToApply);
document.documentElement.style.colorScheme = themeToApply;
})();`.trim();
2 changes: 2 additions & 0 deletions src/generators/web/utils/processing.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import getConfig from '../../../utils/configuration/index.mjs';
import { populate } from '../../../utils/configuration/templates.mjs';
import { minifyHTML } from '../../../utils/html-minifier.mjs';
import { SPECULATION_RULES } from '../constants.mjs';
import themeScript from '../ui/theme-script.mjs';

/**
* Populates a template string by evaluating it as a JavaScript template literal,
Expand Down Expand Up @@ -137,6 +138,7 @@ export async function processJSXEntries(entries, template) {
importMap: clientBundle.importMap?.replaceAll('/', root) ?? '',
entrypoint: `${data.api}.js?${randomUUID()}`,
speculationRules: SPECULATION_RULES,
themeScript,
root,
metadata: data,
config,
Expand Down
Loading