@bino-bi/bn-template-engine 1.0.0-next.35 → 1.0.0-next.36

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.
@@ -9,13 +9,13 @@ import { StringAdapter } from "../../../utils/helper/StringAdapter";
9
9
  import { IBCSRuleSet, stylesBySlot } from "../../../utils/ibcsRuleSet";
10
10
  import { DataFormatDigits, DataFormatDigitsAdapter } from "../../../utils/model/DataFormatDigits";
11
11
  import { OrderAdapter } from "../../../utils/model/Order";
12
- import { CellBarChart } from "../utils/elements/CellBarChart";
12
+ import { CellBarChart, formatValue, zeroOnPositiveSide, } from "../utils/elements/CellBarChart";
13
13
  import { WaterfallBar } from "../utils/elements/WaterfallBar";
14
14
  import withComponentStatus from "../../../utils/withComponentStatus";
15
15
  import withComponentStyle from "../../../utils/withComponentStyle";
16
16
  import { getStores } from "../../../context/context-protocol";
17
17
  import { sourceExpr } from "../../../context/scopedDb";
18
- import { absoluteBarGeometry, BAR_LABEL_FONT_RATIO, relativePinGeometry } from "../utils/helper/barColumnGeometry";
18
+ import { absoluteBarGeometry, BAR_LABEL_FONT_RATIO, estimateLabelWidth, PIN_HEAD_SIZE, pinLabelsFit, relativePinGeometry, } from "../utils/helper/barColumnGeometry";
19
19
  import { NOT_AVAILABLE } from "../../../utils/relativeVariance";
20
20
  import { normalizeFillPattern } from "../../../utils/model/styles/SVGStyle";
21
21
  /**
@@ -108,6 +108,7 @@ export class BnTableRenderer {
108
108
  /** @internal */
109
109
  this.scaleFactor = 1;
110
110
  this.componentDataFormatDigits = new DataFormatDigits();
111
+ this.barColumnLayouts = new Map();
111
112
  withComponentStatus(this);
112
113
  this.componentStyle = withComponentStyle(this);
113
114
  }
@@ -228,14 +229,15 @@ export class BnTableRenderer {
228
229
  return h("div", { class: "empty-state" }, errorMsg);
229
230
  }
230
231
  const locale = (_d = (_c = (_b = this.stores) === null || _b === void 0 ? void 0 : _b.context) === null || _c === void 0 ? void 0 : _c.state) === null || _d === void 0 ? void 0 : _d.locale;
231
- return (h("table", null, h("thead", null, this.table.getHeader().map((row) => (h("tr", { class: row.cssStyle }, row.getCells().map((cell) => (h("th", { colSpan: cell.colSpan, class: cell.cssStyle }, cell.getAsHeaderList().map((line, i, arr) => (h("span", null, i === arr.length - 1 ? (h("span", { class: line === " " ? "table-footer" : "" }, line, cell.drawPrefix(), " ")) : (h("span", null, line, cell.drawPrefix(), h("br", null))))))))))))), h("tbody", null, this.table.getBody().map((row) => (h("tr", Object.assign({ class: row.cssStyle }, dataPointAttributes(row.key, "element")), row === null || row === void 0 ? void 0 : row.getCells().map((cell) => (h("td", Object.assign({ colSpan: cell.colSpan, class: cell.type ? `${cell.cssStyle} ${cell.type}` : cell.cssStyle }, (row.key && cell.value != null && cell.value !== "" && cell.value !== "-"
232
- ? dataPointAttributes(Object.assign(Object.assign({}, row.key), { date: cell.date, scenario: cell.key }), "element")
233
- : {})), cell.prefix != null ? (h("span", { class: cell.cssStyle + " " + cell.prefixStyle }, cell.drawPrefix())) : (""), cell.isBarChart &&
234
- cell.columnStats &&
235
- cell.value !== NOT_AVAILABLE &&
236
- (cell.waterfall !== undefined || row.type !== TableRowType.SUM) ? (cell.waterfall !== undefined ? (h(WaterfallBar, { value: cell.value, scenario: cell.key, columnStats: cell.columnStats, height: 18 * this.scaleFactor, isRelative: false, isPositiveGood: cell.direction === "pos", measureScale: cell.measureScale, locale: locale, columnWidthEm: this.barColumnMaxWidth, styles: this.barChartStyles, waterfall: cell.waterfall })) : (h(CellBarChart, { value: cell.value, scenario: cell.key, columnStats: cell.columnStats, height: 18 * this.scaleFactor, isRelative: cell.key.startsWith("dr"), isPositiveGood: cell.direction === "pos",
237
- // percentage points: the fraction times 100, no measure scale
238
- measureScale: cell.type === "percentpoint" ? 0.01 : cell.measureScale, locale: locale, percentDigits: this.componentDataFormatDigits.percent, columnWidthEm: this.barColumnMaxWidth, styles: this.barChartStyles }))) : (cell.draw(this.componentDataFormatDigits, locale)))))))))));
232
+ return (h("table", null, h("thead", null, this.table.getHeader().map((row) => (h("tr", { class: row.cssStyle }, row.getCells().map((cell) => (h("th", { colSpan: cell.colSpan, class: cell.cssStyle }, cell.getAsHeaderList().map((line, i, arr) => (h("span", null, i === arr.length - 1 ? (h("span", { class: line === " " ? "table-footer" : "" }, line, cell.drawPrefix(), " ")) : (h("span", null, line, cell.drawPrefix(), h("br", null))))))))))))), h("tbody", null, this.table.getBody().map((row) => (h("tr", Object.assign({ class: row.cssStyle }, dataPointAttributes(row.key, "element")), row === null || row === void 0 ? void 0 : row.getCells().map((cell) => {
233
+ var _a, _b, _c, _d;
234
+ return (h("td", Object.assign({ colSpan: cell.colSpan, class: cell.type ? `${cell.cssStyle} ${cell.type}` : cell.cssStyle }, (row.key && cell.value != null && cell.value !== "" && cell.value !== "-"
235
+ ? dataPointAttributes(Object.assign(Object.assign({}, row.key), { date: cell.date, scenario: cell.key }), "element")
236
+ : {})), cell.prefix != null ? (h("span", { class: cell.cssStyle + " " + cell.prefixStyle }, cell.drawPrefix())) : (""), cell.isBarChart &&
237
+ cell.columnStats &&
238
+ cell.value !== NOT_AVAILABLE &&
239
+ (cell.waterfall !== undefined || row.type !== TableRowType.SUM) ? (cell.waterfall !== undefined ? (h(WaterfallBar, { value: cell.value, scenario: cell.key, columnStats: cell.columnStats, height: 18 * this.scaleFactor, isRelative: false, isPositiveGood: cell.direction === "pos", measureScale: cell.measureScale, locale: locale, columnWidthEm: this.barColumnMaxWidth, styles: this.barChartStyles, waterfall: cell.waterfall })) : (h(CellBarChart, { value: cell.value, scenario: cell.key, columnStats: cell.columnStats, height: 18 * this.scaleFactor, isRelative: cell.key.startsWith("dr"), isPositiveGood: cell.direction === "pos", measureScale: barLabelMeasureScale(cell), locale: locale, percentDigits: (_b = (_a = this.barColumnLayouts.get(cell.key)) === null || _a === void 0 ? void 0 : _a.percentDigits) !== null && _b !== void 0 ? _b : this.componentDataFormatDigits.percent, percentSign: (_c = this.barColumnLayouts.get(cell.key)) === null || _c === void 0 ? void 0 : _c.percentSign, columnWidthEm: this.barColumnMaxWidth, labelWidths: (_d = this.barColumnLayouts.get(cell.key)) === null || _d === void 0 ? void 0 : _d.labels, styles: this.barChartStyles }))) : (cell.draw(this.componentDataFormatDigits, locale))));
240
+ })))))));
239
241
  };
240
242
  return h(Host, { class: { "no-data": ((_a = this.table) === null || _a === void 0 ? void 0 : _a.hasNoData()) === true } }, helper());
241
243
  }
@@ -280,6 +282,7 @@ export class BnTableRenderer {
280
282
  else {
281
283
  (_h = this.errors) === null || _h === void 0 ? void 0 : _h.remove("WARN_orderBucket");
282
284
  }
285
+ this.barColumnLayouts = this.collectBarColumnLayouts();
283
286
  this.barChartStyles = this.prepareBarChartStyles();
284
287
  }
285
288
  prepareConfig(db) {
@@ -402,64 +405,99 @@ export class BnTableRenderer {
402
405
  /**
403
406
  * Auto-calculate unitScaling so the largest absolute variance bar
404
407
  * fills ~80% of its side of the bar area, without tripping the overdrive break.
408
+ * One scaling for all columns, so it is the smallest that fits every column.
405
409
  */
406
410
  autoUnitScaling() {
407
411
  const emPx = this.emPx();
408
412
  const fs = emPx * BAR_LABEL_FONT_RATIO;
409
- const { absMax, hasNeg, hasPos } = this.getAbsBarColumnStats();
410
- if (absMax <= 0 || fs <= 0) {
411
- return 0.01;
413
+ let scaling = Infinity;
414
+ for (const { isRelative, absMax, labels } of this.barColumnLayouts.values()) {
415
+ if (isRelative || absMax <= 0)
416
+ continue;
417
+ const { maxBarWidth, cutWidth } = absoluteBarGeometry(this.barColumnMaxWidth, emPx, labels);
418
+ scaling = Math.min(scaling, Math.min(maxBarWidth * 0.8, cutWidth) / (absMax * fs));
412
419
  }
413
- const { maxBarWidth, cutWidth } = absoluteBarGeometry(this.barColumnMaxWidth, emPx, hasNeg, hasPos);
414
- const targetWidth = Math.min(maxBarWidth * 0.8, cutWidth);
415
- return targetWidth / (absMax * fs);
420
+ return Number.isFinite(scaling) && fs > 0 ? scaling : 0.01;
416
421
  }
417
422
  /**
418
- * Auto-calculate percentageScaling so the largest relative variance pin
419
- * fills ~80% of the pin area.
423
+ * Auto-calculate percentageScaling so the longest relative variance pin, its head and
424
+ * its label exactly fill the column. One scaling for all columns, the smallest that fits.
420
425
  */
421
426
  autoPercentageScaling() {
422
427
  const emPx = this.emPx();
423
428
  const fs = emPx * BAR_LABEL_FONT_RATIO;
424
- const { absMax: maxPct, hasNeg, hasPos } = this.getRelativeBarColumnStats();
425
- if (maxPct <= 0 || fs <= 0) {
426
- return 0.5;
429
+ let scaling = Infinity;
430
+ for (const { isRelative, absMax, labels } of this.barColumnLayouts.values()) {
431
+ if (!isRelative || absMax <= 0)
432
+ continue;
433
+ const headSize = PIN_HEAD_SIZE * this.scaleFactor;
434
+ const { maxPinLength } = relativePinGeometry(this.barColumnMaxWidth, emPx, labels, headSize);
435
+ scaling = Math.min(scaling, maxPinLength / (absMax * fs));
427
436
  }
428
- const { maxPinLength } = relativePinGeometry(this.barColumnMaxWidth, emPx, hasNeg, hasPos);
429
- return (maxPinLength * 0.8) / (maxPct * fs);
437
+ return Number.isFinite(scaling) && fs > 0 ? scaling : 0.5;
430
438
  }
431
439
  /**
432
- * Maximum value and sign coverage across all absolute variance columns (d_*) in the table body.
433
- * Sign coverage decides how much of the column the bar area gets (see barColumnGeometry.ts);
434
- * OR-ing it across columns keeps the single shared scaling inside the narrowest bar area.
440
+ * Largest value and widest label per side of every bar and pin column, from the cells
441
+ * that draw one: total rows and n/a draw none. Interval buckets share the column key,
442
+ * so they share the layout and the axis.
435
443
  */
436
- getAbsBarColumnStats() {
437
- // waterfall cells scale independently and must not skew variance auto-scaling
438
- return this.collectBarColumnStats((cell) => !cell.key.startsWith("dr") && !cell.waterfall, 1);
439
- }
440
- /**
441
- * Same for the relative variance columns (dr_*). Values are stored as decimals
442
- * (e.g. 0.2 = 20%), returned as percentage (20).
443
- */
444
- getRelativeBarColumnStats() {
445
- return this.collectBarColumnStats((cell) => cell.key.startsWith("dr"), 100);
446
- }
447
- collectBarColumnStats(accept, valueFactor) {
448
- const stats = { absMax: 0, hasNeg: false, hasPos: false };
449
- if (!this.table)
450
- return stats;
444
+ collectBarColumnLayouts() {
445
+ var _a, _b, _c, _d;
446
+ const layouts = new Map();
447
+ if (!this.table || this.table.hasNoData())
448
+ return layouts;
449
+ const cellsByKey = new Map();
451
450
  for (const row of this.table.getBody()) {
452
451
  if (row.type === TableRowType.SUM)
453
452
  continue;
454
453
  for (const cell of row.getCells()) {
455
- if (!cell.isBarChart || !cell.columnStats || !accept(cell))
454
+ // waterfall cells scale independently
455
+ if (!cell.isBarChart || !cell.columnStats || cell.waterfall !== undefined)
456
+ continue;
457
+ if (typeof cell.value !== "number" || isNaN(cell.value))
456
458
  continue;
457
- stats.absMax = Math.max(stats.absMax, cell.columnStats.absMax * valueFactor);
458
- stats.hasNeg = stats.hasNeg || cell.columnStats.min < 0;
459
- stats.hasPos = stats.hasPos || cell.columnStats.max > 0;
459
+ cellsByKey.set(cell.key, [...((_a = cellsByKey.get(cell.key)) !== null && _a !== void 0 ? _a : []), cell]);
460
460
  }
461
461
  }
462
- return stats;
462
+ const emPx = this.emPx();
463
+ const fs = emPx * BAR_LABEL_FONT_RATIO;
464
+ const headSize = PIN_HEAD_SIZE * this.scaleFactor;
465
+ const locale = (_d = (_c = (_b = this.stores) === null || _b === void 0 ? void 0 : _b.context) === null || _c === void 0 ? void 0 : _c.state) === null || _d === void 0 ? void 0 : _d.locale;
466
+ for (const [key, cells] of cellsByKey) {
467
+ const isRelative = key.startsWith("dr");
468
+ const values = cells.map((cell) => cell.value);
469
+ const measure = (percentDigits, percentSign) => {
470
+ var _a;
471
+ const labels = {
472
+ neg: values.some((value) => value < 0) ? 0 : undefined,
473
+ pos: values.some((value) => value > 0) ? 0 : undefined,
474
+ };
475
+ const zeroPositive = zeroOnPositiveSide(labels);
476
+ for (const cell of cells) {
477
+ const value = cell.value;
478
+ const side = value > 0 || (value === 0 && zeroPositive) ? "pos" : "neg";
479
+ const text = formatValue(value, isRelative, barLabelMeasureScale(cell), locale, percentDigits, percentSign);
480
+ labels[side] = Math.max((_a = labels[side]) !== null && _a !== void 0 ? _a : 0, estimateLabelWidth(text, fs));
481
+ }
482
+ return labels;
483
+ };
484
+ // a narrow pin column drops percent digits, then the %, so every label keeps its sign
485
+ let percentDigits = Math.min(20, Math.max(0, Math.trunc(this.componentDataFormatDigits.percent) || 0));
486
+ let percentSign = true;
487
+ let labels = measure(percentDigits, percentSign);
488
+ while (isRelative && (percentDigits > 0 || percentSign)) {
489
+ if (pinLabelsFit(this.barColumnMaxWidth, emPx, labels, headSize))
490
+ break;
491
+ if (percentDigits > 0)
492
+ percentDigits--;
493
+ else
494
+ percentSign = false;
495
+ labels = measure(percentDigits, percentSign);
496
+ }
497
+ const absMax = Math.max(...values.map(Math.abs)) * (isRelative ? 100 : 1);
498
+ layouts.set(key, { isRelative, absMax, labels, percentDigits, percentSign });
499
+ }
500
+ return layouts;
463
501
  }
464
502
  static get is() { return "bn-table-renderer"; }
465
503
  static get encapsulation() { return "shadow"; }
@@ -1388,3 +1426,7 @@ export class BnTableRenderer {
1388
1426
  }
1389
1427
  static get elementRef() { return "element"; }
1390
1428
  }
1429
+ /** Percentage points: the fraction times 100, no measure scale. */
1430
+ function barLabelMeasureScale(cell) {
1431
+ return cell.type === "percentpoint" ? 0.01 : cell.measureScale;
1432
+ }
@@ -1,7 +1,7 @@
1
1
  import { h } from "@stencil/core";
2
2
  import { Formatter } from "../../../../utils";
3
3
  import { VarianceScenario } from "../../../../utils/model/VarianceScenario";
4
- import { absoluteBarGeometry, BAR_LABEL_FONT_RATIO, relativePinGeometry } from "../helper/barColumnGeometry";
4
+ import { absoluteBarGeometry, BAR_LABEL_FONT_RATIO, estimateLabelWidth, PIN_HEAD_SIZE, relativePinGeometry, VARIANCE_AXIS_EM, } from "../helper/barColumnGeometry";
5
5
  /** Matches SYSTEM_STYLE_DEFAULTS.global.fontSizePx; only used when `styles` is omitted. */
6
6
  const DEFAULT_EM_PX = 13.3333;
7
7
  // Default fallback colors (should come from componentStyle)
@@ -24,13 +24,8 @@ export const DEFAULT_STYLES = {
24
24
  scaleFactor: 1,
25
25
  };
26
26
  export const AXIS_COLOR = "#666666";
27
- /** Width of the axis of a variance bar or pin, in em: near the 0.3em scenario marker in the header. */
28
- const VARIANCE_AXIS_EM = 0.25;
29
- /** Side of the square pin head and width of the pin line, in px before scaleFactor. */
30
- const PIN_HEAD_SIZE = 10;
27
+ /** Width of the pin line, in px before scaleFactor. */
31
28
  const PIN_LINE_WIDTH = 3;
32
- /** Rough average glyph width, in label font sizes, to tell if an outlier label fits inside its pin. */
33
- const LABEL_CHAR_WIDTH = 0.6;
34
29
  /**
35
30
  * Creates a unique pattern ID for the SVG defs
36
31
  */
@@ -55,16 +50,20 @@ export const PatternDefs = ({ styles }) => {
55
50
  ];
56
51
  return (h("defs", null, patterns.map((p) => (h("pattern", { id: p.id, patternUnits: "userSpaceOnUse", width: patternSize, height: patternSize }, h("rect", { width: patternSize, height: patternSize, fill: "#ffffff" }), h("line", { x1: "0", y1: patternSize, x2: patternSize, y2: "0", stroke: p.stroke, "stroke-width": 1.5 * s }))))));
57
52
  };
58
- /** Characters that fit the pin label gutter (PIN_LABEL_EM), the cell cuts off the rest. */
53
+ /** Longest relative label that keeps all percent digits; a longer one drops digits so its gutter does not eat the pins. */
59
54
  const PIN_LABEL_CHARS = 7;
60
55
  /**
61
56
  * Formats a number for display with appropriate SI prefix.
62
57
  */
63
- export function formatValue(value, isRelative, measureScale = 1, locale, percentDigits = 0) {
64
- const prefix = value >= 0 ? "+" : "";
58
+ export function formatValue(value, isRelative, measureScale = 1, locale, percentDigits = 0, percentSign = true) {
59
+ // IBCS prints a value that rounds to zero without a sign
60
+ const signed = (text, zero) => (value > 0 && text !== zero ? "+" : "") + text;
65
61
  if (isRelative) {
66
62
  // Relative variance is stored as decimal (e.g., -2.0 = -200%)
67
- const format = (digits) => prefix + Formatter.number(value, "percent", digits, digits, 1, locale);
63
+ const number = (v, digits) => percentSign
64
+ ? Formatter.number(v, "percent", digits, digits, 1, locale)
65
+ : Formatter.number(v * 100, "decimal", digits, digits, 1, locale);
66
+ const format = (digits) => signed(number(value, digits), number(0, digits));
68
67
  // Intl throws on a digit count outside 0 to 20
69
68
  let digits = Math.min(20, Math.max(0, Math.trunc(percentDigits) || 0));
70
69
  while (digits > 0 && format(digits).length > PIN_LABEL_CHARS) {
@@ -91,7 +90,7 @@ export function formatValue(value, isRelative, measureScale = 1, locale, percent
91
90
  suffix = "K";
92
91
  }
93
92
  const digits = absValue >= unit * 10 ? 0 : 1;
94
- return prefix + Formatter.number(scaledValue / unit, "decimal", digits, 0, 1, locale) + suffix;
93
+ return (signed(Formatter.number(scaledValue / unit, "decimal", digits, 0, 1, locale), Formatter.number(0, "decimal", digits, 0, 1, locale)) + suffix);
95
94
  }
96
95
  /**
97
96
  * Checks if the column is a scenario column (ac, pp, fc, pl) vs variance (d_, dr_).
@@ -157,6 +156,17 @@ const VarianceAxis = ({ x, height, look, styles }) => {
157
156
  }
158
157
  return h("g", { class: `variance-axis axis-${referenceSlot}` }, lines);
159
158
  };
159
+ /** A zero value is drawn on the positive side, unless the column only has negative values. */
160
+ export function zeroOnPositiveSide(labels) {
161
+ return labels.pos !== undefined || labels.neg === undefined;
162
+ }
163
+ /** Side coverage from the column statistics, with only this cell's label as the width. */
164
+ function ownLabelWidths(columnStats, width) {
165
+ return {
166
+ neg: columnStats.min < 0 ? width : undefined,
167
+ pos: columnStats.max > 0 ? width : undefined,
168
+ };
169
+ }
160
170
  /**
161
171
  * Gets the variance style based on value and sentiment direction.
162
172
  * pos suffix = positive values are good (green), negative are bad (red)
@@ -245,13 +255,12 @@ function renderZigzagBreak(breakX, breakGap, yTop, barHeight, s) {
245
255
  * exactly `columnWidthEm` em - see barColumnGeometry.ts.
246
256
  */
247
257
  const AbsoluteVarianceBar = (props) => {
248
- const { value, scenario, columnStats, height, isPositiveGood, formattedValue, measureScale, locale, columnWidthEm = 10, styles = DEFAULT_STYLES, } = props;
258
+ const { value, scenario, columnStats, height, isPositiveGood, formattedValue, measureScale, locale, columnWidthEm = 10, labelWidths, styles = DEFAULT_STYLES, } = props;
249
259
  const s = styles.scaleFactor;
250
260
  const fs = styles.fontSize;
251
- // Adaptive axis placement based on data range
252
- const hasNeg = columnStats.min < 0;
253
- const hasPos = columnStats.max > 0;
254
- const { totalWidth, axisX, breakGap, overdriveZoneWidth, cutWidth, labelGap } = absoluteBarGeometry(columnWidthEm, styles.emPx, hasNeg, hasPos);
261
+ const displayValue = formattedValue || formatValue(value, false, measureScale, locale);
262
+ const sides = labelWidths !== null && labelWidths !== void 0 ? labelWidths : ownLabelWidths(columnStats, estimateLabelWidth(displayValue, fs));
263
+ const { totalWidth, axisX, breakGap, overdriveZoneWidth, cutWidth, labelGap } = absoluteBarGeometry(columnWidthEm, styles.emPx, sides);
255
264
  // Direct unit scaling via fontSize
256
265
  const scaledWidth = Math.abs(value) * styles.unitScaling * fs;
257
266
  // auto scaling puts the largest bar on the cut, float rounding must not turn it into an overdrive bar
@@ -264,7 +273,7 @@ const AbsoluteVarianceBar = (props) => {
264
273
  const padding = 2 * s;
265
274
  const barHeight = height - padding * 2;
266
275
  const barY = padding;
267
- const isPositive = value >= 0;
276
+ const isPositive = value > 0 || (value === 0 && zeroOnPositiveSide(sides));
268
277
  // Get style based on column type (scenario vs variance)
269
278
  const look = getVarianceLook(scenario, styles);
270
279
  const sentimentStyle = getBarStyle(scenario, value, isPositiveGood, styles);
@@ -284,7 +293,6 @@ const AbsoluteVarianceBar = (props) => {
284
293
  const fillValue = getBarFill(barStyle, patternPrefix);
285
294
  // a hatched variance bar keeps an outline, the shared getBarStroke also serves the waterfall
286
295
  const { stroke: barStroke, strokeWidth: barStrokeWidth } = look && barStyle.fillpattern === "hatched" ? { stroke: barStyle.stroke, strokeWidth: 1 } : getBarStroke(barStyle);
287
- const displayValue = formattedValue || formatValue(value, false, measureScale, locale);
288
296
  // bars start at the outer edge of the thick variance axis
289
297
  const axisOffset = look ? (VARIANCE_AXIS_EM * styles.emPx) / 2 : 0;
290
298
  const rootX = isPositive ? axisX + axisOffset : axisX - axisOffset;
@@ -301,7 +309,7 @@ const AbsoluteVarianceBar = (props) => {
301
309
  * Renders a relative variance pin chart (dr_ prefix).
302
310
  * Line from the axis in the sentiment colour, ending in a square head in the look of the
303
311
  * minuend, with the value label beside the head like an absolute bar label. A pin beyond
304
- * the pin area is cut and ends in an arrow, its label inside the pin before the arrow.
312
+ * the pin area is cut and ends in an arrow, its label after the arrow tip.
305
313
  *
306
314
  * Layout: [left label area][pin area with axis][right label area], summing to exactly
307
315
  * `columnWidthEm` em - see barColumnGeometry.ts.
@@ -309,40 +317,32 @@ const AbsoluteVarianceBar = (props) => {
309
317
  */
310
318
  const RelativeVariancePin = (props) => {
311
319
  var _a, _b;
312
- const { value, scenario, columnStats, height, isPositiveGood, formattedValue, measureScale, locale, percentDigits, columnWidthEm = 10, styles = DEFAULT_STYLES, } = props;
320
+ const { value, scenario, columnStats, height, isPositiveGood, formattedValue, measureScale, locale, percentDigits, percentSign, columnWidthEm = 10, labelWidths, styles = DEFAULT_STYLES, } = props;
313
321
  const s = styles.scaleFactor;
314
322
  const fs = styles.fontSize;
315
- // Adaptive axis placement based on data range
316
- const hasNeg = columnStats.min < 0;
317
- const hasPos = columnStats.max > 0;
318
- const { totalWidth, maxPinLength, axisX, labelGap } = relativePinGeometry(columnWidthEm, styles.emPx, hasNeg, hasPos);
323
+ const headSize = PIN_HEAD_SIZE * s;
324
+ const displayValue = formattedValue || formatValue(value, true, measureScale, locale, percentDigits, percentSign);
325
+ const sides = labelWidths !== null && labelWidths !== void 0 ? labelWidths : ownLabelWidths(columnStats, estimateLabelWidth(displayValue, fs));
326
+ const { totalWidth, maxPinLength, axisX, labelGap } = relativePinGeometry(columnWidthEm, styles.emPx, sides, headSize);
319
327
  const centerY = height / 2;
320
328
  // Direct unit scaling via fontSize
321
329
  const percentValue = Math.abs(value) * 100;
322
330
  const scaledLength = percentValue * styles.percentageScaling * fs;
323
- const isExtreme = scaledLength > maxPinLength;
331
+ // auto scaling puts the longest pin on the limit, float rounding must not cut it
332
+ const isExtreme = scaledLength - maxPinLength > 1e-6;
324
333
  const pinLength = Math.min(scaledLength, maxPinLength);
325
- // a zero label goes to the side that has a label gutter
326
- const isPositive = value > 0 || (value === 0 && (hasPos || !hasNeg));
334
+ const isPositive = value > 0 || (value === 0 && zeroOnPositiveSide(sides));
327
335
  const direction = isPositive ? 1 : -1;
328
336
  const pinEndX = axisX + direction * pinLength;
329
337
  // Get style based on column type (scenario vs variance)
330
338
  const barStyle = getBarStyle(scenario, value, isPositiveGood, styles);
331
339
  const look = getVarianceLook(scenario, styles);
332
340
  const headStyle = (_a = look === null || look === void 0 ? void 0 : look.minuend) !== null && _a !== void 0 ? _a : styles.scenarios.ac;
333
- const headSize = PIN_HEAD_SIZE * s;
334
- const displayValue = formattedValue || formatValue(value, true, measureScale, locale, percentDigits);
335
- // the arrow tip lands on the outer edge of a full-length head
341
+ // the arrow tip lands on the outer edge of a full-length head, so the label after it stays in the cell
336
342
  const tipX = axisX + direction * (maxPinLength + headSize / 2);
337
343
  const arrowBaseX = tipX - direction * headSize;
338
- const labelFitsInside = maxPinLength - headSize / 2 - labelGap >= displayValue.length * LABEL_CHAR_WIDTH * fs;
339
- const labelInside = isExtreme && labelFitsInside;
340
- let labelX = pinEndX + direction * (headSize / 2 + labelGap);
341
- if (isExtreme) {
342
- labelX = labelInside ? arrowBaseX - direction * labelGap : tipX + direction * labelGap;
343
- }
344
- const labelAtStart = isPositive !== labelInside;
345
- return (h("svg", { width: totalWidth, height: height, class: "cell-bar-chart relative-variance", style: { overflow: "visible" } }, h(PatternDefs, { styles: styles }), look ? (h(VarianceAxis, { x: axisX, height: height, look: look, styles: styles })) : (h("line", { x1: axisX, y1: 0, x2: axisX, y2: height, stroke: AXIS_COLOR, "stroke-width": 1 * s })), h("line", { x1: axisX, y1: centerY, x2: isExtreme ? arrowBaseX : pinEndX, y2: centerY, stroke: barStyle.fill, "stroke-width": PIN_LINE_WIDTH * s }), isExtreme ? (h("polygon", { points: `${tipX},${centerY} ${arrowBaseX},${centerY - headSize / 2} ${arrowBaseX},${centerY + headSize / 2}`, fill: barStyle.fill })) : (h("rect", { x: pinEndX - headSize / 2, y: centerY - headSize / 2, width: headSize, height: headSize, fill: headStyle.fillpattern === "outlined" ? "#ffffff" : getBarFill(headStyle, (_b = look === null || look === void 0 ? void 0 : look.minuendSlot) !== null && _b !== void 0 ? _b : "ac"), stroke: headStyle.stroke, "stroke-width": 1 * s })), h("text", Object.assign({ x: labelX, y: height / 2, dy: "0.35em", "text-anchor": labelAtStart ? "start" : "end", fill: styles.fontColor, "font-size": fs, "font-style": "italic", "font-family": styles.fontFamily }, (labelInside ? { stroke: "#ffffff", "stroke-width": 3 * s, "paint-order": "stroke" } : {})), displayValue)));
344
+ const labelX = (isExtreme ? tipX : pinEndX + direction * (headSize / 2)) + direction * labelGap;
345
+ return (h("svg", { width: totalWidth, height: height, class: "cell-bar-chart relative-variance", style: { overflow: "visible" } }, h(PatternDefs, { styles: styles }), look ? (h(VarianceAxis, { x: axisX, height: height, look: look, styles: styles })) : (h("line", { x1: axisX, y1: 0, x2: axisX, y2: height, stroke: AXIS_COLOR, "stroke-width": 1 * s })), h("line", { x1: axisX, y1: centerY, x2: isExtreme ? arrowBaseX : pinEndX, y2: centerY, stroke: barStyle.fill, "stroke-width": PIN_LINE_WIDTH * s }), isExtreme ? (h("polygon", { points: `${tipX},${centerY} ${arrowBaseX},${centerY - headSize / 2} ${arrowBaseX},${centerY + headSize / 2}`, fill: barStyle.fill })) : (h("rect", { x: pinEndX - headSize / 2, y: centerY - headSize / 2, width: headSize, height: headSize, fill: headStyle.fillpattern === "outlined" ? "#ffffff" : getBarFill(headStyle, (_b = look === null || look === void 0 ? void 0 : look.minuendSlot) !== null && _b !== void 0 ? _b : "ac"), stroke: headStyle.stroke, "stroke-width": 1 * s })), h("text", { x: labelX, y: height / 2, dy: "0.35em", "text-anchor": isPositive ? "start" : "end", fill: styles.fontColor, "font-size": fs, "font-style": "italic", "font-family": styles.fontFamily }, displayValue)));
346
346
  };
347
347
  /**
348
348
  * CellBarChart - Renders IBCS-compliant variance bar charts.
@@ -22,60 +22,103 @@ export const BAR_LABEL_FONT_RATIO = 0.85;
22
22
  * `.category-wN` (bn-table-renderer.scss:50-83) produces.
23
23
  */
24
24
  const BAR_CELL_PADDING_EM = 0.5;
25
- /** Value-label gutter beside a bar, in em (was a hardcoded 38 px at the 13.3333 px em). */
25
+ /** Value-label gutter beside a waterfall bar, in em (was a hardcoded 38 px at the 13.3333 px em). */
26
26
  const BAR_LABEL_EM = 2.85;
27
- /** Value-label gutter beside a pin, in em (was 45 px). */
28
- const PIN_LABEL_EM = 3.375;
29
- /** Gap between the axis and the start of a pin's reserved side, in em (was 5 px). */
30
- const PIN_PADDING_EM = 0.375;
31
27
  /** Zigzag break gap of an overdrive bar, in em (was 4 px). */
32
28
  const BREAK_GAP_EM = 0.3;
33
29
  /** Gap between a bar/pin end and its value label, in em (was 4 px). */
34
30
  const LABEL_GAP_EM = 0.3;
31
+ /** Pin extent per side kept before a pin column drops label digits, in em. */
32
+ const MIN_EXTENT_EM = 1;
35
33
  /** Share of the per-side bar extent reserved for the overdrive stub. */
36
34
  const OVERDRIVE_FRACTION = 0.15;
35
+ /** Width of the axis of a variance bar or pin, in em: near the 0.3em scenario marker in the header. */
36
+ export const VARIANCE_AXIS_EM = 0.25;
37
+ /** Side of the square pin head, in px before scaleFactor. */
38
+ export const PIN_HEAD_SIZE = 10;
39
+ /**
40
+ * Advance widths in em, the larger of Noto Sans and Arial. The engine ships no font, so a
41
+ * wider fallback (DejaVu Sans, Verdana) is possible: LABEL_WIDTH_MARGIN and the cell
42
+ * padding cover it. Any glyph not listed counts as a wide letter.
43
+ */
44
+ const GLYPH_EM = {
45
+ ".": 0.28,
46
+ ",": 0.28,
47
+ "-": 0.34,
48
+ "%": 0.89,
49
+ " ": 0.28,
50
+ "\u00a0": 0.28,
51
+ "\u202f": 0.28,
52
+ M: 0.9,
53
+ };
54
+ const DIGIT_EM = 0.59;
55
+ const OTHER_EM = 0.72;
56
+ /** Labels fill the cell to the edge, so the estimate keeps room for a wider fallback font. */
57
+ const LABEL_WIDTH_MARGIN = 1.1;
58
+ /** Estimated rendered width of a value label in px, with a margin for wider fonts. */
59
+ export function estimateLabelWidth(text, fontSize) {
60
+ var _a;
61
+ let em = 0;
62
+ for (const char of text) {
63
+ em += (_a = GLYPH_EM[char]) !== null && _a !== void 0 ? _a : (/[0-9+]/.test(char) ? DIGIT_EM : OTHER_EM);
64
+ }
65
+ return em * fontSize * LABEL_WIDTH_MARGIN;
66
+ }
37
67
  /** The SVG fills the cell's content box: the requested column width minus the cell padding. */
38
68
  function contentWidth(widthEm, emPx) {
39
69
  return Math.max(0, (widthEm - BAR_CELL_PADDING_EM) * emPx);
40
70
  }
41
- /** Sides the axis serves. Clamped to 1 so a hypothetical all-zero column never divides by 0. */
42
- function sideCount(hasNeg, hasPos) {
43
- return Math.max(1, (hasNeg ? 1 : 0) + (hasPos ? 1 : 0));
71
+ /** `outerReserve` covers what sticks out beyond the bar or pin end, e.g. the half head. */
72
+ function sideNeeds(labels, outerReserve, labelGap) {
73
+ const hasNeg = labels.neg !== undefined;
74
+ const hasPos = labels.pos !== undefined || !hasNeg;
75
+ const need = (has, width) => (has ? outerReserve + labelGap + (width !== null && width !== void 0 ? width : 0) : 0);
76
+ return { sides: (hasNeg ? 1 : 0) + (hasPos ? 1 : 0), neg: need(hasNeg, labels.neg), pos: need(hasPos, labels.pos) };
77
+ }
78
+ /** Bar or pin extent per side that a column keeps as long as its labels allow. */
79
+ function minExtent(totalWidth, emPx, sides) {
80
+ return Math.min(MIN_EXTENT_EM * emPx, totalWidth / (2 * sides));
81
+ }
82
+ /**
83
+ * Reserves per side only what its widest label needs and gives the rest to the bars or
84
+ * pins. A column too narrow for that shortens the bars or pins first, down to zero, so a
85
+ * label keeps its sign. Only a column narrower than its labels alone shrinks the
86
+ * reserves, and then the labels overflow. wN stays wN in every case.
87
+ */
88
+ function splitSides(totalWidth, labels, outerReserve, labelGap) {
89
+ const { sides, neg, pos } = sideNeeds(labels, outerReserve, labelGap);
90
+ const shrink = neg + pos > 0 ? Math.min(1, totalWidth / (neg + pos)) : 1;
91
+ const extent = Math.max(0, (totalWidth - (neg + pos) * shrink) / sides);
92
+ return { extent, axisX: labels.neg !== undefined ? neg * shrink + extent : 0 };
93
+ }
94
+ /** True when the labels fit beside pins of at least the minimum extent; else the caller drops digits. */
95
+ export function pinLabelsFit(widthEm, emPx, labels, headSize) {
96
+ const totalWidth = contentWidth(widthEm, emPx);
97
+ const { sides, neg, pos } = sideNeeds(labels, headSize / 2, LABEL_GAP_EM * emPx);
98
+ return neg + pos + sides * minExtent(totalWidth, emPx, sides) <= totalWidth + 1e-6;
44
99
  }
45
- export function absoluteBarGeometry(widthEm, emPx, hasNeg, hasPos) {
100
+ export function absoluteBarGeometry(widthEm, emPx, labels) {
46
101
  const totalWidth = contentWidth(widthEm, emPx);
47
- const sides = sideCount(hasNeg, hasPos);
48
- // Narrow columns shrink the gutters rather than the total, so wN stays wN.
49
- const labelAreaWidth = Math.min(BAR_LABEL_EM * emPx, totalWidth / (2 * sides));
50
- const maxBarWidth = (totalWidth - labelAreaWidth * sides) / sides;
102
+ const labelGap = LABEL_GAP_EM * emPx;
103
+ // a variance bar starts at the outer edge of the thick axis
104
+ const { extent: maxBarWidth, axisX } = splitSides(totalWidth, labels, (VARIANCE_AXIS_EM * emPx) / 2, labelGap);
51
105
  const breakGap = Math.min(BREAK_GAP_EM * emPx, maxBarWidth * 0.2);
52
106
  const overdriveZoneWidth = maxBarWidth * OVERDRIVE_FRACTION;
53
107
  return {
54
108
  totalWidth,
55
- labelAreaWidth,
56
109
  maxBarWidth,
57
- axisX: hasNeg ? labelAreaWidth + maxBarWidth : 0,
110
+ axisX,
58
111
  breakGap,
59
112
  overdriveZoneWidth,
60
113
  cutWidth: Math.max(0, maxBarWidth - breakGap - overdriveZoneWidth),
61
- labelGap: LABEL_GAP_EM * emPx,
114
+ labelGap,
62
115
  };
63
116
  }
64
- export function relativePinGeometry(widthEm, emPx, hasNeg, hasPos) {
117
+ export function relativePinGeometry(widthEm, emPx, labels, headSize) {
65
118
  const totalWidth = contentWidth(widthEm, emPx);
66
- const sides = sideCount(hasNeg, hasPos);
67
- const labelAreaWidth = Math.min(PIN_LABEL_EM * emPx, totalWidth / (2 * sides));
68
- const sideWidth = (totalWidth - labelAreaWidth * sides) / sides;
69
- // also leaves room for the outer half of the pin head
70
- const pinPadding = Math.min(PIN_PADDING_EM * emPx, sideWidth * 0.2);
71
- return {
72
- totalWidth,
73
- labelAreaWidth,
74
- maxPinLength: Math.max(0, sideWidth - pinPadding),
75
- pinPadding,
76
- axisX: hasNeg ? labelAreaWidth + sideWidth : 0,
77
- labelGap: LABEL_GAP_EM * emPx,
78
- };
119
+ const labelGap = LABEL_GAP_EM * emPx;
120
+ const { extent, axisX } = splitSides(totalWidth, labels, headSize / 2, labelGap);
121
+ return { totalWidth, maxPinLength: extent, axisX, labelGap };
79
122
  }
80
123
  export function waterfallGeometry(widthEm, emPx) {
81
124
  const totalWidth = contentWidth(widthEm, emPx);
@@ -1 +1 @@
1
- import{B as o,d as s}from"./p-BW842XlW.js";const p=o,r=s;export{p as BnTableRenderer,r as defineCustomElement}
1
+ import{B as o,d as s}from"./p-CLilvhjH.js";const p=o,r=s;export{p as BnTableRenderer,r as defineCustomElement}