Tooltip: make widget accessible (#43468)

* add useToolTipTrigger react aria and state to grafana-ui

* show tooltip on focus and close tooltip when esc key is pressed

* remove react-aria/tooltip package

* fix failing test
This commit is contained in:
Uchechukwu Obasi 2021-12-22 18:11:07 +01:00 committed by GitHub
parent 7d3bdb6d1b
commit 98bf9a6d2a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 25 additions and 23 deletions

View File

@ -1,18 +1,16 @@
import React from 'react';
import renderer from 'react-test-renderer';
import { render, screen } from '@testing-library/react';
import { Tooltip } from './Tooltip';
describe('Tooltip', () => {
it('renders correctly', () => {
const tree = renderer
.create(
<Tooltip placement="auto" content="Tooltip text">
<a className="test-class" href="http://www.grafana.com">
Link with tooltip
</a>
</Tooltip>
)
.toJSON();
expect(tree).toMatchSnapshot();
render(
<Tooltip placement="auto" content="Tooltip text">
<a className="test-class" href="http://www.grafana.com">
Link with tooltip
</a>
</Tooltip>
);
expect(screen.getByText('Link with tooltip')).toBeInTheDocument();
});
});

View File

@ -16,6 +16,19 @@ export type PopoverContent = string | React.ReactElement<any> | ((props: Popover
export const Tooltip: FC<TooltipProps> = React.memo(({ children, theme, ...controllerProps }: TooltipProps) => {
const tooltipTriggerRef = createRef<HTMLElement | VirtualElement>();
const popperBackgroundClassName = 'popper__background' + (theme ? ' popper__background--' + theme : '');
const closePopover = (event: React.KeyboardEvent<HTMLDivElement>, hidePopper: () => void) => {
if (event.key === 'Tab' || event.altKey || event.ctrlKey || event.metaKey) {
return;
}
event.stopPropagation();
if (event.key === 'Escape') {
hidePopper();
}
return;
};
return (
<PopoverController {...controllerProps}>
@ -46,6 +59,9 @@ export const Tooltip: FC<TooltipProps> = React.memo(({ children, theme, ...contr
ref: tooltipTriggerRef,
onMouseEnter: showPopper,
onMouseLeave: hidePopper,
onKeyDown: (event: React.KeyboardEvent<HTMLDivElement>) => closePopover(event, hidePopper),
onFocus: showPopper,
onBlur: hidePopper,
})}
</>
);

View File

@ -1,12 +0,0 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`Tooltip renders correctly 1`] = `
<a
className="test-class"
href="http://www.grafana.com"
onMouseEnter={[Function]}
onMouseLeave={[Function]}
>
Link with tooltip
</a>
`;