@react-magma/charts 13.3.0-next.1 → 13.3.1

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.
@@ -157,6 +157,16 @@ export interface CarbonChartProps extends React.HTMLAttributes<HTMLDivElement> {
157
157
  * toolbar is automatically disabled.
158
158
  */
159
159
  chartToolbar?: ChartToolbarConfig;
160
+ /**
161
+ * Custom content rendered below the toolbar row and above the chart itself,
162
+ * for example a filter. Requires `chartToolbar`; ignored without it.
163
+ *
164
+ * Providing this lays the toolbar out in normal flow instead of overlaying
165
+ * the single row Carbon reserves for its title, so the rendered height
166
+ * becomes toolbar + content + chart rather than the chart box alone. Set
167
+ * `options.height` so the chart still has a definite height of its own.
168
+ */
169
+ additionalContent?: React.ReactNode;
160
170
  }
161
171
 
162
172
  const ChartContentWrapper = styled.div`
@@ -165,6 +175,7 @@ const ChartContentWrapper = styled.div`
165
175
  `;
166
176
 
167
177
  const FullscreenRoot = styled.div<{
178
+ isFlowLayout?: boolean;
168
179
  isInverse?: boolean;
169
180
  theme: ThemeInterface;
170
181
  }>`
@@ -177,9 +188,34 @@ const FullscreenRoot = styled.div<{
177
188
  props.isInverse
178
189
  ? props.theme.colors.primary700
179
190
  : props.theme.colors.neutral100};
191
+
192
+ ${props =>
193
+ props.isFlowLayout
194
+ ? `
195
+ box-sizing: border-box;
196
+ display: flex;
197
+ flex-direction: column;
198
+ padding: 2em;
199
+
200
+ .carbon-chart-wrapper,
201
+ .carbon-chart-content {
202
+ display: flex;
203
+ flex: 1 1 auto;
204
+ flex-direction: column;
205
+ min-height: 0;
206
+ }
207
+
208
+ .cds--chart-holder {
209
+ flex: 1 1 auto;
210
+ height: auto !important;
211
+ min-height: 0;
212
+ }
213
+ `
214
+ : `
180
215
  .cds--chart-holder {
181
216
  height: 100vh !important;
182
217
  }
218
+ `}
183
219
  }
184
220
  `;
185
221
 
@@ -217,6 +253,14 @@ const CarbonChartWrapper = styled.div<{
217
253
  }
218
254
  }
219
255
 
256
+ .cds--chart-holder.filled,
257
+ .cds--chart-holder.filled .cds--cc--chart-wrapper {
258
+ background-color: ${props =>
259
+ props.isInverse
260
+ ? props.theme.colors.primary600
261
+ : props.theme.colors.neutral100};
262
+ }
263
+
220
264
  .cds--data-table thead tr th {
221
265
  background: ${props =>
222
266
  props.isInverse ? props.theme.colors.primary700 : ''} !important;
@@ -700,6 +744,7 @@ interface ExtendedChartOptions extends ChartOptions {
700
744
  }
701
745
 
702
746
  const ToolbarWrapper = styled.div<{
747
+ isFlowLayout?: boolean;
703
748
  isFullscreen?: boolean;
704
749
  isInverse?: boolean;
705
750
  theme: ThemeInterface;
@@ -707,12 +752,20 @@ const ToolbarWrapper = styled.div<{
707
752
  align-items: center;
708
753
  display: flex;
709
754
  justify-content: space-between;
710
- left: ${props => (props.isFullscreen ? '2em' : '0')};
711
- position: absolute;
712
- right: ${props => (props.isFullscreen ? '2em' : '0')};
713
- top: ${props => (props.isFullscreen ? '2em' : '0')};
714
755
  z-index: 2;
715
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
+
716
769
  button {
717
770
  color: ${props =>
718
771
  props.isInverse
@@ -758,6 +811,10 @@ const TitleSlot = styled.div`
758
811
  display: flex;
759
812
  `;
760
813
 
814
+ const ChartSlot = styled.div<{ theme: ThemeInterface }>`
815
+ margin: ${props => props.theme.spaceScale.spacing05} 0 0;
816
+ `;
817
+
761
818
  const ToolbarActions = styled.div<{ theme: ThemeInterface }>`
762
819
  align-items: center;
763
820
  display: flex;
@@ -823,189 +880,54 @@ function downloadCsv(dataSet: Array<Record<string, unknown>>, title: string) {
823
880
  URL.revokeObjectURL(url);
824
881
  }
825
882
 
826
- function inlineStyles(source: Element, target: Element) {
827
- const computed = window.getComputedStyle(source);
828
- if (target instanceof HTMLElement || target instanceof SVGElement) {
829
- target.setAttribute(
830
- 'style',
831
- Array.from(computed)
832
- .map(prop => `${prop}:${computed.getPropertyValue(prop)}`)
833
- .join(';')
834
- );
835
- }
836
- for (let i = 0; i < source.children.length; i++) {
837
- if (target.children[i]) {
838
- inlineStyles(source.children[i], target.children[i]);
839
- }
840
- }
841
- }
842
-
843
- interface LegendItem {
844
- label: string;
845
- color: string;
883
+ interface CarbonChartCore {
884
+ services?: {
885
+ domUtils?: { exportToPNG: () => void; exportToJPG: () => void };
886
+ };
846
887
  }
847
888
 
848
- function readLegendItems(wrapper: HTMLElement): LegendItem[] {
849
- const items: LegendItem[] = [];
850
- wrapper.querySelectorAll('.legend-item').forEach(item => {
851
- const checkbox = item.querySelector<HTMLElement>('.checkbox');
852
- const label = item.querySelector('p');
853
- if (checkbox && label) {
854
- items.push({
855
- color: checkbox.style.background || checkbox.style.backgroundColor,
856
- label: label.textContent || '',
857
- });
858
- }
859
- });
860
- return items;
889
+ interface CarbonChartComponent {
890
+ chart?: CarbonChartCore;
861
891
  }
862
892
 
863
- function drawLegend(
864
- ctx: CanvasRenderingContext2D,
865
- items: LegendItem[],
866
- startY: number,
867
- canvasWidth: number,
868
- scale: number
893
+ function exportCarbonChartImage(
894
+ chart: CarbonChartCore | null | undefined,
895
+ toolbarWrapper: Element | null | undefined,
896
+ format: 'png' | 'jpg'
869
897
  ) {
870
- const fontSize = 13 * scale;
871
- const swatchSize = 12 * scale;
872
- const gap = 8 * scale;
873
- const itemGap = 16 * scale;
874
- const paddingX = 16 * scale;
898
+ const domUtils = chart?.services?.domUtils;
875
899
 
876
- ctx.font = `${fontSize}px sans-serif`;
877
- ctx.textBaseline = 'middle';
900
+ if (!domUtils) return;
878
901
 
879
- let x = paddingX;
880
- let y = startY;
902
+ const magmaWrapper = toolbarWrapper?.classList.contains('has-magma-toolbar')
903
+ ? toolbarWrapper
904
+ : null;
881
905
 
882
- for (const item of items) {
883
- const textWidth = ctx.measureText(item.label).width;
884
- const itemWidth = swatchSize + gap + textWidth + itemGap;
906
+ magmaWrapper?.classList.remove('has-magma-toolbar');
885
907
 
886
- if (x + itemWidth > canvasWidth - paddingX && x > paddingX) {
887
- x = paddingX;
888
- y += fontSize + gap;
889
- }
890
-
891
- ctx.fillStyle = item.color;
892
- ctx.fillRect(x, y - swatchSize / 2, swatchSize, swatchSize);
893
-
894
- ctx.fillStyle = '#161616';
895
- ctx.fillText(item.label, x + swatchSize + gap, y);
896
-
897
- x += itemWidth;
898
- }
899
-
900
- return y + fontSize + gap;
901
- }
902
-
903
- function downloadImage(
904
- wrapperRef: React.RefObject<HTMLDivElement | null>,
905
- title: string,
906
- format: 'png' | 'jpg'
907
- ) {
908
- const wrapper = wrapperRef.current;
909
- if (!wrapper) return;
910
- const svg = wrapper.querySelector('svg.layout-svg-wrapper');
911
- if (!svg) return;
912
-
913
- const svgRect = svg.getBoundingClientRect();
914
- const legendItems = readLegendItems(wrapper);
915
-
916
- const doWork = () => {
917
- const scale = 2;
918
-
919
- // Measure legend height
920
- const tempCanvas = document.createElement('canvas');
921
- const tempCtx = tempCanvas.getContext('2d');
922
- const fontSize = 13 * scale;
923
- const swatchSize = 12 * scale;
924
- const gap = 8 * scale;
925
- const itemGap = 16 * scale;
926
- const paddingX = 16 * scale;
927
- const canvasWidth = svgRect.width * scale;
928
-
929
- let legendHeight = 0;
930
- if (legendItems.length > 0 && tempCtx) {
931
- tempCtx.font = `${fontSize}px sans-serif`;
932
- let x = paddingX;
933
- let rows = 1;
934
- for (const item of legendItems) {
935
- const textWidth = tempCtx.measureText(item.label).width;
936
- const itemWidth = swatchSize + gap + textWidth + itemGap;
937
- if (x + itemWidth > canvasWidth - paddingX && x > paddingX) {
938
- x = paddingX;
939
- rows++;
940
- }
941
- x += itemWidth;
942
- }
943
- legendHeight = rows * (fontSize + gap) + gap * 2;
944
- }
945
-
946
- const width = svgRect.width * scale;
947
- const height = svgRect.height * scale + legendHeight;
948
-
949
- const clone = svg.cloneNode(true) as SVGSVGElement;
950
- clone.setAttribute('width', String(svgRect.width));
951
- clone.setAttribute('height', String(svgRect.height));
952
- clone.setAttribute('viewBox', `0 0 ${svgRect.width} ${svgRect.height}`);
953
- clone.setAttribute('xmlns', 'http://www.w3.org/2000/svg');
954
-
955
- inlineStyles(svg, clone);
956
-
957
- const serializer = new XMLSerializer();
958
- const svgString = serializer.serializeToString(clone);
959
- const svgBlob = new Blob([svgString], {
960
- type: 'image/svg+xml;charset=utf-8',
961
- });
962
- const url = URL.createObjectURL(svgBlob);
963
-
964
- const mimeType = format === 'jpg' ? 'image/jpeg' : 'image/png';
965
- const ext = format === 'jpg' ? 'jpg' : 'png';
966
-
967
- const img = new Image();
968
- img.onload = () => {
969
- const canvas = document.createElement('canvas');
970
- canvas.width = width;
971
- canvas.height = height;
972
- const ctx = canvas.getContext('2d');
973
- if (!ctx) return;
974
-
975
- ctx.fillStyle = '#ffffff';
976
- ctx.fillRect(0, 0, canvas.width, canvas.height);
977
- ctx.drawImage(img, 0, 0, svgRect.width * scale, svgRect.height * scale);
978
- URL.revokeObjectURL(url);
979
-
980
- if (legendItems.length > 0) {
981
- drawLegend(
982
- ctx,
983
- legendItems,
984
- svgRect.height * scale + gap,
985
- width,
986
- scale
987
- );
988
- }
989
-
990
- canvas.toBlob(blob => {
991
- if (!blob) return;
992
- const imgUrl = URL.createObjectURL(blob);
993
- const a = document.createElement('a');
994
- a.href = imgUrl;
995
- a.download = `${title || 'chart'}.${ext}`;
996
- a.click();
997
- URL.revokeObjectURL(imgUrl);
998
- }, mimeType);
999
- };
1000
- img.onerror = () => URL.revokeObjectURL(url);
1001
- img.src = url;
908
+ let restored = false;
909
+ const restore = () => {
910
+ if (restored) return;
911
+ restored = true;
912
+ magmaWrapper?.classList.add('has-magma-toolbar');
1002
913
  };
1003
914
 
1004
- // Defer to idle time with a 2-second deadline so it always runs.
1005
- if (typeof requestIdleCallback === 'function') {
1006
- requestIdleCallback(doWork, { timeout: 2000 });
1007
- } else {
1008
- setTimeout(doWork, 0);
915
+ try {
916
+ if (format === 'jpg') {
917
+ domUtils.exportToJPG();
918
+ } else {
919
+ domUtils.exportToPNG();
920
+ }
921
+ } catch (error) {
922
+ console.warn('Carbon chart image export failed', error);
923
+ } finally {
924
+ // Re-add before the next paint so the title swap is never visible on
925
+ // screen; the timeout is only a fallback for when requestAnimationFrame is
926
+ // paused (e.g. the tab is in the background).
927
+ if (typeof requestAnimationFrame === 'function') {
928
+ requestAnimationFrame(restore);
929
+ }
930
+ setTimeout(restore, 1000);
1009
931
  }
1010
932
  }
1011
933
 
@@ -1031,8 +953,10 @@ const ALL_CHARTS: Record<CarbonChartType, React.ComponentType<any>> = {
1031
953
  };
1032
954
 
1033
955
  interface InternalToolbarProps {
956
+ chartRef: React.MutableRefObject<CarbonChartComponent | null>;
1034
957
  config: ChartToolbarConfig;
1035
958
  dataSet: Array<Record<string, unknown>>;
959
+ isFlowLayout: boolean;
1036
960
  isInverse: boolean;
1037
961
  isTableOpen: boolean;
1038
962
  isFullscreen: boolean;
@@ -1044,8 +968,10 @@ interface InternalToolbarProps {
1044
968
  }
1045
969
 
1046
970
  function CarbonChartToolbar({
971
+ chartRef,
1047
972
  config,
1048
973
  dataSet,
974
+ isFlowLayout,
1049
975
  isInverse,
1050
976
  isTableOpen,
1051
977
  isFullscreen,
@@ -1060,17 +986,28 @@ function CarbonChartToolbar({
1060
986
  const showFullscreen = config.fullscreen !== false;
1061
987
  const resolvedTitle = title || t.defaultTitle;
1062
988
 
989
+ const exportImage = React.useCallback(
990
+ (format: 'png' | 'jpg') => {
991
+ exportCarbonChartImage(
992
+ chartRef.current?.chart,
993
+ wrapperRef.current?.querySelector('.carbon-chart-wrapper'),
994
+ format
995
+ );
996
+ },
997
+ [chartRef, wrapperRef]
998
+ );
999
+
1063
1000
  const handleDownloadCsv = React.useCallback(() => {
1064
1001
  downloadCsv(dataSet, title);
1065
1002
  }, [dataSet, title]);
1066
1003
 
1067
1004
  const handleDownloadPng = React.useCallback(() => {
1068
- downloadImage(wrapperRef, title, 'png');
1069
- }, [wrapperRef, title]);
1005
+ exportImage('png');
1006
+ }, [exportImage]);
1070
1007
 
1071
1008
  const handleDownloadJpg = React.useCallback(() => {
1072
- downloadImage(wrapperRef, title, 'jpg');
1073
- }, [wrapperRef, title]);
1009
+ exportImage('jpg');
1010
+ }, [exportImage]);
1074
1011
 
1075
1012
  const moreOptionsContent = (
1076
1013
  <>
@@ -1094,6 +1031,7 @@ function CarbonChartToolbar({
1094
1031
 
1095
1032
  return (
1096
1033
  <ToolbarWrapper
1034
+ isFlowLayout={isFlowLayout}
1097
1035
  isFullscreen={isFullscreen}
1098
1036
  isInverse={isInverse}
1099
1037
  theme={theme}
@@ -1152,6 +1090,7 @@ export const CarbonChart = React.forwardRef<HTMLDivElement, CarbonChartProps>(
1152
1090
  type,
1153
1091
  dataSet,
1154
1092
  options,
1093
+ additionalContent,
1155
1094
  ariaLabel,
1156
1095
  chartToolbar,
1157
1096
  ...rest
@@ -1160,6 +1099,7 @@ export const CarbonChart = React.forwardRef<HTMLDivElement, CarbonChartProps>(
1160
1099
  const isInverse = useIsInverse(isInverseProp);
1161
1100
  const toolbarI18n = useChartToolbarI18n();
1162
1101
  const internalRef = React.useRef<HTMLDivElement | null>(null);
1102
+ const chartComponentRef = React.useRef<CarbonChartComponent | null>(null);
1163
1103
 
1164
1104
  const [isTableOpen, setIsTableOpen] = React.useState(false);
1165
1105
  const [isFullscreen, setIsFullscreen] = React.useState(false);
@@ -1186,6 +1126,8 @@ export const CarbonChart = React.forwardRef<HTMLDivElement, CarbonChartProps>(
1186
1126
  ? chartToolbar.fullscreen !== false
1187
1127
  : false;
1188
1128
 
1129
+ const isFlowLayout = Boolean(chartToolbar && additionalContent);
1130
+
1189
1131
  const savedHeightRef = React.useRef<string>('');
1190
1132
 
1191
1133
  React.useEffect(() => {
@@ -1197,7 +1139,8 @@ export const CarbonChart = React.forwardRef<HTMLDivElement, CarbonChartProps>(
1197
1139
 
1198
1140
  const chartHolder =
1199
1141
  internalRef.current?.querySelector<HTMLElement>('.cds--chart-holder');
1200
- if (chartHolder) {
1142
+
1143
+ if (chartHolder && !isFlowLayout) {
1201
1144
  if (isFs) {
1202
1145
  savedHeightRef.current = chartHolder.style.height;
1203
1146
  chartHolder.style.height = '100vh';
@@ -1212,11 +1155,11 @@ export const CarbonChart = React.forwardRef<HTMLDivElement, CarbonChartProps>(
1212
1155
  // Restore height if the component unmounts while in fullscreen.
1213
1156
  const chartHolder =
1214
1157
  internalRef.current?.querySelector<HTMLElement>('.cds--chart-holder');
1215
- if (chartHolder && document.fullscreenElement) {
1158
+ if (chartHolder && document.fullscreenElement && !isFlowLayout) {
1216
1159
  chartHolder.style.height = savedHeightRef.current;
1217
1160
  }
1218
1161
  };
1219
- }, [fullscreenEnabled]);
1162
+ }, [fullscreenEnabled, isFlowLayout]);
1220
1163
 
1221
1164
  const openTableModal = React.useCallback(
1222
1165
  (event: React.MouseEvent<HTMLButtonElement>) => {
@@ -1442,7 +1385,15 @@ export const CarbonChart = React.forwardRef<HTMLDivElement, CarbonChartProps>(
1442
1385
  type: 'none',
1443
1386
  },
1444
1387
  },
1445
- ...(chartToolbar ? { toolbar: { enabled: false } } : {}),
1388
+ ...(chartToolbar
1389
+ ? {
1390
+ toolbar: { enabled: false },
1391
+ title: chartTitle,
1392
+ ...(options.fileDownload
1393
+ ? {}
1394
+ : { fileDownload: { fileName: chartTitle } }),
1395
+ }
1396
+ : {}),
1446
1397
  };
1447
1398
 
1448
1399
  const ChartType = ALL_CHARTS[type];
@@ -1457,94 +1408,17 @@ export const CarbonChart = React.forwardRef<HTMLDivElement, CarbonChartProps>(
1457
1408
  return () => cancelAnimationFrame(rafId);
1458
1409
  }, [ariaLabel]);
1459
1410
 
1460
- // Make Carbon Charts data points keyboard-focusable.
1461
- React.useEffect(() => {
1462
- const wrapper = internalRef.current;
1463
- if (!wrapper) return;
1464
-
1465
- const isDot = (el: EventTarget | null): el is SVGCircleElement =>
1466
- el instanceof Element &&
1467
- el.nodeName.toLowerCase() === 'circle' &&
1468
- el.classList.contains('dot');
1469
-
1470
- const onFocusIn = (e: FocusEvent) => {
1471
- if (!isDot(e.target)) return;
1472
- const dot = e.target as SVGCircleElement;
1473
- dot.style.opacity = '1';
1474
- const { left, top, width, height } = dot.getBoundingClientRect();
1475
- const cx = left + width / 2;
1476
- const cy = top + height / 2;
1477
- dot.dispatchEvent(
1478
- new MouseEvent('mouseover', {
1479
- bubbles: true,
1480
- clientX: cx,
1481
- clientY: cy,
1482
- screenX: cx,
1483
- screenY: cy,
1484
- })
1485
- );
1486
- dot.dispatchEvent(
1487
- new MouseEvent('mousemove', {
1488
- bubbles: true,
1489
- clientX: cx,
1490
- clientY: cy,
1491
- screenX: cx,
1492
- screenY: cy,
1493
- })
1494
- );
1495
- };
1496
-
1497
- const onFocusOut = (e: FocusEvent) => {
1498
- if (!isDot(e.target)) return;
1499
- const dot = e.target;
1500
- dot.style.opacity = '';
1501
- dot.dispatchEvent(new MouseEvent('mouseout', { bubbles: true }));
1502
- };
1503
-
1504
- const onKeyDown = (e: KeyboardEvent) => {
1505
- if (!isDot(e.target)) return;
1506
- if (e.key !== 'Enter' && e.key !== ' ') return;
1507
- e.preventDefault();
1508
- const dot = e.target;
1509
- const { left, top, width, height } = dot.getBoundingClientRect();
1510
- const cx = left + width / 2;
1511
- const cy = top + height / 2;
1512
- dot.dispatchEvent(
1513
- new MouseEvent('click', {
1514
- bubbles: true,
1515
- clientX: cx,
1516
- clientY: cy,
1517
- })
1518
- );
1519
- };
1520
-
1521
- const rafId = requestAnimationFrame(() => {
1522
- wrapper
1523
- .querySelectorAll<SVGCircleElement>('circle.dot')
1524
- .forEach(dot => {
1525
- if (!dot.hasAttribute('tabindex')) {
1526
- dot.setAttribute('tabindex', '0');
1527
- }
1528
- });
1529
- });
1530
-
1531
- wrapper.addEventListener('focusin', onFocusIn);
1532
- wrapper.addEventListener('focusout', onFocusOut);
1533
- wrapper.addEventListener('keydown', onKeyDown);
1534
-
1535
- return () => {
1536
- cancelAnimationFrame(rafId);
1537
- wrapper.removeEventListener('focusin', onFocusIn);
1538
- wrapper.removeEventListener('focusout', onFocusOut);
1539
- wrapper.removeEventListener('keydown', onKeyDown);
1540
- };
1541
- }, [type]);
1542
-
1543
1411
  React.useEffect(() => {
1544
1412
  const timer = setTimeout(() => {
1545
1413
  if (internalRef.current) {
1546
1414
  internalRef.current
1547
- .querySelectorAll<SVGGElement>('g[aria-label]')
1415
+ .querySelectorAll<SVGGElement>('g.ruler[aria-label]')
1416
+ .forEach(g => {
1417
+ g.setAttribute('aria-hidden', 'true');
1418
+ });
1419
+
1420
+ internalRef.current
1421
+ .querySelectorAll<SVGGElement>('g[aria-label]:not(.ruler)')
1548
1422
  .forEach(g => {
1549
1423
  const role = g.getAttribute('role');
1550
1424
 
@@ -1560,6 +1434,30 @@ export const CarbonChart = React.forwardRef<HTMLDivElement, CarbonChartProps>(
1560
1434
  return () => clearTimeout(timer);
1561
1435
  }, [type, dataSet]);
1562
1436
 
1437
+ React.useEffect(() => {
1438
+ const container = internalRef.current;
1439
+
1440
+ if (!container) return;
1441
+
1442
+ const hideRulerFromAT = () => {
1443
+ container
1444
+ .querySelectorAll<SVGGElement>('g.ruler[aria-label]')
1445
+ .forEach(g => {
1446
+ if (!g.hasAttribute('aria-hidden')) {
1447
+ g.setAttribute('aria-hidden', 'true');
1448
+ }
1449
+ });
1450
+ };
1451
+
1452
+ hideRulerFromAT();
1453
+
1454
+ const observer = new MutationObserver(hideRulerFromAT);
1455
+
1456
+ observer.observe(container, { childList: true, subtree: true });
1457
+
1458
+ return () => observer.disconnect();
1459
+ }, [type, dataSet]);
1460
+
1563
1461
  React.useEffect(() => {
1564
1462
  const wrapper = internalRef.current;
1565
1463
 
@@ -1621,6 +1519,113 @@ export const CarbonChart = React.forwardRef<HTMLDivElement, CarbonChartProps>(
1621
1519
  return () => observer.disconnect();
1622
1520
  }, [type, dataSet]);
1623
1521
 
1522
+ // Make Carbon Charts data points keyboard-focusable.
1523
+ React.useEffect(() => {
1524
+ const wrapper = internalRef.current;
1525
+
1526
+ if (!wrapper) return;
1527
+
1528
+ const stampDotTabIndex = () => {
1529
+ wrapper
1530
+ .querySelectorAll<SVGCircleElement>('circle.dot')
1531
+ .forEach(dot => {
1532
+ if (!dot.hasAttribute('tabindex')) {
1533
+ dot.setAttribute('tabindex', '0');
1534
+ }
1535
+ });
1536
+ };
1537
+
1538
+ const isDot = (el: EventTarget | null): el is SVGCircleElement =>
1539
+ el instanceof Element &&
1540
+ el.nodeName.toLowerCase() === 'circle' &&
1541
+ el.classList.contains('dot');
1542
+
1543
+ const onFocusIn = (e: FocusEvent) => {
1544
+ if (!isDot(e.target)) return;
1545
+ const dot = e.target as SVGCircleElement;
1546
+
1547
+ const { left, top, width, height } = dot.getBoundingClientRect();
1548
+ const cx = left + width / 2;
1549
+ const cy = top + height / 2;
1550
+
1551
+ dot.dispatchEvent(
1552
+ new MouseEvent('mouseover', {
1553
+ bubbles: true,
1554
+ clientX: cx,
1555
+ clientY: cy,
1556
+ screenX: cx,
1557
+ screenY: cy,
1558
+ })
1559
+ );
1560
+ dot.dispatchEvent(
1561
+ new MouseEvent('mousemove', {
1562
+ bubbles: true,
1563
+ clientX: cx,
1564
+ clientY: cy,
1565
+ screenX: cx,
1566
+ screenY: cy,
1567
+ })
1568
+ );
1569
+ };
1570
+
1571
+ const onFocusOut = (e: FocusEvent) => {
1572
+ if (!isDot(e.target)) return;
1573
+ const dot = e.target;
1574
+
1575
+ // Keep tooltip context while Tab focus moves between chart points.
1576
+ if (isDot(e.relatedTarget)) {
1577
+ return;
1578
+ }
1579
+
1580
+ dot.dispatchEvent(new MouseEvent('mouseout', { bubbles: true }));
1581
+ };
1582
+
1583
+ const onKeyDown = (e: KeyboardEvent) => {
1584
+ if (!isDot(e.target)) return;
1585
+ if (e.key !== 'Enter' && e.key !== ' ') return;
1586
+ e.preventDefault();
1587
+ const dot = e.target;
1588
+ const { left, top, width, height } = dot.getBoundingClientRect();
1589
+ const cx = left + width / 2;
1590
+ const cy = top + height / 2;
1591
+
1592
+ dot.dispatchEvent(
1593
+ new MouseEvent('click', {
1594
+ bubbles: true,
1595
+ clientX: cx,
1596
+ clientY: cy,
1597
+ })
1598
+ );
1599
+ };
1600
+
1601
+ const rafId = requestAnimationFrame(() => {
1602
+ stampDotTabIndex();
1603
+ });
1604
+
1605
+ const dotObserver = new MutationObserver(() => {
1606
+ stampDotTabIndex();
1607
+ });
1608
+
1609
+ dotObserver.observe(wrapper, {
1610
+ childList: true,
1611
+ subtree: true,
1612
+ attributes: true,
1613
+ attributeFilter: ['class', 'style', 'tabindex'],
1614
+ });
1615
+
1616
+ wrapper.addEventListener('focusin', onFocusIn);
1617
+ wrapper.addEventListener('focusout', onFocusOut);
1618
+ wrapper.addEventListener('keydown', onKeyDown);
1619
+
1620
+ return () => {
1621
+ cancelAnimationFrame(rafId);
1622
+ dotObserver.disconnect();
1623
+ wrapper.removeEventListener('focusin', onFocusIn);
1624
+ wrapper.removeEventListener('focusout', onFocusOut);
1625
+ wrapper.removeEventListener('keydown', onKeyDown);
1626
+ };
1627
+ }, [type, dataSet]);
1628
+
1624
1629
  const groupsLength = Object.keys(colorScale).length;
1625
1630
 
1626
1631
  const showTable = chartToolbar?.showAsTable !== false;
@@ -1628,7 +1633,12 @@ export const CarbonChart = React.forwardRef<HTMLDivElement, CarbonChartProps>(
1628
1633
  if (!ChartType) return null;
1629
1634
 
1630
1635
  return (
1631
- <FullscreenRoot ref={mergedRef} isInverse={isInverse} theme={theme}>
1636
+ <FullscreenRoot
1637
+ ref={mergedRef}
1638
+ isFlowLayout={isFlowLayout}
1639
+ isInverse={isInverse}
1640
+ theme={theme}
1641
+ >
1632
1642
  <VisuallyHidden>
1633
1643
  <Announce>{legendAnnouncement}</Announce>
1634
1644
  </VisuallyHidden>
@@ -1639,14 +1649,16 @@ export const CarbonChart = React.forwardRef<HTMLDivElement, CarbonChartProps>(
1639
1649
  data-testid={testId}
1640
1650
  isInverse={isInverse}
1641
1651
  theme={theme}
1642
- className={`carbon-chart-wrapper${chartToolbar ? ' has-magma-toolbar' : ''}`}
1652
+ className={`carbon-chart-wrapper${
1653
+ chartToolbar ? ' has-magma-toolbar' : ''
1654
+ }`}
1643
1655
  groupsLength={groupsLength < 6 ? groupsLength : 14}
1644
1656
  role="region"
1645
1657
  aria-label={ariaLabel || chartTitle}
1646
1658
  aria-roledescription="chart"
1647
1659
  {...rest}
1648
1660
  >
1649
- <ChartContentWrapper>
1661
+ <ChartContentWrapper className="carbon-chart-content">
1650
1662
  {chartToolbar && (
1651
1663
  /*
1652
1664
  * Slot content comes from the adopter, so it resolves
@@ -1656,8 +1668,10 @@ export const CarbonChart = React.forwardRef<HTMLDivElement, CarbonChartProps>(
1656
1668
  */
1657
1669
  <InverseContext.Provider value={{ isInverse }}>
1658
1670
  <CarbonChartToolbar
1671
+ chartRef={chartComponentRef}
1659
1672
  config={chartToolbar}
1660
1673
  dataSet={dataSet as Array<Record<string, unknown>>}
1674
+ isFlowLayout={isFlowLayout}
1661
1675
  isInverse={isInverse}
1662
1676
  isTableOpen={isTableOpen}
1663
1677
  isFullscreen={isFullscreen}
@@ -1667,9 +1681,16 @@ export const CarbonChart = React.forwardRef<HTMLDivElement, CarbonChartProps>(
1667
1681
  title={chartTitle}
1668
1682
  wrapperRef={internalRef}
1669
1683
  />
1684
+ {isFlowLayout && (
1685
+ <ChartSlot theme={theme}>{additionalContent}</ChartSlot>
1686
+ )}
1670
1687
  </InverseContext.Provider>
1671
1688
  )}
1672
- <ChartType data={dataSet} options={newOptions} />
1689
+ <ChartType
1690
+ ref={chartComponentRef}
1691
+ data={dataSet}
1692
+ options={newOptions}
1693
+ />
1673
1694
  </ChartContentWrapper>
1674
1695
  </CarbonChartWrapper>
1675
1696
  {chartToolbar && showTable && (