@veyforma/charts 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1104 @@
1
+ /*!
2
+ * Veyforma Exposure Heatmap v1.2.0
3
+ * A dependency-free heatmap that reveals concentrations, for example
4
+ * exposure by sector and country, or by sector and rating.
5
+ * Original work created for Veyforma. Contains no third-party code.
6
+ * Released under the MIT License. Copyright (c) 2026 Veyforma.
7
+ * https://github.com/veyforma/veyforma-charts
8
+ *
9
+ * File layout
10
+ * 1. Themes ............ colour scale, fonts and shapes (edit or add your own)
11
+ * 2. Helpers ........... colours, formatting, measuring
12
+ * 3. Calculation ....... pivot, ordering, "Other" grouping, concentration
13
+ * 4. Chart instance .... drawing, summary, legend, tooltips, keyboard, resizing
14
+ * 5. Export and notes .. data for the Veyforma Toolkit menu (optional file)
15
+ * 6. Public API ........ window.VeyHeatmap
16
+ *
17
+ * Load veyforma-toolkit.js as well to get the chart menu: full screen, print,
18
+ * PNG, JPEG, SVG, PDF, CSV and Excel downloads, copy and notes.
19
+ */
20
+ (function (root) {
21
+ "use strict";
22
+
23
+ var VERSION = "1.2.0";
24
+ var SVG_NS = "http://www.w3.org/2000/svg";
25
+ var instanceCount = 0;
26
+
27
+ /* ======================================================================
28
+ 1. THEMES
29
+ The colour scale runs from "low" through "mid" to "high". Scale colours
30
+ must be hex values, such as "#9a3412", so they can be blended.
31
+ ====================================================================== */
32
+ var BASE_THEME = {
33
+ low: "#fbf1ea", // smallest values
34
+ mid: "#ef8a54", // middle of the scale
35
+ high: "#9a3412", // largest values
36
+ empty: "#ffffff", // cells with no exposure (drawn with a dashed outline)
37
+ limit: "#111111", // outline of cells above the concentration limit
38
+ cellText: "#000000", // numbers on light cells (pure black and white keep 4.5:1 on any cell)
39
+ cellTextOnDark: "#ffffff", // numbers on dark cells
40
+ totalBar: "#111111", // data bars behind the totals
41
+ totalBarOpacity: 0.12, // strength of those data bars
42
+ headerText: "#555555", // row and column names
43
+ text: "#111111", // totals, legend and summary values
44
+ mutedText: "#6b6b6b", // secondary text
45
+ summaryBackground: "#f6f6f6", // background of the summary figures
46
+ background: "transparent", // chart background
47
+ tooltipBackground: "#111111",
48
+ tooltipText: "#ffffff",
49
+ focus: "#2563eb", // keyboard focus ring
50
+ fontFamily: "inherit", // "inherit" uses the page font
51
+ fontSize: 12, // base text size in pixels
52
+ cellRadius: 3, // corner rounding of cells
53
+ cellGap: 2 // space between cells in pixels
54
+ };
55
+
56
+ var THEMES = {
57
+ veyforma: {},
58
+ mono: {
59
+ low: "#f4f4f4", mid: "#9a9a9a", high: "#111111", empty: "#ffffff", limit: "#111111"
60
+ },
61
+ "colour-safe": {
62
+ low: "#eef3fb", mid: "#6d9be0", high: "#1d3f8f", limit: "#d9730d"
63
+ },
64
+ ocean: {
65
+ low: "#ecf6f8", mid: "#5aaec0", high: "#0c3b5e", limit: "#be123c", summaryBackground: "#eef5f8"
66
+ },
67
+ forest: {
68
+ low: "#f1f5ea", mid: "#8fb36b", high: "#22441a", limit: "#a8590b", summaryBackground: "#f2f4ee"
69
+ },
70
+ corporate: {
71
+ low: "#eef1f6", mid: "#8195b8", high: "#1e3a6e", limit: "#b91c1c", summaryBackground: "#f1f4f8", cellRadius: 0
72
+ },
73
+ midnight: {
74
+ background: "#111418", low: "#1e242c", mid: "#2f6aa8", high: "#9cd0ff", empty: "#111418",
75
+ limit: "#fbbf24", cellText: "#000000", cellTextOnDark: "#ffffff", totalBar: "#9cd0ff", totalBarOpacity: 0.18,
76
+ headerText: "#c3c9d2", text: "#f3f4f6", mutedText: "#a3abb8", summaryBackground: "#1b2027",
77
+ tooltipBackground: "#f3f4f6", tooltipText: "#111418", focus: "#93c5fd"
78
+ }
79
+ };
80
+
81
+ function resolveTheme(theme) {
82
+ if (theme == null || theme === "") theme = "veyforma";
83
+ if (typeof theme === "string") {
84
+ if (!THEMES.hasOwnProperty(theme)) {
85
+ warn('Unknown theme "' + theme + '". The "veyforma" theme is used instead.');
86
+ theme = "veyforma";
87
+ }
88
+ return assign({}, BASE_THEME, THEMES[theme]);
89
+ }
90
+ if (typeof theme !== "object") {
91
+ warn("The theme option must be a theme name or an object.");
92
+ return assign({}, BASE_THEME);
93
+ }
94
+ var base = theme["extends"] ? resolveTheme(theme["extends"]) : assign({}, BASE_THEME);
95
+ var out = assign(base, theme);
96
+ delete out["extends"];
97
+ ["low", "mid", "high", "empty"].forEach(function (k) {
98
+ if (!parseHex(out[k])) {
99
+ warn('Theme colour "' + k + '" must be a hex value such as "#9a3412". The default is used instead.');
100
+ out[k] = BASE_THEME[k];
101
+ }
102
+ });
103
+ return out;
104
+ }
105
+
106
+ /* ======================================================================
107
+ 2. HELPERS
108
+ ====================================================================== */
109
+ function assign(target) {
110
+ for (var i = 1; i < arguments.length; i++) {
111
+ var src = arguments[i];
112
+ if (src) for (var k in src) if (Object.prototype.hasOwnProperty.call(src, k)) target[k] = src[k];
113
+ }
114
+ return target;
115
+ }
116
+ function clamp(v, lo, hi) { return Math.min(hi, Math.max(lo, v)); }
117
+ function warn(msg) { if (root.console) root.console.warn("VeyHeatmap: " + msg); }
118
+ function svgEl(tag, attrs, parent) {
119
+ var n = document.createElementNS(SVG_NS, tag);
120
+ if (attrs) for (var k in attrs) if (attrs[k] != null) n.setAttribute(k, attrs[k]);
121
+ if (parent) parent.appendChild(n);
122
+ return n;
123
+ }
124
+ function htmlEl(tag, className, parent) {
125
+ var n = document.createElement(tag);
126
+ if (className) n.className = className;
127
+ if (parent) parent.appendChild(n);
128
+ return n;
129
+ }
130
+
131
+ function parseHex(hex) {
132
+ if (typeof hex !== "string") return null;
133
+ var h = hex.trim().replace(/^#/, "");
134
+ if (h.length === 3) h = h.split("").map(function (c) { return c + c; }).join("");
135
+ if (!/^[0-9a-fA-F]{6}$/.test(h)) return null;
136
+ var n = parseInt(h, 16);
137
+ return [(n >> 16) & 255, (n >> 8) & 255, n & 255];
138
+ }
139
+ function toHex(rgb) {
140
+ return "#" + rgb.map(function (v) { var s = Math.round(clamp(v, 0, 255)).toString(16); return s.length < 2 ? "0" + s : s; }).join("");
141
+ }
142
+ function mix(a, b, t) { return [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t, a[2] + (b[2] - a[2]) * t]; }
143
+ function makeRamp(theme) {
144
+ var lo = parseHex(theme.low), md = parseHex(theme.mid), hi = parseHex(theme.high);
145
+ return function (t) {
146
+ t = clamp(t, 0, 1);
147
+ return toHex(t < 0.5 ? mix(lo, md, t * 2) : mix(md, hi, (t - 0.5) * 2));
148
+ };
149
+ }
150
+ /** Contrast ratio between two hex colours (1 to 21), as defined by WCAG. */
151
+ function contrast(a, b) {
152
+ var x = luminance(a), y = luminance(b);
153
+ return (Math.max(x, y) + 0.05) / (Math.min(x, y) + 0.05);
154
+ }
155
+ function luminance(hex) {
156
+ var c = parseHex(hex);
157
+ if (!c) return 1;
158
+ var lin = c.map(function (v) { v /= 255; return v <= 0.03928 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4); });
159
+ return 0.2126 * lin[0] + 0.7152 * lin[1] + 0.0722 * lin[2];
160
+ }
161
+
162
+ var measureCtx = null;
163
+ function textWidth(text, sizePx, weight, family) {
164
+ if (!measureCtx) {
165
+ var c = document.createElement("canvas");
166
+ measureCtx = c.getContext && c.getContext("2d");
167
+ }
168
+ if (!measureCtx) return String(text).length * sizePx * 0.6;
169
+ measureCtx.font = (weight || 400) + " " + sizePx + "px " + family;
170
+ return measureCtx.measureText(String(text)).width;
171
+ }
172
+ function ellipsis(text, maxW, size, weight, family) {
173
+ text = String(text);
174
+ if (textWidth(text, size, weight, family) <= maxW) return text;
175
+ var lo = 0, hi = text.length;
176
+ while (lo < hi) {
177
+ var mid = Math.ceil((lo + hi) / 2);
178
+ if (textWidth(text.slice(0, mid) + "…", size, weight, family) <= maxW) lo = mid; else hi = mid - 1;
179
+ }
180
+ return lo > 0 ? text.slice(0, lo).replace(/\s+$/, "") + "…" : "";
181
+ }
182
+ function wrapTwo(text, maxW, size, weight, family) {
183
+ var words = String(text).split(/\s+/), lines = [], cur = "";
184
+ for (var i = 0; i < words.length; i++) {
185
+ var test = cur ? cur + " " + words[i] : words[i];
186
+ if (textWidth(test, size, weight, family) > maxW && cur) { lines.push(cur); cur = words[i]; }
187
+ else cur = test;
188
+ }
189
+ if (cur) lines.push(cur);
190
+ var ok = lines.length <= 2 && lines.every(function (l) { return textWidth(l, size, weight, family) <= maxW; });
191
+ return ok ? lines : null;
192
+ }
193
+ function pct(share) {
194
+ var v = Math.round(share * 10000) / 100;
195
+ return String(v) + "%";
196
+ }
197
+
198
+ function makeFormatters(data, locale) {
199
+ var decimals = data.decimals != null ? data.decimals : 0;
200
+ var prefix = data.prefix || "", suffix = data.suffix || "";
201
+ var cache = {};
202
+ function nf(key, opts) {
203
+ if (!cache[key]) cache[key] = new Intl.NumberFormat(locale || undefined, opts);
204
+ return cache[key];
205
+ }
206
+ function value(v, d) {
207
+ if (d == null) d = decimals;
208
+ var step = Math.pow(10, -d);
209
+ // A positive amount that would round to zero is shown as "<$0.1bn" rather than "$0.0bn".
210
+ if (v > 0 && v < step / 2) return "<" + prefix + nf("f" + d, { minimumFractionDigits: d, maximumFractionDigits: d }).format(step) + suffix;
211
+ var body = prefix + nf("f" + d, { minimumFractionDigits: d, maximumFractionDigits: d }).format(Math.abs(v)) + suffix;
212
+ if (v >= 0) return body;
213
+ // Negative numbers: "minus" (default) or "brackets", as in accounts.
214
+ return data.negatives === "brackets" ? "(" + body + ")" : "−" + body;
215
+ }
216
+ function compact(v) {
217
+ // With a unit suffix such as "m", shorten by dropping decimals rather than adding "K" or "M".
218
+ if (suffix) return value(v, 0);
219
+ return (v < 0 ? "−" : "") + prefix + nf("c", { notation: "compact", maximumFractionDigits: 1 }).format(Math.abs(v));
220
+ }
221
+ function percent(share, d) {
222
+ if (d == null) d = 1;
223
+ return nf("p" + d, { minimumFractionDigits: d, maximumFractionDigits: d }).format(share * 100) + "%";
224
+ }
225
+ function count(n) { return nf("n", { maximumFractionDigits: 0 }).format(n); }
226
+ return { value: value, compact: compact, percent: percent, count: count };
227
+ }
228
+
229
+ function fill(template, values) {
230
+ return String(template).replace(/\{(\w+)\}/g, function (m, k) { return values[k] != null ? values[k] : m; });
231
+ }
232
+
233
+ /* ======================================================================
234
+ 3. CALCULATION
235
+ Records such as { sector: "Energy", country: "Norway", rating: "BBB", value: 120 }
236
+ are summed into a grid. You choose which field forms the rows and which
237
+ the columns. Values must be zero or more.
238
+ ====================================================================== */
239
+ var OTHER_KEY = "\u0000other";
240
+
241
+ function normaliseData(data) {
242
+ if (Array.isArray(data.values)) {
243
+ var rl = data.rowLabels, cl = data.columnLabels;
244
+ var cached = aggCache && aggCache.get(data.values);
245
+ if (cached && cached.grid && cached.gridRows === rl && cached.gridCols === cl) return cached.grid;
246
+ if (!Array.isArray(rl) || !Array.isArray(cl)) throw new Error("VeyHeatmap: a values grid needs rowLabels and columnLabels.");
247
+ if (data.values.length !== rl.length) throw new Error("VeyHeatmap: values has " + data.values.length + " rows but rowLabels has " + rl.length + ".");
248
+ var recs = [];
249
+ data.values.forEach(function (row, r) {
250
+ if (!Array.isArray(row) || row.length !== cl.length) throw new Error("VeyHeatmap: row " + (r + 1) + " of values needs " + cl.length + " numbers.");
251
+ row.forEach(function (v, c) { recs.push({ row: rl[r], column: cl[c], value: v }); });
252
+ });
253
+ var grid = {
254
+ records: recs, rows: "row", columns: "column",
255
+ dimensions: {
256
+ row: { label: data.rowTitle || "Row", order: rl.slice(), ordered: true },
257
+ column: { label: data.columnTitle || "Column", order: cl.slice(), ordered: true }
258
+ }
259
+ };
260
+ if (aggCache) {
261
+ var bucket = aggCache.get(data.values) || {};
262
+ bucket.grid = grid; bucket.gridRows = rl; bucket.gridCols = cl;
263
+ aggCache.set(data.values, bucket);
264
+ }
265
+ return grid;
266
+ }
267
+ if (!Array.isArray(data.records) || !data.records.length) {
268
+ throw new Error("VeyHeatmap: data needs records, or values with rowLabels and columnLabels.");
269
+ }
270
+ var keys = Object.keys(data.records[0]).filter(function (k) { return k !== "value"; });
271
+ var dims = assign({}, data.dimensions || {});
272
+ keys.forEach(function (k) { if (!dims[k]) dims[k] = { label: k.charAt(0).toUpperCase() + k.slice(1) }; });
273
+ return { records: data.records, rows: data.rows || keys[0], columns: data.columns || keys[1], dimensions: dims };
274
+ }
275
+
276
+ // Sums are cached per records array (or values grid) and per pair of fields, so
277
+ // changing the theme, display mode, limit, grouping or screen size never re-reads
278
+ // the records. If you change the records in place, call chart.setData() to clear it.
279
+ var aggCache = typeof WeakMap === "function" ? new WeakMap() : null;
280
+
281
+ function aggregate(nd, rk, ck, source) {
282
+ var key = rk + "\u0001" + ck, bucket = aggCache && source ? aggCache.get(source) : null;
283
+ if (bucket && bucket[key]) return bucket[key];
284
+ var cells = new Map(), rowTot = new Map(), colTot = new Map(), total = 0;
285
+ var recs = nd.records, n = recs.length;
286
+ for (var i = 0; i < n; i++) {
287
+ var rec = recs[i], r = rec[rk], c = rec[ck];
288
+ if (r == null || r === "") throw new Error("VeyHeatmap: record " + (i + 1) + ' has no "' + rk + '".');
289
+ if (c == null || c === "") throw new Error("VeyHeatmap: record " + (i + 1) + ' has no "' + ck + '".');
290
+ var raw = rec.value, v = typeof raw === "number" ? raw : Number(raw);
291
+ if (raw === null || raw === undefined || raw === "" || !isFinite(v)) {
292
+ throw new Error("VeyHeatmap: record " + (i + 1) + " has no numeric value.");
293
+ }
294
+ if (v < 0) throw new Error("VeyHeatmap: record " + (i + 1) + " is negative. Exposure values must be zero or more.");
295
+ if (typeof r !== "string") r = String(r);
296
+ if (typeof c !== "string") c = String(c);
297
+ var row = cells.get(r);
298
+ if (!row) { row = new Map(); cells.set(r, row); rowTot.set(r, 0); }
299
+ row.set(c, (row.get(c) || 0) + v);
300
+ rowTot.set(r, rowTot.get(r) + v);
301
+ colTot.set(c, (colTot.get(c) || 0) + v);
302
+ total += v;
303
+ }
304
+ var toObj = function (m) { var o = {}; m.forEach(function (v, k) { o[k] = v; }); return o; };
305
+ var result = {
306
+ cell: function (r, c) { var row = cells.get(r); return row ? (row.get(c) || 0) : 0; },
307
+ rowTot: toObj(rowTot), colTot: toObj(colTot),
308
+ rowSeen: Array.from(rowTot.keys()), colSeen: Array.from(colTot.keys()), total: total
309
+ };
310
+ if (aggCache && source) {
311
+ if (!bucket) { bucket = {}; aggCache.set(source, bucket); }
312
+ bucket[key] = result;
313
+ }
314
+ return result;
315
+ }
316
+
317
+ function buildPivot(data, o, L) {
318
+ var nd = normaliseData(data);
319
+ var rk = o.rows || nd.rows, ck = o.columns || nd.columns;
320
+ if (!rk || !ck) throw new Error("VeyHeatmap: choose a field for the rows and a field for the columns.");
321
+ if (rk === ck) throw new Error('VeyHeatmap: rows and columns cannot both use "' + rk + '".');
322
+ var dR = assign({ label: rk }, nd.dimensions[rk]), dC = assign({ label: ck }, nd.dimensions[ck]);
323
+ var agg = aggregate(nd, rk, ck, Array.isArray(data.values) ? data.values : data.records);
324
+ var rowTot = agg.rowTot, colTot = agg.colTot, rowSeen = agg.rowSeen, colSeen = agg.colSeen, total = agg.total;
325
+
326
+ function arrange(seen, totals, dim, sortMode, top) {
327
+ var natural = seen.slice();
328
+ if (Array.isArray(dim.order)) {
329
+ var ord = dim.order.map(String);
330
+ natural.sort(function (a, b) {
331
+ var ia = ord.indexOf(a), ib = ord.indexOf(b);
332
+ if (ia < 0) ia = ord.length + seen.indexOf(a);
333
+ if (ib < 0) ib = ord.length + seen.indexOf(b);
334
+ return ia - ib;
335
+ });
336
+ }
337
+ var byTotal = natural.slice().sort(function (a, b) { return totals[b] - totals[a] || natural.indexOf(a) - natural.indexOf(b); });
338
+ var useTotal = sortMode === "total" || (sortMode !== "natural" && !dim.ordered);
339
+ var list = useTotal ? byTotal : natural;
340
+ var groups = list.map(function (k) { return { key: k, label: k, members: [k] }; });
341
+ if (top && top > 0 && list.length > top + 1) {
342
+ var keep = byTotal.slice(0, top);
343
+ var kept = list.filter(function (k) { return keep.indexOf(k) >= 0; });
344
+ var rest = list.filter(function (k) { return keep.indexOf(k) < 0; });
345
+ groups = kept.map(function (k) { return { key: k, label: k, members: [k] }; });
346
+ groups.push({ key: OTHER_KEY, label: fill(L.other, { count: rest.length }), members: rest, other: true });
347
+ }
348
+ groups.forEach(function (g) { g.total = g.members.reduce(function (s, k) { return s + totals[k]; }, 0); });
349
+ return groups;
350
+ }
351
+
352
+ var rows = arrange(rowSeen, rowTot, dR, o.sortRows, o.topRows);
353
+ var cols = arrange(colSeen, colTot, dC, o.sortColumns, o.topColumns);
354
+ var values = rows.map(function (rg) {
355
+ return cols.map(function (cg) {
356
+ var s = 0;
357
+ rg.members.forEach(function (r) { cg.members.forEach(function (c) { s += agg.cell(r, c); }); });
358
+ return s;
359
+ });
360
+ });
361
+ return { rowKey: rk, colKey: ck, rowDim: dR, colDim: dC, rows: rows, cols: cols, values: values, total: total };
362
+ }
363
+
364
+ function concentration(p, limitShare) {
365
+ var cells = [], hhi = 0;
366
+ p.values.forEach(function (row, r) {
367
+ row.forEach(function (v, c) {
368
+ var share = p.total > 0 ? v / p.total : 0;
369
+ hhi += share * share * 10000;
370
+ cells.push({ r: r, c: c, value: v, share: share });
371
+ });
372
+ });
373
+ cells.sort(function (a, b) { return b.value - a.value; });
374
+ var top5 = cells.slice(0, 5).reduce(function (s, x) { return s + x.share; }, 0);
375
+ var above = limitShare > 0 ? cells.filter(function (x) { return x.share > limitShare + 1e-12; }) : [];
376
+ return { hhi: hhi, effective: hhi > 0 ? 10000 / hhi : 0, largest: cells[0], top5: top5, above: above };
377
+ }
378
+
379
+ /* ======================================================================
380
+ 4. CHART INSTANCE
381
+ ====================================================================== */
382
+ var DEFAULT_OPTIONS = {
383
+ data: null, // required, see the user manual
384
+ theme: "veyforma", // theme name or theme object
385
+ locale: undefined, // e.g. "en-GB"; default is the visitor's locale
386
+ rows: undefined, // field for the rows; overrides data.rows
387
+ columns: undefined, // field for the columns; overrides data.columns
388
+ valueMode: "amount", // "amount", "shareOfTotal", "shareOfRow" or "shareOfColumn"
389
+ scale: "linear", // "linear" or "sqrt" (brings out small values)
390
+ sortRows: "auto", // "auto", "total" or "natural"
391
+ sortColumns: "auto", // "auto", "total" or "natural"
392
+ topRows: 0, // keep the largest N rows and group the rest as "Other"; 0 keeps all
393
+ topColumns: 0, // the same for columns
394
+ fit: "auto", // narrow screens: "auto" groups small columns into Other (scrolls ordered ones such as ratings), "group" or "scroll"
395
+ limit: undefined, // share of total, e.g. 0.05; overrides data.limit
396
+ totals: true, // show row and column totals
397
+ cellLabels: "auto", // "auto" shows numbers where they fit; true or false
398
+ cellHeight: undefined, // pixels; default 34 (28 on small screens)
399
+ summary: true, // show the key figures above the chart
400
+ legend: true, // show the colour legend
401
+ tooltip: true, // tooltips on hover, tap and keyboard focus
402
+ animate: true, // cells fade in on first draw and when the data changes
403
+ labels: null, // wording, see DEFAULT_LABELS
404
+ ariaLabel: undefined, // screen-reader description; default uses data.title
405
+ tooltipFormatter: null, // function (cell, format) -> string or array of strings
406
+ onClick: null, // function (cell, event)
407
+ caption: true, // explanation under the chart: true (built-in), your own text, or false
408
+ annotations: null, // notes, e.g. [{ row: "Energy", column: "United Kingdom", text: "Hedged in Q3" }]
409
+ onAnnotationsChange: null, // function (notes) called when a note is added or removed from the menu
410
+ toolbar: true // chart menu from veyforma-toolkit.js: true, false or toolbar settings
411
+ };
412
+ var DEFAULT_LABELS = {
413
+ total: "Total", other: "Other ({count})", empty: "No exposure",
414
+ totalExposure: "Total exposure", largest: "Largest concentration", hhi: "Concentration (HHI)",
415
+ aboveLimit: "Above limit", top5: "Top 5 cells",
416
+ hhiNote: "Like {n} equal-sized cells", aboveNote: "Cells above {limit} of total",
417
+ gridNote: "{rows} {rowDim} × {cols} {colDim}", top5Note: "Share of total exposure",
418
+ exposure: "Exposure", shareOfTotal: "Share of total", shareOfRow: "Share of {row}", shareOfColumn: "Share of {column}",
419
+ limitLegend: "Above {limit} limit", limitTip: "Above the {limit} limit", rowTotalTip: "{label} total",
420
+ scrollNote: "Scroll sideways to see all {columns}.",
421
+ groupNote: "Smaller {columns} are grouped as Other to fit this screen. Tap an Other cell to see which.",
422
+ includes: "Other includes {list}"
423
+ };
424
+
425
+ function injectStyles() {
426
+ if (document.getElementById("vhm-styles")) return;
427
+ var css =
428
+ ".vhm{position:relative;color:var(--vhm-text);background:var(--vhm-bg);font-family:var(--vhm-font);line-height:1.4}" +
429
+ ".vhm.vhm-filled{padding:14px 14px 8px;border-radius:10px}" +
430
+ ".vhm-summary{display:grid;grid-template-columns:repeat(auto-fit,minmax(130px,1fr));gap:8px;margin:0 0 12px}" +
431
+ ".vhm-stat{background:var(--vhm-summary-bg);border-radius:10px;padding:10px 12px;min-width:0}" +
432
+ ".vhm-stat-label{font-size:11px;letter-spacing:.04em;text-transform:uppercase;color:var(--vhm-muted)}" +
433
+ ".vhm-stat-value{font-size:20px;font-weight:650;letter-spacing:-.01em;margin-top:2px;font-variant-numeric:tabular-nums;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}" +
434
+ ".vhm-stat-note{font-size:11.5px;color:var(--vhm-muted);margin-top:1px;overflow-wrap:anywhere}" +
435
+ ".vhm-legend{display:flex;flex-wrap:wrap;align-items:center;gap:6px 18px;font-size:12px;margin:0 0 10px}" +
436
+ ".vhm-legend>span{display:inline-flex;align-items:center;gap:6px}" +
437
+ ".vhm-legend .vhm-ramp{display:inline-flex;flex-direction:column;align-items:stretch;gap:2px}" +
438
+ ".vhm-ramp-bar{width:150px;height:10px;border-radius:3px}" +
439
+ ".vhm-ramp-ticks{display:flex;justify-content:space-between;gap:8px;font-size:11px;color:var(--vhm-muted);font-variant-numeric:tabular-nums}" +
440
+ ".vhm-plot-host{overflow-x:auto;-webkit-overflow-scrolling:touch}" +
441
+ ".vhm-plot{display:block;overflow:visible;outline:none}" +
442
+ ".vhm-plot:focus-visible{outline:2px solid var(--vhm-focus);outline-offset:4px;border-radius:4px}" +
443
+ ".vhm-animate .vhm-cell{animation:vhm-fade .45s ease both}" +
444
+ "@keyframes vhm-fade{from{opacity:0}to{opacity:1}}" +
445
+ "@media (prefers-reduced-motion:reduce){.vhm-animate .vhm-cell{animation:none}}" +
446
+ ".vhm-scroll-note{font-size:11.5px;color:var(--vhm-muted);margin-top:4px}" +
447
+ ".vhm-tip{position:absolute;left:0;top:0;pointer-events:none;background:var(--vhm-tip-bg);color:var(--vhm-tip-text);" +
448
+ "font-size:12px;line-height:1.45;padding:8px 10px;border-radius:8px;opacity:0;transform:translateY(4px);" +
449
+ "transition:opacity .12s,transform .12s;white-space:nowrap;z-index:5}" +
450
+ ".vhm-tip.vhm-on{opacity:1;transform:none}" +
451
+ ".vhm-tip b{font-weight:600}" +
452
+ ".vhm-table{width:100%;border-collapse:collapse;font-size:13px}" +
453
+ ".vhm-table th,.vhm-table td{text-align:right;padding:7px 6px;border-bottom:1px solid rgba(127,127,127,.25);font-variant-numeric:tabular-nums;white-space:nowrap}" +
454
+ ".vhm-table th:first-child,.vhm-table td:first-child{text-align:left}" +
455
+ ".vhm-table th{font-weight:600;font-size:12px}" +
456
+ ".vhm-table tr.vhm-total td{font-weight:600}";
457
+ var style = document.createElement("style");
458
+ style.id = "vhm-styles";
459
+ style.appendChild(document.createTextNode(css));
460
+ (document.head || document.documentElement).appendChild(style);
461
+ }
462
+
463
+ function Chart(target, options) {
464
+ var container = typeof target === "string" ? document.querySelector(target) : target;
465
+ if (!container || container.nodeType !== 1) throw new Error("VeyHeatmap: container not found (" + target + ").");
466
+ if (!options || !options.data) throw new Error("VeyHeatmap: options.data is required.");
467
+ injectStyles();
468
+ this.id = ++instanceCount;
469
+ this.container = container;
470
+ this.options = assign({}, DEFAULT_OPTIONS, options);
471
+ this.element = htmlEl("div", "vhm");
472
+ this.summaryEl = htmlEl("div", "vhm-summary", this.element);
473
+ this.legendEl = htmlEl("div", "vhm-legend", this.element);
474
+ this.plotHost = htmlEl("div", "vhm-plot-host", this.element);
475
+ this.noteEl = htmlEl("div", "vhm-scroll-note", this.element);
476
+ this.tipEl = htmlEl("div", "vhm-tip", this.element);
477
+ this.tipEl.setAttribute("role", "tooltip");
478
+ this.tipEl.id = "vhm-tip-" + this.id;
479
+ container.appendChild(this.element);
480
+ this._animateNext = !!this.options.animate;
481
+ this._lastWidth = 0;
482
+ this._active = null;
483
+
484
+ var self = this;
485
+ if (root.ResizeObserver) {
486
+ this._observer = new root.ResizeObserver(function () {
487
+ var w = Math.round(self.element.clientWidth);
488
+ if (w && w !== self._lastWidth) self.redraw();
489
+ });
490
+ this._observer.observe(this.element);
491
+ } else {
492
+ this._onResize = function () { self.redraw(); };
493
+ root.addEventListener("resize", this._onResize);
494
+ }
495
+ this._onDocTap = function (e) { if (!self.element.contains(e.target)) self._hideTip(); };
496
+ document.addEventListener("pointerdown", this._onDocTap);
497
+ this.redraw();
498
+ if (this.options.toolbar !== false && root.VeyformaToolkit) this.toolkit = root.VeyformaToolkit.attach(this, this.options.toolbar);
499
+ }
500
+
501
+ Chart.prototype.update = function (partial) {
502
+ if (!partial) return this;
503
+ if (partial.data && partial.data !== this.options.data && this.options.animate) { this._animateNext = true; this._active = null; }
504
+ if (partial.rows || partial.columns || partial.topRows != null || partial.topColumns != null) this._active = null;
505
+ if (partial.animate === true) this._animateNext = true;
506
+ assign(this.options, partial);
507
+ return this.redraw();
508
+ };
509
+ /** Replaces the data and recalculates from scratch, even if the same records were changed in place. */
510
+ Chart.prototype.setData = function (data) {
511
+ if (aggCache && data) {
512
+ if (Array.isArray(data.records)) aggCache["delete"](data.records);
513
+ if (Array.isArray(data.values)) aggCache["delete"](data.values);
514
+ }
515
+ return this.update({ data: data });
516
+ };
517
+ Chart.prototype.setTheme = function (theme) { return this.update({ theme: theme }); };
518
+ Chart.prototype.getTheme = function () { return resolveTheme(this.options.theme); };
519
+
520
+ Chart.prototype._labels = function () { return assign({}, DEFAULT_LABELS, this.options.labels); };
521
+ Chart.prototype._limit = function () {
522
+ var o = this.options, l = o.limit !== undefined ? o.limit : (o.data.limit && o.data.limit.share);
523
+ l = Number(l);
524
+ return isFinite(l) && l > 0 && l < 1 ? l : 0;
525
+ };
526
+
527
+ /** The grid as plain objects: rows, columns, values and totals. */
528
+ Chart.prototype.getMatrix = function () {
529
+ var p = buildPivot(this.options.data, this.options, this._labels());
530
+ var strip = function (g) { return { key: g.key === OTHER_KEY ? null : g.key, label: g.label, total: g.total, other: !!g.other, members: g.members.slice() }; };
531
+ return {
532
+ rowField: p.rowKey, columnField: p.colKey,
533
+ rows: p.rows.map(strip), columns: p.cols.map(strip),
534
+ values: p.values.map(function (r) { return r.slice(); }), total: p.total
535
+ };
536
+ };
537
+
538
+ /** Concentration figures for the current grid. */
539
+ Chart.prototype.getStats = function () {
540
+ var p = buildPivot(this.options.data, assign({}, this.options, { topRows: 0, topColumns: 0 }), this._labels());
541
+ var lim = this._limit(), c = concentration(p, lim);
542
+ var cellOut = function (x) { return { row: p.rows[x.r].label, column: p.cols[x.c].label, value: x.value, share: x.share }; };
543
+ return {
544
+ total: p.total, rows: p.rows.length, columns: p.cols.length,
545
+ hhi: c.hhi, effectiveCells: c.effective, top5Share: c.top5,
546
+ largest: c.largest ? cellOut(c.largest) : null,
547
+ limit: lim || null, aboveLimit: c.above.map(cellOut)
548
+ };
549
+ };
550
+
551
+ Chart.prototype.createTable = function () {
552
+ var o = this.options, data = o.data, L = this._labels();
553
+ var p = buildPivot(data, o, L), f = makeFormatters(data, o.locale);
554
+ var table = document.createElement("table");
555
+ table.className = "vhm-table";
556
+ if (data.title) {
557
+ var cap = htmlEl("caption", null, table);
558
+ cap.textContent = data.title;
559
+ cap.style.cssText = "text-align:left;font-weight:600;padding:0 6px 6px";
560
+ }
561
+ var head = htmlEl("tr", null, htmlEl("thead", null, table));
562
+ var th0 = htmlEl("th", null, head); th0.scope = "col"; th0.textContent = p.rowDim.label;
563
+ p.cols.forEach(function (c) { var th = htmlEl("th", null, head); th.scope = "col"; th.textContent = c.label; });
564
+ var thT = htmlEl("th", null, head); thT.scope = "col"; thT.textContent = L.total;
565
+ var body = htmlEl("tbody", null, table);
566
+ p.rows.forEach(function (r, ri) {
567
+ var tr = htmlEl("tr", null, body);
568
+ var th = htmlEl("th", null, tr); th.scope = "row"; th.textContent = r.label; th.style.textAlign = "left"; th.style.fontWeight = "400";
569
+ p.values[ri].forEach(function (v) { htmlEl("td", null, tr).textContent = v ? f.value(v) : "—"; });
570
+ htmlEl("td", null, tr).textContent = f.value(r.total);
571
+ });
572
+ var trT = htmlEl("tr", "vhm-total", body);
573
+ htmlEl("td", null, trT).textContent = L.total;
574
+ p.cols.forEach(function (c) { htmlEl("td", null, trT).textContent = f.value(c.total); });
575
+ htmlEl("td", null, trT).textContent = f.value(p.total);
576
+ return table;
577
+ };
578
+
579
+ Chart.prototype.destroy = function () {
580
+ if (this.toolkit) this.toolkit.destroy();
581
+ if (this._observer) this._observer.disconnect();
582
+ if (this._onResize) root.removeEventListener("resize", this._onResize);
583
+ document.removeEventListener("pointerdown", this._onDocTap);
584
+ if (this.element.parentNode) this.element.parentNode.removeChild(this.element);
585
+ };
586
+
587
+ Chart.prototype._hideTip = function () {
588
+ this.tipEl.classList.remove("vhm-on");
589
+ if (this._focusRect) this._focusRect.setAttribute("opacity", 0);
590
+ if (this._boldReset) this._boldReset();
591
+ };
592
+
593
+ Chart.prototype._placeTip = function (lines, anchor, evt) {
594
+ var tip = this.tipEl;
595
+ tip.textContent = "";
596
+ lines.forEach(function (ln, i) {
597
+ if (i) tip.appendChild(document.createElement("br"));
598
+ var node = i === 0 ? document.createElement("b") : document.createTextNode("");
599
+ node.textContent = ln;
600
+ tip.appendChild(node);
601
+ });
602
+ var box = this.element.getBoundingClientRect();
603
+ var px = evt && evt.clientX ? evt.clientX : anchor.left + anchor.width / 2;
604
+ var py = evt && evt.clientY ? evt.clientY : anchor.top;
605
+ tip.classList.add("vhm-on");
606
+ var tw = tip.offsetWidth, th = tip.offsetHeight;
607
+ var left = clamp(px - box.left - tw / 2, 4, Math.max(4, box.width - tw - 4));
608
+ var top = py - box.top - th - 14;
609
+ if (top < 0) top = (anchor.bottom != null ? anchor.bottom : py) - box.top + 10;
610
+ tip.style.left = left + "px";
611
+ tip.style.top = top + "px";
612
+ };
613
+
614
+ Chart.prototype.redraw = function () {
615
+ var o = this.options, data = o.data, self = this;
616
+ var theme = resolveTheme(o.theme), L = this._labels();
617
+ var p = buildPivot(data, o, L);
618
+ var f = makeFormatters(data, o.locale);
619
+ // Concentration figures always use the full grid, so grouping into Other never changes them.
620
+ var pFull = (o.topRows > 0 || o.topColumns > 0) ? buildPivot(data, assign({}, o, { topRows: 0, topColumns: 0 }), L) : p;
621
+ var lim = this._limit(), conc = concentration(pFull, lim);
622
+ var el = this.element, ramp = makeRamp(theme);
623
+ var paper = theme.background && theme.background !== "transparent" ? theme.background : "#ffffff";
624
+ var family = theme.fontFamily === "inherit"
625
+ ? (root.getComputedStyle ? root.getComputedStyle(this.container).fontFamily : "sans-serif")
626
+ : theme.fontFamily;
627
+ var st = el.style;
628
+ st.setProperty("--vhm-text", theme.text);
629
+ st.setProperty("--vhm-muted", theme.mutedText);
630
+ st.setProperty("--vhm-bg", theme.background);
631
+ st.setProperty("--vhm-font", family);
632
+ st.setProperty("--vhm-focus", theme.focus);
633
+ st.setProperty("--vhm-tip-bg", theme.tooltipBackground);
634
+ st.setProperty("--vhm-tip-text", theme.tooltipText);
635
+ st.setProperty("--vhm-summary-bg", theme.summaryBackground);
636
+ el.classList.toggle("vhm-filled", !!theme.background && theme.background !== "transparent");
637
+ el.classList.toggle("vhm-animate", !!this._animateNext);
638
+
639
+ // ---- Fit the columns to the space ------------------------------------------
640
+ var hostW = Math.max(this.plotHost.clientWidth || el.clientWidth || 0, 280);
641
+ this._lastWidth = Math.round(el.clientWidth);
642
+ var narrow = hostW < 560;
643
+ var fs = Number(theme.fontSize) || 12;
644
+ var headSize = narrow ? fs - 1.5 : fs - 0.5, cellSize = narrow ? fs - 2 : fs - 1;
645
+ var cellH = o.cellHeight || (narrow ? 28 : 34);
646
+ var gap = Math.max(0, Number(theme.cellGap) || 0);
647
+ var minCell = narrow ? 26 : 34;
648
+ var rowLabelFull = Math.max.apply(null, p.rows.map(function (r) { return textWidth(r.label, headSize, 400, family); }));
649
+ var labelW = Math.min(Math.ceil(rowLabelFull) + 12, Math.round(hostW * (narrow ? 0.3 : 0.26)));
650
+ var totalsW = o.totals ? Math.max(narrow ? 50 : 70, Math.ceil(textWidth(f.value(Math.max.apply(null, p.rows.map(function (r) { return r.total; }))), fs - 1, 600, family)) + 12) : 0;
651
+ if (o.totals && narrow) totalsW = Math.min(totalsW, 64);
652
+ var totalsGap = o.totals ? 8 : 0;
653
+ var gridW = hostW - labelW - totalsGap - totalsW - 2;
654
+ var fitMode = o.fit || "auto", grouped = false;
655
+ var fitsN = Math.floor(gridW / minCell);
656
+ var canGroup = fitMode === "group" || (fitMode === "auto" && !p.colDim.ordered && !(o.topColumns > 0));
657
+ if (canGroup && p.cols.length > fitsN && fitsN >= 3) {
658
+ p = buildPivot(data, assign({}, o, { topColumns: fitsN - 1 }), L);
659
+ grouped = true;
660
+ }
661
+
662
+ var nR = p.rows.length, nC = p.cols.length;
663
+ var rowWord = (p.rowDim.plural || p.rowDim.label).toLowerCase();
664
+ var colWord = (p.colDim.plural || p.colDim.label).toLowerCase();
665
+
666
+ // ---- Metric shown in the cells ------------------------------------------
667
+ var mode = o.valueMode;
668
+ if (["amount", "shareOfTotal", "shareOfRow", "shareOfColumn"].indexOf(mode) < 0) mode = "amount";
669
+ var metric = function (r, c) {
670
+ var v = p.values[r][c];
671
+ if (mode === "shareOfTotal") return p.total ? v / p.total : 0;
672
+ if (mode === "shareOfRow") return p.rows[r].total ? v / p.rows[r].total : 0;
673
+ if (mode === "shareOfColumn") return p.cols[c].total ? v / p.cols[c].total : 0;
674
+ return v;
675
+ };
676
+ var maxM = 0;
677
+ for (var r0 = 0; r0 < nR; r0++) for (var c0 = 0; c0 < nC; c0++) maxM = Math.max(maxM, metric(r0, c0));
678
+ var useSqrt = o.scale === "sqrt";
679
+ var tOf = function (m) { if (maxM <= 0) return 0; var t = m / maxM; return useSqrt ? Math.sqrt(t) : t; };
680
+ var mText = function (m, short) {
681
+ if (mode === "amount") return short ? f.compact(m) : f.value(m);
682
+ return f.percent(m, short ? 0 : 1);
683
+ };
684
+
685
+ // ---- Summary --------------------------------------------------------------
686
+ var sum = this.summaryEl;
687
+ sum.textContent = "";
688
+ sum.style.display = o.summary ? "" : "none";
689
+ if (o.summary) {
690
+ var stat = function (label, value, note) {
691
+ var d = htmlEl("div", "vhm-stat", sum);
692
+ htmlEl("div", "vhm-stat-label", d).textContent = label;
693
+ htmlEl("div", "vhm-stat-value", d).textContent = value;
694
+ if (note) htmlEl("div", "vhm-stat-note", d).textContent = note;
695
+ };
696
+ stat(L.totalExposure, f.value(p.total), fill(L.gridNote, { rows: pFull.rows.length, rowDim: rowWord, cols: pFull.cols.length, colDim: colWord }));
697
+ if (conc.largest) {
698
+ stat(L.largest, f.percent(conc.largest.share), pFull.rows[conc.largest.r].label + " × " + pFull.cols[conc.largest.c].label + " · " + f.value(conc.largest.value));
699
+ }
700
+ stat(L.hhi, f.count(conc.hhi), fill(L.hhiNote, { n: f.count(Math.round(conc.effective)) }));
701
+ if (lim) stat(L.aboveLimit, f.count(conc.above.length), fill(L.aboveNote, { limit: pct(lim) }));
702
+ else stat(L.top5, f.percent(conc.top5), L.top5Note);
703
+ }
704
+
705
+ // ---- Legend --------------------------------------------------------------
706
+ var legend = this.legendEl;
707
+ legend.textContent = "";
708
+ legend.style.display = o.legend ? "" : "none";
709
+ if (o.legend) {
710
+ var rampWrap = htmlEl("span", "vhm-ramp", legend);
711
+ var bar = htmlEl("span", "vhm-ramp-bar", rampWrap);
712
+ bar.style.background = "linear-gradient(to right," + [0, 0.25, 0.5, 0.75, 1].map(function (t) { return ramp(t); }).join(",") + ")";
713
+ var ticks = htmlEl("span", "vhm-ramp-ticks", rampWrap);
714
+ var midVal = useSqrt ? maxM * 0.25 : maxM * 0.5;
715
+ [0, midVal, maxM].forEach(function (v) { htmlEl("span", null, ticks).textContent = mText(v, true); });
716
+ var emptyItem = htmlEl("span", null, legend);
717
+ var es = svgEl("svg", { width: 14, height: 14, "aria-hidden": "true" }, emptyItem);
718
+ svgEl("rect", { x: 1, y: 1, width: 12, height: 12, rx: 2, fill: theme.empty, stroke: theme.mutedText, "stroke-opacity": 0.45, "stroke-dasharray": "2 2" }, es);
719
+ emptyItem.appendChild(document.createTextNode(L.empty));
720
+ if (lim) {
721
+ var limItem = htmlEl("span", null, legend);
722
+ var ls = svgEl("svg", { width: 14, height: 14, "aria-hidden": "true" }, limItem);
723
+ svgEl("rect", { x: 1.5, y: 1.5, width: 11, height: 11, rx: 2, fill: ramp(0.7), stroke: theme.limit, "stroke-width": 2 }, ls);
724
+ svgEl("rect", { x: 3.5, y: 3.5, width: 7, height: 7, rx: 1, fill: "none", stroke: paper, "stroke-width": 1 }, ls);
725
+ limItem.appendChild(document.createTextNode(fill(L.limitLegend, { limit: pct(lim) })));
726
+ }
727
+ }
728
+
729
+ // ---- Layout ----------------------------------------------------------------
730
+ var cellW = gridW / nC;
731
+ var scrolls = false;
732
+ if (cellW < minCell) { cellW = minCell; scrolls = true; }
733
+ gridW = cellW * nC;
734
+
735
+ // Column headers: one or two lines if they fit, otherwise tilted.
736
+ var colLines = p.cols.map(function (c) { return wrapTwo(c.label, cellW - 4, headSize, 400, family); });
737
+ var tiltCols = colLines.some(function (x) { return x === null; });
738
+ var colLabelMax = Math.max.apply(null, p.cols.map(function (c) { return textWidth(c.label, headSize, 400, family); }));
739
+ var maxColLabel = Math.min(colLabelMax, 140);
740
+ var headerH = tiltCols
741
+ ? Math.ceil(maxColLabel * 0.7071 + headSize + 10)
742
+ : (Math.max.apply(null, colLines.map(function (x) { return x.length; })) * (headSize + 3) + 10);
743
+ var tiltOverflow = tiltCols ? Math.max(0, maxColLabel * 0.7071 - totalsW - totalsGap) : 0;
744
+ var W = labelW + gridW + totalsGap + totalsW + 2 + tiltOverflow;
745
+ if (W > hostW + 0.5) scrolls = true;
746
+ var gridTop = headerH;
747
+ var totalsRowH = o.totals ? cellH : 0;
748
+ var H = gridTop + nR * cellH + (o.totals ? totalsGap + totalsRowH : 0) + 4;
749
+ var x0 = labelW;
750
+ var cx = function (c) { return x0 + c * cellW; };
751
+ var cy = function (r) { return gridTop + r * cellH; };
752
+
753
+ // ---- SVG ----------------------------------------------------------------------
754
+ this.plotHost.textContent = "";
755
+ this.noteEl.textContent = scrolls ? fill(L.scrollNote, { columns: colWord }) : grouped ? fill(L.groupNote, { columns: colWord }) : "";
756
+ this.noteEl.style.display = scrolls || grouped ? "" : "none";
757
+ var svg = svgEl("svg", {
758
+ "class": "vhm-plot", viewBox: "0 0 " + W + " " + H, width: W, height: H, tabindex: 0, role: "img",
759
+ "aria-label": o.ariaLabel || [data.title, p.rowDim.label + " by " + p.colDim.label,
760
+ conc.largest ? L.largest + ": " + pFull.rows[conc.largest.r].label + " × " + pFull.cols[conc.largest.c].label + ", " + f.percent(conc.largest.share) : null].filter(Boolean).join(". ")
761
+ }, this.plotHost);
762
+ if (!scrolls) { svg.style.width = "100%"; svg.style.height = "auto"; }
763
+ var txt = function (attrs, content, parent) {
764
+ var t = svgEl("text", assign({ "font-family": family }, attrs), parent || svg);
765
+ t.textContent = content;
766
+ return t;
767
+ };
768
+
769
+ // Column headers
770
+ var colHeadEls = [];
771
+ p.cols.forEach(function (c, ci) {
772
+ var mx = cx(ci) + cellW / 2;
773
+ var g = svgEl("g", null, svg);
774
+ if (tiltCols) {
775
+ var by = headerH - 6;
776
+ txt({ x: mx - 2, y: by, "text-anchor": "start", transform: "rotate(-45 " + (mx - 2) + " " + by + ")",
777
+ "font-size": headSize, fill: c.other ? theme.mutedText : theme.headerText }, ellipsis(c.label, 140, headSize, 400, family), g);
778
+ } else {
779
+ var lines = colLines[ci];
780
+ lines.forEach(function (ln, k) {
781
+ txt({ x: mx, y: headerH - 6 - (lines.length - 1 - k) * (headSize + 3), "text-anchor": "middle", "font-size": headSize,
782
+ fill: c.other ? theme.mutedText : theme.headerText }, ln, g);
783
+ });
784
+ }
785
+ colHeadEls.push(g);
786
+ });
787
+ if (o.totals) {
788
+ txt({ x: x0 + gridW + totalsGap + totalsW - 4, y: headerH - 6, "text-anchor": "end", "font-size": headSize, "font-weight": 600, fill: theme.text }, L.total);
789
+ }
790
+
791
+ // Row headers
792
+ var rowHeadEls = p.rows.map(function (r, ri) {
793
+ var label = ellipsis(r.label, labelW - 12, headSize, 400, family);
794
+ var t = txt({ x: labelW - 8, y: cy(ri) + cellH / 2 + headSize * 0.35, "text-anchor": "end", "font-size": headSize,
795
+ fill: r.other ? theme.mutedText : theme.headerText }, label);
796
+ if (label !== r.label) { var tt = svgEl("title", null, t); tt.textContent = r.label; }
797
+ return t;
798
+ });
799
+ if (o.totals) {
800
+ txt({ x: labelW - 8, y: cy(nR) + totalsGap + cellH / 2 + headSize * 0.35, "text-anchor": "end", "font-size": headSize, "font-weight": 600, fill: theme.text }, L.total);
801
+ }
802
+
803
+ // Cells
804
+ var cellsG = svgEl("g", null, svg);
805
+ var showLabels = o.cellLabels === true || (o.cellLabels === "auto");
806
+ for (var r = 0; r < nR; r++) {
807
+ for (var c = 0; c < nC; c++) {
808
+ var v = p.values[r][c], m = metric(r, c);
809
+ var colour = v > 0 ? ramp(tOf(m)) : theme.empty;
810
+ var rect = svgEl("rect", { x: cx(c) + gap / 2, y: cy(r) + gap / 2, width: Math.max(cellW - gap, 1), height: Math.max(cellH - gap, 1),
811
+ rx: Math.min(theme.cellRadius, cellW / 4), fill: colour, "class": "vhm-cell", "data-r": r, "data-c": c }, cellsG);
812
+ // An empty cell gets a dashed outline, so "no exposure" never looks like a very small exposure.
813
+ if (!(v > 0)) { rect.setAttribute("stroke", theme.mutedText); rect.setAttribute("stroke-opacity", 0.45); rect.setAttribute("stroke-dasharray", "2 2"); rect.setAttribute("stroke-width", 1); }
814
+ rect.style.animationDelay = Math.min((r + c) * 18, 500) + "ms";
815
+ if (lim && p.total > 0 && v / p.total > lim + 1e-12 && !p.rows[r].other && !p.cols[c].other) {
816
+ svgEl("rect", { x: cx(c) + gap / 2 + 1, y: cy(r) + gap / 2 + 1, width: Math.max(cellW - gap - 2, 1), height: Math.max(cellH - gap - 2, 1),
817
+ rx: Math.min(theme.cellRadius, cellW / 4), fill: "none", stroke: theme.limit, "stroke-width": 2, "pointer-events": "none" }, cellsG);
818
+ svgEl("rect", { x: cx(c) + gap / 2 + 3, y: cy(r) + gap / 2 + 3, width: Math.max(cellW - gap - 6, 1), height: Math.max(cellH - gap - 6, 1),
819
+ rx: Math.max(0, Math.min(theme.cellRadius, cellW / 4) - 1), fill: "none", stroke: paper, "stroke-width": 1, "pointer-events": "none" }, cellsG);
820
+ }
821
+ if (showLabels && v > 0 && cellH - gap >= 16) {
822
+ var room = cellW - gap - 8;
823
+ var label = mText(m, false);
824
+ if (textWidth(label, cellSize, 500, family) > room) label = mText(m, true);
825
+ if (textWidth(label, cellSize, 500, family) <= room) {
826
+ // Use whichever text colour stands out more from this cell, so numbers stay readable on mid-tones too.
827
+ var onCell = contrast(colour, theme.cellTextOnDark) > contrast(colour, theme.cellText) ? theme.cellTextOnDark : theme.cellText;
828
+ txt({ x: cx(c) + cellW / 2, y: cy(r) + cellH / 2 + cellSize * 0.35, "text-anchor": "middle", "font-size": cellSize, "font-weight": 500,
829
+ fill: onCell, "pointer-events": "none", "class": "vhm-cell-label" }, label, cellsG);
830
+ }
831
+ }
832
+ }
833
+ }
834
+
835
+ // Totals as data bars
836
+ var totalsG = null;
837
+ if (o.totals) {
838
+ totalsG = svgEl("g", null, svg);
839
+ var maxRow = Math.max.apply(null, p.rows.map(function (x) { return x.total; })) || 1;
840
+ var maxCol = Math.max.apply(null, p.cols.map(function (x) { return x.total; })) || 1;
841
+ var tx0 = x0 + gridW + totalsGap;
842
+ p.rows.forEach(function (rg, ri) {
843
+ var w = Math.max(2, (totalsW - 2) * rg.total / maxRow);
844
+ svgEl("rect", { x: tx0, y: cy(ri) + gap / 2 + 3, width: w, height: cellH - gap - 6, rx: 2, fill: theme.totalBar, "fill-opacity": theme.totalBarOpacity,
845
+ "data-tr": ri }, totalsG);
846
+ var label = f.value(rg.total);
847
+ if (textWidth(label, fs - 1, 600, family) > totalsW - 6) label = f.compact(rg.total);
848
+ txt({ x: tx0 + totalsW - 4, y: cy(ri) + cellH / 2 + (fs - 1) * 0.35, "text-anchor": "end", "font-size": fs - 1, "font-weight": 600, fill: theme.text, "pointer-events": "none" }, label, totalsG);
849
+ });
850
+ var ty = cy(nR) + totalsGap;
851
+ p.cols.forEach(function (cg, ci) {
852
+ var h = Math.max(2, (cellH - gap - 4) * cg.total / maxCol);
853
+ svgEl("rect", { x: cx(ci) + gap / 2 + 2, y: ty + cellH - gap / 2 - 2 - h, width: Math.max(cellW - gap - 4, 1), height: h, rx: 2,
854
+ fill: theme.totalBar, "fill-opacity": theme.totalBarOpacity, "data-tc": ci }, totalsG);
855
+ var label = f.value(cg.total);
856
+ if (textWidth(label, cellSize, 600, family) > cellW - gap - 6) label = f.compact(cg.total);
857
+ if (textWidth(label, cellSize, 600, family) <= cellW - gap - 6) {
858
+ txt({ x: cx(ci) + cellW / 2, y: ty + cellH / 2 + cellSize * 0.35, "text-anchor": "middle", "font-size": cellSize, "font-weight": 600, fill: theme.text, "pointer-events": "none" }, label, totalsG);
859
+ }
860
+ });
861
+ var grand = f.value(p.total);
862
+ if (textWidth(grand, fs - 1, 700, family) > totalsW - 6) grand = f.compact(p.total);
863
+ txt({ x: tx0 + totalsW - 4, y: ty + cellH / 2 + (fs - 1) * 0.35, "text-anchor": "end", "font-size": fs - 1, "font-weight": 700, fill: theme.text }, grand);
864
+ }
865
+
866
+ // Focus ring for hover and keyboard
867
+ this._focusRect = svgEl("rect", { x: 0, y: 0, width: 0, height: 0, rx: Math.min(theme.cellRadius + 1, 6), fill: "none", stroke: theme.text, "stroke-width": 2, opacity: 0, "pointer-events": "none" }, svg);
868
+
869
+ // ---- Interaction ------------------------------------------------------------
870
+ var cellInfo = function (r, c) {
871
+ var v = p.values[r][c];
872
+ return {
873
+ row: p.rows[r].label, column: p.cols[c].label, rowIndex: r, columnIndex: c, value: v,
874
+ shareOfTotal: p.total ? v / p.total : 0,
875
+ shareOfRow: p.rows[r].total ? v / p.rows[r].total : 0,
876
+ shareOfColumn: p.cols[c].total ? v / p.cols[c].total : 0,
877
+ aboveLimit: !!(lim && p.total && v / p.total > lim + 1e-12 && !p.rows[r].other && !p.cols[c].other),
878
+ rowMembers: p.rows[r].members.slice(), columnMembers: p.cols[c].members.slice()
879
+ };
880
+ };
881
+ var bolded = [];
882
+ this._boldReset = function () { bolded.forEach(function (n) { n.removeAttribute("font-weight"); }); bolded = []; };
883
+ var boldHeaders = function (r, c) {
884
+ self._boldReset();
885
+ var rt = rowHeadEls[r]; rt.setAttribute("font-weight", 600); bolded.push(rt);
886
+ Array.prototype.forEach.call(colHeadEls[c].childNodes, function (n) { n.setAttribute("font-weight", 600); bolded.push(n); });
887
+ };
888
+ var showCell = function (r, c, evt) {
889
+ self._active = [r, c];
890
+ self._focusRect.setAttribute("x", cx(c) + gap / 2 - 1);
891
+ self._focusRect.setAttribute("y", cy(r) + gap / 2 - 1);
892
+ self._focusRect.setAttribute("width", cellW - gap + 2);
893
+ self._focusRect.setAttribute("height", cellH - gap + 2);
894
+ self._focusRect.setAttribute("opacity", 1);
895
+ boldHeaders(r, c);
896
+ if (!o.tooltip) return;
897
+ var info = cellInfo(r, c), lines;
898
+ if (typeof o.tooltipFormatter === "function") {
899
+ lines = o.tooltipFormatter(info, f);
900
+ if (!Array.isArray(lines)) lines = [String(lines)];
901
+ } else {
902
+ lines = [info.row + " × " + info.column];
903
+ if (!info.value) lines.push(L.empty);
904
+ else {
905
+ lines.push(L.exposure + ": " + f.value(info.value));
906
+ lines.push(L.shareOfTotal + ": " + f.percent(info.shareOfTotal));
907
+ lines.push(fill(L.shareOfRow, { row: info.row }) + ": " + f.percent(info.shareOfRow));
908
+ lines.push(fill(L.shareOfColumn, { column: info.column }) + ": " + f.percent(info.shareOfColumn));
909
+ if (info.aboveLimit) lines.push(fill(L.limitTip, { limit: pct(lim) }));
910
+ }
911
+ if (p.rows[r].other) lines.push(fill(L.includes, { list: p.rows[r].members.join(", ") }));
912
+ if (p.cols[c].other) lines.push(fill(L.includes, { list: p.cols[c].members.join(", ") }));
913
+ }
914
+ var rb = svg.getBoundingClientRect(), k = rb.width / W;
915
+ self._placeTip(lines, { left: rb.left + cx(c) * k, top: rb.top + cy(r) * k, width: cellW * k, bottom: rb.top + (cy(r) + cellH) * k }, evt);
916
+ };
917
+ var totalTip = function (isRow, i, evt) {
918
+ var g = isRow ? p.rows[i] : p.cols[i];
919
+ var lines = [fill(L.rowTotalTip, { label: g.label }), f.value(g.total) + " · " + f.percent(p.total ? g.total / p.total : 0) + " " + L.shareOfTotal.toLowerCase()];
920
+ if (g.other) lines.push(g.members.join(", "));
921
+ self._placeTip(lines, { left: evt.clientX, top: evt.clientY, width: 0 }, evt);
922
+ };
923
+
924
+ cellsG.addEventListener("mousemove", function (e) {
925
+ var t = e.target; if (!t.hasAttribute || !t.hasAttribute("data-r")) return;
926
+ showCell(+t.getAttribute("data-r"), +t.getAttribute("data-c"), e);
927
+ });
928
+ cellsG.addEventListener("pointerdown", function (e) {
929
+ var t = e.target; if (!t.hasAttribute || !t.hasAttribute("data-r")) return;
930
+ showCell(+t.getAttribute("data-r"), +t.getAttribute("data-c"), e);
931
+ });
932
+ cellsG.addEventListener("mouseleave", function () { self._hideTip(); });
933
+ if (typeof o.onClick === "function") {
934
+ cellsG.style.cursor = "pointer";
935
+ cellsG.addEventListener("click", function (e) {
936
+ var t = e.target; if (!t.hasAttribute || !t.hasAttribute("data-r")) return;
937
+ o.onClick(cellInfo(+t.getAttribute("data-r"), +t.getAttribute("data-c")), e);
938
+ });
939
+ }
940
+ if (totalsG) {
941
+ totalsG.addEventListener("mousemove", function (e) {
942
+ var t = e.target;
943
+ if (t.hasAttribute && t.hasAttribute("data-tr")) totalTip(true, +t.getAttribute("data-tr"), e);
944
+ else if (t.hasAttribute && t.hasAttribute("data-tc")) totalTip(false, +t.getAttribute("data-tc"), e);
945
+ });
946
+ totalsG.addEventListener("mouseleave", function () { self._hideTip(); });
947
+ }
948
+
949
+ // Positions kept for notes
950
+ this._geom = { rows: p.rows, cols: p.cols, cx: cx, cy: cy, cellW: cellW, cellH: cellH, gap: gap };
951
+
952
+ svg.setAttribute("aria-describedby", this.tipEl.id);
953
+ var start = [0, 0];
954
+ if (conc.largest) {
955
+ var sr = p.rows.map(function (g) { return g.key; }).indexOf(pFull.rows[conc.largest.r].key);
956
+ var sc = p.cols.map(function (g) { return g.key; }).indexOf(pFull.cols[conc.largest.c].key);
957
+ if (sr >= 0 && sc >= 0) start = [sr, sc];
958
+ }
959
+ svg.addEventListener("focus", function () {
960
+ var a = self._active && self._active[0] < nR && self._active[1] < nC ? self._active : start;
961
+ showCell(a[0], a[1]);
962
+ });
963
+ svg.addEventListener("blur", function () { self._hideTip(); });
964
+ svg.addEventListener("keydown", function (e) {
965
+ var a = self._active && self._active[0] < nR && self._active[1] < nC ? self._active.slice() : start.slice();
966
+ if (e.key === "ArrowLeft") a[1] = Math.max(0, a[1] - 1);
967
+ else if (e.key === "ArrowRight") a[1] = Math.min(nC - 1, a[1] + 1);
968
+ else if (e.key === "ArrowUp") a[0] = Math.max(0, a[0] - 1);
969
+ else if (e.key === "ArrowDown") a[0] = Math.min(nR - 1, a[0] + 1);
970
+ else if (e.key === "Home") a[1] = 0;
971
+ else if (e.key === "End") a[1] = nC - 1;
972
+ else if ((e.key === "Enter" || e.key === " ") && typeof o.onClick === "function") { e.preventDefault(); o.onClick(cellInfo(a[0], a[1]), e); return; }
973
+ else return;
974
+ e.preventDefault();
975
+ showCell(a[0], a[1]);
976
+ });
977
+
978
+ this._hideTip();
979
+ this._animateNext = false;
980
+ return this;
981
+ };
982
+
983
+ /* ======================================================================
984
+ 5. EXPORT AND NOTES
985
+ Used by the chart menu in veyforma-toolkit.js, and available to you.
986
+ ====================================================================== */
987
+ function findGroup(groups, key) {
988
+ if (key == null) return -1;
989
+ key = String(key);
990
+ for (var i = 0; i < groups.length; i++) {
991
+ if (groups[i].label === key || groups[i].key === key || groups[i].members.indexOf(key) >= 0) return i;
992
+ }
993
+ return -1;
994
+ }
995
+
996
+ /** One-paragraph guide to reading the heatmap. */
997
+ Chart.prototype.howToRead = function () {
998
+ var p = buildPivot(this.options.data, this.options, this._labels());
999
+ var rw = (p.rowDim.label || "row").toLowerCase(), cw = (p.colDim.label || "column").toLowerCase();
1000
+ return "Each cell is the exposure where a " + rw + " meets a " + cw + "; darker cells hold more. " +
1001
+ "The bars on the right and along the bottom are the totals for each " + rw + " and " + cw + ". " +
1002
+ "HHI measures concentration: the higher it is, the more the book depends on a few cells." +
1003
+ (this._limit() ? " Cells with a double outline are above the concentration limit." : "");
1004
+ };
1005
+
1006
+ /** A plain-English summary of the main findings, for screen readers and the explanation box. */
1007
+ Chart.prototype.describe = function () {
1008
+ var st = this.getStats(), f = makeFormatters(this.options.data, this.options.locale);
1009
+ var p = buildPivot(this.options.data, this.options, this._labels());
1010
+ var out = ["In this example total exposure is " + f.value(st.total) + " across " + st.rows + " " + (p.rowDim.plural || p.rowDim.label).toLowerCase() +
1011
+ " and " + st.columns + " " + (p.colDim.plural || p.colDim.label).toLowerCase() + "."];
1012
+ if (st.largest) out.push("The largest cell is " + st.largest.row + " × " + st.largest.column + " with " + f.value(st.largest.value) + " (" + f.percent(st.largest.share) + " of the total).");
1013
+ out.push("HHI is " + f.count(st.hhi) + ", like " + f.count(Math.round(st.effectiveCells)) + " equal-sized cells.");
1014
+ if (st.limit) out.push(st.aboveLimit.length + " " + (st.aboveLimit.length === 1 ? "cell is" : "cells are") + " above the " + pct(st.limit) + " limit.");
1015
+ return out.join(" ");
1016
+ };
1017
+
1018
+ /** Tables, wording and audit details for the export menu. Uses the full grid, without Other grouping. */
1019
+ Chart.prototype.getExportData = function () {
1020
+ var o = this.options, data = o.data, L = this._labels();
1021
+ var p = buildPivot(data, assign({}, o, { topRows: 0, topColumns: 0 }), L), f = makeFormatters(data, o.locale);
1022
+ var st = this.getStats(), lim = this._limit();
1023
+ var unit = { prefix: data.prefix || "", suffix: data.suffix || "", decimals: data.decimals != null ? data.decimals : 0, negatives: data.negatives };
1024
+ var cols = [{ label: p.rowDim.label, type: "text" }].concat(p.cols.map(function (c) { return { label: c.label, type: "number", unit: unit }; }), [{ label: L.total, type: "number", unit: unit }]);
1025
+ var mRows = p.rows.map(function (r, ri) { return [r.label].concat(p.values[ri], [r.total]); });
1026
+ mRows.push([L.total].concat(p.cols.map(function (c) { return c.total; }), [p.total]));
1027
+ var mText = p.rows.map(function (r, ri) { return [r.label].concat(p.values[ri].map(function (v) { return v ? f.value(v) : "—"; }), [f.value(r.total)]); });
1028
+ mText.push([L.total].concat(p.cols.map(function (c) { return f.value(c.total); }), [f.value(p.total)]));
1029
+ var cells = [];
1030
+ p.rows.forEach(function (r, ri) { p.cols.forEach(function (c, ci) { var v = p.values[ri][ci]; if (v) cells.push([r.label, c.label, v, p.total ? v / p.total : 0]); }); });
1031
+ cells.sort(function (a, b) { return b[2] - a[2]; });
1032
+ var above = function (share) { return lim && share > lim + 1e-12 ? "Yes" : "No"; };
1033
+ var conc = [
1034
+ [L.totalExposure, st.total, f.value(st.total)],
1035
+ [L.hhi, st.hhi, f.count(st.hhi)],
1036
+ ["Effective number of cells", st.effectiveCells, f.count(Math.round(st.effectiveCells))],
1037
+ [L.top5, st.top5Share, f.percent(st.top5Share)]
1038
+ ];
1039
+ if (st.largest) conc.push([L.largest, st.largest.share, st.largest.row + " × " + st.largest.column + " · " + f.percent(st.largest.share)]);
1040
+ if (lim) { conc.push(["Limit (share of total)", lim, pct(lim)]); conc.push([L.aboveLimit, st.aboveLimit.length, f.count(st.aboveLimit.length)]); }
1041
+ var notes = (o.annotations || []).map(function (a, i) { return [String(i + 1), String(a.row || ""), String(a.column || ""), a.text || ""]; });
1042
+ var sheets = [
1043
+ { name: "Matrix", columns: cols, rows: mRows, text: mText, bold: mRows.map(function (r, i) { return i === mRows.length - 1; }) },
1044
+ { name: "Cells", columns: [{ label: p.rowDim.label, type: "text" }, { label: p.colDim.label, type: "text" }, { label: L.exposure, type: "number", unit: unit },
1045
+ { label: L.shareOfTotal, type: "percent", decimals: 2 }, { label: L.aboveLimit, type: "text" }],
1046
+ rows: cells.map(function (c) { return [c[0], c[1], c[2], c[3], above(c[3])]; }),
1047
+ text: cells.map(function (c) { return [c[0], c[1], f.value(c[2]), f.percent(c[3], 2), above(c[3])]; }) },
1048
+ { name: "Concentration", columns: [{ label: "Measure", type: "text" }, { label: "Value", type: "general" }, { label: "As shown", type: "text" }],
1049
+ rows: conc, text: conc.map(function (r) { return [r[0], typeof r[1] === "number" ? String(Number(r[1].toPrecision(10))) : String(r[1]), r[2]]; }) }
1050
+ ];
1051
+ if (notes.length) sheets.push({ name: "Notes", columns: [{ label: "No.", type: "text" }, { label: p.rowDim.label, type: "text" }, { label: p.colDim.label, type: "text" }, { label: "Note", type: "text" }], rows: notes });
1052
+ return {
1053
+ title: data.title || "Exposure heatmap", subtitle: data.subtitle || "", summary: this.describe(),
1054
+ library: "Veyforma Exposure Heatmap " + VERSION, sheets: sheets,
1055
+ meta: [["Method", "HHI = 10,000 × sum of squared cell shares; effective number of cells = 10,000 ÷ HHI; a cell is above the limit when its share is strictly greater"],
1056
+ ["Grid", p.rowDim.label + " × " + p.colDim.label + ", full grid without Other grouping"],
1057
+ ["Unit", data.unit], ["Limit", lim ? pct(lim) + " of total" : null], ["As of", data.asOf], ["Data source", data.source]]
1058
+ };
1059
+ };
1060
+
1061
+ /** Where a note's marker goes: inside the top-left corner of its cell. */
1062
+ Chart.prototype._annotationPoint = function (a) {
1063
+ var g = this._geom;
1064
+ if (!g || !a) return null;
1065
+ var r = findGroup(g.rows, a.row), c = findGroup(g.cols, a.column);
1066
+ if (r < 0 || c < 0) return null;
1067
+ // A cell grouped into "Other" keeps its note: the marker moves to the Other cell and the list says so.
1068
+ var grouped = (g.rows[r] && g.rows[r].other) || (g.cols[c] && g.cols[c].other);
1069
+ return { x: g.cx(c) + g.gap / 2 + 11, y: g.cy(r) + g.gap / 2 + 11, inside: true, where: grouped ? "shown in Other" : null };
1070
+ };
1071
+ /** The cell under the pointer (or the cell picked with the keyboard), as a note target. */
1072
+ Chart.prototype._annotationTarget = function (evt) {
1073
+ var g = this._geom, r, c;
1074
+ if (!g) return null;
1075
+ if (evt) {
1076
+ var t = evt.target;
1077
+ if (!t || !t.getAttribute || t.getAttribute("data-r") == null) return null;
1078
+ r = +t.getAttribute("data-r"); c = +t.getAttribute("data-c");
1079
+ } else if (this._active) { r = this._active[0]; c = this._active[1]; }
1080
+ else return null;
1081
+ if (!g.rows[r] || !g.cols[c] || g.rows[r].other || g.cols[c].other) return null;
1082
+ return { row: g.rows[r].label, column: g.cols[c].label };
1083
+ };
1084
+ Chart.prototype._annotationLabel = function (a) { return [a.row, a.column].filter(Boolean).join(" × "); };
1085
+
1086
+ /* ======================================================================
1087
+ 6. PUBLIC API
1088
+ ====================================================================== */
1089
+ root.VeyHeatmap = {
1090
+ version: VERSION,
1091
+ /** Draws a heatmap inside a container element or CSS selector. */
1092
+ create: function (target, options) { return new Chart(target, options); },
1093
+ /** Adds or replaces a named theme. Use "extends" to start from another theme. */
1094
+ registerTheme: function (name, theme) {
1095
+ if (!name || typeof name !== "string") throw new Error("VeyHeatmap: registerTheme needs a name.");
1096
+ THEMES[name] = resolveTheme(theme || {});
1097
+ return THEMES[name];
1098
+ },
1099
+ /** Returns the full set of values for a theme name or partial theme. */
1100
+ getTheme: function (theme) { return resolveTheme(theme); },
1101
+ /** Lists the names of all available themes. */
1102
+ listThemes: function () { return Object.keys(THEMES); }
1103
+ };
1104
+ })(typeof window !== "undefined" ? window : this);