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 13 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,27 @@
* 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 +45,22 @@ export function DiscoverChart({
stateContainer: GetStateReturn;
timefield?: string;
}) {
const { data, uiSettings: config } = services;
const [showChartOptionsPopover, setShowChartOptionsPopover] = useState(false);

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

const onShowChartOptions = useCallback(() => {
setShowChartOptionsPopover(!showChartOptionsPopover);
}, [showChartOptionsPopover]);

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

useEffect(() => {
if (chartRef.current.moveFocus && chartRef.current.element) {
chartRef.current.element.focus();
Expand All @@ -57,15 +73,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,49 +83,51 @@ export function DiscoverChart({
},
[data]
);
const panels = useChartPanels(
state,
savedSearchDataChart$,
toggleHideChart,
(interval) => stateContainer.setAppState({ interval }),
() => setShowChartOptionsPopover(false)
);

return (
<EuiFlexGroup direction="column" alignItems="stretch" gutterSize="none" responsive={false}>
<EuiFlexItem grow={false} className="dscResultCount">
<EuiFlexGroup alignItems="center" justifyContent="spaceBetween">
<EuiFlexGroup justifyContent="spaceBetween" responsive={false}>
<EuiFlexItem
grow={false}
className="dscResuntCount__title eui-textTruncate eui-textNoWrap"
className="dscResultCount__title eui-textTruncate eui-textNoWrap"
>
<HitsCounter
savedSearchData$={savedSearchDataTotalHits$}
showResetButton={!!(savedSearch && savedSearch.id)}
onResetQuery={resetSavedSearch}
/>
</EuiFlexItem>
{!state.hideChart && (
<EuiFlexItem className="dscResultCount__actions">
<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="dscChartOptions"
button={
<EuiButtonEmpty
size="xs"
iconType={'gear'}
onClick={onShowChartOptions}
data-test-subj="discoverChartOptionsToggle"
>
{i18n.translate('discover.chartOptionsButton', {
defaultMessage: 'Chart options',
})}
</EuiButtonEmpty>
</EuiButtonEmpty>
}
isOpen={showChartOptionsPopover}
closePopover={closeChartOptions}
panelPaddingSize="none"
anchorPosition="downLeft"
>
<EuiContextMenu initialPanelId={0} panels={panels} />
</EuiPopover>
</EuiFlexItem>
)}
</EuiFlexGroup>
Expand All @@ -133,13 +142,11 @@ export function DiscoverChart({
})}
className="dscTimechart"
>
<div className="dscHistogram" data-test-subj="discoverChart">
<DiscoverHistogramMemoized
savedSearchData$={savedSearchDataChart$}
timefilterUpdateHandler={timefilterUpdateHandler}
services={services}
/>
</div>
<DiscoverHistogramMemoized
savedSearchData$={savedSearchDataChart$}
timefilterUpdateHandler={timefilterUpdateHandler}
services={services}
/>
</section>
<EuiSpacer size="s" />
</EuiFlexItem>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,10 @@
*/
import './histogram.scss';
import moment, { unitOfTime } from 'moment-timezone';
import React, { useCallback } from 'react';
import React, { useCallback, useMemo } from 'react';
import { EuiLoadingChart, EuiSpacer, EuiText } from '@elastic/eui';
import { FormattedMessage } from '@kbn/i18n/react';

import dateMath from '@elastic/datemath';
import {
Axis,
BrushEndListener,
Expand All @@ -23,7 +23,6 @@ import {
TooltipType,
XYChartElementEvent,
} from '@elastic/charts';

import { IUiSettingsClient } from 'kibana/public';
import {
CurrentTime,
Expand Down Expand Up @@ -92,14 +91,42 @@ export function DiscoverHistogram({
[timefilterUpdateHandler]
);

const { timefilter } = services.data.query.timefilter;

const { from, to } = timefilter.getTime();
const dateFormat = uiSettings.get('dateFormat');

const toMoment = useCallback(
(datetime: moment.Moment | undefined) => {
if (!datetime) {
return '';
}
if (!dateFormat) {
return String(datetime);
}
return datetime.format(dateFormat);
},
[dateFormat]
);

const timeRangeText = useMemo(() => {
const timeRange = {
from: dateMath.parse(from),
to: dateMath.parse(to, { roundUp: true }),
};
return `${toMoment(timeRange.from)} - ${toMoment(timeRange.to)}`;
}, [from, to, toMoment]);

if (!chartData && fetchStatus === FetchStatus.LOADING) {
return (
<div className="dscChart__loading">
<EuiText size="xs" color="subdued">
<EuiLoadingChart mono size="l" />
<EuiSpacer size="s" />
<FormattedMessage id="discover.loadingChartResults" defaultMessage="Loading chart" />
</EuiText>
<div className="dscHistogram" data-test-subj="discoverChart">
<div className="dscChart__loading">
<EuiText size="xs" color="subdued">
<EuiLoadingChart mono size="l" />
<EuiSpacer size="s" />
<FormattedMessage id="discover.loadingChartResults" defaultMessage="Loading chart" />
</EuiText>
</div>
</div>
);
}
Expand Down Expand Up @@ -152,51 +179,52 @@ export function DiscoverHistogram({
const xAxisFormatter = services.data.fieldFormats.deserialize(chartData.yAxisFormat);

return (
<Chart size="100%">
<Settings
xDomain={xDomain}
onBrushEnd={onBrushEnd}
onElementClick={onElementClick(xInterval)}
tooltip={tooltipProps}
theme={chartTheme}
baseTheme={chartBaseTheme}
allowBrushingLastHistogramBucket={true}
/>
<Axis
id="discover-histogram-left-axis"
position={Position.Left}
ticks={5}
title={chartData.yAxisLabel}
integersOnly
tickFormat={(value) => xAxisFormatter.convert(value)}
/>
<Axis
id="discover-histogram-bottom-axis"
position={Position.Bottom}
title={chartData.xAxisLabel}
tickFormat={formatXValue}
ticks={10}
/>
<CurrentTime isDarkMode={isDarkMode} domainEnd={domainEnd} />
<Endzones
isDarkMode={isDarkMode}
domainStart={domainStart}
domainEnd={domainEnd}
interval={xDomain.minInterval}
domainMin={xDomain.min}
domainMax={xDomain.max}
/>
<HistogramBarSeries
id="discover-histogram"
minBarHeight={2}
xScaleType={ScaleType.Time}
yScaleType={ScaleType.Linear}
xAccessor="x"
yAccessors={['y']}
data={data}
timeZone={timeZone}
name={chartData.yAxisLabel}
/>
</Chart>
<div className="dscHistogram" data-test-subj="discoverChart" data-time-range={timeRangeText}>
<Chart size="100%">
<Settings
xDomain={xDomain}
onBrushEnd={onBrushEnd}
onElementClick={onElementClick(xInterval)}
tooltip={tooltipProps}
theme={chartTheme}
baseTheme={chartBaseTheme}
allowBrushingLastHistogramBucket={true}
/>
<Axis
id="discover-histogram-left-axis"
position={Position.Left}
ticks={5}
integersOnly
tickFormat={(value) => xAxisFormatter.convert(value)}
/>
<Axis
id="discover-histogram-bottom-axis"
position={Position.Bottom}
title={timeRangeText}
tickFormat={formatXValue}
ticks={10}
/>
<CurrentTime isDarkMode={isDarkMode} domainEnd={domainEnd} />
<Endzones
isDarkMode={isDarkMode}
domainStart={domainStart}
domainEnd={domainEnd}
interval={xDomain.minInterval}
domainMin={xDomain.min}
domainMax={xDomain.max}
/>
<HistogramBarSeries
id="discover-histogram"
minBarHeight={2}
xScaleType={ScaleType.Time}
yScaleType={ScaleType.Linear}
xAccessor="x"
yAccessors={['y']}
data={data}
timeZone={timeZone}
name={chartData.yAxisLabel}
/>
</Chart>
</div>
);
}
Loading