Mörkt läge som följer systemet, med val för ljust och mörkt
Temat har nu tre lägen (automatiskt, ljust, mörkt) och följer webbläsarens eller systemets inställning som standard. Ett skript i <head> sätter temat innan sidan ritas så att mörkt läge inte blinkar till ljust. Kartplattorna dämpas i mörkt läge. Tester och README ingår. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
5c58f70bdd
commit
96399ba2d8
9 files changed
+160
-18
No files matched your search
@@ -254,6 +254,10 @@ Namnen viktas efter hur vanliga de var, så en man född 1960 blir oftare Anders
|
||||
- Från en posts sida kan du gå direkt till *Placera på karta*.
|
||||
- Kartplattor och adressökning hämtas som standard från OpenStreetMaps publika servrar, som är tänkta för lätt användning. För tyngre bruk, sätt `MAP_TILE_URL` och `MAP_GEOCODER_URL` till egen eller betald tjänst. Adressökningar skickas då från webbläsaren till den tjänsten.
|
||||
|
||||
## Mörkt läge
|
||||
|
||||
Knappen längst ned i sidomenyn växlar mellan tre lägen: **automatiskt** (följer webbläsarens eller systemets inställning, och byter när den ändras), **ljust** och **mörkt**. Valet sparas i kakan `theme` (saknas den gäller automatiskt). Ett litet skript i `<head>` sätter temat innan sidan ritas, så mörkt läge blinkar inte till ljust vid sidladdning. Logik och skript finns i `src/lib/theme.ts`.
|
||||
|
||||
## Tester
|
||||
|
||||
Testerna körs med Vitest (`npm test`). Det finns cirka 570 tester:
|
||||
|
||||
@@ -160,3 +160,8 @@
|
||||
.bm-palette-item.active {
|
||||
background: var(--tblr-primary-lt, rgba(32, 107, 196, 0.1));
|
||||
}
|
||||
|
||||
/* Mörkt läge: dämpa kartplattorna så att den ljusa kartan inte lyser mot en mörk sida. Markörer och egna kartbilder påverkas inte. */
|
||||
[data-bs-theme="dark"] .leaflet-tile-pane {
|
||||
filter: invert(1) hue-rotate(180deg) brightness(0.9) contrast(0.9) saturate(0.8);
|
||||
}
|
||||
+7
-2
@@ -7,6 +7,7 @@ import { I18nProvider } from "@/i18n/client";
|
||||
import { dictionaries } from "@/i18n/core";
|
||||
import { getLocale } from "@/i18n/server";
|
||||
import { TablerJs } from "@/components/tabler-js";
|
||||
import { THEME_BOOT_SCRIPT, parseThemeMode, serverTheme } from "@/lib/theme";
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: { default: "Bokplanerare", template: "%s · Bokplanerare" },
|
||||
@@ -15,10 +16,14 @@ export const metadata: Metadata = {
|
||||
|
||||
export default async function RootLayout({ children }: { children: React.ReactNode }) {
|
||||
const locale = await getLocale();
|
||||
const theme = (await cookies()).get("theme")?.value === "dark" ? "dark" : "light";
|
||||
const theme = serverTheme(parseThemeMode((await cookies()).get("theme")?.value));
|
||||
|
||||
return (
|
||||
<html lang={locale} data-bs-theme={theme}>
|
||||
// suppressHydrationWarning: skriptet i <head> kan byta tema till mörkt före hydreringen när valet är auto
|
||||
<html lang={locale} data-bs-theme={theme} suppressHydrationWarning>
|
||||
<head>
|
||||
<script dangerouslySetInnerHTML={{ __html: THEME_BOOT_SCRIPT }} />
|
||||
</head>
|
||||
<body>
|
||||
<I18nProvider locale={locale} dict={dictionaries[locale]}>
|
||||
<TablerJs />
|
||||
|
||||
@@ -30,6 +30,8 @@ import { KINDS } from "@/lib/kinds";
|
||||
import { kindIcons } from "./kind-icons";
|
||||
import { CommandPalette, PaletteButton } from "./command-palette";
|
||||
import { NavLink } from "./nav-link";
|
||||
import { cookies } from "next/headers";
|
||||
import { parseThemeMode } from "@/lib/theme";
|
||||
import { ThemeToggle } from "./theme-toggle";
|
||||
|
||||
type ShellProps = {
|
||||
@@ -40,6 +42,7 @@ type ShellProps = {
|
||||
|
||||
export async function Shell({ user, book, children }: ShellProps) {
|
||||
const { t, locale } = await getT();
|
||||
const themeMode = parseThemeMode((await cookies()).get("theme")?.value);
|
||||
const base = book ? `/books/${book.id}` : "";
|
||||
const admin = await isAdminUser(user.id, user.email ?? null);
|
||||
const canEdit = !book || hasRole(book.role ?? "VIEWER", "EDITOR");
|
||||
@@ -213,7 +216,7 @@ export async function Shell({ user, book, children }: ShellProps) {
|
||||
</button>
|
||||
))}
|
||||
</form>
|
||||
<ThemeToggle />
|
||||
<ThemeToggle initial={themeMode} />
|
||||
</div>
|
||||
<div className="text-secondary small opacity-75">v{APP_VERSION_LABEL}</div>
|
||||
<div className="d-flex align-items-center justify-content-between gap-2">
|
||||
|
||||
@@ -1,28 +1,40 @@
|
||||
"use client";
|
||||
|
||||
import { IconMoon, IconSun } from "@tabler/icons-react";
|
||||
import { useEffect, useState } from "react";
|
||||
import { IconDeviceDesktop, IconMoon, IconSun } from "@tabler/icons-react";
|
||||
import { useT } from "@/i18n/client";
|
||||
import { effectiveTheme, nextThemeMode, type ThemeMode } from "@/lib/theme";
|
||||
|
||||
export function ThemeToggle() {
|
||||
function apply(mode: ThemeMode) {
|
||||
const systemDark = window.matchMedia("(prefers-color-scheme: dark)").matches;
|
||||
document.documentElement.setAttribute("data-bs-theme", effectiveTheme(mode, systemDark));
|
||||
}
|
||||
|
||||
/** Växlar mellan auto (följer systemet), ljust och mörkt. Valet sparas i en kaka så att servern ritar rätt tema direkt. */
|
||||
export function ThemeToggle({ initial }: { initial: ThemeMode }) {
|
||||
const t = useT();
|
||||
const [mode, setMode] = useState<ThemeMode>(initial);
|
||||
|
||||
function toggle() {
|
||||
const root = document.documentElement;
|
||||
const next = root.getAttribute("data-bs-theme") === "dark" ? "light" : "dark";
|
||||
root.setAttribute("data-bs-theme", next);
|
||||
// I auto följer sidan systemet även när det ändras medan sidan är öppen
|
||||
useEffect(() => {
|
||||
if (mode !== "auto") return;
|
||||
const query = window.matchMedia("(prefers-color-scheme: dark)");
|
||||
const follow = () => apply("auto");
|
||||
query.addEventListener("change", follow);
|
||||
return () => query.removeEventListener("change", follow);
|
||||
}, [mode]);
|
||||
|
||||
function change() {
|
||||
const next = nextThemeMode(mode);
|
||||
setMode(next);
|
||||
apply(next);
|
||||
document.cookie = `theme=${next}; path=/; max-age=31536000; samesite=lax`;
|
||||
}
|
||||
|
||||
const label = t(`theme.${mode}`);
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn-icon btn-ghost-secondary"
|
||||
onClick={toggle}
|
||||
title={t("nav.theme")}
|
||||
aria-label={t("nav.theme")}
|
||||
>
|
||||
<IconMoon size={18} className="hide-theme-dark" />
|
||||
<IconSun size={18} className="hide-theme-light" />
|
||||
<button type="button" className="btn btn-icon btn-ghost-secondary" onClick={change} title={`${t("nav.theme")}: ${label}`} aria-label={`${t("nav.theme")}: ${label}`}>
|
||||
{mode === "auto" ? <IconDeviceDesktop size={18} /> : mode === "light" ? <IconSun size={18} /> : <IconMoon size={18} />}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
@@ -613,4 +613,8 @@ export const en: Record<keyof typeof sv, string> = {
|
||||
|
||||
"presence.editing": "{names} has this open for editing right now. Your changes may collide.",
|
||||
"presence.badge": "{names} editing",
|
||||
|
||||
"theme.auto": "Follows the system",
|
||||
"theme.light": "Light",
|
||||
"theme.dark": "Dark",
|
||||
};
|
||||
@@ -611,4 +611,8 @@ export const sv = {
|
||||
|
||||
"presence.editing": "{names} har det här öppet för redigering just nu. Era ändringar kan krocka.",
|
||||
"presence.badge": "{names} redigerar",
|
||||
|
||||
"theme.auto": "Följer systemet",
|
||||
"theme.light": "Ljust",
|
||||
"theme.dark": "Mörkt",
|
||||
} as const;
|
||||
@@ -0,0 +1,22 @@
|
||||
// Tema: "auto" följer webbläsarens eller systemets inställning, "light" och "dark" är ett eget val. Valet sparas i kakan
|
||||
// "theme". Saknas kakan räknas det som auto.
|
||||
|
||||
export type ThemeMode = "auto" | "light" | "dark";
|
||||
export const THEME_MODES: ThemeMode[] = ["auto", "light", "dark"];
|
||||
|
||||
export const parseThemeMode = (value: unknown): ThemeMode => (value === "light" || value === "dark" ? value : "auto");
|
||||
|
||||
/** Nästa val när man klickar på knappen: auto, ljust, mörkt, och sedan auto igen. */
|
||||
export const nextThemeMode = (mode: ThemeMode): ThemeMode => THEME_MODES[(THEME_MODES.indexOf(mode) + 1) % THEME_MODES.length];
|
||||
|
||||
/**
|
||||
* Vilket tema sidan får innan webbläsaren hunnit säga vad den föredrar. Auto börjar ljust på servern, och ett litet
|
||||
* skript i <head> byter till mörkt innan sidan ritas om systemet föredrar det.
|
||||
*/
|
||||
export const serverTheme = (mode: ThemeMode): "light" | "dark" => (mode === "dark" ? "dark" : "light");
|
||||
|
||||
/** Skriptet som körs i <head> innan sidan ritas, så att mörkt läge inte blinkar till ljust. */
|
||||
export const THEME_BOOT_SCRIPT = `(function(){try{var m=document.cookie.match(/(?:^|; )theme=([^;]*)/);var v=m?m[1]:"auto";var t=v==="dark"||v==="light"?v:(window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light");document.documentElement.setAttribute("data-bs-theme",t)}catch(e){}})()`;
|
||||
|
||||
/** Det tema som gäller för ett val, givet om systemet föredrar mörkt. */
|
||||
export const effectiveTheme = (mode: ThemeMode, systemDark: boolean): "light" | "dark" => (mode === "auto" ? (systemDark ? "dark" : "light") : mode);
|
||||
@@ -0,0 +1,83 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { THEME_BOOT_SCRIPT, effectiveTheme, nextThemeMode, parseThemeMode, serverTheme } from "@/lib/theme";
|
||||
|
||||
describe("parseThemeMode", () => {
|
||||
it("känner igen ljust och mörkt", () => {
|
||||
expect(parseThemeMode("light")).toBe("light");
|
||||
expect(parseThemeMode("dark")).toBe("dark");
|
||||
});
|
||||
|
||||
it("räknar allt annat, även saknad kaka, som auto", () => {
|
||||
expect(parseThemeMode(undefined)).toBe("auto");
|
||||
expect(parseThemeMode("auto")).toBe("auto");
|
||||
expect(parseThemeMode("")).toBe("auto");
|
||||
expect(parseThemeMode("blå")).toBe("auto");
|
||||
expect(parseThemeMode(42)).toBe("auto");
|
||||
});
|
||||
});
|
||||
|
||||
describe("nextThemeMode", () => {
|
||||
it("går auto → ljust → mörkt → auto", () => {
|
||||
expect(nextThemeMode("auto")).toBe("light");
|
||||
expect(nextThemeMode("light")).toBe("dark");
|
||||
expect(nextThemeMode("dark")).toBe("auto");
|
||||
});
|
||||
});
|
||||
|
||||
describe("serverTheme", () => {
|
||||
it("ger mörkt bara när mörkt är valt, annars ljust", () => {
|
||||
expect(serverTheme("dark")).toBe("dark");
|
||||
expect(serverTheme("light")).toBe("light");
|
||||
expect(serverTheme("auto")).toBe("light");
|
||||
});
|
||||
});
|
||||
|
||||
describe("effectiveTheme", () => {
|
||||
it("följer systemet i auto", () => {
|
||||
expect(effectiveTheme("auto", true)).toBe("dark");
|
||||
expect(effectiveTheme("auto", false)).toBe("light");
|
||||
});
|
||||
|
||||
it("ett eget val vinner över systemet", () => {
|
||||
expect(effectiveTheme("light", true)).toBe("light");
|
||||
expect(effectiveTheme("dark", false)).toBe("dark");
|
||||
});
|
||||
});
|
||||
|
||||
describe("THEME_BOOT_SCRIPT", () => {
|
||||
// Kör skriptet mot en låtsas-webbläsare för att se vilket tema det väljer
|
||||
const run = (cookie: string, systemDark: boolean) => {
|
||||
let applied: string | undefined;
|
||||
const doc = { cookie, documentElement: { setAttribute: (_: string, v: string) => (applied = v) } };
|
||||
const win = { matchMedia: (q: string) => ({ matches: q.includes("dark") && systemDark }) };
|
||||
new Function("document", "window", THEME_BOOT_SCRIPT)(doc, win);
|
||||
return applied;
|
||||
};
|
||||
|
||||
it("väljer systemets tema när kakan saknas", () => {
|
||||
expect(run("", true)).toBe("dark");
|
||||
expect(run("", false)).toBe("light");
|
||||
expect(run("a=1; b=2", true)).toBe("dark");
|
||||
});
|
||||
|
||||
it("följer kakan när den säger ljust eller mörkt", () => {
|
||||
expect(run("theme=light", true)).toBe("light");
|
||||
expect(run("x=1; theme=dark", false)).toBe("dark");
|
||||
});
|
||||
|
||||
it("behandlar okända värden som auto", () => {
|
||||
expect(run("theme=auto", true)).toBe("dark");
|
||||
expect(run("theme=nonsens", false)).toBe("light");
|
||||
});
|
||||
|
||||
it("hittar inte en annan kaka som slutar på theme", () => {
|
||||
expect(run("mytheme=dark", false)).toBe("light");
|
||||
});
|
||||
|
||||
it("kraschar inte om webbläsaren saknar matchMedia", () => {
|
||||
let applied: string | undefined;
|
||||
const doc = { cookie: "", documentElement: { setAttribute: (_: string, v: string) => (applied = v) } };
|
||||
new Function("document", "window", THEME_BOOT_SCRIPT)(doc, {});
|
||||
expect(applied).toBe("light");
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user