mirror of
https://github.com/BeamMP/BeamMP-Website.git
synced 2026-11-29 01:04:27 +00:00
Compare commits
16
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3907e1ae42 | ||
|
|
b7666cec1f | ||
|
|
38955dcbfe | ||
|
|
1488e3bbdb | ||
|
|
700932de82 | ||
|
|
5e1da1cc4b | ||
|
|
b772af5d39 | ||
|
|
e317ede87f | ||
|
|
836b2c3878 | ||
|
|
77c1d01025 | ||
|
|
9f20c38abe | ||
|
|
f45156a143 | ||
|
|
46b0a26969 | ||
|
|
7a268897f1 | ||
|
|
f450856b42 | ||
|
|
5304762dbb |
No files matched your search
@@ -0,0 +1,23 @@
|
||||
name: CI
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
push:
|
||||
branches: [main]
|
||||
|
||||
jobs:
|
||||
checks:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 22
|
||||
cache: npm
|
||||
- run: npm ci
|
||||
- name: Lint
|
||||
run: npm run lint:check
|
||||
- name: Tests
|
||||
run: npm test
|
||||
- name: Build
|
||||
run: npm run build
|
||||
@@ -5,7 +5,26 @@ on:
|
||||
types: [published]
|
||||
|
||||
jobs:
|
||||
# Nothing is built and pushed unless the same checks the CI workflow runs pass first.
|
||||
checks:
|
||||
if: "!github.event.release.prerelease"
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 22
|
||||
cache: npm
|
||||
- run: npm ci
|
||||
- name: Lint
|
||||
run: npm run lint:check
|
||||
- name: Tests
|
||||
run: npm test
|
||||
- name: Build
|
||||
run: npm run build
|
||||
|
||||
docker:
|
||||
needs: checks
|
||||
if: "!github.event.release.prerelease"
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
|
||||
@@ -5,7 +5,26 @@ on:
|
||||
types: [published]
|
||||
|
||||
jobs:
|
||||
# Nothing is built and pushed unless the same checks the CI workflow runs pass first.
|
||||
checks:
|
||||
if: github.event.release.prerelease
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 22
|
||||
cache: npm
|
||||
- run: npm ci
|
||||
- name: Lint
|
||||
run: npm run lint:check
|
||||
- name: Tests
|
||||
run: npm test
|
||||
- name: Build
|
||||
run: npm run build
|
||||
|
||||
docker:
|
||||
needs: checks
|
||||
if: github.event.release.prerelease
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
|
||||
@@ -34,6 +34,7 @@ export default [
|
||||
alert: 'readonly',
|
||||
prompt: 'readonly',
|
||||
getComputedStyle: 'readonly',
|
||||
Image: 'readonly',
|
||||
// Node globals
|
||||
process: 'readonly',
|
||||
__dirname: 'readonly',
|
||||
@@ -71,4 +72,24 @@ export default [
|
||||
'no-var': 'error',
|
||||
},
|
||||
},
|
||||
// Tests: Vitest's globals (vitest.config.js sets `globals: true`) and the
|
||||
// browser classes jsdom provides.
|
||||
{
|
||||
files: ['tests/**/*.js', 'vitest.config.js'],
|
||||
languageOptions: {
|
||||
globals: {
|
||||
describe: 'readonly',
|
||||
test: 'readonly',
|
||||
it: 'readonly',
|
||||
expect: 'readonly',
|
||||
vi: 'readonly',
|
||||
beforeEach: 'readonly',
|
||||
afterEach: 'readonly',
|
||||
beforeAll: 'readonly',
|
||||
afterAll: 'readonly',
|
||||
globalThis: 'readonly',
|
||||
HTMLCanvasElement: 'readonly',
|
||||
},
|
||||
},
|
||||
},
|
||||
]
|
||||
Generated
+1222
-29
File diff suppressed because it is too large.
Load diff
+9
-3
@@ -1,13 +1,16 @@
|
||||
{
|
||||
"name": "beammp-website",
|
||||
"private": true,
|
||||
"version": "2.5.4",
|
||||
"version": "2.7.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "vite build",
|
||||
"preview": "vite preview",
|
||||
"lint": "eslint . --fix",
|
||||
"lint:check": "eslint .",
|
||||
"test": "vitest run",
|
||||
"test:watch": "vitest",
|
||||
"format": "prettier --write \"src/**/*.{js,vue,css,json}\""
|
||||
},
|
||||
"dependencies": {
|
||||
@@ -23,18 +26,21 @@
|
||||
"tailwindcss": "^4.1.17",
|
||||
"tailwindcss-animate": "^1.0.7",
|
||||
"vue": "^3.5.25",
|
||||
"vue-i18n": "^11.2.2",
|
||||
"vue-i18n": "^11.4.14",
|
||||
"vue-router": "^4.6.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@vitejs/plugin-vue": "^6.0.2",
|
||||
"@vue/eslint-config-prettier": "^10.2.0",
|
||||
"@vue/test-utils": "^2.5.1",
|
||||
"eslint": "^9.39.1",
|
||||
"eslint-config-prettier": "^10.1.8",
|
||||
"eslint-plugin-prettier": "^5.5.4",
|
||||
"eslint-plugin-vue": "^10.6.2",
|
||||
"jsdom": "^29.1.1",
|
||||
"prettier": "^3.7.3",
|
||||
"tw-animate-css": "^1.4.0",
|
||||
"vite": "^8.0.16"
|
||||
"vite": "^8.0.16",
|
||||
"vitest": "^4.1.11"
|
||||
}
|
||||
}
|
||||
@@ -76,11 +76,11 @@
|
||||
"website": "https://tlsservers.com/beammp",
|
||||
"from": "$2.00/mo",
|
||||
"logo": "/partner_logos/TLS_Servers-Studios.png"
|
||||
}
|
||||
{
|
||||
},
|
||||
{
|
||||
"name": "RaveNodes",
|
||||
"website": "https://www.ravenodes.com/beammp-hosting",
|
||||
"from": "$1.00/mo",
|
||||
"logo": "/partner_logos/RaveNodes.png"
|
||||
}
|
||||
]
|
||||
]
|
||||
@@ -1,5 +1,5 @@
|
||||
<script setup>
|
||||
import { Github, Facebook, Instagram, createLucideIcon } from 'lucide-vue-next'
|
||||
import { Github, Facebook, Instagram, Twitch, createLucideIcon } from 'lucide-vue-next'
|
||||
import { getLocalizedPath } from '@/utils/locale'
|
||||
import { RouterLink, useRoute } from 'vue-router'
|
||||
|
||||
@@ -143,6 +143,16 @@ const TikTokIcon = createLucideIcon('TikTok', [
|
||||
>
|
||||
<BlueskyIcon class="w-5 h-5" />
|
||||
</a>
|
||||
<!-- Twitch -->
|
||||
<a
|
||||
href="https://www.twitch.tv/beammpofficial"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
class="text-neutral-500 hover:text-beammp-blue transition-colors dark:text-neutral-400 dark:hover:text-blue-400"
|
||||
aria-label="Twitch"
|
||||
>
|
||||
<Twitch class="w-5 h-5" />
|
||||
</a>
|
||||
<!-- Instagram -->
|
||||
<a
|
||||
href="https://www.instagram.com/beammpofficial"
|
||||
|
||||
@@ -11,12 +11,14 @@ import {
|
||||
import { cn } from '@/lib/utils'
|
||||
import ThemeToggle from '@/components/ThemeToggle.vue'
|
||||
import LanguageSelector from '@/components/LanguageSelector.vue'
|
||||
import { Menu, X } from 'lucide-vue-next'
|
||||
import { Menu, X, CircleUser } from 'lucide-vue-next'
|
||||
import { getLocalizedPath } from '@/utils/locale'
|
||||
|
||||
const mobileMenuOpen = ref(false)
|
||||
const route = useRoute()
|
||||
|
||||
const ACCOUNTS_URL = 'https://accounts.beammp.com'
|
||||
|
||||
function toggleMobileMenu() {
|
||||
mobileMenuOpen.value = !mobileMenuOpen.value
|
||||
}
|
||||
@@ -90,6 +92,21 @@ function localRoute(path) {
|
||||
</RouterLink>
|
||||
</NavigationMenuLink>
|
||||
</NavigationMenuItem>
|
||||
<NavigationMenuItem>
|
||||
<NavigationMenuLink as-child>
|
||||
<RouterLink
|
||||
:to="localRoute('events')"
|
||||
:class="
|
||||
cn(
|
||||
navigationMenuTriggerStyle(),
|
||||
'bg-transparent text-neutral-900 hover:bg-neutral-100 hover:text-neutral-900 dark:bg-transparent dark:text-white dark:hover:bg-neutral-800 dark:hover:text-white'
|
||||
)
|
||||
"
|
||||
>
|
||||
{{ $t('message.nav.events') }}
|
||||
</RouterLink>
|
||||
</NavigationMenuLink>
|
||||
</NavigationMenuItem>
|
||||
<NavigationMenuItem>
|
||||
<NavigationMenuLink as-child>
|
||||
<RouterLink
|
||||
@@ -212,6 +229,13 @@ function localRoute(path) {
|
||||
</NavigationMenuItem>
|
||||
</NavigationMenuList>
|
||||
</NavigationMenu>
|
||||
<a
|
||||
:href="ACCOUNTS_URL"
|
||||
class="inline-flex items-center gap-2 shrink-0 whitespace-nowrap rounded-md bg-beammp-orange px-4 py-2 text-sm font-semibold text-white shadow-sm transition-colors hover:bg-beammp-orange/90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-beammp-orange focus-visible:ring-offset-2 dark:focus-visible:ring-offset-neutral-900"
|
||||
>
|
||||
<CircleUser class="w-4 h-4" aria-hidden="true" />
|
||||
{{ $t('message.nav.account') }}
|
||||
</a>
|
||||
<div class="flex items-center gap-1 sm:gap-2 flex-shrink-0">
|
||||
<LanguageSelector />
|
||||
<ThemeToggle />
|
||||
@@ -261,6 +285,13 @@ function localRoute(path) {
|
||||
>
|
||||
{{ $t('message.nav.partners') }}
|
||||
</RouterLink>
|
||||
<RouterLink
|
||||
:to="localRoute('events')"
|
||||
class="block px-4 py-3 text-neutral-900 dark:text-white hover:bg-neutral-100 dark:hover:bg-neutral-800 rounded-md transition-colors"
|
||||
@click="closeMobileMenu"
|
||||
>
|
||||
{{ $t('message.nav.events') }}
|
||||
</RouterLink>
|
||||
<RouterLink
|
||||
:to="localRoute('servers')"
|
||||
class="block px-4 py-3 text-neutral-900 dark:text-white hover:bg-neutral-100 dark:hover:bg-neutral-800 rounded-md transition-colors"
|
||||
@@ -311,6 +342,14 @@ function localRoute(path) {
|
||||
>
|
||||
{{ $t('message.nav.patreon') }}
|
||||
</a>
|
||||
<a
|
||||
:href="ACCOUNTS_URL"
|
||||
class="mt-2 flex items-center justify-center gap-2 px-4 py-3 rounded-md bg-beammp-orange font-semibold text-white hover:bg-beammp-orange/90 transition-colors"
|
||||
@click="closeMobileMenu"
|
||||
>
|
||||
<CircleUser class="w-5 h-5" aria-hidden="true" />
|
||||
{{ $t('message.nav.account') }}
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</Transition>
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
// Where BeamMP's own services live. The container writes /assets/env.js when it starts
|
||||
// (website-entrypoint.sh, from API_URL and ACCOUNTS_URL, as Accounts does); the defaults are
|
||||
// the real services.
|
||||
const trim = (url) => url.replace(/\/+$/, '')
|
||||
|
||||
export const API_BASE = trim(window.__ENV__?.API_URL || 'https://api.beammp.com')
|
||||
export const ACCOUNTS_BASE = trim(window.__ENV__?.ACCOUNTS_URL || 'https://accounts.beammp.com')
|
||||
+60
-1
@@ -13,14 +13,17 @@
|
||||
"partners": "Partners",
|
||||
"servers": "Server",
|
||||
"statistics": "Statistiken",
|
||||
"store": "Merch-Shop",
|
||||
"github": "GitHub",
|
||||
"patreon": "Patreon",
|
||||
"account": "Anmelden",
|
||||
"language": "Sprache auswählen",
|
||||
"theme": {
|
||||
"light": "Helles Theme",
|
||||
"dark": "Dunkles Theme",
|
||||
"system": "System-Theme"
|
||||
}
|
||||
},
|
||||
"events": "Events"
|
||||
},
|
||||
"footer": {
|
||||
"support_on_patreon": "Unterstütze uns auf Patreon",
|
||||
@@ -272,6 +275,62 @@
|
||||
},
|
||||
"thank_you": "Gemeinsam bauen wir etwas Besonderes. Danke, dass du Teil der BeamMP-Community bist!"
|
||||
}
|
||||
},
|
||||
"events": {
|
||||
"title": "Events",
|
||||
"description": "Verfolge die aktuellen Ranglisten der BeamMP-Events, zusammengeführt von allen teilnehmenden Servern.",
|
||||
"loading": "Events werden geladen…",
|
||||
"empty": "Es wurden noch keine Events eingerichtet.",
|
||||
"viewTop": "Top {count} ansehen →",
|
||||
"ranked": "Gewertete Fahrer: {count}",
|
||||
"servers": "Server: {count}",
|
||||
"back": "← Alle Events",
|
||||
"loadingEvent": "Event wird geladen…",
|
||||
"standings": "Gesamtwertung",
|
||||
"topDrivers": "Top {count} Fahrer",
|
||||
"statDrivers": "Gewertete Fahrer",
|
||||
"statLaps": "Erfasste Runden",
|
||||
"statServers": "Server",
|
||||
"statPlace": "Platz {count}",
|
||||
"standingsTitle": "Rangliste",
|
||||
"search": "Fahrer suchen…",
|
||||
"pos": "Pos",
|
||||
"driver": "Fahrer",
|
||||
"bestLap": "Beste Runde",
|
||||
"gap": "Abstand",
|
||||
"pen": "Str.",
|
||||
"server": "Server",
|
||||
"leader": "Führender",
|
||||
"noMatch": "Keine passenden Fahrer.",
|
||||
"waiting": "Warte auf die ersten Ergebnisse der Event-Server.",
|
||||
"sources": "Server-Quellen",
|
||||
"lastResult": "Letztes Ergebnis: {when}",
|
||||
"none": "noch keins",
|
||||
"noServers": "Noch kein Server ist beigetreten.",
|
||||
"live": "Wird automatisch aktualisiert, sobald Server Runden melden.",
|
||||
"lost": "Verbindung verloren. Neuer Versuch…",
|
||||
"lastShown": "Zeige die zuletzt empfangenen Ergebnisse.",
|
||||
"rules": "Event-Regeln",
|
||||
"r1t": "Nur registrierte Fahrer.",
|
||||
"r1": "Gäste werden nicht gewertet.",
|
||||
"r2t": "Zeiten wie aufgezeichnet.",
|
||||
"r2": "Strafen werden vom Spielserver verhängt; die angezeigte Zeit ist die von ihm gemeldete.",
|
||||
"r3t": "Ein Platz pro Fahrer.",
|
||||
"r3": "Beste Runde über alle Event-Server.",
|
||||
"r4t": "Prüfung.",
|
||||
"r4": "Das Team kann Fahrer nach einer Prüfung ausschließen.",
|
||||
"status": {
|
||||
"qualifying": "Qualifying",
|
||||
"live": "Live-Event",
|
||||
"upcoming": "Demnächst",
|
||||
"finished": "Beendet"
|
||||
},
|
||||
"errors": {
|
||||
"notFound": "Dieses Event ist nicht verfügbar.",
|
||||
"rateLimited": "Zu viele Anfragen. Neuer Versuch in Kürze.",
|
||||
"unavailable": "Die Event-Ergebnisse sind nicht verfügbar.",
|
||||
"timeout": "Zeitüberschreitung. Automatischer neuer Versuch."
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+59
-1
@@ -16,12 +16,14 @@
|
||||
"store": "Merch Store",
|
||||
"github": "GitHub",
|
||||
"patreon": "Patreon",
|
||||
"account": "Sign In",
|
||||
"language": "Select Language",
|
||||
"theme": {
|
||||
"light": "Light Theme",
|
||||
"dark": "Dark Theme",
|
||||
"system": "System Theme"
|
||||
}
|
||||
},
|
||||
"events": "Events"
|
||||
},
|
||||
"footer": {
|
||||
"support_on_patreon": "Support us on Patreon",
|
||||
@@ -273,6 +275,62 @@
|
||||
},
|
||||
"thank_you": "Together, we’re building something special. Thank you for being part of the BeamMP community!"
|
||||
}
|
||||
},
|
||||
"events": {
|
||||
"title": "Events",
|
||||
"description": "Follow the latest standings for BeamMP events, combined across every server taking part.",
|
||||
"loading": "Loading events…",
|
||||
"empty": "No events have been set up yet.",
|
||||
"viewTop": "View top {count} →",
|
||||
"ranked": "Ranked drivers: {count}",
|
||||
"servers": "Servers: {count}",
|
||||
"back": "← All events",
|
||||
"loadingEvent": "Loading event…",
|
||||
"standings": "Global standings",
|
||||
"topDrivers": "Top {count} drivers",
|
||||
"statDrivers": "Ranked drivers",
|
||||
"statLaps": "Recorded laps",
|
||||
"statServers": "Servers",
|
||||
"statPlace": "Place {count}",
|
||||
"standingsTitle": "Standings",
|
||||
"search": "Search drivers…",
|
||||
"pos": "Pos",
|
||||
"driver": "Driver",
|
||||
"bestLap": "Best lap",
|
||||
"gap": "Gap",
|
||||
"pen": "Pen.",
|
||||
"server": "Server",
|
||||
"leader": "Leader",
|
||||
"noMatch": "No matching drivers.",
|
||||
"waiting": "Waiting for the first results from event servers.",
|
||||
"sources": "Server sources",
|
||||
"lastResult": "Last result: {when}",
|
||||
"none": "none yet",
|
||||
"noServers": "No servers have joined yet.",
|
||||
"live": "Updates automatically as servers report laps.",
|
||||
"lost": "Connection lost. Retrying…",
|
||||
"lastShown": "Showing the last received results.",
|
||||
"rules": "Event rules",
|
||||
"r1t": "Registered drivers only.",
|
||||
"r1": "Guests are not ranked.",
|
||||
"r2t": "Times as recorded.",
|
||||
"r2": "Penalties are applied by the game server; the time shown is the time it reported.",
|
||||
"r3t": "One place per driver.",
|
||||
"r3": "Best lap across all event servers.",
|
||||
"r4t": "Review.",
|
||||
"r4": "Staff can exclude drivers after review.",
|
||||
"status": {
|
||||
"qualifying": "Qualifying",
|
||||
"live": "Live event",
|
||||
"upcoming": "Upcoming",
|
||||
"finished": "Finished"
|
||||
},
|
||||
"errors": {
|
||||
"notFound": "This event is not available.",
|
||||
"rateLimited": "Too many requests. Retrying shortly.",
|
||||
"unavailable": "Event results are unavailable.",
|
||||
"timeout": "Connection timed out. Retrying automatically."
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+60
-1
@@ -13,14 +13,17 @@
|
||||
"partners": "Socios",
|
||||
"servers": "Servidores",
|
||||
"statistics": "Estadísticas",
|
||||
"store": "Tienda de merchandising",
|
||||
"github": "GitHub",
|
||||
"patreon": "Patreon",
|
||||
"account": "Iniciar sesión",
|
||||
"language": "Seleccionar idioma",
|
||||
"theme": {
|
||||
"light": "Tema claro",
|
||||
"dark": "Tema oscuro",
|
||||
"system": "Tema del sistema"
|
||||
}
|
||||
},
|
||||
"events": "Eventos"
|
||||
},
|
||||
"footer": {
|
||||
"support_on_patreon": "Apóyanos en Patreon",
|
||||
@@ -272,6 +275,62 @@
|
||||
},
|
||||
"thank_you": "Juntos estamos construyendo algo especial. ¡Gracias por ser parte de la comunidad BeamMP!"
|
||||
}
|
||||
},
|
||||
"events": {
|
||||
"title": "Eventos",
|
||||
"description": "Sigue las clasificaciones de los eventos de BeamMP, combinadas de todos los servidores participantes.",
|
||||
"loading": "Cargando eventos…",
|
||||
"empty": "Aún no se ha creado ningún evento.",
|
||||
"viewTop": "Ver el top {count} →",
|
||||
"ranked": "Pilotos clasificados: {count}",
|
||||
"servers": "Servidores: {count}",
|
||||
"back": "← Todos los eventos",
|
||||
"loadingEvent": "Cargando evento…",
|
||||
"standings": "Clasificación global",
|
||||
"topDrivers": "Top {count} pilotos",
|
||||
"statDrivers": "Pilotos clasificados",
|
||||
"statLaps": "Vueltas registradas",
|
||||
"statServers": "Servidores",
|
||||
"statPlace": "Puesto {count}",
|
||||
"standingsTitle": "Clasificación",
|
||||
"search": "Buscar pilotos…",
|
||||
"pos": "Pos",
|
||||
"driver": "Piloto",
|
||||
"bestLap": "Mejor vuelta",
|
||||
"gap": "Diferencia",
|
||||
"pen": "Pen.",
|
||||
"server": "Servidor",
|
||||
"leader": "Líder",
|
||||
"noMatch": "Ningún piloto coincide.",
|
||||
"waiting": "Esperando los primeros resultados de los servidores del evento.",
|
||||
"sources": "Servidores de origen",
|
||||
"lastResult": "Último resultado: {when}",
|
||||
"none": "aún ninguno",
|
||||
"noServers": "Aún no se ha unido ningún servidor.",
|
||||
"live": "Se actualiza automáticamente cuando los servidores informan de vueltas.",
|
||||
"lost": "Conexión perdida. Reintentando…",
|
||||
"lastShown": "Mostrando los últimos resultados recibidos.",
|
||||
"rules": "Reglas del evento",
|
||||
"r1t": "Solo pilotos registrados.",
|
||||
"r1": "Los invitados no se clasifican.",
|
||||
"r2t": "Tiempos tal como se registran.",
|
||||
"r2": "El servidor del juego aplica las penalizaciones; el tiempo mostrado es el que informó.",
|
||||
"r3t": "Un puesto por piloto.",
|
||||
"r3": "Mejor vuelta en todos los servidores del evento.",
|
||||
"r4t": "Revisión.",
|
||||
"r4": "El personal puede excluir pilotos tras revisarlos.",
|
||||
"status": {
|
||||
"qualifying": "Clasificación previa",
|
||||
"live": "Evento en vivo",
|
||||
"upcoming": "Próximamente",
|
||||
"finished": "Finalizado"
|
||||
},
|
||||
"errors": {
|
||||
"notFound": "Este evento no está disponible.",
|
||||
"rateLimited": "Demasiadas solicitudes. Reintentando en breve.",
|
||||
"unavailable": "Los resultados del evento no están disponibles.",
|
||||
"timeout": "Se agotó el tiempo de conexión. Reintentando automáticamente."
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+60
-1
@@ -13,14 +13,17 @@
|
||||
"partners": "Partenaires",
|
||||
"servers": "Serveurs",
|
||||
"statistics": "Statistiques",
|
||||
"store": "Boutique de produits dérivés",
|
||||
"github": "GitHub",
|
||||
"patreon": "Patreon",
|
||||
"account": "Se connecter",
|
||||
"language": "Choisir la langue",
|
||||
"theme": {
|
||||
"light": "Thème clair",
|
||||
"dark": "Thème sombre",
|
||||
"system": "Thème système"
|
||||
}
|
||||
},
|
||||
"events": "Événements"
|
||||
},
|
||||
"footer": {
|
||||
"support_on_patreon": "Soutenez-nous sur notre Patreon",
|
||||
@@ -272,6 +275,62 @@
|
||||
},
|
||||
"thank_you": "Ensemble, nous construisons quelque chose de spécial. Merci de faire partie de la communauté BeamMP !"
|
||||
}
|
||||
},
|
||||
"events": {
|
||||
"title": "Événements",
|
||||
"description": "Suivez les classements des événements BeamMP, regroupés depuis tous les serveurs participants.",
|
||||
"loading": "Chargement des événements…",
|
||||
"empty": "Aucun événement n'a encore été créé.",
|
||||
"viewTop": "Voir le top {count} →",
|
||||
"ranked": "Pilotes classés: {count}",
|
||||
"servers": "Serveurs: {count}",
|
||||
"back": "← Tous les événements",
|
||||
"loadingEvent": "Chargement de l'événement…",
|
||||
"standings": "Classement général",
|
||||
"topDrivers": "Top {count} pilotes",
|
||||
"statDrivers": "Pilotes classés",
|
||||
"statLaps": "Tours enregistrés",
|
||||
"statServers": "Serveurs",
|
||||
"statPlace": "Place {count}",
|
||||
"standingsTitle": "Classement",
|
||||
"search": "Rechercher un pilote…",
|
||||
"pos": "Pos",
|
||||
"driver": "Pilote",
|
||||
"bestLap": "Meilleur tour",
|
||||
"gap": "Écart",
|
||||
"pen": "Pén.",
|
||||
"server": "Serveur",
|
||||
"leader": "Leader",
|
||||
"noMatch": "Aucun pilote correspondant.",
|
||||
"waiting": "En attente des premiers résultats des serveurs de l'événement.",
|
||||
"sources": "Serveurs sources",
|
||||
"lastResult": "Dernier résultat : {when}",
|
||||
"none": "aucun pour l'instant",
|
||||
"noServers": "Aucun serveur n'a encore rejoint l'événement.",
|
||||
"live": "Mise à jour automatique à mesure que les serveurs envoient des tours.",
|
||||
"lost": "Connexion perdue. Nouvelle tentative…",
|
||||
"lastShown": "Affichage des derniers résultats reçus.",
|
||||
"rules": "Règles de l'événement",
|
||||
"r1t": "Pilotes enregistrés uniquement.",
|
||||
"r1": "Les invités ne sont pas classés.",
|
||||
"r2t": "Temps tels qu'enregistrés.",
|
||||
"r2": "Les pénalités sont appliquées par le serveur de jeu ; le temps affiché est celui qu'il a transmis.",
|
||||
"r3t": "Une place par pilote.",
|
||||
"r3": "Meilleur tour sur tous les serveurs de l'événement.",
|
||||
"r4t": "Vérification.",
|
||||
"r4": "Le staff peut exclure des pilotes après examen.",
|
||||
"status": {
|
||||
"qualifying": "Qualifications",
|
||||
"live": "Événement en direct",
|
||||
"upcoming": "À venir",
|
||||
"finished": "Terminé"
|
||||
},
|
||||
"errors": {
|
||||
"notFound": "Cet événement n'est pas disponible.",
|
||||
"rateLimited": "Trop de requêtes. Nouvelle tentative sous peu.",
|
||||
"unavailable": "Les résultats de l'événement sont indisponibles.",
|
||||
"timeout": "Délai de connexion dépassé. Nouvelle tentative automatique."
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+60
-1
@@ -13,14 +13,17 @@
|
||||
"partners": "Partner",
|
||||
"servers": "Server",
|
||||
"statistics": "Statistiche",
|
||||
"store": "Negozio di merchandising",
|
||||
"github": "GitHub",
|
||||
"patreon": "Patreon",
|
||||
"account": "Accedi",
|
||||
"language": "Seleziona lingua",
|
||||
"theme": {
|
||||
"light": "Tema chiaro",
|
||||
"dark": "Tema scuro",
|
||||
"system": "Tema di sistema"
|
||||
}
|
||||
},
|
||||
"events": "Eventi"
|
||||
},
|
||||
"footer": {
|
||||
"support_on_patreon": "Supportaci su Patreon",
|
||||
@@ -272,6 +275,62 @@
|
||||
},
|
||||
"thank_you": "Insieme stiamo costruendo qualcosa di speciale. Grazie per far parte della community BeamMP!"
|
||||
}
|
||||
},
|
||||
"events": {
|
||||
"title": "Eventi",
|
||||
"description": "Segui le classifiche degli eventi BeamMP, riunite da tutti i server partecipanti.",
|
||||
"loading": "Caricamento eventi…",
|
||||
"empty": "Nessun evento è stato ancora creato.",
|
||||
"viewTop": "Vedi la top {count} →",
|
||||
"ranked": "Piloti in classifica: {count}",
|
||||
"servers": "Server: {count}",
|
||||
"back": "← Tutti gli eventi",
|
||||
"loadingEvent": "Caricamento evento…",
|
||||
"standings": "Classifica globale",
|
||||
"topDrivers": "Top {count} piloti",
|
||||
"statDrivers": "Piloti in classifica",
|
||||
"statLaps": "Giri registrati",
|
||||
"statServers": "Server",
|
||||
"statPlace": "Posizione {count}",
|
||||
"standingsTitle": "Classifica",
|
||||
"search": "Cerca piloti…",
|
||||
"pos": "Pos",
|
||||
"driver": "Pilota",
|
||||
"bestLap": "Giro migliore",
|
||||
"gap": "Distacco",
|
||||
"pen": "Pen.",
|
||||
"server": "Server",
|
||||
"leader": "Leader",
|
||||
"noMatch": "Nessun pilota corrispondente.",
|
||||
"waiting": "In attesa dei primi risultati dai server dell'evento.",
|
||||
"sources": "Server di origine",
|
||||
"lastResult": "Ultimo risultato: {when}",
|
||||
"none": "ancora nessuno",
|
||||
"noServers": "Nessun server si è ancora unito.",
|
||||
"live": "Si aggiorna automaticamente quando i server inviano giri.",
|
||||
"lost": "Connessione persa. Nuovo tentativo…",
|
||||
"lastShown": "Mostro gli ultimi risultati ricevuti.",
|
||||
"rules": "Regole dell'evento",
|
||||
"r1t": "Solo piloti registrati.",
|
||||
"r1": "Gli ospiti non vengono classificati.",
|
||||
"r2t": "Tempi come registrati.",
|
||||
"r2": "Le penalità sono applicate dal server di gioco; il tempo mostrato è quello da lui comunicato.",
|
||||
"r3t": "Un posto per pilota.",
|
||||
"r3": "Giro migliore su tutti i server dell'evento.",
|
||||
"r4t": "Revisione.",
|
||||
"r4": "Lo staff può escludere piloti dopo una verifica.",
|
||||
"status": {
|
||||
"qualifying": "Qualifiche",
|
||||
"live": "Evento live",
|
||||
"upcoming": "In arrivo",
|
||||
"finished": "Concluso"
|
||||
},
|
||||
"errors": {
|
||||
"notFound": "Questo evento non è disponibile.",
|
||||
"rateLimited": "Troppe richieste. Nuovo tentativo a breve.",
|
||||
"unavailable": "I risultati dell'evento non sono disponibili.",
|
||||
"timeout": "Connessione scaduta. Nuovo tentativo automatico."
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+60
-1
@@ -13,14 +13,17 @@
|
||||
"partners": "Партнёры",
|
||||
"servers": "Серверы",
|
||||
"statistics": "Статистика",
|
||||
"store": "Магазин мерча",
|
||||
"github": "GitHub",
|
||||
"patreon": "Patreon",
|
||||
"account": "Войти",
|
||||
"language": "Выбрать язык",
|
||||
"theme": {
|
||||
"light": "Светлая тема",
|
||||
"dark": "Тёмная тема",
|
||||
"system": "Системная тема"
|
||||
}
|
||||
},
|
||||
"events": "События"
|
||||
},
|
||||
"footer": {
|
||||
"support_on_patreon": "Поддержите нас на Patreon",
|
||||
@@ -272,6 +275,62 @@
|
||||
},
|
||||
"thank_you": "Вместе мы строим нечто особенное. Спасибо, что вы — часть сообщества BeamMP!"
|
||||
}
|
||||
},
|
||||
"events": {
|
||||
"title": "События",
|
||||
"description": "Следите за актуальными таблицами результатов событий BeamMP, объединёнными со всех участвующих серверов.",
|
||||
"loading": "Загрузка событий…",
|
||||
"empty": "События ещё не созданы.",
|
||||
"viewTop": "Смотреть топ-{count} →",
|
||||
"ranked": "Пилотов в рейтинге: {count}",
|
||||
"servers": "Серверы: {count}",
|
||||
"back": "← Все события",
|
||||
"loadingEvent": "Загрузка события…",
|
||||
"standings": "Общий зачёт",
|
||||
"topDrivers": "Топ-{count} пилотов",
|
||||
"statDrivers": "Пилотов в рейтинге",
|
||||
"statLaps": "Записано кругов",
|
||||
"statServers": "Серверы",
|
||||
"statPlace": "{count}-е место",
|
||||
"standingsTitle": "Таблица",
|
||||
"search": "Поиск пилотов…",
|
||||
"pos": "Поз",
|
||||
"driver": "Пилот",
|
||||
"bestLap": "Лучший круг",
|
||||
"gap": "Отставание",
|
||||
"pen": "Штр.",
|
||||
"server": "Сервер",
|
||||
"leader": "Лидер",
|
||||
"noMatch": "Подходящих пилотов нет.",
|
||||
"waiting": "Ожидание первых результатов от серверов события.",
|
||||
"sources": "Серверы-источники",
|
||||
"lastResult": "Последний результат: {when}",
|
||||
"none": "пока нет",
|
||||
"noServers": "Ни один сервер ещё не присоединился.",
|
||||
"live": "Обновляется автоматически, когда серверы присылают круги.",
|
||||
"lost": "Соединение потеряно. Повторная попытка…",
|
||||
"lastShown": "Показаны последние полученные результаты.",
|
||||
"rules": "Правила события",
|
||||
"r1t": "Только зарегистрированные пилоты.",
|
||||
"r1": "Гости не учитываются в рейтинге.",
|
||||
"r2t": "Время как записано.",
|
||||
"r2": "Штрафы применяет игровой сервер; показано время, которое он передал.",
|
||||
"r3t": "Одно место на пилота.",
|
||||
"r3": "Лучший круг среди всех серверов события.",
|
||||
"r4t": "Проверка.",
|
||||
"r4": "Персонал может исключать пилотов после проверки.",
|
||||
"status": {
|
||||
"qualifying": "Квалификация",
|
||||
"live": "Событие в прямом эфире",
|
||||
"upcoming": "Скоро",
|
||||
"finished": "Завершено"
|
||||
},
|
||||
"errors": {
|
||||
"notFound": "Это событие недоступно.",
|
||||
"rateLimited": "Слишком много запросов. Скоро повторим попытку.",
|
||||
"unavailable": "Результаты события недоступны.",
|
||||
"timeout": "Превышено время ожидания. Повтор автоматически."
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+59
-1
@@ -16,12 +16,14 @@
|
||||
"store": "周边商店",
|
||||
"github": "GitHub",
|
||||
"patreon": "在 Patreon 上为我们捐献",
|
||||
"account": "登录",
|
||||
"language": "选择语言",
|
||||
"theme": {
|
||||
"light": "明亮主题",
|
||||
"dark": "黑暗主题",
|
||||
"system": "跟随系统"
|
||||
}
|
||||
},
|
||||
"events": "赛事"
|
||||
},
|
||||
"footer": {
|
||||
"support_on_patreon": "Patreon",
|
||||
@@ -273,6 +275,62 @@
|
||||
},
|
||||
"thank_you": "我们正在共同打造一个独特的作品—真诚感谢您成为BeamMP社区的一员!"
|
||||
}
|
||||
},
|
||||
"events": {
|
||||
"title": "赛事",
|
||||
"description": "查看 BeamMP 赛事的最新排名,汇总所有参赛服务器的成绩。",
|
||||
"loading": "正在加载赛事…",
|
||||
"empty": "尚未创建任何赛事。",
|
||||
"viewTop": "查看前 {count} 名 →",
|
||||
"ranked": "已排名车手: {count}",
|
||||
"servers": "服务器: {count}",
|
||||
"back": "← 全部赛事",
|
||||
"loadingEvent": "正在加载赛事…",
|
||||
"standings": "总排名",
|
||||
"topDrivers": "前 {count} 名车手",
|
||||
"statDrivers": "已排名车手",
|
||||
"statLaps": "已记录圈数",
|
||||
"statServers": "服务器",
|
||||
"statPlace": "第 {count} 名",
|
||||
"standingsTitle": "排名",
|
||||
"search": "搜索车手…",
|
||||
"pos": "名次",
|
||||
"driver": "车手",
|
||||
"bestLap": "最佳圈速",
|
||||
"gap": "差距",
|
||||
"pen": "罚",
|
||||
"server": "服务器",
|
||||
"leader": "领先",
|
||||
"noMatch": "没有匹配的车手。",
|
||||
"waiting": "正在等待赛事服务器的首批成绩。",
|
||||
"sources": "服务器来源",
|
||||
"lastResult": "最近成绩:{when}",
|
||||
"none": "暂无",
|
||||
"noServers": "尚无服务器加入。",
|
||||
"live": "服务器上报圈速后自动更新。",
|
||||
"lost": "连接已断开,正在重试…",
|
||||
"lastShown": "显示最近收到的成绩。",
|
||||
"rules": "赛事规则",
|
||||
"r1t": "仅限注册车手。",
|
||||
"r1": "访客不计入排名。",
|
||||
"r2t": "按记录计时。",
|
||||
"r2": "处罚由游戏服务器执行;显示的是其上报的时间。",
|
||||
"r3t": "每位车手一个名次。",
|
||||
"r3": "取所有赛事服务器中的最佳圈速。",
|
||||
"r4t": "审核。",
|
||||
"r4": "工作人员可在审核后排除车手。",
|
||||
"status": {
|
||||
"qualifying": "排位赛",
|
||||
"live": "直播赛事",
|
||||
"upcoming": "即将开始",
|
||||
"finished": "已结束"
|
||||
},
|
||||
"errors": {
|
||||
"notFound": "此赛事不可用。",
|
||||
"rateLimited": "请求过多,稍后重试。",
|
||||
"unavailable": "赛事成绩暂不可用。",
|
||||
"timeout": "连接超时,正在自动重试。"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+30
-2
@@ -66,6 +66,27 @@ const baseRoutes = [
|
||||
},
|
||||
},
|
||||
|
||||
{
|
||||
path: 'events',
|
||||
name: 'Events',
|
||||
component: () => import('@/views/events/EventList.vue'),
|
||||
meta: {
|
||||
title: 'Events - BeamMP',
|
||||
description: 'Live standings for BeamMP events',
|
||||
requiresAuth: false,
|
||||
},
|
||||
},
|
||||
{
|
||||
path: 'events/:eventId',
|
||||
name: 'EventDetail',
|
||||
component: () => import('@/views/events/EventDetail.vue'),
|
||||
meta: {
|
||||
title: 'Event standings - BeamMP',
|
||||
description: 'Live standings for a BeamMP event',
|
||||
requiresAuth: false,
|
||||
},
|
||||
},
|
||||
|
||||
{
|
||||
path: 'privacy',
|
||||
name: 'Privacy',
|
||||
@@ -143,13 +164,20 @@ const router = createRouter({
|
||||
|
||||
// Global navigation guard for meta data and locale
|
||||
router.beforeEach(async (to, from, next) => {
|
||||
// The language is the first part of the address. The not-found route matches
|
||||
// anything, so it has no `locale` param even for /en/nope: read the language
|
||||
// from the path itself, or /en/nope would look like it has none and be sent
|
||||
// to /en/en/nope, then /en/en/en/nope, and never finish.
|
||||
const firstSegment = to.path.split('/')[1]
|
||||
const pathLocale = SUPPORT_LOCALES.includes(firstSegment) ? firstSegment : null
|
||||
|
||||
// If the path has no locale prefix (e.g. /servers), redirect to /<lang>/servers
|
||||
if (!to.params.locale && to.path !== '/') {
|
||||
if (!to.params.locale && !pathLocale && to.path !== '/') {
|
||||
const locale = localStorage.getItem('lang') || 'en'
|
||||
return next(`/${locale}${to.path}`)
|
||||
}
|
||||
|
||||
const paramsLocale = to.params.locale || 'en'
|
||||
const paramsLocale = to.params.locale || pathLocale || 'en'
|
||||
const i18n = window.i18n
|
||||
|
||||
// Ensure i18n is available
|
||||
|
||||
+4
-6
@@ -16,7 +16,7 @@ import {
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import landingLq from '@/assets/landing-lq.jpg'
|
||||
import landingHq from '@/assets/landing_hq.png'
|
||||
const { t } = useI18n()
|
||||
const { t, locale } = useI18n()
|
||||
|
||||
const onlinePlayers = ref('...')
|
||||
const onlineServers = ref('...')
|
||||
@@ -37,13 +37,13 @@ const installerDownloadUrl = computed(() => {
|
||||
onMounted(async () => {
|
||||
try {
|
||||
const response = await fetch('https://api.beammp.com/metrics')
|
||||
// beammp_players_online 2783
|
||||
// beammp_public_servers 2959
|
||||
// beammp_players_online 2783
|
||||
// beammp_public_servers 2959
|
||||
// beammp_all_servers 4663
|
||||
|
||||
const data = await response.text()
|
||||
const lines = data.split('\n')
|
||||
const values = lines.map(line => line.split(' '))
|
||||
const values = lines.map((line) => line.split(' '))
|
||||
if (values.length >= 3) {
|
||||
onlinePlayers.value = values[0][1]
|
||||
onlineServers.value = values[1][1]
|
||||
@@ -123,7 +123,6 @@ const devFeatures = computed(() => [
|
||||
description: t('message.home.devFeatures.lua.description'),
|
||||
link:
|
||||
'https://docs.beammp.com/' +
|
||||
// eslint-disable-next-line no-undef
|
||||
(locale.value == 'en' ? '' : locale.value + '/') +
|
||||
'scripting/mod-reference/',
|
||||
},
|
||||
@@ -131,7 +130,6 @@ const devFeatures = computed(() => [
|
||||
icon: BookOpen,
|
||||
title: t('message.home.devFeatures.docs.title'),
|
||||
description: t('message.home.devFeatures.docs.description'),
|
||||
// eslint-disable-next-line no-undef
|
||||
link: 'https://docs.beammp.com/' + (locale.value == 'en' ? '' : locale.value + '/'),
|
||||
},
|
||||
{
|
||||
|
||||
+18
-2
@@ -289,7 +289,7 @@ const filteredServers = computed(() => {
|
||||
if (searchQuery.value) {
|
||||
const query = searchQuery.value.toLowerCase()
|
||||
const matchesSearch =
|
||||
cleanServerName(server.sname).toLowerCase().includes(query) ||
|
||||
plainServerName(server.sname).toLowerCase().includes(query) ||
|
||||
(server.sdesc && server.sdesc.toLowerCase().includes(query)) ||
|
||||
formatMapName(server.map).toLowerCase().includes(query) ||
|
||||
server.owner.toLowerCase().includes(query)
|
||||
@@ -352,7 +352,23 @@ function applyCode(string, codes) {
|
||||
}
|
||||
// eslint-disable-next-line no-control-regex
|
||||
string = string.replace(/\x00*/g, '')
|
||||
return `<span style="${style}">${string}</span>`
|
||||
// The name is set by whoever hosts the server and is shown as HTML (v-html)
|
||||
// so the colours can apply: the text must be escaped, never trusted.
|
||||
return `<span style="${style}">${escapeHtml(string)}</span>`
|
||||
}
|
||||
|
||||
function escapeHtml(text) {
|
||||
return text
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, ''')
|
||||
}
|
||||
|
||||
// The name as plain text, colour codes removed: what the search looks through.
|
||||
function plainServerName(name) {
|
||||
return name.replace(/\^.{1}/g, '')
|
||||
}
|
||||
|
||||
function cleanServerName(name) {
|
||||
|
||||
@@ -0,0 +1,236 @@
|
||||
<script setup>
|
||||
import { computed, ref, watch } from 'vue'
|
||||
import { useRoute } from 'vue-router'
|
||||
import { bannerSrc, formatLap, formatWhen, useEventsFeed, useEventText } from './helpers'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
const { t } = useI18n()
|
||||
const { status, errorText } = useEventText()
|
||||
const route = useRoute()
|
||||
const locale = computed(() => route.params.locale || 'en')
|
||||
const eventId = computed(() => String(route.params.eventId || ''))
|
||||
const search = ref('')
|
||||
|
||||
const { data, error, connected, restart } = useEventsFeed(
|
||||
() => `/v1/events/${encodeURIComponent(eventId.value)}/leaderboard?mode=top&limit=100`
|
||||
)
|
||||
watch(eventId, () => {
|
||||
search.value = ''
|
||||
restart()
|
||||
})
|
||||
|
||||
const event = computed(() => data.value?.event)
|
||||
const topRows = computed(() =>
|
||||
(data.value?.rows ?? []).slice(0, event.value?.leaderboardSize ?? 100)
|
||||
)
|
||||
const rows = computed(() =>
|
||||
topRows.value.filter((r) => r.name.toLowerCase().includes(search.value.toLowerCase()))
|
||||
)
|
||||
const cutoff = computed(() => topRows.value.find((r) => r.rank === event.value?.leaderboardSize))
|
||||
const servers = computed(() => data.value?.servers ?? [])
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="max-w-6xl mx-auto px-4 py-10">
|
||||
<RouterLink
|
||||
:to="`/${locale}/events`"
|
||||
class="text-sm text-neutral-600 dark:text-neutral-300 hover:text-orange-600"
|
||||
>{{ t('message.events.back') }}</RouterLink
|
||||
>
|
||||
|
||||
<p v-if="error" class="mt-4 text-sm text-red-600" role="status">
|
||||
{{ errorText(error) }}
|
||||
<span v-if="data">{{ t('message.events.lastShown') }}</span>
|
||||
</p>
|
||||
|
||||
<div v-if="!event && !error" class="py-16 text-center text-neutral-600 dark:text-neutral-300">
|
||||
{{ t('message.events.loadingEvent') }}
|
||||
</div>
|
||||
|
||||
<template v-if="event">
|
||||
<div
|
||||
:class="[
|
||||
'mt-4 mb-8',
|
||||
event.bannerVersion
|
||||
? 'relative overflow-hidden rounded-xl bg-neutral-900 px-6 py-10 sm:px-10 sm:py-16'
|
||||
: '',
|
||||
]"
|
||||
>
|
||||
<template v-if="event.bannerVersion">
|
||||
<img
|
||||
:src="bannerSrc(event, 'hero')"
|
||||
alt=""
|
||||
class="absolute inset-0 h-full w-full object-cover"
|
||||
/>
|
||||
<div
|
||||
class="absolute inset-0 bg-gradient-to-r from-black/85 via-black/60 to-black/20"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
</template>
|
||||
<div class="relative">
|
||||
<div
|
||||
class="text-xs uppercase tracking-wide text-orange-600 dark:text-orange-400 font-semibold"
|
||||
>
|
||||
{{ status(event.status) }} · {{ t('message.events.standings') }}
|
||||
</div>
|
||||
<h1
|
||||
:class="[
|
||||
'mt-1 text-4xl font-extrabold tracking-tight',
|
||||
event.bannerVersion ? 'text-white' : 'text-neutral-900 dark:text-white',
|
||||
]"
|
||||
>
|
||||
{{ event.title }}
|
||||
</h1>
|
||||
<p
|
||||
:class="[
|
||||
'mt-3 max-w-2xl',
|
||||
event.bannerVersion ? 'text-white/85' : 'text-neutral-600 dark:text-neutral-300',
|
||||
]"
|
||||
>
|
||||
{{ event.subtitle }}
|
||||
<span v-if="event.subtitle">·</span>
|
||||
{{ t('message.events.topDrivers', { count: event.leaderboardSize }) }}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="grid grid-cols-2 md:grid-cols-4 gap-4 mb-8">
|
||||
<div
|
||||
class="rounded-lg border border-neutral-200 dark:border-neutral-800 p-4 bg-white/70 dark:bg-neutral-900/60"
|
||||
>
|
||||
<div class="text-xs uppercase tracking-wide text-neutral-500 dark:text-neutral-400">
|
||||
{{ t('message.events.statDrivers') }}
|
||||
</div>
|
||||
<div class="mt-1 text-3xl font-semibold">{{ event.stats.players.toLocaleString() }}</div>
|
||||
</div>
|
||||
<div
|
||||
class="rounded-lg border border-neutral-200 dark:border-neutral-800 p-4 bg-white/70 dark:bg-neutral-900/60"
|
||||
>
|
||||
<div class="text-xs uppercase tracking-wide text-neutral-500 dark:text-neutral-400">
|
||||
{{ t('message.events.statLaps') }}
|
||||
</div>
|
||||
<div class="mt-1 text-3xl font-semibold">{{ event.stats.laps.toLocaleString() }}</div>
|
||||
</div>
|
||||
<div
|
||||
class="rounded-lg border border-neutral-200 dark:border-neutral-800 p-4 bg-white/70 dark:bg-neutral-900/60"
|
||||
>
|
||||
<div class="text-xs uppercase tracking-wide text-neutral-500 dark:text-neutral-400">
|
||||
Servers
|
||||
</div>
|
||||
<div class="mt-1 text-3xl font-semibold">{{ servers.length }}</div>
|
||||
</div>
|
||||
<div
|
||||
class="rounded-lg border border-neutral-200 dark:border-neutral-800 p-4 bg-white/70 dark:bg-neutral-900/60"
|
||||
>
|
||||
<div class="text-xs uppercase tracking-wide text-neutral-500 dark:text-neutral-400">
|
||||
{{ t('message.events.statPlace', { count: event.leaderboardSize }) }}
|
||||
</div>
|
||||
<div class="mt-1 text-2xl sm:text-3xl font-semibold tabular-nums">
|
||||
{{ cutoff ? formatLap(cutoff.time) : '—' }}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="grid gap-6 lg:grid-cols-[1fr_18rem]">
|
||||
<div
|
||||
class="rounded-lg border border-neutral-200 dark:border-neutral-800 bg-white/70 dark:bg-neutral-900/60 overflow-hidden"
|
||||
>
|
||||
<div
|
||||
class="flex items-center justify-between gap-3 p-4 border-b border-neutral-200 dark:border-neutral-800"
|
||||
>
|
||||
<h2 class="font-semibold">{{ t('message.events.standingsTitle') }}</h2>
|
||||
<input
|
||||
v-model="search"
|
||||
type="search"
|
||||
:aria-label="t('message.events.search')"
|
||||
:placeholder="t('message.events.search')"
|
||||
class="w-48 rounded-md border border-neutral-300 dark:border-neutral-700 bg-transparent px-3 py-1.5 text-sm"
|
||||
/>
|
||||
</div>
|
||||
<div class="overflow-x-auto">
|
||||
<table class="w-full text-sm">
|
||||
<thead
|
||||
class="text-left text-xs uppercase tracking-wide text-neutral-500 dark:text-neutral-400"
|
||||
>
|
||||
<tr>
|
||||
<th scope="col" class="px-4 py-2">{{ t('message.events.pos') }}</th>
|
||||
<th scope="col" class="px-4 py-2">{{ t('message.events.driver') }}</th>
|
||||
<th scope="col" class="px-4 py-2">{{ t('message.events.bestLap') }}</th>
|
||||
<th scope="col" class="px-4 py-2">{{ t('message.events.gap') }}</th>
|
||||
<th scope="col" class="px-4 py-2">{{ t('message.events.pen') }}</th>
|
||||
<th scope="col" class="px-4 py-2 hidden sm:table-cell">
|
||||
{{ t('message.events.server') }}
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody class="tabular-nums">
|
||||
<tr
|
||||
v-for="row in rows"
|
||||
:key="row.identityKey"
|
||||
class="border-t border-neutral-200 dark:border-neutral-800"
|
||||
>
|
||||
<td class="px-4 py-2 font-semibold">{{ String(row.rank).padStart(2, '0') }}</td>
|
||||
<td class="px-4 py-2">{{ row.name }}</td>
|
||||
<td class="px-4 py-2">{{ formatLap(row.time) }}</td>
|
||||
<td class="px-4 py-2 text-neutral-500 dark:text-neutral-400">
|
||||
{{ row.rank === 1 ? t('message.events.leader') : '+' + row.gap.toFixed(3) }}
|
||||
</td>
|
||||
<td class="px-4 py-2">{{ row.penalties }}</td>
|
||||
<td class="px-4 py-2 hidden sm:table-cell text-neutral-500 dark:text-neutral-400">
|
||||
{{ row.server }}
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<p v-if="!rows.length" class="p-6 text-center text-neutral-600 dark:text-neutral-300">
|
||||
{{ topRows.length ? t('message.events.noMatch') : t('message.events.waiting') }}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<aside class="space-y-6">
|
||||
<div
|
||||
class="rounded-lg border border-neutral-200 dark:border-neutral-800 p-4 bg-white/70 dark:bg-neutral-900/60"
|
||||
>
|
||||
<h2 class="font-semibold">{{ t('message.events.sources') }}</h2>
|
||||
<ul class="mt-3 space-y-2 text-sm">
|
||||
<li v-for="s in servers" :key="s.id">
|
||||
{{ s.name }}
|
||||
<div class="text-xs text-neutral-500 dark:text-neutral-400">
|
||||
{{
|
||||
t('message.events.lastResult', {
|
||||
when: formatWhen(s.lastEventAt) || t('message.events.none'),
|
||||
})
|
||||
}}
|
||||
</div>
|
||||
</li>
|
||||
<li v-if="!servers.length" class="text-neutral-500">
|
||||
{{ t('message.events.noServers') }}
|
||||
</li>
|
||||
</ul>
|
||||
<p class="mt-3 text-xs text-neutral-500 dark:text-neutral-400">
|
||||
{{ connected ? t('message.events.live') : t('message.events.lost') }}
|
||||
</p>
|
||||
</div>
|
||||
<div
|
||||
class="rounded-lg border border-neutral-200 dark:border-neutral-800 p-4 bg-white/70 dark:bg-neutral-900/60 text-sm space-y-3"
|
||||
>
|
||||
<h2 class="font-semibold">{{ t('message.events.rules') }}</h2>
|
||||
<p>
|
||||
<b>{{ t('message.events.r1t') }}</b> {{ t('message.events.r1') }}
|
||||
</p>
|
||||
<p>
|
||||
<b>{{ t('message.events.r2t') }}</b> {{ t('message.events.r2') }}
|
||||
</p>
|
||||
<p>
|
||||
<b>{{ t('message.events.r3t') }}</b> {{ t('message.events.r3') }}
|
||||
</p>
|
||||
<p>
|
||||
<b>{{ t('message.events.r4t') }}</b> {{ t('message.events.r4') }}
|
||||
</p>
|
||||
</div>
|
||||
</aside>
|
||||
</div>
|
||||
</template>
|
||||
</section>
|
||||
</template>
|
||||
@@ -0,0 +1,114 @@
|
||||
<script setup>
|
||||
import { computed } from 'vue'
|
||||
import { useRoute } from 'vue-router'
|
||||
import { bannerSrc, useEventsFeed, useEventText } from './helpers'
|
||||
|
||||
const { status, errorText } = useEventText()
|
||||
const route = useRoute()
|
||||
const locale = computed(() => route.params.locale || 'en')
|
||||
const { data, error, connected } = useEventsFeed(() => '/v1/events', { intervalMs: 5000 })
|
||||
const events = computed(() => data.value?.events ?? [])
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="max-w-6xl mx-auto px-4 py-10">
|
||||
<div class="mb-8">
|
||||
<h1 class="text-4xl font-extrabold tracking-tight text-neutral-900 dark:text-white">
|
||||
{{ $t('message.events.title') }}
|
||||
</h1>
|
||||
<p class="mt-3 text-neutral-600 dark:text-neutral-300 max-w-2xl">
|
||||
{{ $t('message.events.description') }}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<p v-if="error" class="mb-6 text-sm text-red-600" role="status">
|
||||
{{ errorText(error) }}
|
||||
</p>
|
||||
|
||||
<div v-if="!data && !error" class="py-16 text-center text-neutral-600 dark:text-neutral-300">
|
||||
{{ $t('message.events.loading') }}
|
||||
</div>
|
||||
|
||||
<div v-else class="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
|
||||
<RouterLink
|
||||
v-for="event in events"
|
||||
:key="event.id"
|
||||
:to="`/${locale}/events/${event.id}`"
|
||||
:class="[
|
||||
'group relative overflow-hidden rounded-lg border border-neutral-200 dark:border-neutral-800 p-5 hover:border-orange-500 transition-colors',
|
||||
event.bannerVersion
|
||||
? 'bg-neutral-900 min-h-[13rem]'
|
||||
: 'bg-white/70 dark:bg-neutral-900/60',
|
||||
]"
|
||||
>
|
||||
<template v-if="event.bannerVersion">
|
||||
<img
|
||||
:src="bannerSrc(event, 'card')"
|
||||
alt=""
|
||||
loading="lazy"
|
||||
class="absolute inset-0 h-full w-full object-cover transition-transform duration-300 group-hover:scale-105"
|
||||
/>
|
||||
<div
|
||||
class="absolute inset-0 bg-gradient-to-t from-black/90 via-black/55 to-black/25"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
</template>
|
||||
<div class="relative flex h-full flex-col">
|
||||
<div class="flex items-center justify-between text-xs uppercase tracking-wide">
|
||||
<span class="text-orange-600 dark:text-orange-400 font-semibold">{{
|
||||
status(event.status)
|
||||
}}</span>
|
||||
<span
|
||||
v-if="event.partner === 'moza'"
|
||||
:class="
|
||||
event.bannerVersion ? 'text-white/80' : 'text-neutral-500 dark:text-neutral-400'
|
||||
"
|
||||
>MOZA × BeamMP</span
|
||||
>
|
||||
</div>
|
||||
<h2
|
||||
:class="[
|
||||
'mt-3 text-xl font-semibold',
|
||||
event.bannerVersion ? 'text-white' : 'text-neutral-900 dark:text-white',
|
||||
]"
|
||||
>
|
||||
{{ event.title }}
|
||||
</h2>
|
||||
<p
|
||||
v-if="event.subtitle"
|
||||
:class="[
|
||||
'mt-1 text-sm',
|
||||
event.bannerVersion ? 'text-white/85' : 'text-neutral-600 dark:text-neutral-300',
|
||||
]"
|
||||
>
|
||||
{{ event.subtitle }}
|
||||
</p>
|
||||
<div
|
||||
:class="[
|
||||
'mt-4 flex gap-4 text-sm',
|
||||
event.bannerVersion ? 'text-white/85' : 'text-neutral-600 dark:text-neutral-300',
|
||||
]"
|
||||
>
|
||||
<span>{{ $t('message.events.ranked', { count: event.stats.players }) }}</span>
|
||||
<span>{{ $t('message.events.servers', { count: event.serverCount }) }}</span>
|
||||
</div>
|
||||
<div
|
||||
:class="[
|
||||
'mt-4 text-sm font-medium group-hover:text-orange-500',
|
||||
event.bannerVersion ? 'text-white' : 'text-neutral-900 dark:text-white',
|
||||
]"
|
||||
>
|
||||
{{ $t('message.events.viewTop', { count: event.leaderboardSize }) }}
|
||||
</div>
|
||||
</div>
|
||||
</RouterLink>
|
||||
</div>
|
||||
|
||||
<p
|
||||
v-if="data && !events.length && connected"
|
||||
class="py-16 text-center text-neutral-600 dark:text-neutral-300"
|
||||
>
|
||||
{{ $t('message.events.empty') }}
|
||||
</p>
|
||||
</section>
|
||||
</template>
|
||||
@@ -0,0 +1,104 @@
|
||||
import { onBeforeUnmount, onMounted, ref } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { API_BASE } from '@/lib/config'
|
||||
|
||||
/** Seconds to m:ss.mmm, as shown on the boards. */
|
||||
export function formatLap(value) {
|
||||
const ms = Math.round(value * 1000)
|
||||
return `${Math.floor(ms / 60000)}:${String(Math.floor(ms / 1000) % 60).padStart(2, '0')}.${String(ms % 1000).padStart(3, '0')}`
|
||||
}
|
||||
|
||||
export function formatWhen(value) {
|
||||
return value
|
||||
? new Date(value)
|
||||
.toISOString()
|
||||
.replace('T', ' ')
|
||||
.replace(/\.\d+Z$/, ' UTC')
|
||||
: null
|
||||
}
|
||||
|
||||
/**
|
||||
* Polls one public events path and keeps the last good result on screen if a refresh fails.
|
||||
* The path (/v1/events/...) is served by the main API at API_BASE, which holds the read key, so no key
|
||||
* ever reaches the browser.
|
||||
*/
|
||||
export function useEventsFeed(pathGetter, { intervalMs = 2000 } = {}) {
|
||||
const data = ref(null)
|
||||
const error = ref('')
|
||||
const connected = ref(false)
|
||||
let timer
|
||||
let controller
|
||||
let generation = 0
|
||||
let stopped = false
|
||||
|
||||
async function refresh() {
|
||||
const token = ++generation
|
||||
controller?.abort()
|
||||
const mine = new window.AbortController()
|
||||
controller = mine
|
||||
const timeout = window.setTimeout(() => mine.abort(), 7000)
|
||||
try {
|
||||
const res = await fetch(`${API_BASE}${pathGetter()}`, {
|
||||
cache: 'no-store',
|
||||
signal: mine.signal,
|
||||
})
|
||||
if (!res.ok) {
|
||||
throw new Error(
|
||||
res.status === 404 ? 'notFound' : res.status === 429 ? 'rateLimited' : 'unavailable'
|
||||
)
|
||||
}
|
||||
const json = await res.json()
|
||||
if (token !== generation || stopped) return
|
||||
data.value = json
|
||||
error.value = ''
|
||||
connected.value = true
|
||||
} catch (failure) {
|
||||
if (token !== generation || stopped) return
|
||||
connected.value = false
|
||||
error.value = failure.name === 'AbortError' ? 'timeout' : failure.message
|
||||
} finally {
|
||||
window.clearTimeout(timeout)
|
||||
if (token === generation && !stopped) timer = window.setTimeout(refresh, intervalMs)
|
||||
}
|
||||
}
|
||||
|
||||
function restart() {
|
||||
window.clearTimeout(timer)
|
||||
data.value = null
|
||||
refresh()
|
||||
}
|
||||
|
||||
onMounted(refresh)
|
||||
onBeforeUnmount(() => {
|
||||
stopped = true
|
||||
window.clearTimeout(timer)
|
||||
controller?.abort()
|
||||
})
|
||||
return { data, error, connected, restart }
|
||||
}
|
||||
|
||||
/** Translated status and error text. The keys are written out so the locale check can see them. */
|
||||
export function useEventText() {
|
||||
const { t } = useI18n()
|
||||
const status = (value) =>
|
||||
({
|
||||
qualifying: t('message.events.status.qualifying'),
|
||||
live: t('message.events.status.live'),
|
||||
upcoming: t('message.events.status.upcoming'),
|
||||
finished: t('message.events.status.finished'),
|
||||
})[value] ?? value
|
||||
const errorText = (code) =>
|
||||
({
|
||||
notFound: t('message.events.errors.notFound'),
|
||||
rateLimited: t('message.events.errors.rateLimited'),
|
||||
timeout: t('message.events.errors.timeout'),
|
||||
})[code] ?? t('message.events.errors.unavailable')
|
||||
return { status, errorText }
|
||||
}
|
||||
|
||||
/** Address of an event's banner image, or null when it has none. Images are served by the main API. */
|
||||
export function bannerSrc(event, size) {
|
||||
const version = event?.bannerVersion
|
||||
if (!version) return null
|
||||
return `${API_BASE}/v1/event-banners/${encodeURIComponent(event.id)}/${encodeURIComponent(version)}/${size}`
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import { describe, expect, test } from 'vitest'
|
||||
import { bannerSrc, formatLap } from '@/views/events/helpers'
|
||||
|
||||
describe('event helpers', () => {
|
||||
test('banner address is built on the main API from the event id and version', () => {
|
||||
const version = 'a'.repeat(32)
|
||||
expect(bannerSrc({ id: 'hirochi', bannerVersion: version }, 'card')).toMatch(
|
||||
new RegExp(`/v1/event-banners/hirochi/${version}/card$`)
|
||||
)
|
||||
expect(bannerSrc({ id: 'a/b', bannerVersion: 'v 1' }, 'hero')).toMatch(/\/a%2Fb\/v%201\/hero$/)
|
||||
})
|
||||
test('an event without a banner has no address', () => {
|
||||
expect(bannerSrc({ id: 'x', bannerVersion: null }, 'card')).toBeNull()
|
||||
expect(bannerSrc({ id: 'x' }, 'hero')).toBeNull()
|
||||
expect(bannerSrc(undefined, 'hero')).toBeNull()
|
||||
})
|
||||
test('lap times are shown as m:ss.mmm', () => {
|
||||
expect(formatLap(80.122)).toBe('1:20.122')
|
||||
expect(formatLap(59.9996)).toBe('1:00.000')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,86 @@
|
||||
/**
|
||||
* The footer is on every page: the social links, the Patreon link, and the
|
||||
* legal links. A wrong address or a missing "opens in a new tab" safety
|
||||
* attribute here is shipped to every visitor.
|
||||
*/
|
||||
|
||||
import { mount, flushPromises } from '@vue/test-utils'
|
||||
import { installI18n } from './helpers'
|
||||
import router from '@/routes'
|
||||
import AppFooter from '@/components/AppFooter.vue'
|
||||
|
||||
async function mountFooter() {
|
||||
const i18n = installI18n('en')
|
||||
await router.push('/en')
|
||||
await router.isReady()
|
||||
const wrapper = mount(AppFooter, { global: { plugins: [i18n, router] } })
|
||||
await flushPromises()
|
||||
return wrapper
|
||||
}
|
||||
|
||||
const SOCIAL = {
|
||||
GitHub: 'https://github.com/BeamMP',
|
||||
Discord: 'https://discord.gg/beammp',
|
||||
YouTube: 'https://www.youtube.com/@beammpofficial',
|
||||
X: 'https://x.com/beammpofficial',
|
||||
Reddit: 'https://www.reddit.com/r/BeamMP',
|
||||
Bluesky: 'https://bsky.app/profile/beammp.com',
|
||||
Twitch: 'https://www.twitch.tv/beammpofficial',
|
||||
Instagram: 'https://www.instagram.com/beammpofficial',
|
||||
TikTok: 'https://www.tiktok.com/@beammpofficial',
|
||||
Facebook: 'https://www.facebook.com/BeamMPTeam',
|
||||
}
|
||||
|
||||
test('shows each social link, in order, with the right address', async () => {
|
||||
const wrapper = await mountFooter()
|
||||
const links = wrapper.findAll('a[aria-label]')
|
||||
expect(links.map((a) => a.attributes('aria-label'))).toEqual(Object.keys(SOCIAL))
|
||||
for (const a of links) {
|
||||
expect(a.attributes('href'), a.attributes('aria-label')).toBe(
|
||||
SOCIAL[a.attributes('aria-label')]
|
||||
)
|
||||
}
|
||||
})
|
||||
|
||||
test('Twitch and Bluesky are both there, side by side', async () => {
|
||||
const wrapper = await mountFooter()
|
||||
const labels = wrapper.findAll('a[aria-label]').map((a) => a.attributes('aria-label'))
|
||||
expect(labels.indexOf('Twitch')).toBe(labels.indexOf('Bluesky') + 1)
|
||||
})
|
||||
|
||||
test('every link that leaves the site opens in a new tab without handing over the opener', async () => {
|
||||
const wrapper = await mountFooter()
|
||||
const external = wrapper
|
||||
.findAll('a')
|
||||
.filter((a) => /^https?:\/\//.test(a.attributes('href') || ''))
|
||||
expect(external.length).toBeGreaterThanOrEqual(Object.keys(SOCIAL).length + 3)
|
||||
for (const a of external) {
|
||||
expect(a.attributes('target'), a.attributes('href')).toBe('_blank')
|
||||
expect(a.attributes('rel'), a.attributes('href')).toContain('noopener')
|
||||
}
|
||||
})
|
||||
|
||||
test('every social icon is a labelled link with a drawn icon', async () => {
|
||||
const wrapper = await mountFooter()
|
||||
for (const a of wrapper.findAll('a[aria-label]')) {
|
||||
expect(a.find('svg').exists(), a.attributes('aria-label')).toBe(true)
|
||||
}
|
||||
})
|
||||
|
||||
test('has the Patreon link and the legal links, and this year in the copyright', async () => {
|
||||
const wrapper = await mountFooter()
|
||||
const hrefs = wrapper.findAll('a').map((a) => a.attributes('href'))
|
||||
expect(hrefs).toContain('https://www.patreon.com/BeamMP')
|
||||
expect(hrefs).toContain('https://beammp.com/privacy')
|
||||
expect(hrefs).toContain('https://beammp.com/terms')
|
||||
expect(hrefs).toContain('/en/about')
|
||||
expect(wrapper.text()).toContain(`2019 - ${new Date().getFullYear()}`)
|
||||
})
|
||||
|
||||
test('the About link follows the language', async () => {
|
||||
const i18n = installI18n('en')
|
||||
await router.push('/de')
|
||||
const wrapper = mount(AppFooter, { global: { plugins: [i18n, router] } })
|
||||
await flushPromises()
|
||||
expect(wrapper.findAll('a').map((a) => a.attributes('href'))).toContain('/de/about')
|
||||
})
|
||||
@@ -0,0 +1,90 @@
|
||||
import fs from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { flushPromises, mount } from '@vue/test-utils'
|
||||
import { setupI18n } from '@/i18n'
|
||||
import en from '@/locales/en.json'
|
||||
import router from '@/routes'
|
||||
import App from '@/App.vue'
|
||||
|
||||
export const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
|
||||
export const publicFile = (name) => fs.readFileSync(path.join(root, 'public', name), 'utf8')
|
||||
|
||||
// The same i18n the app builds in main.js, with English loaded. The router's
|
||||
// guard reads window.i18n to switch language, so it is set here too.
|
||||
export function installI18n(locale = 'en') {
|
||||
const i18n = setupI18n({ legacy: false, locale, fallbackLocale: 'en', messages: { en } })
|
||||
window.i18n = i18n
|
||||
return i18n
|
||||
}
|
||||
|
||||
const reply = (body, ok = true, status = ok ? 200 : 503) => ({
|
||||
ok,
|
||||
status,
|
||||
json: async () => (typeof body === 'string' ? JSON.parse(body) : body),
|
||||
text: async () => (typeof body === 'string' ? body : JSON.stringify(body)),
|
||||
})
|
||||
|
||||
/**
|
||||
* Stands in for fetch. Local files come from the repo's public folder; the
|
||||
* backend feeds can be given as data, or left to answer 503 ("backend down").
|
||||
* Nothing reaches the network, and a URL nobody planned for fails the test.
|
||||
*/
|
||||
export function stubFetch({ servers, metrics } = {}) {
|
||||
const calls = []
|
||||
const stub = async (url) => {
|
||||
const address = String(url)
|
||||
calls.push(address)
|
||||
if (
|
||||
address.startsWith('/docs/') ||
|
||||
address === '/partners.json' ||
|
||||
address === '/servers.json'
|
||||
) {
|
||||
return reply(publicFile(address.slice(1)))
|
||||
}
|
||||
if (address === 'https://backend.beammp.com/servers-info')
|
||||
return servers ? reply(servers) : reply('', false)
|
||||
if (address === 'https://api.beammp.com/metrics')
|
||||
return metrics ? reply(metrics) : reply('', false)
|
||||
// The statistics page's release and stats feeds: down unless a test says otherwise.
|
||||
if (
|
||||
/^https:\/\/(api|backend)\.beammp\.com\//.test(address) ||
|
||||
address.startsWith('https://api.github.com/')
|
||||
)
|
||||
return reply('', false)
|
||||
throw new Error(`Unplanned fetch to ${address}`)
|
||||
}
|
||||
stub.calls = calls
|
||||
vi.stubGlobal('fetch', stub)
|
||||
return stub
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs `action` (a navigation) and fails it if the router's language guard
|
||||
* keeps redirecting. A runaway redirect would otherwise freeze the test run
|
||||
* the way it freezes the page. The guard reads the saved language on every
|
||||
* redirect, which is what is counted.
|
||||
*/
|
||||
export async function withRedirectLimit(action, limit = 5) {
|
||||
const real = localStorage.getItem.bind(localStorage)
|
||||
let passes = 0
|
||||
localStorage.getItem = (key) => {
|
||||
if (key === 'lang' && ++passes > limit) throw new Error('still redirecting')
|
||||
return real(key)
|
||||
}
|
||||
try {
|
||||
return await action()
|
||||
} finally {
|
||||
localStorage.getItem = real
|
||||
}
|
||||
}
|
||||
|
||||
/** Opens a page of the real app (router, layout, nav and footer) and lets it finish loading. */
|
||||
export async function openPage(pathname) {
|
||||
const i18n = installI18n('en')
|
||||
await withRedirectLimit(() => router.push(pathname))
|
||||
await router.isReady()
|
||||
const wrapper = mount(App, { attachTo: document.body, global: { plugins: [i18n, router] } })
|
||||
await flushPromises()
|
||||
return wrapper
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
/**
|
||||
* The helpers that build and switch the /<language>/... paths. Every link on
|
||||
* the site goes through these, so a slip here breaks navigation everywhere.
|
||||
*/
|
||||
|
||||
import { getCurrentLocale, getLocalizedPath, switchLocale } from '@/utils/locale'
|
||||
|
||||
afterEach(() => {
|
||||
delete window.i18n
|
||||
})
|
||||
|
||||
describe('getLocalizedPath', () => {
|
||||
test('puts the language first, with or without a leading slash on the page', () => {
|
||||
expect(getLocalizedPath('servers', 'de')).toBe('/de/servers')
|
||||
expect(getLocalizedPath('/servers', 'de')).toBe('/de/servers')
|
||||
})
|
||||
|
||||
test('never doubles a slash', () => {
|
||||
expect(getLocalizedPath('//servers', 'fr')).toBe('/fr/servers')
|
||||
expect(getLocalizedPath('', 'fr')).toBe('/fr/')
|
||||
})
|
||||
|
||||
test('uses the saved language when none is given, and English if nothing is saved', () => {
|
||||
expect(getLocalizedPath('about')).toBe('/en/about')
|
||||
localStorage.setItem('lang', 'it')
|
||||
expect(getLocalizedPath('about')).toBe('/it/about')
|
||||
})
|
||||
|
||||
test('the language the app is showing wins over the saved one', () => {
|
||||
localStorage.setItem('lang', 'it')
|
||||
window.i18n = { global: { locale: { value: 'ru' } } }
|
||||
expect(getLocalizedPath('about')).toBe('/ru/about')
|
||||
})
|
||||
})
|
||||
|
||||
describe('getCurrentLocale', () => {
|
||||
test('reads a plain string locale as well as a ref', () => {
|
||||
window.i18n = { global: { locale: 'es' } }
|
||||
expect(getCurrentLocale()).toBe('es')
|
||||
window.i18n = { global: { locale: { value: 'zh' } } }
|
||||
expect(getCurrentLocale()).toBe('zh')
|
||||
})
|
||||
})
|
||||
|
||||
describe('switchLocale', () => {
|
||||
test('swaps the language and keeps the page', () => {
|
||||
expect(switchLocale('de', '/en/servers')).toBe('/de/servers')
|
||||
expect(switchLocale('fr', '/ru/about')).toBe('/fr/about')
|
||||
})
|
||||
|
||||
test('keeps deeper paths', () => {
|
||||
expect(switchLocale('de', '/en/docs/getting-started')).toBe('/de/docs/getting-started')
|
||||
})
|
||||
|
||||
test('the home page of one language is the home page of the next', () => {
|
||||
expect(switchLocale('es', '/en')).toBe('/es')
|
||||
expect(switchLocale('es', '/en/')).toBe('/es')
|
||||
})
|
||||
|
||||
test('drops the old query string rather than carrying it across', () => {
|
||||
expect(switchLocale('de', '/en/servers?search=drift')).toBe('/de/servers')
|
||||
})
|
||||
|
||||
test('adds a language to a path that has none', () => {
|
||||
expect(switchLocale('de', '/servers')).toBe('/de/servers')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,133 @@
|
||||
/**
|
||||
* The site is shown in seven languages from seven JSON files. Nothing else
|
||||
* notices when one of them falls behind, so this does: every language has
|
||||
* every English text, nothing is blank, translations keep the same {placeholders}
|
||||
* as English, and every text a page asks for exists.
|
||||
*/
|
||||
|
||||
import fs from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { LANGUAGES, SUPPORT_LOCALES } from '@/i18n'
|
||||
|
||||
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
|
||||
const localesDir = path.join(root, 'src/locales')
|
||||
const read = (code) => JSON.parse(fs.readFileSync(path.join(localesDir, `${code}.json`), 'utf8'))
|
||||
|
||||
function flatten(obj, prefix = '') {
|
||||
const out = {}
|
||||
for (const [key, value] of Object.entries(obj)) {
|
||||
const full = prefix ? `${prefix}.${key}` : key
|
||||
if (value && typeof value === 'object' && !Array.isArray(value))
|
||||
Object.assign(out, flatten(value, full))
|
||||
else out[full] = value
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// Texts that are known to be untranslated, so the test can pass today and still
|
||||
// catch anything new. Translate one and delete it from here: the "still
|
||||
// missing" test below fails if an entry is left behind.
|
||||
const KNOWN_UNTRANSLATED = {}
|
||||
|
||||
const english = flatten(read('en'))
|
||||
const others = SUPPORT_LOCALES.filter((code) => code !== 'en')
|
||||
|
||||
describe('the language list', () => {
|
||||
test('every supported language has a file, and every file is a supported language', () => {
|
||||
const files = fs
|
||||
.readdirSync(localesDir)
|
||||
.filter((f) => f.endsWith('.json'))
|
||||
.map((f) => f.replace('.json', ''))
|
||||
expect(files.sort()).toEqual([...SUPPORT_LOCALES].sort())
|
||||
})
|
||||
|
||||
test('every supported language has a name and a flag for the picker', () => {
|
||||
for (const code of SUPPORT_LOCALES) {
|
||||
expect(LANGUAGES[code]).toMatchObject({
|
||||
code,
|
||||
name: expect.any(String),
|
||||
flag: expect.any(String),
|
||||
})
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe.each(others)('%s translation', (code) => {
|
||||
const messages = flatten(read(code))
|
||||
const allowedMissing = (key) => (KNOWN_UNTRANSLATED[key] || []).includes(code)
|
||||
|
||||
test('has every English text', () => {
|
||||
const missing = Object.keys(english).filter((key) => !(key in messages) && !allowedMissing(key))
|
||||
expect(missing).toEqual([])
|
||||
})
|
||||
|
||||
test('has no text English does not have (a leftover or a typo in the name)', () => {
|
||||
expect(Object.keys(messages).filter((key) => !(key in english))).toEqual([])
|
||||
})
|
||||
|
||||
test('has no blank texts', () => {
|
||||
const blank = Object.entries(messages).filter(
|
||||
([, value]) => typeof value !== 'string' || !value.trim()
|
||||
)
|
||||
expect(blank.map(([key]) => key)).toEqual([])
|
||||
})
|
||||
|
||||
test('keeps the same {placeholders} as English', () => {
|
||||
const placeholders = (text) => [...String(text).matchAll(/\{(\w+)\}/g)].map((m) => m[1]).sort()
|
||||
const mismatched = Object.keys(messages)
|
||||
.filter((key) => key in english)
|
||||
.filter(
|
||||
(key) =>
|
||||
JSON.stringify(placeholders(messages[key])) !== JSON.stringify(placeholders(english[key]))
|
||||
)
|
||||
expect(mismatched).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
test('every entry in the known-untranslated list is still untranslated', () => {
|
||||
const stale = []
|
||||
for (const [key, codes] of Object.entries(KNOWN_UNTRANSLATED)) {
|
||||
if (!(key in english)) stale.push(`${key} (not in English)`)
|
||||
for (const code of codes)
|
||||
if (key in flatten(read(code))) stale.push(`${key} (${code} has it now)`)
|
||||
}
|
||||
expect(stale).toEqual([])
|
||||
})
|
||||
|
||||
describe('texts the pages ask for', () => {
|
||||
const sourceFiles = []
|
||||
const walk = (dir) => {
|
||||
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
||||
const full = path.join(dir, entry.name)
|
||||
if (entry.isDirectory()) walk(full)
|
||||
else if (/\.(vue|js)$/.test(entry.name)) sourceFiles.push(full)
|
||||
}
|
||||
}
|
||||
walk(path.join(root, 'src'))
|
||||
|
||||
const used = new Map()
|
||||
const dynamic = []
|
||||
for (const file of sourceFiles) {
|
||||
const source = fs.readFileSync(file, 'utf8')
|
||||
for (const m of source.matchAll(/(?<![\w.])\$?(?:t|te|tm|rt)\(\s*(['"`])([^'"`]+)\1/g)) {
|
||||
if (m[2].includes('${')) dynamic.push(`${path.relative(root, file)}: ${m[2]}`)
|
||||
else used.set(m[2], path.relative(root, file))
|
||||
}
|
||||
}
|
||||
|
||||
test('finds the texts the pages use (the scan itself works)', () => {
|
||||
expect(used.size).toBeGreaterThan(50)
|
||||
})
|
||||
|
||||
test('every text a page asks for exists in English', () => {
|
||||
const missing = [...used].filter(
|
||||
([key]) => !(key in english) && !Object.keys(english).some((k) => k.startsWith(`${key}.`))
|
||||
)
|
||||
expect(missing.map(([key, file]) => `${key} (${file})`)).toEqual([])
|
||||
})
|
||||
|
||||
test('no page builds a text name on the fly, which this check could not see', () => {
|
||||
expect(dynamic).toEqual([])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,275 @@
|
||||
/**
|
||||
* Opens each page of the real app (router, navigation, page, footer) with
|
||||
* fetch stubbed, the way a visitor gets it. A page that throws while loading,
|
||||
* logs a Vue warning, or goes blank when the backend is down shows up here.
|
||||
* The checks are about what a page says, not how it looks.
|
||||
*/
|
||||
|
||||
import { openPage, publicFile, stubFetch } from './helpers'
|
||||
|
||||
const PAGES = [
|
||||
['home', '/en'],
|
||||
['about', '/en/about'],
|
||||
['communities', '/en/communities'],
|
||||
['servers', '/en/servers'],
|
||||
['statistics', '/en/stats'],
|
||||
['partners', '/en/partners'],
|
||||
['privacy', '/en/privacy'],
|
||||
['terms', '/en/terms'],
|
||||
]
|
||||
|
||||
let wrapper
|
||||
let warnings
|
||||
|
||||
beforeEach(() => {
|
||||
warnings = []
|
||||
vi.spyOn(console, 'warn').mockImplementation((...args) => warnings.push(args.join(' ')))
|
||||
vi.spyOn(console, 'error').mockImplementation((...args) => warnings.push(args.join(' ')))
|
||||
vi.spyOn(console, 'log').mockImplementation(() => {})
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
wrapper?.unmount()
|
||||
wrapper = undefined
|
||||
document.body.innerHTML = ''
|
||||
vi.unstubAllGlobals()
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
describe.each(PAGES)('the %s page', (_name, address) => {
|
||||
test('opens with the navigation and footer around it, and no Vue warnings', async () => {
|
||||
stubFetch()
|
||||
wrapper = await openPage(address)
|
||||
expect(wrapper.find('nav, header').exists()).toBe(true)
|
||||
expect(wrapper.find('footer').exists()).toBe(true)
|
||||
expect(wrapper.find('main').text().length).toBeGreaterThan(0)
|
||||
expect(warnings.filter((w) => w.includes('[Vue warn]'))).toEqual([])
|
||||
})
|
||||
|
||||
test('still opens, and says something, when the backend is down', async () => {
|
||||
stubFetch()
|
||||
wrapper = await openPage(address)
|
||||
expect(wrapper.find('main').text().trim()).not.toBe('')
|
||||
expect(wrapper.find('footer').exists()).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('home', () => {
|
||||
test('shows the live numbers from the metrics feed', async () => {
|
||||
stubFetch({
|
||||
metrics: 'beammp_players_online 2783\nbeammp_public_servers 2959\nbeammp_all_servers 4663\n',
|
||||
})
|
||||
wrapper = await openPage('/en')
|
||||
const text = wrapper.text()
|
||||
expect(text).toContain('2783')
|
||||
expect(text).toContain('2959')
|
||||
expect(text).toContain('4663')
|
||||
})
|
||||
|
||||
test('shows N/A rather than a broken number when the metrics are down', async () => {
|
||||
vi.stubGlobal('fetch', async () => {
|
||||
throw new Error('network down')
|
||||
})
|
||||
wrapper = await openPage('/en')
|
||||
expect(wrapper.text()).toContain('N/A')
|
||||
expect(wrapper.text()).not.toContain('undefined')
|
||||
})
|
||||
})
|
||||
|
||||
describe('the docs links on the home page', () => {
|
||||
test('point at the docs in the language of the page', async () => {
|
||||
stubFetch()
|
||||
wrapper = await openPage('/en')
|
||||
const english = wrapper.findAll('a').map((a) => a.attributes('href'))
|
||||
expect(english).toContain('https://docs.beammp.com/')
|
||||
expect(english).toContain('https://docs.beammp.com/scripting/mod-reference/')
|
||||
wrapper.unmount()
|
||||
|
||||
wrapper = await openPage('/de')
|
||||
const german = wrapper.findAll('a').map((a) => a.attributes('href'))
|
||||
expect(german).toContain('https://docs.beammp.com/de/')
|
||||
expect(german).toContain('https://docs.beammp.com/de/scripting/mod-reference/')
|
||||
})
|
||||
})
|
||||
|
||||
describe('servers', () => {
|
||||
const servers = JSON.parse(publicFile('servers.json')).slice(0, 25)
|
||||
|
||||
test('lists the servers the backend returns', async () => {
|
||||
stubFetch({ servers })
|
||||
wrapper = await openPage('/en/servers')
|
||||
const text = wrapper.find('main').text()
|
||||
expect(text).toContain('MTRTR Christmas')
|
||||
expect(text).not.toContain('Failed to load servers')
|
||||
})
|
||||
|
||||
// A server's name is set by whoever hosts it and is shown as HTML so the
|
||||
// colour codes can apply, so the page escapes it itself. (The API also strips
|
||||
// every `<` at heartbeat, which is why the real feed has none: this is the
|
||||
// second layer, and it holds even if the first ever slips.)
|
||||
test('a server name with HTML in it is shown as text, not turned into page elements', async () => {
|
||||
const hostile = {
|
||||
...servers[0],
|
||||
sname: '^1Evil <img src="x-probe" onerror="window.__pwned=1"> <b id="probe-b">bold</b>',
|
||||
}
|
||||
stubFetch({ servers: [hostile] })
|
||||
wrapper = await openPage('/en/servers')
|
||||
expect(document.querySelector('img[src="x-probe"]')).toBeNull()
|
||||
expect(document.querySelector('#probe-b')).toBeNull()
|
||||
expect(wrapper.find('main').text()).toContain('<b id="probe-b">bold</b>')
|
||||
})
|
||||
|
||||
test('names with & and quotes still read as written, and keep their colours', async () => {
|
||||
const named = [
|
||||
{ ...servers[0], ident: 'a1', sname: '^1C&B\'s ^2"Banger" League' },
|
||||
{ ...servers[1], ident: 'a2', sname: 'Plain & simple' },
|
||||
]
|
||||
stubFetch({ servers: named })
|
||||
wrapper = await openPage('/en/servers')
|
||||
const text = wrapper.find('main').text()
|
||||
expect(text).toContain('C&B\'s "Banger" League')
|
||||
expect(text).toContain('Plain & simple')
|
||||
expect(text).not.toContain('&')
|
||||
// ^1 is dark blue: the colour codes are not shown, and the colour is applied
|
||||
expect(text).not.toContain('^1')
|
||||
expect(wrapper.find('.name-cell span[style*="color"]').exists()).toBe(true)
|
||||
})
|
||||
|
||||
test('text that looks like an HTML entity is shown exactly as typed', async () => {
|
||||
stubFetch({
|
||||
servers: [{ ...servers[0], ident: 'a1', sname: 'Tags <b> and & shown as typed' }],
|
||||
})
|
||||
wrapper = await openPage('/en/servers')
|
||||
expect(wrapper.find('main').text()).toContain('Tags <b> and & shown as typed')
|
||||
})
|
||||
|
||||
describe('searching', () => {
|
||||
const named = () => [
|
||||
{
|
||||
...servers[0],
|
||||
ident: 'a1',
|
||||
sname: "^1C&B's ^2Banger League",
|
||||
sdesc: 'drift night',
|
||||
owner: 'zed',
|
||||
map: '/levels/west_coast_usa/info.json',
|
||||
},
|
||||
{
|
||||
...servers[1],
|
||||
ident: 'a2',
|
||||
sname: '^4Quiet Valley',
|
||||
sdesc: 'relaxed driving',
|
||||
owner: 'amy',
|
||||
map: '/levels/italy/info.json',
|
||||
},
|
||||
]
|
||||
const search = async (query) => {
|
||||
await wrapper.find('input.search-input').setValue(query)
|
||||
return wrapper.findAll('.name-cell').map((cell) => cell.text())
|
||||
}
|
||||
|
||||
test('finds a name containing & or an apostrophe by what you type', async () => {
|
||||
stubFetch({ servers: named() })
|
||||
wrapper = await openPage('/en/servers')
|
||||
expect(await search("c&b's")).toEqual([expect.stringContaining("C&B's Banger League")])
|
||||
expect(await search('banger league')).toHaveLength(1)
|
||||
})
|
||||
|
||||
test('does not match on the colour markup behind the name', async () => {
|
||||
stubFetch({ servers: named() })
|
||||
wrapper = await openPage('/en/servers')
|
||||
expect(await search('span')).toEqual([])
|
||||
expect(await search('color')).toEqual([])
|
||||
})
|
||||
|
||||
test('still finds by description and owner', async () => {
|
||||
stubFetch({ servers: named() })
|
||||
wrapper = await openPage('/en/servers')
|
||||
expect(await search('relaxed')).toEqual([expect.stringContaining('Quiet Valley')])
|
||||
expect(await search('zed')).toEqual([expect.stringContaining("C&B's")])
|
||||
})
|
||||
})
|
||||
|
||||
test('says so when the servers cannot be loaded', async () => {
|
||||
stubFetch()
|
||||
wrapper = await openPage('/en/servers')
|
||||
expect(wrapper.find('main').text()).toContain('Failed to load servers')
|
||||
})
|
||||
})
|
||||
|
||||
describe('the policy pages', () => {
|
||||
test.each([
|
||||
['privacy', '/en/privacy', 'docs/privacy_policy.md'],
|
||||
['terms', '/en/terms', 'docs/terms.md'],
|
||||
])('%s shows the text of its document', async (_name, address, file) => {
|
||||
stubFetch()
|
||||
wrapper = await openPage(address)
|
||||
const firstHeading = publicFile(file)
|
||||
.split('\n')
|
||||
.find((line) => /^#\s+\S/.test(line))
|
||||
.replace(/^#\s+/, '')
|
||||
.trim()
|
||||
expect(wrapper.find('main').text()).toContain(firstHeading)
|
||||
})
|
||||
})
|
||||
|
||||
describe('partners', () => {
|
||||
test('shows each partner in the partners file', async () => {
|
||||
stubFetch()
|
||||
wrapper = await openPage('/en/partners')
|
||||
const partners = JSON.parse(publicFile('partners.json'))
|
||||
const list = Array.isArray(partners) ? partners : Object.values(partners).flat()
|
||||
expect(list.length).toBeGreaterThan(0)
|
||||
const names = list.map((p) => p.name).filter(Boolean)
|
||||
expect(names.length).toBeGreaterThan(0)
|
||||
for (const name of names) expect(wrapper.find('main').text(), name).toContain(name)
|
||||
})
|
||||
})
|
||||
|
||||
describe('getting around', () => {
|
||||
// The Communities, Stats and forum entries sit in dropdown menus that only
|
||||
// draw their links once opened, so they are not on a freshly loaded page.
|
||||
test('the home page links to the main pages in the current language', async () => {
|
||||
stubFetch()
|
||||
wrapper = await openPage('/en')
|
||||
const hrefs = wrapper.findAll('a').map((a) => a.attributes('href'))
|
||||
for (const page of ['/en/', '/en/communities', '/en/partners', '/en/servers', '/en/about']) {
|
||||
expect(hrefs, page).toContain(page)
|
||||
}
|
||||
})
|
||||
|
||||
test('the navigation bar links out to the docs, the store, GitHub, Patreon and the accounts portal', async () => {
|
||||
stubFetch()
|
||||
wrapper = await openPage('/en')
|
||||
const hrefs = wrapper.findAll('nav a, header a').map((a) => a.attributes('href'))
|
||||
for (const url of [
|
||||
'https://docs.beammp.com',
|
||||
'https://store.beammp.com',
|
||||
'https://github.com/BeamMP/BeamMP',
|
||||
'https://www.patreon.com/BeamMP',
|
||||
'https://accounts.beammp.com',
|
||||
]) {
|
||||
expect(hrefs, url).toContain(url)
|
||||
}
|
||||
})
|
||||
|
||||
test('the language is part of every internal link', async () => {
|
||||
stubFetch()
|
||||
wrapper = await openPage('/en')
|
||||
const internal = wrapper
|
||||
.findAll('a')
|
||||
.map((a) => a.attributes('href'))
|
||||
.filter((h) => h.startsWith('/') && !h.startsWith('/installer'))
|
||||
expect(internal.length).toBeGreaterThan(4)
|
||||
for (const href of internal) expect(href).toMatch(/^\/en(\/|$)/)
|
||||
})
|
||||
})
|
||||
|
||||
describe('the not-found page', () => {
|
||||
test('opens at a missing address, with its message and a way back', async () => {
|
||||
stubFetch()
|
||||
wrapper = await openPage('/en/this-page-does-not-exist')
|
||||
expect(wrapper.find('main').text()).toContain('404')
|
||||
expect(wrapper.find('main a').exists()).toBe(true)
|
||||
expect(warnings.filter((w) => w.includes('[Vue warn]'))).toEqual([])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,127 @@
|
||||
/**
|
||||
* Every address on the site starts with the language: /de/servers. The router
|
||||
* adds one when it is missing, remembers the one in use, switches the page's
|
||||
* language and sets the title. The real router and its guard run here.
|
||||
*/
|
||||
|
||||
import { installI18n, withRedirectLimit } from './helpers'
|
||||
import router from '@/routes'
|
||||
|
||||
// Pushing the address the router is already on does nothing (and so skips the
|
||||
// guard), so every test starts from the same neutral page.
|
||||
beforeEach(async () => {
|
||||
installI18n('en')
|
||||
await router.push('/en/privacy')
|
||||
localStorage.clear()
|
||||
installI18n('en')
|
||||
document.title = ''
|
||||
})
|
||||
|
||||
describe('addresses without a language', () => {
|
||||
test('the home address goes to the language you used last, or English', async () => {
|
||||
await router.push('/')
|
||||
expect(router.currentRoute.value.fullPath).toBe('/en')
|
||||
expect(router.currentRoute.value.name).toBe('Home')
|
||||
|
||||
localStorage.setItem('lang', 'fr')
|
||||
await router.push('/')
|
||||
expect(router.currentRoute.value.fullPath).toBe('/fr')
|
||||
})
|
||||
|
||||
test('a page address gets the language put in front of it', async () => {
|
||||
await router.push('/servers')
|
||||
expect(router.currentRoute.value.fullPath).toBe('/en/servers')
|
||||
expect(router.currentRoute.value.name).toBe('Servers')
|
||||
|
||||
localStorage.setItem('lang', 'de')
|
||||
await router.push('/about')
|
||||
expect(router.currentRoute.value.fullPath).toBe('/de/about')
|
||||
})
|
||||
})
|
||||
|
||||
describe('opening a page in a language', () => {
|
||||
test('sets the page language, remembers it, and sets the title', async () => {
|
||||
await router.push('/de/about')
|
||||
expect(router.currentRoute.value.name).toBe('About')
|
||||
expect(document.documentElement.getAttribute('lang')).toBe('de')
|
||||
expect(localStorage.getItem('lang')).toBe('de')
|
||||
expect(document.title).toBe('About - BeamMP')
|
||||
})
|
||||
|
||||
test('loads a language the first time it is used', async () => {
|
||||
expect(window.i18n.global.availableLocales).toEqual(['en'])
|
||||
await router.push('/ru/about')
|
||||
expect(window.i18n.global.availableLocales).toContain('ru')
|
||||
})
|
||||
|
||||
test('every language in the picker opens', async () => {
|
||||
for (const code of ['en', 'es', 'fr', 'de', 'it', 'ru', 'zh']) {
|
||||
await router.push(`/${code}/partners`)
|
||||
expect(router.currentRoute.value.fullPath).toBe(`/${code}/partners`)
|
||||
expect(document.documentElement.getAttribute('lang')).toBe(code)
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('the pages', () => {
|
||||
const pages = ['', 'about', 'communities', 'servers', 'stats', 'partners', 'privacy', 'terms']
|
||||
|
||||
test.each(pages)('/en/%s opens its page', async (page) => {
|
||||
await router.push(`/en/${page}`)
|
||||
expect(router.currentRoute.value.matched.length).toBeGreaterThan(0)
|
||||
expect(router.currentRoute.value.name).not.toBe('NotFound')
|
||||
})
|
||||
|
||||
test('every page has its own title and description for search engines and tabs', () => {
|
||||
const named = router.getRoutes().filter((r) => r.name && r.name !== 'NotFound')
|
||||
expect(named.length).toBeGreaterThanOrEqual(pages.length)
|
||||
for (const route of named) {
|
||||
expect(route.meta.title, `${String(route.name)} title`).toMatch(/ - BeamMP$/)
|
||||
expect(route.meta.description, `${String(route.name)} description`).toBeTruthy()
|
||||
}
|
||||
const titles = named.map((r) => r.meta.title)
|
||||
expect(new Set(titles).size).toBe(titles.length)
|
||||
})
|
||||
})
|
||||
|
||||
// This used to never finish: the not-found route matches anything, so it has
|
||||
// no `locale` param even for /en/nope. The guard took that to mean "no
|
||||
// language", redirected to /en/en/nope, which also has none, and so on - the
|
||||
// page froze instead of showing the not-found page. withRedirectLimit stops a
|
||||
// runaway redirect so a regression fails the test instead of hanging it.
|
||||
describe('an address the site does not have', () => {
|
||||
const openWithRedirectLimit = (address) => withRedirectLimit(() => router.push(address))
|
||||
|
||||
test.each([
|
||||
['/en/does-not-exist', '/en/does-not-exist'],
|
||||
['/de/does-not-exist', '/de/does-not-exist'],
|
||||
['/en/servers/nope/deeper', '/en/servers/nope/deeper'],
|
||||
])('%s shows the not-found page where it is', async (address, expected) => {
|
||||
await openWithRedirectLimit(address)
|
||||
expect(router.currentRoute.value.name).toBe('NotFound')
|
||||
expect(router.currentRoute.value.fullPath).toBe(expected)
|
||||
})
|
||||
|
||||
test('one with no language gets the language you last used, then the not-found page', async () => {
|
||||
await openWithRedirectLimit('/does-not-exist')
|
||||
expect(router.currentRoute.value.fullPath).toBe('/en/does-not-exist')
|
||||
expect(router.currentRoute.value.name).toBe('NotFound')
|
||||
|
||||
localStorage.setItem('lang', 'fr')
|
||||
await openWithRedirectLimit('/also-missing')
|
||||
expect(router.currentRoute.value.fullPath).toBe('/fr/also-missing')
|
||||
expect(router.currentRoute.value.name).toBe('NotFound')
|
||||
})
|
||||
|
||||
test('a language the site does not have is treated as part of the missing address', async () => {
|
||||
await openWithRedirectLimit('/xx/about')
|
||||
expect(router.currentRoute.value.fullPath).toBe('/en/xx/about')
|
||||
expect(router.currentRoute.value.name).toBe('NotFound')
|
||||
})
|
||||
|
||||
test('the not-found page is shown in the language of the address', async () => {
|
||||
await openWithRedirectLimit('/de/does-not-exist')
|
||||
expect(document.documentElement.getAttribute('lang')).toBe('de')
|
||||
expect(localStorage.getItem('lang')).toBe('de')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,88 @@
|
||||
// Runs before every test file (see vitest.config.js).
|
||||
|
||||
// jsdom has no matchMedia, which the theme toggle reads.
|
||||
if (!window.matchMedia) {
|
||||
window.matchMedia = (query) => ({
|
||||
matches: false,
|
||||
media: query,
|
||||
onchange: null,
|
||||
addListener: () => {},
|
||||
removeListener: () => {},
|
||||
addEventListener: () => {},
|
||||
removeEventListener: () => {},
|
||||
dispatchEvent: () => false,
|
||||
})
|
||||
}
|
||||
|
||||
// jsdom has no IntersectionObserver / ResizeObserver, which some views use.
|
||||
for (const name of ['IntersectionObserver', 'ResizeObserver']) {
|
||||
if (!window[name]) {
|
||||
window[name] = class {
|
||||
observe() {}
|
||||
unobserve() {}
|
||||
disconnect() {}
|
||||
takeRecords() {
|
||||
return []
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// jsdom cannot draw: canvas.getContext() is null, and the statistics charts call
|
||||
// ctx.scale() straight away. A stand-in whose every method does nothing lets
|
||||
// the page run; what it would have drawn is not what is tested.
|
||||
HTMLCanvasElement.prototype.getContext = function getContext() {
|
||||
const noop = () => {}
|
||||
return new Proxy(
|
||||
{ canvas: this },
|
||||
{
|
||||
get: (target, prop) =>
|
||||
prop in target ? target[prop] : prop === 'measureText' ? () => ({ width: 0 }) : noop,
|
||||
set: (target, prop, value) => {
|
||||
target[prop] = value
|
||||
return true
|
||||
},
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
// Node 22+ has its own `localStorage` global that wins over jsdom's and does
|
||||
// nothing useful unless node is started with --localstorage-file. A plain
|
||||
// in-memory one means the tests do not depend on the node version or a flag.
|
||||
class MemoryStorage {
|
||||
#map = new Map()
|
||||
getItem(key) {
|
||||
return this.#map.has(key) ? this.#map.get(key) : null
|
||||
}
|
||||
setItem(key, value) {
|
||||
this.#map.set(key, String(value))
|
||||
}
|
||||
removeItem(key) {
|
||||
this.#map.delete(key)
|
||||
}
|
||||
clear() {
|
||||
this.#map.clear()
|
||||
}
|
||||
key(index) {
|
||||
return Array.from(this.#map.keys())[index] ?? null
|
||||
}
|
||||
get length() {
|
||||
return this.#map.size
|
||||
}
|
||||
}
|
||||
|
||||
const memoryStorage = new MemoryStorage()
|
||||
Object.defineProperty(globalThis, 'localStorage', {
|
||||
value: memoryStorage,
|
||||
configurable: true,
|
||||
writable: true,
|
||||
})
|
||||
Object.defineProperty(window, 'localStorage', {
|
||||
value: memoryStorage,
|
||||
configurable: true,
|
||||
writable: true,
|
||||
})
|
||||
|
||||
beforeEach(() => {
|
||||
localStorage.clear()
|
||||
})
|
||||
@@ -0,0 +1,25 @@
|
||||
import { defineConfig } from 'vite'
|
||||
import { fileURLToPath, URL } from 'node:url'
|
||||
import vue from '@vitejs/plugin-vue'
|
||||
|
||||
// Tailwind's plugin is left out on purpose: the tests check what a page says
|
||||
// and links to, not how it looks.
|
||||
export default defineConfig({
|
||||
plugins: [vue()],
|
||||
resolve: {
|
||||
alias: {
|
||||
'@': fileURLToPath(new URL('./src', import.meta.url)),
|
||||
},
|
||||
},
|
||||
test: {
|
||||
environment: 'jsdom',
|
||||
environmentOptions: {
|
||||
jsdom: { url: 'http://localhost:5173' },
|
||||
},
|
||||
globals: true,
|
||||
setupFiles: ['./tests/setup.js'],
|
||||
// The first test to mount a big view pays for compiling it too.
|
||||
testTimeout: 20000,
|
||||
hookTimeout: 20000,
|
||||
},
|
||||
})
|
||||
Reference in new issue
Block a user