File size: 7,432 Bytes
6457edb 59a662c 6457edb 59a662c 6457edb 59a662c 6457edb 59a662c 6457edb 59a662c 6457edb 59a662c 6457edb 59a662c 6457edb 59a662c 6457edb 59a662c 6457edb 59a662c 6457edb 59a662c 6457edb 59a662c 6457edb 1c27952 b2b8a15 3346207 6457edb 3346207 1c27952 59a662c 6457edb 59a662c 6457edb 59a662c 6457edb 7f68fbf 6457edb 59a662c 6457edb 59a662c 6457edb 59a662c | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 | // 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();
|