72 lines
2.1 KiB
Vue
72 lines
2.1 KiB
Vue
<script setup lang="ts">
|
|
import { AUTH_CHANGED, authToken } from '~/utils/auth'
|
|
|
|
const { public: { apiBase } } = useRuntimeConfig()
|
|
const route = useRoute()
|
|
const SESSION_PREFIX = 'commander-session-'
|
|
|
|
const authCookie = useCookie('commander-auth-token')
|
|
const signedIn = ref(Boolean(authCookie.value))
|
|
|
|
const seatedGames = ref<{ id: string; label: string }[]>([])
|
|
let poll: ReturnType<typeof setInterval> | undefined
|
|
|
|
function syncAuth() {
|
|
signedIn.value = Boolean(authToken())
|
|
}
|
|
|
|
function seatedGameIds(): string[] {
|
|
return Object.keys(sessionStorage)
|
|
.filter(key => key.startsWith(SESSION_PREFIX))
|
|
.map(key => key.slice(SESSION_PREFIX.length))
|
|
}
|
|
|
|
async function refreshSeatedGames() {
|
|
const ids = seatedGameIds()
|
|
const known = ids.length === seatedGames.value.length && ids.every(id => seatedGames.value.some(game => game.id === id))
|
|
if (known) return
|
|
if (!ids.length) {
|
|
seatedGames.value = []
|
|
return
|
|
}
|
|
try {
|
|
const { games } = await $fetch<{ games: { id: string; hostName: string }[] }>(`${apiBase}/games`)
|
|
seatedGames.value = ids.flatMap(id => {
|
|
const game = games.find(entry => entry.id === id)
|
|
return game ? [{ id, label: `${game.hostName}'s game` }] : []
|
|
})
|
|
} catch {
|
|
// Keep the current tabs when the game list is unavailable.
|
|
}
|
|
}
|
|
|
|
onMounted(() => {
|
|
syncAuth()
|
|
window.addEventListener(AUTH_CHANGED, syncAuth)
|
|
void refreshSeatedGames()
|
|
poll = setInterval(refreshSeatedGames, 5000)
|
|
})
|
|
watch(() => route.fullPath, refreshSeatedGames)
|
|
onUnmounted(() => {
|
|
window.removeEventListener(AUTH_CHANGED, syncAuth)
|
|
if (poll) clearInterval(poll)
|
|
})
|
|
</script>
|
|
|
|
<template>
|
|
<NuxtRouteAnnouncer />
|
|
<nav v-if="signedIn" class="app-nav">
|
|
<strong>Commander</strong>
|
|
<NuxtLink to="/">Play</NuxtLink>
|
|
<NuxtLink to="/decks">Decks</NuxtLink>
|
|
<NuxtLink to="/cards">Cards</NuxtLink>
|
|
<NuxtLink to="/account">Account</NuxtLink>
|
|
<div v-if="seatedGames.length" class="nav-games">
|
|
<NuxtLink v-for="game in seatedGames" :key="game.id" :to="`/games/${game.id}`">
|
|
{{ game.label }}
|
|
</NuxtLink>
|
|
</div>
|
|
</nav>
|
|
<NuxtPage />
|
|
</template>
|