Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
93 changes: 83 additions & 10 deletions public/dagi-choropleth.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,9 @@
* create({ L, map, doc, fetchJson, decode, readVar, escape, onPick }):
* fetchJson(query) a Promise of GET /api/config/dagi/polygons?<query>
* (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.
Expand Down Expand Up @@ -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).
Expand Down Expand Up @@ -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';
Expand Down Expand Up @@ -201,17 +274,16 @@
});
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();
var list = [];
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);
Expand All @@ -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 };
Expand Down Expand Up @@ -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 },
};
})();
9 changes: 6 additions & 3 deletions public/dagi-filter.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;
}
Expand Down
36 changes: 32 additions & 4 deletions test-dagi-choropleth.js
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand Down Expand Up @@ -261,14 +262,15 @@ test('the tooltip is a DOM node with textContent (a name cannot inject markup)',
const rows = [{ code: '0751', name: '<img src=x onerror=alert(1)>', 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('<img src=x onerror=alert(1)>'));
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);
});

Expand Down Expand Up @@ -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);
Expand Down
Loading
Loading