Skip to content

fix: screen should not flash in the dark mode #14

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 22, 2025
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
2 changes: 1 addition & 1 deletion index.typ
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
#show: load-html-template.with(
"/typ/templates/template.html",
extra-head: {
vite.load-files(("src/main.ts",))
vite.load-files(("src/main.ts", "src/theme.ts#nomodule"))
},
)

Expand Down
2 changes: 0 additions & 2 deletions src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,4 @@ import "./global.css";
import "./show-example.css";
import "./util.css";

import "./theme.ts";

import "./respec/mod.ts";
79 changes: 53 additions & 26 deletions src/theme.ts
Original file line number Diff line number Diff line change
@@ -1,41 +1,68 @@
type Theme = 'auto' | 'light' | 'dark';
/**
* Theme toggle.
*
* This script should be executed before DOM is loaded.
* Otherwise, the screen will flash in the dark mode.
*/

const themeToggle = document.getElementById("theme-toggle") as HTMLElement;
const themeSelections: HTMLDivElement[] = Array.from(themeToggle.querySelectorAll('div.theme-icon'));
type Theme = "auto" | "light" | "dark";

// Load saved theme preference or default to auto (sync system)
if (typeof localStorage !== "undefined") {
const theme = localStorage.getItem("theme") ?? 'auto';
applyTheme(theme as Theme);
}

// Theme toggle functionality
themeToggle.addEventListener("click", () => {
const current = themeSelections.findIndex(icon => !icon.hidden);
const next = themeSelections[(current + 1) % themeSelections.length].classList;
const theme = next.contains("auto") ? "auto" : next.contains("light") ? "light" : "dark";
applyTheme(theme);
});

function applyTheme(theme: Theme): void {
/** Same as `applyTheme`, but works before DOM is loaded */
function applyThemeWithoutDOM(theme: Theme): void {
// Change the page’s theme
const resolved = theme === 'auto' ? getSystemTheme() : theme;
const resolved = theme === "auto" ? getSystemTheme() : theme;
if (resolved === "dark") {
document.documentElement.classList.add("dark");
} else {
document.documentElement.classList.remove("dark");
}
}

// Update theme selections
themeSelections.forEach(icon => {
icon.hidden = !icon.classList.contains(theme);
// Load saved theme preference or default to auto (sync system)
if (typeof localStorage !== "undefined") {
const theme = localStorage.getItem("theme") ?? "auto";
applyThemeWithoutDOM(theme as Theme);
}

document.addEventListener("DOMContentLoaded", () => {
const themeToggle = document.getElementById("theme-toggle") as HTMLElement;
const themeSelections: HTMLDivElement[] = Array.from(
themeToggle.querySelectorAll("div.theme-icon"),
);

// Load saved theme preference or default to auto (sync system)
if (typeof localStorage !== "undefined") {
const theme = localStorage.getItem("theme") ?? "auto";
applyTheme(theme as Theme);
}

// Theme toggle functionality
themeToggle.addEventListener("click", () => {
const current = themeSelections.findIndex((icon) => !icon.hidden);
const next =
themeSelections[(current + 1) % themeSelections.length].classList;
const theme = next.contains("auto")
? "auto"
: next.contains("light")
? "light"
: "dark";
applyTheme(theme);
});

// Save for future loads
localStorage.setItem("theme", theme);
}
function applyTheme(theme: Theme): void {
applyThemeWithoutDOM(theme);

// Update theme selections
themeSelections.forEach((icon) => {
icon.hidden = !icon.classList.contains(theme);
});

// Save for future loads
localStorage.setItem("theme", theme);
}
});

function getSystemTheme(): 'dark' | 'light' {
function getSystemTheme(): "dark" | "light" {
const match = window.matchMedia &&
window.matchMedia("(prefers-color-scheme: dark)").matches;
return match ? "dark" : "light";
Expand Down
30 changes: 24 additions & 6 deletions typ/packages/vite.typ
Original file line number Diff line number Diff line change
Expand Up @@ -6,28 +6,46 @@

#let manifest-path = "/dist/.vite/manifest.json"

/// - raw-path (str):
/// -> (path: str, as-module: bool)
#let _parse-path(raw-path) = {
if raw-path.ends-with("#nomodule") {
(path: raw-path.trim("#nomodule", at: end), as-module: false)
} else {
(path: raw-path, as-module: true)
}
}

/// Load a file
///
/// - paths (array<str>):
/// - mode ("dev" | "prod"):
/// All scripts will be loaded as a module be default.
///
/// If a script should be executed before DOM is loaded, add a `#nomodule` suffix.
/// Note that it is not officially supported by vite, and does not work in `dev` mode.
///
/// - paths (array<str>): Path to typescript entry points.
/// -> content
#let load-files(paths) = {
let url(path) = asset-url("/" + path)

if mode == "dev" {
h.script({ }, type: "module", src: url("@vite/client"))
for path in paths {
for raw-path in paths {
let (path, as-module) = _parse-path(raw-path)
h.script({ }, type: "module", src: url(path))
}
} else {
let manifest = json(manifest-path)

for chunk in manifest.values() {
for raw-path in paths {
let (path, as-module) = _parse-path(raw-path)
let chunk = manifest.at(path)

assert("imports" not in chunk, message: "the `imports` field is not supported yet")

h.script({ }, type: "module", src: url(chunk.file))
h.script({ }, src: url(chunk.file), ..if as-module { (type: "module") })

for css in chunk.css {
for css in chunk.at("css", default: ()) {
h.link({ }, rel: "stylesheet", href: url(css))
}
}
Expand Down
1 change: 1 addition & 0 deletions vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ export default defineConfig({
rollupOptions: {
input: {
main: resolve(__dirname, "src/main.ts"),
theme: resolve(__dirname, "src/theme.ts"),
},
},
manifest: true, // https://vite.dev/guide/backend-integration.html
Expand Down