app: refonte JWE v2 - SvelteKit 2 + Svelte 5 + MapLibre, 4 modes de jeu, API anti-triche, ecran Cas B 'Pwen blinde', i18n FR/GCF, PWA

This commit is contained in:
sucupira
2026-07-16 21:05:22 -04:00
parent ee85a10e20
commit 923fa2869f
38 changed files with 8570 additions and 0 deletions
+421
View File
@@ -0,0 +1,421 @@
<script lang="ts">
import { onMount } from 'svelte';
import { env } from '$env/dynamic/public';
import { t } from '$lib/i18n/store.svelte';
import { MAX_BOUNDS, MIN_ZOOM, REGION_BOUNDS, REGIONS } from '$lib/map/regions';
import styleOki from '$lib/map/style-oki.json';
import type { Coordonnees, Region } from '$lib/types';
import type { Map as MLMap, Marker, StyleSpecification } from 'maplibre-gl';
interface Paire {
from: Coordonnees;
to: Coordonnees;
label?: string;
}
interface MarqueurInfo {
id: string;
lat: number;
lon: number;
label: string;
}
interface Props {
guess?: Coordonnees | null;
real?: Coordonnees | null;
interactive?: boolean;
pairs?: Paire[];
markers?: MarqueurInfo[];
onguess?: (c: Coordonnees) => void;
onvalidate?: () => void;
onmarkerclick?: (id: string) => void;
}
let {
guess = $bindable(null),
real = null,
interactive = true,
pairs = [],
markers = [],
onguess,
onvalidate,
onmarkerclick
}: Props = $props();
let conteneur: HTMLDivElement;
let map: MLMap | null = null;
let ml: typeof import('maplibre-gl') | null = null;
let guessMarker: Marker | null = null;
let realMarker: Marker | null = null;
let explorerMarkers: Marker[] = [];
let raf = 0;
const SRC_LIGNE = 'jwe-ligne';
const SRC_PAIRES = 'jwe-paires';
const reducedMotion =
typeof window !== 'undefined' && window.matchMedia('(prefers-reduced-motion: reduce)').matches;
function styleUrl(): string | StyleSpecification {
// Bascule vers un tileserver auto-hébergé sans changement de code.
if (env.PUBLIC_TILES_URL) return env.PUBLIC_TILES_URL;
return styleOki as unknown as StyleSpecification;
}
function ensureSource(id: string): void {
if (map && !map.getSource(id)) {
map.addSource(id, {
type: 'geojson',
data: { type: 'FeatureCollection', features: [] }
});
}
}
function setGeoJSON(id: string, data: GeoJSON.FeatureCollection): void {
const src = map?.getSource(id) as import('maplibre-gl').GeoJSONSource | undefined;
src?.setData(data);
}
function ligneFeature(from: Coordonnees, to: Coordonnees, props: GeoJSON.GeoJsonProperties): GeoJSON.Feature {
return {
type: 'Feature',
properties: props,
geometry: { type: 'LineString', coordinates: [[from.lon, from.lat], [to.lon, to.lat]] }
};
}
function pointFeature(c: Coordonnees, props: GeoJSON.GeoJsonProperties): GeoJSON.Feature {
return {
type: 'Feature',
properties: props,
geometry: { type: 'Point', coordinates: [c.lon, c.lat] }
};
}
function dessinerRevelation(): void {
if (!map || !ml || !real) return;
ensureSource(SRC_LIGNE);
if (!map.getLayer('jwe-ligne-line')) {
map.addLayer({
id: 'jwe-ligne-line',
type: 'line',
source: SRC_LIGNE,
paint: { 'line-color': '#e4572e', 'line-width': 3, 'line-dasharray': [2, 1.5] }
});
}
const features: GeoJSON.Feature[] = guess ? [ligneFeature(guess, real, null)] : [];
setGeoJSON(SRC_LIGNE, { type: 'FeatureCollection', features });
// Marqueur vert = position réelle
realMarker?.remove();
realMarker = new ml.Marker({ color: '#0b3d2e' }).setLngLat([real.lon, real.lat]).addTo(map);
// Le marqueur du joueur « vole » vers la position réelle (sauf reduced-motion)
if (guessMarker && guess) {
const from = { ...guess };
if (reducedMotion) {
guessMarker.setLngLat([real.lon, real.lat]);
} else {
const debut = performance.now();
const duree = 1400;
const step = (now: number) => {
if (!guessMarker) return;
const k = Math.min(1, (now - debut) / duree);
const e = 1 - Math.pow(1 - k, 3);
guessMarker.setLngLat([
from.lon + (real.lon - from.lon) * e,
from.lat + (real.lat - from.lat) * e
]);
if (k < 1) raf = requestAnimationFrame(step);
};
raf = requestAnimationFrame(step);
}
const bounds = new ml.LngLatBounds(
[Math.min(from.lon, real.lon), Math.min(from.lat, real.lat)],
[Math.max(from.lon, real.lon), Math.max(from.lat, real.lat)]
);
map.fitBounds(bounds, { padding: 80, duration: reducedMotion ? 0 : 900, maxZoom: 12 });
} else {
map.easeTo({ center: [real.lon, real.lat], zoom: 11, duration: reducedMotion ? 0 : 900 });
}
}
function nettoyerRevelation(): void {
cancelAnimationFrame(raf);
realMarker?.remove();
realMarker = null;
setGeoJSON(SRC_LIGNE, { type: 'FeatureCollection', features: [] });
}
function syncGuessMarker(): void {
if (!map || !ml) return;
if (guess) {
if (!guessMarker) {
guessMarker = new ml.Marker({ color: '#e4572e', draggable: true })
.setLngLat([guess.lon, guess.lat])
.addTo(map);
guessMarker.on('dragend', () => {
const ll = guessMarker?.getLngLat();
if (ll) {
guess = { lat: ll.lat, lon: ll.lng };
onguess?.(guess);
}
});
} else {
guessMarker.setLngLat([guess.lon, guess.lat]);
}
guessMarker.setDraggable(interactive && !real);
} else {
guessMarker?.remove();
guessMarker = null;
}
}
function syncPaires(): void {
if (!map || !ml) return;
ensureSource(SRC_PAIRES);
if (!map.getLayer('jwe-paires-line')) {
map.addLayer({
id: 'jwe-paires-line',
type: 'line',
source: SRC_PAIRES,
filter: ['==', ['geometry-type'], 'LineString'],
paint: { 'line-color': '#5a6b62', 'line-width': 2, 'line-dasharray': [2, 1.5] }
});
map.addLayer({
id: 'jwe-paires-points',
type: 'circle',
source: SRC_PAIRES,
filter: ['==', ['geometry-type'], 'Point'],
paint: {
'circle-radius': 7,
'circle-color': ['get', 'couleur'],
'circle-stroke-color': '#fffdf8',
'circle-stroke-width': 2
}
});
}
const features: GeoJSON.Feature[] = [];
for (const p of pairs) {
features.push(ligneFeature(p.from, p.to, null));
features.push(pointFeature(p.from, { couleur: '#e4572e' })); // joueur
features.push(pointFeature(p.to, { couleur: '#0b3d2e' })); // réel
}
setGeoJSON(SRC_PAIRES, { type: 'FeatureCollection', features });
if (pairs.length > 0) {
const b = new ml.LngLatBounds();
for (const p of pairs) {
b.extend([p.from.lon, p.from.lat]);
b.extend([p.to.lon, p.to.lat]);
}
map.fitBounds(b, { padding: 60, duration: reducedMotion ? 0 : 800 });
}
}
function syncExplorerMarkers(): void {
if (!map || !ml) return;
for (const m of explorerMarkers) m.remove();
explorerMarkers = [];
for (const info of markers) {
const el = document.createElement('button');
el.type = 'button';
el.className = 'marqueur-explorer';
el.setAttribute('aria-label', info.label);
const mk = new ml.Marker({ element: el, color: '#175e70' })
.setLngLat([info.lon, info.lat])
.addTo(map!);
el.addEventListener('click', (e) => {
e.stopPropagation();
onmarkerclick?.(info.id);
});
explorerMarkers.push(mk);
}
}
function sauterVers(region: Region): void {
const b = REGION_BOUNDS[region];
map?.fitBounds(
[
[b[0], b[1]],
[b[2], b[3]]
],
{ duration: reducedMotion ? 0 : 800 }
);
}
function onKeydown(e: KeyboardEvent): void {
if (!map) return;
const pas = 140; // pixels de déplacement
if (e.key === 'Enter') {
e.preventDefault();
onvalidate?.();
return;
}
const dirs: Record<string, [number, number]> = {
ArrowUp: [0, -pas],
ArrowDown: [0, pas],
ArrowLeft: [-pas, 0],
ArrowRight: [pas, 0]
};
const d = dirs[e.key];
if (!d) return;
e.preventDefault();
if (guessMarker && interactive && !real) {
// Déplacer le marqueur : conversion écran → géo pour garder un pas constant
const ll = guessMarker.getLngLat();
const pt = map.project([ll.lng, ll.lat]);
const nv = map.unproject([pt.x + d[0], pt.y + d[1]]);
guess = { lat: nv.lat, lon: nv.lng };
onguess?.(guess);
} else {
map.panBy(d, { duration: 100 });
}
}
onMount(() => {
let detruit = false;
// Lazy load : MapLibre (JS + CSS) n'est chargé que sur les écrans avec carte.
void (async () => {
const [mod] = await Promise.all([import('maplibre-gl'), import('maplibre-gl/dist/maplibre-gl.css')]);
if (detruit) return;
ml = mod;
map = new mod.Map({
container: conteneur,
style: styleUrl(),
center: [-58, 0],
zoom: 3.6,
minZoom: MIN_ZOOM,
maxBounds: [
[MAX_BOUNDS[0], MAX_BOUNDS[1]],
[MAX_BOUNDS[2], MAX_BOUNDS[3]]
],
attributionControl: { compact: true },
// Libellés FR/créole des contrôles natifs (sinon « Zoom in/out » en anglais)
locale: {
'NavigationControl.ZoomIn': t().carte.zoomIn,
'NavigationControl.ZoomOut': t().carte.zoomOut
}
});
map.addControl(new mod.NavigationControl({ showCompass: false }), 'top-left');
map.on('click', (e) => {
if (!interactive || real) return;
guess = { lat: e.lngLat.lat, lon: e.lngLat.lng };
onguess?.(guess);
});
map.on('load', () => {
syncGuessMarker();
syncPaires();
syncExplorerMarkers();
if (real) dessinerRevelation();
});
})();
return () => {
detruit = true;
cancelAnimationFrame(raf);
map?.remove();
map = null;
};
});
let ancienReal: Coordonnees | null = null;
$effect(() => {
if (!map || !map.loaded()) return;
if (real && !ancienReal) dessinerRevelation();
if (!real && ancienReal) nettoyerRevelation();
ancienReal = real;
});
$effect(() => {
if (map?.loaded()) syncGuessMarker();
void guess;
void interactive;
});
$effect(() => {
if (map?.loaded()) syncPaires();
void pairs;
});
$effect(() => {
if (map?.loaded()) syncExplorerMarkers();
void markers;
});
</script>
<div class="carte-wrap">
<!-- La zone carte est volontairement focusable : flèches = déplacer le marqueur, Entrée = valider -->
<!-- svelte-ignore a11y_no_noninteractive_tabindex, a11y_no_noninteractive_element_interactions -->
<div
class="carte"
bind:this={conteneur}
role="application"
aria-label={t().carte.ariaLabel}
tabindex="0"
onkeydown={onKeydown}
></div>
<div class="sauts" role="group" aria-label={t().carte.sautRegion}>
{#each REGIONS as region (region)}
<button type="button" class="saut" onclick={() => sauterVers(region)}>
{t().regions[region]}
</button>
{/each}
</div>
</div>
<style>
.carte-wrap {
position: relative;
width: 100%;
height: 100%;
}
.carte {
width: 100%;
height: 100%;
border-radius: var(--oki-radius);
overflow: hidden;
}
.sauts {
position: absolute;
bottom: 0.75rem;
left: 50%;
transform: translateX(-50%);
display: flex;
gap: 0.4rem;
flex-wrap: wrap;
justify-content: center;
padding: 0 0.5rem;
}
.saut {
background: rgba(255, 253, 248, 0.94);
color: var(--oki-vert);
border: 1px solid var(--oki-sable-fonce);
border-radius: 999px;
padding: 0.35rem 0.8rem;
font-size: 0.8rem;
font-weight: 650;
cursor: pointer;
box-shadow: var(--oki-ombre);
}
.saut:hover {
background: var(--oki-vert-doux);
}
:global(.marqueur-explorer) {
width: 26px;
height: 26px;
border-radius: 50%;
border: 2.5px solid var(--oki-blanc);
background: var(--oki-bleu);
cursor: pointer;
box-shadow: var(--oki-ombre);
}
:global(.marqueur-explorer:hover),
:global(.marqueur-explorer:focus-visible) {
background: var(--oki-vert-clair);
}
</style>
+43
View File
@@ -0,0 +1,43 @@
<script lang="ts">
import { t } from '$lib/i18n/store.svelte';
import { getLang, setLang, type Lang } from '$lib/i18n/store.svelte';
</script>
<div class="lang-switch" role="group" aria-label="Langue / Lang">
{#each ['fr', 'gcf'] as l (l)}
<button
type="button"
class:actif={getLang() === l}
aria-pressed={getLang() === l}
onclick={() => setLang(l as Lang)}
>
{t().langue[l as Lang]}
</button>
{/each}
</div>
<style>
.lang-switch {
display: flex;
gap: 0.25rem;
background: var(--oki-vert-doux);
border-radius: 999px;
padding: 0.2rem;
}
button {
border: none;
background: transparent;
color: var(--oki-vert);
border-radius: 999px;
padding: 0.3rem 0.75rem;
font-size: 0.85rem;
font-weight: 600;
cursor: pointer;
}
button.actif {
background: var(--oki-vert);
color: #fff;
}
</style>
+47
View File
@@ -0,0 +1,47 @@
<script lang="ts">
import type { Photo } from '$lib/types';
interface Props {
photo: Photo;
revealed?: boolean;
}
let { photo, revealed = false }: Props = $props();
</script>
<figure class="photo-panel">
<img src={photo.url} alt={photo.alt} loading="lazy" decoding="async" />
{#if revealed}
<figcaption>{photo.credit}</figcaption>
{/if}
</figure>
<style>
.photo-panel {
position: relative;
margin: 0;
width: 100%;
height: 100%;
overflow: hidden;
background: var(--oki-vert);
border-radius: var(--oki-radius);
}
img {
width: 100%;
height: 100%;
object-fit: cover;
display: block;
}
figcaption {
position: absolute;
bottom: 0;
left: 0;
right: 0;
padding: 0.4rem 0.8rem;
font-size: 0.72rem;
color: #fff;
background: linear-gradient(transparent, rgba(11, 61, 46, 0.85));
}
</style>
+114
View File
@@ -0,0 +1,114 @@
<script lang="ts">
import WikiFiche from './WikiFiche.svelte';
import { t } from '$lib/i18n/store.svelte';
import type { GuessResult } from '$lib/types';
interface Props {
result: GuessResult;
labelBouton?: string;
creditPhoto?: string;
onsuivant?: () => void;
}
let { result, labelBouton, creditPhoto, onsuivant }: Props = $props();
</script>
<section class="resultat" aria-live="polite">
<header class="score-bloc">
<p class="bravo">{result.score > 0 ? t().micro.bravo : t().micro.kiteSaYe}</p>
<p class="score">
<span class="valeur">{result.score}</span>
<span class="unite">{t().resultat.points}</span>
</p>
{#if result.distanceKm !== null}
<p class="distance">{t().resultat.distance} : {result.distanceKm} {t().resultat.km}</p>
{/if}
<p class="lieu">
<strong>{result.nom}</strong>
{#if result.nom_creole && result.nom_creole !== result.nom}
<span class="creole"> · {result.nom_creole}</span>
{/if}
<br />
{t().resultat.commune} : {result.commune}{t().regions[result.region]}
</p>
</header>
{#key result.nom}
<WikiFiche
nom={result.nom}
wikidataId={result.wikidata_id}
tonPositif={result.score > 0 ? t().resultat.trouve : t().resultat.aDecouvrir}
/>
{/key}
{#if creditPhoto}
<p class="credit-photo">{creditPhoto}</p>
{/if}
{#if onsuivant}
<button type="button" class="btn btn-primaire suivant" onclick={onsuivant}>
{labelBouton ?? t().resultat.suivant}
</button>
{/if}
</section>
<style>
.resultat {
display: flex;
flex-direction: column;
gap: 1rem;
}
.score-bloc {
text-align: center;
}
.bravo {
margin: 0;
font-size: 1.3rem;
font-weight: 700;
color: var(--oki-vert-clair);
}
.score {
margin: 0.2rem 0;
}
.score .valeur {
font-size: 2.6rem;
font-weight: 800;
color: var(--oki-vert);
}
.score .unite {
font-size: 1rem;
color: var(--oki-encre-doux);
margin-left: 0.3rem;
}
.distance {
margin: 0;
color: var(--oki-encre-doux);
}
.credit-photo {
margin: 0;
font-size: 0.72rem;
color: var(--oki-encre-doux);
text-align: center;
}
.lieu {
margin: 0.5rem 0 0;
}
.creole {
color: var(--oki-vert-clair);
font-style: italic;
}
.suivant {
align-self: center;
min-width: 220px;
}
</style>
+87
View File
@@ -0,0 +1,87 @@
<script lang="ts">
import { onMount } from 'svelte';
interface Props {
dureeMs?: number; // fenêtre du bonus temps (60 s)
actif?: boolean;
}
let { dureeMs = 60000, actif = true }: Props = $props();
let ecoule = $state(0);
let intervalle: ReturnType<typeof setInterval> | null = null;
const depart = Date.now();
// Fraction restante, de 1 (plein) à 0 (vide) — informatif, jamais anxiogène.
let fraction = $derived(Math.max(0, 1 - ecoule / dureeMs));
let termine = $derived(ecoule >= dureeMs);
const R = 15.5;
const C = 2 * Math.PI * R;
/** Temps écoulé en ms (pour le bonus côté /api/guess). */
export function tempsMs(): number {
return Date.now() - depart;
}
onMount(() => {
if (actif) {
intervalle = setInterval(() => {
ecoule = Date.now() - depart;
if (ecoule >= dureeMs && intervalle) {
clearInterval(intervalle);
intervalle = null;
}
}, 250);
}
return () => {
if (intervalle) clearInterval(intervalle);
};
});
</script>
<div class="timer" class:termine role="timer" aria-label="Minuteur" title="Minuteur">
<svg viewBox="0 0 36 36" aria-hidden="true">
<circle class="fond" cx="18" cy="18" r={R} />
<circle
class="reste"
cx="18"
cy="18"
r={R}
stroke-dasharray={C}
stroke-dashoffset={C * (1 - fraction)}
transform="rotate(-90 18 18)"
/>
</svg>
</div>
<style>
.timer {
width: 40px;
height: 40px;
}
svg {
width: 100%;
height: 100%;
display: block;
}
.fond {
fill: rgba(255, 253, 248, 0.85);
stroke: var(--oki-sable-fonce);
stroke-width: 3;
}
.reste {
fill: none;
stroke: var(--oki-vert-clair); /* couleur douce, calm technology */
stroke-width: 3;
stroke-linecap: round;
transition: stroke-dashoffset 0.25s linear;
}
.termine .reste {
stroke: var(--oki-sable-fonce);
}
</style>
+182
View File
@@ -0,0 +1,182 @@
<script lang="ts">
import { onMount } from 'svelte';
import { t } from '$lib/i18n/store.svelte';
import type { WikiSummary } from '$lib/types';
interface Props {
nom: string;
wikidataId: string | null;
tonPositif?: string;
tonNeutre?: string;
}
let { nom, wikidataId, tonPositif, tonNeutre }: Props = $props();
// undefined = chargement, null = pas de fiche (Cas B), WikiSummary = Cas A
let wiki = $state<WikiSummary | null | undefined>(undefined);
onMount(() => {
if (!wikidataId) {
wiki = null;
return;
}
let annule = false;
void (async () => {
try {
const res = await fetch(`/api/wiki/${wikidataId}`);
if (annule) return;
wiki = res.ok ? ((await res.json()) as WikiSummary) : null;
} catch {
if (!annule) wiki = null;
}
})();
return () => {
annule = true;
};
});
const lienContribution = $derived(
`https://fr.wikipedia.org/w/index.php?search=${encodeURIComponent(nom)}&title=Sp%C3%A9cial:Recherche`
);
</script>
{#if wiki === undefined}
<div class="panneau chargement">
<p>{t().explorer.chargerFiche}</p>
</div>
{:else if wiki}
<!-- Cas A : fiche Wikipédia existante -->
<article class="panneau cas-a">
<h2>
<a href={wiki.url} target="_blank" rel="noopener noreferrer">{wiki.title}</a>
</h2>
{#if tonPositif || tonNeutre}
<p class="ton">{tonPositif ?? tonNeutre}</p>
{/if}
{#if wiki.thumbnail}
<img src={wiki.thumbnail} alt="" loading="lazy" decoding="async" />
{/if}
<p class="extrait">{wiki.extract}</p>
<a class="lien-wiki" href={wiki.url} target="_blank" rel="noopener noreferrer">
{t().resultat.lireWiki}
</a>
</article>
{:else}
<!-- Cas B : lacune documentaire — panneau volontairement distinct (Peak-End) -->
<article class="panneau cas-b">
<h2><span class="icone" aria-hidden="true"></span> {t().lacune.titre}</h2>
<p class="texte">{t().lacune.texte}</p>
<a class="btn btn-cta" href={lienContribution} target="_blank" rel="noopener noreferrer">
{t().lacune.cta}
</a>
<p class="guide">
{t().lacune.guide}
<a href="https://fr.wikipedia.org/wiki/Aide:Premiers_pas" target="_blank" rel="noopener noreferrer">
{t().lacune.guideLien}
</a>
</p>
</article>
{/if}
<style>
.panneau {
border-radius: var(--oki-radius);
padding: 1.1rem 1.25rem;
box-shadow: var(--oki-ombre);
}
.chargement {
background: var(--oki-blanc);
color: var(--oki-encre-doux);
text-align: center;
}
/* Cas A : vert doux, apaisé */
.cas-a {
background: var(--oki-vert-doux);
border: 1.5px solid var(--oki-vert-clair);
}
.cas-a h2 {
margin: 0 0 0.3rem;
font-size: 1.2rem;
}
.cas-a h2 a {
color: var(--oki-vert);
}
.cas-a .ton {
margin: 0 0 0.6rem;
font-weight: 600;
color: var(--oki-vert-clair);
}
.cas-a img {
float: right;
width: 96px;
height: auto;
margin: 0 0 0.5rem 0.8rem;
border-radius: var(--oki-radius-petit);
}
.cas-a .extrait {
margin: 0 0 0.6rem;
}
.lien-wiki {
color: var(--oki-bleu);
font-weight: 650;
}
/* Cas B : teinte sable/orangée distincte, icône spécifique */
.cas-b {
background: var(--oki-lacune-fond);
border: 2px solid var(--oki-lacune-bord);
}
.cas-b h2 {
margin: 0 0 0.5rem;
font-size: 1.25rem;
color: #8a5a00;
display: flex;
align-items: center;
gap: 0.5rem;
}
.cas-b .icone {
display: inline-flex;
align-items: center;
justify-content: center;
width: 1.6rem;
height: 1.6rem;
border: 2.5px dashed var(--oki-lacune-bord);
border-radius: 50%;
font-size: 1rem;
}
.cas-b .texte {
margin: 0 0 0.9rem;
font-size: 1.02rem;
}
.btn-cta {
background: var(--oki-lacune-bord);
color: #fff;
}
.btn-cta:hover {
background: #b98a2f;
}
.guide {
margin: 0.8rem 0 0;
font-size: 0.88rem;
color: var(--oki-encre-doux);
}
.guide a {
color: var(--oki-bleu);
font-weight: 600;
}
</style>