@react-magma/charts 15.0.0-rc.3 → 15.0.0-rc.5

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.
@@ -56,6 +56,11 @@ export interface ChartToolbarConfig {
56
56
  * @default 2
57
57
  */
58
58
  tableHeaderLevel?: 1 | 2 | 3 | 4 | 5 | 6;
59
+ /**
60
+ * Heading level for the chart title.
61
+ * @default 2
62
+ */
63
+ titleLevel?: 1 | 2 | 3 | 4 | 5 | 6;
59
64
  }
60
65
  export interface CarbonChartProps extends React.HTMLAttributes<HTMLDivElement> {
61
66
  dataSet: Array<object>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@react-magma/charts",
3
- "version": "15.0.0-rc.3",
3
+ "version": "15.0.0-rc.5",
4
4
  "license": "MIT",
5
5
  "repository": {
6
6
  "type": "git",
@@ -853,6 +853,27 @@ describe('CarbonChart', () => {
853
853
  ).not.toBeInTheDocument();
854
854
  });
855
855
 
856
+ it('should render the chart title as h2 by default', () => {
857
+ render(<CarbonChart {...toolbarProps} />);
858
+
859
+ expect(
860
+ screen.getByRole('heading', { level: 2, name: chartOptions.title })
861
+ ).toBeInTheDocument();
862
+ });
863
+
864
+ it('should render the chart title at the level set by titleLevel', () => {
865
+ render(
866
+ <CarbonChart {...toolbarProps} chartToolbar={{ titleLevel: 3 }} />
867
+ );
868
+
869
+ expect(
870
+ screen.getByRole('heading', { level: 3, name: chartOptions.title })
871
+ ).toBeInTheDocument();
872
+ expect(
873
+ screen.queryByRole('heading', { level: 2, name: chartOptions.title })
874
+ ).not.toBeInTheDocument();
875
+ });
876
+
856
877
  it('should always render the more options dropdown with built-in download items', () => {
857
878
  render(<CarbonChart {...toolbarProps} />);
858
879
 
@@ -979,6 +1000,37 @@ describe('CarbonChart', () => {
979
1000
  expect(after[0]).toBe(before[0]);
980
1001
  });
981
1002
 
1003
+ it('unwraps the stale fieldset when Carbon re-renders the legend deeper inside it', () => {
1004
+ const { getByTestId } = render(
1005
+ <CarbonChart
1006
+ testId={testId}
1007
+ dataSet={dataSet}
1008
+ options={chartOptions}
1009
+ type={CarbonChartType.bar}
1010
+ />
1011
+ );
1012
+ const wrapper = getByTestId(testId);
1013
+
1014
+ const staleFieldset = wrapper.querySelector('.cds--cc--legend-fieldset');
1015
+ const legend = staleFieldset.querySelector('.cds--cc--legend');
1016
+
1017
+ act(() => {
1018
+ const layoutChild = document.createElement('div');
1019
+ layoutChild.className = 'layout-child legend';
1020
+ staleFieldset.append(layoutChild);
1021
+ layoutChild.append(legend);
1022
+ mutationObserverCallback?.();
1023
+ });
1024
+
1025
+ const fieldsets = wrapper.querySelectorAll('.cds--cc--legend-fieldset');
1026
+ expect(fieldsets).toHaveLength(1);
1027
+ expect(
1028
+ fieldsets[0].querySelector('.cds--cc--legend-fieldset')
1029
+ ).toBeNull();
1030
+ expect(fieldsets[0].contains(legend)).toBe(true);
1031
+ expect(fieldsets[0].querySelectorAll(':scope > legend')).toHaveLength(1);
1032
+ });
1033
+
982
1034
  it('replaces Carbon\'s generic "Data groups" aria-label with semantic list roles on the legend and its items', () => {
983
1035
  const { getByTestId } = render(
984
1036
  <CarbonChart
@@ -992,16 +1044,53 @@ describe('CarbonChart', () => {
992
1044
 
993
1045
  const legend = wrapper.querySelector('.cds--cc--legend');
994
1046
  expect(legend).not.toBeNull();
995
- expect(legend.getAttribute('aria-label')).toBeNull();
996
- expect(legend.getAttribute('role')).toBe('list');
997
1047
 
998
- const items = legend.querySelectorAll('.legend-item');
1048
+ const itemsHost = legend.matches('[data-name="legend-items"]')
1049
+ ? legend
1050
+ : legend.querySelector('[data-name="legend-items"]') || legend;
1051
+ expect(itemsHost.getAttribute('aria-label')).toBeNull();
1052
+ expect(itemsHost.getAttribute('role')).toBe('list');
1053
+
1054
+ if (itemsHost !== legend) {
1055
+ expect(legend.getAttribute('role')).toBeNull();
1056
+ expect(legend.getAttribute('aria-label')).toBeNull();
1057
+ }
1058
+
1059
+ const items = itemsHost.querySelectorAll('.legend-item');
999
1060
  expect(items.length).toBeGreaterThan(0);
1000
1061
  items.forEach(item => {
1001
1062
  expect(item.getAttribute('role')).toBe('listitem');
1002
1063
  });
1003
1064
  });
1004
1065
 
1066
+ it('restores list semantics when Carbon re-applies role="group" and aria-label on the items container', () => {
1067
+ const { getByTestId } = render(
1068
+ <CarbonChart
1069
+ testId={testId}
1070
+ dataSet={dataSet}
1071
+ options={chartOptions}
1072
+ type={CarbonChartType.bar}
1073
+ />
1074
+ );
1075
+ const wrapper = getByTestId(testId);
1076
+
1077
+ const itemsHost = wrapper.querySelector('[data-name="legend-items"]');
1078
+ expect(itemsHost).not.toBeNull();
1079
+ expect(itemsHost.getAttribute('role')).toBe('list');
1080
+
1081
+ act(() => {
1082
+ itemsHost.setAttribute('role', 'group');
1083
+ itemsHost.setAttribute('aria-label', 'Data groups');
1084
+ mutationObserverCallback();
1085
+ });
1086
+ act(() => {
1087
+ mutationObserverCallback();
1088
+ });
1089
+
1090
+ expect(itemsHost.getAttribute('role')).toBe('list');
1091
+ expect(itemsHost.getAttribute('aria-label')).toBeNull();
1092
+ });
1093
+
1005
1094
  it('uses translated legend instructions from I18nContext', () => {
1006
1095
  const translatedInstructions =
1007
1096
  'Marquer ces cases mettra à jour le graphique.';
@@ -29,6 +29,7 @@ import {
29
29
  DropdownMenuItem,
30
30
  ThemeInterface,
31
31
  ThemeContext,
32
+ useDeviceDetect,
32
33
  useIsInverse,
33
34
  VisuallyHidden,
34
35
  } from 'react-magma-dom';
@@ -105,6 +106,11 @@ export interface ChartToolbarConfig {
105
106
  * @default 2
106
107
  */
107
108
  tableHeaderLevel?: 1 | 2 | 3 | 4 | 5 | 6;
109
+ /**
110
+ * Heading level for the chart title.
111
+ * @default 2
112
+ */
113
+ titleLevel?: 1 | 2 | 3 | 4 | 5 | 6;
108
114
  }
109
115
 
110
116
  export interface CarbonChartProps extends React.HTMLAttributes<HTMLDivElement> {
@@ -1024,7 +1030,11 @@ function CarbonChartToolbar({
1024
1030
  isInverse={isInverse}
1025
1031
  theme={theme}
1026
1032
  >
1027
- <ChartTitle isInverse={isInverse} theme={theme}>
1033
+ <ChartTitle
1034
+ as={`h${config.titleLevel ?? 2}` as keyof JSX.IntrinsicElements}
1035
+ isInverse={isInverse}
1036
+ theme={theme}
1037
+ >
1028
1038
  {resolvedTitle}
1029
1039
  </ChartTitle>
1030
1040
  <ToolbarActions theme={theme}>
@@ -1078,8 +1088,11 @@ export const CarbonChart = React.forwardRef<HTMLDivElement, CarbonChartProps>(
1078
1088
  const [isTableOpen, setIsTableOpen] = React.useState(false);
1079
1089
  const [isFullscreen, setIsFullscreen] = React.useState(false);
1080
1090
  const [legendAnnouncement, setLegendAnnouncement] = React.useState('');
1091
+ const legendGroupAnnounceRef = React.useRef<HTMLDivElement | null>(null);
1081
1092
  const lastTableTriggerRef = React.useRef<HTMLButtonElement | null>(null);
1082
1093
  const legendAnnouncedRef = React.useRef(false);
1094
+ const selectionSignatureRef = React.useRef<string | undefined>(undefined);
1095
+ const { isMacOS, isChrome } = useDeviceDetect();
1083
1096
 
1084
1097
  const mergedRef = React.useCallback(
1085
1098
  (node: HTMLDivElement | null) => {
@@ -1164,11 +1177,37 @@ export const CarbonChart = React.forwardRef<HTMLDivElement, CarbonChartProps>(
1164
1177
  if (!container) return;
1165
1178
 
1166
1179
  const applyListSemantics = (legend: Element) => {
1167
- legend.removeAttribute('aria-label');
1168
- legend.setAttribute('role', 'list');
1169
- legend
1170
- .querySelectorAll('.legend-item')
1171
- .forEach(item => item.setAttribute('role', 'listitem'));
1180
+ const itemsHost = legend.matches('[data-name="legend-items"]')
1181
+ ? legend
1182
+ : legend.querySelector('[data-name="legend-items"]') || legend;
1183
+
1184
+ itemsHost.removeAttribute('aria-label');
1185
+
1186
+ if (itemsHost.getAttribute('role') !== 'list') {
1187
+ itemsHost.setAttribute('role', 'list');
1188
+ }
1189
+
1190
+ legend.querySelectorAll('.legend-item').forEach(item => {
1191
+ if (item.getAttribute('role') !== 'listitem') {
1192
+ item.setAttribute('role', 'listitem');
1193
+ }
1194
+ });
1195
+
1196
+ container.querySelectorAll('[role="list"]').forEach(el => {
1197
+ if (el !== itemsHost && el.contains(itemsHost)) {
1198
+ el.removeAttribute('role');
1199
+ }
1200
+ });
1201
+ container.querySelectorAll('[aria-label="Data groups"]').forEach(el => {
1202
+ if (el !== itemsHost && el.contains(itemsHost)) {
1203
+ el.removeAttribute('aria-label');
1204
+ }
1205
+ });
1206
+ };
1207
+
1208
+ const unwrapFieldset = (fieldset: Element) => {
1209
+ fieldset.querySelector(':scope > legend')?.remove();
1210
+ fieldset.replaceWith(...Array.from(fieldset.childNodes));
1172
1211
  };
1173
1212
 
1174
1213
  const wrapLegend = () => {
@@ -1178,10 +1217,21 @@ export const CarbonChart = React.forwardRef<HTMLDivElement, CarbonChartProps>(
1178
1217
 
1179
1218
  applyListSemantics(legend);
1180
1219
 
1181
- const parent = legend.parentElement;
1220
+ const closestFieldset = legend.closest(
1221
+ 'fieldset.cds--cc--legend-fieldset'
1222
+ );
1223
+
1224
+ container
1225
+ .querySelectorAll('fieldset.cds--cc--legend-fieldset')
1226
+ .forEach(fieldset => {
1227
+ if (fieldset !== closestFieldset) {
1228
+ unwrapFieldset(fieldset);
1229
+ }
1230
+ });
1182
1231
 
1183
- if (parent?.tagName === 'FIELDSET') {
1184
- const existingCaption = parent.querySelector('legend');
1232
+ if (closestFieldset) {
1233
+ const existingCaption =
1234
+ closestFieldset.querySelector(':scope > legend');
1185
1235
 
1186
1236
  if (existingCaption && existingCaption.textContent !== legendLabel) {
1187
1237
  existingCaption.textContent = legendLabel;
@@ -1202,11 +1252,71 @@ export const CarbonChart = React.forwardRef<HTMLDivElement, CarbonChartProps>(
1202
1252
  wrapLegend();
1203
1253
  const observer = new MutationObserver(wrapLegend);
1204
1254
 
1205
- observer.observe(container, { childList: true, subtree: true });
1255
+ observer.observe(container, {
1256
+ childList: true,
1257
+ subtree: true,
1258
+ attributes: true,
1259
+ attributeFilter: ['role', 'aria-label'],
1260
+ });
1206
1261
 
1207
1262
  return () => observer.disconnect();
1208
1263
  }, [legendLabel]);
1209
1264
 
1265
+ React.useEffect(() => {
1266
+ const container = internalRef.current;
1267
+
1268
+ if (!container || !isMacOS || !isChrome) return;
1269
+
1270
+ let announceTimer: ReturnType<typeof setTimeout>;
1271
+ let alternateSuffix = false;
1272
+
1273
+ const closestLegend = (node: EventTarget | null) =>
1274
+ node instanceof Element ? node.closest('.cds--cc--legend') : null;
1275
+
1276
+ const handleFocusIn = (event: FocusEvent) => {
1277
+ const enteredLegend = closestLegend(event.target);
1278
+ const cameFromLegend = closestLegend(event.relatedTarget);
1279
+
1280
+ if (enteredLegend && !cameFromLegend) {
1281
+ if (legendGroupAnnounceRef.current) {
1282
+ legendGroupAnnounceRef.current.textContent = '';
1283
+ }
1284
+
1285
+ clearTimeout(announceTimer);
1286
+ announceTimer = setTimeout(() => {
1287
+ if (legendGroupAnnounceRef.current) {
1288
+ alternateSuffix = !alternateSuffix;
1289
+ legendGroupAnnounceRef.current.textContent =
1290
+ legendLabel + (alternateSuffix ? ' ' : '');
1291
+ }
1292
+ }, 250);
1293
+ }
1294
+ };
1295
+
1296
+ const handleFocusOut = (event: FocusEvent) => {
1297
+ const leftLegend =
1298
+ closestLegend(event.target) && !closestLegend(event.relatedTarget);
1299
+
1300
+ // Reset once focus leaves the legend so re-entering announces again.
1301
+ if (leftLegend) {
1302
+ clearTimeout(announceTimer);
1303
+
1304
+ if (legendGroupAnnounceRef.current) {
1305
+ legendGroupAnnounceRef.current.textContent = '';
1306
+ }
1307
+ }
1308
+ };
1309
+
1310
+ container.addEventListener('focusin', handleFocusIn);
1311
+ container.addEventListener('focusout', handleFocusOut);
1312
+
1313
+ return () => {
1314
+ clearTimeout(announceTimer);
1315
+ container.removeEventListener('focusin', handleFocusIn);
1316
+ container.removeEventListener('focusout', handleFocusOut);
1317
+ };
1318
+ }, [isMacOS, isChrome, legendLabel]);
1319
+
1210
1320
  const handleModalDownloadCsv = React.useCallback(() => {
1211
1321
  downloadCsv(dataSet as Array<Record<string, unknown>>, chartTitle);
1212
1322
  }, [dataSet, chartTitle]);
@@ -1319,6 +1429,20 @@ export const CarbonChart = React.forwardRef<HTMLDivElement, CarbonChartProps>(
1319
1429
  }
1320
1430
  });
1321
1431
 
1432
+ // Carbon re-applies aria-checked (with the same values) on every
1433
+ // render, which still triggers this observer. Only announce when the
1434
+ // selection actually changed, otherwise unrelated re-renders (e.g.
1435
+ // the legend group announcement) cause phantom announcements.
1436
+ const selectionSignature = `${activeLabels.join('|')}::${allItems.length}`;
1437
+
1438
+ if (selectionSignatureRef.current === selectionSignature) return;
1439
+
1440
+ const isFirstRun = selectionSignatureRef.current === undefined;
1441
+
1442
+ selectionSignatureRef.current = selectionSignature;
1443
+
1444
+ if (isFirstRun) return;
1445
+
1322
1446
  if (activeLabels.length === 1) {
1323
1447
  if (!legendAnnouncedRef.current) {
1324
1448
  legendAnnouncedRef.current = true;
@@ -1334,6 +1458,7 @@ export const CarbonChart = React.forwardRef<HTMLDivElement, CarbonChartProps>(
1334
1458
  });
1335
1459
 
1336
1460
  observer.observe(wrapper, {
1461
+ childList: true,
1337
1462
  subtree: true,
1338
1463
  attributes: true,
1339
1464
  attributeFilter: ['aria-checked'],
@@ -1351,6 +1476,9 @@ export const CarbonChart = React.forwardRef<HTMLDivElement, CarbonChartProps>(
1351
1476
  <VisuallyHidden>
1352
1477
  <Announce>{legendAnnouncement}</Announce>
1353
1478
  </VisuallyHidden>
1479
+ <VisuallyHidden>
1480
+ <div aria-live="polite" ref={legendGroupAnnounceRef} />
1481
+ </VisuallyHidden>
1354
1482
  <CarbonChartWrapper
1355
1483
  data-testid={testId}
1356
1484
  isInverse={isInverse}
@@ -18,12 +18,19 @@ export default {
18
18
  control: { type: 'select' },
19
19
  options: Object.values(CarbonChartType),
20
20
  },
21
+ titleLevel: {
22
+ control: { type: 'select' },
23
+ options: [1, 2, 3, 4, 5, 6],
24
+ description: 'Heading level for the chart title (h1–h6).',
25
+ },
21
26
  },
22
27
  } as Meta;
23
28
 
24
- const Template: StoryFn<CarbonChartProps> = args => (
29
+ const Template: StoryFn<
30
+ CarbonChartProps & { titleLevel?: 1 | 2 | 3 | 4 | 5 | 6 }
31
+ > = ({ titleLevel, ...args }) => (
25
32
  <Card isInverse={args.isInverse} style={{ padding: '12px' }}>
26
- <CarbonChart {...args} />
33
+ <CarbonChart {...args} chartToolbar={{ titleLevel }} />
27
34
  </Card>
28
35
  );
29
36