import { computed, ref } from 'vue' import { defineStore } from 'pinia' import { adminNavigation, filterAdminNavigation, getFirstNavigationLeaf, } from '@/core/navigation/adminNavigation' import { useAuthStore } from '@/core/auth/auth' const LOCAL_FULL_ACCESS_STORAGE_KEY = 'baiyue-admin-local-full-access' class LocalFullAccessPermissionSet extends Set { override has(_permissionCode: string): boolean { return true } } export function isLocalFullAccessHost(hostname: string): boolean { return hostname === 'localhost' || hostname === '127.0.0.1' || hostname === '::1' } export const useAccessPreviewStore = defineStore('access-preview', () => { const auth = useAuthStore() const initialized = ref(false) const localFullAccessAvailable = import.meta.env.DEV && typeof window !== 'undefined' && isLocalFullAccessHost(window.location.hostname) const localFullAccessEnabled = ref( localFullAccessAvailable && window.localStorage.getItem(LOCAL_FULL_ACCESS_STORAGE_KEY) === 'true', ) const permissionCodes = computed>(() => ( localFullAccessEnabled.value ? new LocalFullAccessPermissionSet(auth.permissionCodes) : auth.permissionCodes )) const permissionSignature = computed(() => ( localFullAccessEnabled.value ? '__LOCAL_FULL_ACCESS__' : [...permissionCodes.value].sort().join('|') )) const filteredNavigation = computed(() => filterAdminNavigation(adminNavigation, permissionCodes.value)) const firstAccessiblePath = computed(() => getFirstNavigationLeaf(filteredNavigation.value)?.path ?? null) function initializeAfterLogin() { initialized.value = auth.isAuthenticated } function can(permissionCode: string): boolean { return permissionCodes.value.has(permissionCode) } function setLocalFullAccessEnabled(enabled: boolean) { if (!localFullAccessAvailable) return localFullAccessEnabled.value = enabled if (enabled) window.localStorage.setItem(LOCAL_FULL_ACCESS_STORAGE_KEY, 'true') else window.localStorage.removeItem(LOCAL_FULL_ACCESS_STORAGE_KEY) } function toggleLocalFullAccess() { setLocalFullAccessEnabled(!localFullAccessEnabled.value) } function reset() { initialized.value = false } return { initialized, localFullAccessAvailable, localFullAccessEnabled, permissionCodes, permissionSignature, filteredNavigation, firstAccessiblePath, initializeAfterLogin, can, setLocalFullAccessEnabled, toggleLocalFullAccess, reset, } })