diff --git a/public/dagi-choropleth.js b/public/dagi-choropleth.js index c261e5446..ec76e9cff 100644 --- a/public/dagi-choropleth.js +++ b/public/dagi-choropleth.js @@ -8,8 +8,9 @@ * create({ L, map, doc, fetchJson, decode, readVar, escape, onPick }): * fetchJson(query) a Promise of GET /api/config/dagi/polygons? * (the browser caches it: max-age plus an ETag). - * decode(resp) DagiFilter.decodeRings, called once per area with that - * area's features (no second decoder). + * decode(resp, vertex) DagiFilter.decodeRings, called once per area with + * that area's features (no second decoder); vertex makes + * Leaflet's own LatLngs. * readVar(name) a CSS variable's value (--dagi-choro-1…5, -none). * escape(s) HTML-escapes the credit, which Leaflet's attribution * control renders as HTML. @@ -128,12 +129,83 @@ /* ---------- the layer ---------- */ + /** + * Leaflet's Polygon and FeatureGroup, minus work a choropleth of 605 + * postnummer shapes (44K vertices) does not need; what they draw is what + * L.polygon draws (the E2E compares every path's d on one map): + * + * Shape(rings, options, bounds): rings of L.LatLng from the decoder, and + * its bounds. Leaflet's _setLatLngs converts and bounds every vertex + * again; this keeps them (the decoder's rings leave the closing vertex + * implicit, so there is none to drop). + * _projectLatlngs makes the same points in the same order as + * latLngToLayerPoint (project, transform at the zoom's scale, round, + * minus the pixel origin) without the per-vertex scale and origin + * lookups. _clipPoints skips the clipping pass for a shape that lies + * inside the clip box (the fitted map): there every point is inside, + * and the clipper hands back the same points. The shapes keep + * Leaflet's focus listeners: Chromium makes an SVG path focusable + * once it has them, which is what puts every shape in the Tab order + * and gives a tapped one its focus ring. + * Group: the map's one tooltip (one per shape cost a tooltip and its + * listeners per shape). Leaflet marks every shape of a group as + * described by the tooltip when it opens; this marks the one under the + * pointer, as a shape's own tooltip does. + */ + function shapeClasses(L) { + var Polygon = L.Polygon, LatLng = L.LatLng; + var Shape = Polygon.extend({ + initialize: function (rings, options, bounds) { + this._decodedBounds = bounds; + Polygon.prototype.initialize.call(this, rings, options); + }, + _setLatLngs: function (rings) { + var b = this._decodedBounds; + this._decodedBounds = null; + if (!b) return Polygon.prototype._setLatLngs.call(this, rings); // a later setLatLngs + this._bounds = L.latLngBounds(b[0], b[1]); + this._latlngs = rings; // the decoder's rings never repeat their first vertex + }, + _projectLatlngs: function (latlngs, result, pxBounds) { + if (!(latlngs[0] && latlngs[0][0] instanceof LatLng)) { + return Polygon.prototype._projectLatlngs.call(this, latlngs, result, pxBounds); + } + var m = this._map, crs = m.options.crs, proj = crs.projection, tr = crs.transformation; + var scale = crs.scale(m.getZoom()), origin = m.getPixelOrigin(); + for (var r = 0; r < latlngs.length; r++) { + var src = latlngs[r], ring = new Array(src.length); + for (var i = 0; i < src.length; i++) { + ring[i] = tr._transform(proj.project(src[i]), scale)._round()._subtract(origin); + pxBounds.extend(ring[i]); + } + result.push(ring); + } + }, + _clipPoints: function () { + var b = this._renderer._bounds, w = this.options.weight, r = this._rawPxBounds; + if (r && r.min.x >= b.min.x - w && r.min.y >= b.min.y - w && r.max.x <= b.max.x + w && r.max.y <= b.max.y + w) { + this._parts = this._rings.slice(); + return; + } + Polygon.prototype._clipPoints.call(this); + }, + }); + var Group = L.FeatureGroup.extend({ + _setAriaDescribedByOnLayer: function (layer) { + if (this._tooltip && layer === this._tooltip._source) L.FeatureGroup.prototype._setAriaDescribedByOnLayer.call(this, layer); + }, + }); + return { Shape: Shape, Group: Group }; + } + function now() { return typeof performance !== 'undefined' && performance.now ? performance.now() : Date.now(); } function create(opts) { var L = opts.L, map = opts.map, doc = opts.doc || document; + var cls = shapeClasses(L); + function latLng(lat, lon) { return new L.LatLng(lat, lon); } // layer → the Promise of its polygon answer, set when the request starts, // so a second show() during the load waits on the same request (one // entry per layer seen, at most the 4 layers; a failure drops it). @@ -167,9 +239,10 @@ shapes = new Map(); } - /** A shape's tooltip, built when it opens (Leaflet calls a content - * function then), so a draw makes no tooltip DOM: name and value as - * textContent, so an area name cannot inject markup. */ + /** The tooltip of shape sh, built when it opens (Leaflet calls the + * group's content function then, with the shape under the pointer), + * so a draw makes no tooltip DOM: name and value as textContent, so an + * area name cannot inject markup. */ function tooltipOf(sh) { var tip = doc.createElement('div'); tip.className = 'dagi-choro-tip'; @@ -201,7 +274,7 @@ }); var decoded = []; byKey.forEach(function (e, k) { - var d = opts.decode({ quantum: resp.quantum, features: e.features }); + var d = opts.decode({ quantum: resp.quantum, features: e.features }, latLng); if (d.rings.length) decoded.push({ key: k, name: e.name, d: d }); }); var t1 = now(); @@ -209,9 +282,8 @@ var s = Infinity, w = Infinity, n = -Infinity, ea = -Infinity; decoded.forEach(function (x) { var sh = { poly: null, name: x.name, label: '' }; - var p = sh.poly = L.polygon(x.d.rings, { weight: 0.6, opacity: 0.9, fillOpacity: 0.72, className: 'dagi-choro-shape dagi-choro-k-' + String(x.key).replace(/[^\w-]/g, ''), color: col.line, fillColor: col.pal[sc.slotOf.get(x.key) || 0] }); + var p = sh.poly = new cls.Shape(x.d.rings, { weight: 0.6, opacity: 0.9, fillOpacity: 0.72, className: 'dagi-choro-shape dagi-choro-k-' + String(x.key).replace(/[^\w-]/g, ''), color: col.line, fillColor: col.pal[sc.slotOf.get(x.key) || 0] }, x.d.bounds); p.key = x.key; - p.bindTooltip(function () { return tooltipOf(sh); }, { sticky: true }); p.on('click', function () { if (opts.onPick) opts.onPick(x.key); }); shapes.set(x.key, sh); list.push(p); @@ -221,7 +293,8 @@ }); var gopts = {}; if (typeof resp.credit === 'string' && resp.credit) gopts.attribution = opts.escape(resp.credit); - group = L.featureGroup(list, gopts); + group = new cls.Group(list, gopts); + group.bindTooltip(function (layer) { return tooltipOf(shapes.get(layer.key)); }, { sticky: true }); group.addTo(map); if (list.length && map.fitBounds) map.fitBounds([[s, w], [n, ea]], { padding: [8, 8] }); var t = lastTiming = { layer: layer, decodeMs: t1 - t0, drawMs: now() - t1, shapes: list.length, paintMs: null }; @@ -285,6 +358,6 @@ window.DagiChoropleth = { create: create, THEME_VARS: THEME_VARS, - _test: { quantileEdges: quantileEdges, classOf: classOf, rampSlot: rampSlot, colorVar: colorVar, scale: scale, legend: legend }, + _test: { shapeClasses: shapeClasses, quantileEdges: quantileEdges, classOf: classOf, rampSlot: rampSlot, colorVar: colorVar, scale: scale, legend: legend }, }; })(); diff --git a/public/dagi-filter.js b/public/dagi-filter.js index 1405a77cc..ce6783209 100644 --- a/public/dagi-filter.js +++ b/public/dagi-filter.js @@ -178,8 +178,11 @@ * rings, each [lon0, lat0, dlon, dlat, …] in quantum degrees with the * closing vertex implicit, summed and swapped to [lat, lon]. The rings * are one even-odd shape (holes and islands alike), so they are drawn as - * one polygon. bounds is [[south, west], [north, east]], null for none. */ - function decodeRings(resp) { + * one polygon. bounds is [[south, west], [north, east]], null for none. + * vertex(lat, lon), when given, makes each vertex instead of [lat, lon] + * (the choropleth makes Leaflet's own LatLngs, so Leaflet does not + * convert 44K postnummer vertices a second time). */ + function decodeRings(resp, vertex) { var out = { rings: [], bounds: null, vertices: 0 }; var q = resp && Number(resp.quantum); if (!q || !isFinite(q) || q <= 0 || !Array.isArray(resp.features)) return out; @@ -193,7 +196,7 @@ for (var i = 0, k = 0; i + 1 < r.length; i += 2, k++) { x += r[i]; y += r[i + 1]; var lat = y * q, lon = x * q; - ring[k] = [lat, lon]; + ring[k] = vertex ? vertex(lat, lon) : [lat, lon]; if (lat < s) s = lat; if (lat > n) n = lat; if (lon < w) w = lon; if (lon > e) e = lon; } diff --git a/test-dagi-choropleth.js b/test-dagi-choropleth.js index 7fcc78c8b..ef9abb423 100644 --- a/test-dagi-choropleth.js +++ b/test-dagi-choropleth.js @@ -204,7 +204,8 @@ test('show() fetches the layer once and draws one polygon per row key (a group\' const grp = w.made.find((p) => p.key === '1050'); assert.strictEqual(grp.rings.length, 2, 'the street-postcode group is one shape'); const ll = aarhus.rings[0][0]; - assert.ok(Math.abs(ll[0] - 56.1) < 1e-9 && Math.abs(ll[1] - 10.1) < 1e-9, 'decoded by DagiFilter.decodeRings to [lat, lon]: ' + ll); + assert.ok(ll instanceof w.L.LatLng, 'the decoder makes the LatLngs the shape keeps: ' + JSON.stringify(ll)); + assert.ok(Math.abs(ll.lat - 56.1) < 1e-9 && Math.abs(ll.lng - 10.1) < 1e-9, 'decoded by DagiFilter.decodeRings: ' + JSON.stringify(ll)); const made = w.made.length; await w.ch.show('kommune', KROWS, valueOf, String); assert.deepStrictEqual(w.fetched, ['layer=kommune'], 'a second show of the same layer fetched again'); @@ -261,14 +262,15 @@ test('the tooltip is a DOM node with textContent (a name cannot inject markup)', const rows = [{ code: '0751', name: '', v: 3 }]; await w.ch.show('kommune', rows, valueOf, (v) => v.toFixed(2)); const p = w.made.find((x) => x.key === '0751'); - assert.strictEqual(typeof p.tooltip, 'function', 'the tooltip DOM is built at draw time, not when it opens'); - const tip = p.tooltip(p); // Leaflet calls a content function when the tooltip opens + const grp = w.map.layers.find((l) => l.list); + assert.strictEqual(typeof grp.tooltip, 'function', 'the tooltip DOM is built at draw time, not when it opens'); + const tip = grp.tooltip(p); // Leaflet calls a group's content function with the shape under the pointer assert.ok(tip && typeof tip.tagName === 'string', 'tooltip is not an element'); assert.ok(tip.textContent.includes('')); assert.ok(tip.textContent.includes('3.00'), 'the value in the metric\'s format: ' + tip.textContent); assert.ok(!tip.all().some((e) => e.tagName === 'IMG'), 'markup became an element'); w.ch.restyle([{ code: '0751', name: 'Aarhus', v: 7 }], valueOf, (v) => v.toFixed(2)); - const again = p.tooltip(p).textContent; + const again = grp.tooltip(p).textContent; assert.ok(again.includes('Aarhus') && again.includes('7.00'), 'the tooltip does not follow a restyle: ' + again); }); @@ -296,6 +298,32 @@ test('each shape carries a class with its key (for the browser check), stripped w.made.forEach((p) => assert.ok(/^dagi-choro-shape dagi-choro-k-[\w-]+$/.test(p.style.className), p.style.className)); }); +test('each shape keeps the decoder\'s LatLngs and bounds, so Leaflet converts no vertex a second time (#1002 M3 perf)', async () => { + const w = instance(); + await w.ch.show('kommune', KROWS, valueOf, String); + const resp = polygons('kommune'); + const shapes = w.made.filter((p) => p.key); + assert.strictEqual(shapes.length, 4); + shapes.forEach((p) => { + assert.ok(p.proto, p.key + ': made with L.polygon, not the choropleth\'s Polygon subclass'); + const feats = resp.features.filter((f) => String(f.group || f.code) === p.key); + eq(p.bounds, plain(decodeRings({ quantum: resp.quantum, features: feats }).bounds), p.key + ': bounds'); + assert.ok(p.rings.every((r) => r.every((v) => v instanceof w.L.LatLng)), p.key + ': a vertex is not an L.LatLng'); + }); +}); + +test('one tooltip for the whole map (sticky), none per shape (#1002 M3 perf)', async () => { + const w = instance(); + await w.ch.show('kommune', KROWS, valueOf, String); + const grp = w.map.layers.find((l) => l.list); + assert.ok(grp.proto, 'the group is a plain L.featureGroup, not the choropleth\'s subclass'); + assert.strictEqual(typeof grp.tooltip, 'function'); + assert.strictEqual(grp.tooltipOptions && grp.tooltipOptions.sticky, true, 'not sticky'); + assert.ok(w.made.every((p) => p.tooltip === null), 'a shape has its own tooltip'); + const tip = grp.tooltip(w.made.find((p) => p.key === '1050')); + assert.ok(tip.textContent.length > 0, 'a shape with no row has no tooltip text'); +}); + test('a click on a shape picks that row\'s key', async () => { const w = instance(); await w.ch.show('kommune', KROWS, valueOf, String); diff --git a/test-issue-1002-m3-dagi-choropleth-e2e.js b/test-issue-1002-m3-dagi-choropleth-e2e.js index 70bda76c3..83981d707 100644 --- a/test-issue-1002-m3-dagi-choropleth-e2e.js +++ b/test-issue-1002-m3-dagi-choropleth-e2e.js @@ -18,7 +18,9 @@ * (the legend follows) and sends no request. * 2. Desktop 1440x900: the deep link …&layer=kommune&map=1 shows the map * with one polygon request; a header click (Heard) restyles with no - * request; a click on Aarhus picks it (kommune=0751 in the URL). + * request; the map's one tooltip names Aarhus, then Odense under the + * pointer, and marks only those two shapes as described by it; a click + * on Aarhus picks it (kommune=0751 in the URL). * 3. A theme change restyles the drawn map (#1071 review F1): with the map * shown at 1440x900, the dark-mode toggle (which sends no event) puts * every fill in the dark ramp and every outline on --text-muted, and a @@ -31,6 +33,10 @@ * each pick the area (URL, card) while the map's top on screen moves * by 2 px or less; a row tap afterwards still brings the overview up * (#1069 R1). + * 4c. The choropleth's Polygon subclass draws exactly what L.polygon + * draws from the same answer: every path's d attribute on one map, + * fitted and zoomed in on Aarhus and København (shapes clipped by + * Leaflet), kommune and postnummer. * 5. Perf (AGENTS.md rule 0), 375x560 at a plain 4x CDP CPU throttle * (Emulation.setCPUThrottlingRate, not relative to the host): decode + * draw of the kommune and postnummer layers <= PERF_BUDGET_MS, from the @@ -123,6 +129,23 @@ function populate(resp) { }); return { ctx, page, polys }; } + // A screen point inside the shape `key` where it is the hit element. + const pointIn = (page, key) => page.evaluate((k) => { + const p = document.querySelector('.analytics-dagi-map path.dagi-choro-k-' + k); + const b = p && p.getBoundingClientRect(); + if (!b) return null; + for (let fy = 0.5, i = 0; i < 9; i++, fy = 0.5 + ((i % 2 ? 1 : -1) * Math.ceil(i / 2)) / 10) { + for (let fx = 0.5, j = 0; j < 9; j++, fx = 0.5 + ((j % 2 ? 1 : -1) * Math.ceil(j / 2)) / 10) { + const x = b.left + b.width * fx, y = b.top + b.height * fy; + if (document.elementFromPoint(x, y) === p) return { x, y }; + } + } + return null; + }, key); + const tipText = (page) => page.evaluate(() => { + const t = document.querySelector('.leaflet-tooltip .dagi-choro-tip strong'); + return t ? t.textContent : null; + }); async function shot(page, name) { if (SHOTS) await page.screenshot({ path: path.join(SHOTS, name + '.png'), fullPage: false }); } const rowsShown = (page, n) => page.waitForFunction((count) => document.querySelectorAll('.analytics-dagi-row').length === count, n); const shapesShown = (page, n) => page.waitForFunction((count) => document.querySelectorAll('.analytics-dagi-map path.dagi-choro-shape').length === count, n); @@ -195,8 +218,45 @@ function populate(resp) { const f2 = await fills(page); assert(Object.keys(f1).some((k) => f1[k] !== f2[k]), 'the header sort changed no colour'); await shot(page, 'm3-desktop-map'); + // One sticky tooltip for the map (#1002 M3 perf): it names the shape + // under the pointer and follows it from one shape to the next. + const inAarhus = await pointIn(page, '0751'), inOdense = await pointIn(page, '0461'); + assert(inAarhus && inOdense, 'no point inside Aarhus/Odense on the map'); + await page.mouse.move(inAarhus.x, inAarhus.y); + await page.waitForFunction(() => !!document.querySelector('.leaflet-tooltip .dagi-choro-tip')); + assert(await tipText(page) === 'Aarhus', 'tooltip over Aarhus: ' + await tipText(page)); + await page.mouse.move(inOdense.x, inOdense.y); // one move: out of Aarhus, into Odense + await page.waitForFunction(() => ((document.querySelector('.leaflet-tooltip .dagi-choro-tip strong') || {}).textContent) === 'Odense'); + assert(await page.evaluate(() => document.querySelectorAll('.leaflet-tooltip').length) === 1, 'more than one tooltip open'); + const described = await page.evaluate(() => [...document.querySelectorAll('.analytics-dagi-map path.dagi-choro-shape[aria-describedby]')] + .map((p) => (p.getAttribute('class').match(/dagi-choro-k-(\S+)/) || [])[1])); + assert(described.sort().join(',') === '0461,0751', 'shapes described by the tooltip (only the two hovered, not all 99): ' + described.join(',')); + // The shapes stay in the keyboard Tab order, as on master (#1091 review + // F1): Tab from "Hide map" reaches the first shapes, and focusing one + // opens its tooltip and marks it as described by it. + await page.mouse.move(0, 0); + await page.focus('.analytics-dagi-map-toggle'); + const tabbed = []; + for (let i = 0; i < 4; i++) { // the map itself, then the first three shapes + await page.keyboard.press('Tab'); + tabbed.push(await page.evaluate(() => { + const a = document.activeElement; + return { shape: !!(a && a.matches && a.matches('path.dagi-choro-shape')), + key: a && a.getAttribute && ((a.getAttribute('class') || '').match(/dagi-choro-k-(\S+)/) || [])[1], + described: a && a.getAttribute && a.getAttribute('aria-describedby') }; + })); + } + assert(!tabbed[0].shape && tabbed.slice(1).every((t) => t.shape), 'Tab from "Hide map" did not go map, then the first three shapes: ' + JSON.stringify(tabbed)); + assert(tabbed.slice(1).every((t) => t.described), 'a focused shape is not described by the tooltip: ' + JSON.stringify(tabbed)); + const focusKey = tabbed[3].key; + await page.waitForFunction(() => !!document.querySelector('.leaflet-tooltip .dagi-choro-tip strong')); + const focusTip = await tipText(page); + assert(focusTip && focusTip.length > 0 && await page.evaluate((id) => !!document.getElementById(id) && document.getElementById(id).textContent.includes( + document.querySelector('.leaflet-tooltip .dagi-choro-tip strong').textContent), tabbed[3].described), 'the focused shape (' + focusKey + ') has no tooltip named ' + focusTip); await page.locator('path.dagi-choro-k-0751').click({ force: true }); await page.waitForFunction(() => /kommune=0751/.test(location.hash)); + // A click leaves the focus (and its ring) on the shape, as on master. + assert(await page.evaluate(() => { const a = document.activeElement; return !!(a && a.matches && a.matches('path.dagi-choro-k-0751')); }), 'a clicked shape does not take the focus'); await page.waitForSelector('.analytics-dagi-card', { state: 'visible' }); assert(await page.evaluate(() => document.querySelector('.analytics-dagi-title').textContent) === 'Aarhus', 'the card is not Aarhus'); assert(polys.length === 1, 'the pick fetched polygons again'); @@ -336,6 +396,101 @@ function populate(resp) { await ctx.close(); }); + // The choropleth's own Polygon subclass (#1002 M3 perf: the decoder's + // LatLngs and bounds kept, one projection pass, no clipping pass for a + // ring that lies inside the clip box) must draw exactly what Leaflet's + // L.polygon draws from the same answer: every path's d attribute, on one + // map, fitted (nothing clipped) and zoomed in on Aarhus and on København + // (most shapes off screen or clipped by Leaflet). + await step('the choropleth\'s shapes draw exactly what L.polygon draws (every path, fitted and zoomed in; kommune, postnummer)', async () => { + const { ctx, page } = await cold({ width: 375, height: 560 }, true); + await page.goto(BASE + '/#/analytics?tab=dagi-areas&layer=kommune', { waitUntil: 'domcontentloaded' }); + await rowsShown(page, 99); + const res = await page.evaluate(async () => { + const L = window.L, out = []; + const { Shape } = window.DagiChoropleth._test.shapeClasses(L); + const el = document.createElement('div'); + el.style.cssText = 'position:fixed;left:0;top:0;width:375px;height:320px'; + document.body.appendChild(el); + const map = L.map(el, { zoomSnap: 0.25, zoomAnimation: false, fadeAnimation: false }); + for (const layer of ['kommune', 'postnummer']) { + const resp = await (await fetch('/api/config/dagi/polygons?layer=' + layer)).json(); + const byKey = new Map(); + resp.features.forEach((f) => { const k = String(f.group || f.code); if (!byKey.has(k)) byKey.set(k, []); byKey.get(k).push(f); }); + const pairs = [], all = L.latLngBounds([]); + byKey.forEach((features, k) => { + const a = window.DagiFilter.decodeRings({ quantum: resp.quantum, features }); + const b = window.DagiFilter.decodeRings({ quantum: resp.quantum, features }, (lat, lon) => new L.LatLng(lat, lon)); + if (!a.rings.length) return; + const style = { weight: 0.6, opacity: 0.9, fillOpacity: 0.72 }; + pairs.push({ k, ref: L.polygon(a.rings, style).addTo(map), fast: new Shape(b.rings, style, b.bounds).addTo(map) }); + all.extend(a.bounds); + }); + const views = [ + ['fitted', () => map.fitBounds(all, { padding: [8, 8], animate: false })], + ['Aarhus z11', () => map.setView([56.16, 10.2], 11, { animate: false })], + ['København z13', () => map.setView([55.68, 12.57], 13, { animate: false })], + // zoomSnap 0.25, as the app's map: a projection at a rounded zoom + // draws other points (#1091 review F2) + ['Aarhus z9.25', () => map.setView([56.16, 10.2], 9.25, { animate: false })], + ['Fanø z11.75', () => map.setView([55.43, 8.4], 11.75, { animate: false })], + ]; + for (const [name, go] of views) { + go(); + let differ = 0, drawn = 0, clipped = 0, first = null; + const rb = pairs[0].fast._renderer._bounds; + pairs.forEach(({ k, ref, fast }) => { + const da = ref._path.getAttribute('d'), db = fast._path.getAttribute('d'); + if (da !== db) { differ++; if (!first) first = k + ': ' + String(da).slice(0, 80) + ' | ' + String(db).slice(0, 80); } + if (db && db !== 'M0 0') drawn++; + const r = fast._rawPxBounds; + if (r && r.intersects(rb) && !rb.contains(r)) clipped++; + }); + out.push({ layer, view: name, shapes: pairs.length, differ, drawn, clipped, first }); + } + if (layer === 'postnummer') { + // The clip fast path's boundary (#1091 review F3): a shape whose + // box overhangs the clip box by more than the stroke weight must + // be clipped, one that overhangs by less must not change. Skagen + // (9493) at z8.5, panned so each of its four sides crosses the + // clip box edge by -3 .. +3 px. + const sk = pairs.find((p) => p.k === '9493'); + const w = 0.6; + let cases = 0, differ = 0, first = null, overhangs = 0; + const sides = [['x', 'max', 1], ['x', 'min', -1], ['y', 'max', 1], ['y', 'min', -1]]; + map.setView(sk.fast.getBounds().getCenter(), 8.5, { animate: false }); + for (const [axis, edge, sign] of sides) { + for (let t = -3; t <= 3; t++) { + map.setView(sk.fast.getBounds().getCenter(), 8.5, { animate: false }); + const r = sk.fast._rawPxBounds, rb = sk.fast._renderer._bounds; + const gap = (r[edge][axis] - rb[edge][axis]) * sign; // + : the shape overhangs the clip box + const d = Math.round(gap - t) * sign; // pan until it overhangs by t px + map.panBy(axis === 'x' ? [d, 0] : [0, d], { animate: false }); + const r2 = sk.fast._rawPxBounds, rb2 = sk.fast._renderer._bounds; + const over = (r2[edge][axis] - rb2[edge][axis]) * sign; + if (over > w && over <= 3 * w + 1) overhangs++; + pairs.forEach(({ k, ref, fast }) => { + if (ref._path.getAttribute('d') !== fast._path.getAttribute('d')) { differ++; if (!first) first = k; } + }); + cases++; + } + } + out.push({ layer, view: 'Skagen edge z8.5', shapes: pairs.length, differ, drawn: cases, clipped: overhangs, first, edge: true }); + } + pairs.forEach(({ ref, fast }) => { map.removeLayer(ref); map.removeLayer(fast); }); + } + map.remove(); el.remove(); + return out; + }); + res.forEach((r) => console.log(` ${r.layer} ${r.view}: ${r.shapes} shapes, ${r.drawn} drawn, ${r.clipped} cut by the clip box, ${r.differ} differ${r.first ? ' (' + r.first + ')' : ''}`)); + assert(res.length === 11, 'views measured: ' + res.length); + res.forEach((r) => assert(r.differ === 0, `${r.layer} ${r.view}: ${r.differ} paths differ from L.polygon: ${r.first}`)); + assert(res.filter((r) => r.view !== 'fitted' && !r.edge).every((r) => r.clipped > 0), 'a zoomed view clipped nothing: the clipping branch was not exercised'); + assert(res.filter((r) => r.edge).every((r) => r.clipped > 0), 'no pan put Skagen between 1x and 3x the stroke weight over the clip box edge: the tolerance was not exercised'); + assert(res.filter((r) => r.view === 'fitted').every((r) => r.drawn === r.shapes), 'the fitted view did not draw every shape'); + await ctx.close(); + }); + await step(`perf: decode + draw at a plain ${CPU_THROTTLE}x CPU throttle, 375x560, <= ${PERF_BUDGET_MS} ms (kommune, postnummer)`, async () => { const out = [`CPU throttle ${CPU_THROTTLE}x (CDP Emulation.setCPUThrottlingRate), budget ${PERF_BUDGET_MS} ms on decode + draw`]; const fails = []; diff --git a/test-issue-740-m3b-dagi-packets-map.js b/test-issue-740-m3b-dagi-packets-map.js index 2a855abbe..46efb0328 100644 --- a/test-issue-740-m3b-dagi-packets-map.js +++ b/test-issue-740-m3b-dagi-packets-map.js @@ -108,6 +108,22 @@ test('decodeRings: deltas summed, times the quantum, swapped to [lat, lon]; hole sameLatLngs(d.bounds, [[55, 10], [57, 12.5]], 'bounds'); }); +test('decodeRings(resp, vertex): every vertex is vertex(lat, lon), in the same order, with the same numbers and bounds as the default (#1002 M3 perf)', () => { + const { DF } = loadDagi(); + const plainD = DF.decodeRings(squareResponse()); + const calls = []; + const d = DF.decodeRings(squareResponse(), (lat, lon) => { calls.push([lat, lon]); return { lat, lon }; }); + assert.strictEqual(calls.length, plainD.vertices, 'one call per vertex'); + assert.strictEqual(d.rings.length, plainD.rings.length); + d.rings.forEach((r, i) => { + assert.strictEqual(r.length, plainD.rings[i].length, 'ring ' + i); + r.forEach((v, k) => assert.ok(v.lat === plainD.rings[i][k][0] && v.lon === plainD.rings[i][k][1], + 'ring ' + i + ' vertex ' + k + ': ' + JSON.stringify(v) + ' vs ' + JSON.stringify(plainD.rings[i][k]))); + }); + same(d.bounds, plainD.bounds, 'bounds'); + assert.strictEqual(d.vertices, plainD.vertices); +}); + test('decodeRings: the closing vertex stays implicit (no first point repeated)', () => { const { DF } = loadDagi(); const r = DF.decodeRings(squareResponse()).rings[0]; diff --git a/tests/fake-leaflet.js b/tests/fake-leaflet.js index dbfd15627..f7793e9c2 100644 --- a/tests/fake-leaflet.js +++ b/tests/fake-leaflet.js @@ -1,30 +1,43 @@ /* tests/fake-leaflet.js — a recording Leaflet stub for the #1002 M3 * choropleth tests (test-dagi-choropleth.js, test-analytics-dagi-areas-map.js): - * L.polygon and L.featureGroup record their rings, style, setStyle calls, - * tooltip and handlers; the map records layers, removals and fitBounds. + * polygons and feature groups record their rings, bounds, style, setStyle + * calls, tooltip and handlers; the map records layers, removals and fitBounds. + * + * L.Polygon.extend and L.FeatureGroup.extend return constructors that make + * the same recording objects and keep the subclass's overrides on `proto`: + * the overridden Leaflet internals (projection, clipping) never run here; + * the real-Leaflet E2E checks what they draw. */ 'use strict'; function fakeLeaflet() { const made = []; + function LatLng(lat, lng) { this.lat = +lat; this.lng = +lng; } + function polygon(rings, style, bounds, proto) { + const p = { + rings, bounds: bounds || null, proto: proto || null, style: Object.assign({}, style), handlers: {}, tooltip: null, onMap: false, + setStyle(s) { Object.assign(this.style, s); this.styleCalls = (this.styleCalls || 0) + 1; return this; }, + bindTooltip(el) { this.tooltip = el; return this; }, + on(ev, fn) { this.handlers[ev] = fn; return this; }, + addTo(m) { m.layers.push(this); this.onMap = true; return this; }, + }; + made.push(p); + return p; + } + function featureGroup(list, o, proto) { + return { list, attribution: (o && o.attribution) || null, onMap: false, proto: proto || null, + tooltip: null, tooltipOptions: null, handlers: {}, + bindTooltip(fn, opts) { this.tooltip = fn; this.tooltipOptions = opts || null; return this; }, + on(ev, fn) { this.handlers[ev] = fn; return this; }, + addTo(m) { m.layers.push(this); this.onMap = true; return this; }, + getAttribution() { return this.attribution; } }; + } const L = { - polygon(rings, style) { - const p = { - rings, style: Object.assign({}, style), handlers: {}, tooltip: null, onMap: false, - setStyle(s) { Object.assign(this.style, s); this.styleCalls = (this.styleCalls || 0) + 1; return this; }, - bindTooltip(el) { this.tooltip = el; return this; }, - on(ev, fn) { this.handlers[ev] = fn; return this; }, - addTo(m) { m.layers.push(this); this.onMap = true; return this; }, - }; - made.push(p); - return p; - }, - featureGroup(list, o) { - const g = { list, attribution: (o && o.attribution) || null, onMap: false, - addTo(m) { m.layers.push(this); this.onMap = true; return this; }, - getAttribution() { return this.attribution; } }; - return g; - }, + LatLng, + polygon(rings, style) { return polygon(rings, style); }, + featureGroup(list, o) { return featureGroup(list, o); }, + Polygon: { extend(proto) { return function Shape(rings, style, bounds) { return polygon(rings, style, bounds, proto); }; } }, + FeatureGroup: { extend(proto) { return function Group(list, o) { return featureGroup(list, o, proto); }; } }, }; const map = { layers: [], fitted: null, removed: [], invalidated: 0, gone: false, invalidateSize() { this.invalidated++; },