From 52ebd8ac9409dda562678ea11779cf70bca1eee9 Mon Sep 17 00:00:00 2001 From: bassem chagra Date: Sat, 24 Oct 2026 13:50:03 +0200 Subject: [PATCH 01/17] feat(alpr): show datasheet specs for mapped ALPR camera models Read the OSM `model` tag on ALPR records and resolve it, with the `manufacturer` tag, against 16 vendored CCTV Camera Database records (v2.29.0): Motorola Solutions Vigilant, Genetec AutoVu, Axis, Verkada and Bosch MIC. A resolved camera's card gains a SPEC line; an unknown or mis-attributed model shows nothing, and the raw tag text never reaches the card or the voice tools. The CCTV matcher becomes createModelSpecLookup(records) so both layers share one set of matching rules, and specSummary falls back to pixel size or megapixels when a record has no resolution label. 459 of the 1,567 OSM ALPR nodes with a model tag resolve. The hourly extract the layer reads by default has no model field yet, so tile records carry it only once the extract publishes it. --- DATA_SOURCES.md | 7 + docs/CURRENT-STATE.md | 7 + scripts/package-boundaries.json | 4 + src/data/alprCameras.test.mjs | 1 + src/layers/alpr/modelSpecs.js | 257 ++++++++++++++++++++++++++++ src/layers/alpr/modelSpecs.test.mjs | 100 +++++++++++ src/layers/alpr/records.js | 2 + src/layers/alpr/tileRecords.js | 2 + src/layers/alpr/visuals.js | 10 +- src/layers/cctv/modelSpecs.js | 115 +++++++------ 10 files changed, 452 insertions(+), 53 deletions(-) create mode 100644 src/layers/alpr/modelSpecs.js create mode 100644 src/layers/alpr/modelSpecs.test.mjs diff --git a/DATA_SOURCES.md b/DATA_SOURCES.md index 3557c4137b..13c3dbac80 100644 --- a/DATA_SOURCES.md +++ b/DATA_SOURCES.md @@ -234,6 +234,13 @@ commercial use with attribution and applicable database share-alike/access obligations; it does not license the application code. Trimmed test-only tile fixtures retain their provenance in `src/data/fixtures/README.md`. +A mapped `model` tag that names datasheet hardware adds a spec line to the +selected card. The specs are 16 verbatim CC0-1.0 records from the CCTV Camera +Database model-enrichment extract (v2.29.0), compiled into +`src/layers/alpr/modelSpecs.js`; nothing is fetched at runtime, and an +unrecognised tag is never displayed. The hourly extract does not carry `model` +yet, so only an Overpass-backed source shows these lines today. + ### CCTV Camera Database (`src/layers/cctv/modelSpecs.js`) The CCTV layer's hardware-model specs are a small verbatim extract (v2.26.0) of the diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index ede889fdc7..fddce328ae 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -788,6 +788,13 @@ The row count explicitly says **nearby**: loaded records can be outside the screen. Cyan camera badges use Manjunath's camera artwork; selection switches to a larger coral badge with corner brackets and an animated tactical card. Numeric mapped bearings draw illustrative 90 m direction wedges (not measured coverage). +A camera whose OSM `model` tag names known hardware (Motorola Solutions Vigilant, +Genetec AutoVu SharpV, Axis, Verkada, Bosch MIC; 459 of the 1,567 tagged cameras +in October 2026) gets a `SPEC` line on its card from vendored datasheet records +(`src/layers/alpr/modelSpecs.js`, matched with the CCTV layer's +`createModelSpecLookup`). A `manufacturer` naming another maker rejects the +match, and the raw tag text is never shown. The hourly extract has no `model` +field yet, so only an Overpass-backed source fills it. The shared overlay paints gradients for at most 64 nearby cameras, promoting the selected camera; farther cameras keep native Cesium badges without wedges. Native ground-clamped wedges (a ground polyline plus a classification polygon per diff --git a/scripts/package-boundaries.json b/scripts/package-boundaries.json index 3970a1ee2d..3787b57b1e 100644 --- a/scripts/package-boundaries.json +++ b/scripts/package-boundaries.json @@ -1497,6 +1497,8 @@ "src/layers/alpr/policy.js", "src/layers/alpr/presentation.js", "src/layers/alpr/visuals.js", + "src/layers/alpr/modelSpecs.js", + "src/layers/cctv/modelSpecs.js", "src/layers/alpr/overlay.js", "src/layers/alpr/source.js", "src/data/inputOwnership.js", @@ -1927,6 +1929,7 @@ "src/layers/alpr/policy.js", "src/layers/alpr/presentation.js", "src/layers/alpr/visuals.js", + "src/layers/alpr/modelSpecs.js", "src/layers/alpr/overlay.js", "src/layers/alpr/source.js", "src/layers/awareness/controls.js", @@ -2717,6 +2720,7 @@ "src/layers/alpr/policy.js", "src/layers/alpr/presentation.js", "src/layers/alpr/visuals.js", + "src/layers/alpr/modelSpecs.js", "src/layers/alpr/overlay.js", "src/layers/alpr/source.js", "src/layers/awareness/controls.js", diff --git a/src/data/alprCameras.test.mjs b/src/data/alprCameras.test.mjs index 5a50220d54..8867739a10 100644 --- a/src/data/alprCameras.test.mjs +++ b/src/data/alprCameras.test.mjs @@ -54,6 +54,7 @@ test('normalizeAlprNode: maps a full OSM node to a plain record', () => { longitude: -97.7431, operator: 'Flock Safety', manufacturer: null, + model: null, cameraType: 'fixed', zone: 'traffic', directionDeg: 270, diff --git a/src/layers/alpr/modelSpecs.js b/src/layers/alpr/modelSpecs.js new file mode 100644 index 0000000000..789b6fc4a5 --- /dev/null +++ b/src/layers/alpr/modelSpecs.js @@ -0,0 +1,257 @@ +/** + * @module alprModelSpecs + * + * Datasheet specs for the ALPR hardware that OpenStreetMap mappers name. + * + * 1,567 mapped ALPR cameras carry a `model` tag (October 2026). This module + * vendors the records for the models among them that the CCTV Camera Database + * (https://github.com/ch-bas/cctv-camera-database, CC0-1.0) covers — + * Motorola Solutions Vigilant, Genetec AutoVu, Axis, Verkada and Bosch MIC, + * which resolve 459 of those cameras — and resolves a camera's `model` (with + * its `manufacturer`) through the CCTV layer's matcher. The hourly extract the + * layer reads by default does not publish `model` yet, so today only an + * Overpass-backed source shows these specs. Flock Safety publishes no + * datasheet resolution, so Flock models stay unresolved; an unknown model + * never implies anything. + * + * Scope guardrail: records describe camera PRODUCTS (optics, resolution, + * night vision) — never endpoints, operators or what a camera records. + */ + +import { createModelSpecLookup } from '../cctv/modelSpecs.js'; + +/** + * Verbatim records from the dataset's model-enrichment extract (v2.29.0). + * Mappers tag the bare product code ("L6Q", "MIC-7522-Z30B") where the + * datasheet names the product line too ("Vigilant L6Q"), so each record also + * lists its bare code as an alias. + */ +const RECORDS = [ + { + id: 'motorola-solutions-l5f', + brand: 'Motorola Solutions', + model: 'Vigilant L5F', + type: 'box', + url: 'https://www.cctv-database.com/camera/motorola-solutions-l5f/', + aliases: ['L5F', 'L5F Fixed LPR Camera System'], + resolution: { mp: 1.6, w: 1440, h: 1080 }, + lens_count: 2, + night_vision: { type: 'ir' }, + environment: ['outdoor'], + }, + { + id: 'motorola-solutions-l5m', + brand: 'Motorola Solutions', + model: 'Vigilant L5M', + type: 'box', + url: 'https://www.cctv-database.com/camera/motorola-solutions-l5m/', + aliases: [ + 'L5M', + 'L5M Mobile LPR Camera System', + 'L5M Mobile ANPR Camera System', + ], + resolution: { mp: 1.6, w: 1440, h: 1080 }, + lens_count: 2, + night_vision: { type: 'ir' }, + environment: ['outdoor'], + }, + { + id: 'motorola-solutions-l5q', + brand: 'Motorola Solutions', + model: 'Vigilant L5Q', + type: 'box', + url: 'https://www.cctv-database.com/camera/motorola-solutions-l5q/', + aliases: ['L5Q', 'L5Q Quick Deploy LPR Camera System'], + resolution: { mp: 3 }, + environment: ['outdoor'], + }, + { + id: 'motorola-solutions-l6d', + brand: 'Motorola Solutions', + model: 'Vigilant L6D', + type: 'bullet', + url: 'https://www.cctv-database.com/camera/motorola-solutions-l6d/', + aliases: [ + 'L6D', + 'L6D Dual-Purpose LPR Camera', + 'VSM-L6D-8IR', + 'VSM-L6D-7IR', + ], + fov_deg: '52-3 horizontal', + resolution: { mp: 1.6, w: 1440, h: 1080 }, + lens_count: 2, + varifocal: true, + night_vision: { type: 'ir' }, + environment: ['outdoor'], + }, + { + id: 'motorola-solutions-l6q', + brand: 'Motorola Solutions', + model: 'Vigilant L6Q', + type: 'box', + url: 'https://www.cctv-database.com/camera/motorola-solutions-l6q/', + aliases: ['L6Q', 'L6Q Quick-Deploy LPR Camera System'], + resolution: { mp: 2.1, w: 1920, h: 1080, label: '1080p' }, + night_vision: { type: 'ir' }, + environment: ['outdoor'], + }, + { + id: 'genetec-autovu-sharpv', + brand: 'Genetec', + model: 'AutoVu SharpV', + type: 'box', + url: 'https://www.cctv-database.com/camera/genetec-autovu-sharpv/', + aliases: [ + 'AutoVu SharpV G3', + 'AU-V-WS850-LC-G3-000', + 'AU-V-BS850-LC-G3-0M0', + 'AU-V-BS850-LC-G3-0M1', + ], + resolution: { mp: 2.3, w: 1920, h: 1200, label: '1920x1200' }, + lens_count: 2, + night_vision: { type: 'ir' }, + environment: ['outdoor'], + }, + { + id: 'genetec-autovu-sharpv-g2', + brand: 'Genetec', + model: 'AutoVu SharpV G2', + type: 'box', + url: 'https://www.cctv-database.com/camera/genetec-autovu-sharpv-g2/', + aliases: ['AutoVu SharpV G1', 'AU-V-WS850-LC-G2', 'AU-V-WS850-LC'], + resolution: { mp: 1.2, w: 1280, h: 960, label: '1280x960' }, + lens_count: 2, + night_vision: { type: 'ir' }, + environment: ['outdoor'], + }, + { + id: 'genetec-autovu-sharpx', + brand: 'Genetec', + model: 'AutoVu SharpX', + type: 'box', + url: 'https://www.cctv-database.com/camera/genetec-autovu-sharpx/', + // i18n-ignore: datasheet label + resolution: { mp: 1, w: 1024, h: 946, label: 'XGA (1024x946)' }, + lens_count: 2, + night_vision: { type: 'ir' }, + environment: ['outdoor'], + }, + { + id: 'genetec-autovu-sharpz3', + brand: 'Genetec', + model: 'AutoVu SharpZ3', + type: 'box', + url: 'https://www.cctv-database.com/camera/genetec-autovu-sharpz3/', + resolution: { mp: 1.6, w: 1456, h: 1088, label: '1456x1088' }, + lens_count: 3, + night_vision: { type: 'ir' }, + environment: ['outdoor'], + }, + { + id: 'axis-q1700-le', + brand: 'Axis', + model: 'Q1700-LE', + type: 'box', + url: 'https://www.cctv-database.com/camera/axis-q1700-le/', + fov_deg: '16-2.3 horizontal / 9.6-1.3 vertical', + resolution: { mp: 2, w: 1920, h: 1080, label: '1080p' }, + varifocal: true, + night_vision: { type: 'ir', range_m: 50 }, + environment: ['outdoor'], + ndaa_compliant: true, + }, + { + id: 'axis-q1800-le', + brand: 'Axis', + model: 'Q1800-LE', + type: 'bullet', + url: 'https://www.cctv-database.com/camera/axis-q1800-le/', + aliases: ['03107-001', 'Q1800-LE-3 (License Plate Verifier kit)'], + fov_deg: '38-2.3 horizontal', + resolution: { mp: 2, w: 1920, h: 1080, label: '1080p' }, + varifocal: true, + night_vision: { type: 'ir', range_m: 40 }, + environment: ['indoor', 'outdoor'], + ndaa_compliant: true, + }, + { + id: 'verkada-cb62-te-f', + brand: 'Verkada', + model: 'CB62-TE-F', + type: 'bullet', + url: 'https://www.cctv-database.com/camera/verkada-cb62-te-f/', + fov_deg: '42 to 17 H', + resolution: { mp: 8.3, w: 3840, h: 2160, label: '4K' }, + varifocal: true, + night_vision: { type: 'ir', range_m: 50 }, + environment: ['outdoor'], + ndaa_compliant: true, + }, + { + id: 'verkada-ch52-e-f', + brand: 'Verkada', + model: 'CH52-E-F', + type: 'panoramic', + url: 'https://www.cctv-database.com/camera/verkada-ch52-e-f/', + fov_deg: '89 to 37 H (per sensor); up to 328 combined', + // i18n-ignore: datasheet label + resolution: { mp: 5, w: 2688, h: 1944, label: '4 x 5MP (20MP)' }, + lens_count: 4, + varifocal: true, + night_vision: { type: 'ir', range_m: 30 }, + environment: ['outdoor'], + ndaa_compliant: true, + }, + { + id: 'verkada-cp63-e', + brand: 'Verkada', + model: 'CP63-E', + type: 'ptz', + url: 'https://www.cctv-database.com/camera/verkada-cp63-e/', + fov_deg: '64 to 2 H', + resolution: { mp: 8.3, w: 3840, h: 2160, label: '4K' }, + ptz: true, + varifocal: true, + night_vision: { type: 'ir', range_m: 100 }, + environment: ['outdoor'], + ndaa_compliant: true, + }, + { + id: 'verkada-cr63-e', + brand: 'Verkada', + model: 'CR63-E', + type: 'bullet', + url: 'https://www.cctv-database.com/camera/verkada-cr63-e/', + fov_deg: '109 to 49 H', + resolution: { mp: 8.3, w: 3840, h: 2160, label: '4K' }, + varifocal: true, + night_vision: { type: 'ir', range_m: 20 }, + environment: ['indoor', 'outdoor'], + }, + { + id: 'bosch-mic-7522-z30b', + brand: 'Bosch', + model: 'MIC IP starlight 7100i (MIC-7522-Z30B)', + type: 'ptz', + url: 'https://www.cctv-database.com/camera/bosch-mic-7522-z30b/', + aliases: ['MIC-7522-Z30B'], + fov_deg: '2.1-58.3', + // i18n-ignore: datasheet label + resolution: { mp: 2, w: 1920, h: 1080, label: '1080p HD' }, + ptz: true, + varifocal: true, + night_vision: { type: 'color' }, + environment: ['outdoor'], + ndaa_compliant: true, + }, +]; + +/** + * Datasheet record for a mapped ALPR camera's `model` tag. A `manufacturer` + * naming another maker rejects the match, so a "Flock Safety" camera tagged + * "L6Q" stays unresolved rather than borrowing Motorola's specs. + * @param {string|null} model - The OSM `model` tag. + * @param {string|null} [manufacturer] - The OSM `manufacturer` tag. + * @returns {Object|null} The verbatim spec record, or null when unknown. + */ +export const lookupAlprModelSpec = createModelSpecLookup(RECORDS); diff --git a/src/layers/alpr/modelSpecs.test.mjs b/src/layers/alpr/modelSpecs.test.mjs new file mode 100644 index 0000000000..b33c1d879b --- /dev/null +++ b/src/layers/alpr/modelSpecs.test.mjs @@ -0,0 +1,100 @@ +// src/layers/alpr/modelSpecs.test.mjs +// Mapped ALPR model tags resolve to vendored datasheets, and never guess. +import { test } from 'node:test'; +import assert from 'node:assert/strict'; + +import { lookupAlprModelSpec } from './modelSpecs.js'; +import { normalizeAlprNode } from './records.js'; +import { alprLabelDetails } from './visuals.js'; + +const OSM = { attribution: { name: 'OpenStreetMap' } }; + +test('the model tags mappers write resolve to their datasheet record', () => { + // [model tag, manufacturer tag, record id] as they appear on OSM nodes. + for (const [model, manufacturer, id] of [ + ['L6Q', 'Motorola Solutions', 'motorola-solutions-l6q'], + ['L5F', 'Motorola Solutions', 'motorola-solutions-l5f'], + ['L6D', 'Motorola Solutions', 'motorola-solutions-l6d'], + ['L6Q', null, 'motorola-solutions-l6q'], + ['AutoVu SharpV', 'Genetec', 'genetec-autovu-sharpv'], + ['Q1700-LE', 'Axis Communications', 'axis-q1700-le'], + ['Q1800-LE', 'Axis Communications', 'axis-q1800-le'], + ['CP63-E', 'Verkada Inc.', 'verkada-cp63-e'], + ['CB62-TE-F', 'Verkada Inc.', 'verkada-cb62-te-f'], + ['CH52-E-F', 'Verkada Inc.', 'verkada-ch52-e-f'], + ['CR63-E', 'Verkada', 'verkada-cr63-e'], + ['MIC-7522-Z30B', 'The Bosch Group', 'bosch-mic-7522-z30b'], + ]) + assert.equal( + lookupAlprModelSpec(model, manufacturer)?.id, + id, + `${manufacturer} ${model}`, + ); +}); + +test('unknown, mis-attributed or partial models stay unresolved', () => { + for (const [model, manufacturer] of [ + ['Falcon', 'Flock Safety'], + // A Motorola code under another maker is a mapping error, not a match. + ['L6Q', 'Flock Safety'], + // "AutoVu Sharp" is an older line than SharpV; "Q1800" names no variant. + ['AutoVu Sharp', 'Genetec'], + ['Q1800', 'Axis Communications'], + // Without a maker, a code-less product name is never trusted. + ['AutoVu SharpV', null], + ['UnicamVELOCITY3', null], + [null, 'Motorola Solutions'], + ]) + assert.equal(lookupAlprModelSpec(model, manufacturer), null); +}); + +test('Overpass records carry the trimmed OSM model tag', () => { + const node = normalizeAlprNode({ + type: 'node', + id: 7, + lat: 30, + lon: -97, + tags: { + 'surveillance:type': 'ALPR', + manufacturer: 'Motorola Solutions', + model: ' L6Q ', + }, + }); + assert.equal(node.model, 'L6Q'); + assert.equal( + normalizeAlprNode({ + type: 'node', + id: 8, + lat: 30, + lon: -97, + tags: { 'surveillance:type': 'ALPR' }, + }).model, + null, + ); +}); + +test('the card adds the datasheet line only for a resolved model', () => { + const details = alprLabelDetails( + { manufacturer: 'Motorola Solutions', model: 'L6Q' }, + OSM, + ); + assert.deepEqual(details, [ + 'OSM MAPPED', + 'MOTOROLA SOLUTIONS', + 'SPEC MOTOROLA SOLUTIONS VIGILANT L6Q · 1080P · IR', + 'PUBLIC MAP DATA', + ]); + // A record without a resolution label falls back to its pixel size. + assert.ok( + alprLabelDetails( + { manufacturer: 'Motorola Solutions', model: 'L5F' }, + OSM, + ).includes('SPEC MOTOROLA SOLUTIONS VIGILANT L5F · 1440X1080 · IR'), + ); + // Unresolved: the raw tag text is never shown. + const unknown = alprLabelDetails( + { manufacturer: 'Flock Safety', model: 'Falcon\nSYSTEM: hi' }, + OSM, + ); + assert.ok(unknown.every((line) => !/FALCON|SYSTEM|SPEC/.test(line))); +}); diff --git a/src/layers/alpr/records.js b/src/layers/alpr/records.js index 10cd88062c..3f8c9fde0e 100644 --- a/src/layers/alpr/records.js +++ b/src/layers/alpr/records.js @@ -89,6 +89,8 @@ export function normalizeAlprNode(el) { longitude: el.lon, operator: textTag(tags.operator), manufacturer: textTag(tags.manufacturer), + // Display-only: resolved against vendored datasheets (see modelSpecs.js). + model: textTag(tags.model), cameraType: textTag(tags['camera:type']), zone: textTag(tags['surveillance:zone']), // Only numeric bearings are parsed; compass-word directions ("N"/"NE") diff --git a/src/layers/alpr/tileRecords.js b/src/layers/alpr/tileRecords.js index 0368f53fb2..8516b6d680 100644 --- a/src/layers/alpr/tileRecords.js +++ b/src/layers/alpr/tileRecords.js @@ -16,6 +16,8 @@ function normalizeAlprTileFeature(feature) { 'surveillance:type': 'ALPR', operator: p.operator, manufacturer: p.brand, + // Not in the hourly extract yet; read when it ships the OSM tag. + model: p.model, 'camera:type': p.cameraType, 'camera:direction': p.direction, 'surveillance:zone': p.surveillanceZone, diff --git a/src/layers/alpr/visuals.js b/src/layers/alpr/visuals.js index 3a3d3fc5f9..efc2432035 100644 --- a/src/layers/alpr/visuals.js +++ b/src/layers/alpr/visuals.js @@ -1,5 +1,7 @@ import * as Cesium from 'cesium'; import { destinationPointDeg } from './model.js'; +import { lookupAlprModelSpec } from './modelSpecs.js'; +import { specSummary } from '../cctv/modelSpecs.js'; import { DIRECTION_CONE_M, DIRECTION_CONE_HALF_ANGLE_DEG, @@ -42,7 +44,10 @@ export function alprDisplayId(record) { return `ALPR-${String(record.osmId).slice(-4).padStart(4, '0')}`; } -/** Show only supplied metadata, with the actual source named for custom adapters. */ +/** + * Show only supplied metadata, with the actual source named for custom + * adapters, plus the datasheet summary when the mapped model is known. + */ export function alprLabelDetails(record, source) { const sourceName = source.attribution?.name || source.label || 'Camera source'; @@ -63,6 +68,9 @@ export function alprLabelDetails(record, source) { ), ]; if (equipment.length) details.push(equipment.join(' · ')); + // Only a datasheet match is shown: the raw OSM `model` text never is. + const spec = lookupAlprModelSpec(record.model, record.manufacturer); + if (spec) details.push(`SPEC ${specSummary(spec).toUpperCase()}`); if (sourceName === 'OpenStreetMap') details.push('PUBLIC MAP DATA'); return details; } diff --git a/src/layers/cctv/modelSpecs.js b/src/layers/cctv/modelSpecs.js index 2d93166a72..128f30d6fd 100644 --- a/src/layers/cctv/modelSpecs.js +++ b/src/layers/cctv/modelSpecs.js @@ -387,33 +387,67 @@ const BRAND_ALIASES = { Hikvision: ['hiwatch'], }; -function brandWords(record) { - return new Set([ - ...words(record.brand), - ...(BRAND_ALIASES[record.brand] || []), - ]); -} - /** - * One entry per record name (model + aliases). `required` is every - * non-generic word of the name — all must appear in a query, so a generation - * or suffix ("Mk II", "7000i" vs "7000") is never dropped. `hasCode` marks - * names carrying a letter+digit model code; names without one ("3950", - * "01959-004", "AUTODOME 800 Series") match only when the brand does. + * Builds a model lookup over a record table, so another layer can resolve its + * own vendored records with the same matching rules (see lookupModelSpec). + * @param {Object[]} records - Spec records in this module's shape. + * @param {Object} [brandAliases] - Extra manufacturer words + * accepted per record brand. + * @returns {(model: string, manufacturer?: string) => (Object|null)} Lookup. */ -const NAME_INDEX = RECORDS.flatMap((record) => { - const brand = brandWords(record); - return [record.model, ...(record.aliases || [])].map((name) => { - const nameWords = words(name); - return { - record, - brand, - allowed: new Set(nameWords), - required: nameWords.filter((word) => !isGeneric(word)), - hasCode: nameWords.some(isModelCode), - }; +export function createModelSpecLookup(records, brandAliases = BRAND_ALIASES) { + /** + * One entry per record name (model + aliases). `required` is every + * non-generic word of the name — all must appear in a query, so a + * generation or suffix ("Mk II", "7000i" vs "7000") is never dropped. + * `hasCode` marks names carrying a letter+digit model code; names without + * one ("3950", "01959-004", "AUTODOME 800 Series") match only when the + * brand does. + */ + const nameIndex = records.flatMap((record) => { + const brand = new Set([ + ...words(record.brand), + ...(brandAliases[record.brand] || []), + ]); + return [record.model, ...(record.aliases || [])].map((name) => { + const nameWords = words(name); + return { + record, + brand, + allowed: new Set(nameWords), + required: nameWords.filter((word) => !isGeneric(word)), + hasCode: nameWords.some(isModelCode), + }; + }); }); -}); + return (model, manufacturer) => { + const query = words(model).map(stripVariantSuffix); + if (!query.length) return null; + const maker = words(manufacturer); + const found = new Set(); + for (const entry of nameIndex) { + const makerMatches = maker.some((word) => entry.brand.has(word)); + if (maker.length && !makerMatches) continue; + if ( + !entry.hasCode && + !makerMatches && + !query.some((word) => entry.brand.has(word)) + ) + continue; + if (!entry.required.length) continue; + if (!entry.required.every((word) => query.includes(word))) continue; + if ( + !query.every( + (word) => + entry.allowed.has(word) || entry.brand.has(word) || isGeneric(word), + ) + ) + continue; + found.add(entry.record); + } + return found.size === 1 ? [...found][0] : null; + }; +} /** * Looks up a spec record for a hardware-model string. @@ -433,33 +467,7 @@ const NAME_INDEX = RECORDS.flatMap((record) => { * @param {string} [manufacturer] - The source's manufacturer, when published. * @returns {Object|null} The verbatim spec record, or null when unknown. */ -export function lookupModelSpec(model, manufacturer) { - const query = words(model).map(stripVariantSuffix); - if (!query.length) return null; - const maker = words(manufacturer); - const found = new Set(); - for (const entry of NAME_INDEX) { - const makerMatches = maker.some((word) => entry.brand.has(word)); - if (maker.length && !makerMatches) continue; - if ( - !entry.hasCode && - !makerMatches && - !query.some((word) => entry.brand.has(word)) - ) - continue; - if (!entry.required.length) continue; - if (!entry.required.every((word) => query.includes(word))) continue; - if ( - !query.every( - (word) => - entry.allowed.has(word) || entry.brand.has(word) || isGeneric(word), - ) - ) - continue; - found.add(entry.record); - } - return found.size === 1 ? [...found][0] : null; -} +export const lookupModelSpec = createModelSpecLookup(RECORDS); /** * Datasheet horizontal FOV as the range the hardware can cover. Only @@ -539,7 +547,10 @@ export function specFovCapabilityToken( export function specSummary(spec) { if (!spec) return ''; const parts = [`${spec.brand} ${spec.model}`]; - if (spec.resolution?.label) parts.push(spec.resolution.label); + const { label, w, h, mp } = spec.resolution || {}; + if (label) parts.push(label); + else if (w && h) parts.push(`${w}x${h}`); + else if (mp) parts.push(`${mp}MP`); if (spec.night_vision) { parts.push( `${spec.night_vision.type.toUpperCase()}${spec.night_vision.range_m ? ` ${spec.night_vision.range_m}m` : ''}`, From 434fc1b852c9fdeaabca0a47c617dad9d923377a Mon Sep 17 00:00:00 2001 From: bassem chagra Date: Sat, 24 Oct 2026 13:54:35 +0200 Subject: [PATCH 02/17] docs(changelog): add fragment for #1360 --- changelog.d/1360-alpr-model-specs.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 changelog.d/1360-alpr-model-specs.md diff --git a/changelog.d/1360-alpr-model-specs.md b/changelog.d/1360-alpr-model-specs.md new file mode 100644 index 0000000000..2e34f02168 --- /dev/null +++ b/changelog.d/1360-alpr-model-specs.md @@ -0,0 +1,5 @@ +- Mapped ALPR cameras whose OpenStreetMap `model` tag names known hardware + (Motorola Solutions Vigilant, Genetec AutoVu, Axis, Verkada, Bosch MIC) show + a datasheet spec line on their card, from 16 vendored CCTV Camera Database + records; unknown or mis-attributed models show nothing (bassem chagra, + @ch-bas, #1360). From 71d853dff0d98fe76b24c515240dbc73677e22f2 Mon Sep 17 00:00:00 2001 From: Said Turksever Date: Tue, 3 Nov 2026 16:26:48 +0000 Subject: [PATCH 03/17] chore: adopt ALPR model spec tests into format scope --- scripts/format-scope.json | 1 + 1 file changed, 1 insertion(+) diff --git a/scripts/format-scope.json b/scripts/format-scope.json index 2852445270..b59bf0e42e 100644 --- a/scripts/format-scope.json +++ b/scripts/format-scope.json @@ -579,6 +579,7 @@ "src/data/dataCredits.test.mjs", "src/layers/alpr/index.js", "src/layers/alpr/model.js", + "src/layers/alpr/modelSpecs.test.mjs", "src/layers/alpr/policy.js", "src/layers/alpr/presentation.js", "src/layers/alpr/visuals.js", From 5371f3ee70f936ffcdbf67dc4dfde1efd09fefec Mon Sep 17 00:00:00 2001 From: Kevin Rajan <7121943+kvnloo@users.noreply.github.com> Date: Fri, 13 Nov 2026 03:19:15 -0600 Subject: [PATCH 04/17] fix(alpr): require explicit SharpV G3 before showing G3 specs Address gekh's P2 review of ch-bas's ALPR datasheet feature. Keep the vendored records verbatim, reject generation-ambiguous SharpV model tags, and cover G1/G2/G3 matching and the rendered card with node:test. Update the documented matched-camera count and changelog, preserving original author ch-bas and existing attribution. --- changelog.d/1360-alpr-model-specs.md | 4 ++-- docs/CURRENT-STATE.md | 7 ++++--- src/layers/alpr/modelSpecs.js | 19 ++++++++++++++++--- src/layers/alpr/modelSpecs.test.mjs | 22 +++++++++++++++++++++- 4 files changed, 43 insertions(+), 9 deletions(-) diff --git a/changelog.d/1360-alpr-model-specs.md b/changelog.d/1360-alpr-model-specs.md index 2e34f02168..90addb2adb 100644 --- a/changelog.d/1360-alpr-model-specs.md +++ b/changelog.d/1360-alpr-model-specs.md @@ -1,5 +1,5 @@ - Mapped ALPR cameras whose OpenStreetMap `model` tag names known hardware (Motorola Solutions Vigilant, Genetec AutoVu, Axis, Verkada, Bosch MIC) show a datasheet spec line on their card, from 16 vendored CCTV Camera Database - records; unknown or mis-attributed models show nothing (bassem chagra, - @ch-bas, #1360). + records; unknown, generation-ambiguous or mis-attributed models show nothing + (bassem chagra, @ch-bas, #1360). diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index dd5dfab20a..f1f2201e93 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -971,12 +971,13 @@ screen. Cyan camera badges use Manjunath's camera artwork; selection switches to larger coral badge with corner brackets and an animated tactical card. Numeric mapped bearings draw illustrative 90 m direction wedges (not measured coverage). A camera whose OSM `model` tag names known hardware (Motorola Solutions Vigilant, -Genetec AutoVu SharpV, Axis, Verkada, Bosch MIC; 459 of the 1,567 tagged cameras +Genetec AutoVu, Axis, Verkada, Bosch MIC; 408 of the 1,567 tagged cameras in October 2026) gets a `SPEC` line on its card from vendored datasheet records (`src/layers/alpr/modelSpecs.js`, matched with the CCTV layer's `createModelSpecLookup`). A `manufacturer` naming another maker rejects the -match, and the raw tag text is never shown. The hourly extract has no `model` -field yet, so only an Overpass-backed source fills it. +match, and the raw tag text is never shown. Unversioned `AutoVu SharpV` tags +cannot choose between G1/G2/G3 datasheets and show no specs. The hourly extract +has no `model` field yet, so only an Overpass-backed source fills it. The shared overlay paints gradients for at most 64 nearby cameras, promoting the selected camera; farther cameras keep native Cesium badges without wedges. Native ground-clamped wedges (a ground polyline plus a classification polygon per diff --git a/src/layers/alpr/modelSpecs.js b/src/layers/alpr/modelSpecs.js index 789b6fc4a5..33314531c1 100644 --- a/src/layers/alpr/modelSpecs.js +++ b/src/layers/alpr/modelSpecs.js @@ -7,8 +7,9 @@ * vendors the records for the models among them that the CCTV Camera Database * (https://github.com/ch-bas/cctv-camera-database, CC0-1.0) covers — * Motorola Solutions Vigilant, Genetec AutoVu, Axis, Verkada and Bosch MIC, - * which resolve 459 of those cameras — and resolves a camera's `model` (with - * its `manufacturer`) through the CCTV layer's matcher. The hourly extract the + * which resolve 408 of those cameras (excluding unversioned SharpV tags) — + * and resolves a camera's `model` (with its `manufacturer`) through the CCTV + * layer's matcher. The hourly extract the * layer reads by default does not publish `model` yet, so today only an * Overpass-backed source shows these specs. Flock Safety publishes no * datasheet resolution, so Flock models stay unresolved; an unknown model @@ -254,4 +255,16 @@ const RECORDS = [ * @param {string|null} [manufacturer] - The OSM `manufacturer` tag. * @returns {Object|null} The verbatim spec record, or null when unknown. */ -export const lookupAlprModelSpec = createModelSpecLookup(RECORDS); +const lookupDatasheetSpec = createModelSpecLookup(RECORDS); + +export function lookupAlprModelSpec(model, manufacturer) { + const spec = lookupDatasheetSpec(model, manufacturer); + // The dataset's unversioned SharpV label is tied to G3 hardware, but OSM + // tags may name G1 or G2. Require an explicit G3 or a G3 part number. + if ( + spec?.id === 'genetec-autovu-sharpv' && + !/\bg3\b/i.test(String(model || '')) + ) + return null; + return spec; +} diff --git a/src/layers/alpr/modelSpecs.test.mjs b/src/layers/alpr/modelSpecs.test.mjs index b33c1d879b..fb6d8fbd49 100644 --- a/src/layers/alpr/modelSpecs.test.mjs +++ b/src/layers/alpr/modelSpecs.test.mjs @@ -16,7 +16,10 @@ test('the model tags mappers write resolve to their datasheet record', () => { ['L5F', 'Motorola Solutions', 'motorola-solutions-l5f'], ['L6D', 'Motorola Solutions', 'motorola-solutions-l6d'], ['L6Q', null, 'motorola-solutions-l6q'], - ['AutoVu SharpV', 'Genetec', 'genetec-autovu-sharpv'], + ['AutoVu SharpV G3', 'Genetec', 'genetec-autovu-sharpv'], + ['AU-V-WS850-LC-G3-000', 'Genetec', 'genetec-autovu-sharpv'], + ['AutoVu SharpV G2', 'Genetec', 'genetec-autovu-sharpv-g2'], + ['AutoVu SharpV G1', 'Genetec', 'genetec-autovu-sharpv-g2'], ['Q1700-LE', 'Axis Communications', 'axis-q1700-le'], ['Q1800-LE', 'Axis Communications', 'axis-q1800-le'], ['CP63-E', 'Verkada Inc.', 'verkada-cp63-e'], @@ -42,6 +45,9 @@ test('unknown, mis-attributed or partial models stay unresolved', () => { ['Q1800', 'Axis Communications'], // Without a maker, a code-less product name is never trusted. ['AutoVu SharpV', null], + ['AutoVu SharpV', 'Genetec'], + ['AutoVu SharpV HD', 'Genetec'], + ['Genetec AutoVu SharpV', 'Genetec'], ['UnicamVELOCITY3', null], [null, 'Motorola Solutions'], ]) @@ -98,3 +104,17 @@ test('the card adds the datasheet line only for a resolved model', () => { ); assert.ok(unknown.every((line) => !/FALCON|SYSTEM|SPEC/.test(line))); }); + +test('unversioned SharpV does not display G3 specs on an ALPR card', () => { + const ambiguous = alprLabelDetails( + { manufacturer: 'Genetec', model: 'AutoVu SharpV' }, + OSM, + ); + assert.deepEqual(ambiguous, ['OSM MAPPED', 'GENETEC', 'PUBLIC MAP DATA']); + + const g3 = alprLabelDetails( + { manufacturer: 'Genetec', model: 'AutoVu SharpV G3' }, + OSM, + ); + assert.ok(g3.includes('SPEC GENETEC AUTOVU SHARPV · 1920X1200 · IR')); +}); From 77fe8299d79840983059b710d858c91ec838b352 Mon Sep 17 00:00:00 2001 From: German Khokhlov Date: Thu, 19 Nov 2026 18:24:10 +0400 Subject: [PATCH 05/17] fix(alpr): tighten model spec matching and card text - Name the G3 record "AutoVu SharpV G3" and the SharpX record "XGA", so a bare SharpV or SharpX tag shows no specs without a separate wrapper. - Reuse the CCTV layer's Bosch MIC-7522-Z30 record instead of a copy. - Drop the brand from the SPEC line when the equipment line already names it, so long lines fit the card; pass the summary to entity properties. - Fall back to the OSM `brand` tag when `manufacturer` is missing. - Reject non-string or overlong model/manufacturer values before matching. - Remove the unused `brandAliases` parameter; shorten JSDoc and comments. - Cover the tile `model` path and the megapixel summary in tests; fold duplicate tests into existing ones. - Docs and changelog: the default hourly extract has no `model`; any source that supplies it shows the SPEC line. --- DATA_SOURCES.md | 16 ++-- changelog.d/1360-alpr-model-specs.md | 4 +- docs/CURRENT-STATE.md | 8 +- src/data/alprCameras.test.mjs | 3 +- src/layers/alpr/index.js | 4 +- src/layers/alpr/modelSpecs.js | 68 ++++++---------- src/layers/alpr/modelSpecs.test.mjs | 115 ++++++++++++++++++--------- src/layers/alpr/presentation.js | 6 ++ src/layers/alpr/records.js | 2 +- src/layers/alpr/visuals.js | 13 +-- src/layers/cctv/modelSpecs.js | 22 +++-- 11 files changed, 147 insertions(+), 114 deletions(-) diff --git a/DATA_SOURCES.md b/DATA_SOURCES.md index 57ffcbe313..d5b4300932 100644 --- a/DATA_SOURCES.md +++ b/DATA_SOURCES.md @@ -425,7 +425,7 @@ The [Bhote Koshi event pack](public/events/bhote-koshi-2026/README.md), under `p | **Yale Bright Star Catalogue** (9,096 stars, sky background) | `sky/` | **Public domain** | ✅ (no restrictions) | "Yale Bright Star Catalogue (Hoffleit & Warren, via CDS)" (courtesy credit) | | **ESO Milky Way panorama** (eso0932a, blurred cube map, sky background) | `sky/` | **CC BY 4.0** | ✅ (attribution; changes stated) | "ESO/S. Brunier" | | **CCTV ground heights** (3,445 cameras) | `cctv_ground_heights/` | Precomputed camera placement heights, aligned to work with Google Photorealistic 3D Tiles (folder README) | — | — | -| **CCTV Camera Database** model-enrichment extract v2.26.0 + v2.29.0 (20 camera-model records) | `src/layers/cctv/modelSpecs.js` | **CC0-1.0** (public domain dedication) | ✅ (no restrictions) | "Specs: cctv-database.com" (courtesy — not legally required) | +| **CCTV Camera Database** model-enrichment extract v2.26.0 + v2.29.0 (20 CCTV and 15 ALPR camera-model records) | `src/layers/cctv/modelSpecs.js`, `src/layers/alpr/modelSpecs.js` | **CC0-1.0** (public domain dedication) | ✅ (no restrictions) | "Specs: cctv-database.com" (courtesy — not legally required) | ### ⚠️ TeleGeography is bundled but NonCommercial @@ -452,11 +452,15 @@ obligations; it does not license the application code. Trimmed test-only tile fixtures retain their provenance in `src/data/fixtures/README.md`. A mapped `model` tag that names datasheet hardware adds a spec line to the -selected card. The specs are 16 verbatim CC0-1.0 records from the CCTV Camera -Database model-enrichment extract (v2.29.0), compiled into -`src/layers/alpr/modelSpecs.js`; nothing is fetched at runtime, and an -unrecognised tag is never displayed. The hourly extract does not carry `model` -yet, so only an Overpass-backed source shows these lines today. +selected card. The specs are 16 CC0-1.0 records from the CCTV Camera Database +model-enrichment extract (v2.29.0): 15 compiled into +`src/layers/alpr/modelSpecs.js`, with the bare product codes mappers tag added +as aliases and the SharpV G3 and SharpX XGA titles naming their variant, plus +the CCTV layer's Bosch MIC-7522-Z30 record. Nothing is fetched at runtime, and +an unrecognised tag is never displayed. The default hourly extract does not +carry `model` yet, so the line appears only with a source that supplies it: an +Overpass-backed source or a custom adapter whose records include the optional +`model` field. ### CCTV Camera Database (`src/layers/cctv/modelSpecs.js`) diff --git a/changelog.d/1360-alpr-model-specs.md b/changelog.d/1360-alpr-model-specs.md index 90addb2adb..a7db9817c5 100644 --- a/changelog.d/1360-alpr-model-specs.md +++ b/changelog.d/1360-alpr-model-specs.md @@ -1,5 +1,7 @@ - Mapped ALPR cameras whose OpenStreetMap `model` tag names known hardware (Motorola Solutions Vigilant, Genetec AutoVu, Axis, Verkada, Bosch MIC) show a datasheet spec line on their card, from 16 vendored CCTV Camera Database - records; unknown, generation-ambiguous or mis-attributed models show nothing + records, when their source supplies `model` (an Overpass-backed source or an + integration adapter; the default hourly extract does not yet); unknown, + generation-ambiguous or mis-attributed models show nothing (bassem chagra, @ch-bas, #1360). diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index 7772983cee..3402746489 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -1508,9 +1508,11 @@ Genetec AutoVu, Axis, Verkada, Bosch MIC; 408 of the 1,567 tagged cameras in October 2026) gets a `SPEC` line on its card from vendored datasheet records (`src/layers/alpr/modelSpecs.js`, matched with the CCTV layer's `createModelSpecLookup`). A `manufacturer` naming another maker rejects the -match, and the raw tag text is never shown. Unversioned `AutoVu SharpV` tags -cannot choose between G1/G2/G3 datasheets and show no specs. The hourly extract -has no `model` field yet, so only an Overpass-backed source fills it. +match, and the raw tag text is never shown. +Unversioned `AutoVu SharpV` and `AutoVu SharpX` tags show no specs; G1/G2 +tags show the G2 (1280x960) record and G3 tags the G3 record. The default +hourly extract has no `model` field yet; an Overpass-backed source or a custom +adapter record's optional `model` fills it. The shared overlay paints gradients for at most 64 nearby cameras, promoting the selected camera; farther cameras keep native Cesium badges without wedges. Native ground-clamped wedges (a ground polyline plus a classification polygon per diff --git a/src/data/alprCameras.test.mjs b/src/data/alprCameras.test.mjs index bee648a443..05ed7d06ec 100644 --- a/src/data/alprCameras.test.mjs +++ b/src/data/alprCameras.test.mjs @@ -43,6 +43,7 @@ test('normalizeAlprNode: maps a full OSM node to a plain record', () => { 'surveillance:type': 'ALPR', operator: 'Flock Safety', 'camera:type': 'fixed', + model: ' L6Q ', 'surveillance:zone': 'traffic', 'camera:direction': '270', ref: 'ATX-001', @@ -56,7 +57,7 @@ test('normalizeAlprNode: maps a full OSM node to a plain record', () => { longitude: -97.7431, operator: 'Flock Safety', manufacturer: null, - model: null, + model: 'L6Q', cameraType: 'fixed', zone: 'traffic', directionDeg: 270, diff --git a/src/layers/alpr/index.js b/src/layers/alpr/index.js index 474ec1de03..cbd3cda3fb 100644 --- a/src/layers/alpr/index.js +++ b/src/layers/alpr/index.js @@ -23,7 +23,9 @@ import { t, tn, msg } from '../../i18n/index.js'; * records fully cover, reused for later views inside it) and `zoom` (their * tile precision; `source.detailZoom(box)` names the zoom a view needs). Records use stable string ids and latitude / * longitude in degrees; optional directionDeg is a compass bearing [0, 360). - * Manufacturer, operator and cameraType are optional display fields. + * Manufacturer, operator, cameraType and model are optional display fields; + * model only selects a vendored datasheet line (modelSpecs.js), never shown + * as text. * Source label and attribution { name, description, text, href } identify the * actual provider; href must be HTTPS. Provider payload parsing stays in source. * Context services remove obsolete records with diff --git a/src/layers/alpr/modelSpecs.js b/src/layers/alpr/modelSpecs.js index 33314531c1..1e71789f28 100644 --- a/src/layers/alpr/modelSpecs.js +++ b/src/layers/alpr/modelSpecs.js @@ -1,17 +1,9 @@ /** * @module alprModelSpecs * - * Datasheet specs for the ALPR hardware that OpenStreetMap mappers name. - * - * 1,567 mapped ALPR cameras carry a `model` tag (October 2026). This module - * vendors the records for the models among them that the CCTV Camera Database - * (https://github.com/ch-bas/cctv-camera-database, CC0-1.0) covers — - * Motorola Solutions Vigilant, Genetec AutoVu, Axis, Verkada and Bosch MIC, - * which resolve 408 of those cameras (excluding unversioned SharpV tags) — - * and resolves a camera's `model` (with its `manufacturer`) through the CCTV - * layer's matcher. The hourly extract the - * layer reads by default does not publish `model` yet, so today only an - * Overpass-backed source shows these specs. Flock Safety publishes no + * Datasheet specs for the ALPR hardware that OpenStreetMap `model` tags name, + * vendored from the CCTV Camera Database (CC0-1.0) and matched with the CCTV + * layer's rules; DATA_SOURCES.md has the provenance. Flock Safety publishes no * datasheet resolution, so Flock models stay unresolved; an unknown model * never implies anything. * @@ -19,13 +11,15 @@ * night vision) — never endpoints, operators or what a camera records. */ -import { createModelSpecLookup } from '../cctv/modelSpecs.js'; +import { createModelSpecLookup, lookupModelSpec } from '../cctv/modelSpecs.js'; /** - * Verbatim records from the dataset's model-enrichment extract (v2.29.0). - * Mappers tag the bare product code ("L6Q", "MIC-7522-Z30B") where the - * datasheet names the product line too ("Vigilant L6Q"), so each record also - * lists its bare code as an alias. + * Records from the dataset's model-enrichment extract (v2.29.0), with the + * bare product codes mappers tag ("L6Q") added as aliases where the title + * names the product line ("Vigilant L6Q"). A tag without a generation or + * variant could name any of them, so the SharpV G3 and SharpX XGA titles + * carry theirs. Fields the card does not read (type, url, fov_deg, …) stay as + * in the dataset, like the CCTV records. */ const RECORDS = [ { @@ -99,11 +93,10 @@ const RECORDS = [ { id: 'genetec-autovu-sharpv', brand: 'Genetec', - model: 'AutoVu SharpV', + model: 'AutoVu SharpV G3', type: 'box', url: 'https://www.cctv-database.com/camera/genetec-autovu-sharpv/', aliases: [ - 'AutoVu SharpV G3', 'AU-V-WS850-LC-G3-000', 'AU-V-BS850-LC-G3-0M0', 'AU-V-BS850-LC-G3-0M1', @@ -128,7 +121,7 @@ const RECORDS = [ { id: 'genetec-autovu-sharpx', brand: 'Genetec', - model: 'AutoVu SharpX', + model: 'AutoVu SharpX XGA', type: 'box', url: 'https://www.cctv-database.com/camera/genetec-autovu-sharpx/', // i18n-ignore: datasheet label @@ -229,42 +222,29 @@ const RECORDS = [ night_vision: { type: 'ir', range_m: 20 }, environment: ['indoor', 'outdoor'], }, - { - id: 'bosch-mic-7522-z30b', - brand: 'Bosch', - model: 'MIC IP starlight 7100i (MIC-7522-Z30B)', - type: 'ptz', - url: 'https://www.cctv-database.com/camera/bosch-mic-7522-z30b/', - aliases: ['MIC-7522-Z30B'], - fov_deg: '2.1-58.3', - // i18n-ignore: datasheet label - resolution: { mp: 2, w: 1920, h: 1080, label: '1080p HD' }, - ptz: true, - varifocal: true, - night_vision: { type: 'color' }, - environment: ['outdoor'], - ndaa_compliant: true, - }, + // The CCTV layer's record: one colour-neutral title for the B/G/W variants. + lookupModelSpec('MIC-7522-Z30B', 'Bosch'), ]; +const lookupDatasheetSpec = createModelSpecLookup(RECORDS); + /** * Datasheet record for a mapped ALPR camera's `model` tag. A `manufacturer` * naming another maker rejects the match, so a "Flock Safety" camera tagged * "L6Q" stays unresolved rather than borrowing Motorola's specs. * @param {string|null} model - The OSM `model` tag. * @param {string|null} [manufacturer] - The OSM `manufacturer` tag. - * @returns {Object|null} The verbatim spec record, or null when unknown. + * @returns {Object|null} The spec record, or null when unknown. */ -const lookupDatasheetSpec = createModelSpecLookup(RECORDS); - export function lookupAlprModelSpec(model, manufacturer) { - const spec = lookupDatasheetSpec(model, manufacturer); - // The dataset's unversioned SharpV label is tied to G3 hardware, but OSM - // tags may name G1 or G2. Require an explicit G3 or a G3 part number. + // Adapter records arrive unnormalized and the matcher's word trim is + // quadratic on long punctuation runs: match only tag-sized strings (the + // built-in sources keep 180 characters). + if (typeof model !== 'string' || model.length > 180) return null; if ( - spec?.id === 'genetec-autovu-sharpv' && - !/\bg3\b/i.test(String(model || '')) + manufacturer != null && + (typeof manufacturer !== 'string' || manufacturer.length > 180) ) return null; - return spec; + return lookupDatasheetSpec(model, manufacturer); } diff --git a/src/layers/alpr/modelSpecs.test.mjs b/src/layers/alpr/modelSpecs.test.mjs index fb6d8fbd49..dd2c8c20c6 100644 --- a/src/layers/alpr/modelSpecs.test.mjs +++ b/src/layers/alpr/modelSpecs.test.mjs @@ -2,9 +2,10 @@ // Mapped ALPR model tags resolve to vendored datasheets, and never guess. import { test } from 'node:test'; import assert from 'node:assert/strict'; +import { PbfWriter } from 'pbf'; import { lookupAlprModelSpec } from './modelSpecs.js'; -import { normalizeAlprNode } from './records.js'; +import { decodeAlprTile } from './tileRecords.js'; import { alprLabelDetails } from './visuals.js'; const OSM = { attribution: { name: 'OpenStreetMap' } }; @@ -20,6 +21,7 @@ test('the model tags mappers write resolve to their datasheet record', () => { ['AU-V-WS850-LC-G3-000', 'Genetec', 'genetec-autovu-sharpv'], ['AutoVu SharpV G2', 'Genetec', 'genetec-autovu-sharpv-g2'], ['AutoVu SharpV G1', 'Genetec', 'genetec-autovu-sharpv-g2'], + ['AutoVu SharpX XGA', 'Genetec', 'genetec-autovu-sharpx'], ['Q1700-LE', 'Axis Communications', 'axis-q1700-le'], ['Q1800-LE', 'Axis Communications', 'axis-q1800-le'], ['CP63-E', 'Verkada Inc.', 'verkada-cp63-e'], @@ -45,37 +47,61 @@ test('unknown, mis-attributed or partial models stay unresolved', () => { ['Q1800', 'Axis Communications'], // Without a maker, a code-less product name is never trusted. ['AutoVu SharpV', null], + // A SharpV without its generation could be G1, G2 or G3, and a SharpX + // without XGA could be the VGA model. ['AutoVu SharpV', 'Genetec'], ['AutoVu SharpV HD', 'Genetec'], ['Genetec AutoVu SharpV', 'Genetec'], + ['AutoVu SharpX', 'Genetec'], ['UnicamVELOCITY3', null], [null, 'Motorola Solutions'], + // Adapter text is matched only as a string of tag size. + [['L6Q'], 'Motorola Solutions'], + ['L6Q' + ' IP'.repeat(60), 'Motorola Solutions'], ]) assert.equal(lookupAlprModelSpec(model, manufacturer), null); }); -test('Overpass records carry the trimmed OSM model tag', () => { - const node = normalizeAlprNode({ - type: 'node', - id: 7, - lat: 30, - lon: -97, - tags: { - 'surveillance:type': 'ALPR', - manufacturer: 'Motorola Solutions', - model: ' L6Q ', - }, +/** A one-point `cameras` vector tile (z0) with string attributes. */ +function cameraTile(properties) { + const tile = new PbfWriter(); + tile.writeMessage(3, (_, layer) => { + layer.writeVarintField(15, 2); + layer.writeStringField(1, 'cameras'); + layer.writeVarintField(5, 4096); + const keys = Object.keys(properties); + layer.writeMessage(2, (_, feature) => { + feature.writePackedVarint( + 2, + keys.flatMap((_, i) => [i, i]), + ); + feature.writeVarintField(3, 1); // Point + feature.writePackedVarint(4, [9, 4096, 4096]); // MoveTo(2048, 2048) + }); + for (const key of keys) layer.writeStringField(3, key); + for (const key of keys) + layer.writeMessage(4, (_, value) => + value.writeStringField(1, String(properties[key])), + ); }); - assert.equal(node.model, 'L6Q'); - assert.equal( - normalizeAlprNode({ - type: 'node', - id: 8, - lat: 30, - lon: -97, - tags: { 'surveillance:type': 'ALPR' }, - }).model, - null, + return tile.finish(); +} + +test('extract tiles carry the model tag to the card', () => { + const [record] = decodeAlprTile( + cameraTile({ + osmType: 'node', + osmId: '7', + brand: 'Motorola Solutions', + model: 'L6Q', + }), + 0, + 0, + 0, + ); + assert.equal(record.model, 'L6Q'); + assert.ok( + alprLabelDetails(record, OSM).includes('SPEC VIGILANT L6Q · 1080P · IR'), ); }); @@ -87,15 +113,40 @@ test('the card adds the datasheet line only for a resolved model', () => { assert.deepEqual(details, [ 'OSM MAPPED', 'MOTOROLA SOLUTIONS', - 'SPEC MOTOROLA SOLUTIONS VIGILANT L6Q · 1080P · IR', + 'SPEC VIGILANT L6Q · 1080P · IR', 'PUBLIC MAP DATA', ]); - // A record without a resolution label falls back to its pixel size. + // Without a maker on the equipment line, the spec line names it. + assert.ok( + alprLabelDetails({ model: 'L6Q' }, OSM).includes( + 'SPEC MOTOROLA SOLUTIONS VIGILANT L6Q · 1080P · IR', + ), + ); + // A record without a resolution label falls back to its pixel size, then + // to megapixels. assert.ok( alprLabelDetails( { manufacturer: 'Motorola Solutions', model: 'L5F' }, OSM, - ).includes('SPEC MOTOROLA SOLUTIONS VIGILANT L5F · 1440X1080 · IR'), + ).includes('SPEC VIGILANT L5F · 1440X1080 · IR'), + ); + assert.ok( + alprLabelDetails( + { manufacturer: 'Motorola Solutions', model: 'L5Q' }, + OSM, + ).includes('SPEC VIGILANT L5Q · 3MP'), + ); + assert.ok( + alprLabelDetails( + { manufacturer: 'Genetec', model: 'AutoVu SharpV G3' }, + OSM, + ).includes('SPEC AUTOVU SHARPV G3 · 1920X1200 · IR'), + ); + assert.ok( + alprLabelDetails( + { manufacturer: 'The Bosch Group', model: 'MIC-7522-Z30B' }, + OSM, + ).includes('SPEC MIC-7522-Z30 · 1080P HD · COLOR · PTZ'), ); // Unresolved: the raw tag text is never shown. const unknown = alprLabelDetails( @@ -104,17 +155,3 @@ test('the card adds the datasheet line only for a resolved model', () => { ); assert.ok(unknown.every((line) => !/FALCON|SYSTEM|SPEC/.test(line))); }); - -test('unversioned SharpV does not display G3 specs on an ALPR card', () => { - const ambiguous = alprLabelDetails( - { manufacturer: 'Genetec', model: 'AutoVu SharpV' }, - OSM, - ); - assert.deepEqual(ambiguous, ['OSM MAPPED', 'GENETEC', 'PUBLIC MAP DATA']); - - const g3 = alprLabelDetails( - { manufacturer: 'Genetec', model: 'AutoVu SharpV G3' }, - OSM, - ); - assert.ok(g3.includes('SPEC GENETEC AUTOVU SHARPV · 1920X1200 · IR')); -}); diff --git a/src/layers/alpr/presentation.js b/src/layers/alpr/presentation.js index c7343d5738..9d378160d9 100644 --- a/src/layers/alpr/presentation.js +++ b/src/layers/alpr/presentation.js @@ -16,6 +16,8 @@ import { boxContains } from './model.js'; import { msg } from '../../i18n/index.js'; import { createAlprFloorResolver } from './floors.js'; import { createAlprOverlay } from './overlay.js'; +import { lookupAlprModelSpec } from './modelSpecs.js'; +import { specSummary } from '../cctv/modelSpecs.js'; import { MARKER_IMAGE, SELECTED_IMAGE, @@ -458,6 +460,10 @@ export function createAlprPresentation({ state, services, source }) { properties: { operator: record.operator, manufacturer: record.manufacturer, + spec: + specSummary( + lookupAlprModelSpec(record.model, record.manufacturer), + ) || null, cameraType: record.cameraType, zone: record.zone, directionDeg: record.directionDeg, diff --git a/src/layers/alpr/records.js b/src/layers/alpr/records.js index 391884536e..c85ca35785 100644 --- a/src/layers/alpr/records.js +++ b/src/layers/alpr/records.js @@ -89,7 +89,7 @@ export function normalizeAlprNode(el) { latitude: el.lat, longitude: el.lon, operator: textTag(tags.operator), - manufacturer: textTag(tags.manufacturer), + manufacturer: textTag(tags.manufacturer) ?? textTag(tags.brand), // Display-only: resolved against vendored datasheets (see modelSpecs.js). model: textTag(tags.model), cameraType: textTag(tags['camera:type']), diff --git a/src/layers/alpr/visuals.js b/src/layers/alpr/visuals.js index 748fcf1074..f9dab5b4ab 100644 --- a/src/layers/alpr/visuals.js +++ b/src/layers/alpr/visuals.js @@ -45,10 +45,7 @@ export function alprDisplayId(record) { return `ALPR-${String(record.osmId).slice(-4).padStart(4, '0')}`; } -/** - * Show only supplied metadata, with the actual source named for custom - * adapters, plus the datasheet summary when the mapped model is known. - */ +/** Show only supplied metadata, with the actual source named for custom adapters. */ export function alprLabelDetails(record, source) { const sourceName = source.attribution?.name || source.label || 'Camera source'; @@ -71,7 +68,13 @@ export function alprLabelDetails(record, source) { if (equipment.length) details.push(equipment.join(' · ')); // Only a datasheet match is shown: the raw OSM `model` text never is. const spec = lookupAlprModelSpec(record.model, record.manufacturer); - if (spec) details.push(`SPEC ${specSummary(spec).toUpperCase()}`); + if (spec) { + // The equipment line usually names the maker already; the card does not wrap. + const withBrand = !equipment.some((line) => + line.includes(spec.brand.toUpperCase()), + ); + details.push(`SPEC ${specSummary(spec, { withBrand }).toUpperCase()}`); + } if (sourceName === 'OpenStreetMap') details.push('PUBLIC MAP DATA'); return details; } diff --git a/src/layers/cctv/modelSpecs.js b/src/layers/cctv/modelSpecs.js index be0e316c1c..4be78de085 100644 --- a/src/layers/cctv/modelSpecs.js +++ b/src/layers/cctv/modelSpecs.js @@ -456,15 +456,8 @@ const BRAND_ALIASES = { Hikvision: ['hiwatch'], }; -/** - * Builds a model lookup over a record table, so another layer can resolve its - * own vendored records with the same matching rules (see lookupModelSpec). - * @param {Object[]} records - Spec records in this module's shape. - * @param {Object} [brandAliases] - Extra manufacturer words - * accepted per record brand. - * @returns {(model: string, manufacturer?: string) => (Object|null)} Lookup. - */ -export function createModelSpecLookup(records, brandAliases = BRAND_ALIASES) { +/** A model lookup over `records` with this module's matching rules (see lookupModelSpec). */ +export function createModelSpecLookup(records) { /** * One entry per record name (model + aliases). `required` is every * non-generic word of the name — all must appear in a query, so a @@ -476,7 +469,7 @@ export function createModelSpecLookup(records, brandAliases = BRAND_ALIASES) { const nameIndex = records.flatMap((record) => { const brand = new Set([ ...words(record.brand), - ...(brandAliases[record.brand] || []), + ...(BRAND_ALIASES[record.brand] || []), ]); return [record.model, ...(record.aliases || [])].map((name) => { const nameWords = words(name); @@ -610,12 +603,15 @@ export function specFovCapabilityToken( /** * One-line spec summary for HUD meta text. - * @param {Object} spec - A record from this module. + * @param {Object} spec - A spec record (CCTV or ALPR). Resolution falls back + * from label to WxH to NMP. + * @param {{withBrand?: boolean}} [options] - `withBrand: false` leaves the + * brand out. * @returns {string} e.g. 'Axis Q6135-LE · 1080p · IR 250m · PTZ' ('' for null). */ -export function specSummary(spec) { +export function specSummary(spec, { withBrand = true } = {}) { if (!spec) return ''; - const parts = [`${spec.brand} ${spec.model}`]; + const parts = [withBrand ? `${spec.brand} ${spec.model}` : spec.model]; const { label, w, h, mp } = spec.resolution || {}; if (label) parts.push(label); else if (w && h) parts.push(`${w}x${h}`); From 340f3b59ab368e913400aedcc5ade892b9453912 Mon Sep 17 00:00:00 2001 From: Sameh Khamis Date: Thu, 19 Nov 2026 14:17:23 -0800 Subject: [PATCH 06/17] fix(ui): a phone no longer zooms the page when a text field gets focus iPhone Safari zooms the page in whenever a text field under 16 px gets focus, and every field in the app is under 16 px, so tapping the search box left the page zoomed in with its buttons out of reach. The viewport now has a maximum scale of 1, as map pages usually do: the map handles pinch zoom itself, and iPhones still let a pinch zoom the page. --- index.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/index.html b/index.html index ded159f2c9..ed18f8e240 100644 --- a/index.html +++ b/index.html @@ -2,7 +2,7 @@ - + God's Eye View

', + ]) + assert.equal(rawButtons(markup).length, 0, markup); + + for (const markup of [ + '', + '', + '', + '', + ]) + assert.equal(materialGlyphs(markup).length, 1, markup); + for (const markup of [ + '', + '', + '', + ]) + assert.equal(materialGlyphs(markup).length, 0, markup); + + assert.equal( + nativeInputs( + '', + 'checkbox', + ).length, + 1, + ); + assert.equal( + nativeInputs( + '', + 'range', + ).length, + 1, + ); + assert.equal( + nativeInputs( + '', + 'checkbox', + ).length, + 0, + ); + assert.equal( + nativeInputs( + '', + 'checkbox', + ).length, + 0, + ); +}); + test('the views are read: the scan reaches the views and skips the kit', () => { const files = views.map((view) => view.file); assert.ok(files.includes('src/ui/views/panels/ChatPanel.vue')); @@ -169,3 +265,79 @@ test('no view hand-writes a close button; each is a UiCloseButton', () => { found.push(`${file}: ${markup}`); assert.deepEqual(found, []); }); + +test('every button in the views is a kit button', () => { + const found = []; + for (const { file, source } of views) + for (const markup of rawButtons(source)) found.push(`${file}: ${markup}`); + assert.deepEqual(found, []); +}); + +test('every Material Symbols glyph in the views is a UiIcon', () => { + const found = []; + for (const { file, source } of views) + for (const markup of materialGlyphs(source)) + found.push(`${file}: ${markup}`); + assert.deepEqual(found, []); +}); + +test('every checkbox in the views is a UiCheckbox', () => { + const found = []; + for (const { file, source } of views) + for (const markup of nativeInputs(source, 'checkbox')) + found.push(`${file}: ${markup}`); + assert.deepEqual(found, []); +}); + +test('every range in the views is a UiSlider apart from the two named', () => { + const counts = {}; + for (const { file, source } of views) { + const n = nativeInputs(source, 'range').length; + if (n) counts[file] = n; + } + assert.deepEqual(counts, NATIVE_RANGES); +}); + +/** Every module under src outside the kit, tests and test support. */ +function scriptFiles(directory = SRC_ROOT) { + const files = []; + for (const entry of readdirSync(directory, { withFileTypes: true })) { + const absolute = path.join(directory, entry.name); + if (entry.isDirectory()) { + if ( + path.relative(KIT_ROOT, absolute) !== '' && + entry.name !== 'testSupport' + ) + files.push(...scriptFiles(absolute)); + } else if ( + entry.isFile() && + /\.(?:js|mjs|ts)$/.test(entry.name) && + !/\.test\.(?:js|mjs|ts)$/.test(entry.name) && + !/Fixture\.mjs$/.test(entry.name) + ) + files.push(absolute); + } + return files.sort(); +} + +const SCRIPT_CONTROL = + /\bcreateElement(?:NS)?\(\s*(?:[^,)]*,\s*)?['"`](?:button|select|input|textarea)['"`]/; +const SCRIPT_GLYPH = + /['"`][^'"`]*\bmaterial-symbols-(?:outlined|rounded|sharp)\b/; + +test('no module outside the kit builds a control or Material glyph in script', () => { + assert.ok(SCRIPT_CONTROL.test("const b = document.createElement('button');")); + assert.ok(SCRIPT_CONTROL.test('doc.createElement("input")')); + assert.ok(SCRIPT_GLYPH.test("span.className = 'material-symbols-outlined';")); + assert.ok(!SCRIPT_CONTROL.test("document.createElement('div')")); + const found = []; + for (const file of scriptFiles()) { + const relative = path.relative(REPO_ROOT, file).split(path.sep).join('/'); + const source = readFileSync(file, 'utf8'); + source.split('\n').forEach((line, index) => { + if (SCRIPT_CONTROL.test(line) || SCRIPT_GLYPH.test(line)) + found.push(`${relative}:${index + 1}: ${line.trim()}`); + }); + } + assert.deepEqual(found, []); +}); From 91e42b887f1bd8a2ddc9b9629afb865329b1e96a Mon Sep 17 00:00:00 2001 From: Sameh Khamis Date: Thu, 19 Nov 2026 15:04:57 -0800 Subject: [PATCH 11/17] Add the changelog entry for #1869 Co-authored-by: Manjunath Paparaju --- changelog.d/1869-kit-sweep-final-scan.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 changelog.d/1869-kit-sweep-final-scan.md diff --git a/changelog.d/1869-kit-sweep-final-scan.md b/changelog.d/1869-kit-sweep-final-scan.md new file mode 100644 index 0000000000..bcdfc9d9ff --- /dev/null +++ b/changelog.d/1869-kit-sweep-final-scan.md @@ -0,0 +1,3 @@ +- The view scan now forbids any hand-written button, Material glyph, + checkbox or range in the views, and any control built in script + (manjunath22466, samehkhamis, #1869). From 559a7cec7168d1b1125cb8d00bea4e689e62402d Mon Sep 17 00:00:00 2001 From: Sameh Khamis Date: Thu, 19 Nov 2026 15:31:47 -0800 Subject: [PATCH 12/17] Vue kit: the view scan reads SFC scripts, string markup and bound types Following review, the scan now also: - reads every SFC's script blocks, not only modules; - matches a createElement call Prettier wraps over lines, and any case of the tag name; - fails on a button, select, input or textarea written as markup in a string, comments aside, apart from the globe panel's standalone page (plain HTML a host serves, with no Vue or kit), which the test names and requires to still be the reason; - catches a Material class built in a template string; - reads an input's type when bound to a quoted literal or named in a v-bind object, in any case, and unquoted before `/>`; - catches a Material class named in a v-bind object. Each new path was confirmed to fail when its violation is put back. docs/VUE-MIGRATION.md now names the globe panel page as the exception, lists the two text areas among the native fields left, and notes that the scene dialog's field takes text-like types from its callers only. Co-authored-by: Manjunath Paparaju --- docs/VUE-MIGRATION.md | 14 ++- src/ui/kit/viewControls.test.mjs | 160 ++++++++++++++++++++++++------- 2 files changed, 138 insertions(+), 36 deletions(-) diff --git a/docs/VUE-MIGRATION.md b/docs/VUE-MIGRATION.md index 8e1c34d046..aa2909df10 100644 --- a/docs/VUE-MIGRATION.md +++ b/docs/VUE-MIGRATION.md @@ -89,10 +89,16 @@ the kit is a `UiButton`, `UiCloseButton` or another kit control, every Material Symbols glyph a `UiIcon`, every checkbox a `UiCheckbox`, every select a `UiSelect`, and every range a `UiSlider` except the radio tuner's and the world timeline's, for the reasons given below. No module -outside the kit builds a button, select, field or Material glyph in script -(`src/ui/kit/viewControls.test.mjs` pins all of it). The native fields -left are the text, number, password and file inputs the kit has no -control for, and the search fields whose surfaces this document names. +outside the kit, and no SFC's script, builds a button, select, field or +Material glyph in script or writes one as markup in a string, apart from +the globe panel's standalone page (`src/tools/globePanel.js`), plain HTML +a host serves with no Vue or kit, whose Expand and Open buttons are +written as markup (`src/ui/kit/viewControls.test.mjs` pins all of it). +The native fields left are the text, number, password and file inputs +and the two text areas (the chat's message box and the scene dialog's +multiline field) the kit has no control for, and the search fields whose +surfaces this document names. The scene dialog's single-line field takes +its type from its caller, which passes text-like types only. `UiButton` adds `pressedClass`, Core's class on a pressed toggle (most use `active`); its pressed classes toggle through `classList`, so a class other code adds (a voice highlight) survives a press. Every pressed toggle (a diff --git a/src/ui/kit/viewControls.test.mjs b/src/ui/kit/viewControls.test.mjs index 0ab62e717f..7ef7d42ba2 100644 --- a/src/ui/kit/viewControls.test.mjs +++ b/src/ui/kit/viewControls.test.mjs @@ -5,8 +5,10 @@ // pressed toggle is a UiButton with `pressed` (no template hand-writes // `aria-pressed` on any element, as an attribute or inside a `v-bind` // object, apart from the exceptions below), and every close, dismiss and -// clear button a UiCloseButton. Outside the kit, no module builds a button, -// select, field or Material glyph in script. +// clear button a UiCloseButton. Outside the kit, no module (nor an SFC's +// script) builds a button, select, field or Material glyph in script, or +// writes one as markup in a string, apart from the globe panel's standalone +// page named below. import { test } from 'node:test'; import assert from 'node:assert/strict'; import { readFileSync, readdirSync } from 'node:fs'; @@ -77,15 +79,31 @@ const NATIVE_RANGES = { 'src/ui/views/panels/WorldTimeline.vue': 1, }; const RAW_BUTTON = /`, 'gi'); -// A tag's static `type`, read from its attributes rather than their values. -const ATTRIBUTE = /([^\s=]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"']+)))?/g; +// An attribute and its value, read from the tag rather than other values. +const ATTRIBUTE = /([^\s=/]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'/>]+)))?/g; +/** + * A tag's `type`: written, bound to a quoted literal (`:type="'checkbox'"`), + * or named in a `v-bind` object; null when it is bound to anything else. + */ function inputType(attrs) { - for (const m of attrs.matchAll(ATTRIBUTE)) - if (m[1] === 'type') return m[2] ?? m[3] ?? m[4] ?? ''; + for (const m of attrs.matchAll(ATTRIBUTE)) { + const name = m[1].toLowerCase(); + const value = m[2] ?? m[3] ?? m[4] ?? ''; + if (name === 'type') return value.toLowerCase(); + if (name === ':type' || name === 'v-bind:type') { + const literal = /^\s*(['`])([^'`]*)\1\s*$/.exec(value); + if (literal) return literal[2].toLowerCase(); + } + if (name === 'v-bind' || name === ':') { + const named = /\btype\s*:\s*(['`])([^'`]*)\1/.exec(value); + if (named) return named[2].toLowerCase(); + } + } return null; } @@ -228,6 +246,25 @@ test('the scans find each hand-written button, glyph, checkbox and range', () => ).length, 0, ); + for (const markup of [ + ``, + ``, + ``, + '', + '', + ]) + assert.equal(nativeInputs(markup, 'checkbox').length, 1, markup); + assert.equal( + nativeInputs('', 'checkbox') + .length, + 0, + ); + assert.equal( + materialGlyphs( + ``, + ).length, + 1, + ); }); test('the views are read: the scan reaches the views and skips the kit', () => { @@ -298,46 +335,105 @@ test('every range in the views is a UiSlider apart from the two named', () => { assert.deepEqual(counts, NATIVE_RANGES); }); -/** Every module under src outside the kit, tests and test support. */ -function scriptFiles(directory = SRC_ROOT) { - const files = []; +// The globe panel's standalone page: plain HTML a host serves, with no Vue +// and no kit, so its two buttons are written as markup. +const STRING_MARKUP_PAGES = new Set(['src/tools/globePanel.js']); + +/** + * Every module under src outside the kit, tests and test support, and every + * SFC's script blocks, as `{ file, source }`. + */ +function scriptSources(directory = SRC_ROOT) { + const found = []; for (const entry of readdirSync(directory, { withFileTypes: true })) { const absolute = path.join(directory, entry.name); + const file = path.relative(REPO_ROOT, absolute).split(path.sep).join('/'); if (entry.isDirectory()) { if ( path.relative(KIT_ROOT, absolute) !== '' && entry.name !== 'testSupport' ) - files.push(...scriptFiles(absolute)); + found.push(...scriptSources(absolute)); } else if ( - entry.isFile() && - /\.(?:js|mjs|ts)$/.test(entry.name) && - !/\.test\.(?:js|mjs|ts)$/.test(entry.name) && - !/Fixture\.mjs$/.test(entry.name) - ) - files.push(absolute); + !entry.isFile() || + /\.test\.(?:js|mjs|ts)$|Fixture\.mjs$/.test(entry.name) + ) { + continue; + } else if (/\.(?:js|mjs|ts)$/.test(entry.name)) { + found.push({ file, source: readFileSync(absolute, 'utf8') }); + } else if (entry.name.endsWith('.vue')) { + const blocks = [ + ...readFileSync(absolute, 'utf8').matchAll( + /]*>([\s\S]*?)<\/script\s*>/g, + ), + ]; + found.push({ file, source: blocks.map((m) => m[1]).join('\n') }); + } } - return files.sort(); + return found; } const SCRIPT_CONTROL = - /\bcreateElement(?:NS)?\(\s*(?:[^,)]*,\s*)?['"`](?:button|select|input|textarea)['"`]/; + /\bcreateElement(?:NS)?\(\s*(?:[^,)]*,\s*)?['"`](?:button|select|input|textarea)['"`]/gi; const SCRIPT_GLYPH = - /['"`][^'"`]*\bmaterial-symbols-(?:outlined|rounded|sharp)\b/; + /['"`][^'"`]*\bmaterial-symbols-(?:outlined|rounded|sharp|\$\{)/g; +const STRING_MARKUP = /<(?:button|select|input|textarea)\b/gi; + +/** A source with its comments blanked, line numbers kept. */ +const uncommented = (source) => + source + .replace(/\/\*[\s\S]*?\*\//g, (comment) => comment.replace(/[^\n]/g, ' ')) + .replace(/(^|[^:'"`\\])\/\/[^\n]*/g, '$1'); + +/** Each match in a source, as `file:line: text`. */ +function hits(file, source, pattern) { + return [...source.matchAll(pattern)].map((m) => { + const line = source.slice(0, m.index).split('\n').length; + return `${file}:${line}: ${source.split('\n')[line - 1].trim()}`; + }); +} test('no module outside the kit builds a control or Material glyph in script', () => { - assert.ok(SCRIPT_CONTROL.test("const b = document.createElement('button');")); - assert.ok(SCRIPT_CONTROL.test('doc.createElement("input")')); - assert.ok(SCRIPT_GLYPH.test("span.className = 'material-symbols-outlined';")); - assert.ok(!SCRIPT_CONTROL.test("document.createElement('div')")); + const sees = (pattern, text) => [...text.matchAll(pattern)].length > 0; + assert.ok( + sees(SCRIPT_CONTROL, "const b = document.createElement('button');"), + ); + assert.ok(sees(SCRIPT_CONTROL, 'doc.createElement("INPUT")')); + assert.ok( + sees(SCRIPT_CONTROL, "someDocument.createElement(\n 'button',\n);"), + ); + assert.ok(!sees(SCRIPT_CONTROL, "document.createElement('div')")); + assert.ok( + sees(SCRIPT_GLYPH, "span.className = 'material-symbols-outlined';"), + ); + assert.ok(sees(SCRIPT_GLYPH, 'el.className = `material-symbols-${style}`;')); + assert.ok( + !sees(SCRIPT_GLYPH, 'ctx.font = \'24px "Material Symbols Outlined"\';'), + ); + assert.ok(sees(STRING_MARKUP, "host.innerHTML = '';")); + assert.ok( + !sees(STRING_MARKUP, "''".replace('', '')), + ); + + const sources = scriptSources(); + assert.ok( + sources.some(({ file }) => file === 'src/ui/views/panels/ChatPanel.vue'), + ); const found = []; - for (const file of scriptFiles()) { - const relative = path.relative(REPO_ROOT, file).split(path.sep).join('/'); - const source = readFileSync(file, 'utf8'); - source.split('\n').forEach((line, index) => { - if (SCRIPT_CONTROL.test(line) || SCRIPT_GLYPH.test(line)) - found.push(`${relative}:${index + 1}: ${line.trim()}`); - }); + for (const { file, source } of sources) { + found.push( + ...hits(file, source, SCRIPT_CONTROL), + ...hits(file, source, SCRIPT_GLYPH), + ); + if (!STRING_MARKUP_PAGES.has(file)) + found.push(...hits(file, uncommented(source), STRING_MARKUP)); } assert.deepEqual(found, []); + for (const file of STRING_MARKUP_PAGES) { + const page = sources.find((s) => s.file === file); + assert.ok( + page && hits(file, page.source, STRING_MARKUP).length, + `${file} no longer writes markup`, + ); + } }); From 33ac0545efafe1679a4357347aaf83a4d5c96e79 Mon Sep 17 00:00:00 2001 From: Sameh Khamis Date: Thu, 19 Nov 2026 15:48:50 -0800 Subject: [PATCH 13/17] Street Level photo viewer: settle opens, a gapless picker, a stated contract Follow-ups to the photo viewer's move to a Vue view (#1868): - A panorama's open waits for a draw of the canvas counted from before it is shown, so a view that draws at once inside its listener no longer leaves the open pending; and when the last view unsubscribes, an open waiting on a draw goes on instead of hanging. - photoViewers.js supersedes the mounts not drawn on a microtask, after the winning presentation has reached every subscriber: a second subscriber sees the earlier mount, then the later one, never null between. - A presentation without a mountKey counts as the latest mount (among several without, the one that began presenting last), and one without actions or supersede is passed over without throwing. Both fields are documented on ViewerAdapter.subscribeView in registry.js and in the store's comment. - The guard test also refuses .width, .height, .ariaLabel, .id and .value writes in photoViewer.js, and .src writes outside loadImage, where only the off-page Image it creates may take one. - The test fakes draw every viewer through one shared view behind photoViewers.js's picker, as the application does, so provider and layer tests see supersede. Nothing changes in the running app. Co-authored-by: Manjunath Paparaju --- docs/CURRENT-STATE.md | 5 +- src/layers/streetLevel/photoViewer.js | 61 ++++++++----- src/layers/streetLevel/photoViewer.test.mjs | 91 ++++++++++++++++++++ src/layers/streetLevel/photoViewers.js | 64 ++++++++++---- src/layers/streetLevel/photoViewers.test.mjs | 80 ++++++++++++++++- src/layers/streetLevel/registry.js | 9 +- src/testSupport/kartaViewFakes.mjs | 49 +++++++++-- src/ui/kit/streetLevelPhotoControls.test.mjs | 18 +++- src/ui/stores/streetLevelPhoto.js | 9 +- 9 files changed, 337 insertions(+), 49 deletions(-) diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index 06c3093d7d..ce7a0e21c7 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -6354,8 +6354,9 @@ viewer host and hands back the canvas the panorama is drawn on (a fresh one after a lost context). Each mount and each canvas has a key of its own, so a viewer never draws on another one's elements, and of two viewers mounting at once only the later one is drawn (`photoViewers.js`): the -earlier one's mount closes. Without a subscribed view these photos cannot -open. +earlier one's mount closes. A view may draw at once or later; what it +reads (`mountKey`, `actions.supersede()`) is `ViewerAdapter.subscribeView` +in `registry.js`. Without a subscribed view these photos cannot open. Panoramax (`providers/panoramax/`) is keyless and browser-side: the meta-catalogue `api.panoramax.xyz` (CORS open) federates every instance, and diff --git a/src/layers/streetLevel/photoViewer.js b/src/layers/streetLevel/photoViewer.js index c9b9f48a11..f802777e78 100644 --- a/src/layers/streetLevel/photoViewer.js +++ b/src/layers/streetLevel/photoViewer.js @@ -228,13 +228,15 @@ export function panoSizeFor(canvasPixels, fovDeg) { * each change, * or null while unmounted. A view draws it into `host` (the application's is * `StreetLevelPhotoViewer`), forwards its events to `actions` and hands each - * element back through `actions.attach(name, element)`: the panorama canvas - * to draw on, the frame and picture to measure, the root and buttons to - * keep focus. Each mount has its own `mountKey`, and a new `canvasKey` asks - * for a fresh canvas (a lost WebGL context): neither is ever reused. - * `actions.supersede()` tells a viewer another one is drawn in its place: - * it unmounts, and a mount still waiting to be drawn fails as closed. - * Mounting with no view subscribed fails. + * element back through `actions.attach(name, element)` on every draw: the + * panorama canvas to draw on, the frame and picture to measure, the root + * and buttons to keep focus. A view may draw at once, inside its listener, + * or later (Vue draws on a microtask). Each mount has its own `mountKey`, + * and a new `canvasKey` asks for a fresh canvas (a lost WebGL context): + * neither is ever reused. `actions.supersede()` tells a viewer another one + * is drawn in its place: it unmounts, and a mount still waiting to be drawn + * fails as closed. Mounting with no view subscribed fails; an open waiting + * on a draw when the last view leaves goes on without it. * * Photos are normalized by the provider: `{id, sequenceId, lon, lat, * heading, isPano, capturedAt}` plus whatever its `sources` read. @@ -284,6 +286,8 @@ export function createPhotoViewer({ /** Waiting for the view's root (a mount), or its canvas: a fresh one, or the next draw. */ const rootWaiters = new Set(); const canvasWaiters = new Set(); + /** How many times the view has handed the canvas back (once per draw). */ + let canvasDraws = 0; let renderer = null; /** WebGL failed once: 360° photos show their front view instead. */ let rendererFailed = false; @@ -396,22 +400,28 @@ export function createPhotoViewer({ waiters.clear(); } - /** The panorama canvas once the view has drawn it, or the open stopped. */ - function canvasReady(signal) { - if (canvas || !presented || signal?.aborted) return Promise.resolve(); + /** A draw of the canvas, or none coming: unmounted, no view, or the open stopped. */ + function canvasDrawn(drawn, signal) { + if (drawn() || !presented || !viewListeners.size || signal?.aborted) + return Promise.resolve(); return new Promise((resolve) => { canvasWaiters.add(resolve); signal?.addEventListener?.('abort', resolve, { once: true }); }); } - /** The view's next draw (it hands the canvas back each time), or none coming. */ - function nextDraw(signal) { - if (!presented || signal?.aborted) return Promise.resolve(); - return new Promise((resolve) => { - canvasWaiters.add(resolve); - signal?.addEventListener?.('abort', resolve, { once: true }); - }); + /** The panorama canvas once the view has drawn it, or the open stopped. */ + function canvasReady(signal) { + return canvasDrawn(() => Boolean(canvas), signal); + } + + /** + * A draw of the canvas after the `count`th (it hands the canvas back each + * time), or none coming. A view may draw synchronously, inside the + * presentation, before anything waits: counted, that draw is not missed. + */ + function drawnAfter(count, signal) { + return canvasDrawn(() => canvasDraws > count, signal); } function syncButtons() { @@ -667,7 +677,10 @@ export function createPhotoViewer({ if (presented?.actions !== actions || !element) return; ELEMENTS[name]?.(element); if (name === 'root') wake(rootWaiters); - if (name === 'canvas') wake(canvasWaiters); + if (name === 'canvas') { + canvasDraws++; + wake(canvasWaiters); + } }, keydown: current(onKeyDown), pointerdown: current(onPointerDown), @@ -865,9 +878,11 @@ export function createPhotoViewer({ renderer.setView({ yaw: 0, pitch: 0, fov: PANO_FOV_DEFAULT_DEG }); photo = target; // Shown first: a hidden canvas measures 0 and would be sized 1×1. The - // view draws it shown on a microtask, and hands the canvas back then. + // view draws it shown, at once or on a microtask, and hands the canvas + // back then. + const draws = canvasDraws; show('pano'); - await nextDraw(signal); + await drawnAfter(draws, signal); if (seq !== openSeq || !renderer) { image.close?.(); if (seq !== openSeq) return false; @@ -1029,7 +1044,11 @@ export function createPhotoViewer({ subscribeView(listener) { viewListeners.add(listener); listener(presented); - return () => viewListeners.delete(listener); + return () => { + // The last view went: an open waiting on its draw goes on without. + if (viewListeners.delete(listener) && !viewListeners.size) + wake(canvasWaiters); + }; }, }; return adapter; diff --git a/src/layers/streetLevel/photoViewer.test.mjs b/src/layers/streetLevel/photoViewer.test.mjs index 97c8bf4000..e1e9b14f5d 100644 --- a/src/layers/streetLevel/photoViewer.test.mjs +++ b/src/layers/streetLevel/photoViewer.test.mjs @@ -636,3 +636,94 @@ test('a panorama reopened after a lost context waits for the view’s fresh canv ); assert.equal(shown.kind, 'pano', 'not the front view'); }); + +/** + * A panorama viewer whose sequence goes on both ways (its ‹ › present no + * change once shown), drawn by `view` alone, not by the shared fake view. + */ +function panoramaViewer() { + const images = []; + const viewer = createPhotoViewer({ + providerId: 'test', + name: 'Test', + sources: SOURCES, + getPhoto: async (id) => PHOTOS[id], + step: async () => 'b', + onStep() {}, + load: async (url) => ({ src: url }), + createRenderer: () => ({ + setImage: (image) => images.push(image.src), + setView() {}, + getView: () => ({ yaw: 0, pitch: 0, fov: 80 }), + resize() {}, + clear() {}, + destroy() {}, + }), + }); + return { viewer, images }; +} + +/** Elements a view hands back: what the viewer measures and focuses. */ +const elements = () => + Object.fromEntries( + ['root', 'picture', 'canvas', 'prev', 'next'].map((name) => [ + name, + { clientWidth: 400, clientHeight: 250 }, + ]), + ); + +/** Whether `promise` settles within a few macrotasks. */ +const settles = (promise) => + Promise.race([ + promise.then( + () => true, + () => true, + ), + new Promise((resolve) => setTimeout(() => resolve(false), 50)), + ]); + +test('a view that draws at once, inside its listener, opens a panorama', async () => { + const { viewer, images } = panoramaViewer(); + const parts = elements(); + const unsubscribe = viewer.subscribeView((view) => { + if (!view) return; + for (const [name, element] of Object.entries(parts)) + view.actions.attach(name, element); + }); + await viewer.mount(fakeHost()); + assert.equal(await settles(viewer.open('a')), true, 'not left pending'); + assert.deepEqual(images, ['a-first']); + viewer.unmount(); + unsubscribe(); +}); + +test('an open waiting on the view’s draw goes on when the view unsubscribes', async () => { + const { viewer } = panoramaViewer(); + const parts = elements(); + const kinds = []; + // Draws the mount, then nothing more. + const unsubscribe = viewer.subscribeView((view) => { + if (!view) return; + kinds.push(view.kind); + if (kinds.length > 1) return; + for (const [name, element] of Object.entries(parts)) + view.actions.attach(name, element); + }); + await viewer.mount(fakeHost()); + const opening = viewer.open('a'); + assert.ok(await until(() => kinds.includes('pano')), 'waiting on a draw'); + unsubscribe(); + assert.equal(await settles(opening), true, 'not left pending'); + viewer.unmount(); +}); + +test('the shared fake view draws only the later of two mounts, as the app does', async () => { + const one = setup(); + const two = setup(); + await one.viewer.mount(one.host); + assert.equal(one.host.children.length, 1); + await two.viewer.mount(one.host); + assert.equal(one.host.children.length, 1, 'one root, not one per viewer'); + await assert.rejects(one.viewer.open('f'), /not mounted/, 'superseded'); + two.viewer.unmount(); +}); diff --git a/src/layers/streetLevel/photoViewers.js b/src/layers/streetLevel/photoViewers.js index ecf4eab5a1..bb1ddf404f 100644 --- a/src/layers/streetLevel/photoViewers.js +++ b/src/layers/streetLevel/photoViewers.js @@ -1,37 +1,70 @@ /** * Receive the photo viewer to draw, out of several photo viewers mounting - * in one host (see photoViewer.js): the one mounted last, by its mount key, - * whatever order they present in. One view draws one viewer, so a viewer - * still mounting when a later one presents is superseded: it settles its - * mount as closed and stops presenting. Starts with the current one (null - * while none is mounted). + * in one host (see photoViewer.js): the one mounted last, whatever order + * they present in. One view draws one viewer, so a viewer still mounting + * when a later one presents is superseded: it settles its mount as closed + * and stops presenting. Starts with the current one (null while none is + * mounted). + * + * Two fields of a presentation are read here (see ViewerAdapter.subscribeView + * in registry.js): + * - `mountKey`, a number larger for each later mount, orders the mounts. A + * presentation without one counts as the latest mount; among several + * without, the one that began presenting last is. + * - `actions.supersede()`, where present, is called on each presentation + * not drawn once the pick changes. It runs on a microtask, after the + * presentation that won has reached every subscriber: a subscriber never + * sees the superseded one withdraw before it sees the one replacing it. * @param {Iterable<{subscribeView?: Function}>} viewers * @param {(view: ?object) => void} listener * @returns {() => void} Unsubscribe. */ export function subscribePhotoViewers(viewers, listener) { - // Each viewer's current presentation. + // Each viewer's current presentation, and when it began presenting. const shown = new Map(); + let arrivals = 0; let ready = false; + let closed = false; + let superseding = false; let last; + /** Whether `a` was mounted after `b`. */ + const later = (a, b) => { + const key = ({ view }) => + Number.isFinite(view.mountKey) ? view.mountKey : Infinity; + const ka = key(a); + const kb = key(b); + return ka !== kb ? ka > kb : a.arrival > b.arrival; + }; + // The others are not drawn: a mount still waiting on the view never + // would be. + const supersede = () => { + superseding = false; + if (closed || !last) return; + for (const { view } of [...shown.values()]) + if (view !== last) view.actions?.supersede?.(); + }; const publish = () => { let next = null; - for (const view of shown.values()) - if (!next || view.mountKey > next.mountKey) next = view; + for (const entry of shown.values()) + if (!next || later(entry, next)) next = entry; + next = next?.view ?? null; if (!ready || next === last) return; last = next; listener(next); - // The others are not drawn: a mount still waiting on the view never - // would be. - if (next) - for (const view of [...shown.values()]) - if (view.mountKey < next.mountKey) view.actions.supersede(); + if (next && shown.size > 1 && !superseding) { + superseding = true; + queueMicrotask(supersede); + } }; const unsubscribes = []; for (const viewer of viewers) { const unsubscribe = viewer?.subscribeView?.((view) => { - if (view) shown.set(viewer, view); - else shown.delete(viewer); + if (closed) return; + const entry = shown.get(viewer); + if (!view) shown.delete(viewer); + else if (entry && entry.view.mountKey === view.mountKey) + entry.view = view; + else shown.set(viewer, { view, arrival: ++arrivals }); publish(); }); if (typeof unsubscribe === 'function') unsubscribes.push(unsubscribe); @@ -40,6 +73,7 @@ export function subscribePhotoViewers(viewers, listener) { publish(); if (last === undefined) listener((last = null)); return () => { + closed = true; for (const unsubscribe of unsubscribes.splice(0)) unsubscribe(); }; } diff --git a/src/layers/streetLevel/photoViewers.test.mjs b/src/layers/streetLevel/photoViewers.test.mjs index a4525723bc..f9b3f609d6 100644 --- a/src/layers/streetLevel/photoViewers.test.mjs +++ b/src/layers/streetLevel/photoViewers.test.mjs @@ -29,7 +29,7 @@ function fakeViewer() { return viewer; } -test('the later mount is drawn, whatever order the viewers present in', () => { +test('the later mount is drawn, whatever order the viewers present in', async () => { const a = fakeViewer(); const b = fakeViewer(); const shown = []; @@ -40,6 +40,8 @@ test('the later mount is drawn, whatever order the viewers present in', () => { const later = b.view(2); b.present(later); assert.equal(shown.at(-1), later); + // Once every subscriber has the later one. + await Promise.resolve(); assert.equal(a.superseded, 1, 'the earlier mount is told it is not drawn'); // The earlier viewer presents again: it does not take the view back. a.present({ ...first, kind: 'flat' }); @@ -53,3 +55,79 @@ test('the later mount is drawn, whatever order the viewers present in', () => { a.present(first); assert.equal(shown.length, 5, 'unsubscribed'); }); + +/** A viewer that, superseded, unmounts as photoViewer.js does: it presents null. */ +function unmountingViewer() { + const viewer = fakeViewer(); + const view = viewer.view; + viewer.view = (mountKey) => { + const presented = view(mountKey); + const supersede = presented.actions.supersede; + presented.actions.supersede = () => { + supersede(); + viewer.present(null); + }; + return presented; + }; + return viewer; +} + +test('every subscriber sees the earlier mount, then the later one, with no gap', async () => { + const a = unmountingViewer(); + const b = unmountingViewer(); + const first = []; + const second = []; + const unsubscribes = [ + subscribePhotoViewers([a, b], (view) => first.push(view)), + subscribePhotoViewers([a, b], (view) => second.push(view)), + ]; + const earlier = a.view(1); + a.present(earlier); + const later = b.view(2); + b.present(later); + await Promise.resolve(); + assert.equal(a.superseded, 1, 'superseded once, by both'); + assert.deepEqual(first, [null, earlier, later]); + assert.deepEqual(second, [null, earlier, later], 'never null between'); + for (const unsubscribe of unsubscribes) unsubscribe(); +}); + +test('a presentation without a mount key counts as the latest mount', () => { + const a = fakeViewer(); + const b = fakeViewer(); + const c = fakeViewer(); + const shown = []; + const unsubscribe = subscribePhotoViewers([a, b, c], (view) => + shown.push(view), + ); + a.present(a.view(5)); + const keyless = { actions: {} }; + b.present(keyless); + assert.equal(shown.at(-1), keyless, 'after the keyed one'); + // A keyed mount presenting later does not take it back. + a.present(a.view(6)); + assert.equal(shown.at(-1), keyless); + // Of two without, the one that began presenting last. + const newer = { actions: {} }; + c.present(newer); + assert.equal(shown.at(-1), newer); + b.present({ ...keyless, kind: 'flat' }); + assert.equal(shown.at(-1), newer, 'presenting again is not a new mount'); + unsubscribe(); +}); + +test('a presentation without actions or supersede is drawn and passed over without throwing', async () => { + const a = fakeViewer(); + const b = fakeViewer(); + const shown = []; + const unsubscribe = subscribePhotoViewers([a, b], (view) => shown.push(view)); + a.present({ mountKey: 1 }); + const later = { mountKey: 2, actions: {} }; + assert.doesNotThrow(() => b.present(later)); + await Promise.resolve(); + assert.equal(shown.at(-1), later); + a.present({ mountKey: 3 }); + await Promise.resolve(); + assert.equal(shown.at(-1).mountKey, 3); + unsubscribe(); +}); diff --git a/src/layers/streetLevel/registry.js b/src/layers/streetLevel/registry.js index b74cfcdc99..177028d570 100644 --- a/src/layers/streetLevel/registry.js +++ b/src/layers/streetLevel/registry.js @@ -65,7 +65,14 @@ export function filtersOf(provider) { * @property {(listener: (pose: StreetPose) => void) => () => void} onPose * @property {(listener: (view: ?object) => void) => () => void} [subscribeView] * An adapter that draws nothing itself presents its viewer here, for the - * layer's `subscribePhotoViewer()` (see photoViewer.js). + * layer's `subscribePhotoViewer()` (see photoViewer.js): its current + * presentation at once, then each new one, null while unmounted. One view + * draws one viewer (photoViewers.js picks it), reading two fields: + * `mountKey`, a number larger for each later mount (the later mount is + * drawn; a presentation without one counts as the latest), and + * `actions.supersede()`, called on a mount that is not drawn because a + * later one is (it should unmount, failing a mount still waiting to be + * drawn; an adapter without it is simply not drawn). * * @typedef {object} StreetPose * @property {string} providerId diff --git a/src/testSupport/kartaViewFakes.mjs b/src/testSupport/kartaViewFakes.mjs index 83ed5f38f5..c4b5ba5cce 100644 --- a/src/testSupport/kartaViewFakes.mjs +++ b/src/testSupport/kartaViewFakes.mjs @@ -1,4 +1,5 @@ // DOM stand-ins for the KartaView viewer's tests (no browser in Node). +import { subscribePhotoViewers } from '../layers/streetLevel/photoViewers.js'; /** A DOM element with what the viewer touches: children, events, attributes. */ function fakeElement(tag) { @@ -71,7 +72,45 @@ export function fakeHost(viewer = null) { } /** - * Draw a photo viewer's presentations with fake elements, as + * The one view of the photo viewers given to `drawPhotoViewer`, as the + * application has one StreetLevelPhotoViewer: the viewers reach it through + * photoViewers.js's picker, as the layer's `subscribePhotoViewer()` does, + * so only the mount made last is drawn and the earlier ones are superseded. + */ +const shared = { + viewers: new Set(), + draw: null, + unsubscribe: null, + generation: 0, +}; + +/** Subscribe the view to the viewers it has now, then let the old picker go. */ +function resubscribe() { + const previous = shared.unsubscribe; + const generation = ++shared.generation; + // The new picker first: a viewer is never left without a view. + shared.unsubscribe = subscribePhotoViewers([...shared.viewers], (view) => { + if (generation === shared.generation) shared.draw(view); + }); + previous?.(); +} + +/** + * Draw a photo viewer with the shared view, alongside every other viewer + * given here (see `shared`). + * @returns {() => void} Stop drawing it. + */ +export function drawPhotoViewer(viewer) { + shared.draw ??= photoView(); + shared.viewers.add(viewer); + resubscribe(); + return () => { + if (shared.viewers.delete(viewer)) resubscribe(); + }; +} + +/** + * A view drawing the presentations it is given with fake elements, as * StreetLevelPhotoViewer does through Vue: changes made in one tick are * drawn once, on a microtask, with their final value; the root (keyed by * the mount) holds the picture, the panorama canvas (keyed by its canvas @@ -79,9 +118,9 @@ export function fakeHost(viewer = null) { * is handed back on each draw. A value is written only when the drawn * presentation changes it, and the elements' events reach the viewer's * actions. - * @returns {() => void} Stop drawing. + * @returns {(view: ?object) => void} Draw this presentation. */ -export function drawPhotoViewer(viewer) { +function photoView() { let parts = null; let last = null; let pending = null; @@ -162,7 +201,7 @@ export function drawPhotoViewer(viewer) { for (const name of ['root', 'picture', 'canvas', 'prev', 'next']) view.actions.attach(name, parts[name]); }; - return viewer.subscribeView((view) => { + return (view) => { pending = view; if (queued) return; queued = true; @@ -170,7 +209,7 @@ export function drawPhotoViewer(viewer) { queued = false; draw(pending); }); - }); + }; } /** diff --git a/src/ui/kit/streetLevelPhotoControls.test.mjs b/src/ui/kit/streetLevelPhotoControls.test.mjs index be1d65a8b5..5f20b03faf 100644 --- a/src/ui/kit/streetLevelPhotoControls.test.mjs +++ b/src/ui/kit/streetLevelPhotoControls.test.mjs @@ -74,10 +74,20 @@ test('the step buttons are not pressed toggles', () => { } }); +/** + * `loadImage`, which downloads through an Image of its own that is never on + * the page: the one place a `.src` is written. + */ +const LOADER = /^export function loadImage\([\s\S]*?^}$/m; + test('the photo viewer is drawn by its view, and its layer needs no Vue', () => { const source = read(VIEWER); + const loader = source.match(LOADER)?.[0]; + assert.ok(loader, 'loadImage is found'); + const rest = source.replace(LOADER, ''); // No element made, inserted, moved, removed or written: the view does - // all of that. (An Image the loader downloads with is not on the page.) + // all of that. (The panorama renderer in panorama.js sizes its canvas's + // drawing buffer, as WebGL drawing does; nothing here does.) for (const write of [ /createElement/, /\b(?:inner|outer)HTML\b/, @@ -87,9 +97,15 @@ test('the photo viewer is drawn by its view, and its layer needs no Vue', () => /\.(?:set|remove|toggle)Attribute(?:NS)?\(/, /\.(?:classList|className|dataset|style)\b/, /\.(?:hidden|disabled|textContent|innerText|tabIndex|title|alt)\s*=[^=]/, + /\.(?:width|height|ariaLabel|id|value)\s*=[^=]/, /from 'vue'|\.vue'/, ]) assert.doesNotMatch(source, write); + assert.doesNotMatch(rest, /\.src\s*=[^=]/, 'a .src written on the page'); + // In loadImage, only on the off-page Image it creates. + assert.match(loader, /\bconst image = new Image\(\);/); + for (const [write] of loader.matchAll(/[\w$.\]]+\.src\s*=(?!=)/g)) + assert.match(write, /^image\.src\s*=$/, write); const markup = template(VIEW); const opening = (name, attribute) => new RegExp(String.raw`<${name}\b${ATTRS}\s${attribute}${ATTRS}>`); diff --git a/src/ui/stores/streetLevelPhoto.js b/src/ui/stores/streetLevelPhoto.js index dc0ebffacb..b9498452b3 100644 --- a/src/ui/stores/streetLevelPhoto.js +++ b/src/ui/stores/streetLevelPhoto.js @@ -10,9 +10,12 @@ export const useStreetLevelPhotoStore = defineStore( 'gev-street-level-photo', () => { /** - * `{host, providerId, label, alt, kind, src, fit, canvasKey, dragging, - * prevLabel, prevDisabled, nextLabel, nextDisabled, actions}`, or null - * while no photo viewer is mounted. + * `{host, mountKey, providerId, label, alt, kind, src, fit, canvasKey, + * dragging, prevLabel, prevDisabled, nextLabel, nextDisabled, actions}`, + * or null while no photo viewer is mounted. Of the viewers mounting in + * the host, only the one mounted last (the largest `mountKey`) is + * published; `actions.supersede()` tells the others they are not drawn + * (see `ViewerAdapter.subscribeView` in src/layers/streetLevel/registry.js). */ const photo = shallowRef(null); From e6f21777babd296f71a084e37a3d9c54ef197e33 Mon Sep 17 00:00:00 2001 From: Sameh Khamis Date: Thu, 19 Nov 2026 16:04:21 -0800 Subject: [PATCH 14/17] Street Level photo viewer: keyless ranking, closed waits, a moved canvas Review follow-ups to the previous commit: - photoViewers.js ranks a presentation without a mountKey as mounted when it began presenting (after the latest key seen, before any later mount), so a photo viewer mounting while a keyless one shows is drawn and the keyless one superseded; supersede is queued whenever more than one presents after any change, not only when the pick changes. - A panorama's open still waiting on a draw when the last view leaves fails as closed and leaves no photo shown, instead of uploading to a canvas never drawn. A mount waiting on its first draw then also fails as closed and is unmounted, so a view subscribing later sees nothing. - A view handing back another canvas element than the renderer's drops the renderer and draws the panorama again on the new one, as after a lost context. - The guard test allows a .src write in loadImage only on the one `image` binding, created by new Image() and never rebound or shadowed, and refuses `(expr).src =` and bracket property writes anywhere. - The test fakes' shared view is reset before each test (resetPhotoView), so a viewer left by an earlier test is neither drawn with nor superseded by a later test's. Nothing changes in the running app. Co-authored-by: Manjunath Paparaju --- src/layers/streetLevel/photoViewer.js | 79 ++++++++++--- src/layers/streetLevel/photoViewer.test.mjs | 107 +++++++++++++++++- src/layers/streetLevel/photoViewers.js | 45 +++++--- src/layers/streetLevel/photoViewers.test.mjs | 67 ++++++++++- .../providers/kartaview/provider.test.mjs | 4 + .../providers/kartaview/viewer.test.mjs | 4 + .../providers/panoramax/provider.test.mjs | 4 + .../providers/panoramax/viewer.test.mjs | 9 +- src/layers/streetLevel/registry.js | 8 +- src/testSupport/kartaViewFakes.mjs | 15 ++- src/ui/kit/streetLevelPhotoControls.test.mjs | 35 +++++- 11 files changed, 327 insertions(+), 50 deletions(-) diff --git a/src/layers/streetLevel/photoViewer.js b/src/layers/streetLevel/photoViewer.js index f802777e78..e2d8d14e29 100644 --- a/src/layers/streetLevel/photoViewer.js +++ b/src/layers/streetLevel/photoViewer.js @@ -159,6 +159,16 @@ async function loadBitmap(url, timeoutMs, resize, failure, signal) { } } +/** + * Unmounted, superseded or left without a view before the view drew what + * was waiting on it (`undrawn`): a mount or an open that fails as closed. + */ +function undrawn() { + return Object.assign(new Error('Street-level viewer was closed'), { + undrawn: true, + }); +} + /** * A picture refused for its size (`tooLarge`): the viewer will not load * that file another way, an having no size limit at all. @@ -235,8 +245,11 @@ export function panoSizeFor(canvasPixels, fovDeg) { * and a new `canvasKey` asks for a fresh canvas (a lost WebGL context): * neither is ever reused. `actions.supersede()` tells a viewer another one * is drawn in its place: it unmounts, and a mount still waiting to be drawn - * fails as closed. Mounting with no view subscribed fails; an open waiting - * on a draw when the last view leaves goes on without it. + * fails as closed. Mounting with no view subscribed fails, and a mount or + * a panorama's open waiting on a draw when the last view leaves fails as + * closed (the mount unmounts; the open leaves no photo shown). A view + * handing back another canvas element than the renderer's (one subscribed + * since) gets the panorama drawn again on it, as after a lost context. * * Photos are normalized by the provider: `{id, sequenceId, lon, lat, * heading, isPano, capturedAt}` plus whatever its `sources` read. @@ -479,6 +492,27 @@ export function createPhotoViewer({ const from = event?.currentTarget ?? event?.target; if (from && from !== canvas) return; event.preventDefault?.(); + dropRenderer(); + // A lost canvas hands back its lost context: the view draws a new + // element in its place and hands it back. + canvas = null; + present({ canvasKey: ++viewKeys }); + reopen(); + } + + /** + * The view drew the panorama on another canvas element than the + * renderer's (a view that subscribed since): the renderer cannot follow + * it, so the photo is drawn again on a new one, as after a lost context. + */ + function moveCanvas(element) { + dropRenderer(); + canvas = element; + reopen(); + } + + /** Let the renderer go, keeping the user's look for the photo's reopen. */ + function dropRenderer() { const lost = renderer; renderer = null; // The new renderer starts facing the photo's heading: keep the user's look. @@ -489,11 +523,10 @@ export function createPhotoViewer({ } catch { /* already gone */ } - // A lost canvas hands back its lost context: the view draws a new - // element in its place and hands it back. - canvas = null; - present({ canvasKey: ++viewKeys }); - // Show the photo again through the core, unless a newer one is opening. + } + + /** Show the panorama again through the core, unless a newer photo is opening. */ + function reopen() { if (showing === 'pano' && photo && openingId === null) { const again = photo.id; show(null); @@ -675,7 +708,9 @@ export function createPhotoViewer({ const actions = { attach(name, element) { if (presented?.actions !== actions || !element) return; - ELEMENTS[name]?.(element); + if (name === 'canvas' && renderer && canvas && element !== canvas) + moveCanvas(element); + else ELEMENTS[name]?.(element); if (name === 'root') wake(rootWaiters); if (name === 'canvas') { canvasDraws++; @@ -883,6 +918,14 @@ export function createPhotoViewer({ const draws = canvasDraws; show('pano'); await drawnAfter(draws, signal); + // The last view left before drawing it: the canvas was never shown, and + // nothing is drawn until a view is back. + if (seq === openSeq && canvasDraws === draws && !viewListeners.size) { + image.close?.(); + photo = null; + show(null); + throw undrawn(); + } if (seq !== openSeq || !renderer) { image.close?.(); if (seq !== openSeq) return false; @@ -931,7 +974,8 @@ export function createPhotoViewer({ if (sources.hasPano(target) && ensureRenderer()) { try { shown = await showPano(target, seq, keepView, signal); - } catch { + } catch (error) { + if (error?.undrawn) throw error; // The panorama failed: its front view is better than nothing. if (seq !== openSeq) return; shown = await showFlat(target, seq, signal); @@ -952,12 +996,16 @@ export function createPhotoViewer({ rendererFailed = false; if (!viewListeners.size) throw new Error('Street Level photo viewer has no view to draw it'); - // Resolves once the view drew the viewer, or it was unmounted meanwhile. + // Resolves once the view drew the viewer, or it was unmounted, or its + // last view left, meanwhile. const drawn = new Promise((resolve) => rootWaiters.add(resolve)); build(host); if (!root) await drawn; - // Unmounted or superseded before the view drew it. - if (!root) throw new Error('Street-level viewer was closed'); + if (root) return; + // The last view left before drawing it: no view will. Unmounted, as + // when superseded, so a view subscribing later draws nothing. + if (presented) adapter.unmount(); + throw undrawn(); }, /** Resolves once the photo is on screen and its pose was emitted. */ @@ -1045,9 +1093,12 @@ export function createPhotoViewer({ viewListeners.add(listener); listener(presented); return () => { - // The last view went: an open waiting on its draw goes on without. - if (viewListeners.delete(listener) && !viewListeners.size) + // The last view went: a mount or an open waiting on its draw fails + // as closed. + if (viewListeners.delete(listener) && !viewListeners.size) { + wake(rootWaiters); wake(canvasWaiters); + } }; }, }; diff --git a/src/layers/streetLevel/photoViewer.test.mjs b/src/layers/streetLevel/photoViewer.test.mjs index e1e9b14f5d..ac3e252885 100644 --- a/src/layers/streetLevel/photoViewer.test.mjs +++ b/src/layers/streetLevel/photoViewer.test.mjs @@ -1,7 +1,14 @@ import assert from 'node:assert/strict'; import test from 'node:test'; import { createPhotoViewer } from './photoViewer.js'; -import { fakeHost, until } from '../../testSupport/kartaViewFakes.mjs'; +import { + fakeHost, + until, + resetPhotoView, +} from '../../testSupport/kartaViewFakes.mjs'; + +// Each test draws its own viewers only. +test.beforeEach(resetPhotoView); const PHOTOS = { a: { id: 'a', sequenceId: 's', lon: 1, lat: 2, heading: 0, isPano: true }, @@ -697,12 +704,14 @@ test('a view that draws at once, inside its listener, opens a panorama', async ( unsubscribe(); }); -test('an open waiting on the view’s draw goes on when the view unsubscribes', async () => { - const { viewer } = panoramaViewer(); +test('a panorama’s open waiting on the view’s draw fails as closed when the view leaves', async () => { + const { viewer, images } = panoramaViewer(); const parts = elements(); const kinds = []; + const presented = []; // Draws the mount, then nothing more. const unsubscribe = viewer.subscribeView((view) => { + presented.push(view); if (!view) return; kinds.push(view.kind); if (kinds.length > 1) return; @@ -714,9 +723,85 @@ test('an open waiting on the view’s draw goes on when the view unsubscribes', assert.ok(await until(() => kinds.includes('pano')), 'waiting on a draw'); unsubscribe(); assert.equal(await settles(opening), true, 'not left pending'); + await assert.rejects(opening, /viewer was closed/); + assert.deepEqual(images, [], 'nothing uploaded to a canvas never shown'); + // A view back draws the viewer mounted, with no photo shown. + let again = null; + const resubscribe = viewer.subscribeView((view) => (again = view)); + assert.ok(again, 'still mounted'); + assert.equal(again.kind, ''); + resubscribe(); viewer.unmount(); }); +test('a mount waiting on the view’s draw fails as closed when the view leaves, and is unmounted', async () => { + const { viewer } = panoramaViewer(); + const unsubscribe = viewer.subscribeView(() => {}); + const mounting = viewer.mount(fakeHost()); + unsubscribe(); + assert.equal(await settles(mounting), true, 'not left pending'); + await assert.rejects(mounting, /viewer was closed/); + let current; + const resubscribe = viewer.subscribeView((view) => (current = view)); + assert.equal(current, null, 'nothing presented'); + await assert.rejects(viewer.open('a'), /not mounted/); + resubscribe(); +}); + +test('a view handing back another canvas gets the panorama drawn again on it', async () => { + const renderers = []; + const reopened = []; + const viewer = createPhotoViewer({ + providerId: 'test', + name: 'Test', + sources: SOURCES, + getPhoto: async (id) => PHOTOS[id], + step: async () => 'b', + onStep() {}, + onReopen: (id) => { + reopened.push(id); + viewer.open(id); + }, + load: async (url) => ({ src: url }), + createRenderer: (canvas) => { + const renderer = { + canvas, + images: [], + destroyed: false, + setImage: (image) => renderer.images.push(image.src), + setView() {}, + getView: () => ({ yaw: 10, pitch: 0, fov: 80 }), + resize() {}, + clear() {}, + destroy: () => (renderer.destroyed = true), + }; + renderers.push(renderer); + return renderer; + }, + }); + const drawWith = (parts) => (view) => { + if (!view) return; + for (const [name, element] of Object.entries(parts)) + view.actions.attach(name, element); + }; + const first = elements(); + const unsubscribe = viewer.subscribeView(drawWith(first)); + await viewer.mount(fakeHost()); + await viewer.open('a'); + assert.equal(renderers[0].canvas, first.canvas); + // Another view takes over, with elements of its own. + const second = elements(); + const resubscribe = viewer.subscribeView(drawWith(second)); + unsubscribe(); + assert.ok(await until(() => renderers[1]?.images.length > 0)); + assert.deepEqual(reopened, ['a']); + assert.equal(renderers[0].destroyed, true); + assert.equal(renderers[1].canvas, second.canvas); + assert.deepEqual(renderers[1].images, ['a-first']); + viewer.unmount(); + resubscribe(); +}); + test('the shared fake view draws only the later of two mounts, as the app does', async () => { const one = setup(); const two = setup(); @@ -727,3 +812,19 @@ test('the shared fake view draws only the later of two mounts, as the app does', await assert.rejects(one.viewer.open('f'), /not mounted/, 'superseded'); two.viewer.unmount(); }); + +test('a viewer left by an earlier test is not superseded by a later test’s', async () => { + const earlier = setup(); + await earlier.viewer.mount(earlier.host); + // As before each test. + resetPhotoView(); + const later = setup(); + await later.viewer.mount(later.host); + await tick(); + const opening = earlier.viewer.open('f'); + await until(() => earlier.loads.includes('f-first')); + earlier.release('f-first'); + await opening; + earlier.viewer.unmount(); + later.viewer.unmount(); +}); diff --git a/src/layers/streetLevel/photoViewers.js b/src/layers/streetLevel/photoViewers.js index bb1ddf404f..d8e0176a98 100644 --- a/src/layers/streetLevel/photoViewers.js +++ b/src/layers/streetLevel/photoViewers.js @@ -9,31 +9,40 @@ * Two fields of a presentation are read here (see ViewerAdapter.subscribeView * in registry.js): * - `mountKey`, a number larger for each later mount, orders the mounts. A - * presentation without one counts as the latest mount; among several - * without, the one that began presenting last is. + * presentation without one counts as mounted when it began presenting: + * after every mount presenting before it, before any later mount, keyed + * or not. * - `actions.supersede()`, where present, is called on each presentation - * not drawn once the pick changes. It runs on a microtask, after the - * presentation that won has reached every subscriber: a subscriber never - * sees the superseded one withdraw before it sees the one replacing it. + * not drawn, whenever more than one presents. It runs on a microtask, + * after the presentation that won has reached every subscriber: a + * subscriber never sees the superseded one withdraw before it sees the + * one replacing it. * @param {Iterable<{subscribeView?: Function}>} viewers * @param {(view: ?object) => void} listener * @returns {() => void} Unsubscribe. */ export function subscribePhotoViewers(viewers, listener) { - // Each viewer's current presentation, and when it began presenting. + // Each viewer's current presentation and its rank, {key, arrival}. const shown = new Map(); let arrivals = 0; + /** The largest mount key seen: a keyless mount ranks just after it. */ + let latestKey = -Infinity; let ready = false; let closed = false; let superseding = false; let last; /** Whether `a` was mounted after `b`. */ - const later = (a, b) => { - const key = ({ view }) => - Number.isFinite(view.mountKey) ? view.mountKey : Infinity; - const ka = key(a); - const kb = key(b); - return ka !== kb ? ka > kb : a.arrival > b.arrival; + const later = (a, b) => + a.key !== b.key ? a.key > b.key : a.arrival > b.arrival; + /** A new mount's rank: its key, or, without one, the latest key seen. */ + const rank = (view) => { + const keyed = Number.isFinite(view.mountKey); + if (keyed) latestKey = Math.max(latestKey, view.mountKey); + return { + key: keyed ? view.mountKey : latestKey, + // A keyed mount comes before a keyless one ranked on its key. + arrival: keyed ? 0 : ++arrivals, + }; }; // The others are not drawn: a mount still waiting on the view never // would be. @@ -48,10 +57,12 @@ export function subscribePhotoViewers(viewers, listener) { for (const entry of shown.values()) if (!next || later(entry, next)) next = entry; next = next?.view ?? null; - if (!ready || next === last) return; - last = next; - listener(next); - if (next && shown.size > 1 && !superseding) { + if (!ready) return; + if (next !== last) { + last = next; + listener(next); + } + if (last && shown.size > 1 && !superseding) { superseding = true; queueMicrotask(supersede); } @@ -64,7 +75,7 @@ export function subscribePhotoViewers(viewers, listener) { if (!view) shown.delete(viewer); else if (entry && entry.view.mountKey === view.mountKey) entry.view = view; - else shown.set(viewer, { view, arrival: ++arrivals }); + else shown.set(viewer, { view, ...rank(view) }); publish(); }); if (typeof unsubscribe === 'function') unsubscribes.push(unsubscribe); diff --git a/src/layers/streetLevel/photoViewers.test.mjs b/src/layers/streetLevel/photoViewers.test.mjs index f9b3f609d6..b27e315b78 100644 --- a/src/layers/streetLevel/photoViewers.test.mjs +++ b/src/layers/streetLevel/photoViewers.test.mjs @@ -1,5 +1,6 @@ import assert from 'node:assert/strict'; import test from 'node:test'; +import { createPhotoViewer } from './photoViewer.js'; import { subscribePhotoViewers } from './photoViewers.js'; /** @@ -92,7 +93,7 @@ test('every subscriber sees the earlier mount, then the later one, with no gap', for (const unsubscribe of unsubscribes) unsubscribe(); }); -test('a presentation without a mount key counts as the latest mount', () => { +test('a presentation without a mount key counts as mounted when it began presenting', async () => { const a = fakeViewer(); const b = fakeViewer(); const c = fakeViewer(); @@ -101,18 +102,72 @@ test('a presentation without a mount key counts as the latest mount', () => { shown.push(view), ); a.present(a.view(5)); - const keyless = { actions: {} }; + const keyless = b.view(undefined); b.present(keyless); assert.equal(shown.at(-1), keyless, 'after the keyed one'); - // A keyed mount presenting later does not take it back. - a.present(a.view(6)); - assert.equal(shown.at(-1), keyless); // Of two without, the one that began presenting last. - const newer = { actions: {} }; + const newer = c.view(undefined); c.present(newer); assert.equal(shown.at(-1), newer); b.present({ ...keyless, kind: 'flat' }); assert.equal(shown.at(-1), newer, 'presenting again is not a new mount'); + // A keyed mount made after them wins. + const latest = a.view(6); + a.present(latest); + assert.equal(shown.at(-1), latest); + await Promise.resolve(); + assert.ok(b.superseded > 0 && c.superseded > 0, 'the keyless ones are told'); + unsubscribe(); +}); + +test('a presentation that is not drawn is superseded even when the pick stays', async () => { + const a = fakeViewer(); + const b = fakeViewer(); + const shown = []; + const unsubscribe = subscribePhotoViewers([a, b], (view) => shown.push(view)); + const later = b.view(2); + b.present(later); + // An earlier mount presents once the later one is drawn. + a.present(a.view(1)); + assert.deepEqual(shown, [null, later]); + await Promise.resolve(); + assert.equal(a.superseded, 1); + unsubscribe(); +}); + +test('a photo viewer mounting while a keyless presentation shows is drawn, and the keyless one superseded', async () => { + let superseded = 0; + const keyless = { + subscribeView(listener) { + listener({ actions: { supersede: () => superseded++ } }); + return () => {}; + }, + }; + const viewer = createPhotoViewer({ + providerId: 'test', + name: 'Test', + sources: {}, + getPhoto: async () => null, + step: async () => null, + onStep() {}, + }); + const shown = []; + const element = { clientWidth: 400, clientHeight: 250 }; + const unsubscribe = subscribePhotoViewers([keyless, viewer], (view) => { + shown.push(view); + if (!view?.mountKey) return; + for (const name of ['root', 'picture', 'canvas', 'prev', 'next']) + view.actions.attach(name, element); + }); + const mounting = viewer.mount({}); + const outcome = await Promise.race([ + mounting.then(() => 'mounted'), + new Promise((resolve) => setTimeout(() => resolve('pending'), 50)), + ]); + assert.equal(outcome, 'mounted'); + assert.ok(Number.isFinite(shown.at(-1)?.mountKey), 'the mount is drawn'); + assert.ok(superseded >= 1, 'the keyless one is told'); + viewer.unmount(); unsubscribe(); }); diff --git a/src/layers/streetLevel/providers/kartaview/provider.test.mjs b/src/layers/streetLevel/providers/kartaview/provider.test.mjs index caf1cd3aef..bb8b167022 100644 --- a/src/layers/streetLevel/providers/kartaview/provider.test.mjs +++ b/src/layers/streetLevel/providers/kartaview/provider.test.mjs @@ -17,6 +17,7 @@ import { drawn, fakeHost, until, + resetPhotoView, } from '../../../../testSupport/kartaViewFakes.mjs'; import { bindStreetViewer, @@ -26,6 +27,9 @@ import { } from '../../../../testSupport/streetLevelFakes.mjs'; import { fakeDrawPort } from '../../../../testSupport/fakeDrawPort.mjs'; +// Each test draws its own viewers only. +test.beforeEach(resetPhotoView); + /** A photo record `metres` east of (42.3314, -83.0458), in sequence `seq` at `index`. */ function photoRecord(id, { metres = 0, seq = '14010', index = 0 } = {}) { const lon = -83.0458 + metres / 82_300; diff --git a/src/layers/streetLevel/providers/kartaview/viewer.test.mjs b/src/layers/streetLevel/providers/kartaview/viewer.test.mjs index 9c6218d52c..05dabd27a0 100644 --- a/src/layers/streetLevel/providers/kartaview/viewer.test.mjs +++ b/src/layers/streetLevel/providers/kartaview/viewer.test.mjs @@ -5,8 +5,12 @@ import { drawn, fakeHost, until, + resetPhotoView, } from '../../../../testSupport/kartaViewFakes.mjs'; +// Each test draws its own viewers only. +test.beforeEach(resetPhotoView); + const PHOTOS = { flat1: { id: 'flat1', diff --git a/src/layers/streetLevel/providers/panoramax/provider.test.mjs b/src/layers/streetLevel/providers/panoramax/provider.test.mjs index f26be6d023..99e3a92d77 100644 --- a/src/layers/streetLevel/providers/panoramax/provider.test.mjs +++ b/src/layers/streetLevel/providers/panoramax/provider.test.mjs @@ -18,6 +18,7 @@ import { drawn, fakeHost, until, + resetPhotoView, } from '../../../../testSupport/kartaViewFakes.mjs'; import { bindStreetViewer, @@ -31,6 +32,9 @@ import { stacItem, } from '../../../../testSupport/panoramaxFixtures.mjs'; +// Each test draws its own viewers only. +test.beforeEach(resetPhotoView); + const ORIGIN = { lon: 2.3495, lat: 48.8874 }; /** A point `metres` east of ORIGIN. */ const east = (metres) => ({ diff --git a/src/layers/streetLevel/providers/panoramax/viewer.test.mjs b/src/layers/streetLevel/providers/panoramax/viewer.test.mjs index 185e9eeb21..ddd97fcc20 100644 --- a/src/layers/streetLevel/providers/panoramax/viewer.test.mjs +++ b/src/layers/streetLevel/providers/panoramax/viewer.test.mjs @@ -2,9 +2,16 @@ import assert from 'node:assert/strict'; import test from 'node:test'; import { PANORAMAX_SOURCES, createPanoramaxViewer } from './viewer.js'; import { normalizeItem } from './policy.js'; -import { fakeHost, until } from '../../../../testSupport/kartaViewFakes.mjs'; +import { + fakeHost, + until, + resetPhotoView, +} from '../../../../testSupport/kartaViewFakes.mjs'; import { stacItem } from '../../../../testSupport/panoramaxFixtures.mjs'; +// Each test draws its own viewers only. +test.beforeEach(resetPhotoView); + const photo = (options) => normalizeItem(stacItem({ lon: 2.35, lat: 48.85, ...options })); diff --git a/src/layers/streetLevel/registry.js b/src/layers/streetLevel/registry.js index 177028d570..b332b61355 100644 --- a/src/layers/streetLevel/registry.js +++ b/src/layers/streetLevel/registry.js @@ -69,10 +69,10 @@ export function filtersOf(provider) { * presentation at once, then each new one, null while unmounted. One view * draws one viewer (photoViewers.js picks it), reading two fields: * `mountKey`, a number larger for each later mount (the later mount is - * drawn; a presentation without one counts as the latest), and - * `actions.supersede()`, called on a mount that is not drawn because a - * later one is (it should unmount, failing a mount still waiting to be - * drawn; an adapter without it is simply not drawn). + * drawn; a presentation without one counts as mounted when it began + * presenting), and `actions.supersede()`, called on a mount that is not + * drawn because a later one is (it should unmount, failing a mount still + * waiting to be drawn; an adapter without it is simply not drawn). * * @typedef {object} StreetPose * @property {string} providerId diff --git a/src/testSupport/kartaViewFakes.mjs b/src/testSupport/kartaViewFakes.mjs index c4b5ba5cce..5849e8f7d2 100644 --- a/src/testSupport/kartaViewFakes.mjs +++ b/src/testSupport/kartaViewFakes.mjs @@ -95,9 +95,22 @@ function resubscribe() { previous?.(); } +/** + * Start the shared view afresh, with no viewer: a test file calls it before + * each test, so a viewer left by an earlier test is not drawn with a later + * test's (nor superseded by it). A viewer it held is left without a view. + */ +export function resetPhotoView() { + shared.generation++; + shared.unsubscribe?.(); + shared.unsubscribe = null; + shared.viewers.clear(); + shared.draw = null; +} + /** * Draw a photo viewer with the shared view, alongside every other viewer - * given here (see `shared`). + * given here since the last `resetPhotoView()` (see `shared`). * @returns {() => void} Stop drawing it. */ export function drawPhotoViewer(viewer) { diff --git a/src/ui/kit/streetLevelPhotoControls.test.mjs b/src/ui/kit/streetLevelPhotoControls.test.mjs index 5f20b03faf..f30f86c6c7 100644 --- a/src/ui/kit/streetLevelPhotoControls.test.mjs +++ b/src/ui/kit/streetLevelPhotoControls.test.mjs @@ -101,11 +101,38 @@ test('the photo viewer is drawn by its view, and its layer needs no Vue', () => /from 'vue'|\.vue'/, ]) assert.doesNotMatch(source, write); - assert.doesNotMatch(rest, /\.src\s*=[^=]/, 'a .src written on the page'); - // In loadImage, only on the off-page Image it creates. + // No property written through brackets (`picture['src'] = …`, + // `el[name] = …`), outside array destructuring declarations. + assert.doesNotMatch( + source.replace(/\b(?:const|let|var)\s*\[/g, ''), + /[\w$)\]]\s*\[[^[\]]*\]\s*=(?![=>])/, + 'a bracket write', + ); + const SRC = /\.src\s*=(?![=>])/g; + assert.doesNotMatch(rest, SRC, 'a .src written on the page'); + // In loadImage, only on the off-page Image it creates: `image` is bound + // once, to that Image, and never rebound or shadowed. assert.match(loader, /\bconst image = new Image\(\);/); - for (const [write] of loader.matchAll(/[\w$.\]]+\.src\s*=(?!=)/g)) - assert.match(write, /^image\.src\s*=$/, write); + assert.equal( + loader.match(/\b(?:const|let|var|function|class)\s+image\b/g)?.length, + 1, + 'one binding of image', + ); + for (const rebinding of [ + /(?])/, + /(?/, + /\((?:[^()]*[,{[\s(])?image\b[^()]*\)\s*=>/, + /\bfunction\b[^(]*\((?:[^)]*[,{[\s(])?image\b[^)]*\)/, + /\b(?:const|let|var)\s*[{[][^=]*\bimage\b/, + /\bcatch\s*\(\s*image\b/, + ]) + assert.doesNotMatch(loader, rebinding, 'image rebound or shadowed'); + const writes = loader.match(SRC)?.length ?? 0; + assert.equal( + loader.match(/(?])/g)?.length ?? 0, + writes, + 'a .src written on something other than the Image', + ); const markup = template(VIEW); const opening = (name, attribute) => new RegExp(String.raw`<${name}\b${ATTRS}\s${attribute}${ATTRS}>`); From 22485dcb01d3328e9f7f2dcecdd4f72af93d895b Mon Sep 17 00:00:00 2001 From: Sameh Khamis Date: Thu, 19 Nov 2026 16:23:42 -0800 Subject: [PATCH 15/17] Street Level photo viewer: a failed mount spares the next, stable keyless ranks MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Second review follow-ups: - A mount woken without being drawn unmounts only its own presentation: an earlier mount overtaken by a second mount of the same viewer fails as closed and leaves the second one mounted and presented. - A mount whose last view left fails only if no view has subscribed since; one subscribed in the same tick draws it. - Mount keys come from photoViewers.js's nextViewKey(), and a keyless presentation is stamped from the same counter when any picker first sees it, kept until it presents null: its rank no longer depends on the picker's lifetime or the order it subscribes in. - A canvas handed back while a panorama's open waits on its draw takes the panorama: the open builds its renderer there instead of falling back to the front view. A canvas the panorama moved off is not moved back to, so two views drawing their own cannot take it in turns. - The guard test also refuses compound writes (+=, ||=, ??=, &&=…), destructuring writes to properties, Object.assign (other than onto a new Error), Object.defineProperty and Reflect.set, and a catch binding that shadows loadImage's image. Nothing changes in the running app. Co-authored-by: Manjunath Paparaju --- src/layers/streetLevel/photoViewer.js | 68 +++++++--- src/layers/streetLevel/photoViewer.test.mjs | 126 +++++++++++++++++++ src/layers/streetLevel/photoViewers.js | 64 ++++++---- src/layers/streetLevel/photoViewers.test.mjs | 35 +++++- src/ui/kit/streetLevelPhotoControls.test.mjs | 39 ++++-- 5 files changed, 275 insertions(+), 57 deletions(-) diff --git a/src/layers/streetLevel/photoViewer.js b/src/layers/streetLevel/photoViewer.js index e2d8d14e29..8a6f2a97de 100644 --- a/src/layers/streetLevel/photoViewer.js +++ b/src/layers/streetLevel/photoViewer.js @@ -4,8 +4,14 @@ import { wrapDegrees, } from './panorama.js'; import { imageSize } from './imageSize.js'; +import { nextViewKey } from './photoViewers.js'; import { msg, t } from '../../i18n/index.js'; +// Each mount's and each canvas's key comes from `nextViewKey()`, never +// reused by any viewer: a view that sees one viewer unmount and another +// mount in the same tick still draws them fresh elements (a destroyed +// renderer leaves its canvas's context lost). + /** * EXPAND puts the viewer's wrap full screen, or (iPhone) opens it as a * popover. Each is tried on its own: a browser that cannot parse one @@ -36,14 +42,6 @@ function tooManyPixels(width, height) { ); } -/** - * Keys for each mount's and each canvas's elements, never reused by any - * viewer: a view that sees one viewer unmount and another mount in the same - * tick still draws them fresh elements (a destroyed renderer leaves its - * canvas's context lost). - */ -let viewKeys = 0; - /** Panorama texture widths: enough for a docked viewer, and for an expanded one. */ const PANO_MID_SIZE = Object.freeze([2048, 1024]); export const PANO_FULL_SIZE = Object.freeze([4096, 2048]); @@ -301,6 +299,13 @@ export function createPhotoViewer({ const canvasWaiters = new Set(); /** How many times the view has handed the canvas back (once per draw). */ let canvasDraws = 0; + /** + * Canvases the panorama moved off: one handed back again (a second view + * drawing its own) is not moved back to, so two views cannot take turns. + */ + const retiredCanvases = new WeakSet(); + /** The canvas moved while an open waited on its draw. */ + let canvasMoved = false; let renderer = null; /** WebGL failed once: 360° photos show their front view instead. */ let rendererFailed = false; @@ -496,7 +501,7 @@ export function createPhotoViewer({ // A lost canvas hands back its lost context: the view draws a new // element in its place and hands it back. canvas = null; - present({ canvasKey: ++viewKeys }); + present({ canvasKey: nextViewKey() }); reopen(); } @@ -507,8 +512,11 @@ export function createPhotoViewer({ */ function moveCanvas(element) { dropRenderer(); + retiredCanvases.add(canvas); canvas = element; - reopen(); + // An open waiting on the draw goes on, on the new canvas. + if (openingId !== null) canvasMoved = true; + else reopen(); } /** Let the renderer go, keeping the user's look for the photo's reopen. */ @@ -708,6 +716,7 @@ export function createPhotoViewer({ const actions = { attach(name, element) { if (presented?.actions !== actions || !element) return; + if (name === 'canvas' && retiredCanvases.has(element)) return; if (name === 'canvas' && renderer && canvas && element !== canvas) moveCanvas(element); else ELEMENTS[name]?.(element); @@ -731,7 +740,7 @@ export function createPhotoViewer({ }; presented = { host, - mountKey: ++viewKeys, + mountKey: nextViewKey(), providerId, label: t( '{name} photo. ← and → step along the sequence. On a 360° photo, drag or use Shift+← →, ↑ ↓ to look around, and + − to zoom', @@ -741,7 +750,7 @@ export function createPhotoViewer({ kind: undefined, src: null, fit: renderMode === 'fill' ? 'cover' : 'contain', - canvasKey: ++viewKeys, + canvasKey: nextViewKey(), dragging: false, prevLabel: t('Previous photo in this sequence (←)'), prevDisabled: true, @@ -916,8 +925,16 @@ export function createPhotoViewer({ // view draws it shown, at once or on a microtask, and hands the canvas // back then. const draws = canvasDraws; + canvasMoved = false; show('pano'); await drawnAfter(draws, signal); + // The view drew it on another canvas: the panorama goes there. + if (canvasMoved && seq === openSeq && !renderer && ensureRenderer()) { + const moved = restoreView?.id === target.id ? restoreView.view : null; + restoreView = null; + if (moved) renderer.setView(moved); + } + canvasMoved = false; // The last view left before drawing it: the canvas was never shown, and // nothing is drawn until a view is back. if (seq === openSeq && canvasDraws === draws && !viewListeners.size) { @@ -998,14 +1015,27 @@ export function createPhotoViewer({ throw new Error('Street Level photo viewer has no view to draw it'); // Resolves once the view drew the viewer, or it was unmounted, or its // last view left, meanwhile. - const drawn = new Promise((resolve) => rootWaiters.add(resolve)); + const waitRoot = () => new Promise((resolve) => rootWaiters.add(resolve)); + let drawn = waitRoot(); build(host); - if (!root) await drawn; - if (root) return; - // The last view left before drawing it: no view will. Unmounted, as - // when superseded, so a view subscribing later draws nothing. - if (presented) adapter.unmount(); - throw undrawn(); + // This mount's presentation: a later mount presents its own. + const mine = presented.actions; + for (;;) { + if (!root) await drawn; + const current = presented?.actions === mine; + if (root && current) return; + // Unmounted, superseded or mounted again: that is not this mount. + if (!current) throw undrawn(); + // Its last view left, and another subscribed since: it draws. + if (viewListeners.size) { + drawn = waitRoot(); + continue; + } + // No view will draw it. Unmounted, as when superseded, so a view + // subscribing later draws nothing. + adapter.unmount(); + throw undrawn(); + } }, /** Resolves once the photo is on screen and its pose was emitted. */ diff --git a/src/layers/streetLevel/photoViewer.test.mjs b/src/layers/streetLevel/photoViewer.test.mjs index ac3e252885..370ae53986 100644 --- a/src/layers/streetLevel/photoViewer.test.mjs +++ b/src/layers/streetLevel/photoViewer.test.mjs @@ -828,3 +828,129 @@ test('a viewer left by an earlier test is not superseded by a later test’s', a earlier.viewer.unmount(); later.viewer.unmount(); }); + +/** A panorama viewer whose renderers and flat loads the test reads. */ +function trackedViewer(options = {}) { + const renderers = []; + const loads = []; + const viewer = createPhotoViewer({ + providerId: 'test', + name: 'Test', + sources: SOURCES, + getPhoto: async (id) => PHOTOS[id], + step: async () => null, + onStep() {}, + load: async (url) => { + loads.push(url); + return { src: url }; + }, + createRenderer: (canvas) => { + const renderer = { + canvas, + images: [], + setImage: (image) => renderer.images.push(image.src), + setView() {}, + getView: () => ({ yaw: 0, pitch: 0, fov: 80 }), + resize() {}, + clear() {}, + destroy() {}, + }; + renderers.push(renderer); + return renderer; + }, + ...options, + }); + return { viewer, renderers, loads }; +} + +/** Hand `parts` back to the viewer that presented `view`. */ +const attachAll = (view, parts) => { + for (const [name, element] of Object.entries(parts)) + view.actions.attach(name, element); +}; + +test('a mount overtaken by a second mount of the same viewer closes, and the second stays', async () => { + const { viewer } = trackedViewer(); + let latest = null; + const unsubscribe = viewer.subscribeView((view) => (latest = view)); + const first = viewer.mount({ id: 1 }); + const hostTwo = { id: 2 }; + const second = viewer.mount(hostTwo); + // The view draws on a later macrotask. + setTimeout(() => latest && attachAll(latest, elements()), 0); + await assert.rejects(first, /viewer was closed/); + await second; + assert.equal(latest?.host, hostTwo, 'the second mount is presented'); + viewer.unmount(); + unsubscribe(); +}); + +test('a mount whose view subscribes again in the same tick is drawn', async () => { + const { viewer } = trackedViewer(); + let latest = null; + const view = (next) => (latest = next); + let unsubscribe = viewer.subscribeView(view); + const mounting = viewer.mount({}); + // The view is replaced at once, and draws on a later macrotask. + unsubscribe(); + unsubscribe = viewer.subscribeView(view); + setTimeout(() => latest && attachAll(latest, elements()), 0); + await mounting; + assert.ok(latest, 'still presented'); + viewer.unmount(); + unsubscribe(); +}); + +test('a canvas handed back while a panorama’s open waits on its draw takes the panorama', async () => { + const { viewer, renderers, loads } = trackedViewer(); + const first = elements(); + const second = elements(); + let latest = null; + let hold = false; + const unsubscribe = viewer.subscribeView((view) => { + latest = view; + if (view && !hold) attachAll(view, first); + }); + await viewer.mount({}); + hold = true; + const opening = viewer.open('a'); + assert.ok(await until(() => latest?.kind === 'pano'), 'waiting on a draw'); + // The view draws it with a canvas of its own. + attachAll(latest, second); + await opening; + assert.equal(latest.kind, 'pano', 'not the front view'); + assert.deepEqual(loads, ['a-first'], 'no flat version loaded'); + assert.equal(renderers.at(-1).canvas, second.canvas); + assert.deepEqual(renderers.at(-1).images, ['a-first']); + viewer.unmount(); + unsubscribe(); +}); + +test('two views handing back canvases of their own do not take the panorama in turns', async () => { + let reopened = 0; + const { viewer, renderers } = trackedViewer({ + onReopen: (id) => { + reopened++; + if (reopened < 20) viewer.open(id).catch(() => {}); + }, + }); + const one = elements(); + const two = elements(); + const unsubscribes = [ + viewer.subscribeView((view) => view && attachAll(view, one)), + viewer.subscribeView((view) => view && attachAll(view, two)), + ]; + await viewer.mount({}); + await viewer.open('a'); + const built = renderers.length; + // Each presentation is drawn by both views. + for (const mode of ['fill', 'letterbox', 'fill']) { + viewer.setRenderMode(mode); + for (let i = 0; i < 5; i++) await tick(); + } + assert.equal(reopened, 0); + assert.equal(renderers.length, built, 'the panorama stays where it is'); + assert.deepEqual(renderers.at(-1).images, ['a-first']); + viewer.unmount(); + for (const unsubscribe of unsubscribes) unsubscribe(); +}); diff --git a/src/layers/streetLevel/photoViewers.js b/src/layers/streetLevel/photoViewers.js index d8e0176a98..ed32dd5208 100644 --- a/src/layers/streetLevel/photoViewers.js +++ b/src/layers/streetLevel/photoViewers.js @@ -1,3 +1,22 @@ +/** The last key handed out by `nextViewKey()`. */ +let viewKeys = 0; + +/** + * A key no viewer or picker was ever given: photo viewers key their mounts + * and canvases with it, and a presentation without a mount key is stamped + * with one when first seen, so both rank on one scale. + */ +export function nextViewKey() { + return ++viewKeys; +} + +/** + * Each keyless viewer's current mount, `{actions, key}`: stamped once, by + * whichever picker sees it first, and kept until it presents null, so a + * picker made later ranks it the same. + */ +const keylessMounts = new WeakMap(); + /** * Receive the photo viewer to draw, out of several photo viewers mounting * in one host (see photoViewer.js): the one mounted last, whatever order @@ -8,10 +27,10 @@ * * Two fields of a presentation are read here (see ViewerAdapter.subscribeView * in registry.js): - * - `mountKey`, a number larger for each later mount, orders the mounts. A - * presentation without one counts as mounted when it began presenting: - * after every mount presenting before it, before any later mount, keyed - * or not. + * - `mountKey`, a number larger for each later mount (from `nextViewKey()`), + * orders the mounts. A presentation without one counts as mounted when + * any picker first saw it present: it is stamped with a `nextViewKey()` + * then, the same for every picker, however many are made later. * - `actions.supersede()`, where present, is called on each presentation * not drawn, whenever more than one presents. It runs on a microtask, * after the presentation that won has reached every subscriber: a @@ -22,27 +41,21 @@ * @returns {() => void} Unsubscribe. */ export function subscribePhotoViewers(viewers, listener) { - // Each viewer's current presentation and its rank, {key, arrival}. + // Each viewer's current presentation and its rank, {view, key}. const shown = new Map(); - let arrivals = 0; - /** The largest mount key seen: a keyless mount ranks just after it. */ - let latestKey = -Infinity; let ready = false; let closed = false; let superseding = false; let last; - /** Whether `a` was mounted after `b`. */ - const later = (a, b) => - a.key !== b.key ? a.key > b.key : a.arrival > b.arrival; - /** A new mount's rank: its key, or, without one, the latest key seen. */ - const rank = (view) => { - const keyed = Number.isFinite(view.mountKey); - if (keyed) latestKey = Math.max(latestKey, view.mountKey); - return { - key: keyed ? view.mountKey : latestKey, - // A keyed mount comes before a keyless one ranked on its key. - arrival: keyed ? 0 : ++arrivals, - }; + /** A mount's rank: its key, or the stamp of its first presentation. */ + const rank = (viewer, view) => { + if (Number.isFinite(view.mountKey)) return view.mountKey; + let mount = keylessMounts.get(viewer); + if (!mount || mount.actions !== view.actions) { + mount = { actions: view.actions, key: nextViewKey() }; + keylessMounts.set(viewer, mount); + } + return mount.key; }; // The others are not drawn: a mount still waiting on the view never // would be. @@ -55,7 +68,7 @@ export function subscribePhotoViewers(viewers, listener) { const publish = () => { let next = null; for (const entry of shown.values()) - if (!next || later(entry, next)) next = entry; + if (!next || entry.key > next.key) next = entry; next = next?.view ?? null; if (!ready) return; if (next !== last) { @@ -71,11 +84,10 @@ export function subscribePhotoViewers(viewers, listener) { for (const viewer of viewers) { const unsubscribe = viewer?.subscribeView?.((view) => { if (closed) return; - const entry = shown.get(viewer); - if (!view) shown.delete(viewer); - else if (entry && entry.view.mountKey === view.mountKey) - entry.view = view; - else shown.set(viewer, { view, ...rank(view) }); + if (!view) { + shown.delete(viewer); + keylessMounts.delete(viewer); + } else shown.set(viewer, { view, key: rank(viewer, view) }); publish(); }); if (typeof unsubscribe === 'function') unsubscribes.push(unsubscribe); diff --git a/src/layers/streetLevel/photoViewers.test.mjs b/src/layers/streetLevel/photoViewers.test.mjs index b27e315b78..aa56b6b316 100644 --- a/src/layers/streetLevel/photoViewers.test.mjs +++ b/src/layers/streetLevel/photoViewers.test.mjs @@ -1,7 +1,7 @@ import assert from 'node:assert/strict'; import test from 'node:test'; import { createPhotoViewer } from './photoViewer.js'; -import { subscribePhotoViewers } from './photoViewers.js'; +import { nextViewKey, subscribePhotoViewers } from './photoViewers.js'; /** * A photo viewer whose presentations the test sends; `superseded` counts. @@ -10,6 +10,7 @@ import { subscribePhotoViewers } from './photoViewers.js'; */ function fakeViewer() { const listeners = new Set(); + let current = null; const viewer = { superseded: 0, view(mountKey) { @@ -19,11 +20,12 @@ function fakeViewer() { }; }, present(view) { + current = view; for (const listener of [...listeners]) listener(view); }, subscribeView(listener) { listeners.add(listener); - listener(null); + listener(current); return () => listeners.delete(listener); }, }; @@ -101,7 +103,7 @@ test('a presentation without a mount key counts as mounted when it began present const unsubscribe = subscribePhotoViewers([a, b, c], (view) => shown.push(view), ); - a.present(a.view(5)); + a.present(a.view(nextViewKey())); const keyless = b.view(undefined); b.present(keyless); assert.equal(shown.at(-1), keyless, 'after the keyed one'); @@ -112,7 +114,7 @@ test('a presentation without a mount key counts as mounted when it began present b.present({ ...keyless, kind: 'flat' }); assert.equal(shown.at(-1), newer, 'presenting again is not a new mount'); // A keyed mount made after them wins. - const latest = a.view(6); + const latest = a.view(nextViewKey()); a.present(latest); assert.equal(shown.at(-1), latest); await Promise.resolve(); @@ -186,3 +188,28 @@ test('a presentation without actions or supersede is drawn and passed over witho assert.equal(shown.at(-1).mountKey, 3); unsubscribe(); }); + +test('a keyless viewer on screen keeps its place when the picker is made again', async () => { + const keyed = fakeViewer(); + const keyless = fakeViewer(); + keyed.present(keyed.view(nextViewKey())); + const shown = []; + let unsubscribe = subscribePhotoViewers([keyless, keyed], (view) => + shown.push(view), + ); + const mounted = keyless.view(undefined); + keyless.present(mounted); + assert.equal(shown.at(-1), mounted); + await Promise.resolve(); + unsubscribe(); + // A new picker, the keyless viewer first: it is still the later mount. + const again = []; + unsubscribe = subscribePhotoViewers([keyless, keyed], (view) => + again.push(view), + ); + assert.equal(again.at(-1), mounted); + await Promise.resolve(); + assert.equal(keyless.superseded, 0, 'never told it is not drawn'); + assert.ok(keyed.superseded > 0); + unsubscribe(); +}); diff --git a/src/ui/kit/streetLevelPhotoControls.test.mjs b/src/ui/kit/streetLevelPhotoControls.test.mjs index f30f86c6c7..1c65279af4 100644 --- a/src/ui/kit/streetLevelPhotoControls.test.mjs +++ b/src/ui/kit/streetLevelPhotoControls.test.mjs @@ -79,6 +79,13 @@ test('the step buttons are not pressed toggles', () => { * the page: the one place a `.src` is written. */ const LOADER = /^export function loadImage\([\s\S]*?^}$/m; +// An assignment, plain or compound (`=`, `+=`, `||=`, `??=`, `**=`…), not +// a comparison or an arrow. +const ASSIGN = String.raw`\s*(?:[-+*/%&|^]|\*\*|<<|>>>?|&&|\|\||\?\?)?=(?![=>])`; +const assigned = (target, flags = '') => + new RegExp(String.raw`${target}${ASSIGN}`, flags); +// A member or computed member: what a destructuring write must not target. +const MEMBER = /[\w$)\]]\s*(?:\.\s*[\w$]|\[)/; test('the photo viewer is drawn by its view, and its layer needs no Vue', () => { const source = read(VIEWER); @@ -96,19 +103,34 @@ test('the photo viewer is drawn by its view, and its layer needs no Vue', () => /\.remove\(\)/, /\.(?:set|remove|toggle)Attribute(?:NS)?\(/, /\.(?:classList|className|dataset|style)\b/, - /\.(?:hidden|disabled|textContent|innerText|tabIndex|title|alt)\s*=[^=]/, - /\.(?:width|height|ariaLabel|id|value)\s*=[^=]/, + assigned( + String.raw`\.(?:hidden|disabled|textContent|innerText|tabIndex|title|alt)`, + ), + assigned(String.raw`\.(?:width|height|ariaLabel|id|value)`), + // Properties written in bulk or by reflection (an Error's own fields + // aside). + /\bObject\.assign\(\s*(?!new Error\()/, + /\bObject\.definePropert(?:y|ies)\(/, + /\bReflect\.(?:set|defineProperty)\(/, /from 'vue'|\.vue'/, ]) assert.doesNotMatch(source, write); // No property written through brackets (`picture['src'] = …`, - // `el[name] = …`), outside array destructuring declarations. + // `el[name] ||= …`), outside array destructuring declarations. assert.doesNotMatch( source.replace(/\b(?:const|let|var)\s*\[/g, ''), - /[\w$)\]]\s*\[[^[\]]*\]\s*=(?![=>])/, + assigned(String.raw`[\w$)\]]\s*\[[^[\]]*\]`), 'a bracket write', ); - const SRC = /\.src\s*=(?![=>])/g; + // No destructuring write to a property (`[el.src] = …`, + // `({ a: el.id } = …)`); declarations bind names only. + for (const pattern of [ + /(?])/g, + /(?])/g, + ]) + for (const [write, targets] of source.matchAll(pattern)) + assert.doesNotMatch(targets, MEMBER, write); + const SRC = assigned(String.raw`\.src`, 'g'); assert.doesNotMatch(rest, SRC, 'a .src written on the page'); // In loadImage, only on the off-page Image it creates: `image` is bound // once, to that Image, and never rebound or shadowed. @@ -119,17 +141,18 @@ test('the photo viewer is drawn by its view, and its layer needs no Vue', () => 'one binding of image', ); for (const rebinding of [ - /(?])/, + assigned(String.raw`(?/, /\((?:[^()]*[,{[\s(])?image\b[^()]*\)\s*=>/, /\bfunction\b[^(]*\((?:[^)]*[,{[\s(])?image\b[^)]*\)/, /\b(?:const|let|var)\s*[{[][^=]*\bimage\b/, - /\bcatch\s*\(\s*image\b/, + /\bcatch\s*\([^)]*\bimage\b/, ]) assert.doesNotMatch(loader, rebinding, 'image rebound or shadowed'); const writes = loader.match(SRC)?.length ?? 0; assert.equal( - loader.match(/(?])/g)?.length ?? 0, + loader.match(assigned(String.raw`(? Date: Thu, 19 Nov 2026 16:31:34 -0800 Subject: [PATCH 16/17] Street Level photo viewer: take a moved-off canvas back, and close a mount unmounted in its first draw MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A canvas the panorama moved off (a second view drew its own) is no longer ignored for good: its draws are counted, so an open waiting on one goes on, and once a single view is left its canvas is taken back. Before, after the second view left, the next 360° open waited forever and the panorama stayed on the departed view's canvas. A mount whose view unmounts it inside its first draw now fails as closed, as every other unmounted mount does, rather than with a TypeError. Both found in review; each new test fails without its fix. Co-authored-by: Manjunath Paparaju --- src/layers/streetLevel/photoViewer.js | 35 ++++++++++++----- src/layers/streetLevel/photoViewer.test.mjs | 42 +++++++++++++++++++++ 2 files changed, 68 insertions(+), 9 deletions(-) diff --git a/src/layers/streetLevel/photoViewer.js b/src/layers/streetLevel/photoViewer.js index 8a6f2a97de..509ee48c75 100644 --- a/src/layers/streetLevel/photoViewer.js +++ b/src/layers/streetLevel/photoViewer.js @@ -247,7 +247,9 @@ export function panoSizeFor(canvasPixels, fovDeg) { * a panorama's open waiting on a draw when the last view leaves fails as * closed (the mount unmounts; the open leaves no photo shown). A view * handing back another canvas element than the renderer's (one subscribed - * since) gets the panorama drawn again on it, as after a lost context. + * since) gets the panorama drawn again on it, as after a lost context; + * while several views draw, a canvas the panorama moved off is not moved + * back to, and once one view is left its canvas is taken back. * * Photos are normalized by the provider: `{id, sequenceId, lon, lat, * heading, isPano, capturedAt}` plus whatever its `sources` read. @@ -300,10 +302,12 @@ export function createPhotoViewer({ /** How many times the view has handed the canvas back (once per draw). */ let canvasDraws = 0; /** - * Canvases the panorama moved off: one handed back again (a second view - * drawing its own) is not moved back to, so two views cannot take turns. + * Canvases the panorama moved off while more than one view draws: one + * handed back again (a second view drawing its own) is not moved back to, + * so two views cannot take turns. Forgotten once a single view is left, + * so its canvas is taken back. */ - const retiredCanvases = new WeakSet(); + let retiredCanvases = new WeakSet(); /** The canvas moved while an open waited on its draw. */ let canvasMoved = false; let renderer = null; @@ -716,8 +720,16 @@ export function createPhotoViewer({ const actions = { attach(name, element) { if (presented?.actions !== actions || !element) return; - if (name === 'canvas' && retiredCanvases.has(element)) return; - if (name === 'canvas' && renderer && canvas && element !== canvas) + const retired = name === 'canvas' && retiredCanvases.has(element); + if (retired) { + // Another view still draws the panorama: this draw is counted, so + // an open waiting on it goes on, but the panorama stays put. + } else if ( + name === 'canvas' && + renderer && + canvas && + element !== canvas + ) moveCanvas(element); else ELEMENTS[name]?.(element); if (name === 'root') wake(rootWaiters); @@ -1018,8 +1030,10 @@ export function createPhotoViewer({ const waitRoot = () => new Promise((resolve) => rootWaiters.add(resolve)); let drawn = waitRoot(); build(host); - // This mount's presentation: a later mount presents its own. - const mine = presented.actions; + // This mount's presentation: a later mount presents its own. A view + // may have unmounted it already, inside its first draw. + const mine = presented?.actions; + if (!mine) throw undrawn(); for (;;) { if (!root) await drawn; const current = presented?.actions === mine; @@ -1125,7 +1139,10 @@ export function createPhotoViewer({ return () => { // The last view went: a mount or an open waiting on its draw fails // as closed. - if (viewListeners.delete(listener) && !viewListeners.size) { + if (!viewListeners.delete(listener)) return; + // One view left: the canvases moved off are its to hand back again. + if (viewListeners.size <= 1) retiredCanvases = new WeakSet(); + if (!viewListeners.size) { wake(rootWaiters); wake(canvasWaiters); } diff --git a/src/layers/streetLevel/photoViewer.test.mjs b/src/layers/streetLevel/photoViewer.test.mjs index 370ae53986..1f01117957 100644 --- a/src/layers/streetLevel/photoViewer.test.mjs +++ b/src/layers/streetLevel/photoViewer.test.mjs @@ -954,3 +954,45 @@ test('two views handing back canvases of their own do not take the panorama in t viewer.unmount(); for (const unsubscribe of unsubscribes) unsubscribe(); }); + +test('the panorama goes back to the one view left once a second view leaves', async () => { + const { viewer, renderers } = trackedViewer({ + onReopen: (id) => viewer.open(id).catch(() => {}), + }); + const one = elements(); + const two = elements(); + const unsubscribeOne = viewer.subscribeView( + (view) => view && attachAll(view, one), + ); + await viewer.mount({}); + await viewer.open('a'); + // A second view subscribes and draws its own canvas: the panorama moves. + const unsubscribeTwo = viewer.subscribeView( + (view) => view && attachAll(view, two), + ); + for (let i = 0; i < 5; i++) await tick(); + assert.equal(renderers.at(-1).canvas, two.canvas); + unsubscribeTwo(); + assert.ok( + await settles(viewer.open('b')), + 'the next open is not left waiting', + ); + for (let i = 0; i < 5; i++) await tick(); + assert.equal( + renderers.at(-1).canvas, + one.canvas, + 'the panorama is back on the view left', + ); + assert.equal(renderers.at(-1).images.at(-1), 'b-first'); + viewer.unmount(); + unsubscribeOne(); +}); + +test('a mount its view unmounts inside the first draw fails as closed', async () => { + const { viewer } = trackedViewer(); + const unsubscribe = viewer.subscribeView((view) => { + if (view) viewer.unmount(); + }); + await assert.rejects(viewer.mount({}), /Street-level viewer was closed/); + unsubscribe(); +}); From 80999ff00780d502acb040de3b849e84cee0764f Mon Sep 17 00:00:00 2001 From: Sameh Khamis Date: Thu, 19 Nov 2026 16:36:54 -0800 Subject: [PATCH 17/17] Add the changelog entry for #1871 Co-authored-by: Manjunath Paparaju --- changelog.d/1871-street-level-photo-followups.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 changelog.d/1871-street-level-photo-followups.md diff --git a/changelog.d/1871-street-level-photo-followups.md b/changelog.d/1871-street-level-photo-followups.md new file mode 100644 index 0000000000..e68357f915 --- /dev/null +++ b/changelog.d/1871-street-level-photo-followups.md @@ -0,0 +1,3 @@ +- Street Level's photo viewer settles every open and mount, draws one + viewer at a time and states its view contract (manjunath22466, + samehkhamis, #1871).