Port the Data Library Browse dialog to Vue and Pinia

The dialog is now DataLibraryDialog.vue (with DataLibraryCard.vue for each
entry), placed with the Browse button by DataLibraryBrowse.vue in
LayerPanelsView and teleported to the body. It renders what the
gev-data-library store holds and sends clicks and typing to the owner.

src/ui/libraryBrowser.js is now the framework-free owner: it presents the
open state, filters, the rows they show, the stat summary and Remove all
through `publish`, and its controls answer the view. Its text helpers are
what the view renders with t(), so every label follows the locale without
rebuilding anything. Only showModal/close and focus moves stay imperative;
focus returns to Browse also when the browser closes the dialog on Escape
itself.

Component tests mount the view over the real owner (open, filters, Add to
Remove keeping focus, Zoom, Remove all, a language switch, clean view).
This commit is contained in:
Said Turksever committed 2026-11-12 23:01:00 +00:00
1 parent 24ccdd4dc3
commit 1a2589d4ef
11 files changed
+773 -474

No files matched your search

+3 -5
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,11 +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: src/ui/libraryBrowser.js owns the dialog; the button
shows once the library controller is mounted (src/app/tools.js). -->
<div class="data-library-footer">
<button id="data-library-browse" type="button" class="data-library-browse" aria-haspopup="dialog" aria-controls="data-library" hidden>{{ t('BROWSE DATA LIBRARY') }}</button>
</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>