From afbae53b71260b09acd03e1ce2c99fad5b454c33 Mon Sep 17 00:00:00 2001 From: n30nex Date: Tue, 10 Nov 2026 18:00:26 -0500 Subject: [PATCH] ui(nodes): add direct map and packet navigation (#2295) Fixes #2290; addresses U6 of #1154. Full node details, the side preview and tablet slide-over offer Open in Map and View packets through existing deep links. A shared renderer validates coordinates, including zero, and encodes identifiers without extra fetches. Closing a preview preserves newly selected destinations and titles; manual close returns to Nodes. Tablet targets stay separate, and modified clicks retain native behavior. Refreshed at `538cb169` by normally merging current master `d1bf4ca0`, with zero conflicts. The original five commits and exact seven-file feature patch are preserved. The [original RED CI](https://github.com/Kpa-clawbot/CoreScope/actions/runs/40203064817) remains; the preserved RED also reproduces 39 assertions locally. Upstream #2333 now supplies the correction for the previous unrelated navigation-focus CI failure. Current validation: all 225 frontend suites; 52 focused unit checks; 31 shortcut browser cases in each theme; 24 additional title/native-click cases; navigation 60/60, branding 17/17 and slide-over 27/27. Parent independently reran 52 unit and 31 browser cases. Native server and ingestor suites pass. General browser smoke reports 149 passes and three existing fixture skips. Unchanged serial retries resolved two documented local test-server/navigation setup failures. Browser verified: disposable local Go fixture at `http://127.0.0.1:14954`. E2E assertion added: `tests/e2e/test-node-quick-actions-e2e.js`. Constant work for one detail view; no new requests, dependencies or settings. [Final refreshed CI](https://github.com/Kpa-clawbot/CoreScope/actions/runs/42318272198) passes. Independent adversarial, UI and test-quality reviews found no must-fixes; Kent Beck Gate: PASS. --------- Co-authored-by: n30nex <6686206+n30nex@users.noreply.github.com> --- .github/workflows/deploy.yml | 1 + public/nodes.js | 31 ++- public/style.css | 8 + scripts/non-unit-tests.json | 1 + test-all.sh | 1 + tests/e2e/test-node-quick-actions-e2e.js | 239 +++++++++++++++++++++++ tests/unit/test-node-quick-actions.js | 149 ++++++++++++++ 7 files changed, 427 insertions(+), 3 deletions(-) create mode 100644 tests/e2e/test-node-quick-actions-e2e.js create mode 100644 tests/unit/test-node-quick-actions.js diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index 233b5253..350c2864 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -723,6 +723,7 @@ jobs: suite 1 test-touch-targets.js CHROMIUM_REQUIRE=1 BASE_URL=$B suite 3 test-live-dedup.js BASE_URL=$B suite 1 test-nodes-export-e2e.js BASE_URL=$B + suite 1 test-node-quick-actions-e2e.js BASE_URL=$B suite 2 test-show-neighbors.js BASE_URL=$B suite 3 test-user-management-e2e.js BASE_URL=http://localhost:13582 BASE_URL_OFF=$B diff --git a/public/nodes.js b/public/nodes.js index 5ac68efa..72a54773 100644 --- a/public/nodes.js +++ b/public/nodes.js @@ -253,6 +253,19 @@ return renderNodeMetric('Hash Prefix', value, table); } + function renderNodeQuickActions(n) { + const nodeQuery = 'node=' + encodeURIComponent(n.public_key); + // Reject blanks/coercible non-numbers before the shared viewport parser + // validates the ranges. Zero coordinates are valid navigation targets. + const numeric = value => typeof value === 'number' || (typeof value === 'string' && value.trim() !== ''); + const viewport = numeric(n.lat) && numeric(n.lon) + ? parseViewportHash('lat=' + Number(n.lat) + '&lon=' + Number(n.lon) + '&zoom=14') : null; + const mapLink = viewport + ? ' Open in Map' : ''; + return '
' + mapLink + + ' View packets
'; + } + function getStatusTooltip(role, status) { const isInfra = role === 'repeater' || role === 'room'; const threshMs = isInfra ? HEALTH_THRESHOLDS.infraSilentMs : HEALTH_THRESHOLDS.nodeSilentMs; @@ -824,6 +837,7 @@ Analytics Reach + ${renderNodeQuickActions(n)} Observer → @@ -1858,9 +1872,12 @@ + '"]'); }, onClose: function () { + // Only closing this preview returns to the list; keep any new route. + if (selectedKey === pubkey && location.hash === '#/nodes/' + encodeURIComponent(pubkey)) { + history.replaceState(null, '', '#/nodes'); + if (window.setRouteTitle) window.setRouteTitle('nodes'); + } selectedKey = null; - history.replaceState(null, '', '#/nodes'); - if (window.setRouteTitle) window.setRouteTitle('nodes'); renderRows(); } }); @@ -1885,7 +1902,14 @@ '
Adverts
' + (n.advert_count != null ? n.advert_count : '—') + '
' + renderHashPrefix(n) + '' + - '

Open full detail →

'; + '

Open full detail →

' + + renderNodeQuickActions(n); + so.querySelector('.node-detail-btn').addEventListener('click', function (e) { + if (e.ctrlKey || e.metaKey || e.shiftKey || e.altKey) return; + e.preventDefault(); + window.SlideOver.close(); + navigateToNode(pubkey); + }); } catch (e) { so.innerHTML = '
Error: ' + (e && e.message ? e.message : String(e)) + '
'; } @@ -1943,6 +1967,7 @@ Reach + ${renderNodeQuickActions(n)} ${renderStatusExplanation(n)} ${hasLoc ? `
diff --git a/public/style.css b/public/style.css index 4ffdc90c..44a9c02f 100644 --- a/public/style.css +++ b/public/style.css @@ -2068,6 +2068,14 @@ button.ch-item:hover .ch-icon-btn { opacity: 1; } .node-detail { padding: 4px 0; } .node-detail-name { font-size: 20px; font-weight: 700; margin: 12px 0 4px; } .node-detail-role { margin-bottom: 12px; } +.node-quick-actions { display: flex; flex-wrap: wrap; gap: 6px; } +.node-quick-actions .btn-primary { + display: inline-flex; align-items: center; gap: 4px; + font-size: 12px; padding: 4px 10px; text-decoration: none; +} +@media (pointer: coarse) { + .node-quick-actions .btn-primary { min-height: 44px; min-width: 44px; } +} .node-detail-section { background: var(--card-bg); border: 1px solid var(--border); border-radius: 8px; padding: 12px; margin-bottom: 8px; diff --git a/scripts/non-unit-tests.json b/scripts/non-unit-tests.json index ec3fe110..bff67ea9 100644 --- a/scripts/non-unit-tests.json +++ b/scripts/non-unit-tests.json @@ -109,6 +109,7 @@ "tests/e2e/test-nav-priority-1311-e2e.js", "tests/e2e/test-nav-priority-1391-e2e.js", "tests/e2e/test-neighbor-map-btn-clip-e2e.js", + "tests/e2e/test-node-quick-actions-e2e.js", "tests/e2e/test-node-reach-coverage-e2e.js", "tests/e2e/test-node-reach-e2e.js", "tests/e2e/test-nodes-export-e2e.js", diff --git a/test-all.sh b/test-all.sh index 05da3abb..b82a8bcb 100755 --- a/test-all.sh +++ b/test-all.sh @@ -185,6 +185,7 @@ node tests/unit/test-node-reach-coverage.js node tests/unit/test-nodes-export-wiring.js node tests/unit/test-nav-drawer-version-footer.js node tests/unit/test-nodes-export.js +node tests/unit/test-node-quick-actions.js node tests/unit/test-notifications-ui.js node tests/unit/test-observer-iata-1188.js node tests/unit/test-observer-menu-interactions.js diff --git a/tests/e2e/test-node-quick-actions-e2e.js b/tests/e2e/test-node-quick-actions-e2e.js new file mode 100644 index 00000000..8230a30d --- /dev/null +++ b/tests/e2e/test-node-quick-actions-e2e.js @@ -0,0 +1,239 @@ +'use strict'; +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const { chromium } = require('playwright'); + +const BASE = process.env.BASE_URL || 'http://localhost:3000'; +assert.ok(['localhost', '127.0.0.1', '[::1]'].includes(new URL(BASE).hostname), 'Use a local fixture server'); +const surfaces = [ + { name: 'desktop-full', width: 1400, selector: '#nodeFullBody', full: true }, + { name: 'desktop-side', width: 1400, selector: '#nodesRight' }, + { name: 'tablet-slide-over', width: 820, selector: '.slide-over-content' }, + { name: 'phone-full', width: 390, selector: '#nodeFullBody', full: true, touch: true }, +]; +let passed = 0, failed = 0; +async function test(name, run) { + try { await run(); passed++; console.log('PASS ' + name); } + catch (error) { failed++; console.error('FAIL ' + name + ': ' + error.message); } +} + +(async () => { + const browser = await chromium.launch({ headless: true, executablePath: process.env.CHROMIUM_PATH || undefined }); + try { + const requestContext = await browser.newContext(); + const response = await requestContext.request.get(BASE + '/api/nodes?limit=1'); + assert.ok(response.ok(), 'fixture nodes API succeeds'); + const node = (await response.json()).nodes[0]; + assert.ok(node && node.public_key, 'fixture must contain a node'); + const detailResponse = await requestContext.request.get(BASE + '/api/nodes/' + encodeURIComponent(node.public_key)); + assert.ok(detailResponse.ok(), 'fixture detail API succeeds'); + const detail = await detailResponse.json(); + assert.ok(detail.node, 'actual detail response has a node field'); + await requestContext.close(); + + async function open(surface, overrides = {}) { + const ctx = await browser.newContext({ + viewport: { width: surface.width, height: 900 }, + hasTouch: !!surface.touch, isMobile: surface.mobile == null ? !!surface.touch : surface.mobile, + }); + await ctx.addInitScript(() => { + localStorage.setItem('meshcore-time-window', '60'); + localStorage.setItem('map-view', JSON.stringify({ lat: 40, lng: -80, zoom: 3 })); + }); + const page = await ctx.newPage(); + page.setDefaultTimeout(10000); + page.setDefaultNavigationTimeout(30000); // index.html loads vendor scripts from a CDN + const current = { ...detail.node, lat: 12.5, lon: 34.5, ...overrides }; + // Preserve the live API shape, replacing just the chosen node so edge + // cases are deterministic; all application scripts and routing are real. + await page.route(url => url.pathname === '/api/nodes', route => route.fulfill({ json: { + nodes: [current], total: 1, has_more: false, + counts: { repeaters: 1, rooms: 0, companions: 0, sensors: 0 }, + } })); + await page.route(url => url.pathname === '/api/nodes/' + encodeURIComponent(node.public_key), + route => route.fulfill({ json: { ...detail, node: current } })); + await page.goto(BASE + '/#/nodes' + (surface.full ? '/' + encodeURIComponent(node.public_key) : ''), { waitUntil: 'domcontentloaded' }); + // The startup theme response refreshes the Nodes renderer. Open the + // slide-over after that refresh, so it cannot replace a link mid-click. + await page.waitForFunction(() => window.SITE_CONFIG && window.SITE_CONFIG.timestamps && _themeRefreshTimer === null); + if (!surface.full) await page.locator('#nodesBody tr[data-action="select"]').first().click(); + const host = page.locator(surface.selector); + const existing = surface.name === 'tablet-slide-over' + ? host.getByRole('link', { name: 'Open full detail →', exact: true }) + : host.getByRole('link', { name: 'Analytics', exact: true }); + await existing.waitFor({ state: 'visible' }); + return { ctx, page, host, current }; + } + + for (const surface of surfaces) { + for (const destination of ['map', 'packets']) { + await test(surface.name + ' opens ' + destination, async () => { + const { ctx, page, host, current } = await open(surface); + try { + const label = destination === 'map' ? 'Open in Map' : 'View packets'; + const link = host.getByRole('link', { name: label, exact: true }); + assert.equal(await link.count(), 1, label + ' must be present'); + const rect = await link.boundingBox(); + assert.ok(rect && rect.width > 0 && rect.x >= 0 && rect.x + rect.width <= surface.width, + label + ' fits within the viewport'); + if (surface.touch) assert.ok(rect.height >= 44 && rect.width >= 44, 'phone actions have a 44px touch target'); + if (process.env.SCREENSHOT_DIR && destination === 'map') { + fs.mkdirSync(process.env.SCREENSHOT_DIR, { recursive: true }); + await page.screenshot({ path: path.join(process.env.SCREENSHOT_DIR, surface.name + '.png'), animations: 'disabled' }); + } + const regionBefore = await page.evaluate(() => localStorage.getItem('meshcore-region-filter')); + const packetRequest = destination === 'packets' + ? page.waitForRequest(request => { + const url = new URL(request.url()); + return url.pathname === '/api/packets' && url.searchParams.get('node') === current.public_key; + }) : null; + // Native anchor keyboard behavior on desktop; actual tap on phone. + const activate = async () => { + if (surface.touch) await link.tap(); + else if (surface.name === 'desktop-full') { await link.focus(); await page.keyboard.press('Enter'); } + else await link.click(); + }; + if (packetRequest) await Promise.all([packetRequest, activate()]); + else await activate(); + await page.waitForURL(url => url.hash.startsWith('#/' + destination + '?')); + const params = new URLSearchParams(new URL(page.url()).hash.split('?')[1]); + assert.equal(params.get('node'), current.public_key); + if (destination === 'map') { + await page.locator('.leaflet-popup-content .map-popup').waitFor({ state: 'visible' }); + assert.ok((await page.locator('.leaflet-popup-content').innerText()).includes(current.name), 'selected node popup opens'); + const viewport = await page.evaluate(() => ({ center: window.__mc_map.getCenter(), zoom: window.__mc_map.getZoom() })); + assert.ok(Math.abs(viewport.center.lat - current.lat) < .001 && Math.abs(viewport.center.lng - current.lon) < .001); + assert.equal(viewport.zoom, 14); + } else { + await packetRequest; + await page.locator('#fNode').waitFor({ state: 'attached' }); + if (surface.touch) await page.getByRole('button', { name: 'Filters ▾', exact: true }).tap(); + await page.locator('#fNode').waitFor({ state: 'visible' }); + assert.equal(await page.locator('#fNode').inputValue(), current.public_key.slice(0, 8)); + assert.equal(await page.evaluate(() => localStorage.getItem('meshcore-time-window')), '60'); + } + assert.equal(new URL(page.url()).hash.split('?')[0], '#/' + destination, 'closing the detail must preserve the destination'); + assert.equal(await page.evaluate(() => localStorage.getItem('meshcore-region-filter')), regionBefore); + } finally { await ctx.close(); } + }); + } + } + + for (const surface of [surfaces[0], surfaces[1]]) { + for (const label of ['Analytics', 'Reach']) { + await test(surface.name + ' preserves ' + label, async () => { + const { ctx, page, host, current } = await open(surface); + try { + await host.getByRole('link', { name: label, exact: true }).click(); + const destination = '#/nodes/' + encodeURIComponent(current.public_key) + '/' + label.toLowerCase(); + await page.waitForURL(url => url.hash === destination); + await page.waitForFunction(expected => currentPage === expected, 'node-' + label.toLowerCase()); + assert.equal(new URL(page.url()).hash, destination); + } finally { await ctx.close(); } + }); + } + } + for (const method of ['Escape', 'backdrop']) { + await test('tablet preview ' + method + ' returns to the list', async () => { + const { ctx, page } = await open(surfaces[2]); + try { + if (method === 'Escape') await page.keyboard.press('Escape'); + else await page.locator('.slide-over-backdrop').click({ position: { x: 20, y: 400 } }); + await page.locator('.slide-over-panel').waitFor({ state: 'detached' }); + assert.equal(new URL(page.url()).hash, '#/nodes'); + assert.ok(await page.locator('#nodesBody tr[data-action="select"]').count()); + } finally { await ctx.close(); } + }); + } + await test('desktop preview Details still opens full detail', async () => { + const { ctx, page, host, current } = await open(surfaces[1]); + try { + await host.locator('.node-detail-btn').click(); + await page.locator('#nodeFullBody').getByRole('link', { name: 'Analytics', exact: true }).waitFor(); + assert.equal(new URL(page.url()).hash, '#/nodes/' + encodeURIComponent(current.public_key)); + } finally { await ctx.close(); } + }); + await test('tablet preview opens full detail without losing its hash', async () => { + const { ctx, page, host, current } = await open(surfaces[2]); + try { + await host.getByRole('link', { name: 'Open full detail →', exact: true }).click(); + await page.locator('.slide-over-panel').waitFor({ state: 'detached' }); + await page.locator('#nodeFullBody').getByRole('link', { name: 'Analytics', exact: true }).waitFor(); + assert.equal(new URL(page.url()).hash, '#/nodes/' + encodeURIComponent(current.public_key)); + await page.getByRole('button', { name: 'Back to nodes', exact: true }).click(); + await page.locator('#nodesBody tr[data-action="select"]').waitFor(); + assert.equal(new URL(page.url()).hash, '#/nodes'); + } finally { await ctx.close(); } + }); + await test('touch tablet actions have separate 44px targets', async () => { + const { ctx, page, host } = await open({ ...surfaces[2], touch: true, mobile: false }); + try { + assert.equal(await page.evaluate(() => matchMedia('(pointer: coarse)').matches), true); + await host.evaluate(element => Promise.all(element.closest('.slide-over-panel').getAnimations().map(animation => animation.finished))); + const labels = ['Open full detail →', 'Open in Map', 'View packets']; + const bounds = []; + for (const label of labels) { + const rect = await host.getByRole('link', { name: label, exact: true }).boundingBox(); + assert.ok(rect, label + ' must be visible'); + bounds.push({ label, ...rect }); + } + console.log('TABLET_ACTION_BOUNDS ' + JSON.stringify(bounds)); + if (process.env.SCREENSHOT_DIR) { + fs.mkdirSync(process.env.SCREENSHOT_DIR, { recursive: true }); + await page.screenshot({ path: path.join(process.env.SCREENSHOT_DIR, 'tablet-touch-actions.png'), animations: 'disabled' }); + } + for (let i = 0; i < bounds.length; i++) { + for (let j = i + 1; j < bounds.length; j++) { + const a = bounds[i], b = bounds[j]; + const overlap = Math.max(0, Math.min(a.x + a.width, b.x + b.width) - Math.max(a.x, b.x)) * + Math.max(0, Math.min(a.y + a.height, b.y + b.height) - Math.max(a.y, b.y)); + assert.equal(overlap, 0, a.label + ' overlaps ' + b.label + ' by ' + overlap + 'px²'); + } + } + for (const rect of bounds) assert.ok(rect.width >= 44 && rect.height >= 44, rect.label + ' must have a 44px touch target'); + } finally { await ctx.close(); } + }); + for (const surface of [surfaces[0], surfaces[1], surfaces[2], surfaces[3]]) { + for (const coords of [{ lat: null }, { lat: '12north' }, { lon: 181 }]) { + await test(surface.name + ' suppresses Map for ' + JSON.stringify(coords), async () => { + const { ctx, host } = await open(surface, coords); + try { + assert.equal(await host.getByRole('link', { name: 'Open in Map', exact: true }).count(), 0); + assert.equal(await host.getByRole('link', { name: 'View packets', exact: true }).count(), 1); + } finally { await ctx.close(); } + }); + } + } + await test('zero coordinates override the saved map viewport', async () => { + const { ctx, page, host } = await open(surfaces[3], { lat: 0, lon: 0 }); + try { + const link = host.getByRole('link', { name: 'Open in Map', exact: true }); + assert.equal(await link.count(), 1); + await link.tap(); + await page.waitForFunction(() => window.__mc_map && document.getElementById('leaflet-map')); + const viewport = await page.evaluate(() => ({ center: window.__mc_map.getCenter(), zoom: window.__mc_map.getZoom() })); + assert.ok(Math.abs(viewport.center.lat) < .001 && Math.abs(viewport.center.lng) < .001); + assert.equal(viewport.zoom, 14); + } finally { await ctx.close(); } + }); + await test('hostile identifiers stay inside the node query parameter', async () => { + const key = 'node" onfocus="bad &/?#%\''; + const { ctx, page, host } = await open(surfaces[0], { public_key: key }); + try { + for (const label of ['Open in Map', 'View packets']) { + const link = host.getByRole('link', { name: label, exact: true }); + assert.equal(await link.count(), 1); + const attrs = await link.evaluate(element => ({ href: element.getAttribute('href'), injected: element.hasAttribute('onfocus') })); + assert.equal(new URLSearchParams(attrs.href.split('?')[1]).get('node'), key); + assert.equal(attrs.injected, false); + } + await host.getByRole('link', { name: 'View packets', exact: true }).click(); + await page.waitForURL(url => url.hash.startsWith('#/packets?')); + assert.equal(new URLSearchParams(new URL(page.url()).hash.split('?')[1]).get('node'), key); + } finally { await ctx.close(); } + }); + } finally { await browser.close(); } + console.log(`${passed} passed, ${failed} failed`); + process.exitCode = failed ? 1 : 0; +})().catch(error => { console.error(error); process.exitCode = 1; }); diff --git a/tests/unit/test-node-quick-actions.js b/tests/unit/test-node-quick-actions.js new file mode 100644 index 00000000..55cc79c4 --- /dev/null +++ b/tests/unit/test-node-quick-actions.js @@ -0,0 +1,149 @@ +'use strict'; +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const vm = require('node:vm'); +const root = path.resolve(__dirname, '../..'); + +// Run the real side-pane renderer. Stop at its DOM write: later map/QR/API +// effects are unrelated to the links, and no browser dependency is needed. +const ctx = vm.createContext({ + console, URLSearchParams, clearTimeout() {}, + localStorage: { getItem() { return null; } }, + location: { origin: 'http://localhost' }, + registerPage() {}, + ROLE_COLORS: {}, HEALTH_THRESHOLDS: { infraSilentMs: 3600000, nodeSilentMs: 3600000 }, + getNodeStatus() { return 'active'; }, getEffectiveHeardMs() { return NaN; }, + groupRecentAdverts() { return []; }, + api() { throw new Error('Rendering quick actions must not request data'); }, +}); +ctx.window = ctx; +const appSource = fs.readFileSync(path.join(root, 'public/app.js'), 'utf8'); +for (const name of ['escapeHtml', 'parseViewportHash']) { + const source = appSource.match(new RegExp('function ' + name + '\\([^]*?\\n}')); + assert.ok(source, name + ' must exist in app.js'); + vm.runInContext(source[0], ctx); +} +const nodesSource = fs.readFileSync(path.join(root, 'public/nodes.js'), 'utf8'); +vm.runInContext(nodesSource.replace(/\}\)\(\);\s*$/, 'window.renderDetailForTest = renderDetail; window.selectNodeForTest = selectNode; window.destroyNodeForTest = destroy; })();'), ctx); + +function render(node) { + let html; + const done = new Error('DOM captured'); + const panel = { set innerHTML(value) { html = value; throw done; } }; + assert.throws(() => ctx.renderDetailForTest(panel, { + node: { public_key: 'ab'.repeat(32), name: 'Fixture node', role: 'companion', ...node }, + }), error => error === done); + return html; +} +function action(html, label) { + const links = [...html.matchAll(/]*href="([^"]*)"[^>]*>([^]*?)<\/a>/g)]; + const found = links.filter(match => match[2].replace(/<[^>]*>/g, '').trim() === label); + assert.ok(found.length <= 1, 'duplicate action: ' + label); + if (!found.length) return null; + const href = found[0][1].replace(/&/g, '&').replace(/'/g, "'").replace(/"/g, '"'); + return { markup: found[0][0], href, params: new URLSearchParams(href.split('?')[1]) }; +} + +let passed = 0, failed = 0; +function test(name, run) { + try { run(); passed++; console.log('PASS ' + name); } + catch (error) { failed++; console.error('FAIL ' + name + ': ' + error.message); } +} + +test('both actions use existing routes without overriding packet preferences', () => { + const html = render({ lat: 12.5, lon: 34.5 }); + const map = action(html, 'Open in Map'); + const packets = action(html, 'View packets'); + assert.ok(map, 'Open in Map is missing'); + assert.ok(packets, 'View packets is missing'); + assert.equal(map.href.split('?')[0], '#/map'); + assert.deepEqual(Object.fromEntries(map.params), { node: 'ab'.repeat(32), lat: '12.5', lon: '34.5', zoom: '14' }); + assert.equal(packets.href.split('?')[0], '#/packets'); + assert.deepEqual(Object.fromEntries(packets.params), { node: 'ab'.repeat(32) }); + assert.ok(action(html, 'Analytics') && action(html, 'Reach'), 'existing actions remain'); + assert.ok(html.includes('node-detail-btn'), 'Details remains'); +}); + +for (const [lat, lon] of [[0, 0], [0, -45], [45, 0], ['0', '0'], ['12.5', '-34.5'], [-90, -180], [90, 180]]) { + test('valid coordinates ' + JSON.stringify([lat, lon]), () => { + const map = action(render({ lat, lon }), 'Open in Map'); + assert.ok(map, 'valid coordinates must offer Map'); + assert.equal(Number(map.params.get('lat')), Number(lat)); + assert.equal(Number(map.params.get('lon')), Number(lon)); + }); +} +for (const value of [null, undefined, '', ' ', '12north', 'NaN', NaN, Infinity, -Infinity, true, [], {}]) { + for (const coordinate of ['lat', 'lon']) { + test('invalid ' + coordinate + ': ' + String(value), () => { + const html = render({ lat: 1, lon: 2, [coordinate]: value }); + assert.equal(action(html, 'Open in Map'), null); + assert.ok(action(html, 'View packets'), 'packets remain available without coordinates'); + }); + } +} +for (const [lat, lon] of [[90.01, 0], [-90.01, 0], [0, 180.01], [0, -180.01]]) { + test('out-of-range coordinates ' + JSON.stringify([lat, lon]), () => { + assert.equal(action(render({ lat, lon }), 'Open in Map'), null); + }); +} +test('hostile identifiers remain one encoded node parameter', () => { + const key = 'node" onfocus="bad &/?#%\''; + const html = render({ public_key: key, lat: 1, lon: 2 }); + for (const label of ['Open in Map', 'View packets']) { + const link = action(html, label); + assert.ok(link, label + ' is missing'); + assert.equal(link.params.get('node'), key); + assert.ok(!link.markup.includes('onfocus='), 'identifier escaped into an attribute'); + assert.ok(!link.markup.includes(''), 'identifier escaped into markup'); + } +}); + +(async () => { + // Exercise the actual callback captured by SlideOver.open, including the + // destroy-before-close sequence used when opening the full detail page. + const key = 'ab'.repeat(32); + let close; + let fullDetailClick; + const routeTitleCalls = []; + ctx.setRouteTitle = (...args) => routeTitleCalls.push(args); + ctx.innerWidth = 820; + ctx.document = { getElementById() { return null; }, querySelector() { return null; } }; + ctx.history = { replaceState(_state, _title, hash) { ctx.location.hash = hash; } }; + ctx.CLIENT_TTL = {}; + ctx.api = async () => ({ node: { public_key: key, role: 'companion' } }); + ctx.SlideOver = { + shouldUse() { return true; }, + open(options) { close = options.onClose; return { querySelector() { return { addEventListener(_type, handler) { fullDetailClick = handler; } }; } }; }, + }; + for (const destination of ['#/nodes/' + key, '#/map?node=' + key, '#/packets?node=' + key, + '#/nodes/' + key + '/analytics', '#/nodes/' + key + '/reach', '#/nodes/other']) { + await ctx.selectNodeForTest(key); + routeTitleCalls.length = 0; + ctx.location.hash = destination; + close(); + test('closing the preview preserves destination ' + destination.split('?')[0], () => { + assert.equal(ctx.location.hash, destination === '#/nodes/' + key ? '#/nodes' : destination); + }); + test('closing the preview preserves the route title for ' + destination.split('?')[0], () => { + assert.deepEqual(routeTitleCalls, destination === '#/nodes/' + key ? [['nodes']] : []); + }); + } + await ctx.selectNodeForTest(key); + ctx.destroyNodeForTest(); + routeTitleCalls.length = 0; + close(); + test('closing after full-detail navigation does not reset its title', () => { + assert.deepEqual(routeTitleCalls, []); + }); + test('closing after full-detail navigation does not reset its identical hash', () => { + assert.equal(ctx.location.hash, '#/nodes/' + key); + }); + test('modified full-detail clicks preserve native link behavior', () => { + for (const modifier of ['ctrlKey', 'metaKey', 'shiftKey', 'altKey']) { + fullDetailClick({ [modifier]: true, preventDefault() { assert.fail('Do not intercept ' + modifier + ' clicks'); } }); + } + }); + console.log(`${passed} passed, ${failed} failed`); + process.exitCode = failed ? 1 : 0; +})().catch(error => { console.error(error); process.exitCode = 1; });