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
26 changes: 26 additions & 0 deletions src/generators/web/ui/theme-script.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
'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).
*/
function initializeTheme() {
var THEME_STORAGE_KEY = 'theme';
var THEME_DATA_ATTRIBUTE = 'data-theme';
var DARK_QUERY = '(prefers-color-scheme: dark)';

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

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

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

document.documentElement.setAttribute(THEME_DATA_ATTRIBUTE, themeToApply);
document.documentElement.style.colorScheme = themeToApply;
}

export var THEME_SCRIPT = `(${initializeTheme.toString()})();`;
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 { THEME_SCRIPT } 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: THEME_SCRIPT,
root,
metadata: data,
config,
Expand Down
Loading