@veyforma/charts 0.0.0-stage → 1.0.2

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,2952 @@
1
+ /*! @veyforma/charts v1.0.2 · MIT License · Copyright (c) 2026 Veyforma · https://github.com/veyforma/veyforma-charts */
2
+ var __vfRoot = typeof window !== "undefined" ? window : {};
3
+ /*!
4
+ * Veyforma Exposure Heatmap v1.2.0
5
+ * A dependency-free heatmap that reveals concentrations, for example
6
+ * exposure by sector and country, or by sector and rating.
7
+ * Original work created for Veyforma. Contains no third-party code.
8
+ * Released under the MIT License. Copyright (c) 2026 Veyforma.
9
+ * https://github.com/veyforma/veyforma-charts
10
+ *
11
+ * File layout
12
+ * 1. Themes ............ colour scale, fonts and shapes (edit or add your own)
13
+ * 2. Helpers ........... colours, formatting, measuring
14
+ * 3. Calculation ....... pivot, ordering, "Other" grouping, concentration
15
+ * 4. Chart instance .... drawing, summary, legend, tooltips, keyboard, resizing
16
+ * 5. Export and notes .. data for the Veyforma Toolkit menu (optional file)
17
+ * 6. Public API ........ window.VeyHeatmap
18
+ *
19
+ * Load veyforma-toolkit.js as well to get the chart menu: full screen, print,
20
+ * PNG, JPEG, SVG, PDF, CSV and Excel downloads, copy and notes.
21
+ */
22
+ (function (root) {
23
+ "use strict";
24
+
25
+ var VERSION = "1.2.0";
26
+ var SVG_NS = "http://www.w3.org/2000/svg";
27
+ var instanceCount = 0;
28
+
29
+ /* ======================================================================
30
+ 1. THEMES
31
+ The colour scale runs from "low" through "mid" to "high". Scale colours
32
+ must be hex values, such as "#9a3412", so they can be blended.
33
+ ====================================================================== */
34
+ var BASE_THEME = {
35
+ low: "#fbf1ea", // smallest values
36
+ mid: "#ef8a54", // middle of the scale
37
+ high: "#9a3412", // largest values
38
+ empty: "#ffffff", // cells with no exposure (drawn with a dashed outline)
39
+ limit: "#111111", // outline of cells above the concentration limit
40
+ cellText: "#000000", // numbers on light cells (pure black and white keep 4.5:1 on any cell)
41
+ cellTextOnDark: "#ffffff", // numbers on dark cells
42
+ totalBar: "#111111", // data bars behind the totals
43
+ totalBarOpacity: 0.12, // strength of those data bars
44
+ headerText: "#555555", // row and column names
45
+ text: "#111111", // totals, legend and summary values
46
+ mutedText: "#6b6b6b", // secondary text
47
+ summaryBackground: "#f6f6f6", // background of the summary figures
48
+ background: "transparent", // chart background
49
+ tooltipBackground: "#111111",
50
+ tooltipText: "#ffffff",
51
+ focus: "#2563eb", // keyboard focus ring
52
+ fontFamily: "inherit", // "inherit" uses the page font
53
+ fontSize: 12, // base text size in pixels
54
+ cellRadius: 3, // corner rounding of cells
55
+ cellGap: 2 // space between cells in pixels
56
+ };
57
+
58
+ var THEMES = {
59
+ veyforma: {},
60
+ mono: {
61
+ low: "#f4f4f4", mid: "#9a9a9a", high: "#111111", empty: "#ffffff", limit: "#111111"
62
+ },
63
+ "colour-safe": {
64
+ low: "#eef3fb", mid: "#6d9be0", high: "#1d3f8f", limit: "#d9730d"
65
+ },
66
+ ocean: {
67
+ low: "#ecf6f8", mid: "#5aaec0", high: "#0c3b5e", limit: "#be123c", summaryBackground: "#eef5f8"
68
+ },
69
+ forest: {
70
+ low: "#f1f5ea", mid: "#8fb36b", high: "#22441a", limit: "#a8590b", summaryBackground: "#f2f4ee"
71
+ },
72
+ corporate: {
73
+ low: "#eef1f6", mid: "#8195b8", high: "#1e3a6e", limit: "#b91c1c", summaryBackground: "#f1f4f8", cellRadius: 0
74
+ },
75
+ midnight: {
76
+ background: "#111418", low: "#1e242c", mid: "#2f6aa8", high: "#9cd0ff", empty: "#111418",
77
+ limit: "#fbbf24", cellText: "#000000", cellTextOnDark: "#ffffff", totalBar: "#9cd0ff", totalBarOpacity: 0.18,
78
+ headerText: "#c3c9d2", text: "#f3f4f6", mutedText: "#a3abb8", summaryBackground: "#1b2027",
79
+ tooltipBackground: "#f3f4f6", tooltipText: "#111418", focus: "#93c5fd"
80
+ }
81
+ };
82
+
83
+ function resolveTheme(theme) {
84
+ if (theme == null || theme === "") theme = "veyforma";
85
+ if (typeof theme === "string") {
86
+ if (!THEMES.hasOwnProperty(theme)) {
87
+ warn('Unknown theme "' + theme + '". The "veyforma" theme is used instead.');
88
+ theme = "veyforma";
89
+ }
90
+ return assign({}, BASE_THEME, THEMES[theme]);
91
+ }
92
+ if (typeof theme !== "object") {
93
+ warn("The theme option must be a theme name or an object.");
94
+ return assign({}, BASE_THEME);
95
+ }
96
+ var base = theme["extends"] ? resolveTheme(theme["extends"]) : assign({}, BASE_THEME);
97
+ var out = assign(base, theme);
98
+ delete out["extends"];
99
+ ["low", "mid", "high", "empty"].forEach(function (k) {
100
+ if (!parseHex(out[k])) {
101
+ warn('Theme colour "' + k + '" must be a hex value such as "#9a3412". The default is used instead.');
102
+ out[k] = BASE_THEME[k];
103
+ }
104
+ });
105
+ return out;
106
+ }
107
+
108
+ /* ======================================================================
109
+ 2. HELPERS
110
+ ====================================================================== */
111
+ function assign(target) {
112
+ for (var i = 1; i < arguments.length; i++) {
113
+ var src = arguments[i];
114
+ if (src) for (var k in src) if (Object.prototype.hasOwnProperty.call(src, k)) target[k] = src[k];
115
+ }
116
+ return target;
117
+ }
118
+ function clamp(v, lo, hi) { return Math.min(hi, Math.max(lo, v)); }
119
+ function warn(msg) { if (root.console) root.console.warn("VeyHeatmap: " + msg); }
120
+ function svgEl(tag, attrs, parent) {
121
+ var n = document.createElementNS(SVG_NS, tag);
122
+ if (attrs) for (var k in attrs) if (attrs[k] != null) n.setAttribute(k, attrs[k]);
123
+ if (parent) parent.appendChild(n);
124
+ return n;
125
+ }
126
+ function htmlEl(tag, className, parent) {
127
+ var n = document.createElement(tag);
128
+ if (className) n.className = className;
129
+ if (parent) parent.appendChild(n);
130
+ return n;
131
+ }
132
+
133
+ function parseHex(hex) {
134
+ if (typeof hex !== "string") return null;
135
+ var h = hex.trim().replace(/^#/, "");
136
+ if (h.length === 3) h = h.split("").map(function (c) { return c + c; }).join("");
137
+ if (!/^[0-9a-fA-F]{6}$/.test(h)) return null;
138
+ var n = parseInt(h, 16);
139
+ return [(n >> 16) & 255, (n >> 8) & 255, n & 255];
140
+ }
141
+ function toHex(rgb) {
142
+ return "#" + rgb.map(function (v) { var s = Math.round(clamp(v, 0, 255)).toString(16); return s.length < 2 ? "0" + s : s; }).join("");
143
+ }
144
+ 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]; }
145
+ function makeRamp(theme) {
146
+ var lo = parseHex(theme.low), md = parseHex(theme.mid), hi = parseHex(theme.high);
147
+ return function (t) {
148
+ t = clamp(t, 0, 1);
149
+ return toHex(t < 0.5 ? mix(lo, md, t * 2) : mix(md, hi, (t - 0.5) * 2));
150
+ };
151
+ }
152
+ /** Contrast ratio between two hex colours (1 to 21), as defined by WCAG. */
153
+ function contrast(a, b) {
154
+ var x = luminance(a), y = luminance(b);
155
+ return (Math.max(x, y) + 0.05) / (Math.min(x, y) + 0.05);
156
+ }
157
+ function luminance(hex) {
158
+ var c = parseHex(hex);
159
+ if (!c) return 1;
160
+ var lin = c.map(function (v) { v /= 255; return v <= 0.03928 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4); });
161
+ return 0.2126 * lin[0] + 0.7152 * lin[1] + 0.0722 * lin[2];
162
+ }
163
+
164
+ var measureCtx = null;
165
+ function textWidth(text, sizePx, weight, family) {
166
+ if (!measureCtx) {
167
+ var c = document.createElement("canvas");
168
+ measureCtx = c.getContext && c.getContext("2d");
169
+ }
170
+ if (!measureCtx) return String(text).length * sizePx * 0.6;
171
+ measureCtx.font = (weight || 400) + " " + sizePx + "px " + family;
172
+ return measureCtx.measureText(String(text)).width;
173
+ }
174
+ function ellipsis(text, maxW, size, weight, family) {
175
+ text = String(text);
176
+ if (textWidth(text, size, weight, family) <= maxW) return text;
177
+ var lo = 0, hi = text.length;
178
+ while (lo < hi) {
179
+ var mid = Math.ceil((lo + hi) / 2);
180
+ if (textWidth(text.slice(0, mid) + "…", size, weight, family) <= maxW) lo = mid; else hi = mid - 1;
181
+ }
182
+ return lo > 0 ? text.slice(0, lo).replace(/\s+$/, "") + "…" : "";
183
+ }
184
+ function wrapTwo(text, maxW, size, weight, family) {
185
+ var words = String(text).split(/\s+/), lines = [], cur = "";
186
+ for (var i = 0; i < words.length; i++) {
187
+ var test = cur ? cur + " " + words[i] : words[i];
188
+ if (textWidth(test, size, weight, family) > maxW && cur) { lines.push(cur); cur = words[i]; }
189
+ else cur = test;
190
+ }
191
+ if (cur) lines.push(cur);
192
+ var ok = lines.length <= 2 && lines.every(function (l) { return textWidth(l, size, weight, family) <= maxW; });
193
+ return ok ? lines : null;
194
+ }
195
+ function pct(share) {
196
+ var v = Math.round(share * 10000) / 100;
197
+ return String(v) + "%";
198
+ }
199
+
200
+ function makeFormatters(data, locale) {
201
+ var decimals = data.decimals != null ? data.decimals : 0;
202
+ var prefix = data.prefix || "", suffix = data.suffix || "";
203
+ var cache = {};
204
+ function nf(key, opts) {
205
+ if (!cache[key]) cache[key] = new Intl.NumberFormat(locale || undefined, opts);
206
+ return cache[key];
207
+ }
208
+ function value(v, d) {
209
+ if (d == null) d = decimals;
210
+ var step = Math.pow(10, -d);
211
+ // A positive amount that would round to zero is shown as "<$0.1bn" rather than "$0.0bn".
212
+ if (v > 0 && v < step / 2) return "<" + prefix + nf("f" + d, { minimumFractionDigits: d, maximumFractionDigits: d }).format(step) + suffix;
213
+ var body = prefix + nf("f" + d, { minimumFractionDigits: d, maximumFractionDigits: d }).format(Math.abs(v)) + suffix;
214
+ if (v >= 0) return body;
215
+ // Negative numbers: "minus" (default) or "brackets", as in accounts.
216
+ return data.negatives === "brackets" ? "(" + body + ")" : "−" + body;
217
+ }
218
+ function compact(v) {
219
+ // With a unit suffix such as "m", shorten by dropping decimals rather than adding "K" or "M".
220
+ if (suffix) return value(v, 0);
221
+ return (v < 0 ? "−" : "") + prefix + nf("c", { notation: "compact", maximumFractionDigits: 1 }).format(Math.abs(v));
222
+ }
223
+ function percent(share, d) {
224
+ if (d == null) d = 1;
225
+ return nf("p" + d, { minimumFractionDigits: d, maximumFractionDigits: d }).format(share * 100) + "%";
226
+ }
227
+ function count(n) { return nf("n", { maximumFractionDigits: 0 }).format(n); }
228
+ return { value: value, compact: compact, percent: percent, count: count };
229
+ }
230
+
231
+ function fill(template, values) {
232
+ return String(template).replace(/\{(\w+)\}/g, function (m, k) { return values[k] != null ? values[k] : m; });
233
+ }
234
+
235
+ /* ======================================================================
236
+ 3. CALCULATION
237
+ Records such as { sector: "Energy", country: "Norway", rating: "BBB", value: 120 }
238
+ are summed into a grid. You choose which field forms the rows and which
239
+ the columns. Values must be zero or more.
240
+ ====================================================================== */
241
+ var OTHER_KEY = "\u0000other";
242
+
243
+ function normaliseData(data) {
244
+ if (Array.isArray(data.values)) {
245
+ var rl = data.rowLabels, cl = data.columnLabels;
246
+ var cached = aggCache && aggCache.get(data.values);
247
+ if (cached && cached.grid && cached.gridRows === rl && cached.gridCols === cl) return cached.grid;
248
+ if (!Array.isArray(rl) || !Array.isArray(cl)) throw new Error("VeyHeatmap: a values grid needs rowLabels and columnLabels.");
249
+ if (data.values.length !== rl.length) throw new Error("VeyHeatmap: values has " + data.values.length + " rows but rowLabels has " + rl.length + ".");
250
+ var recs = [];
251
+ data.values.forEach(function (row, r) {
252
+ if (!Array.isArray(row) || row.length !== cl.length) throw new Error("VeyHeatmap: row " + (r + 1) + " of values needs " + cl.length + " numbers.");
253
+ row.forEach(function (v, c) { recs.push({ row: rl[r], column: cl[c], value: v }); });
254
+ });
255
+ var grid = {
256
+ records: recs, rows: "row", columns: "column",
257
+ dimensions: {
258
+ row: { label: data.rowTitle || "Row", order: rl.slice(), ordered: true },
259
+ column: { label: data.columnTitle || "Column", order: cl.slice(), ordered: true }
260
+ }
261
+ };
262
+ if (aggCache) {
263
+ var bucket = aggCache.get(data.values) || {};
264
+ bucket.grid = grid; bucket.gridRows = rl; bucket.gridCols = cl;
265
+ aggCache.set(data.values, bucket);
266
+ }
267
+ return grid;
268
+ }
269
+ if (!Array.isArray(data.records) || !data.records.length) {
270
+ throw new Error("VeyHeatmap: data needs records, or values with rowLabels and columnLabels.");
271
+ }
272
+ var keys = Object.keys(data.records[0]).filter(function (k) { return k !== "value"; });
273
+ var dims = assign({}, data.dimensions || {});
274
+ keys.forEach(function (k) { if (!dims[k]) dims[k] = { label: k.charAt(0).toUpperCase() + k.slice(1) }; });
275
+ return { records: data.records, rows: data.rows || keys[0], columns: data.columns || keys[1], dimensions: dims };
276
+ }
277
+
278
+ // Sums are cached per records array (or values grid) and per pair of fields, so
279
+ // changing the theme, display mode, limit, grouping or screen size never re-reads
280
+ // the records. If you change the records in place, call chart.setData() to clear it.
281
+ var aggCache = typeof WeakMap === "function" ? new WeakMap() : null;
282
+
283
+ function aggregate(nd, rk, ck, source) {
284
+ var key = rk + "\u0001" + ck, bucket = aggCache && source ? aggCache.get(source) : null;
285
+ if (bucket && bucket[key]) return bucket[key];
286
+ var cells = new Map(), rowTot = new Map(), colTot = new Map(), total = 0;
287
+ var recs = nd.records, n = recs.length;
288
+ for (var i = 0; i < n; i++) {
289
+ var rec = recs[i], r = rec[rk], c = rec[ck];
290
+ if (r == null || r === "") throw new Error("VeyHeatmap: record " + (i + 1) + ' has no "' + rk + '".');
291
+ if (c == null || c === "") throw new Error("VeyHeatmap: record " + (i + 1) + ' has no "' + ck + '".');
292
+ var raw = rec.value, v = typeof raw === "number" ? raw : Number(raw);
293
+ if (raw === null || raw === undefined || raw === "" || !isFinite(v)) {
294
+ throw new Error("VeyHeatmap: record " + (i + 1) + " has no numeric value.");
295
+ }
296
+ if (v < 0) throw new Error("VeyHeatmap: record " + (i + 1) + " is negative. Exposure values must be zero or more.");
297
+ if (typeof r !== "string") r = String(r);
298
+ if (typeof c !== "string") c = String(c);
299
+ var row = cells.get(r);
300
+ if (!row) { row = new Map(); cells.set(r, row); rowTot.set(r, 0); }
301
+ row.set(c, (row.get(c) || 0) + v);
302
+ rowTot.set(r, rowTot.get(r) + v);
303
+ colTot.set(c, (colTot.get(c) || 0) + v);
304
+ total += v;
305
+ }
306
+ var toObj = function (m) { var o = {}; m.forEach(function (v, k) { o[k] = v; }); return o; };
307
+ var result = {
308
+ cell: function (r, c) { var row = cells.get(r); return row ? (row.get(c) || 0) : 0; },
309
+ rowTot: toObj(rowTot), colTot: toObj(colTot),
310
+ rowSeen: Array.from(rowTot.keys()), colSeen: Array.from(colTot.keys()), total: total
311
+ };
312
+ if (aggCache && source) {
313
+ if (!bucket) { bucket = {}; aggCache.set(source, bucket); }
314
+ bucket[key] = result;
315
+ }
316
+ return result;
317
+ }
318
+
319
+ function buildPivot(data, o, L) {
320
+ var nd = normaliseData(data);
321
+ var rk = o.rows || nd.rows, ck = o.columns || nd.columns;
322
+ if (!rk || !ck) throw new Error("VeyHeatmap: choose a field for the rows and a field for the columns.");
323
+ if (rk === ck) throw new Error('VeyHeatmap: rows and columns cannot both use "' + rk + '".');
324
+ var dR = assign({ label: rk }, nd.dimensions[rk]), dC = assign({ label: ck }, nd.dimensions[ck]);
325
+ var agg = aggregate(nd, rk, ck, Array.isArray(data.values) ? data.values : data.records);
326
+ var rowTot = agg.rowTot, colTot = agg.colTot, rowSeen = agg.rowSeen, colSeen = agg.colSeen, total = agg.total;
327
+
328
+ function arrange(seen, totals, dim, sortMode, top) {
329
+ var natural = seen.slice();
330
+ if (Array.isArray(dim.order)) {
331
+ var ord = dim.order.map(String);
332
+ natural.sort(function (a, b) {
333
+ var ia = ord.indexOf(a), ib = ord.indexOf(b);
334
+ if (ia < 0) ia = ord.length + seen.indexOf(a);
335
+ if (ib < 0) ib = ord.length + seen.indexOf(b);
336
+ return ia - ib;
337
+ });
338
+ }
339
+ var byTotal = natural.slice().sort(function (a, b) { return totals[b] - totals[a] || natural.indexOf(a) - natural.indexOf(b); });
340
+ var useTotal = sortMode === "total" || (sortMode !== "natural" && !dim.ordered);
341
+ var list = useTotal ? byTotal : natural;
342
+ var groups = list.map(function (k) { return { key: k, label: k, members: [k] }; });
343
+ if (top && top > 0 && list.length > top + 1) {
344
+ var keep = byTotal.slice(0, top);
345
+ var kept = list.filter(function (k) { return keep.indexOf(k) >= 0; });
346
+ var rest = list.filter(function (k) { return keep.indexOf(k) < 0; });
347
+ groups = kept.map(function (k) { return { key: k, label: k, members: [k] }; });
348
+ groups.push({ key: OTHER_KEY, label: fill(L.other, { count: rest.length }), members: rest, other: true });
349
+ }
350
+ groups.forEach(function (g) { g.total = g.members.reduce(function (s, k) { return s + totals[k]; }, 0); });
351
+ return groups;
352
+ }
353
+
354
+ var rows = arrange(rowSeen, rowTot, dR, o.sortRows, o.topRows);
355
+ var cols = arrange(colSeen, colTot, dC, o.sortColumns, o.topColumns);
356
+ var values = rows.map(function (rg) {
357
+ return cols.map(function (cg) {
358
+ var s = 0;
359
+ rg.members.forEach(function (r) { cg.members.forEach(function (c) { s += agg.cell(r, c); }); });
360
+ return s;
361
+ });
362
+ });
363
+ return { rowKey: rk, colKey: ck, rowDim: dR, colDim: dC, rows: rows, cols: cols, values: values, total: total };
364
+ }
365
+
366
+ function concentration(p, limitShare) {
367
+ var cells = [], hhi = 0;
368
+ p.values.forEach(function (row, r) {
369
+ row.forEach(function (v, c) {
370
+ var share = p.total > 0 ? v / p.total : 0;
371
+ hhi += share * share * 10000;
372
+ cells.push({ r: r, c: c, value: v, share: share });
373
+ });
374
+ });
375
+ cells.sort(function (a, b) { return b.value - a.value; });
376
+ var top5 = cells.slice(0, 5).reduce(function (s, x) { return s + x.share; }, 0);
377
+ var above = limitShare > 0 ? cells.filter(function (x) { return x.share > limitShare + 1e-12; }) : [];
378
+ return { hhi: hhi, effective: hhi > 0 ? 10000 / hhi : 0, largest: cells[0], top5: top5, above: above };
379
+ }
380
+
381
+ /* ======================================================================
382
+ 4. CHART INSTANCE
383
+ ====================================================================== */
384
+ var DEFAULT_OPTIONS = {
385
+ data: null, // required, see the user manual
386
+ theme: "veyforma", // theme name or theme object
387
+ locale: undefined, // e.g. "en-GB"; default is the visitor's locale
388
+ rows: undefined, // field for the rows; overrides data.rows
389
+ columns: undefined, // field for the columns; overrides data.columns
390
+ valueMode: "amount", // "amount", "shareOfTotal", "shareOfRow" or "shareOfColumn"
391
+ scale: "linear", // "linear" or "sqrt" (brings out small values)
392
+ sortRows: "auto", // "auto", "total" or "natural"
393
+ sortColumns: "auto", // "auto", "total" or "natural"
394
+ topRows: 0, // keep the largest N rows and group the rest as "Other"; 0 keeps all
395
+ topColumns: 0, // the same for columns
396
+ fit: "auto", // narrow screens: "auto" groups small columns into Other (scrolls ordered ones such as ratings), "group" or "scroll"
397
+ limit: undefined, // share of total, e.g. 0.05; overrides data.limit
398
+ totals: true, // show row and column totals
399
+ cellLabels: "auto", // "auto" shows numbers where they fit; true or false
400
+ cellHeight: undefined, // pixels; default 34 (28 on small screens)
401
+ summary: true, // show the key figures above the chart
402
+ legend: true, // show the colour legend
403
+ tooltip: true, // tooltips on hover, tap and keyboard focus
404
+ animate: true, // cells fade in on first draw and when the data changes
405
+ labels: null, // wording, see DEFAULT_LABELS
406
+ ariaLabel: undefined, // screen-reader description; default uses data.title
407
+ tooltipFormatter: null, // function (cell, format) -> string or array of strings
408
+ onClick: null, // function (cell, event)
409
+ caption: true, // explanation under the chart: true (built-in), your own text, or false
410
+ annotations: null, // notes, e.g. [{ row: "Energy", column: "United Kingdom", text: "Hedged in Q3" }]
411
+ onAnnotationsChange: null, // function (notes) called when a note is added or removed from the menu
412
+ toolbar: true // chart menu from veyforma-toolkit.js: true, false or toolbar settings
413
+ };
414
+ var DEFAULT_LABELS = {
415
+ total: "Total", other: "Other ({count})", empty: "No exposure",
416
+ totalExposure: "Total exposure", largest: "Largest concentration", hhi: "Concentration (HHI)",
417
+ aboveLimit: "Above limit", top5: "Top 5 cells",
418
+ hhiNote: "Like {n} equal-sized cells", aboveNote: "Cells above {limit} of total",
419
+ gridNote: "{rows} {rowDim} × {cols} {colDim}", top5Note: "Share of total exposure",
420
+ exposure: "Exposure", shareOfTotal: "Share of total", shareOfRow: "Share of {row}", shareOfColumn: "Share of {column}",
421
+ limitLegend: "Above {limit} limit", limitTip: "Above the {limit} limit", rowTotalTip: "{label} total",
422
+ scrollNote: "Scroll sideways to see all {columns}.",
423
+ groupNote: "Smaller {columns} are grouped as Other to fit this screen. Tap an Other cell to see which.",
424
+ includes: "Other includes {list}"
425
+ };
426
+
427
+ function injectStyles() {
428
+ if (document.getElementById("vhm-styles")) return;
429
+ var css =
430
+ ".vhm{position:relative;color:var(--vhm-text);background:var(--vhm-bg);font-family:var(--vhm-font);line-height:1.4}" +
431
+ ".vhm.vhm-filled{padding:14px 14px 8px;border-radius:10px}" +
432
+ ".vhm-summary{display:grid;grid-template-columns:repeat(auto-fit,minmax(130px,1fr));gap:8px;margin:0 0 12px}" +
433
+ ".vhm-stat{background:var(--vhm-summary-bg);border-radius:10px;padding:10px 12px;min-width:0}" +
434
+ ".vhm-stat-label{font-size:11px;letter-spacing:.04em;text-transform:uppercase;color:var(--vhm-muted)}" +
435
+ ".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}" +
436
+ ".vhm-stat-note{font-size:11.5px;color:var(--vhm-muted);margin-top:1px;overflow-wrap:anywhere}" +
437
+ ".vhm-legend{display:flex;flex-wrap:wrap;align-items:center;gap:6px 18px;font-size:12px;margin:0 0 10px}" +
438
+ ".vhm-legend>span{display:inline-flex;align-items:center;gap:6px}" +
439
+ ".vhm-legend .vhm-ramp{display:inline-flex;flex-direction:column;align-items:stretch;gap:2px}" +
440
+ ".vhm-ramp-bar{width:150px;height:10px;border-radius:3px}" +
441
+ ".vhm-ramp-ticks{display:flex;justify-content:space-between;gap:8px;font-size:11px;color:var(--vhm-muted);font-variant-numeric:tabular-nums}" +
442
+ ".vhm-plot-host{overflow-x:auto;-webkit-overflow-scrolling:touch}" +
443
+ ".vhm-plot{display:block;overflow:visible;outline:none}" +
444
+ ".vhm-plot:focus-visible{outline:2px solid var(--vhm-focus);outline-offset:4px;border-radius:4px}" +
445
+ ".vhm-animate .vhm-cell{animation:vhm-fade .45s ease both}" +
446
+ "@keyframes vhm-fade{from{opacity:0}to{opacity:1}}" +
447
+ "@media (prefers-reduced-motion:reduce){.vhm-animate .vhm-cell{animation:none}}" +
448
+ ".vhm-scroll-note{font-size:11.5px;color:var(--vhm-muted);margin-top:4px}" +
449
+ ".vhm-tip{position:absolute;left:0;top:0;pointer-events:none;background:var(--vhm-tip-bg);color:var(--vhm-tip-text);" +
450
+ "font-size:12px;line-height:1.45;padding:8px 10px;border-radius:8px;opacity:0;transform:translateY(4px);" +
451
+ "transition:opacity .12s,transform .12s;white-space:nowrap;z-index:5}" +
452
+ ".vhm-tip.vhm-on{opacity:1;transform:none}" +
453
+ ".vhm-tip b{font-weight:600}" +
454
+ ".vhm-table{width:100%;border-collapse:collapse;font-size:13px}" +
455
+ ".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}" +
456
+ ".vhm-table th:first-child,.vhm-table td:first-child{text-align:left}" +
457
+ ".vhm-table th{font-weight:600;font-size:12px}" +
458
+ ".vhm-table tr.vhm-total td{font-weight:600}";
459
+ var style = document.createElement("style");
460
+ style.id = "vhm-styles";
461
+ style.appendChild(document.createTextNode(css));
462
+ (document.head || document.documentElement).appendChild(style);
463
+ }
464
+
465
+ function Chart(target, options) {
466
+ var container = typeof target === "string" ? document.querySelector(target) : target;
467
+ if (!container || container.nodeType !== 1) throw new Error("VeyHeatmap: container not found (" + target + ").");
468
+ if (!options || !options.data) throw new Error("VeyHeatmap: options.data is required.");
469
+ injectStyles();
470
+ this.id = ++instanceCount;
471
+ this.container = container;
472
+ this.options = assign({}, DEFAULT_OPTIONS, options);
473
+ this.element = htmlEl("div", "vhm");
474
+ this.summaryEl = htmlEl("div", "vhm-summary", this.element);
475
+ this.legendEl = htmlEl("div", "vhm-legend", this.element);
476
+ this.plotHost = htmlEl("div", "vhm-plot-host", this.element);
477
+ this.noteEl = htmlEl("div", "vhm-scroll-note", this.element);
478
+ this.tipEl = htmlEl("div", "vhm-tip", this.element);
479
+ this.tipEl.setAttribute("role", "tooltip");
480
+ this.tipEl.id = "vhm-tip-" + this.id;
481
+ container.appendChild(this.element);
482
+ this._animateNext = !!this.options.animate;
483
+ this._lastWidth = 0;
484
+ this._active = null;
485
+
486
+ var self = this;
487
+ if (root.ResizeObserver) {
488
+ this._observer = new root.ResizeObserver(function () {
489
+ var w = Math.round(self.element.clientWidth);
490
+ if (w && w !== self._lastWidth) self.redraw();
491
+ });
492
+ this._observer.observe(this.element);
493
+ } else {
494
+ this._onResize = function () { self.redraw(); };
495
+ root.addEventListener("resize", this._onResize);
496
+ }
497
+ this._onDocTap = function (e) { if (!self.element.contains(e.target)) self._hideTip(); };
498
+ document.addEventListener("pointerdown", this._onDocTap);
499
+ this.redraw();
500
+ if (this.options.toolbar !== false && root.VeyformaToolkit) this.toolkit = root.VeyformaToolkit.attach(this, this.options.toolbar);
501
+ }
502
+
503
+ Chart.prototype.update = function (partial) {
504
+ if (!partial) return this;
505
+ if (partial.data && partial.data !== this.options.data && this.options.animate) { this._animateNext = true; this._active = null; }
506
+ if (partial.rows || partial.columns || partial.topRows != null || partial.topColumns != null) this._active = null;
507
+ if (partial.animate === true) this._animateNext = true;
508
+ assign(this.options, partial);
509
+ return this.redraw();
510
+ };
511
+ /** Replaces the data and recalculates from scratch, even if the same records were changed in place. */
512
+ Chart.prototype.setData = function (data) {
513
+ if (aggCache && data) {
514
+ if (Array.isArray(data.records)) aggCache["delete"](data.records);
515
+ if (Array.isArray(data.values)) aggCache["delete"](data.values);
516
+ }
517
+ return this.update({ data: data });
518
+ };
519
+ Chart.prototype.setTheme = function (theme) { return this.update({ theme: theme }); };
520
+ Chart.prototype.getTheme = function () { return resolveTheme(this.options.theme); };
521
+
522
+ Chart.prototype._labels = function () { return assign({}, DEFAULT_LABELS, this.options.labels); };
523
+ Chart.prototype._limit = function () {
524
+ var o = this.options, l = o.limit !== undefined ? o.limit : (o.data.limit && o.data.limit.share);
525
+ l = Number(l);
526
+ return isFinite(l) && l > 0 && l < 1 ? l : 0;
527
+ };
528
+
529
+ /** The grid as plain objects: rows, columns, values and totals. */
530
+ Chart.prototype.getMatrix = function () {
531
+ var p = buildPivot(this.options.data, this.options, this._labels());
532
+ 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() }; };
533
+ return {
534
+ rowField: p.rowKey, columnField: p.colKey,
535
+ rows: p.rows.map(strip), columns: p.cols.map(strip),
536
+ values: p.values.map(function (r) { return r.slice(); }), total: p.total
537
+ };
538
+ };
539
+
540
+ /** Concentration figures for the current grid. */
541
+ Chart.prototype.getStats = function () {
542
+ var p = buildPivot(this.options.data, assign({}, this.options, { topRows: 0, topColumns: 0 }), this._labels());
543
+ var lim = this._limit(), c = concentration(p, lim);
544
+ var cellOut = function (x) { return { row: p.rows[x.r].label, column: p.cols[x.c].label, value: x.value, share: x.share }; };
545
+ return {
546
+ total: p.total, rows: p.rows.length, columns: p.cols.length,
547
+ hhi: c.hhi, effectiveCells: c.effective, top5Share: c.top5,
548
+ largest: c.largest ? cellOut(c.largest) : null,
549
+ limit: lim || null, aboveLimit: c.above.map(cellOut)
550
+ };
551
+ };
552
+
553
+ Chart.prototype.createTable = function () {
554
+ var o = this.options, data = o.data, L = this._labels();
555
+ var p = buildPivot(data, o, L), f = makeFormatters(data, o.locale);
556
+ var table = document.createElement("table");
557
+ table.className = "vhm-table";
558
+ if (data.title) {
559
+ var cap = htmlEl("caption", null, table);
560
+ cap.textContent = data.title;
561
+ cap.style.cssText = "text-align:left;font-weight:600;padding:0 6px 6px";
562
+ }
563
+ var head = htmlEl("tr", null, htmlEl("thead", null, table));
564
+ var th0 = htmlEl("th", null, head); th0.scope = "col"; th0.textContent = p.rowDim.label;
565
+ p.cols.forEach(function (c) { var th = htmlEl("th", null, head); th.scope = "col"; th.textContent = c.label; });
566
+ var thT = htmlEl("th", null, head); thT.scope = "col"; thT.textContent = L.total;
567
+ var body = htmlEl("tbody", null, table);
568
+ p.rows.forEach(function (r, ri) {
569
+ var tr = htmlEl("tr", null, body);
570
+ var th = htmlEl("th", null, tr); th.scope = "row"; th.textContent = r.label; th.style.textAlign = "left"; th.style.fontWeight = "400";
571
+ p.values[ri].forEach(function (v) { htmlEl("td", null, tr).textContent = v ? f.value(v) : "—"; });
572
+ htmlEl("td", null, tr).textContent = f.value(r.total);
573
+ });
574
+ var trT = htmlEl("tr", "vhm-total", body);
575
+ htmlEl("td", null, trT).textContent = L.total;
576
+ p.cols.forEach(function (c) { htmlEl("td", null, trT).textContent = f.value(c.total); });
577
+ htmlEl("td", null, trT).textContent = f.value(p.total);
578
+ return table;
579
+ };
580
+
581
+ Chart.prototype.destroy = function () {
582
+ if (this.toolkit) this.toolkit.destroy();
583
+ if (this._observer) this._observer.disconnect();
584
+ if (this._onResize) root.removeEventListener("resize", this._onResize);
585
+ document.removeEventListener("pointerdown", this._onDocTap);
586
+ if (this.element.parentNode) this.element.parentNode.removeChild(this.element);
587
+ };
588
+
589
+ Chart.prototype._hideTip = function () {
590
+ this.tipEl.classList.remove("vhm-on");
591
+ if (this._focusRect) this._focusRect.setAttribute("opacity", 0);
592
+ if (this._boldReset) this._boldReset();
593
+ };
594
+
595
+ Chart.prototype._placeTip = function (lines, anchor, evt) {
596
+ var tip = this.tipEl;
597
+ tip.textContent = "";
598
+ lines.forEach(function (ln, i) {
599
+ if (i) tip.appendChild(document.createElement("br"));
600
+ var node = i === 0 ? document.createElement("b") : document.createTextNode("");
601
+ node.textContent = ln;
602
+ tip.appendChild(node);
603
+ });
604
+ var box = this.element.getBoundingClientRect();
605
+ var px = evt && evt.clientX ? evt.clientX : anchor.left + anchor.width / 2;
606
+ var py = evt && evt.clientY ? evt.clientY : anchor.top;
607
+ tip.classList.add("vhm-on");
608
+ var tw = tip.offsetWidth, th = tip.offsetHeight;
609
+ var left = clamp(px - box.left - tw / 2, 4, Math.max(4, box.width - tw - 4));
610
+ var top = py - box.top - th - 14;
611
+ if (top < 0) top = (anchor.bottom != null ? anchor.bottom : py) - box.top + 10;
612
+ tip.style.left = left + "px";
613
+ tip.style.top = top + "px";
614
+ };
615
+
616
+ Chart.prototype.redraw = function () {
617
+ var o = this.options, data = o.data, self = this;
618
+ var theme = resolveTheme(o.theme), L = this._labels();
619
+ var p = buildPivot(data, o, L);
620
+ var f = makeFormatters(data, o.locale);
621
+ // Concentration figures always use the full grid, so grouping into Other never changes them.
622
+ var pFull = (o.topRows > 0 || o.topColumns > 0) ? buildPivot(data, assign({}, o, { topRows: 0, topColumns: 0 }), L) : p;
623
+ var lim = this._limit(), conc = concentration(pFull, lim);
624
+ var el = this.element, ramp = makeRamp(theme);
625
+ var paper = theme.background && theme.background !== "transparent" ? theme.background : "#ffffff";
626
+ var family = theme.fontFamily === "inherit"
627
+ ? (root.getComputedStyle ? root.getComputedStyle(this.container).fontFamily : "sans-serif")
628
+ : theme.fontFamily;
629
+ var st = el.style;
630
+ st.setProperty("--vhm-text", theme.text);
631
+ st.setProperty("--vhm-muted", theme.mutedText);
632
+ st.setProperty("--vhm-bg", theme.background);
633
+ st.setProperty("--vhm-font", family);
634
+ st.setProperty("--vhm-focus", theme.focus);
635
+ st.setProperty("--vhm-tip-bg", theme.tooltipBackground);
636
+ st.setProperty("--vhm-tip-text", theme.tooltipText);
637
+ st.setProperty("--vhm-summary-bg", theme.summaryBackground);
638
+ el.classList.toggle("vhm-filled", !!theme.background && theme.background !== "transparent");
639
+ el.classList.toggle("vhm-animate", !!this._animateNext);
640
+
641
+ // ---- Fit the columns to the space ------------------------------------------
642
+ var hostW = Math.max(this.plotHost.clientWidth || el.clientWidth || 0, 280);
643
+ this._lastWidth = Math.round(el.clientWidth);
644
+ var narrow = hostW < 560;
645
+ var fs = Number(theme.fontSize) || 12;
646
+ var headSize = narrow ? fs - 1.5 : fs - 0.5, cellSize = narrow ? fs - 2 : fs - 1;
647
+ var cellH = o.cellHeight || (narrow ? 28 : 34);
648
+ var gap = Math.max(0, Number(theme.cellGap) || 0);
649
+ var minCell = narrow ? 26 : 34;
650
+ var rowLabelFull = Math.max.apply(null, p.rows.map(function (r) { return textWidth(r.label, headSize, 400, family); }));
651
+ var labelW = Math.min(Math.ceil(rowLabelFull) + 12, Math.round(hostW * (narrow ? 0.3 : 0.26)));
652
+ 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;
653
+ if (o.totals && narrow) totalsW = Math.min(totalsW, 64);
654
+ var totalsGap = o.totals ? 8 : 0;
655
+ var gridW = hostW - labelW - totalsGap - totalsW - 2;
656
+ var fitMode = o.fit || "auto", grouped = false;
657
+ var fitsN = Math.floor(gridW / minCell);
658
+ var canGroup = fitMode === "group" || (fitMode === "auto" && !p.colDim.ordered && !(o.topColumns > 0));
659
+ if (canGroup && p.cols.length > fitsN && fitsN >= 3) {
660
+ p = buildPivot(data, assign({}, o, { topColumns: fitsN - 1 }), L);
661
+ grouped = true;
662
+ }
663
+
664
+ var nR = p.rows.length, nC = p.cols.length;
665
+ var rowWord = (p.rowDim.plural || p.rowDim.label).toLowerCase();
666
+ var colWord = (p.colDim.plural || p.colDim.label).toLowerCase();
667
+
668
+ // ---- Metric shown in the cells ------------------------------------------
669
+ var mode = o.valueMode;
670
+ if (["amount", "shareOfTotal", "shareOfRow", "shareOfColumn"].indexOf(mode) < 0) mode = "amount";
671
+ var metric = function (r, c) {
672
+ var v = p.values[r][c];
673
+ if (mode === "shareOfTotal") return p.total ? v / p.total : 0;
674
+ if (mode === "shareOfRow") return p.rows[r].total ? v / p.rows[r].total : 0;
675
+ if (mode === "shareOfColumn") return p.cols[c].total ? v / p.cols[c].total : 0;
676
+ return v;
677
+ };
678
+ var maxM = 0;
679
+ for (var r0 = 0; r0 < nR; r0++) for (var c0 = 0; c0 < nC; c0++) maxM = Math.max(maxM, metric(r0, c0));
680
+ var useSqrt = o.scale === "sqrt";
681
+ var tOf = function (m) { if (maxM <= 0) return 0; var t = m / maxM; return useSqrt ? Math.sqrt(t) : t; };
682
+ var mText = function (m, short) {
683
+ if (mode === "amount") return short ? f.compact(m) : f.value(m);
684
+ return f.percent(m, short ? 0 : 1);
685
+ };
686
+
687
+ // ---- Summary --------------------------------------------------------------
688
+ var sum = this.summaryEl;
689
+ sum.textContent = "";
690
+ sum.style.display = o.summary ? "" : "none";
691
+ if (o.summary) {
692
+ var stat = function (label, value, note) {
693
+ var d = htmlEl("div", "vhm-stat", sum);
694
+ htmlEl("div", "vhm-stat-label", d).textContent = label;
695
+ htmlEl("div", "vhm-stat-value", d).textContent = value;
696
+ if (note) htmlEl("div", "vhm-stat-note", d).textContent = note;
697
+ };
698
+ stat(L.totalExposure, f.value(p.total), fill(L.gridNote, { rows: pFull.rows.length, rowDim: rowWord, cols: pFull.cols.length, colDim: colWord }));
699
+ if (conc.largest) {
700
+ 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));
701
+ }
702
+ stat(L.hhi, f.count(conc.hhi), fill(L.hhiNote, { n: f.count(Math.round(conc.effective)) }));
703
+ if (lim) stat(L.aboveLimit, f.count(conc.above.length), fill(L.aboveNote, { limit: pct(lim) }));
704
+ else stat(L.top5, f.percent(conc.top5), L.top5Note);
705
+ }
706
+
707
+ // ---- Legend --------------------------------------------------------------
708
+ var legend = this.legendEl;
709
+ legend.textContent = "";
710
+ legend.style.display = o.legend ? "" : "none";
711
+ if (o.legend) {
712
+ var rampWrap = htmlEl("span", "vhm-ramp", legend);
713
+ var bar = htmlEl("span", "vhm-ramp-bar", rampWrap);
714
+ bar.style.background = "linear-gradient(to right," + [0, 0.25, 0.5, 0.75, 1].map(function (t) { return ramp(t); }).join(",") + ")";
715
+ var ticks = htmlEl("span", "vhm-ramp-ticks", rampWrap);
716
+ var midVal = useSqrt ? maxM * 0.25 : maxM * 0.5;
717
+ [0, midVal, maxM].forEach(function (v) { htmlEl("span", null, ticks).textContent = mText(v, true); });
718
+ var emptyItem = htmlEl("span", null, legend);
719
+ var es = svgEl("svg", { width: 14, height: 14, "aria-hidden": "true" }, emptyItem);
720
+ 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);
721
+ emptyItem.appendChild(document.createTextNode(L.empty));
722
+ if (lim) {
723
+ var limItem = htmlEl("span", null, legend);
724
+ var ls = svgEl("svg", { width: 14, height: 14, "aria-hidden": "true" }, limItem);
725
+ 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);
726
+ svgEl("rect", { x: 3.5, y: 3.5, width: 7, height: 7, rx: 1, fill: "none", stroke: paper, "stroke-width": 1 }, ls);
727
+ limItem.appendChild(document.createTextNode(fill(L.limitLegend, { limit: pct(lim) })));
728
+ }
729
+ }
730
+
731
+ // ---- Layout ----------------------------------------------------------------
732
+ var cellW = gridW / nC;
733
+ var scrolls = false;
734
+ if (cellW < minCell) { cellW = minCell; scrolls = true; }
735
+ gridW = cellW * nC;
736
+
737
+ // Column headers: one or two lines if they fit, otherwise tilted.
738
+ var colLines = p.cols.map(function (c) { return wrapTwo(c.label, cellW - 4, headSize, 400, family); });
739
+ var tiltCols = colLines.some(function (x) { return x === null; });
740
+ var colLabelMax = Math.max.apply(null, p.cols.map(function (c) { return textWidth(c.label, headSize, 400, family); }));
741
+ var maxColLabel = Math.min(colLabelMax, 140);
742
+ var headerH = tiltCols
743
+ ? Math.ceil(maxColLabel * 0.7071 + headSize + 10)
744
+ : (Math.max.apply(null, colLines.map(function (x) { return x.length; })) * (headSize + 3) + 10);
745
+ var tiltOverflow = tiltCols ? Math.max(0, maxColLabel * 0.7071 - totalsW - totalsGap) : 0;
746
+ var W = labelW + gridW + totalsGap + totalsW + 2 + tiltOverflow;
747
+ if (W > hostW + 0.5) scrolls = true;
748
+ var gridTop = headerH;
749
+ var totalsRowH = o.totals ? cellH : 0;
750
+ var H = gridTop + nR * cellH + (o.totals ? totalsGap + totalsRowH : 0) + 4;
751
+ var x0 = labelW;
752
+ var cx = function (c) { return x0 + c * cellW; };
753
+ var cy = function (r) { return gridTop + r * cellH; };
754
+
755
+ // ---- SVG ----------------------------------------------------------------------
756
+ this.plotHost.textContent = "";
757
+ this.noteEl.textContent = scrolls ? fill(L.scrollNote, { columns: colWord }) : grouped ? fill(L.groupNote, { columns: colWord }) : "";
758
+ this.noteEl.style.display = scrolls || grouped ? "" : "none";
759
+ var svg = svgEl("svg", {
760
+ "class": "vhm-plot", viewBox: "0 0 " + W + " " + H, width: W, height: H, tabindex: 0, role: "img",
761
+ "aria-label": o.ariaLabel || [data.title, p.rowDim.label + " by " + p.colDim.label,
762
+ 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(". ")
763
+ }, this.plotHost);
764
+ if (!scrolls) { svg.style.width = "100%"; svg.style.height = "auto"; }
765
+ var txt = function (attrs, content, parent) {
766
+ var t = svgEl("text", assign({ "font-family": family }, attrs), parent || svg);
767
+ t.textContent = content;
768
+ return t;
769
+ };
770
+
771
+ // Column headers
772
+ var colHeadEls = [];
773
+ p.cols.forEach(function (c, ci) {
774
+ var mx = cx(ci) + cellW / 2;
775
+ var g = svgEl("g", null, svg);
776
+ if (tiltCols) {
777
+ var by = headerH - 6;
778
+ txt({ x: mx - 2, y: by, "text-anchor": "start", transform: "rotate(-45 " + (mx - 2) + " " + by + ")",
779
+ "font-size": headSize, fill: c.other ? theme.mutedText : theme.headerText }, ellipsis(c.label, 140, headSize, 400, family), g);
780
+ } else {
781
+ var lines = colLines[ci];
782
+ lines.forEach(function (ln, k) {
783
+ txt({ x: mx, y: headerH - 6 - (lines.length - 1 - k) * (headSize + 3), "text-anchor": "middle", "font-size": headSize,
784
+ fill: c.other ? theme.mutedText : theme.headerText }, ln, g);
785
+ });
786
+ }
787
+ colHeadEls.push(g);
788
+ });
789
+ if (o.totals) {
790
+ txt({ x: x0 + gridW + totalsGap + totalsW - 4, y: headerH - 6, "text-anchor": "end", "font-size": headSize, "font-weight": 600, fill: theme.text }, L.total);
791
+ }
792
+
793
+ // Row headers
794
+ var rowHeadEls = p.rows.map(function (r, ri) {
795
+ var label = ellipsis(r.label, labelW - 12, headSize, 400, family);
796
+ var t = txt({ x: labelW - 8, y: cy(ri) + cellH / 2 + headSize * 0.35, "text-anchor": "end", "font-size": headSize,
797
+ fill: r.other ? theme.mutedText : theme.headerText }, label);
798
+ if (label !== r.label) { var tt = svgEl("title", null, t); tt.textContent = r.label; }
799
+ return t;
800
+ });
801
+ if (o.totals) {
802
+ 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);
803
+ }
804
+
805
+ // Cells
806
+ var cellsG = svgEl("g", null, svg);
807
+ var showLabels = o.cellLabels === true || (o.cellLabels === "auto");
808
+ for (var r = 0; r < nR; r++) {
809
+ for (var c = 0; c < nC; c++) {
810
+ var v = p.values[r][c], m = metric(r, c);
811
+ var colour = v > 0 ? ramp(tOf(m)) : theme.empty;
812
+ 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),
813
+ rx: Math.min(theme.cellRadius, cellW / 4), fill: colour, "class": "vhm-cell", "data-r": r, "data-c": c }, cellsG);
814
+ // An empty cell gets a dashed outline, so "no exposure" never looks like a very small exposure.
815
+ 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); }
816
+ rect.style.animationDelay = Math.min((r + c) * 18, 500) + "ms";
817
+ if (lim && p.total > 0 && v / p.total > lim + 1e-12 && !p.rows[r].other && !p.cols[c].other) {
818
+ 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),
819
+ rx: Math.min(theme.cellRadius, cellW / 4), fill: "none", stroke: theme.limit, "stroke-width": 2, "pointer-events": "none" }, cellsG);
820
+ 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),
821
+ rx: Math.max(0, Math.min(theme.cellRadius, cellW / 4) - 1), fill: "none", stroke: paper, "stroke-width": 1, "pointer-events": "none" }, cellsG);
822
+ }
823
+ if (showLabels && v > 0 && cellH - gap >= 16) {
824
+ var room = cellW - gap - 8;
825
+ var label = mText(m, false);
826
+ if (textWidth(label, cellSize, 500, family) > room) label = mText(m, true);
827
+ if (textWidth(label, cellSize, 500, family) <= room) {
828
+ // Use whichever text colour stands out more from this cell, so numbers stay readable on mid-tones too.
829
+ var onCell = contrast(colour, theme.cellTextOnDark) > contrast(colour, theme.cellText) ? theme.cellTextOnDark : theme.cellText;
830
+ txt({ x: cx(c) + cellW / 2, y: cy(r) + cellH / 2 + cellSize * 0.35, "text-anchor": "middle", "font-size": cellSize, "font-weight": 500,
831
+ fill: onCell, "pointer-events": "none", "class": "vhm-cell-label" }, label, cellsG);
832
+ }
833
+ }
834
+ }
835
+ }
836
+
837
+ // Totals as data bars
838
+ var totalsG = null;
839
+ if (o.totals) {
840
+ totalsG = svgEl("g", null, svg);
841
+ var maxRow = Math.max.apply(null, p.rows.map(function (x) { return x.total; })) || 1;
842
+ var maxCol = Math.max.apply(null, p.cols.map(function (x) { return x.total; })) || 1;
843
+ var tx0 = x0 + gridW + totalsGap;
844
+ p.rows.forEach(function (rg, ri) {
845
+ var w = Math.max(2, (totalsW - 2) * rg.total / maxRow);
846
+ 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,
847
+ "data-tr": ri }, totalsG);
848
+ var label = f.value(rg.total);
849
+ if (textWidth(label, fs - 1, 600, family) > totalsW - 6) label = f.compact(rg.total);
850
+ 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);
851
+ });
852
+ var ty = cy(nR) + totalsGap;
853
+ p.cols.forEach(function (cg, ci) {
854
+ var h = Math.max(2, (cellH - gap - 4) * cg.total / maxCol);
855
+ 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,
856
+ fill: theme.totalBar, "fill-opacity": theme.totalBarOpacity, "data-tc": ci }, totalsG);
857
+ var label = f.value(cg.total);
858
+ if (textWidth(label, cellSize, 600, family) > cellW - gap - 6) label = f.compact(cg.total);
859
+ if (textWidth(label, cellSize, 600, family) <= cellW - gap - 6) {
860
+ 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);
861
+ }
862
+ });
863
+ var grand = f.value(p.total);
864
+ if (textWidth(grand, fs - 1, 700, family) > totalsW - 6) grand = f.compact(p.total);
865
+ 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);
866
+ }
867
+
868
+ // Focus ring for hover and keyboard
869
+ 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);
870
+
871
+ // ---- Interaction ------------------------------------------------------------
872
+ var cellInfo = function (r, c) {
873
+ var v = p.values[r][c];
874
+ return {
875
+ row: p.rows[r].label, column: p.cols[c].label, rowIndex: r, columnIndex: c, value: v,
876
+ shareOfTotal: p.total ? v / p.total : 0,
877
+ shareOfRow: p.rows[r].total ? v / p.rows[r].total : 0,
878
+ shareOfColumn: p.cols[c].total ? v / p.cols[c].total : 0,
879
+ aboveLimit: !!(lim && p.total && v / p.total > lim + 1e-12 && !p.rows[r].other && !p.cols[c].other),
880
+ rowMembers: p.rows[r].members.slice(), columnMembers: p.cols[c].members.slice()
881
+ };
882
+ };
883
+ var bolded = [];
884
+ this._boldReset = function () { bolded.forEach(function (n) { n.removeAttribute("font-weight"); }); bolded = []; };
885
+ var boldHeaders = function (r, c) {
886
+ self._boldReset();
887
+ var rt = rowHeadEls[r]; rt.setAttribute("font-weight", 600); bolded.push(rt);
888
+ Array.prototype.forEach.call(colHeadEls[c].childNodes, function (n) { n.setAttribute("font-weight", 600); bolded.push(n); });
889
+ };
890
+ var showCell = function (r, c, evt) {
891
+ self._active = [r, c];
892
+ self._focusRect.setAttribute("x", cx(c) + gap / 2 - 1);
893
+ self._focusRect.setAttribute("y", cy(r) + gap / 2 - 1);
894
+ self._focusRect.setAttribute("width", cellW - gap + 2);
895
+ self._focusRect.setAttribute("height", cellH - gap + 2);
896
+ self._focusRect.setAttribute("opacity", 1);
897
+ boldHeaders(r, c);
898
+ if (!o.tooltip) return;
899
+ var info = cellInfo(r, c), lines;
900
+ if (typeof o.tooltipFormatter === "function") {
901
+ lines = o.tooltipFormatter(info, f);
902
+ if (!Array.isArray(lines)) lines = [String(lines)];
903
+ } else {
904
+ lines = [info.row + " × " + info.column];
905
+ if (!info.value) lines.push(L.empty);
906
+ else {
907
+ lines.push(L.exposure + ": " + f.value(info.value));
908
+ lines.push(L.shareOfTotal + ": " + f.percent(info.shareOfTotal));
909
+ lines.push(fill(L.shareOfRow, { row: info.row }) + ": " + f.percent(info.shareOfRow));
910
+ lines.push(fill(L.shareOfColumn, { column: info.column }) + ": " + f.percent(info.shareOfColumn));
911
+ if (info.aboveLimit) lines.push(fill(L.limitTip, { limit: pct(lim) }));
912
+ }
913
+ if (p.rows[r].other) lines.push(fill(L.includes, { list: p.rows[r].members.join(", ") }));
914
+ if (p.cols[c].other) lines.push(fill(L.includes, { list: p.cols[c].members.join(", ") }));
915
+ }
916
+ var rb = svg.getBoundingClientRect(), k = rb.width / W;
917
+ 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);
918
+ };
919
+ var totalTip = function (isRow, i, evt) {
920
+ var g = isRow ? p.rows[i] : p.cols[i];
921
+ var lines = [fill(L.rowTotalTip, { label: g.label }), f.value(g.total) + " · " + f.percent(p.total ? g.total / p.total : 0) + " " + L.shareOfTotal.toLowerCase()];
922
+ if (g.other) lines.push(g.members.join(", "));
923
+ self._placeTip(lines, { left: evt.clientX, top: evt.clientY, width: 0 }, evt);
924
+ };
925
+
926
+ cellsG.addEventListener("mousemove", function (e) {
927
+ var t = e.target; if (!t.hasAttribute || !t.hasAttribute("data-r")) return;
928
+ showCell(+t.getAttribute("data-r"), +t.getAttribute("data-c"), e);
929
+ });
930
+ cellsG.addEventListener("pointerdown", function (e) {
931
+ var t = e.target; if (!t.hasAttribute || !t.hasAttribute("data-r")) return;
932
+ showCell(+t.getAttribute("data-r"), +t.getAttribute("data-c"), e);
933
+ });
934
+ cellsG.addEventListener("mouseleave", function () { self._hideTip(); });
935
+ if (typeof o.onClick === "function") {
936
+ cellsG.style.cursor = "pointer";
937
+ cellsG.addEventListener("click", function (e) {
938
+ var t = e.target; if (!t.hasAttribute || !t.hasAttribute("data-r")) return;
939
+ o.onClick(cellInfo(+t.getAttribute("data-r"), +t.getAttribute("data-c")), e);
940
+ });
941
+ }
942
+ if (totalsG) {
943
+ totalsG.addEventListener("mousemove", function (e) {
944
+ var t = e.target;
945
+ if (t.hasAttribute && t.hasAttribute("data-tr")) totalTip(true, +t.getAttribute("data-tr"), e);
946
+ else if (t.hasAttribute && t.hasAttribute("data-tc")) totalTip(false, +t.getAttribute("data-tc"), e);
947
+ });
948
+ totalsG.addEventListener("mouseleave", function () { self._hideTip(); });
949
+ }
950
+
951
+ // Positions kept for notes
952
+ this._geom = { rows: p.rows, cols: p.cols, cx: cx, cy: cy, cellW: cellW, cellH: cellH, gap: gap };
953
+
954
+ svg.setAttribute("aria-describedby", this.tipEl.id);
955
+ var start = [0, 0];
956
+ if (conc.largest) {
957
+ var sr = p.rows.map(function (g) { return g.key; }).indexOf(pFull.rows[conc.largest.r].key);
958
+ var sc = p.cols.map(function (g) { return g.key; }).indexOf(pFull.cols[conc.largest.c].key);
959
+ if (sr >= 0 && sc >= 0) start = [sr, sc];
960
+ }
961
+ svg.addEventListener("focus", function () {
962
+ var a = self._active && self._active[0] < nR && self._active[1] < nC ? self._active : start;
963
+ showCell(a[0], a[1]);
964
+ });
965
+ svg.addEventListener("blur", function () { self._hideTip(); });
966
+ svg.addEventListener("keydown", function (e) {
967
+ var a = self._active && self._active[0] < nR && self._active[1] < nC ? self._active.slice() : start.slice();
968
+ if (e.key === "ArrowLeft") a[1] = Math.max(0, a[1] - 1);
969
+ else if (e.key === "ArrowRight") a[1] = Math.min(nC - 1, a[1] + 1);
970
+ else if (e.key === "ArrowUp") a[0] = Math.max(0, a[0] - 1);
971
+ else if (e.key === "ArrowDown") a[0] = Math.min(nR - 1, a[0] + 1);
972
+ else if (e.key === "Home") a[1] = 0;
973
+ else if (e.key === "End") a[1] = nC - 1;
974
+ else if ((e.key === "Enter" || e.key === " ") && typeof o.onClick === "function") { e.preventDefault(); o.onClick(cellInfo(a[0], a[1]), e); return; }
975
+ else return;
976
+ e.preventDefault();
977
+ showCell(a[0], a[1]);
978
+ });
979
+
980
+ this._hideTip();
981
+ this._animateNext = false;
982
+ return this;
983
+ };
984
+
985
+ /* ======================================================================
986
+ 5. EXPORT AND NOTES
987
+ Used by the chart menu in veyforma-toolkit.js, and available to you.
988
+ ====================================================================== */
989
+ function findGroup(groups, key) {
990
+ if (key == null) return -1;
991
+ key = String(key);
992
+ for (var i = 0; i < groups.length; i++) {
993
+ if (groups[i].label === key || groups[i].key === key || groups[i].members.indexOf(key) >= 0) return i;
994
+ }
995
+ return -1;
996
+ }
997
+
998
+ /** One-paragraph guide to reading the heatmap. */
999
+ Chart.prototype.howToRead = function () {
1000
+ var p = buildPivot(this.options.data, this.options, this._labels());
1001
+ var rw = (p.rowDim.label || "row").toLowerCase(), cw = (p.colDim.label || "column").toLowerCase();
1002
+ return "Each cell is the exposure where a " + rw + " meets a " + cw + "; darker cells hold more. " +
1003
+ "The bars on the right and along the bottom are the totals for each " + rw + " and " + cw + ". " +
1004
+ "HHI measures concentration: the higher it is, the more the book depends on a few cells." +
1005
+ (this._limit() ? " Cells with a double outline are above the concentration limit." : "");
1006
+ };
1007
+
1008
+ /** A plain-English summary of the main findings, for screen readers and the explanation box. */
1009
+ Chart.prototype.describe = function () {
1010
+ var st = this.getStats(), f = makeFormatters(this.options.data, this.options.locale);
1011
+ var p = buildPivot(this.options.data, this.options, this._labels());
1012
+ var out = ["In this example total exposure is " + f.value(st.total) + " across " + st.rows + " " + (p.rowDim.plural || p.rowDim.label).toLowerCase() +
1013
+ " and " + st.columns + " " + (p.colDim.plural || p.colDim.label).toLowerCase() + "."];
1014
+ 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).");
1015
+ out.push("HHI is " + f.count(st.hhi) + ", like " + f.count(Math.round(st.effectiveCells)) + " equal-sized cells.");
1016
+ if (st.limit) out.push(st.aboveLimit.length + " " + (st.aboveLimit.length === 1 ? "cell is" : "cells are") + " above the " + pct(st.limit) + " limit.");
1017
+ return out.join(" ");
1018
+ };
1019
+
1020
+ /** Tables, wording and audit details for the export menu. Uses the full grid, without Other grouping. */
1021
+ Chart.prototype.getExportData = function () {
1022
+ var o = this.options, data = o.data, L = this._labels();
1023
+ var p = buildPivot(data, assign({}, o, { topRows: 0, topColumns: 0 }), L), f = makeFormatters(data, o.locale);
1024
+ var st = this.getStats(), lim = this._limit();
1025
+ var unit = { prefix: data.prefix || "", suffix: data.suffix || "", decimals: data.decimals != null ? data.decimals : 0, negatives: data.negatives };
1026
+ 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 }]);
1027
+ var mRows = p.rows.map(function (r, ri) { return [r.label].concat(p.values[ri], [r.total]); });
1028
+ mRows.push([L.total].concat(p.cols.map(function (c) { return c.total; }), [p.total]));
1029
+ 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)]); });
1030
+ mText.push([L.total].concat(p.cols.map(function (c) { return f.value(c.total); }), [f.value(p.total)]));
1031
+ var cells = [];
1032
+ 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]); }); });
1033
+ cells.sort(function (a, b) { return b[2] - a[2]; });
1034
+ var above = function (share) { return lim && share > lim + 1e-12 ? "Yes" : "No"; };
1035
+ var conc = [
1036
+ [L.totalExposure, st.total, f.value(st.total)],
1037
+ [L.hhi, st.hhi, f.count(st.hhi)],
1038
+ ["Effective number of cells", st.effectiveCells, f.count(Math.round(st.effectiveCells))],
1039
+ [L.top5, st.top5Share, f.percent(st.top5Share)]
1040
+ ];
1041
+ if (st.largest) conc.push([L.largest, st.largest.share, st.largest.row + " × " + st.largest.column + " · " + f.percent(st.largest.share)]);
1042
+ if (lim) { conc.push(["Limit (share of total)", lim, pct(lim)]); conc.push([L.aboveLimit, st.aboveLimit.length, f.count(st.aboveLimit.length)]); }
1043
+ var notes = (o.annotations || []).map(function (a, i) { return [String(i + 1), String(a.row || ""), String(a.column || ""), a.text || ""]; });
1044
+ var sheets = [
1045
+ { name: "Matrix", columns: cols, rows: mRows, text: mText, bold: mRows.map(function (r, i) { return i === mRows.length - 1; }) },
1046
+ { name: "Cells", columns: [{ label: p.rowDim.label, type: "text" }, { label: p.colDim.label, type: "text" }, { label: L.exposure, type: "number", unit: unit },
1047
+ { label: L.shareOfTotal, type: "percent", decimals: 2 }, { label: L.aboveLimit, type: "text" }],
1048
+ rows: cells.map(function (c) { return [c[0], c[1], c[2], c[3], above(c[3])]; }),
1049
+ text: cells.map(function (c) { return [c[0], c[1], f.value(c[2]), f.percent(c[3], 2), above(c[3])]; }) },
1050
+ { name: "Concentration", columns: [{ label: "Measure", type: "text" }, { label: "Value", type: "general" }, { label: "As shown", type: "text" }],
1051
+ 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]]; }) }
1052
+ ];
1053
+ 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 });
1054
+ return {
1055
+ title: data.title || "Exposure heatmap", subtitle: data.subtitle || "", summary: this.describe(),
1056
+ library: "Veyforma Exposure Heatmap " + VERSION, sheets: sheets,
1057
+ 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"],
1058
+ ["Grid", p.rowDim.label + " × " + p.colDim.label + ", full grid without Other grouping"],
1059
+ ["Unit", data.unit], ["Limit", lim ? pct(lim) + " of total" : null], ["As of", data.asOf], ["Data source", data.source]]
1060
+ };
1061
+ };
1062
+
1063
+ /** Where a note's marker goes: inside the top-left corner of its cell. */
1064
+ Chart.prototype._annotationPoint = function (a) {
1065
+ var g = this._geom;
1066
+ if (!g || !a) return null;
1067
+ var r = findGroup(g.rows, a.row), c = findGroup(g.cols, a.column);
1068
+ if (r < 0 || c < 0) return null;
1069
+ // A cell grouped into "Other" keeps its note: the marker moves to the Other cell and the list says so.
1070
+ var grouped = (g.rows[r] && g.rows[r].other) || (g.cols[c] && g.cols[c].other);
1071
+ 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 };
1072
+ };
1073
+ /** The cell under the pointer (or the cell picked with the keyboard), as a note target. */
1074
+ Chart.prototype._annotationTarget = function (evt) {
1075
+ var g = this._geom, r, c;
1076
+ if (!g) return null;
1077
+ if (evt) {
1078
+ var t = evt.target;
1079
+ if (!t || !t.getAttribute || t.getAttribute("data-r") == null) return null;
1080
+ r = +t.getAttribute("data-r"); c = +t.getAttribute("data-c");
1081
+ } else if (this._active) { r = this._active[0]; c = this._active[1]; }
1082
+ else return null;
1083
+ if (!g.rows[r] || !g.cols[c] || g.rows[r].other || g.cols[c].other) return null;
1084
+ return { row: g.rows[r].label, column: g.cols[c].label };
1085
+ };
1086
+ Chart.prototype._annotationLabel = function (a) { return [a.row, a.column].filter(Boolean).join(" × "); };
1087
+
1088
+ /* ======================================================================
1089
+ 6. PUBLIC API
1090
+ ====================================================================== */
1091
+ root.VeyHeatmap = {
1092
+ version: VERSION,
1093
+ /** Draws a heatmap inside a container element or CSS selector. */
1094
+ create: function (target, options) { return new Chart(target, options); },
1095
+ /** Adds or replaces a named theme. Use "extends" to start from another theme. */
1096
+ registerTheme: function (name, theme) {
1097
+ if (!name || typeof name !== "string") throw new Error("VeyHeatmap: registerTheme needs a name.");
1098
+ THEMES[name] = resolveTheme(theme || {});
1099
+ return THEMES[name];
1100
+ },
1101
+ /** Returns the full set of values for a theme name or partial theme. */
1102
+ getTheme: function (theme) { return resolveTheme(theme); },
1103
+ /** Lists the names of all available themes. */
1104
+ listThemes: function () { return Object.keys(THEMES); }
1105
+ };
1106
+ })(__vfRoot);
1107
+
1108
+ // Risk-Factor Tornado – Veyforma Chart Library · https://www.veyforma.com/charts/risk-factor-tornado
1109
+ /*!
1110
+ * Veyforma Risk-Factor Tornado v1.0.0
1111
+ * Ranks the risk factors that move P&L, economic value or capital the most, for a down and
1112
+ * an up shock to each factor. Impacts come from full revaluation or from delta and gamma
1113
+ * (Taylor), and can be rescaled to any shock size. On top of the classic tornado it shows the
1114
+ * convexity of each factor (how unequal the up and down results are), breaches of a loss
1115
+ * limit, how much the top factors explain, groups such as risk classes, the interaction when
1116
+ * every factor is shocked together, and each factor's share of the combined move once the
1117
+ * factors' correlations are taken into account, so hedges become visible.
1118
+ * Original work created for Veyforma. Contains no third-party code.
1119
+ * Released under the MIT License. Copyright (c) 2026 Veyforma.
1120
+ * https://github.com/veyforma/veyforma-charts
1121
+ *
1122
+ * Load veyforma-toolkit.js as well to get the chart menu: full screen, print,
1123
+ * PNG, JPEG, SVG, PDF, CSV and Excel downloads, copy, notes and the
1124
+ * "How to read this chart" box.
1125
+ *
1126
+ * File layout
1127
+ * 1. Settings .......... themes, labels and options
1128
+ * 2. Helpers ........... formatting and small utilities
1129
+ * 3. Calculation ....... impacts, ranking, convexity, groups, correlated contributions
1130
+ * 4. Chart instance .... factor, group and contribution views, tooltips, keyboard
1131
+ * 5. Export and notes .. data for the Veyforma Toolkit menu (optional file)
1132
+ * 6. Public API ........ window.VeyRiskTornado
1133
+ *
1134
+ * Method in one paragraph (see the manual for detail):
1135
+ * Each factor has a down and an up impact, given directly or as Δ·s + ½Γ·s² for the shock s.
1136
+ * Swing = |up − down|; the linear part is L = (up − down) ÷ 2 and the convexity C = (up + down) ÷ 2,
1137
+ * so a shock k times larger moves the result by about L·k + C·k². Factors are ranked by swing (or by
1138
+ * their worst result). Combined move σ = √(Lᵀ ρ L) with ρ the factor correlations; factor k's share of it
1139
+ * is L_k (ρL)_k ÷ σ, which adds up exactly to σ; a negative share means the factor hedges the others.
1140
+ */
1141
+ (function (root) {
1142
+ "use strict";
1143
+
1144
+ var VERSION = "1.0.0";
1145
+ var SVG_NS = "http://www.w3.org/2000/svg";
1146
+ var instanceCount = 0;
1147
+
1148
+ /* ======================================================================
1149
+ 1. SETTINGS
1150
+ ====================================================================== */
1151
+ var BASE_THEME = {
1152
+ down: "#4b5563", // bars for the down shock
1153
+ up: "#c2410c", // bars for the up shock
1154
+ hedge: "#2f6fed", // contributions that lower the combined move
1155
+ contribution: "#a63d16", // contributions that add to it
1156
+ convexity: "#111827", // convexity marker (midpoint of the two results)
1157
+ limit: "#b91c1c", // loss limit line and breaches
1158
+ grid: "#ececec",
1159
+ axis: "#9ca3af",
1160
+ text: "#111827",
1161
+ mutedText: "#4b5563",
1162
+ axisText: "#4b5563",
1163
+ cardBackground: "#f9fafb",
1164
+ background: "transparent",
1165
+ tooltipBackground: "#111827",
1166
+ tooltipText: "#ffffff",
1167
+ focus: "#c2410c",
1168
+ accent: "#c2410c",
1169
+ fontFamily: "inherit",
1170
+ fontSize: 12
1171
+ };
1172
+ var THEMES = {
1173
+ veyforma: {},
1174
+ mono: { down: "#8a8a8a", up: "#111111", hedge: "#8a8a8a", contribution: "#111111", convexity: "#111111", limit: "#111111", accent: "#111111", focus: "#111111" },
1175
+ "colour-safe": { down: "#2166ac", up: "#b2182b", hedge: "#1b7837", contribution: "#762a83", limit: "#b2182b", accent: "#2166ac" },
1176
+ ocean: { down: "#64748b", up: "#0c6e8f", hedge: "#c2410c", contribution: "#0c3b5e", cardBackground: "#eef5f8", accent: "#0c6e8f" },
1177
+ forest: { down: "#78716c", up: "#4d6b31", hedge: "#2f6fed", contribution: "#22311a", cardBackground: "#f2f4ee", accent: "#4d6b31" },
1178
+ corporate: { down: "#64748b", up: "#1d4ed8", hedge: "#c2410c", contribution: "#1e293b", cardBackground: "#f1f4f8", accent: "#1d4ed8" },
1179
+ midnight: { background: "#111418", down: "#a3abb8", up: "#f08a5d", hedge: "#93c5fd", contribution: "#f08a5d", convexity: "#f3f4f6", limit: "#fb7185",
1180
+ grid: "#252a31", axis: "#4b5563", text: "#f3f4f6", mutedText: "#a3abb8", axisText: "#a3abb8",
1181
+ cardBackground: "#1b2027", tooltipBackground: "#f3f4f6", tooltipText: "#111418", focus: "#93c5fd", accent: "#f08a5d" }
1182
+ };
1183
+
1184
+ var DEFAULT_OPTIONS = {
1185
+ data: null, // required: { factors: [...], … }
1186
+ view: "factors", // "factors" | "groups" | "contribution"
1187
+ sort: "swing", // rank factors by "swing" (|up − down|) or by their "worst" result
1188
+ top: 15, // rows shown before the rest are summed into one "Other" row (0 = all)
1189
+ shockScale: 1, // multiply every shock size, e.g. 2 for twice the shock
1190
+ whatIf: null, // scale positions by factor or group key, e.g. { "EUR 10Y": 0, "FX": 0.5 }
1191
+ theme: "veyforma",
1192
+ locale: undefined,
1193
+ animate: true,
1194
+ summary: true,
1195
+ legend: true,
1196
+ labels: null,
1197
+ ariaLabel: undefined,
1198
+ caption: true,
1199
+ annotations: null, // notes, e.g. [{ factor: "EUR 10Y", text: "Hedge rolled in March" }] or { group, text }
1200
+ onAnnotationsChange: null,
1201
+ onItemClick: null, // function (detail, event): every figure for the factor or group clicked
1202
+ exportRows: 20000, // the factor sheet keeps the largest swings above this many rows
1203
+ toolbar: true
1204
+ };
1205
+
1206
+ var DEFAULT_LABELS = {
1207
+ factors: "Impact by risk factor", groups: "Impact by group", contribution: "Share of the combined move",
1208
+ down: "Down shock", up: "Up shock", swing: "Swing", worst: "Worst result", convexity: "Convexity", linear: "Linear part",
1209
+ limit: "Limit", largest: "Largest driver", worstShock: "Worst single shock", topShare: "Top {n} factors", combined: "Combined move",
1210
+ contributionAdds: "Adds to the combined move", hedge: "Hedges (lowers it)", standalone: "Stand-alone", other: "Other {n} factors",
1211
+ whatIf: "What-if", interaction: "Interaction", noData: "n/a"
1212
+ };
1213
+ /* ======================================================================
1214
+ 2. HELPERS
1215
+ ====================================================================== */
1216
+ function assign(t) {
1217
+ for (var i = 1; i < arguments.length; i++) {
1218
+ var s = arguments[i];
1219
+ if (s) for (var k in s) if (Object.prototype.hasOwnProperty.call(s, k)) t[k] = s[k];
1220
+ }
1221
+ return t;
1222
+ }
1223
+ var warned = {};
1224
+ function warn(msg) { if (warned[msg]) return; warned[msg] = 1; if (root.console && console.warn) console.warn("VeyRiskTornado: " + msg); }
1225
+ function fail(msg) { throw new Error("VeyRiskTornado: " + msg); }
1226
+ function clamp(v, lo, hi) { return Math.min(hi, Math.max(lo, v)); }
1227
+ function fill(t, map) { return String(t).replace(/\{(\w+)\}/g, function (m, k) { return map[k] != null ? map[k] : m; }); }
1228
+ /** A name inside a sentence: "CET1 requirement" stays, "Pillar 1 minimum" becomes "pillar 1 minimum". */
1229
+ function lower(t) { t = String(t); return /^[A-Z0-9]{2}/.test(t) ? t : t.charAt(0).toLowerCase() + t.slice(1); }
1230
+ function num(v) { return typeof v === "number" ? v : v == null || v === "" ? NaN : +v; }
1231
+ function svgEl(tag, attrs, parent) {
1232
+ var n = document.createElementNS(SVG_NS, tag);
1233
+ if (attrs) for (var k in attrs) if (attrs[k] != null) n.setAttribute(k, attrs[k]);
1234
+ if (parent) parent.appendChild(n);
1235
+ return n;
1236
+ }
1237
+ function htmlEl(tag, cls, parent) {
1238
+ var n = document.createElement(tag);
1239
+ if (cls) n.className = cls;
1240
+ if (parent) parent.appendChild(n);
1241
+ return n;
1242
+ }
1243
+ var measureCtx = null;
1244
+ function textWidth(text, size, weight, family) {
1245
+ if (!measureCtx) { var c = document.createElement("canvas"); measureCtx = c.getContext && c.getContext("2d"); }
1246
+ if (!measureCtx) return String(text).length * size * 0.6;
1247
+ measureCtx.font = (weight || 400) + " " + size + "px " + family;
1248
+ return measureCtx.measureText(String(text)).width;
1249
+ }
1250
+ function fit(text, max, size, weight, family) {
1251
+ text = String(text);
1252
+ if (textWidth(text, size, weight, family) <= max) return text;
1253
+ while (text.length > 2 && textWidth(text + "…", size, weight, family) > max) text = text.slice(0, -1);
1254
+ return text.replace(/\s+$/, "") + "…";
1255
+ }
1256
+ function hexRgb(c) {
1257
+ var m = /^#?([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(String(c || "").trim());
1258
+ if (!m) return null;
1259
+ var h = m[1].length === 3 ? m[1].replace(/./g, "$&$&") : m[1], n = parseInt(h, 16);
1260
+ return [(n >> 16) & 255, (n >> 8) & 255, n & 255];
1261
+ }
1262
+ function luminance(rgb) {
1263
+ var a = rgb.map(function (v) { v /= 255; return v <= 0.03928 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4); });
1264
+ return 0.2126 * a[0] + 0.7152 * a[1] + 0.0722 * a[2];
1265
+ }
1266
+ function contrast(a, b) {
1267
+ var x = hexRgb(a), y = hexRgb(b);
1268
+ if (!x || !y) return 21;
1269
+ var l1 = luminance(x), l2 = luminance(y);
1270
+ return (Math.max(l1, l2) + 0.05) / (Math.min(l1, l2) + 0.05);
1271
+ }
1272
+ function ensureContrast(col, bg, min) {
1273
+ var c = hexRgb(col), b = hexRgb(bg);
1274
+ if (!c || !b || contrast(col, bg) >= min) return col;
1275
+ var dark = luminance(b) > 0.4, t = 0, out = col;
1276
+ while (t <= 1 && contrast(out, bg) < min) {
1277
+ t += 0.05;
1278
+ out = "#" + c.map(function (v) { var x = dark ? v * (1 - t) : v + (255 - v) * t; return ("0" + Math.round(x).toString(16)).slice(-2); }).join("");
1279
+ }
1280
+ return out;
1281
+ }
1282
+ function makeFormatters(data, locale) {
1283
+ var decimals = data.decimals != null ? data.decimals : 0, rd = data.ratioDecimals != null ? data.ratioDecimals : 1;
1284
+ var prefix = data.prefix || "", suffix = data.suffix || "", cache = {}, brackets = data.negatives === "brackets";
1285
+ function nf(d) {
1286
+ if (!cache[d]) cache[d] = new Intl.NumberFormat(locale || undefined, { minimumFractionDigits: d, maximumFractionDigits: d });
1287
+ return cache[d];
1288
+ }
1289
+ function value(v, d) {
1290
+ if (v == null || !isFinite(v)) return "–";
1291
+ if (d == null) d = decimals;
1292
+ var r = Number(v.toFixed(d)), body = prefix + nf(d).format(Math.abs(r)) + suffix;
1293
+ if (r >= 0) return body;
1294
+ return brackets ? "(" + body + ")" : "−" + body;
1295
+ }
1296
+ function signed(v, d) { var s = value(v, d); return v != null && Number(v.toFixed(d == null ? decimals : d)) > 0 ? "+" + s : s; }
1297
+ function ratio(v, d) { return v == null || !isFinite(v) ? "–" : (v < 0 ? "−" : "") + nf(d == null ? rd : d).format(Math.abs(v) * 100) + "%"; }
1298
+ function pp(v, d) {
1299
+ if (v == null || !isFinite(v)) return "–";
1300
+ var dd = d == null ? Math.max(rd, 1) : d, r = Number((v * 100).toFixed(dd));
1301
+ return (r > 0 ? "+" : r < 0 ? "−" : "") + nf(dd).format(Math.abs(r)) + " pp";
1302
+ }
1303
+ function percent(v, d) { return v == null || !isFinite(v) ? "–" : nf(d == null ? 1 : d).format(v * 100) + "%"; }
1304
+ return { value: value, signed: signed, ratio: ratio, pp: pp, percent: percent, nf: nf };
1305
+ }
1306
+
1307
+
1308
+ /* ======================================================================
1309
+ 3. CALCULATION
1310
+ ====================================================================== */
1311
+ function finite(v, what) { var x = num(v); if (!isFinite(x)) fail(what + " must be a number."); return x; }
1312
+ function corrOf(v, what) { var x = finite(v, what); if (x < -1 || x > 1) fail(what + " must be between −1 and 1."); return x; }
1313
+
1314
+ /** Reads the factors and works out each one's down and up impact for the shock scale and what-if. */
1315
+ function readFactors(data, k, whatIf) {
1316
+ var list = data.factors;
1317
+ if (!Array.isArray(list) || !list.length) fail("data.factors must be a non-empty array of risk factors.");
1318
+ var seen = {};
1319
+ return list.map(function (x, i) {
1320
+ if (!x || typeof x !== "object") fail("data.factors[" + i + "] is not an object.");
1321
+ if (x.key == null && x.label == null) fail("data.factors[" + i + "] needs a key or a label.");
1322
+ var key = String(x.key != null ? x.key : x.label), w = 'factor "' + key + '"';
1323
+ if (seen[key]) fail(w + " is used twice.");
1324
+ seen[key] = 1;
1325
+ var group = x.group != null ? String(x.group) : "Other";
1326
+ var sd = x.shockDown != null ? finite(x.shockDown, w + ": shockDown") : x.shock != null ? -Math.abs(finite(x.shock, w + ": shock")) : null;
1327
+ var su = x.shockUp != null ? finite(x.shockUp, w + ": shockUp") : x.shock != null ? Math.abs(finite(x.shock, w + ": shock")) : null;
1328
+ var down, up, source;
1329
+ if (x.delta != null) {
1330
+ // Taylor: impact = Δ·s + ½·Γ·s² at the (scaled) shock
1331
+ var d = finite(x.delta, w + ": delta"), g = x.gamma != null ? finite(x.gamma, w + ": gamma") : 0;
1332
+ if (sd == null || su == null) fail(w + ": delta needs shockDown and shockUp (or shock).");
1333
+ var a = sd * k, b = su * k;
1334
+ down = d * a + 0.5 * g * a * a; up = d * b + 0.5 * g * b * b; source = "taylor";
1335
+ } else {
1336
+ if (x.down == null || x.up == null) fail(w + " needs down and up impacts, or delta (and gamma) with a shock.");
1337
+ var dn = finite(x.down, w + ": down"), u = finite(x.up, w + ": up");
1338
+ if (k === 1) { down = dn; up = u; }
1339
+ else { var L = (u - dn) / 2, C = (u + dn) / 2; down = -L * k + C * k * k; up = L * k + C * k * k; } // two-point fit, exact at k = 1
1340
+ source = "revaluation";
1341
+ }
1342
+ var m = 1;
1343
+ if (whatIf) {
1344
+ if (whatIf[key] != null) m *= finite(whatIf[key], "whatIf." + key);
1345
+ if (whatIf[group] != null && group !== key) m *= finite(whatIf[group], "whatIf." + group);
1346
+ }
1347
+ return { key: key, label: x.label != null ? String(x.label) : key, group: group, unit: x.unit != null ? String(x.unit) : "",
1348
+ shockDown: sd == null ? null : sd * k, shockUp: su == null ? null : su * k, down: down * m, up: up * m, source: source, index: i };
1349
+ });
1350
+ }
1351
+
1352
+ /** (ρL)_k for every factor: one pass for within/across correlations, a full product for a matrix. */
1353
+ function corrTimes(fs, corr, Lv) {
1354
+ var n = fs.length, out = new Array(n), i, j;
1355
+ if (corr && corr.matrix) {
1356
+ var M = corr.matrix;
1357
+ for (i = 0; i < n; i++) { var s = 0, row = M[i]; for (j = 0; j < n; j++) s += (i === j ? 1 : row[j]) * Lv[j]; out[i] = s; }
1358
+ return out;
1359
+ }
1360
+ var wi = corr ? corr.within : 0, ac = corr ? corr.across : 0, G = {}, T = 0;
1361
+ for (i = 0; i < n; i++) { G[fs[i].group] = (G[fs[i].group] || 0) + Lv[i]; T += Lv[i]; }
1362
+ for (i = 0; i < n; i++) { var gs = G[fs[i].group]; out[i] = Lv[i] + wi * (gs - Lv[i]) + ac * (T - gs); }
1363
+ return out;
1364
+ }
1365
+ function readCorr(data, n) {
1366
+ var c = data.correlation;
1367
+ if (c == null) return null;
1368
+ if (typeof c !== "object") fail("data.correlation must be { within, across } or { matrix }.");
1369
+ if (c.matrix) {
1370
+ var M = c.matrix;
1371
+ if (!Array.isArray(M) || M.length !== n || M.some(function (r) { return !Array.isArray(r) || r.length !== n; })) fail("data.correlation.matrix must be square with one row per factor.");
1372
+ M.forEach(function (r, i) { r.forEach(function (v, j) { corrOf(v, "data.correlation.matrix[" + i + "][" + j + "]"); }); });
1373
+ return { matrix: M };
1374
+ }
1375
+ return { within: c.within != null ? corrOf(c.within, "data.correlation.within") : 0, across: c.across != null ? corrOf(c.across, "data.correlation.across") : 0 };
1376
+ }
1377
+
1378
+ /** Every figure. opts: { shockScale, whatIf, sort }. */
1379
+ function compute(data, opts) {
1380
+ opts = opts || {};
1381
+ if (!data || typeof data !== "object") fail("data is required.");
1382
+ var k = opts.shockScale != null ? finite(opts.shockScale, "shockScale") : 1;
1383
+ if (!(k > 0)) fail("shockScale must be more than 0.");
1384
+ var wi = opts.whatIf && Object.keys(opts.whatIf).length ? opts.whatIf : null;
1385
+ var fs = readFactors(data, k, wi), n = fs.length;
1386
+ if (wi) Object.keys(wi).forEach(function (key) { if (!fs.some(function (f) { return f.key === key || f.group === key; })) warn('whatIf: there is no factor or group "' + key + '", so it changes nothing.'); });
1387
+ var hib = data.higherIsBetter !== false;
1388
+ var bad = function (v) { return hib ? -v : v; };
1389
+ var limit = data.limit != null ? Math.abs(finite(data.limit, "data.limit")) : null;
1390
+ var corr = readCorr(data, n);
1391
+ var Lv = fs.map(function (f) { return (f.up - f.down) / 2; });
1392
+ var RL = corrTimes(fs, corr, Lv), q = 0, i;
1393
+ for (i = 0; i < n; i++) q += Lv[i] * RL[i];
1394
+ var sigma = Math.sqrt(Math.max(0, q)), totalSwing = 0, sumDown = 0, sumUp = 0, standalone = 0;
1395
+ fs.forEach(function (f, j) {
1396
+ f.swing = Math.abs(f.up - f.down);
1397
+ f.linear = Lv[j];
1398
+ f.convexity = (f.up + f.down) / 2;
1399
+ f.asymmetry = Math.abs(f.linear) + Math.abs(f.convexity) > 0 ? Math.abs(f.convexity) / (Math.abs(f.linear) + Math.abs(f.convexity)) : 0;
1400
+ f.worst = bad(f.down) >= bad(f.up) ? "down" : "up";
1401
+ f.worstValue = f[f.worst];
1402
+ f.best = f.worst === "down" ? "up" : "down";
1403
+ f.breach = limit != null && bad(f.worstValue) > limit + 1e-12 * Math.max(1, limit);
1404
+ f.standalone = Math.abs(Lv[j]);
1405
+ f.contribution = sigma > 0 ? Lv[j] * RL[j] / sigma : 0;
1406
+ totalSwing += f.swing; sumDown += f.down; sumUp += f.up; standalone += f.standalone;
1407
+ });
1408
+ var order = fs.slice().sort(opts.sort === "worst"
1409
+ ? function (a, b) { return bad(b.worstValue) - bad(a.worstValue) || a.index - b.index; }
1410
+ : function (a, b) { return b.swing - a.swing || a.index - b.index; });
1411
+ var cum = 0;
1412
+ order.forEach(function (f, r) { f.rank = r + 1; f.share = totalSwing > 0 ? f.swing / totalSwing : 0; cum += f.share; f.cumShare = cum; });
1413
+ // Groups, in the order they first appear
1414
+ var gm = {}, groups = [];
1415
+ fs.forEach(function (f, j) {
1416
+ var g = gm[f.group];
1417
+ if (!g) { g = gm[f.group] = { key: f.group, label: f.group, factors: [], idx: [], down: 0, up: 0, contribution: 0, standaloneSum: 0 }; groups.push(g); }
1418
+ g.factors.push(f.key); g.idx.push(j); g.down += f.down; g.up += f.up; g.contribution += f.contribution; g.standaloneSum += f.standalone;
1419
+ });
1420
+ groups.forEach(function (g) {
1421
+ g.swing = Math.abs(g.up - g.down); g.linear = (g.up - g.down) / 2; g.convexity = (g.up + g.down) / 2;
1422
+ g.worst = bad(g.down) >= bad(g.up) ? "down" : "up"; g.worstValue = g[g.worst];
1423
+ g.breach = limit != null && bad(g.worstValue) > limit + 1e-12 * Math.max(1, limit);
1424
+ g.share = totalSwing > 0 ? g.swing / totalSwing : 0;
1425
+ // the group's own combined move, with the correlations between its factors
1426
+ var sub = g.idx.map(function (j) { return fs[j]; }), subL = g.idx.map(function (j) { return Lv[j]; }), sc = corr && corr.matrix ? { matrix: g.idx.map(function (a) { return g.idx.map(function (b) { return corr.matrix[a][b]; }); }) } : corr;
1427
+ var r2 = corrTimes(sub, sc, subL), qq = 0; for (var t = 0; t < subL.length; t++) qq += subL[t] * r2[t];
1428
+ g.standalone = Math.sqrt(Math.max(0, qq));
1429
+ delete g.idx;
1430
+ });
1431
+ var topN = n >= 10 ? 5 : Math.max(1, Math.ceil(n / 2)); // short lists: about half of them
1432
+ var top5 = order.slice(0, topN).reduce(function (a, f) { return a + f.share; }, 0);
1433
+ var res = { factors: fs, order: order, groups: groups, higherIsBetter: hib, limit: limit, base: data.base != null ? finite(data.base, "data.base") : null,
1434
+ totalSwing: totalSwing, sumDown: sumDown, sumUp: sumUp, sigma: sigma, standalone: standalone, diversification: standalone - sigma,
1435
+ correlated: !!corr, topN: topN, topShare: top5, breaches: fs.filter(function (f) { return f.breach; }).length, shockScale: k, whatIf: wi };
1436
+ res.worstFactor = fs.slice().sort(function (a, b) { return bad(b.worstValue) - bad(a.worstValue) || a.index - b.index; })[0];
1437
+ // Joint revaluation: all factors shocked together, only valid at the base shocks and positions
1438
+ if (data.joint && (data.joint.down != null || data.joint.up != null)) {
1439
+ if (k === 1 && !wi) {
1440
+ res.joint = { down: data.joint.down != null ? finite(data.joint.down, "data.joint.down") : null, up: data.joint.up != null ? finite(data.joint.up, "data.joint.up") : null };
1441
+ res.interaction = { down: res.joint.down != null ? res.joint.down - sumDown : null, up: res.joint.up != null ? res.joint.up - sumUp : null };
1442
+ } else res.jointHidden = true;
1443
+ }
1444
+ if (wi) {
1445
+ var b0 = compute(data, { shockScale: k, sort: opts.sort });
1446
+ res.baseline = { totalSwing: b0.totalSwing, sigma: b0.sigma, worstValue: b0.worstFactor.worstValue, worstFactor: b0.worstFactor.key };
1447
+ }
1448
+ return res;
1449
+ }
1450
+ /* ======================================================================
1451
+ 4. CHART INSTANCE
1452
+ ====================================================================== */
1453
+ function injectStyles() {
1454
+ if (document.getElementById("vtr-styles")) return;
1455
+ var css =
1456
+ ".vtr{position:relative;color:var(--vtr-text);background:var(--vtr-bg);font-family:var(--vtr-font);line-height:1.4}" +
1457
+ ".vtr.vtr-filled{padding:14px 14px 8px;border-radius:10px}" +
1458
+ ".vtr-summary{display:grid;grid-template-columns:repeat(auto-fit,minmax(150px,1fr));gap:8px;margin:0 0 10px}" +
1459
+ ".vtr-stat{background:var(--vtr-card);border-radius:8px;padding:9px 12px;min-width:0}" +
1460
+ ".vtr-stat .k{font-size:11px;letter-spacing:.04em;text-transform:uppercase;color:var(--vtr-card-muted);font-weight:600;overflow-wrap:anywhere;hyphens:auto}" +
1461
+ ".vtr-stat .v{font-size:19px;font-weight:700;font-variant-numeric:tabular-nums;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}" +
1462
+ ".vtr-stat .n{font-size:12px;color:var(--vtr-card-muted)}" +
1463
+ ".vtr-stat .v.vtr-wrap{white-space:normal;overflow-wrap:anywhere;line-height:1.2;font-size:17px}" +
1464
+ ".vtr-scope{font-size:12px;color:var(--vtr-muted);margin:0 0 4px}" +
1465
+ ".vtr-legend{display:flex;flex-wrap:wrap;gap:4px 14px;font-size:12px;margin:0 0 6px;color:var(--vtr-text)}" +
1466
+ ".vtr-legend span{display:inline-flex;align-items:center;gap:6px}" +
1467
+ ".vtr-legend i{display:inline-block;width:12px;height:12px;border-radius:3px}" +
1468
+ ".vtr-legend i.vtr-tick{width:3px;height:14px;border-radius:1px}" +
1469
+ ".vtr-legend i.vtr-ring{background:transparent!important;border:2px solid;border-radius:2px;width:9px;height:9px;transform:rotate(45deg)}" +
1470
+ ".vtr-plot{display:block;width:100%;height:auto;overflow:visible;outline:none}" +
1471
+ ".vtr-plot:focus-visible{outline:2px solid var(--vtr-focus);outline-offset:4px;border-radius:4px}" +
1472
+ ".vtr-animate .vtr-grow{animation:vtr-fade .45s ease both}" +
1473
+ "@keyframes vtr-fade{from{opacity:0}to{opacity:1}}" +
1474
+ "@media (prefers-reduced-motion:reduce){.vtr-animate .vtr-grow{animation:none}}" +
1475
+ ".vtr-tip{position:absolute;left:0;top:0;pointer-events:none;background:var(--vtr-tip-bg);color:var(--vtr-tip-text);" +
1476
+ "font-size:12px;line-height:1.45;padding:8px 10px;border-radius:8px;opacity:0;transform:translateY(4px);" +
1477
+ "transition:opacity .12s,transform .12s;white-space:nowrap;z-index:5;font-variant-numeric:tabular-nums}" +
1478
+ ".vtr-tip.vtr-on{opacity:1;transform:none}.vtr-tip b{font-weight:600}" +
1479
+ ".vtr-table{border-collapse:collapse;font-size:12px;font-variant-numeric:tabular-nums;margin:0 0 14px;min-width:100%}" +
1480
+ ".vtr-table caption{text-align:left;font-weight:700;padding:0 0 6px}" +
1481
+ ".vtr-table th,.vtr-table td{padding:5px 8px;border-bottom:1px solid rgba(127,127,127,.25);text-align:right;white-space:nowrap}" +
1482
+ ".vtr-table th:first-child,.vtr-table td:first-child{text-align:left}" +
1483
+ ".vtr-table tr.vtr-breach td{color:var(--vtr-hedge);font-weight:600}" +
1484
+ "@media (max-width:420px){.vtr-summary{grid-template-columns:repeat(auto-fit,minmax(118px,1fr))}.vtr-stat{padding:8px 10px}.vtr-stat .v{font-size:17px}}";
1485
+ var s = htmlEl("style");
1486
+ s.id = "vtr-styles";
1487
+ s.textContent = css;
1488
+ (document.head || document.documentElement).appendChild(s);
1489
+ }
1490
+ function resolveTrTheme(theme) {
1491
+ var t;
1492
+ if (theme == null || theme === "") theme = "veyforma";
1493
+ if (typeof theme === "string") {
1494
+ if (!THEMES.hasOwnProperty(theme)) { warn('Unknown theme "' + theme + '". The "veyforma" theme is used instead.'); theme = "veyforma"; }
1495
+ t = assign({}, BASE_THEME, THEMES[theme]);
1496
+ } else if (typeof theme === "object") {
1497
+ t = assign(theme["extends"] ? resolveTrTheme(theme["extends"]) : assign({}, BASE_THEME), theme);
1498
+ delete t["extends"];
1499
+ } else { warn("The theme option must be a theme name or an object."); t = assign({}, BASE_THEME); }
1500
+ var bg = /^#/.test(t.background) ? t.background : "#ffffff", card = /^#/.test(t.cardBackground) ? t.cardBackground : bg;
1501
+ ["axisText", "mutedText"].forEach(function (k) { t[k] = ensureContrast(t[k], bg, 4.5); });
1502
+ t.cardMuted = ensureContrast(t.mutedText, card, 4.5);
1503
+ t.hedgeText = ensureContrast(ensureContrast(t.hedge, bg, 4.5), card, 4.5);
1504
+ t.limitText = ensureContrast(ensureContrast(t.limit, bg, 4.5), card, 4.5);
1505
+ t.accentText = ensureContrast(t.accent, bg, 4.5);
1506
+ return t;
1507
+ }
1508
+
1509
+ function Chart(target, options) {
1510
+ var container = typeof target === "string" ? document.querySelector(target) : target;
1511
+ if (!container || container.nodeType !== 1) fail("container not found (" + target + ").");
1512
+ if (!options || !options.data) fail("options.data is required.");
1513
+ injectStyles();
1514
+ this.id = ++instanceCount;
1515
+ this.container = container;
1516
+ this.options = assign({}, DEFAULT_OPTIONS, options);
1517
+ this.element = htmlEl("div", "vtr");
1518
+ this.element.setAttribute("role", "figure");
1519
+ this.summaryEl = htmlEl("div", "vtr-summary", this.element);
1520
+ this.scopeEl = htmlEl("p", "vtr-scope", this.element);
1521
+ this.legendEl = htmlEl("div", "vtr-legend", this.element);
1522
+ this.plotHost = htmlEl("div", "vtr-plot-host", this.element);
1523
+ this.tipEl = htmlEl("div", "vtr-tip", this.element);
1524
+ this.tipEl.setAttribute("role", "tooltip");
1525
+ container.appendChild(this.element);
1526
+ this._animateNext = !!this.options.animate;
1527
+ this._lastWidth = 0;
1528
+ this._active = -1;
1529
+ var self = this;
1530
+ if (root.ResizeObserver) {
1531
+ this._observer = new root.ResizeObserver(function () {
1532
+ var w = Math.round(self.element.clientWidth);
1533
+ if (w && Math.abs(w - self._lastWidth) > 1) self.redraw();
1534
+ });
1535
+ this._observer.observe(this.element);
1536
+ } else {
1537
+ this._onResize = function () { self.redraw(); };
1538
+ root.addEventListener("resize", this._onResize);
1539
+ }
1540
+ this._onDocTap = function (e) { if (!self.element.contains(e.target)) self._hideTip(); };
1541
+ document.addEventListener("pointerdown", this._onDocTap);
1542
+ this.redraw();
1543
+ if (this.options.toolbar !== false && root.VeyformaToolkit) this.toolkit = root.VeyformaToolkit.attach(this, this.options.toolbar);
1544
+ }
1545
+
1546
+ Chart.prototype.update = function (partial) {
1547
+ if (!partial) return this;
1548
+ if (partial.data && partial.data !== this.options.data && this.options.animate) this._animateNext = true;
1549
+ if (partial.view && partial.view !== this.options.view && this.options.animate) this._animateNext = true;
1550
+ assign(this.options, partial);
1551
+ return this.redraw();
1552
+ };
1553
+ Chart.prototype.setData = function (data) { this._res = null; return this.update({ data: data }); };
1554
+ Chart.prototype.setView = function (view) { return this.update({ view: view }); };
1555
+ Chart.prototype.setTheme = function (theme) { return this.update({ theme: theme }); };
1556
+ Chart.prototype.getTheme = function () { return resolveTrTheme(this.options.theme); };
1557
+ Chart.prototype._opts = function () { return { shockScale: this.options.shockScale, whatIf: this.options.whatIf, sort: this.options.sort }; };
1558
+ Chart.prototype.getResult = function () { return compute(this.options.data, this._opts()); };
1559
+ Chart.prototype.getFactor = function (key) { return this.getResult().factors.filter(function (f) { return f.key === String(key); })[0] || null; };
1560
+ Chart.prototype.setWhatIf = function (whatIf) { return this.update({ whatIf: whatIf }); };
1561
+ Chart.prototype.setShockScale = function (k) { return this.update({ shockScale: k }); };
1562
+ Chart.prototype._labels = function () { return assign({}, DEFAULT_LABELS, this.options.labels); };
1563
+ Chart.prototype.destroy = function () {
1564
+ if (this.toolkit && this.toolkit.destroy) this.toolkit.destroy();
1565
+ if (this._observer) this._observer.disconnect();
1566
+ if (this._onResize) root.removeEventListener("resize", this._onResize);
1567
+ document.removeEventListener("pointerdown", this._onDocTap);
1568
+ if (this.element.parentNode) this.element.parentNode.removeChild(this.element);
1569
+ };
1570
+ Chart.prototype._hideTip = function () { this.tipEl.classList.remove("vtr-on"); if (this._hlEl) this._hlEl.setAttribute("opacity", 0); };
1571
+ Chart.prototype._placeTip = function (lines, rect, evt) {
1572
+ var tip = this.tipEl;
1573
+ tip.textContent = "";
1574
+ lines.forEach(function (ln, i) {
1575
+ if (i) tip.appendChild(document.createElement("br"));
1576
+ var node = i === 0 ? document.createElement("b") : document.createElement("span");
1577
+ node.textContent = ln;
1578
+ tip.appendChild(node);
1579
+ });
1580
+ var box = this.element.getBoundingClientRect();
1581
+ var px = evt && evt.clientX ? evt.clientX : rect.left + rect.width / 2;
1582
+ var py = evt && evt.clientY ? evt.clientY : rect.top + 10;
1583
+ tip.classList.add("vtr-on");
1584
+ var tw = tip.offsetWidth, th = tip.offsetHeight;
1585
+ tip.style.left = clamp(px - box.left - tw / 2, 4, Math.max(4, box.width - tw - 4)) + "px";
1586
+ var top = py - box.top - th - 14;
1587
+ if (top < 0) top = py - box.top + 18;
1588
+ tip.style.top = top + "px";
1589
+ };
1590
+ /** A "nice" axis from lo to hi with about n ticks. */
1591
+ function niceTicks(lo, hi, n) {
1592
+ if (!(hi > lo)) { hi = lo + 1; }
1593
+ var span = hi - lo, step = Math.pow(10, Math.floor(Math.log(span / n) / Math.LN10)), err = span / n / step;
1594
+ if (err >= 7.5) step *= 10; else if (err >= 3.5) step *= 5; else if (err >= 1.5) step *= 2;
1595
+ var a = Math.floor(lo / step + 1e-9) * step, b = Math.ceil(hi / step - 1e-9) * step, out = [];
1596
+ for (var v = a; v <= b + step / 2; v += step) out.push(Math.round(v / step) * step);
1597
+ return { lo: a, hi: b, ticks: out, step: step };
1598
+ }
1599
+
1600
+ function label(g, x, y, text, attrs) {
1601
+ var t = svgEl("text", assign({ x: x, y: y }, attrs || {}), g);
1602
+ t.textContent = text;
1603
+ return t;
1604
+ }
1605
+
1606
+ Chart.prototype._bindInteraction = function (svg, W, H, theme, L, f) {
1607
+ var self = this, items = this._items, o = this.options;
1608
+ function idxAt(evt) {
1609
+ var r = svg.getBoundingClientRect(), x = (evt.clientX - r.left) * (W / r.width), y = (evt.clientY - r.top) * (H / r.height);
1610
+ for (var i = 0; i < items.length; i++) { var it = items[i]; if (x >= it.x && x <= it.x + it.w && y >= it.y && y <= it.y + it.h) return i; }
1611
+ return -1;
1612
+ }
1613
+ function show(i, evt) {
1614
+ if (i < 0) { self._hideTip(); return; }
1615
+ self._active = i;
1616
+ var it = items[i], hl = self._hlEl;
1617
+ hl.setAttribute("x", it.x - 4); hl.setAttribute("y", it.y); hl.setAttribute("width", it.w + 8); hl.setAttribute("height", it.h); hl.setAttribute("opacity", 1);
1618
+ var r = svg.getBoundingClientRect(), sx = r.width / W;
1619
+ var rect = { left: r.left + it.px * sx, top: r.top + it.py * (r.height / H), width: 0, height: 0 };
1620
+ self._placeTip(self._tipLines(it), rect, evt && evt.clientX ? evt : null);
1621
+ }
1622
+ svg.addEventListener("pointermove", function (e) { show(idxAt(e), e); });
1623
+ svg.addEventListener("pointerleave", function () { self._hideTip(); });
1624
+ svg.addEventListener("click", function (e) {
1625
+ var i = idxAt(e);
1626
+ if (i >= 0 && typeof o.onItemClick === "function") o.onItemClick(self._detail(items[i]), e);
1627
+ });
1628
+ svg.addEventListener("keydown", function (e) {
1629
+ var i = self._active;
1630
+ if (e.key === "ArrowRight" || e.key === "ArrowDown") i = Math.min(items.length - 1, i + 1);
1631
+ else if (e.key === "ArrowLeft" || e.key === "ArrowUp") i = Math.max(0, i < 0 ? 0 : i - 1);
1632
+ else if (e.key === "Home") i = 0;
1633
+ else if (e.key === "End") i = items.length - 1;
1634
+ else if (e.key === "Escape") { self._hideTip(); return; }
1635
+ else if ((e.key === "Enter" || e.key === " ") && i >= 0) {
1636
+ if (typeof o.onItemClick === "function") o.onItemClick(self._detail(items[i]), e);
1637
+ e.preventDefault(); return;
1638
+ } else return;
1639
+ e.preventDefault();
1640
+ show(i, null);
1641
+ });
1642
+ svg.addEventListener("blur", function () { self._hideTip(); });
1643
+ };
1644
+
1645
+ Chart.prototype.createTable = function () {
1646
+ var ex = this.getExportData(), wrap = htmlEl("div", "vtr-tables");
1647
+ ex.sheets.forEach(function (sh) {
1648
+ if (sh.name === "Notes") return;
1649
+ var tb = htmlEl("table", "vtr-table", wrap);
1650
+ htmlEl("caption", null, tb).textContent = sh.name;
1651
+ var hr = htmlEl("tr", null, htmlEl("thead", null, tb));
1652
+ sh.columns.forEach(function (c) { var th = htmlEl("th", null, hr); th.scope = "col"; th.textContent = c.label; });
1653
+ var body = htmlEl("tbody", null, tb);
1654
+ sh.text.forEach(function (r, i) {
1655
+ var tr = htmlEl("tr", sh.flag && sh.flag[i] ? "vtr-breach" : null, body);
1656
+ r.forEach(function (v, j) { var td = htmlEl(j ? "td" : "th", null, tr); if (!j) td.scope = "row"; td.textContent = v; });
1657
+ });
1658
+ });
1659
+ return wrap;
1660
+ };
1661
+
1662
+ function shockText(v, unit, locale) {
1663
+ if (v == null || !isFinite(v)) return "";
1664
+ var body = Number(Math.abs(v).toFixed(4)).toLocaleString(locale || undefined, { maximumFractionDigits: 4 });
1665
+ return (v > 0 ? "+" : v < 0 ? "−" : "") + body + (unit ? (unit === "%" ? "%" : " " + unit) : "");
1666
+ }
1667
+
1668
+ Chart.prototype.redraw = function () {
1669
+ var o = this.options, data = o.data, L = this._labels();
1670
+ var res = this._res = compute(data, this._opts());
1671
+ var theme = resolveTrTheme(o.theme), f = makeFormatters(data, o.locale), el = this.element, st = el.style;
1672
+ var family = theme.fontFamily === "inherit" ? (root.getComputedStyle ? root.getComputedStyle(this.container).fontFamily : "sans-serif") : theme.fontFamily;
1673
+ var filled = theme.background && theme.background !== "transparent", bg = filled ? theme.background : "#ffffff";
1674
+ st.setProperty("--vtr-text", theme.text); st.setProperty("--vtr-muted", theme.mutedText);
1675
+ st.setProperty("--vtr-bg", filled ? theme.background : "transparent"); st.setProperty("--vtr-font", family);
1676
+ st.setProperty("--vtr-card", theme.cardBackground); st.setProperty("--vtr-card-muted", theme.cardMuted);
1677
+ st.setProperty("--vtr-tip-bg", theme.tooltipBackground); st.setProperty("--vtr-tip-text", theme.tooltipText);
1678
+ st.setProperty("--vtr-focus", theme.focus); st.setProperty("--vtr-hedge", theme.limitText);
1679
+ el.classList.toggle("vtr-filled", !!filled);
1680
+ el.setAttribute("aria-label", o.ariaLabel || data.title || "Risk-factor tornado");
1681
+ var view = o.view;
1682
+ if (["factors", "groups", "contribution"].indexOf(view) < 0) { warn('Unknown view "' + view + '". The factor view is shown instead.'); view = "factors"; }
1683
+ if (o.sort !== "swing" && o.sort !== "worst") warn('Unknown sort "' + o.sort + '". Factors are ranked by swing instead.');
1684
+ this._view = view;
1685
+ this._renderSummary(res, f, L);
1686
+ var scope = [L[view], o.shockScale != null && +o.shockScale !== 1 ? "shocks ×" + (+o.shockScale) : null, data.unit || null, res.whatIf ? L.whatIf + " applied" : null].filter(Boolean).join(" · ");
1687
+ this.scopeEl.textContent = scope;
1688
+ this._renderLegend(view, theme, L, res);
1689
+ var W = Math.max(280, Math.round(this.plotHost.clientWidth || el.clientWidth || 720));
1690
+ this._lastWidth = Math.round(el.clientWidth);
1691
+ var fs = theme.fontSize || 12;
1692
+ this.plotHost.textContent = "";
1693
+ var svg = svgEl("svg", { "class": "vtr-plot", role: "img", tabindex: 0, "font-family": family }, this.plotHost);
1694
+ svg.style.fontSize = fs + "px";
1695
+ var animate = this._animateNext && o.animate; this._animateNext = false;
1696
+ if (animate) svg.classList.add("vtr-animate");
1697
+ var ctx = { svg: svg, W: W, fs: fs, theme: theme, f: f, L: L, family: family, bg: bg, res: res, items: [], points: {} };
1698
+ var H = view === "contribution" ? this._drawContribution(ctx) : this._drawRows(ctx, view);
1699
+ svg.setAttribute("viewBox", "0 0 " + W + " " + H);
1700
+ svg.setAttribute("width", W); svg.setAttribute("height", H);
1701
+ svg.setAttribute("aria-label", (o.ariaLabel || data.title || "Risk-factor tornado") + ". " + this.describe());
1702
+ this._items = ctx.items; this._points = ctx.points;
1703
+ this._hlEl = svgEl("rect", { x: 0, y: 0, width: 0, height: 0, rx: 4, fill: theme.text, "fill-opacity": 0.06, opacity: 0, "pointer-events": "none" }, svg);
1704
+ svg.insertBefore(this._hlEl, svg.firstChild);
1705
+ this._bindInteraction(svg, W, H, theme, L, f);
1706
+ return this;
1707
+ };
1708
+
1709
+ Chart.prototype._shockNames = function () {
1710
+ var L = this._labels(), s = this.options.data.shockLabels || {};
1711
+ return { down: s.down || L.down, up: s.up || L.up };
1712
+ };
1713
+
1714
+ Chart.prototype._renderSummary = function (res, f, L) {
1715
+ var box = this.summaryEl, o = this.options;
1716
+ box.textContent = "";
1717
+ box.style.display = o.summary === false ? "none" : "";
1718
+ if (o.summary === false) return;
1719
+ function stat(k, v, n, wrap) {
1720
+ var s = htmlEl("div", "vtr-stat", box);
1721
+ htmlEl("div", "k", s).textContent = k;
1722
+ htmlEl("div", wrap ? "v vtr-wrap" : "v", s).textContent = v;
1723
+ if (n) htmlEl("div", "n", s).textContent = n;
1724
+ }
1725
+ var SN = this._shockNames(), top = res.order[0], w = res.worstFactor;
1726
+ stat(L.largest, top.label, L.swing.toLowerCase() + " " + f.value(top.swing) + " · " + f.percent(top.share, 0) + " of the total", true);
1727
+ stat(L.worstShock, f.signed(w.worstValue), w.label + ", " + SN[w.worst].toLowerCase() + (res.limit != null ? (res.breaches ? " · " + res.breaches + " beyond the limit" : " · within the limit") : "") +
1728
+ (res.baseline ? " · was " + f.signed(res.baseline.worstValue) : ""));
1729
+ stat(fill(L.topShare, { n: res.topN }), f.percent(res.topShare, 0), "of the total swing across " + res.factors.length + " factors");
1730
+ stat(L.combined, "±" + f.value(res.sigma), res.baseline ? L.whatIf + ": was ±" + f.value(res.baseline.sigma)
1731
+ : res.correlated ? (res.standalone > 0 ? f.percent(res.diversification / res.standalone, 0) + " below the sum of stand-alone moves" : "") : "factors treated as independent");
1732
+ Array.prototype.forEach.call(box.querySelectorAll(".vtr-stat .v"), function (v) {
1733
+ v.style.fontSize = "";
1734
+ var size = parseFloat(root.getComputedStyle ? root.getComputedStyle(v).fontSize : 19) || 19;
1735
+ while (v.scrollWidth > v.clientWidth && size > 12) { size -= 1; v.style.fontSize = size + "px"; }
1736
+ });
1737
+ };
1738
+
1739
+ Chart.prototype._renderLegend = function (view, theme, L, res) {
1740
+ var box = this.legendEl, SN = this._shockNames();
1741
+ box.textContent = "";
1742
+ box.style.display = this.options.legend === false ? "none" : "";
1743
+ function item(colour, text, cls) {
1744
+ var s = htmlEl("span", null, box), i = htmlEl("i", cls || null, s);
1745
+ if (cls === "vtr-ring") i.style.borderColor = colour; else i.style.background = colour;
1746
+ s.appendChild(document.createTextNode(text));
1747
+ }
1748
+ if (view === "contribution") { item(theme.contribution, L.contributionAdds); item(theme.hedge, L.hedge); item(theme.convexity, L.standalone, "vtr-ring"); return; }
1749
+ item(theme.down, SN.down); item(theme.up, SN.up);
1750
+ if (res.factors.some(function (x) { return x.asymmetry >= 0.1; })) item(theme.convexity, L.convexity + " (midpoint)", "vtr-ring");
1751
+ if (res.limit != null) item(theme.limit, L.limit, "vtr-tick");
1752
+ };
1753
+
1754
+ function rowLayout(c, names) {
1755
+ var nameW = Math.min(Math.max.apply(null, names.map(function (n) { return textWidth(n, c.fs, 600, c.family); })) + 12, c.W * 0.34);
1756
+ var narrow = c.W - nameW < 260;
1757
+ return { nameW: narrow ? 0 : nameW, narrow: narrow };
1758
+ }
1759
+ /** Axis ticks along the top, thinned so no two labels touch. */
1760
+ function topTicks(c, g, nt, xs, y, x0, x1, gridTop, gridBottom) {
1761
+ var theme = c.theme, fs = c.fs, fam = c.family, W = c.W, f = c.f, lastRight = -Infinity;
1762
+ var tickW = Math.max.apply(null, nt.ticks.map(function (t) { return textWidth(f.value(t), fs - 1, 400, fam); }));
1763
+ var every = Math.max(1, Math.ceil((tickW + 10) / ((x1 - x0) / Math.max(1, nt.ticks.length - 1))));
1764
+ nt.ticks.forEach(function (t, ti) {
1765
+ svgEl("line", { x1: xs(t), x2: xs(t), y1: gridTop, y2: gridBottom, stroke: t === 0 ? theme.axis : theme.grid, "stroke-width": t === 0 ? 1.2 : 1 }, g);
1766
+ if (ti % every) return;
1767
+ var tt = f.value(t), tw = textWidth(tt, fs - 1, 400, fam), w2 = tw / 2, tx = xs(t), anc = tx - w2 < 0 ? "start" : tx + w2 > W ? "end" : "middle";
1768
+ var left = anc === "start" ? tx : anc === "end" ? tx - tw : tx - w2;
1769
+ if (left < lastRight + 8) return;
1770
+ lastRight = left + tw;
1771
+ label(g, tx, y + fs, tt, { "text-anchor": anc, fill: theme.axisText, "font-size": fs - 1, "class": "vtr-tick" });
1772
+ });
1773
+ }
1774
+ /** Factor rows (ranked, top N plus "Other") or group rows. */
1775
+ Chart.prototype._rowsFor = function (res, view, L) {
1776
+ if (view === "groups") return res.groups.slice().sort(function (a, b) { return b.swing - a.swing; }).map(function (g) { return { kind: "group", obj: g, name: g.label, down: g.down, up: g.up, breach: g.breach, convexity: g.convexity, asym: Math.abs(g.linear) + Math.abs(g.convexity) > 0 ? Math.abs(g.convexity) / (Math.abs(g.linear) + Math.abs(g.convexity)) : 0 }; });
1777
+ var top = +this.options.top > 0 ? Math.floor(+this.options.top) : res.order.length;
1778
+ var rows = res.order.slice(0, top).map(function (x) { return { kind: "factor", obj: x, name: x.rank + ". " + x.label, down: x.down, up: x.up, breach: x.breach, convexity: x.convexity, asym: x.asymmetry }; });
1779
+ var rest = res.order.slice(top);
1780
+ if (rest.length) {
1781
+ var d = 0, u = 0, sw = 0; rest.forEach(function (x) { d += x.down; u += x.up; sw += x.swing; });
1782
+ rows.push({ kind: "other", obj: { count: rest.length, down: d, up: u, swing: sw, share: res.totalSwing > 0 ? sw / res.totalSwing : 0, factors: rest }, name: fill(L.other, { n: rest.length }), down: d, up: u, breach: false, convexity: (d + u) / 2, asym: 0 });
1783
+ }
1784
+ return rows;
1785
+ };
1786
+ Chart.prototype._drawRows = function (c, view) {
1787
+ var res = c.res, theme = c.theme, f = c.f, L = c.L, fs = c.fs, fam = c.family, W = c.W, svg = c.svg, hib = res.higherIsBetter;
1788
+ var rows = this._rowsFor(res, view, L);
1789
+ var lay = rowLayout(c, rows.map(function (r) { return r.name; }));
1790
+ var limX = res.limit != null ? (hib ? -res.limit : res.limit) : null;
1791
+ var vals = []; rows.forEach(function (r) { vals.push(r.down, r.up); });
1792
+ var lo = Math.min.apply(null, vals.concat([0, limX != null ? limX : 0])), hi = Math.max.apply(null, vals.concat([0, limX != null ? limX : 0]));
1793
+ var lw = function (v) { return textWidth(f.signed(v), fs - 1, 600, fam) + 6; };
1794
+ var padL = Math.max.apply(null, [4].concat(vals.filter(function (v) { return v < 0; }).map(lw)));
1795
+ var padR = Math.max.apply(null, [4].concat(vals.filter(function (v) { return v >= 0; }).map(lw)));
1796
+ var x0 = lay.nameW + padL, x1 = W - padR;
1797
+ var nt = niceTicks(lo, hi, Math.max(2, Math.min(6, Math.floor((x1 - x0) / 90))));
1798
+ var xs = function (v) { return x0 + (clamp(v, nt.lo, nt.hi) - nt.lo) / (nt.hi - nt.lo) * (x1 - x0); };
1799
+ var y = 4, rowH = Math.max(36, fs * 3), extra = lay.narrow ? fs + 4 : 0, gridTop = y + fs + 6, gridBottom = gridTop + rows.length * (rowH + extra);
1800
+ var g = svgEl("g", { "class": "vtr-rows" }, svg);
1801
+ topTicks(c, g, nt, xs, y, x0, x1, gridTop, gridBottom);
1802
+ var gb = svgEl("g", null, g), gc = svgEl("g", { "class": "vtr-cvx-layer" }, g), gl = svgEl("g", null, g); // bars, then diamonds, then labels on top
1803
+ if (limX != null) svgEl("line", { x1: xs(limX), x2: xs(limX), y1: gridTop - 2, y2: gridBottom, stroke: theme.limit, "stroke-width": 1.6, "stroke-dasharray": "5 3", "class": "vtr-limit" }, gc);
1804
+ var SN = this._shockNames(), self = this;
1805
+ rows.forEach(function (r, i) {
1806
+ var ry = gridTop + i * (rowH + extra) + extra, bh = Math.max(rowH * 0.32, fs), by = ry + (rowH - 2 * bh - 3) / 2;
1807
+ var nameFill = r.breach ? theme.limitText : r.kind === "other" ? theme.mutedText : theme.text;
1808
+ var nm = fit(r.name, lay.narrow ? W : lay.nameW - 8, fs, r.kind === "other" ? 400 : 600, fam);
1809
+ if (lay.narrow) svgEl("rect", { x: 0, y: ry - 3 - fs * 0.95, width: textWidth(nm, fs, 600, fam) + 4, height: fs * 1.25, fill: c.bg, "class": "vtr-lbg" }, gl);
1810
+ label(gl, 0, lay.narrow ? ry - 3 : ry + rowH / 2 + fs * 0.35, fit(r.name, lay.narrow ? W : lay.nameW - 8, fs, r.kind === "other" ? 400 : 600, fam), { fill: nameFill, "font-size": fs, "font-weight": r.kind === "other" ? 400 : 600, "class": "vtr-name" });
1811
+ [["down", by], ["up", by + bh + 3]].forEach(function (p) {
1812
+ var v = r[p[0]], xa = xs(Math.min(0, v)), xb = xs(Math.max(0, v)), isWorst = r.kind !== "other" && r.obj.worst === p[0];
1813
+ svgEl("rect", { x: xa, y: p[1], width: Math.max(0.8, xb - xa), height: bh, rx: 2, fill: theme[p[0]], "class": "vtr-grow vtr-bar", "data-shock": p[0] }, gb);
1814
+ var lbreach = r.breach && isWorst;
1815
+ var vt = f.signed(v), vw = textWidth(vt, fs - 1, lbreach ? 700 : 400, fam), vx = v < 0 ? xa - 4 - vw : xb + 4;
1816
+ svgEl("rect", { x: vx - 2, y: p[1] + bh / 2 - (fs - 1) * 0.6, width: vw + 4, height: (fs - 1) * 1.2, fill: c.bg, "class": "vtr-lbg" }, gl);
1817
+ label(gl, v < 0 ? xa - 4 : xb + 4, p[1] + bh / 2 + (fs - 1) * 0.35, f.signed(v), { "text-anchor": v < 0 ? "end" : "start", fill: lbreach ? theme.limitText : theme.text, "font-size": fs - 1, "font-weight": lbreach ? 700 : 400, "class": "vtr-val" });
1818
+ });
1819
+ if (r.asym >= 0.1) {
1820
+ var cx = xs(r.convexity), cy = by + bh + 1.5;
1821
+ svgEl("path", { d: "M" + cx + "," + (cy - 4) + "L" + (cx + 4) + "," + cy + "L" + cx + "," + (cy + 4) + "L" + (cx - 4) + "," + cy + "Z", fill: c.bg, stroke: theme.convexity, "stroke-width": 1.5, "class": "vtr-cvx" }, gc);
1822
+ }
1823
+ var endX = xs(Math.max(0, r.down, r.up));
1824
+ if (r.kind === "factor") c.points[r.obj.key] = { x: endX, y: by };
1825
+ if (r.kind === "group") c.points["group:" + r.obj.key] = { x: endX, y: by };
1826
+ c.items.push({ kind: r.kind, obj: r.obj, x: 0, y: ry - extra, w: W, h: rowH + extra, px: endX, py: by });
1827
+ });
1828
+ if (view === "groups") res.factors.forEach(function (x) { if (!c.points[x.key]) c.points[x.key] = c.points["group:" + x.group]; });
1829
+ var notes = [];
1830
+ if (limX != null) notes.push(L.limit + " " + f.signed(limX) + (res.breaches ? ": " + res.breaches + " factor" + (res.breaches > 1 ? "s" : "") + " beyond it" : ": no factor beyond it"));
1831
+ if (view === "factors") {
1832
+ var shown = rows.filter(function (r) { return r.kind === "factor"; }).length;
1833
+ notes.push("Each factor shocked alone" + (shown < res.factors.length ? "; top " + shown + " of " + res.factors.length + ", the rest summed" : ""));
1834
+ if (res.interaction) {
1835
+ var it = res.interaction, parts = [];
1836
+ if (it.down != null) parts.push(SN.down.toLowerCase() + " together " + f.signed(res.joint.down) + " vs sum " + f.signed(res.sumDown));
1837
+ if (it.up != null) parts.push(SN.up.toLowerCase() + " together " + f.signed(res.joint.up) + " vs sum " + f.signed(res.sumUp));
1838
+ notes.push("All factors " + parts.join(", "));
1839
+ }
1840
+ } else notes.push("Every factor in the group shocked the same way at once (sum of single shocks)");
1841
+ var y2 = gridBottom + fs + 8;
1842
+ notes.forEach(function (t) { label(svg, 0, y2, fit(t + ".", W, fs - 1, 400, fam), { fill: theme.mutedText, "font-size": fs - 1, "class": "vtr-note" }); y2 += fs + 3; });
1843
+ return Math.ceil(y2 - fs + 6);
1844
+ };
1845
+
1846
+ /** Contribution view: each factor's share of the combined (correlated) move, hedges to the left, stand-alone move as a diamond. */
1847
+ Chart.prototype._drawContribution = function (c) {
1848
+ var res = c.res, theme = c.theme, f = c.f, L = c.L, fs = c.fs, fam = c.family, W = c.W, svg = c.svg;
1849
+ var srt = res.factors.slice().sort(function (a, b) { return Math.abs(b.contribution) - Math.abs(a.contribution) || a.index - b.index; });
1850
+ var top = +this.options.top > 0 ? Math.floor(+this.options.top) : srt.length, rest = srt.slice(top);
1851
+ var rows = srt.slice(0, top).sort(function (a, b) { return b.contribution - a.contribution; }).map(function (x) { return { kind: "factor", obj: x, name: x.label, v: x.contribution, k: x.standalone }; });
1852
+ if (rest.length) { var sv = 0, sk = 0; rest.forEach(function (x) { sv += x.contribution; sk += x.standalone; }); rows.push({ kind: "other", obj: { count: rest.length, contribution: sv, standalone: sk, factors: rest }, name: fill(L.other, { n: rest.length }), v: sv, k: null }); }
1853
+ var lay = rowLayout(c, rows.map(function (r) { return r.name; }));
1854
+ var valW = Math.max.apply(null, rows.map(function (r) { return textWidth(f.signed(r.v), fs, 700, fam); })) + 10;
1855
+ var x0 = lay.nameW, x1 = W - valW, rowH = Math.max(24, fs * 2), extra = lay.narrow ? fs + 4 : 0, y = 4;
1856
+ var lo = Math.min(0, Math.min.apply(null, rows.map(function (r) { return r.v; }))), hi = Math.max.apply(null, rows.map(function (r) { return Math.max(r.v, r.k || 0); })) || 1;
1857
+ var nt = niceTicks(lo, hi, Math.max(2, Math.min(6, Math.floor((x1 - x0) / 90))));
1858
+ var xs = function (v) { return x0 + (clamp(v, nt.lo, nt.hi) - nt.lo) / (nt.hi - nt.lo) * (x1 - x0); };
1859
+ var gridTop = y + fs + 6, gridBottom = gridTop + rows.length * (rowH + extra), g = svgEl("g", { "class": "vtr-contrib" }, svg);
1860
+ topTicks(c, g, nt, xs, y, x0, x1, gridTop, gridBottom);
1861
+ rows.forEach(function (r, i) {
1862
+ var ry = gridTop + i * (rowH + extra) + extra, bh = rowH * 0.56, by = ry + (rowH - bh) / 2, neg = r.v < 0;
1863
+ label(g, 0, lay.narrow ? ry - 3 : by + bh / 2 + fs * 0.35, fit(r.name, lay.narrow ? W - valW : lay.nameW - 8, fs, r.kind === "other" ? 400 : 600, fam), { fill: r.kind === "other" ? theme.mutedText : theme.text, "font-size": fs, "font-weight": r.kind === "other" ? 400 : 600, "class": "vtr-name" });
1864
+ var xa = xs(Math.min(0, r.v)), xb = xs(Math.max(0, r.v));
1865
+ svgEl("rect", { x: xa, y: by, width: Math.max(0.8, xb - xa), height: bh, rx: 2, fill: neg ? theme.hedge : theme.contribution, "class": "vtr-grow vtr-cbar" + (neg ? " vtr-hedge" : "") }, g);
1866
+ if (r.k != null) { var kx = xs(r.k), ky = by + bh / 2;
1867
+ svgEl("path", { d: "M" + kx + "," + (ky - 5) + "L" + (kx + 5) + "," + ky + "L" + kx + "," + (ky + 5) + "L" + (kx - 5) + "," + ky + "Z", fill: c.bg, stroke: theme.convexity, "stroke-width": 1.6, "class": "vtr-sa" }, g); }
1868
+ label(g, W, by + bh / 2 + fs * 0.35, f.signed(r.v), { "text-anchor": "end", fill: neg ? theme.hedgeText : theme.text, "font-size": fs, "font-weight": 700, "class": "vtr-val" });
1869
+ if (r.kind === "factor") c.points[r.obj.key] = { x: neg ? xa : xb, y: by };
1870
+ c.items.push({ kind: r.kind, obj: r.obj, contrib: true, x: 0, y: ry - extra, w: W, h: rowH + extra, px: neg ? xa : xb, py: by });
1871
+ });
1872
+ var corrText = !res.correlated ? "no correlations given, so factors are treated as independent and none can hedge another"
1873
+ : this.options.data.correlation.matrix ? "with the correlation matrix given" : "with correlations of " + f.percent(this.options.data.correlation.within || 0, 0) + " within groups and " + f.percent(this.options.data.correlation.across || 0, 0) + " across";
1874
+ var notes = ["Shares add up to the combined move of ±" + f.value(res.sigma) + "; stand-alone moves add up to " + f.value(res.standalone), "Combined " + corrText];
1875
+ var y2 = gridBottom + fs + 8;
1876
+ notes.forEach(function (t) { label(svg, 0, y2, fit(t + ".", W, fs - 1, 400, fam), { fill: theme.mutedText, "font-size": fs - 1, "class": "vtr-note" }); y2 += fs + 3; });
1877
+ return Math.ceil(y2 - fs + 6);
1878
+ };
1879
+
1880
+ Chart.prototype._tipLines = function (it) {
1881
+ var o = this.options, f = makeFormatters(o.data, o.locale), L = this._labels(), res = this._res, SN = this._shockNames(), loc = o.locale;
1882
+ var lvl = function (v) { return res.base != null ? " → " + f.value(res.base + v) : ""; };
1883
+ if (it.kind === "other") {
1884
+ var q = it.obj;
1885
+ return it.contrib ? [fill(L.other, { n: q.count }), "Shares together " + f.signed(q.contribution)]
1886
+ : [fill(L.other, { n: q.count }), SN.down + " (sum) " + f.signed(q.down), SN.up + " (sum) " + f.signed(q.up), L.swing + " together " + f.value(q.swing) + " (" + f.percent(q.share, 0) + " of the total)"];
1887
+ }
1888
+ if (it.kind === "group") {
1889
+ var g = it.obj;
1890
+ return [g.label + " · " + g.factors.length + " factor" + (g.factors.length > 1 ? "s" : ""), SN.down + " " + f.signed(g.down) + lvl(g.down), SN.up + " " + f.signed(g.up) + lvl(g.up),
1891
+ L.swing + " " + f.value(g.swing) + " (" + f.percent(g.share, 0) + " of the total)", "Combined move of the group ±" + f.value(g.standalone) + " · share of the total ±" + f.value(res.sigma) + ": " + f.signed(g.contribution)]
1892
+ .concat(g.breach ? [L.worst + " beyond the limit"] : []);
1893
+ }
1894
+ var x = it.obj;
1895
+ var lines = [x.label, x.group + " · rank " + x.rank + " of " + res.factors.length,
1896
+ SN.down + (x.shockDown != null ? " (" + shockText(x.shockDown, x.unit, loc) + ")" : "") + " " + f.signed(x.down) + lvl(x.down),
1897
+ SN.up + (x.shockUp != null ? " (" + shockText(x.shockUp, x.unit, loc) + ")" : "") + " " + f.signed(x.up) + lvl(x.up),
1898
+ L.swing + " " + f.value(x.swing) + " · " + f.percent(x.share, 0) + " of the total (top " + x.rank + ": " + f.percent(x.cumShare, 0) + ")",
1899
+ L.linear + " ±" + f.value(Math.abs(x.linear)) + " · " + L.convexity.toLowerCase() + " " + f.signed(x.convexity),
1900
+ "Share of the combined move " + f.signed(x.contribution) + " (stand-alone " + f.value(x.standalone) + ")"];
1901
+ if (x.breach) lines.push(SN[x.worst] + " is beyond the limit of " + f.value(res.limit));
1902
+ return lines;
1903
+ };
1904
+
1905
+ Chart.prototype._detail = function (it) {
1906
+ if (!it) return null;
1907
+ var view = this._view;
1908
+ if (it.kind === "other") return { view: view, kind: "other", count: it.obj.count, down: it.obj.down, up: it.obj.up, swing: it.obj.swing, contribution: it.obj.contribution, factors: it.obj.factors.map(function (x) { return x.key; }) };
1909
+ if (it.kind === "group") { var g = it.obj; return { view: view, kind: "group", key: g.key, label: g.label, factors: g.factors.slice(), down: g.down, up: g.up, swing: g.swing, share: g.share, linear: g.linear, convexity: g.convexity, worst: g.worst, worstValue: g.worstValue, breach: g.breach, contribution: g.contribution, standalone: g.standalone }; }
1910
+ var x = it.obj;
1911
+ return { view: view, kind: "factor", key: x.key, label: x.label, group: x.group, unit: x.unit, shockDown: x.shockDown, shockUp: x.shockUp, down: x.down, up: x.up, swing: x.swing, share: x.share, cumShare: x.cumShare, rank: x.rank,
1912
+ linear: x.linear, convexity: x.convexity, asymmetry: x.asymmetry, worst: x.worst, worstValue: x.worstValue, breach: x.breach, contribution: x.contribution, standalone: x.standalone, source: x.source };
1913
+ };
1914
+
1915
+ Chart.prototype.howToRead = function () {
1916
+ var v = this._view || this.options.view;
1917
+ if (v === "contribution") return "Each bar is one factor's share of the combined move when all factors move together with their correlations. Shares add up exactly to the combined move; a bar to the left means the factor hedges the others. The diamond marks the factor's move on its own, so the gap between the diamond and the bar is diversification.";
1918
+ if (v === "groups") return "Each row is one group of factors, such as a risk class, with every factor in it shocked down (upper bar) and up (lower bar) at the same time. Rows are sorted by swing, the distance between the two results.";
1919
+ return "Each row is one risk factor, shocked down (upper bar) and up (lower bar) on its own while everything else stays put. Rows are ranked by swing, the distance between the two results, so the factors that matter most are at the top. A diamond marks the midpoint of the two results when they are clearly unequal (convexity)" + (this._res && this._res.limit != null ? "; the dashed line is the loss limit." : ".");
1920
+ };
1921
+
1922
+ Chart.prototype.describe = function () {
1923
+ var o = this.options, f = makeFormatters(o.data, o.locale), L = this._labels(), res = this._res || compute(o.data, this._opts()), SN = this._shockNames(), out = [];
1924
+ var t = res.order[0];
1925
+ out.push("The largest driver is " + t.label + ": " + SN.down.toLowerCase() + " gives " + f.signed(t.down) + " and " + SN.up.toLowerCase() + " " + f.signed(t.up) + ", a swing of " + f.value(t.swing) + " (" + f.percent(t.share, 0) + " of the total swing).");
1926
+ if (res.factors.length > res.topN) out.push("The top " + res.topN + " of " + res.factors.length + " factors explain " + f.percent(res.topShare, 0) + ".");
1927
+ var w = res.worstFactor;
1928
+ out.push("The worst single shock is " + w.label + " " + SN[w.worst].toLowerCase() + " at " + f.signed(w.worstValue) + (res.limit != null ? (res.breaches ? ", beyond the limit of " + f.value(res.limit) + " (" + res.breaches + " factor" + (res.breaches > 1 ? "s" : "") + " in all)" : ", within the limit of " + f.value(res.limit)) : "") + ".");
1929
+ var cv = res.factors.filter(function (x) { return x.asymmetry >= 0.25 && x.swing > 0; }).sort(function (a, b) { return Math.abs(b.convexity) - Math.abs(a.convexity); });
1930
+ if (cv.length) out.push(cv.length + " factor" + (cv.length > 1 ? "s are" : " is") + " strongly asymmetric, led by " + cv[0].label + " (convexity " + f.signed(cv[0].convexity) + "), so a bigger shock would cost more than in proportion.");
1931
+ if (res.correlated) {
1932
+ var cs = res.factors.slice().sort(function (a, b) { return b.contribution - a.contribution; }), hedges = res.factors.filter(function (x) { return x.contribution < 0; }).sort(function (a, b) { return a.contribution - b.contribution; });
1933
+ out.push("Moving together with their correlations, the factors give a combined move of ±" + f.value(res.sigma) + ", " + f.percent(res.standalone > 0 ? res.diversification / res.standalone : 0, 0) + " less than the sum of their stand-alone moves; " + cs[0].label + " contributes most (" + f.signed(cs[0].contribution) + ")" + (hedges.length ? " and " + hedges[0].label + " hedges the most (" + f.signed(hedges[0].contribution) + ")" : "") + ".");
1934
+ }
1935
+ if (res.interaction && res.interaction.down != null) out.push("Shocked all at once, the down case gives " + f.signed(res.joint.down) + " against " + f.signed(res.sumDown) + " for the sum of single shocks, an interaction of " + f.signed(res.interaction.down) + ".");
1936
+ if (res.baseline) out.push("The what-if changes the worst single shock from " + f.signed(res.baseline.worstValue) + " to " + f.signed(w.worstValue) + ".");
1937
+ return out.join(" ");
1938
+ };
1939
+
1940
+ /* ======================================================================
1941
+ 5. EXPORT AND NOTES
1942
+ ====================================================================== */
1943
+ Chart.prototype.getExportData = function () {
1944
+ var o = this.options, data = o.data, L = this._labels(), f = makeFormatters(data, o.locale), res = this._res || compute(data, this._opts()), SN = this._shockNames(), loc = o.locale;
1945
+ var unit = { prefix: data.prefix || "", suffix: data.suffix || "", decimals: data.decimals != null ? data.decimals : 0, negatives: data.negatives };
1946
+ var money = function (label) { return { label: label, type: "number", unit: unit }; };
1947
+ var plain = function (label) { return { label: label, type: "number", unit: { decimals: 4 } }; };
1948
+ var pct = function (label) { return { label: label, type: "percent", decimals: 1 }; };
1949
+ var txt = function (label) { return { label: label, type: "text" }; };
1950
+ var sheets = [];
1951
+ var limit = o.exportRows != null ? o.exportRows : 20000, order = res.order, cut = order.length > limit;
1952
+ if (cut) order = order.slice(0, limit);
1953
+ var fr = order.map(function (x) { return [x.rank, x.label, x.group, x.unit, x.shockDown, x.shockUp, x.down, x.up, x.swing, x.share, x.cumShare, x.linear, x.convexity, SN[x.worst], x.worstValue, x.breach ? "Yes" : "No", x.contribution, x.standalone]; });
1954
+ sheets.push({ name: "Factors", columns: [{ label: "Rank", type: "number", unit: { decimals: 0 } }, txt("Risk factor"), txt("Group"), txt("Shock unit"), plain("Shock down"), plain("Shock up"), money(SN.down), money(SN.up), money(L.swing), pct("Share of total swing"), pct("Cumulative share"), money(L.linear), money(L.convexity), txt("Worst shock"), money(L.worst), txt("Beyond limit"), money("Share of combined move"), money("Stand-alone move")],
1955
+ rows: fr, text: order.map(function (x) { return [String(x.rank), x.label, x.group, x.unit, shockText(x.shockDown, "", loc) || "–", shockText(x.shockUp, "", loc) || "–", f.signed(x.down), f.signed(x.up), f.value(x.swing), f.percent(x.share), f.percent(x.cumShare), f.signed(x.linear), f.signed(x.convexity), SN[x.worst], f.signed(x.worstValue), x.breach ? "Yes" : "No", f.signed(x.contribution), f.value(x.standalone)]; }),
1956
+ flag: order.map(function (x) { return x.breach; }) });
1957
+ sheets.push({ name: "Groups", columns: [txt("Group"), { label: "Factors", type: "number", unit: { decimals: 0 } }, money(SN.down + " (sum)"), money(SN.up + " (sum)"), money(L.swing), pct("Share of total swing"), money(L.worst), txt("Beyond limit"), money("Share of combined move"), money("Group combined move")],
1958
+ rows: res.groups.map(function (g) { return [g.label, g.factors.length, g.down, g.up, g.swing, g.share, g.worstValue, g.breach ? "Yes" : "No", g.contribution, g.standalone]; }),
1959
+ text: res.groups.map(function (g) { return [g.label, String(g.factors.length), f.signed(g.down), f.signed(g.up), f.value(g.swing), f.percent(g.share), f.signed(g.worstValue), g.breach ? "Yes" : "No", f.signed(g.contribution), f.value(g.standalone)]; }),
1960
+ flag: res.groups.map(function (g) { return g.breach; }) });
1961
+ var sm = [["Total swing", res.totalSwing], ["Sum of " + SN.down.toLowerCase() + " impacts", res.sumDown], ["Sum of " + SN.up.toLowerCase() + " impacts", res.sumUp]];
1962
+ if (res.joint) {
1963
+ if (res.joint.down != null) sm.push(["All factors " + SN.down.toLowerCase() + " together", res.joint.down], [L.interaction + " (" + SN.down.toLowerCase() + ")", res.interaction.down]);
1964
+ if (res.joint.up != null) sm.push(["All factors " + SN.up.toLowerCase() + " together", res.joint.up], [L.interaction + " (" + SN.up.toLowerCase() + ")", res.interaction.up]);
1965
+ }
1966
+ sm.push([L.combined + " (±)", res.sigma], ["Sum of stand-alone moves", res.standalone], ["Diversification", res.diversification]);
1967
+ if (res.limit != null) sm.push([L.limit, res.limit]);
1968
+ sheets.push({ name: "Summary", columns: [txt("Item"), money("Amount")], rows: sm, text: sm.map(function (r) { return [r[0], /Sum|Interaction|together/.test(r[0]) ? f.signed(r[1]) : f.value(r[1])]; }) });
1969
+ var notes = (o.annotations || []).map(function (a, i) { return [String(i + 1), a.factor != null ? String(a.factor) : "Group: " + String(a.group || ""), a.text || ""]; });
1970
+ if (notes.length) sheets.push({ name: "Notes", columns: [txt("No."), txt("Factor or group"), txt("Note")], rows: notes });
1971
+ var c = data.correlation;
1972
+ return {
1973
+ title: data.title || "Risk-factor tornado", subtitle: data.subtitle || "", summary: this.describe(), library: "Veyforma Risk-Factor Tornado " + VERSION, sheets: sheets,
1974
+ meta: [["Unit", data.unit], ["As of", data.asOf], ["Desk", data.desk], ["Measure", res.higherIsBetter ? "Higher is better (for example P&L)" : "Lower is better (for example capital)"],
1975
+ ["Ranking", o.sort === "worst" ? "By worst result" : "By swing"], ["Shocks", SN.down + " / " + SN.up + (res.shockScale !== 1 ? ", scaled ×" + res.shockScale : "")],
1976
+ ["What-if", res.whatIf ? Object.keys(res.whatIf).map(function (k) { return k + " × " + res.whatIf[k]; }).join(", ") : null],
1977
+ ["Correlation", !c ? "None given (independent factors)" : c.matrix ? "Matrix given" : "Within groups " + (c.within || 0) + ", across " + (c.across || 0)],
1978
+ ["Limit", res.limit != null ? f.value(res.limit) + " (" + res.breaches + " beyond)" : null],
1979
+ ["Method", "Impact = given down/up result, or Δ·s + ½Γ·s²; swing = |up − down|; linear part L = (up − down) ÷ 2, convexity C = (up + down) ÷ 2; a shock k times larger ≈ L·k + C·k²; combined move σ = √(Lᵀ ρ L); factor share = L_k (ρL)_k ÷ σ (Euler allocation, adds up to σ)" + (cut ? "; factor sheet limited to the " + limit + " largest swings" : "")],
1980
+ ["Data source", data.source]]
1981
+ };
1982
+ };
1983
+ Chart.prototype._annotationPoint = function (a) {
1984
+ var p = this._points || {};
1985
+ if (a.factor != null) return p[String(a.factor)] || null;
1986
+ if (a.group != null) return p["group:" + String(a.group)] || null;
1987
+ return null;
1988
+ };
1989
+ Chart.prototype._annotationTarget = function (evt) {
1990
+ var items = this._items || [], it = null;
1991
+ if (!evt) it = items[this._active];
1992
+ else {
1993
+ var svg = this.plotHost.querySelector("svg"), r = svg.getBoundingClientRect(), vb = svg.viewBox.baseVal;
1994
+ var x = (evt.clientX - r.left) * (vb.width / r.width), y = (evt.clientY - r.top) * (vb.height / r.height);
1995
+ for (var i = 0; i < items.length; i++) { var q = items[i]; if (x >= q.x && x <= q.x + q.w && y >= q.y && y <= q.y + q.h) { it = q; break; } }
1996
+ }
1997
+ if (!it || it.kind === "other") return null;
1998
+ return it.kind === "group" ? { group: it.obj.key } : { factor: it.obj.key };
1999
+ };
2000
+ Chart.prototype._annotationLabel = function (a) {
2001
+ if (a.group != null) return String(a.group);
2002
+ var x = (this._res || this.getResult()).factors.filter(function (q) { return q.key === String(a.factor); })[0];
2003
+ return x ? x.label : String(a.factor || "");
2004
+ };
2005
+
2006
+ /* ======================================================================
2007
+ 6. PUBLIC API
2008
+ ====================================================================== */
2009
+ root.VeyRiskTornado = {
2010
+ version: VERSION,
2011
+ /** Draws the chart inside a container element or CSS selector. */
2012
+ create: function (target, options) { return new Chart(target, options); },
2013
+ /** Works out every figure without drawing. opts: { shockScale, whatIf, sort }. */
2014
+ compute: function (data, opts) { return compute(data, opts); },
2015
+ listThemes: function () { return Object.keys(THEMES); },
2016
+ getTheme: function (t) { return resolveTrTheme(t); },
2017
+ defaults: { options: DEFAULT_OPTIONS, labels: DEFAULT_LABELS, theme: BASE_THEME }
2018
+ };
2019
+ })(__vfRoot);
2020
+
2021
+ // P&L Attribution – Veyforma Chart Library · https://www.veyforma.com/charts/pnl-attribution
2022
+ /*!
2023
+ * Veyforma P&L Attribution v1.0.0
2024
+ * Explains the gap between front-office hypothetical P&L (HPL) and the risk model's risk-theoretical
2025
+ * P&L (RTPL) factor by factor, and runs the FRTB P&L attribution test on the daily totals: Spearman
2026
+ * correlation and the Kolmogorov-Smirnov statistic over the last 250 days, with the green, amber and
2027
+ * red zones. On top of the test it shows each factor's share of the unexplained P&L volatility (adds up
2028
+ * exactly), the test result if each factor's gap were closed, and the shortest path of fixes to green.
2029
+ * Original work created for Veyforma. Contains no third-party code.
2030
+ * Released under the MIT License. Copyright (c) 2026 Veyforma.
2031
+ * https://github.com/veyforma/veyforma-charts
2032
+ *
2033
+ * Load veyforma-toolkit.js as well to get the chart menu: full screen, print,
2034
+ * PNG, JPEG, SVG, PDF, CSV and Excel downloads, copy, notes and the
2035
+ * "How to read this chart" box.
2036
+ *
2037
+ * File layout
2038
+ * 1. Settings .......... themes, labels and options
2039
+ * 2. Helpers ........... formatting and small utilities
2040
+ * 3. Calculation ....... totals, Spearman, KS, zones, factor shares, fixes, path to green
2041
+ * 4. Chart instance .... factor, daily and distribution views, tooltips, keyboard
2042
+ * 5. Export and notes .. data for the Veyforma Toolkit menu (optional file)
2043
+ * 6. Public API ........ window.VeyPlaAttribution
2044
+ *
2045
+ * Method in one paragraph (see the manual for detail):
2046
+ * Daily totals HPL_t = Σ_k HPL_k,t and RTPL_t = Σ_k RTPL_k,t; unexplained U_t = HPL_t − RTPL_t, made of
2047
+ * factor gaps g_k,t = HPL_k,t − RTPL_k,t. Over the window: Spearman = Pearson correlation of the ranks
2048
+ * (ties get their average rank); KS = largest distance between the two empirical distribution functions.
2049
+ * Green if Spearman > 0.80 and KS < 0.09; red if Spearman < 0.70 or KS > 0.12; otherwise amber.
2050
+ * Factor share of the unexplained volatility = cov(g_k, U) ÷ sd(U), which adds up exactly to sd(U).
2051
+ * "If fixed" re-runs the test with RTPL_k = HPL_k; the path to green adds fixes one at a time, each time
2052
+ * taking the factor that brings the desk closest to green.
2053
+ */
2054
+ (function (root) {
2055
+ "use strict";
2056
+
2057
+ var VERSION = "1.0.0";
2058
+ var SVG_NS = "http://www.w3.org/2000/svg";
2059
+ var instanceCount = 0;
2060
+
2061
+ /* ======================================================================
2062
+ 1. SETTINGS
2063
+ ====================================================================== */
2064
+ var BASE_THEME = {
2065
+ hpl: "#111827", // front-office hypothetical P&L line
2066
+ rtpl: "#c2410c", // risk model P&L line
2067
+ unexplained: "#6b7280", // daily HPL − RTPL bars
2068
+ contribution: "#a63d16", // factors that add to the unexplained volatility
2069
+ offset: "#2f6fed", // factors whose gap offsets the others
2070
+ standalone: "#111827", // stand-alone diamonds
2071
+ zones: { green: "#15803d", amber: "#b45309", red: "#b91c1c" },
2072
+ outside: "#d1d5db", // days outside the test window
2073
+ grid: "#ececec",
2074
+ axis: "#9ca3af",
2075
+ text: "#111827",
2076
+ mutedText: "#4b5563",
2077
+ axisText: "#4b5563",
2078
+ cardBackground: "#f9fafb",
2079
+ background: "transparent",
2080
+ tooltipBackground: "#111827",
2081
+ tooltipText: "#ffffff",
2082
+ focus: "#c2410c",
2083
+ accent: "#c2410c",
2084
+ fontFamily: "inherit",
2085
+ fontSize: 12
2086
+ };
2087
+ var THEMES = {
2088
+ veyforma: {},
2089
+ mono: { hpl: "#111111", rtpl: "#6b6b6b", unexplained: "#8a8a8a", contribution: "#111111", offset: "#8a8a8a", zones: { green: "#111111", amber: "#4b4b4b", red: "#111111" }, accent: "#111111", focus: "#111111" },
2090
+ "colour-safe": { hpl: "#1f2937", rtpl: "#d55e00", unexplained: "#6b7280", contribution: "#cc3311", offset: "#0072b2", zones: { green: "#007a5e", amber: "#a35c00", red: "#b2182b" }, accent: "#0072b2" },
2091
+ ocean: { hpl: "#0c3b5e", rtpl: "#0e7490", contribution: "#0c3b5e", offset: "#c2410c", cardBackground: "#eef5f8", accent: "#0e7490" },
2092
+ forest: { hpl: "#22311a", rtpl: "#4d6b31", contribution: "#22311a", offset: "#2f6fed", cardBackground: "#f2f4ee", accent: "#4d6b31" },
2093
+ corporate: { hpl: "#1e293b", rtpl: "#1d4ed8", contribution: "#1e293b", offset: "#c2410c", cardBackground: "#f1f4f8", accent: "#1d4ed8" },
2094
+ midnight: { background: "#111418", hpl: "#f3f4f6", rtpl: "#f08a5d", unexplained: "#8b93a1", contribution: "#f08a5d", offset: "#93c5fd", standalone: "#f3f4f6",
2095
+ zones: { green: "#4ade80", amber: "#fbbf24", red: "#fb7185" }, outside: "#374151",
2096
+ grid: "#252a31", axis: "#4b5563", text: "#f3f4f6", mutedText: "#a3abb8", axisText: "#a3abb8",
2097
+ cardBackground: "#1b2027", tooltipBackground: "#f3f4f6", tooltipText: "#111418", focus: "#93c5fd", accent: "#f08a5d" }
2098
+ };
2099
+ var THRESHOLDS = { spearmanGreen: 0.80, spearmanRed: 0.70, ksGreen: 0.09, ksRed: 0.12 };
2100
+
2101
+ var DEFAULT_OPTIONS = {
2102
+ data: null, // required: { dates: [...], factors: [{ key, hpl: [...], rtpl: [...] }], … }
2103
+ view: "factors", // "factors" | "daily" | "distribution"
2104
+ window: 250, // test window in days (the most recent ones)
2105
+ fix: null, // factor keys to treat as fixed (RTPL = HPL), e.g. ["EUR 3s6s basis"]
2106
+ thresholds: null, // { spearmanGreen, spearmanRed, ksGreen, ksRed }; Basel values by default
2107
+ top: 15, // factor rows before the rest are summed into "Other" (0 = all)
2108
+ pathSteps: 5, // most fixes tried on the path to green
2109
+ theme: "veyforma",
2110
+ locale: undefined,
2111
+ animate: true,
2112
+ summary: true,
2113
+ legend: true,
2114
+ labels: null,
2115
+ ariaLabel: undefined,
2116
+ caption: true,
2117
+ annotations: null, // notes, e.g. [{ factor: "USD/JPY vol smile", text: "Smile added to the risk model in Q4" }] or { date, text }
2118
+ onAnnotationsChange: null,
2119
+ onItemClick: null, // function (detail, event): every figure for the factor or day clicked
2120
+ exportDays: 20000, // most rows in the daily sheet
2121
+ toolbar: true
2122
+ };
2123
+
2124
+ var DEFAULT_LABELS = {
2125
+ factors: "Unexplained P&L by risk factor", daily: "HPL and RTPL by day", distribution: "Distribution of HPL and RTPL",
2126
+ hpl: "HPL (front office)", rtpl: "RTPL (risk model)", unexplained: "Unexplained (HPL − RTPL)",
2127
+ adds: "Adds to unexplained volatility", offsets: "Offsets other gaps", standalone: "Gap on its own",
2128
+ test: "PLA test", unexplainedCard: "Unexplained P&L", largest: "Largest driver", path: "Path to green",
2129
+ green: "Green", amber: "Amber", red: "Red", na: "n/a", other: "Other {n} factors", unattributed: "Unattributed",
2130
+ notModelled: "not in the risk model", ifFixed: "If fixed", outside: "Outside the test window"
2131
+ };
2132
+ /* ======================================================================
2133
+ 2. HELPERS
2134
+ ====================================================================== */
2135
+ function assign(t) {
2136
+ for (var i = 1; i < arguments.length; i++) {
2137
+ var s = arguments[i];
2138
+ if (s) for (var k in s) if (Object.prototype.hasOwnProperty.call(s, k)) t[k] = s[k];
2139
+ }
2140
+ return t;
2141
+ }
2142
+ var warned = {};
2143
+ function warn(msg) { if (warned[msg]) return; warned[msg] = 1; if (root.console && console.warn) console.warn("VeyPlaAttribution: " + msg); }
2144
+ function fail(msg) { throw new Error("VeyPlaAttribution: " + msg); }
2145
+ function clamp(v, lo, hi) { return Math.min(hi, Math.max(lo, v)); }
2146
+ function fill(t, map) { return String(t).replace(/\{(\w+)\}/g, function (m, k) { return map[k] != null ? map[k] : m; }); }
2147
+ /** A name inside a sentence: "CET1 requirement" stays, "Pillar 1 minimum" becomes "pillar 1 minimum". */
2148
+ function lower(t) { t = String(t); return /^[A-Z0-9]{2}/.test(t) ? t : t.charAt(0).toLowerCase() + t.slice(1); }
2149
+ function num(v) { return typeof v === "number" ? v : v == null || v === "" ? NaN : +v; }
2150
+ function svgEl(tag, attrs, parent) {
2151
+ var n = document.createElementNS(SVG_NS, tag);
2152
+ if (attrs) for (var k in attrs) if (attrs[k] != null) n.setAttribute(k, attrs[k]);
2153
+ if (parent) parent.appendChild(n);
2154
+ return n;
2155
+ }
2156
+ function htmlEl(tag, cls, parent) {
2157
+ var n = document.createElement(tag);
2158
+ if (cls) n.className = cls;
2159
+ if (parent) parent.appendChild(n);
2160
+ return n;
2161
+ }
2162
+ var measureCtx = null;
2163
+ function textWidth(text, size, weight, family) {
2164
+ if (!measureCtx) { var c = document.createElement("canvas"); measureCtx = c.getContext && c.getContext("2d"); }
2165
+ if (!measureCtx) return String(text).length * size * 0.6;
2166
+ measureCtx.font = (weight || 400) + " " + size + "px " + family;
2167
+ return measureCtx.measureText(String(text)).width;
2168
+ }
2169
+ function fit(text, max, size, weight, family) {
2170
+ text = String(text);
2171
+ if (textWidth(text, size, weight, family) <= max) return text;
2172
+ while (text.length > 2 && textWidth(text + "…", size, weight, family) > max) text = text.slice(0, -1);
2173
+ return text.replace(/\s+$/, "") + "…";
2174
+ }
2175
+ function hexRgb(c) {
2176
+ var m = /^#?([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(String(c || "").trim());
2177
+ if (!m) return null;
2178
+ var h = m[1].length === 3 ? m[1].replace(/./g, "$&$&") : m[1], n = parseInt(h, 16);
2179
+ return [(n >> 16) & 255, (n >> 8) & 255, n & 255];
2180
+ }
2181
+ function luminance(rgb) {
2182
+ var a = rgb.map(function (v) { v /= 255; return v <= 0.03928 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4); });
2183
+ return 0.2126 * a[0] + 0.7152 * a[1] + 0.0722 * a[2];
2184
+ }
2185
+ function contrast(a, b) {
2186
+ var x = hexRgb(a), y = hexRgb(b);
2187
+ if (!x || !y) return 21;
2188
+ var l1 = luminance(x), l2 = luminance(y);
2189
+ return (Math.max(l1, l2) + 0.05) / (Math.min(l1, l2) + 0.05);
2190
+ }
2191
+ function ensureContrast(col, bg, min) {
2192
+ var c = hexRgb(col), b = hexRgb(bg);
2193
+ if (!c || !b || contrast(col, bg) >= min) return col;
2194
+ var dark = luminance(b) > 0.4, t = 0, out = col;
2195
+ while (t <= 1 && contrast(out, bg) < min) {
2196
+ t += 0.05;
2197
+ out = "#" + c.map(function (v) { var x = dark ? v * (1 - t) : v + (255 - v) * t; return ("0" + Math.round(x).toString(16)).slice(-2); }).join("");
2198
+ }
2199
+ return out;
2200
+ }
2201
+ function makeFormatters(data, locale) {
2202
+ var decimals = data.decimals != null ? data.decimals : 0, rd = data.ratioDecimals != null ? data.ratioDecimals : 1;
2203
+ var prefix = data.prefix || "", suffix = data.suffix || "", cache = {}, brackets = data.negatives === "brackets";
2204
+ function nf(d) {
2205
+ if (!cache[d]) cache[d] = new Intl.NumberFormat(locale || undefined, { minimumFractionDigits: d, maximumFractionDigits: d });
2206
+ return cache[d];
2207
+ }
2208
+ function value(v, d) {
2209
+ if (v == null || !isFinite(v)) return "–";
2210
+ if (d == null) d = decimals;
2211
+ var r = Number(v.toFixed(d)), body = prefix + nf(d).format(Math.abs(r)) + suffix;
2212
+ if (r >= 0) return body;
2213
+ return brackets ? "(" + body + ")" : "−" + body;
2214
+ }
2215
+ function signed(v, d) { var s = value(v, d); return v != null && Number(v.toFixed(d == null ? decimals : d)) > 0 ? "+" + s : s; }
2216
+ function ratio(v, d) { return v == null || !isFinite(v) ? "–" : (v < 0 ? "−" : "") + nf(d == null ? rd : d).format(Math.abs(v) * 100) + "%"; }
2217
+ function pp(v, d) {
2218
+ if (v == null || !isFinite(v)) return "–";
2219
+ var dd = d == null ? Math.max(rd, 1) : d, r = Number((v * 100).toFixed(dd));
2220
+ return (r > 0 ? "+" : r < 0 ? "−" : "") + nf(dd).format(Math.abs(r)) + " pp";
2221
+ }
2222
+ function percent(v, d) { return v == null || !isFinite(v) ? "–" : nf(d == null ? 1 : d).format(v * 100) + "%"; }
2223
+ return { value: value, signed: signed, ratio: ratio, pp: pp, percent: percent, nf: nf };
2224
+ }
2225
+
2226
+
2227
+
2228
+ /* ======================================================================
2229
+ 3. CALCULATION
2230
+ ====================================================================== */
2231
+ function finite(v, what) { var x = num(v); if (!isFinite(x)) fail(what + " must be a number."); return x; }
2232
+
2233
+ /** Ranks 1..n, ties get their average rank. */
2234
+ function ranks(a) {
2235
+ var n = a.length, idx = new Array(n), r = new Array(n), i, j;
2236
+ for (i = 0; i < n; i++) idx[i] = i;
2237
+ idx.sort(function (p, q) { return a[p] - a[q]; });
2238
+ for (i = 0; i < n; i = j) {
2239
+ j = i; while (j < n && a[idx[j]] === a[idx[i]]) j++;
2240
+ var avg = (i + j + 1) / 2; // ranks i+1 .. j
2241
+ for (var k = i; k < j; k++) r[idx[k]] = avg;
2242
+ }
2243
+ return r;
2244
+ }
2245
+ function pearson(x, y) {
2246
+ var n = x.length, mx = 0, my = 0, i;
2247
+ for (i = 0; i < n; i++) { mx += x[i]; my += y[i]; }
2248
+ mx /= n; my /= n;
2249
+ var sxy = 0, sxx = 0, syy = 0;
2250
+ for (i = 0; i < n; i++) { var dx = x[i] - mx, dy = y[i] - my; sxy += dx * dy; sxx += dx * dx; syy += dy * dy; }
2251
+ return sxx > 0 && syy > 0 ? sxy / Math.sqrt(sxx * syy) : null;
2252
+ }
2253
+ function spearman(x, y) { return pearson(ranks(x), ranks(y)); }
2254
+ /** Two-sample Kolmogorov-Smirnov statistic: the largest gap between the two empirical distribution functions. */
2255
+ function ksStat(x, y) {
2256
+ var a = x.slice().sort(function (p, q) { return p - q; }), b = y.slice().sort(function (p, q) { return p - q; });
2257
+ var n = a.length, m = b.length, i = 0, j = 0, d = 0, at = a.length ? a[0] : 0;
2258
+ while (i < n && j < m) {
2259
+ var v = Math.min(a[i], b[j]);
2260
+ while (i < n && a[i] === v) i++;
2261
+ while (j < m && b[j] === v) j++;
2262
+ var g = Math.abs(i / n - j / m);
2263
+ if (g > d + 1e-15) { d = g; at = v; }
2264
+ }
2265
+ return { d: d, at: at };
2266
+ }
2267
+ function zoneOf(rho, ks, T) {
2268
+ if (rho == null) return "red";
2269
+ rho = Math.round(rho * 1e12) / 1e12; ks = Math.round(ks * 1e12) / 1e12; // so a value exactly on a threshold is not tipped over by rounding
2270
+ if (rho > T.spearmanGreen && ks < T.ksGreen) return "green";
2271
+ if (rho < T.spearmanRed || ks > T.ksRed) return "red";
2272
+ return "amber";
2273
+ }
2274
+ /** How far a result is from green: 0 when green. */
2275
+ function distance(t, T) { return Math.max(0, T.spearmanGreen - (t.spearman == null ? -1 : t.spearman)) / 0.1 + Math.max(0, t.ks - T.ksGreen) / 0.03; }
2276
+ function test(H, R, T) {
2277
+ var rho = spearman(H, R), k = ksStat(H, R);
2278
+ return { spearman: rho, ks: k.d, ksAt: k.at, zone: zoneOf(rho, k.d, T) };
2279
+ }
2280
+ function sdOf(a) { var n = a.length, m = 0, s = 0, i; for (i = 0; i < n; i++) m += a[i]; m /= n; for (i = 0; i < n; i++) s += (a[i] - m) * (a[i] - m); return Math.sqrt(s / n); }
2281
+ function meanOf(a) { var s = 0; for (var i = 0; i < a.length; i++) s += a[i]; return a.length ? s / a.length : 0; }
2282
+
2283
+ function readData(data) {
2284
+ if (!data || typeof data !== "object") fail("data is required.");
2285
+ var dates = data.dates;
2286
+ if (!Array.isArray(dates) || dates.length < 2) fail("data.dates must be an array of at least two days.");
2287
+ var n = dates.length;
2288
+ var series = function (a, what, allowNull) {
2289
+ if (a == null && allowNull) return null;
2290
+ if (!Array.isArray(a) || a.length !== n) fail(what + " must be an array with one value per date (" + n + ").");
2291
+ return a.map(function (v, i) { return finite(v, what + "[" + i + "]"); });
2292
+ };
2293
+ if (!Array.isArray(data.factors) || !data.factors.length) fail("data.factors must be a non-empty array of risk factors.");
2294
+ var seen = {};
2295
+ var fs = data.factors.map(function (x, i) {
2296
+ if (!x || typeof x !== "object") fail("data.factors[" + i + "] is not an object.");
2297
+ if (x.key == null && x.label == null) fail("data.factors[" + i + "] needs a key or a label.");
2298
+ var key = String(x.key != null ? x.key : x.label), w = 'factor "' + key + '"';
2299
+ if (seen[key]) fail(w + " is used twice.");
2300
+ seen[key] = 1;
2301
+ var h = series(x.hpl, w + ": hpl"), r = series(x.rtpl, w + ": rtpl", true);
2302
+ return { key: key, label: x.label != null ? String(x.label) : key, group: x.group != null ? String(x.group) : "Other", modelled: r != null, hpl: h, rtpl: r || h.map(function () { return 0; }), index: i };
2303
+ });
2304
+ var ht = series(data.hplTotal, "data.hplTotal", true), rt = series(data.rtplTotal, "data.rtplTotal", true);
2305
+ if (ht || rt) {
2306
+ // what the factors do not explain becomes one more row
2307
+ var sh = new Array(n), sr = new Array(n), t;
2308
+ for (t = 0; t < n; t++) { sh[t] = 0; sr[t] = 0; fs.forEach(function (f) { sh[t] += f.hpl[t]; sr[t] += f.rtpl[t]; }); }
2309
+ fs.push({ key: "__unattributed", label: data.unattributedLabel || DEFAULT_LABELS.unattributed, group: "Unattributed", modelled: true, unattributed: true,
2310
+ hpl: sh.map(function (v, i) { return ht ? ht[i] - v : 0; }), rtpl: sr.map(function (v, i) { return rt ? rt[i] - v : 0; }), index: fs.length });
2311
+ }
2312
+ return { dates: dates.map(String), factors: fs, n: n };
2313
+ }
2314
+
2315
+ /** Every figure. opts: { window, fix, thresholds, pathSteps }. */
2316
+ function compute(data, opts) {
2317
+ opts = opts || {};
2318
+ var D = readData(data), n = D.n, fs = D.factors;
2319
+ var T = assign({}, THRESHOLDS, opts.thresholds || {});
2320
+ var w = opts.window != null ? Math.floor(finite(opts.window, "window")) : 250;
2321
+ if (!(w >= 2)) fail("window must be at least 2 days.");
2322
+ var short = w > n; if (short) w = n;
2323
+ var start = n - w;
2324
+ var fix = {};
2325
+ (opts.fix || []).forEach(function (k) { if (!fs.some(function (f) { return f.key === String(k); })) warn('fix: there is no factor "' + k + '", so it changes nothing.'); fix[String(k)] = 1; });
2326
+ fs.forEach(function (f) { f.fixed = !!fix[f.key]; f.rt = f.fixed ? f.hpl : f.rtpl; f.gap = f.hpl.map(function (v, t) { return v - f.rt[t]; }); });
2327
+ var H = new Array(n), R = new Array(n), U = new Array(n), t, k;
2328
+ for (t = 0; t < n; t++) { var h = 0, r = 0; for (k = 0; k < fs.length; k++) { h += fs[k].hpl[t]; r += fs[k].rt[t]; } H[t] = h; R[t] = r; U[t] = h - r; }
2329
+ var Hw = H.slice(start), Rw = R.slice(start), Uw = U.slice(start);
2330
+ var res = { dates: D.dates, hpl: H, rtpl: R, unexplained: U, start: start, window: w, shortWindow: short, thresholds: T, fixed: Object.keys(fix) };
2331
+ res.test = test(Hw, Rw, T);
2332
+ var sdU = sdOf(Uw), sdH = sdOf(Hw), mU = meanOf(Uw);
2333
+ res.sdUnexplained = sdU; res.sdHpl = sdH; res.meanUnexplained = mU;
2334
+ res.volRatio = sdH > 0 ? sdU / sdH : null; res.meanRatio = sdH > 0 ? mU / sdH : null; res.varRatio = sdH > 0 ? (sdU * sdU) / (sdH * sdH) : null;
2335
+ // factor figures over the window
2336
+ fs.forEach(function (f) {
2337
+ var g = f.gap.slice(start), mg = meanOf(g), c = 0;
2338
+ for (t = 0; t < w; t++) c += (g[t] - mg) * (Uw[t] - mU);
2339
+ c /= w;
2340
+ f.meanGap = mg; f.sdGap = sdOf(g); f.contribution = sdU > 0 ? c / sdU : 0; f.share = sdU > 0 ? f.contribution / sdU : 0;
2341
+ f.hplSum = 0; f.rtplSum = 0; for (t = start; t < n; t++) { f.hplSum += f.hpl[t]; f.rtplSum += f.rt[t]; }
2342
+ f.hasGap = f.sdGap > 0 || mg !== 0;
2343
+ if (f.hasGap) { var R2 = Rw.map(function (v, i) { return v + g[i]; }); f.ifFixed = test(Hw, R2, T); }
2344
+ else f.ifFixed = res.test;
2345
+ });
2346
+ var order = fs.slice().sort(function (a, b) { return Math.abs(b.contribution) - Math.abs(a.contribution) || a.index - b.index; });
2347
+ order.forEach(function (f, i) { f.rank = i + 1; });
2348
+ res.factors = fs; res.order = order;
2349
+ // shortest path to green: add the fix that brings the desk closest to green, one at a time
2350
+ var steps = opts.pathSteps != null ? Math.max(0, Math.floor(opts.pathSteps)) : 5, path = [], cur = Rw.slice(), curT = res.test, used = {};
2351
+ while (curT.zone !== "green" && path.length < steps) {
2352
+ var best = null;
2353
+ fs.forEach(function (f) {
2354
+ if (used[f.key] || f.fixed || !f.hasGap) return;
2355
+ var g = f.gap.slice(start), R2 = cur.map(function (v, i) { return v + g[i]; }), tt = test(Hw, R2, T), dd = distance(tt, T);
2356
+ if (!best || dd < best.d - 1e-12 || (Math.abs(dd - best.d) <= 1e-12 && (tt.spearman || -1) > (best.t.spearman || -1))) best = { f: f, t: tt, d: dd, R: R2 };
2357
+ });
2358
+ if (!best || best.d >= distance(curT, T) - 1e-12) break; // nothing helps any more
2359
+ used[best.f.key] = 1; path.push({ key: best.f.key, label: best.f.label, test: best.t }); cur = best.R; curT = best.t;
2360
+ }
2361
+ res.path = path; res.pathReachesGreen = res.test.zone === "green" || (path.length > 0 && path[path.length - 1].test.zone === "green");
2362
+ res.distribution = { hpl: Hw.slice().sort(function (a, b) { return a - b; }), rtpl: Rw.slice().sort(function (a, b) { return a - b; }) };
2363
+ return res;
2364
+ }
2365
+ /* ======================================================================
2366
+ 4. CHART INSTANCE
2367
+ ====================================================================== */
2368
+ function injectStyles() {
2369
+ if (document.getElementById("vpa-styles")) return;
2370
+ var css =
2371
+ ".vpa{position:relative;color:var(--vpa-text);background:var(--vpa-bg);font-family:var(--vpa-font);line-height:1.4}" +
2372
+ ".vpa.vpa-filled{padding:14px 14px 8px;border-radius:10px}" +
2373
+ ".vpa-summary{display:grid;grid-template-columns:repeat(auto-fit,minmax(150px,1fr));gap:8px;margin:0 0 10px}" +
2374
+ ".vpa-stat{background:var(--vpa-card);border-radius:8px;padding:9px 12px;min-width:0}" +
2375
+ ".vpa-stat .k{font-size:11px;letter-spacing:.04em;text-transform:uppercase;color:var(--vpa-card-muted);font-weight:600;overflow-wrap:anywhere;hyphens:auto}" +
2376
+ ".vpa-stat .v{font-size:19px;font-weight:700;font-variant-numeric:tabular-nums;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}" +
2377
+ ".vpa-stat .n{font-size:12px;color:var(--vpa-card-muted)}" +
2378
+ ".vpa-stat .v.vpa-zone{font-weight:800}" +
2379
+ ".vpa-stat .v.vpa-wrap{white-space:normal;overflow-wrap:anywhere;line-height:1.2;font-size:17px}" +
2380
+ ".vpa-scope{font-size:12px;color:var(--vpa-muted);margin:0 0 4px}" +
2381
+ ".vpa-legend{display:flex;flex-wrap:wrap;gap:4px 14px;font-size:12px;margin:0 0 6px;color:var(--vpa-text)}" +
2382
+ ".vpa-legend span{display:inline-flex;align-items:center;gap:6px}" +
2383
+ ".vpa-legend i{display:inline-block;width:12px;height:12px;border-radius:3px}" +
2384
+ ".vpa-legend i.vpa-tick{width:16px;height:3px;border-radius:1px}" +
2385
+ ".vpa-legend i.vpa-ring{background:transparent!important;border:2px solid;border-radius:2px;width:9px;height:9px;transform:rotate(45deg)}" +
2386
+ ".vpa-plot{display:block;width:100%;height:auto;overflow:visible;outline:none}" +
2387
+ ".vpa-plot:focus-visible{outline:2px solid var(--vpa-focus);outline-offset:4px;border-radius:4px}" +
2388
+ ".vpa-animate .vpa-grow{animation:vpa-fade .45s ease both}" +
2389
+ "@keyframes vpa-fade{from{opacity:0}to{opacity:1}}" +
2390
+ "@media (prefers-reduced-motion:reduce){.vpa-animate .vpa-grow{animation:none}}" +
2391
+ ".vpa-tip{position:absolute;left:0;top:0;pointer-events:none;background:var(--vpa-tip-bg);color:var(--vpa-tip-text);" +
2392
+ "font-size:12px;line-height:1.45;padding:8px 10px;border-radius:8px;opacity:0;transform:translateY(4px);" +
2393
+ "transition:opacity .12s,transform .12s;white-space:nowrap;z-index:5;font-variant-numeric:tabular-nums}" +
2394
+ ".vpa-tip.vpa-on{opacity:1;transform:none}.vpa-tip b{font-weight:600}" +
2395
+ ".vpa-table{border-collapse:collapse;font-size:12px;font-variant-numeric:tabular-nums;margin:0 0 14px;min-width:100%}" +
2396
+ ".vpa-table caption{text-align:left;font-weight:700;padding:0 0 6px}" +
2397
+ ".vpa-table th,.vpa-table td{padding:5px 8px;border-bottom:1px solid rgba(127,127,127,.25);text-align:right;white-space:nowrap}" +
2398
+ ".vpa-table th:first-child,.vpa-table td:first-child{text-align:left}" +
2399
+ ".vpa-table tr.vpa-breach td{color:var(--vpa-hedge);font-weight:600}" +
2400
+ "@media (max-width:420px){.vpa-summary{grid-template-columns:repeat(auto-fit,minmax(118px,1fr))}.vpa-stat{padding:8px 10px}.vpa-stat .v{font-size:17px}}";
2401
+ var s = htmlEl("style");
2402
+ s.id = "vpa-styles";
2403
+ s.textContent = css;
2404
+ (document.head || document.documentElement).appendChild(s);
2405
+ }
2406
+ function resolvePaTheme(theme) {
2407
+ var t;
2408
+ if (theme == null || theme === "") theme = "veyforma";
2409
+ if (typeof theme === "string") {
2410
+ if (!THEMES.hasOwnProperty(theme)) { warn('Unknown theme "' + theme + '". The "veyforma" theme is used instead.'); theme = "veyforma"; }
2411
+ t = assign({}, BASE_THEME, THEMES[theme]);
2412
+ } else if (typeof theme === "object") {
2413
+ t = assign(theme["extends"] ? resolvePaTheme(theme["extends"]) : assign({}, BASE_THEME), theme);
2414
+ delete t["extends"];
2415
+ } else { warn("The theme option must be a theme name or an object."); t = assign({}, BASE_THEME); }
2416
+ var bg = /^#/.test(t.background) ? t.background : "#ffffff", card = /^#/.test(t.cardBackground) ? t.cardBackground : bg;
2417
+ ["axisText", "mutedText"].forEach(function (k) { t[k] = ensureContrast(t[k], bg, 4.5); });
2418
+ t.cardMuted = ensureContrast(t.mutedText, card, 4.5);
2419
+ t.offsetText = ensureContrast(ensureContrast(t.offset, bg, 4.5), card, 4.5);
2420
+ t.zoneText = {};
2421
+ ["green", "amber", "red"].forEach(function (z) { t.zoneText[z] = ensureContrast(ensureContrast(t.zones[z], bg, 4.5), card, 4.5); });
2422
+ t.accentText = ensureContrast(t.accent, bg, 4.5);
2423
+ return t;
2424
+ }
2425
+
2426
+ function Chart(target, options) {
2427
+ var container = typeof target === "string" ? document.querySelector(target) : target;
2428
+ if (!container || container.nodeType !== 1) fail("container not found (" + target + ").");
2429
+ if (!options || !options.data) fail("options.data is required.");
2430
+ injectStyles();
2431
+ this.id = ++instanceCount;
2432
+ this.container = container;
2433
+ this.options = assign({}, DEFAULT_OPTIONS, options);
2434
+ this.element = htmlEl("div", "vpa");
2435
+ this.element.setAttribute("role", "figure");
2436
+ this.summaryEl = htmlEl("div", "vpa-summary", this.element);
2437
+ this.scopeEl = htmlEl("p", "vpa-scope", this.element);
2438
+ this.legendEl = htmlEl("div", "vpa-legend", this.element);
2439
+ this.plotHost = htmlEl("div", "vpa-plot-host", this.element);
2440
+ this.tipEl = htmlEl("div", "vpa-tip", this.element);
2441
+ this.tipEl.setAttribute("role", "tooltip");
2442
+ container.appendChild(this.element);
2443
+ this._animateNext = !!this.options.animate;
2444
+ this._lastWidth = 0;
2445
+ this._active = -1;
2446
+ var self = this;
2447
+ if (root.ResizeObserver) {
2448
+ this._observer = new root.ResizeObserver(function () {
2449
+ var w = Math.round(self.element.clientWidth);
2450
+ if (w && Math.abs(w - self._lastWidth) > 1) self.redraw();
2451
+ });
2452
+ this._observer.observe(this.element);
2453
+ } else {
2454
+ this._onResize = function () { self.redraw(); };
2455
+ root.addEventListener("resize", this._onResize);
2456
+ }
2457
+ this._onDocTap = function (e) { if (!self.element.contains(e.target)) self._hideTip(); };
2458
+ document.addEventListener("pointerdown", this._onDocTap);
2459
+ this.redraw();
2460
+ if (this.options.toolbar !== false && root.VeyformaToolkit) this.toolkit = root.VeyformaToolkit.attach(this, this.options.toolbar);
2461
+ }
2462
+
2463
+ Chart.prototype.update = function (partial) {
2464
+ if (!partial) return this;
2465
+ if (partial.data && partial.data !== this.options.data && this.options.animate) this._animateNext = true;
2466
+ if (partial.view && partial.view !== this.options.view && this.options.animate) this._animateNext = true;
2467
+ assign(this.options, partial);
2468
+ return this.redraw();
2469
+ };
2470
+ Chart.prototype.setData = function (data) { this._res = null; return this.update({ data: data }); };
2471
+ Chart.prototype.setView = function (view) { return this.update({ view: view }); };
2472
+ Chart.prototype.setTheme = function (theme) { return this.update({ theme: theme }); };
2473
+ Chart.prototype.getTheme = function () { return resolvePaTheme(this.options.theme); };
2474
+ Chart.prototype._opts = function () { return { window: this.options.window, fix: this.options.fix, thresholds: this.options.thresholds }; };
2475
+ Chart.prototype.getResult = function () { return compute(this.options.data, this._opts()); };
2476
+ Chart.prototype.getFactor = function (key) { return this.getResult().factors.filter(function (f) { return f.key === String(key); })[0] || null; };
2477
+ Chart.prototype.setFix = function (keys) { return this.update({ fix: keys }); };
2478
+ Chart.prototype.setWindow = function (days) { return this.update({ window: days }); };
2479
+ Chart.prototype._labels = function () { return assign({}, DEFAULT_LABELS, this.options.labels); };
2480
+ Chart.prototype.destroy = function () {
2481
+ if (this.toolkit && this.toolkit.destroy) this.toolkit.destroy();
2482
+ if (this._observer) this._observer.disconnect();
2483
+ if (this._onResize) root.removeEventListener("resize", this._onResize);
2484
+ document.removeEventListener("pointerdown", this._onDocTap);
2485
+ if (this.element.parentNode) this.element.parentNode.removeChild(this.element);
2486
+ };
2487
+ Chart.prototype._hideTip = function () { this.tipEl.classList.remove("vpa-on"); if (this._hlEl) this._hlEl.setAttribute("opacity", 0); };
2488
+ Chart.prototype._placeTip = function (lines, rect, evt) {
2489
+ var tip = this.tipEl;
2490
+ tip.textContent = "";
2491
+ lines.forEach(function (ln, i) {
2492
+ if (i) tip.appendChild(document.createElement("br"));
2493
+ var node = i === 0 ? document.createElement("b") : document.createElement("span");
2494
+ node.textContent = ln;
2495
+ tip.appendChild(node);
2496
+ });
2497
+ var box = this.element.getBoundingClientRect();
2498
+ var px = evt && evt.clientX ? evt.clientX : rect.left + rect.width / 2;
2499
+ var py = evt && evt.clientY ? evt.clientY : rect.top + 10;
2500
+ tip.classList.add("vpa-on");
2501
+ var tw = tip.offsetWidth, th = tip.offsetHeight;
2502
+ tip.style.left = clamp(px - box.left - tw / 2, 4, Math.max(4, box.width - tw - 4)) + "px";
2503
+ var top = py - box.top - th - 14;
2504
+ if (top < 0) top = py - box.top + 18;
2505
+ tip.style.top = top + "px";
2506
+ };
2507
+ /** A "nice" axis from lo to hi with about n ticks. */
2508
+ function niceTicks(lo, hi, n) {
2509
+ if (!(hi > lo)) { hi = lo + 1; }
2510
+ var span = hi - lo, step = Math.pow(10, Math.floor(Math.log(span / n) / Math.LN10)), err = span / n / step;
2511
+ if (err >= 7.5) step *= 10; else if (err >= 3.5) step *= 5; else if (err >= 1.5) step *= 2;
2512
+ var a = Math.floor(lo / step + 1e-9) * step, b = Math.ceil(hi / step - 1e-9) * step, out = [];
2513
+ for (var v = a; v <= b + step / 2; v += step) out.push(Math.round(v / step) * step);
2514
+ return { lo: a, hi: b, ticks: out, step: step };
2515
+ }
2516
+
2517
+ function label(g, x, y, text, attrs) {
2518
+ var t = svgEl("text", assign({ x: x, y: y }, attrs || {}), g);
2519
+ t.textContent = text;
2520
+ return t;
2521
+ }
2522
+
2523
+ Chart.prototype._bindInteraction = function (svg, W, H, theme, L, f) {
2524
+ var self = this, items = this._items, o = this.options;
2525
+ function idxAt(evt) {
2526
+ var r = svg.getBoundingClientRect(), x = (evt.clientX - r.left) * (W / r.width), y = (evt.clientY - r.top) * (H / r.height);
2527
+ for (var i = 0; i < items.length; i++) { var it = items[i]; if (x >= it.x && x <= it.x + it.w && y >= it.y && y <= it.y + it.h) return i; }
2528
+ return -1;
2529
+ }
2530
+ function show(i, evt) {
2531
+ if (i < 0) { self._hideTip(); return; }
2532
+ self._active = i;
2533
+ var it = items[i], hl = self._hlEl;
2534
+ hl.setAttribute("x", it.x - 4); hl.setAttribute("y", it.y); hl.setAttribute("width", it.w + 8); hl.setAttribute("height", it.h); hl.setAttribute("opacity", 1);
2535
+ var r = svg.getBoundingClientRect(), sx = r.width / W;
2536
+ var rect = { left: r.left + it.px * sx, top: r.top + it.py * (r.height / H), width: 0, height: 0 };
2537
+ self._placeTip(self._tipLines(it), rect, evt && evt.clientX ? evt : null);
2538
+ }
2539
+ svg.addEventListener("pointermove", function (e) { show(idxAt(e), e); });
2540
+ svg.addEventListener("pointerleave", function () { self._hideTip(); });
2541
+ svg.addEventListener("click", function (e) {
2542
+ var i = idxAt(e);
2543
+ if (i >= 0 && typeof o.onItemClick === "function") o.onItemClick(self._detail(items[i]), e);
2544
+ });
2545
+ svg.addEventListener("keydown", function (e) {
2546
+ var i = self._active;
2547
+ if (e.key === "ArrowRight" || e.key === "ArrowDown") i = Math.min(items.length - 1, i + 1);
2548
+ else if (e.key === "ArrowLeft" || e.key === "ArrowUp") i = Math.max(0, i < 0 ? 0 : i - 1);
2549
+ else if (e.key === "Home") i = 0;
2550
+ else if (e.key === "End") i = items.length - 1;
2551
+ else if (e.key === "Escape") { self._hideTip(); return; }
2552
+ else if ((e.key === "Enter" || e.key === " ") && i >= 0) {
2553
+ if (typeof o.onItemClick === "function") o.onItemClick(self._detail(items[i]), e);
2554
+ e.preventDefault(); return;
2555
+ } else return;
2556
+ e.preventDefault();
2557
+ show(i, null);
2558
+ });
2559
+ svg.addEventListener("blur", function () { self._hideTip(); });
2560
+ };
2561
+
2562
+ Chart.prototype.createTable = function () {
2563
+ var ex = this.getExportData(), wrap = htmlEl("div", "vpa-tables");
2564
+ ex.sheets.forEach(function (sh) {
2565
+ if (sh.name === "Notes") return;
2566
+ var tb = htmlEl("table", "vpa-table", wrap);
2567
+ htmlEl("caption", null, tb).textContent = sh.name;
2568
+ var hr = htmlEl("tr", null, htmlEl("thead", null, tb));
2569
+ sh.columns.forEach(function (c) { var th = htmlEl("th", null, hr); th.scope = "col"; th.textContent = c.label; });
2570
+ var body = htmlEl("tbody", null, tb);
2571
+ sh.text.forEach(function (r, i) {
2572
+ var tr = htmlEl("tr", sh.flag && sh.flag[i] ? "vpa-breach" : null, body);
2573
+ r.forEach(function (v, j) { var td = htmlEl(j ? "td" : "th", null, tr); if (!j) td.scope = "row"; td.textContent = v; });
2574
+ });
2575
+ });
2576
+ return wrap;
2577
+ };
2578
+
2579
+
2580
+ Chart.prototype.redraw = function () {
2581
+ var o = this.options, data = o.data, L = this._labels();
2582
+ var res = this._res = compute(data, assign(this._opts(), { pathSteps: o.pathSteps }));
2583
+ var theme = resolvePaTheme(o.theme), f = makeFormatters(data, o.locale), el = this.element, st = el.style;
2584
+ var family = theme.fontFamily === "inherit" ? (root.getComputedStyle ? root.getComputedStyle(this.container).fontFamily : "sans-serif") : theme.fontFamily;
2585
+ var filled = theme.background && theme.background !== "transparent", bg = filled ? theme.background : "#ffffff";
2586
+ st.setProperty("--vpa-text", theme.text); st.setProperty("--vpa-muted", theme.mutedText);
2587
+ st.setProperty("--vpa-bg", filled ? theme.background : "transparent"); st.setProperty("--vpa-font", family);
2588
+ st.setProperty("--vpa-card", theme.cardBackground); st.setProperty("--vpa-card-muted", theme.cardMuted);
2589
+ st.setProperty("--vpa-tip-bg", theme.tooltipBackground); st.setProperty("--vpa-tip-text", theme.tooltipText);
2590
+ st.setProperty("--vpa-focus", theme.focus); st.setProperty("--vpa-hedge", theme.zoneText.red);
2591
+ el.classList.toggle("vpa-filled", !!filled);
2592
+ el.setAttribute("aria-label", o.ariaLabel || data.title || "P&L attribution");
2593
+ var view = o.view;
2594
+ if (["factors", "daily", "distribution"].indexOf(view) < 0) { warn('Unknown view "' + view + '". The factor view is shown instead.'); view = "factors"; }
2595
+ if (res.shortWindow && !this._warnedShort) { warn("There are fewer days than the " + (o.window || 250) + "-day window; all " + res.window + " are used."); this._warnedShort = true; }
2596
+ this._view = view;
2597
+ this._renderSummary(res, f, L, theme);
2598
+ this.scopeEl.textContent = [L[view], res.window + "-day window", data.unit || null, res.fixed.length ? res.fixed.length + " fix" + (res.fixed.length > 1 ? "es" : "") + " applied" : null].filter(Boolean).join(" · ");
2599
+ this._renderLegend(view, theme, L, res);
2600
+ var W = Math.max(280, Math.round(this.plotHost.clientWidth || el.clientWidth || 720));
2601
+ this._lastWidth = Math.round(el.clientWidth);
2602
+ var fs = theme.fontSize || 12;
2603
+ this.plotHost.textContent = "";
2604
+ var svg = svgEl("svg", { "class": "vpa-plot", role: "img", tabindex: 0, "font-family": family }, this.plotHost);
2605
+ svg.style.fontSize = fs + "px";
2606
+ var animate = this._animateNext && o.animate; this._animateNext = false;
2607
+ if (animate) svg.classList.add("vpa-animate");
2608
+ var ctx = { svg: svg, W: W, fs: fs, theme: theme, f: f, L: L, family: family, bg: bg, res: res, items: [], points: {} };
2609
+ var H = view === "daily" ? this._drawDaily(ctx) : view === "distribution" ? this._drawDistribution(ctx) : this._drawFactors(ctx);
2610
+ svg.setAttribute("viewBox", "0 0 " + W + " " + H);
2611
+ svg.setAttribute("width", W); svg.setAttribute("height", H);
2612
+ svg.setAttribute("aria-label", (o.ariaLabel || data.title || "P&L attribution") + ". " + this.describe());
2613
+ this._items = ctx.items; this._points = ctx.points;
2614
+ this._hlEl = svgEl("rect", { x: 0, y: 0, width: 0, height: 0, rx: 4, fill: theme.text, "fill-opacity": 0.06, opacity: 0, "pointer-events": "none" }, svg);
2615
+ svg.insertBefore(this._hlEl, svg.firstChild);
2616
+ this._bindInteraction(svg, W, H, theme, L, f);
2617
+ return this;
2618
+ };
2619
+
2620
+ function num2(v) { return v == null ? "n/a" : v.toFixed(2); }
2621
+ Chart.prototype._zoneName = function (z) { var L = this._labels(); return L[z] || z; };
2622
+
2623
+ Chart.prototype._renderSummary = function (res, f, L, theme) {
2624
+ var box = this.summaryEl, o = this.options, self = this;
2625
+ box.textContent = "";
2626
+ box.style.display = o.summary === false ? "none" : "";
2627
+ if (o.summary === false) return;
2628
+ function stat(k, v, n, cls, colour) {
2629
+ var s = htmlEl("div", "vpa-stat", box);
2630
+ htmlEl("div", "k", s).textContent = k;
2631
+ var vv = htmlEl("div", cls ? "v " + cls : "v", s); vv.textContent = v; if (colour) vv.style.color = colour;
2632
+ if (n) htmlEl("div", "n", s).textContent = n;
2633
+ }
2634
+ var t = res.test, top = res.order[0];
2635
+ stat(L.test, this._zoneName(t.zone), "Spearman " + num2(t.spearman) + " · KS " + num2(t.ks) + " (" + res.window + " days)", "vpa-zone", theme.zoneText[t.zone]);
2636
+ stat(L.unexplainedCard, "±" + f.value(res.sdUnexplained), (res.volRatio != null ? f.percent(res.volRatio, 0) + " of HPL volatility · " : "") + "mean " + f.signed(res.meanUnexplained) + " a day");
2637
+ stat(L.largest, top.label, f.percent(top.share, 0) + " of the unexplained volatility", "vpa-wrap");
2638
+ if (t.zone === "green") stat(L.path, "Already green", "margin: Spearman +" + (t.spearman - res.thresholds.spearmanGreen).toFixed(2) + ", KS −" + (res.thresholds.ksGreen - t.ks).toFixed(2));
2639
+ else if (res.pathReachesGreen) stat(L.path, "Fix " + res.path.length + " factor" + (res.path.length > 1 ? "s" : ""), res.path.map(function (p) { return p.label; }).join(", ") + " → Spearman " + num2(res.path[res.path.length - 1].test.spearman) + ", KS " + num2(res.path[res.path.length - 1].test.ks), "vpa-wrap");
2640
+ else stat(L.path, res.path.length ? "Not within " + res.path.length + " fix" + (res.path.length > 1 ? "es" : "") : "No single fix helps", res.path.length ? "best reached: " + this._zoneName(res.path[res.path.length - 1].test.zone).toLowerCase() : "the gap is spread across factors");
2641
+ Array.prototype.forEach.call(box.querySelectorAll(".vpa-stat .v"), function (v) {
2642
+ v.style.fontSize = "";
2643
+ var size = parseFloat(root.getComputedStyle ? root.getComputedStyle(v).fontSize : 19) || 19;
2644
+ while (v.scrollWidth > v.clientWidth && size > 12) { size -= 1; v.style.fontSize = size + "px"; }
2645
+ });
2646
+ };
2647
+
2648
+ Chart.prototype._renderLegend = function (view, theme, L, res) {
2649
+ var box = this.legendEl;
2650
+ box.textContent = "";
2651
+ box.style.display = this.options.legend === false ? "none" : "";
2652
+ function item(colour, text, cls) {
2653
+ var s = htmlEl("span", null, box), i = htmlEl("i", cls || null, s);
2654
+ if (cls === "vpa-ring") i.style.borderColor = colour; else i.style.background = colour;
2655
+ s.appendChild(document.createTextNode(text));
2656
+ }
2657
+ if (view === "factors") { item(theme.contribution, L.adds); item(theme.offset, L.offsets); item(theme.standalone, L.standalone, "vpa-ring"); return; }
2658
+ item(theme.hpl, L.hpl, "vpa-tick"); item(theme.rtpl, L.rtpl, "vpa-tick");
2659
+ if (view === "daily") { item(theme.unexplained, L.unexplained); if (res.start > 0) item(theme.outside, L.outside); }
2660
+ };
2661
+
2662
+ function rowLayout(c, names) {
2663
+ var nameW = Math.min(Math.max.apply(null, names.map(function (n) { return textWidth(n, c.fs, 600, c.family); })) + 12, c.W * 0.34);
2664
+ var narrow = c.W - nameW < 300;
2665
+ return { nameW: narrow ? 0 : nameW, narrow: narrow };
2666
+ }
2667
+ function axisTicks(c, g, nt, xs, y, x0, x1, gridTop, gridBottom, fmt) {
2668
+ var theme = c.theme, fs = c.fs, fam = c.family, W = c.W, lastRight = -Infinity;
2669
+ nt.ticks.forEach(function (t) {
2670
+ svgEl("line", { x1: xs(t), x2: xs(t), y1: gridTop, y2: gridBottom, stroke: t === 0 ? theme.axis : theme.grid, "stroke-width": t === 0 ? 1.2 : 1 }, g);
2671
+ var tt = fmt(t), tw = textWidth(tt, fs - 1, 400, fam), tx = xs(t), anc = tx - tw / 2 < 0 ? "start" : tx + tw / 2 > W ? "end" : "middle";
2672
+ var left = anc === "start" ? tx : anc === "end" ? tx - tw : tx - tw / 2;
2673
+ if (left < lastRight + 8) return;
2674
+ lastRight = left + tw;
2675
+ label(g, tx, y + fs, tt, { "text-anchor": anc, fill: theme.axisText, "font-size": fs - 1, "class": "vpa-tick" });
2676
+ });
2677
+ }
2678
+
2679
+ /** Factor view: each factor's share of the unexplained volatility (adds up), stand-alone gap as a diamond, and the zone if fixed. */
2680
+ Chart.prototype._drawFactors = function (c) {
2681
+ var res = c.res, theme = c.theme, f = c.f, L = c.L, fs = c.fs, fam = c.family, W = c.W, svg = c.svg, self = this;
2682
+ var top = +this.options.top > 0 ? Math.floor(+this.options.top) : res.order.length, rest = res.order.slice(top);
2683
+ var rows = res.order.slice(0, top).sort(function (a, b) { return b.contribution - a.contribution; }).map(function (x) { return { kind: "factor", obj: x, name: x.label + (x.modelled ? "" : " *"), v: x.contribution, k: x.sdGap }; });
2684
+ if (rest.length) { var sv = 0, sk = 0; rest.forEach(function (x) { sv += x.contribution; sk += x.sdGap; }); rows.push({ kind: "other", obj: { count: rest.length, contribution: sv, factors: rest }, name: fill(L.other, { n: rest.length }), v: sv, k: null }); }
2685
+ var lay = rowLayout(c, rows.map(function (r) { return r.name; }));
2686
+ var zoneW = Math.max(textWidth("→ " + L.amber, fs - 1, 600, fam), textWidth("→ " + L.green, fs - 1, 600, fam), textWidth("→ " + L.red, fs - 1, 600, fam)) + 14;
2687
+ var valW = Math.max.apply(null, rows.map(function (r) { return textWidth(f.signed(r.v), fs, 700, fam); })) + 10;
2688
+ var x0 = lay.nameW, x1 = W - valW - zoneW, rowH = Math.max(26, fs * 2.1), extra = lay.narrow ? fs + 4 : 0, y = 4;
2689
+ var lo = Math.min(0, Math.min.apply(null, rows.map(function (r) { return r.v; }))), hi = Math.max.apply(null, rows.map(function (r) { return Math.max(r.v, r.k || 0); })) || 1;
2690
+ var nt = niceTicks(lo, hi, Math.max(2, Math.min(6, Math.floor((x1 - x0) / 90))));
2691
+ var xs = function (v) { return x0 + (clamp(v, nt.lo, nt.hi) - nt.lo) / (nt.hi - nt.lo) * (x1 - x0); };
2692
+ var gridTop = y + fs + 6, gridBottom = gridTop + rows.length * (rowH + extra), g = svgEl("g", { "class": "vpa-factors" }, svg);
2693
+ axisTicks(c, g, nt, xs, y, x0, x1, gridTop, gridBottom, function (v) { return f.value(v); });
2694
+ label(g, W, y + fs, L.ifFixed, { "text-anchor": "end", fill: theme.axisText, "font-size": fs - 1, "class": "vpa-tick" });
2695
+ rows.forEach(function (r, i) {
2696
+ var ry = gridTop + i * (rowH + extra) + extra, bh = rowH * 0.56, by = ry + (rowH - bh) / 2, neg = r.v < 0 && f.value(-r.v) !== f.value(0); // a value that rounds to zero is shown as neutral
2697
+ label(g, 0, lay.narrow ? ry - 3 : by + bh / 2 + fs * 0.35, fit(r.name, lay.narrow ? W - zoneW : lay.nameW - 8, fs, r.kind === "other" ? 400 : 600, fam), { fill: r.kind === "other" ? theme.mutedText : theme.text, "font-size": fs, "font-weight": r.kind === "other" ? 400 : 600, "class": "vpa-name" });
2698
+ var xa = xs(Math.min(0, r.v)), xb = xs(Math.max(0, r.v));
2699
+ svgEl("rect", { x: xa, y: by, width: Math.max(0.8, xb - xa), height: bh, rx: 2, fill: neg ? theme.offset : theme.contribution, "class": "vpa-grow vpa-cbar" + (neg ? " vpa-offset" : "") }, g);
2700
+ if (r.k != null) { var kx = xs(r.k), ky = by + bh / 2;
2701
+ svgEl("path", { d: "M" + kx + "," + (ky - 5) + "L" + (kx + 5) + "," + ky + "L" + kx + "," + (ky + 5) + "L" + (kx - 5) + "," + ky + "Z", fill: c.bg, stroke: theme.standalone, "stroke-width": 1.6, "class": "vpa-sa" }, g); }
2702
+ label(g, W - zoneW, by + bh / 2 + fs * 0.35, f.signed(r.v), { "text-anchor": "end", fill: neg ? theme.offsetText : theme.text, "font-size": fs, "font-weight": 700, "class": "vpa-val" });
2703
+ if (r.kind === "factor") {
2704
+ var z = r.obj.ifFixed.zone;
2705
+ label(g, W, by + bh / 2 + fs * 0.35, "→ " + self._zoneName(z), { "text-anchor": "end", fill: theme.zoneText[z], "font-size": fs - 1, "font-weight": 600, "class": "vpa-zonefix" });
2706
+ c.points[r.obj.key] = { x: neg ? xa : xb, y: by };
2707
+ }
2708
+ c.items.push({ kind: r.kind, obj: r.obj, x: 0, y: ry - extra, w: W, h: rowH + extra, px: neg ? xa : xb, py: by });
2709
+ });
2710
+ var notes = ["Shares add up to the unexplained volatility of ±" + f.value(res.sdUnexplained) + " a day over " + res.window + " days"];
2711
+ if (res.factors.some(function (x) { return !x.modelled; })) notes.push("* " + L.notModelled + " (RTPL taken as zero)");
2712
+ notes.push("“" + L.ifFixed + "”: test zone with that factor's RTPL set equal to its HPL");
2713
+ var y2 = gridBottom + fs + 8;
2714
+ notes.forEach(function (t) { label(svg, 0, y2, fit(t + ".", W, fs - 1, 400, fam), { fill: theme.mutedText, "font-size": fs - 1, "class": "vpa-note" }); y2 += fs + 3; });
2715
+ return Math.ceil(y2 - fs + 6);
2716
+ };
2717
+
2718
+ /** Daily view: HPL and RTPL lines with the unexplained P&L as bars; days outside the test window are greyed. */
2719
+ Chart.prototype._drawDaily = function (c) {
2720
+ var res = c.res, theme = c.theme, f = c.f, L = c.L, fs = c.fs, fam = c.family, W = c.W, svg = c.svg, n = res.dates.length;
2721
+ var all = res.hpl.concat(res.rtpl, res.unexplained);
2722
+ var nt = niceTicks(Math.min(0, Math.min.apply(null, all)), Math.max(0, Math.max.apply(null, all)), W < 480 ? 4 : 6);
2723
+ var tickW = Math.max.apply(null, nt.ticks.map(function (t) { return textWidth(f.value(t), fs - 1, 400, fam); }));
2724
+ var x0 = tickW + 10, x1 = W - 4, top = 6, ph = W < 480 ? 220 : 300, bottom = top + ph;
2725
+ var xs = function (i) { return x0 + (i + 0.5) / n * (x1 - x0); }, ys = function (v) { return top + (nt.hi - clamp(v, nt.lo, nt.hi)) / (nt.hi - nt.lo) * ph; };
2726
+ var g = svgEl("g", { "class": "vpa-daily" }, svg);
2727
+ if (res.start > 0) svgEl("rect", { x: x0, y: top, width: xs(res.start) - (x1 - x0) / n / 2 - x0, height: ph, fill: theme.outside, "fill-opacity": 0.35, "class": "vpa-outside" }, g);
2728
+ nt.ticks.forEach(function (t) {
2729
+ svgEl("line", { x1: x0, x2: x1, y1: ys(t), y2: ys(t), stroke: t === 0 ? theme.axis : theme.grid, "stroke-width": t === 0 ? 1.2 : 1 }, g);
2730
+ label(g, x0 - 6, ys(t) + (fs - 1) * 0.35, f.value(t), { "text-anchor": "end", fill: theme.axisText, "font-size": fs - 1, "class": "vpa-tick" });
2731
+ });
2732
+ var bw = Math.max(0.6, (x1 - x0) / n * 0.7);
2733
+ res.unexplained.forEach(function (u, i) { var ya = ys(Math.max(0, u)), yb = ys(Math.min(0, u)); svgEl("rect", { x: xs(i) - bw / 2, y: ya, width: bw, height: Math.max(0.6, yb - ya), fill: theme.unexplained, "fill-opacity": i < res.start ? 0.4 : 0.85, "class": "vpa-grow vpa-ubar" }, g); });
2734
+ var path = function (a) { return a.map(function (v, i) { return (i ? "L" : "M") + xs(i).toFixed(2) + "," + ys(v).toFixed(2); }).join(""); };
2735
+ svgEl("path", { d: path(res.hpl), fill: "none", stroke: theme.hpl, "stroke-width": 1.6, "stroke-linejoin": "round", "class": "vpa-line vpa-hpl" }, g);
2736
+ svgEl("path", { d: path(res.rtpl), fill: "none", stroke: theme.rtpl, "stroke-width": 1.6, "stroke-dasharray": "4 2", "stroke-linejoin": "round", "class": "vpa-line vpa-rtpl" }, g);
2737
+ // date labels, thinned
2738
+ var lw = textWidth(res.dates[0], fs - 1, 400, fam) + 16, every = Math.max(1, Math.ceil(lw / ((x1 - x0) / n))), lastRight = -Infinity;
2739
+ for (var i = 0; i < n; i += every) {
2740
+ var tx = xs(i), tw = textWidth(res.dates[i], fs - 1, 400, fam), anc = tx - tw / 2 < 0 ? "start" : tx + tw / 2 > W ? "end" : "middle", left = anc === "start" ? tx : anc === "end" ? tx - tw : tx - tw / 2;
2741
+ if (left < lastRight + 8) continue;
2742
+ lastRight = left + tw;
2743
+ label(g, tx, bottom + fs + 9, res.dates[i], { "text-anchor": anc, fill: theme.axisText, "font-size": fs - 1, "class": "vpa-tick" });
2744
+ }
2745
+ var step = (x1 - x0) / n;
2746
+ res.dates.forEach(function (d, j) {
2747
+ c.items.push({ kind: "day", index: j, x: xs(j) - step / 2, y: top, w: step, h: ph, px: xs(j), py: ys(Math.max(res.hpl[j], res.rtpl[j])) });
2748
+ c.points["date:" + d] = { x: xs(j), y: ys(Math.max(res.hpl[j], res.rtpl[j])) };
2749
+ });
2750
+ var notes = ["Unexplained P&L ±" + f.value(res.sdUnexplained) + " a day (" + (res.volRatio != null ? f.percent(res.volRatio, 0) + " of HPL volatility" : "") + ") over the last " + res.window + " days"];
2751
+ var y2 = bottom + fs * 2 + 17;
2752
+ notes.forEach(function (t) { label(svg, 0, y2, fit(t + ".", W, fs - 1, 400, fam), { fill: theme.mutedText, "font-size": fs - 1, "class": "vpa-note" }); y2 += fs + 3; });
2753
+ return Math.ceil(y2 - fs + 6);
2754
+ };
2755
+
2756
+ /** Distribution view: the two empirical distribution functions with the KS distance marked. */
2757
+ Chart.prototype._drawDistribution = function (c) {
2758
+ var res = c.res, theme = c.theme, f = c.f, L = c.L, fs = c.fs, fam = c.family, W = c.W, svg = c.svg, D = res.distribution, n = D.hpl.length, T = res.thresholds;
2759
+ var lo = Math.min(D.hpl[0], D.rtpl[0]), hi = Math.max(D.hpl[n - 1], D.rtpl[n - 1]);
2760
+ var nt = niceTicks(lo, hi, W < 480 ? 4 : 6);
2761
+ var x0 = textWidth("100%", fs - 1, 400, fam) + 10, x1 = W - 6, top = 8, ph = W < 480 ? 200 : 270, bottom = top + ph;
2762
+ var xs = function (v) { return x0 + (clamp(v, nt.lo, nt.hi) - nt.lo) / (nt.hi - nt.lo) * (x1 - x0); }, ys = function (p) { return top + (1 - p) * ph; };
2763
+ var g = svgEl("g", { "class": "vpa-dist" }, svg);
2764
+ [0, 0.25, 0.5, 0.75, 1].forEach(function (p) {
2765
+ svgEl("line", { x1: x0, x2: x1, y1: ys(p), y2: ys(p), stroke: p === 0 ? theme.axis : theme.grid }, g);
2766
+ label(g, x0 - 6, ys(p) + (fs - 1) * 0.35, Math.round(p * 100) + "%", { "text-anchor": "end", fill: theme.axisText, "font-size": fs - 1, "class": "vpa-tick" });
2767
+ });
2768
+ axisTicks(c, g, nt, xs, bottom + 8, x0, x1, top, bottom, function (v) { return f.value(v); });
2769
+ var step = function (a) { var d = "M" + xs(nt.lo) + "," + ys(0); a.forEach(function (v, i) { d += "L" + xs(v).toFixed(2) + "," + ys(i / n).toFixed(2) + "L" + xs(v).toFixed(2) + "," + ys((i + 1) / n).toFixed(2); }); return d + "L" + xs(nt.hi) + "," + ys(1); };
2770
+ svgEl("path", { d: step(D.hpl), fill: "none", stroke: theme.hpl, "stroke-width": 1.8, "class": "vpa-line vpa-hpl" }, g);
2771
+ svgEl("path", { d: step(D.rtpl), fill: "none", stroke: theme.rtpl, "stroke-width": 1.8, "stroke-dasharray": "4 2", "class": "vpa-line vpa-rtpl" }, g);
2772
+ var cdf = function (a, v) { var lo2 = 0, hi2 = a.length; while (lo2 < hi2) { var m = (lo2 + hi2) >> 1; if (a[m] <= v) lo2 = m + 1; else hi2 = m; } return lo2 / a.length; };
2773
+ var at = res.test.ksAt, p1 = cdf(D.hpl, at), p2 = cdf(D.rtpl, at), kx = xs(at), z = res.test.zone;
2774
+ svgEl("line", { x1: kx, x2: kx, y1: ys(p1), y2: ys(p2), stroke: theme.zoneText[z], "stroke-width": 3, "class": "vpa-ksline" }, g);
2775
+ var kt = "KS " + num2(res.test.ks), ktw = textWidth(kt, fs, 700, fam), kl = kx + 8 + ktw > W ? kx - 8 : kx + 8;
2776
+ svgEl("rect", { x: (kx + 8 + ktw > W ? kl - ktw : kl) - 3, y: (ys(p1) + ys(p2)) / 2 - fs * 0.7, width: ktw + 6, height: fs * 1.4, rx: 3, fill: c.bg, "class": "vpa-lbg" }, g);
2777
+ label(g, kl, (ys(p1) + ys(p2)) / 2 + fs * 0.35, kt, { "text-anchor": kx + 8 + ktw > W ? "end" : "start", fill: theme.zoneText[z], "font-size": fs, "font-weight": 700, "class": "vpa-kslabel" });
2778
+ for (var i = 0; i <= 20; i++) {
2779
+ var v = nt.lo + (nt.hi - nt.lo) * i / 20, wx = (x1 - x0) / 20;
2780
+ c.items.push({ kind: "point", value: v, ph: cdf(D.hpl, v), pr: cdf(D.rtpl, v), x: xs(v) - wx / 2, y: top, w: wx, h: ph, px: xs(v), py: ys(Math.max(cdf(D.hpl, v), cdf(D.rtpl, v))) });
2781
+ }
2782
+ var notes = ["Spearman " + num2(res.test.spearman) + " (green above " + T.spearmanGreen.toFixed(2) + ", red below " + T.spearmanRed.toFixed(2) + ") · KS " + num2(res.test.ks) + " (green below " + T.ksGreen.toFixed(2) + ", red above " + T.ksRed.toFixed(2) + ")",
2783
+ "Share of the " + res.window + " days with P&L at or below each value"];
2784
+ var y2 = bottom + fs * 2 + 12;
2785
+ notes.forEach(function (t) { label(svg, 0, y2, fit(t + ".", W, fs - 1, 400, fam), { fill: theme.mutedText, "font-size": fs - 1, "class": "vpa-note" }); y2 += fs + 3; });
2786
+ return Math.ceil(y2 - fs + 6);
2787
+ };
2788
+
2789
+ Chart.prototype._tipLines = function (it) {
2790
+ var o = this.options, f = makeFormatters(o.data, o.locale), L = this._labels(), res = this._res, self = this;
2791
+ if (it.kind === "other") return [fill(L.other, { n: it.obj.count }), "Together " + f.signed(it.obj.contribution) + " of the unexplained volatility"];
2792
+ if (it.kind === "day") {
2793
+ var j = it.index, gaps = res.factors.map(function (x) { return { l: x.label, g: x.gap[j] }; }).filter(function (q) { return q.g !== 0; }).sort(function (a, b) { return Math.abs(b.g) - Math.abs(a.g); }).slice(0, 3);
2794
+ return [res.dates[j] + (j < res.start ? " · " + L.outside.toLowerCase() : ""), L.hpl + " " + f.signed(res.hpl[j]), L.rtpl + " " + f.signed(res.rtpl[j]), L.unexplained + " " + f.signed(res.unexplained[j])]
2795
+ .concat(gaps.length ? ["Largest gaps: " + gaps.map(function (q) { return q.l + " " + f.signed(q.g); }).join(", ")] : []);
2796
+ }
2797
+ if (it.kind === "point") return ["P&L at or below " + f.signed(it.value), "HPL " + f.percent(it.ph, 0) + " of days · RTPL " + f.percent(it.pr, 0), "Gap " + f.percent(Math.abs(it.ph - it.pr), 0) + " (KS is the largest gap: " + num2(res.test.ks) + ")"];
2798
+ var x = it.obj, t = x.ifFixed;
2799
+ return [x.label + (x.modelled ? "" : " (" + L.notModelled + ")"), x.group + " · rank " + x.rank + " of " + res.factors.length,
2800
+ "Share of unexplained volatility " + f.signed(x.contribution) + " (" + f.percent(x.share, 0) + ")",
2801
+ "Gap on its own ±" + f.value(x.sdGap) + " a day · mean " + f.signed(x.meanGap),
2802
+ "HPL " + f.signed(x.hplSum) + " · RTPL " + f.signed(x.rtplSum) + " over " + res.window + " days",
2803
+ L.ifFixed + ": " + self._zoneName(t.zone).toLowerCase() + " (Spearman " + num2(t.spearman) + ", KS " + num2(t.ks) + ")"];
2804
+ };
2805
+
2806
+ Chart.prototype._detail = function (it) {
2807
+ if (!it) return null;
2808
+ var res = this._res, view = this._view;
2809
+ if (it.kind === "other") return { view: view, kind: "other", count: it.obj.count, contribution: it.obj.contribution, factors: it.obj.factors.map(function (x) { return x.key; }) };
2810
+ if (it.kind === "day") { var j = it.index; return { view: view, kind: "day", date: res.dates[j], hpl: res.hpl[j], rtpl: res.rtpl[j], unexplained: res.unexplained[j], inWindow: j >= res.start, gaps: res.factors.map(function (x) { return { key: x.key, gap: x.gap[j] }; }) }; }
2811
+ if (it.kind === "point") return { view: view, kind: "point", value: it.value, hplShare: it.ph, rtplShare: it.pr };
2812
+ var x = it.obj;
2813
+ return { view: view, kind: "factor", key: x.key, label: x.label, group: x.group, modelled: x.modelled, fixed: x.fixed, rank: x.rank, contribution: x.contribution, share: x.share, sdGap: x.sdGap, meanGap: x.meanGap,
2814
+ hplSum: x.hplSum, rtplSum: x.rtplSum, ifFixed: { spearman: x.ifFixed.spearman, ks: x.ifFixed.ks, zone: x.ifFixed.zone } };
2815
+ };
2816
+
2817
+ Chart.prototype.howToRead = function () {
2818
+ var v = this._view || this.options.view;
2819
+ if (v === "daily") return "The dark line is front-office hypothetical P&L (HPL) and the dashed line the risk model's P&L (RTPL), day by day. Grey bars are the difference, the unexplained P&L. Only the most recent days, inside the test window, count for the test.";
2820
+ if (v === "distribution") return "Each line shows the share of days with P&L at or below a value, for HPL and for RTPL. If the risk model matched the front office, the two lines would sit on top of each other. The coloured bar marks the largest gap between them, the Kolmogorov-Smirnov (KS) statistic.";
2821
+ return "Each bar is one risk factor's share of the unexplained P&L volatility (HPL − RTPL). Shares add up exactly to the total; a bar to the left means the factor's gap offsets other gaps. The diamond is the factor's gap on its own, and the right column shows the test zone the desk would reach if that factor's gap were closed.";
2822
+ };
2823
+
2824
+ Chart.prototype.describe = function () {
2825
+ var o = this.options, f = makeFormatters(o.data, o.locale), L = this._labels(), res = this._res || compute(o.data, this._opts()), t = res.test, T = res.thresholds, out = [], self = this;
2826
+ var why = [];
2827
+ if (t.spearman == null || t.spearman <= T.spearmanGreen) why.push("Spearman " + num2(t.spearman) + (t.spearman != null && t.spearman >= T.spearmanRed ? " is below " + T.spearmanGreen.toFixed(2) : " is below " + T.spearmanRed.toFixed(2)));
2828
+ if (t.ks >= T.ksGreen) why.push("KS " + num2(t.ks) + (t.ks <= T.ksRed ? " is above " + T.ksGreen.toFixed(2) : " is above " + T.ksRed.toFixed(2)));
2829
+ out.push("Over the last " + res.window + " days the desk is in the " + this._zoneName(t.zone).toLowerCase() + " zone of the P&L attribution test" + (why.length ? ": " + why.join(" and ") + "." : " (Spearman " + num2(t.spearman) + ", KS " + num2(t.ks) + ")."));
2830
+ out.push("Unexplained P&L is ±" + f.value(res.sdUnexplained) + " a day" + (res.volRatio != null ? ", " + f.percent(res.volRatio, 0) + " of the front office's P&L volatility" : "") + ".");
2831
+ var a = res.order[0], b = res.order[1];
2832
+ out.push(a.label + (a.modelled ? "" : ", which is not in the risk model,") + " explains " + f.percent(a.share, 0) + " of it" + (b ? ", followed by " + b.label + " (" + f.percent(b.share, 0) + ")" : "") + ".");
2833
+ var off = res.factors.filter(function (x) { return x.share < -0.02; }).sort(function (p, q) { return p.contribution - q.contribution; });
2834
+ if (off.length) out.push("The gap on " + off[0].label + " partly offsets the others.");
2835
+ if (t.zone !== "green") {
2836
+ if (res.pathReachesGreen) { var last = res.path[res.path.length - 1].test; out.push("Closing the gap on " + res.path.map(function (p) { return p.label; }).join(" and ") + " would bring the desk to green (Spearman " + num2(last.spearman) + ", KS " + num2(last.ks) + ")."); }
2837
+ else if (res.path.length) out.push("Even closing the gaps on " + res.path.map(function (p) { return p.label; }).join(", ") + " only reaches " + this._zoneName(res.path[res.path.length - 1].test.zone).toLowerCase() + ".");
2838
+ }
2839
+ if (res.fixed.length) out.push("Fixes applied: " + res.fixed.join(", ") + ".");
2840
+ return out.join(" ");
2841
+ };
2842
+
2843
+ /* ======================================================================
2844
+ 5. EXPORT AND NOTES
2845
+ ====================================================================== */
2846
+ Chart.prototype.getExportData = function () {
2847
+ var o = this.options, data = o.data, L = this._labels(), f = makeFormatters(data, o.locale), res = this._res || compute(data, this._opts()), self = this, T = res.thresholds;
2848
+ var unit = { prefix: data.prefix || "", suffix: data.suffix || "", decimals: data.decimals != null ? data.decimals : 0, negatives: data.negatives };
2849
+ var money = function (label) { return { label: label, type: "number", unit: unit }; };
2850
+ var ratio = function (label) { return { label: label, type: "number", unit: { decimals: 3 } }; };
2851
+ var pct = function (label) { return { label: label, type: "percent", decimals: 1 }; };
2852
+ var txt = function (label) { return { label: label, type: "text" }; };
2853
+ var sheets = [];
2854
+ sheets.push({ name: "Factors", columns: [{ label: "Rank", type: "number", unit: { decimals: 0 } }, txt("Risk factor"), txt("Group"), txt("In risk model"), txt("Fixed"), money("HPL over window"), money("RTPL over window"), money("Mean daily gap"), money("Gap volatility"), money("Share of unexplained volatility"), pct("Share (%)"), ratio("Spearman if fixed"), ratio("KS if fixed"), txt("Zone if fixed")],
2855
+ rows: res.order.map(function (x) { return [x.rank, x.label, x.group, x.modelled ? "Yes" : "No", x.fixed ? "Yes" : "No", x.hplSum, x.rtplSum, x.meanGap, x.sdGap, x.contribution, x.share, x.ifFixed.spearman, x.ifFixed.ks, self._zoneName(x.ifFixed.zone)]; }),
2856
+ text: res.order.map(function (x) { return [String(x.rank), x.label, x.group, x.modelled ? "Yes" : "No", x.fixed ? "Yes" : "No", f.signed(x.hplSum), f.signed(x.rtplSum), f.signed(x.meanGap), f.value(x.sdGap), f.signed(x.contribution), f.percent(x.share), num2(x.ifFixed.spearman), num2(x.ifFixed.ks), self._zoneName(x.ifFixed.zone)]; }),
2857
+ flag: res.order.map(function (x) { return !x.modelled; }) });
2858
+ var cap = o.exportDays != null ? o.exportDays : 20000, from = Math.max(0, res.dates.length - cap), idx = [];
2859
+ for (var j = from; j < res.dates.length; j++) idx.push(j);
2860
+ sheets.push({ name: "Daily", columns: [txt("Date"), money("HPL"), money("RTPL"), money("Unexplained"), txt("In test window")],
2861
+ rows: idx.map(function (j) { return [res.dates[j], res.hpl[j], res.rtpl[j], res.unexplained[j], j >= res.start ? "Yes" : "No"]; }),
2862
+ text: idx.map(function (j) { return [res.dates[j], f.signed(res.hpl[j]), f.signed(res.rtpl[j]), f.signed(res.unexplained[j]), j >= res.start ? "Yes" : "No"]; }) });
2863
+ var tr = [["Spearman correlation", res.test.spearman, "green above " + T.spearmanGreen + ", red below " + T.spearmanRed], ["Kolmogorov-Smirnov statistic", res.test.ks, "green below " + T.ksGreen + ", red above " + T.ksRed],
2864
+ ["Unexplained volatility ÷ HPL volatility", res.volRatio, ""], ["Mean unexplained ÷ HPL volatility", res.meanRatio, ""], ["Variance of unexplained ÷ variance of HPL", res.varRatio, ""]];
2865
+ res.path.forEach(function (p, i) { tr.push(["Path step " + (i + 1) + ": fix " + p.label + " → Spearman", p.test.spearman, self._zoneName(p.test.zone)], ["Path step " + (i + 1) + ": fix " + p.label + " → KS", p.test.ks, self._zoneName(p.test.zone)]); });
2866
+ sheets.push({ name: "Test", columns: [txt("Measure"), ratio("Value"), txt("Note")], rows: tr, text: tr.map(function (r) { return [r[0], r[1] == null ? "n/a" : r[1].toFixed(3), r[2]]; }) });
2867
+ var notes = (o.annotations || []).map(function (a, i) { return [String(i + 1), a.factor != null ? String(a.factor) : "Date: " + String(a.date || ""), a.text || ""]; });
2868
+ if (notes.length) sheets.push({ name: "Notes", columns: [txt("No."), txt("Factor or date"), txt("Note")], rows: notes });
2869
+ return {
2870
+ title: data.title || "P&L attribution", subtitle: data.subtitle || "", summary: this.describe(), library: "Veyforma P&L Attribution " + VERSION, sheets: sheets,
2871
+ meta: [["Unit", data.unit], ["As of", data.asOf], ["Desk", data.desk], ["Test window", res.window + " days (" + res.dates[res.start] + " to " + res.dates[res.dates.length - 1] + ")"],
2872
+ ["PLA test zone", self._zoneName(res.test.zone) + " (Spearman " + num2(res.test.spearman) + ", KS " + num2(res.test.ks) + ")"],
2873
+ ["Fixes applied", res.fixed.length ? res.fixed.join(", ") : null],
2874
+ ["Method", "Spearman = correlation of the ranks of daily HPL and RTPL (ties averaged); KS = largest gap between their empirical distribution functions; green if Spearman > " + T.spearmanGreen + " and KS < " + T.ksGreen + ", red if Spearman < " + T.spearmanRed + " or KS > " + T.ksRed + ", otherwise amber; factor share = cov(gap, unexplained) ÷ sd(unexplained), adds up to sd(unexplained); \"if fixed\" sets that factor's RTPL equal to its HPL" + (from > 0 ? "; daily sheet limited to the last " + cap + " days" : "")],
2875
+ ["Data source", data.source]]
2876
+ };
2877
+ };
2878
+ Chart.prototype._annotationPoint = function (a) {
2879
+ var p = this._points || {};
2880
+ if (a.factor != null) return p[String(a.factor)] || null;
2881
+ if (a.date != null) return p["date:" + String(a.date)] || null;
2882
+ return null;
2883
+ };
2884
+ Chart.prototype._annotationTarget = function (evt) {
2885
+ var items = this._items || [], it = null;
2886
+ if (!evt) it = items[this._active];
2887
+ else {
2888
+ var svg = this.plotHost.querySelector("svg"), r = svg.getBoundingClientRect(), vb = svg.viewBox.baseVal;
2889
+ var x = (evt.clientX - r.left) * (vb.width / r.width), y = (evt.clientY - r.top) * (vb.height / r.height);
2890
+ for (var i = 0; i < items.length; i++) { var q = items[i]; if (x >= q.x && x <= q.x + q.w && y >= q.y && y <= q.y + q.h) { it = q; break; } }
2891
+ }
2892
+ if (!it) return null;
2893
+ if (it.kind === "factor") return { factor: it.obj.key };
2894
+ if (it.kind === "day") return { date: this._res.dates[it.index] };
2895
+ return null;
2896
+ };
2897
+ Chart.prototype._annotationLabel = function (a) {
2898
+ if (a.date != null) return String(a.date);
2899
+ var x = (this._res || this.getResult()).factors.filter(function (q) { return q.key === String(a.factor); })[0];
2900
+ return x ? x.label : String(a.factor || "");
2901
+ };
2902
+
2903
+ /* ======================================================================
2904
+ 6. PUBLIC API
2905
+ ====================================================================== */
2906
+ root.VeyPlaAttribution = {
2907
+ version: VERSION,
2908
+ /** Draws the chart inside a container element or CSS selector. */
2909
+ create: function (target, options) { return new Chart(target, options); },
2910
+ /** Works out every figure without drawing. opts: { window, fix, thresholds, pathSteps }. */
2911
+ compute: function (data, opts) { return compute(data, opts); },
2912
+ /** The test on two series of daily P&L: { spearman, ks, zone }. */
2913
+ test: function (hpl, rtpl, thresholds) { return test(hpl, rtpl, assign({}, THRESHOLDS, thresholds || {})); },
2914
+ thresholds: THRESHOLDS,
2915
+ listThemes: function () { return Object.keys(THEMES); },
2916
+ getTheme: function (t) { return resolvePaTheme(t); },
2917
+ defaults: { options: DEFAULT_OPTIONS, labels: DEFAULT_LABELS, theme: BASE_THEME }
2918
+ };
2919
+ })(__vfRoot);
2920
+
2921
+ /*!
2922
+ * Veyforma Charts
2923
+ * One entry point for every chart in this package. Each chart is also available
2924
+ * on its own global (VeyHeatmap, VeyRiskTornado, VeyPlaAttribution).
2925
+ * Released under the MIT License. Copyright (c) 2026 Veyforma.
2926
+ * https://github.com/veyforma/veyforma-charts
2927
+ */
2928
+ (function (root) {
2929
+ "use strict";
2930
+
2931
+ function need(name) {
2932
+ var lib = root[name];
2933
+ if (!lib) throw new Error("VeyformaCharts: " + name + " is not loaded. Load its script before veyforma-charts.js, or use the bundled dist/veyforma-charts.js.");
2934
+ return lib;
2935
+ }
2936
+
2937
+ root.VeyformaCharts = {
2938
+ version: "1.0.2",
2939
+ /** Exposure heatmap: concentrations by any two fields, e.g. sector × country. */
2940
+ heatmap: function (target, options) { return need("VeyHeatmap").create(target, options); },
2941
+ /** Risk-factor tornado: down and up impact per factor, with convexity, limits and hedges. */
2942
+ tornado: function (target, options) { return need("VeyRiskTornado").create(target, options); },
2943
+ /** P&L attribution: HPL vs RTPL by factor, with the FRTB PLA test and the path to green. */
2944
+ plaAttribution: function (target, options) { return need("VeyPlaAttribution").create(target, options); }
2945
+ };
2946
+ })(__vfRoot);
2947
+
2948
+ export const VeyformaCharts = __vfRoot.VeyformaCharts;
2949
+ export const VeyHeatmap = __vfRoot.VeyHeatmap;
2950
+ export const VeyRiskTornado = __vfRoot.VeyRiskTornado;
2951
+ export const VeyPlaAttribution = __vfRoot.VeyPlaAttribution;
2952
+ export default __vfRoot.VeyformaCharts;