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

[Lens] (Accessibility) focus on adding/removing layers #84900

Merged
Merged
Show file tree
Hide file tree
Changes from 5 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
Original file line number Diff line number Diff line change
@@ -0,0 +1,178 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/

import React from 'react';
import { act } from 'react-dom/test-utils';
import {
createMockVisualization,
createMockFramePublicAPI,
createMockDatasource,
DatasourceMock,
} from '../../mocks';
import { Visualization } from '../../../types';
import { mountWithIntl } from '@kbn/test/jest';
import { LayerPanels } from './config_panel';
import { LayerPanel } from './layer_panel';
import { coreMock } from 'src/core/public/mocks';
import { generateId } from '../../../id_generator';

jest.mock('../../../id_generator');

describe('ConfigPanel', () => {
let mockVisualization: jest.Mocked<Visualization>;
let mockVisualization2: jest.Mocked<Visualization>;
let mockDatasource: DatasourceMock;
const frame = createMockFramePublicAPI();

function getDefaultProps() {
frame.datasourceLayers = {
first: mockDatasource.publicAPIMock,
};
return {
activeVisualizationId: 'vis1',
visualizationMap: {
vis1: mockVisualization,
vis2: mockVisualization2,
},
activeDatasourceId: 'ds1',
datasourceMap: {
ds1: mockDatasource,
},
activeVisualization: ({
...mockVisualization,
getLayerIds: () => Object.keys(frame.datasourceLayers),
appendLayer: true,
} as unknown) as Visualization,
datasourceStates: {
ds1: {
isLoading: false,
state: 'state',
},
},
visualizationState: 'state',
updateVisualization: jest.fn(),
updateDatasource: jest.fn(),
updateAll: jest.fn(),
framePublicAPI: frame,
dispatch: jest.fn(),
core: coreMock.createStart(),
};
}

beforeEach(() => {
mockVisualization = {
...createMockVisualization(),
id: 'testVis',
visualizationTypes: [
{
icon: 'empty',
id: 'testVis',
label: 'TEST1',
},
],
};

mockVisualization2 = {
...createMockVisualization(),

id: 'testVis2',
visualizationTypes: [
{
icon: 'empty',
id: 'testVis2',
label: 'TEST2',
},
],
};

mockVisualization.getLayerIds.mockReturnValue(Object.keys(frame.datasourceLayers));
mockDatasource = createMockDatasource('ds1');
});

describe('focus behavior when adding or removing layers', () => {
it('should focus the only layer when resetting the layer', () => {
const component = mountWithIntl(<LayerPanels {...getDefaultProps()} />);
const firstLayerFocusable = component
.find(LayerPanel)
.first()
.find('button')
.first()
.instance();
act(() => {
component.find('[data-test-subj="lnsLayerRemove"]').first().simulate('click');
});
const focusedEl = document.activeElement;
expect(focusedEl).toEqual(firstLayerFocusable);
});

it('should focus the second layer when removing the first layer', () => {
const defaultProps = getDefaultProps();
// overwriting datasourceLayers to test two layers
frame.datasourceLayers = {
first: mockDatasource.publicAPIMock,
second: mockDatasource.publicAPIMock,
};
const component = mountWithIntl(<LayerPanels {...defaultProps} />);
const secondLayerFocusable = component
.find(LayerPanel)
.at(1)
.find('button')
.first()
.instance();
act(() => {
component.find('[data-test-subj="lnsLayerRemove"]').at(0).simulate('click');
});
const focusedEl = document.activeElement;
expect(focusedEl).toEqual(secondLayerFocusable);
expect(focusedEl?.closest('.lnsLayerPanel')?.getAttribute('data-test-subj')).toEqual(
'lns-layerPanel-1'
);
});

it('should focus the first layer when removing the second layer', () => {
const defaultProps = getDefaultProps();
// overwriting datasourceLayers to test two layers
frame.datasourceLayers = {
first: mockDatasource.publicAPIMock,
second: mockDatasource.publicAPIMock,
};
const component = mountWithIntl(<LayerPanels {...defaultProps} />);
const firstLayerFocusable = component
.find(LayerPanel)
.first()
.find('button')
.first()
.instance();
act(() => {
component.find('[data-test-subj="lnsLayerRemove"]').at(2).simulate('click');
});
const focusedEl = document.activeElement;
expect(focusedEl).toEqual(firstLayerFocusable);
expect(focusedEl?.closest('.lnsLayerPanel')?.getAttribute('data-test-subj')).toEqual(
'lns-layerPanel-0'
);
});

it('should focus the added layer', () => {
(generateId as jest.Mock).mockReturnValue(`second`);
jest.useFakeTimers();
const dispatch = jest.fn((x) => {
if (x.subType === 'ADD_LAYER') {
frame.datasourceLayers.second = mockDatasource.publicAPIMock;
}
});

const component = mountWithIntl(<LayerPanels {...getDefaultProps()} dispatch={dispatch} />);
act(() => {
component.find('[data-test-subj="lnsLayerAddButton"]').first().simulate('click');
});
const focusedEl = document.activeElement;
expect(focusedEl?.closest('.lnsLayerPanel')?.getAttribute('data-test-subj')).toEqual(
'lns-layerPanel-1'
);
});
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
*/
import './config_panel.scss';

import React, { useMemo, memo } from 'react';
import React, { useMemo, memo, useEffect, useState, useCallback } from 'react';
import { EuiFlexItem, EuiToolTip, EuiButton, EuiForm } from '@elastic/eui';
import { i18n } from '@kbn/i18n';
import { Visualization } from '../../../types';
Expand All @@ -24,7 +24,76 @@ export const ConfigPanelWrapper = memo(function ConfigPanelWrapper(props: Config
) : null;
});

function LayerPanels(
const getFirstFocusable = (el: HTMLElement | null) => {
if (!el) {
return null;
}
const firstFocusable = el.querySelector(
mbondyra marked this conversation as resolved.
Show resolved Hide resolved
'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'
);
if (!firstFocusable) {
return null;
}
return (firstFocusable as unknown) as { focus: () => void };
};

function useFocusUpdate(layerIds: string[]) {
const [lastUpdated, setLastUpdated] = useState<{
type: 'ADD_LAYER' | 'REMOVE_OR_CLEAR_LAYER';
id: string;
} | null>(null);
const [layerRefs, setLayersRefs] = useState<Record<string, HTMLElement | null>>({});
useEffect(() => {
if (!lastUpdated) {
return;
}
let focusable;

const { type, id } = lastUpdated;

if (type === 'ADD_LAYER') {
focusable = getFirstFocusable(layerRefs[id]);
} else if (type === 'REMOVE_OR_CLEAR_LAYER') {
const firstLayer = layerIds.length === 1 ? layerIds[0] : layerIds.filter((l) => l !== id)[0];
focusable = firstLayer && getFirstFocusable(layerRefs[firstLayer]);
}

if (focusable) {
focusable.focus();
setLastUpdated(null);
}
}, [layerIds, layerRefs, lastUpdated]);

const setLayerRef = useCallback((layerId, el) => {
if (el) {
setLayersRefs((refs) => ({
...refs,
[layerId]: el,
}));
}
}, []);

const removeLayerRef = useCallback(
(layerId) => {
if (layerIds.length > 1) {
setLayersRefs((refs) => {
const newLayerRefs = { ...refs };
delete newLayerRefs[layerId];
return newLayerRefs;
});
}
setLastUpdated({
type: 'REMOVE_OR_CLEAR_LAYER',
id: layerId,
});
},
[layerIds]
);

return { setLastUpdated, removeLayerRef, setLayerRef };
}

export function LayerPanels(
props: ConfigPanelWrapperProps & {
activeDatasourceId: string;
activeVisualization: Visualization;
Expand All @@ -37,6 +106,10 @@ function LayerPanels(
activeDatasourceId,
datasourceMap,
} = props;

const layerIds = activeVisualization.getLayerIds(visualizationState);
const { setLastUpdated, removeLayerRef, setLayerRef } = useFocusUpdate(layerIds);

const setVisualizationState = useMemo(
() => (newState: unknown) => {
dispatch({
Expand Down Expand Up @@ -85,13 +158,13 @@ function LayerPanels(
},
[dispatch]
);
const layerIds = activeVisualization.getLayerIds(visualizationState);

return (
<EuiForm className="lnsConfigPanel">
{layerIds.map((layerId, index) => (
<LayerPanel
{...props}
setLayerRef={setLayerRef}
key={layerId}
layerId={layerId}
index={index}
Expand All @@ -113,6 +186,7 @@ function LayerPanels(
state,
}),
});
removeLayerRef(layerId);
}}
/>
))}
Expand All @@ -138,18 +212,23 @@ function LayerPanels(
defaultMessage: 'Add layer',
})}
onClick={() => {
const id = generateId();
dispatch({
type: 'UPDATE_STATE',
subType: 'ADD_LAYER',
updater: (state) =>
appendLayer({
activeVisualization,
generateId,
generateId: () => id,
trackUiEvent,
activeDatasource: datasourceMap[activeDatasourceId],
state,
}),
});
setLastUpdated({
type: 'ADD_LAYER',
id,
});
}}
iconType="plusInCircleFilled"
/>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ describe('LayerPanel', () => {
dispatch: jest.fn(),
core: coreMock.createStart(),
index: 0,
setLayerRef: jest.fn(),
};
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -74,20 +74,26 @@ export function LayerPanel(
newVisualizationState: unknown
) => void;
onRemoveLayer: () => void;
setLayerRef: (layerId: string, instance: HTMLDivElement | null) => void;
}
) {
const dragDropContext = useContext(DragContext);
const [activeDimension, setActiveDimension] = useState<ActiveDimensionState>(
initialActiveDimensionState
);

const { framePublicAPI, layerId, isOnlyLayer, onRemoveLayer, index } = props;
const { framePublicAPI, layerId, isOnlyLayer, onRemoveLayer, setLayerRef, index } = props;
const datasourcePublicAPI = framePublicAPI.datasourceLayers[layerId];

useEffect(() => {
setActiveDimension(initialActiveDimensionState);
}, [props.activeVisualizationId]);

const setLayerRefMemoized = React.useCallback((el) => setLayerRef(layerId, el), [
layerId,
setLayerRef,
]);

if (
!datasourcePublicAPI ||
!props.activeVisualizationId ||
Expand Down Expand Up @@ -133,6 +139,7 @@ export function LayerPanel(
<ChildDragDropProvider {...dragDropContext}>
<EuiPanel
data-test-subj={`lns-layerPanel-${index}`}
panelRef={setLayerRefMemoized}
className="lnsLayerPanel"
paddingSize="s"
>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -602,7 +602,7 @@ describe('editor_frame', () => {
});

// validation requires to calls this getConfiguration API
expect(mockVisualization.getConfiguration).toHaveBeenCalledTimes(6);
expect(mockVisualization.getConfiguration).toHaveBeenCalledTimes(7);
expect(mockVisualization.getConfiguration).toHaveBeenLastCalledWith(
expect.objectContaining({
state: updatedState,
Expand Down Expand Up @@ -682,7 +682,7 @@ describe('editor_frame', () => {
});

// validation requires to calls this getConfiguration API
expect(mockVisualization.getConfiguration).toHaveBeenCalledTimes(6);
expect(mockVisualization.getConfiguration).toHaveBeenCalledTimes(7);
expect(mockVisualization.getConfiguration).toHaveBeenLastCalledWith(
expect.objectContaining({
frame: expect.objectContaining({
Expand Down Expand Up @@ -1196,7 +1196,7 @@ describe('editor_frame', () => {
});

// validation requires to calls this getConfiguration API
expect(mockVisualization.getConfiguration).toHaveBeenCalledTimes(4);
expect(mockVisualization.getConfiguration).toHaveBeenCalledTimes(5);
expect(mockVisualization.getConfiguration).toHaveBeenCalledWith(
expect.objectContaining({
state: suggestionVisState,
Expand Down