app.ts 2.03 KB
import { computed, ref } from "vue";

import { defineStore } from "pinia";

export const useAppStore = defineStore("app", () => {
	const sidebarCollapsed = ref(false);
	const theme = ref<"dark" | "light">("light");
	const loading = ref(false);
	const device = ref<"desktop" | "mobile">("desktop");
	const language = ref("zh-CN");

	const isMobile = computed(() => device.value === "mobile");
	const isDark = computed(() => theme.value === "dark");

	const toggleSidebar = () => {
		sidebarCollapsed.value = !sidebarCollapsed.value;
	};

	const setSidebarCollapsed = (collapsed: boolean) => {
		sidebarCollapsed.value = collapsed;
	};

	const toggleTheme = () => {
		theme.value = theme.value === "light" ? "dark" : "light";
		document.documentElement.dataset.theme = theme.value;
	};

	const setTheme = (newTheme: "dark" | "light") => {
		theme.value = newTheme;
		document.documentElement.dataset.theme = newTheme;
	};

	const setLoading = (isLoading: boolean) => {
		loading.value = isLoading;
	};

	const setDevice = (deviceType: "desktop" | "mobile") => {
		device.value = deviceType;
	};

	const setLanguage = (lang: string) => {
		language.value = lang;
	};

	const initApp = () => {
		const savedTheme = localStorage.getItem("theme") as "dark" | "light" | null;
		if (savedTheme) {
			setTheme(savedTheme);
		}

		const savedSidebarState = localStorage.getItem("sidebarCollapsed");
		if (savedSidebarState !== null) {
			sidebarCollapsed.value = savedSidebarState === "true";
		}

		const checkDevice = () => {
			const width = window.innerWidth;
			setDevice(width < 768 ? "mobile" : "desktop");
		};

		checkDevice();
		window.addEventListener("resize", checkDevice);
	};

	const saveAppState = () => {
		localStorage.setItem("theme", theme.value);
		localStorage.setItem("sidebarCollapsed", String(sidebarCollapsed.value));
	};

	return {
		sidebarCollapsed,
		theme,
		loading,
		device,
		language,
		isMobile,
		isDark,
		toggleSidebar,
		setSidebarCollapsed,
		toggleTheme,
		setTheme,
		setLoading,
		setDevice,
		setLanguage,
		initApp,
		saveAppState,
	};
});