Rewrite cosmetics and theme preferences (#1328)

- Cosmetics and theme preferences are now only stored in cookies instead
  of a combination of both cookies and state.

- The theme plugin now supports client hints. This allows the server
  to render a page using the client-preferred theme provided it supplies
  this information (any browser other than Firefox), helping to avoid an
  annoying flash while the page is hydrating.

- For the future, the theme plugin now supports additional light themes.
  Light theme preferences are currently not stored, but this can easily
  be fixed if the need arises.

- The previous workaround using the Nitro plugin has been removed. Its
  functionality is now handled by the Nuxt theme plugin with cleaner
  code.

- All pages and components now use the new plugins.

- Compared to the previous attempt, this commit has been improved to be
  more robust in cases where the theme cookie contains invalid values.

Co-authored-by: Geometrically <18202329+Geometrically@users.noreply.github.com>
This commit is contained in:
Sasha Sorokin
2024-07-31 21:42:55 +02:00
committed by GitHub
parent 984da93a7b
commit 1e0d7c7e28
25 changed files with 379 additions and 252 deletions

View File

@@ -1,27 +0,0 @@
export default defineNuxtPlugin(async (nuxtApp) => {
await useAuth();
await useUser();
const themeStore = useTheme();
const cosmetics = useCosmetics();
nuxtApp.hook("app:mounted", () => {
if (import.meta.client && themeStore.value.preference === "system") {
const colorSchemeQueryList = window.matchMedia("(prefers-color-scheme: light)");
const setColorScheme = (e) => {
if (themeStore.value.preference === "system") {
if (e.matches) {
updateTheme("light");
} else {
updateTheme(cosmetics.value.preferredDarkTheme ?? "dark");
}
}
};
setColorScheme(colorSchemeQueryList);
colorSchemeQueryList.addEventListener("change", setColorScheme);
}
});
nuxtApp.provide("colorMode", themeStore.value);
});

View File

@@ -0,0 +1,60 @@
import type { DarkTheme } from "./theme/index.ts";
export type DisplayMode = "list" | "gallery" | "grid";
export type DisplayLocation =
| "mod"
| "plugin"
| "resourcepack"
| "modpack"
| "shader"
| "datapack"
| "user"
| "collection";
export interface Cosmetics {
searchLayout: boolean;
projectLayout: boolean;
advancedRendering: boolean;
externalLinksNewTab: boolean;
notUsingBlockers: boolean;
hideModrinthAppPromos: boolean;
preferredDarkTheme: DarkTheme;
searchDisplayMode: Record<DisplayLocation, DisplayMode>;
hideStagingBanner: boolean;
}
export default defineNuxtPlugin({
name: "cosmetics",
setup() {
const cosmetics = useCookie<Cosmetics>("cosmetics", {
maxAge: 60 * 60 * 24 * 365 * 10,
sameSite: "lax",
secure: true,
httpOnly: false,
path: "/",
default: () => ({
searchLayout: false,
projectLayout: false,
advancedRendering: true,
externalLinksNewTab: true,
notUsingBlockers: false,
hideModrinthAppPromos: false,
preferredDarkTheme: "dark",
searchDisplayMode: {
mod: "list",
plugin: "list",
resourcepack: "gallery",
modpack: "list",
shader: "gallery",
datapack: "list",
user: "list",
collection: "list",
},
hideStagingBanner: false,
}),
});
return { provide: { cosmetics } };
},
});

View File

@@ -0,0 +1,90 @@
import { ref } from "vue";
import { isDarkTheme } from "./themes.ts";
import { useNativeTheme } from "./native-theme.ts";
import { usePreferredThemes } from "./preferred-theme.ts";
import { useThemeSettings } from "./theme-settings.ts";
export * from "./themes.ts";
export default defineNuxtPlugin({
name: "theme",
dependsOn: ["cosmetics"],
setup(nuxtApp) {
const $nativeTheme = useNativeTheme();
const $preferredThemes = usePreferredThemes();
function getPreferredNativeTheme() {
const nativeTheme = $nativeTheme.value;
switch (nativeTheme) {
case "light":
return $preferredThemes.light;
case "dark":
case "unknown":
if (import.meta.dev && import.meta.server && nativeTheme === "unknown") {
console.warn(
"[theme] no client hint is available for request, using dark theme as default",
);
}
return $preferredThemes.dark;
}
}
const $settings = useThemeSettings(() => getPreferredNativeTheme());
useHead({ htmlAttrs: { class: () => [`${$settings.active}-mode`] } });
function syncTheme() {
$settings.active =
$settings.preferred === "system" ? getPreferredNativeTheme() : $settings.preferred;
}
if (
import.meta.server &&
$settings.preferred === "system" &&
$nativeTheme.value !== "unknown"
) {
// take advantage of the client hint
syncTheme();
}
if (import.meta.client) {
const $clientReady = ref(false);
nuxtApp.hook("app:suspense:resolve", () => {
$clientReady.value = true;
});
watchEffect(() => $clientReady.value && syncTheme());
}
function cycle() {
const nextTheme = isDarkTheme($settings.active)
? $preferredThemes.light
: $preferredThemes.dark;
$settings.preferred = nextTheme;
return nextTheme;
}
return {
provide: {
theme: reactive({
...toRefs($settings),
/**
* Preferred themes for each mode.
*/
preferences: $preferredThemes,
/**
* Current native (system) theme provided through client hint header or
* `prefers-color-scheme` media query.
*/
native: $nativeTheme,
cycle,
}),
},
};
},
});

View File

@@ -0,0 +1,38 @@
export type SystemTheme = "unknown" | "light" | "dark";
function useNativeThemeServer() {
let clientHint;
switch (useRequestHeader("Sec-CH-Prefers-Color-Scheme")) {
case "light":
clientHint = "light";
break;
case "dark":
clientHint = "dark";
break;
default:
clientHint = "unknown";
}
return computed(() => clientHint as SystemTheme);
}
function useNativeThemeClient() {
const lightPreference = window.matchMedia("(prefers-color-scheme: light)");
const isLight = ref(lightPreference.matches);
const onPreferenceChange = ({ matches }: MediaQueryListEvent) => (isLight.value = matches);
lightPreference.addEventListener("change", onPreferenceChange);
onScopeDispose(() => lightPreference.removeEventListener("change", onPreferenceChange));
return computed<SystemTheme>(() => (isLight.value ? "light" : "dark"));
}
export function useNativeTheme() {
if (import.meta.server) return useNativeThemeServer();
if (import.meta.client) return useNativeThemeClient();
throw new Error("Cannot determine the side");
}

View File

@@ -0,0 +1,32 @@
import { type DarkTheme, isDarkTheme } from "./themes.ts";
export function usePreferredThemes() {
// TODO: migrate theme preferences out of cosmetics to theme settings
const cosmetics = useCosmetics();
const dark = computed({
get(): DarkTheme {
const theme = cosmetics.value?.preferredDarkTheme;
if (theme == null) {
console.warn("[theme] cosmetics.preferredDarkTheme is not defined");
return "dark";
}
if (!isDarkTheme(theme)) {
console.warn(`[theme] cosmetics.preferredDarkTheme contains invalid value: ${theme}`);
return "dark";
}
return theme;
},
set(value) {
cosmetics.value.preferredDarkTheme = value;
},
});
return reactive({
dark,
light: "light" as const,
});
}

View File

@@ -0,0 +1,38 @@
import type { Theme } from "./themes.ts";
interface ThemeSettings {
preference: Theme | "system";
value: Theme;
}
export function useThemeSettings(getDefaultTheme?: () => Theme) {
getDefaultTheme ??= () => "dark";
const $settings = useCookie<ThemeSettings>("color-mode", {
maxAge: 60 * 60 * 24 * 365 * 10,
sameSite: "lax",
secure: true,
httpOnly: false,
path: "/",
});
// reset theme settings to a default value if the cookie is missing or contains invalid value
if ($settings.value == null || typeof $settings.value !== "object") {
$settings.value = {
preference: "system",
value: getDefaultTheme(),
};
}
return reactive({
preferred: computed({
get: () => $settings.value.preference ?? "system",
set: (value) => ($settings.value.preference = value),
}),
active: computed({
get: () => $settings.value.value ?? getDefaultTheme(),
set: (value) => ($settings.value.value = value),
}),
});
}

View File

@@ -0,0 +1,27 @@
export const LightThemes = ["light"] as const;
export type LightTheme = (typeof LightThemes)[number];
export const DarkThemes = ["dark", "oled", "retro"] as const;
export type DarkTheme = (typeof DarkThemes)[number];
export type Theme = LightTheme | DarkTheme;
export function isLightTheme(theme: Theme | (string & Record<never, never>)): theme is LightTheme {
return LightThemes.includes(theme as any);
}
export function isDarkTheme(theme: Theme | (string & Record<never, never>)): theme is DarkTheme {
return DarkThemes.includes(theme as any);
}
export type ThemeType = "light" | "dark";
export function getThemeType(
theme: Theme | (string & Record<never, never>),
): ThemeType | "unknown" {
if (isLightTheme(theme)) return "light";
if (isDarkTheme(theme)) return "dark";
return "unknown";
}