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

[Discover] Add "Chart options" menu #112453

Merged
merged 22 commits into from
Sep 28, 2021
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
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
Expand Up @@ -100,10 +100,10 @@ function getProps(timefield?: string) {
describe('Discover chart', () => {
test('render without timefield', () => {
const component = mountWithIntl(<DiscoverChart {...getProps()} />);
expect(component.find('[data-test-subj="discoverChartToggle"]').exists()).toBeFalsy();
expect(component.find('[data-test-subj="discoverChartOptionsToggle"]').exists()).toBeFalsy();
});
test('render with filefield', () => {
const component = mountWithIntl(<DiscoverChart {...getProps('timefield')} />);
expect(component.find('[data-test-subj="discoverChartToggle"]').exists()).toBeTruthy();
expect(component.find('[data-test-subj="discoverChartOptionsToggle"]').exists()).toBeTruthy();
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -5,21 +5,29 @@
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
import React, { useCallback, useEffect, useRef, memo } from 'react';
import React, { memo, useCallback, useEffect, useRef, useState } from 'react';
import moment from 'moment';
import { EuiFlexGroup, EuiFlexItem, EuiButtonEmpty, EuiSpacer } from '@elastic/eui';
import {
EuiButtonEmpty,
EuiContextMenu,
EuiFlexGroup,
EuiFlexItem,
EuiPopover,
EuiSpacer,
} from '@elastic/eui';
import { i18n } from '@kbn/i18n';
import { HitsCounter } from '../hits_counter';
import { search } from '../../../../../../../data/public';
import { TimechartHeader } from '../timechart_header';
import { SavedSearch } from '../../../../../saved_searches';
import { AppState, GetStateReturn } from '../../services/discover_state';
import { DiscoverHistogram } from './histogram';
import { DataCharts$, DataTotalHits$ } from '../../services/use_saved_search';
import { DiscoverServices } from '../../../../../build_services';
import { useChartPanels } from './use_chart_panels';

const TimechartHeaderMemoized = memo(TimechartHeader);
const DiscoverHistogramMemoized = memo(DiscoverHistogram);

export function DiscoverChart({
resetSavedSearch,
savedSearch,
Expand All @@ -39,12 +47,22 @@ export function DiscoverChart({
stateContainer: GetStateReturn;
timefield?: string;
}) {
const [areChartOptionVisible, setChartOptionsVisible] = useState(false);

const { data, uiSettings: config } = services;
const chartRef = useRef<{ element: HTMLElement | null; moveFocus: boolean }>({
element: null,
moveFocus: false,
});

const onShowChartOptions = useCallback(() => {
setChartOptionsVisible(!areChartOptionVisible);
}, [areChartOptionVisible]);

const closeChartOptions = useCallback(() => {
setChartOptionsVisible(false);
}, [setChartOptionsVisible]);

useEffect(() => {
if (chartRef.current.moveFocus && chartRef.current.element) {
chartRef.current.element.focus();
Expand All @@ -57,15 +75,6 @@ export function DiscoverChart({
chartRef.current.moveFocus = !newHideChart;
}, [state, stateContainer]);

const onChangeInterval = useCallback(
(interval: string) => {
if (interval) {
stateContainer.setAppState({ interval });
}
},
[stateContainer]
);

const timefilterUpdateHandler = useCallback(
(ranges: { from: number; to: number }) => {
data.query.timefilter.timefilter.setTime({
Expand All @@ -76,6 +85,13 @@ export function DiscoverChart({
},
[data]
);
const panels = useChartPanels(
state,
savedSearchDataChart$,
toggleHideChart,
(interval) => stateContainer.setAppState({ interval }),
() => setChartOptionsVisible(false)
);

return (
<EuiFlexGroup direction="column" alignItems="stretch" gutterSize="none" responsive={false}>
Expand All @@ -96,29 +112,34 @@ export function DiscoverChart({
<TimechartHeaderMemoized
data={data}
dateFormat={config.get('dateFormat')}
options={search.aggs.intervalOptions}
onChangeInterval={onChangeInterval}
stateInterval={state.interval || ''}
savedSearchData$={savedSearchDataChart$}
/>
</EuiFlexItem>
)}
{timefield && (
<EuiFlexItem className="dscResultCount__toggle" grow={false}>
<EuiButtonEmpty
size="xs"
iconType={!state.hideChart ? 'eyeClosed' : 'eye'}
onClick={toggleHideChart}
data-test-subj="discoverChartToggle"
>
{!state.hideChart
? i18n.translate('discover.hideChart', {
defaultMessage: 'Hide chart',
})
: i18n.translate('discover.showChart', {
defaultMessage: 'Show chart',
<EuiPopover
id="contextMenuExample"
button={
<EuiButtonEmpty
size="xs"
iconType={'gear'}
onClick={onShowChartOptions}
data-test-subj="discoverChartOptionsToggle"
>
{i18n.translate('discover.chartOptionsButton', {
defaultMessage: 'Chart options',
})}
</EuiButtonEmpty>
</EuiButtonEmpty>
}
isOpen={areChartOptionVisible}
closePopover={closeChartOptions}
panelPaddingSize="none"
anchorPosition="downLeft"
>
<EuiContextMenu initialPanelId={0} panels={panels} />
</EuiPopover>
</EuiFlexItem>
)}
</EuiFlexGroup>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,6 @@ export function DiscoverHistogram({
id="discover-histogram-left-axis"
position={Position.Left}
ticks={5}
title={chartData.yAxisLabel}
integersOnly
tickFormat={(value) => xAxisFormatter.convert(value)}
/>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/

import { renderHook } from '@testing-library/react-hooks';

import { useChartPanels } from './use_chart_panels';
import { AppState } from '../../services/discover_state';
import { BehaviorSubject } from 'rxjs';
import { DataCharts$ } from '../../services/use_saved_search';
import { FetchStatus } from '../../../../types';
import { EuiContextMenuPanelDescriptor } from '@elastic/eui';

describe('test useChartPanels', () => {
test('useChartsPanel when hideChart is true', async () => {
const charts$ = new BehaviorSubject({
fetchStatus: FetchStatus.COMPLETE,
}) as DataCharts$;
const { result } = renderHook(() => {
return useChartPanels(
{ hideChart: true, interval: 'auto' } as AppState,
charts$,
jest.fn(),
jest.fn(),
jest.fn()
);
});
const panels: EuiContextMenuPanelDescriptor[] = result.current;
const panel0: EuiContextMenuPanelDescriptor = result.current[0];
expect(panels.length).toBe(1);
expect(panel0!.items![0].icon).toBe('eye');
});
test('useChartsPanel when hideChart is false', async () => {
const charts$ = new BehaviorSubject({
fetchStatus: FetchStatus.COMPLETE,
}) as DataCharts$;
const { result } = renderHook(() => {
return useChartPanels(
{ hideChart: false, interval: 'auto' } as AppState,
charts$,
jest.fn(),
jest.fn(),
jest.fn()
);
});
const panels: EuiContextMenuPanelDescriptor[] = result.current;
const panel0: EuiContextMenuPanelDescriptor = result.current[0];
expect(panels.length).toBe(2);
expect(panel0!.items![0].icon).toBe('eyeClosed');
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
import { i18n } from '@kbn/i18n';
import type {
EuiContextMenuPanelItemDescriptor,
EuiContextMenuPanelDescriptor,
} from '@elastic/eui';
import { search } from '../../../../../../../data/public';
import { AppState } from '../../services/discover_state';
import { DataCharts$, DataChartsMessage } from '../../services/use_saved_search';
import { useDataState } from '../../utils/use_data_state';

export function useChartPanels(
state: AppState,
savedSearchDataChart$: DataCharts$,
toggleHideChart: () => void,
onChangeInterval: (value: string) => void,
closePopover: () => void
) {
const dataState: DataChartsMessage = useDataState(savedSearchDataChart$);
const { bucketInterval } = dataState;
const { interval, hideChart } = state;
const selectedOptionIdx = search.aggs.intervalOptions.findIndex((opt) => opt.val === interval);
const intervalDisplay =
selectedOptionIdx > -1
? search.aggs.intervalOptions[selectedOptionIdx].display
: search.aggs.intervalOptions[0].display;

const mainPanelItems: EuiContextMenuPanelItemDescriptor[] = [
{
name: !hideChart
? i18n.translate('discover.hideChart', {
defaultMessage: 'Hide chart',
})
: i18n.translate('discover.showChart', {
defaultMessage: 'Show chart',
}),
icon: !hideChart ? 'eyeClosed' : 'eye',
onClick: () => {
toggleHideChart();
closePopover();
},
'data-test-subj': 'discoverChartToggle',
},
];
if (!hideChart) {
mainPanelItems.push({
name: i18n.translate('discover.timeIntervalWithValue', {
defaultMessage: 'Time interval: {timeInterval}',
values: {
timeInterval: intervalDisplay,
},
}),
icon: bucketInterval?.scaled ? 'alert' : '',
toolTipTitle: bucketInterval?.scaled
? i18n.translate('discover.timeIntervalWithValueWarning', {
defaultMessage: 'Warning',
})
: '',
toolTipContent: bucketInterval?.scaled
? i18n.translate('discover.bucketIntervalTooltip', {
defaultMessage:
'This interval creates {bucketsDescription} to show in the selected time range, so it has been scaled to {bucketIntervalDescription}.',
values: {
bucketsDescription:
bucketInterval!.scale && bucketInterval!.scale > 1
? i18n.translate('discover.bucketIntervalTooltip.tooLargeBucketsText', {
defaultMessage: 'buckets that are too large',
})
: i18n.translate('discover.bucketIntervalTooltip.tooManyBucketsText', {
defaultMessage: 'too many buckets',
}),
bucketIntervalDescription: bucketInterval?.description,
},
})
: '',
panel: 1,
'data-test-subj': 'discoverTimeIntervalPanel',
});
}

const panels: EuiContextMenuPanelDescriptor[] = [
{
id: 0,
title: i18n.translate('discover.chartOptions', {
defaultMessage: 'Chart options',
}),
items: mainPanelItems,
},
];
if (!hideChart) {
panels.push({
id: 1,
initialFocusedItemIndex: selectedOptionIdx > -1 ? selectedOptionIdx : 0,
title: i18n.translate('discover.timeIntervals', {
defaultMessage: 'Time intervals',
}),
items: search.aggs.intervalOptions
.filter(({ val }) => val !== 'custom')
.map(({ display, val }) => {
return {
name: display,
label: display,
icon: val === interval ? 'check' : 'empty',
onClick: () => {
onChangeInterval(val);
closePopover();
},
'data-test-subj': `discoverTimeInterval-${display}`,
className: val === interval ? 'discoverIntervalSelected' : '',
};
}),
});
}
return panels;
}
Original file line number Diff line number Diff line change
Expand Up @@ -137,12 +137,12 @@ function getProps(indexPattern: IndexPattern): DiscoverLayoutProps {
describe('Discover component', () => {
test('selected index pattern without time field displays no chart toggle', () => {
const component = mountWithIntl(<DiscoverLayout {...getProps(indexPatternMock)} />);
expect(component.find('[data-test-subj="discoverChartToggle"]').exists()).toBeFalsy();
expect(component.find('[data-test-subj="discoverChartOptionsToggle"]').exists()).toBeFalsy();
});
test('selected index pattern with time field displays chart toggle', () => {
const component = mountWithIntl(
<DiscoverLayout {...getProps(indexPatternWithTimefieldMock)} />
);
expect(component.find('[data-test-subj="discoverChartToggle"]').exists()).toBeTruthy();
expect(component.find('[data-test-subj="discoverChartOptionsToggle"]').exists()).toBeTruthy();
});
});
Loading