@geolith/globe 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,885 @@
1
+ import { computed, createBlock, createCommentVNode, createElementBlock, createElementVNode, createVNode, defineComponent, onBeforeUnmount, onMounted, openBlock, ref, shallowRef, toDisplayString, unref, watch, withCtx } from "vue";
2
+ import { WeatherFieldLayer, WindParticleLayer, decodeGrid } from "@geoql/maplibre-gl-weather";
3
+ import { SliderRange, SliderRoot, SliderThumb, SliderTrack } from "reka-ui";
4
+ // src/components/GlobeSkeleton.vue
5
+ const _hoisted_1$4 = {
6
+ "data-globe-skeleton": "",
7
+ class: "globe-skeleton"
8
+ };
9
+ const _sfc_main$3 = /*@__PURE__*/ defineComponent({
10
+ __name: "GlobeSkeleton",
11
+ setup(__props) {
12
+ return (_ctx, _cache) => {
13
+ return openBlock(), createElementBlock("div", _hoisted_1$4, [..._cache[0] || (_cache[0] = [createElementVNode("span", {
14
+ class: "globe-skeleton-ring",
15
+ "aria-hidden": "true"
16
+ }, null, -1), createElementVNode("span", { class: "globe-skeleton-label" }, "Loading the globe", -1)])]);
17
+ };
18
+ }
19
+ });
20
+ // src/utils/camera.ts
21
+ /**
22
+ * The globe opens at a fixed zoom and pitch, over one place: the visitor's
23
+ * country when the caller resolved it, the world otherwise.
24
+ */
25
+ const OPEN_ZOOM = 1.8;
26
+ /** The globe is never tilted on open: a tilted planet hides half the field. */
27
+ const OPEN_PITCH = 0;
28
+ /**
29
+ * Slow rotation so a still visitor sees a planet, not a poster. One full turn
30
+ * takes five minutes; faster reads as a loading spinner.
31
+ */
32
+ const ROTATE_DEGREES_PER_SECOND = 1.2;
33
+ /** The world view: equirectangular centre of the planet, 20° north. */
34
+ const WORLD_CENTRE = [0, 20];
35
+ /**
36
+ * The opening camera: the visitor's country's centroid when it is known, the
37
+ * world otherwise.
38
+ *
39
+ * @param centroid - `[lon, lat]` of the visitor's country, or null when unknown.
40
+ */
41
+ function openingCamera(centroid) {
42
+ return {
43
+ center: centroid ? [centroid[0], centroid[1]] : [WORLD_CENTRE[0], WORLD_CENTRE[1]],
44
+ zoom: OPEN_ZOOM,
45
+ pitch: 0
46
+ };
47
+ }
48
+ /**
49
+ * Whether the globe should rotate right now. Reduced motion is honoured, and the
50
+ * first interaction hands control to the visitor for good.
51
+ */
52
+ function shouldRotate(reducedMotion, interacted) {
53
+ return !reducedMotion && !interacted;
54
+ }
55
+ // src/utils/handover.ts
56
+ /**
57
+ * Zoom range over which the field fades out and the districts fade in. They are
58
+ * the same two numbers on purpose: the globe is always showing one of them, and
59
+ * a seam between the ramps would show as a flash of bare basemap.
60
+ */
61
+ const FIELD_FADE = [6.5, 8];
62
+ /** The districts' half of the same handover. */
63
+ const DISTRICT_FADE = [6.5, 8];
64
+ /** The desktop particle count the spike measured as free on a desktop GPU. */
65
+ const PARTICLE_CAP = 42e3;
66
+ const RAMP = FIELD_FADE;
67
+ /**
68
+ * Opacity of the global field at a zoom: 1 below the ramp, 0 above it, linear
69
+ * between.
70
+ */
71
+ function fieldOpacity(zoom) {
72
+ const [from, to] = RAMP;
73
+ if (zoom <= from) return 1;
74
+ if (zoom >= to) return 0;
75
+ return (to - zoom) / (to - from);
76
+ }
77
+ /** Opacity of the district fill at a zoom; the field's complement. */
78
+ function districtOpacity(zoom) {
79
+ return 1 - fieldOpacity(zoom);
80
+ }
81
+ /**
82
+ * How many particles to draw. A phone is given fewer because the fragment cost
83
+ * is per device pixel, and a visitor who prefers reduced motion gets none.
84
+ *
85
+ * @param width - The map's width in CSS pixels.
86
+ * @param dpr - The device pixel ratio the map draws at.
87
+ */
88
+ function particleCount(width, dpr, reducedMotion) {
89
+ if (reducedMotion) return 0;
90
+ return Math.min(PARTICLE_CAP, Math.round(width * (width < 600 ? dpr >= 2 ? 18 : 26 : 30)));
91
+ }
92
+ // src/utils/palette.ts
93
+ /**
94
+ * The field ramps. They are data ramps, not brand colours: a shader needs plain
95
+ * RGB stops, and these are perceptually spaced so a 1 mm cell never looks like a
96
+ * 40 mm cell. A caller may pass its own stops to `WeatherFieldLayer`.
97
+ */
98
+ const RAIN_RAMP = [
99
+ "#f7fbff",
100
+ "#deebf7",
101
+ "#9ecae1",
102
+ "#4292c6",
103
+ "#2171b5",
104
+ "#08519c",
105
+ "#5e3c99"
106
+ ];
107
+ /** Cold to hot, through a neutral middle so 0 °C is not tinted. */
108
+ const TEMPERATURE_RAMP = [
109
+ "#2166ac",
110
+ "#67a9cf",
111
+ "#d1e5f0",
112
+ "#f7f7f7",
113
+ "#fddbc7",
114
+ "#f4a582",
115
+ "#d6604d",
116
+ "#b2182b"
117
+ ];
118
+ /** Calm to strong, the magma ramp. */
119
+ const WIND_RAMP = [
120
+ "#3b0f70",
121
+ "#8c2981",
122
+ "#de4968",
123
+ "#fe9f6d",
124
+ "#fcfdbf"
125
+ ];
126
+ /** Every ramp the globe ships, keyed by the field family it draws. */
127
+ const FIELD_PALETTES = {
128
+ rain: RAIN_RAMP,
129
+ temperature: TEMPERATURE_RAMP,
130
+ wind: WIND_RAMP
131
+ };
132
+ /**
133
+ * The ramp for a field name: rain grids take the rain ramp, both temperature
134
+ * fields the temperature ramp, both wind components the wind ramp.
135
+ */
136
+ function paletteFor(field) {
137
+ if (field === "rain") return RAIN_RAMP;
138
+ if (field === "tmax" || field === "tmin") return TEMPERATURE_RAMP;
139
+ return WIND_RAMP;
140
+ }
141
+ // src/utils/field-frames.ts
142
+ /** The quantised cell that means "no data" in every grid. */
143
+ const NO_DATA = 255;
144
+ /**
145
+ * Rain as a field is mostly dry: the ramp's lowest stop is near-white, so a dry
146
+ * cell would paint the planet white. Cells under `minValue` (millimetres) are
147
+ * set to the no-data byte, so rain shows where rain is and nothing elsewhere.
148
+ *
149
+ * Only a rain grid is masked: a temperature cell is never "dry", and a wind
150
+ * component of zero is calm air, not an absence.
151
+ */
152
+ function maskDryRain(frames, minValue) {
153
+ return frames.map((grid) => {
154
+ const { meta } = grid;
155
+ if (meta.field !== "rain" || !(meta.scale > 0)) return grid;
156
+ const cut = Math.ceil((minValue - meta.offset) / meta.scale);
157
+ if (cut <= 0) return grid;
158
+ const bytes = new Uint8Array(grid.bytes);
159
+ let changed = false;
160
+ for (let index = 0; index < bytes.length; index += 1) if ((bytes[index] ?? NO_DATA) < cut) {
161
+ bytes[index] = NO_DATA;
162
+ changed = true;
163
+ }
164
+ return changed ? decodeGrid(bytes, meta) : grid;
165
+ });
166
+ }
167
+ // src/utils/particles.ts
168
+ /**
169
+ * How much of the particle budget the field may carry.
170
+ *
171
+ * Measured on this Mac (Chromium, SwiftShader, 1440×900, globe at z1.5, the
172
+ * field hidden so only the wind shows): the share of canvas pixels carrying a
173
+ * stroke is 1.1 % at 200 particles, 8.2 % at 4 200, 8.9 % at 8 000, 9.3 % at
174
+ * 14 700 and 9.9 % at 42 000. The curve is flat above ~4 000: 42 000 buys
175
+ * 1.7 points of coverage for ten times the work. `0.15` spends 6 300 at a
176
+ * desktop width and ~1 100 on a phone, just above the knee; the console's own
177
+ * report (a full budget became a white sheet on a phone) is the same finding
178
+ * from the other side. A host that wants more can pass its own count.
179
+ */
180
+ const PARTICLE_DENSITY = .15;
181
+ /**
182
+ * Particles for a viewport: the handover budget scaled by the measured density,
183
+ * and none at all for a visitor who prefers reduced motion.
184
+ */
185
+ function particleDensity(width, dpr, reducedMotion) {
186
+ if (reducedMotion) return 0;
187
+ return Math.max(1, Math.round(particleCount(width, dpr, false) * PARTICLE_DENSITY));
188
+ }
189
+ // src/utils/districts.ts
190
+ /** The source layer the area tiles carry. */
191
+ const AREA_SOURCE_LAYER = "areas";
192
+ const AREA_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
193
+ /**
194
+ * A district feature's own id.
195
+ *
196
+ * The MVT feature id is a tile-local integer; the area's UUID is the `id`
197
+ * property. Reading the integer asks the API for "area=192", which is not an
198
+ * area at all.
199
+ */
200
+ function areaIdOf(properties) {
201
+ const id = properties?.["id"];
202
+ return typeof id === "string" && AREA_ID.test(id) ? id : null;
203
+ }
204
+ /**
205
+ * Adds a country's area source and its two layers, once per style. The fill
206
+ * fades in on the same ramp the field fades out on; the line keeps a coastline
207
+ * readable over the weather.
208
+ */
209
+ function addDistrictLayers(map, country, url) {
210
+ const sourceId = `globe-districts-${country}`;
211
+ const fill = `${sourceId}-fill`;
212
+ const line = `${sourceId}-line`;
213
+ if (!map.getSource(sourceId)) map.addSource(sourceId, {
214
+ type: "vector",
215
+ tiles: [url],
216
+ minzoom: 0,
217
+ maxzoom: 9
218
+ });
219
+ if (!map.getLayer(fill)) map.addLayer({
220
+ id: fill,
221
+ type: "fill",
222
+ source: sourceId,
223
+ "source-layer": AREA_SOURCE_LAYER,
224
+ paint: {
225
+ "fill-color": paletteFor("rain")[4] ?? "#7fb2c9",
226
+ "fill-opacity": [
227
+ "interpolate",
228
+ ["linear"],
229
+ ["zoom"],
230
+ 6,
231
+ 0,
232
+ 7.5,
233
+ .45
234
+ ]
235
+ }
236
+ });
237
+ if (!map.getLayer(line)) map.addLayer({
238
+ id: line,
239
+ type: "line",
240
+ source: sourceId,
241
+ "source-layer": AREA_SOURCE_LAYER,
242
+ paint: {
243
+ "line-color": paletteFor("rain")[6] ?? "#2b5d74",
244
+ "line-width": .6,
245
+ "line-opacity": .7
246
+ }
247
+ });
248
+ return {
249
+ sourceId,
250
+ fill,
251
+ line
252
+ };
253
+ }
254
+ /** Reports a district click by the area's own UUID, and the pointer shape. */
255
+ function bindDistrictClicks(map, fill, onSelect) {
256
+ map.on("click", fill, (event) => {
257
+ const id = areaIdOf(event.features?.[0]?.properties ?? null);
258
+ if (id !== null) onSelect(id);
259
+ });
260
+ map.on("mousemove", fill, () => {
261
+ map.getCanvas().style.cursor = "pointer";
262
+ });
263
+ map.on("mouseleave", fill, () => {
264
+ map.getCanvas().style.cursor = "";
265
+ });
266
+ }
267
+ // src/composables/use-globe-map.ts
268
+ const FIELD_ID = "globe-field";
269
+ const FIELD_OPACITY = .85;
270
+ const PARTICLES_ID = "globe-particles";
271
+ /** Rain under this many millimetres is dry: no-data, not a white wash. */
272
+ const DRY_RAIN_MM = 1;
273
+ /**
274
+ * The map's lifecycle and its layers.
275
+ *
276
+ * MapLibre 6 refuses `setProjection` until a style is loaded, so the globe is
277
+ * converted on `load` and again on `style.load` (a new style drops both the
278
+ * projection and every custom layer). A mount can never run twice, and every
279
+ * add is guarded by the layer's existence, so N mounts and any number of prop
280
+ * changes leave exactly one map and one canvas.
281
+ */
282
+ function useGlobeMap(input) {
283
+ const map = shallowRef(null);
284
+ let field = null;
285
+ let particles = null;
286
+ let frame = 0;
287
+ let interacted = false;
288
+ let mounting = false;
289
+ let districtBound = false;
290
+ const stopRotation = () => {
291
+ if (frame !== 0) cancelAnimationFrame(frame);
292
+ frame = 0;
293
+ };
294
+ const rotate = () => {
295
+ const instance = map.value;
296
+ if (!instance || !shouldRotate(input.reducedMotion, interacted)) return;
297
+ const centre = instance.getCenter();
298
+ const lng = centre.lng + ROTATE_DEGREES_PER_SECOND / 60;
299
+ instance.setCenter([lng > 180 ? lng - 360 : lng, centre.lat]);
300
+ frame = requestAnimationFrame(rotate);
301
+ };
302
+ /** The projection, once the style can take it. */
303
+ const project = (instance) => {
304
+ if (!instance.isStyleLoaded()) return;
305
+ instance.setProjection({ type: "globe" });
306
+ };
307
+ const addField = (instance) => {
308
+ const frames = input.frames.value;
309
+ if (frames.length === 0) return;
310
+ if (field && instance.getLayer(FIELD_ID)) {
311
+ field.setFrames(maskDryRain(frames, DRY_RAIN_MM), input.mix.value);
312
+ return;
313
+ }
314
+ const first = frames[0];
315
+ const palette = input.palette ?? paletteFor(first?.meta.field ?? "rain");
316
+ field = new WeatherFieldLayer({
317
+ id: FIELD_ID,
318
+ frames: maskDryRain(frames, DRY_RAIN_MM),
319
+ mix: input.mix.value,
320
+ palette,
321
+ opacity: FIELD_OPACITY
322
+ });
323
+ if (!instance.getLayer(FIELD_ID)) instance.addLayer(field);
324
+ };
325
+ const addParticles = (instance) => {
326
+ const wind = input.wind.value;
327
+ if (!wind || particles) return;
328
+ const width = input.host.value?.clientWidth ?? 0;
329
+ const dpr = globalThis.devicePixelRatio ?? 1;
330
+ particles = new WindParticleLayer({
331
+ id: PARTICLES_ID,
332
+ u: wind.u,
333
+ v: wind.v,
334
+ count: particleDensity(width, dpr, input.reducedMotion),
335
+ animated: !input.reducedMotion
336
+ });
337
+ if (!instance.getLayer(PARTICLES_ID)) instance.addLayer(particles);
338
+ };
339
+ const addDistricts = (instance) => {
340
+ const district = input.district.value;
341
+ if (!district) return;
342
+ const ids = addDistrictLayers(instance, district.country, district.url);
343
+ if (districtBound || !input.onSelect) return;
344
+ districtBound = true;
345
+ bindDistrictClicks(instance, ids.fill, input.onSelect);
346
+ };
347
+ const wire = () => {
348
+ const instance = map.value;
349
+ if (!instance || !instance.isStyleLoaded()) return;
350
+ addField(instance);
351
+ addParticles(instance);
352
+ addDistricts(instance);
353
+ };
354
+ const mount = async () => {
355
+ if (map.value || mounting) return;
356
+ const host = input.host.value;
357
+ if (!host || typeof window === "undefined") return;
358
+ const rect = host.getBoundingClientRect();
359
+ if (rect.width === 0 || rect.height === 0) return;
360
+ mounting = true;
361
+ try {
362
+ const { Map } = await import("maplibre-gl");
363
+ if (map.value) return;
364
+ const camera = openingCamera(input.centroid);
365
+ const created = new Map({
366
+ container: host,
367
+ style: input.style,
368
+ center: camera.center,
369
+ zoom: camera.zoom,
370
+ minZoom: 0,
371
+ pitch: camera.pitch,
372
+ attributionControl: false
373
+ });
374
+ map.value = created;
375
+ created.on("load", () => {
376
+ project(created);
377
+ wire();
378
+ input.onIdle();
379
+ });
380
+ created.on("style.load", () => {
381
+ districtBound = false;
382
+ project(created);
383
+ wire();
384
+ });
385
+ created.on("zoom", () => {
386
+ if (!field) return;
387
+ field.setOpacity(FIELD_OPACITY * fieldOpacity(created.getZoom()));
388
+ });
389
+ const stop = () => {
390
+ interacted = true;
391
+ stopRotation();
392
+ };
393
+ const canvas = created.getCanvas();
394
+ canvas.addEventListener("pointerdown", stop, { once: true });
395
+ canvas.addEventListener("wheel", stop, { once: true });
396
+ canvas.addEventListener("touchstart", stop, { once: true });
397
+ if (shouldRotate(input.reducedMotion, interacted)) frame = requestAnimationFrame(rotate);
398
+ } finally {
399
+ mounting = false;
400
+ }
401
+ };
402
+ watch(input.frames, () => wire());
403
+ watch(input.mix, (value) => field?.setMix(value));
404
+ watch(input.wind, () => wire());
405
+ watch(input.district, () => wire());
406
+ const dispose = () => {
407
+ stopRotation();
408
+ field = null;
409
+ particles = null;
410
+ districtBound = false;
411
+ map.value?.remove();
412
+ map.value = null;
413
+ };
414
+ return {
415
+ map,
416
+ mount,
417
+ dispose
418
+ };
419
+ }
420
+ // src/components/GlobeCanvas.vue
421
+ const _hoisted_1$3 = ["data-globe"];
422
+ /**
423
+ * The globe itself. It draws the skeleton until the caller's data is ready,
424
+ * mounts a WebGL map only where its host has a size, and rotates slowly until
425
+ * the visitor touches it. `data-globe` carries the caller's status: it is what
426
+ * the 2.5 s budget waits for.
427
+ */
428
+ const _sfc_main = /*@__PURE__*/ defineComponent({
429
+ __name: "GlobeCanvas",
430
+ props: {
431
+ layers: {},
432
+ dataSource: {},
433
+ style: {},
434
+ status: {},
435
+ centroid: { default: null },
436
+ reducedMotion: {
437
+ type: Boolean,
438
+ default: false
439
+ },
440
+ frames: { default: () => [] },
441
+ mix: { default: 0 },
442
+ palette: { default: null },
443
+ wind: { default: null },
444
+ district: { default: null }
445
+ },
446
+ emits: ["idle", "select"],
447
+ setup(__props, { emit: __emit }) {
448
+ const props = __props;
449
+ const emit = __emit;
450
+ const host = ref(null);
451
+ const frames = ref(props.frames);
452
+ const mix = ref(props.mix);
453
+ const wind = ref(props.wind);
454
+ const district = ref(props.district);
455
+ const mountWhen = ref(props.status === "ready");
456
+ const globe = useGlobeMap({
457
+ host,
458
+ style: props.style,
459
+ centroid: props.centroid,
460
+ reducedMotion: props.reducedMotion,
461
+ source: props.dataSource,
462
+ frames,
463
+ mix,
464
+ palette: props.palette,
465
+ wind,
466
+ district,
467
+ mountWhen,
468
+ onIdle: () => emit("idle"),
469
+ onSelect: (areaId) => emit("select", areaId)
470
+ });
471
+ watch(() => props.frames, (value) => {
472
+ frames.value = value;
473
+ });
474
+ watch(() => props.mix, (value) => {
475
+ mix.value = value;
476
+ });
477
+ watch(() => props.wind, (value) => {
478
+ wind.value = value;
479
+ });
480
+ watch(() => props.district, (value) => {
481
+ district.value = value;
482
+ });
483
+ watch(() => props.status, (value) => {
484
+ mountWhen.value = value === "ready";
485
+ });
486
+ onMounted(() => {
487
+ if (props.status === "ready") globe.mount();
488
+ });
489
+ onBeforeUnmount(() => globe.dispose());
490
+ return (_ctx, _cache) => {
491
+ return openBlock(), createElementBlock("div", {
492
+ ref_key: "host",
493
+ ref: host,
494
+ class: "globe-canvas",
495
+ "data-globe": __props.status,
496
+ "data-globe-host": ""
497
+ }, [__props.status === "loading" ? (openBlock(), createBlock(_sfc_main$3, { key: 0 })) : createCommentVNode("v-if", true)], 8, _hoisted_1$3);
498
+ };
499
+ }
500
+ });
501
+ // src/components/GlobeLock.vue
502
+ const _hoisted_1$2 = ["data-globe-lock"];
503
+ /**
504
+ * The locked state for a country whose district numbers the caller may not
505
+ * show: one sentence in the catalogue's words, and a button the page answers
506
+ * with its own unlock flow.
507
+ */
508
+ const _sfc_main$1 = /*@__PURE__*/ defineComponent({
509
+ __name: "GlobeLock",
510
+ props: { country: {} },
511
+ emits: ["unlockRequest"],
512
+ setup(__props, { emit: __emit }) {
513
+ const emit = __emit;
514
+ return (_ctx, _cache) => {
515
+ return openBlock(), createElementBlock("div", {
516
+ class: "globe-lock",
517
+ "data-globe-lock": __props.country
518
+ }, [_cache[1] || (_cache[1] = createElementVNode("p", { class: "globe-lock-copy" }, " District data is not open for this country yet. ", -1)), createElementVNode("button", {
519
+ type: "button",
520
+ class: "globe-lock-action",
521
+ onClick: _cache[0] || (_cache[0] = ($event) => emit("unlockRequest", { country: __props.country }))
522
+ }, " Unlock district data for 230 countries ")], 8, _hoisted_1$2);
523
+ };
524
+ }
525
+ });
526
+ // src/components/GlobeReadout.vue
527
+ const _hoisted_1$1 = ["data-globe-readout"];
528
+ /**
529
+ * Shows the field's value under the pointer. A cell with no data prints
530
+ * nothing — never `NaN`, never `0`, which a reader would take for a
531
+ * measurement.
532
+ */
533
+ const _sfc_main$2 = /*@__PURE__*/ defineComponent({
534
+ __name: "GlobeReadout",
535
+ props: {
536
+ value: { default: null },
537
+ unit: {}
538
+ },
539
+ setup(__props) {
540
+ const props = __props;
541
+ const shown = computed(() => {
542
+ const value = props.value;
543
+ if (value === null) return "";
544
+ return `${Math.round(value * 10) / 10} ${props.unit}`;
545
+ });
546
+ return (_ctx, _cache) => {
547
+ return openBlock(), createElementBlock("span", {
548
+ class: "globe-readout",
549
+ "data-globe-readout": shown.value === "" ? void 0 : ""
550
+ }, toDisplayString(shown.value), 9, _hoisted_1$1);
551
+ };
552
+ }
553
+ });
554
+ // src/components/GlobeTimeSlider.vue
555
+ const _hoisted_1 = {
556
+ class: "globe-slider",
557
+ "data-globe-slider": ""
558
+ };
559
+ const _hoisted_2 = ["aria-label", "aria-pressed"];
560
+ const _hoisted_3 = { class: "globe-slider-label" };
561
+ /**
562
+ * The time axis of the globe. The label is the index's label (a UTC day),
563
+ * never a date computed here, and it is the slider's `aria-valuetext`, so a
564
+ * screen reader and the visible caption read the same value.
565
+ */
566
+ const _sfc_main$4 = /*@__PURE__*/ defineComponent({
567
+ __name: "GlobeTimeSlider",
568
+ props: {
569
+ labels: {},
570
+ modelValue: {},
571
+ playing: {
572
+ type: Boolean,
573
+ default: false
574
+ }
575
+ },
576
+ emits: ["update:modelValue", "toggle"],
577
+ setup(__props, { emit: __emit }) {
578
+ const props = __props;
579
+ const emit = __emit;
580
+ const label = computed(() => props.labels[props.modelValue] ?? "");
581
+ const onUpdate = (value) => {
582
+ const next = value?.[0];
583
+ if (typeof next === "number") emit("update:modelValue", next);
584
+ };
585
+ return (_ctx, _cache) => {
586
+ return openBlock(), createElementBlock("div", _hoisted_1, [
587
+ createElementVNode("button", {
588
+ type: "button",
589
+ class: "globe-slider-play",
590
+ "aria-label": __props.playing ? "Pause" : "Play",
591
+ "aria-pressed": __props.playing,
592
+ onClick: _cache[0] || (_cache[0] = ($event) => emit("toggle"))
593
+ }, toDisplayString(__props.playing ? "Pause" : "Play"), 9, _hoisted_2),
594
+ createVNode(unref(SliderRoot), {
595
+ class: "globe-slider-root",
596
+ "model-value": [__props.modelValue],
597
+ max: Math.max(__props.labels.length - 1, 0),
598
+ step: 1,
599
+ "onUpdate:modelValue": onUpdate
600
+ }, {
601
+ default: withCtx(() => [createVNode(unref(SliderTrack), { class: "globe-slider-track" }, {
602
+ default: withCtx(() => [createVNode(unref(SliderRange), { class: "globe-slider-range" })]),
603
+ _: 1
604
+ }), createVNode(unref(SliderThumb), {
605
+ class: "globe-slider-thumb",
606
+ "aria-label": "Forecast day",
607
+ "aria-valuetext": label.value
608
+ }, null, 8, ["aria-valuetext"])]),
609
+ _: 1
610
+ }, 8, ["model-value", "max"]),
611
+ createElementVNode("span", _hoisted_3, toDisplayString(label.value), 1)
612
+ ]);
613
+ };
614
+ }
615
+ });
616
+ // src/composables/use-globe-state.ts
617
+ const clamp = (value, max) => {
618
+ if (!Number.isFinite(value)) return 0;
619
+ const whole = Math.trunc(value);
620
+ if (whole < 0) return 0;
621
+ return whole > max ? max : whole;
622
+ };
623
+ /**
624
+ * The globe's state machine: which layer, model and day are showing, whether it
625
+ * plays, and which countries may show district numbers.
626
+ *
627
+ * Pure Vue reactivity — no browser API and no HTTP — so a page and a test share
628
+ * one behaviour. `now` is injected so a test can advance the exploration clock
629
+ * without sleeping.
630
+ */
631
+ function useGlobeState(initial) {
632
+ const { layers, unlocked, unlockedCountries } = initial;
633
+ const now = initial.now ?? (() => Date.now());
634
+ const dayCount = clamp(initial.days, Number.MAX_SAFE_INTEGER);
635
+ const opening = layers[0];
636
+ const selection = ref({
637
+ layerId: opening?.id ?? "",
638
+ model: opening?.models[0] ?? "ecmwf-ifs",
639
+ dayIndex: 0
640
+ });
641
+ const playing = ref(false);
642
+ const explored = ref({
643
+ layers: new Set(opening ? [opening.id] : []),
644
+ startedAt: now()
645
+ });
646
+ const lastDay = computed(() => clamp(dayCount, Number.MAX_SAFE_INTEGER) - 1);
647
+ const layer = computed(() => layers.find((entry) => entry.id === selection.value.layerId) ?? null);
648
+ const remember = (layerId) => {
649
+ if (explored.value.layers.has(layerId)) return;
650
+ explored.value = {
651
+ layers: /* @__PURE__ */ new Set([...explored.value.layers, layerId]),
652
+ startedAt: explored.value.startedAt
653
+ };
654
+ };
655
+ const select = (layerId) => {
656
+ const next = layers.find((entry) => entry.id === layerId);
657
+ if (!next) return;
658
+ const model = next.models.includes(selection.value.model) ? selection.value.model : next.models[0] ?? selection.value.model;
659
+ selection.value = {
660
+ ...selection.value,
661
+ layerId,
662
+ model
663
+ };
664
+ remember(layerId);
665
+ };
666
+ const setModel = (model) => {
667
+ if (!layer.value?.models.includes(model)) return;
668
+ selection.value = {
669
+ ...selection.value,
670
+ model
671
+ };
672
+ };
673
+ const setDay = (index) => {
674
+ selection.value = {
675
+ ...selection.value,
676
+ dayIndex: clamp(index, lastDay.value)
677
+ };
678
+ };
679
+ const togglePlaying = (value) => {
680
+ playing.value = value ?? !playing.value;
681
+ };
682
+ const lockFor = (country) => {
683
+ if (unlocked) return false;
684
+ const key = country.trim().toLowerCase();
685
+ return !unlockedCountries.some((entry) => entry.toLowerCase() === key);
686
+ };
687
+ return {
688
+ selection,
689
+ playing,
690
+ explored,
691
+ layer,
692
+ lastDay,
693
+ select,
694
+ setModel,
695
+ setDay,
696
+ togglePlaying,
697
+ lockFor
698
+ };
699
+ }
700
+ // src/composables/use-globe-fields.ts
701
+ const isIndex$1 = (value) => {
702
+ if (typeof value !== "object" || value === null) return false;
703
+ const candidate = value;
704
+ return typeof candidate.run === "string" && Array.isArray(candidate.days) && typeof candidate.width === "number" && typeof candidate.height === "number" && typeof candidate.step === "number";
705
+ };
706
+ /** A 404 is a country or run with no data, not a broken globe. */
707
+ const isMissing = (error) => {
708
+ if (error?.status === 404) return true;
709
+ return /404|not found/i.test(String(error));
710
+ };
711
+ /** `'forecast-rain'` → `'rain'`, for a caller that passes no field list. */
712
+ const fieldFromLayer = (layerId) => {
713
+ const tail = layerId.split("-").pop() ?? "";
714
+ if (tail === "rain") return "rain";
715
+ if (tail === "temperature" || tail === "tmax" || tail === "tmin") return "tmax";
716
+ return "wind-u";
717
+ };
718
+ /**
719
+ * Loads one field's index, then the selected day and the day after it, so the
720
+ * shader can blend. The composable never invents a zero field: no data is
721
+ * `'empty'` and a failed grid after a good index keeps the frames it had.
722
+ */
723
+ function useGlobeFields(input) {
724
+ const index = ref(null);
725
+ const frames = ref([]);
726
+ const mix = ref(0);
727
+ const status = ref("idle");
728
+ const labels = ref([]);
729
+ let run = 0;
730
+ const meta = (dto, day) => ({
731
+ field: dto.field,
732
+ run: dto.run,
733
+ day,
734
+ width: dto.width,
735
+ height: dto.height,
736
+ lonMin: dto.lonMin,
737
+ latMax: dto.latMax,
738
+ step: dto.step,
739
+ scale: dto.scale,
740
+ offset: dto.offset,
741
+ unit: dto.unit
742
+ });
743
+ const load = async () => {
744
+ const ticket = ++run;
745
+ const { source, selection } = input;
746
+ const field = input.fields?.[0] ?? fieldFromLayer(selection.value.layerId);
747
+ const model = selection.value.model;
748
+ status.value = "loading";
749
+ let dto;
750
+ try {
751
+ const raw = await input.fetchJson(source.indexUrl(model, field));
752
+ if (!isIndex$1(raw)) throw new Error("field index is not an index");
753
+ dto = raw;
754
+ } catch (error) {
755
+ if (ticket !== run) return;
756
+ frames.value = [];
757
+ index.value = null;
758
+ labels.value = [];
759
+ mix.value = 0;
760
+ status.value = isMissing(error) ? "empty" : "error";
761
+ return;
762
+ }
763
+ if (ticket !== run) return;
764
+ index.value = dto;
765
+ labels.value = dto.days;
766
+ const at = Math.min(Math.max(selection.value.dayIndex, 0), dto.days.length - 1);
767
+ const day = dto.days[at];
768
+ if (day === void 0) {
769
+ frames.value = [];
770
+ status.value = "empty";
771
+ return;
772
+ }
773
+ const nextDay = dto.days[at + 1] ?? day;
774
+ try {
775
+ const first = await input.fetchBytes(source.gridUrl(model, field, dto.run, day));
776
+ const second = nextDay === day ? first : await input.fetchBytes(source.gridUrl(model, field, dto.run, nextDay));
777
+ if (ticket !== run) return;
778
+ frames.value = [decodeGrid(first, meta(dto, day)), decodeGrid(second, meta(dto, nextDay))];
779
+ mix.value = 0;
780
+ status.value = "ready";
781
+ } catch (error) {
782
+ if (ticket !== run) return;
783
+ status.value = isMissing(error) ? "empty" : "error";
784
+ }
785
+ };
786
+ return {
787
+ index,
788
+ frames,
789
+ mix,
790
+ status,
791
+ labels,
792
+ load
793
+ };
794
+ }
795
+ // src/composables/use-globe-particles.ts
796
+ const isIndex = (value) => {
797
+ if (typeof value !== "object" || value === null) return false;
798
+ const candidate = value;
799
+ return typeof candidate.run === "string" && Array.isArray(candidate.days) && typeof candidate.width === "number" && typeof candidate.height === "number";
800
+ };
801
+ const dayOf = (dto, index) => {
802
+ const at = Math.min(Math.max(index, 0), dto.days.length - 1);
803
+ return dto.days[at] ?? null;
804
+ };
805
+ /**
806
+ * Loads the 10 m wind pair (`u` east, `v` north) for the selected day. A layer
807
+ * with no wind fields, or a run that published none, is `'empty'` — the globe
808
+ * then draws the field alone, never particles advected by zero wind.
809
+ */
810
+ function useGlobeParticles(input) {
811
+ const wind = ref(null);
812
+ const status = ref("idle");
813
+ let run = 0;
814
+ const one = async (model, field, dayIndex) => {
815
+ const raw = await input.fetchJson(input.source.indexUrl(model, field));
816
+ if (!isIndex(raw)) throw new Error("wind index is not an index");
817
+ const day = dayOf(raw, dayIndex);
818
+ if (day === null) return null;
819
+ const bytes = await input.fetchBytes(input.source.gridUrl(model, field, raw.run, day));
820
+ return decodeGrid(bytes, {
821
+ field,
822
+ run: raw.run,
823
+ day,
824
+ width: raw.width,
825
+ height: raw.height,
826
+ lonMin: raw.lonMin,
827
+ latMax: raw.latMax,
828
+ step: raw.step,
829
+ scale: raw.scale,
830
+ offset: raw.offset,
831
+ unit: raw.unit
832
+ });
833
+ };
834
+ const load = async () => {
835
+ const ticket = ++run;
836
+ status.value = "loading";
837
+ const { model, dayIndex } = input.selection.value;
838
+ try {
839
+ const [u, v] = await Promise.all([one(model, "wind-u", dayIndex), one(model, "wind-v", dayIndex)]);
840
+ if (ticket !== run) return;
841
+ if (!u || !v) {
842
+ wind.value = null;
843
+ status.value = "empty";
844
+ return;
845
+ }
846
+ wind.value = {
847
+ u,
848
+ v
849
+ };
850
+ status.value = "ready";
851
+ } catch (error) {
852
+ if (ticket !== run) return;
853
+ const missing = error?.status === 404;
854
+ status.value = missing ? "empty" : "error";
855
+ if (missing) wind.value = null;
856
+ }
857
+ };
858
+ return {
859
+ wind,
860
+ status,
861
+ load
862
+ };
863
+ }
864
+ // src/composables/use-globe-districts.ts
865
+ /**
866
+ * Decides whether a country's districts may be drawn at all. A locked country
867
+ * gets `null`, so the component never mounts a source it may not show: no
868
+ * district geometry reaches a browser that may not read it.
869
+ */
870
+ function useGlobeDistricts(input) {
871
+ const dataset = input.dataset ?? "boundaries";
872
+ const layerFor = (country) => {
873
+ if (!input.unlocked) return null;
874
+ const key = country.trim().toLowerCase();
875
+ if (key === "") return null;
876
+ return {
877
+ id: `globe-districts-${key}`,
878
+ source: input.districtUrl(dataset, key)
879
+ };
880
+ };
881
+ return { layerFor };
882
+ }
883
+ export { DISTRICT_FADE, FIELD_FADE, FIELD_PALETTES, _sfc_main as GlobeCanvas, _sfc_main$1 as GlobeLock, _sfc_main$2 as GlobeReadout, _sfc_main$3 as GlobeSkeleton, _sfc_main$4 as GlobeTimeSlider, OPEN_PITCH, OPEN_ZOOM, PARTICLE_CAP, RAIN_RAMP, ROTATE_DEGREES_PER_SECOND, TEMPERATURE_RAMP, WIND_RAMP, WORLD_CENTRE, districtOpacity, fieldOpacity, openingCamera, paletteFor, particleCount, shouldRotate, useGlobeDistricts, useGlobeFields, useGlobeMap, useGlobeParticles, useGlobeState };
884
+
885
+ //# sourceMappingURL=index.js.map