Files
syops/frontend/src/App.vue
T

106 lines
2.8 KiB
Vue

<script setup lang="ts">
import { useI18n } from 'vue-i18n';
import { watch, onMounted, onBeforeUnmount } from 'vue';
import { useTheme } from './composables/useTheme';
import LevelMessageDialog from './components/LevelMessageDialog.vue';
import { useGlobalMessageDialog } from './composables/useGlobalMessageDialog';
import { getAuthHeaders, clearAuthUser } from './utils/auth';
const { locale } = useI18n();
const { themePreference, initTheme, setThemePreference } = useTheme();
const {
messageDialogVisible,
messageDialogLevel,
messageDialogTitle,
messageDialogContent,
showMessageDialog,
closeMessageDialog,
} = useGlobalMessageDialog();
const updateLanguagePreference = async (lang: string) => {
const headers = getAuthHeaders();
if (Object.keys(headers).length === 0) return; // Not logged in
try {
await fetch('/api/user/profile', {
method: 'PUT',
headers: { 'Content-Type': 'application/json', ...headers },
body: JSON.stringify({ language: lang })
});
} catch (e) {
console.error('Failed to update language preference', e);
}
};
const updateThemePreference = async (theme: string) => {
const headers = getAuthHeaders();
if (Object.keys(headers).length === 0) return;
try {
await fetch('/api/user/profile', {
method: 'PUT',
headers: { 'Content-Type': 'application/json', ...headers },
body: JSON.stringify({ theme_preference: theme })
});
} catch (e) {
console.error('Failed to update theme preference', e);
}
};
watch(locale, (newLang) => {
updateLanguagePreference(newLang as string);
});
watch(themePreference, (newTheme) => {
updateThemePreference(newTheme);
});
const onUnauthorized = () => {
showMessageDialog('error', '认证已过期或无效,请重新登录');
clearAuthUser();
if (window.location.pathname !== '/') {
window.location.href = '/';
}
};
onMounted(async () => {
window.addEventListener('hxops:unauthorized', onUnauthorized as EventListener);
initTheme();
const headers = getAuthHeaders();
if (Object.keys(headers).length > 0) {
try {
const res = await fetch('/api/user/home', { headers });
if (res.ok) {
const data = await res.json();
if (data.user && data.user.language) {
locale.value = data.user.language;
}
if (data.user && data.user.theme_preference) {
setThemePreference(data.user.theme_preference);
}
}
} catch (e) {
console.error('Failed to sync language', e);
}
}
});
onBeforeUnmount(() => {
window.removeEventListener('hxops:unauthorized', onUnauthorized as EventListener);
});
</script>
<template>
<router-view />
<LevelMessageDialog
v-model="messageDialogVisible"
:level="messageDialogLevel"
:title="messageDialogTitle"
:message="messageDialogContent"
@close="closeMessageDialog"
/>
</template>