@pioneer-code/pioneer-charts 22.2.11 → 22.2.13

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.
@@ -1,16 +1,16 @@
1
1
  import * as i0 from '@angular/core';
2
- import { Injectable, inject, ApplicationRef, DestroyRef, afterNextRender, TemplateRef, Directive, input, viewChild, contentChild, effect, ViewEncapsulation, Component, model, output, computed } from '@angular/core';
2
+ import { Injectable, inject, ApplicationRef, DOCUMENT, DestroyRef, afterNextRender, TemplateRef, Directive, input, viewChild, contentChild, effect, ViewEncapsulation, Component, model, output, computed } from '@angular/core';
3
3
  import { color } from 'd3-color';
4
4
  import { scaleLinear, scaleBand } from 'd3-scale';
5
- import { select as select$1 } from 'd3-selection';
5
+ import { select } from 'd3-selection';
6
+ import { transition } from 'd3-transition';
6
7
  import { Subject } from 'rxjs';
7
8
  import { axisLeft, axisBottom } from 'd3-axis';
8
9
  import { format } from 'd3-format';
9
- import { select, scaleTime, zoom } from 'd3';
10
10
  import { takeUntilDestroyed, outputFromObservable } from '@angular/core/rxjs-interop';
11
11
  import { debounceTime } from 'rxjs/operators';
12
- import { transition } from 'd3-transition';
13
12
  import { range } from 'd3-array';
13
+ import { scaleTime, zoom } from 'd3';
14
14
  import { line, area, arc, pie } from 'd3-shape';
15
15
  import { interpolate } from 'd3-interpolate';
16
16
 
@@ -210,6 +210,12 @@ class PcacAxisChartConfig extends PcacChartConfig {
210
210
  class PcacData {
211
211
  key = null;
212
212
  value = null;
213
+ /**
214
+ * Hides the item while keeping its place in the color order, so a `<pcac-legend>` can toggle it
215
+ * without the other items changing color. A line/area/plot series draws no line, area, points or
216
+ * hover effects; a bar (or every bar of a group) is drawn at zero size, keeping its slot; a pie
217
+ * slice takes no angle.
218
+ */
213
219
  hide = false;
214
220
  data = [];
215
221
  /**
@@ -493,15 +499,24 @@ class PcacColorService {
493
499
  warning = '#fec163';
494
500
  orange = '#ffa177';
495
501
  blue = '#55d8fe';
496
- scale = [
497
- this.primaryLight,
498
- this.success,
499
- this.danger,
500
- this.warning,
501
- this.orange,
502
- this.blue
503
- ];
504
502
  alert = 'red';
503
+ /** A consumer's own scale from `setScale()`; replaces the default palette while set. */
504
+ customScale = null;
505
+ /**
506
+ * The palette charts cycle through: the `setScale()` one when given, else the default colors
507
+ * built from the current fields - so a setter like `setSuccess()` changes the charts drawn after
508
+ * it, rather than a copy of the colors taken when the service was created.
509
+ */
510
+ get scale() {
511
+ return this.customScale ?? [
512
+ this.primaryLight,
513
+ this.success,
514
+ this.danger,
515
+ this.warning,
516
+ this.orange,
517
+ this.blue,
518
+ ];
519
+ }
505
520
  /**
506
521
  * Get a scale of colors dynamically
507
522
  * @param numberOfNodes Number of items in dynamically build collection of colors
@@ -518,12 +533,15 @@ class PcacColorService {
518
533
  return this.alert;
519
534
  }
520
535
  /**
521
- * Set the scale that charts use to set colors of data[x] on the UI.
536
+ * Set the scale that charts use to set colors of data[x] on the UI, in place of the default
537
+ * palette (and of the individual color setters below, which only shape the default). An empty
538
+ * array goes back to the default palette rather than leaving charts with no colors.
522
539
  * @param colors A collection of hex values
523
540
  */
524
541
  setScale(colors) {
525
- this.scale = colors;
542
+ this.customScale = colors.length ? [...colors] : null;
526
543
  }
544
+ /** @deprecated No chart reads the primary color; it isn't part of the palette. */
527
545
  setPrimary(color) {
528
546
  this.primary = color;
529
547
  }
@@ -536,6 +554,9 @@ class PcacColorService {
536
554
  setDanger(color) {
537
555
  this.danger = color;
538
556
  }
557
+ setWarning(color) {
558
+ this.warning = color;
559
+ }
539
560
  setOrange(color) {
540
561
  this.orange = color;
541
562
  }
@@ -572,15 +593,25 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.1.7", ngImpor
572
593
 
573
594
  class PcacTooltipBuilder {
574
595
  appRef = inject(ApplicationRef);
596
+ document = inject(DOCUMENT);
597
+ shell = null;
575
598
  /**
576
599
  * One tooltip element shared by every chart on the page, appended to `<body>` so it can float
577
600
  * over anything. It's only ever a positioning shell: the default look (`.pcac-d3-tooltip-default`)
578
601
  * is toggled on when the library renders its own key/value content and off when a consumer's
579
602
  * `<ng-template pcacTooltip>` is rendered into it instead, so a custom template owns the whole box.
603
+ *
604
+ * Created on first use rather than with the service, which every chart builder injects: that
605
+ * way nothing touches the DOM until a chart actually shows a tooltip, so building a chart
606
+ * where there's no browser `document` (server-side rendering) doesn't throw. Removed again in
607
+ * `ngOnDestroy()`, when the app that owns this root service is destroyed.
580
608
  */
581
- tooltip = select('body')
582
- .append('div')
583
- .attr('class', 'pcac-d3-tooltip');
609
+ get tooltip() {
610
+ this.shell ??= select(this.document.body)
611
+ .append('div')
612
+ .attr('class', 'pcac-d3-tooltip');
613
+ return this.shell;
614
+ }
584
615
  /**
585
616
  * The consumer template currently rendered into the shell, if any. Created on the first show
586
617
  * of a hover and torn down in `hideTooltip()` - not kept around between hovers - so a view is
@@ -619,14 +650,33 @@ class PcacTooltipBuilder {
619
650
  this.showTooltip(event, undefined, { $implicit: data, parent: null, isThreshold: false, index: 0, parentIndex: null, coincident: [] }, valueFormat, keyFormat);
620
651
  }
621
652
  hideTooltip() {
622
- this.tooltip.style('display', 'none');
653
+ if (!this.shell) {
654
+ // Never shown, so there's nothing to hide - and no reason to create the element just to.
655
+ return;
656
+ }
657
+ this.shell.style('display', 'none');
658
+ this.destroyView();
659
+ }
660
+ ngOnDestroy() {
623
661
  this.destroyView();
662
+ this.shell?.remove();
663
+ this.shell = null;
624
664
  }
665
+ /**
666
+ * The library's own key/value content. Built from text nodes, never parsed as HTML: `key` and
667
+ * `value` are consumer data, and markup in them must show as text rather than run.
668
+ */
625
669
  renderDefault(data, valueFormat, keyFormat) {
626
670
  this.destroyView();
627
- this.tooltip
671
+ const { key, value } = this.getBarTipData(data, valueFormat, keyFormat);
672
+ const shell = this.tooltip
628
673
  .classed('pcac-d3-tooltip-default', true)
629
- .html(this.getBarTipData(data, valueFormat, keyFormat));
674
+ .html(null)
675
+ .node();
676
+ if (key !== null) {
677
+ shell.append(key, this.document.createElement('br'));
678
+ }
679
+ shell.append(value);
630
680
  }
631
681
  renderTemplate(template, context) {
632
682
  if (this.view && this.viewTemplate === template) {
@@ -663,7 +713,7 @@ class PcacTooltipBuilder {
663
713
  this.view.destroy();
664
714
  this.view = null;
665
715
  this.viewTemplate = null;
666
- this.tooltip.html(null);
716
+ this.shell?.html(null);
667
717
  }
668
718
  /**
669
719
  * Shows the (already rendered) shell at the page's top-left so it can be measured. Left where the
@@ -699,7 +749,8 @@ class PcacTooltipBuilder {
699
749
  const width = shell.offsetWidth;
700
750
  const height = shell.offsetHeight;
701
751
  // `clientWidth`/`clientHeight` of the root, unlike `innerWidth`/`innerHeight`, exclude scrollbars.
702
- const viewport = document.documentElement;
752
+ const viewport = this.document.documentElement;
753
+ const view = this.document.defaultView;
703
754
  const right = viewport.clientWidth - box.right - gap;
704
755
  const left = box.left - gap;
705
756
  const above = box.top - gap;
@@ -710,9 +761,10 @@ class PcacTooltipBuilder {
710
761
  const y = toTop ? box.top - gap - height : box.bottom + gap;
711
762
  // The rect is in viewport coordinates; the shell is absolutely positioned against the page.
712
763
  this.tooltip
713
- .style('left', x + window.scrollX + 'px')
714
- .style('top', y + window.scrollY + 'px');
764
+ .style('left', x + (view?.scrollX ?? 0) + 'px')
765
+ .style('top', y + (view?.scrollY ?? 0) + 'px');
715
766
  }
767
+ /** The default tooltip's two lines as plain text; `key` is null when the datum has none. */
716
768
  getBarTipData(data, valueFormat, keyFormat) {
717
769
  let value = data.value;
718
770
  let key = data.key;
@@ -740,8 +792,11 @@ class PcacTooltipBuilder {
740
792
  break;
741
793
  }
742
794
  }
743
- const finalValue = value ? value.toString() : value;
744
- return key ? key + '<br>' + finalValue : `${finalValue}`;
795
+ // A key of 0 (e.g. hour 0) is a real key; only a missing or empty one leaves the line out.
796
+ return {
797
+ key: key === null || key === undefined || key === '' ? null : String(key),
798
+ value: value === null || value === undefined ? '' : String(value),
799
+ };
745
800
  }
746
801
  static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "22.1.7", ngImport: i0, type: PcacTooltipBuilder, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
747
802
  static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "22.1.7", ngImport: i0, type: PcacTooltipBuilder, providedIn: 'root' });
@@ -778,6 +833,20 @@ class PcacChart {
778
833
  height = 400;
779
834
  colors = [];
780
835
  startData = [];
836
+ /**
837
+ * Swaps a consumer's `colorOverride` in for the theme palette `initializeChartState` set, in
838
+ * order. Checks `length` rather than truthiness: every config class defaults its override to
839
+ * `[]`, and an empty array is truthy - taken as an override, it would leave every mark with no
840
+ * color. Cycled out to at least as many entries as the theme palette, the same way that palette
841
+ * cycles its own colors, so an override shorter than the data repeats rather than leaving the
842
+ * marks past its end with an `undefined` color. Call after `initializeChartState()`.
843
+ */
844
+ applyColorOverride(override) {
845
+ if (!override?.length) {
846
+ return;
847
+ }
848
+ this.colors = Array.from({ length: Math.max(this.colors.length, override.length) }, (_, i) => override[i % override.length]);
849
+ }
781
850
  /**
782
851
  * Raw, unadjusted container width measured by the last successful `initializeChartState()`
783
852
  * call, or `null` if none has succeeded yet. Deliberately tracked separately from `width`:
@@ -989,17 +1058,31 @@ class PcacChart {
989
1058
  * @param chartElm Reference to SVG on dom
990
1059
  * @param config Chart specific configuration
991
1060
  */
1061
+ /**
1062
+ * Removes whatever the chart last drew, for a build with no data to draw. Builders call it
1063
+ * rather than just returning, which left the previous data on screen when a consumer emptied
1064
+ * the chart (e.g. a filter that now matches nothing).
1065
+ */
1066
+ clearChart(chartElm) {
1067
+ select(chartElm.nativeElement).select('g').remove();
1068
+ }
992
1069
  initializeChartState(chartElm, config) {
993
- select$1(chartElm.nativeElement).select('g').remove();
1070
+ select(chartElm.nativeElement).select('g').remove();
994
1071
  const container = chartElm.nativeElement.parentNode;
995
1072
  const containerWidth = container.clientWidth;
996
1073
  const measuredWidth = containerWidth - this.margin.left - this.margin.right;
997
1074
  if (measuredWidth <= 0) {
1075
+ // The previous drawing was just removed above, so nothing is on screen any more. Forget the
1076
+ // size it was drawn at, or a container that comes back at that same width (a hidden tab
1077
+ // shown again) would read as unchanged to `containerSizeChanged()` and never be redrawn.
1078
+ this.lastContainerWidth = null;
998
1079
  return false;
999
1080
  }
1000
1081
  this.width = measuredWidth;
1001
1082
  this.height = this.resolveHeight(container, config);
1002
- this.colors = this.colorService.getColorScale(Math.max(config.data.length, config.data[0]?.data ? config.data[0].data.length : 0));
1083
+ // One color per group or per series within a group, whichever needs more - sized by the
1084
+ // largest group, since bars index colors by their position within their own group.
1085
+ this.colors = this.colorService.getColorScale(Math.max(config.data.length, ...config.data.map((d) => d.data?.length ?? 0)));
1003
1086
  this.lastContainerWidth = containerWidth;
1004
1087
  this.lastContainerHeight = container.clientHeight;
1005
1088
  this.lastHeightFull = config.heightFull === true;
@@ -1069,7 +1152,7 @@ class PcacChart {
1069
1152
  buildContainer(chartElm, center = false) {
1070
1153
  const combinedHeight = this.height + this.margin.top + this.margin.bottom;
1071
1154
  const combinedWidth = this.width + this.margin.left + this.margin.right;
1072
- this.svg = select$1(chartElm.nativeElement)
1155
+ this.svg = select(chartElm.nativeElement)
1073
1156
  .attr('width', combinedWidth)
1074
1157
  .attr('height', combinedHeight);
1075
1158
  if (center) {
@@ -1101,7 +1184,7 @@ class PcacChart {
1101
1184
  axisY.tickSizeInner(this.yAxis.tickSize);
1102
1185
  }
1103
1186
  let max = 0;
1104
- select$1(chartElm.nativeElement).append('g')
1187
+ select(chartElm.nativeElement).append('g')
1105
1188
  .call(axisY)
1106
1189
  .each((d, i, n) => {
1107
1190
  const width = n[i].getBBox().width;
@@ -1122,25 +1205,104 @@ class PcacChart {
1122
1205
  }
1123
1206
 
1124
1207
  /**
1125
- * Where each bar of a stacked group starts: the running total of the bars before it, in data
1126
- * order, so the first bar sits on the baseline and each later one on top of the previous. Values
1127
- * are the bar's *own* size (segment), not a pre-accumulated total; a null value counts as 0.
1208
+ * How long each bar is drawn: its value, or 0 when it can't be drawn - a null or non-numeric
1209
+ * value, or `hide` set on the bar or on its whole group. A hidden bar keeps its slot (and so its
1210
+ * color) and just draws nothing, the same way a hidden line/area/plot series keeps its place.
1211
+ * Negative values are kept as they are; the bar charts only draw upward from 0.
1128
1212
  *
1129
1213
  * Keyed by the bar's own `PcacData` object so D3 callbacks (which only get the datum) can look
1130
- * their offset up directly.
1214
+ * their size up directly.
1131
1215
  */
1132
- function stackStarts(groups) {
1216
+ function barSizes(groups) {
1217
+ const sizes = new Map();
1218
+ for (const group of groups) {
1219
+ for (const bar of group.data ?? []) {
1220
+ const value = Number(bar.value ?? 0);
1221
+ sizes.set(bar, group.hide || bar.hide || !Number.isFinite(value) ? 0 : value);
1222
+ }
1223
+ }
1224
+ return sizes;
1225
+ }
1226
+ /**
1227
+ * Where each bar of a stacked group starts: the running total of the bars before it, in data
1228
+ * order, so the first bar sits on the baseline and each later one on top of the previous. Sizes
1229
+ * are the bar's *own* (segment), not a pre-accumulated total, taken from `barSizes` - so a null,
1230
+ * non-numeric or hidden bar adds nothing to the stack.
1231
+ */
1232
+ function stackStarts(groups, sizes = barSizes(groups)) {
1133
1233
  const starts = new Map();
1134
1234
  for (const group of groups) {
1135
1235
  let total = 0;
1136
- for (const bar of group.data) {
1236
+ for (const bar of group.data ?? []) {
1137
1237
  starts.set(bar, total);
1138
- total += Number(bar.value ?? 0);
1238
+ total += sizes.get(bar) ?? 0;
1139
1239
  }
1140
1240
  }
1141
1241
  return starts;
1142
1242
  }
1143
1243
 
1244
+ /** Whether a threshold entry carries per-bar values in its `data`. */
1245
+ function hasBars(entry) {
1246
+ return (entry.data?.length ?? 0) > 0;
1247
+ }
1248
+ /** A threshold is only drawn when its value is a finite number. */
1249
+ function drawable(threshold) {
1250
+ if (!threshold || threshold.value === null || threshold.value === undefined) {
1251
+ return null;
1252
+ }
1253
+ return Number.isFinite(Number(threshold.value)) ? threshold : null;
1254
+ }
1255
+ /**
1256
+ * Reads the shape of `thresholds` the way the docs describe it:
1257
+ * - one entry with an empty (or no) `data` - a single threshold across the whole chart;
1258
+ * - one entry per group, each with an empty `data` - a threshold per group;
1259
+ * - one entry per group, each with an entry per bar in its `data` - a threshold per bar.
1260
+ *
1261
+ * A stacked group is drawn as one bar, so on a stacked chart per-bar entries give per-group
1262
+ * thresholds, each group's taken from its entry's first `data` item. Checks `data.length` rather
1263
+ * than `data`'s truthiness: `PcacData.data` defaults to `[]`, which is truthy.
1264
+ */
1265
+ function barThresholdLayout(thresholds, isStacked) {
1266
+ if (!thresholds?.length) {
1267
+ return 'none';
1268
+ }
1269
+ if (!thresholds.some(hasBars)) {
1270
+ return thresholds.length === 1 ? 'chart' : 'group';
1271
+ }
1272
+ return isStacked ? 'group' : 'bar';
1273
+ }
1274
+ /**
1275
+ * The threshold drawn across the group at `groupIndex` (or across the chart, for index 0 of a
1276
+ * `'chart'` layout): the entry itself, or its first `data` item when it has per-bar values. Null
1277
+ * when there's no entry for that group or no numeric value to draw.
1278
+ */
1279
+ function groupThreshold(thresholds, groupIndex) {
1280
+ const entry = thresholds[groupIndex];
1281
+ if (!entry) {
1282
+ return null;
1283
+ }
1284
+ return drawable(hasBars(entry) ? entry.data[0] : entry);
1285
+ }
1286
+ /** The threshold drawn across one bar, or null when that bar has none (or no numeric value). */
1287
+ function barThreshold(thresholds, groupIndex, barIndex) {
1288
+ return drawable(thresholds[groupIndex]?.data?.[barIndex]);
1289
+ }
1290
+
1291
+ /**
1292
+ * Every series key across all groups, in first-seen order: the domain of a grouped bar chart's
1293
+ * inner band, so each series has its own slot in every group. Taken from the first group alone,
1294
+ * a series that only later groups have fell outside the band and was drawn over the first slot.
1295
+ */
1296
+ function seriesKeys(groups) {
1297
+ const keys = new Set();
1298
+ for (const group of groups) {
1299
+ for (const bar of group.data ?? []) {
1300
+ keys.add(bar.key);
1301
+ }
1302
+ }
1303
+ return [...keys];
1304
+ }
1305
+
1144
1306
  /**
1145
1307
  * Provided per-component (see PcacBarHorizontalChartComponent's `providers`), not root-scoped:
1146
1308
  * this builder extends PcacChart, which holds mutable per-chart-instance state (margin, width,
@@ -1156,6 +1318,7 @@ class BarHorizontalChartBuilder extends PcacChart {
1156
1318
  barClicked$ = this.barClickedSource.asObservable();
1157
1319
  buildChart(chartElm, config) {
1158
1320
  if (!config?.data?.length) {
1321
+ this.clearChart(chartElm);
1159
1322
  return;
1160
1323
  }
1161
1324
  this.config = JSON.parse(JSON.stringify(config));
@@ -1163,18 +1326,11 @@ class BarHorizontalChartBuilder extends PcacChart {
1163
1326
  if (!this.initializeChartState(chartElm, this.config)) {
1164
1327
  return;
1165
1328
  }
1166
- // Copy before reversing: `.reverse()` is in place, and this is the consumer's own array -
1167
- // reversing it directly flipped their palette on every rebuild (i.e. every resize).
1168
- if (config.colorOverride && config.colorOverride.colors) {
1169
- this.colors = [...config.colorOverride.colors].reverse();
1170
- }
1329
+ this.applyColorOverride(config.colorOverride?.colors);
1171
1330
  this.buildScales(chartElm, this.config);
1172
1331
  this.drawChart(chartElm, this.config);
1173
1332
  }
1174
1333
  buildScales(chartElm, config) {
1175
- config.data[0].data.map((d) => {
1176
- return d.value;
1177
- });
1178
1334
  // Bars grow from 0, so only `domainMax` is read; `xAxis.domainMin` is ignored.
1179
1335
  this.xScale = scaleLinear()
1180
1336
  .domain([0, this.xAxis.domainMax]);
@@ -1185,7 +1341,7 @@ class BarHorizontalChartBuilder extends PcacChart {
1185
1341
  this.yScaleGrouped = scaleBand()
1186
1342
  .padding(0.05)
1187
1343
  .rangeRound([0, this.yScaleStacked.bandwidth()])
1188
- .domain(config.data[0].data.map((d) => d.key));
1344
+ .domain(seriesKeys(config.data));
1189
1345
  // The left margin is sized to the y axis's labels - unless there is no y axis to size it to
1190
1346
  if (!this.yAxis.hide) {
1191
1347
  this.setHorizontalMarginsBasedOnContent(chartElm, this.yScaleStacked);
@@ -1212,33 +1368,31 @@ class BarHorizontalChartBuilder extends PcacChart {
1212
1368
  .attr('transform', (d) => 'translate(0,' + this.yScaleStacked(d.key) + ')');
1213
1369
  const group = groupsContainer.selectAll('rect')
1214
1370
  .data((d) => {
1215
- return d.data;
1371
+ return d.data ?? [];
1216
1372
  });
1217
1373
  this.drawBarsPerGroup(group, config);
1218
- // We have no thresholds to draw
1219
- if (!config.thresholds) {
1220
- return;
1221
- }
1222
- // Draw threshold across entire chart
1223
- if (config.thresholds.length === 1 && !config.thresholds[0].data) {
1224
- this.drawThresholdAcrossChart(config);
1225
- }
1226
- // Draw threshold across each group
1227
- if (config.thresholds.length > 1 && (!config.thresholds[0].data || config.isStacked)) {
1228
- this.drawThresholdsPerGroup(group, config);
1229
- }
1230
- // Draw threshold across each bar in group
1231
- if (config.thresholds.length > 1 && config.thresholds[0].data && !config.isStacked) {
1232
- this.drawThresholdsPerBarInGroup(group, config);
1374
+ switch (barThresholdLayout(config.thresholds, config.isStacked)) {
1375
+ case 'chart':
1376
+ this.drawThresholdAcrossChart(config);
1377
+ break;
1378
+ case 'group':
1379
+ this.drawThresholdsPerGroup(config);
1380
+ break;
1381
+ case 'bar':
1382
+ this.drawThresholdsPerBarInGroup(group, config);
1383
+ break;
1233
1384
  }
1234
1385
  }
1235
1386
  drawBarsPerGroup(groups, config) {
1236
1387
  const self = this;
1237
1388
  // Stacked bars start where the previous bar in their group ends; every other layout draws
1238
1389
  // from the baseline (start 0).
1239
- const starts = config.isStacked ? stackStarts(config.data) : new Map();
1390
+ // Sizes honor `hide` (and treat a null or non-numeric value as 0), so a hidden bar keeps its
1391
+ // slot and color but draws nothing - see `barSizes`.
1392
+ const sizes = barSizes(config.data);
1393
+ const starts = config.isStacked ? stackStarts(config.data, sizes) : new Map();
1240
1394
  const startOf = (d) => starts.get(d) ?? 0;
1241
- const endOf = (d) => startOf(d) + Number(d.value ?? 0);
1395
+ const endOf = (d) => startOf(d) + (sizes.get(d) ?? 0);
1242
1396
  groups.enter().append('rect')
1243
1397
  .attr('class', 'pcac-bar')
1244
1398
  .attr('x', (d) => this.xScale(startOf(d)))
@@ -1259,7 +1413,7 @@ class BarHorizontalChartBuilder extends PcacChart {
1259
1413
  })
1260
1414
  .attr('width', 0)
1261
1415
  .on('mouseover', function () {
1262
- select$1(this)
1416
+ select(this)
1263
1417
  .transition()
1264
1418
  .duration(self.transitionService.getTransitionDuration() / 7.5)
1265
1419
  .style('fill', () => {
@@ -1282,7 +1436,7 @@ class BarHorizontalChartBuilder extends PcacChart {
1282
1436
  })
1283
1437
  .on('mouseout', function () {
1284
1438
  self.hideTooltip();
1285
- select$1(this)
1439
+ select(this)
1286
1440
  .transition()
1287
1441
  .duration(self.transitionService.getTransitionDuration() / 5)
1288
1442
  .style('fill', () => {
@@ -1304,53 +1458,63 @@ class BarHorizontalChartBuilder extends PcacChart {
1304
1458
  });
1305
1459
  }
1306
1460
  drawThresholdAcrossChart(config) {
1461
+ const threshold = groupThreshold(config.thresholds, 0);
1462
+ if (!threshold) {
1463
+ return;
1464
+ }
1307
1465
  this.applyPreTransitionThresholdStyles(this.svg.select('.pcac-bars').append('rect'))
1308
1466
  .attr('height', this.height)
1309
- .attr('data-group-threshold-id', (_, i) => {
1310
- return i;
1311
- })
1467
+ .attr('data-group-threshold-id', 0)
1312
1468
  .on('mousemove', (event) => {
1313
- this.showTooltip(event, config.thresholds[0], { index: 0, isThreshold: true, valueFormat: this.xAxis.format });
1469
+ this.showTooltip(event, threshold, { index: 0, isThreshold: true, valueFormat: this.xAxis.format });
1314
1470
  })
1315
1471
  .transition()
1316
1472
  .duration(this.transitionService.getTransitionDuration())
1317
- .attr('x', (_, i) => {
1318
- return this.xScale(config.thresholds[i].value);
1319
- });
1473
+ .attr('x', this.xScale(Number(threshold.value)));
1320
1474
  }
1321
- drawThresholdsPerGroup(group, config) {
1475
+ /** One threshold across each group that has one; groups without an entry are skipped. */
1476
+ drawThresholdsPerGroup(config) {
1322
1477
  const self = this;
1323
- this.applyPreTransitionThresholdStyles(this.svg.selectAll('.pcac-bar-group').append('rect'))
1478
+ const groupIndexOf = (rect) => Number(rect.parentElement.dataset['groupId']);
1479
+ const groups = this.svg.selectAll('.pcac-bar-group')
1480
+ .filter((_, i) => groupThreshold(config.thresholds, i) !== null);
1481
+ this.applyPreTransitionThresholdStyles(groups.append('rect'))
1324
1482
  .attr('height', this.yScaleStacked.bandwidth())
1325
- .attr('data-group-threshold-id', (_, i) => {
1326
- return i;
1483
+ .attr('data-group-threshold-id', function () {
1484
+ return groupIndexOf(this);
1327
1485
  })
1328
1486
  .on('mousemove', function (event) {
1329
- const index = Number(this.parentElement.dataset['groupId']);
1330
- const threshold = config.thresholds[index];
1487
+ const index = groupIndexOf(this);
1331
1488
  // A threshold's own PcacData is typically just a value, so its parent is the *data* group
1332
1489
  // it's drawn against (which has the key) rather than the threshold entry it came from.
1333
- self.showTooltip(event, config.isStacked ? threshold.data[0] : threshold, { index, parent: config.data[index], parentIndex: index, isThreshold: true, valueFormat: self.xAxis.format });
1490
+ self.showTooltip(event, groupThreshold(config.thresholds, index), { index, parent: config.data[index], parentIndex: index, isThreshold: true, valueFormat: self.xAxis.format });
1334
1491
  })
1335
1492
  .transition()
1336
1493
  .duration(this.transitionService.getTransitionDuration())
1337
- .attr('x', (_, i) => {
1338
- return this.xScale(config.isStacked ? config.thresholds[i].data[0].value : config.thresholds[i].value);
1494
+ .attr('x', (_, i, nodes) => {
1495
+ return this.xScale(Number(groupThreshold(config.thresholds, groupIndexOf(nodes[i]))?.value));
1339
1496
  });
1340
1497
  }
1498
+ /** One threshold across each bar that has one; bars without an entry are skipped. */
1341
1499
  drawThresholdsPerBarInGroup(group, config) {
1342
1500
  const self = this;
1343
- this.applyPreTransitionThresholdStyles(group.enter().append('rect'))
1501
+ const thresholdOf = (rect) => barThreshold(config.thresholds, Number(rect.parentElement.dataset['groupId']), Number(rect.getAttribute('data-group-threshold-id')));
1502
+ const rects = this.applyPreTransitionThresholdStyles(group.enter().append('rect'))
1344
1503
  .attr('data-group-threshold-id', (_, i) => {
1345
1504
  return i;
1346
1505
  })
1347
- .attr('height', this.yScaleGrouped.bandwidth())
1506
+ .attr('height', this.yScaleGrouped.bandwidth());
1507
+ rects.filter(function () {
1508
+ return thresholdOf(this) === null;
1509
+ }).remove();
1510
+ rects.filter(function () {
1511
+ return thresholdOf(this) !== null;
1512
+ })
1348
1513
  .on('mousemove', function (event) {
1349
- const target = event.target;
1350
- const index = Number(target.getAttribute("data-group-threshold-id"));
1514
+ const index = Number(this.getAttribute('data-group-threshold-id'));
1351
1515
  const groupIndex = Number(this.parentElement.dataset['groupId']);
1352
1516
  // Parent is the data group (see drawThresholdsPerGroup), not the threshold entry itself.
1353
- self.showTooltip(event, config.thresholds[groupIndex].data[index], { index, parent: config.data[groupIndex], parentIndex: groupIndex, isThreshold: true, valueFormat: self.xAxis.format });
1517
+ self.showTooltip(event, thresholdOf(this), { index, parent: config.data[groupIndex], parentIndex: groupIndex, isThreshold: true, valueFormat: self.xAxis.format });
1354
1518
  })
1355
1519
  .transition()
1356
1520
  .duration(this.transitionService.getTransitionDuration())
@@ -1358,8 +1522,8 @@ class BarHorizontalChartBuilder extends PcacChart {
1358
1522
  // ScaleBand can return undefined for a key outside its domain; `.attr()` needs null, not undefined.
1359
1523
  return this.yScaleGrouped(d.key) ?? null;
1360
1524
  })
1361
- .attr('x', (d, i, n) => {
1362
- return this.xScale(config.thresholds[n[0].parentElement.dataset['groupId']].data[i].value);
1525
+ .attr('x', (_, i, nodes) => {
1526
+ return this.xScale(Number(thresholdOf(nodes[i])?.value));
1363
1527
  });
1364
1528
  }
1365
1529
  applyPreTransitionThresholdStyles(elm) {
@@ -1529,7 +1693,8 @@ class PcacBarHorizontalChartComponent {
1529
1693
  }
1530
1694
  buildChart() {
1531
1695
  const config = this.config();
1532
- if (config && config.data && config.data.length > 0) {
1696
+ // Handed over even when empty: the builder clears what it last drew rather than leaving it.
1697
+ if (config) {
1533
1698
  this.chartBuilder.buildChart(this.chartElm(), config);
1534
1699
  }
1535
1700
  }
@@ -1565,6 +1730,7 @@ class BarVerticalChartBuilder extends PcacChart {
1565
1730
  barClicked$ = this.barClickedSource.asObservable();
1566
1731
  buildChart(chartElm, config) {
1567
1732
  if (!config?.data?.length) {
1733
+ this.clearChart(chartElm);
1568
1734
  return;
1569
1735
  }
1570
1736
  // Shallow copy: initializeAxisState() rewrites `height` for hidden axes, and that must not
@@ -1575,11 +1741,7 @@ class BarVerticalChartBuilder extends PcacChart {
1575
1741
  if (!this.initializeChartState(chartElm, config)) {
1576
1742
  return;
1577
1743
  }
1578
- // Copy before reversing: `.reverse()` is in place, and this is the consumer's own array -
1579
- // reversing it directly flipped their palette on every rebuild (i.e. every resize).
1580
- if (config.colorOverride && config.colorOverride.colors) {
1581
- this.colors = [...config.colorOverride.colors].reverse();
1582
- }
1744
+ this.applyColorOverride(config.colorOverride?.colors);
1583
1745
  this.buildScales(config);
1584
1746
  this.drawChart(chartElm, config);
1585
1747
  }
@@ -1597,7 +1759,7 @@ class BarVerticalChartBuilder extends PcacChart {
1597
1759
  this.xScaleGrouped = scaleBand()
1598
1760
  .padding(0.2)
1599
1761
  .rangeRound([0, this.xScaleStacked.bandwidth()])
1600
- .domain(config.data[0].data.map((d) => d.key));
1762
+ .domain(seriesKeys(config.data));
1601
1763
  }
1602
1764
  drawChart(chartElm, config) {
1603
1765
  this.buildContainer(chartElm);
@@ -1621,33 +1783,31 @@ class BarVerticalChartBuilder extends PcacChart {
1621
1783
  });
1622
1784
  const group = groupsContainer.selectAll('rect')
1623
1785
  .data((d) => {
1624
- return d.data;
1786
+ return d.data ?? [];
1625
1787
  });
1626
1788
  this.drawBarsPerGroup(group, config);
1627
- // We have no thresholds to draw
1628
- if (!config.thresholds) {
1629
- return;
1630
- }
1631
- // Draw threshold across entire chart
1632
- if (config.thresholds.length === 1 && !config.thresholds[0].data) {
1633
- this.drawThresholdAcrossChart(config);
1634
- }
1635
- // Draw threshold across each group
1636
- if (config.thresholds.length > 1 && (!config.thresholds[0].data || config.isStacked)) {
1637
- this.drawThresholdsPerGroup(group, config);
1638
- }
1639
- // Draw threshold across each bar in group
1640
- if (config.thresholds.length > 1 && config.thresholds[0].data && !config.isStacked) {
1641
- this.drawThresholdsPerBarInGroup(group, config);
1789
+ switch (barThresholdLayout(config.thresholds, config.isStacked)) {
1790
+ case 'chart':
1791
+ this.drawThresholdAcrossChart(config);
1792
+ break;
1793
+ case 'group':
1794
+ this.drawThresholdsPerGroup(config);
1795
+ break;
1796
+ case 'bar':
1797
+ this.drawThresholdsPerBarInGroup(group, config);
1798
+ break;
1642
1799
  }
1643
1800
  }
1644
1801
  drawBarsPerGroup(group, config) {
1645
1802
  const self = this;
1646
1803
  // Stacked bars sit on top of the ones before them in their group; every other layout draws
1647
1804
  // from the baseline (start 0).
1648
- const starts = config.isStacked ? stackStarts(config.data) : new Map();
1805
+ // Sizes honor `hide` (and treat a null or non-numeric value as 0), so a hidden bar keeps its
1806
+ // slot and color but draws nothing - see `barSizes`.
1807
+ const sizes = barSizes(config.data);
1808
+ const starts = config.isStacked ? stackStarts(config.data, sizes) : new Map();
1649
1809
  const startOf = (d) => starts.get(d) ?? 0;
1650
- const endOf = (d) => startOf(d) + Number(d.value ?? 0);
1810
+ const endOf = (d) => startOf(d) + (sizes.get(d) ?? 0);
1651
1811
  group.enter().append('rect')
1652
1812
  .attr('class', 'pcac-bar')
1653
1813
  .attr('x', (d) => {
@@ -1669,7 +1829,7 @@ class BarVerticalChartBuilder extends PcacChart {
1669
1829
  })
1670
1830
  .attr('height', 0)
1671
1831
  .on('mouseover', function () {
1672
- select$1(this)
1832
+ select(this)
1673
1833
  .transition()
1674
1834
  .duration(self.transitionService.getTransitionDuration() / 5)
1675
1835
  .style('fill', () => {
@@ -1692,7 +1852,7 @@ class BarVerticalChartBuilder extends PcacChart {
1692
1852
  })
1693
1853
  .on('mouseout', function () {
1694
1854
  self.hideTooltip();
1695
- select$1(this)
1855
+ select(this)
1696
1856
  .transition()
1697
1857
  .duration(self.transitionService.getTransitionDuration() / 5)
1698
1858
  .style('fill', () => {
@@ -1721,58 +1881,71 @@ class BarVerticalChartBuilder extends PcacChart {
1721
1881
  });
1722
1882
  }
1723
1883
  drawThresholdAcrossChart(config) {
1884
+ const threshold = groupThreshold(config.thresholds, 0);
1885
+ if (!threshold) {
1886
+ return;
1887
+ }
1724
1888
  this.applyPreTransitionThresholdStyles(this.svg.select('.pcac-bars').append('rect'))
1725
1889
  .attr('width', this.width)
1726
- .attr('data-group-threshold-id', (_, i) => {
1727
- return i;
1728
- })
1890
+ .attr('data-group-threshold-id', 0)
1729
1891
  .on('mousemove', (event) => {
1730
- this.showTooltip(event, config.thresholds[0], { index: 0, isThreshold: true, valueFormat: this.yAxis.format });
1892
+ this.showTooltip(event, threshold, { index: 0, isThreshold: true, valueFormat: this.yAxis.format });
1731
1893
  })
1732
1894
  .transition()
1733
1895
  .duration(this.transitionService.getTransitionDuration())
1734
- .attr('y', (_, i) => {
1735
- return this.yScale(config.thresholds[i].value);
1736
- });
1896
+ .attr('y', this.yScale(Number(threshold.value)));
1737
1897
  }
1738
- drawThresholdsPerGroup(group, config) {
1898
+ /** One threshold across each group that has one; groups without an entry are skipped. */
1899
+ drawThresholdsPerGroup(config) {
1739
1900
  const self = this;
1740
- this.applyPreTransitionThresholdStyles(this.svg.selectAll('.pcac-bar-group').append('rect'))
1901
+ const groupIndexOf = (rect) => Number(rect.parentElement.dataset['groupId']);
1902
+ const groups = this.svg.selectAll('.pcac-bar-group')
1903
+ .filter((_, i) => groupThreshold(config.thresholds, i) !== null);
1904
+ this.applyPreTransitionThresholdStyles(groups.append('rect'))
1905
+ // Spans its whole group: the pre-transition styles place a rect by bar key, which a group
1906
+ // key can collide with.
1907
+ .attr('x', 0)
1741
1908
  .attr('width', this.xScaleStacked.bandwidth())
1742
- .attr('data-group-threshold-id', (_, i) => {
1743
- return i;
1909
+ .attr('data-group-threshold-id', function () {
1910
+ return groupIndexOf(this);
1744
1911
  })
1745
1912
  .on('mousemove', function (event) {
1746
- const index = Number(this.parentElement.dataset['groupId']);
1747
- const threshold = config.thresholds[index];
1913
+ const index = groupIndexOf(this);
1748
1914
  // A threshold's own PcacData is typically just a value, so its parent is the *data* group
1749
1915
  // it's drawn against (which has the key) rather than the threshold entry it came from.
1750
- self.showTooltip(event, config.isStacked ? threshold.data[0] : threshold, { index, parent: config.data[index], parentIndex: index, isThreshold: true, valueFormat: self.yAxis.format });
1916
+ self.showTooltip(event, groupThreshold(config.thresholds, index), { index, parent: config.data[index], parentIndex: index, isThreshold: true, valueFormat: self.yAxis.format });
1751
1917
  })
1752
1918
  .transition()
1753
1919
  .duration(this.transitionService.getTransitionDuration())
1754
- .attr('y', (_, i) => {
1755
- return this.yScale(config.isStacked ? config.thresholds[i].data[0].value : config.thresholds[i].value);
1920
+ .attr('y', (_, i, nodes) => {
1921
+ return this.yScale(Number(groupThreshold(config.thresholds, groupIndexOf(nodes[i]))?.value));
1756
1922
  });
1757
1923
  }
1924
+ /** One threshold across each bar that has one; bars without an entry are skipped. */
1758
1925
  drawThresholdsPerBarInGroup(group, config) {
1759
1926
  const self = this;
1760
- this.applyPreTransitionThresholdStyles(group.enter().append('rect'))
1927
+ const thresholdOf = (rect) => barThreshold(config.thresholds, Number(rect.parentElement.dataset['groupId']), Number(rect.getAttribute('data-group-threshold-id')));
1928
+ const rects = this.applyPreTransitionThresholdStyles(group.enter().append('rect'))
1761
1929
  .attr('data-group-threshold-id', (_, i) => {
1762
1930
  return i;
1931
+ })
1932
+ .attr('width', this.xScaleGrouped.bandwidth());
1933
+ rects.filter(function () {
1934
+ return thresholdOf(this) === null;
1935
+ }).remove();
1936
+ rects.filter(function () {
1937
+ return thresholdOf(this) !== null;
1763
1938
  })
1764
1939
  .on('mousemove', function (event) {
1765
- const target = event.target;
1766
- const index = Number(target.getAttribute("data-group-threshold-id"));
1940
+ const index = Number(this.getAttribute('data-group-threshold-id'));
1767
1941
  const groupIndex = Number(this.parentElement.dataset['groupId']);
1768
1942
  // Parent is the data group (see drawThresholdsPerGroup), not the threshold entry itself.
1769
- self.showTooltip(event, config.thresholds[groupIndex].data[index], { index, parent: config.data[groupIndex], parentIndex: groupIndex, isThreshold: true, valueFormat: self.yAxis.format });
1943
+ self.showTooltip(event, thresholdOf(this), { index, parent: config.data[groupIndex], parentIndex: groupIndex, isThreshold: true, valueFormat: self.yAxis.format });
1770
1944
  })
1771
- .attr('width', this.xScaleGrouped.bandwidth())
1772
1945
  .transition()
1773
1946
  .duration(this.transitionService.getTransitionDuration())
1774
- .attr('y', (d, i, n) => {
1775
- return this.yScale(config.thresholds[n[0].parentElement.dataset['groupId']].data[i].value);
1947
+ .attr('y', (_, i, nodes) => {
1948
+ return this.yScale(Number(thresholdOf(nodes[i])?.value));
1776
1949
  });
1777
1950
  }
1778
1951
  applyPreTransitionThresholdStyles(elm) {
@@ -1843,7 +2016,8 @@ class PcacBarVerticalChartComponent {
1843
2016
  }
1844
2017
  buildChart() {
1845
2018
  const config = this.config();
1846
- if (config && config.data && config.data.length > 0) {
2019
+ // Handed over even when empty: the builder clears what it last drew rather than leaving it.
2020
+ if (config) {
1847
2021
  this.chartBuilder.buildChart(this.chartElm(), config);
1848
2022
  }
1849
2023
  }
@@ -1969,7 +2143,8 @@ class PcacLineAreaChartConfig extends PcacAxisChartConfig {
1969
2143
  enableZoomX = false;
1970
2144
  enableZoomY = false;
1971
2145
  /**
1972
- * Hex color codes to override the default colors
2146
+ * Hex color codes to override the default colors, one per series in order. Repeats from the
2147
+ * start when there are more series than colors, as the default palette does.
1973
2148
  */
1974
2149
  colorOverride = [];
1975
2150
  /**
@@ -2127,7 +2302,7 @@ class PlaChartEffectsBuilder {
2127
2302
  }
2128
2303
  }
2129
2304
  const textTarget = this.config.y.invert(pos.y);
2130
- select$1(nodes[index]).select('text')
2305
+ select(nodes[index]).select('text')
2131
2306
  .text(textTarget.toFixed(0));
2132
2307
  return 'translate(' + mousePos[0] + ',' + pos.y + ')';
2133
2308
  });
@@ -2253,8 +2428,16 @@ function getXFormat(type, data, index, xScale) {
2253
2428
  }
2254
2429
  }
2255
2430
 
2431
+ /** Whether a point has a numeric value to draw at. */
2432
+ function hasValue(d) {
2433
+ return d.value !== null && d.value !== undefined && d.value !== '' && Number.isFinite(Number(d.value));
2434
+ }
2435
+
2256
2436
  function buildLineGenerator(format, scales) {
2257
2437
  return line()
2438
+ // A point with no numeric value leaves a gap rather than a NaN in the path, which browsers stop
2439
+ // drawing at - hiding the rest of the line.
2440
+ .defined(hasValue)
2258
2441
  .x((d, i) => {
2259
2442
  return getXFormat(format, d, i, scales.x);
2260
2443
  })
@@ -2265,6 +2448,9 @@ function buildLineGenerator(format, scales) {
2265
2448
 
2266
2449
  function buildAreaGenerator(format, scales, chartHeight) {
2267
2450
  return area()
2451
+ // A point with no numeric value leaves a gap rather than a NaN in the path, which browsers stop
2452
+ // drawing at - hiding the rest of the area.
2453
+ .defined(hasValue)
2268
2454
  .x((d, i) => {
2269
2455
  return getXFormat(format, d, i, scales.x);
2270
2456
  })
@@ -2619,6 +2805,8 @@ class PlaChartBuilder extends PcacChart {
2619
2805
  dotClicked$ = this.dotClickedSource.asObservable();
2620
2806
  buildChart(chartElm, config, type) {
2621
2807
  if (!config?.data?.length) {
2808
+ this.leavePoint();
2809
+ this.clearChart(chartElm);
2622
2810
  return;
2623
2811
  }
2624
2812
  // A rebuild throws the hovered point away with everything else, and a removed element gets
@@ -2639,12 +2827,7 @@ class PlaChartBuilder extends PcacChart {
2639
2827
  if (!this.initializeChartState(chartElm, this.config)) {
2640
2828
  return;
2641
2829
  }
2642
- // `?.length`, not a bare truthiness check: PcacLineAreaChartConfig defaults colorOverride to
2643
- // `[]`, and an empty array is truthy - a config built with `new` would otherwise replace the
2644
- // theme palette with nothing and every series would render with no color at all.
2645
- if (this.config.colorOverride?.length) {
2646
- this.colors = this.config.colorOverride;
2647
- }
2830
+ this.applyColorOverride(this.config.colorOverride);
2648
2831
  this.scales = new PlaChartScalesBuilder().build(this.xAxis, this.yAxis, this.config.data, this.width, this.height);
2649
2832
  this.lineGenerator = buildLineGenerator(this.xAxis.format, this.scales);
2650
2833
  this.areaGenerator = buildAreaGenerator(this.xAxis.format, this.scales, this.height);
@@ -2940,7 +3123,7 @@ class PlaChartBuilder extends PcacChart {
2940
3123
  if (!node) {
2941
3124
  return;
2942
3125
  }
2943
- const group = select$1(node);
3126
+ const group = select(node);
2944
3127
  const { x, y } = this.pointPosition(point, index, scales);
2945
3128
  const extent = rangeExtent(point, x, y, this.xAxis.format, scales);
2946
3129
  if (!extent) {
@@ -2959,7 +3142,7 @@ class PlaChartBuilder extends PcacChart {
2959
3142
  this.svg.selectAll('.point-range.is-focused').classed('is-focused', false);
2960
3143
  const node = d ? this.rangeGroupOf.get(d) : undefined;
2961
3144
  if (node) {
2962
- select$1(node).classed('is-focused', true);
3145
+ select(node).classed('is-focused', true);
2963
3146
  }
2964
3147
  this.svg.select('.point-ranges').classed('has-focus', !!node);
2965
3148
  }
@@ -3057,12 +3240,12 @@ class PlaChartBuilder extends PcacChart {
3057
3240
  valueFormat: self.yAxis.format,
3058
3241
  keyFormat: self.xAxis.format,
3059
3242
  // The dot or image itself rather than the group, so the tooltip clears what's drawn.
3060
- anchor: select$1(this).select('.dot, .dot-image').node(),
3243
+ anchor: select(this).select('.dot, .dot-image').node(),
3061
3244
  });
3062
3245
  // No-op for an image point (no circle inside to grow). Its own transition name, so it
3063
3246
  // runs alongside the enter rise rather than cancelling it (see DOT_HOVER_TRANSITION);
3064
3247
  // it only takes over the entry's size tween, which it would otherwise fight over `r`.
3065
- select$1(this).select('.dot')
3248
+ select(this).select('.dot')
3066
3249
  .interrupt(DOT_GROW_TRANSITION)
3067
3250
  .transition(DOT_HOVER_TRANSITION)
3068
3251
  .duration(duration / 3)
@@ -3118,7 +3301,7 @@ class PlaChartBuilder extends PcacChart {
3118
3301
  this.hoveredPoint = null;
3119
3302
  this.hideTooltip();
3120
3303
  this.focusPointRange(null);
3121
- select$1(point).select('.dot')
3304
+ select(point).select('.dot')
3122
3305
  .interrupt(DOT_GROW_TRANSITION)
3123
3306
  .transition(DOT_HOVER_TRANSITION)
3124
3307
  .duration(this.transitionService.getTransitionDuration() / 3)
@@ -3252,7 +3435,8 @@ class PcacLineAreaChartComponent {
3252
3435
  }
3253
3436
  buildChart() {
3254
3437
  const config = this.config();
3255
- if (config && config.data && config.data.length > 0) {
3438
+ // Handed over even when empty: the builder clears what it last drew rather than leaving it.
3439
+ if (config) {
3256
3440
  this.chartBuilder.buildChart(this.chartElm(), config, this.type());
3257
3441
  }
3258
3442
  }
@@ -3335,6 +3519,57 @@ class PcacAreaChartConfig extends PcacLineAreaChartConfig {
3335
3519
  // the point-image and point-range types are part of those configs' public shape, so they're
3336
3520
  // exported alone.
3337
3521
 
3522
+ /**
3523
+ * Turns the pie into a donut: slices drawn as a ring around an empty center, which can hold a
3524
+ * short label - typically the total the slices add up to.
3525
+ */
3526
+ class PcacPieDonutConfig {
3527
+ /**
3528
+ * Radius of the hole as a fraction of the pie's radius, from 0 (a plain pie) to 0.9. Values
3529
+ * outside that range are clamped.
3530
+ */
3531
+ innerRadius = 0.6;
3532
+ /**
3533
+ * Large text centered in the hole, e.g. `'67'`. Sized to the hole and shrunk to fit across it;
3534
+ * left out if it would have to go below 8px. Not drawn when not set.
3535
+ */
3536
+ label;
3537
+ /** Smaller line under `label`, e.g. `'balls'`, fitted the same way. Not drawn when not set. */
3538
+ subLabel;
3539
+ /**
3540
+ * `label` color, any CSS color; theme default `$gray-800`. Applied as
3541
+ * `--pcac-pie-center-label-color` on the chart's `.pcac-pie-center` group, so a stylesheet can
3542
+ * set it on an ancestor instead (a config value wins).
3543
+ */
3544
+ labelColor;
3545
+ /** `subLabel` color, likewise (`--pcac-pie-center-sub-label-color`); theme default `$gray-600`. */
3546
+ subLabelColor;
3547
+ }
3548
+ class PcacPieChartConfig extends PcacChartConfig {
3549
+ /**
3550
+ * Draw the pie as a donut. Off when not set; `{}` turns it on with every `PcacPieDonutConfig`
3551
+ * default. Slices, hover and `sliceClicked` behave the same either way.
3552
+ */
3553
+ donut;
3554
+ /**
3555
+ * Slice colors, any CSS color, in data order - the first slice takes the first color - in place
3556
+ * of the theme palette. Repeated when there are more slices than colors. Omitted or empty, the
3557
+ * theme palette is used. Match a `<pcac-legend>` to it with each item's `colorOverride`.
3558
+ */
3559
+ colorOverride;
3560
+ }
3561
+
3562
+ /** The largest `PcacPieDonutConfig.innerRadius` honored, so a ring is always left to draw. */
3563
+ const MAX_DONUT_INNER_RADIUS = 0.9;
3564
+ /** Smallest font a center line is drawn at; a line that can't fit the hole at this size is left out. */
3565
+ const MIN_CENTER_FONT_SIZE = 8;
3566
+ /** Share of the hole's diameter the center text may span, leaving a margin inside the ring. */
3567
+ const CENTER_TEXT_WIDTH = 1.6;
3568
+ /**
3569
+ * Average glyph width as a fraction of font size. Only used where text can't be measured (no
3570
+ * layout, e.g. jsdom); in a browser each line is measured and scaled to fit instead.
3571
+ */
3572
+ const ESTIMATED_GLYPH_WIDTH = 0.6;
3338
3573
  /**
3339
3574
  * Provided per-component (see PcacPieChartComponent's `providers`), not root-scoped:
3340
3575
  * this builder extends PcacChart, which holds mutable per-chart-instance state (margin, width,
@@ -3343,6 +3578,7 @@ class PcacAreaChartConfig extends PcacLineAreaChartConfig {
3343
3578
  */
3344
3579
  class PieChartBuilder extends PcacChart {
3345
3580
  radius;
3581
+ innerRadius = 0;
3346
3582
  arcShape;
3347
3583
  arcOverShape;
3348
3584
  pieAngles;
@@ -3350,6 +3586,7 @@ class PieChartBuilder extends PcacChart {
3350
3586
  sliceClicked$ = this.sliceClickedSource.asObservable();
3351
3587
  buildChart(chartElm, config) {
3352
3588
  if (!config?.data?.length) {
3589
+ this.clearChart(chartElm);
3353
3590
  return;
3354
3591
  }
3355
3592
  // The pie deliberately opts out of `heightFull`: `height` here feeds the radius rather than a
@@ -3360,21 +3597,31 @@ class PieChartBuilder extends PcacChart {
3360
3597
  if (!this.initializeChartState(chartElm, { ...config, heightFull: false })) {
3361
3598
  return;
3362
3599
  }
3600
+ this.applyColorOverride(config.colorOverride);
3363
3601
  this.radius = Math.min(Math.min(this.height, this.width), Math.min(this.height, this.width)) / 2;
3364
- this.buildShapes();
3602
+ this.buildShapes(config.donut);
3365
3603
  this.drawChart(chartElm, config);
3604
+ if (config.donut && this.innerRadius > 0) {
3605
+ this.drawCenter(config.donut);
3606
+ }
3366
3607
  }
3367
- buildShapes() {
3608
+ buildShapes(donut) {
3368
3609
  const radiusOffset = 10;
3610
+ const outerRadius = this.radius - radiusOffset;
3611
+ const ratio = donut ? (donut.innerRadius ?? new PcacPieDonutConfig().innerRadius) : 0;
3612
+ // Sized against the resting slice, so the hole stays put when a hovered slice grows outward.
3613
+ this.innerRadius = Math.max(0, outerRadius * Math.min(Math.max(ratio, 0), MAX_DONUT_INNER_RADIUS));
3369
3614
  this.arcShape = arc()
3370
- .innerRadius(0)
3371
- .outerRadius(this.radius - radiusOffset);
3615
+ .innerRadius(this.innerRadius)
3616
+ .outerRadius(outerRadius);
3372
3617
  this.arcOverShape = arc()
3373
- .innerRadius(0)
3374
- .outerRadius(this.radius - radiusOffset + radiusOffset);
3618
+ .innerRadius(this.innerRadius)
3619
+ .outerRadius(outerRadius + radiusOffset);
3375
3620
  this.pieAngles = pie()
3376
3621
  .sort(null)
3377
- .value((d) => d.value);
3622
+ // A hidden slice takes no angle but keeps its index - and so its color, matching a legend -
3623
+ // the same way a hidden line/area/plot series keeps its place.
3624
+ .value((d) => (d.hide ? 0 : Number(d.value ?? 0)));
3378
3625
  }
3379
3626
  drawChart(chartElm, config) {
3380
3627
  this.buildContainer(chartElm, true);
@@ -3391,7 +3638,7 @@ class PieChartBuilder extends PcacChart {
3391
3638
  const t = transition().duration(self.transitionService.getTransitionDuration() / 3);
3392
3639
  const c = color(self.colors[d.index]);
3393
3640
  const ct = c ? c.darker(1).toString() : self.colors[d.index];
3394
- select$1(this).transition(t)
3641
+ select(this).transition(t)
3395
3642
  .attr('d', self.arcOverShape)
3396
3643
  .style('fill', ct);
3397
3644
  })
@@ -3400,7 +3647,7 @@ class PieChartBuilder extends PcacChart {
3400
3647
  })
3401
3648
  .on('mouseout', function (_, d) {
3402
3649
  self.hideTooltip();
3403
- select$1(this)
3650
+ select(this)
3404
3651
  .transition()
3405
3652
  .duration(self.transitionService.getTransitionDuration() / 3)
3406
3653
  .attr('d', self.arcShape)
@@ -3415,10 +3662,62 @@ class PieChartBuilder extends PcacChart {
3415
3662
  return this.tweenChart(b);
3416
3663
  });
3417
3664
  }
3665
+ /**
3666
+ * The donut's `label` / `subLabel`, stacked around the center of the hole. Each line starts at a
3667
+ * size proportional to the hole and shrinks until it fits across it; a line that would have to
3668
+ * drop below `MIN_CENTER_FONT_SIZE` is left out rather than spill over the slices. Drawn after
3669
+ * the slices and ignoring the pointer, so it never blocks a slice's hover or click.
3670
+ */
3671
+ drawCenter(donut) {
3672
+ if (!donut.label && !donut.subLabel) {
3673
+ return;
3674
+ }
3675
+ const maxWidth = this.innerRadius * CENTER_TEXT_WIDTH;
3676
+ const center = this.svg.append('g')
3677
+ .attr('class', 'pcac-pie-center')
3678
+ .attr('pointer-events', 'none')
3679
+ .style('--pcac-pie-center-label-color', () => donut.labelColor ?? null)
3680
+ .style('--pcac-pie-center-sub-label-color', () => donut.subLabelColor ?? null);
3681
+ const label = this.drawCenterLine(center, 'pcac-pie-center-label', donut.label, Math.min(this.innerRadius * 0.5, 40), maxWidth);
3682
+ const subLabel = this.drawCenterLine(center, 'pcac-pie-center-sub-label', donut.subLabel, Math.min(this.innerRadius * 0.2, 16), maxWidth);
3683
+ if (!label && !subLabel) {
3684
+ center.remove();
3685
+ return;
3686
+ }
3687
+ // Stacked as a pair about the center; a line on its own sits on it.
3688
+ if (label && subLabel) {
3689
+ label.element.attr('y', -subLabel.size * 0.6);
3690
+ subLabel.element.attr('y', label.size * 0.55);
3691
+ }
3692
+ }
3693
+ /**
3694
+ * One centered line of the donut's center text at the largest size up to `preferredSize` that
3695
+ * fits `maxWidth`, or nothing (null) when there's no text or it can't fit at a readable size.
3696
+ */
3697
+ drawCenterLine(center, className, text, preferredSize, maxWidth) {
3698
+ if (!text || preferredSize < MIN_CENTER_FONT_SIZE) {
3699
+ return null;
3700
+ }
3701
+ const element = center.append('text')
3702
+ .attr('class', className)
3703
+ .attr('text-anchor', 'middle')
3704
+ .attr('dominant-baseline', 'central')
3705
+ .style('font-size', `${preferredSize}px`)
3706
+ .text(text);
3707
+ const node = element.node();
3708
+ const measured = node && typeof node.getComputedTextLength === 'function'
3709
+ ? node.getComputedTextLength()
3710
+ : 0;
3711
+ const width = measured > 0 ? measured : text.length * preferredSize * ESTIMATED_GLYPH_WIDTH;
3712
+ const size = width > maxWidth ? preferredSize * (maxWidth / width) : preferredSize;
3713
+ if (size < MIN_CENTER_FONT_SIZE) {
3714
+ element.remove();
3715
+ return null;
3716
+ }
3717
+ element.style('font-size', `${size}px`);
3718
+ return { element, size };
3719
+ }
3418
3720
  tweenChart(b) {
3419
- // `innerRadius`/`outerRadius` aren't part of PieArcDatum - arcShape's own .innerRadius()/.outerRadius()
3420
- // accessors are fixed constants and never read them from the datum, so this is a legacy no-op kept for parity.
3421
- b.innerRadius = 0;
3422
3721
  const i = interpolate({ startAngle: 0, endAngle: 0 }, b);
3423
3722
  return (t) => this.arcShape(i(t)) ?? '';
3424
3723
  }
@@ -3461,7 +3760,8 @@ class PcacPieChartComponent {
3461
3760
  }
3462
3761
  buildChart() {
3463
3762
  const config = this.config();
3464
- if (config && config.data && config.data.length > 0) {
3763
+ // Handed over even when empty: the builder clears what it last drew rather than leaving it.
3764
+ if (config) {
3465
3765
  this.chartBuilder.buildChart(this.chartElm(), config);
3466
3766
  }
3467
3767
  }
@@ -3473,9 +3773,6 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.1.7", ngImpor
3473
3773
  args: [{ selector: 'pcac-pie-chart', encapsulation: ViewEncapsulation.None, providers: [PieChartBuilder], template: "<section class=\"pcac-pie-chart\">\n <svg #chart></svg>\n</section>\n\n", styles: [".pcac-pie-chart svg{width:100%;display:block}.pcac-pie-chart .dot{fill:none;stroke-width:1px}\n"] }]
3474
3774
  }], ctorParameters: () => [], propDecorators: { config: [{ type: i0.Input, args: [{ isSignal: true, alias: "config", required: true }] }], chartElm: [{ type: i0.ViewChild, args: ['chart', { isSignal: true }] }], sliceClicked: [{ type: i0.Output, args: ["sliceClicked"] }], tooltipTemplate: [{ type: i0.ContentChild, args: [i0.forwardRef(() => PcacTooltipDirective), { isSignal: true }] }] } });
3475
3775
 
3476
- class PcacPieChartConfig extends PcacChartConfig {
3477
- }
3478
-
3479
3776
  /*
3480
3777
  * Public API Surface of pioneer-charts
3481
3778
  */
@@ -3484,5 +3781,5 @@ class PcacPieChartConfig extends PcacChartConfig {
3484
3781
  * Generated bundle index. Do not edit.
3485
3782
  */
3486
3783
 
3487
- export { BarHorizontalChartBuilder, BarVerticalChartBuilder, PCAC_AXIS_LABEL_SPACE, PCAC_AXIS_SUB_LABEL_SPACE, PcacAreaChart, PcacAreaChartConfig, PcacAxisBuilder, PcacAxisChartConfig, PcacAxisConfig, PcacAxisSubLabels, PcacBarHorizontalChartColorOverrideConfig, PcacBarHorizontalChartComponent, PcacBarHorizontalChartConfig, PcacBarVerticalChartColorOverrideConfig, PcacBarVerticalChartComponent, PcacBarVerticalChartConfig, PcacChart, PcacChartConfig, PcacChartResizeService, PcacColorService, PcacData, PcacDataRange, PcacFormatEnum, PcacGridBuilder, PcacLegend, PcacLegendConfig, PcacLegendConfigItem, PcacLineChart, PcacLineChartConfig, PcacPieChartComponent, PcacPieChartConfig, PcacPlotChart, PcacPlotChartConfig, PcacPointFanOutConfig, PcacPointImageConfig, PcacPointRangeConfig, PcacPointRangeShow, PcacPointRangeStyle, PcacRangeBounds, PcacTooltipBuilder, PcacTooltipDirective, PcacTransitionService, PieChartBuilder, axisLabelSpace, hasAxisSubLabels, resolveAxisConfig };
3784
+ export { BarHorizontalChartBuilder, BarVerticalChartBuilder, PCAC_AXIS_LABEL_SPACE, PCAC_AXIS_SUB_LABEL_SPACE, PcacAreaChart, PcacAreaChartConfig, PcacAxisBuilder, PcacAxisChartConfig, PcacAxisConfig, PcacAxisSubLabels, PcacBarHorizontalChartColorOverrideConfig, PcacBarHorizontalChartComponent, PcacBarHorizontalChartConfig, PcacBarVerticalChartColorOverrideConfig, PcacBarVerticalChartComponent, PcacBarVerticalChartConfig, PcacChart, PcacChartConfig, PcacChartResizeService, PcacColorService, PcacData, PcacDataRange, PcacFormatEnum, PcacGridBuilder, PcacLegend, PcacLegendConfig, PcacLegendConfigItem, PcacLineChart, PcacLineChartConfig, PcacPieChartComponent, PcacPieChartConfig, PcacPieDonutConfig, PcacPlotChart, PcacPlotChartConfig, PcacPointFanOutConfig, PcacPointImageConfig, PcacPointRangeConfig, PcacPointRangeShow, PcacPointRangeStyle, PcacRangeBounds, PcacTooltipBuilder, PcacTooltipDirective, PcacTransitionService, PieChartBuilder, axisLabelSpace, hasAxisSubLabels, resolveAxisConfig };
3488
3785
  //# sourceMappingURL=pioneer-code-pioneer-charts.mjs.map