@react-magma/charts 15.0.0-rc.4 → 16.0.0-next.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 (35) hide show
  1. package/dist/charts.js +363 -197
  2. package/dist/charts.js.map +1 -1
  3. package/dist/charts.modern.module.js +364 -198
  4. package/dist/charts.modern.module.js.map +1 -1
  5. package/dist/charts.umd.js +962 -422
  6. package/dist/charts.umd.js.map +1 -1
  7. package/dist/components/CarbonChart/CarbonChart.d.ts +25 -0
  8. package/package.json +3 -3
  9. package/src/components/CarbonChart/CarbonChart.test.js +502 -3
  10. package/src/components/CarbonChart/CarbonChart.tsx +559 -256
  11. package/src/components/CarbonChart/CarbonChartArea.stories.tsx +1 -1
  12. package/src/components/CarbonChart/CarbonChartAreaStacked.stories.tsx +1 -1
  13. package/src/components/CarbonChart/CarbonChartBarFloating.stories.tsx +1 -1
  14. package/src/components/CarbonChart/CarbonChartBarGrouped.stories.tsx +1 -1
  15. package/src/components/CarbonChart/CarbonChartBarStacked.stories.tsx +1 -1
  16. package/src/components/CarbonChart/CarbonChartBoxplot.stories.tsx +1 -1
  17. package/src/components/CarbonChart/CarbonChartBubble.stories.tsx +1 -1
  18. package/src/components/CarbonChart/CarbonChartBullet.stories.tsx +1 -1
  19. package/src/components/CarbonChart/CarbonChartCombo.stories.tsx +1 -1
  20. package/src/components/CarbonChart/CarbonChartDonut.stories.tsx +3 -1
  21. package/src/components/CarbonChart/CarbonChartGauge.stories.tsx +1 -1
  22. package/src/components/CarbonChart/CarbonChartHistogram.stories.tsx +1 -1
  23. package/src/components/CarbonChart/CarbonChartLine.stories.tsx +1 -1
  24. package/src/components/CarbonChart/CarbonChartLollipop.stories.tsx +1 -1
  25. package/src/components/CarbonChart/CarbonChartMeter.stories.tsx +1 -1
  26. package/src/components/CarbonChart/CarbonChartPie.stories.tsx +1 -1
  27. package/src/components/CarbonChart/CarbonChartRadar.stories.tsx +1 -1
  28. package/src/components/CarbonChart/CarbonChartScatter.stories.tsx +1 -1
  29. package/src/components/CarbonChart/CarbonChartSparkline.stories.tsx +1 -1
  30. package/src/components/CarbonChart/CarbonChartStep.stories.tsx +1 -1
  31. package/src/components/CarbonChart/carbon-charts.css +89 -87
  32. package/src/components/ChartTable/ChartMoreOptionsButton.tsx +1 -0
  33. package/src/components/ChartTable/ChartTable.stories.tsx +140 -1
  34. package/dist/components/ChartTable/ChartTable.test.d.ts +0 -1
  35. /package/src/components/ChartTable/{ChartTable.test.tsx → ChartTable.test.js} +0 -0
@@ -27,8 +27,10 @@ import {
27
27
  Announce,
28
28
  DropdownDivider,
29
29
  DropdownMenuItem,
30
+ InverseContext,
30
31
  ThemeInterface,
31
32
  ThemeContext,
33
+ useDeviceDetect,
32
34
  useIsInverse,
33
35
  VisuallyHidden,
34
36
  } from 'react-magma-dom';
@@ -110,6 +112,22 @@ export interface ChartToolbarConfig {
110
112
  * @default 2
111
113
  */
112
114
  titleLevel?: 1 | 2 | 3 | 4 | 5 | 6;
115
+ /**
116
+ * Custom content rendered before the chart title.
117
+ *
118
+ * The content is placed inline in the title row and follows the same
119
+ * accessibility rules as `titleSuffix`.
120
+ */
121
+ titlePrefix?: React.ReactNode;
122
+
123
+ /**
124
+ * Custom content rendered after the chart title and before toolbar actions.
125
+ *
126
+ * The content is placed inline in the title row and renders outside the
127
+ * heading element to preserve `options.title` as the heading's accessible name.
128
+ * Useful for patterns like Tooltip + IconButton.
129
+ */
130
+ titleSuffix?: React.ReactNode;
113
131
  }
114
132
 
115
133
  export interface CarbonChartProps extends React.HTMLAttributes<HTMLDivElement> {
@@ -138,6 +156,16 @@ export interface CarbonChartProps extends React.HTMLAttributes<HTMLDivElement> {
138
156
  * toolbar is automatically disabled.
139
157
  */
140
158
  chartToolbar?: ChartToolbarConfig;
159
+ /**
160
+ * Custom content rendered below the toolbar row and above the chart itself,
161
+ * for example a filter. Requires `chartToolbar`; ignored without it.
162
+ *
163
+ * Providing this lays the toolbar out in normal flow instead of overlaying
164
+ * the single row Carbon reserves for its title, so the rendered height
165
+ * becomes toolbar + content + chart rather than the chart box alone. Set
166
+ * `options.height` so the chart still has a definite height of its own.
167
+ */
168
+ additionalContent?: React.ReactNode;
141
169
  }
142
170
 
143
171
  const ChartContentWrapper = styled.div`
@@ -146,6 +174,7 @@ const ChartContentWrapper = styled.div`
146
174
  `;
147
175
 
148
176
  const FullscreenRoot = styled.div<{
177
+ isFlowLayout?: boolean;
149
178
  isInverse?: boolean;
150
179
  theme: ThemeInterface;
151
180
  }>`
@@ -158,9 +187,34 @@ const FullscreenRoot = styled.div<{
158
187
  props.isInverse
159
188
  ? props.theme.colors.primary700
160
189
  : props.theme.colors.neutral100};
190
+
191
+ ${props =>
192
+ props.isFlowLayout
193
+ ? `
194
+ box-sizing: border-box;
195
+ display: flex;
196
+ flex-direction: column;
197
+ padding: 2em;
198
+
199
+ .carbon-chart-wrapper,
200
+ .carbon-chart-content {
201
+ display: flex;
202
+ flex: 1 1 auto;
203
+ flex-direction: column;
204
+ min-height: 0;
205
+ }
206
+
207
+ .cds--chart-holder {
208
+ flex: 1 1 auto;
209
+ height: auto !important;
210
+ min-height: 0;
211
+ }
212
+ `
213
+ : `
161
214
  .cds--chart-holder {
162
215
  height: 100vh !important;
163
216
  }
217
+ `}
164
218
  }
165
219
  `;
166
220
 
@@ -198,6 +252,14 @@ const CarbonChartWrapper = styled.div<{
198
252
  }
199
253
  }
200
254
 
255
+ .cds--chart-holder.filled,
256
+ .cds--chart-holder.filled .cds--cc--chart-wrapper {
257
+ background-color: ${props =>
258
+ props.isInverse
259
+ ? props.theme.colors.primary600
260
+ : props.theme.colors.neutral100};
261
+ }
262
+
201
263
  .cds--data-table thead tr th {
202
264
  background: ${props =>
203
265
  props.isInverse ? props.theme.colors.primary700 : ''} !important;
@@ -515,6 +577,9 @@ const CarbonChartWrapper = styled.div<{
515
577
  : props.theme.colors.focus} !important;
516
578
  outline-offset: 0;
517
579
  }
580
+ circle.dot:focus {
581
+ outline: none !important;
582
+ }
518
583
  .cds--overflow-menu-options__btn:focus,
519
584
  .cds--overflow-menu:focus,
520
585
  .cds--overflow-menu__trigger:focus,
@@ -619,6 +684,17 @@ const CarbonChartWrapper = styled.div<{
619
684
  overflow: visible;
620
685
  }
621
686
 
687
+ circle.dot:focus {
688
+ outline: none;
689
+ stroke: ${props =>
690
+ props.isInverse
691
+ ? props.theme.colors.focusInverse
692
+ : props.theme.colors.focus} !important;
693
+ stroke-width: 6px !important;
694
+ stroke-opacity: 1 !important;
695
+ paint-order: stroke fill;
696
+ }
697
+
622
698
  .cds--cc--chart-wrapper text {
623
699
  font-size: ${props => props.theme.typeScale.size02.fontSize};
624
700
  }
@@ -662,7 +738,13 @@ interface ColorsObject {
662
738
  [key: string]: string;
663
739
  }
664
740
 
741
+ type ExtendedChartOptions = ChartOptions & {
742
+ title?: string;
743
+ colors?: string[];
744
+ };
745
+
665
746
  const ToolbarWrapper = styled.div<{
747
+ isFlowLayout?: boolean;
666
748
  isFullscreen?: boolean;
667
749
  isInverse?: boolean;
668
750
  theme: ThemeInterface;
@@ -670,12 +752,20 @@ const ToolbarWrapper = styled.div<{
670
752
  align-items: center;
671
753
  display: flex;
672
754
  justify-content: space-between;
673
- left: ${props => (props.isFullscreen ? '2em' : '0')};
674
- position: absolute;
675
- right: ${props => (props.isFullscreen ? '2em' : '0')};
676
- top: ${props => (props.isFullscreen ? '2em' : '0')};
677
755
  z-index: 2;
678
756
 
757
+ ${props =>
758
+ props.isFlowLayout
759
+ ? `
760
+ position: relative;
761
+ `
762
+ : `
763
+ left: ${props.isFullscreen ? '2em' : '0'};
764
+ position: absolute;
765
+ right: ${props.isFullscreen ? '2em' : '0'};
766
+ top: ${props.isFullscreen ? '2em' : '0'};
767
+ `}
768
+
679
769
  button {
680
770
  color: ${props =>
681
771
  props.isInverse
@@ -709,6 +799,22 @@ const ChartTitle = styled.h2<{
709
799
  : props.theme.colors.neutral700} !important;
710
800
  `;
711
801
 
802
+ const TitleGroup = styled.div<{ theme: ThemeInterface }>`
803
+ align-items: center;
804
+ display: flex;
805
+ gap: ${props => props.theme.spaceScale.spacing02};
806
+ min-width: 0;
807
+ `;
808
+
809
+ const TitleSlot = styled.div`
810
+ align-items: center;
811
+ display: flex;
812
+ `;
813
+
814
+ const ChartSlot = styled.div<{ theme: ThemeInterface }>`
815
+ margin: ${props => props.theme.spaceScale.spacing05} 0 0;
816
+ `;
817
+
712
818
  const ToolbarActions = styled.div<{ theme: ThemeInterface }>`
713
819
  align-items: center;
714
820
  display: flex;
@@ -778,192 +884,83 @@ function downloadCsv(dataSet: Array<Record<string, unknown>>, title: string) {
778
884
  URL.revokeObjectURL(url);
779
885
  }
780
886
 
781
- function inlineStyles(source: Element, target: Element) {
782
- const computed = window.getComputedStyle(source);
783
-
784
- if (target instanceof HTMLElement || target instanceof SVGElement) {
785
- target.setAttribute(
786
- 'style',
787
- Array.from(computed)
788
- .map(prop => `${prop}:${computed.getPropertyValue(prop)}`)
789
- .join(';')
790
- );
791
- }
792
- for (let i = 0; i < source.children.length; i++) {
793
- if (target.children[i]) {
794
- inlineStyles(source.children[i], target.children[i]);
795
- }
796
- }
797
- }
798
-
799
- interface LegendItem {
800
- label: string;
801
- color: string;
802
- }
803
-
804
- function readLegendItems(wrapper: HTMLElement): LegendItem[] {
805
- const items: LegendItem[] = [];
806
-
807
- wrapper.querySelectorAll('.legend-item').forEach(item => {
808
- const checkbox = item.querySelector<HTMLElement>('.checkbox');
809
- const label = item.querySelector('p');
810
-
811
- if (checkbox && label) {
812
- items.push({
813
- color: checkbox.style.background || checkbox.style.backgroundColor,
814
- label: label.textContent || '',
815
- });
816
- }
817
- });
818
-
819
- return items;
887
+ interface CarbonChartCore {
888
+ services?: {
889
+ domUtils?: { exportToPNG: () => void; exportToJPG: () => void };
890
+ };
820
891
  }
821
892
 
822
- function drawLegend(
823
- ctx: CanvasRenderingContext2D,
824
- items: LegendItem[],
825
- startY: number,
826
- canvasWidth: number,
827
- scale: number
828
- ) {
829
- const fontSize = 13 * scale;
830
- const swatchSize = 12 * scale;
831
- const gap = 8 * scale;
832
- const itemGap = 16 * scale;
833
- const paddingX = 16 * scale;
834
-
835
- ctx.font = `${fontSize}px sans-serif`;
836
- ctx.textBaseline = 'middle';
837
-
838
- let x = paddingX;
839
- let y = startY;
840
-
841
- for (const item of items) {
842
- const textWidth = ctx.measureText(item.label).width;
843
- const itemWidth = swatchSize + gap + textWidth + itemGap;
844
-
845
- if (x + itemWidth > canvasWidth - paddingX && x > paddingX) {
846
- x = paddingX;
847
- y += fontSize + gap;
848
- }
849
-
850
- ctx.fillStyle = item.color;
851
- ctx.fillRect(x, y - swatchSize / 2, swatchSize, swatchSize);
852
-
853
- ctx.fillStyle = '#161616';
854
- ctx.fillText(item.label, x + swatchSize + gap, y);
855
-
856
- x += itemWidth;
857
- }
858
-
859
- return y + fontSize + gap;
893
+ interface CarbonChartComponent {
894
+ chart?: CarbonChartCore;
860
895
  }
861
896
 
862
- function downloadImage(
863
- wrapperRef: React.RefObject<HTMLDivElement | null>,
864
- title: string,
897
+ function exportCarbonChartImage(
898
+ chart: CarbonChartCore | null | undefined,
899
+ toolbarWrapper: Element | null | undefined,
865
900
  format: 'png' | 'jpg'
866
901
  ) {
867
- const wrapper = wrapperRef.current;
868
-
869
- if (!wrapper) return;
870
- const svg = wrapper.querySelector('svg.layout-svg-wrapper');
871
-
872
- if (!svg) return;
873
-
874
- const svgRect = svg.getBoundingClientRect();
875
- const legendItems = readLegendItems(wrapper);
876
- const scale = 2;
902
+ const domUtils = chart?.services?.domUtils;
877
903
 
878
- // Measure legend height
879
- const tempCanvas = document.createElement('canvas');
880
- const tempCtx = tempCanvas.getContext('2d');
881
- const fontSize = 13 * scale;
882
- const swatchSize = 12 * scale;
883
- const gap = 8 * scale;
884
- const itemGap = 16 * scale;
885
- const paddingX = 16 * scale;
886
- const canvasWidth = svgRect.width * scale;
904
+ if (!domUtils) return;
887
905
 
888
- let legendHeight = 0;
906
+ const magmaWrapper = toolbarWrapper?.classList.contains('has-magma-toolbar')
907
+ ? toolbarWrapper
908
+ : null;
889
909
 
890
- if (legendItems.length > 0 && tempCtx) {
891
- tempCtx.font = `${fontSize}px sans-serif`;
892
- let x = paddingX;
893
- let rows = 1;
910
+ magmaWrapper?.classList.remove('has-magma-toolbar');
894
911
 
895
- for (const item of legendItems) {
896
- const textWidth = tempCtx.measureText(item.label).width;
897
- const itemWidth = swatchSize + gap + textWidth + itemGap;
912
+ let restored = false;
913
+ const restore = () => {
914
+ if (restored) return;
915
+ restored = true;
916
+ magmaWrapper?.classList.add('has-magma-toolbar');
917
+ };
898
918
 
899
- if (x + itemWidth > canvasWidth - paddingX && x > paddingX) {
900
- x = paddingX;
901
- rows++;
902
- }
903
- x += itemWidth;
919
+ try {
920
+ if (format === 'jpg') {
921
+ domUtils.exportToJPG();
922
+ } else {
923
+ domUtils.exportToPNG();
904
924
  }
905
- legendHeight = rows * (fontSize + gap) + gap * 2;
906
- }
907
-
908
- const width = svgRect.width * scale;
909
- const height = svgRect.height * scale + legendHeight;
910
-
911
- const clone = svg.cloneNode(true) as SVGSVGElement;
912
-
913
- clone.setAttribute('width', String(svgRect.width));
914
- clone.setAttribute('height', String(svgRect.height));
915
- clone.setAttribute('viewBox', `0 0 ${svgRect.width} ${svgRect.height}`);
916
- clone.setAttribute('xmlns', 'http://www.w3.org/2000/svg');
917
-
918
- inlineStyles(svg, clone);
919
-
920
- const serializer = new XMLSerializer();
921
- const svgString = serializer.serializeToString(clone);
922
- const svgBlob = new Blob([svgString], {
923
- type: 'image/svg+xml;charset=utf-8',
924
- });
925
- const url = URL.createObjectURL(svgBlob);
926
-
927
- const mimeType = format === 'jpg' ? 'image/jpeg' : 'image/png';
928
- const ext = format === 'jpg' ? 'jpg' : 'png';
929
-
930
- const img = new Image();
931
-
932
- img.onload = () => {
933
- const canvas = document.createElement('canvas');
934
-
935
- canvas.width = width;
936
- canvas.height = height;
937
- const ctx = canvas.getContext('2d');
938
-
939
- if (!ctx) return;
940
-
941
- ctx.fillStyle = '#ffffff';
942
- ctx.fillRect(0, 0, canvas.width, canvas.height);
943
- ctx.drawImage(img, 0, 0, svgRect.width * scale, svgRect.height * scale);
944
- URL.revokeObjectURL(url);
945
-
946
- if (legendItems.length > 0) {
947
- drawLegend(ctx, legendItems, svgRect.height * scale + gap, width, scale);
925
+ } catch (error) {
926
+ console.warn('Carbon chart image export failed', error);
927
+ } finally {
928
+ // Re-add before the next paint so the title swap is never visible on
929
+ // screen; the timeout is only a fallback for when requestAnimationFrame is
930
+ // paused (e.g. the tab is in the background).
931
+ if (typeof requestAnimationFrame === 'function') {
932
+ requestAnimationFrame(restore);
948
933
  }
949
-
950
- canvas.toBlob(blob => {
951
- if (!blob) return;
952
- const imgUrl = URL.createObjectURL(blob);
953
- const a = document.createElement('a');
954
-
955
- a.href = imgUrl;
956
- a.download = `${title || 'chart'}.${ext}`;
957
- a.click();
958
- URL.revokeObjectURL(imgUrl);
959
- }, mimeType);
960
- };
961
- img.src = url;
934
+ setTimeout(restore, 1000);
935
+ }
962
936
  }
963
937
 
938
+ const ALL_CHARTS: Record<CarbonChartType, React.ComponentType<any>> = {
939
+ area: AreaChart,
940
+ areaStacked: StackedAreaChart,
941
+ bar: SimpleBarChart,
942
+ barGrouped: GroupedBarChart,
943
+ barStacked: StackedBarChart,
944
+ donut: DonutChart,
945
+ line: LineChart,
946
+ lollipop: LollipopChart,
947
+ pie: PieChart,
948
+ radar: RadarChart,
949
+ boxplot: BoxplotChart,
950
+ bubble: BubbleChart,
951
+ bullet: BulletChart,
952
+ gauge: GaugeChart,
953
+ histogram: HistogramChart,
954
+ meter: MeterChart,
955
+ scatter: ScatterChart,
956
+ combo: ComboChart,
957
+ };
958
+
964
959
  interface InternalToolbarProps {
960
+ chartRef: React.MutableRefObject<CarbonChartComponent | null>;
965
961
  config: ChartToolbarConfig;
966
962
  dataSet: Array<Record<string, unknown>>;
963
+ isFlowLayout: boolean;
967
964
  isInverse: boolean;
968
965
  isTableOpen: boolean;
969
966
  isFullscreen: boolean;
@@ -975,8 +972,10 @@ interface InternalToolbarProps {
975
972
  }
976
973
 
977
974
  function CarbonChartToolbar({
975
+ chartRef,
978
976
  config,
979
977
  dataSet,
978
+ isFlowLayout,
980
979
  isInverse,
981
980
  isTableOpen,
982
981
  isFullscreen,
@@ -991,17 +990,28 @@ function CarbonChartToolbar({
991
990
  const showFullscreen = config.fullscreen !== false;
992
991
  const resolvedTitle = title || t.defaultTitle;
993
992
 
993
+ const exportImage = React.useCallback(
994
+ (format: 'png' | 'jpg') => {
995
+ exportCarbonChartImage(
996
+ chartRef.current?.chart,
997
+ wrapperRef.current?.querySelector('.carbon-chart-wrapper'),
998
+ format
999
+ );
1000
+ },
1001
+ [chartRef, wrapperRef]
1002
+ );
1003
+
994
1004
  const handleDownloadCsv = React.useCallback(() => {
995
1005
  downloadCsv(dataSet, title);
996
1006
  }, [dataSet, title]);
997
1007
 
998
1008
  const handleDownloadPng = React.useCallback(() => {
999
- downloadImage(wrapperRef, title, 'png');
1000
- }, [wrapperRef, title]);
1009
+ exportImage('png');
1010
+ }, [exportImage]);
1001
1011
 
1002
1012
  const handleDownloadJpg = React.useCallback(() => {
1003
- downloadImage(wrapperRef, title, 'jpg');
1004
- }, [wrapperRef, title]);
1013
+ exportImage('jpg');
1014
+ }, [exportImage]);
1005
1015
 
1006
1016
  const moreOptionsContent = (
1007
1017
  <>
@@ -1025,17 +1035,26 @@ function CarbonChartToolbar({
1025
1035
 
1026
1036
  return (
1027
1037
  <ToolbarWrapper
1038
+ isFlowLayout={isFlowLayout}
1028
1039
  isFullscreen={isFullscreen}
1029
1040
  isInverse={isInverse}
1030
1041
  theme={theme}
1031
1042
  >
1032
- <ChartTitle
1033
- as={`h${config.titleLevel ?? 2}` as keyof JSX.IntrinsicElements}
1034
- isInverse={isInverse}
1035
- theme={theme}
1036
- >
1037
- {resolvedTitle}
1038
- </ChartTitle>
1043
+ <TitleGroup theme={theme}>
1044
+ {config.titlePrefix ? (
1045
+ <TitleSlot>{config.titlePrefix}</TitleSlot>
1046
+ ) : null}
1047
+ <ChartTitle
1048
+ as={`h${config.titleLevel ?? 2}` as keyof JSX.IntrinsicElements}
1049
+ isInverse={isInverse}
1050
+ theme={theme}
1051
+ >
1052
+ {resolvedTitle}
1053
+ </ChartTitle>
1054
+ {config.titleSuffix ? (
1055
+ <TitleSlot>{config.titleSuffix}</TitleSlot>
1056
+ ) : null}
1057
+ </TitleGroup>
1039
1058
  <ToolbarActions theme={theme}>
1040
1059
  {showTable && (
1041
1060
  <ChartTableButton
@@ -1075,6 +1094,7 @@ export const CarbonChart = React.forwardRef<HTMLDivElement, CarbonChartProps>(
1075
1094
  type,
1076
1095
  dataSet,
1077
1096
  options,
1097
+ additionalContent,
1078
1098
  ariaLabel,
1079
1099
  chartToolbar,
1080
1100
  ...rest
@@ -1083,12 +1103,16 @@ export const CarbonChart = React.forwardRef<HTMLDivElement, CarbonChartProps>(
1083
1103
  const isInverse = useIsInverse(isInverseProp);
1084
1104
  const toolbarI18n = useChartToolbarI18n();
1085
1105
  const internalRef = React.useRef<HTMLDivElement | null>(null);
1106
+ const chartComponentRef = React.useRef<CarbonChartComponent | null>(null);
1086
1107
 
1087
1108
  const [isTableOpen, setIsTableOpen] = React.useState(false);
1088
1109
  const [isFullscreen, setIsFullscreen] = React.useState(false);
1089
1110
  const [legendAnnouncement, setLegendAnnouncement] = React.useState('');
1111
+ const legendGroupAnnounceRef = React.useRef<HTMLDivElement | null>(null);
1090
1112
  const lastTableTriggerRef = React.useRef<HTMLButtonElement | null>(null);
1091
1113
  const legendAnnouncedRef = React.useRef(false);
1114
+ const selectionSignatureRef = React.useRef<string | undefined>(undefined);
1115
+ const { isMacOS, isChrome } = useDeviceDetect();
1092
1116
 
1093
1117
  const mergedRef = React.useCallback(
1094
1118
  (node: HTMLDivElement | null) => {
@@ -1106,6 +1130,8 @@ export const CarbonChart = React.forwardRef<HTMLDivElement, CarbonChartProps>(
1106
1130
  ? chartToolbar.fullscreen !== false
1107
1131
  : false;
1108
1132
 
1133
+ const isFlowLayout = Boolean(chartToolbar && additionalContent);
1134
+
1109
1135
  const savedHeightRef = React.useRef<string>('');
1110
1136
 
1111
1137
  React.useEffect(() => {
@@ -1119,7 +1145,7 @@ export const CarbonChart = React.forwardRef<HTMLDivElement, CarbonChartProps>(
1119
1145
  const chartHolder =
1120
1146
  internalRef.current?.querySelector<HTMLElement>('.cds--chart-holder');
1121
1147
 
1122
- if (chartHolder) {
1148
+ if (chartHolder && !isFlowLayout) {
1123
1149
  if (isFs) {
1124
1150
  savedHeightRef.current = chartHolder.style.height;
1125
1151
  chartHolder.style.height = '100vh';
@@ -1131,9 +1157,17 @@ export const CarbonChart = React.forwardRef<HTMLDivElement, CarbonChartProps>(
1131
1157
 
1132
1158
  document.addEventListener('fullscreenchange', onFullscreenChange);
1133
1159
 
1134
- return () =>
1160
+ return () => {
1135
1161
  document.removeEventListener('fullscreenchange', onFullscreenChange);
1136
- }, [fullscreenEnabled]);
1162
+ // Restore height if the component unmounts while in fullscreen.
1163
+ const chartHolder =
1164
+ internalRef.current?.querySelector<HTMLElement>('.cds--chart-holder');
1165
+
1166
+ if (chartHolder && document.fullscreenElement) {
1167
+ chartHolder.style.height = savedHeightRef.current;
1168
+ }
1169
+ };
1170
+ }, [fullscreenEnabled, isFlowLayout]);
1137
1171
 
1138
1172
  const openTableModal = React.useCallback(
1139
1173
  (event: React.MouseEvent<HTMLButtonElement>) => {
@@ -1145,9 +1179,9 @@ export const CarbonChart = React.forwardRef<HTMLDivElement, CarbonChartProps>(
1145
1179
 
1146
1180
  const closeTableModal = React.useCallback(() => {
1147
1181
  setIsTableOpen(false);
1148
- setTimeout(() => {
1182
+ requestAnimationFrame(() => {
1149
1183
  lastTableTriggerRef.current?.focus();
1150
- }, 0);
1184
+ });
1151
1185
  }, []);
1152
1186
 
1153
1187
  const toggleFullscreen = React.useCallback(() => {
@@ -1163,7 +1197,7 @@ export const CarbonChart = React.forwardRef<HTMLDivElement, CarbonChartProps>(
1163
1197
  }, []);
1164
1198
 
1165
1199
  const chartTitle: string =
1166
- (options as any).title || toolbarI18n.defaultTitle;
1200
+ (options as ExtendedChartOptions).title || toolbarI18n.defaultTitle;
1167
1201
 
1168
1202
  const legendLabel = `${ariaLabel || chartTitle}. ${toolbarI18n.legendInstructions}`;
1169
1203
 
@@ -1173,11 +1207,37 @@ export const CarbonChart = React.forwardRef<HTMLDivElement, CarbonChartProps>(
1173
1207
  if (!container) return;
1174
1208
 
1175
1209
  const applyListSemantics = (legend: Element) => {
1176
- legend.removeAttribute('aria-label');
1177
- legend.setAttribute('role', 'list');
1178
- legend
1179
- .querySelectorAll('.legend-item')
1180
- .forEach(item => item.setAttribute('role', 'listitem'));
1210
+ const itemsHost = legend.matches('[data-name="legend-items"]')
1211
+ ? legend
1212
+ : legend.querySelector('[data-name="legend-items"]') || legend;
1213
+
1214
+ itemsHost.removeAttribute('aria-label');
1215
+
1216
+ if (itemsHost.getAttribute('role') !== 'list') {
1217
+ itemsHost.setAttribute('role', 'list');
1218
+ }
1219
+
1220
+ legend.querySelectorAll('.legend-item').forEach(item => {
1221
+ if (item.getAttribute('role') !== 'listitem') {
1222
+ item.setAttribute('role', 'listitem');
1223
+ }
1224
+ });
1225
+
1226
+ container.querySelectorAll('[role="list"]').forEach(el => {
1227
+ if (el !== itemsHost && el.contains(itemsHost)) {
1228
+ el.removeAttribute('role');
1229
+ }
1230
+ });
1231
+ container.querySelectorAll('[aria-label="Data groups"]').forEach(el => {
1232
+ if (el !== itemsHost && el.contains(itemsHost)) {
1233
+ el.removeAttribute('aria-label');
1234
+ }
1235
+ });
1236
+ };
1237
+
1238
+ const unwrapFieldset = (fieldset: Element) => {
1239
+ fieldset.querySelector(':scope > legend')?.remove();
1240
+ fieldset.replaceWith(...Array.from(fieldset.childNodes));
1181
1241
  };
1182
1242
 
1183
1243
  const wrapLegend = () => {
@@ -1187,10 +1247,21 @@ export const CarbonChart = React.forwardRef<HTMLDivElement, CarbonChartProps>(
1187
1247
 
1188
1248
  applyListSemantics(legend);
1189
1249
 
1190
- const parent = legend.parentElement;
1250
+ const closestFieldset = legend.closest(
1251
+ 'fieldset.cds--cc--legend-fieldset'
1252
+ );
1253
+
1254
+ container
1255
+ .querySelectorAll('fieldset.cds--cc--legend-fieldset')
1256
+ .forEach(fieldset => {
1257
+ if (fieldset !== closestFieldset) {
1258
+ unwrapFieldset(fieldset);
1259
+ }
1260
+ });
1191
1261
 
1192
- if (parent?.tagName === 'FIELDSET') {
1193
- const existingCaption = parent.querySelector('legend');
1262
+ if (closestFieldset) {
1263
+ const existingCaption =
1264
+ closestFieldset.querySelector(':scope > legend');
1194
1265
 
1195
1266
  if (existingCaption && existingCaption.textContent !== legendLabel) {
1196
1267
  existingCaption.textContent = legendLabel;
@@ -1211,68 +1282,111 @@ export const CarbonChart = React.forwardRef<HTMLDivElement, CarbonChartProps>(
1211
1282
  wrapLegend();
1212
1283
  const observer = new MutationObserver(wrapLegend);
1213
1284
 
1214
- observer.observe(container, { childList: true, subtree: true });
1285
+ observer.observe(container, {
1286
+ childList: true,
1287
+ subtree: true,
1288
+ attributes: true,
1289
+ attributeFilter: ['role', 'aria-label'],
1290
+ });
1215
1291
 
1216
1292
  return () => observer.disconnect();
1217
1293
  }, [legendLabel]);
1218
1294
 
1295
+ React.useEffect(() => {
1296
+ const container = internalRef.current;
1297
+
1298
+ if (!container || !isMacOS || !isChrome) return;
1299
+
1300
+ let announceTimer: ReturnType<typeof setTimeout>;
1301
+ let alternateSuffix = false;
1302
+
1303
+ const closestLegend = (node: EventTarget | null) =>
1304
+ node instanceof Element ? node.closest('.cds--cc--legend') : null;
1305
+
1306
+ const handleFocusIn = (event: FocusEvent) => {
1307
+ const enteredLegend = closestLegend(event.target);
1308
+ const cameFromLegend = closestLegend(event.relatedTarget);
1309
+
1310
+ if (enteredLegend && !cameFromLegend) {
1311
+ if (legendGroupAnnounceRef.current) {
1312
+ legendGroupAnnounceRef.current.textContent = '';
1313
+ }
1314
+
1315
+ clearTimeout(announceTimer);
1316
+ announceTimer = setTimeout(() => {
1317
+ if (legendGroupAnnounceRef.current) {
1318
+ alternateSuffix = !alternateSuffix;
1319
+ legendGroupAnnounceRef.current.textContent =
1320
+ legendLabel + (alternateSuffix ? ' ' : '');
1321
+ }
1322
+ }, 250);
1323
+ }
1324
+ };
1325
+
1326
+ const handleFocusOut = (event: FocusEvent) => {
1327
+ const leftLegend =
1328
+ closestLegend(event.target) && !closestLegend(event.relatedTarget);
1329
+
1330
+ // Reset once focus leaves the legend so re-entering announces again.
1331
+ if (leftLegend) {
1332
+ clearTimeout(announceTimer);
1333
+
1334
+ if (legendGroupAnnounceRef.current) {
1335
+ legendGroupAnnounceRef.current.textContent = '';
1336
+ }
1337
+ }
1338
+ };
1339
+
1340
+ container.addEventListener('focusin', handleFocusIn);
1341
+ container.addEventListener('focusout', handleFocusOut);
1342
+
1343
+ return () => {
1344
+ clearTimeout(announceTimer);
1345
+ container.removeEventListener('focusin', handleFocusIn);
1346
+ container.removeEventListener('focusout', handleFocusOut);
1347
+ };
1348
+ }, [isMacOS, isChrome, legendLabel]);
1349
+
1219
1350
  const handleModalDownloadCsv = React.useCallback(() => {
1220
1351
  downloadCsv(dataSet as Array<Record<string, unknown>>, chartTitle);
1221
1352
  }, [dataSet, chartTitle]);
1222
1353
 
1223
1354
  useCarbonModalFocusManagement(internalRef);
1224
- const allCharts = {
1225
- area: AreaChart,
1226
- areaStacked: StackedAreaChart,
1227
- bar: SimpleBarChart,
1228
- barGrouped: GroupedBarChart,
1229
- barStacked: StackedBarChart,
1230
- donut: DonutChart,
1231
- line: LineChart,
1232
- lollipop: LollipopChart,
1233
- pie: PieChart,
1234
- radar: RadarChart,
1235
- boxplot: BoxplotChart,
1236
- bubble: BubbleChart,
1237
- bullet: BulletChart,
1238
- gauge: GaugeChart,
1239
- histogram: HistogramChart,
1240
- meter: MeterChart,
1241
- scatter: ScatterChart,
1242
- combo: ComboChart,
1243
- };
1244
1355
 
1245
- function buildColors() {
1356
+ const colorScale = React.useMemo(() => {
1246
1357
  const scaleColorsObj: ColorsObject = {};
1247
-
1248
- const allGroups = dataSet.map(item => {
1249
- return 'group' in item ? item['group'] : null;
1250
- });
1251
- const uniqueGroups = allGroups.filter(
1252
- (g, index) => allGroups.indexOf(g) === index
1253
- );
1254
- const customColors = ((options as any).colors as string[]) || [];
1358
+ const customColors = (options as ExtendedChartOptions).colors || [];
1255
1359
  const allColors = [...customColors, ...theme.chartColors];
1256
1360
  const allInverseColors = [...customColors, ...theme.chartColorsInverse];
1361
+ const allGroups = dataSet.map(item =>
1362
+ 'group' in item ? (item as Record<string, unknown>)['group'] : null
1363
+ );
1364
+ const uniqueGroups = Array.from(new Set(allGroups));
1365
+
1366
+ if (uniqueGroups.length <= allColors.length) {
1367
+ for (let i = 0; i < uniqueGroups.length; i++) {
1368
+ const group = uniqueGroups[i];
1257
1369
 
1258
- uniqueGroups.forEach((group, i) => {
1259
- if (uniqueGroups.length <= allColors.length) {
1260
- return (scaleColorsObj[group || ('null' as any)] = isInverse
1370
+ scaleColorsObj[String(group ?? 'null')] = isInverse
1261
1371
  ? allInverseColors[i]
1262
- : allColors[i]);
1372
+ : allColors[i];
1263
1373
  }
1264
-
1265
- return {};
1266
- });
1374
+ }
1267
1375
 
1268
1376
  return scaleColorsObj;
1269
- }
1377
+ }, [
1378
+ dataSet,
1379
+ options,
1380
+ theme.chartColors,
1381
+ theme.chartColorsInverse,
1382
+ isInverse,
1383
+ ]);
1270
1384
 
1271
1385
  const newOptions = {
1272
1386
  ...options,
1273
1387
  theme: isInverse ? ChartTheme.G100 : ChartTheme.WHITE,
1274
1388
  color: {
1275
- scale: buildColors(),
1389
+ scale: colorScale,
1276
1390
  },
1277
1391
  tooltip: {
1278
1392
  ...(options?.tooltip || {}),
@@ -1280,16 +1394,30 @@ export const CarbonChart = React.forwardRef<HTMLDivElement, CarbonChartProps>(
1280
1394
  type: 'none',
1281
1395
  },
1282
1396
  },
1283
- ...(chartToolbar ? { toolbar: { enabled: false } } : {}),
1397
+ ...(chartToolbar
1398
+ ? {
1399
+ toolbar: { enabled: false },
1400
+ title: chartTitle,
1401
+ ...(options.fileDownload
1402
+ ? {}
1403
+ : { fileDownload: { fileName: chartTitle } }),
1404
+ }
1405
+ : {}),
1284
1406
  };
1285
1407
 
1286
- const ChartType = allCharts[type] as any;
1408
+ const ChartType = ALL_CHARTS[type];
1287
1409
 
1288
1410
  React.useEffect(() => {
1289
1411
  const timer = setTimeout(() => {
1290
1412
  if (internalRef.current) {
1291
1413
  internalRef.current
1292
- .querySelectorAll<SVGGElement>('g[aria-label]')
1414
+ .querySelectorAll<SVGGElement>('g.ruler[aria-label]')
1415
+ .forEach(g => {
1416
+ g.setAttribute('aria-hidden', 'true');
1417
+ });
1418
+
1419
+ internalRef.current
1420
+ .querySelectorAll<SVGGElement>('g[aria-label]:not(.ruler)')
1293
1421
  .forEach(g => {
1294
1422
  const role = g.getAttribute('role');
1295
1423
 
@@ -1305,6 +1433,30 @@ export const CarbonChart = React.forwardRef<HTMLDivElement, CarbonChartProps>(
1305
1433
  return () => clearTimeout(timer);
1306
1434
  }, [type, dataSet]);
1307
1435
 
1436
+ React.useEffect(() => {
1437
+ const container = internalRef.current;
1438
+
1439
+ if (!container) return;
1440
+
1441
+ const hideRulerFromAT = () => {
1442
+ container
1443
+ .querySelectorAll<SVGGElement>('g.ruler[aria-label]')
1444
+ .forEach(g => {
1445
+ if (!g.hasAttribute('aria-hidden')) {
1446
+ g.setAttribute('aria-hidden', 'true');
1447
+ }
1448
+ });
1449
+ };
1450
+
1451
+ hideRulerFromAT();
1452
+
1453
+ const observer = new MutationObserver(hideRulerFromAT);
1454
+
1455
+ observer.observe(container, { childList: true, subtree: true });
1456
+
1457
+ return () => observer.disconnect();
1458
+ }, [type, dataSet]);
1459
+
1308
1460
  React.useEffect(() => {
1309
1461
  const wrapper = internalRef.current;
1310
1462
 
@@ -1328,6 +1480,20 @@ export const CarbonChart = React.forwardRef<HTMLDivElement, CarbonChartProps>(
1328
1480
  }
1329
1481
  });
1330
1482
 
1483
+ // Carbon re-applies aria-checked (with the same values) on every
1484
+ // render, which still triggers this observer. Only announce when the
1485
+ // selection actually changed, otherwise unrelated re-renders (e.g.
1486
+ // the legend group announcement) cause phantom announcements.
1487
+ const selectionSignature = `${activeLabels.join('|')}::${allItems.length}`;
1488
+
1489
+ if (selectionSignatureRef.current === selectionSignature) return;
1490
+
1491
+ const isFirstRun = selectionSignatureRef.current === undefined;
1492
+
1493
+ selectionSignatureRef.current = selectionSignature;
1494
+
1495
+ if (isFirstRun) return;
1496
+
1331
1497
  if (activeLabels.length === 1) {
1332
1498
  if (!legendAnnouncedRef.current) {
1333
1499
  legendAnnouncedRef.current = true;
@@ -1343,6 +1509,7 @@ export const CarbonChart = React.forwardRef<HTMLDivElement, CarbonChartProps>(
1343
1509
  });
1344
1510
 
1345
1511
  observer.observe(wrapper, {
1512
+ childList: true,
1346
1513
  subtree: true,
1347
1514
  attributes: true,
1348
1515
  attributeFilter: ['aria-checked'],
@@ -1351,42 +1518,178 @@ export const CarbonChart = React.forwardRef<HTMLDivElement, CarbonChartProps>(
1351
1518
  return () => observer.disconnect();
1352
1519
  }, [type, dataSet]);
1353
1520
 
1354
- const groupsLength = Object.keys(buildColors()).length;
1521
+ // Make Carbon Charts data points keyboard-focusable.
1522
+ React.useEffect(() => {
1523
+ const wrapper = internalRef.current;
1524
+
1525
+ if (!wrapper) return;
1526
+
1527
+ const stampDotTabIndex = () => {
1528
+ wrapper
1529
+ .querySelectorAll<SVGCircleElement>('circle.dot')
1530
+ .forEach(dot => {
1531
+ if (!dot.hasAttribute('tabindex')) {
1532
+ dot.setAttribute('tabindex', '0');
1533
+ }
1534
+ });
1535
+ };
1536
+
1537
+ const isDot = (el: EventTarget | null): el is SVGCircleElement =>
1538
+ el instanceof Element &&
1539
+ el.nodeName.toLowerCase() === 'circle' &&
1540
+ el.classList.contains('dot');
1541
+
1542
+ const onFocusIn = (e: FocusEvent) => {
1543
+ if (!isDot(e.target)) return;
1544
+ const dot = e.target as SVGCircleElement;
1545
+
1546
+ const { left, top, width, height } = dot.getBoundingClientRect();
1547
+ const cx = left + width / 2;
1548
+ const cy = top + height / 2;
1549
+
1550
+ dot.dispatchEvent(
1551
+ new MouseEvent('mouseover', {
1552
+ bubbles: true,
1553
+ clientX: cx,
1554
+ clientY: cy,
1555
+ screenX: cx,
1556
+ screenY: cy,
1557
+ })
1558
+ );
1559
+ dot.dispatchEvent(
1560
+ new MouseEvent('mousemove', {
1561
+ bubbles: true,
1562
+ clientX: cx,
1563
+ clientY: cy,
1564
+ screenX: cx,
1565
+ screenY: cy,
1566
+ })
1567
+ );
1568
+ };
1569
+
1570
+ const onFocusOut = (e: FocusEvent) => {
1571
+ if (!isDot(e.target)) return;
1572
+ const dot = e.target;
1573
+
1574
+ // Keep tooltip context while Tab focus moves between chart points.
1575
+ if (isDot(e.relatedTarget)) {
1576
+ return;
1577
+ }
1578
+
1579
+ dot.dispatchEvent(new MouseEvent('mouseout', { bubbles: true }));
1580
+ };
1581
+
1582
+ const onKeyDown = (e: KeyboardEvent) => {
1583
+ if (!isDot(e.target)) return;
1584
+ if (e.key !== 'Enter' && e.key !== ' ') return;
1585
+ e.preventDefault();
1586
+ const dot = e.target;
1587
+ const { left, top, width, height } = dot.getBoundingClientRect();
1588
+ const cx = left + width / 2;
1589
+ const cy = top + height / 2;
1590
+
1591
+ dot.dispatchEvent(
1592
+ new MouseEvent('click', {
1593
+ bubbles: true,
1594
+ clientX: cx,
1595
+ clientY: cy,
1596
+ })
1597
+ );
1598
+ };
1599
+
1600
+ const rafId = requestAnimationFrame(() => {
1601
+ stampDotTabIndex();
1602
+ });
1603
+
1604
+ const dotObserver = new MutationObserver(() => {
1605
+ stampDotTabIndex();
1606
+ });
1607
+
1608
+ dotObserver.observe(wrapper, {
1609
+ childList: true,
1610
+ subtree: true,
1611
+ attributes: true,
1612
+ attributeFilter: ['class', 'style', 'tabindex'],
1613
+ });
1614
+
1615
+ wrapper.addEventListener('focusin', onFocusIn);
1616
+ wrapper.addEventListener('focusout', onFocusOut);
1617
+ wrapper.addEventListener('keydown', onKeyDown);
1618
+
1619
+ return () => {
1620
+ cancelAnimationFrame(rafId);
1621
+ dotObserver.disconnect();
1622
+ wrapper.removeEventListener('focusin', onFocusIn);
1623
+ wrapper.removeEventListener('focusout', onFocusOut);
1624
+ wrapper.removeEventListener('keydown', onKeyDown);
1625
+ };
1626
+ }, [type, dataSet]);
1627
+
1628
+ const groupsLength = Object.keys(colorScale).length;
1355
1629
 
1356
1630
  const showTable = chartToolbar?.showAsTable !== false;
1357
1631
 
1632
+ if (!ChartType) return null;
1633
+
1358
1634
  return (
1359
- <FullscreenRoot ref={mergedRef} isInverse={isInverse} theme={theme}>
1635
+ <FullscreenRoot
1636
+ ref={mergedRef}
1637
+ isFlowLayout={isFlowLayout}
1638
+ isInverse={isInverse}
1639
+ theme={theme}
1640
+ >
1360
1641
  <VisuallyHidden>
1361
1642
  <Announce>{legendAnnouncement}</Announce>
1362
1643
  </VisuallyHidden>
1644
+ <VisuallyHidden>
1645
+ <div aria-live="polite" ref={legendGroupAnnounceRef} />
1646
+ </VisuallyHidden>
1363
1647
  <CarbonChartWrapper
1364
1648
  data-testid={testId}
1365
1649
  isInverse={isInverse}
1366
1650
  theme={theme}
1367
- className={`carbon-chart-wrapper${chartToolbar ? ' has-magma-toolbar' : ''}`}
1651
+ className={`carbon-chart-wrapper${
1652
+ chartToolbar ? ' has-magma-toolbar' : ''
1653
+ }`}
1368
1654
  groupsLength={groupsLength < 6 ? groupsLength : 14}
1369
1655
  role="region"
1370
1656
  aria-label={ariaLabel || chartTitle}
1371
1657
  aria-roledescription="chart"
1372
1658
  {...rest}
1373
1659
  >
1374
- <ChartContentWrapper>
1660
+ <ChartContentWrapper className="carbon-chart-content">
1375
1661
  {chartToolbar && (
1376
- <CarbonChartToolbar
1377
- config={chartToolbar}
1378
- dataSet={dataSet as Array<Record<string, unknown>>}
1379
- isInverse={isInverse}
1380
- isTableOpen={isTableOpen}
1381
- isFullscreen={isFullscreen}
1382
- onOpenTable={openTableModal}
1383
- onToggleFullscreen={toggleFullscreen}
1384
- theme={theme}
1385
- title={chartTitle}
1386
- wrapperRef={internalRef}
1387
- />
1662
+ /*
1663
+ * Slot content comes from the adopter, so it resolves
1664
+ * `isInverse` from context rather than from our prop. Without
1665
+ * this provider a Magma component in a title slot would stay
1666
+ * light on an inverse chart.
1667
+ */
1668
+ <InverseContext.Provider value={{ isInverse }}>
1669
+ <CarbonChartToolbar
1670
+ chartRef={chartComponentRef}
1671
+ config={chartToolbar}
1672
+ dataSet={dataSet as Array<Record<string, unknown>>}
1673
+ isFlowLayout={isFlowLayout}
1674
+ isInverse={isInverse}
1675
+ isTableOpen={isTableOpen}
1676
+ isFullscreen={isFullscreen}
1677
+ onOpenTable={openTableModal}
1678
+ onToggleFullscreen={toggleFullscreen}
1679
+ theme={theme}
1680
+ title={chartTitle}
1681
+ wrapperRef={internalRef}
1682
+ />
1683
+ {isFlowLayout && (
1684
+ <ChartSlot theme={theme}>{additionalContent}</ChartSlot>
1685
+ )}
1686
+ </InverseContext.Provider>
1388
1687
  )}
1389
- <ChartType data={dataSet} options={newOptions} />
1688
+ <ChartType
1689
+ ref={chartComponentRef}
1690
+ data={dataSet}
1691
+ options={newOptions}
1692
+ />
1390
1693
  </ChartContentWrapper>
1391
1694
  </CarbonChartWrapper>
1392
1695
  {chartToolbar && showTable && (