diff --git a/CHANGELOG.md b/CHANGELOG.md index 064964f38..b1edd67b7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,39 +2,6 @@ ## [Unreleased] -- Timeline marks have labels. Hovering a tick shows its label (a launch's - mission name, or an earthquake's magnitude and place, such as - `M6.4 · 113 km SSE of Lata, Solomon Islands`), and a tap on or within 6 px - of a tick goes exactly to its mark rather than to the point tapped; a tap - elsewhere and a drag work as before. The arrow keys still step from mark to - mark, and the handle then tells the mark's label with the time to screen - readers and shows it over the track while focused. A layer's world clock - coverage may give each mark as `{ time, label, id, kind }` as well as a - bare time; `worldClock.coverage()` keeps `marks` as the sorted times and - adds `markDetails`, the merged marks themselves (samehkhamis). -- The timeline marks only events: launches, and earthquakes of magnitude 6 - and up while the Earthquakes layer is on (about one every two days - worldwide). It no longer draws a tick for every weather frame, which came - every few minutes and made the track a wall of dashes; the weather frames - still set the time the timeline covers, and Play still waits at each next - frame until it loads. With no mark ahead, the arrow keys step along the - track. The map still draws every earthquake, and an earthquake layer never - widens the timeline beyond its strong quakes' own times. A weather row's - `step` param goes to the previous or next weather frame (samehkhamis). -- The main timeline is the only time control. The Weather panel no longer - has a slider, step buttons, Latest or Play of its own; it shows the frame - time instead: the newest frame and its age while live, the timeline time - alone at a past time. The timeline's Play runs the world clock at the - chosen speed for weather too, stopping at each next frame until it loads, - rather than stepping the observed frames every two seconds and going round - from the last to the first. A weather row's `play`, `latest` and `step` - params move the world clock as the timeline does (`step` goes to the - previous or next mark, as its arrow keys do). **Breaking:** the catalog's - `weatherClock` (`gods-eye-view/application/layers`) no longer has - `setTarget`, `step`, `latest`, `play`, `pause` or `togglePlay`, its state - no longer has `playing`, and it no longer attaches itself to the world - clock as a driver; move time with the world clock (`gods-eye-view/time`, - also `weatherClock.world`) instead (samehkhamis). - A double-click on the map no longer follows or zooms to what is under it. The globe's own double-click did that for some layers' markers and shapes (earthquakes, cyclones, air quality, news, cables, places and diff --git a/docs/APPLICATION.md b/docs/APPLICATION.md index cdd5582bf..3cbd1c027 100644 --- a/docs/APPLICATION.md +++ b/docs/APPLICATION.md @@ -302,28 +302,7 @@ instances. Configure sources with `application/sources` before registration or state restoration, and release them after the consumers stop. The catalog constructor (`application/layers`) also requires `wind`, `weather` and `cyclones` sources with `getSnapshot` for the Weather layers, and owns the -observed-history clock those layers share for the catalog's lifetime. That -clock, the catalog's `weatherClock`, follows the world clock (`gods-eye-view/time`) -and has no time controls of its own: move time with the world clock's `seek`, -`play`, `pause` and `goLive` (`weatherClock.world` is the one it follows). - -A layer gives the world clock's timeline the time it can show with -`worldClock.register({ id, coverage })` (`gods-eye-view/time`), which returns -the unregister; call `worldClock.coverageChanged()` when that time changes. -`coverage()` returns null while the layer has none, or -`{ start, end, marks? }` in epoch ms. `marks` are the moments worth going to, -drawn as ticks the timeline's arrow keys step to and a tap on or within 6 px of -snaps to. Each mark is a number, or `{ time, label?, id?, kind? }`: `label` is -short text shown when the pointer is on the tick and told with the time while -the handle is on the mark, `id` the layer's own key for the event and `kind` -what sort of event it is (`'launch'`, `'earthquake'`). The two forms may be -mixed; a mark without a finite time, and a `label`, `id` or `kind` that is not -a non-empty string, are ignored. `worldClock.coverage()` returns the union of -the registered layers, `{ start, end, marks, markDetails }`, or null: `marks` -is every mark's time once, in order, as numbers, and `markDetails` the marks in -time order, each a frozen `{ time, label?, id?, kind? }` holding only the -fields given, with marks given alike by several layers once and a bare time -left out where a mark with more to say shares it. +observed-history clock those layers share for the catalog's lifetime. A `weather` source may also supply decoded frames: an optional `getFrameImage({ product, time, size, bbox, signal })` returns a whole-extent or detail image and an optional `getFrameTile({ product, time, z, x, y, size, diff --git a/docs/CODE-BOUNDARIES.md b/docs/CODE-BOUNDARIES.md index 44d598cac..2c3058627 100644 --- a/docs/CODE-BOUNDARIES.md +++ b/docs/CODE-BOUNDARIES.md @@ -294,9 +294,9 @@ the user's later collapse choice, including body remounts. Mark the body `max-height` and puts the scroll offset back afterwards. Panel bodies only scroll on an open-card change, with one write, never on a refresh. -Compose `createRailCards({ container, document, onParams, onOpen })`. Rails -have no time controls of their own; the world timeline moves time. Cards -reconcile `{ id, title, badge, open, compact, +Compose `createRailCards({ container, document, onParams, onOpen })` and +`createRailTimeline({ container, document, onCommit, onPreview, onStep, +onLatest, onPlay })`. Cards reconcile `{ id, title, badge, open, compact, compactStatus, blocks }` in place. Their full-width native button headers expose `aria-expanded` and `aria-controls`; articles expose `data-open`. The feature adapter owns accordion state. Generic cards do not select data or enable layers. @@ -331,9 +331,10 @@ consumers. They expose `summary.settings`, `summary.actions` and optional subscriptions still refresh the cards. Cards own configuration and readings. Weather orders cyclones, wind, then a bordered Observed history group containing -the frame time and active radar, satellite and lightning cards. The group -heading and scope name its active products. The frame time shows whenever any -observed product is enabled and has a frame; the world timeline moves time. +the timeline and active radar, satellite and lightning cards. The group heading +and scope name its active products. The timeline stays visible whenever any +observed product is enabled; fewer than two ticks disables transport. Pass +`heading: false` to the timeline when the containing group owns the heading. Exactly one active card is open. Header clicks and newly enabled ids choose it (the last new entry wins a batch); refreshes and clock ticks retain it. First appearance uses cyclones with storms, otherwise the first card. Disabling the @@ -341,7 +342,7 @@ open layer falls back to the first remaining card. A WeakMap per document keeps explicit choices through body remounts without adding share state. Card opening, storm selection and layer enabling remain independent. -Optional card/badge class names provide feature styling. Card titles use +Optional card/badge/slider class names provide feature styling. Card titles use `.data-name` typography; meta/time/badges use `.data-toggle-meta` typography; setting/result labels use `.panel-title`; chips retain `.data-toggle-chip`. Reserve one status line, even without a legend. Use app tokens. Wind's footer diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index 978862a65..2ba25becc 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -1704,14 +1704,7 @@ it a Cesium viewer, with no renderer bound, loads the `./render/cesium/unbound` export once first. `depthColor` returns a renderer colour `[r, g, b, a]` and `depthAccent` its CSS. The standalone adapter keeps the existing USGS daily feed, M2.5+ filtering, static discs, magnitude labels and analyst records. Disabling or -destroying the layer cancels pending work and ignores late results. While on, -the layer registers its quakes of magnitude 6 and up -(`EARTHQUAKE_MARK_MAGNITUDE`) with the world clock as timeline marks, spanning -only their own times, and none while off; the map still draws every M2.5+ -quake. Each mark is labelled with the magnitude as the map shows it and the -feed's place, cut to 40 characters (`earthquakeMarkLabel` in -`src/layers/earthquakes/model.js`: `M6.4 · 113 km SSE of Lata, Solomon -Islands`, or `M6.4` with no place). +destroying the layer cancels pending work and ignores late results. Air quality (`./layers/air-quality`) draws its station discs as one renderer draw set of ground-clamped fills and reads the view through the camera port; it @@ -8630,21 +8623,9 @@ Wind supports selectable GFS/IFS models with persisted model choice. Each fetch Weather combines the GFS/ECMWF surface forecast with three observation layers: NOAA Rain radar (CONUS), Satellite clouds (regional GOES or slower global infrared), and 15-minute lightning density (Americas and Pacific). One transient observed -clock moves all enabled observation rows with the world clock; the world -timeline is the only time control. Each product's advertised times span time on -that timeline but are not marks on it: the timeline marks only events (launches, -and earthquakes of magnitude 6 and up while that layer is on), so its arrow keys -step to those, or along the track where there are none. A mark may carry a -label (a launch's mission name, cut to 27 characters in capitals as the mission -index shows names; an earthquake's magnitude and place). The pointer within -6 px of a tick shows its label over the track, and a tap there goes to the -mark's time exactly; a tap elsewhere goes to the time under it and a drag -scrubs. With the handle on a mark, its label follows the time in the handle's -`aria-valuetext` and shows over the track while the handle has focus. The -coverage contract is in [APPLICATION.md](./APPLICATION.md). A weather row's `step` -param goes to the previous or next weather frame. Each product selects its -nearest frame at or before the world time, never a future frame or an -interpolation. +clock drives all enabled observation rows. Earlier/Later use the sorted union of +non-suspended products' advertised times; each product selects its nearest frame +at or before the requested UTC time, never a future frame or an interpolation. The maximum gap is 30 minutes for radar, regional infrared and lightning, and 3 hours for hourly global infrared, but never less than one and a half of the feed's median frame spacing over its latest frames, so a regional feed whose @@ -8654,29 +8635,21 @@ lightning, 4 hours for global infrared). A missing eligible frame hides that pro and reports the gap; rows show actual displayed UTC time with synced/nearest labels. Manifest rollover preserves the requested history time, even when frames expire. -Live follows each product's own newest frame, so its timestamps can differ. -The timeline's Play runs the world clock at the chosen speed and stops at each -product's next frame until that frame loads (for at most eight seconds), so -every frame shows. Hidden documents, reduced motion and unavailable imagery -hosts suspend products. Re-enabling or +Latest follows each product's own newest frame, so its timestamps can differ. +Playback advances two seconds after all products settle, wraps, and stops with +fewer than two union times or when all products are suspended. Hidden documents, +reduced motion and unavailable imagery hosts suspend products. Re-enabling or restoring a host joins the retained history target. The wind row explicitly says “Forecast · does not follow history” while the observed clock is in history mode, unless a host follows the world clock for `wind` (`weatherClock.follows('wind')`): its source then follows the timeline and the row says nothing of it. In history mode, frame ages and the “Source observations delayed” status are measured from -the timeline time rather than the wall clock, and the panel's frame time shows -the time alone; live, it shows the newest frame and its age, and ages count -from now as before. -The catalog exposes `weatherClock` and destroys it with its lifetime signal. It -has no time controls of its own: `weatherClock.world` is the world clock it -follows, where time moves. A weather row's `play`, `latest` and `step` params -move that world clock as the timeline does. A weather layer built without a shared -clock keeps one of its own on the page's world clock for its lifetime; it has -no frame replay of its own either way. +the timeline time rather than the wall clock, and the timeline readout shows the +time alone; live, they count from now as before. +The catalog exposes `weatherClock` and destroys it with its lifetime signal. -Source, opacity and coverage navigation live in the WEATHER panel's cards, not -in the rows; the panel shows the frame time and has no time controls. The -viewer clock is untouched. +Source, opacity, coverage navigation and transport controls live in the WEATHER +panel's cards and timeline, not in the rows. The viewer clock is untouched. Observation layers are off by default; share/persist includes appearance and product, while history is transient and shared links open latest. Rendering retains the previous frame when an incoming frame fails; no eligible historical frame instead hides imagery. diff --git a/docs/VUE-MIGRATION.md b/docs/VUE-MIGRATION.md index 91a9d4228..3dcd7f63b 100644 --- a/docs/VUE-MIGRATION.md +++ b/docs/VUE-MIGRATION.md @@ -153,9 +153,9 @@ a feature supplying only its accent. `t()`, which follows the locale as the view renders; the views carry no `data-i18n*` markers, which `npm run i18n` rejects in a template. Shared builders become components first and keep their imperative entry points until their owners are components: - the rail cards and card blocks (`src/ui/rail/`) render through - Vue's synchronous `render()` behind `createRailCards()` and - `createRailCardBlocks()`. Order: Scenes (done: `SceneOptions` and + the rail cards, card blocks and timeline (`src/ui/rail/`) render through + Vue's synchronous `render()` behind `createRailCards()`, + `createRailCardBlocks()` and `createRailTimeline()`. Order: Scenes (done: `SceneOptions` and `SceneShotList` over the `gev-scenes` store; the panel's buttons, status line, progress bar and the runtime chip render the panel SceneControls presents there, and the buttons and file chooser call its actions), Weather (done: the owner diff --git a/scripts/format-scope.json b/scripts/format-scope.json index 4aaf837c5..849c6c0d7 100644 --- a/scripts/format-scope.json +++ b/scripts/format-scope.json @@ -982,6 +982,8 @@ "src/ui/weatherPanel.test.mjs", "src/ui/railCards.js", "src/ui/railCards.test.mjs", + "src/ui/railTimeline.js", + "src/ui/railTimeline.test.mjs", "src/layers/weather/imageryOrder.js", "src/layers/weather/imageryOrder.test.mjs", "server/providers/cyclones.js", diff --git a/scripts/package-boundaries.json b/scripts/package-boundaries.json index 590f07703..a4f835e63 100644 --- a/scripts/package-boundaries.json +++ b/scripts/package-boundaries.json @@ -861,6 +861,7 @@ "src/ui/layerPanel/RowSwitch.vue", "src/ui/layerPanel/RowRange.vue", "src/ui/layerPanel/RowSlider.vue", + "src/ui/railTimeline.js", "src/ui/clearLayersControl.js", "src/loadingFeedback.js", "src/data/installationFeedback.js", @@ -893,6 +894,7 @@ "src/ui/rail/RailCard.vue", "src/ui/rail/RailCards.vue", "src/ui/rail/utcClock.js", + "src/ui/rail/RailTimeline.vue", "src/ui/rail/rangeValue.js", "src/ui/weather/WeatherReadout.vue", "src/ui/newsPanel.js", @@ -1352,6 +1354,7 @@ "src/ui/layerPanel/RowSwitch.vue", "src/ui/layerPanel/RowRange.vue", "src/ui/layerPanel/RowSlider.vue", + "src/ui/railTimeline.js", "src/ui/layers.js", "src/ui/leftPanelRail.js", "src/ui/location.js", @@ -1454,6 +1457,7 @@ "src/ui/rail/RailCard.vue", "src/ui/rail/RailCards.vue", "src/ui/rail/utcClock.js", + "src/ui/rail/RailTimeline.vue", "src/ui/rail/rangeValue.js", "src/ui/weather/WeatherReadout.vue", "src/ui/newsPanel.js", @@ -2423,8 +2427,7 @@ "src/geo/vector.js", "src/layers/earthquakes/model.js", "src/layers/earthquakes/source.js", - "src/layers/earthquakes/records.js", - "src/time/worldClock.js" + "src/layers/earthquakes/records.js" ], "external": ["cesium"] }, @@ -4569,6 +4572,7 @@ "src/ui/layerPanel/RowSwitch.vue", "src/ui/layerPanel/RowRange.vue", "src/ui/layerPanel/RowSlider.vue", + "src/ui/railTimeline.js", "src/ui/layers.js", "src/ui/leftPanelRail.js", "src/ui/location.js", @@ -5127,6 +5131,7 @@ "src/ui/rail/RailCards.vue", "src/ui/rail/RailCardBlocks.vue", "src/ui/rail/utcClock.js", + "src/ui/rail/RailTimeline.vue", "src/ui/rail/rangeValue.js", "src/ui/weather/WeatherReadout.vue", "src/ui/newsPanel.js", diff --git a/src/app/constructCatalog.test.mjs b/src/app/constructCatalog.test.mjs index 8e742ff6b..dadf2c541 100644 --- a/src/app/constructCatalog.test.mjs +++ b/src/app/constructCatalog.test.mjs @@ -6,11 +6,6 @@ import { createStandaloneLayerSources } from '../standalone/layerSources.js'; import { catalogControlServices } from './catalog.js'; import { LayerLifecycle } from '../data/lifecycle.js'; import { fakeStreetLevelProvider } from '../testSupport/streetLevelFakes.mjs'; -import { worldClock } from '../time/worldClock.js'; - -const flush = async () => { - for (let i = 0; i < 20; i++) await Promise.resolve(); -}; function fixtureSources(ids, calls) { const sources = createStandaloneLayerSources(); @@ -32,7 +27,6 @@ test('catalogs construct distinct layers and classification from their supplied t.after(() => { a.abort(); b.abort(); - worldClock.goLive(); }); const callsA = []; const callsB = []; @@ -59,10 +53,7 @@ test('catalogs construct distinct layers and classification from their supplied 'the hardware-local layer is never serialized into links', ); assert.notEqual(first.weatherClock, second.weatherClock); - // Time moves on the world clock, which the catalog's weather clock follows. - assert.equal(first.weatherClock.world, worldClock); - worldClock.seek(Date.parse('2026-09-21T12:00:00.000Z')); - await flush(); + await first.weatherClock.setTarget('2026-09-21T12:00:00.000Z'); assert.match( first.get('wind').getRowControls().info, /Forecast · does not follow history/, @@ -120,16 +111,9 @@ test('catalogs construct distinct layers and classification from their supplied assert.equal(first.militaryRegistry.isMilitaryIcao('def456'), false); assert.equal(second.militaryRegistry.isMilitaryIcao('def456'), true); a.abort(); - worldClock.seek(Date.parse('2026-09-21T13:00:00.000Z')); - await flush(); assert.equal( - first.weatherClock.getState().target, - '2026-09-21T12:00:00.000Z', - 'an aborted catalog no longer follows the world clock', - ); - assert.equal( - second.weatherClock.getState().target, - '2026-09-21T13:00:00.000Z', + await first.weatherClock.setTarget('2026-09-21T13:00:00.000Z'), + false, ); assert.equal(callsA[0].aborted, true); assert.equal(first.militaryRegistry.isMilitaryIcao('abc123'), false); diff --git a/src/data/rocketLaunches.test.mjs b/src/data/rocketLaunches.test.mjs index 99fc05c2e..71dce817f 100644 --- a/src/data/rocketLaunches.test.mjs +++ b/src/data/rocketLaunches.test.mjs @@ -1247,15 +1247,7 @@ test('real mission build, select, refresh, deselect, disable, and destroy paths assert.equal(worldClock.coverage(), null, 'nothing loaded, no time to show'); await rocketLaunchesLayer.update(); const at = Date.parse(launchTime); - // The launch is a mark labelled with its mission's name. - assert.deepEqual(worldClock.coverage(), { - start: at, - end: at, - marks: [at], - markDetails: [ - { time: at, label: 'GAUNTLET PAYLOAD', id: 'mission-runtime', kind: 'launch' }, - ], - }); + assert.deepEqual(worldClock.coverage(), { start: at, end: at, marks: [at] }); assert.equal(worldClock.isSupported(), true, 'loaded launches bring up the timeline'); assert.ok(missionItems().size >= 7, 'runtime guard requires the populated mission build path'); diff --git a/src/i18n/locales/ar.json b/src/i18n/locales/ar.json index 3c0748ce4..c42e7e25b 100644 --- a/src/i18n/locales/ar.json +++ b/src/i18n/locales/ar.json @@ -2031,6 +2031,7 @@ "60°S–60°N · typically 2–3 h delayed": "60° ج–60° ش · بتأخير 2–3 س عادةً", "North America · infrared imagery": "أمريكا الشمالية · صور بالأشعة تحت الحمراء", "Reduced motion · history playback unavailable": "تقليل الحركة · تشغيل السجل غير متاح", + "Reduced motion · manual history available": "تقليل الحركة · التصفح اليدوي للسجل متاح", "Rain radar · US": "رادار الأمطار · الولايات المتحدة", "Lightning density · 15 min": "كثافة البرق · 15 د", "Satellite clouds": "الغيوم من الأقمار الصناعية", @@ -2540,8 +2541,12 @@ "PAUSE": "إيقاف مؤقت", "RESUME": "استئناف", "Clear reading": "مسح القراءة", + "Earlier observation": "رصد أسبق", "Observed history": "سجل الأرصاد", + "Later observation": "رصد لاحق", "Latest": "الأحدث", + "Newest frame per product": "أحدث إطار لكل منتج", + "Replay observed history": "إعادة تشغيل سجل الأرصاد", "Imagery on Esri · Google 3D returns when cleared": "الصور على Esri · تعود Google 3D عند المسح", "Point the camera at the ground to use the view": "وجّه الكاميرا نحو الأرض لاستخدام العرض", "That point cannot anchor a box": "لا يمكن تثبيت منطقة على تلك النقطة", @@ -2842,6 +2847,7 @@ "dB": "dB", "{time} · {minutes} min ago": "{time} · قبل {minutes} د", "Active weather": "الطقس النشط", + "LATEST · newest per product": "الأحدث · آخر إطار لكل منتج", "Forecast · valid {valid} · issued {issued}": "توقع عند {valid} · صدر {issued}", "{detail} · Does not follow history": "{detail} · لا يتبع السجل", "Forecast · valid {valid}": "توقع عند {valid}", diff --git a/src/i18n/locales/de.json b/src/i18n/locales/de.json index f6cd32606..d23b3e225 100644 --- a/src/i18n/locales/de.json +++ b/src/i18n/locales/de.json @@ -1935,6 +1935,7 @@ "60°S–60°N · typically 2–3 h delayed": "60°S–60°N · meist 2–3 h verzögert", "North America · infrared imagery": "Nordamerika · Infrarotbilder", "Reduced motion · history playback unavailable": "Reduzierte Bewegung · Verlaufswiedergabe nicht verfügbar", + "Reduced motion · manual history available": "Reduzierte Bewegung · manueller Verlauf verfügbar", "Rain radar · US": "Regenradar · USA", "Lightning density · 15 min": "Blitzdichte · 15 min", "Satellite clouds": "Wolken (Satellit)", @@ -2400,8 +2401,12 @@ "PAUSE": "PAUSE", "RESUME": "FORTSETZEN", "Clear reading": "Wert ausblenden", + "Earlier observation": "Frühere Beobachtung", "Observed history": "Beobachteter Verlauf", + "Later observation": "Spätere Beobachtung", "Latest": "Neueste", + "Newest frame per product": "Neuester Frame je Produkt", + "Replay observed history": "Beobachteten Verlauf abspielen", "Imagery on Esri · Google 3D returns when cleared": "Bilder auf Esri · nach LÖSCHEN wieder Google 3D", "Point the camera at the ground to use the view": "Kamera auf den Boden richten, um die Ansicht zu verwenden", "That point cannot anchor a box": "Dieser Punkt kann keinen Bereich verankern", @@ -2650,6 +2655,7 @@ "dB": "dB", "{time} · {minutes} min ago": "{time} · vor {minutes} min", "Active weather": "Aktives Wetter", + "LATEST · newest per product": "NEUESTE · je Produkt", "Forecast · valid {valid} · issued {issued}": "Vorhersage · gültig {valid} · ausgegeben {issued}", "{detail} · Does not follow history": "{detail} · Folgt nicht dem Verlauf", "Forecast · valid {valid}": "Vorhersage · gültig {valid}", diff --git a/src/i18n/locales/es.json b/src/i18n/locales/es.json index 2ae722509..edbdb7cc9 100644 --- a/src/i18n/locales/es.json +++ b/src/i18n/locales/es.json @@ -1437,6 +1437,7 @@ "60°S–60°N · typically 2–3 h delayed": "60°S–60°N · normalmente con 2–3 h de retraso", "North America · infrared imagery": "Norteamérica · imágenes infrarrojas", "Reduced motion · history playback unavailable": "Movimiento reducido · reproducción del historial no disponible", + "Reduced motion · manual history available": "Movimiento reducido · puedes recorrer el historial a mano", "Rain radar · US": "Radar de lluvia · EE. UU.", "Lightning density · 15 min": "Densidad de rayos · 15 min", "Satellite clouds": "Nubes por satélite", @@ -1667,8 +1668,12 @@ "CH {index} / {total}": "CANAL {index} / {total}", "Station unavailable after directory refresh": "Emisora no disponible tras actualizar el directorio", "Clear reading": "Borrar lectura", + "Earlier observation": "Observación anterior", "Observed history": "Historial observado", + "Later observation": "Observación posterior", "Latest": "Último", + "Newest frame per product": "Fotograma más reciente por producto", + "Replay observed history": "Reproducir el historial observado", "S on another day replaces it · × unpins": "S en otro día lo reemplaza · × quita la fijación", "← → preview · S shows the focused day": "← → vista previa · S muestra el día enfocado", "Recent imagery": "Imágenes recientes", @@ -1832,6 +1837,7 @@ "Reset map bearing to north": "Restablecer la orientación del mapa al norte", "Rain radar": "Radar de lluvia", "Lightning density": "Densidad de rayos", + "LATEST · newest per product": "ÚLTIMO · más reciente por producto", "Forecast · valid {valid} · issued {issued}": "Pronóstico · válido {valid} · emitido {issued}", "{detail} · Does not follow history": "{detail} · No sigue el historial", "Forecast · valid {valid}": "Pronóstico · válido {valid}", diff --git a/src/i18n/locales/fr.json b/src/i18n/locales/fr.json index 3efc15ca5..b0320cd29 100644 --- a/src/i18n/locales/fr.json +++ b/src/i18n/locales/fr.json @@ -1349,6 +1349,7 @@ "60°S–60°N · typically 2–3 h delayed": "60°S–60°N · retard habituel de 2 à 3 h", "North America · infrared imagery": "Amérique du Nord · imagerie infrarouge", "Reduced motion · history playback unavailable": "Animations réduites · lecture de l'historique indisponible", + "Reduced motion · manual history available": "Animations réduites · historique parcourable manuellement", "Rain radar · US": "Radar de pluie · États-Unis", "Lightning density · 15 min": "Densité de foudre · 15 min", "Satellite clouds": "Nuages par satellite", @@ -2148,8 +2149,12 @@ "Radio is disabling…": "Désactivation de la Radio…", "Radio lifecycle is uncertain — use Enable or Disable to reconcile": "État de la Radio incertain — utilisez Activer ou Désactiver pour le rétablir", "Clear reading": "Effacer le relevé", + "Earlier observation": "Observation précédente", "Observed history": "Historique des observations", + "Later observation": "Observation suivante", "Latest": "Dernière", + "Newest frame per product": "Image la plus récente par produit", + "Replay observed history": "Rejouer l'historique des observations", "Imagery on Esri · Google 3D returns when cleared": "Sur Esri · EFFACER rétablit Google 3D", "Point the camera at the ground to use the view": "Orientez la caméra vers le sol pour utiliser la vue", "That point cannot anchor a box": "Ce point ne peut pas ancrer une zone", @@ -2440,6 +2445,7 @@ "DETECT": "DÉTECT.", "{time} · {minutes} min ago": "{time} · il y a {minutes} min", "Active weather": "Couches météo actives", + "LATEST · newest per product": "DERNIÈRE · la plus récente par produit", "Forecast · valid {valid} · issued {issued}": "Prévision · valide {valid} · émise {issued}", "{detail} · Does not follow history": "{detail} · Ne suit pas l'historique", "Forecast · valid {valid}": "Prévision · valide {valid}", diff --git a/src/i18n/locales/he.json b/src/i18n/locales/he.json index 59a2e16b0..2ee2cee1b 100644 --- a/src/i18n/locales/he.json +++ b/src/i18n/locales/he.json @@ -1207,6 +1207,7 @@ "Color: strikes/km²/min ×10³": "צבע: פגיעות ברק/קמ\"ר/דק׳ ×10³", "Color: {units}": "צבע: {units}", "Reduced motion · history playback unavailable": "תנועה מופחתת · הצגת ההיסטוריה אינה זמינה", + "Reduced motion · manual history available": "תנועה מופחתת · היסטוריה ידנית זמינה", "Rain radar · US": "רדאר גשם · ארה\"ב", "Lightning density · 15 min": "צפיפות ברקים · 15 דק׳", "Satellite clouds": "עננים מלוויין", @@ -1994,7 +1995,11 @@ "READY": "מוכן", "Clear reading": "ניקוי הקריאה", "Observed history": "היסטוריה נצפית", + "Earlier observation": "תצפית קודמת", + "Later observation": "תצפית מאוחרת", + "Newest frame per product": "השקופית החדשה לכל מוצר", "Latest": "האחרונה", + "Replay observed history": "הצגת ההיסטוריה הנצפית שוב", "Imagery on Esri · Google 3D returns when cleared": "צילומים ב-Esri · Google 3D חוזר כשמנקים", "Point the camera at the ground to use the view": "כוון את המצלמה אל הקרקע כדי להשתמש בתצוגה", "That point cannot anchor a box": "אין אפשרות לעגן תיבה באותה נקודה", @@ -2777,6 +2782,7 @@ "Detection overlay: off": "שכבת הזיהוי: כבויה", "Active weather": "מזג אוויר פעיל", "{time} · {minutes} min ago": "{time} · לפני {minutes} דק׳", + "LATEST · newest per product": "האחרון · החדש ביותר לכל מוצר", "Forecast · valid {valid} · issued {issued}": "תחזית · תקפה {valid} · פורסמה {issued}", "{detail} · Does not follow history": "{detail} · אינו נע עם ההיסטוריה", "Forecast · valid {valid}": "תחזית · תקפה {valid}", diff --git a/src/i18n/locales/it.json b/src/i18n/locales/it.json index 469cc6a9c..73de3f271 100644 --- a/src/i18n/locales/it.json +++ b/src/i18n/locales/it.json @@ -1349,6 +1349,7 @@ "60°S–60°N · typically 2–3 h delayed": "60°S–60°N · di solito 2–3 h di ritardo", "North America · infrared imagery": "Nord America · immagini all'infrarosso", "Reduced motion · history playback unavailable": "Movimento ridotto · riproduzione dello storico non disponibile", + "Reduced motion · manual history available": "Movimento ridotto · storico manuale disponibile", "Rain radar · US": "Radar pioggia · USA", "Lightning density · 15 min": "Densità di fulmini · 15 min", "Satellite clouds": "Nuvole da satellite", @@ -2148,8 +2149,12 @@ "Radio is disabling…": "Disattivazione della Radio…", "Radio lifecycle is uncertain — use Enable or Disable to reconcile": "Il ciclo di vita della Radio è incerto: usa Attiva o Disattiva per riconciliare", "Clear reading": "Cancella la lettura", + "Earlier observation": "Osservazione precedente", "Observed history": "Storico osservato", + "Later observation": "Osservazione successiva", "Latest": "Più recente", + "Newest frame per product": "Fotogramma più recente per prodotto", + "Replay observed history": "Rivedi lo storico osservato", "Imagery on Esri · Google 3D returns when cleared": "Immagini su Esri · Google 3D torna con CANCELLA", "Point the camera at the ground to use the view": "Punta la camera verso il suolo per usare la vista", "That point cannot anchor a box": "Quel punto non può ancorare un riquadro", @@ -2440,6 +2445,7 @@ "DETECT": "RILEV.", "{time} · {minutes} min ago": "{time} · {minutes} min fa", "Active weather": "Meteo attivo", + "LATEST · newest per product": "ULTIMO · il più recente per prodotto", "Forecast · valid {valid} · issued {issued}": "Previsione · valida {valid} · emessa {issued}", "{detail} · Does not follow history": "{detail} · Non segue lo storico", "Forecast · valid {valid}": "Previsione · valida {valid}", diff --git a/src/i18n/locales/ja.json b/src/i18n/locales/ja.json index 2ce7a7ffc..02dca3b7d 100644 --- a/src/i18n/locales/ja.json +++ b/src/i18n/locales/ja.json @@ -1311,6 +1311,7 @@ "60°S–60°N · typically 2–3 h delayed": "60°S–60°N · 通常2–3時間遅れ", "North America · infrared imagery": "北米 · 赤外画像", "Reduced motion · history playback unavailable": "動きを減らす設定 · 履歴再生は利用不可", + "Reduced motion · manual history available": "動きを減らす設定 · 履歴は手動で表示可能", "Rain radar · US": "降水レーダー · 米国", "Lightning density · 15 min": "雷密度 · 15分", "Satellite clouds": "衛星雲画像", @@ -2074,8 +2075,12 @@ "Radio is disabling…": "ラジオを無効化しています…", "Radio lifecycle is uncertain — use Enable or Disable to reconcile": "ラジオのライフサイクルが不明確です。有効化または無効化で再調整してください", "Clear reading": "読み取り値を消去", + "Earlier observation": "前の観測", "Observed history": "観測履歴", + "Later observation": "次の観測", "Latest": "最新", + "Newest frame per product": "プロダクトごとの最新フレーム", + "Replay observed history": "観測履歴を再生", "Imagery on Esri · Google 3D returns when cleared": "画像はEsri上に表示 · 消去するとGoogle 3Dに戻ります", "Point the camera at the ground to use the view": "このビューを使うにはカメラを地面に向けてください", "That point cannot anchor a box": "その地点は範囲の基点にできません", @@ -2340,6 +2345,7 @@ "DETECT": "検出", "{time} · {minutes} min ago": "{time} · {minutes}分前", "Active weather": "有効な気象レイヤー", + "LATEST · newest per product": "最新 · プロダクトごとの最新", "Forecast · valid {valid} · issued {issued}": "予報 · 対象時刻 {valid} · 発表 {issued}", "{detail} · Does not follow history": "{detail} · 履歴とは連動しません", "Forecast · valid {valid}": "予報 · 対象時刻 {valid}", diff --git a/src/i18n/locales/pt.json b/src/i18n/locales/pt.json index f56cfac2a..6859125e6 100644 --- a/src/i18n/locales/pt.json +++ b/src/i18n/locales/pt.json @@ -1347,6 +1347,7 @@ "60°S–60°N · typically 2–3 h delayed": "60°S–60°N · normalmente com 2–3 h de atraso", "North America · infrared imagery": "América do Norte · imagens infravermelhas", "Reduced motion · history playback unavailable": "Movimento reduzido · reprodução do histórico indisponível", + "Reduced motion · manual history available": "Movimento reduzido · é possível percorrer o histórico manualmente", "Rain radar · US": "Radar de chuva · EUA", "Lightning density · 15 min": "Densidade de raios · 15 min", "Satellite clouds": "Nuvens por satélite", @@ -2148,8 +2149,12 @@ "Radio is disabling…": "O rádio está sendo desativado…", "Radio lifecycle is uncertain — use Enable or Disable to reconcile": "O ciclo de vida do rádio é incerto — use Ativar ou Desativar para reconciliar", "Clear reading": "Limpar leitura", + "Earlier observation": "Observação anterior", "Observed history": "Histórico observado", + "Later observation": "Observação posterior", "Latest": "Mais recente", + "Newest frame per product": "Quadro mais recente por produto", + "Replay observed history": "Reproduzir o histórico observado", "Imagery on Esri · Google 3D returns when cleared": "Imagens sobre o Esri · LIMPAR restaura o Google 3D", "Point the camera at the ground to use the view": "Aponte a câmera para o chão para usar a vista", "That point cannot anchor a box": "Esse ponto não pode ancorar uma área", @@ -2440,6 +2445,7 @@ "DETECT": "DETECÇÃO", "{time} · {minutes} min ago": "{time} · há {minutes} min", "Active weather": "Camadas de clima ativas", + "LATEST · newest per product": "MAIS RECENTE · último por produto", "Forecast · valid {valid} · issued {issued}": "Previsão · válida para {valid} · emitida em {issued}", "{detail} · Does not follow history": "{detail} · Não acompanha o histórico", "Forecast · valid {valid}": "Previsão · válida para {valid}", diff --git a/src/i18n/locales/ru.json b/src/i18n/locales/ru.json index ab0273fd4..d0aa48e4e 100644 --- a/src/i18n/locales/ru.json +++ b/src/i18n/locales/ru.json @@ -1459,6 +1459,7 @@ "60°S–60°N · typically 2–3 h delayed": "60° ю. ш.–60° с. ш. · обычно задержка 2–3 ч", "North America · infrared imagery": "Северная Америка · ИК-снимки", "Reduced motion · history playback unavailable": "Уменьшение движения · воспроизведение истории недоступно", + "Reduced motion · manual history available": "Уменьшение движения · историю можно листать вручную", "Rain radar · US": "Радар осадков · США", "Lightning density · 15 min": "Плотность молний · 15 мин", "Satellite clouds": "Спутниковая облачность", @@ -1697,8 +1698,12 @@ "CH {index} / {total}": "КАН. {index} / {total}", "Station unavailable after directory refresh": "Станция недоступна после обновления каталога", "Clear reading": "Очистить показания", + "Earlier observation": "Более раннее наблюдение", "Observed history": "История наблюдений", + "Later observation": "Более позднее наблюдение", "Latest": "Последние", + "Newest frame per product": "Самый свежий кадр каждого продукта", + "Replay observed history": "Воспроизвести историю наблюдений", "S on another day replaces it · × unpins": "S в другой день заменяет его · × открепляет", "← → preview · S shows the focused day": "← → просмотр · S показывает выбранный день", "Recent imagery": "Свежие снимки", @@ -1863,6 +1868,7 @@ "Reset map bearing to north": "Сбросить азимут карты на север", "Rain radar": "Радар осадков", "Lightning density": "Плотность молний", + "LATEST · newest per product": "ПОСЛЕДНИЕ · самые свежие по каждому продукту", "Forecast · valid {valid} · issued {issued}": "Прогноз · действует на {valid} · выпущен {issued}", "{detail} · Does not follow history": "{detail} · не следует за историей", "Forecast · valid {valid}": "Прогноз · действует на {valid}", diff --git a/src/i18n/locales/sv.json b/src/i18n/locales/sv.json index 82702ec8e..41858177b 100644 --- a/src/i18n/locales/sv.json +++ b/src/i18n/locales/sv.json @@ -1857,6 +1857,7 @@ "60°S–60°N · typically 2–3 h delayed": "60° S–60° N · oftast 2–3 h fördröjning", "North America · infrared imagery": "Nordamerika · infraröda bilder", "Reduced motion · history playback unavailable": "Minskad rörelse · uppspelning av historik otillgänglig", + "Reduced motion · manual history available": "Minskad rörelse · manuell historik tillgänglig", "Rain radar · US": "Regnradar · USA", "Lightning density · 15 min": "Blixttäthet · 15 min", "Satellite clouds": "Satellitmoln", @@ -2322,8 +2323,12 @@ "PAUSE": "PAUSA", "RESUME": "FORTSÄTT", "Clear reading": "Rensa avläsningen", + "Earlier observation": "Tidigare observation", "Observed history": "Observerad historik", + "Later observation": "Senare observation", "Latest": "Senaste", + "Newest frame per product": "Senaste bildruta per produkt", + "Replay observed history": "Spela upp observerad historik", "Imagery on Esri · Google 3D returns when cleared": "Bilder på Esri · Google 3D återkommer när de rensas", "Point the camera at the ground to use the view": "Rikta kameran mot marken för att använda vyn", "That point cannot anchor a box": "Den punkten kan inte förankra ett område", @@ -2572,6 +2577,7 @@ "dB": "dB", "{time} · {minutes} min ago": "{time} · för {minutes} min sedan", "Active weather": "Aktuellt väder", + "LATEST · newest per product": "SENASTE · nyaste per produkt", "Forecast · valid {valid} · issued {issued}": "Prognos · gäller {valid} · utfärdad {issued}", "{detail} · Does not follow history": "{detail} · Följer inte historiken", "Forecast · valid {valid}": "Prognos · gäller {valid}", diff --git a/src/i18n/locales/uk.json b/src/i18n/locales/uk.json index db78d9cab..39fa54f11 100644 --- a/src/i18n/locales/uk.json +++ b/src/i18n/locales/uk.json @@ -1367,6 +1367,7 @@ "60°S–60°N · typically 2–3 h delayed": "60° пд. ш.–60° пн. ш. · зазвичай затримка 2–3 год", "North America · infrared imagery": "Північна Америка · ІЧ-знімки", "Reduced motion · history playback unavailable": "Зменшення руху · відтворення історії недоступне", + "Reduced motion · manual history available": "Зменшення руху · історію можна гортати вручну", "Rain radar · US": "Радар опадів · США", "Lightning density · 15 min": "Щільність блискавок · 15 хв", "Satellite clouds": "Супутникова хмарність", @@ -2184,8 +2185,12 @@ "Radio is disabling…": "Радіо вимикається…", "Radio lifecycle is uncertain — use Enable or Disable to reconcile": "Стан радіо невизначений — звірте через «Увімкнути» або «Вимкнути»", "Clear reading": "Очистити покази", + "Earlier observation": "Попереднє спостереження", "Observed history": "Історія спостережень", + "Later observation": "Наступне спостереження", "Latest": "Останні", + "Newest frame per product": "Найсвіжіший кадр кожного продукту", + "Replay observed history": "Відтворити історію спостережень", "Imagery on Esri · Google 3D returns when cleared": "Підкладка: Esri · скидання поверне Google 3D", "Point the camera at the ground to use the view": "Наведіть камеру на землю, щоб вибрати видиму область", "That point cannot anchor a box": "Від цієї точки не можна побудувати область", @@ -2489,6 +2494,7 @@ "DETECT": "ВИЯВЛЕННЯ", "{time} · {minutes} min ago": "{time} · {minutes} хв тому", "Active weather": "Активні погодні шари", + "LATEST · newest per product": "ОСТАННІ · найсвіжіші для кожного продукту", "Forecast · valid {valid} · issued {issued}": "Прогноз · чинний на {valid} · випущено {issued}", "{detail} · Does not follow history": "{detail} · не синхронізується з історією", "Forecast · valid {valid}": "Прогноз · чинний на {valid}", diff --git a/src/i18n/locales/zh-CN.json b/src/i18n/locales/zh-CN.json index 9a2c08d11..c541fdf49 100644 --- a/src/i18n/locales/zh-CN.json +++ b/src/i18n/locales/zh-CN.json @@ -1287,6 +1287,7 @@ "60°S–60°N · typically 2–3 h delayed": "60°S–60°N · 通常延迟 2–3 小时", "North America · infrared imagery": "北美洲 · 红外影像", "Reduced motion · history playback unavailable": "减弱动效 · 历史回放不可用", + "Reduced motion · manual history available": "减弱动效 · 可手动浏览历史", "Rain radar · US": "降雨雷达 · 美国", "Lightning density · 15 min": "闪电密度 · 15 分钟", "Satellite clouds": "卫星云图", @@ -2044,8 +2045,12 @@ "Radio is disabling…": "电台正在停用…", "Radio lifecycle is uncertain — use Enable or Disable to reconcile": "电台生命周期状态不确定——请使用“启用”或“停用”进行核对", "Clear reading": "清除读数", + "Earlier observation": "较早观测", "Observed history": "观测历史", + "Later observation": "较晚观测", "Latest": "最新", + "Newest frame per product": "每个产品的最新一帧", + "Replay observed history": "回放观测历史", "Imagery on Esri · Google 3D returns when cleared": "影像显示在 Esri 底图上 · 清除后恢复 Google 3D", "Point the camera at the ground to use the view": "将相机对准地面才能使用当前视野", "That point cannot anchor a box": "该点无法作为框选锚点", @@ -2304,6 +2309,7 @@ "DETECT": "探测", "{time} · {minutes} min ago": "{time} · {minutes} 分钟前", "Active weather": "已启用的天气图层", + "LATEST · newest per product": "最新 · 每个产品的最新一帧", "Forecast · valid {valid} · issued {issued}": "预报 · 有效时间 {valid} · 发布时间 {issued}", "{detail} · Does not follow history": "{detail} · 不随观测历史变化", "Forecast · valid {valid}": "预报 · 有效时间 {valid}", diff --git a/src/i18n/locales/zh-Hant.json b/src/i18n/locales/zh-Hant.json index e595234fe..62f5d5436 100644 --- a/src/i18n/locales/zh-Hant.json +++ b/src/i18n/locales/zh-Hant.json @@ -1282,6 +1282,7 @@ "60°S–60°N · typically 2–3 h delayed": "60°S–60°N · 通常延遲 2–3 小時", "North America · infrared imagery": "北美洲 · 紅外影像", "Reduced motion · history playback unavailable": "減弱動效 · 歷史回放不可用", + "Reduced motion · manual history available": "減弱動效 · 可手動瀏覽歷史", "Rain radar · US": "降雨雷達 · 美國", "Lightning density · 15 min": "閃電密度 · 15 分鐘", "Satellite clouds": "衛星雲圖", @@ -2034,8 +2035,12 @@ "Radio is disabling…": "電臺正在停用…", "Radio lifecycle is uncertain — use Enable or Disable to reconcile": "電臺生命週期狀態不確定——請使用“啟用”或“停用”進行核對", "Clear reading": "清除讀數", + "Earlier observation": "較早觀測", "Observed history": "觀測歷史", + "Later observation": "較晚觀測", "Latest": "最新", + "Newest frame per product": "每個產品的最新一幀", + "Replay observed history": "回放觀測歷史", "Imagery on Esri · Google 3D returns when cleared": "影像顯示在 Esri 底圖上 · 清除後恢復 Google 3D", "Point the camera at the ground to use the view": "將相機對準地面才能使用當前視野", "That point cannot anchor a box": "該點無法作為框選錨點", @@ -2294,6 +2299,7 @@ "DETECT": "探測", "{time} · {minutes} min ago": "{time} · {minutes} 分鐘前", "Active weather": "已啟用的天氣圖層", + "LATEST · newest per product": "最新 · 每個產品的最新一幀", "Forecast · valid {valid} · issued {issued}": "預報 · 有效時間 {valid} · 發布時間 {issued}", "{detail} · Does not follow history": "{detail} · 不隨觀測歷史變化", "Forecast · valid {valid}": "預報 · 有效時間 {valid}", diff --git a/src/layers/earthquakes/index.js b/src/layers/earthquakes/index.js index 3c8c6f5d7..3db74cf52 100644 --- a/src/layers/earthquakes/index.js +++ b/src/layers/earthquakes/index.js @@ -1,6 +1,5 @@ import { fromDegrees } from '../../geo/ellipsoid.js'; import { drawOf } from '../../render/rendererOf.js'; -import { worldClock } from '../../time/worldClock.js'; import { EARTHQUAKE_OVERLAY_SOURCE_ID, EARTHQUAKE_OVERLAY_COHORT_LIMIT, @@ -10,7 +9,6 @@ import { createEarthquakeOverlayEntry, selectEarthquakeOverlayCohort, mapAnalystRecord, - earthquakeCoverage, } from './model.js'; export * from './model.js'; export { createUsgsEarthquakeSource } from './source.js'; @@ -47,18 +45,6 @@ export function createEarthquakesLayer({ source, overlayHost } = {}) { let _lastUpdate = null; let _lastError = null; let _enabled = false; - let _uncover = null; - // The marks last told to the clock, so a refresh with the same strong - // quakes does not tell it again. - let _marksKey = null; - const coverage = () => (_enabled ? earthquakeCoverage(_events) : null); - const coverageChanged = () => { - const covered = coverage(); - const key = covered ? JSON.stringify(covered.marks) : null; - if (key === _marksKey) return; - _marksKey = key; - worldClock.coverageChanged(); - }; const layer = { id: 'earthquakes', @@ -74,10 +60,6 @@ export function createEarthquakesLayer({ source, overlayHost } = {}) { show: false, }); _viewer = viewer; - // While on, the strong quakes are marks on the world clock's timeline. - // Registered once; off, the layer has no time to show. - _marksKey = null; - _uncover = worldClock.register({ id: 'earthquakes', coverage }); _count = 0; _lastUpdate = null; _lastError = null; @@ -92,7 +74,6 @@ export function createEarthquakesLayer({ source, overlayHost } = {}) { // layer has no per-frame animator to keep the render loop alive for. if (_discs) _discs.show = true; overlayHost.setVisible(EARTHQUAKE_OVERLAY_SOURCE_ID, true); - coverageChanged(); }, disable(viewer) { @@ -102,7 +83,6 @@ export function createEarthquakesLayer({ source, overlayHost } = {}) { if (_discs) _discs.show = false; overlayHost.clearSource(EARTHQUAKE_OVERLAY_SOURCE_ID); overlayHost.setVisible(EARTHQUAKE_OVERLAY_SOURCE_ID, false); - coverageChanged(); }, async update(viewer) { @@ -166,7 +146,6 @@ export function createEarthquakesLayer({ source, overlayHost } = {}) { _discs.set(nextDiscs); _events = nextEvents; - coverageChanged(); if (_enabled) { overlayHost.setEntries( EARTHQUAKE_OVERLAY_SOURCE_ID, @@ -205,9 +184,6 @@ export function createEarthquakesLayer({ source, overlayHost } = {}) { _discs?.dispose(); _discs = null; _events = []; - _uncover?.(); - _uncover = null; - _marksKey = null; _count = 0; _lastUpdate = null; _lastError = null; diff --git a/src/layers/earthquakes/model.js b/src/layers/earthquakes/model.js index 458f39e71..86eca72d4 100644 --- a/src/layers/earthquakes/model.js +++ b/src/layers/earthquakes/model.js @@ -2,64 +2,6 @@ export const EARTHQUAKE_OVERLAY_SOURCE_ID = 'earthquakes'; export const EARTHQUAKE_OVERLAY_COHORT_LIMIT = 96; export const EARTHQUAKE_OVERLAY_COLLISION_CAPACITY = 48; -/** - * The smallest magnitude the timeline marks. Most quakes are small shakes; - * M6 and up come about once every two days worldwide, so each is an event - * worth stepping to. The map still draws every quake. - */ -export const EARTHQUAKE_MARK_MAGNITUDE = 6; - -/** The longest place a timeline mark's label carries, ellipsis and all. */ -const MARK_PLACE_LENGTH = 40; - -/** A magnitude as the map's labels show it: `M6.4`. */ -export const earthquakeMagnitudeTitle = (magnitude) => - `M${Number(magnitude).toFixed(1)}`; - -/** - * A strong quake's timeline label: its magnitude and, where the feed names - * one, its place, cut short (`M6.4 · 113 km SSE of Lata, Solomon Islands`). - * @param {{mag: number, place?: string | null}} event - * @returns {string} - */ -export function earthquakeMarkLabel({ mag, place }) { - const title = earthquakeMagnitudeTitle(mag); - const where = - typeof place === 'string' ? place.replace(/\s+/g, ' ').trim() : ''; - if (!where) return title; - const short = - where.length > MARK_PLACE_LENGTH - ? `${where.slice(0, MARK_PLACE_LENGTH - 1).trimEnd()}…` - : where; - return `${title} · ${short}`; -} - -/** - * The time a world clock's timeline can show for `events` (`{mag, time, - * place?, usgsId?}`, time in ms): the span of the quakes of - * EARTHQUAKE_MARK_MAGNITUDE and up, each one a mark labelled with its - * magnitude and place, or null with none, so the layer never stretches the - * timeline past what its feed covers. - * @returns {{start: number, end: number, marks: Array<{time: number, label: string, id?: string, kind: string}>} | null} - */ -export function earthquakeCoverage(events) { - const marks = events - .filter( - ({ mag, time }) => - mag >= EARTHQUAKE_MARK_MAGNITUDE && Number.isFinite(time), - ) - .map((event) => ({ - time: event.time, - label: earthquakeMarkLabel(event), - ...(event.usgsId ? { id: String(event.usgsId) } : {}), - kind: 'earthquake', - })) - .sort((a, b) => a.time - b.time); - return marks.length - ? { start: marks[0].time, end: marks.at(-1).time, marks } - : null; -} - // The depth bands' colours: CSS red, orange and yellow, as the renderer's // colour tuples (`[r, g, b, a]`, 0..1) and as CSS for the labels' accent. const SHALLOW = Object.freeze({ rgba: [1, 0, 0, 1], css: 'rgb(255,0,0)' }); @@ -108,7 +50,7 @@ export function createEarthquakeOverlayEntry({ id: String(id), position, variant: 'label', - title: earthquakeMagnitudeTitle(mag), + title: `M${mag.toFixed(1)}`, accent, priority: Math.round(mag * 1000), collisionGroup: 'ambient-label', diff --git a/src/layers/earthquakes/ownership.test.mjs b/src/layers/earthquakes/ownership.test.mjs index 5f6513552..45fd35dad 100644 --- a/src/layers/earthquakes/ownership.test.mjs +++ b/src/layers/earthquakes/ownership.test.mjs @@ -2,8 +2,6 @@ import assert from 'node:assert/strict'; import test from 'node:test'; import { createEarthquakesLayer } from './index.js'; import { createUsgsEarthquakeSource } from './source.js'; -import { EARTHQUAKE_MARK_MAGNITUDE, earthquakeMarkLabel } from './model.js'; -import { worldClock } from '../../time/worldClock.js'; import { bindFakeDraw } from '../../testSupport/fakeDrawPort.mjs'; function harness(source) { const events = []; @@ -170,71 +168,3 @@ test('a viewer with nothing to draw with is refused at init, and init can be ret layer.destroy(); unbind(); }); -test('the timeline marks only strong quakes, while the layer is on', async () => { - assert.equal(EARTHQUAKE_MARK_MAGNITUDE, 6); - const rows = [ - { ...row, stableId: 'small', mag: 4.5, time: 1_000 }, - { ...row, stableId: 'strong', usgsId: 'us-strong', mag: 6, time: 5_000 }, - { - ...row, - stableId: 'great', - usgsId: 'us-great', - mag: 7.2, - place: ' 113 km SSE of Lata, Solomon Islands region of the Pacific ', - time: 3_000, - }, - { ...row, stableId: 'untimed', mag: 6.5, time: null }, - ]; - let snapshot = rows; - const h = harness({ getSnapshot: async () => snapshot }); - assert.equal(worldClock.coverage(), null, 'nothing loaded, no time to show'); - let changes = 0; - const unsubscribe = worldClock.subscribe(() => changes++); - await h.layer.update(h.viewer); - // Every quake is drawn; only M6 and up are marks, spanning their own time. - assert.equal(h.draw.find('earthquakes:').items.size, 4); - // Each labelled with its magnitude and, cut short, its place. - assert.deepEqual(worldClock.coverage(), { - start: 3_000, - end: 5_000, - marks: [3_000, 5_000], - markDetails: [ - { - time: 3_000, - label: 'M7.2 · 113 km SSE of Lata, Solomon Islands reg…', - id: 'us-great', - kind: 'earthquake', - }, - { - time: 5_000, - label: 'M6.0 · Fixture', - id: 'us-strong', - kind: 'earthquake', - }, - ], - }); - const told = changes; - await h.layer.update(h.viewer); - assert.equal(changes, told, 'the same strong quakes are not told again'); - snapshot = rows.slice(0, 1); - await h.layer.update(h.viewer); - assert.equal(worldClock.coverage(), null, 'small shakes alone cover no time'); - snapshot = rows; - await h.layer.update(h.viewer); - h.layer.disable(h.viewer); - assert.equal(worldClock.coverage(), null, 'off, no time to show'); - h.layer.enable(h.viewer); - assert.deepEqual(worldClock.coverage().marks, [3_000, 5_000]); - h.layer.destroy(); - assert.equal(worldClock.coverage(), null); - unsubscribe(); -}); - -test('a strong quake with no place is labelled with its magnitude alone', () => { - assert.equal(earthquakeMarkLabel({ mag: 6.44, place: null }), 'M6.4'); - assert.equal(earthquakeMarkLabel({ mag: 6, place: ' ' }), 'M6.0'); - assert.equal( - earthquakeMarkLabel({ mag: 8.1, place: 'Off the coast' }), - 'M8.1 · Off the coast', - ); -}); diff --git a/src/layers/launches/lifecycle.js b/src/layers/launches/lifecycle.js index 526676381..a6e88a721 100644 --- a/src/layers/launches/lifecycle.js +++ b/src/layers/launches/lifecycle.js @@ -147,9 +147,6 @@ function restoreCameraView(viewer, view, landedView) { camera.setView(view); } -/** The longest name a timeline mark carries, as in the mission index. */ -const MARK_LABEL_LENGTH = 27; - export function createLifecycle({ state: layerState, services, @@ -159,30 +156,18 @@ export function createLifecycle({ const { holdContinuousRender, releaseContinuousRender } = services.render; let hover = null; // While on, the launches loaded span the time from the first to the last, - // each one a mark labelled with its mission's name (the launch's where it - // has none), cut short and in capitals as the mission index shows names. - // Registered once; off, the layer has no time to show, and each step tells - // the clock once it has settled. + // each one a mark. Registered once; off, the layer has no time to show, and + // each step tells the clock once it has settled. worldClock.register({ id: 'rocket-launches', coverage: () => { if (!layerState._enabled) return null; const marks = layerState._launches - .map((launch) => ({ - time: Date.parse(launch.launchTime), - label: parts.overlays - .shortMissionLabel( - launch.missionName || launch.name, - MARK_LABEL_LENGTH, - ) - .toUpperCase(), - ...(launch.id != null ? { id: String(launch.id) } : {}), - kind: 'launch', - })) - .filter(({ time }) => Number.isFinite(time)) - .sort((a, b) => a.time - b.time); + .map((launch) => Date.parse(launch.launchTime)) + .filter(Number.isFinite) + .sort((a, b) => a - b); if (!marks.length) return null; - return { start: marks[0].time, end: marks.at(-1).time, marks }; + return { start: marks[0], end: marks.at(-1), marks }; }, }); diff --git a/src/layers/weather/clock.js b/src/layers/weather/clock.js index 9e0f7c823..15d242742 100644 --- a/src/layers/weather/clock.js +++ b/src/layers/weather/clock.js @@ -59,15 +59,12 @@ export const PLAY_WAIT_MS = 8_000; // costs play nothing. let clocks = 0; -// How many weather clocks follow each world clock. -const followers = new WeakMap(); /** * Transient observed time. Products must honor the signal before installing a * frame. Its time is the world clock's: latest while the world is live, - * history at the world's time otherwise. It never moves the world clock - * itself; the world's own controls (its timeline) move time, and while the - * world plays it stops at each next frame until that frame loads. + * history at the world's time otherwise. Replay steps the observed frames and + * moves the world clock as it goes, as the world clock's driver. */ export function createWeatherClock({ now = Date.now, @@ -79,10 +76,17 @@ export function createWeatherClock({ const listeners = new Set(); let mode = 'latest'; let target = null; - // The world time last applied. + let playing = false; + // The world time last applied; while this clock moves the world, the + // transition its move started. let seen = 'latest'; + let moving = false; + let moved = null; const releases = new Map(); + // Attached at the end, once the API exists. + let driver = null; let generation = 0; + let timer = null; let pending = null; // This clock's name on the world, for its holds and its gate. const holdId = `weather:${++clocks}`; @@ -143,9 +147,10 @@ export function createWeatherClock({ const getState = () => ({ mode, target, - // Frames come on one after another as the world plays on through them, - // so the next is worth loading ahead. - advancing: worldPlaysOn(), + playing, + // Frames come on one after another: this clock replays them, or the world + // plays on through them, so the next is worth loading ahead. + advancing: playing || worldPlaysOn(), timeline: getTimeline(), products: [...registry.values()].map(({ product }) => ({ id: product.id, @@ -157,12 +162,60 @@ export function createWeatherClock({ const notify = () => { if (!destroyed) for (const listener of listeners) listener(getState()); }; + const cancelTimer = () => { + if (timer !== null) clearTimeout(timer); + timer = null; + }; + const canPlay = () => getTimeline().length >= 2; + const stopPlaying = () => { + if (!playing) return; + playing = false; + driver?.driven(false); + }; + // Move the world clock; the change comes back through followWorld. Returns + // the transition the move started, if it started one. + const move = (fn) => { + const outer = [moving, moved]; + moving = true; + moved = null; + try { + fn(); + return moved; + } finally { + [moving, moved] = outer; + } + }; const selections = () => [...registry.values()].map(({ product }) => selectedFor(product)).join(); let applied = null; + function schedule() { + cancelTimer(); + if (!playing || destroyed || pending) return; + if (!canPlay()) { + stopPlaying(); + notify(); + return; + } + const owner = generation; + timer = setTimeout(() => { + timer = null; + if (destroyed || !playing || owner !== generation) return; + const timeline = getTimeline(); + if (timeline.length < 2) { + api.pause(); + return; + } + const next = timeline.find( + (time) => Date.parse(time) > Date.parse(target), + ); + void api.setTarget(next ?? timeline[0]); + }, 2000); + } function transition() { if (destroyed) return Promise.resolve(false); + cancelTimer(); const owner = ++generation; + if (!canPlay()) stopPlaying(); // A scrub drops what loads and moves on; play goes on as this loads. applied = selections(); deferred = false; @@ -182,12 +235,15 @@ export function createWeatherClock({ if (destroyed || owner !== generation) return false; stopWaiting(); pending = null; + if (!canPlay()) stopPlaying(); notify(); + schedule(); // Play held at the next frame for this one goes on to it. if (deferred) void transition(); return true; }); pending = result; + if (moving) moved ??= result; notify(); return result; } @@ -198,13 +254,11 @@ export function createWeatherClock({ throw new Error(`Duplicate weather product: ${product.id}`); const entry = { product, controller: null }; registry.set(product.id, entry); - // The product moves with the world clock, and the span of its frames is - // time the world clock's timeline can show while it is on, suspended or - // not, so the way back to live stays on screen. The frames are not - // marks: they come every few minutes, and the timeline marks only - // events. Both calls notify the world's listeners, which may destroy - // this clock: the release is in place first, and anything acquired - // after a destroy is let go at once. + // The product moves with the world clock, and its frames are time the + // world clock's timeline can show while it is on, suspended or not, so + // the way back to live stays on screen. Both calls notify the world's + // listeners, which may destroy this clock: the release is in place + // first, and anything acquired after a destroy is let go at once. let unhold = null; let uncover = null; const release = () => { @@ -218,12 +272,9 @@ export function createWeatherClock({ uncover = world.register({ id: product.id, coverage: () => { - const times = timesFor(product); - return times.length - ? { - start: Date.parse(times[0]), - end: Date.parse(times.at(-1)), - } + const marks = timesFor(product).map((time) => Date.parse(time)); + return marks.length + ? { start: marks[0], end: marks.at(-1), marks } : null; }, }); @@ -249,17 +300,81 @@ export function createWeatherClock({ * wind, gives that layer the timeline time rather than the live edge. */ follows: (id) => world.follows(id), - /** - * The world clock this clock follows. Time moves there, through the same - * seek, play and live the world's timeline uses, never through this clock. - */ - world, + setTarget(time) { + if (destroyed) return Promise.resolve(false); + if (!Number.isFinite(Date.parse(time))) + throw new TypeError('Weather target must be a UTC time'); + const normalized = new Date(time).toISOString(); + if (mode === 'history' && target === normalized) + return pending ?? Promise.resolve(true); + return ( + move(() => world.seek(Date.parse(normalized))) ?? + pending ?? + Promise.resolve(true) + ); + }, + step(direction) { + if (destroyed || ![-1, 1].includes(direction)) + return Promise.resolve(false); + api.pause(); + const timeline = getTimeline(); + if (!timeline.length) return Promise.resolve(false); + const at = Date.parse(target ?? timeline.at(-1)); + const next = + direction < 0 + ? (timeline.findLast((time) => Date.parse(time) < at) ?? timeline[0]) + : (timeline.find((time) => Date.parse(time) > at) ?? timeline.at(-1)); + return api.setTarget(next); + }, + latest() { + if (destroyed) return Promise.resolve(false); + stopPlaying(); + if (mode === 'latest') return transition(); + return move(() => world.goLive()) ?? pending ?? Promise.resolve(true); + }, + play() { + if (destroyed || playing || !canPlay()) + return pending ?? Promise.resolve(false); + playing = true; + if (mode === 'latest') { + const timeline = getTimeline(); + const start = + timeline.findLast((time) => Date.parse(time) <= now()) ?? timeline[0]; + // Playing and at the first frame in one move of the world. + return ( + move(() => driver.driven(true, Date.parse(start))) ?? + pending ?? + Promise.resolve(true) + ); + } + driver.driven(true); + notify(); + schedule(); + return pending ?? Promise.resolve(true); + }, + pause() { + cancelTimer(); + if (!playing) { + // The world may be playing on its own; a pause or step here holds it. + if (world.isPlaying()) world.pause(); + return; + } + stopPlaying(); + notify(); + }, + togglePlay() { + return playing ? api.pause() : api.play(); + }, refresh() { if (destroyed) return Promise.resolve(false); // New frames, or products added or dropped, and with them the next. world.coverageChanged(); gated = undefined; gateNext(world.getState()); + if (!canPlay()) { + stopPlaying(); + cancelTimer(); + } if (mode === 'history') return transition(); notify(); return Promise.resolve(true); @@ -271,15 +386,15 @@ export function createWeatherClock({ }, destroy() { if (destroyed) return; + stopPlaying(); destroyed = true; ++generation; stopWaiting(); world.gate(holdId, null); + cancelTimer(); unfollowWorld(); // The last weather clock leaves the world live, as a new one expects. - const left = followers.get(world) - 1; - followers.set(world, left); - if (left === 0) world.goLive(); + if (driver.detach() === 0) world.goLive(); for (const release of releases.values()) release(); releases.clear(); for (const entry of registry.values()) entry.controller?.abort(); @@ -288,8 +403,9 @@ export function createWeatherClock({ pending = null; }, }; - // Follow the world clock. A move (a seek, play going on) applies only when - // it changes the mode or a product's frame. + // Follow the world clock. A move of this clock's own always applies; one + // from elsewhere (a host's seek, continuous play) applies only when it + // changes the mode or a product's frame. function followWorld(state) { if (destroyed) return; gateNext(state); @@ -310,7 +426,7 @@ export function createWeatherClock({ const modeChanged = nextMode !== mode; mode = nextMode; target = nextTarget; - if (!modeChanged && selections() === applied) { + if (!moving && !modeChanged && selections() === applied) { // Back at the frame that loads, play need not hold for it. if (deferred) { deferred = false; @@ -323,7 +439,7 @@ export function createWeatherClock({ } // Playing on into the next frame while the one before it loads, the // world holds here until that one shows. - if (!modeChanged && pending && playsOn) { + if (!moving && !modeChanged && pending && playsOn) { deferred = true; startWaiting(); notify(); @@ -346,7 +462,10 @@ export function createWeatherClock({ world.gate(holdId, next); } const unfollowWorld = world.subscribe(followWorld); - followers.set(world, (followers.get(world) ?? 0) + 1); + driver = world.attachDriver({ + play: () => (canPlay() ? void api.play() : false), + pause: () => api.pause(), + }); followWorld(world.getState()); return api; } diff --git a/src/layers/weather/clock.test.mjs b/src/layers/weather/clock.test.mjs index ba2544073..90cd1bd6b 100644 --- a/src/layers/weather/clock.test.mjs +++ b/src/layers/weather/clock.test.mjs @@ -158,16 +158,13 @@ test('a product’s gap is at least one and a half of its feed’s frame spacing assert.equal(clock.selectFor('clouds', time(211)), null); }); -const at = (minutes) => Date.parse(time(minutes)); - -test('history applies per-product selections, including null; live restores unequal newest times', async (t) => { - const { clock, world } = harness(t); +test('history applies per-product selections, including null; latest restores unequal newest times', async (t) => { + const { clock } = harness(t); const radar = product('radar', [0, 10, 20]); const satellite = product('satellite', [5, 15]); const lightning = product('lightning', [15]); for (const p of [radar, satellite, lightning]) clock.register(p); - world.seek(at(10)); - await flush(); + await clock.setTarget(time(10)); assert.deepEqual( [radar.shown, satellite.shown, lightning.shown], [time(10), time(5), null], @@ -176,19 +173,18 @@ test('history applies per-product selections, including null; live restores uneq clock.getState().products.map(({ selected }) => selected), [time(10), time(5), null], ); - world.goLive(); - await flush(); + await clock.latest(); assert.deepEqual( [radar.shown, satellite.shown, lightning.shown], [time(20), time(15), time(15)], ); assert.equal(clock.getState().mode, 'latest'); assert.equal(clock.getState().target, null); - assert.equal(clock.getState().advancing, false); + assert.equal(clock.getState().playing, false); }); -test('superseded completions cannot commit or notify', async (t) => { - const { clock, world, timers } = harness(t); +test('superseded completions cannot commit, notify or schedule a new playback advance', async (t) => { + const { clock, timers } = harness(t); const p = product('radar', [0, 10, 20]); const loads = []; p.apply = (selected, { signal }) => @@ -205,44 +201,113 @@ test('superseded completions cannot commit or notify', async (t) => { clock.register(p); let notifications = 0; clock.subscribe(() => notifications++); - world.seek(at(0)); + const old = clock.setTarget(time(0)); await flush(); - world.seek(at(10)); + const current = clock.setTarget(time(10)); await flush(); assert.equal(loads[0].signal.aborted, true); loads[1].finish(); - await flush(); + assert.equal(await current, true); const count = notifications; loads[0].finish(); - await flush(); + assert.equal(await old, false); assert.equal(notifications, count); assert.equal(p.shown, time(10)); assert.equal(clock.getState().target, time(10)); assert.equal(timers.size, 0); }); -test('the clock has no time controls of its own; the world clock moves time', (t) => { - const { clock, world } = harness(t); - for (const name of [ - 'setTarget', - 'step', - 'latest', - 'play', - 'pause', - 'togglePlay', - ]) - assert.equal(clock[name], undefined, name); - assert.equal(clock.world, world); +test('steps use strict union neighbours from arbitrary targets and clamp at endpoints', async (t) => { + const { clock } = harness(t); + clock.register(product('radar', [0, 10, 20])); + clock.register(product('satellite', [5, 15])); + await clock.step(-1); + assert.equal(clock.getState().target, time(15)); + await clock.setTarget(time(12)); + await clock.step(-1); + assert.equal(clock.getState().target, time(10)); + await clock.setTarget(time(12)); + await clock.step(1); + assert.equal(clock.getState().target, time(15)); + await clock.setTarget(time(0)); + await clock.step(-1); + assert.equal(clock.getState().target, time(0)); + await clock.setTarget(time(20)); + await clock.step(1); + assert.equal(clock.getState().target, time(20)); +}); + +test('playback waits for every product to settle, including rejection, then waits 2000 ms and wraps', async (t) => { + const { clock, tick, timers } = harness(t); + const a = product('radar', [0, 10]); + const b = product('satellite', [5]); + const loads = []; + b.apply = () => + new Promise((resolve, reject) => loads.push({ resolve, reject })); + clock.register(a); + clock.register(b); + const start = clock.play(); + await flush(); + assert.equal(clock.getState().target, time(10)); + tick(10_000); + assert.equal(timers.size, 0); + assert.equal(a.calls.length, 1); + loads[0].reject(new Error('unavailable')); + await start; + assert.equal(timers.size, 1); + tick(1999); + assert.equal(clock.getState().target, time(10)); + tick(1); + await flush(); + assert.equal(clock.getState().target, time(0)); + assert.equal(timers.size, 0); + tick(10_000); + assert.equal(clock.getState().target, time(0)); + loads[1].resolve(true); + await flush(); + tick(2000); + await flush(); + assert.equal(clock.getState().target, time(5)); + clock.pause(); + loads[2].resolve(false); + await flush(); + assert.equal(timers.size, 0, 'pausing during a load prevents rescheduling'); +}); + +test('pause cancels a pending advance; playback stops with one time or all products suspended', async (t) => { + const { clock, tick, timers } = harness(t); + const p = product('radar', [0, 10]); + clock.register(p); + await clock.play(); + await clock.play(); + assert.equal(timers.size, 1); + clock.pause(); + tick(2000); + assert.equal(clock.getState().target, time(10)); + assert.equal(timers.size, 0); + await clock.togglePlay(); + p.times = [time(0)]; + await clock.refresh(); + assert.equal(clock.getState().playing, false); + await clock.play(); + assert.equal(clock.getState().playing, false); + p.times = [time(0), time(10)]; + await clock.refresh(); + await clock.play(); + p.suspended = true; + await clock.refresh(); + assert.equal(clock.getState().playing, false); + assert.deepEqual(clock.getTimeline(), []); + assert.equal(timers.size, 0); }); test('refresh does not apply in latest; history retains its target as expired frames disappear', async (t) => { - const { clock, world } = harness(t); + const { clock } = harness(t); const p = product('radar', [0, 10]); clock.register(p); await clock.refresh(); assert.equal(p.calls.length, 0); - world.seek(at(10)); - await flush(); + await clock.setTarget(time(10)); p.times = [time(0), time(20)]; await clock.refresh(); assert.equal(p.shown, time(0)); @@ -253,16 +318,15 @@ test('refresh does not apply in latest; history retains its target as expired fr }); test('registration joins history; unregister and destroy abort work and release subscriptions/timers', async (t) => { - const { clock, world, timers } = harness(t); + const { clock, timers, tick } = harness(t); const p = product('radar', [0, 10]); const unregister = clock.register(p); - world.seek(at(0)); - await flush(); + await clock.setTarget(time(0)); const b = product('satellite', [0, 5]); clock.register(b); await flush(); assert.equal(b.shown, time(0)); - world.seek(at(5)); + await clock.play(); unregister(); unregister(); await flush(); @@ -273,27 +337,31 @@ test('registration joins history; unregister and destroy abort work and release ); let notifications = 0; const off = clock.subscribe(() => notifications++); + clock.pause(); off(); - world.seek(at(0)); - await flush(); - assert.equal(notifications, 0); - world.seek(at(5)); + const before = notifications; + await clock.play(); + assert.equal(notifications, before); clock.destroy(); clock.destroy(); - await flush(); + tick(2000); assert.equal(timers.size, 0); assert.equal(b.calls.at(-1).signal.aborted, true); + assert.equal(clock.getState().playing, false); assert.deepEqual(clock.getTimeline(), []); + assert.equal(await clock.setTarget(time(5)), false); }); -test('the weather time is the world time', async (t) => { +test('the weather time is the world time, both ways', async (t) => { const { clock, world } = harness(t); const radar = product('radar', [0, 10, 20]); clock.register(radar); assert.equal(world.follows('radar'), true); - world.seek(at(3)); + await clock.setTarget(time(10)); + assert.equal(world.isLive(), false); + assert.equal(world.now(), Date.parse(time(10))); + world.seek(Date.parse(time(3))); await flush(); - assert.equal(clock.getState().mode, 'history'); assert.equal(clock.getState().target, time(3)); assert.equal(radar.shown, time(0)); world.goLive(); @@ -302,22 +370,30 @@ test('the weather time is the world time', async (t) => { assert.equal(radar.shown, time(20)); }); -test('world play runs the world on its own at its rate; weather does not drive it', async (t) => { +test('world play and pause drive the weather replay', async (t) => { const { clock, world, tick } = harness(t); const radar = product('radar', [0, 10, 20]); clock.register(radar); - world.seek(at(0)); + world.seek(Date.parse(time(0))); await flush(); - world.play({ rate: 60 }); - assert.equal(world.getState().stepping, false); - assert.equal(clock.getState().advancing, true); - tick(5_000); - assert.equal(world.now(), at(5), 'five minutes on at a minute a second'); - tick(10_000); + world.play(); + assert.equal(clock.getState().playing, true); + assert.equal(world.isPlaying(), true); + tick(2000); await flush(); - assert.equal(world.now(), at(10), 'held at the next frame'); + assert.equal(radar.shown, time(10)); + assert.equal(world.now(), Date.parse(time(10))); world.pause(); - assert.equal(clock.getState().advancing, false); + assert.equal(clock.getState().playing, false); + clock.play(); + assert.equal(world.isPlaying(), true); + clock.pause(); + assert.equal(world.isPlaying(), false); + clock.play(); + world.goLive(); + await flush(); + assert.equal(clock.getState().playing, false); + assert.equal(clock.getState().mode, 'latest'); }); test('a moving world re-applies frames only when a product changes frame', async (t) => { @@ -340,6 +416,15 @@ test('a moving world re-applies frames only when a product changes frame', async assert.equal(radar.shown, time(10)); }); +test('a world without frames to step plays on its own', async (t) => { + const { clock, world, tick } = harness(t); + world.seek(Date.parse(time(0))); + world.play(); + assert.equal(clock.getState().playing, false); + tick(1000); + assert.equal(world.now(), Date.parse(time(0)) + 1000); +}); + function worldAt(at) { return createWorldClock({ now: () => at, @@ -349,25 +434,74 @@ function worldAt(at) { }); } -test('weather clocks sharing a world: the last one destroyed leaves it live', () => { +test('weather clocks sharing a world hand play over, and the last leaves it live', async () => { const world = worldAt(Date.parse(time(20))); const a = createWeatherClock({ world, now: () => Date.parse(time(20)) }); const b = createWeatherClock({ world, now: () => Date.parse(time(20)) }); - a.register(product('radar', [0, 10, 20])); - b.register(product('radar', [0, 10, 20])); - world.seek(Date.parse(time(0))); - world.play(); + const radarA = product('radar', [0, 10, 20]); + const radarB = product('radar', [0, 10, 20]); + a.register(radarA); + b.register(radarB); + await a.play(); + assert.equal(world.isPlaying(), true); + world.pause(); + assert.equal(a.getState().playing, false); + assert.equal(world.isPlaying(), false); + await a.play(); + world.goLive(); + assert.equal(a.getState().playing, false); b.destroy(); assert.equal(world.follows('radar'), true); - assert.equal(world.isLive(), false); - assert.equal(world.isPlaying(), true); + world.seek(Date.parse(time(0))); + world.play(); + assert.equal(a.getState().playing, true); a.destroy(); assert.equal(world.follows('radar'), false); assert.equal(world.isLive(), true); assert.equal(world.isPlaying(), false); }); -test('each product’s frames span world clock coverage, with no marks, and support the timeline while shown', (t) => { +test('pausing from inside the first playing notice stops the world too', async (t) => { + const { clock, world } = harness(t); + clock.register(product('radar', [0, 10, 20])); + const off = clock.subscribe((state) => { + if (state.playing) { + off(); + clock.pause(); + } + }); + await clock.play(); + assert.equal(clock.getState().playing, false); + assert.equal(world.isPlaying(), false); +}); + +test('a step holds a world that was playing on its own', async (t) => { + const { clock, world } = harness(t); + world.seek(Date.parse(time(0))); + world.play(); + clock.register(product('radar', [0, 10, 20])); + await clock.step(1); + assert.equal(world.isPlaying(), false); + assert.equal(world.now(), Date.parse(time(10))); +}); + +test('a target superseded from a listener resolves false', async (t) => { + const { clock } = harness(t); + const radar = product('radar', [0, 10, 20]); + clock.register(radar); + await flush(); + let redirected = false; + clock.subscribe((state) => { + if (state.target === time(0) && !redirected) { + redirected = true; + void clock.setTarget(time(10)); + } + }); + assert.equal(await clock.setTarget(time(0)), false); + assert.equal(radar.shown, time(10)); +}); + +test('each product’s frames are world clock coverage, and support the timeline while shown', (t) => { const { clock, world } = harness(t); assert.equal(world.coverage(), null); assert.equal(world.getState().supported, false); @@ -377,17 +511,11 @@ test('each product’s frames span world clock coverage, with no marks, and supp assert.deepEqual(world.coverage(), { start: Date.parse(time(0)), end: Date.parse(time(10)), - marks: [], - markDetails: [], + marks: [0, 5, 10].map((m) => Date.parse(time(m))), }); assert.equal(world.getState().supported, true); unregister(); - assert.deepEqual(world.coverage(), { - start: Date.parse(time(5)), - end: Date.parse(time(5)), - marks: [], - markDetails: [], - }); + assert.deepEqual(world.coverage().marks, [Date.parse(time(5))]); clock.destroy(); assert.equal(world.coverage(), null); assert.equal(world.getState().supported, false); @@ -400,12 +528,10 @@ test('a suspended product keeps its coverage, so the way back to live stays', (t radar.suspended = true; void clock.refresh(); assert.equal(world.getState().supported, true); - assert.deepEqual(world.coverage(), { - start: Date.parse(time(0)), - end: Date.parse(time(10)), - marks: [], - markDetails: [], - }); + assert.deepEqual( + world.coverage().marks, + [0, 10].map((m) => Date.parse(time(m))), + ); }); test('new frames reach the world clock through refresh', (t) => { diff --git a/src/layers/weather/index.js b/src/layers/weather/index.js index 83f52d86e..9f393ddfe 100644 --- a/src/layers/weather/index.js +++ b/src/layers/weather/index.js @@ -9,9 +9,7 @@ import { GLOBAL_INFRARED_MAX_GAP_MS, LIGHTNING_MAX_GAP_MS, atLeastFrameSpacing, - createWeatherClock, } from './clock.js'; -import { worldClock } from '../../time/worldClock.js'; import { formatUtcDayMonth, t, msg } from '../../i18n/index.js'; import { formatScaleLabel } from '../../ui/unitLabels.js'; import { toLonLatH } from '../../geo/ellipsoid.js'; @@ -62,49 +60,12 @@ const utc = (value) => ? `${formatUtcDayMonth(value)} ${value.slice(11, 16)} UTC` : t('Unavailable'); -/** - * Move `world`, the world clock, as its timeline does: `play` toggles play - * (from the start of the covered time when live) and `latest` goes live. - * `step` (-1 or 1) goes to the previous or next of `frames`, the weather - * frames; the timeline does not mark them, so this is the row's own way to - * step through them. - */ -function moveWorldTime(world, frames, { play, latest, step }) { - if (!world) return; - if (play === true) { - const state = world.getState(); - if (state.playing) world.pause(); - else { - const covered = world.coverage(); - if (state.live && covered) world.seek(covered.start); - world.play({ continuous: true }); - } - } - if (latest === true) world.goLive(); - if (step === -1 || step === 1) { - const at = world.getState().timeMs; - const times = frames - .map((time) => Date.parse(time)) - .filter(Number.isFinite) - .sort((a, b) => a - b); - const to = - step < 0 - ? times.findLast((frame) => frame < at) - : times.find((frame) => frame > at); - if (to === undefined) return; - world.pause(); - world.seek(to); - } -} - /** A per-application observation layer, using the existing layer lifecycle and * row controls. Its time is the world clock's, so a link made away from live - * opens its imagery at that time; one made live opens the latest. Its frames - * follow `clock`, a weather clock several layers share; without one the layer - * keeps its own on the page's world clock, for its lifetime. */ + * opens its imagery at that time; one made live opens the latest. */ export function createWeatherLayer({ feed, - clock: sharedClock, + clock, id = 'weather-radar', createRendering = createWeatherRendering, documentRef = globalThis.document, @@ -113,10 +74,6 @@ export function createWeatherLayer({ } = {}) { if (typeof feed?.getSnapshot !== 'function') throw new TypeError('Weather requires a snapshot source'); - const ownClock = sharedClock - ? null - : createWeatherClock({ world: worldClock }); - const clock = sharedClock ?? ownClock; // A feed may also supply decoded frames; see weatherFrameSource. const radar = id === 'weather-radar'; const lightning = id === 'weather-lightning'; @@ -130,8 +87,11 @@ export function createWeatherLayer({ request = null, listener = null; let enabled = false, - loading = false; + loading = false, + playing = false, + followLatest = true; let generation = 0, + timer = null, error = null, removeCamera = null; let motion = null; @@ -171,11 +131,12 @@ export function createWeatherLayer({ return spaced; }; const maxGap = () => spacedTimes().gap; - const isLatest = () => clock.getState().mode === 'latest'; + const isLatest = () => + clock ? clock.getState().mode === 'latest' : followLatest; const getHost = () => imageryHost?.() ?? globeImageryHost(viewer); const notify = () => listener?.(); const shownTime = () => (noFrame ? null : rendering?.getDiagnostics().time); - const unsubscribeClock = clock.subscribe(() => { + const unsubscribeClock = clock?.subscribe(() => { if (!clock.getState().advancing || suspended()) rendering?.cancelPrefetch?.(); notify(); @@ -183,18 +144,26 @@ export function createWeatherLayer({ // Ages and delays are measured from the time the layer shows: the world // clock's time at a past time, the wall clock while live. const worldNow = () => { - const shared = clock.getState(); - return shared.mode === 'history' && shared.target + const shared = clock?.getState(); + return shared?.mode === 'history' && shared.target ? Date.parse(shared.target) : Date.now(); }; const observationDelayed = () => manifest?.latest && worldNow() - Date.parse(manifest.latest) > spacedTimes().delay; + const stop = () => { + if (clock) return; + playing = false; + rendering?.cancelPrefetch?.(); + clearTimeout(timer); + timer = null; + }; const suspended = () => hostHidden || documentRef?.hidden || motion?.matches; const onVisibility = () => { if (suspended()) rendering?.cancelPrefetch?.(); - void clock.refresh(); + if (clock) void clock.refresh(); + else if (suspended()) stop(); notify(); }; @@ -209,15 +178,46 @@ export function createWeatherLayer({ if (!changed || !rendering) return; ++generation; rendering.rehome?.(); + clearTimeout(timer); + timer = null; loading = Boolean(request && !request.signal.aborted); - if (enabled && resume) { - void clock.refresh(); - if (!hostHidden && manifest && isLatest()) void show(manifest.latest); + if (clock && enabled) { + if (resume) { + void clock.refresh(); + if (!hostHidden && manifest && isLatest()) void show(manifest.latest); + } + notify(); + return; + } + if (resume && enabled && !hostHidden && manifest) { + const time = + followLatest || !manifest.times.includes(shownTime()) + ? manifest.latest + : shownTime(); + if ( + time !== shownTime() || + (satellite && rendering.getDiagnostics().infrared !== infrared) + ) + void show(time); + else schedule(); } notify(); } const onMapStackChanged = () => checkHost(); + function schedule() { + if (clock) return; + clearTimeout(timer); + timer = null; + if (!enabled || !playing || suspended()) return; + timer = setTimeout(() => { + timer = null; + const times = manifest?.times || []; + const next = (times.indexOf(shownTime()) + 1) % times.length; + if (times[next]) void show(times[next]); + else stop(); + }, 2000); + } async function applyClockTime(time, { signal }) { if (!enabled || signal.aborted) return false; if (time !== null) return show(time, signal); @@ -231,7 +231,7 @@ export function createWeatherLayer({ return true; } function registerClock() { - if (unregisterClock || !rendering || !enabled) return; + if (!clock || unregisterClock || !rendering || !enabled) return; unregisterClock = clock.register({ id, get maxGapMs() { @@ -244,11 +244,15 @@ export function createWeatherLayer({ }); } async function warmNext(time) { - if (!enabled || suspended() || !clock.getState().advancing) return; - // The world plays on past the newest frame, never round to the first. + if ( + !enabled || + suspended() || + !(clock ? clock.getState().advancing : playing) + ) + return; const times = manifest?.times ?? []; - const next = times[times.indexOf(time) + 1]; - if (!next) return; + const next = times[(times.indexOf(time) + 1) % times.length]; + if (!next || next === time) return; try { await rendering.prefetch?.(manifest, next, { infrared }); } catch { @@ -283,10 +287,13 @@ export function createWeatherLayer({ error = ok ? null : msg('Frame unavailable; previous observation retained'); + if (!ok) stop(); return ok; } catch { - if (owner === generation && !controller.signal.aborted) + if (owner === generation && !controller.signal.aborted) { error = msg('Weather imagery unavailable'); + stop(); + } return false; } finally { signal?.removeEventListener('abort', abort); @@ -294,7 +301,8 @@ export function createWeatherLayer({ if (owner === generation) { loading = Boolean(request && !request.signal.aborted); notify(); - if (isLatest()) void clock.refresh(); + if (clock && isLatest()) void clock.refresh(); + schedule(); } } } @@ -363,20 +371,26 @@ export function createWeatherLayer({ noFrame = false; request?.abort(); request = null; - rendering?.cancelPrefetch?.(); + stop(); rendering?.clear(); manifest = null; loading = false; error = null; + followLatest = true; }, async update(_viewer, { signal } = {}) { if (!enabled) return false; checkHost(false); + clearTimeout(timer); + timer = null; request?.abort(); const controller = new AbortController(); if (signal?.aborted) controller.abort(signal.reason); request = controller; - const abort = () => controller.abort(signal.reason); + const abort = () => { + controller.abort(signal.reason); + stop(); + }; signal?.addEventListener('abort', abort, { once: true }); loading = true; notify(); @@ -392,15 +406,36 @@ export function createWeatherLayer({ error = msg( 'Weather source unavailable; previous observation retained', ); + stop(); return true; } manifest = snapshot; error = null; // The shown frame may stay; its credit follows the refreshed manifest. rendering?.updateSnapshot?.(snapshot); - await clock.refresh(); - if (isLatest() && request === controller && !controller.signal.aborted) - await show(snapshot.latest, controller.signal); + if (clock) { + await clock.refresh(); + if ( + isLatest() && + request === controller && + !controller.signal.aborted + ) + await show(snapshot.latest, controller.signal); + return ( + enabled && + !signal?.aborted && + (!controller.signal.aborted || request !== controller) + ); + } + const time = + followLatest || !snapshot.times.includes(shownTime()) + ? snapshot.latest + : shownTime(); + if ( + shownTime() !== time || + (satellite && rendering.getDiagnostics().infrared !== infrared) + ) + await show(time, controller.signal); return ( enabled && !signal?.aborted && @@ -410,6 +445,7 @@ export function createWeatherLayer({ if (controller.signal.aborted || request !== controller) return enabled && !signal?.aborted && request !== controller; error = cause?.message || msg('Weather unavailable'); + stop(); return true; } finally { signal?.removeEventListener('abort', abort); @@ -417,6 +453,7 @@ export function createWeatherLayer({ request = null; loading = Boolean(rendering?.getDiagnostics().loading); notify(); + schedule(); } } }, @@ -451,16 +488,19 @@ export function createWeatherLayer({ noFrame = false; request?.abort(); request = null; - rendering?.cancelPrefetch?.(); + stop(); manifest = null; error = null; loading = false; + followLatest = true; rendering?.clear(); - void clock.refresh(); + if (clock) void clock.refresh(); if (enabled) void layer.update(viewer); } if (infraredChanged && enabled && manifest) { - if (!isLatest()) void clock.refresh(); + clearTimeout(timer); + timer = null; + if (clock && !isLatest()) void clock.refresh(); else void show(shownTime() || manifest.latest); } if ( @@ -488,16 +528,38 @@ export function createWeatherLayer({ ); }); } - // Time is the world's: these move the world clock as its timeline - // does, and every layer that follows it moves along. A step goes - // through every shown observation's frames, and this row's own even - // while it is suspended. - if (enabled) - moveWorldTime( - clock.world, - [...clock.getTimeline(), ...(manifest?.times ?? [])], - params, + if (clock && enabled) { + if (params.play === true) void clock.togglePlay(); + if (params.latest === true) void clock.latest(); + if ([-1, 1].includes(params.step)) void clock.step(params.step); + } + if ( + !clock && + params.play === true && + enabled && + manifest?.times?.length > 1 && + !suspended() + ) { + playing = !playing; + followLatest = false; + if (playing) schedule(); + else stop(); + } + if (!clock && params.latest === true && manifest) { + stop(); + followLatest = true; + void show(manifest.latest); + } + if (!clock && [-1, 1].includes(params.step) && manifest && !loading) { + stop(); + followLatest = false; + const at = manifest.times.indexOf(shownTime()); + const next = Math.max( + 0, + Math.min(manifest.times.length - 1, at + params.step), ); + void show(manifest.times[next]); + } notify(); }, getParams() { @@ -508,13 +570,13 @@ export function createWeatherLayer({ : { product, opacity }; }, getRowControls() { - const shared = clock.getState(); + const shared = clock?.getState(); const followLatest = isLatest(); // Source-described text is data: shown as is, never translated. const display = weatherDisplay(manifest); const missing = noFrame && - shared.mode === 'history' && + shared?.mode === 'history' && shared.products.find((entry) => entry.id === id)?.selected === null ? maxGap() / 60_000 < 60 ? t('No frame within {gap} min of {time}', { @@ -635,7 +697,9 @@ export function createWeatherLayer({ const stops = display.legend ?? (radar ? STOPS : lightning ? LIGHTNING_STOPS : []); const infoMotion = motion?.matches - ? t('Reduced motion · history playback unavailable') + ? clock + ? t('Reduced motion · history playback unavailable') + : t('Reduced motion · manual history available') : ''; const controls = { readout: true, @@ -825,23 +889,27 @@ export function createWeatherLayer({ }; }, getDiagnostics() { - const shared = clock.getState(); + const shared = clock?.getState(); return { ...rendering?.getDiagnostics(), - playing: shared.advancing, + playing: shared ? shared.playing : playing && !hostHidden, followLatest: isLatest(), - clock: { - mode: shared.mode, - target: shared.target, - playing: shared.advancing, - }, + ...(shared + ? { + clock: { + mode: shared.mode, + target: shared.target, + playing: shared.playing, + }, + } + : {}), historyFrames: manifest?.times?.length || 0, + timerActive: timer !== null, }; }, destroy() { layer.disable(); - unsubscribeClock(); - ownClock?.destroy(); + unsubscribeClock?.(); removeCamera?.(); removeCamera = null; motion?.removeEventListener?.('change', onVisibility); diff --git a/src/layers/weather/weather.test.mjs b/src/layers/weather/weather.test.mjs index 029cc0999..bd67d8305 100644 --- a/src/layers/weather/weather.test.mjs +++ b/src/layers/weather/weather.test.mjs @@ -1,9 +1,8 @@ -import test, { afterEach } from 'node:test'; +import test from 'node:test'; import assert from 'node:assert/strict'; import { createWeatherRendering, READY_WAKE_MS } from './rendering.js'; import { createWeatherLayer } from './index.js'; import { createWeatherClock } from './clock.js'; -import { worldClock } from '../../time/worldClock.js'; import * as Cesium from 'cesium'; import { Color, ImageryLayerCollection, GeographicTilingScheme } from 'cesium'; import { NO_IMAGERY_HOST } from './imageryHost.js'; @@ -42,16 +41,6 @@ const deferred = () => { const flush = async () => { for (let i = 0; i < 30; i++) await Promise.resolve(); }; -// Time moves on the world clock the weather clock follows, as the timeline -// moves it. -const seekTo = (clock, time) => { - clock.world.seek(Date.parse(time)); - return flush(); -}; -const goLive = (clock) => { - clock.world.goLive(); - return flush(); -}; function event() { const listeners = new Set(); return { @@ -568,14 +557,6 @@ test('failed and timed-out stages retain the previous observation; a healthy rep h.rendering.clear(); }); -// A layer built without a clock keeps its own on the page's world clock: -// each test leaves that clock live, with no layer of its own on it. -const harnessed = new Set(); -afterEach(() => { - for (const layer of harnessed) layer.destroy(); - harnessed.clear(); - worldClock.goLive(); -}); function layerHarness({ clock, reducedMotion = false, @@ -657,7 +638,6 @@ function layerHarness({ }); layer.init(viewer); layer.enable(); - harnessed.add(layer); return { layer, rendering, @@ -671,96 +651,72 @@ function layerHarness({ }; } -test('without a clock the layer keeps one of its own on the world clock and lets it go on destroy', async () => { +test('history has one owned timer, stops while hidden, and releases all work on disable/destroy', async (t) => { + t.mock.timers.enable({ apis: ['setTimeout'] }); const h = layerHarness(); const update = h.layer.update(); await flush(); h.stages[0].finish(); await update; - assert.equal(worldClock.follows('weather-radar'), true); - // The frames span the timeline's time; they are not marks on it. - assert.deepEqual(worldClock.coverage(), { - start: Date.parse(times[0]), - end: Date.parse(times.at(-1)), - marks: [], - markDetails: [], - }); h.layer.setParams({ play: true }); - assert.equal(worldClock.isPlaying(), true); - assert.equal(worldClock.getState().stepping, false); - assert.equal(h.layer.getDiagnostics().playing, true); + assert.equal(h.layer.getDiagnostics().timerActive, true); + t.mock.timers.tick(2000); + assert.equal(h.stages.length, 2); + assert.equal( + h.layer.getDiagnostics().timerActive, + false, + 'next timer waits for stage settlement', + ); + h.stages[1].finish(); + await flush(); + assert.equal(h.layer.getDiagnostics().timerActive, true); h.documentRef.hidden = true; h.documentRef.emit('visibilitychange'); - await flush(); - assert.equal(worldClock.isPlaying(), true, 'hiding suspends the layer only'); + assert.equal(h.layer.getDiagnostics().playing, false); + assert.equal(h.layer.getDiagnostics().timerActive, false); + t.mock.timers.tick(20_000); + assert.equal(h.stages.length, 2); h.documentRef.hidden = false; h.documentRef.emit('visibilitychange'); h.layer.setParams({ play: true }); - assert.equal(worldClock.isPlaying(), false); h.layer.disable(); + assert.equal(h.layer.getDiagnostics().timerActive, false); assert.equal(h.layer.getDiagnostics().historyFrames, 0); + t.mock.timers.tick(20_000); + assert.equal(h.stages.length, 2); h.layer.destroy(); - assert.equal(worldClock.follows('weather-radar'), false); assert.equal(h.documentRef.size, 0); assert.equal(h.motion.size, 0); assert.equal(h.moveEnd.size, 0); assert.ok(h.clears() >= 1); }); -test('reduced motion offers no play; steps still move the world clock from frame to frame', async () => { +test('reduced motion blocks autoplay but permits manual history and stops newly suspended playback', async (t) => { + t.mock.timers.enable({ apis: ['setTimeout'] }); const h = layerHarness({ reducedMotion: true }); const update = h.layer.update(); await flush(); h.stages[0].finish(); await update; + h.layer.setParams({ play: true }); + assert.equal(h.layer.getDiagnostics().timerActive, false); assert.equal( h.layer.getRowControls().chips.some((chip) => chip.id === 'play'), false, ); - // A step back from live goes to the newest frame, and the next one back - // to the frame before it. h.layer.setParams({ step: -1 }); + assert.equal(h.stages[1].time, times[1]); + h.stages[1].finish(); await flush(); - assert.equal(worldClock.now(), Date.parse(times[2])); - h.layer.setParams({ step: -1 }); - await flush(); - assert.equal(worldClock.now(), Date.parse(times[1])); - assert.equal(h.stages.at(-1).time, times[1]); -}); - -test('a row steps forward and plays from a past time through the world clock', async () => { - const h = layerHarness(); - const update = h.layer.update(); - await flush(); - h.stages[0].finish(); - await update; - worldClock.seek(Date.parse(times[0])); - await flush(); - h.layer.setParams({ step: 1 }); - assert.equal(worldClock.now(), Date.parse(times[1])); - assert.equal(worldClock.isPlaying(), false); - await flush(); - assert.equal(h.stages.at(-1).time, times[1]); - h.layer.setParams({ step: 1 }); - assert.equal(worldClock.now(), Date.parse(times[2])); - h.layer.setParams({ step: 1 }); - assert.equal( - worldClock.now(), - Date.parse(times[2]), - 'no frame after the newest', - ); - worldClock.seek(Date.parse(times[1])); - await flush(); + h.motion.matches = false; + h.motion.emit('change'); h.layer.setParams({ play: true }); - assert.equal(worldClock.isPlaying(), true); - assert.equal(worldClock.getState().stepping, false); - assert.ok( - worldClock.now() - Date.parse(times[1]) < 1_000, - 'away from live, play goes on from the time shown', - ); - h.layer.setParams({ step: 1 }); - assert.equal(worldClock.isPlaying(), false, 'a step holds play'); - assert.equal(worldClock.now(), Date.parse(times[2])); + assert.equal(h.layer.getDiagnostics().playing, true); + h.motion.matches = true; + h.motion.emit('change'); + assert.equal(h.layer.getDiagnostics().playing, false); + assert.equal(h.layer.getDiagnostics().timerActive, false); + h.layer.destroy(); }); test('disable invalidates an abort-insensitive source result and an already staged frame', async (t) => { @@ -789,6 +745,7 @@ test('disable invalidates an abort-insensitive source result and an already stag await next; await flush(); assert.equal(h.layer.getStats().count, 0); + assert.equal(h.layer.getDiagnostics().timerActive, false); assert.equal(h.layer.getStats().loading, false); h.layer.destroy(); }); @@ -847,6 +804,7 @@ test('update cancellation reaches imagery after source acquisition has completed assert.equal(h.stages[0].signal.aborted, true); assert.equal(h.layer.getStats().count, 0); assert.equal(h.layer.getStats().loading, false); + assert.equal(h.layer.getDiagnostics().timerActive, false); h.layer.destroy(); }); @@ -954,22 +912,21 @@ test('coverage navigation requires the shared shell handoff and detaches cleanly h.layer.destroy(); }); -test('manifest refresh during a history stage restages the same time and does not strand loading controls', async () => { +test('manifest refresh during a manual history stage does not strand loading controls', async () => { const h = layerHarness(); const first = h.layer.update(); await flush(); h.stages[0].finish(); await first; - worldClock.seek(Date.parse(times[1])); - await flush(); + h.layer.setParams({ step: -1 }); assert.equal(h.layer.getStats().loading, true); - const refreshed = h.layer.update(); - await flush(); - assert.equal(h.stages.length, 3); - assert.equal(h.stages[1].signal.aborted, true); - assert.equal(h.stages[2].time, times[1], 'the refresh keeps the time'); - h.stages[2].finish(); - await refreshed; + await h.layer.update(); + assert.equal( + h.stages.length, + 2, + 'metadata refresh preserves the staged manual selection', + ); + h.stages[1].finish(); await flush(); assert.equal(h.layer.getStats().loading, false); assert.equal(h.layer.getStats().observedAt, times[1]); @@ -999,8 +956,7 @@ test('historical observations do not relabel a fresh lightning feed as stale', a await flush(); h.stages[0].finish(); await first; - worldClock.seek(Date.parse(old)); - await flush(); + h.layer.setParams({ step: -1 }); h.stages[1].finish(); await flush(); assert.equal(h.layer.getStats().stale, false); @@ -1357,7 +1313,8 @@ test('404 fails a frame without retry', async () => { h.rendering.clear(); }); -test('no host holds the shown history frame, refreshes metadata, and restores the retained time', async () => { +test('no host pauses history, refreshes metadata, and restores retained time and playback', async (t) => { + t.mock.timers.enable({ apis: ['setTimeout'] }); let refreshes = 0; const h = layerHarness({ feed: { @@ -1373,23 +1330,28 @@ test('no host holds the shown history frame, refreshes metadata, and restores th await flush(); h.stages[0].finish(); await update; - worldClock.seek(Date.parse(times[0])); - await flush(); + h.layer.setParams({ play: true }); + t.mock.timers.tick(2000); assert.equal(h.stages.length, 2); - h.stages[1].finish(); - await flush(); host = { collection: null, kind: 'none' }; h.eventTarget.emit('gev:map-stack-changed'); await flush(); + assert.equal(h.layer.getDiagnostics().playing, false); + assert.equal(h.layer.getDiagnostics().timerActive, false); assert.equal(h.layer.getRowControls().summary.status, NO_IMAGERY_HOST); assert.equal(h.layer.getRowControls().info, NO_IMAGERY_HOST); await h.layer.update(); assert.equal(refreshes, 2); - assert.equal(h.stages.length, 2, 'nothing stages without a host'); + t.mock.timers.tick(10_000); + assert.equal(h.stages.length, 2); + assert.equal(h.layer.getDiagnostics().time, times[2]); host = { collection: {}, kind: 'globe' }; h.eventTarget.emit('gev:map-stack-changed'); - await flush(); - assert.equal(h.stages.at(-1).time, times[0], 'the retained time restages'); + assert.equal(h.layer.getDiagnostics().playing, true); + assert.equal(h.layer.getDiagnostics().timerActive, true); + t.mock.timers.tick(2000); + assert.equal(h.stages.length, 3); + assert.equal(h.stages[2].time, times[0]); h.layer.destroy(); assert.equal(h.eventTarget.size, 0); }); @@ -1503,21 +1465,25 @@ for (const [id, product] of [ const [shell] = h.shells(); assert.equal(shell.show, true); - worldClock.seek(Date.parse(times[0])); + layer.setParams({ play: true }); + t.mock.timers.tick(2000); await flush(); assert.equal( layer.getDiagnostics().time, times[0], - 'history moves at street level', + 'history advances at street level', ); camera.positionCartographic.height = 59_999; camera.moveEnd.emit(); assert.equal(shell.show, true, 'no height gate'); + assert.equal(layer.getDiagnostics().playing, true); + assert.equal(layer.getDiagnostics().timerActive, true); host = { collection: null, kind: 'none' }; events.emit('gev:map-stack-changed'); assert.equal(shell.show, false); assert.equal(layer.getRowControls().summary.status, NO_IMAGERY_HOST); + assert.equal(layer.getDiagnostics().timerActive, false); host = { collection: h.viewer.imageryLayers, kind: 'globe' }; events.emit('gev:map-stack-changed'); assert.equal(shell.destroyed, true); @@ -1709,12 +1675,10 @@ test('satellite mode chips restage history without changing time or latest-follo await flush(); h.stages[0].finish(); await update; - worldClock.seek(Date.parse(times[1])); - await flush(); + h.layer.setParams({ step: -1 }); h.stages[1].finish(); await flush(); h.layer.setParams({ infrared: 'full' }); - await flush(); assert.equal(h.stages[2].time, times[1]); assert.equal(h.stages[2].infrared, 0); assert.equal(h.layer.getParams().infrared, 0); @@ -1838,7 +1802,7 @@ test('a delayed installation failure retains the replacement and does not throw h.rendering.clear(); }); -test('a row steps the world clock through every registered observation; missing frames hide and latest goes live', async (t) => { +test('one row steps every registered observation; missing frames hide and latest restores each product', async (t) => { const clock = createWeatherClock(); const radar = layerHarness({ clock }); const satellite = layerHarness({ @@ -1871,14 +1835,6 @@ test('a row steps the world clock through every registered observation; missing .chips.filter(({ id }) => ['previous', 'play', 'next', 'latest'].includes(id), ); - // A step back from live goes to the newest frame, and the next one back - // to the frame before it. - radar.layer.setParams({ step: -1 }); - await flush(); - assert.equal(clock.getState().target, times[2]); - assert.equal(clock.world.isPlaying(), false); - for (const h of [radar, satellite]) h.stages.at(-1)?.finish(); - await flush(); radar.layer.setParams({ step: -1 }); await flush(); assert.equal(clock.getState().target, times[1]); @@ -1930,33 +1886,6 @@ test('a row steps the world clock through every registered observation; missing assert.equal(clock.getState().products.length, 1); }); -test('a row’s play and latest move the world clock as its timeline does', async (t) => { - const clock = createWeatherClock(); - const { world } = clock; - const h = layerHarness({ clock }); - t.after(() => { - h.layer.destroy(); - clock.destroy(); - }); - const update = h.layer.update(); - await flush(); - h.stages.at(-1).finish(); - await update; - h.layer.setParams({ play: true }); - assert.equal(world.isPlaying(), true); - assert.equal(world.getState().stepping, false, 'the world plays on its own'); - assert.ok( - world.now() - Date.parse(times[0]) < 1_000, - 'from the start when live', - ); - h.layer.setParams({ play: true }); - assert.equal(world.isPlaying(), false); - h.layer.setParams({ latest: true }); - assert.equal(world.isLive(), true); - await flush(); - assert.equal(clock.getState().mode, 'latest'); -}); - test('history manifest expiry hides imagery without jumping to latest; host resume keeps the target', async (t) => { const clock = createWeatherClock(); let value = snapshot; @@ -1969,7 +1898,7 @@ test('history manifest expiry hides imagery without jumping to latest; host resu await flush(); h.stages.at(-1).finish(); await update; - const history = seekTo(clock, times[0]); + const history = clock.setTarget(times[0]); await flush(); h.stages.at(-1).finish(); await history; @@ -2038,7 +1967,7 @@ test('satellite global selection uses the three-hour gap and preserves the share await flush(); h.stages.at(-1).finish(); await update; - await seekTo(clock, times[0]); + await clock.setTarget(times[0]); assert.equal( h.layer.getDiagnostics().hidden, true, @@ -2097,8 +2026,7 @@ test('satellite clouds from an hourly feed draw all through each hour and read l ); // Forty-five minutes past a frame, between it and the next, it still shows. - const between = seekTo( - clock, + const between = clock.setTarget( new Date(Date.parse(hourly[0]) + 45 * 60_000).toISOString(), ); await flush(); @@ -2109,7 +2037,7 @@ test('satellite clouds from an hourly feed draw all through each hour and read l // Live again (a past time judges delay from the timeline's time), past // one and a half hours it reads late. - const live = goLive(clock); + const live = clock.latest(); await flush(); h.stages.at(-1).finish(); await live; @@ -2131,11 +2059,11 @@ test('switching to history cancels a still-loading latest refresh and a later ta const update = h.layer.update(); await flush(); const latest = h.stages.at(-1); - const oldHistory = seekTo(clock, times[0]); + const oldHistory = clock.setTarget(times[0]); await flush(); assert.equal(latest.signal.aborted, true); const oldStage = h.stages.at(-1); - const current = seekTo(clock, times[1]); + const current = clock.setTarget(times[1]); await flush(); assert.equal(oldStage.signal.aborted, true); h.stages.at(-1).finish(); @@ -2445,9 +2373,8 @@ test('failed prefetch leaves the current frame and errors unchanged and releases assert.deepEqual(h.rendering.getDiagnostics(), before); }); -test('as the world plays, the layer warms the next advertised observation after each frame that shows', async (t) => { +test('layer warms the next advertised observation only after a successful playing frame, wrapping at the end', async (t) => { const clock = createWeatherClock(); - const { world } = clock; const h = layerHarness({ clock }); const warmed = []; let cancels = 0; @@ -2465,45 +2392,45 @@ test('as the world plays, the layer warms the next advertised observation after await flush(); h.stages.at(-1).finish(); await updated; - await seekTo(clock, times[0]); - h.stages.at(-1).finish(); + assert.equal(warmed.length, 0); + const play = clock.play(); await flush(); - assert.equal(warmed.length, 0, 'paused, nothing is warmed'); - world.play({ rate: 1e-9, continuous: true }); - assert.equal(clock.getState().advancing, true); - await seekTo(clock, times[1]); assert.equal(warmed.length, 0, 'still staging'); h.stages.at(-1).finish(); - await flush(); + await play; assert.deepEqual( warmed.map(({ time }) => time), - [times[2]], + [times[0]], ); assert.deepEqual(warmed[0].options, { infrared: 100 }); - await seekTo(clock, times[0]); + const next = clock.setTarget(times[0]); + await flush(); + h.stages.at(-1).finish(); + await next; + assert.deepEqual( + warmed.map(({ time }) => time), + [times[0], times[1]], + ); + const failed = clock.setTarget(times[1]); + await flush(); h.stages.at(-1).finish(false); - await flush(); - assert.equal(warmed.length, 1, 'a failed frame warms nothing'); - await seekTo(clock, times[2]); - h.stages.at(-1).finish(); - await flush(); - assert.equal(warmed.length, 1, 'the world plays on past the newest frame'); + await failed; + assert.equal(warmed.length, 2); const priorCancels = cancels; - world.pause(); - await flush(); + clock.pause(); assert.ok(cancels > priorCancels); - await seekTo(clock, times[1]); - h.stages.at(-1).finish(); + const paused = clock.setTarget(times[2]); await flush(); - assert.equal(warmed.length, 1); - world.play({ rate: 1e-9, continuous: true }); + h.stages.at(-1).finish(); + await paused; + assert.equal(warmed.length, 2); + await clock.play(); h.documentRef.hidden = true; h.documentRef.emit('visibilitychange'); await flush(); - h.stages.at(-1)?.finish(); + h.stages.at(-1).finish(); await flush(); - assert.equal(warmed.length, 1, 'hidden products do not prefetch'); - world.goLive(); + assert.equal(warmed.length, 2, 'hidden products do not prefetch'); }); for (const product of ['radar', 'clouds-regional', 'lightning']) { @@ -2840,7 +2767,7 @@ test('at a past time a frame is aged and its source judged delayed from the time // Years later, the world clock is moved back to the newest frame. Date.now.mock.mockImplementation(() => Date.parse('2032-01-01T00:00:00Z')); - void seekTo(clock, times[2]); + void clock.setTarget(times[2]); await flush(); h.stages.at(-1)?.finish(); await flush(); @@ -2851,7 +2778,7 @@ test('at a past time a frame is aged and its source judged delayed from the time assert.equal(h.layer.getStats().stale, false); // Ten minutes after the newest frame, the frame is ten minutes old. - void seekTo(clock, '2026-09-15T20:20:00.000Z'); + void clock.setTarget('2026-09-15T20:20:00.000Z'); await flush(); h.stages.at(-1)?.finish(); await flush(); diff --git a/src/layers/wind/index.test.mjs b/src/layers/wind/index.test.mjs index 8f79a18d9..45a54b24e 100644 --- a/src/layers/wind/index.test.mjs +++ b/src/layers/wind/index.test.mjs @@ -390,24 +390,20 @@ test('sample stays fixed across model, field and unit changes; dismissal and dis test('observed history labels wind as a forecast without changing its data or parameters', async () => { const { createWeatherClock } = await import('../weather/clock.js'); const clock = createWeatherClock(); - const { world } = clock; const layer = createWindLayer({ feed: { getSnapshot: async () => snapshot('gfs') }, clock }); let changes = 0; layer.setRowControlsListener(() => changes++); const params = layer.getParams(); - world.seek(Date.parse('2026-09-14T12:00:00.000Z')); - await Promise.resolve(); + await clock.setTarget('2026-09-14T12:00:00.000Z'); assert.equal(layer.getRowControls().summary.status, null, 'history does not mask source status'); assert.ok(changes > 0); assert.match(layer.getRowControls().info, /Forecast · does not follow history/); assert.deepEqual(layer.getParams(), params); - world.goLive(); - await Promise.resolve(); + await clock.latest(); assert.equal(layer.getRowControls().summary.status, null); layer.destroy(); const before = changes; - world.seek(Date.parse('2026-09-14T12:00:00.000Z')); - await Promise.resolve(); + await clock.setTarget('2026-09-14T12:00:00.000Z'); assert.equal(changes, before); clock.destroy(); }); @@ -466,8 +462,7 @@ test('wind whose source follows the timeline drops the note that it does not fol const clock = createWeatherClock({ world }); const layer = createWindLayer({ feed: { getSnapshot: async () => snapshot('gfs') }, clock }); world.follow('wind'); - world.seek(Date.parse('2026-09-14T12:00:00.000Z')); - await Promise.resolve(); + await clock.setTarget('2026-09-14T12:00:00.000Z'); assert.equal(clock.getState().mode, 'history'); assert.doesNotMatch(layer.getRowControls().info, /does not follow history/); world.follow('wind', false); diff --git a/src/time/snapshotTimeline.test.mjs b/src/time/snapshotTimeline.test.mjs index 6e053b611..a9cf52eac 100644 --- a/src/time/snapshotTimeline.test.mjs +++ b/src/time/snapshotTimeline.test.mjs @@ -119,7 +119,6 @@ test('at the live edge a layer with a timeline only follows and registers', asyn start: WALL - 3_600_000, end: WALL, marks: [], - markDetails: [], }); assert.equal(h.follower.active(), false); assert.deepEqual(h.calls, []); diff --git a/src/time/worldClock.js b/src/time/worldClock.js index 772252338..ad83f6a41 100644 --- a/src/time/worldClock.js +++ b/src/time/worldClock.js @@ -14,55 +14,11 @@ * src/time/snapshotTimeline.js); otherwise they stay live. * * Playback is continuous (`cursor + elapsed × rate`) unless a driver takes - * it: a driver steps the clock itself and moves it as it goes, so play and - * pause hand over to it. Several drivers may be attached; play goes to the - * newest that can play, pause to the one playing. Layers that load frames - * (weather) do not drive it: they gate continuous play at their next frame. + * it: weather replay steps its observed frames itself and moves the clock as + * it goes, so play and pause hand over to it. Several drivers may be attached; + * play goes to the newest that can play, pause to the one playing. */ -/** - * A timeline mark as a layer gives it: its time in epoch ms, and optionally - * a short label to show for it, the layer's own id for it and its kind. - * @typedef {{time: number, label?: string, id?: string, kind?: string}} WorldClockMarkInput - */ - -/** - * A timeline mark as `coverage().markDetails` returns it: a finite time, and - * only those of `label`, `id` and `kind` that are non-empty strings. - * @typedef {Readonly<{time: number, label?: string, id?: string, kind?: string}>} WorldClockMark - */ - -const MARK_TEXT = ['label', 'id', 'kind']; - -/** - * A mark (a number, or `{time, label?, id?, kind?}`) in its one shape, or - * null for one with no finite time. - * @param {unknown} input - * @returns {WorldClockMark | null} - */ -function readMark(input) { - if (typeof input === 'number') - return Number.isFinite(input) ? Object.freeze({ time: input }) : null; - if (!input || typeof input !== 'object') return null; - const { time } = input; - if (typeof time !== 'number' || !Number.isFinite(time)) return null; - const mark = { time }; - for (const key of MARK_TEXT) { - const value = input[key]; - if (typeof value === 'string' && value.trim()) mark[key] = value.trim(); - } - return Object.freeze(mark); -} - -// Marks in time order; at one time, by kind, label and id, so the order -// never depends on which source registered first. -const byText = (a = '', b = '') => (a < b ? -1 : a > b ? 1 : 0); -const byMark = (a, b) => - a.time - b.time || - byText(a.kind, b.kind) || - byText(a.label, b.label) || - byText(a.id, b.id); - /** The span a JS Date can hold, either side of 1970. */ const MAX_DATE_MS = 8.64e15; @@ -415,15 +371,7 @@ export function createWorldClock({ /** * A layer's span of time it can show, for a host's timeline; null while * it has none (off, or nothing loaded). Returns the unregister. - * - * `marks` are the moments in that span worth going to (a launch, a strong - * earthquake), drawn as ticks the timeline's arrow keys step to. Each is - * an epoch ms number, or `{time, label?, id?, kind?}`: `label` is short - * text the timeline shows for it (a name, `M6.4 · a place`), `id` the - * layer's own key for the event and `kind` what sort of event it is. - * Numbers and objects may be mixed; a mark with no finite time is - * ignored, as are a label, id or kind that is not a non-empty string. - * @param {{id: string, coverage: () => ({start: number, end: number, marks?: Array} | null)}} source + * @param {{id: string, coverage: () => ({start: number, end: number, marks?: number[]} | null)}} source */ register(source) { // Each registration is its own, even under a shared id. @@ -438,45 +386,20 @@ export function createWorldClock({ coverageChanged: () => changed(), /** Whether a followed layer has time to show; see getState().supported. */ isSupported, - /** - * The union of the registered sources' coverage, or null with none: - * `{start, end, marks, markDetails}`. `marks` is every mark's time, once - * each, in order, as numbers. `markDetails` is the marks themselves, in - * time order, each `{time, label?, id?, kind?}` (frozen): a mark several - * sources give alike is there once, and a bare time is dropped where a - * mark with more to say shares it. - * @returns {{start: number, end: number, marks: number[], markDetails: WorldClockMark[]} | null} - */ + /** The union of the registered sources' coverage, or null with none. */ coverage() { let start = Infinity; let end = -Infinity; - const details = new Map(); + const marks = new Set(); for (const { source } of sources) { const span = spanOf(source); if (!span) continue; start = Math.min(start, span.start); end = Math.max(end, span.end); - for (const input of span.marks ?? []) { - const mark = readMark(input); - if (!mark) continue; - const key = JSON.stringify([ - mark.time, - mark.label, - mark.id, - mark.kind, - ]); - if (!details.has(key)) details.set(key, mark); - } + for (const mark of span.marks ?? []) marks.add(mark); } if (start > end) return null; - const told = new Set(); - for (const mark of details.values()) - if (Object.keys(mark).length > 1) told.add(mark.time); - const markDetails = [...details.values()] - .filter((mark) => Object.keys(mark).length > 1 || !told.has(mark.time)) - .sort(byMark); - const marks = [...new Set(markDetails.map((mark) => mark.time))]; - return { start, end, marks, markDetails }; + return { start, end, marks: [...marks].sort((a, b) => a - b) }; }, getState, diff --git a/src/time/worldClock.test.mjs b/src/time/worldClock.test.mjs index 0533db957..323fa7202 100644 --- a/src/time/worldClock.test.mjs +++ b/src/time/worldClock.test.mjs @@ -253,60 +253,9 @@ test('coverage is the union of the registered sources', () => { start: 50, end: 200, marks: [100, 150, 200], - markDetails: [{ time: 100 }, { time: 150 }, { time: 200 }], }); off(); - assert.deepEqual(clock.coverage(), { - start: 50, - end: 180, - marks: [], - markDetails: [], - }); -}); - -test('marks may carry a label, an id and a kind, and merge in one order', () => { - const clock = createWorldClock(fakeTime().options); - clock.register({ - id: 'launches', - coverage: () => ({ - start: 100, - end: 300, - marks: [ - { time: 300, label: ' ARTEMIS II ', id: 'a2', kind: 'launch' }, - 100, - { time: 200, label: 'M6.4 · Fiji', kind: 'earthquake', extra: 1 }, - ], - }), - }); - clock.register({ - id: 'others', - coverage: () => ({ - start: 100, - end: 300, - marks: [ - 200, - { time: 200, label: 'M6.4 · Fiji', kind: 'earthquake' }, - { time: 200, label: 'ALPHA', kind: 'launch' }, - { time: 250, label: '', id: 7, kind: null }, - { time: Number.NaN, label: 'never' }, - Number.POSITIVE_INFINITY, - null, - 'soon', - ], - }), - }); - const covered = clock.coverage(); - assert.deepEqual(covered.marks, [100, 200, 250, 300], 'the times, once each'); - assert.deepEqual(covered.markDetails, [ - { time: 100 }, - // A bare 200 says nothing a labelled mark there does not; alike marks - // from two sources are one. - { time: 200, label: 'M6.4 · Fiji', kind: 'earthquake' }, - { time: 200, label: 'ALPHA', kind: 'launch' }, - { time: 250 }, - { time: 300, label: 'ARTEMIS II', id: 'a2', kind: 'launch' }, - ]); - assert.ok(covered.markDetails.every(Object.isFrozen)); + assert.deepEqual(clock.coverage(), { start: 50, end: 180, marks: [] }); }); test('seek refuses anything but epoch ms and rate must be positive', () => { diff --git a/src/ui/rail/RailTimeline.vue b/src/ui/rail/RailTimeline.vue new file mode 100644 index 000000000..7b4153531 --- /dev/null +++ b/src/ui/rail/RailTimeline.vue @@ -0,0 +1,178 @@ + + + diff --git a/src/ui/railTimeline.js b/src/ui/railTimeline.js new file mode 100644 index 000000000..b6dcd178e --- /dev/null +++ b/src/ui/railTimeline.js @@ -0,0 +1,56 @@ +import { h, render } from 'vue'; +import RailTimeline from './rail/RailTimeline.vue'; + +export { utcClock } from './rail/utcClock.js'; + +/** + * Stable native transport with local preview and a coalesced 150 ms drag + * commit. Renders the RailTimeline component into `container` and patches it + * synchronously on every update. + */ +export function createRailTimeline({ + container, + document = container?.ownerDocument, + sliderClassName = '', + heading = true, + onCommit = () => {}, + onPreview = () => {}, + onStep = () => {}, + onLatest = () => {}, + onPlay = () => {}, +} = {}) { + if (!document?.createElement || !container) return null; + let destroyed = false; + const paint = (state) => + render( + h(RailTimeline, { + state, + sliderClassName, + heading, + onCommit, + onPreview, + onStep, + onLatest, + onPlay, + }), + container, + ); + paint({ + ticks: [], + index: 0, + mode: 'latest', + playing: false, + readout: '', + disabled: true, + }); + return { + update(state) { + if (!destroyed) paint(state); + }, + destroy() { + if (destroyed) return; + destroyed = true; + render(null, container); + }, + }; +} diff --git a/src/ui/railTimeline.test.mjs b/src/ui/railTimeline.test.mjs new file mode 100644 index 000000000..9e408bdf3 --- /dev/null +++ b/src/ui/railTimeline.test.mjs @@ -0,0 +1,178 @@ +import '../testSupport/registerDom.mjs'; +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { assertSameNode } from '../testSupport/domAssert.mjs'; +import { nextTick } from 'vue'; +import { createRailTimeline } from './railTimeline.js'; +import { railDocumentFixture as railFixture } from './railTestFixture.mjs'; +const ticks = [ + '2026-09-22T01:00:00Z', + '2026-09-22T01:05:00Z', + '2026-09-22T01:10:00Z', +]; +const props = { + ticks, + index: 2, + mode: 'latest', + playing: false, + readout: 'Latest', + disabled: false, +}; +test('preview is immediate, commits are coalesced and the drag DOM and tick mapping stay stable', async (t) => { + t.mock.timers.enable({ apis: ['setTimeout'] }); + const f = railFixture(); + const previews = []; + const commits = []; + const view = createRailTimeline({ + ...f, + onPreview: (tick) => { + previews.push(tick); + return tick; + }, + onCommit: (tick) => commits.push(tick), + }); + view.update(props); + const slider = f.find((n) => n.tagName === 'INPUT'); + const row = slider.parentElement; + assert.equal(slider.getAttribute('aria-label'), 'Observed history'); + slider.value = '0'; + slider.dispatchEvent(new Event('input')); + assert.deepEqual(commits, []); + assert.deepEqual(previews, [ticks[0]]); + await nextTick(); + assert.equal(slider.getAttribute('aria-valuetext'), '09-22 01:00 UTC'); + view.update({ + ...props, + ticks: ticks.slice(1), + index: 1, + readout: 'Refresh', + }); + assertSameNode(slider.parentElement, row); + assertSameNode(row.children[1], slider); + assert.equal(slider.value, '0'); + assert.equal(slider.max, '2'); + assert.equal( + f.find((n) => n.className === 'rail-timeline-readout').textContent, + ticks[0], + ); + t.mock.timers.tick(149); + assert.equal(commits.length, 0); + slider.value = '1'; + slider.dispatchEvent(new Event('input')); + t.mock.timers.tick(1); + assert.deepEqual(commits, [ticks[1]]); + slider.value = '2'; + slider.dispatchEvent(new Event('input')); + slider.dispatchEvent(new Event('change')); + assert.deepEqual(commits, [ticks[1], ticks[2]]); + t.mock.timers.tick(150); + assert.equal(commits.length, 2); + await nextTick(); + assert.equal(slider.max, '1', 'release applies the latest update'); + view.destroy(); +}); +test('identical updates write nothing; controls call actions and destruction cancels commits', (t) => { + t.mock.timers.enable({ apis: ['setTimeout'] }); + const f = railFixture(); + const calls = []; + const view = createRailTimeline({ + ...f, + onCommit: () => calls.push('commit'), + onStep: (n) => calls.push(n), + onLatest: () => calls.push('latest'), + onPlay: () => calls.push('play'), + }); + view.update({ ...props, index: 1 }); + f.writes(); + view.update({ ...props, index: 1 }); + assert.equal(f.writes(), 0); + for (const label of ['‹', '›', 'Latest', 'Play']) + f.find((n) => n.textContent === label).click(); + assert.deepEqual(calls, [-1, 1, 'latest', 'play']); + view.update({ ...props, playing: true }); + assert.ok(f.find((n) => n.textContent === 'Pause')); + const slider = f.find((n) => n.tagName === 'INPUT'); + slider.value = '0'; + slider.dispatchEvent(new Event('change')); + assert.equal(calls.at(-1), 'commit'); + slider.dispatchEvent(new Event('input')); + view.destroy(); + t.mock.timers.tick(150); + assert.equal(calls.length, 5); + assert.equal(f.container.children.length, 0); +}); + +test('observed history label and endpoint times track the advertised tick range', () => { + const f = railFixture(); + const view = createRailTimeline(f); + view.update(props); + assert.equal( + f.find((n) => n.className === 'panel-title').textContent, + 'Observed history', + ); + const endpoints = f.find((n) => n.className === 'rail-timeline-endpoints'); + assert.equal(endpoints.parentElement.className, 'rail-timeline-track'); + assert.deepEqual( + [...endpoints.children].map((n) => n.textContent), + ['01:00 UTC', '01:10 UTC'], + ); + view.update({ ...props, ticks: ticks.slice(1) }); + assert.equal(endpoints.children[0].textContent, '01:05 UTC'); + view.destroy(); +}); + +test('an update from inside the preview neither moves the handle back nor survives a disable', async () => { + const f = railFixture(); + let view; + let next = null; + const commits = []; + view = createRailTimeline({ + ...f, + onPreview: () => { + if (next) view.update(next); + return 'preview'; + }, + onCommit: (tick, index) => commits.push(index), + }); + view.update(props); + const slider = f.find((n) => n.tagName === 'INPUT'); + next = { ...props, readout: 'Refresh' }; + slider.value = '0'; + slider.dispatchEvent(new Event('input')); + assert.equal(slider.value, '0'); + slider.dispatchEvent(new Event('change')); + assert.deepEqual(commits, [0]); + next = { ...props, disabled: true }; + slider.value = '1'; + slider.dispatchEvent(new Event('input')); + await nextTick(); + assert.equal(slider.value, '2', 'the disabled owner keeps its position'); + assert.equal(slider.getAttribute('aria-valuetext'), '09-22 01:10 UTC'); + view.destroy(); +}); +test('a drag that ends where it began puts the handle back on the shown index', async (t) => { + t.mock.timers.enable({ apis: ['setTimeout'] }); + const f = railFixture(); + const commits = []; + const view = createRailTimeline({ + ...f, + onCommit: (tick) => commits.push(tick), + }); + view.update(props); + await nextTick(); + const slider = f.find((n) => n.tagName === 'INPUT'); + slider.value = '0'; + slider.dispatchEvent(new Event('input')); + slider.dispatchEvent(new Event('pointercancel')); + await nextTick(); + assert.equal(slider.value, '2', 'a cancelled drag'); + assert.deepEqual(commits, []); + // A refused commit: the owner keeps its index. + slider.value = '1'; + slider.dispatchEvent(new Event('input')); + slider.dispatchEvent(new Event('change')); + await nextTick(); + assert.deepEqual(commits, [ticks[1]]); + assert.equal(slider.value, '2', 'a refused commit'); + view.destroy(); +}); diff --git a/src/ui/stores/worldTime.js b/src/ui/stores/worldTime.js index 19184b482..9dcb7d4c8 100644 --- a/src/ui/stores/worldTime.js +++ b/src/ui/stores/worldTime.js @@ -27,8 +27,7 @@ export const WORLD_TIME_SPEEDS = Object.freeze({ * buffering, timeMs, supported, span}`, where `supported` says a layer that moves with the clock * has time to show and `span` is the stretch the timeline runs over: the * time those layers cover, reaching to now and to the world time, with their - * marks (`marks`, their times; `markDetails`, each `{time, label?, id?, - * kind?}`, as the world clock's coverage gives them). It follows the page's world clock, which tells it of every move, and + * marks. It follows the page's world clock, which tells it of every move, and * of the time a few times a second while it plays on its own. While a * timeline shows, it reads the clock each second itself, so live and the * track's end keep up with now. @@ -43,7 +42,6 @@ export const useWorldTimeStore = defineStore('gev-world-time', () => { start: Math.min(coverage.start, now), end: Math.max(coverage.end, now), marks: coverage.marks, - markDetails: coverage.markDetails, }; }; const spanOf = (state) => { @@ -54,7 +52,6 @@ export const useWorldTimeStore = defineStore('gev-world-time', () => { start: Math.min(covered.start, state.timeMs), end: Math.max(covered.end, state.timeMs), marks: covered.marks, - markDetails: covered.markDetails, }); }; const nearNow = (ms, length) => @@ -128,8 +125,8 @@ export const useWorldTimeStore = defineStore('gev-world-time', () => { /** * Play runs the track at the speed chosen, from the start when it is at * its end (at live, say), as a video plays again from the top. It runs - * the clock itself: weather follows the time frame by frame like every - * other layer the track covers. + * the clock itself, past weather's own replay: weather follows the time + * frame by frame like every other layer the track covers. */ togglePlay() { const { playing, live, timeMs, span } = time.value; @@ -141,9 +138,9 @@ export const useWorldTimeStore = defineStore('gev-world-time', () => { }, speed, /** - * Choose how fast play runs; playing, it changes at once. A driver steps - * at its own pace, so a speed chosen while one plays takes playback over - * from where it is. + * Choose how fast play runs; playing, it changes at once. Weather's own + * replay steps at its own pace, so a speed chosen while it plays takes + * playback over from where it is. */ setSpeed(next) { if (!Object.hasOwn(WORLD_TIME_SPEEDS, next)) return; diff --git a/src/ui/styles/weather.css b/src/ui/styles/weather.css index d0cf13a25..8fb92e37c 100644 --- a/src/ui/styles/weather.css +++ b/src/ui/styles/weather.css @@ -56,7 +56,8 @@ } /* Card typography follows the layer rows and app tokens. */ .weather-readout, -.rail-card { +.rail-card, +.rail-timeline { min-width: 0; color: var(--text-dim); font: 9px/1.45 var(--font-mono); @@ -127,7 +128,7 @@ text-align: right; } .rail-card-line, -.weather-frame-time { +.rail-timeline-readout { font-family: var(--font-mono); font-size: 9px; letter-spacing: 0.5px; @@ -187,13 +188,54 @@ html:not([lang='en']) .weather-card [data-line-id='status'] { letter-spacing: 0.5px; } .rail-card [hidden], -.weather-frame-time[hidden], +.weather-timeline-block[hidden], .weather-observed-group[hidden] { display: none !important; } -.weather-frame-time { +.rail-timeline { padding: 5px; border-bottom: 1px solid var(--weather-card-border); +} +.rail-timeline-track { + display: grid; + grid-template-columns: auto minmax(0, 1fr) auto; + align-items: center; + gap: 3px 8px; + margin-top: 6px; +} +.rail-timeline-track input { + min-width: 0; + width: 100%; + margin: 0; +} +.rail-timeline-endpoints { + display: flex; + grid-column: 2; + justify-content: space-between; + flex-wrap: wrap; + gap: 3px 8px; + font: 8px/1.45 var(--font-mono); + font-variant-numeric: tabular-nums; +} +.rail-timeline-endpoints span { + white-space: nowrap; +} +.rail-timeline-endpoints span:last-child { + margin-left: auto; +} +.rail-timeline-controls .data-toggle-chip { + flex: 0 0 auto; +} +.rail-timeline-controls { + display: flex; + align-items: center; + flex-wrap: wrap; + gap: 6px; + margin-top: 6px; +} +.rail-timeline-readout { + flex: 1 1 auto; + min-width: 0; overflow-wrap: anywhere; font-variant-numeric: tabular-nums; color: var(--text-secondary); diff --git a/src/ui/styles/world-timeline.css b/src/ui/styles/world-timeline.css index 6f6005859..f644f8543 100644 --- a/src/ui/styles/world-timeline.css +++ b/src/ui/styles/world-timeline.css @@ -194,26 +194,6 @@ body.cockpit-mode #world-timeline { pointer-events: none; } -/* A tick's label, shown over the time's bubble while the pointer is on the - tick (or the handle rests on its mark). It slides across itself as the - bubble does, so it stays within the track. */ -#world-timeline .world-timeline-mark-label { - position: absolute; - bottom: calc(100% + 30px); - left: calc(100% * var(--at)); - z-index: 1; - padding: 2px 8px; - border: 1px solid rgba(0, 212, 255, 0.4); - border-radius: 6px; - background: var(--glass-bg); - color: var(--text-primary); - font-size: 11px; - line-height: 1.4; - white-space: pre; - transform: translateX(calc(var(--at) * -100%)); - pointer-events: none; -} - /* Zoomed, the track drags along. */ #world-timeline .world-timeline-track.is-zoomed { cursor: grab; diff --git a/src/ui/views/panels/WorldTimeline.test.mjs b/src/ui/views/panels/WorldTimeline.test.mjs index def5f43e9..7785e86c1 100644 --- a/src/ui/views/panels/WorldTimeline.test.mjs +++ b/src/ui/views/panels/WorldTimeline.test.mjs @@ -581,91 +581,3 @@ test('a pinch measures from where the fingers are, and a lifted finger ends it', assert.ok(Math.abs(length() - zoomedTo) < 1_000); on(input, 'pointercancel', 100, 1); }); - -test('a tick shows its label on hover, and a tap by it goes to its mark', async (t) => { - const bar = mount(t); - const now = Date.now(); - const start = now - 10 * 86_400_000; - // Ticks a fifth and seven tenths along a 1000 px track. - const launch = start + (now - start) * 0.2; - const quake = start + (now - start) * 0.7; - const release = worldClock.hold('test-launches'); - const unregister = worldClock.register({ - id: 'test-launches', - coverage: () => ({ - start, - end: now, - marks: [ - start, - { time: launch, label: 'GAUNTLET PAYLOAD', id: 'l1', kind: 'launch' }, - { time: quake, label: 'M6.4 · Fiji', kind: 'earthquake' }, - ], - }), - }); - t.after(() => { - unregister(); - release(); - }); - await nextTick(); - const track = bar().querySelector('.world-timeline-track'); - const input = bar().querySelector('input[type=range]'); - Object.defineProperty(track, 'clientWidth', { value: 1_000 }); - track.getBoundingClientRect = () => ({ left: 0, width: 1_000, top: 0, height: 24 }); - const press = (type, clientX, pointerId = 1) => - track.dispatchEvent(new PointerEvent(type, { bubbles: true, clientX, pointerId })); - const tip = () => bar().querySelector('.world-timeline-mark-label'); - assert.equal(bar().querySelectorAll('.world-timeline-tick').length, 3, 'ticks stay ticks'); - assert.equal(tip(), null); - - // Hovering within 6 px of a tick shows its label, in place of the track's hint. - press('pointermove', 205); - await nextTick(); - assert.equal(tip()?.textContent, 'GAUNTLET PAYLOAD'); - assert.equal(track.hasAttribute('title'), false); - press('pointermove', 698); - await nextTick(); - assert.equal(tip()?.textContent, 'M6.4 · Fiji'); - // Further off, or on a tick with no label, nothing shows. - press('pointermove', 690); - await nextTick(); - assert.equal(tip(), null); - assert.equal(track.hasAttribute('title'), true); - press('pointermove', 2); - await nextTick(); - assert.equal(tip(), null, 'an unlabelled mark has no label'); - press('pointermove', 205); - track.dispatchEvent(new PointerEvent('pointerleave', { clientX: 1_100, pointerId: 1 })); - await nextTick(); - assert.equal(tip(), null, 'leaving the track hides it'); - - // A tap by a tick goes to its mark exactly; elsewhere, to the time there. - press('pointerdown', 704); - press('pointerup', 704); - await nextTick(); - assert.equal(worldClock.now(), quake); - assert.match(input.getAttribute('aria-valuetext'), / · M6\.4 · Fiji$/); - press('pointerdown', 500); - press('pointerup', 500); - await nextTick(); - const middle = start + (now - start) / 2; - assert.ok(Math.abs(worldClock.now() - middle) < 60_000, 'went to the middle'); - assert.notEqual(worldClock.now(), quake); - assert.match(input.getAttribute('aria-valuetext'), /UTC$/, 'off a mark, the time alone'); - // A drag from a tick still scrubs. - press('pointerdown', 200); - press('pointermove', 300); - press('pointerup', 300); - await nextTick(); - assert.ok(Math.abs(worldClock.now() - (start + (now - start) * 0.3)) < 60_000); - - // The arrows go to the marks and tell their labels; focused, the label shows. - input.dispatchEvent(new Event('focus')); - input.dispatchEvent(new KeyboardEvent('keydown', { key: 'ArrowLeft' })); - await nextTick(); - assert.equal(worldClock.now(), launch); - assert.match(input.getAttribute('aria-valuetext'), / · GAUNTLET PAYLOAD$/); - assert.equal(tip()?.textContent, 'GAUNTLET PAYLOAD'); - input.dispatchEvent(new Event('blur')); - await nextTick(); - assert.equal(tip(), null); -}); diff --git a/src/ui/views/panels/WorldTimeline.vue b/src/ui/views/panels/WorldTimeline.vue index 6cbede0b5..866380638 100644 --- a/src/ui/views/panels/WorldTimeline.vue +++ b/src/ui/views/panels/WorldTimeline.vue @@ -8,12 +8,11 @@ import UiIcon from '../../kit/UiIcon.vue'; import UiSelect from '../../kit/UiSelect.js'; // The world timeline: play and pause and the speed on the left, a track -// across the stretch the layers on can show (each mark, a launch or a strong -// earthquake, a tick, its label shown over it on hover) with a handle to -// scrub and the time in a bubble over it, and the way back to live on the -// right, lit while live. Scrolling or pinching the track zooms it around the -// handle, dragging it moves along it, a tap on or by a tick goes to its -// mark's time exactly, and a double-click shows it all again. It shows +// across the stretch the layers on can show (each launch or frame a tick) +// with a handle to scrub and the time in a bubble over it, and the way back +// to live on the right, lit while live. Scrolling or pinching the track +// zooms it around the handle, dragging it moves along it, and a double-click +// shows it all again. It shows // while a layer with a time of its own (weather, satellites, launches, // or one a host follows) is on with time to show; with only live feeds such // as flights on, the bar stays hidden. @@ -54,8 +53,6 @@ const ZOOM_STEP = 1.5; const WHEEL_ZOOM = 0.0025; // Two presses this close are a double-click. const DOUBLE_PRESS_MS = 500; -// A tap or a hover this near a tick, in pixels, is on its mark. -const MARK_HIT_PX = 6; const readout = computed(() => Number.isFinite(time.value.timeMs) @@ -215,7 +212,6 @@ let movedTime = false; const onPointerDown = (event) => { // Only the main button: a right-click is for the menu. if (event.button > 0) return; - hovered.value = null; const onHandle = event.target instanceof HTMLInputElement; pointers.set(event.pointerId, { x: event.clientX, onHandle }); if (pointers.size === 1) { @@ -245,10 +241,6 @@ const onPointerDown = (event) => { gesture = { kind: 'press', x: event.clientX, end: view.value.end }; }; const onPointerMove = (event) => { - // A pointer hovering, none pressed, shows the label of the tick under it. - hovered.value = pointers.size - ? null - : (markNear(event.clientX, event.currentTarget)?.time ?? null); const pointer = pointers.get(event.pointerId); if (!pointer) return; pointer.x = event.clientX; @@ -274,14 +266,8 @@ const onPointerMove = (event) => { }; const onPointerUp = (event) => { if (!pointers.delete(event.pointerId)) return; - // A tap on or by a tick goes to its mark exactly; elsewhere, to the time - // under it. if (gesture?.kind === 'press' && event.type === 'pointerup') - store.scrub( - markNear(event.clientX, event.currentTarget)?.time ?? - timeAt(event.clientX, event.currentTarget), - viewLength(), - ); + store.scrub(timeAt(event.clientX, event.currentTarget), viewLength()); // A finger lifted from a pinch ends it; the other one moves nothing. gesture = null; }; @@ -290,66 +276,11 @@ const place = (ms) => { const { start, end } = view.value; return end > start ? ((ms - start) / (end - start)) * 100 : 100; }; -// The labels of the marks at each time marked; a time may have none. -const markLabels = computed(() => { - const labels = new Map(); - for (const mark of span.value?.markDetails ?? []) { - if (!labels.has(mark.time)) labels.set(mark.time, []); - if (mark.label) labels.get(mark.time).push(mark.label); - } - return labels; -}); -// A tick for each time marked in view: where it sits, as a share of the -// track, and its marks' labels. const ticks = computed(() => { const { start, end } = view.value; return span.value.marks .filter((mark) => mark >= start && mark <= end) - .map((mark) => ({ - time: mark, - share: place(mark) / 100, - labels: markLabels.value.get(mark) ?? [], - })); -}); -// The tick nearest `clientX` within MARK_HIT_PX of it, or null. -function markNear(clientX, track) { - if (!view.value) return null; - const { left, width } = track.getBoundingClientRect(); - if (!(width > 0)) return null; - let near = null; - let nearest = MARK_HIT_PX; - for (const tick of ticks.value) { - const off = Math.abs(left + tick.share * width - clientX); - if (off <= nearest) { - near = tick; - nearest = off; - } - } - return near; -} -// The time of the tick the pointer hovers, and whether the handle has focus. -const hovered = shallowRef(null); -const focused = shallowRef(false); -// The labels shown over the track: the hovered tick's, or with the handle -// focused and paused on a mark (an arrow key or a tap took it there), that -// mark's. Nothing for a mark with no label. -const markTip = computed(() => { - if (!view.value) return null; - const onMark = !time.value.live && focused.value ? time.value.timeMs : null; - const over = ticks.value.find((each) => each.time === hovered.value); - const tick = over ?? ticks.value.find((each) => each.time === onMark); - return tick?.labels.length - ? { share: tick.share, text: tick.labels.join('\n'), hover: Boolean(over) } - : null; -}); -// The time as the handle tells it, with the labels of the mark it is on. -const valueText = computed(() => { - const labels = time.value.live - ? null - : markLabels.value.get(time.value.timeMs); - return labels?.length - ? `${readout.value} · ${labels.join('; ')}` - : readout.value; + .map((mark) => `${place(mark)}%`); }); const shown = computed(() => Math.min(view.value.end, Math.max(view.value.start, at.value)), @@ -363,11 +294,10 @@ const scrub = (event) => { } store.scrub(Number(event.target.value), viewLength()); }; -// Arrows go to the previous or next mark (a launch, a strong earthquake), -// whose label the handle then tells with the time, or a step along the track -// as shown where there is none; Page keys take a tenth -// of it; Home and End go to the ends of all of it. Plus and minus zoom, and -// zero shows it all; with a modifier they are the browser's own zoom. +// Arrows go to the previous or next mark (a launch, a frame), or a step along +// the track as shown; Page keys take a tenth of it; Home and End go to the +// ends of all of it. Plus and minus zoom, and zero shows it all; with a +// modifier they are the browser's own zoom. const ZOOM_KEYS = ['+', '=', '-', '0']; const onKey = (event) => { if (ZOOM_KEYS.includes(event.key)) { @@ -401,18 +331,17 @@ const onKey = (event) => { >
{ @input="scrub" aria-keyshortcuts="+ - 0" @keydown="onKey" - @focus="focused = true" - @blur="focused = false" />
{{ t('Live') }}
diff --git a/src/ui/weather/WeatherReadout.vue b/src/ui/weather/WeatherReadout.vue index b89e6ed86..c7c341816 100644 --- a/src/ui/weather/WeatherReadout.vue +++ b/src/ui/weather/WeatherReadout.vue @@ -1,14 +1,15 @@ @@ -30,9 +31,16 @@ defineProps({ :aria-label="t('Observed history')" >

{{ t('Observed history') }}

{{ view.scope }}
{{ - view.frameTime - }}
clock?.setTarget(tick), + onPreview: (time) => historyTime(time, clock?.getState()), + onStep: (direction) => clock?.step(direction), + onLatest: () => clock?.latest(), + onPlay: () => clock?.togglePlay(), + }, }; // The readout patches synchronously, so a newly opened card can be measured. const paint = (view) => @@ -106,7 +113,14 @@ export function createWeatherPanel({ hidden: true, observed: false, scope: '', - frameTime: '', + timeline: { + ticks: [], + index: 0, + mode: 'latest', + playing: false, + readout: '', + disabled: true, + }, cards: [], observedCards: [], }); @@ -121,18 +135,32 @@ export function createWeatherPanel({ .filter(({ summary }) => summary) .sort((a, b) => ORDER.indexOf(a.id) - ORDER.indexOf(b.id)); const observed = active.filter(({ id }) => OBSERVED.has(id)); - const showObserved = observed.length > 0; + const showTimeline = observed.length > 0; const names = { 'weather-radar': t('Rain radar'), 'weather-satellite': t('Satellite clouds'), 'weather-lightning': t('Lightning density'), }; - // While live, the newest frame and its age; at a past time, the timeline - // time alone. The world timeline moves the time. - const shownTime = - state.mode === 'latest' ? state.timeline.at(-1) : state.target; - const frameTime = - showObserved && shownTime ? historyTime(shownTime, state) : ''; + const index = + state.mode === 'latest' + ? state.timeline.length - 1 + : Math.max( + 0, + state.timeline.findLastIndex( + (tick) => Date.parse(tick) <= Date.parse(state.target), + ), + ); + const timeline = { + ticks: state.timeline, + index, + mode: state.mode, + playing: Boolean(state.playing), + disabled: !showTimeline || state.timeline.length < 2, + readout: + state.mode === 'latest' + ? t('LATEST · newest per product') + : historyTime(state.target, state), + }; const models = active.map((entry) => { const { id, icon, summary, legend = [], list } = entry; // Discrete classes (storm geometry, AQHI bands) list swatches, not a ramp. @@ -217,9 +245,9 @@ export function createWeatherPanel({ const hidden = active.length === 0; paint({ hidden, - observed: showObserved, + observed: showTimeline, scope: observed.map(({ id }) => names[id]).join(' · '), - frameTime, + timeline, cards: models.filter(({ id }) => !OBSERVED.has(id)), observedCards: models.filter(({ id }) => OBSERVED.has(id)), }); diff --git a/src/ui/weatherPanel.test.mjs b/src/ui/weatherPanel.test.mjs index ebb28189a..4a438e4d9 100644 --- a/src/ui/weatherPanel.test.mjs +++ b/src/ui/weatherPanel.test.mjs @@ -55,6 +55,10 @@ function fixture() { listeners.add(fn); return () => listeners.delete(fn); }, + setTarget: (tick) => calls.push(['target', tick]), + latest: () => calls.push(['latest']), + togglePlay: () => calls.push(['play']), + step: (n) => calls.push(['step', n]), }; return { ...f, @@ -71,36 +75,39 @@ function fixture() { }, }; } -const frameTime = (f) => f.find((n) => n.className === 'weather-frame-time'); +const timelineHost = (f) => + f.find((n) => n.className === 'weather-timeline-block'); const card = (f, id) => f.find((n) => n.dataset.cardId === id); const line = (f, id, name) => f.find((n) => n.dataset.lineId === name, card(f, id)); -test('the frame time shows with any observed product; the panel has no time controls of its own', (t) => { - t.mock.timers.enable({ - apis: ['Date'], - now: Date.parse('2026-09-22T01:17:00Z'), - }); +test('timeline stays visible with any observed product; native preview and transport use the clock', (t) => { + t.mock.timers.enable({ apis: ['setTimeout'] }); const f = fixture(); const view = createWeatherPanel(f); view.update([wind]); - assert.equal(frameTime(f).hidden, true); + assert.equal(timelineHost(f).hidden, true); view.update([wind, radar]); - assert.equal(frameTime(f).hidden, false); - assert.equal(frameTime(f).textContent, '01:05 UTC · 12 min ago'); + assert.equal(timelineHost(f).hidden, false); f.state({ timeline: [ticks[0]] }); - assert.equal(frameTime(f).textContent, '01:00 UTC · 17 min ago'); + assert.equal(timelineHost(f).hidden, false); + assert.equal(f.find((n) => n.tagName === 'INPUT').disabled, true); f.state({ timeline: [] }); - assert.equal(frameTime(f).hidden, true); - f.state({ timeline: ticks, mode: 'history', target: ticks[0] }); - assert.equal(frameTime(f).textContent, '01:00 UTC'); - assert.equal( - f.find((n) => n.tagName === 'INPUT'), - null, - ); - assert.equal( - f.find((n) => ['Play', 'Latest'].includes(n.textContent)), - null, - ); + assert.equal(timelineHost(f).hidden, false); + f.state({ timeline: ticks }); + assert.equal(timelineHost(f).hidden, false); + const slider = f.find((n) => n.tagName === 'INPUT'); + slider.value = '0'; + slider.dispatchEvent(new Event('input')); + assert.deepEqual(f.calls, []); + slider.dispatchEvent(new Event('change')); + assert.deepEqual(f.calls, [['target', ticks[0]]]); + f.find((n) => n.textContent === 'Latest' && n.tagName === 'BUTTON').click(); + f.find((n) => n.textContent === 'Play').click(); + assert.deepEqual(f.calls.slice(1), [['latest'], ['play']]); + slider.dispatchEvent(new Event('input')); + view.update([wind]); + t.mock.timers.tick(150); + assert.equal(f.calls.length, 3, 'hiding cancels pending drag'); view.destroy(); assert.equal(f.listeners.size, 0); }); @@ -173,7 +180,7 @@ test('cyclone readout retains advisory, position, intensity, geometry, coverage, ], }; view.update([cyclone]); - assert.equal(frameTime(f).hidden, true); + assert.equal(timelineHost(f).hidden, true); assert.match( line(f, cyclone.id, 'time').textContent, /JULIO.*Hurricane.*Advisory 10.*UTC/, @@ -404,7 +411,7 @@ test('cyclones lead, and observed history owns one bordered group with only acti group.children[1].textContent, 'Rain radar · Satellite clouds · Lightning density', ); - assertSameNode(group.children[2], frameTime(f)); + assertSameNode(group.children[2], timelineHost(f)); assert.deepEqual( [...group.children[3].children].map((n) => n.dataset.cardId), ['weather-radar', 'weather-satellite', 'weather-lightning'], @@ -667,8 +674,13 @@ test('history time keeps the hour whatever the length of the localized date', () const f = fixture(); const view = createWeatherPanel(f); view.update([wind, radar]); + const ends = f.find((n) => n.className === 'rail-timeline-endpoints'); + assert.deepEqual( + [...ends.children].map((n) => n.textContent), + ['01:00 UTC', '01:05 UTC'], + locale, + ); f.state({ mode: 'history', target: ticks[1] }); - assert.equal(frameTime(f).textContent, '01:05 UTC', locale); assert.match( line(f, radar.id, 'time').textContent, /(^|[^\d:])01:05 UTC/, @@ -796,7 +808,7 @@ test('at a past time, frame ages and the timeline readout count from the timelin ); const readout = f.find((n) => n.textContent === '01:20 UTC'); assert.ok(readout, 'the readout names the timeline time'); - assert.doesNotMatch(frameTime(f).textContent, /min ago/); + assert.doesNotMatch(timelineHost(f).textContent, /min ago/); view.destroy(); });