ваше сообщение коммита

This commit is contained in:
2025-05-05 20:34:11 +03:00
parent ef2da22c70
commit bca410e099
20 changed files with 1684 additions and 403 deletions

View File

@@ -4,15 +4,31 @@
<div class="loading-spinner" />
</div>
<RouterView />
<RouterView v-slot="{ Component }">
<component
:is="Component"
:isAuthenticated="auth.isAuthenticated.value"
:identities="auth.identities.value"
:tokenBalances="tokenBalances"
:isLoadingTokens="isLoadingTokens"
@auth-action-completed="handleAuthActionCompleted"
/>
</RouterView>
</div>
</template>
<script setup>
import { ref, watch } from 'vue';
import { ref, watch, onMounted, computed } from 'vue';
import { RouterView } from 'vue-router';
import { useAuth } from './composables/useAuth';
import './assets/styles/home.css';
import { fetchTokenBalances } from './services/tokens';
import eventBus from './utils/eventBus';
// Импорт стилей
import './assets/styles/variables.css';
import './assets/styles/base.css';
import './assets/styles/layout.css';
import './assets/styles/global.css';
// Состояние загрузки
const isLoading = ref(false);
@@ -20,10 +36,111 @@
// Использование composable для аутентификации
const auth = useAuth();
// --- Логика загрузки баланса токенов ---
const tokenBalances = ref({});
const isLoadingTokens = ref(false);
const identities = computed(() => auth.identities.value);
const hasIdentityType = (type) => {
if (!identities.value) return false;
return identities.value.some((identity) => identity.provider === type);
};
const getIdentityValue = (type) => {
if (!identities.value) return null;
const identity = identities.value.find((identity) => identity.provider === type);
return identity ? identity.provider_id : null;
};
const refreshTokenBalances = async () => {
if (!hasIdentityType('wallet') || !auth.isAuthenticated.value) {
tokenBalances.value = {}; // Очищаем, если нет кошелька или не авторизован
return;
}
isLoadingTokens.value = true;
try {
const walletAddress = getIdentityValue('wallet');
console.log('[App] Обновление балансов для адреса:', walletAddress);
const balances = await fetchTokenBalances(walletAddress);
console.log('[App] Полученные балансы:', balances);
tokenBalances.value = balances || {};
} catch (error) {
console.error('[App] Ошибка при получении балансов:', error);
tokenBalances.value = {};
} finally {
isLoadingTokens.value = false;
}
};
// Следим за изменениями в идентификаторах
watch(identities, (newIdentities, oldIdentities) => {
if (auth.isAuthenticated.value) {
const newWalletId = getIdentityValue('wallet');
const oldWalletIdentity = oldIdentities ? oldIdentities.find(id => id.provider === 'wallet') : null;
const oldWalletId = oldWalletIdentity ? oldWalletIdentity.provider_id : null;
if (newWalletId !== oldWalletId) {
console.log('[App] Обнаружено изменение идентификатора кошелька, обновляем балансы');
refreshTokenBalances();
} else if (hasIdentityType('wallet') && Object.keys(tokenBalances.value).length === 0 && !isLoadingTokens.value) {
// Если кошелек есть, но баланс пустой и не грузится - пробуем загрузить
console.log('[App] Кошелек есть, но баланс пуст, пытаемся загрузить.');
refreshTokenBalances();
}
}
}, { deep: true });
// Мониторинг изменений состояния аутентификации
watch(auth.isAuthenticated, (newValue, oldValue) => {
if (newValue !== oldValue) {
console.log('[App] Состояние аутентификации изменилось:', newValue);
watch(auth.isAuthenticated, (isAuth) => {
console.log('[App] Состояние аутентификации изменилось:', isAuth);
if (isAuth) {
// Убираем задержку, полагаемся на watch(identities) или прямо вызываем
// setTimeout(refreshTokenBalances, 500);
refreshTokenBalances(); // Вызываем сразу, если нужно обновить при смене auth
} else {
// Очищаем баланс при выходе
tokenBalances.value = {};
}
});
// --- Возвращаем и улучшаем функцию-обработчик ---
const handleAuthActionCompleted = async () => {
console.log('[App] Auth action completed, triggering updates...');
isLoading.value = true; // Показываем индикатор загрузки
try {
// 1. Проверяем аутентификацию (обновит identities и isAuthenticated)
await auth.checkAuth();
console.log('[App] auth.checkAuth() completed. isAuthenticated:', auth.isAuthenticated.value);
// 2. Обновляем баланс (использует обновленные identities)
await refreshTokenBalances();
console.log('[App] refreshTokenBalances() completed.');
// 3. Явно оповещаем компоненты об изменении состояния авторизации
// Передаем актуальное состояние из useAuth
eventBus.emit('auth-state-changed', {
isAuthenticated: auth.isAuthenticated.value,
authType: auth.authType.value, // Предполагаем, что authType есть в useAuth
userId: auth.userId.value, // Предполагаем, что userId есть в useAuth
fromApp: true // Флаг, что событие от App.vue
});
console.log('[App] auth-state-changed event emitted.');
} catch (error) {
console.error("[App] Error during auth action handling:", error);
} finally {
isLoading.value = false; // Скрываем индикатор загрузки
}
};
// Первичная загрузка баланса при монтировании, если пользователь уже авторизован
onMounted(() => {
if (auth.isAuthenticated.value) {
refreshTokenBalances();
}
});
</script>