Merge main through #1634 into the renderer seam

Brings in the CCTV opening camera, the Iceland, Giroc HLS, Taiwan, Quebec,
Ottawa and world camera packs, the world clock and timeline, the zoom-out
limit and registered-only layer state, ported onto the renderer contract:
the sky follows the world time through the frame port's setTime in
preUpdate, the Quebec overlay reads the eye, projects and redraws through
the camera, query and frame ports, launches hide pending missions through
their draw records, and mission orbit rings turn on the scene clock.
This commit is contained in:
Sameh Khamis committed 2026-11-10 00:31:23 -08:00
commit 2b60531c3c
170 files changed
+44096 -319

No files matched your search

+1
View File
@@ -1169,6 +1169,7 @@ export class StyleManager extends ShellFacade {
_cctvSummary: this._cctvSummary,
},
cctv: cctvLayer,
viewer: this.viewer,
actions: {
isEnabled: () => this._dataManager?.isEnabled('cctv'),
setParams: (params, options) =>
+5
View File
@@ -23,6 +23,7 @@ import { useCctvStore } from './stores/cctv.js';
import { useStatusStore } from './stores/status.js';
import { applicationPinia } from './vueRuntime.js';
import { onLocaleChange } from '../i18n/index.js';
import { createQuebecCctvOverlay } from './quebecCctvOverlay.js';
/**
* Own camera-panel interaction and presentation; receive the camera port and
@@ -34,6 +35,7 @@ export class CctvControls {
constructor({
elements,
cctv,
viewer = null,
actions,
store = useCctvStore(applicationPinia()),
statusStore = useStatusStore(applicationPinia()),
@@ -42,11 +44,13 @@ export class CctvControls {
this.store = store;
this.statusStore = statusStore;
this.cctv = cctv;
this._quebecCctvOverlay = createQuebecCctvOverlay(viewer);
this.actions = actions;
this.destroyed = false;
this.listeners = new AbortController();
this._cctvUnsubscribe = null;
this._cctvState = null;
this._lastQuebecSelectionRevision = null;
this._cctvSummaryTypingTimer = null;
this._lastCctvSummaryText = '';
this._lastSeenCctvActiveId = null;
@@ -146,6 +150,7 @@ export class CctvControls {
if (this.destroyed) return;
this.destroyed = true;
this._offLocale();
this._quebecCctvOverlay?.dispose();
this._cctvVideoSurface?.stop();
this._videoVisibilityObserver?.disconnect();
this._actionGeneration++;
+19 -3
View File
@@ -154,6 +154,20 @@ export function _renderCctvState(state) {
const enabled = !!state?.enabled && !!this.actions.isEnabled();
const activeId = state?.activeCameraId || '';
const activeCamera = state?.activeCamera || null;
const selectionRevision = Number(state?.activeCameraReselection);
const reselected =
this._lastQuebecSelectionRevision !== null &&
Number.isFinite(selectionRevision) &&
selectionRevision !== this._lastQuebecSelectionRevision;
this._lastQuebecSelectionRevision = Number.isFinite(selectionRevision)
? selectionRevision
: null;
const isQuebecCamera =
enabled && activeCamera?.sourceKind?.startsWith('quebec-');
this._quebecCctvOverlay?.setCamera(isQuebecCamera ? activeCamera : null, {
reselected,
});
if (this._cctvFrameWrap) this._cctvFrameWrap.hidden = Boolean(isQuebecCamera);
// Auto-expand the panel when the active camera CHANGES to a new non-null
// id while the layer is enabled. Covers click-on-globe, panel controls,
@@ -241,7 +255,8 @@ export function _renderCctvState(state) {
this.store.publish(presentCctvPanel(state, enabled));
const liveIntent = enabled && !!activeCamera?.isVideo;
const liveIntent =
enabled && !!activeCamera?.isVideo && !activeCamera?.browserMediaUrl;
this.store.setLive(liveIntent);
if (this._cctvVideo) {
const visible =
@@ -261,8 +276,9 @@ export function _renderCctvState(state) {
}
if (this._cctvFrame && !liveIntent) {
const nextSrc = enabled ? activeCamera?.frameUrl : null;
const nextCameraId = enabled ? activeCamera?.id || '' : '';
const nextSrc = enabled && !isQuebecCamera ? activeCamera?.frameUrl : null;
const nextCameraId =
enabled && !isQuebecCamera ? activeCamera?.id || '' : '';
const cameraChanged = this._frame.cameraId !== nextCameraId;
const frameLoading = this._frame.loading;
// A same-camera refresh waits for the current image to settle. Replacing
+4 -4
View File
@@ -435,12 +435,12 @@ test('Cyber lower-left telemetry tracks the credit anchor with clearance for its
cyberStyles,
/#intel-hud\[data-variant='cyber'\] \.hud-bottom-left/,
);
const offset = telemetry.match(/bottom:\s*calc\(2vh \+ ([\d.]+)rem\);/);
const offset = telemetry.match(/bottom:\s*calc\(2vh \+ ([\d.]+)rem \+ var\(--world-timeline-lift, 0px\)\);/);
assert.ok(offset, 'telemetry must retain the attribution viewport anchor');
const credits = read('./styles/command-dock-trays.css');
const creditOffsets = [
...credits.matchAll(
/#cesium-credits\s*\{[^}]*bottom:\s*calc\(2vh \+ ([\d.]+)rem\);/g,
/#cesium-credits\s*\{[^}]*bottom:\s*calc\(2vh \+ ([\d.]+)rem \+ var\(--world-timeline-lift, 0px\)\);/g,
),
];
assert.ok(creditOffsets.length > 0);
@@ -734,7 +734,7 @@ test('the Display selector, voice schema and final stylesheet expose Cyber', ()
);
assert.match(
cyberStyles,
/#left-panel-stack \{[\s\S]*?top: var\(--cyber-left-rail-top\) !important;[\s\S]*?bottom: calc\(2vh \+ 13rem\);/,
/#left-panel-stack \{[\s\S]*?top: var\(--cyber-left-rail-top\) !important;[\s\S]*?bottom: calc\(2vh \+ 13rem \+ var\(--world-timeline-lift, 0px\)\);/,
);
assert.match(
cyberStyles,
@@ -789,7 +789,7 @@ test('the Display selector, voice schema and final stylesheet expose Cyber', ()
cyberStyles,
/#right-context-rail:has\(> \[data-panel-id\]:not\(\.collapsed, \[hidden\]\)\) \{\s*border-inline-end-color:/,
);
assert.match(cyberStyles, /bottom: calc\(2vh \+ 13rem\);/);
assert.match(cyberStyles, /bottom: calc\(2vh \+ 13rem \+ var\(--world-timeline-lift, 0px\)\);/);
assert.doesNotMatch(cyberStyles, /NAV 01 \/\/ COMMAND BUS \/\/ VIS 03/);
assert.match(cyberStyles, /data-layer-id='satellites'/);
assert.match(cyberStyles, /#search-toggle::before/);
+1 -1
View File
@@ -587,7 +587,7 @@ test('the phone shell keeps the required attribution visible', () => {
};
const lift = (block) =>
Number(
/bottom: calc\(var\(--mobile-tab-space\) \+ (\d+)px\)/.exec(block)?.[1],
/bottom: calc\(var\(--mobile-tab-space\) \+ (\d+)px \+ var\(--world-timeline-lift, 0px\)\)/.exec(block)?.[1],
);
const z = (block) => Number(/z-index: (\d+);/.exec(block)?.[1]);
const idleCredit = rule(
+2
View File
@@ -32,6 +32,7 @@ const LEFT_STACK_OBSTACLE_SELECTOR = [
'#gev-voice-control',
'#pp-toggles',
'#param-slider-panel',
'#world-timeline',
].join(', ');
/**
* Fixed UI regions that can occupy the right control lane. Runtime rectangle
@@ -59,6 +60,7 @@ const RIGHT_STACK_OBSTACLE_SELECTOR = [
'#cesium-credits .cesium-credit-textContainer',
'#command-dock',
'#gev-voice-control',
'#world-timeline',
].join(', ');
export class PanelLayoutController {
constructor({
+478
View File
@@ -0,0 +1,478 @@
import { fromDegrees } from '../geo/ellipsoid.js';
import { horizonFrom } from '../geo/horizon.js';
import { distance } from '../geo/vector.js';
import {
canvasOf,
findCamera,
findFrame,
findQuery,
} from '../render/rendererOf.js';
import { t } from '../i18n/index.js';
function isQuebecCamera(camera) {
return String(camera?.sourceKind || '').startsWith('quebec-');
}
function safeSourceUrl(value) {
try {
const url = new URL(String(value || ''));
return url.protocol === 'https:' && !url.username && !url.password
? url.href
: '';
} catch {
return '';
}
}
function safeMediaUrl(value) {
try {
const url = new URL(String(value || ''));
if (
url.protocol !== 'https:' ||
url.hostname !== 'www.quebec511.info' ||
url.username ||
url.password ||
url.pathname !== '/Carte/Fenetres/camera.ashx' ||
url.searchParams.get('format') !== 'mp4' ||
!/^\d+$/.test(url.searchParams.get('id') || '')
)
return '';
return url.href;
} catch {
return '';
}
}
function setMedia(video, url) {
const current = video.currentSrc || video.src;
if (current === url) return;
video.pause();
video.removeAttribute('src');
if (!url) {
video.load();
return;
}
video.src = url;
video.load();
}
/** Treat an interrupted play() (a pause or a new source) as no failure. */
function onPlayFailure(mark) {
return (error) => {
if (error?.name !== 'AbortError') mark();
};
}
/**
* Québec 511 serves a new clip at the same URL every few minutes, so a refresh
* adds a timestamp to get past the browser's media cache.
*/
function mediaRefreshUrl(value) {
const url = new URL(value);
url.searchParams.set('_', String(Date.now()));
return url.href;
}
/**
* Attach the active Québec source to a floating browser player and map
* preview. The browser contacts Québec 511 only after the viewer presses Play
* for that camera; selecting it (by click, auto-hop, a scene or voice) only
* shows its details and the play control.
*/
export function createQuebecCctvOverlay(viewer) {
if (!viewer || typeof document === 'undefined') return null;
const controller = new AbortController();
const { signal } = controller;
const panel = document.createElement('section');
panel.className = 'qci-panel';
panel.hidden = true;
panel.setAttribute('role', 'region');
panel.setAttribute('aria-label', t('CCTV camera'));
const header = document.createElement('header');
header.className = 'qci-header';
const title = document.createElement('strong');
const close = document.createElement('button');
close.type = 'button';
close.textContent = '×';
close.setAttribute('aria-label', t('Close camera preview'));
header.append(title, close);
const coordinates = document.createElement('p');
coordinates.className = 'qci-coordinates';
const credit = document.createElement('p');
credit.className = 'qci-credit';
const live = document.createElement('video');
live.className = 'qci-live';
live.controls = true;
live.muted = true;
live.autoplay = true;
live.loop = true;
live.playsInline = true;
live.setAttribute('aria-label', t('CCTV camera'));
const actions = document.createElement('div');
actions.className = 'qci-actions';
const play = document.createElement('button');
play.type = 'button';
play.className = 'qci-play';
play.textContent = t('Play');
const refresh = document.createElement('button');
refresh.type = 'button';
refresh.textContent = t('Refresh map still');
actions.append(play, refresh);
const note = document.createElement('p');
note.className = 'qci-note';
const sourceLink = document.createElement('a');
sourceLink.target = '_blank';
sourceLink.rel = 'noopener noreferrer';
sourceLink.textContent = t("Open this image on the provider's site");
panel.append(header, coordinates, credit, live, actions, note, sourceLink);
const marker = document.createElement('div');
marker.className = 'qci-marker';
marker.hidden = true;
const still = document.createElement('video');
still.className = 'qci-marker-still';
still.muted = true;
still.playsInline = true;
still.preload = 'none';
still.setAttribute('aria-hidden', 'true');
const markerLabel = document.createElement('span');
markerLabel.className = 'qci-marker-label';
marker.append(still, markerLabel);
document.body.append(panel, marker);
let selected = null;
let selectedPosition = null;
let closedWindowCameraId = null;
let selectedMediaUrl = '';
/** Camera id the viewer pressed Play for; media loads only for this one. */
let playingCameraId = null;
let mediaRefreshTimer = 0;
let removeRender = null;
let canvasRect = null;
let liveUnavailable = false;
let stillUnavailable = false;
function markerLabelText(camera, hasMedia) {
return hasMedia
? `${t('PREVIEW')} · ${camera.positionSource || camera.name}`
: Number.isFinite(camera.accuracyM) && camera.accuracyM > 0
? `${camera.name} · ±${Math.round(camera.accuracyM)} m`
: camera.name;
}
function markLiveUnavailable() {
liveUnavailable = true;
note.textContent = t('Source unavailable');
note.hidden = false;
}
function markStillUnavailable() {
stillUnavailable = true;
markerLabel.textContent = t('Source unavailable');
}
function startRender() {
if (!removeRender)
removeRender =
findFrame(viewer)?.on('postRender', () => updateMarker()) ?? null;
}
function stopRender() {
removeRender?.();
removeRender = null;
}
function stopMediaRefresh() {
window.clearInterval(mediaRefreshTimer);
mediaRefreshTimer = 0;
}
function startMediaRefresh() {
stopMediaRefresh();
if (!selectedMediaUrl) return;
mediaRefreshTimer = window.setInterval(
() => {
if (document.hidden || closedWindowCameraId === selected?.id) return;
setMedia(live, mediaRefreshUrl(selectedMediaUrl));
void live.play().catch(onPlayFailure(markLiveUnavailable));
refreshStill();
},
2 * 60 * 1000,
);
}
function refreshStill() {
if (!selectedMediaUrl || playingCameraId !== selected?.id) return;
setMedia(still, '');
setMedia(still, mediaRefreshUrl(selectedMediaUrl));
void still.play().catch(onPlayFailure(markStillUnavailable));
}
/** Load and play the selected camera's media: only from a Play click. */
function startPlayback() {
if (!selected || !selectedMediaUrl) return;
playingCameraId = selected.id;
liveUnavailable = false;
stillUnavailable = false;
play.hidden = true;
refresh.hidden = false;
live.hidden = false;
still.hidden = false;
marker.classList.remove('qci-marker-link-only');
note.textContent = t(
'The map still uses a separate request and may show a different moment.',
);
note.hidden = false;
markerLabel.textContent = markerLabelText(selected, true);
setMedia(live, selectedMediaUrl);
setMedia(still, selectedMediaUrl);
void live.play().catch(onPlayFailure(markLiveUnavailable));
void still.play().catch(onPlayFailure(markStillUnavailable));
startMediaRefresh();
}
function setCamera(camera, { reselected = false } = {}) {
if (!isQuebecCamera(camera)) {
selected = null;
selectedPosition = null;
closedWindowCameraId = null;
selectedMediaUrl = '';
playingCameraId = null;
liveUnavailable = false;
stillUnavailable = false;
stopMediaRefresh();
stopRender();
panel.hidden = true;
marker.hidden = true;
setMedia(live, '');
setMedia(still, '');
return;
}
const changed = selected?.id !== camera.id;
if (changed || reselected) closedWindowCameraId = null;
selected = camera;
startRender();
selectedPosition = fromDegrees(
Number(camera.lon),
Number(camera.lat),
Number(camera.elevationM) || 10,
);
if (closedWindowCameraId === camera.id && !reselected) {
panel.hidden = true;
updateMarker();
return;
}
const mediaUrl = safeMediaUrl(camera.browserMediaUrl);
const sourceUrl = safeSourceUrl(camera.sourceUrl);
if (changed || mediaUrl !== selectedMediaUrl) {
liveUnavailable = false;
stillUnavailable = false;
playingCameraId = null;
}
const playing = Boolean(mediaUrl) && playingCameraId === camera.id;
title.textContent = camera.name || t('CCTV camera');
coordinates.textContent = [
`${Number(camera.lat).toFixed(5)}, ${Number(camera.lon).toFixed(5)}`,
Number.isFinite(camera.accuracyM) && camera.accuracyM > 0
? `±${Math.round(camera.accuracyM)} m`
: '',
camera.positionSource || '',
]
.filter(Boolean)
.join(' · ');
credit.textContent = camera.credit || camera.provider || '';
credit.hidden = !credit.textContent;
live.hidden = !playing;
play.hidden = !mediaUrl || playing;
refresh.hidden = !playing;
actions.hidden = !mediaUrl;
note.hidden = !mediaUrl;
note.textContent = mediaUrl
? !playing
? t('Video plays from Québec 511, which sees your IP address.')
: liveUnavailable
? t('Source unavailable')
: t(
'The map still uses a separate request and may show a different moment.',
)
: sourceUrl
? ''
: t('Source unavailable');
note.hidden = !note.textContent;
sourceLink.href = sourceUrl || '#';
sourceLink.hidden = !sourceUrl;
markerLabel.textContent = stillUnavailable
? t('Source unavailable')
: markerLabelText(camera, playing);
marker.classList.toggle('qci-marker-link-only', !playing);
still.hidden = !playing;
panel.hidden = false;
if (changed || mediaUrl !== selectedMediaUrl) {
selectedMediaUrl = mediaUrl;
// A new camera never inherits playback: the browser stays off 511
// until the viewer presses Play for it.
stopMediaRefresh();
setMedia(live, '');
setMedia(still, '');
} else if (reselected && playing) {
if (live.error || live.networkState === 3 || live.readyState < 2) {
setMedia(live, mediaRefreshUrl(mediaUrl));
}
if (live.paused)
void live.play().catch(onPlayFailure(markLiveUnavailable));
startMediaRefresh();
if (still.error || still.networkState === 3 || still.readyState < 2)
refreshStill();
}
updateMarker();
}
function updateMarker() {
if (!selected || !selectedPosition) {
marker.hidden = true;
return;
}
const canvas = canvasOf(viewer);
const eye = findCamera(viewer)?.pose().position;
const point = findQuery(viewer)?.project(selectedPosition) ?? null;
const visible =
point &&
canvas &&
eye &&
horizonFrom(eye).isPointVisible(selectedPosition) &&
point.x >= 0 &&
point.y >= 0 &&
point.x <= canvas.clientWidth &&
point.y <= canvas.clientHeight;
marker.hidden = !visible;
if (!visible) return;
// Measured once per resize or scroll, not every frame, so the per-frame
// style writes never force a layout.
canvasRect ||= canvas.getBoundingClientRect();
const rect = canvasRect;
marker.style.left = `${rect.left + point.x}px`;
marker.style.top = `${rect.top + point.y}px`;
const range = distance(eye, selectedPosition);
marker.style.setProperty(
'--qci-scale',
String(Math.min(1, 600 / Math.max(1, range))),
);
}
still.addEventListener(
'loadeddata',
() => {
stillUnavailable = false;
if (selected)
markerLabel.textContent = markerLabelText(
selected,
Boolean(selectedMediaUrl),
);
still.pause();
},
{ signal },
);
still.addEventListener('error', markStillUnavailable, { signal });
live.addEventListener('error', markLiveUnavailable, { signal });
live.addEventListener(
'loadeddata',
() => {
liveUnavailable = false;
note.textContent = t(
'The map still uses a separate request and may show a different moment.',
);
note.hidden = false;
},
{ signal },
);
refresh.addEventListener('click', refreshStill, { signal });
play.addEventListener('click', startPlayback, { signal });
const resetCanvasRect = () => {
canvasRect = null;
};
window.addEventListener('resize', resetCanvasRect, { signal });
window.addEventListener('scroll', resetCanvasRect, {
signal,
capture: true,
passive: true,
});
panel.addEventListener(
'keydown',
(event) => {
if (event.key === 'Escape') close.click();
},
{ signal },
);
close.addEventListener(
'click',
() => {
closedWindowCameraId = selected?.id || null;
panel.hidden = true;
live.pause();
stopMediaRefresh();
// The floating player closes independently; keep the paused map still.
updateMarker();
},
{ signal },
);
header.addEventListener(
'pointerdown',
(event) => {
if (event.target.closest('button')) return;
const rect = panel.getBoundingClientRect();
const offsetX = event.clientX - rect.left;
const offsetY = event.clientY - rect.top;
header.setPointerCapture(event.pointerId);
const move = (moveEvent) => {
panel.style.left = `${Math.max(0, Math.min(window.innerWidth - panel.offsetWidth, moveEvent.clientX - offsetX))}px`;
panel.style.top = `${Math.max(0, Math.min(window.innerHeight - panel.offsetHeight, moveEvent.clientY - offsetY))}px`;
panel.style.right = 'auto';
};
const stop = () => {
header.removeEventListener('pointermove', move);
header.removeEventListener('pointerup', stop);
header.removeEventListener('pointercancel', stop);
};
header.addEventListener('pointermove', move, { signal });
header.addEventListener('pointerup', stop, { once: true, signal });
header.addEventListener('pointercancel', stop, { once: true, signal });
},
{ signal },
);
document.addEventListener(
'visibilitychange',
() => {
if (!selectedMediaUrl || playingCameraId !== selected?.id) return;
if (document.hidden) {
live.pause();
still.pause();
} else if (closedWindowCameraId !== selected?.id) {
void live.play().catch(onPlayFailure(markLiveUnavailable));
refreshStill();
}
},
{ signal },
);
return {
setCamera,
dispose() {
controller.abort();
stopMediaRefresh();
stopRender();
setMedia(live, '');
setMedia(still, '');
panel.remove();
marker.remove();
selected = null;
selectedPosition = null;
},
};
}
+205
View File
@@ -0,0 +1,205 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { Window } from 'happy-dom';
import { fromDegrees } from '../geo/ellipsoid.js';
import { bindFakeDraw } from '../testSupport/fakeDrawPort.mjs';
import { fakeCameraPort } from '../testSupport/fakeCameraPort.mjs';
import { createQuebecCctvOverlay } from './quebecCctvOverlay.js';
const MEDIA_URL =
'https://www.quebec511.info/Carte/Fenetres/camera.ashx?id=3735&format=mp4';
const CAMERA = Object.freeze({
id: 'qc-511-3735',
sourceKind: 'quebec-511-browser',
name: 'Route 136 at rue Panet',
lat: 45.51651,
lon: -73.5502,
positionSource: 'MTQ georeferenced point',
browserMediaUrl: MEDIA_URL,
sourceUrl:
'https://www.quebec511.info/Carte/Fenetres/FenetreVideo.html?id=3735',
});
/**
* Mount the overlay in a happy-dom window with recorded media loads, timers
* and postRender listeners. `play` decides what each play() returns.
*/
function mountOverlay(t, { play = () => Promise.resolve() } = {}) {
const window = new Window({ url: 'http://localhost:4173/' });
const previousWindow = globalThis.window;
const previousDocument = globalThis.document;
globalThis.window = window;
globalThis.document = window.document;
const loads = [];
window.HTMLMediaElement.prototype.load = function () {
if (this.getAttribute('src')) loads.push(this.getAttribute('src'));
};
window.HTMLMediaElement.prototype.play = function () {
return play(this);
};
window.HTMLMediaElement.prototype.pause = function () {};
const intervals = new Map();
let nextTimer = 1;
window.setInterval = (fn) => {
const id = nextTimer++;
intervals.set(id, fn);
return id;
};
window.clearInterval = (id) => intervals.delete(id);
const renderListeners = new Set();
const viewer = { canvas: { clientWidth: 800, clientHeight: 600 } };
const { unbind } = bindFakeDraw(viewer, {
camera: fakeCameraPort({
pose: { position: fromDegrees(-73.5502, 45.51651, 1000) },
}).port,
query: { project: () => null },
frame: {
on(phase, fn) {
if (phase !== 'postRender') return () => {};
renderListeners.add(fn);
return () => renderListeners.delete(fn);
},
requestRender() {},
},
});
t.after(unbind);
const overlay = createQuebecCctvOverlay(viewer);
t.after(() => {
overlay?.dispose();
globalThis.window = previousWindow;
globalThis.document = previousDocument;
window.close();
});
const [live, still] = window.document.querySelectorAll('video');
return {
window,
overlay,
loads,
intervals,
renderListeners,
live,
still,
note: () => window.document.querySelector('.qci-note').textContent,
label: () => window.document.querySelector('.qci-marker-label').textContent,
playButton: () => window.document.querySelector('.qci-play'),
};
}
test('selecting a Québec camera contacts Québec 511 only after Play', (t) => {
const ui = mountOverlay(t);
assert.equal(ui.renderListeners.size, 0, 'no per-frame work before a camera');
ui.overlay.setCamera(CAMERA);
assert.deepEqual(ui.loads, [], 'selection alone loads no 511 media');
assert.equal(ui.intervals.size, 0, 'and starts no refresh timer');
assert.equal(ui.playButton().hidden, false);
assert.match(ui.note(), /sees your IP address/);
assert.equal(ui.renderListeners.size, 1);
ui.playButton().click();
assert.deepEqual(
ui.loads,
[MEDIA_URL, MEDIA_URL],
'live player and map still',
);
assert.equal(ui.playButton().hidden, true);
assert.equal(ui.intervals.size, 1);
// A different camera never inherits playback.
ui.loads.length = 0;
ui.overlay.setCamera({
...CAMERA,
id: 'qc-511-4103',
browserMediaUrl: MEDIA_URL.replace('3735', '4103'),
});
assert.deepEqual(ui.loads, []);
assert.equal(ui.intervals.size, 0);
assert.equal(ui.playButton().hidden, false);
ui.overlay.setCamera(null);
assert.equal(
ui.renderListeners.size,
0,
'deselect drops the per-frame listener',
);
});
test('a camera without browser media shows only its provider link', (t) => {
const ui = mountOverlay(t);
ui.overlay.setCamera({ ...CAMERA, browserMediaUrl: '' });
assert.equal(ui.playButton().hidden, true);
assert.deepEqual(ui.loads, []);
const link = ui.window.document.querySelector('.qci-panel a');
assert.equal(link.hidden, false);
assert.equal(link.href, CAMERA.sourceUrl);
});
test('routine same-camera updates keep Québec feed errors visible until recovery', (t) => {
const ui = mountOverlay(t);
ui.overlay.setCamera(CAMERA);
ui.playButton().click();
ui.live.dispatchEvent(new ui.window.Event('error'));
ui.still.dispatchEvent(new ui.window.Event('error'));
ui.overlay.setCamera({ ...CAMERA });
assert.equal(ui.note(), 'Source unavailable');
assert.equal(ui.label(), 'Source unavailable');
ui.live.dispatchEvent(new ui.window.Event('loadeddata'));
ui.still.dispatchEvent(new ui.window.Event('loadeddata'));
assert.match(ui.note(), /separate request/);
assert.match(ui.label(), /^PREVIEW ·/);
});
test('an interrupted play() is not reported as an unavailable source', async (t) => {
const abort = () =>
Promise.reject(new DOMException('interrupted by pause()', 'AbortError'));
const ui = mountOverlay(t, { play: abort });
ui.overlay.setCamera(CAMERA);
ui.playButton().click();
await new Promise((resolve) => setImmediate(resolve));
assert.match(ui.note(), /separate request/);
assert.match(ui.label(), /^PREVIEW ·/);
});
test('a real play() failure is reported', async (t) => {
const fail = () =>
Promise.reject(
new DOMException('no supported source', 'NotSupportedError'),
);
const ui = mountOverlay(t, { play: fail });
ui.overlay.setCamera(CAMERA);
ui.playButton().click();
await new Promise((resolve) => setImmediate(resolve));
assert.equal(ui.note(), 'Source unavailable');
});
test('the refresh timer reloads with a cache-buster, skips hidden tabs, and stops on dispose', (t) => {
const ui = mountOverlay(t);
ui.overlay.setCamera(CAMERA);
ui.playButton().click();
const [refresh] = ui.intervals.values();
ui.loads.length = 0;
Object.defineProperty(ui.window.document, 'hidden', {
configurable: true,
get: () => true,
});
refresh();
assert.deepEqual(ui.loads, [], 'a hidden tab does not refresh');
Object.defineProperty(ui.window.document, 'hidden', {
configurable: true,
get: () => false,
});
refresh();
assert.equal(ui.loads.length, 2);
for (const src of ui.loads) assert.match(src, /[?&]_=\d+$/);
ui.overlay.dispose();
assert.equal(ui.intervals.size, 0);
assert.equal(ui.renderListeners.size, 0);
assert.equal(ui.window.document.querySelector('.qci-panel'), null);
});
+12
View File
@@ -5,6 +5,16 @@ import { t, msg, formatDate } from '../i18n/index.js';
import { SHARE_VIEW_ENTITY_KINDS } from '../share/follow.js';
import { UiLifetime } from './uiLifetime.js';
import { followedOf } from '../data/followed.js';
import { isWorldTime, worldClock } from '../time/worldClock.js';
// A link made away from live opens at its world time, paused. One without a
// world time leaves the clock as it is: a page opens live, and Back or Forward
// through long-form hashes (which never carry one) does not stop a replay.
function applySharedWorldTime(state) {
if (!isWorldTime(state?.worldTime)) return;
worldClock.pause();
worldClock.seek(state.worldTime);
}
/** How long a shared vessel may take to appear in the vessel feed. */
export const SHARED_VESSEL_WAIT_MS = 120_000;
@@ -147,6 +157,7 @@ export class ShareRestoration {
: Promise.resolve({ status: 'not-requested', share: null, layers: [] });
if (savedState) {
this._hasShareState = true;
applySharedWorldTime(savedState);
// Reserve camera authority now; the delayed mesh-friendly flight may
// run only if no newer user, voice, or tracking navigation has won.
this._initialShareNavigationGeneration =
@@ -302,6 +313,7 @@ export class ShareRestoration {
layers: [],
});
this._initialShareState = state;
applySharedWorldTime(state);
this._initialShareSelectionSuperseded = false;
this._hasShareState = true;
this._navigatedShareRestoreActive = true;
+166
View File
@@ -0,0 +1,166 @@
import { defineStore } from 'pinia';
import { onScopeDispose, shallowRef } from 'vue';
import { worldClock } from '../../time/worldClock.js';
/** How often a shown timeline moves its readout and its end on with now. */
const LIVE_TICK_MS = 1000;
/** A scrub this close to now, as a share of the track, is a scrub to live. */
const LIVE_EDGE = 0.005;
/** The least that counts as at now, past the readout's own second. */
const LIVE_EDGE_MS = 5000;
/** The speeds play offers, in world ms per real ms. */
export const WORLD_TIME_SPEEDS = Object.freeze({
real: 1,
minute: 60,
hour: 3_600,
day: 86_400,
week: 604_800,
});
/**
* The world clock as the timeline shows it: `{live, playing, stepping,
* 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. 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.
*/
export const useWorldTimeStore = defineStore('gev-world-time', () => {
// The time the layers cover, reaching to now.
const reach = () => {
const coverage = worldClock.coverage();
if (!coverage) return null;
const now = worldClock.wallNow();
return {
start: Math.min(coverage.start, now),
end: Math.max(coverage.end, now),
marks: coverage.marks,
};
};
const spanOf = (state) => {
if (!state.supported) return null;
const covered = reach();
if (!covered) return null;
return Object.freeze({
start: Math.min(covered.start, state.timeMs),
end: Math.max(covered.end, state.timeMs),
marks: covered.marks,
});
};
const nearNow = (ms, length) =>
Math.abs(ms - worldClock.wallNow()) <=
Math.max(LIVE_EDGE_MS, length * LIVE_EDGE);
// Whether the track ends at now (and moves on with it), not past it.
const endsAtNow = (covered) =>
covered.end - worldClock.wallNow() <= LIVE_EDGE_MS;
// Play stops at the end of the track: at now it goes live, past now (a
// satellite's future) it holds there.
let stopping = false;
const stopAtEnd = (state) => {
if (stopping || !state.playing || state.live || !state.supported)
return false;
const covered = reach();
if (!covered || state.timeMs < covered.end) return false;
stopping = true;
try {
if (endsAtNow(covered)) worldClock.goLive();
else {
// Back to the end first, so nothing hears the overshoot as paused.
worldClock.seek(covered.end);
worldClock.pause();
worldClock.seek(covered.end);
}
} finally {
stopping = false;
}
return true;
};
const read = (state = worldClock.getState()) =>
Object.freeze({
live: state.live,
playing: state.playing,
stepping: state.stepping,
buffering: state.buffering,
timeMs: state.timeMs,
supported: state.supported,
span: spanOf(state),
});
const time = shallowRef(read());
const speed = shallowRef('real');
const rate = () => WORLD_TIME_SPEEDS[speed.value];
let ticker = null;
const syncTicker = () => {
// Playing, the clock tells of the time itself.
const ticking = Boolean(time.value.span) && !time.value.playing;
if (ticking && ticker === null)
ticker = setInterval(() => {
time.value = read();
}, LIVE_TICK_MS);
else if (!ticking && ticker !== null) {
clearInterval(ticker);
ticker = null;
}
};
const unsubscribe = worldClock.subscribe((state) => {
if (stopAtEnd(state)) return;
time.value = read(state);
syncTicker();
});
syncTicker();
onScopeDispose(() => {
unsubscribe();
if (ticker !== null) clearInterval(ticker);
ticker = null;
});
return {
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, 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;
if (playing) return worldClock.pause();
const covered = reach();
if (span && covered && (live || timeMs >= covered.end))
worldClock.seek(span.start);
worldClock.play({ rate: rate(), continuous: true });
},
speed,
/**
* 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;
speed.value = next;
const { playing, stepping } = worldClock.getState();
if (!playing) return;
if (!stepping) return worldClock.setRate(rate());
worldClock.pause();
worldClock.play({ rate: rate(), continuous: true });
},
goLive: () => worldClock.goLive(),
/**
* Scrub to `ms`: playback stops where the hand puts it; at now, live.
* How near now counts as now goes by `length`, the stretch the track
* shows, all of the span unless it is zoomed.
*/
scrub(ms, length) {
const span = time.value.span;
length ??= span ? span.end - span.start : 0;
if (nearNow(ms, length)) {
worldClock.goLive();
return;
}
worldClock.pause();
worldClock.seek(ms);
},
};
});
+2 -2
View File
@@ -900,7 +900,7 @@ html:not([lang='en']) .cockpit-roll-token.is-separator {
position: fixed;
z-index: 146;
right: 36px;
bottom: calc(2vh + 4.5rem);
bottom: calc(2vh + 4.5rem + var(--world-timeline-lift, 0px));
display: grid;
gap: 6px;
}
@@ -2079,7 +2079,7 @@ body.cockpit-mode #intel-hud .hud-right-edge {
@media (max-width: 760px) {
#view-switcher {
right: 16px;
bottom: 16px;
bottom: calc(16px + var(--world-timeline-lift, 0px));
}
body.cockpit-mode #view-switcher {
right: auto;
+3 -3
View File
@@ -377,15 +377,15 @@
/* Compact dock clearance keeps the reference-like low profile. */
body:not(.ui-clean-view):not(.recording-mode) #cesium-credits {
bottom: calc(2vh + 4.7rem);
bottom: calc(2vh + 4.7rem + var(--world-timeline-lift, 0px));
}
#intel-hud[data-variant='minimal'] .hud-bottom-left {
bottom: calc(2vh + 5.4rem);
bottom: calc(2vh + 5.4rem + var(--world-timeline-lift, 0px));
}
#intel-hud[data-variant='minimal'] .hud-bottom-bar {
bottom: calc(2vh + 8.9rem);
bottom: calc(2vh + 8.9rem + var(--world-timeline-lift, 0px));
}
@media (max-width: 900px) {
+6 -6
View File
@@ -455,7 +455,7 @@ body:not(.ui-clean-view):not(.recording-mode):has(
)
#cesium-credits {
right: auto;
bottom: calc(2vh + 5rem);
bottom: calc(2vh + 5rem + var(--world-timeline-lift, 0px));
left: 1.5rem;
width: auto !important;
max-width: calc(100vw - 3rem);
@@ -464,21 +464,21 @@ body:not(.ui-clean-view):not(.recording-mode):has(
#intel-hud[data-variant='tactical'] .hud-bottom-left,
#intel-hud[data-variant='tactical'] .hud-bottom-right {
bottom: calc(2vh + 6.5rem);
bottom: calc(2vh + 6.5rem + var(--world-timeline-lift, 0px));
}
#intel-hud[data-variant='minimal'] .hud-bottom-left {
bottom: calc(2vh + 5.4rem);
bottom: calc(2vh + 5.4rem + var(--world-timeline-lift, 0px));
}
:root[data-scope-mask='off']
#intel-hud[data-variant='minimal']
.hud-bottom-left {
bottom: calc(2vh + 6.5rem);
bottom: calc(2vh + 6.5rem + var(--world-timeline-lift, 0px));
}
#intel-hud[data-variant='minimal'] .hud-bottom-bar {
bottom: calc(2vh + 9rem);
bottom: calc(2vh + 9rem + var(--world-timeline-lift, 0px));
}
@media (max-width: 900px) {
@@ -487,7 +487,7 @@ body:not(.ui-clean-view):not(.recording-mode):has(
#intel-hud[data-variant='minimal'].active
)
#cesium-credits {
bottom: calc(2vh + 5rem);
bottom: calc(2vh + 5rem + var(--world-timeline-lift, 0px));
left: 0.75rem;
max-width: calc(100vw - 1.5rem);
}
+9 -8
View File
@@ -2,7 +2,8 @@
#command-dock {
position: fixed;
right: auto;
bottom: 2vh;
/* Above the world timeline while it shows (world-timeline.css). */
bottom: calc(2vh + var(--world-timeline-lift, 0px));
left: 50%;
z-index: 145;
display: grid;
@@ -216,7 +217,7 @@
/* Keep required map attribution clear of the full-width command surface. */
body:not(.ui-clean-view):not(.recording-mode) #cesium-credits {
bottom: calc(2vh + 7rem);
bottom: calc(2vh + 7rem + var(--world-timeline-lift, 0px));
}
body:not(.ui-clean-view):not(.recording-mode):has(
@@ -244,11 +245,11 @@ body.recording-mode #cesium-credits {
}
#intel-hud[data-variant='minimal'] .hud-bottom-left {
bottom: calc(2vh + 7.5rem);
bottom: calc(2vh + 7.5rem + var(--world-timeline-lift, 0px));
}
#intel-hud[data-variant='minimal'] .hud-bottom-bar {
bottom: calc(2vh + 11.5rem);
bottom: calc(2vh + 11.5rem + var(--world-timeline-lift, 0px));
}
@media (max-width: 980px) {
@@ -275,21 +276,21 @@ body.recording-mode #cesium-credits {
}
body:not(.ui-clean-view):not(.recording-mode) #cesium-credits {
bottom: calc(2vh + 9.5rem);
bottom: calc(2vh + 9.5rem + var(--world-timeline-lift, 0px));
}
#intel-hud[data-variant='minimal'] .hud-bottom-left {
bottom: calc(2vh + 12rem);
bottom: calc(2vh + 12rem + var(--world-timeline-lift, 0px));
}
#intel-hud[data-variant='minimal'] .hud-bottom-bar {
bottom: calc(2vh + 16rem);
bottom: calc(2vh + 16rem + var(--world-timeline-lift, 0px));
}
}
@media (max-width: 720px) {
#command-dock {
bottom: 8px;
bottom: calc(8px + var(--world-timeline-lift, 0px));
}
#command-dock .location-search-wrap {
+5 -5
View File
@@ -1590,7 +1590,7 @@
}
#intel-hud[data-variant='cyber'] .hud-bottom-bar {
bottom: calc(2vh + 9.8rem);
bottom: calc(2vh + 9.8rem + var(--world-timeline-lift, 0px));
width: min(48vw, 680px);
}
@@ -1601,13 +1601,13 @@
#intel-hud[data-variant='cyber'] .hud-bottom-left,
#intel-hud[data-variant='cyber'] .hud-bottom-right {
bottom: calc(2vh + 6.5rem);
bottom: calc(2vh + 6.5rem + var(--world-timeline-lift, 0px));
}
/* Attribution's logo row extends above its text baseline. Reserve the whole
row plus a gap above the dock-relative 2vh + 5rem credit position. */
#intel-hud[data-variant='cyber'] .hud-bottom-left {
bottom: calc(2vh + 7.75rem);
bottom: calc(2vh + 7.75rem + var(--world-timeline-lift, 0px));
}
#intel-hud[data-variant='cyber'] .hud-corner {
@@ -1652,7 +1652,7 @@
below its 650px threshold. Keep the left rail inside the same telemetry
and attribution-safe floor while its panel bodies take over scrolling. */
:root[data-ui-theme='cyber'] #left-panel-stack {
bottom: calc(2vh + 13rem);
bottom: calc(2vh + 13rem + var(--world-timeline-lift, 0px));
}
}
@@ -1675,7 +1675,7 @@
/* The stack holds still, so its rail needs no offset (leftPanelRail.js). */
--panel-stack-top-pinned: 1;
top: var(--cyber-left-rail-top) !important;
bottom: calc(2vh + 13rem);
bottom: calc(2vh + 13rem + var(--world-timeline-lift, 0px));
inset-inline-start: calc(54px + var(--panel-rail-clearance));
width: 300px;
padding-inline-start: 10px;
+3 -3
View File
@@ -200,7 +200,7 @@ body.mobile-shell #command-dock {
/* The dock's tray rules size voice by this basis; a column makes it a height. */
--dock-voice-width: auto;
top: auto;
bottom: calc(var(--mobile-tab-space) + 10px);
bottom: calc(var(--mobile-tab-space) + 10px + var(--world-timeline-lift, 0px));
display: flex;
flex-direction: column;
align-items: center;
@@ -380,7 +380,7 @@ body.mobile-shell #command-dock #gev-voice-control {
body.mobile-shell:not(.recording-mode):not(.cockpit-mode):not(.ui-clean-view)
#cesium-credits {
right: auto;
bottom: calc(var(--mobile-tab-space) + 106px) !important;
bottom: calc(var(--mobile-tab-space) + 106px + var(--world-timeline-lift, 0px)) !important;
left: 10px;
/* With the base rule's nowrap the credits run off the right edge, and a
max-width alone wrapped them into a narrow column: the line needs wrapping
@@ -407,7 +407,7 @@ body.mobile-shell[data-mobile-sheet]:not(.recording-mode):not(
/* The view switcher clears the tab bar and the voice bar, opposite the credit. */
body.mobile-shell:not(.cockpit-mode) #view-switcher {
right: 12px;
bottom: calc(var(--mobile-tab-space) + 106px);
bottom: calc(var(--mobile-tab-space) + 106px + var(--world-timeline-lift, 0px));
}
body.mobile-shell #corner-actions {
+98
View File
@@ -0,0 +1,98 @@
.qci-panel {
position: fixed;
z-index: 2000;
top: 80px;
right: 24px;
width: min(360px, calc(100vw - 32px));
overflow: hidden;
border: 1px solid #3eabbc;
border-radius: 8px;
background: #071117;
color: #e6f8fb;
box-shadow: 0 12px 36px #000a;
font: 12px/1.4 sans-serif;
}
.qci-panel[hidden],
.qci-live[hidden],
.qci-note[hidden],
.qci-panel a[hidden],
.qci-marker[hidden],
.qci-marker-still[hidden] {
display: none;
}
.qci-header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 8px 10px;
cursor: move;
touch-action: none;
}
.qci-panel button {
border: 1px solid #43818d;
border-radius: 4px;
padding: 4px 8px;
background: #102830;
color: inherit;
cursor: pointer;
}
.qci-panel button:focus-visible {
outline: 2px solid #82e9f7;
outline-offset: 2px;
}
.qci-coordinates,
.qci-credit,
.qci-note {
margin: 0 10px 8px;
color: #a9c5ca;
font: 10px/1.45 'Cascadia Code', Consolas, monospace;
}
.qci-credit {
color: #7fc7d2;
}
.qci-live {
display: block;
width: 100%;
aspect-ratio: 16 / 9;
background: #000;
}
.qci-actions {
display: flex;
gap: 8px;
padding: 8px 10px 0;
}
.qci-actions[hidden] {
display: none;
}
.qci-panel a {
display: inline-block;
margin: 0 10px 10px;
color: #82e9f7;
}
.qci-marker {
position: fixed;
z-index: 500;
width: 160px;
transform: translate(-50%, -100%) scale(var(--qci-scale, 1));
transform-origin: 50% 100%;
pointer-events: none;
padding: 3px;
border: 1px solid #65d7e7;
background: #071117;
color: #d8f9ff;
font: 10px/1.3 sans-serif;
}
.qci-marker-still {
display: block;
width: 100%;
aspect-ratio: 16 / 9;
background: #000;
}
.qci-marker-label {
display: block;
padding: 3px;
}
.qci-marker-link-only {
width: max-content;
max-width: 220px;
}
+1 -1
View File
@@ -177,7 +177,7 @@
drawn straight over the notice. Track the credit's own anchor instead
and the 12px of clear air holds regardless of height; the rail already
scrolls (overflow-y below), so it loses reach, not content. */
bottom: calc(2vh + 7.5rem);
bottom: calc(2vh + 7.5rem + var(--world-timeline-lift, 0px));
left: 16px;
width: auto;
max-height: none;
+1 -1
View File
@@ -390,7 +390,7 @@ html:not([lang='en']) #global-loading-detail {
/* ── Toast Notification ──────────────────────── */
#toast {
position: fixed;
bottom: 100px;
bottom: calc(100px + var(--world-timeline-lift, 0px));
left: 50%;
transform: translateX(-50%) translateY(20px);
z-index: 200;
+325
View File
@@ -0,0 +1,325 @@
/* ── World timeline ─────────────────────────── */
/* Shown while a layer with time to show is on, centred along the bottom of
the screen; the command dock and what sits above it rise by its height. */
:root {
--world-timeline-lift: 0px;
}
/* The bar and the time's bubble over its handle. */
body:has(#world-timeline) {
--world-timeline-lift: 66px;
}
/* Clean view, recording and the cockpit put the dock away; the bar goes too. */
body.ui-clean-view,
body.recording-mode,
body.cockpit-mode {
--world-timeline-lift: 0px !important;
}
body.ui-clean-view #world-timeline,
body.recording-mode #world-timeline,
body.cockpit-mode #world-timeline {
display: none;
}
/* Time runs left to right in every language, so the handle, the fill, the
ticks and the bubble agree under a right-to-left page too. */
#world-timeline {
direction: ltr;
position: fixed;
bottom: 2vh;
left: 50%;
z-index: 146;
display: flex;
align-items: center;
gap: 10px;
width: min(820px, calc(100vw - 24px));
height: 42px;
box-sizing: border-box;
padding: 4px 6px;
border: 1px solid var(--glass-border);
border-radius: 10px;
background: var(--glass-bg);
backdrop-filter: blur(24px) saturate(1.4);
-webkit-backdrop-filter: blur(24px) saturate(1.4);
box-shadow: 0 8px 28px rgba(0, 0, 0, 0.5);
transform: translateX(-50%);
}
#world-timeline .world-timeline-play,
#world-timeline .world-timeline-live {
display: inline-flex;
align-items: center;
justify-content: center;
min-width: 32px;
height: 32px;
padding: 0 8px;
border: 1px solid rgba(123, 189, 211, 0.28);
border-radius: 8px;
background: rgba(0, 212, 255, 0.08);
color: var(--text-primary);
font: inherit;
cursor: pointer;
}
#world-timeline .world-timeline-play:hover,
#world-timeline .world-timeline-live:hover {
background: rgba(0, 212, 255, 0.18);
}
#world-timeline .world-timeline-live.is-live {
border-color: rgba(0, 212, 255, 0.6);
background: rgba(0, 212, 255, 0.2);
color: var(--accent);
cursor: default;
}
#world-timeline .world-timeline-live {
font-size: 11px;
letter-spacing: 0.08em;
text-transform: uppercase;
}
#world-timeline .world-timeline-speed {
flex: none;
}
/* The time rides over the handle. It slides across itself as the handle
crosses the track (its start at the handle at the track's start, its end at
the end), so however wide its date it stays within the track. */
#world-timeline .world-timeline-time {
--inset: 0px;
position: absolute;
bottom: calc(100% + 6px);
left: calc(var(--inset) + (100% - var(--inset)) * var(--at));
padding: 2px 8px;
border: 1px solid rgba(0, 212, 255, 0.4);
border-radius: 6px;
background: var(--glass-bg);
color: var(--text-primary);
font-family: var(--font-mono);
font-size: 11px;
font-variant-numeric: tabular-nums;
white-space: nowrap;
transform: translateX(calc(var(--at) * -100%));
pointer-events: none;
}
/* Playing, held while a layer loads the time's data: a spinner by the time. */
#world-timeline .world-timeline-time.is-waiting {
display: inline-flex;
align-items: center;
gap: 6px;
}
#world-timeline .world-timeline-spinner {
width: 10px;
height: 10px;
border: 2px solid rgba(255, 255, 255, 0.2);
border-top-color: var(--accent);
border-radius: 50%;
animation: world-timeline-spin 0.9s linear infinite;
}
@keyframes world-timeline-spin {
to {
transform: rotate(360deg);
}
}
@media (prefers-reduced-motion: reduce) {
#world-timeline .world-timeline-spinner {
animation: none;
border-color: var(--accent);
}
}
/* The track: ticks for each launch or frame, the elapsed fill, and a native
range input on top for dragging and the keyboard. */
#world-timeline .world-timeline-track {
position: relative;
/* Two fingers pinch the track, not the page. */
touch-action: none;
flex: 1 1 auto;
cursor: pointer;
min-width: 80px;
height: 24px;
}
/* Zoomed, the track's ends fade, as it goes on past them. */
#world-timeline .world-timeline-track.is-zoomed::before {
background: linear-gradient(
90deg,
transparent,
rgba(123, 189, 211, 0.22) 12px,
rgba(123, 189, 211, 0.22) calc(100% - 12px),
transparent
);
}
#world-timeline .world-timeline-track::before {
position: absolute;
top: 50%;
right: 0;
left: 0;
height: 4px;
border-radius: 2px;
background: rgba(123, 189, 211, 0.22);
content: '';
transform: translateY(-50%);
}
#world-timeline .world-timeline-fill {
position: absolute;
top: 50%;
left: 0;
height: 4px;
border-radius: 2px;
background: var(--accent);
opacity: 0.7;
transform: translateY(-50%);
pointer-events: none;
}
#world-timeline .world-timeline-tick {
position: absolute;
top: 50%;
width: 2px;
height: 12px;
margin-left: -1px;
border-radius: 1px;
background: rgba(0, 212, 255, 0.75);
transform: translateY(-50%);
pointer-events: none;
}
/* Zoomed, the track drags along. */
#world-timeline .world-timeline-track.is-zoomed {
cursor: grab;
}
#world-timeline .world-timeline-track.is-zoomed:active {
cursor: grabbing;
}
/* Only the handle takes the pointer as a slider; the track around it takes
taps, drags and pinches itself. */
#world-timeline .world-timeline-scrub {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
margin: 0;
background: transparent;
appearance: none;
pointer-events: none;
}
#world-timeline .world-timeline-scrub::-webkit-slider-thumb {
cursor: ew-resize;
pointer-events: auto;
}
#world-timeline .world-timeline-scrub::-moz-range-thumb {
cursor: ew-resize;
pointer-events: auto;
}
/* The time dragged off the track: the handle waits at its edge, unseen. */
#world-timeline .world-timeline-scrub.is-off-view::-webkit-slider-thumb {
opacity: 0;
pointer-events: none;
}
#world-timeline .world-timeline-scrub.is-off-view::-moz-range-thumb {
opacity: 0;
pointer-events: none;
}
#world-timeline .world-timeline-scrub::-webkit-slider-runnable-track {
height: 100%;
background: transparent;
}
#world-timeline .world-timeline-scrub::-moz-range-track {
background: transparent;
}
#world-timeline .world-timeline-scrub::-webkit-slider-thumb {
width: 14px;
height: 14px;
margin-top: 5px;
border: 2px solid var(--accent);
border-radius: 50%;
background: #031018;
box-shadow: 0 0 8px rgba(0, 212, 255, 0.6);
appearance: none;
}
#world-timeline .world-timeline-scrub::-moz-range-thumb {
width: 12px;
height: 12px;
border: 2px solid var(--accent);
border-radius: 50%;
background: #031018;
}
/* A finger needs a bigger handle. */
@media (pointer: coarse) {
#world-timeline .world-timeline-scrub::-webkit-slider-thumb {
width: 22px;
height: 22px;
margin-top: 1px;
}
#world-timeline .world-timeline-scrub::-moz-range-thumb {
width: 20px;
height: 20px;
}
}
#world-timeline .world-timeline-scrub:focus-visible {
outline: 1px solid var(--accent);
outline-offset: 2px;
}
@media (max-width: 720px) {
#world-timeline {
bottom: 8px;
}
}
/* On phones the bar sits just above the tab bar, under the voice dock, with
the track and the speed on a row of their own beneath play and live. */
body.mobile-shell:has(#world-timeline) {
--world-timeline-lift: 80px;
}
body.mobile-shell #world-timeline {
bottom: calc(var(--mobile-tab-space) + 6px);
flex-wrap: wrap;
row-gap: 4px;
height: auto;
}
/* The bubble rises into the first row, clear of play on its left. */
body.mobile-shell #world-timeline .world-timeline-time {
--inset: 48px;
}
/* The speed sits on the track's row, a full-size target beside it. */
body.mobile-shell #world-timeline .world-timeline-track {
order: 1;
flex: 1 1 calc(100% - 96px);
}
body.mobile-shell #world-timeline .world-timeline-live {
margin-inline-start: auto;
}
body.mobile-shell #world-timeline .world-timeline-speed {
order: 2;
height: 32px;
}
+2
View File
@@ -18,6 +18,7 @@ import ScreenAnnotations from './panels/ScreenAnnotations.vue';
import AwarenessDirection from './panels/AwarenessDirection.vue';
import UiButton from '../kit/UiButton.vue';
import GlobeActions from './panels/GlobeActions.vue';
import WorldTimeline from './panels/WorldTimeline.vue';
// The ACTIVE STYLE corner shows the style VisualSettings publishes.
const { style } = storeToRefs(useDisplayStore());
@@ -117,4 +118,5 @@ const vToastText = {
<MissionReplayOverlay />
<ScreenAnnotations />
<AwarenessDirection />
<WorldTimeline />
</template>
+548
View File
@@ -0,0 +1,548 @@
// The world timeline shows the world time while a layer with time to show is
// on, with play and pause on the left and the way back to live on the right.
import '../../../testSupport/registerDom.mjs';
import test from 'node:test';
import assert from 'node:assert/strict';
import { createApp, nextTick } from 'vue';
import { createPinia } from 'pinia';
import { worldClock } from '../../../time/worldClock.js';
import WorldTimeline from './WorldTimeline.vue';
import { useWorldTimeStore } from '../../stores/worldTime.js';
function mount(t) {
document.body.replaceChildren();
const pinia = createPinia();
const app = createApp(WorldTimeline).use(pinia);
app.mount(document.body.appendChild(document.createElement('div')));
t.after(() => {
app.unmount();
// The store outlives the view; dispose it with its clock subscription.
useWorldTimeStore(pinia).$dispose();
worldClock.goLive();
});
return () => document.getElementById('world-timeline');
}
// A layer that moves with the clock and has an hour of frames.
function supportingLayer(t, at) {
const release = worldClock.hold('test-radar');
const unregister = worldClock.register({
id: 'test-radar',
coverage: () => ({ start: at - 3_600_000, end: at }),
});
t.after(() => {
unregister();
release();
});
return () => {
unregister();
release();
};
}
test('the timeline shows live, and plays, pauses and goes back', async (t) => {
const bar = mount(t);
const at = Date.UTC(2026, 9, 30, 6, 15, 42);
supportingLayer(t, at);
await nextTick();
assert.ok(bar(), 'shown while live');
const live = bar().querySelector('.world-timeline-live');
assert.equal(live.disabled, true, 'already live');
assert.equal(live.getAttribute('aria-pressed'), 'true');
worldClock.seek(at);
await nextTick();
assert.ok(bar());
const time = bar().querySelector('time');
assert.equal(time.getAttribute('datetime'), new Date(at).toISOString());
assert.match(time.textContent, /UTC$/);
const play = bar().querySelector('.world-timeline-play');
assert.equal(play.getAttribute('aria-label'), 'Play');
play.click();
await nextTick();
assert.equal(worldClock.isPlaying(), true);
assert.equal(play.getAttribute('aria-label'), 'Pause');
play.click();
await nextTick();
assert.equal(worldClock.isPlaying(), false);
assert.equal(bar().querySelector('.world-timeline-live').disabled, false);
bar().querySelector('.world-timeline-live').click();
await nextTick();
assert.equal(worldClock.isLive(), true);
assert.ok(bar(), 'still shown, live');
assert.equal(bar().querySelector('.world-timeline-live').disabled, true);
});
test('the timeline hides while no layer with time to show is on', async (t) => {
const bar = mount(t);
const at = Date.UTC(2026, 9, 30, 6, 15, 42);
await nextTick();
assert.equal(bar(), null, 'live, nothing to play');
worldClock.seek(at);
await nextTick();
assert.equal(bar(), null, 'away from live, but nothing to play');
const remove = supportingLayer(t, at);
await nextTick();
assert.ok(bar());
remove();
await nextTick();
assert.equal(bar(), null, 'the layer went off');
});
test('the track runs over the time the layers show, to now, and scrubs', async (t) => {
const bar = mount(t);
const now = Date.now();
const at = now - 2 * 86_400_000;
const release = worldClock.hold('test-launches');
const unregister = worldClock.register({
id: 'test-launches',
coverage: () => ({ start: at - 86_400_000, end: at, marks: [at - 86_400_000, at] }),
});
t.after(() => {
unregister();
release();
});
await nextTick();
const input = bar().querySelector('input[type=range]');
assert.equal(Number(input.min), at - 86_400_000);
assert.ok(Number(input.max) >= now, 'reaches to now');
assert.equal(bar().querySelectorAll('.world-timeline-tick').length, 2);
worldClock.play();
input.value = String(at);
input.dispatchEvent(new Event('input'));
await nextTick();
assert.equal(worldClock.isPlaying(), false, 'a scrub stops playback');
assert.equal(worldClock.now(), at);
assert.equal(bar().querySelector('time').getAttribute('datetime'), new Date(at).toISOString());
input.dispatchEvent(new KeyboardEvent('keydown', { key: 'ArrowLeft' }));
await nextTick();
assert.equal(worldClock.now(), at - 86_400_000, 'the arrow goes to the previous mark');
input.dispatchEvent(new KeyboardEvent('keydown', { key: 'ArrowRight' }));
await nextTick();
assert.equal(worldClock.now(), at, 'and back to the next');
input.value = String(Date.now() + 2_000);
input.dispatchEvent(new Event('input'));
await nextTick();
assert.equal(worldClock.isLive(), true, 'a scrub to now goes live');
// A layer that reaches ahead of now, as satellites do.
const holdAhead = worldClock.hold('test-ahead');
const unregisterAhead = worldClock.register({
id: 'test-ahead',
coverage: () => ({ start: now, end: now + 3 * 86_400_000 }),
});
t.after(() => {
unregisterAhead();
holdAhead();
});
await nextTick();
const ahead = Date.now() + 86_400_000;
input.value = String(ahead);
input.dispatchEvent(new Event('input'));
await nextTick();
assert.equal(worldClock.isLive(), false, 'a scrub past now stays there');
assert.equal(worldClock.now(), ahead);
});
test('play runs in real time, from the start of the track when at live', async (t) => {
const bar = mount(t);
const now = Date.now();
const start = now - 10 * 86_400_000;
const release = worldClock.hold('test-launches');
const unregister = worldClock.register({
id: 'test-launches',
coverage: () => ({ start, end: now - 86_400_000 }),
});
t.after(() => {
unregister();
release();
});
await nextTick();
// Weather's replay stepping its own frames does not take the track's play.
const stepped = [];
const driver = worldClock.attachDriver({
play: () => stepped.push('play'),
pause: () => stepped.push('pause'),
});
t.after(() => driver.detach());
bar().querySelector('.world-timeline-play').click();
worldClock.pause();
await nextTick();
assert.deepEqual(stepped, []);
const rate = worldClock.getRate();
assert.ok(worldClock.now() - start < rate * 1_000, 'from the start of the track');
assert.equal(rate, 1, 'real time to start with');
worldClock.play({ continuous: true });
// Playing on to now goes live.
worldClock.seek(Date.now() + 1_000);
await nextTick();
assert.equal(worldClock.isLive(), true);
assert.equal(worldClock.isPlaying(), false);
assert.equal(worldClock.getRate(), 1, 'live plays at the rate of the world');
});
test('play holds at the end of a track that reaches past now', async (t) => {
const bar = mount(t);
const now = Date.now();
// An hour ahead is within the track's share of now, but still ahead of it.
const end = now + 3_600_000;
const release = worldClock.hold('test-ahead');
const unregister = worldClock.register({
id: 'test-ahead',
coverage: () => ({ start: now - 10 * 86_400_000, end }),
});
t.after(() => {
unregister();
release();
});
await nextTick();
// Paused just past now, play plays on rather than from the top.
worldClock.seek(Date.now() + 1_000);
await nextTick();
const from = worldClock.now();
bar().querySelector('.world-timeline-play').click();
worldClock.pause();
assert.ok(worldClock.now() >= from, 'plays on from where it was');
worldClock.play();
worldClock.seek(end + 60_000);
await nextTick();
assert.equal(worldClock.isPlaying(), false);
assert.equal(worldClock.isLive(), false);
assert.equal(worldClock.now(), end);
});
test('the speed chosen sets how fast play runs, at once while playing', async (t) => {
const bar = mount(t);
const now = Date.now();
const release = worldClock.hold('test-launches');
const unregister = worldClock.register({
id: 'test-launches',
coverage: () => ({ start: now - 10 * 86_400_000, end: now - 86_400_000 }),
});
t.after(() => {
unregister();
release();
});
await nextTick();
const select = bar().querySelector('select.world-timeline-speed');
assert.equal(select.value, 'real');
assert.deepEqual(
[...select.options].map((option) => option.value),
['real', 'minute', 'hour', 'day', 'week'],
);
select.value = 'week';
select.dispatchEvent(new Event('change'));
await nextTick();
bar().querySelector('.world-timeline-play').click();
assert.equal(worldClock.getRate(), 604_800, 'a week a second');
select.value = 'hour';
select.dispatchEvent(new Event('change'));
await nextTick();
assert.equal(worldClock.isPlaying(), true);
assert.equal(worldClock.getRate(), 3_600, 'changed while playing');
select.value = 'minute';
select.dispatchEvent(new Event('change'));
await nextTick();
assert.equal(worldClock.getRate(), 60, 'a minute a second');
select.value = 'real';
select.dispatchEvent(new Event('change'));
await nextTick();
assert.equal(worldClock.getRate(), 1, 'the world as it goes');
});
test('a speed chosen while weather replay steps takes playback over', async (t) => {
const bar = mount(t);
const at = Date.now() - 3_600_000;
supportingLayer(t, at);
const calls = [];
const driver = worldClock.attachDriver({
play() {
calls.push('play');
driver.driven(true, at - 600_000);
},
pause() {
calls.push('pause');
driver.driven(false);
},
});
t.after(() => driver.detach());
worldClock.play();
await nextTick();
assert.equal(worldClock.getState().stepping, true);
const select = bar().querySelector('select.world-timeline-speed');
select.value = 'hour';
select.dispatchEvent(new Event('change'));
await nextTick();
assert.deepEqual(calls, ['play', 'pause']);
assert.equal(worldClock.getState().stepping, false);
assert.equal(worldClock.isPlaying(), true);
assert.equal(worldClock.getRate(), 3_600);
assert.ok(worldClock.now() - (at - 600_000) < 3_600 * 1_000, 'on from where it was');
worldClock.pause();
});
test('paused just before the end, play carries on rather than restarting', async (t) => {
const bar = mount(t);
const now = Date.now();
const end = now + 86_400_000;
const release = worldClock.hold('test-ahead');
const unregister = worldClock.register({
id: 'test-ahead',
coverage: () => ({ start: now - 86_400_000, end }),
});
t.after(() => {
unregister();
release();
});
await nextTick();
worldClock.seek(end - 4_000);
await nextTick();
bar().querySelector('.world-timeline-play').click();
worldClock.pause();
assert.ok(worldClock.now() >= end - 4_000, 'not back to the start');
});
test('the track zooms around the handle, follows it, and shows it all again', async (t) => {
const bar = mount(t);
const now = Date.now();
const start = now - 26 * 86_400_000;
const release = worldClock.hold('test-launches');
const unregister = worldClock.register({
id: 'test-launches',
// A month of launches and three hours of lightning, sharing one track.
coverage: () => ({
start,
end: now,
marks: [start, now - 3 * 3_600_000, now - 2 * 3_600_000, now - 3_600_000],
}),
});
t.after(() => {
unregister();
release();
});
await nextTick();
const track = bar().querySelector('.world-timeline-track');
const input = bar().querySelector('input[type=range]');
const length = () => Number(input.max) - Number(input.min);
const full = length();
assert.equal(bar().querySelectorAll('.world-timeline-tick').length, 4);
// Live, the handle is at the end: zooming in keeps the view on now.
for (let i = 0; i < 10; i++) {
track.dispatchEvent(new WheelEvent('wheel', { deltaY: -200, cancelable: true }));
await nextTick();
}
assert.ok(length() < full / 100, 'zoomed in');
assert.ok(Number(input.max) >= now, 'still ending at now');
assert.equal(track.classList.contains('is-zoomed'), true);
assert.equal(bar().querySelectorAll('.world-timeline-tick').length, 3, 'only the ticks in view');
// A seek off the view takes the view along.
worldClock.seek(start + 86_400_000);
await nextTick();
assert.ok(Number(input.min) <= start + 86_400_000 && Number(input.max) >= start + 86_400_000);
assert.ok(length() < full / 100, 'at the same zoom');
// Minus widens, zero and a double-click show it all.
input.dispatchEvent(new KeyboardEvent('keydown', { key: '-' }));
await nextTick();
input.dispatchEvent(new KeyboardEvent('keydown', { key: '0' }));
await nextTick();
assert.ok(Math.abs(length() - full) < 1_000, 'all of it');
input.dispatchEvent(new KeyboardEvent('keydown', { key: '+' }));
await nextTick();
assert.ok(length() < full);
track.dispatchEvent(new MouseEvent('dblclick'));
await nextTick();
assert.equal(track.classList.contains('is-zoomed'), false);
});
test('zoomed, a scrub near now stays off live, and the view keeps a still handle', async (t) => {
const bar = mount(t);
const now = Date.now();
const start = now - 26 * 86_400_000;
let end = now;
const release = worldClock.hold('test-launches');
const unregister = worldClock.register({
id: 'test-launches',
coverage: () => ({ start, end, marks: [start, now - 3_600_000] }),
});
t.after(() => {
unregister();
release();
});
await nextTick();
const track = bar().querySelector('.world-timeline-track');
const input = bar().querySelector('input[type=range]');
// Ten notches of a line-mode wheel, as Firefox sends them.
for (let i = 0; i < 10; i++) {
track.dispatchEvent(new WheelEvent('wheel', { deltaY: -12, deltaMode: 1, cancelable: true }));
await nextTick();
}
assert.ok(Number(input.max) - Number(input.min) < 6 * 3_600_000, 'lines zoom like pixels');
// Twenty minutes back is near now on a month, not on a few hours.
input.value = String(now - 20 * 60_000);
input.dispatchEvent(new Event('input'));
await nextTick();
assert.equal(worldClock.isLive(), false);
assert.ok(Math.abs(worldClock.now() - (now - 20 * 60_000)) < 1_000);
// The span running on past the paused handle takes the view back to it.
end = now + 86_400_000;
worldClock.coverageChanged();
await nextTick();
const at = worldClock.now();
assert.ok(Number(input.min) <= at && Number(input.max) >= at, 'handle in view');
// With a modifier, plus is the browser's zoom.
const browserZoom = new KeyboardEvent('keydown', { key: '+', ctrlKey: true, cancelable: true });
input.dispatchEvent(browserZoom);
assert.equal(browserZoom.defaultPrevented, false);
// A double-click puts back the time its first press moved.
track.dispatchEvent(new PointerEvent('pointerdown', { bubbles: true, pointerId: 1 }));
track.dispatchEvent(new PointerEvent('pointerup', { bubbles: true, pointerId: 1 }));
input.value = String(at - 3_600_000);
input.dispatchEvent(new Event('input'));
track.dispatchEvent(new MouseEvent('dblclick', { bubbles: true }));
await nextTick();
assert.equal(track.classList.contains('is-zoomed'), false);
assert.ok(Math.abs(worldClock.now() - at) < 1_000, 'time as it was');
});
test('play held for a layer to load shows a spinner once the hold lasts', async (t) => {
const bar = mount(t);
const at = Date.UTC(2026, 9, 30, 6, 15, 42);
supportingLayer(t, at);
worldClock.seek(at - 1_800_000);
worldClock.play({ continuous: true });
await nextTick();
const bubble = () => bar().querySelector('.world-timeline-time');
const release = worldClock.wait('test-radar');
t.after(release);
// A clock tick (a quarter second) tells of the hold; the spinner waits on.
await new Promise((resolve) => setTimeout(resolve, 250));
await nextTick();
assert.equal(bubble().querySelector('.world-timeline-spinner'), null, 'not for a quick frame');
// The clock tells of the hold on its next tick, and the bar shows it after.
const until = async (shown) => {
for (let waited = 0; waited < 3_000; waited += 50) {
if (Boolean(bubble().querySelector('.world-timeline-spinner')) === shown) return true;
await new Promise((resolve) => setTimeout(resolve, 50));
await nextTick();
}
return false;
};
assert.ok(await until(true), 'spinner once the hold lasts');
assert.match(bubble().textContent, /UTC$/, 'the time stays');
release();
assert.ok(await until(false), 'gone once play goes on');
});
test('the track drags along, a tap goes to its time, and the handle waits off it', async (t) => {
const bar = mount(t);
const now = Date.now();
const start = now - 26 * 86_400_000;
const release = worldClock.hold('test-launches');
const unregister = worldClock.register({
id: 'test-launches',
coverage: () => ({ start, end: now, marks: [start] }),
});
t.after(() => {
unregister();
release();
});
await nextTick();
const track = bar().querySelector('.world-timeline-track');
const input = bar().querySelector('input[type=range]');
// A 1000 px track from x = 0.
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 view = () => ({ min: Number(input.min), max: Number(input.max) });
// All of it shown, a tap goes to the time under it.
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');
// Zoomed to a day around it, dragging right by half the track goes back half a day.
for (let i = 0; i < 6; i++) {
input.dispatchEvent(new KeyboardEvent('keydown', { key: '+' }));
await nextTick();
}
const before = view();
const day = before.max - before.min;
press('pointerdown', 600, 2);
press('pointermove', 700, 2);
press('pointermove', 1_100, 2);
press('pointerup', 1_100, 2);
await nextTick();
assert.ok(Math.abs(view().max - (before.max - day / 2)) < 1_000, 'dragged half a view');
assert.ok(Math.abs(worldClock.now() - middle) < 60_000, 'a drag leaves the time');
// Dragged off the handle, it waits unseen at the edge; a sideways swipe drags too.
track.dispatchEvent(new WheelEvent('wheel', { deltaX: -2_000, deltaY: 0, cancelable: true }));
await nextTick();
assert.ok(view().max < worldClock.now(), 'the handle is past the view');
assert.equal(input.classList.contains('is-off-view'), true);
// Moving the time takes the view back to it.
input.dispatchEvent(new KeyboardEvent('keydown', { key: 'PageUp' }));
await nextTick();
assert.equal(input.classList.contains('is-off-view'), false);
});
test('a pinch measures from where the fingers are, and a lifted finger ends it', async (t) => {
const bar = mount(t);
const now = Date.now();
const start = now - 26 * 86_400_000;
const release = worldClock.hold('test-launches');
const unregister = worldClock.register({
id: 'test-launches',
coverage: () => ({ start, end: now, marks: [start] }),
});
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 on = (target, type, clientX, pointerId) =>
target.dispatchEvent(new PointerEvent(type, { bubbles: true, clientX, pointerId }));
const length = () => Number(input.max) - Number(input.min);
for (let i = 0; i < 4; i++) {
input.dispatchEvent(new KeyboardEvent('keydown', { key: '+' }));
await nextTick();
}
const before = length();
// A finger on the handle moves before the second comes down.
on(input, 'pointerdown', 300, 1);
on(input, 'pointermove', 500, 1);
on(track, 'pointerdown', 700, 2);
on(input, 'pointermove', 500, 1);
await nextTick();
assert.ok(Math.abs(length() - before) < 1_000, 'no zoom from a stale finger');
on(track, 'pointermove', 900, 2);
await nextTick();
assert.ok(length() < before, 'spread apart, it zooms in');
// One finger up: the other moving does nothing, and throws nothing.
const zoomedTo = length();
on(track, 'pointerup', 900, 2);
on(input, 'pointermove', 100, 1);
await nextTick();
assert.ok(Math.abs(length() - zoomedTo) < 1_000);
on(input, 'pointercancel', 100, 1);
});
+355
View File
@@ -0,0 +1,355 @@
<script setup>
import { computed, onBeforeUnmount, shallowRef, watch } from 'vue';
import { storeToRefs } from 'pinia';
import { formatDate, t } from '../../../i18n/index.js';
import { useWorldTimeStore } from '../../stores/worldTime.js';
import UiButton from '../../kit/UiButton.vue';
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 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.
const store = useWorldTimeStore();
const { time, speed } = storeToRefs(store);
const speeds = computed(() => [
{ value: 'real', label: '1×' },
{ value: 'minute', label: t('1 min/s') },
{ value: 'hour', label: t('1 h/s') },
{ value: 'day', label: t('1 d/s') },
{ value: 'week', label: t('1 wk/s') },
]);
const DATE_TIME = Object.freeze({
dateStyle: 'medium',
timeStyle: 'medium',
timeZone: 'UTC',
});
// The bubble over the handle: the date and the minute, kept short.
const BUBBLE_DATE = Object.freeze({
month: 'short',
day: 'numeric',
timeZone: 'UTC',
});
const BUBBLE_TIME = Object.freeze({
hour: '2-digit',
minute: '2-digit',
hourCycle: 'h23',
timeZone: 'UTC',
});
// The keyboard's fallback step, as a share of the track, with no mark to go to.
const KEY_STEP = 0.01;
const PAGE_STEP = 0.1;
// Zooming: the shortest stretch the track narrows to, the step a key or a
// notch of the wheel takes, and how far a wheel's pixel of scroll zooms.
const MIN_VIEW_MS = 5 * 60_000;
const ZOOM_STEP = 1.5;
const WHEEL_ZOOM = 0.0025;
// Two presses this close are a double-click.
const DOUBLE_PRESS_MS = 500;
const readout = computed(() =>
Number.isFinite(time.value.timeMs)
? `${formatDate(time.value.timeMs, DATE_TIME)} UTC`
: '',
);
const bubble = computed(() =>
Number.isFinite(time.value.timeMs)
? `${formatDate(time.value.timeMs, BUBBLE_DATE)} · ${formatDate(time.value.timeMs, BUBBLE_TIME)} UTC`
: '',
);
// Play held while a layer loads the time's data shows a spinner by the time,
// once the hold lasts long enough to notice, so a quick frame does not flash
// it, and until play has run a while, so a run of slow frames keeps it still.
const WAIT_SHOWN_MS = 300;
const WAIT_HIDDEN_MS = 500;
const waiting = shallowRef(false);
let waitTimer = null;
watch(
() => time.value.buffering,
(buffering) => {
clearTimeout(waitTimer);
waitTimer = null;
if (buffering === waiting.value) return;
waitTimer = setTimeout(
() => {
waitTimer = null;
waiting.value = buffering;
},
buffering ? WAIT_SHOWN_MS : WAIT_HIDDEN_MS,
);
},
);
onBeforeUnmount(() => clearTimeout(waitTimer));
const span = computed(() => time.value.span);
// Where the handle is, or null with no track.
const at = computed(() => {
if (!span.value) return null;
const { start, end } = span.value;
return Math.min(end, Math.max(start, time.value.timeMs));
});
// The track shows the whole span, or zoomed, a stretch of it: `length` long,
// ending at `end`, or at the span's end (and so at now) while `end` is null.
// Everything still plays together; zooming only changes what the track shows.
const zoom = shallowRef(null);
const view = computed(() => {
if (!span.value) return null;
const { start, end } = span.value;
const length = zoom.value?.length;
if (!length || length >= end - start) return { start, end };
const viewEnd = Math.min(end, Math.max(start + length, zoom.value.end ?? end));
return { start: viewEnd - length, end: viewEnd };
});
const zoomed = computed(() => zoom.value !== null);
const viewLength = () => view.value.end - view.value.start;
// Show `length` of the span ending at `viewEnd`, held to the span.
function showView(length, viewEnd) {
const { start, end } = span.value;
if (length >= end - start) {
showWhole();
return;
}
const clamped = Math.min(end, Math.max(start + length, viewEnd));
zoom.value = { length, end: clamped >= end ? null : clamped };
}
// Narrow or widen the view to `length`, keeping the handle where it is on it,
// or with the handle off it, the middle.
function zoomTo(length) {
const { start: from, end: to } = view.value;
const pivot = offView(at.value) ? (from + to) / 2 : at.value;
const share = (pivot - from) / (to - from);
const next = Math.max(MIN_VIEW_MS, length);
showView(next, pivot + (1 - share) * next);
}
const zoomBy = (factor) => zoomTo(viewLength() * factor);
// A view dragged off the handle stays where it was put while the handle only
// creeps on with now; playing or a move of the handle takes it back.
let panned = false;
const follow = (ms) => {
panned = false;
showView(zoom.value.length, ms + zoom.value.length / 2);
};
const offView = (ms) => ms < view.value.start || ms > view.value.end;
const showWhole = () => {
zoom.value = null;
panned = false;
};
// The span narrowing to the zoom or less, or going, lets go of the zoom.
watch(span, (next) => {
if (zoom.value && (!next || zoom.value.length >= next.end - next.start))
showWhole();
});
watch(at, (ms) => {
if (!zoom.value || ms === null || !offView(ms)) return;
if (panned && time.value.live && !time.value.playing) return;
follow(ms);
});
// Left behind as now moves the view on, the handle takes the view back.
watch(view, () => {
if (zoom.value && !panned && at.value !== null && offView(at.value))
follow(at.value);
});
const pan = (ms) => {
panned = true;
showView(zoom.value.length, view.value.end + ms);
};
// A wheel's lines and pages, in pixels.
const WHEEL_UNITS = [1, 16, 400];
const onWheel = (event) => {
const unit = WHEEL_UNITS[event.deltaMode] ?? 1;
const sideways = Math.abs(event.deltaX) > Math.abs(event.deltaY);
// A sideways swipe, or a wheel with shift, drags; a wheel zooms.
if (sideways || event.shiftKey) {
if (!zoom.value) return;
event.preventDefault();
const width = event.currentTarget.clientWidth;
const pixels = (sideways ? event.deltaX : event.deltaY) * unit;
if (width > 0) pan((pixels / width) * viewLength());
return;
}
event.preventDefault();
zoomBy(Math.exp(event.deltaY * unit * WHEEL_ZOOM));
};
// A double-click starts with presses that move the time, so it puts back the
// time from before its first; so does a pinch, which may start on the handle.
let before = null;
let pressedAt = -Infinity;
const onPress = (event) => {
if (event.timeStamp - pressedAt > DOUBLE_PRESS_MS)
before = { live: time.value.live, timeMs: time.value.timeMs };
pressedAt = event.timeStamp;
};
const restore = () => {
if (!before) return;
if (before.live) store.goLive();
else store.scrub(before.timeMs, 0);
};
const showAll = () => {
restore();
showWhole();
};
// The handle drags the time. The rest of the track takes the pointer: a tap
// goes to the time under it, a drag drags a zoomed track along (or the time,
// with all of it shown), and two fingers pinch it.
const DRAG_PX = 4;
const pointers = new Map();
let gesture = null;
const timeAt = (clientX, track) => {
const { left, width } = track.getBoundingClientRect();
const share = width > 0 ? Math.min(1, Math.max(0, (clientX - left) / width)) : 1;
return view.value.start + share * viewLength();
};
// Whether the first finger has moved the time, for a pinch to put it back.
let movedTime = false;
const onPointerDown = (event) => {
// Only the main button: a right-click is for the menu.
if (event.button > 0) return;
const onHandle = event.target instanceof HTMLInputElement;
pointers.set(event.pointerId, { x: event.clientX, onHandle });
if (pointers.size === 1) {
onPress(event);
movedTime = onHandle;
// The keys zoom and step the track as soon as it is touched.
if (!onHandle)
event.currentTarget.querySelector('input')?.focus({ preventScroll: true });
}
if (pointers.size === 2) {
const [a, b] = [...pointers.values()];
if (movedTime) restore();
gesture = {
kind: 'pinch',
spread: Math.abs(a.x - b.x),
length: viewLength(),
};
return;
}
if (onHandle || pointers.size !== 1) return;
// The drag goes on past the track's ends; without the capture, to them.
try {
event.currentTarget.setPointerCapture?.(event.pointerId);
} catch {
// A pointer the page no longer knows of drags no further than the track.
}
gesture = { kind: 'press', x: event.clientX, end: view.value.end };
};
const onPointerMove = (event) => {
const pointer = pointers.get(event.pointerId);
if (!pointer) return;
pointer.x = event.clientX;
if (!gesture) return;
const track = event.currentTarget;
if (gesture.kind === 'pinch') {
const [a, b] = [...pointers.values()];
const spreadNow = Math.abs(a.x - b.x);
if (spreadNow > 0) zoomTo((gesture.length * gesture.spread) / spreadNow);
return;
}
if (gesture.kind === 'press') {
if (Math.abs(event.clientX - gesture.x) < DRAG_PX) return;
gesture.kind = zoom.value ? 'pan' : 'scrub';
movedTime = gesture.kind === 'scrub';
}
if (gesture.kind === 'pan') {
if (!track.clientWidth) return;
panned = true;
const moved = ((gesture.x - event.clientX) / track.clientWidth) * viewLength();
showView(zoom.value.length, gesture.end + moved);
} else store.scrub(timeAt(event.clientX, track), viewLength());
};
const onPointerUp = (event) => {
if (!pointers.delete(event.pointerId)) return;
if (gesture?.kind === 'press' && event.type === 'pointerup')
store.scrub(timeAt(event.clientX, event.currentTarget), viewLength());
// A finger lifted from a pinch ends it; the other one moves nothing.
gesture = null;
};
const place = (ms) => {
const { start, end } = view.value;
return end > start ? ((ms - start) / (end - start)) * 100 : 100;
};
const ticks = computed(() => {
const { start, end } = view.value;
return span.value.marks
.filter((mark) => mark >= start && mark <= end)
.map((mark) => `${place(mark)}%`);
});
const shown = computed(() =>
Math.min(view.value.end, Math.max(view.value.start, at.value)),
);
const handleOff = computed(() => at.value !== shown.value);
const scrub = (event) => {
// A pinch only zooms; the input goes back to the handle.
if (gesture?.kind === 'pinch') {
event.target.value = shown.value;
return;
}
store.scrub(Number(event.target.value), viewLength());
};
// 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)) {
if (event.ctrlKey || event.metaKey || event.altKey) return;
event.preventDefault();
if (event.key === '-') zoomBy(ZOOM_STEP);
else if (event.key === '0') showWhole();
else zoomBy(1 / ZOOM_STEP);
return;
}
const { start, end, marks } = span.value;
const now = at.value;
const length = viewLength();
let to = null;
if (event.key === 'ArrowLeft' || event.key === 'ArrowDown')
to = marks.findLast((mark) => mark < now) ?? now - length * KEY_STEP;
else if (event.key === 'ArrowRight' || event.key === 'ArrowUp')
to = marks.find((mark) => mark > now) ?? now + length * KEY_STEP;
else if (event.key === 'PageDown') to = now - length * PAGE_STEP;
else if (event.key === 'PageUp') to = now + length * PAGE_STEP;
else if (event.key === 'Home') to = start;
else if (event.key === 'End') to = end;
if (to === null) return;
event.preventDefault();
store.scrub(Math.min(end, Math.max(start, to)), length);
};
</script>
<template>
<div v-if="time.supported && time.span" id="world-timeline" role="group" :aria-label="t('World time')"
><UiButton class="world-timeline-play" :label="time.playing ? t('Pause') : t('Play')" @click="store.togglePlay()"
><UiIcon :name="time.playing ? 'pause' : 'play_arrow'" :size="20" /></UiButton
><UiSelect class="gev-field gev-field--compact world-timeline-speed" :aria-label="t('Play speed')" :title="t('Play speed')" :options="speeds" :model-value="speed" @update:model-value="store.setSpeed($event)"
/><div class="world-timeline-track" :class="{ 'is-zoomed': zoomed }" :title="t('Scroll or pinch to zoom, drag to move along · double-click to see it all')" @wheel="onWheel" @dblclick="showAll" @pointerdown="onPointerDown" @pointermove="onPointerMove" @pointerup="onPointerUp" @pointercancel="onPointerUp"
><time class="world-timeline-time" :class="{ 'is-waiting': waiting }" :style="{ '--at': place(shown) / 100 }" :datetime="new Date(time.timeMs).toISOString()" aria-live="off"
><span v-if="waiting" class="world-timeline-spinner" aria-hidden="true"></span>{{ bubble }}</time
><span v-for="(left, index) in ticks" :key="index" class="world-timeline-tick" :style="{ left }" aria-hidden="true"></span
><span class="world-timeline-fill" :style="{ width: `${place(shown)}%` }" aria-hidden="true"></span
><input
class="world-timeline-scrub"
:class="{ 'is-off-view': handleOff }"
type="range"
:aria-label="t('World time')"
:aria-valuetext="readout"
:min="view.start"
:max="view.end"
step="any"
:value="shown"
@input="scrub"
aria-keyshortcuts="+ - 0"
@keydown="onKey"
/></div
><UiButton class="world-timeline-live" :label="time.live ? t('Live') : t('Back to live')" :pressed="time.live" pressed-class="is-live" :disabled="time.live" @click="store.goLive()">{{ t('Live') }}</UiButton
></div>
</template>