237 lines
13 KiB
React
237 lines
13 KiB
React
import { useEffect, useRef, useState } from "react";
|
||
import { ActionIcon, Card, Group, Input, Loader, Stack, Text, Tooltip } from "@mantine/core";
|
||
import { IconArrowLeft, IconArrowRight, IconChevronLeft, IconChevronRight } from "@tabler/icons-react";
|
||
import { appel } from "../commun.jsx";
|
||
|
||
// Les images de la station et de la plage choisies ; compacte : à la largeur d'une colonne (page Data), au format de l'image ;
|
||
// basculer : la flèche qui agrandit l'image vers la gauche (large) ou la ramène ; instant {t} : montrer la première image à t ou après
|
||
export function ImagesDe({ selection, compacte, large, basculer, instant }) {
|
||
const [donnees, setDonnees] = useState(null), [charge, setCharge] = useState(false);
|
||
const { station, du, au } = selection;
|
||
useEffect(() => {
|
||
setDonnees(null);
|
||
if (!station) return;
|
||
setCharge(true);
|
||
appel(`/api/images?${new URLSearchParams({ station, du, au })}`).then(d => { setDonnees(d); setCharge(false); });
|
||
}, [station, du, au]);
|
||
if (charge) return <Loader />;
|
||
if (donnees && !donnees.images.length) return <Text size="sm" c="dimmed">Aucune image de {station} sur cette plage.</Text>;
|
||
return donnees && <Visionneuse key={`${station}${du}${au}`} station={station} d={donnees} compacte={compacte} large={large} basculer={basculer} instant={instant} />;
|
||
}
|
||
|
||
function Visionneuse({ station, d, compacte, large, basculer, instant }) {
|
||
const r = { cadre: useRef(), couche: useRef(), img: useRef(), marques: useRef(), vecteurs: useRef(), glis: useRef(),
|
||
heure: useRef(), noms: useRef(), barre: useRef(), bande: useRef(), plage: useRef(), echelle: useRef(),
|
||
prec: useRef(), suiv: useRef(), montre: useRef() };
|
||
const XY = d.positions, refs = new Set(d.references), avecPositions = Object.keys(XY).length > 0;
|
||
|
||
useEffect(() => installer(r, station, d), [d]);
|
||
useEffect(() => { // « AAAA-MM-JJTHH:MMZ » face aux heures des images, « AAAA-MM-JJ HH:MM » (UTC)
|
||
if (!instant) return;
|
||
const t = instant.t.slice(0, 16).replace("T", " "), i = d.images.findIndex(im => im.t >= t);
|
||
r.montre.current(i < 0 ? d.images.length - 1 : i);
|
||
}, [instant, d]);
|
||
|
||
return (
|
||
<Card shadow="sm" withBorder padding={0} className="visionneuse">
|
||
{basculer && (
|
||
<Tooltip label={large ? "Réduire l'image" : "Agrandir l'image"}>
|
||
<ActionIcon className="agrandir" variant="filled" color="dark" aria-label={large ? "Réduire l'image" : "Agrandir l'image"} onClick={basculer}>
|
||
{large ? <IconArrowRight size={18} /> : <IconArrowLeft size={18} />}
|
||
</ActionIcon>
|
||
</Tooltip>
|
||
)}
|
||
<div className={compacte ? "cadre compacte" : "cadre"} ref={r.cadre}>
|
||
<div className="couche" ref={r.couche}>
|
||
<img ref={r.img} alt="" draggable="false" />
|
||
<svg className="marques" ref={r.marques} style={{ display: "none" }}>
|
||
{Object.entries(XY).map(([s, [x, y]]) => (
|
||
<g key={s} className={refs.has(s) ? "ref" : "cible"}>
|
||
<circle cx={x} cy={y} r=".7em" /><text x={x} y={y} dy="-1em">{s}</text>
|
||
</g>
|
||
))}
|
||
</svg>
|
||
<svg className="vecteurs" ref={r.vecteurs} style={{ display: "none" }}>
|
||
<defs><marker id="pointe" viewBox="0 0 10 14" refX="9" refY="7" markerWidth="5" markerHeight="7" orient="auto">
|
||
<path d="M0,0 L10,7 L0,14 z" fill="#2ecc40" /></marker></defs>
|
||
</svg>
|
||
</div>
|
||
</div>
|
||
<Stack gap={6} p="md">
|
||
<Group gap="sm" wrap="nowrap">
|
||
<ActionIcon ref={r.prec} variant="light" aria-label="Image précédente"><IconChevronLeft size={18} /></ActionIcon>
|
||
<input ref={r.glis} className="glisseur" type="range" min="0" max={d.images.length - 1} defaultValue="0" />
|
||
<ActionIcon ref={r.suiv} variant="light" aria-label="Image suivante"><IconChevronRight size={18} /></ActionIcon>
|
||
</Group>
|
||
<div className="barre-plages" ref={r.barre}><div className="bande" ref={r.bande} style={{ display: "none" }} /></div>
|
||
<Group gap="lg" justify="space-between">
|
||
<Text ref={r.heure} ff="monospace" size="sm" />
|
||
<Group gap="md">
|
||
<label className="case"><input type="checkbox" ref={r.noms} disabled={!avecPositions} /> Noms</label>
|
||
{avecPositions
|
||
? <span className="legende"><span className="cible">○ Cible</span> <span className="ref">◌ Référence</span></span>
|
||
: <Text size="sm" c="dimmed">x, y ne sont pas des positions dans l'image sur cette station</Text>}
|
||
</Group>
|
||
</Group>
|
||
<Group gap="lg" justify="space-between">
|
||
<Text ref={r.plage} size="sm" />
|
||
<Group gap="xs" wrap="nowrap">
|
||
<Text size="sm">Flèches ×</Text>
|
||
<Input ref={r.echelle} type="number" min={1} defaultValue={100} w={90} size="xs" />
|
||
</Group>
|
||
</Group>
|
||
<Text size="xs" c="dimmed">← → image · molette : zoom · glisser : se déplacer · double clic : image entière · flèche :
|
||
corr_x, corr_y à la fin moins au début (px), dans les axes de l'image</Text>
|
||
</Stack>
|
||
</Card>
|
||
);
|
||
}
|
||
|
||
// Le code de view/view.py (PAGE_JS), sur les éléments de la page -> la fonction qui défait ce qu'il a installé
|
||
function installer(r, station, d) {
|
||
const IM = d.images.map(i => ({ t: i.t, src: `/api/image/${encodeURIComponent(station)}/${encodeURIComponent(i.nom)}` }));
|
||
const C = d.corr, XY = d.positions;
|
||
const cadre = r.cadre.current, couche = r.couche.current, img = r.img.current, glis = r.glis.current, heure = r.heure.current;
|
||
const marques = r.marques.current, vecteurs = r.vecteurs.current, labels = r.noms.current;
|
||
const barre = r.barre.current, bande = r.bande.current, plage = r.plage.current, echelle = r.echelle.current;
|
||
let V = 0, Z = { k: 1, x: 0, y: 0 }, P = null;
|
||
|
||
function zoom() {
|
||
Z.x = Math.min(0, Math.max(1 - Z.k, Z.x)); // l'image couvre toujours le cadre : on ne la perd pas en la glissant
|
||
Z.y = Math.min(0, Math.max(1 - Z.k, Z.y));
|
||
couche.style.transform = `translate(${Z.x * 100}%, ${Z.y * 100}%) scale(${Z.k})`;
|
||
// Les noms restent à 12 px à l'écran : les tailles des marques sont en em, et 1 px du svg vaut 1 px de l'image.
|
||
const W = img.naturalWidth, H = img.naturalHeight;
|
||
if (W) marques.style.fontSize = vecteurs.style.fontSize = `${12 / (Z.k * Math.min(cadre.clientWidth / W, cadre.clientHeight / H))}px`;
|
||
cale();
|
||
}
|
||
const affiche = () => { marques.style.display = labels.checked && img.naturalWidth ? "" : "none"; };
|
||
labels.onchange = affiche;
|
||
r.montre.current = i => montre(i); // pour la page Data : l'image du début d'un événement
|
||
|
||
function montre(i) {
|
||
V = Math.max(0, Math.min(IM.length - 1, i));
|
||
glis.value = V;
|
||
img.src = IM[V].src;
|
||
for (const n of [V - 1, V + 1]) if (IM[n]) new Image().src = IM[n].src; // les voisines, en cache
|
||
}
|
||
// L'heure change avec l'image, pas avant : l'image d'avant reste affichée tant que la nouvelle se charge.
|
||
img.onload = () => {
|
||
heure.textContent = `${IM[V].t} UTC (${V + 1}/${IM.length})`;
|
||
marques.setAttribute("viewBox", `0 0 ${img.naturalWidth} ${img.naturalHeight}`); // cadré comme l'image, object-fit: contain
|
||
vecteurs.setAttribute("viewBox", marques.getAttribute("viewBox"));
|
||
fleches(); zoom(); affiche();
|
||
};
|
||
img.onerror = () => {
|
||
img.removeAttribute("src");
|
||
heure.textContent = `${IM[V].t} UTC (${V + 1}/${IM.length}) : image illisible`;
|
||
affiche();
|
||
};
|
||
|
||
glis.oninput = () => montre(+glis.value);
|
||
r.prec.current.onclick = () => montre(V - 1);
|
||
r.suiv.current.onclick = () => montre(V + 1);
|
||
const clavier = e => {
|
||
if (e.target.matches("textarea, select, input:not([type=range])") || !["ArrowLeft", "ArrowRight"].includes(e.key)) return;
|
||
e.preventDefault(); // sinon le glisseur, s'il a le focus, avance une seconde fois
|
||
montre(V + (e.key === "ArrowLeft" ? -1 : 1));
|
||
};
|
||
document.addEventListener("keydown", clavier);
|
||
|
||
const molette = ev => { // zoom autour du pointeur
|
||
ev.preventDefault();
|
||
const b = cadre.getBoundingClientRect(), u = (ev.clientX - b.left) / b.width, v = (ev.clientY - b.top) / b.height;
|
||
const k = Math.min(40, Math.max(1, Z.k * Math.exp(-ev.deltaY / 500)));
|
||
Z = { k, x: u - k * (u - Z.x) / Z.k, y: v - k * (v - Z.y) / Z.k };
|
||
zoom();
|
||
};
|
||
cadre.addEventListener("wheel", molette, { passive: false });
|
||
cadre.onpointerdown = ev => { // déplacement à la souris
|
||
cadre.setPointerCapture(ev.pointerId);
|
||
const b = cadre.getBoundingClientRect(), de = { ...Z, cx: ev.clientX, cy: ev.clientY };
|
||
cadre.onpointermove = e => { Z.x = de.x + (e.clientX - de.cx) / b.width; Z.y = de.y + (e.clientY - de.cy) / b.height; zoom(); };
|
||
cadre.onpointerup = () => { cadre.onpointermove = null; };
|
||
};
|
||
cadre.ondblclick = () => { Z = { k: 1, x: 0, y: 0 }; zoom(); };
|
||
|
||
// La plage : glisser sur la barre, alignée sur le glisseur ; les flèches vont de la position du capteur à position + k × déplacement.
|
||
function cale() {
|
||
const g = glis.getBoundingClientRect(), b = barre.getBoundingClientRect();
|
||
barre.style.marginLeft = `${(parseFloat(barre.style.marginLeft) || 0) + g.left - b.left}px`; barre.style.width = `${g.width}px`;
|
||
}
|
||
const indice = ev => { const b = barre.getBoundingClientRect(); return Math.round(Math.max(0, Math.min(1, (ev.clientX - b.left) / b.width)) * (IM.length - 1)); };
|
||
function bandeau() {
|
||
const n = Math.max(1, IM.length - 1), [i, j] = P ? [Math.min(...P), Math.max(...P)] : [0, 0];
|
||
bande.style.left = `${i / n * 100}%`; bande.style.width = `${(j - i) / n * 100}%`; bande.style.display = P ? "" : "none";
|
||
}
|
||
function deplacements() {
|
||
if (!P || P[0] === P[1]) return {};
|
||
const [i, j] = [Math.min(...P), Math.max(...P)], dep = {};
|
||
for (const [s, c] of Object.entries(C)) if (c[i] && c[j]) dep[s] = [c[j][0] - c[i][0], c[j][1] - c[i][1]];
|
||
return dep;
|
||
}
|
||
function fleches() {
|
||
const dep = deplacements(), W = img.naturalWidth, k = +echelle.value;
|
||
vecteurs.style.display = Object.keys(dep).length && W ? "" : "none";
|
||
vecteurs.querySelectorAll("line").forEach(l => l.remove());
|
||
for (const [s, [dx, dy]] of Object.entries(dep)) {
|
||
const [x, y] = XY[s], l = document.createElementNS("http://www.w3.org/2000/svg", "line");
|
||
Object.entries({ x1: x, y1: y, x2: x + k * dx, y2: y + k * dy }).forEach(([a, v]) => l.setAttribute(a, v));
|
||
const titre = document.createElementNS("http://www.w3.org/2000/svg", "title");
|
||
titre.textContent = `${s} : corr_x ${dx.toFixed(3)} px, corr_y ${dy.toFixed(3)} px`;
|
||
l.appendChild(titre);
|
||
vecteurs.appendChild(l);
|
||
}
|
||
if (P && P[0] !== P[1]) {
|
||
const [i, j] = [Math.min(...P), Math.max(...P)], manque = Object.keys(C).filter(s => !(s in dep));
|
||
plage.textContent = `${IM[i].t} → ${IM[j].t} UTC` + (manque.length ? ` · pas de mesure valide à une borne : ${manque.join(", ")}` : "");
|
||
} else plage.textContent = Object.keys(C).length ? "Glisser sur la barre pour choisir une plage" : "Pas de flèches : x, y ne sont pas des positions dans l'image";
|
||
}
|
||
// Ce que saisit le pointeur sur une plage placée : 0 son début, 1 sa fin (à 6 px près), 2 la bande entière, null rien.
|
||
function prise(ev) {
|
||
if (!P) return null;
|
||
const x = ev.clientX - barre.getBoundingClientRect().left, px = i => i / Math.max(1, IM.length - 1) * barre.clientWidth;
|
||
return Math.abs(x - px(P[0])) < 6 ? 0 : Math.abs(x - px(P[1])) < 6 ? 1 : x > px(P[0]) && x < px(P[1]) ? 2 : null;
|
||
}
|
||
barre.onpointermove = e => {
|
||
if (!barre.hasPointerCapture(e.pointerId)) barre.style.cursor = ["ew-resize", "ew-resize", "grab"][prise(e)] || "crosshair";
|
||
};
|
||
barre.onpointerdown = ev => {
|
||
barre.setPointerCapture(ev.pointerId);
|
||
const g = prise(ev), i0 = indice(ev), de = P && [...P];
|
||
if (g === null) P = [i0, i0];
|
||
bandeau(); montre(i0);
|
||
const survol = barre.onpointermove;
|
||
barre.onpointermove = e => {
|
||
const i = indice(e);
|
||
if (g === 2) { // la bande glisse sans sortir de la barre
|
||
const dd = Math.max(-de[0], Math.min(IM.length - 1 - de[1], i - i0));
|
||
P = [de[0] + dd, de[1] + dd];
|
||
} else P[g === null ? 1 : g] = i;
|
||
bandeau(); fleches(); montre(i);
|
||
};
|
||
barre.onpointerup = () => {
|
||
barre.onpointermove = survol;
|
||
P = [Math.min(...P), Math.max(...P)];
|
||
if (P[0] === P[1]) P = null;
|
||
else if (g === null) { // nouvelle plage, facteur proposé : la plus grande flèche fait 8 % de la largeur de l'image
|
||
const m = Math.max(...Object.values(deplacements()).map(([a, b]) => Math.hypot(a, b)), 0);
|
||
if (m && img.naturalWidth) echelle.value = Math.max(1, Math.round(0.08 * img.naturalWidth / m));
|
||
}
|
||
bandeau(); fleches();
|
||
};
|
||
};
|
||
echelle.oninput = fleches;
|
||
addEventListener("resize", zoom);
|
||
const observateur = new ResizeObserver(zoom); // la barre latérale qui se replie change la largeur sans resize
|
||
observateur.observe(cadre);
|
||
|
||
montre(0); cale(); fleches();
|
||
return () => {
|
||
document.removeEventListener("keydown", clavier);
|
||
removeEventListener("resize", zoom);
|
||
cadre.removeEventListener("wheel", molette);
|
||
observateur.disconnect();
|
||
};
|
||
}
|