Merge origin/main into the renderer-contract branch: the procedural fleet models drawn through the renderer's model sets

Aircraft, military, local ADS-B, vessel, transit and rail models come from
the fleet model set, loaded up front and drawn life size through the draw
port's models sets; no layer touches the viewer or Cesium outside
src/render/cesium/. The models capability gains glTF bytes (gltf), a
per-axis stretch (axisScale), a colour for tinted parts (maskColor) and a
cut below the origin (clip: 'belowOrigin'), with conformance checks.

Main's rail layer and Data Library are ported to the ports; the CCTV
footprint probe keeps the globe-terrain clamp through the query port.
This commit is contained in:
Sameh Khamis committed 2026-11-13 14:14:42 -08:00
commit e3865f462f
533 files changed
+55738 -2518

No files matched your search

+2 -2
View File
@@ -102,7 +102,7 @@ export class StyleManager extends ShellFacade {
* @param {object} viewer - The scene object the renderer draws.
* @param {object} [options]
* @param {boolean} [options.localePicker=true] - false removes the language
* picker, for a host that does not initialize Core's locale.
* picker, for a host that offers its own language choice.
*/
constructor(
viewer,
@@ -779,7 +779,7 @@ export class StyleManager extends ShellFacade {
this._lifetime.own(
onLocaleChange(() => nextTick(() => this._sizeDisplayLabelColumn())),
);
// A host that does not initialize Core's locale shows no picker.
// A host that offers its own language choice shows no picker.
if (this._localePickerEnabled === false) return;
this._publishLocalePicker();
}
+9 -1
View File
@@ -10,7 +10,8 @@ const STYLE_KEYS = Object.freeze({
/**
* Bind the application's existing bubbling keyboard shortcuts.
* Capture-phase surfaces keep first refusal. The caller owns each action and
* persistence; form controls keep native typing except for Escape.
* persistence; form controls keep native typing except for Escape, and a key
* held with Cmd, Ctrl or Alt is left to the browser.
* @param {object} options
* @param {Document} options.documentRef Keyboard event target.
* @param {HTMLElement} options.searchInput Additional editing target.
@@ -27,6 +28,13 @@ export function bindApplicationShortcuts({
event.target?.matches?.('select, input, textarea') ||
event.target === searchInput;
if (isFormControl && event.key !== 'Escape') return;
// Cmd+C, Ctrl+F, Cmd+1 and the like belong to the browser and the system.
// Shift is not a chord here: Shift+C is still C.
if (
(event.metaKey || event.ctrlKey || event.altKey) &&
event.key !== 'Escape'
)
return;
if (STYLE_KEYS[event.key]) actions.setStyle(STYLE_KEYS[event.key]);
if (event.key === 'Escape') actions.dismissSearch();
+45
View File
@@ -1,6 +1,7 @@
import assert from 'node:assert/strict';
import { test } from 'node:test';
import { CctvControls } from './cctvControls.js';
import { CCTV_FRAME_DECODE_WAIT_MS } from './cctvFrames.js';
function element() {
const classes = new Set();
@@ -59,6 +60,50 @@ test('a late image completion cannot replace a newer camera preview', (t) => {
assert.equal(controls._frame.cameraId, 'b');
});
test('a camera frame settles once decoded, and a stale decode cannot land', async (t) => {
const { controls, requests } = fixture(t);
const decodes = [];
const queue = (src, id) => {
controls._queueCctvFrame(src, id, true);
const request = requests.at(-1);
request.decode = () =>
new Promise((resolve) => decodes.push({ src, resolve }));
return request;
};
const first = queue('first.jpg', 'a');
first.onload();
assert.equal(controls._frame.hasFrame, false);
const second = queue('second.jpg', 'b');
second.onload();
decodes[1].resolve();
await Promise.resolve();
decodes[0].resolve();
await Promise.resolve();
assert.equal(controls._frame.src, 'second.jpg');
assert.equal(controls._frame.cameraId, 'b');
assert.equal(controls._frame.hasFrame, true);
});
test('a loaded frame shows when its decode rejects or never settles', async (t) => {
t.mock.timers.enable({ apis: ['setTimeout'] });
const { controls, requests } = fixture(t);
controls._queueCctvFrame('broken.jpg', 'a', true);
requests[0].decode = () => Promise.reject(new Error('EncodingError'));
requests[0].onload();
await Promise.resolve();
await Promise.resolve();
assert.equal(controls._frame.src, 'broken.jpg');
assert.equal(controls._frame.hasFrame, true);
controls._queueCctvFrame('hidden.jpg', 'b', true);
requests[1].decode = () => new Promise(() => {});
requests[1].onload();
assert.equal(controls._frame.hasFrame, false);
t.mock.timers.tick(CCTV_FRAME_DECODE_WAIT_MS);
assert.equal(controls._frame.src, 'hidden.jpg');
assert.equal(controls._frame.hasFrame, true);
});
test('failed refresh preserves settled pixels, but changing cameras clears them', (t) => {
const { controls, requests } = fixture(t);
controls._queueCctvFrame('first.jpg', 'a', true);
+25 -1
View File
@@ -77,6 +77,9 @@ export function cctvSourceLabelText(label) {
return SOURCE_LABELS[text] ? t(SOURCE_LABELS[text]) : text;
}
/** Longest wait for a loaded frame's decode before it is shown anyway. */
export const CCTV_FRAME_DECODE_WAIT_MS = 1000;
/** The preview before any frame: nothing requested, nothing shown. */
export const EMPTY_CCTV_FRAME = Object.freeze({
cameraId: '',
@@ -127,7 +130,28 @@ export function _queueCctvFrame(src, cameraId, cameraChanged) {
const preloader = new Image();
this._cctvFramePreloader = preloader;
preloader.onload = () => this._settleCctvFrame(token, src, true);
// Settle once the image is decoded, not merely loaded: the panel's <img>
// then paints the frame the moment it takes the src, instead of showing
// its empty box for the decode.
// A decode that rejects after a load still has drawable data, as it was
// before decoding was awaited. A decode that never settles (a hidden tab may
// hold it until the page draws) shows the loaded frame after
// CCTV_FRAME_DECODE_WAIT_MS rather than leaving the preview loading.
preloader.onload = () => {
if (typeof preloader.decode !== 'function') {
this._settleCctvFrame(token, src, true);
return;
}
let settled = false;
const settle = () => {
if (settled) return;
settled = true;
clearTimeout(timer);
this._settleCctvFrame(token, src, true);
};
const timer = setTimeout(settle, CCTV_FRAME_DECODE_WAIT_MS);
preloader.decode().then(settle, settle);
};
preloader.onerror = () => this._settleCctvFrame(token, src, false);
preloader.src = src;
}
+1
View File
@@ -32,6 +32,7 @@ export const LAYER_NAME_KEYS = Object.freeze({
'local-adsb': msg('Local ADS-B'),
'osm-places': msg('OSM Places'),
transit: msg('Transit'),
rail: msg('Rail'),
'recent-imagery': msg('Recent Imagery'),
'fire-perimeters': msg('Fire Perimeters'),
'gnss-integrity': msg('GNSS Integrity'),
+27 -10
View File
@@ -53,6 +53,7 @@ const PANEL_GROUPS = [
'ais-live-vessels',
'traffic',
'transit',
'rail',
'bikeshare',
],
},
@@ -119,6 +120,17 @@ const PANEL_ORDER = PANEL_GROUPS.flatMap(({ label, ids, containerId }) =>
const PANEL_POSITIONS = new Map(
PANEL_ORDER.map(({ id }, index) => [id, index]),
);
// Data Library layers follow every core group, in the order they were added.
const LIBRARY_GROUP = msg('Library');
const panelPosition = (layer) =>
layer.libraryEntryId
? PANEL_ORDER.length + 1
: (PANEL_POSITIONS.get(layer.id) ?? PANEL_ORDER.length);
const panelGroup = (layer) =>
layer.libraryEntryId
? LIBRARY_GROUP
: (PANEL_ORDER[PANEL_POSITIONS.get(layer.id)]?.label ??
msg('Other layers'));
function englishPanelLabel(layer) {
return PANEL_LABELS[layer.id] || LAYER_NAME_KEYS[layer.id] || layer.name;
@@ -371,6 +383,10 @@ export class LayerPanel {
this._groupContainers = new Map();
this._toggleContainer = null;
}
/** Rebuild the rows after the layer set changed (a Data Library add/remove). */
rerender() {
this._renderToggles();
}
_renderToggles() {
if (this._destroyed || !this._toggleContainer) return;
this._releaseBindings();
@@ -379,19 +395,13 @@ export class LayerPanel {
// its toggle and metadata.
const layers = this.getAll()
.slice()
.sort(
(a, b) =>
(PANEL_POSITIONS.get(a.id) ?? PANEL_ORDER.length) -
(PANEL_POSITIONS.get(b.id) ?? PANEL_ORDER.length),
);
.sort((a, b) => panelPosition(a) - panelPosition(b));
this._rows = [];
this._rowViews = new Map();
let previousGroup = '';
for (const layer of layers) {
if (!layer.showInTogglePanel) continue;
const group =
PANEL_ORDER[PANEL_POSITIONS.get(layer.id)]?.label ??
msg('Other layers');
const group = panelGroup(layer);
const containerId =
PANEL_ORDER[PANEL_POSITIONS.get(layer.id)]?.containerId;
const container = this._groupContainers.has(containerId)
@@ -484,6 +494,7 @@ export class LayerPanel {
id: layer.id,
// English name for voice tools, which must not receive translated text.
englishName: englishPanelLabel(layer),
libraryEntry: layer.libraryEntryId || null,
icon: layer.icon,
name: panelLabel(layer),
count: row.count ? presentLayerCount(layer.stats) : null,
@@ -503,7 +514,12 @@ export class LayerPanel {
* controls for good, and a shown info line stays.
*/
_presentControls(row, layer) {
const controls = layer.enabled ? this._rowControlsFor(layer.id) : null;
// A quiet row stays quiet while off, except Data Library rows, whose
// actions (zoom, remove) work on a layer that is off.
const controls =
layer.enabled || layer.libraryEntryId
? this._rowControlsFor(layer.id)
: null;
if (controls?.readout) {
// The row became a rail readout: its controls go for good.
row.controls = false;
@@ -579,7 +595,8 @@ export class LayerPanel {
...(live?.chips || []),
...(live?.segmented?.options || []),
].find((entry) => entry.id === chipId);
if (!chip || chip.disabled || !this.isEnabled(id)) return;
if (!chip || chip.disabled || (!this.isEnabled(id) && !chip.whileOff))
return;
if (typeof chip.onClick === 'function') chip.onClick();
else if (chip.params)
this.setLayerParams(id, chip.params, { origin: 'user' });
+3 -1
View File
@@ -4,7 +4,7 @@ import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { runInNewContext } from 'node:vm';
test('panel presentation places Transit between Street Traffic and Bike Share in Movement', () => {
test('panel presentation places Transit and Rail between Street Traffic and Bike Share in Movement', () => {
const source = readFileSync(
new URL('./layerPanel.js', import.meta.url),
'utf8',
@@ -28,10 +28,12 @@ test('panel presentation places Transit between Street Traffic and Bike Share in
'ais-live-vessels',
'traffic',
'transit',
'rail',
'bikeshare',
],
);
assert.equal(order.filter(({ id }) => id === 'transit').length, 1);
assert.equal(order.filter(({ id }) => id === 'rail').length, 1);
});
test('Wildlife follows Events and precedes Weather', () => {
+1
View File
@@ -33,6 +33,7 @@ defineProps({
}"
:data-layer-id="item.id"
:data-layer-name="item.englishName"
:data-library-entry="item.libraryEntry || undefined"
><div class="data-toggle-top"
><div class="data-toggle-left"
><span class="data-icon" aria-hidden="true">{{ item.icon }}</span
+54
View File
@@ -218,3 +218,57 @@ test('a row range renders start and end pickers and reports which end moved', ()
assert.deepEqual(picks, [['shipwrecks', 'period', 'to', '2007']]);
render(null, container);
});
const libraryRow = (chips) => ({
...row(false),
key: 'lib-night-lights',
id: 'lib-night-lights',
libraryEntry: 'nasa-black-marble',
controls: { hidden: false, chips, legend: [], list: null },
});
test('a Data Library row names its entry and draws icon action chips', () => {
document.body.replaceChildren();
const container = document.body.appendChild(document.createElement('div'));
const zoom = {
id: 'zoom',
icon: 'zoom_in_map',
action: true,
label: 'Zoom to layer',
};
render(h(LayerRows, { items: [libraryRow([zoom])] }), container);
const element = container.querySelector('[data-layer-id="lib-night-lights"]');
assert.equal(element.dataset.libraryEntry, 'nasa-black-marble');
const button = element.querySelector('[data-chip-id="zoom"]');
const glyph = button.children[0];
assert.equal(glyph.className, 'material-symbols-outlined');
assert.equal(glyph.textContent, 'zoom_in_map');
assert.equal(glyph.getAttribute('aria-hidden'), 'true');
assert.equal(button.getAttribute('aria-label'), 'Zoom to layer');
assert.equal(button.title, 'Zoom to layer');
assert.equal(button.getAttribute('aria-pressed'), null);
assert.ok(button.classList.contains('chip-icon'));
// The same id as a text toggle drops the icon semantics.
render(
h(LayerRows, {
items: [libraryRow([{ id: 'zoom', label: 'ZOOM', active: true }])],
}),
container,
);
const toggle = element.querySelector('[data-chip-id="zoom"]');
assert.equal(toggle.textContent, 'ZOOM');
assert.equal(toggle.getAttribute('aria-label'), null);
assert.equal(toggle.getAttribute('aria-pressed'), 'true');
assert.equal(toggle.classList.contains('chip-icon'), false);
render(null, container);
});
test('a core row carries no library entry attribute', () => {
document.body.replaceChildren();
const container = document.body.appendChild(document.createElement('div'));
render(h(LayerRows, { items: [row(false)] }), container);
const element = container.querySelector('[data-layer-id="flights"]');
assert.equal(element.hasAttribute('data-library-entry'), false);
render(null, container);
});
+402
View File
@@ -0,0 +1,402 @@
/**
* DATA LAYERS ▸ Browse data library: the owner of the dialog that lists every
* Data Library entry this build knows, with its licence, coverage and what
* this instance needs to serve it, and adds or removes it from the panel.
*
* Framework-free: `createLibraryBrowser` presents the dialog's state (open,
* filters, the rows they show, the stat summary, Remove all) through
* `publish`, and its `controls` answer the view
* (src/ui/views/panels/DataLibraryDialog.vue, placed by LayerPanelsView). The
* text helpers below are what the view renders; they call `t()`, so text
* rendered through them follows the locale.
*
* A `dialog[data-panel-surface]` per docs/panel-surfaces.md: the view owns
* width, height, labels and focus; this owner closes the dialog when clean
* view, recording or Cockpit hides the panels.
*/
import { formatNumber, msg, t, tn } from '../i18n/index.js';
const PANEL_HIDING_MODES = ['ui-clean-view', 'recording-mode', 'cockpit-mode'];
/** How long Remove all stays armed after its first press. */
const RESET_CONFIRM_MS = 4000;
/** How often the open dialog rereads its stat tiles (the panel's own pace). */
const STATS_REFRESH_MS = 1000;
const FAMILY_LABELS = Object.freeze({
movement: msg('Movement'),
cameras: msg('Cameras'),
infrastructure: msg('Infrastructure'),
events: msg('Events'),
weather: msg('Weather'),
environment: msg('Environment'),
imagery: msg('Imagery'),
demographics: msg('Demographics'),
});
const KIND_LABELS = Object.freeze({
dataset: msg('DATASET'),
tiles: msg('TILES'),
pack: msg('PACK'),
});
const STATUS_LABELS = Object.freeze({
incubating: msg('INCUBATING'),
community: msg('COMMUNITY'),
verified: msg('VERIFIED'),
stale: msg('STALE'),
archived: msg('ARCHIVED'),
});
/** The Theme filter's choices, translated: all themes first. */
export function libraryThemeOptions() {
return [
{ value: '', label: t('All themes') },
...Object.entries(FAMILY_LABELS).map(([value, label]) => ({
value,
label: t(label),
})),
];
}
/**
* An entry card's badges: kind, status, then how it is served (operator
* opt-in, a provider key, or keyless). `tone` is '', 'good' or 'warn'.
* @param {object} entry
* @returns {Array<{ label: string, tone: string }>}
*/
export function libraryBadges(entry) {
const badges = [
{ label: t(KIND_LABELS[entry.kind]), tone: '' },
{
label: t(STATUS_LABELS[entry.status]),
tone:
entry.status === 'verified'
? 'good'
: entry.status === 'stale'
? 'warn'
: '',
},
];
if (entry.licence.operatorOptIn)
badges.push({ label: t('OPT-IN'), tone: 'warn' });
else if (entry.kind !== 'pack' && entry.source.key)
badges.push({ label: t('KEY'), tone: 'warn' });
else if (entry.kind !== 'pack')
badges.push({ label: t('KEYLESS'), tone: '' });
return badges;
}
const compact = (value) =>
formatNumber(value, { notation: 'compact', maximumFractionDigits: 1 });
/**
* The four stat tiles at the top of Browse: label, value and one line of
* breakdown each. Text only; nothing here is a data colour.
* @param {ReturnType<ReturnType<typeof import('../library/controller.js').createDataLibrary>['summary']>} summary
* @returns {Array<{ id: string, label: string, value: string, detail: string }>}
*/
export function libraryStatTiles(summary) {
const { kinds } = summary;
return [
{
id: 'entries',
label: t('Datasets'),
value: compact(summary.entries),
detail: t('{datasets} · {tiles} · {packs}', {
datasets: tn(kinds.dataset, '{count} dataset', '{count} datasets'),
tiles: tn(kinds.tiles, '{count} tile layer', '{count} tile layers'),
packs: tn(kinds.pack, '{count} pack', '{count} packs'),
}),
},
{
id: 'themes',
label: t('Themes'),
value: compact(summary.themes.length),
// The count alone: the theme names are the Theme filter below.
detail: '',
},
{
id: 'added',
label: t('Added'),
value: compact(summary.added),
detail: summary.added
? tn(summary.on, '{count} on the map', '{count} on the map')
: t('none yet'),
},
{
id: 'features',
label: t('Map features'),
value: summary.featureLayers ? compact(summary.features) : '—',
detail: summary.featureLayers
? tn(
summary.featureLayers,
'from {count} dataset',
'from {count} datasets',
)
: t('switch on a dataset to load features'),
},
];
}
/** The sentence explaining what this instance needs to serve an entry. */
export function libraryReasonText({ entry, available, reason }) {
if (entry.kind === 'pack')
return available
? t('Switched on by this instance · part of the CCTV layer')
: t('Operator opt-in: set {env}=1 on the server', {
env: entry.pack.env,
});
if (available) return '';
if (reason === 'operator-opt-in')
return t('Operator opt-in: add {id} to GEV_LIBRARY_ENABLE on the server', {
id: entry.id,
});
if (reason === 'operator-disabled')
return t("Turned off by this instance's operator");
if (reason === 'key-missing') return t('Needs a provider key on the server');
if (reason === 'server-unavailable')
return t("Needs this app's server · not available in a static build");
return t('Checking what this instance serves…');
}
/** Where an entry covers, for its card line. */
export function coverageText(entry) {
const { coverage } = entry;
if (coverage.global) return t('Global');
if (coverage.countries?.length) return coverage.countries.join(' · ');
return t('Regional');
}
const IMAGERY_TYPE_LABELS = Object.freeze({
ortho: msg('Orthophoto'),
'satellite-mosaic': msg('Satellite mosaic'),
oblique: msg('Oblique'),
historic: msg('Historic imagery'),
});
/**
* An imagery entry's specs as label/value pairs for its card: what it is,
* how sharp, when it was flown and how often it is refreshed.
* @param {object} entry
* @returns {Array<{ label: string, value: string }>}
*/
export function imagerySpecs(entry) {
const imagery = entry?.imagery;
if (!imagery) return [];
const type =
imagery.type === 'ortho' && imagery.trueOrtho
? t('True orthophoto')
: t(IMAGERY_TYPE_LABELS[imagery.type]);
return [
{ label: t('Type'), value: type },
{ label: t('Resolution'), value: imagery.resolution },
imagery.vintage && { label: t('Flown'), value: imagery.vintage },
imagery.updateCycle && { label: t('Updates'), value: imagery.updateCycle },
imagery.orthoQuality && {
label: t('Ortho quality'),
value: imagery.orthoQuality,
},
].filter(Boolean);
}
/**
* Whether a row matches the current filters.
* @param {{ entry: object, available: boolean, added: boolean }} row
* @param {{ query: string, family: string, availableOnly: boolean }} filter
*/
export function libraryRowMatches(row, { query, family, availableOnly }) {
const { entry } = row;
if (entry.status === 'archived' && !row.added) return false;
if (family && entry.family !== family) return false;
if (availableOnly && !row.available) return false;
const needle = String(query || '')
.trim()
.toLocaleLowerCase();
if (!needle) return true;
return [
entry.title,
entry.provider,
entry.description,
entry.id,
entry.imagery?.resolution,
...(entry.coverage.countries || []),
]
.join(' ')
.toLocaleLowerCase()
.includes(needle);
}
/**
* Browse order: what a viewer can add first, then what this instance would
* need to switch on, then packs (which a host layer owns), each by title.
* @param {Array<{ entry: object, available: boolean }>} rows
*/
export function sortLibraryRows(rows) {
const rank = ({ entry, available }) =>
entry.kind === 'pack' ? 2 : available ? 0 : 1;
return [...rows].sort(
(a, b) =>
rank(a) - rank(b) || a.entry.title.localeCompare(b.entry.title, 'en'),
);
}
/**
* The Browse dialog's owner. Presents its state through `publish` and answers
* the view through `controls`; never touches the dialog's markup.
* @param {{ library: ReturnType<import('../library/controller.js').createDataLibrary>, publish?: (view: object|null) => void, body?: HTMLElement|null }} options
* @returns {{ controls: object, open: () => void, close: () => void, destroy: () => void }}
*/
export function createLibraryBrowser({
library,
publish = () => {},
body = globalThis.document?.body ?? null,
}) {
const filter = { query: '', family: '', availableOnly: false };
let open = false;
let destroyed = false;
let rows = [];
let statsTimer = null;
// Remove all asks twice: the first press arms it for a few seconds.
let resetArmed = false;
let resetTimer = null;
let resetting = false;
// Bumped when focus should go back to the search field (after Remove all).
let focusSearch = 0;
function disarmReset() {
clearTimeout(resetTimer);
resetTimer = null;
resetArmed = false;
}
/**
* Publish the dialog. Rows are reread from the library unless only the
* stat tiles changed, so an unchanged row list keeps its identity and its
* cards do not re-render.
*/
function present({ rowsChanged = true } = {}) {
if (destroyed) return;
if (rowsChanged || !rows.length) rows = library.list();
const added = rows.filter((row) => row.added).length;
if (!added && !resetting && resetArmed) disarmReset();
publish({
open,
ready: library.ready,
filter: { ...filter },
shown: open
? sortLibraryRows(rows.filter((row) => libraryRowMatches(row, filter)))
: [],
total: rows.length,
added,
summary: library.summary(),
reset: {
visible: added > 0 || resetting,
armed: resetArmed,
busy: resetting,
},
focusSearch,
});
}
function close() {
disarmReset();
clearInterval(statsTimer);
statsTimer = null;
if (!open) return;
open = false;
present();
}
const controls = {
open() {
if (destroyed || open) return;
open = true;
present();
// Feature counts arrive as datasets finish loading, outside the
// library's own notifications; refresh the tiles while open.
clearInterval(statsTimer);
statsTimer = setInterval(
() => present({ rowsChanged: false }),
STATS_REFRESH_MS,
);
},
close,
setQuery(value) {
filter.query = String(value ?? '');
present({ rowsChanged: false });
},
setFamily(value) {
filter.family = String(value ?? '');
present({ rowsChanged: false });
},
setAvailableOnly(value) {
filter.availableOnly = Boolean(value);
present({ rowsChanged: false });
},
add(id) {
Promise.resolve(library.add(id)).catch((error) =>
console.warn(`[Library] ${id} failed:`, error),
);
},
remove(id) {
Promise.resolve(library.remove(id)).catch((error) =>
console.warn(`[Library] ${id} failed:`, error),
);
},
zoom(id) {
// Close first so the flight is visible; focus returns to Browse. An
// entry that is off is switched on first.
close();
Promise.resolve(library.zoom(id)).catch((error) =>
console.warn(`[Library] ${id} zoom failed:`, error),
);
},
reset() {
if (resetting) return;
if (!resetArmed) {
resetArmed = true;
resetTimer = setTimeout(() => {
disarmReset();
present({ rowsChanged: false });
}, RESET_CONFIRM_MS);
present({ rowsChanged: false });
return;
}
disarmReset();
resetting = true;
present({ rowsChanged: false });
Promise.resolve(library.reset())
.catch((error) => console.warn('[Library] reset failed:', error))
.finally(() => {
resetting = false;
focusSearch += 1;
present();
});
},
};
const unsubscribe = library.subscribe(() => present());
const observer =
typeof MutationObserver === 'function' && body
? new MutationObserver(() => {
if (PANEL_HIDING_MODES.some((mode) => body.classList.contains(mode)))
close();
})
: null;
observer?.observe(body, { attributes: true, attributeFilter: ['class'] });
present();
return {
controls,
open: controls.open,
close,
destroy() {
if (destroyed) return;
close();
destroyed = true;
unsubscribe();
observer?.disconnect();
publish(null);
},
};
}
+158
View File
@@ -0,0 +1,158 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {
libraryReasonText,
libraryRowMatches,
libraryStatTiles,
sortLibraryRows,
} from './libraryBrowser.js';
import { libraryEntry } from '../library/catalog.js';
import { localInfrastructureOverlayCopy } from '../data/localGeojsonCore.js';
const row = (id, extra = {}) => ({
entry: libraryEntry(id),
available: true,
added: false,
...extra,
});
const all = { query: '', family: '', availableOnly: false };
test('Browse filters by text, theme and what this instance serves', () => {
assert.ok(
libraryRowMatches(row('eia-power-plants'), { ...all, query: 'eia' }),
);
assert.ok(
libraryRowMatches(row('eia-power-plants'), { ...all, query: 'us' }),
);
assert.equal(
libraryRowMatches(row('eia-power-plants'), { ...all, query: 'volcano' }),
false,
);
assert.equal(
libraryRowMatches(row('eia-power-plants'), { ...all, family: 'events' }),
false,
);
assert.equal(
libraryRowMatches(row('cctv-nyc-dot', { available: false }), {
...all,
availableOnly: true,
}),
false,
);
});
test('the guidance names the exact operator switch', () => {
assert.match(
libraryReasonText({ ...row('cctv-nyc-dot'), available: false }),
/CCTV_NYC_ENABLED=1/,
);
assert.match(
libraryReasonText({ ...row('cctv-nyc-dot'), available: true }),
/part of the CCTV layer/,
);
assert.match(
libraryReasonText({
...row('gvp-holocene-volcanoes'),
available: false,
reason: 'server-unavailable',
}),
/static build/,
);
assert.equal(libraryReasonText(row('nasa-eonet-events')), '');
});
test('library features show their manifest card lines on the map', () => {
const copy = localInfrastructureOverlayCopy(
{
name: 'Grand Coulee',
__gevDetails: ['PrimSource: hydroelectric', 'Total_MW: 6809', 'extra'],
},
'lib-eia-power-plants',
);
assert.deepEqual(copy, {
title: 'Grand Coulee',
details: ['PrimSource: hydroelectric', 'Total_MW: 6809'],
});
});
test('Browse lists what a viewer can add first and packs last', () => {
const order = sortLibraryRows([
row('cctv-nyc-dot', { available: false }),
row('nasa-eonet-events'),
row('gvp-holocene-volcanoes', { available: false }),
row('eia-power-plants'),
]).map(({ entry }) => entry.id);
assert.deepEqual(order, [
'nasa-eonet-events',
'eia-power-plants',
'gvp-holocene-volcanoes',
'cctv-nyc-dot',
]);
});
test('the stat tiles summarise the library in words and compact numbers', () => {
const tiles = libraryStatTiles({
entries: 8,
kinds: { dataset: 3, tiles: 2, pack: 3 },
themes: ['cameras', 'environment', 'events', 'imagery', 'infrastructure'],
available: 5,
unavailable: 3,
added: 2,
on: 1,
features: 3712,
featureLayers: 2,
});
assert.deepEqual(
tiles.map(({ id, value, detail }) => [id, value, detail]),
[
['entries', '8', '3 datasets · 2 tile layers · 3 packs'],
['themes', '5', ''],
['added', '2', '1 on the map'],
['features', '3.7K', 'from 2 datasets'],
],
);
const empty = libraryStatTiles({
entries: 1,
kinds: { dataset: 1, tiles: 0, pack: 0 },
themes: ['events'],
available: 1,
unavailable: 0,
added: 0,
on: 0,
features: 0,
featureLayers: 0,
});
assert.deepEqual(
empty.map(({ value, detail }) => [value, detail]),
[
['1', '1 dataset · 0 tile layers · 0 packs'],
['1', ''],
['0', 'none yet'],
['—', 'switch on a dataset to load features'],
],
);
});
test('an imagery card lists type, resolution, years flown and refresh', async () => {
const { imagerySpecs } = await import('./libraryBrowser.js');
const specs = imagerySpecs({
imagery: {
type: 'ortho',
trueOrtho: true,
resolution: '5 cm',
vintage: '2024',
updateCycle: 'Annual',
},
});
assert.deepEqual(
specs.map(({ label }) => label),
['Type', 'Resolution', 'Flown', 'Updates'],
);
assert.equal(specs[0].value, 'True orthophoto');
assert.equal(specs[1].value, '5 cm');
assert.equal(
imagerySpecs(libraryEntry('ign-orthophotos-france'))[0].value,
'Orthophoto',
);
assert.deepEqual(imagerySpecs(libraryEntry('eia-power-plants')), []);
});
+3
View File
@@ -88,6 +88,9 @@ export class LocationControls {
event.target === elements.search
)
return;
// As for the application shortcuts: Cmd+R, Ctrl+W, Alt+E and the like
// belong to the browser and the system. Shift is not a chord.
if (event.metaKey || event.ctrlKey || event.altKey) return;
const index = POI_KEYS.indexOf(event.key.toUpperCase());
if (index !== -1 && index < (cities[cityId]?.pois.length || 0))
onPoi(cityId, index);
+10
View File
@@ -191,6 +191,16 @@ test('location and POI keys route once while form controls retain typing', () =>
f.controls.reset();
assert.deepEqual(f.calls, [['poi', 'a', 1], ['reset']]);
});
test('POI keys held with Cmd, Ctrl or Alt run no POI; Shift still does', () => {
const f = fixture();
const target = { matches: () => false };
for (const modifier of ['metaKey', 'ctrlKey', 'altKey'])
for (const key of ['q', 'w', 'r', 'R'])
f.doc.fire('keydown', { key, target, [modifier]: true });
assert.deepEqual(f.calls, []);
f.doc.fire('keydown', { key: 'W', target, shiftKey: true });
assert.deepEqual(f.calls, [['poi', 'a', 1]]);
});
test('typing clears a failed search error and closing the emptied field drops it too', () => {
const f = fixture();
f.elements.search.value = 'Pariss';
+13 -4
View File
@@ -2,13 +2,16 @@
import UiButton from '../kit/UiButton.vue';
// Keyed chips shared by rail cards; the owner decides what a click does.
// An `icon` chip shows a Material Symbol (named in index.html's `icon_names`
// subset) with its label as the accessible name and tip; an `action` chip
// (Zoom, Remove) is a plain button, not an on/off toggle.
defineProps({
chips: { type: Array, default: () => [] },
onSelect: { type: Function, default: () => {} },
});
const chipClass = (chip) =>
`data-toggle-chip chip-${chip.state || (chip.active ? 'active' : 'idle')}`;
`data-toggle-chip chip-${chip.state || (chip.active ? 'active' : 'idle')}${chip.icon ? ' chip-icon' : ''}`;
</script>
<template>
@@ -17,14 +20,20 @@ const chipClass = (chip) =>
:key="chip.id"
:data-chip-id="chip.id"
:class="chipClass(chip)"
:pressed="Boolean(chip.active)"
:pressed="chip.action ? undefined : Boolean(chip.active)"
pressed-class="active"
:style="chip.color ? `--chip-color: ${chip.color}` : undefined"
:data-chip-color="chip.color || undefined"
:title="chip.title || undefined"
:label="chip.icon ? chip.label : undefined"
:title="chip.title || (chip.icon ? chip.label : undefined)"
:disabled="Boolean(chip.disabled)"
:aria-busy="String(Boolean(chip.busy))"
@click="onSelect(chip)"
>{{ chip.label }}</UiButton
><span
v-if="chip.icon"
class="material-symbols-outlined"
aria-hidden="true"
>{{ chip.icon }}</span
><template v-else>{{ chip.label }}</template></UiButton
>
</template>
+4
View File
@@ -26,6 +26,10 @@ export function railFixture(onWrite = () => {}) {
getAttribute(key) {
return this.attributes.get(key) ?? null;
},
removeAttribute(key) {
onWrite('attribute');
this.attributes.delete(key);
},
appendChild(child) {
return this.insertBefore(child, null);
},
+1 -1
View File
@@ -627,7 +627,7 @@ test('Authoring PLAY uses the scene context, not the radio PLAY', async (context
const f = fixture();
try {
await nextTick();
assert.equal(f.elements.start.textContent, 'REPROD.');
assert.equal(f.elements.start.textContent, 'REPRODUCIR');
} finally {
f.restore();
}
+29
View File
@@ -0,0 +1,29 @@
import { defineStore } from 'pinia';
import { markRaw, shallowRef } from 'vue';
/**
* DATA LAYERS ▸ Browse data library as its view renders it. The browser owner
* (src/ui/libraryBrowser.js) presents whether the dialog is open, the rows
* the filters show, the stat tiles' summary and Remove all's state, and
* publishes them here; the view sends clicks and typing to the connected
* owner.
*/
export const useDataLibraryStore = defineStore('gev-data-library', () => {
/** The presented browser; null until the owner first publishes. */
const view = shallowRef(null);
/** @param {?object} next A fresh presentation; every publish re-renders. */
function publish(next) {
view.value = next && markRaw(next);
}
/** The browser owner the controls call, or null while none is wired. */
const controls = shallowRef(null);
/** @param {?object} next The owner's controls, or null to disconnect. */
function connect(next) {
controls.value = next && markRaw(next);
}
return { view, publish, controls, connect };
});
+4 -1
View File
@@ -250,8 +250,11 @@ html:not([lang='en']) .cctv-controls .scene-btn {
height: auto;
object-fit: contain;
display: block;
/* No fade: a camera change hides the old frame at once (never its pixels
under the new camera) and shows the new one as soon as it is decoded. A
180 ms fade-in after every arriving frame made each camera click linger
on black. */
opacity: 0;
transition: opacity 180ms ease;
}
#cctv-video {
+368
View File
@@ -0,0 +1,368 @@
/* Data Library: the Browse button under DATA LAYERS and its dialog.
The dialog is a dialog[data-panel-surface] (docs/panel-surfaces.md): the
shared skin draws the surface; this file owns geometry and the list. */
.data-library-footer {
padding: 8px 10px 4px;
border-top: 1px solid var(--glass-border);
}
.data-library-browse {
width: 100%;
min-height: 30px;
padding: 6px 10px;
border: 1px dashed var(--glass-border-hover);
border-radius: var(--btn-radius);
background: transparent;
color: var(--text-secondary);
font: 600 10px/1.4 var(--font-mono);
letter-spacing: 1.2px;
cursor: pointer;
transition:
color var(--transition-fast),
border-color var(--transition-fast),
background var(--transition-fast);
}
.data-library-browse:hover,
.data-library-browse:focus-visible {
color: var(--text-primary);
border-color: var(--accent);
background: var(--accent-dim);
}
.data-library-browse:focus-visible {
outline: 2px solid var(--text-primary);
outline-offset: 2px;
}
.data-library-dialog {
/* Frosted rather than opaque: a lighter surface than the rail panels
(0.72) keeps the globe's colour visible, and the blur stops the HUD text
behind the dialog from competing with the dialog's own. */
--glass-bg: rgba(12, 12, 20, 0.55);
width: min(560px, calc(100vw - 32px));
max-height: min(720px, calc(100dvh - 48px));
margin: auto;
color: var(--text-primary);
-webkit-backdrop-filter: blur(22px) saturate(1.3);
backdrop-filter: blur(22px) saturate(1.3);
/* The blur follows the surface's shape (Cyber's cut corners). The dialog
has no outward popups for a clip to hide. */
clip-path: var(--panel-surface-frame);
}
.data-library-dialog::backdrop {
background: rgba(0, 0, 0, 0.12);
}
.data-library-close {
min-width: 30px;
font-size: 16px;
line-height: 1;
}
/* At a glance: four stat tiles above the intro. Text tokens only. */
.data-library-stats {
display: grid;
grid-template-columns: repeat(4, minmax(0, 1fr));
gap: 6px;
margin: 0 0 12px;
}
.data-library-stat {
display: flex;
flex-direction: column;
gap: 2px;
min-width: 0;
padding: 8px 10px;
border: 1px solid var(--glass-border);
border-radius: 8px;
background: rgba(8, 10, 16, 0.38);
}
.data-library-stat-label {
color: var(--text-secondary);
font: 600 9px/1.3 var(--font-mono);
letter-spacing: 0.1em;
text-transform: uppercase;
}
.data-library-stat-value {
margin: 0;
color: var(--text-primary);
font: 600 20px/1.15 var(--font-sans);
}
.data-library-stat-detail {
margin: 0;
color: rgba(232, 234, 237, 0.68);
font-size: 10px;
line-height: 1.35;
overflow-wrap: anywhere;
}
:root[data-ui-theme='cyber'] .data-library-stat {
border-radius: 0;
}
:root[data-ui-theme='cyber'] .data-library-stat-value {
font-family: var(--font-mono);
}
.data-library-intro {
margin: 0 0 10px;
color: rgba(232, 234, 237, 0.72);
}
.data-library-filters {
display: grid;
grid-template-columns: minmax(0, 1.4fr) minmax(0, 1fr);
gap: 8px;
margin-bottom: 6px;
}
.data-library-field {
display: flex;
flex-direction: column;
gap: 3px;
min-width: 0;
color: var(--text-secondary);
font-size: 10px;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.data-library-field .panel-surface-control {
text-transform: none;
letter-spacing: normal;
font-size: 12px;
}
.data-library-check {
grid-column: 1 / -1;
display: flex;
align-items: center;
gap: 6px;
color: var(--text-secondary);
}
.data-library-toolbar {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
margin: 4px 0 8px;
}
.data-library-status {
margin: 0;
color: var(--text-secondary);
font: 10px/1.4 var(--font-mono);
}
.data-library-reset {
min-height: 26px;
padding: 3px 10px;
font: 600 10px/1.4 var(--font-mono);
letter-spacing: 1px;
}
.data-library-reset.is-armed {
border-color: var(--panel-surface-error);
color: var(--panel-surface-error);
}
.data-library-list {
display: flex;
flex-direction: column;
gap: 8px;
margin: 0;
padding: 0;
list-style: none;
}
.data-library-item {
display: grid;
grid-template-columns: minmax(0, 1fr) auto;
column-gap: 10px;
row-gap: 4px;
padding: 10px;
border: 1px solid var(--glass-border);
border-radius: 10px;
background: rgba(8, 10, 16, 0.38);
}
.data-library-item.is-on {
border-color: var(--accent-glow);
}
.data-library-item.is-unavailable .data-library-name,
.data-library-item.is-unavailable .data-library-description {
color: var(--text-secondary);
}
.data-library-item > :not(.data-library-actions) {
grid-column: 1;
}
.data-library-actions {
grid-column: 2;
grid-row: 1 / span 3;
align-self: center;
display: flex;
flex-direction: column;
gap: 6px;
}
.data-library-action {
min-width: 82px;
font: 600 10px/1.4 var(--font-mono);
letter-spacing: 1px;
}
.data-library-item-head {
display: flex;
flex-wrap: wrap;
align-items: baseline;
gap: 6px;
min-width: 0;
}
.data-library-icon {
width: 14px;
color: var(--accent);
text-align: center;
}
.data-library-name {
font-weight: 600;
overflow-wrap: anywhere;
}
.data-library-badges {
display: inline-flex;
flex-wrap: wrap;
gap: 4px;
}
.data-library-badge {
padding: 0 5px;
border: 1px solid var(--glass-border-hover);
border-radius: 4px;
color: var(--text-secondary);
font: 600 9px/1.6 var(--font-mono);
letter-spacing: 0.08em;
}
.data-library-badge--good {
border-color: var(--accent-glow);
color: var(--accent);
}
.data-library-badge--warn {
border-color: rgba(255, 194, 61, 0.45);
color: #ffc23d;
}
.data-library-description,
.data-library-meta,
.data-library-reason {
margin: 0;
overflow-wrap: anywhere;
}
.data-library-meta {
color: rgba(232, 234, 237, 0.68);
font-size: 11px;
}
.data-library-meta a {
color: inherit;
text-decoration: underline;
text-underline-offset: 2px;
}
.data-library-meta a:hover,
.data-library-meta a:focus-visible {
color: var(--text-primary);
}
/* Imagery specs: label over value, wrapping into as many columns as fit. */
.data-library-specs {
display: flex;
flex-wrap: wrap;
gap: 4px 16px;
margin: 0;
}
.data-library-spec {
display: flex;
flex-direction: column;
min-width: 0;
}
.data-library-spec dt {
color: rgba(232, 234, 237, 0.56);
font: 9px/1.4 var(--font-mono);
letter-spacing: 0.08em;
text-transform: uppercase;
}
.data-library-spec dd {
margin: 0;
color: var(--text-primary);
font-size: 11px;
overflow-wrap: anywhere;
}
.data-library-reason {
color: #ffc23d;
font: 10px/1.5 var(--font-mono);
}
:root[data-ui-theme='cyber'] .data-library-dialog {
--glass-bg: rgba(18, 24, 27, 0.62);
width: min(600px, calc(100vw - 32px));
}
:root[data-ui-theme='cyber'] .data-library-item {
border-radius: 0;
}
:root[data-ui-theme='cyber']
:is(.data-library-icon, .data-library-badge--good) {
color: var(--cyber-red-bright);
border-color: var(--cyber-red-bright);
}
@media (max-width: 720px) {
.data-library-stats {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
.data-library-filters {
grid-template-columns: minmax(0, 1fr);
}
.data-library-item {
grid-template-columns: minmax(0, 1fr);
}
.data-library-actions {
grid-column: 1;
grid-row: auto;
flex-direction: row;
justify-self: start;
}
}
body:is(.ui-clean-view, .recording-mode) .data-library-dialog {
display: none;
}
/* Library rows list their legend one item per line, as Fire Perimeters'
longer labels do, with the zoom and remove icons on their own line. */
.data-toggle-row[data-library-entry] .data-toggle-legend-item {
flex-basis: 100%;
}
+24
View File
@@ -905,6 +905,30 @@ html:not([lang='en'])
outline: none;
}
/* An icon action chip (RailChips.vue `icon`): a square button sized to the
text chips beside it. */
.data-toggle-chip.chip-icon {
display: inline-flex;
align-items: center;
justify-content: center;
min-width: 24px;
height: 20px;
padding: 0 4px;
letter-spacing: 0;
/* A glyph alone needs more contrast than a text chip to read. */
color: var(--text-secondary);
}
.data-toggle-chip.chip-icon:hover,
.data-toggle-chip.chip-icon:focus-visible {
color: var(--text-primary);
}
.data-toggle-chip.chip-icon .material-symbols-outlined {
font-size: 15px;
line-height: 1;
}
.data-toggle-chip:hover,
.data-toggle-chip:focus-visible {
border-color: var(--glass-border-hover);
+1
View File
@@ -437,6 +437,7 @@ html:not([lang='en']) #scene-panel .scene-controls .scene-btn {
#control-panel.collapsed .button-grid,
#data-panel.collapsed .data-toggle-list,
#data-panel.collapsed .data-library-footer,
#global-context-panel.collapsed #radio-panel,
#global-context-panel.collapsed #military-awareness-panel,
#global-context-panel.collapsed .global-context-actions,
+3
View File
@@ -14,6 +14,7 @@ import StreetLevelPanel from './panels/StreetLevelPanel.vue';
import DrawControls from './panels/DrawControls.vue';
import GeoImport from './panels/GeoImport.vue';
import UiSelect from '../kit/UiSelect.js';
import DataLibraryBrowse from './panels/DataLibraryBrowse.vue';
// Scene sharing (src/scenes/sharing.js) offers its authoring bar and presents
// its dialog through this store; without this view, neither is drawn.
@@ -43,6 +44,8 @@ async function importChosen(event) {
<!-- Data Layer Toggle Panel -->
<RailPanel id="data-panel" start-collapsed class="active" :title="t('DATA LAYERS')">
<div id="data-toggles" class="data-toggle-list ui-scroll"></div>
<!-- Data Library: Browse and its dialog (src/ui/libraryBrowser.js). -->
<DataLibraryBrowse />
</RailPanel>
<!-- Utilities: Directions (LayerPanel renders its row here), Draw, Import -->
+29
View File
@@ -0,0 +1,29 @@
<script setup>
import { storeToRefs } from 'pinia';
import { t } from '../../../i18n/index.js';
import UiButton from '../../kit/UiButton.vue';
import { useDataLibraryStore } from '../../stores/dataLibrary.js';
import DataLibraryDialog from './DataLibraryDialog.vue';
// DATA LAYERS ▸ Browse data library: the button at the foot of the panel and
// the dialog it opens, drawn once the library browser (src/ui/libraryBrowser.js)
// publishes. Kept apart from LayerPanelsView so the browser's publishes (the
// stat tiles refresh every second while open) re-render only this.
const { view, controls } = storeToRefs(useDataLibraryStore());
</script>
<template>
<div class="data-library-footer">
<UiButton
id="data-library-browse"
class="data-library-browse"
aria-haspopup="dialog"
aria-controls="data-library"
:hidden="!view"
:native-title="false"
@click="controls?.open()"
>{{ t('BROWSE DATA LIBRARY') }}</UiButton
>
</div>
<Teleport v-if="view" to="body"><DataLibraryDialog :view="view" /></Teleport>
</template>
+93
View File
@@ -0,0 +1,93 @@
<script setup>
import { computed } from 'vue';
import { t } from '../../../i18n/index.js';
import UiButton from '../../kit/UiButton.vue';
import {
coverageText,
imagerySpecs,
libraryBadges,
libraryReasonText,
} from '../../libraryBrowser.js';
// One Data Library entry in Browse, as src/ui/libraryBrowser.js lists it:
// what it is, who provides it under what licence, what this instance needs
// to serve it, and Add / Remove / Zoom. The parent keys cards by entry id, so
// a card (and its focused button) survives Add becoming Remove.
const props = defineProps({ row: { type: Object, required: true } });
const emit = defineEmits(['add', 'remove', 'zoom']);
const entry = computed(() => props.row.entry);
const reason = computed(() => libraryReasonText(props.row));
const actionLabel = computed(() =>
props.row.added
? t('Remove {name} from Data Layers', { name: entry.value.title })
: t('Add {name} to Data Layers', { name: entry.value.title }),
);
</script>
<template>
<li
class="data-library-item"
:class="{
'is-unavailable': !row.available,
'is-on': entry.kind !== 'pack' && row.added && row.on,
}"
:data-library-id="entry.id"
>
<div class="data-library-item-head">
<span class="data-library-icon" aria-hidden="true">{{ entry.icon }}</span>
<span class="data-library-name">{{ entry.title }}</span>
<span class="data-library-badges">
<span
v-for="badge in libraryBadges(entry)"
:key="badge.label"
class="data-library-badge"
:class="badge.tone ? `data-library-badge--${badge.tone}` : undefined"
>{{ badge.label }}</span
>
</span>
</div>
<p class="data-library-description">{{ entry.description }}</p>
<dl v-if="entry.imagery" class="data-library-specs">
<div
v-for="spec in imagerySpecs(entry)"
:key="spec.label"
class="data-library-spec"
>
<dt>{{ spec.label }}</dt>
<dd>{{ spec.value }}</dd>
</div>
</dl>
<p class="data-library-meta">
<span translate="no">{{ entry.provider }}</span> ·
<span>{{ coverageText(entry) }}</span> ·
<a :href="entry.licence.url" target="_blank" rel="noopener noreferrer">{{
entry.licence.name
}}</a>
</p>
<p v-if="reason" class="data-library-reason">{{ reason }}</p>
<div v-if="entry.kind !== 'pack'" class="data-library-actions">
<UiButton
v-if="row.added && row.canZoom"
class="panel-surface-control data-library-action"
:data-library-id="entry.id"
data-library-action="zoom"
:disabled="row.busy"
:label="t('Zoom to {name}', { name: entry.title })"
:native-title="false"
@click="emit('zoom', entry.id)"
>{{ t('ZOOM') }}</UiButton
>
<UiButton
class="panel-surface-control data-library-action"
:data-library-id="entry.id"
:data-library-action="row.added ? 'remove' : 'add'"
:disabled="row.busy || (!row.added && !row.available)"
:label="actionLabel"
:native-title="false"
@click="emit(row.added ? 'remove' : 'add', entry.id)"
>{{ row.busy ? t('WORKING…') : row.added ? t('REMOVE') : t('ADD') }}</UiButton
>
</div>
</li>
</template>
@@ -0,0 +1,237 @@
// The Browse dialog renders what src/ui/libraryBrowser.js presents and sends
// clicks and typing back to it.
import '../../../testSupport/registerDom.mjs';
import test from 'node:test';
import assert from 'node:assert/strict';
import { createApp, defineComponent, h, nextTick } from 'vue';
import { createPinia, storeToRefs } from 'pinia';
import { setLocale, t } from '../../../i18n/index.js';
import { libraryEntry } from '../../../library/catalog.js';
import { createLibraryBrowser } from '../../libraryBrowser.js';
import { useDataLibraryStore } from '../../stores/dataLibrary.js';
import { applicationI18n } from '../../i18n.js';
import DataLibraryDialog from './DataLibraryDialog.vue';
const IDS = ['nasa-eonet-events', 'eia-power-plants', 'cctv-nyc-dot'];
/** A library with three entries; Add and Remove change what it lists. */
function fakeLibrary() {
const added = new Set();
const listeners = new Set();
const notify = () => listeners.forEach((listener) => listener());
return {
ready: true,
added,
calls: [],
subscribe(listener) {
listeners.add(listener);
return () => listeners.delete(listener);
},
list: () =>
IDS.map((id) => ({
entry: libraryEntry(id),
available: id !== 'cctv-nyc-dot',
reason: id === 'cctv-nyc-dot' ? 'operator-opt-in' : null,
added: added.has(id),
on: added.has(id),
busy: false,
canZoom: added.has(id),
})),
summary: () => ({
entries: IDS.length,
kinds: { dataset: 2, tiles: 0, pack: 1 },
themes: ['cameras', 'events', 'infrastructure'],
available: 2,
unavailable: 1,
added: added.size,
on: added.size,
features: 0,
featureLayers: 0,
}),
async add(id) {
added.add(id);
notify();
return true;
},
async remove(id) {
added.delete(id);
notify();
return true;
},
async zoom(id) {
this.calls.push(['zoom', id]);
return true;
},
async reset() {
const count = added.size;
added.clear();
notify();
return count;
},
};
}
const settle = async () => {
for (let i = 0; i < 4; i += 1) {
await nextTick();
await new Promise((resolve) => setTimeout(resolve, 0));
}
};
function mount(t_) {
document.body.replaceChildren();
const browse = document.createElement('button');
browse.id = 'data-library-browse';
document.body.append(browse);
const pinia = createPinia();
const store = useDataLibraryStore(pinia);
const library = fakeLibrary();
const owner = createLibraryBrowser({
library,
publish: (view) => store.publish(view),
});
store.connect(owner.controls);
const Host = defineComponent({
setup() {
const { view } = storeToRefs(store);
return () => (view.value ? h(DataLibraryDialog, { view: view.value }) : null);
},
});
// The page's i18n, as mountApplicationViews installs it: the locale views
// re-render on.
const app = createApp(Host).use(pinia).use(applicationI18n());
app.mount(document.body.appendChild(document.createElement('div')));
t_.after(() => {
owner.destroy();
app.unmount();
setLocale('en');
});
return { owner, library };
}
const $ = (selector) => document.querySelector(selector);
const shownIds = () =>
[...document.querySelectorAll('#data-library .data-library-item')].map(
(item) => item.dataset.libraryId,
);
test('Browse opens a modal on the search field, packs last; Escape returns to Browse', async (t_) => {
const { owner } = mount(t_);
assert.equal($('#data-library').open, false);
owner.open();
await settle();
assert.equal($('#data-library').open, true);
assert.equal(document.activeElement, $('#data-library input[type="search"]'));
assert.equal($('#data-library-title').textContent.trim(), 'DATA LIBRARY');
assert.equal(shownIds().at(-1), 'cctv-nyc-dot');
assert.match(
$('[data-library-id="cctv-nyc-dot"] .data-library-reason').textContent,
/CCTV_NYC_ENABLED=1/,
);
assert.equal(
$('[data-library-id="cctv-nyc-dot"] .data-library-action'),
null,
'a pack offers no Add',
);
$('#data-library').dispatchEvent(new Event('cancel', { cancelable: true }));
await settle();
assert.equal($('#data-library').open, false);
assert.equal(document.activeElement, $('#data-library-browse'));
});
test('filters narrow the list as the viewer types and picks', async (t_) => {
const { owner } = mount(t_);
owner.open();
await settle();
const search = $('#data-library input[type="search"]');
search.value = 'eonet';
search.dispatchEvent(new Event('input'));
await settle();
assert.deepEqual(shownIds(), ['nasa-eonet-events']);
assert.match($('.data-library-status').textContent, /1 of 3/);
search.value = '';
search.dispatchEvent(new Event('input'));
const only = $('.data-library-check input');
only.checked = true;
only.dispatchEvent(new Event('change'));
await settle();
assert.equal(shownIds().includes('cctv-nyc-dot'), false);
const theme = $('#data-library select');
theme.value = 'events';
theme.dispatchEvent(new Event('change'));
await settle();
assert.deepEqual(shownIds(), ['nasa-eonet-events']);
});
test('Add becomes Remove on the same focused button; Zoom closes first', async (t_) => {
const { owner, library } = mount(t_);
owner.open();
await settle();
const add = $('button[data-library-id="nasa-eonet-events"][data-library-action="add"]');
add.focus();
add.click();
await settle();
assert.deepEqual([...library.added], ['nasa-eonet-events']);
const remove = $(
'button[data-library-id="nasa-eonet-events"]:not([data-library-action="zoom"])',
);
assert.equal(remove.dataset.libraryAction, 'remove');
assert.equal(document.activeElement, remove, 'focus stays on the button');
assert.equal($('[data-stat="added"] .data-library-stat-value').textContent, '1');
$('button[data-library-id="nasa-eonet-events"][data-library-action="zoom"]').click();
await settle();
assert.equal($('#data-library').open, false);
assert.deepEqual(library.calls, [['zoom', 'nasa-eonet-events']]);
});
test('Remove all asks twice, then focuses the search field', async (t_) => {
const { owner, library } = mount(t_);
await library.add('nasa-eonet-events');
await library.add('eia-power-plants');
owner.open();
await settle();
const reset = () => $('#data-library .data-library-reset');
assert.equal(reset().hidden, false);
reset().click();
await settle();
assert.equal(reset().classList.contains('is-armed'), true);
assert.match(reset().textContent, /CONFIRM/);
assert.equal(library.added.size, 2, 'one press removes nothing');
reset().click();
await settle();
assert.equal(library.added.size, 0);
assert.equal(reset().hidden, true);
assert.equal(document.activeElement, $('#data-library input[type="search"]'));
});
test('a language switch relabels the open dialog and keeps its filters', async (t_) => {
const { owner } = mount(t_);
owner.open();
await settle();
const search = $('#data-library input[type="search"]');
search.value = 'eonet';
search.dispatchEvent(new Event('input'));
await settle();
setLocale('de');
await settle();
const title = $('#data-library-title').textContent.trim();
assert.equal(title, t('DATA LIBRARY'));
assert.notEqual(title, 'DATA LIBRARY');
assert.equal(
$('.data-library-action').textContent.trim(),
t('ADD'),
'cards follow the locale too',
);
assert.equal($('#data-library').open, true);
assert.equal($('#data-library input[type="search"]').value, 'eonet');
});
test('clean view closes an open dialog', async (t_) => {
const { owner } = mount(t_);
owner.open();
await settle();
document.body.classList.add('ui-clean-view');
await settle();
assert.equal($('#data-library').open, false);
document.body.classList.remove('ui-clean-view');
});
+187
View File
@@ -0,0 +1,187 @@
<script setup>
import { storeToRefs } from 'pinia';
import { computed, nextTick, useTemplateRef, watch } from 'vue';
import { t, tn } from '../../../i18n/index.js';
import UiButton from '../../kit/UiButton.vue';
import UiSelect from '../../kit/UiSelect.js';
import {
libraryStatTiles,
libraryThemeOptions,
} from '../../libraryBrowser.js';
import { useDataLibraryStore } from '../../stores/dataLibrary.js';
import DataLibraryCard from './DataLibraryCard.vue';
// DATA LAYERS ▸ Browse data library, as src/ui/libraryBrowser.js presents it.
// A modal `dialog[data-panel-surface]` (docs/panel-surfaces.md): this view
// opens and closes it as the owner says, moves focus (search on open and
// after Remove all, Browse on close) and sends every click and keystroke to
// the owner. All text is translated here, so it follows the locale.
const props = defineProps({ view: { type: Object, required: true } });
const { controls } = storeToRefs(useDataLibraryStore());
const root = useTemplateRef('root');
const search = useTemplateRef('search');
watch(
() => props.view.open,
async (open, wasOpen) => {
await nextTick();
const dialog = root.value;
if (!dialog) return;
if (open) {
if (!dialog.open) dialog.showModal?.();
search.value?.focus();
return;
}
if (dialog.open) dialog.close();
// The browser may already have closed it (Escape is not always
// cancelable); either way focus returns to Browse, unless the viewer
// has moved it somewhere else meanwhile.
const active = document.activeElement;
if (wasOpen && (!active || active === document.body || dialog.contains(active)))
document.getElementById('data-library-browse')?.focus();
},
{ immediate: true },
);
watch(
() => props.view.focusSearch,
async () => {
await nextTick();
if (props.view.open) search.value?.focus();
},
);
const tiles = computed(() => libraryStatTiles(props.view.summary));
const themes = computed(() => libraryThemeOptions());
const status = computed(() =>
props.view.ready
? t('Showing {shown} of {total}', {
shown: props.view.shown.length,
total: props.view.total,
})
: t('Checking what this instance serves…'),
);
const resetText = computed(() => {
const { reset, added } = props.view;
if (reset.busy) return t('WORKING…');
return reset.armed
? tn(added, 'CONFIRM · REMOVE {count}', 'CONFIRM · REMOVE ALL {count}')
: t('REMOVE ALL');
});
const resetLabel = computed(() =>
props.view.reset.armed
? t('Confirm: remove every added entry from Data Layers')
: t('Remove every added entry from Data Layers'),
);
// A click on the backdrop (the dialog box itself, outside its content)
// dismisses, like Escape.
const onDialogClick = (event) => {
if (event.target === event.currentTarget) controls.value?.close();
};
</script>
<template>
<dialog
id="data-library"
ref="root"
class="data-library-dialog"
data-panel-surface
aria-labelledby="data-library-title"
aria-describedby="data-library-intro"
@cancel.prevent="controls?.close()"
@close="view.open && controls?.close()"
@click="onDialogClick"
>
<header class="data-library-header" data-panel-header>
<h2 id="data-library-title" class="panel-title panel-surface-title">
{{ t('DATA LIBRARY') }}
</h2>
<UiButton
class="panel-surface-control data-library-close"
:label="t('Close data library')"
:native-title="false"
@click="controls?.close()"
>×</UiButton
>
</header>
<div class="data-library-body" data-panel-body>
<dl class="data-library-stats" :aria-label="t('Data Library at a glance')">
<div
v-for="tile in tiles"
:key="tile.id"
class="data-library-stat"
:data-stat="tile.id"
>
<dt class="data-library-stat-label">{{ tile.label }}</dt>
<dd class="data-library-stat-value">{{ tile.value }}</dd>
<dd class="data-library-stat-detail" :hidden="!tile.detail">
{{ tile.detail }}
</dd>
</div>
</dl>
<p id="data-library-intro" class="data-library-intro">
{{
t(
'Live sources beyond the core layers. Each one is fetched from its provider while it is on; nothing is stored in this app. Add one and it appears in Data Layers under Library.',
)
}}
</p>
<div class="data-library-filters">
<label class="data-library-field">
<span>{{ t('Search') }}</span>
<input
ref="search"
class="panel-surface-control"
type="search"
autocomplete="off"
:placeholder="t('Name, provider or country')"
:value="view.filter.query"
@input="controls?.setQuery($event.target.value)"
/>
</label>
<label class="data-library-field">
<span>{{ t('Theme') }}</span>
<UiSelect
class="panel-surface-control"
:options="themes"
:model-value="view.filter.family"
@update:model-value="controls?.setFamily($event)"
/>
</label>
<label class="data-library-check">
<input
type="checkbox"
:checked="view.filter.availableOnly"
@change="controls?.setAvailableOnly($event.target.checked)"
/>
<span>{{ t('Only what this instance serves') }}</span>
</label>
</div>
<div class="data-library-toolbar">
<p class="data-library-status" role="status" aria-live="polite">
{{ status }}
</p>
<UiButton
class="panel-surface-control data-library-reset"
:class="{ 'is-armed': view.reset.armed }"
:hidden="!view.reset.visible"
:disabled="view.reset.busy"
:label="resetLabel"
:native-title="false"
@click="controls?.reset()"
>{{ resetText }}</UiButton
>
</div>
<ul class="data-library-list">
<DataLibraryCard
v-for="row in view.shown"
:key="row.entry.id"
:row="row"
@add="controls?.add($event)"
@remove="controls?.remove($event)"
@zoom="controls?.zoom($event)"
/>
</ul>
</div>
</dialog>
</template>
+16 -3
View File
@@ -117,10 +117,23 @@ test('the supplied search target retains editing even without form markup', () =
assert.deepEqual(f.calls, [['dismissSearch']]);
});
test('shortcut extraction does not change repeat or modifier policy', () => {
test('a held key still repeats its shortcut, and Shift is not a chord', () => {
const f = shortcuts();
f.press('h', new Element(), { repeat: true, ctrlKey: true });
assert.deepEqual(f.calls, [['toggleHud']]);
f.press('h', new Element(), { repeat: true });
f.press('C', new Element(), { shiftKey: true });
assert.deepEqual(f.calls, [['toggleHud'], ['toggleCctv']]);
});
test('browser and system chords on a shortcut key run no shortcut', () => {
const f = shortcuts();
for (const modifier of ['metaKey', 'ctrlKey', 'altKey'])
for (const key of ['1', '6', 'h', 'o', 'v', 'f', 'd', 'c', 'C'])
f.press(key, new Element(), { [modifier]: true });
// Copying (Cmd+C, Ctrl+C) used to turn CCTV on and open the nearest camera.
assert.deepEqual(f.calls, []);
f.press('c');
f.press('Escape', new Element(), { ctrlKey: true });
assert.deepEqual(f.calls, [['toggleCctv'], ['dismissSearch']]);
});
test('destroy synchronously removes shortcuts and a replacement binds once', () => {