EmmaScharfmann's picture
Pick any two of ERA5, PARDIG and IMERG (default IMERG vs PARDIG), with their difference
7f68fbf verified
Raw History Blame Contribute Delete
7.43 kB
// Synchronised MapLibre maps playing hourly frames, one panel per entry of `panels` in the payload.
// Runs as gr.HTML js_on_load: `element` is the component, `props.value` the JSON payload from Python.
const STYLE = "https://basemaps.cartocdn.com/gl/positron-gl-style/style.json";
const state = { maps: {}, ctx: {}, images: {}, labels: [], frame: 0, n: 0, timer: null, playing: true,
key: null, token: 0 };
const $ = (sel) => element.querySelector(sel);
const names = () => Array.from(element.querySelectorAll(".rm-map")).map((d) => d.dataset.map);
function whenMaplibre() {
return new Promise((resolve) => {
const check = () => (window.maplibregl ? resolve(window.maplibregl) : setTimeout(check, 50));
check();
});
}
function loadImages(urls) {
return Promise.all(urls.map((url) => new Promise((resolve, reject) => {
const img = new Image();
img.onload = () => resolve(img);
img.onerror = reject;
img.src = url;
})));
}
async function createMap(name, view) {
const maplibregl = await whenMaplibre();
const container = $(`.rm-map[data-map="${name}"]`);
container.innerHTML = "";
const map = new maplibregl.Map({ container, style: STYLE, center: view.center, zoom: view.zoom,
attributionControl: { compact: true }, dragRotate: false,
pitchWithRotate: false });
map.touchZoomRotate.disableRotation();
map.addControl(new maplibregl.NavigationControl({ showCompass: false }), "top-right");
await new Promise((resolve) => map.on("load", resolve));
return map;
}
// (Re)create a panel's rain layer for frames of a given size: a canvas source must not be resized after it
// is created (its texture keeps the first size and renders opaque).
function rainLayer(name, width, height, corners) {
const map = state.maps[name];
const ctx = state.ctx[name];
if (ctx && ctx.canvas.width === width && ctx.canvas.height === height && map.getSource("rain")) {
map.getSource("rain").setCoordinates(corners);
return;
}
if (map.getLayer("rain")) map.removeLayer("rain");
if (map.getSource("rain")) map.removeSource("rain");
const canvas = document.createElement("canvas");
canvas.width = width; canvas.height = height;
state.ctx[name] = canvas.getContext("2d");
map.addSource("rain", { type: "canvas", canvas, animate: true, coordinates: corners });
// Under the place names, so labels stay readable.
const firstLabel = map.getStyle().layers.find((l) => l.type === "symbol");
map.addLayer({ id: "rain", type: "raster", source: "rain",
paint: { "raster-opacity": 0.88, "raster-resampling": "nearest", "raster-fade-duration": 0 } },
firstLabel ? firstLabel.id : undefined);
}
function syncAll(list) {
let busy = false;
for (const from of list) {
from.on("move", () => {
if (busy) return;
busy = true;
for (const to of list) if (to !== from) to.jumpTo({ center: from.getCenter(), zoom: from.getZoom() });
busy = false;
});
}
}
async function ensureMaps(view) {
const alive = (name) => state.maps[name] && $(`.rm-map[data-map="${name}"] canvas.maplibregl-canvas`);
if (names().every(alive)) return;
state.ctx = {};
for (const name of names()) state.maps[name] = await createMap(name, view);
syncAll(names().map((n) => state.maps[n]));
}
function draw(i) {
state.frame = i;
for (const name of names()) {
const img = (state.images[name] || [])[i];
const ctx = state.ctx[name];
if (!img || !ctx) continue;
ctx.clearRect(0, 0, img.width, img.height);
ctx.drawImage(img, 0, 0);
}
$(".rm-slider").value = i;
$(".rm-time").textContent = state.labels[i] || "";
}
function play(on) {
state.playing = on && state.n > 1;
$(".rm-play").textContent = state.playing ? "❚❚" : "▶";
$(".rm-play").setAttribute("aria-label", state.playing ? "Pause" : "Play");
clearInterval(state.timer);
if (state.playing) state.timer = setInterval(() => draw((state.frame + 1) % state.n), Number($(".rm-speed").value));
}
function legends(specs) {
for (const spec of specs) {
const box = $(`.rm-legend[data-for="${spec.target}"]`);
if (!box) continue;
if (spec.style === "bar") {
const n = spec.colors.length;
const swatches = spec.colors.map((c) => `<div style="flex:1;background:${c}"></div>`).join("");
const ticks = spec.ticks.map((t, i) =>
`<span class="rm-tick" style="left:${((i + 1) / n) * 100}%">${t}</span>`).join("");
const [left, mid, right] = spec.ends;
box.innerHTML = `<div class="rm-leg-title">${spec.title}</div>` +
`<div class="rm-bar-scale">${swatches}</div><div class="rm-ticks">${ticks}</div>` +
`<div class="rm-bar-ends"><span class="wet">← ${left}</span><span class="mid">${mid}</span>` +
`<span class="dry">${right} →</span></div>`;
continue;
}
if (spec.style === "chips") {
const chips = spec.colors.map((c, i) =>
`<span class="rm-chip"><span class="rm-chip-sw" style="background:${c}"></span>${spec.names[i]}</span>`).join("");
box.innerHTML = `<div class="rm-chips">${chips}<span class="rm-chip rm-chip-note">${spec.title}</span></div>`;
continue;
}
const cells = spec.colors.map((c, i) =>
`<div class="rm-leg-cell"><div class="rm-leg-swatch" style="background:${c}"></div>` +
`<div class="rm-leg-name">${spec.names[i]}</div><div class="rm-leg-text">${spec.labels[i]}</div></div>`).join("");
box.innerHTML = `<div class="rm-leg-title">${spec.title}</div><div class="rm-leg-cells">${cells}</div>`;
}
}
async function show() {
if (!props.value) return;
let data;
try { data = JSON.parse(props.value); } catch (e) { return; }
const token = ++state.token;
$(".rm-status").textContent = "Loading…";
await ensureMaps(data.view);
const loaded = await Promise.all(data.panels.map((p) => loadImages(p.frames)));
if (token !== state.token) return; // a newer request arrived meanwhile
state.images = {};
for (const p of data.panels) {
const title = $(`.rm-map[data-map="${p.key}"]`)?.parentElement.querySelector(".rm-title");
if (title && p.title) title.textContent = p.title;
}
data.panels.forEach((p, k) => {
state.images[p.key] = loaded[k];
if (state.maps[p.key]) rainLayer(p.key, loaded[k][0].width, loaded[k][0].height, p.corners);
});
state.labels = data.labels;
state.n = data.labels.length;
if (data.key !== state.key) {
state.maps[names()[0]].jumpTo({ center: data.view.center, zoom: data.view.zoom });
state.key = data.key;
}
$(".rm-slider").max = Math.max(state.n - 1, 0);
legends(data.legends);
$(".rm-status").textContent = "";
draw(Math.min(state.frame, state.n - 1));
play(state.n > 1 && state.playing !== false);
}
$(".rm-play").addEventListener("click", () => play(!state.playing));
$(".rm-slider").addEventListener("input", (e) => { play(false); draw(Number(e.target.value)); });
$(".rm-speed").addEventListener("change", () => play(state.playing));
document.addEventListener("keydown", (e) => {
if (!element.isConnected || state.n < 2 || ["INPUT", "SELECT", "TEXTAREA"].includes(document.activeElement?.tagName)) return;
if (e.key === "ArrowRight") { play(false); draw((state.frame + 1) % state.n); }
if (e.key === "ArrowLeft") { play(false); draw((state.frame - 1 + state.n) % state.n); }
});
watch("value", show);
show();