@redvars/peacock 3.15.0 → 3.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (157) hide show
  1. package/dist/assets/styles.css +1 -1
  2. package/dist/assets/styles.css.map +1 -1
  3. package/dist/assets/theme.js +19 -19
  4. package/dist/assets/tokens.css +1 -1
  5. package/dist/assets/tokens.css.map +1 -1
  6. package/dist/card-content.js +8 -7
  7. package/dist/card-content.js.map +1 -1
  8. package/dist/card.js +142 -98
  9. package/dist/card.js.map +1 -1
  10. package/dist/{chart-bar-D5dGFJfK.js → cartesian-chart-DgE4USyC.js} +529 -312
  11. package/dist/cartesian-chart-DgE4USyC.js.map +1 -0
  12. package/dist/chart-area.js +78 -0
  13. package/dist/chart-area.js.map +1 -0
  14. package/dist/chart-bar.js +283 -213
  15. package/dist/chart-bar.js.map +1 -1
  16. package/dist/{transform-DSwFSqzD.js → chart-base-C2qRMF48.js} +771 -102
  17. package/dist/chart-base-C2qRMF48.js.map +1 -0
  18. package/dist/chart-doughnut.js +55 -287
  19. package/dist/chart-doughnut.js.map +1 -1
  20. package/dist/chart-line.js +626 -0
  21. package/dist/chart-line.js.map +1 -0
  22. package/dist/chart-pie.js +637 -195
  23. package/dist/chart-pie.js.map +1 -1
  24. package/dist/code-editor.js +704 -131
  25. package/dist/code-editor.js.map +1 -1
  26. package/dist/code-group.js +188 -0
  27. package/dist/code-group.js.map +1 -0
  28. package/dist/code-highlighter.js +895 -257
  29. package/dist/code-highlighter.js.map +1 -1
  30. package/dist/custom-elements-jsdocs.json +2278 -677
  31. package/dist/custom-elements.json +13962 -3690
  32. package/dist/image.js +5 -1
  33. package/dist/image.js.map +1 -1
  34. package/dist/index.js +8 -7
  35. package/dist/index.js.map +1 -1
  36. package/dist/loader-full.js +1 -1
  37. package/dist/loader.js +9 -3
  38. package/dist/loader.js.map +1 -1
  39. package/dist/{is-dark-mode-DOcaw4Yq.js → observe-theme-change-DCifz1uv.js} +2 -6
  40. package/dist/observe-theme-change-DCifz1uv.js.map +1 -0
  41. package/dist/pagination.js +408 -110
  42. package/dist/pagination.js.map +1 -1
  43. package/dist/path-CJ0Arqcy.js +166 -0
  44. package/dist/path-CJ0Arqcy.js.map +1 -0
  45. package/dist/snackbar.js +89 -34
  46. package/dist/snackbar.js.map +1 -1
  47. package/dist/src/__internal/chart/cartesian-chart.d.ts +80 -0
  48. package/dist/src/__internal/chart/chart-base.d.ts +113 -0
  49. package/dist/src/__internal/chart/paths.d.ts +5 -0
  50. package/dist/src/__internal/chart/types.d.ts +42 -0
  51. package/dist/src/card/card-content.d.ts +2 -3
  52. package/dist/src/card/card.d.ts +31 -17
  53. package/dist/src/chart-area/chart-area.d.ts +54 -0
  54. package/dist/src/chart-area/index.d.ts +1 -0
  55. package/dist/src/chart-bar/chart-bar.d.ts +44 -33
  56. package/dist/src/chart-bar/index.d.ts +0 -1
  57. package/dist/src/chart-doughnut/chart-doughnut.d.ts +33 -39
  58. package/dist/src/chart-line/chart-line.d.ts +69 -0
  59. package/dist/src/chart-line/index.d.ts +1 -0
  60. package/dist/src/chart-pie/chart-pie.d.ts +63 -28
  61. package/dist/src/code-editor/code-editor.d.ts +52 -13
  62. package/dist/src/code-editor/editor-theme.d.ts +60 -0
  63. package/dist/src/code-highlighter/code-group.d.ts +52 -0
  64. package/dist/src/code-highlighter/code-highlighter.d.ts +122 -15
  65. package/dist/src/code-highlighter/index.d.ts +1 -0
  66. package/dist/src/code-highlighter/line-ranges.d.ts +24 -0
  67. package/dist/src/code-highlighter/local.d.ts +4 -1
  68. package/dist/src/code-highlighter/token-colors.d.ts +8 -0
  69. package/dist/src/index.d.ts +4 -2
  70. package/dist/src/pagination/page-items.d.ts +14 -0
  71. package/dist/src/pagination/pagination.d.ts +46 -7
  72. package/dist/src/snackbar/snackbar.d.ts +13 -1
  73. package/dist/src/table/table.d.ts +125 -27
  74. package/dist/src/toolbar/toolbar.d.ts +56 -51
  75. package/dist/table.js +1007 -338
  76. package/dist/table.js.map +1 -1
  77. package/dist/test/chart.test.d.ts +1 -0
  78. package/dist/test/code-highlighter.test.d.ts +1 -0
  79. package/dist/test/pagination.test.d.ts +1 -0
  80. package/dist/test/table.test.d.ts +1 -0
  81. package/dist/token-colors-0TFHWbcq.js +81 -0
  82. package/dist/token-colors-0TFHWbcq.js.map +1 -0
  83. package/dist/toolbar.js +195 -184
  84. package/dist/toolbar.js.map +1 -1
  85. package/dist/tsconfig.tsbuildinfo +1 -1
  86. package/package.json +1 -2
  87. package/readme.md +7 -6
  88. package/scss/_code-block.scss +139 -0
  89. package/scss/tokens.css +24 -0
  90. package/src/__internal/chart/cartesian-chart.ts +404 -0
  91. package/src/__internal/chart/chart-base.scss +252 -0
  92. package/src/__internal/chart/chart-base.ts +474 -0
  93. package/src/__internal/chart/paths.ts +28 -0
  94. package/src/__internal/chart/types.ts +49 -0
  95. package/src/card/card-content.ts +12 -9
  96. package/src/card/card.scss +66 -54
  97. package/src/card/card.ts +109 -73
  98. package/src/chart-area/chart-area.ts +82 -0
  99. package/src/chart-area/index.ts +1 -0
  100. package/src/chart-bar/chart-bar.ts +336 -250
  101. package/src/chart-bar/index.ts +0 -1
  102. package/src/chart-doughnut/chart-doughnut.ts +62 -262
  103. package/src/chart-doughnut/demo/index.html +14 -22
  104. package/src/chart-line/chart-line.scss +25 -0
  105. package/src/chart-line/chart-line.ts +346 -0
  106. package/src/chart-line/index.ts +1 -0
  107. package/src/chart-pie/chart-pie.scss +35 -16
  108. package/src/chart-pie/chart-pie.ts +282 -188
  109. package/src/chart-pie/demo/index.html +13 -21
  110. package/src/code-editor/code-editor.scss +132 -36
  111. package/src/code-editor/code-editor.ts +308 -88
  112. package/src/code-editor/demo/index.html +39 -12
  113. package/src/code-editor/editor-theme.ts +213 -0
  114. package/src/code-highlighter/code-group.scss +34 -0
  115. package/src/code-highlighter/code-group.ts +173 -0
  116. package/src/code-highlighter/code-highlighter.scss +226 -111
  117. package/src/code-highlighter/code-highlighter.ts +554 -199
  118. package/src/code-highlighter/demo/index.html +68 -4
  119. package/src/code-highlighter/index.ts +1 -0
  120. package/src/code-highlighter/line-ranges.ts +81 -0
  121. package/src/code-highlighter/local.ts +9 -3
  122. package/src/code-highlighter/token-colors.ts +42 -0
  123. package/src/index.ts +4 -2
  124. package/src/loader.ts +8 -2
  125. package/src/pagination/page-items.ts +50 -0
  126. package/src/pagination/pagination.scss +159 -44
  127. package/src/pagination/pagination.ts +275 -74
  128. package/src/snackbar/demo/index.html +39 -4
  129. package/src/snackbar/snackbar.scss +27 -10
  130. package/src/snackbar/snackbar.ts +80 -37
  131. package/src/table/table.scss +337 -109
  132. package/src/table/table.ts +812 -272
  133. package/src/toolbar/toolbar-colors.scss +6 -7
  134. package/src/toolbar/toolbar.scss +35 -106
  135. package/src/toolbar/toolbar.ts +180 -80
  136. package/dist/array-D5vjT2Xm.js +0 -14
  137. package/dist/array-D5vjT2Xm.js.map +0 -1
  138. package/dist/chart-bar-D5dGFJfK.js.map +0 -1
  139. package/dist/chart-stacked-bar.js +0 -403
  140. package/dist/chart-stacked-bar.js.map +0 -1
  141. package/dist/copy-to-clipboard-upGx-Ueo.js +0 -39
  142. package/dist/copy-to-clipboard-upGx-Ueo.js.map +0 -1
  143. package/dist/is-dark-mode-DOcaw4Yq.js.map +0 -1
  144. package/dist/pie-Dz0IDiPt.js +0 -537
  145. package/dist/pie-Dz0IDiPt.js.map +0 -1
  146. package/dist/pierre-dark-DFWl0m-C.js +0 -4
  147. package/dist/pierre-dark-DFWl0m-C.js.map +0 -1
  148. package/dist/pierre-light-BEkAPImt.js +0 -4
  149. package/dist/pierre-light-BEkAPImt.js.map +0 -1
  150. package/dist/src/chart-bar/chart-stacked-bar.d.ts +0 -78
  151. package/dist/src/code-highlighter/constants.d.ts +0 -1
  152. package/dist/transform-DSwFSqzD.js.map +0 -1
  153. package/src/chart-bar/chart-bar.scss +0 -58
  154. package/src/chart-bar/chart-stacked-bar.ts +0 -398
  155. package/src/chart-doughnut/chart-donut.scss +0 -37
  156. package/src/code-highlighter/constants.ts +0 -117
  157. /package/dist/test/{chart-bar.test.d.ts → card.test.d.ts} +0 -0
@@ -1,296 +1,382 @@
1
- import { html, LitElement, PropertyValues } from 'lit';
2
- import { property, query } from 'lit/decorators.js';
3
- import { styleMap } from 'lit/directives/style-map.js';
4
- import { select, max, scaleBand, scaleLinear, scaleOrdinal, axisLeft, axisBottom, ScaleOrdinal } from 'd3';
1
+ import { property } from 'lit/decorators.js';
2
+ import {
3
+ max,
4
+ min,
5
+ scaleBand,
6
+ scaleLinear,
7
+ stack,
8
+ stackOffsetDiverging,
9
+ } from 'd3';
5
10
  import IndividualComponent from '@/IndividualComponent.js';
6
- import styles from './chart-bar.scss';
11
+ import {
12
+ CartesianChart,
13
+ ChartOrientation,
14
+ } from '../__internal/chart/cartesian-chart.js';
15
+ import { roundedRectPath } from '../__internal/chart/paths.js';
16
+ import baseStyles from '../__internal/chart/chart-base.scss';
17
+
18
+ export type {
19
+ ChartConfig,
20
+ ChartDatum,
21
+ ChartSelectDetail,
22
+ ChartSeriesConfig,
23
+ ChartValueFormatter,
24
+ } from '../__internal/chart/types.js';
25
+
26
+ /** Gap between stacked segments, in pixels. */
27
+ const STACK_GAP = 2;
28
+
29
+ /** Room reserved for value labels at the end of horizontal bars, per character. */
30
+ const VALUE_CHAR_WIDTH = 7;
31
+
32
+ /** One drawn bar or stacked segment. */
33
+ type BarModel = {
34
+ id: string;
35
+ index: number;
36
+ key: string;
37
+ color: string;
38
+ /** Start along the category axis. */
39
+ position: number;
40
+ /** Size along the category axis. */
41
+ thickness: number;
42
+ /** Value the bar starts at. */
43
+ from: number;
44
+ /** Value the bar ends at. */
45
+ to: number;
46
+ /** Whether the end away from zero is rounded. */
47
+ rounded: boolean;
48
+ /** Pixels trimmed from the zero-side end, to separate stacked segments. */
49
+ gap: number;
50
+ };
7
51
 
8
- export type ChartBarItem = {
9
- name: string;
52
+ /** A value label at the end of a bar or stack. */
53
+ type ValueLabelModel = {
54
+ id: string;
55
+ index: number;
10
56
  value: number;
11
- label?: string;
12
- color?: string;
57
+ /** Center along the category axis. */
58
+ center: number;
13
59
  };
14
60
 
15
- const chartColors: string[] = [];
16
- ['purple', 'blue', 'red', 'green', 'yellow', 'orange'].forEach(colorName => {
17
- chartColors.push(`var(--color-${colorName})`);
18
- });
19
-
20
- const DEFAULT_WIDTH = 480;
21
- const DEFAULT_HEIGHT = 320;
22
- const BAR_RADIUS = 10;
23
- const DURATION = 450;
24
-
25
- function debounce<T extends (...args: any[]) => void>(fn: T, wait: number): T {
26
- let timer: ReturnType<typeof setTimeout>;
27
- return ((...args: any[]) => {
28
- clearTimeout(timer);
29
- timer = setTimeout(() => fn(...args), wait);
30
- }) as T;
31
- }
32
-
33
61
  /**
34
- * @label Chart Bar
62
+ * @label Bar Chart
35
63
  * @tag wc-chart-bar
36
64
  * @rawTag chart-bar
37
- * @summary A vertical bar chart that follows color and spacing tokens.
65
+ * @summary Compares values across categories with vertical or horizontal bars, grouped or stacked by series.
38
66
  * @tags charts
39
67
  *
40
68
  * @example
41
69
  * ```html
42
- * <wc-chart-bar width="520" height="320"></wc-chart-bar>
70
+ * <wc-chart-bar index="month" label="Visitors by month"></wc-chart-bar>
43
71
  * <script>
44
- * document.querySelector('wc-chart-bar').data = [
45
- * { name: 'apples', label: 'Apples', value: 20 },
46
- * { name: 'bananas', label: 'Bananas', value: 35 },
47
- * { name: 'cherries', label: 'Cherries', value: 15 },
72
+ * const chart = document.querySelector('wc-chart-bar');
73
+ * chart.config = {
74
+ * desktop: { label: 'Desktop' },
75
+ * mobile: { label: 'Mobile' },
76
+ * };
77
+ * chart.data = [
78
+ * { month: 'January', desktop: 186, mobile: 80 },
79
+ * { month: 'February', desktop: 305, mobile: 200 },
80
+ * { month: 'March', desktop: 237, mobile: 120 },
48
81
  * ];
49
82
  * </script>
50
83
  * ```
84
+ *
85
+ * @slot empty - Shown when there is no data. Defaults to "No data".
86
+ *
87
+ * @fires chart-select - A bar group was clicked or chosen with Enter. `detail` holds `index` and `datum`.
88
+ *
89
+ * @csspart container - The outer wrapper.
90
+ * @csspart plot - The focusable plot area holding the SVG.
91
+ * @csspart tooltip - The tooltip.
92
+ * @csspart legend - The legend.
93
+ *
94
+ * @cssprop --color-chart-1 - Color of the first series; series cycle through `--color-chart-1` to `--color-chart-8`.
95
+ * @cssprop --chart-grid-color - Gridline and baseline color. Defaults to `--color-outline-variant`.
96
+ * @cssprop --chart-axis-color - Axis label color. Defaults to `--color-on-surface-variant`.
97
+ * @cssprop --chart-dim-opacity - Opacity of marks that are not hovered. Defaults to `0.4`.
51
98
  */
52
99
  @IndividualComponent
53
- export class ChartBar extends LitElement {
54
- static styles = [styles];
100
+ export class ChartBar extends CartesianChart {
101
+ // ── Static
55
102
 
56
- @query('svg')
57
- private svgElement?: SVGElement;
103
+ static styles = [baseStyles];
58
104
 
59
- /** Width of the chart in pixels. */
60
- @property({ type: Number, reflect: true }) width: number = 0;
105
+ // ── Properties
61
106
 
62
- /** Height of the chart in pixels. */
63
- @property({ type: Number, reflect: true }) height: number = DEFAULT_HEIGHT;
107
+ /** Stacks the series in each category instead of placing them side by side. */
108
+ @property({ type: Boolean, reflect: true }) stacked: boolean = false;
64
109
 
65
- /** Margin around the chart drawing area. */
66
- @property({ type: Number }) margin: number = 24;
110
+ /** `vertical` draws columns; `horizontal` draws bars from the left. */
111
+ @property({ type: String, reflect: true }) orientation: ChartOrientation =
112
+ 'vertical';
67
113
 
68
- /** Chart data array. Each item should have name, value, and optional label and color. */
69
- @property({ type: Array }) data: ChartBarItem[] = [];
114
+ /** Prints each bar's value (each stack's total when stacked) at its end. */
115
+ @property({ type: Boolean, attribute: 'show-values' }) showValues: boolean =
116
+ false;
70
117
 
71
- /** Whether to render value labels above bars. */
72
- @property({ type: Boolean, attribute: 'show-values' }) showValues: boolean = true;
118
+ // ── Private fields
73
119
 
74
- private _initialized = false;
120
+ /** Bars from the last draw, for highlighting. */
121
+ private bars: BarModel[] = [];
75
122
 
76
- private _debouncedRenderChart = debounce(() => {
77
- this._renderChart(true);
78
- }, 200);
79
-
80
- firstUpdated() {
81
- this._renderChart(false);
82
- }
123
+ // ── Private methods
83
124
 
84
- updated(changedProperties: PropertyValues) {
85
- if (!this._initialized) {
86
- this._initialized = true;
87
- return;
88
- }
89
- const watchedProps = ['width', 'height', 'margin', 'data', 'showValues'];
90
- const hasChanged = watchedProps.some(prop => changedProperties.has(prop));
91
- if (hasChanged) {
92
- this._debouncedRenderChart();
93
- }
125
+ protected drawProperties(): string[] {
126
+ return [...super.drawProperties(), 'stacked', 'orientation', 'showValues'];
94
127
  }
95
128
 
96
- private _getPaletteScale() {
97
- return scaleOrdinal<string, string>()
98
- .domain(this.data.map(d => d.name))
99
- .range(chartColors);
129
+ /** Corner radius of the rounded end, from `--shape-corner-extra-small`. */
130
+ private cornerRadius(): number {
131
+ const value = parseFloat(
132
+ getComputedStyle(this).getPropertyValue('--shape-corner-extra-small'),
133
+ );
134
+ return Number.isFinite(value) ? value : 4;
100
135
  }
101
136
 
102
- private _resolveColor(
103
- name: string,
104
- override: string | undefined,
105
- scale: ScaleOrdinal<string, string>,
106
- ) {
107
- return override || scale(name);
137
+ /** Bars and value labels in data space; positions are filled once scales exist. */
138
+ private buildModels() {
139
+ const series = this.visibleSeries();
140
+ const keys = series.map(s => s.key);
141
+ const colors = new Map(series.map(s => [s.key, s.color]));
142
+ const bars: Omit<BarModel, 'position' | 'thickness'>[] = [];
143
+ const labels: Omit<ValueLabelModel, 'center'>[] = [];
144
+
145
+ if (this.stacked) {
146
+ const layers = stack<Record<string, unknown>, string>()
147
+ .keys(keys)
148
+ .value((d, key) => this.seriesValue(d, key))
149
+ .offset(stackOffsetDiverging)(this.data);
150
+ this.data.forEach((datum, index) => {
151
+ // Segments run from the zero side (`from`) outwards (`to`).
152
+ const segments = layers
153
+ .map(layer => {
154
+ const [a, b] = layer[index];
155
+ const positive = this.seriesValue(datum, layer.key) >= 0;
156
+ return {
157
+ key: layer.key,
158
+ from: positive ? Math.min(a, b) : Math.max(a, b),
159
+ to: positive ? Math.max(a, b) : Math.min(a, b),
160
+ };
161
+ })
162
+ .filter(segment => segment.from !== segment.to);
163
+ // The outermost segment on each side of zero gets the rounded end.
164
+ const top = segments
165
+ .filter(s => s.to > 0)
166
+ .sort((a, b) => b.to - a.to)[0]?.key;
167
+ const bottom = segments
168
+ .filter(s => s.to < 0)
169
+ .sort((a, b) => a.to - b.to)[0]?.key;
170
+ segments.forEach(segment => {
171
+ bars.push({
172
+ id: `${index}:${segment.key}`,
173
+ index,
174
+ key: segment.key,
175
+ color: colors.get(segment.key) ?? '',
176
+ from: segment.from,
177
+ to: segment.to,
178
+ rounded: segment.key === (segment.to > 0 ? top : bottom),
179
+ gap: segment.from !== 0 ? STACK_GAP : 0,
180
+ });
181
+ });
182
+ labels.push({
183
+ id: String(index),
184
+ index,
185
+ value: keys.reduce(
186
+ (sum, key) => sum + this.seriesValue(datum, key),
187
+ 0,
188
+ ),
189
+ });
190
+ });
191
+ } else {
192
+ this.data.forEach((datum, index) => {
193
+ keys.forEach(key => {
194
+ const value = this.seriesValue(datum, key);
195
+ bars.push({
196
+ id: `${index}:${key}`,
197
+ index,
198
+ key,
199
+ color: colors.get(key) ?? '',
200
+ from: 0,
201
+ to: value,
202
+ rounded: true,
203
+ gap: 0,
204
+ });
205
+ labels.push({ id: `${index}:${key}`, index, value });
206
+ });
207
+ });
208
+ }
209
+ return { keys, bars, labels };
108
210
  }
109
211
 
110
- private _renderChart(animate: boolean) {
111
- if (!this.svgElement) return;
112
-
113
- const width = this.width > 0 ? this.width : DEFAULT_WIDTH;
114
- const height = this.height > 0 ? this.height : DEFAULT_HEIGHT;
115
- const margin = Math.max(this.margin, 12);
116
- const data = this.data ?? [];
117
-
118
- const svg = select(this.svgElement);
119
- svg.attr('width', width).attr('height', height);
120
-
121
- const innerWidth = Math.max(width - margin * 2, 0);
122
- const innerHeight = Math.max(height - margin * 2, 0);
123
- const colorScale = this._getPaletteScale();
124
-
125
- const container = svg.select<SVGGElement>('.chart-container');
126
- container.attr('transform', `translate(${margin},${margin})`);
127
-
128
- if (!data.length || innerWidth === 0 || innerHeight === 0) {
129
- container.select('.bars').selectAll('*').remove();
130
- container.select('.x-axis').selectAll('*').remove();
131
- container.select('.y-grid').selectAll('*').remove();
132
- container.select('.value-labels').selectAll('*').remove();
133
- return;
212
+ protected draw(animate: boolean): void {
213
+ const root = this.plotArea();
214
+ if (!root) return;
215
+ const vertical = this.orientation !== 'horizontal';
216
+ const { keys, bars, labels } = this.buildModels();
217
+
218
+ const ends = bars.flatMap(bar => [bar.from, bar.to]);
219
+ const valueScale = scaleLinear()
220
+ .domain([Math.min(min(ends) ?? 0, 0), Math.max(max(ends) ?? 0, 0) || 1])
221
+ .nice(5);
222
+
223
+ const longestValue = Math.max(
224
+ ...labels.map(l => this.formatValue(l.value).length),
225
+ 1,
226
+ );
227
+ // Vertical charts only need a flag for headroom; horizontal ones need the label width.
228
+ let valueLabelSpace = 0;
229
+ if (this.showValues) {
230
+ valueLabelSpace = vertical ? 1 : longestValue * VALUE_CHAR_WIDTH + 8;
134
231
  }
135
-
136
- const xScale = scaleBand<string>()
137
- .domain(data.map(d => d.name))
138
- .range([0, innerWidth])
139
- .padding(0.28);
140
-
141
- const maxValue = max(data, d => d.value) ?? 0;
142
- const yScale = scaleLinear()
143
- .domain([0, maxValue || 1])
144
- .nice()
145
- .range([innerHeight, 0]);
146
-
147
- const yGrid = container.select<SVGGElement>('.y-grid');
148
- yGrid
149
- .call(
150
- axisLeft(yScale)
151
- .ticks(5)
152
- .tickSize(-innerWidth)
153
- .tickFormat(() => ''),
154
- )
155
- .selectAll('.tick text')
156
- .remove();
157
- yGrid.select('.domain').remove();
158
- yGrid.selectAll('.tick line').attr('class', 'gridline');
159
-
160
- const xAxis = container.select<SVGGElement>('.x-axis');
161
- xAxis
162
- .attr('transform', `translate(0,${innerHeight})`)
163
- .call(
164
- axisBottom(xScale)
165
- .tickSizeOuter(0)
166
- .tickFormat(name => {
167
- const entry = data.find(d => d.name === name);
168
- return entry?.label ?? name;
169
- }),
232
+ this.computeLayout(valueScale, valueLabelSpace);
233
+ const { left, top, innerWidth, innerHeight } = this.layout;
234
+
235
+ const categoryScale = scaleBand<string>()
236
+ .domain(this.categoryDomain())
237
+ .range([0, vertical ? innerWidth : innerHeight])
238
+ .paddingInner(keys.length > 1 && !this.stacked ? 0.2 : 0.3)
239
+ .paddingOuter(0.15);
240
+ valueScale.range(vertical ? [innerHeight, 0] : [0, innerWidth]);
241
+ this.drawFrame(categoryScale, valueScale);
242
+
243
+ const groupScale = scaleBand<string>()
244
+ .domain(this.stacked ? ['all'] : keys)
245
+ .range([0, categoryScale.bandwidth()])
246
+ .padding(this.stacked || keys.length < 2 ? 0 : 0.1);
247
+
248
+ const placed: BarModel[] = bars.map(bar => ({
249
+ ...bar,
250
+ position:
251
+ (categoryScale(String(bar.index)) ?? 0) +
252
+ (groupScale(this.stacked ? 'all' : bar.key) ?? 0),
253
+ thickness: groupScale.bandwidth(),
254
+ }));
255
+ this.bars = placed;
256
+
257
+ const radius = this.cornerRadius();
258
+ const path = (bar: BarModel, grown: boolean) => {
259
+ const zero = valueScale(0);
260
+ const start = valueScale(grown ? bar.from : 0);
261
+ const end = valueScale(grown ? bar.to : 0);
262
+ const r = bar.rounded ? Math.min(radius, bar.thickness / 2) : 0;
263
+ // Positive bars end up/right; negative ones down/left.
264
+ const positive = bar.to >= bar.from;
265
+ const length = Math.max(Math.abs(end - start) - (grown ? bar.gap : 0), 0);
266
+ if (vertical) {
267
+ const y = positive ? end : start + (grown ? bar.gap : 0);
268
+ const base = grown ? y : zero;
269
+ return roundedRectPath(
270
+ bar.position,
271
+ base,
272
+ bar.thickness,
273
+ length,
274
+ positive ? [r, r, 0, 0] : [0, 0, r, r],
275
+ );
276
+ }
277
+ const x = positive ? start + (grown ? bar.gap : 0) : end;
278
+ return roundedRectPath(
279
+ grown ? x : zero,
280
+ bar.position,
281
+ length,
282
+ bar.thickness,
283
+ positive ? [0, r, r, 0] : [r, 0, 0, r],
170
284
  );
171
- xAxis.select('.domain').attr('stroke', 'var(--color-outline-variant)');
172
- xAxis.selectAll('.tick line').remove();
173
- xAxis
174
- .selectAll('.tick text')
175
- .attr('class', 'axis-label')
176
- .attr('dy', '1.1em');
285
+ };
177
286
 
178
- const bars = container
179
- .select('.bars')
180
- .selectAll<SVGRectElement, ChartBarItem>('rect')
181
- .data(data, d => d.name)
182
- .join(
183
- enter =>
184
- enter
185
- .append('rect')
186
- .attr('class', 'bar')
187
- .attr('x', d => xScale(d.name) ?? 0)
188
- .attr('width', xScale.bandwidth())
189
- .attr('y', innerHeight)
190
- .attr('height', 0)
191
- .attr('rx', BAR_RADIUS)
192
- .attr('ry', BAR_RADIUS)
193
- .style('fill', d =>
194
- this._resolveColor(d.name, d.color, colorScale),
195
- ),
196
- update => update,
197
- exit =>
198
- exit
199
- .transition()
200
- .duration(DURATION)
201
- .attr('height', 0)
202
- .attr('y', innerHeight)
203
- .remove(),
287
+ const marks = root
288
+ .select('.marks')
289
+ .selectAll<SVGPathElement, BarModel>('path.bar')
290
+ .data(placed, d => d.id)
291
+ .join(enter =>
292
+ enter
293
+ .append('path')
294
+ .attr('class', 'mark bar')
295
+ .attr('d', d => path(d, false)),
296
+ )
297
+ .attr('data-index', d => d.index)
298
+ .attr('data-key', d => d.key)
299
+ .style('fill', d => d.color);
300
+ this.motion(marks, animate).attr('d', d => path(d, true));
301
+
302
+ // Value labels sit just past the end of each bar or stack.
303
+ const center = (label: Omit<ValueLabelModel, 'center'>) => {
304
+ if (this.stacked) {
305
+ return (
306
+ (categoryScale(String(label.index)) ?? 0) +
307
+ categoryScale.bandwidth() / 2
308
+ );
309
+ }
310
+ const key = label.id.split(':').slice(1).join(':');
311
+ return (
312
+ (categoryScale(String(label.index)) ?? 0) +
313
+ (groupScale(key) ?? 0) +
314
+ groupScale.bandwidth() / 2
204
315
  );
205
-
206
- bars
207
- .attr('x', d => xScale(d.name) ?? 0)
208
- .attr('width', xScale.bandwidth())
209
- .attr('rx', BAR_RADIUS)
210
- .attr('ry', BAR_RADIUS)
211
- .style('fill', d => this._resolveColor(d.name, d.color, colorScale));
212
-
213
- if (animate) {
214
- bars
215
- .transition()
216
- .duration(DURATION)
217
- .attr('y', d => yScale(d.value))
218
- .attr('height', d => innerHeight - yScale(d.value));
219
- } else {
220
- bars
221
- .attr('y', d => yScale(d.value))
222
- .attr('height', d => innerHeight - yScale(d.value));
223
- }
224
-
225
- const valueLabels = container
316
+ };
317
+ const labelModels: ValueLabelModel[] = this.showValues
318
+ ? labels.map(label => ({ ...label, center: center(label) }))
319
+ : [];
320
+ const valueLabels = root
226
321
  .select('.value-labels')
227
- .selectAll<SVGTextElement, ChartBarItem>('text')
228
- .data(this.showValues ? data : [], d => d.name)
229
- .join(
230
- enter =>
231
- enter
232
- .append('text')
233
- .attr('class', 'value-label')
234
- .attr('text-anchor', 'middle')
235
- .attr('x', d => (xScale(d.name) ?? 0) + xScale.bandwidth() / 2)
236
- .attr('y', innerHeight - 6)
237
- .text(d => d.value.toLocaleString()),
238
- update => update,
239
- exit => exit.remove(),
322
+ .selectAll<SVGTextElement, ValueLabelModel>('text')
323
+ .data(labelModels, d => d.id)
324
+ .join(enter =>
325
+ enter
326
+ .append('text')
327
+ .attr('class', 'value-label')
328
+ .attr('x', d => (vertical ? d.center : valueScale(0)))
329
+ .attr('y', d => (vertical ? valueScale(0) : d.center)),
330
+ )
331
+ .attr('text-anchor', d => {
332
+ if (vertical) return 'middle';
333
+ return d.value < 0 ? 'end' : 'start';
334
+ })
335
+ .attr('dominant-baseline', vertical ? 'auto' : 'middle')
336
+ .text(d => this.formatValue(d.value));
337
+ this.motion(valueLabels, animate)
338
+ .attr('x', d =>
339
+ vertical ? d.center : valueScale(d.value) + (d.value < 0 ? -6 : 6),
340
+ )
341
+ .attr('y', d =>
342
+ vertical ? valueScale(d.value) + (d.value < 0 ? 14 : -6) : d.center,
240
343
  );
241
344
 
242
- const resolveLabelY = (value: number) => {
243
- const offset = yScale(value) - 8;
244
- return Math.min(offset, innerHeight - 8);
245
- };
246
-
247
- if (animate) {
248
- valueLabels
249
- .transition()
250
- .duration(DURATION)
251
- .attr('x', d => (xScale(d.name) ?? 0) + xScale.bandwidth() / 2)
252
- .attr('y', d => resolveLabelY(d.value))
253
- .text(d => d.value.toLocaleString());
254
- } else {
255
- valueLabels
256
- .attr('x', d => (xScale(d.name) ?? 0) + xScale.bandwidth() / 2)
257
- .attr('y', d => resolveLabelY(d.value))
258
- .text(d => d.value.toLocaleString());
259
- }
345
+ // Tooltip anchors at the far end of each category.
346
+ this.anchors = this.data.map((_, index) => {
347
+ const own = placed.filter(bar => bar.index === index);
348
+ const far = max(own, bar => bar.to) ?? 0;
349
+ const c =
350
+ (categoryScale(String(index)) ?? 0) + categoryScale.bandwidth() / 2;
351
+ return vertical
352
+ ? { x: left + c, y: top + Math.max(valueScale(far), 24) }
353
+ : { x: left + Math.min(valueScale(far), innerWidth - 24), y: top + c };
354
+ });
260
355
  }
261
356
 
262
- render() {
263
- const paletteScale = this._getPaletteScale();
264
- const legendItems = this.data.map(item => ({
265
- name: item.label ?? item.name,
266
- color: this._resolveColor(item.name, item.color, paletteScale),
267
- }));
357
+ protected drawHighlight(): void {
358
+ super.drawHighlight();
359
+ const root = this.plotArea();
360
+ if (!root) return;
361
+ const { activeIndex, activeSeries } = this;
362
+ root
363
+ .select('.marks')
364
+ .selectAll<SVGPathElement, BarModel>('path.bar')
365
+ .classed(
366
+ 'is-dimmed',
367
+ d =>
368
+ (activeIndex >= 0 && d.index !== activeIndex) ||
369
+ (activeSeries !== undefined && d.key !== activeSeries),
370
+ );
371
+ }
268
372
 
269
- return html`
270
- <div class="chart-frame">
271
- <svg role="img" aria-label="Bar chart">
272
- <g class="chart-container">
273
- <g class="y-grid"></g>
274
- <g class="bars"></g>
275
- <g class="x-axis"></g>
276
- <g class="value-labels"></g>
277
- </g>
278
- </svg>
279
- ${legendItems.length
280
- ? html`<div class="legend" role="list">
281
- ${legendItems.map(
282
- item => html`<span class="legend-item" role="listitem">
283
- <span
284
- class="swatch"
285
- style=${styleMap({ background: item.color })}
286
- ></span>
287
- <span>${item.name}</span>
288
- </span>`,
289
- )}
290
- </div>`
291
- : null}
292
- </div>
293
- `;
373
+ protected getSelectDetail(index: number) {
374
+ const detail = super.getSelectDetail(index);
375
+ // A single visible series identifies the bar exactly.
376
+ const visible = this.bars.filter(bar => bar.index === index);
377
+ return visible.length === 1
378
+ ? { ...detail, series: visible[0].key }
379
+ : detail;
294
380
  }
295
381
  }
296
382
 
@@ -1,2 +1 @@
1
1
  export { ChartBar } from './chart-bar.js';
2
- export { ChartStackedBar } from './chart-stacked-bar.js';