Rewrite cosmetics and theme preferences (#1292)

- 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.

- 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.
This commit is contained in:
Sasha Sorokin
2024-07-13 21:20:43 +02:00
committed by GitHub
parent ce4250281f
commit 8704d3acb3
21 changed files with 268 additions and 248 deletions

View File

@@ -392,6 +392,14 @@ export default defineNuxtConfig({
autoprefixer: {}, autoprefixer: {},
}, },
}, },
routeRules: {
"/**": {
headers: {
"Accept-CH": "Sec-CH-Prefers-Color-Scheme",
"Critical-CH": "Sec-CH-Prefers-Color-Scheme",
},
},
},
compatibilityDate: "2024-07-03", compatibilityDate: "2024-07-03",
}); });

View File

@@ -162,7 +162,7 @@
<div <div
:style="{ :style="{
'--color-brand': isUsingProjectColors '--color-brand': isUsingProjectColors
? intToRgba(project.color, project.id, theme ?? undefined) ? intToRgba(project.color, project.id, theme.active ?? undefined)
: getDefaultColor(project.id), : getDefaultColor(project.id),
}" }"
class="legend__item__color" class="legend__item__color"

View File

@@ -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;
};

View File

@@ -0,0 +1,7 @@
export function useTheme() {
return useNuxtApp().$theme;
}
export function useCosmetics() {
return useNuxtApp().$cosmetics;
}

View File

@@ -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"];

View 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));
}

View File

@@ -62,7 +62,7 @@
:title="formatMessage(messages.changeTheme)" :title="formatMessage(messages.changeTheme)"
@click="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" /> <SunIcon v-else aria-hidden="true" />
</button> </button>
<div <div
@@ -242,7 +242,7 @@
{{ formatMessage(commonMessages.settingsLabel) }} {{ formatMessage(commonMessages.settingsLabel) }}
</NuxtLink> </NuxtLink>
<button class="iconified-button" @click="changeTheme"> <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" /> <SunIcon v-else class="icon" />
<span class="dropdown-item__text"> <span class="dropdown-item__text">
{{ formatMessage(messages.changeTheme) }} {{ formatMessage(messages.changeTheme) }}
@@ -403,7 +403,7 @@
{{ formatMessage(messages.getModrinthApp) }} {{ formatMessage(messages.getModrinthApp) }}
</nuxt-link> </nuxt-link>
<button class="iconified-button raised-button" @click="changeTheme"> <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" /> <SunIcon v-else aria-hidden="true" />
{{ formatMessage(messages.changeTheme) }} {{ formatMessage(messages.changeTheme) }}
</button> </button>
@@ -449,7 +449,6 @@ import ModalCreation from "~/components/ui/ModalCreation.vue";
import Avatar from "~/components/ui/Avatar.vue"; import Avatar from "~/components/ui/Avatar.vue";
import { getProjectTypeMessage } from "~/utils/i18n-project-type.ts"; import { getProjectTypeMessage } from "~/utils/i18n-project-type.ts";
import { commonMessages } from "~/utils/common-messages.ts"; import { commonMessages } from "~/utils/common-messages.ts";
import { DARK_THEMES } from "~/composables/theme.js";
const { formatMessage } = useVIntl(); const { formatMessage } = useVIntl();
@@ -738,18 +737,11 @@ function toggleBrowseMenu() {
isMobileMenuOpen.value = false; isMobileMenuOpen.value = false;
} }
} }
function changeTheme() {
updateTheme( const { cycle: changeTheme } = useTheme();
DARK_THEMES.includes(app.$colorMode.value)
? "light"
: cosmetics.value.preferredDarkTheme ?? "dark",
true,
);
}
function hideStagingBanner() { function hideStagingBanner() {
cosmetics.value.hideStagingBanner = true; cosmetics.value.hideStagingBanner = true;
saveCosmetics();
} }
</script> </script>

View File

@@ -896,7 +896,7 @@ useSeoMeta({
</div> </div>
<div class="logo-banner"> <div class="logo-banner">
<svg <svg
v-if="$colorMode.value === 'light'" v-if="$theme.active === 'light'"
viewBox="0 0 865 512" viewBox="0 0 865 512"
fill="none" fill="none"
xmlns="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg"

View File

@@ -26,7 +26,7 @@
ref="turnstile" ref="turnstile"
v-model="token" v-model="token"
class="turnstile" 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"> <button class="btn btn-primary centered-btn" :disabled="!token" @click="recovery">

View File

@@ -85,7 +85,7 @@
ref="turnstile" ref="turnstile"
v-model="token" v-model="token"
class="turnstile" class="turnstile"
:options="{ theme: $colorMode.value === 'light' ? 'light' : 'dark' }" :options="{ theme: $theme.active === 'light' ? 'light' : 'dark' }"
/> />
<button <button

View File

@@ -110,7 +110,7 @@
ref="turnstile" ref="turnstile"
v-model="token" v-model="token"
class="turnstile" class="turnstile"
:options="{ theme: $colorMode.value === 'light' ? 'light' : 'dark' }" :options="{ theme: $theme.active === 'light' ? 'light' : 'dark' }"
/> />
<button <button

View File

@@ -487,7 +487,6 @@ function cycleSearchDisplayMode() {
cosmetics.value.searchDisplayMode.collection, cosmetics.value.searchDisplayMode.collection,
tags.value.projectViewModes, tags.value.projectViewModes,
); );
saveCosmetics();
} }
let collection, refreshCollection, creator, projects, refreshProjects; let collection, refreshCollection, creator, projects, refreshProjects;

View File

@@ -199,7 +199,7 @@
<div class="blob-demonstration gradient-border"> <div class="blob-demonstration gradient-border">
<div class="launcher-view"> <div class="launcher-view">
<img <img
v-if="$colorMode.value === 'light'" v-if="$theme.active === 'light'"
src="https://cdn.modrinth.com/landing-new/launcher-light.webp" src="https://cdn.modrinth.com/landing-new/launcher-light.webp"
alt="launcher graphic" alt="launcher graphic"
class="minecraft-screen" class="minecraft-screen"
@@ -407,7 +407,7 @@
</div> </div>
<div class="logo-banner"> <div class="logo-banner">
<svg <svg
v-if="$colorMode.value === 'light'" v-if="$theme.active === 'light'"
viewBox="0 0 865 512" viewBox="0 0 865 512"
fill="none" fill="none"
xmlns="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg"

View File

@@ -763,7 +763,6 @@ function cycleSearchDisplayMode() {
cosmetics.value.searchDisplayMode[projectType.value.id], cosmetics.value.searchDisplayMode[projectType.value.id],
tags.value.projectViewModes, tags.value.projectViewModes,
); );
saveCosmetics();
setClosestMaxResults(); setClosestMaxResults();
} }

View File

@@ -21,7 +21,7 @@
v-for="option in themeOptions" v-for="option in themeOptions"
:key="option" :key="option"
class="preview-radio button-base" class="preview-radio button-base"
:class="{ selected: theme.preference === option }" :class="{ selected: theme.preferred === option }"
@click="() => updateColorTheme(option)" @click="() => updateColorTheme(option)"
> >
<div class="preview" :class="`${option === 'system' ? systemTheme : option}-mode`"> <div class="preview" :class="`${option === 'system' ? systemTheme : option}-mode`">
@@ -32,7 +32,7 @@
</div> </div>
</div> </div>
<div class="label"> <div class="label">
<RadioButtonChecked v-if="theme.preference === option" class="radio" /> <RadioButtonChecked v-if="theme.preferred === option" class="radio" />
<RadioButtonIcon v-else class="radio" /> <RadioButtonIcon v-else class="radio" />
{{ colorTheme[option] ? formatMessage(colorTheme[option]) : option }} {{ colorTheme[option] ? formatMessage(colorTheme[option]) : option }}
<SunIcon <SunIcon
@@ -153,7 +153,6 @@
v-model="cosmetics.advancedRendering" v-model="cosmetics.advancedRendering"
class="switch stylized-toggle" class="switch stylized-toggle"
type="checkbox" type="checkbox"
@change="saveCosmetics"
/> />
</div> </div>
<div class="adjacent-input small"> <div class="adjacent-input small">
@@ -170,7 +169,6 @@
v-model="cosmetics.externalLinksNewTab" v-model="cosmetics.externalLinksNewTab"
class="switch stylized-toggle" class="switch stylized-toggle"
type="checkbox" type="checkbox"
@change="saveCosmetics"
/> />
</div> </div>
<div class="adjacent-input small"> <div class="adjacent-input small">
@@ -187,7 +185,6 @@
v-model="cosmetics.hideModrinthAppPromos" v-model="cosmetics.hideModrinthAppPromos"
class="switch stylized-toggle" class="switch stylized-toggle"
type="checkbox" type="checkbox"
@change="saveCosmetics"
/> />
</div> </div>
<div class="adjacent-input small"> <div class="adjacent-input small">
@@ -204,7 +201,6 @@
v-model="cosmetics.searchLayout" v-model="cosmetics.searchLayout"
class="switch stylized-toggle" class="switch stylized-toggle"
type="checkbox" type="checkbox"
@change="saveCosmetics"
/> />
</div> </div>
<div class="adjacent-input small"> <div class="adjacent-input small">
@@ -221,19 +217,19 @@
v-model="cosmetics.projectLayout" v-model="cosmetics.projectLayout"
class="switch stylized-toggle" class="switch stylized-toggle"
type="checkbox" type="checkbox"
@change="saveCosmetics"
/> />
</div> </div>
</section> </section>
</div> </div>
</template> </template>
<script setup> <script setup lang="ts">
import { CodeIcon, RadioButtonIcon, RadioButtonChecked, SunIcon, MoonIcon } from "@modrinth/assets"; import { CodeIcon, RadioButtonIcon, RadioButtonChecked, SunIcon, MoonIcon } from "@modrinth/assets";
import { Button } from "@modrinth/ui"; import { Button } from "@modrinth/ui";
import { formatProjectType } from "~/plugins/shorthands.js"; import { formatProjectType } from "~/plugins/shorthands.js";
import MessageBanner from "~/components/ui/MessageBanner.vue"; import MessageBanner from "~/components/ui/MessageBanner.vue";
import { DARK_THEMES } from "~/composables/theme.js"; import { DarkThemes, type Theme } from "~/plugins/theme.ts";
import type { DisplayLocation } from "~/plugins/cosmetics";
useHead({ useHead({
title: "Display settings - Modrinth", title: "Display settings - Modrinth",
@@ -330,6 +326,10 @@ const projectListLayouts = defineMessages({
id: "settings.display.project-list-layouts.user", id: "settings.display.project-list-layouts.user",
defaultMessage: "User profile pages", defaultMessage: "User profile pages",
}, },
collection: {
id: "settings.display.project-list.layouts.collection",
defaultMessage: "Collection",
},
}); });
const toggleFeatures = defineMessages({ const toggleFeatures = defineMessages({
@@ -390,45 +390,32 @@ const cosmetics = useCosmetics();
const flags = useFeatureFlags(); const flags = useFeatureFlags();
const tags = useTags(); const tags = useTags();
const systemTheme = ref("light");
const theme = useTheme(); const theme = useTheme();
// On the server the value of native theme can be 'unknown'. To ensure we're
// hydrating correctly, we need to make sure we aren't using 'unknown' or
// otherwise wait until we are mounted and supposedly hydrated at this point...
const systemTheme = useMountedValue((mounted) => {
if (import.meta.server && theme.native !== "unknown") return theme.native;
return mounted ? theme.native : theme.active;
});
const themeOptions = computed(() => { const themeOptions = computed(() => {
const options = ["system", "light", "dark", "oled"]; const options: Theme[] = ["system", "light", "dark", "oled"];
if (flags.value.developerMode || theme.value.preference === "retro") { if (flags.value.developerMode || theme.preferred === "retro") {
options.push("retro"); options.push("retro");
} }
return options; return options;
}); });
onMounted(() => { function updateColorTheme(value: Theme) {
updateSystemTheme(); if (DarkThemes.includes(value)) {
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) {
if (DARK_THEMES.includes(value)) {
cosmetics.value.preferredDarkTheme = value; cosmetics.value.preferredDarkTheme = value;
saveCosmetics();
updateSystemTheme();
} }
updateTheme(value, true);
theme.preferred = value;
} }
function disableDeveloperMode() { function disableDeveloperMode() {
@@ -445,16 +432,18 @@ function disableDeveloperMode() {
const listTypes = computed(() => { const listTypes = computed(() => {
const types = tags.value.projectTypes.map((type) => { const types = tags.value.projectTypes.map((type) => {
return { return {
id: type.id, id: type.id as DisplayLocation,
name: formatProjectType(type.id) + "s", name: formatProjectType(type.id) + "s",
display: "the " + formatProjectType(type.id).toLowerCase() + "s search page", display: "the " + formatProjectType(type.id).toLowerCase() + "s search page",
}; };
}); });
types.push({ types.push({
id: "user", id: "user" as DisplayLocation,
name: "User profiles", name: "User profiles",
display: "user pages", display: "user pages",
}); });
return types; return types;
}); });
</script> </script>

View File

@@ -489,7 +489,6 @@ function cycleSearchDisplayMode() {
cosmetics.value.searchDisplayMode.user, cosmetics.value.searchDisplayMode.user,
tags.value.projectViewModes, tags.value.projectViewModes,
); );
saveCosmetics();
} }
</script> </script>
<script> <script>

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,57 @@
import type { Theme } from "./theme.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: Theme;
searchDisplayMode: Record<DisplayLocation, DisplayMode>;
hideStagingBanner: boolean;
}
export default defineNuxtPlugin(() => {
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,130 @@
import { ref, computed } from "vue";
export type Theme = "system" | "light" | "dark" | "oled" | "retro";
export const DarkThemes: Theme[] = ["dark", "oled", "retro"];
export type SystemTheme = "unknown" | "light" | "dark";
function useNativeTheme() {
if (import.meta.server) {
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);
}
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"));
}
interface ThemeSettings {
preference: Theme;
value: Exclude<Theme, "system">;
}
export default defineNuxtPlugin((nuxtApp) => {
const $nativeTheme = useNativeTheme();
const $themeSettings = useCookie<ThemeSettings>("color-mode", {
maxAge: 60 * 60 * 24 * 365 * 10,
sameSite: "lax",
secure: true,
httpOnly: false,
path: "/",
default: () => ({
preference: "system",
// if we have a client hint - use the associated theme, otherwise use dark
// theme, because it's worse to have a bright flash in the dark than just
// darkened screen in the light
value: $nativeTheme.value === "unknown" ? "dark" : $nativeTheme.value,
}),
});
const $preferredTheme = toRef($themeSettings.value, "preference");
const $cosmetics = useCosmetics();
const $activeTheme = toRef($themeSettings.value, "value");
useHead({ htmlAttrs: { class: () => [`${$activeTheme.value}-mode`] } });
function syncTheme() {
const preferredTheme = $preferredTheme.value;
if (preferredTheme === "system") {
const nativeTheme = $nativeTheme.value;
if (nativeTheme === "unknown" || nativeTheme === "dark") {
let { preferredDarkTheme } = $cosmetics.value;
if (preferredDarkTheme === "system") {
// fail safe in case the user is messing with internals
preferredDarkTheme = "dark";
}
$activeTheme.value = preferredDarkTheme;
} else {
$activeTheme.value = nativeTheme;
}
return;
}
$activeTheme.value = preferredTheme;
}
if (
import.meta.server &&
$preferredTheme.value === "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() {
$preferredTheme.value = DarkThemes.includes($activeTheme.value)
? "light"
: $cosmetics.value.preferredDarkTheme;
}
return {
provide: {
theme: reactive({
preferred: $preferredTheme,
active: $activeTheme,
native: $nativeTheme,
cycle,
}),
},
};
});

View File

@@ -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);
}
});
});

View File

@@ -152,7 +152,7 @@ export const analyticsSetToCSVString = (analytics) => {
return [header, ...data].join(newline); 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) { if (!category || !projects) {
return emptyAnalytics; return emptyAnalytics;
} }
@@ -219,10 +219,9 @@ export const processAnalytics = (category, projects, labelFn, sortFn, mapFn, cha
}, },
], ],
colors: projectData.map((_, i) => { colors: projectData.map((_, i) => {
const theme = useTheme();
const project = chartData[i]; const project = chartData[i];
return intToRgba(project.color, project.id, theme.value); return intToRgba(project.color, project.id, theme);
}), }),
defaultColors: projectData.map((_, i) => { defaultColors: projectData.map((_, i) => {
const project = chartData[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 roundValue = ([ts, value]) => [ts, Math.round(parseFloat(value) * 100) / 100];
const processCountryAnalytics = (c, projects) => processAnalyticsByCountry(c, projects, sortCount); const processCountryAnalytics = (c, projects) => processAnalyticsByCountry(c, projects, sortCount);
const processNumberAnalytics = (c, projects) => const processNumberAnalytics = (c, projects, theme) =>
processAnalytics(c, projects, formatTimestamp, sortTimestamp, null, "Downloads"); processAnalytics(c, projects, formatTimestamp, sortTimestamp, null, "Downloads", theme);
const processRevAnalytics = (c, projects) => const processRevAnalytics = (c, projects, theme) =>
processAnalytics(c, projects, formatTimestamp, sortTimestamp, roundValue, "Revenue"); processAnalytics(c, projects, formatTimestamp, sortTimestamp, roundValue, "Revenue", theme);
const useFetchAnalytics = ( const useFetchAnalytics = (
url, url,
@@ -328,10 +327,12 @@ export const useFetchAllAnalytics = (
viewsByCountry: processCountryAnalytics(viewsByCountry.value, selectedProjects.value), viewsByCountry: processCountryAnalytics(viewsByCountry.value, selectedProjects.value),
})); }));
const theme = useTheme();
const totalData = computed(() => ({ const totalData = computed(() => ({
downloads: processNumberAnalytics(downloadData.value, projects.value), downloads: processNumberAnalytics(downloadData.value, projects.value, theme.active),
views: processNumberAnalytics(viewData.value, projects.value), views: processNumberAnalytics(viewData.value, projects.value, theme.active),
revenue: processRevAnalytics(revenueData.value, projects.value), revenue: processRevAnalytics(revenueData.value, projects.value, theme.active),
})); }));
const fetchData = async (query) => { const fetchData = async (query) => {