[Lens] [A11y] fix creating or removing layers in Lens looses focus (#175893)

## Summary

Fixes https://github.com/elastic/kibana/issues/175191
https://buildkite.com/elastic/kibana-flaky-test-suite-runner/builds/4989
I replaced the unit tests with functional ones because of two reasons :
first, this is a complex behavior and it's tricky to test it with unit
tests with confidence. Secondly, it was actually tested but yet tests
were passing and the bug happened anyway.


### Checklist

Delete any items that are not applicable to this PR.

- [ ] Any text added follows [EUI's writing
guidelines](https://elastic.github.io/eui/#/guidelines/writing), uses
sentence case text and includes [i18n
support](https://github.com/elastic/kibana/blob/main/packages/kbn-i18n/README.md)
- [ ]
[Documentation](https://www.elastic.co/guide/en/kibana/master/development-documentation.html)
was added for features that require explanation or tutorials
- [ ] [Unit or functional
tests](https://www.elastic.co/guide/en/kibana/master/development-tests.html)
were updated or added to match the most common scenarios
- [ ] [Flaky Test
Runner](https://ci-stats.kibana.dev/trigger_flaky_test_runner/1) was
used on any tests changed
- [ ] Any UI touched in this PR is usable by keyboard only (learn more
about [keyboard accessibility](https://webaim.org/techniques/keyboard/))
- [ ] Any UI touched in this PR does not create any new axe failures
(run axe in browser:
[FF](https://addons.mozilla.org/en-US/firefox/addon/axe-devtools/),
[Chrome](https://chrome.google.com/webstore/detail/axe-web-accessibility-tes/lhdoppojpmngadmnindnejefpokejbdd?hl=en-US))
- [ ] If a plugin configuration key changed, check if it needs to be
allowlisted in the cloud and added to the [docker
list](https://github.com/elastic/kibana/blob/main/src/dev/build/tasks/os_packages/docker_generator/resources/base/bin/kibana-docker)
- [ ] This renders correctly on smaller devices using a responsive
layout. (You can test this [in your
browser](https://www.browserstack.com/guide/responsive-testing-on-local-server))
- [ ] This was checked for [cross-browser
compatibility](https://www.elastic.co/support/matrix#matrix_browsers)


### Risk Matrix

Delete this section if it is not applicable to this PR.

Before closing this PR, invite QA, stakeholders, and other developers to
identify risks that should be tested prior to the change/feature
release.

When forming the risk matrix, consider some of the following examples
and how they may potentially impact the change:

| Risk | Probability | Severity | Mitigation/Notes |

|---------------------------|-------------|----------|-------------------------|
| Multiple Spaces—unexpected behavior in non-default Kibana Space.
| Low | High | Integration tests will verify that all features are still
supported in non-default Kibana Space and when user switches between
spaces. |
| Multiple nodes—Elasticsearch polling might have race conditions
when multiple Kibana nodes are polling for the same tasks. | High | Low
| Tasks are idempotent, so executing them multiple times will not result
in logical error, but will degrade performance. To test for this case we
add plenty of unit tests around this logic and document manual testing
procedure. |
| Code should gracefully handle cases when feature X or plugin Y are
disabled. | Medium | High | Unit tests will verify that any feature flag
or plugin combination still results in our service operational. |
| [See more potential risk
examples](https://github.com/elastic/kibana/blob/main/RISK_MATRIX.mdx) |


### For maintainers

- [ ] This was checked for breaking API changes and was [labeled
appropriately](https://www.elastic.co/guide/en/kibana/master/contributing.html#kibana-release-notes-process)
This commit is contained in:
Marta Bondyra 2024-01-31 22:35:01 +01:00 committed by GitHub
parent 4b56efeeae
commit 42b42c8fa5
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
5 changed files with 38 additions and 94 deletions

View file

@ -27,7 +27,6 @@ import { generateId } from '../../../id_generator';
import { mountWithProvider } from '../../../mocks';
import { LayerTypes } from '@kbn/expression-xy-plugin/public';
import { ReactWrapper } from 'enzyme';
import { addLayer } from '../../../state_management';
import { createIndexPatternServiceMock } from '../../../mocks/data_views_service_mock';
import { AddLayerButton } from '../../../visualizations/xy/add_layer';
import { LayerType } from '@kbn/visualizations-plugin/common';
@ -190,96 +189,6 @@ describe('ConfigPanel', () => {
);
});
describe('focus behavior when adding or removing layers', () => {
it('should focus the only layer when resetting the layer', async () => {
const { instance } = await prepareAndMountComponent(getDefaultProps());
const firstLayerFocusable = instance
.find(LayerPanel)
.first()
.find('section')
.first()
.instance();
act(() => {
instance.find('[data-test-subj="lnsLayerRemove--0"]').first().simulate('click');
});
instance.update();
const focusedEl = document.activeElement;
expect(focusedEl).toEqual(firstLayerFocusable);
});
it('should focus the second layer when removing the first layer', async () => {
const datasourceMap = mockDatasourceMap();
const defaultProps = getDefaultProps({ datasourceMap });
// overwriting datasourceLayers to test two layers
frame.datasourceLayers = {
first: datasourceMap.testDatasource.publicAPIMock,
second: datasourceMap.testDatasource.publicAPIMock,
};
const { instance } = await prepareAndMountComponent(defaultProps);
const secondLayerFocusable = instance
.find(LayerPanel)
.at(1)
.find('section')
.first()
.instance();
act(() => {
instance.find('[data-test-subj="lnsLayerRemove--0"]').first().simulate('click');
});
instance.update();
const focusedEl = document.activeElement;
expect(focusedEl).toEqual(secondLayerFocusable);
});
it('should focus the first layer when removing the second layer', async () => {
const datasourceMap = mockDatasourceMap();
const defaultProps = getDefaultProps({ datasourceMap });
// overwriting datasourceLayers to test two layers
frame.datasourceLayers = {
first: datasourceMap.testDatasource.publicAPIMock,
second: datasourceMap.testDatasource.publicAPIMock,
};
const { instance } = await prepareAndMountComponent(defaultProps);
const firstLayerFocusable = instance
.find(LayerPanel)
.first()
.find('section')
.first()
.instance();
act(() => {
instance.find('[data-test-subj="lnsLayerRemove--1"]').first().simulate('click');
});
instance.update();
const focusedEl = document.activeElement;
expect(focusedEl).toEqual(firstLayerFocusable);
});
it('should focus the added layer', async () => {
const datasourceMap = mockDatasourceMap();
frame.datasourceLayers = {
first: datasourceMap.testDatasource.publicAPIMock,
newId: datasourceMap.testDatasource.publicAPIMock,
};
const defaultProps = getDefaultProps({ datasourceMap });
const { instance } = await prepareAndMountComponent(defaultProps, {
dispatch: jest.fn((x) => {
if (x.type === addLayer.type) {
frame.datasourceLayers.newId = datasourceMap.testDatasource.publicAPIMock;
}
}),
});
addNewLayer(instance);
const focusedEl = document.activeElement;
expect(focusedEl?.children[0].getAttribute('data-test-subj')).toEqual('lns-layerPanel-1');
});
});
describe('initial default value', () => {
function clickToAddDimension(instance: ReactWrapper) {
act(() => {

View file

@ -950,6 +950,7 @@ describe('LayerPanel', () => {
});
it('should reorder when dropping in the same group', async () => {
jest.useFakeTimers();
mockVisualization.getConfiguration.mockReturnValue({
groups: [
{
@ -997,6 +998,7 @@ describe('LayerPanel', () => {
.find('[data-test-subj="lnsDragDrop-keyboardHandler"]')
.at(1)
.instance();
jest.runAllTimers();
const focusedEl = document.activeElement;
expect(focusedEl).toEqual(secondButton);
});

View file

@ -363,8 +363,13 @@ export function LayerPanel(
return (
<>
<section tabIndex={-1} ref={registerLayerRef} className="lnsLayerPanel">
<EuiPanel data-test-subj={`lns-layerPanel-${layerIndex}`} paddingSize="none">
<section
tabIndex={-1}
ref={registerLayerRef}
className="lnsLayerPanel"
data-test-subj={`lns-layerPanel-${layerIndex}`}
>
<EuiPanel paddingSize="none">
<header className="lnsLayerPanel__layerHeader">
<EuiFlexGroup gutterSize="s" responsive={false} alignItems="center">
<EuiFlexItem grow className="lnsLayerPanel__layerSettingsWrapper">

View file

@ -30,7 +30,7 @@ export function useFocusUpdate(ids: string[]) {
const element = nextFocusedId && refsById.get(nextFocusedId);
if (element) {
const focusable = getFirstFocusable(element);
focusable?.focus();
setTimeout(() => focusable?.focus());
setNextFocusedId(null);
}
}, [ids, refsById, nextFocusedId]);

View file

@ -5,6 +5,7 @@
* 2.0.
*/
import expect from '@kbn/expect';
import { FtrProviderContext } from '../../ftr_provider_context';
export default function ({ getService, getPageObjects }: FtrProviderContext) {
@ -14,6 +15,13 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) {
const esArchiver = getService('esArchiver');
const listingTable = getService('listingTable');
const kibanaServer = getService('kibanaServer');
const find = getService('find');
const hasFocus = async (testSubject: string) => {
const targetElement = await testSubjects.find(testSubject);
const activeElement = await find.activeElement();
return (await targetElement._webElement.getId()) === (await activeElement._webElement.getId());
};
describe('Lens Accessibility', () => {
const lensChartName = 'MyLensChart';
@ -175,5 +183,25 @@ export default function ({ getService, getPageObjects }: FtrProviderContext) {
await listingTable.clickDeleteSelected();
await PageObjects.common.clickConfirmOnModal();
});
describe('focus behavior when adding or removing layers', () => {
it('should focus the added layer', async () => {
await PageObjects.visualize.navigateToNewVisualization();
await PageObjects.visualize.clickVisType('lens');
await PageObjects.lens.createLayer();
expect(await hasFocus('lns-layerPanel-1')).to.be(true);
});
it('should focus the remaining layer when the first is removed', async () => {
await PageObjects.lens.removeLayer(0);
expect(await hasFocus('lns-layerPanel-0')).to.be(true);
await PageObjects.lens.createLayer();
await PageObjects.lens.removeLayer(1);
expect(await hasFocus('lns-layerPanel-0')).to.be(true);
});
it('should focus the only layer when resetting the layer', async () => {
await PageObjects.lens.removeLayer();
expect(await hasFocus('lns-layerPanel-0')).to.be(true);
});
});
});
}