forked from didirus/AstralRinth
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:
@@ -408,6 +408,14 @@ export default defineNuxtConfig({
|
||||
autoprefixer: {},
|
||||
},
|
||||
},
|
||||
routeRules: {
|
||||
"/**": {
|
||||
headers: {
|
||||
"Accept-CH": "Sec-CH-Prefers-Color-Scheme",
|
||||
"Critical-CH": "Sec-CH-Prefers-Color-Scheme",
|
||||
},
|
||||
},
|
||||
},
|
||||
compatibilityDate: "2024-07-03",
|
||||
});
|
||||
|
||||
|
||||
@@ -162,7 +162,7 @@
|
||||
<div
|
||||
:style="{
|
||||
'--color-brand': isUsingProjectColors
|
||||
? intToRgba(project.color, project.id, theme ?? undefined)
|
||||
? intToRgba(project.color, project.id, theme.active ?? undefined)
|
||||
: getDefaultColor(project.id),
|
||||
}"
|
||||
class="legend__item__color"
|
||||
|
||||
@@ -1,52 +0,0 @@
|
||||
export const useCosmetics = () =>
|
||||
useState("cosmetics", () => {
|
||||
const cosmetics = useCookie("cosmetics", {
|
||||
maxAge: 60 * 60 * 24 * 365 * 10,
|
||||
sameSite: "lax",
|
||||
secure: true,
|
||||
httpOnly: false,
|
||||
path: "/",
|
||||
});
|
||||
|
||||
if (!cosmetics.value) {
|
||||
cosmetics.value = {
|
||||
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 cosmetics.value;
|
||||
});
|
||||
|
||||
export const saveCosmetics = () => {
|
||||
const cosmetics = useCosmetics();
|
||||
|
||||
console.log("SAVING COSMETICS:");
|
||||
console.log(cosmetics);
|
||||
|
||||
const cosmeticsCookie = useCookie("cosmetics", {
|
||||
maxAge: 60 * 60 * 24 * 365 * 10,
|
||||
sameSite: "lax",
|
||||
secure: true,
|
||||
httpOnly: false,
|
||||
path: "/",
|
||||
});
|
||||
|
||||
cosmeticsCookie.value = cosmetics.value;
|
||||
};
|
||||
7
apps/frontend/src/composables/nuxt-accessors.ts
Normal file
7
apps/frontend/src/composables/nuxt-accessors.ts
Normal file
@@ -0,0 +1,7 @@
|
||||
export function useTheme() {
|
||||
return useNuxtApp().$theme;
|
||||
}
|
||||
|
||||
export function useCosmetics() {
|
||||
return useNuxtApp().$cosmetics;
|
||||
}
|
||||
@@ -1,58 +0,0 @@
|
||||
export const useTheme = () =>
|
||||
useState("theme", () => {
|
||||
const colorMode = useCookie("color-mode", {
|
||||
maxAge: 60 * 60 * 24 * 365 * 10,
|
||||
sameSite: "lax",
|
||||
secure: true,
|
||||
httpOnly: false,
|
||||
path: "/",
|
||||
});
|
||||
|
||||
if (!colorMode.value) {
|
||||
colorMode.value = {
|
||||
value: "dark",
|
||||
preference: "system",
|
||||
};
|
||||
}
|
||||
|
||||
if (colorMode.value.preference !== "system") {
|
||||
colorMode.value.value = colorMode.value.preference;
|
||||
}
|
||||
|
||||
return colorMode.value;
|
||||
});
|
||||
|
||||
export const updateTheme = (value, updatePreference = false) => {
|
||||
const theme = useTheme();
|
||||
const cosmetics = useCosmetics();
|
||||
|
||||
const themeCookie = useCookie("color-mode", {
|
||||
maxAge: 60 * 60 * 24 * 365 * 10,
|
||||
sameSite: "lax",
|
||||
secure: true,
|
||||
httpOnly: false,
|
||||
path: "/",
|
||||
});
|
||||
|
||||
if (value === "system") {
|
||||
theme.value.preference = "system";
|
||||
|
||||
const colorSchemeQueryList = window.matchMedia("(prefers-color-scheme: light)");
|
||||
if (colorSchemeQueryList.matches) {
|
||||
theme.value.value = "light";
|
||||
} else {
|
||||
theme.value.value = cosmetics.value.preferredDarkTheme;
|
||||
}
|
||||
} else {
|
||||
theme.value.value = value;
|
||||
if (updatePreference) theme.value.preference = value;
|
||||
}
|
||||
|
||||
if (import.meta.client) {
|
||||
document.documentElement.className = `${theme.value.value}-mode`;
|
||||
}
|
||||
|
||||
themeCookie.value = theme.value;
|
||||
};
|
||||
|
||||
export const DARK_THEMES = ["dark", "oled", "retro"];
|
||||
14
apps/frontend/src/composables/vue.ts
Normal file
14
apps/frontend/src/composables/vue.ts
Normal file
@@ -0,0 +1,14 @@
|
||||
/**
|
||||
* Creates a computed reference that uses a provide getter function called with an argument representing the current mount state of the component.
|
||||
* @param getter A getter function that will run with `mounted` argument representing whether or not the component is mounted.
|
||||
* @returns A computed reference that changes when component becomes mounted or unmounted.
|
||||
*/
|
||||
export function useMountedValue<T>(getter: (isMounted: boolean) => T) {
|
||||
const mounted = ref(getCurrentInstance()?.isMounted ?? false);
|
||||
|
||||
onMounted(() => (mounted.value = true));
|
||||
|
||||
onUnmounted(() => (mounted.value = false));
|
||||
|
||||
return computed(() => getter(mounted.value));
|
||||
}
|
||||
@@ -62,7 +62,7 @@
|
||||
:title="formatMessage(messages.changeTheme)"
|
||||
@click="changeTheme"
|
||||
>
|
||||
<MoonIcon v-if="$colorMode.value === 'light'" aria-hidden="true" />
|
||||
<MoonIcon v-if="$theme.active === 'light'" aria-hidden="true" />
|
||||
<SunIcon v-else aria-hidden="true" />
|
||||
</button>
|
||||
<div
|
||||
@@ -242,7 +242,7 @@
|
||||
{{ formatMessage(commonMessages.settingsLabel) }}
|
||||
</NuxtLink>
|
||||
<button class="iconified-button" @click="changeTheme">
|
||||
<MoonIcon v-if="$colorMode.value === 'light'" class="icon" />
|
||||
<MoonIcon v-if="$theme.active === 'light'" class="icon" />
|
||||
<SunIcon v-else class="icon" />
|
||||
<span class="dropdown-item__text">
|
||||
{{ formatMessage(messages.changeTheme) }}
|
||||
@@ -403,7 +403,7 @@
|
||||
{{ formatMessage(messages.getModrinthApp) }}
|
||||
</nuxt-link>
|
||||
<button class="iconified-button raised-button" @click="changeTheme">
|
||||
<MoonIcon v-if="$colorMode.value === 'light'" aria-hidden="true" />
|
||||
<MoonIcon v-if="$theme.active === 'light'" aria-hidden="true" />
|
||||
<SunIcon v-else aria-hidden="true" />
|
||||
{{ formatMessage(messages.changeTheme) }}
|
||||
</button>
|
||||
@@ -449,7 +449,6 @@ import ModalCreation from "~/components/ui/ModalCreation.vue";
|
||||
import Avatar from "~/components/ui/Avatar.vue";
|
||||
import { getProjectTypeMessage } from "~/utils/i18n-project-type.ts";
|
||||
import { commonMessages } from "~/utils/common-messages.ts";
|
||||
import { DARK_THEMES } from "~/composables/theme.js";
|
||||
|
||||
const { formatMessage } = useVIntl();
|
||||
|
||||
@@ -738,18 +737,11 @@ function toggleBrowseMenu() {
|
||||
isMobileMenuOpen.value = false;
|
||||
}
|
||||
}
|
||||
function changeTheme() {
|
||||
updateTheme(
|
||||
DARK_THEMES.includes(app.$colorMode.value)
|
||||
? "light"
|
||||
: cosmetics.value.preferredDarkTheme ?? "dark",
|
||||
true,
|
||||
);
|
||||
}
|
||||
|
||||
const { cycle: changeTheme } = useTheme();
|
||||
|
||||
function hideStagingBanner() {
|
||||
cosmetics.value.hideStagingBanner = true;
|
||||
saveCosmetics();
|
||||
}
|
||||
</script>
|
||||
|
||||
|
||||
@@ -896,7 +896,7 @@ useSeoMeta({
|
||||
</div>
|
||||
<div class="logo-banner">
|
||||
<svg
|
||||
v-if="$colorMode.value === 'light'"
|
||||
v-if="$theme.active === 'light'"
|
||||
viewBox="0 0 865 512"
|
||||
fill="none"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
|
||||
@@ -26,7 +26,7 @@
|
||||
ref="turnstile"
|
||||
v-model="token"
|
||||
class="turnstile"
|
||||
:options="{ theme: $colorMode.value === 'light' ? 'light' : 'dark' }"
|
||||
:options="{ theme: $theme.active === 'light' ? 'light' : 'dark' }"
|
||||
/>
|
||||
|
||||
<button class="btn btn-primary centered-btn" :disabled="!token" @click="recovery">
|
||||
|
||||
@@ -85,7 +85,7 @@
|
||||
ref="turnstile"
|
||||
v-model="token"
|
||||
class="turnstile"
|
||||
:options="{ theme: $colorMode.value === 'light' ? 'light' : 'dark' }"
|
||||
:options="{ theme: $theme.active === 'light' ? 'light' : 'dark' }"
|
||||
/>
|
||||
|
||||
<button
|
||||
|
||||
@@ -110,7 +110,7 @@
|
||||
ref="turnstile"
|
||||
v-model="token"
|
||||
class="turnstile"
|
||||
:options="{ theme: $colorMode.value === 'light' ? 'light' : 'dark' }"
|
||||
:options="{ theme: $theme.active === 'light' ? 'light' : 'dark' }"
|
||||
/>
|
||||
|
||||
<button
|
||||
|
||||
@@ -487,7 +487,6 @@ function cycleSearchDisplayMode() {
|
||||
cosmetics.value.searchDisplayMode.collection,
|
||||
tags.value.projectViewModes,
|
||||
);
|
||||
saveCosmetics();
|
||||
}
|
||||
|
||||
let collection, refreshCollection, creator, projects, refreshProjects;
|
||||
|
||||
@@ -199,7 +199,7 @@
|
||||
<div class="blob-demonstration gradient-border">
|
||||
<div class="launcher-view">
|
||||
<img
|
||||
v-if="$colorMode.value === 'light'"
|
||||
v-if="$theme.active === 'light'"
|
||||
src="https://cdn.modrinth.com/landing-new/launcher-light.webp"
|
||||
alt="launcher graphic"
|
||||
class="minecraft-screen"
|
||||
@@ -407,7 +407,7 @@
|
||||
</div>
|
||||
<div class="logo-banner">
|
||||
<svg
|
||||
v-if="$colorMode.value === 'light'"
|
||||
v-if="$theme.active === 'light'"
|
||||
viewBox="0 0 865 512"
|
||||
fill="none"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
|
||||
@@ -763,7 +763,6 @@ function cycleSearchDisplayMode() {
|
||||
cosmetics.value.searchDisplayMode[projectType.value.id],
|
||||
tags.value.projectViewModes,
|
||||
);
|
||||
saveCosmetics();
|
||||
setClosestMaxResults();
|
||||
}
|
||||
|
||||
|
||||
@@ -21,7 +21,7 @@
|
||||
v-for="option in themeOptions"
|
||||
:key="option"
|
||||
class="preview-radio button-base"
|
||||
:class="{ selected: theme.preference === option }"
|
||||
:class="{ selected: theme.preferred === option }"
|
||||
@click="() => updateColorTheme(option)"
|
||||
>
|
||||
<div class="preview" :class="`${option === 'system' ? systemTheme : option}-mode`">
|
||||
@@ -32,16 +32,16 @@
|
||||
</div>
|
||||
</div>
|
||||
<div class="label">
|
||||
<RadioButtonChecked v-if="theme.preference === option" class="radio" />
|
||||
<RadioButtonChecked v-if="theme.preferred === option" class="radio" />
|
||||
<RadioButtonIcon v-else class="radio" />
|
||||
{{ colorTheme[option] ? formatMessage(colorTheme[option]) : option }}
|
||||
<SunIcon
|
||||
v-if="'light' === option"
|
||||
v-if="theme.preferences.light === option"
|
||||
v-tooltip="formatMessage(colorTheme.preferredLight)"
|
||||
class="theme-icon"
|
||||
/>
|
||||
<MoonIcon
|
||||
v-else-if="(cosmetics.preferredDarkTheme ?? 'dark') === option"
|
||||
v-else-if="theme.preferences.dark === option"
|
||||
v-tooltip="formatMessage(colorTheme.preferredDark)"
|
||||
class="theme-icon"
|
||||
/>
|
||||
@@ -153,7 +153,6 @@
|
||||
v-model="cosmetics.advancedRendering"
|
||||
class="switch stylized-toggle"
|
||||
type="checkbox"
|
||||
@change="saveCosmetics"
|
||||
/>
|
||||
</div>
|
||||
<div class="adjacent-input small">
|
||||
@@ -170,7 +169,6 @@
|
||||
v-model="cosmetics.externalLinksNewTab"
|
||||
class="switch stylized-toggle"
|
||||
type="checkbox"
|
||||
@change="saveCosmetics"
|
||||
/>
|
||||
</div>
|
||||
<div class="adjacent-input small">
|
||||
@@ -187,7 +185,6 @@
|
||||
v-model="cosmetics.hideModrinthAppPromos"
|
||||
class="switch stylized-toggle"
|
||||
type="checkbox"
|
||||
@change="saveCosmetics"
|
||||
/>
|
||||
</div>
|
||||
<div class="adjacent-input small">
|
||||
@@ -204,7 +201,6 @@
|
||||
v-model="cosmetics.searchLayout"
|
||||
class="switch stylized-toggle"
|
||||
type="checkbox"
|
||||
@change="saveCosmetics"
|
||||
/>
|
||||
</div>
|
||||
<div class="adjacent-input small">
|
||||
@@ -221,19 +217,19 @@
|
||||
v-model="cosmetics.projectLayout"
|
||||
class="switch stylized-toggle"
|
||||
type="checkbox"
|
||||
@change="saveCosmetics"
|
||||
/>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { CodeIcon, RadioButtonIcon, RadioButtonChecked, SunIcon, MoonIcon } from "@modrinth/assets";
|
||||
<script setup lang="ts">
|
||||
import { CodeIcon, MoonIcon, RadioButtonChecked, RadioButtonIcon, SunIcon } from "@modrinth/assets";
|
||||
import { Button } from "@modrinth/ui";
|
||||
import { formatProjectType } from "~/plugins/shorthands.js";
|
||||
import MessageBanner from "~/components/ui/MessageBanner.vue";
|
||||
import { DARK_THEMES } from "~/composables/theme.js";
|
||||
import type { DisplayLocation } from "~/plugins/cosmetics";
|
||||
import { formatProjectType } from "~/plugins/shorthands.js";
|
||||
import { isDarkTheme, type Theme } from "~/plugins/theme/index.ts";
|
||||
|
||||
useHead({
|
||||
title: "Display settings - Modrinth",
|
||||
@@ -330,6 +326,10 @@ const projectListLayouts = defineMessages({
|
||||
id: "settings.display.project-list-layouts.user",
|
||||
defaultMessage: "User profile pages",
|
||||
},
|
||||
collection: {
|
||||
id: "settings.display.project-list.layouts.collection",
|
||||
defaultMessage: "Collection",
|
||||
},
|
||||
});
|
||||
|
||||
const toggleFeatures = defineMessages({
|
||||
@@ -390,45 +390,41 @@ const cosmetics = useCosmetics();
|
||||
const flags = useFeatureFlags();
|
||||
const tags = useTags();
|
||||
|
||||
const systemTheme = ref("light");
|
||||
|
||||
const theme = useTheme();
|
||||
|
||||
// On the server the value of native theme can be 'unknown'. To hydrate
|
||||
// correctly, we need to make sure we aren't using 'unknown' and values between
|
||||
// server and client renders are in sync.
|
||||
|
||||
const serverSystemTheme = useState(() => {
|
||||
const theme_ = theme.native;
|
||||
if (theme_ === "unknown") return "light";
|
||||
return theme_;
|
||||
});
|
||||
|
||||
const systemTheme = useMountedValue((mounted): Theme => {
|
||||
const systemTheme_ = mounted ? theme.native : serverSystemTheme.value;
|
||||
return systemTheme_ === "light" ? theme.preferences.light : theme.preferences.dark;
|
||||
});
|
||||
|
||||
const themeOptions = computed(() => {
|
||||
const options = ["system", "light", "dark", "oled"];
|
||||
if (flags.value.developerMode || theme.value.preference === "retro") {
|
||||
const options: ("system" | Theme)[] = ["system", "light", "dark", "oled"];
|
||||
if (flags.value.developerMode || theme.preferred === "retro") {
|
||||
options.push("retro");
|
||||
}
|
||||
return options;
|
||||
});
|
||||
|
||||
onMounted(() => {
|
||||
updateSystemTheme();
|
||||
window.matchMedia("(prefers-color-scheme: light)").addEventListener("change", (event) => {
|
||||
setSystemTheme(event.matches);
|
||||
});
|
||||
});
|
||||
|
||||
function updateSystemTheme() {
|
||||
const query = window.matchMedia("(prefers-color-scheme: light)");
|
||||
setSystemTheme(query.matches);
|
||||
}
|
||||
|
||||
function setSystemTheme(light) {
|
||||
if (light) {
|
||||
systemTheme.value = "light";
|
||||
} else {
|
||||
systemTheme.value = cosmetics.value.preferredDarkTheme ?? "dark";
|
||||
function updateColorTheme(value: Theme | "system") {
|
||||
if (value !== "system") {
|
||||
if (isDarkTheme(value)) {
|
||||
theme.preferences.dark = value;
|
||||
} else {
|
||||
theme.preferences.light = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function updateColorTheme(value) {
|
||||
if (DARK_THEMES.includes(value)) {
|
||||
cosmetics.value.preferredDarkTheme = value;
|
||||
saveCosmetics();
|
||||
updateSystemTheme();
|
||||
}
|
||||
updateTheme(value, true);
|
||||
theme.preferred = value;
|
||||
}
|
||||
|
||||
function disableDeveloperMode() {
|
||||
@@ -445,16 +441,18 @@ function disableDeveloperMode() {
|
||||
const listTypes = computed(() => {
|
||||
const types = tags.value.projectTypes.map((type) => {
|
||||
return {
|
||||
id: type.id,
|
||||
id: type.id as DisplayLocation,
|
||||
name: formatProjectType(type.id) + "s",
|
||||
display: "the " + formatProjectType(type.id).toLowerCase() + "s search page",
|
||||
};
|
||||
});
|
||||
|
||||
types.push({
|
||||
id: "user",
|
||||
id: "user" as DisplayLocation,
|
||||
name: "User profiles",
|
||||
display: "user pages",
|
||||
});
|
||||
|
||||
return types;
|
||||
});
|
||||
</script>
|
||||
|
||||
@@ -489,7 +489,6 @@ function cycleSearchDisplayMode() {
|
||||
cosmetics.value.searchDisplayMode.user,
|
||||
tags.value.projectViewModes,
|
||||
);
|
||||
saveCosmetics();
|
||||
}
|
||||
</script>
|
||||
<script>
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
60
apps/frontend/src/plugins/cosmetics.ts
Normal file
60
apps/frontend/src/plugins/cosmetics.ts
Normal 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 } };
|
||||
},
|
||||
});
|
||||
90
apps/frontend/src/plugins/theme/index.ts
Normal file
90
apps/frontend/src/plugins/theme/index.ts
Normal 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,
|
||||
}),
|
||||
},
|
||||
};
|
||||
},
|
||||
});
|
||||
38
apps/frontend/src/plugins/theme/native-theme.ts
Normal file
38
apps/frontend/src/plugins/theme/native-theme.ts
Normal 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");
|
||||
}
|
||||
32
apps/frontend/src/plugins/theme/preferred-theme.ts
Normal file
32
apps/frontend/src/plugins/theme/preferred-theme.ts
Normal 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,
|
||||
});
|
||||
}
|
||||
38
apps/frontend/src/plugins/theme/theme-settings.ts
Normal file
38
apps/frontend/src/plugins/theme/theme-settings.ts
Normal 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),
|
||||
}),
|
||||
});
|
||||
}
|
||||
27
apps/frontend/src/plugins/theme/themes.ts
Normal file
27
apps/frontend/src/plugins/theme/themes.ts
Normal 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";
|
||||
}
|
||||
@@ -1,38 +0,0 @@
|
||||
export default defineNitroPlugin((nitroApp) => {
|
||||
nitroApp.hooks.hook("render:html", (html, { event }) => {
|
||||
try {
|
||||
const cookies = parseCookies(event);
|
||||
|
||||
if (cookies && cookies["color-mode"]) {
|
||||
const theme = JSON.parse(cookies["color-mode"]);
|
||||
|
||||
html.htmlAttrs.push(`class="${theme.value}-mode"`);
|
||||
} else {
|
||||
html.htmlAttrs.push(`class="dark-mode"`);
|
||||
}
|
||||
|
||||
// Reset cookie attributes to correct ones
|
||||
if (cookies) {
|
||||
const opts = {
|
||||
maxAge: 60 * 60 * 24 * 365 * 10,
|
||||
sameSite: "lax",
|
||||
secure: true,
|
||||
httpOnly: false,
|
||||
path: "/",
|
||||
};
|
||||
|
||||
if (cookies["auth-token"]) {
|
||||
setCookie(event, "auth-token", cookies["auth-token"], opts);
|
||||
}
|
||||
if (cookies["color-mode"]) {
|
||||
setCookie(event, "color-mode", cookies["color-mode"], opts);
|
||||
}
|
||||
if (cookies.cosmetics) {
|
||||
setCookie(event, "cosmetics", cookies.cosmetics, opts);
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -152,7 +152,7 @@ export const analyticsSetToCSVString = (analytics) => {
|
||||
return [header, ...data].join(newline);
|
||||
};
|
||||
|
||||
export const processAnalytics = (category, projects, labelFn, sortFn, mapFn, chartName) => {
|
||||
export const processAnalytics = (category, projects, labelFn, sortFn, mapFn, chartName, theme) => {
|
||||
if (!category || !projects) {
|
||||
return emptyAnalytics;
|
||||
}
|
||||
@@ -219,10 +219,9 @@ export const processAnalytics = (category, projects, labelFn, sortFn, mapFn, cha
|
||||
},
|
||||
],
|
||||
colors: projectData.map((_, i) => {
|
||||
const theme = useTheme();
|
||||
const project = chartData[i];
|
||||
|
||||
return intToRgba(project.color, project.id, theme.value);
|
||||
return intToRgba(project.color, project.id, theme);
|
||||
}),
|
||||
defaultColors: projectData.map((_, i) => {
|
||||
const project = chartData[i];
|
||||
@@ -282,10 +281,10 @@ const sortTimestamp = ([a], [b]) => a - b;
|
||||
const roundValue = ([ts, value]) => [ts, Math.round(parseFloat(value) * 100) / 100];
|
||||
|
||||
const processCountryAnalytics = (c, projects) => processAnalyticsByCountry(c, projects, sortCount);
|
||||
const processNumberAnalytics = (c, projects) =>
|
||||
processAnalytics(c, projects, formatTimestamp, sortTimestamp, null, "Downloads");
|
||||
const processRevAnalytics = (c, projects) =>
|
||||
processAnalytics(c, projects, formatTimestamp, sortTimestamp, roundValue, "Revenue");
|
||||
const processNumberAnalytics = (c, projects, theme) =>
|
||||
processAnalytics(c, projects, formatTimestamp, sortTimestamp, null, "Downloads", theme);
|
||||
const processRevAnalytics = (c, projects, theme) =>
|
||||
processAnalytics(c, projects, formatTimestamp, sortTimestamp, roundValue, "Revenue", theme);
|
||||
|
||||
const useFetchAnalytics = (
|
||||
url,
|
||||
@@ -328,10 +327,12 @@ export const useFetchAllAnalytics = (
|
||||
viewsByCountry: processCountryAnalytics(viewsByCountry.value, selectedProjects.value),
|
||||
}));
|
||||
|
||||
const theme = useTheme();
|
||||
|
||||
const totalData = computed(() => ({
|
||||
downloads: processNumberAnalytics(downloadData.value, projects.value),
|
||||
views: processNumberAnalytics(viewData.value, projects.value),
|
||||
revenue: processRevAnalytics(revenueData.value, projects.value),
|
||||
downloads: processNumberAnalytics(downloadData.value, projects.value, theme.active),
|
||||
views: processNumberAnalytics(viewData.value, projects.value, theme.active),
|
||||
revenue: processRevAnalytics(revenueData.value, projects.value, theme.active),
|
||||
}));
|
||||
|
||||
const fetchData = async (query) => {
|
||||
|
||||
Reference in New Issue
Block a user