Draw the air quality stations through the renderer's draw port

The station discs are now one draw set of ground-clamped filled ellipses per
layer, with the same band colours, alpha and radius, and their readings as
item meta; they had no visible outline before either (Cesium turns outlines
off on clamped entity ellipses). The readout's in-view list reads the view
rectangle through the camera port. The layer no longer imports Cesium and
leaves the allow-list; a caller handing it a Cesium viewer of their own,
with no renderer bound, loads the ./render/cesium/unbound export once first.

Double-clicking a station no longer starts the viewer's entity follow, since
draw items are not entities.
This commit is contained in:
Sameh Khamis committed 2026-11-07 01:50:52 -08:00
1 parent 03ff8f291f
commit 2061f5647c
9 files changed
+186 -82

No files matched your search

@@ -7,6 +7,7 @@ import { layerNameForId, localizeLayerName } from '../../ui/layerNames.js';
import { LayerPanel } from '../../ui/layerPanel.js';
import { translateFeedError } from '../../ui/statusText.js';
import { createAirQualityLayer } from './index.js';
import { bindFakeDraw } from '../../testSupport/fakeDrawPort.mjs';
function inLocale(locale, run) {
setLocale(locale);
@@ -22,7 +23,8 @@ function harness(source) {
source,
overlayHost: { setEntries() {}, setVisible() {}, clearSource() {} },
});
const viewer = { dataSources: { add() {}, remove() {} } };
const viewer = {};
bindFakeDraw(viewer);
layer.init(viewer);
layer.enable(viewer);
return layer;
+59 -62
View File
@@ -1,4 +1,6 @@
import * as Cesium from 'cesium';
import { fromDegrees } from '../../geo/ellipsoid.js';
import { cssColor } from '../../render/color.js';
import { drawOf, findCamera } from '../../render/rendererOf.js';
import { msg, t, tn } from '../../i18n/index.js';
import { translateFeedError } from '../../ui/statusText.js';
import {
@@ -22,6 +24,15 @@ const STATION_MARKER_RADIUS_M = 6_000;
/** Readings listed in the readout card. */
const READOUT_LIMIT = 5;
export const AIR_QUALITY_MARKER_SET_ID = 'air-quality';
let instances = 0;
/** A reading's colour at `alpha`; an unreadable colour falls back to white. */
function withAlpha(css, alpha) {
const [r, g, b] = cssColor(css) ?? [1, 1, 1];
return [r, g, b, alpha];
}
/** Own one air-quality display, its refresh lifecycle, and its readout card. */
export function createAirQualityLayer({ source, overlayHost } = {}) {
if (typeof source?.getSnapshot !== 'function')
@@ -29,7 +40,7 @@ export function createAirQualityLayer({ source, overlayHost } = {}) {
if (!overlayHost) throw new TypeError('Air quality requires an overlay host');
let _viewer = null;
let _request = null;
let _dataSource = null;
let _markers = null;
let _readings = [];
let _count = 0;
let _lastUpdate = null;
@@ -40,17 +51,8 @@ export function createAirQualityLayer({ source, overlayHost } = {}) {
const notify = () => rowControlsListener?.();
/** The camera's lon/lat rectangle in degrees, or null when unresolvable. */
const viewRectangle = () => {
const rectangle = _viewer?.camera?.computeViewRectangle?.();
if (!rectangle) return null;
const toDeg = Cesium.Math.toDegrees;
return {
west: toDeg(rectangle.west),
south: toDeg(rectangle.south),
east: toDeg(rectangle.east),
north: toDeg(rectangle.north),
};
};
const viewRectangle = () =>
_viewer ? (findCamera(_viewer)?.viewRectangle() ?? null) : null;
const layer = {
id: 'air-quality',
@@ -61,10 +63,11 @@ export function createAirQualityLayer({ source, overlayHost } = {}) {
init(viewer) {
if (_viewer) throw new Error('Air quality layer is already initialized');
_markers = drawOf(viewer).shapes({
id: `${AIR_QUALITY_MARKER_SET_ID}:${++instances}`,
show: false,
});
_viewer = viewer;
_dataSource = new Cesium.CustomDataSource('air-quality');
_dataSource.show = false;
viewer.dataSources.add(_dataSource);
_readings = [];
_count = 0;
_lastUpdate = null;
@@ -75,7 +78,7 @@ export function createAirQualityLayer({ source, overlayHost } = {}) {
enable() {
_enabled = true;
if (_dataSource) _dataSource.show = true;
if (_markers) _markers.show = true;
overlayHost.setVisible(AIR_QUALITY_OVERLAY_SOURCE_ID, true);
notify();
},
@@ -85,14 +88,14 @@ export function createAirQualityLayer({ source, overlayHost } = {}) {
_request?.abort();
_request = null;
_enabled = false;
if (_dataSource) _dataSource.show = false;
if (_markers) _markers.show = false;
overlayHost.clearSource(AIR_QUALITY_OVERLAY_SOURCE_ID);
overlayHost.setVisible(AIR_QUALITY_OVERLAY_SOURCE_ID, false);
notify();
},
async update() {
if (!_enabled || !_dataSource) return false;
if (!_enabled || !_markers) return false;
_request?.abort();
const request = new AbortController();
_request = request;
@@ -120,47 +123,42 @@ export function createAirQualityLayer({ source, overlayHost } = {}) {
}
},
/** Rebuild entities and overlay labels from the current readings. */
/** Redraw the station markers and overlay labels from the current readings. */
_render() {
if (!_dataSource) return;
_dataSource.entities.removeAll();
if (!_markers) return;
const markers = [];
const overlayEntries = [];
for (const reading of _readings) {
const position = Cesium.Cartesian3.fromDegrees(
reading.lon,
reading.lat,
);
const color = Cesium.Color.fromCssColorString(reading.color);
_dataSource.entities.add(
new Cesium.Entity({
id: `air-quality:${reading.id}`,
position,
ellipse: {
// Static axes, as in the earthquake layer: a per-frame axis
// re-tessellates the clamped ground primitive every frame.
semiMajorAxis: STATION_MARKER_RADIUS_M,
semiMinorAxis: STATION_MARKER_RADIUS_M,
material: new Cesium.ColorMaterialProperty(color.withAlpha(0.35)),
outline: true,
outlineColor: color.withAlpha(0.9),
outlineWidth: 2,
heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
},
properties: {
provider: reading.provider,
scale: reading.scale,
value: reading.value,
band: reading.band,
name: reading.name,
zone: reading.zone,
risk: reading.risk,
observedMs: reading.observedMs,
note: reading.note,
lat: reading.lat,
lon: reading.lon,
},
}),
);
const position = fromDegrees(reading.lon, reading.lat);
// A filled disc on the ground with static axes, as in the earthquake
// layer: a per-frame axis re-tessellates clamped ground geometry
// every frame. No outline: clamped to the ground, the default
// renderer never drew one.
markers.push({
id: `air-quality:${reading.id}`,
geometry: {
kind: 'ellipse',
center: { lon: reading.lon, lat: reading.lat },
semiMajor: STATION_MARKER_RADIUS_M,
semiMinor: STATION_MARKER_RADIUS_M,
},
fill: withAlpha(reading.color, 0.35),
height: 'clampGround',
clampTo: 'both',
meta: {
provider: reading.provider,
scale: reading.scale,
value: reading.value,
band: reading.band,
name: reading.name,
zone: reading.zone,
risk: reading.risk,
observedMs: reading.observedMs,
note: reading.note,
lat: reading.lat,
lon: reading.lon,
},
});
overlayEntries.push(
createAirQualityOverlayEntry({
id: reading.id,
@@ -171,6 +169,7 @@ export function createAirQualityLayer({ source, overlayHost } = {}) {
}),
);
}
_markers.set(markers);
if (_enabled) {
overlayHost.setEntries(
AIR_QUALITY_OVERLAY_SOURCE_ID,
@@ -184,16 +183,14 @@ export function createAirQualityLayer({ source, overlayHost } = {}) {
}
},
destroy(viewer = _viewer) {
destroy() {
_request?.abort();
_request = null;
_enabled = false;
overlayHost.clearSource(AIR_QUALITY_OVERLAY_SOURCE_ID);
overlayHost.setVisible(AIR_QUALITY_OVERLAY_SOURCE_ID, false);
if (_dataSource) {
viewer?.dataSources?.remove(_dataSource, true);
_dataSource = null;
}
_markers?.dispose();
_markers = null;
_viewer = null;
_readings = [];
_count = 0;
+66 -17
View File
@@ -3,20 +3,12 @@ import test from 'node:test';
import { createAirQualityLayer } from './index.js';
import { layerFeedState } from '../../data/feedState.js';
import { STALE_AFTER_MS } from './model.js';
import { bindFakeDraw } from '../../testSupport/fakeDrawPort.mjs';
function harness(source) {
const sources = [];
function harness(source, renderer = {}) {
const events = [];
const viewer = {
dataSources: {
add(value) {
sources.push(value);
},
remove(value) {
sources.splice(sources.indexOf(value), 1);
},
},
};
const viewer = {};
const { draw } = bindFakeDraw(viewer, renderer);
const layer = createAirQualityLayer({
source,
overlayHost: {
@@ -29,7 +21,8 @@ function harness(source) {
});
layer.init(viewer);
layer.enable(viewer);
return { layer, viewer, sources, events };
const markers = () => draw.find('air-quality:');
return { layer, viewer, draw, markers, events };
}
const reading = (id, value, overrides = {}) => ({
@@ -61,12 +54,68 @@ test('a layer requires both a snapshot source and an overlay host', () => {
);
});
test('initialization is single-use and owns exactly one data source', () => {
const { layer, viewer, sources } = harness(staticSource([]));
assert.equal(sources.length, 1);
test('initialization is single-use and owns exactly one draw set', () => {
const { layer, viewer, draw, markers } = harness(staticSource([]));
const owned = markers();
assert.equal(owned.kind, 'shapes');
assert.equal(
[...draw.sets.values()].filter((set) => !set.disposed).length,
1,
);
assert.throws(() => layer.init(viewer), /already initialized/);
layer.destroy(viewer);
assert.equal(sources.length, 0);
assert.equal(owned.disposed, true);
});
test('stations are ground discs in their band colour, shown only while enabled', async () => {
const { layer, markers } = harness(
staticSource([reading('A', 2), reading('B', 7, { color: '#c1121f' })]),
);
assert.equal(await layer.update(), true);
const set = markers();
assert.equal(set.show, true);
assert.deepEqual(
[...set.items.keys()],
['air-quality:eccc:A', 'air-quality:eccc:B'],
);
const disc = set.items.get('air-quality:eccc:B');
assert.deepEqual(disc.geometry, {
kind: 'ellipse',
center: { lon: -79.38, lat: 43.65 },
semiMajor: 6_000,
semiMinor: 6_000,
});
assert.equal(disc.height, 'clampGround');
assert.equal(disc.clampTo, 'both');
assert.deepEqual(disc.fill, [0xc1 / 255, 0x12 / 255, 0x1f / 255, 0.35]);
assert.equal(disc.outline, undefined);
assert.equal(disc.meta.name, 'B');
assert.equal(disc.meta.value, 7);
layer.disable();
assert.equal(set.show, false);
layer.enable();
assert.equal(set.show, true);
assert.equal(await layer.update(), true);
assert.equal(set.items.size, 2, 'a refresh replaces, not appends');
});
test('the readout lists only readings inside the camera port view rectangle', async () => {
const { layer } = harness(
staticSource([
reading('Toronto', 2),
reading('Vancouver', 4, { lat: 49.28, lon: -123.12 }),
]),
{
camera: {
viewRectangle: () => ({ west: -90, south: 40, east: -70, north: 50 }),
},
},
);
await layer.update();
assert.deepEqual(
layer.getRowControls().list.items.map((item) => item.text),
['Toronto · Low health risk'],
);
});
test('a refresh renders readings and publishes an overlay cohort', async () => {