Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(a11y): add label for screen readers #1121

Merged
merged 16 commits into from
Apr 22, 2021
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion api/charts.api.md
Original file line number Diff line number Diff line change
Expand Up @@ -621,7 +621,7 @@ export const DEFAULT_TOOLTIP_SNAP = true;
export const DEFAULT_TOOLTIP_TYPE: "vertical";

// @public (undocumented)
export type DefaultSettingsProps = 'id' | 'chartType' | 'specType' | 'rendering' | 'rotation' | 'resizeDebounce' | 'animateData' | 'debug' | 'tooltip' | 'theme' | 'hideDuplicateAxes' | 'brushAxis' | 'minBrushDelta' | 'externalPointerEvents' | 'showLegend' | 'showLegendExtra' | 'legendPosition' | 'legendMaxDepth' | 'description' | 'useDefaultSummary';
export type DefaultSettingsProps = 'id' | 'chartType' | 'specType' | 'rendering' | 'rotation' | 'resizeDebounce' | 'animateData' | 'debug' | 'tooltip' | 'theme' | 'hideDuplicateAxes' | 'brushAxis' | 'minBrushDelta' | 'externalPointerEvents' | 'showLegend' | 'showLegendExtra' | 'legendPosition' | 'legendMaxDepth' | 'description' | 'useDefaultSummary' | 'label' | 'HeadingLevel';

// @public (undocumented)
export const DEPTH_KEY = "depth";
Expand Down Expand Up @@ -1746,7 +1746,10 @@ export interface SettingsSpec extends Spec, LegendSpec {
description?: string;
// @alpha
externalPointerEvents: ExternalPointerEventsSettings;
HeadingLevel: 'h1' | 'h2' | 'h3' | 'h4' | 'h5' | 'h6' | 'p';
hideDuplicateAxes: boolean;
label?: string;
labelledBy?: string;
minBrushDelta?: number;
noResults?: ComponentType | ReactChild;
// (undocumented)
Expand Down
24 changes: 21 additions & 3 deletions src/chart_types/xy_chart/renderer/canvas/xy_chart.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,9 @@ export interface ReactiveChartStateProps {
description?: string;
useDefaultSummary: boolean;
chartId: string;
label?: string;
myasonik marked this conversation as resolved.
Show resolved Hide resolved
labelledBy?: string;
HeadingLevel: 'h1' | 'h2' | 'h3' | 'h4' | 'h5' | 'h6' | 'p';
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

each prop name should follow the camelCase with the first char lowercase, independently if you use them later as component

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should also sanitize this: it's true that in a TS this will throw error if the value is one of the union type, but in the JS compiled world not. This can lead to errors if this heading comes from an user input, or stored string value.
we can have a function that checks and returns/construct the appropriate header based on the input, like:

{label && <HeadingLevel id={chartIdLabel}>{label}</HeadingLevel>}

const ChartLabel = ({headingLevel: 'h1' | 'h2' | 'h3' | 'h4' | 'h5' | 'h6' | 'p', id: string, label?: string}) => {
  if(!label) return null;
  
  switch(headingLevel){ 
    case 'h1':
      return <h1 id={id}>{label}</h1>
      ......
   }
}

.....

<ChartLabel id={chartIdLabel} label={label} headingLevel={headingLevel} />

@nickofthyme other suggestions?

}

interface ReactiveChartDispatchProps {
Expand Down Expand Up @@ -162,6 +165,9 @@ class XYChartComponent extends React.Component<XYChartProps> {
description,
useDefaultSummary,
chartId,
label,
labelledBy,
HeadingLevel,
} = this.props;

if (!initialized || isChartEmpty) {
Expand All @@ -172,8 +178,14 @@ class XYChartComponent extends React.Component<XYChartProps> {
const chartSeriesTypes =
seriesTypes.size > 1 ? `Mixed chart: ${[...seriesTypes].join(' and ')} chart` : `${[...seriesTypes]} chart`;
const chartIdDescription = `${chartId}--description`;
const chartIdLabel = label ? `${chartId}--label` : undefined;

const ariaProps = {
myasonik marked this conversation as resolved.
Show resolved Hide resolved
'aria-labelledby': labelledBy || label ? labelledBy ?? chartIdLabel : '',
myasonik marked this conversation as resolved.
Show resolved Hide resolved
'aria-describedby': `${labelledBy || ''} ${useDefaultSummary ? chartIdLabel : ''}`,

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Did you mean to use chartIdDescription here?

Suggested change
'aria-describedby': `${labelledBy || ''} ${useDefaultSummary ? chartIdLabel : ''}`,
'aria-describedby': `${labelledBy || ''} ${useDefaultSummary ? chartIdDescription : ''}`,

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

And I'm also confused by the fact that we are reusing labelledByin the describedBy. Should we introduce a new props called describedBy?

};
return (
<figure>
<figure {...ariaProps}>
<canvas
ref={forwardStageRef}
className="echCanvasRenderer"
Expand All @@ -185,8 +197,8 @@ class XYChartComponent extends React.Component<XYChartProps> {
}}
// eslint-disable-next-line jsx-a11y/no-interactive-element-to-noninteractive-role
role="presentation"
{...(description ? { 'aria-describedby': chartIdDescription } : {})}
>
{label && <HeadingLevel id={chartIdLabel}>{label}</HeadingLevel>}
{(description || useDefaultSummary) && (
<div className="echScreenReaderOnly">
{description && <p id={chartIdDescription}>{description}</p>}
Expand Down Expand Up @@ -255,6 +267,9 @@ const DEFAULT_PROPS: ReactiveChartStateProps = {
description: undefined,
useDefaultSummary: true,
chartId: '',
label: undefined,
labelledBy: undefined,
HeadingLevel: 'h2',
};

const mapStateToProps = (state: GlobalChartState): ReactiveChartStateProps => {
Expand All @@ -263,7 +278,7 @@ const mapStateToProps = (state: GlobalChartState): ReactiveChartStateProps => {
}

const { geometries, geometriesIndex } = computeSeriesGeometriesSelector(state);
const { debug, description, useDefaultSummary } = getSettingsSpecSelector(state);
const { debug, description, useDefaultSummary, label, labelledBy, HeadingLevel } = getSettingsSpecSelector(state);

return {
initialized: true,
Expand All @@ -288,6 +303,9 @@ const mapStateToProps = (state: GlobalChartState): ReactiveChartStateProps => {
description,
useDefaultSummary,
chartId: getChartIdSelector(state),
label,
labelledBy,
HeadingLevel,
};
};

Expand Down
82 changes: 80 additions & 2 deletions src/chart_types/xy_chart/state/chart_state.a11y.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ import { MockStore } from '../../../mocks/store/store';
import { GlobalChartState } from '../../../state/chart_state';
import { getSettingsSpecSelector } from '../../../state/selectors/get_settings_specs';

describe('custom description for screen readers', () => {
describe('test accessibility prop defaults', () => {
let store: Store<GlobalChartState>;
beforeEach(() => {
store = MockStore.default();
Expand All @@ -43,9 +43,30 @@ describe('custom description for screen readers', () => {
});
it('should test defaults', () => {
const state = store.getState();
const { description, useDefaultSummary } = getSettingsSpecSelector(state);
const { description, useDefaultSummary, HeadingLevel, label, labelledBy } = getSettingsSpecSelector(state);
expect(description).toBeUndefined();
expect(useDefaultSummary).toBeTrue();
expect(HeadingLevel).toBe('h2');
expect(label).toBeUndefined();
expect(labelledBy).toBeUndefined();
});
});
describe('custom description for screen readers', () => {
let store: Store<GlobalChartState>;
beforeEach(() => {
store = MockStore.default();
MockStore.addSpecs(
[
MockSeriesSpec.bar({
data: [
{ x: 1, y: 10 },
{ x: 2, y: 5 },
],
}),
MockGlobalSpec.settings(),
],
store,
);
});
it('should allow user to set a custom description for chart', () => {
MockStore.addSpecs(
Expand Down Expand Up @@ -74,3 +95,60 @@ describe('custom description for screen readers', () => {
expect(useDefaultSummary).toBe(false);
});
});
describe('custom labels for screen readers', () => {
let store: Store<GlobalChartState>;
beforeEach(() => {
store = MockStore.default();
MockStore.addSpecs(
[
MockSeriesSpec.bar({
data: [
{ x: 1, y: 10 },
{ x: 2, y: 5 },
],
}),
MockGlobalSpec.settings(),
],
store,
);
});
it('should allow label set by the user', () => {
MockStore.addSpecs(
[
MockGlobalSpec.settings({
label: 'Label set by user',
}),
],
store,
);
const state = store.getState();
const { label } = getSettingsSpecSelector(state);
expect(label).toBeTruthy();
});
it('should allow labelledBy set by the user', () => {
MockStore.addSpecs(
[
MockGlobalSpec.settings({
labelledBy: 'Label',
}),
],
store,
);
const state = store.getState();
const { labelledBy } = getSettingsSpecSelector(state);
expect(labelledBy).toBeTruthy();
});
it('should allow users to specify valid heading levels', () => {
MockStore.addSpecs(
[
MockGlobalSpec.settings({
HeadingLevel: 'h5',
}),
],
store,
);
const state = store.getState();
const { HeadingLevel } = getSettingsSpecSelector(state);
expect(HeadingLevel).toBe('h5');
});
});
6 changes: 3 additions & 3 deletions src/components/__snapshots__/chart.test.tsx.snap
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ exports[`Chart should render the legend name test 1`] = `
<Connect(SpecsParserComponent)>
<SpecsParserComponent specParsed={[Function (anonymous)]} specUnmounted={[Function (anonymous)]}>
<Connect(SpecInstance) debug={true} rendering=\\"svg\\" showLegend={true}>
<SpecInstance debug={true} rendering=\\"svg\\" showLegend={true} upsertSpec={[Function (anonymous)]} removeSpec={[Function (anonymous)]} id=\\"__global__settings___\\" chartType=\\"global\\" specType=\\"settings\\" rotation={0} animateData={true} resizeDebounce={10} tooltip={{...}} externalPointerEvents={{...}} hideDuplicateAxes={false} baseTheme={{...}} brushAxis=\\"x\\" minBrushDelta={2} useDefaultSummary={true} showLegendExtra={false} legendMaxDepth={Infinity} legendPosition=\\"right\\" />
<SpecInstance debug={true} rendering=\\"svg\\" showLegend={true} upsertSpec={[Function (anonymous)]} removeSpec={[Function (anonymous)]} id=\\"__global__settings___\\" chartType=\\"global\\" specType=\\"settings\\" rotation={0} animateData={true} resizeDebounce={10} tooltip={{...}} externalPointerEvents={{...}} hideDuplicateAxes={false} baseTheme={{...}} brushAxis=\\"x\\" minBrushDelta={2} useDefaultSummary={true} HeadingLevel=\\"h2\\" showLegendExtra={false} legendMaxDepth={Infinity} legendPosition=\\"right\\" />
</Connect(SpecInstance)>
<Connect(SpecInstance) id=\\"test\\" data={{...}}>
<SpecInstance id=\\"test\\" data={{...}} upsertSpec={[Function (anonymous)]} removeSpec={[Function (anonymous)]} chartType=\\"xy_axis\\" specType=\\"series\\" seriesType=\\"bar\\" groupId=\\"__global__\\" xScaleType=\\"ordinal\\" yScaleType=\\"linear\\" xAccessor=\\"x\\" yAccessors={{...}} yScaleToDataExtent={false} hideInLegend={false} enableHistogramMode={false} />
Expand All @@ -72,8 +72,8 @@ exports[`Chart should render the legend name test 1`] = `
</Crosshair>
</Connect(Crosshair)>
<Connect(XYChart) forwardStageRef={{...}}>
<XYChart forwardStageRef={{...}} initialized={true} isChartEmpty={false} debug={true} geometries={{...}} geometriesIndex={{...}} theme={{...}} chartContainerDimensions={{...}} highlightedLegendItem={[undefined]} rotation={0} renderingArea={{...}} chartTransform={{...}} axesSpecs={{...}} perPanelAxisGeoms={{...}} perPanelGridLines={{...}} axesStyles={{...}} annotationDimensions={{...}} annotationSpecs={{...}} panelGeoms={{...}} seriesTypes={{...}} description={[undefined]} useDefaultSummary={true} chartId=\\"chart1\\" onChartRendered={[Function (anonymous)]}>
<figure>
<XYChart forwardStageRef={{...}} initialized={true} isChartEmpty={false} debug={true} geometries={{...}} geometriesIndex={{...}} theme={{...}} chartContainerDimensions={{...}} highlightedLegendItem={[undefined]} rotation={0} renderingArea={{...}} chartTransform={{...}} axesSpecs={{...}} perPanelAxisGeoms={{...}} perPanelGridLines={{...}} axesStyles={{...}} annotationDimensions={{...}} annotationSpecs={{...}} panelGeoms={{...}} seriesTypes={{...}} description={[undefined]} useDefaultSummary={true} chartId=\\"chart1\\" label={[undefined]} labelledBy={[undefined]} HeadingLevel=\\"h2\\" onChartRendered={[Function (anonymous)]}>
<figure aria-labelledby=\\"\\" aria-describedby=\\" undefined\\">
<canvas className=\\"echCanvasRenderer\\" width={150} height={200} style={{...}} role=\\"presentation\\">
<div className=\\"echScreenReaderOnly\\">
<dl>
Expand Down
1 change: 1 addition & 0 deletions src/specs/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,7 @@ export const DEFAULT_SETTINGS_SPEC: SettingsSpec = {
brushAxis: BrushAxis.X,
minBrushDelta: 2,
useDefaultSummary: true,
HeadingLevel: 'h2',

...DEFAULT_LEGEND_CONFIG,
};
17 changes: 16 additions & 1 deletion src/specs/settings.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -548,6 +548,19 @@ export interface SettingsSpec extends Spec, LegendSpec {
* Render component for no results UI
*/
noResults?: ComponentType | ReactChild;
/**
* User can specify the heading level for the label
* @defaultValue 'h2'
*/
HeadingLevel: 'h1' | 'h2' | 'h3' | 'h4' | 'h5' | 'h6' | 'p';
/**
* User can set a label
*/
label?: string;
/**
* User can set a string to the aria-labelled by
* */
labelledBy?: string;
/**
* User can provide a custom description to be read by a screen reader about their chart
*/
Expand Down Expand Up @@ -619,7 +632,9 @@ export type DefaultSettingsProps =
| 'legendPosition'
| 'legendMaxDepth'
| 'description'
| 'useDefaultSummary';
| 'useDefaultSummary'
| 'label'
| 'HeadingLevel';

/** @public */
export type SettingsSpecProps = Partial<Omit<SettingsSpec, 'chartType' | 'specType' | 'id'>>;
Expand Down
15 changes: 12 additions & 3 deletions stories/test_cases/6_a11y_custom_description.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,18 +17,27 @@
* under the License.
*/

import { boolean, text } from '@storybook/addon-knobs';
import { boolean, text, select } from '@storybook/addon-knobs';
import React from 'react';

import { AreaSeries, Chart, ScaleType, Settings } from '../../src';
import { KIBANA_METRICS } from '../../src/utils/data_samples/test_dataset_kibana';

export const Example = () => {
const automatedSeries = boolean('Use the default generated series types of charts for screen readers', true);
const customDescriptionForScreenReaders = text('custom description for screen readers', '');
const customDescriptionForScreenReaders = text('add a description for screen readers', '');
const customLabelForScreenReaders = text('add a label for screen readers', '');
const headingLevelForScreenReaders = customLabelForScreenReaders
? select('heading level for label', { P: 'p', H1: 'h1', H2: 'h2', H3: 'h3', H4: 'h4', H5: 'h5', H6: 'h6' }, 'h2')
: undefined;
return (
<Chart className="story-chart">
<Settings description={customDescriptionForScreenReaders} useDefaultSummary={automatedSeries} />
<Settings
description={customDescriptionForScreenReaders}
useDefaultSummary={automatedSeries}
label={customLabelForScreenReaders}
HeadingLevel={headingLevelForScreenReaders}
/>
<AreaSeries
id="area"
xScaleType={ScaleType.Time}
Expand Down
2 changes: 1 addition & 1 deletion stories/test_cases/test_cases.stories.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -31,4 +31,4 @@ export { Example as chromePathBugFix } from './2_chrome_path_bug_fix';
export { Example as noAxesAnnotationBugFix } from './3_no_axes_annotation';
export { Example as filterZerosInLogFitDomain } from './4_filter_zero_values_log';
export { Example as legendScrollBarSizing } from './5_legend_scroll_bar_sizing';
export { Example as addCustomDescription } from './6_a11y_custom_description';
export { Example as accessibilityCustomizations } from './6_a11y_custom_description';