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
Binary file not shown.
Binary file removed local-packages/support-us-button-2.3.0.tgz
Binary file not shown.
44 changes: 22 additions & 22 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 3 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@
"test:coverage": "vitest run --coverage"
},
"dependencies": {
"@aossie-org/social-share-button": "file:local-packages/aossie-org-social-share-button-1.1.0.tgz",
"@aossie-org/social-share-button": "^1.1.1",
"@aossie-org/support-us-button": "^2.3.1",
"@swc/helpers": "^0.5.23",
"framer-motion": "^13.1.1",
"lenis": "^1.3.25",
Expand All @@ -24,8 +25,7 @@
"next-intl": "^4.13.4",
"next-themes": "^0.4.6",
"react": "19.2.4",
"react-dom": "19.2.4",
"support-us-button": "file:local-packages/support-us-button-2.3.0.tgz"
"react-dom": "19.2.4"
},
"devDependencies": {
"@tailwindcss/postcss": "^4",
Expand Down
5 changes: 5 additions & 0 deletions src/app/[locale]/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { notFound } from "next/navigation";
import { getMessages, setRequestLocale } from "next-intl/server";
import { NextIntlClientProvider } from "next-intl";
import { ThemeProvider } from "@/components/providers/theme-provider";
import { themeInitScript } from "@/components/providers/theme-script";
import { LenisProvider } from "@/components/providers/lenis-provider";
import "./globals.css";

Expand Down Expand Up @@ -66,6 +67,10 @@ export default async function RootLayout({
className={`${inter.variable} ${devanagari.variable} h-full antialiased`}
suppressHydrationWarning
>
<head>
{/* Sets the theme class before <body> is parsed, so the first paint is never the wrong theme */}
<script dangerouslySetInnerHTML={{ __html: themeInitScript }} />
</head>
<body className="min-h-full flex flex-col" suppressHydrationWarning>
<NextIntlClientProvider messages={messages}>
<ThemeProvider>
Expand Down
4 changes: 2 additions & 2 deletions src/components/SupportContent.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
"use client";

import { useTranslations } from "next-intl";
import SupportUsButton from "support-us-button";
import "support-us-button/style.css";
import SupportUsButton from "@aossie-org/support-us-button";
import "@aossie-org/support-us-button/style.css";
import { SITE_LINKS } from "@/config/links";
import { SUPPORT_PAGE, SUPPORTERS } from "@/config/support";

Expand Down
10 changes: 9 additions & 1 deletion src/components/providers/theme-provider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import { ThemeProvider as NextThemesProvider } from "next-themes";
import type { ComponentProps } from "react";
import { DEFAULT_THEME, THEME_STORAGE_KEY } from "./theme-script";

export function ThemeProvider({
children,
Expand All @@ -10,7 +11,14 @@ export function ThemeProvider({
// disableTransitionOnChange: colours switch instantly, so components that read the page's computed colours
// right after a theme change (the Support Us widget in "auto" theme) see the new theme, not a mid-fade value.
return (
<NextThemesProvider attribute="class" defaultTheme="system" enableSystem disableTransitionOnChange {...props}>
<NextThemesProvider
attribute="class"
storageKey={THEME_STORAGE_KEY}
defaultTheme={DEFAULT_THEME}
enableSystem
disableTransitionOnChange
{...props}
>
{children}
</NextThemesProvider>
);
Expand Down
17 changes: 17 additions & 0 deletions src/components/providers/theme-script.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
/** localStorage key and default theme shared by the head script and `ThemeProvider`. */
export const THEME_STORAGE_KEY = "theme";
export const DEFAULT_THEME = "system";

/**
* Applies the saved theme to `<html>` from `<head>`, before `<body>` exists.
*
* next-themes injects the same logic, but inside `<body>`. When the HTML
* arrives in more than one network chunk, the browser can paint the empty
* body in the wrong theme before that script arrives, which flashes white on
* every load in dark mode. Running it in `<head>` means the first paint
* already has the right theme. next-themes still takes over after hydration.
* If localStorage is blocked, the default theme applies.
*/
export const themeInitScript = `(function(){var d=document.documentElement,t;try{t=localStorage.getItem(${JSON.stringify(
THEME_STORAGE_KEY,
)})}catch(e){}t=t||${JSON.stringify(DEFAULT_THEME)};try{if(t==="system")t=matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light";if(t!=="light"&&t!=="dark")return;d.classList.remove("light","dark");d.classList.add(t);d.style.colorScheme=t}catch(e){}})()`;
4 changes: 4 additions & 0 deletions tests/app/routes.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import { SITE_LINKS } from "@/config/links";
import { setRequestLocale } from "../support/next-intl-server";
import { catalogs, locales, renderWithIntl, translator, type TestLocale } from "../support/intl";
import { setPathname } from "../support/navigation";
import { themeInitScript } from "@/components/providers/theme-script";

vi.mock("next-intl/server", () => import("../support/next-intl-server"));
vi.mock("next/font/google", () => ({
Expand Down Expand Up @@ -81,6 +82,9 @@ describe("[locale] layout", () => {
const { NextIntlClientProvider } = await import("next-intl");
expect(findElement(tree, NextIntlClientProvider)?.props.messages).toBe(catalogs[locale]);
expect(findElement(tree, "main")).toBeTruthy();
// The theme is applied from <head>, before <body> exists, so the first paint is never the wrong theme
const script = findElement(findElement(tree, "head"), "script");
expect(script?.props.dangerouslySetInnerHTML).toEqual({ __html: themeInitScript });
});

it("returns the localized home metadata", async () => {
Expand Down
58 changes: 58 additions & 0 deletions tests/theme-script.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import { describe, it, expect, afterEach, vi } from 'vitest';
import { DEFAULT_THEME, THEME_STORAGE_KEY, themeInitScript } from '@/components/providers/theme-script';

const root = document.documentElement;

function run({ stored, systemDark = false }: { stored?: string; systemDark?: boolean }) {
if (stored !== undefined) localStorage.setItem(THEME_STORAGE_KEY, stored);
vi.stubGlobal('matchMedia', (query: string) => ({ matches: query === '(prefers-color-scheme: dark)' && systemDark }));
new Function(themeInitScript)();
}

afterEach(() => {
localStorage.clear();
root.className = '';
root.removeAttribute('style');
vi.unstubAllGlobals();
vi.restoreAllMocks();
});

describe('theme head script', () => {
it('shares its storage key and default with ThemeProvider', () => {
expect(THEME_STORAGE_KEY).toBe('theme');
expect(DEFAULT_THEME).toBe('system');
});

it.each(['dark', 'light'] as const)('applies a saved %s theme and its colour scheme', (theme) => {
root.className = 'font-var light dark';
run({ stored: theme, systemDark: theme === 'light' });
expect(root.className).toBe(`font-var ${theme}`);
expect(root.style.colorScheme).toBe(theme);
});

it.each([
[true, 'dark'],
[false, 'light'],
] as const)('follows the system (prefers dark: %s) when nothing or "system" is saved', (systemDark, expected) => {
run({ systemDark });
expect(root.className).toBe(expected);
root.className = '';
run({ stored: 'system', systemDark });
expect(root.className).toBe(expected);
});

it('leaves the page alone for an unknown saved value', () => {
run({ stored: 'sepia' });
expect(root.className).toBe('');
expect(root.getAttribute('style')).toBeNull();
});

it('falls back to the default (system) theme when storage is blocked', () => {
vi.spyOn(Storage.prototype, 'getItem').mockImplementation(() => {
throw new Error('blocked');
});
expect(() => run({ systemDark: true })).not.toThrow();
expect(root.className).toBe('dark');
expect(root.style.colorScheme).toBe('dark');
});
});
Loading