Skip to content

Commit

Permalink
update date picker component (#79418) (#81494)
Browse files Browse the repository at this point in the history
Co-authored-by: Kibana Machine <[email protected]>

Co-authored-by: Shahzad <[email protected]>
Co-authored-by: Kibana Machine <[email protected]>
  • Loading branch information
3 people authored Oct 23, 2020
1 parent 77081a1 commit 252dd62
Show file tree
Hide file tree
Showing 4 changed files with 140 additions and 17 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,16 @@

import React from 'react';
import { UptimeDatePicker } from '../uptime_date_picker';
import { renderWithRouter, shallowWithRouter, MountWithReduxProvider } from '../../../lib';
import {
renderWithRouter,
shallowWithRouter,
MountWithReduxProvider,
mountWithRouterRedux,
} from '../../../lib';
import { UptimeStartupPluginsContextProvider } from '../../../contexts';
import { startPlugins } from '../../../lib/__mocks__/uptime_plugin_start_mock';
import { ClientPluginsStart } from '../../../apps/plugin';
import { createMemoryHistory } from 'history';

describe('UptimeDatePicker component', () => {
it('validates props with shallow render', () => {
Expand All @@ -22,4 +31,59 @@ describe('UptimeDatePicker component', () => {
);
expect(component).toMatchSnapshot();
});

it('uses shared date range state when there is no url date range state', () => {
const customHistory = createMemoryHistory();
jest.spyOn(customHistory, 'push');

const component = mountWithRouterRedux(
<UptimeStartupPluginsContextProvider
{...((startPlugins as unknown) as Partial<ClientPluginsStart>)}
>
<UptimeDatePicker />
</UptimeStartupPluginsContextProvider>,
{ customHistory }
);

const startBtn = component.find('[data-test-subj="superDatePickerstartDatePopoverButton"]');

expect(startBtn.text()).toBe('~ 30 minutes ago');

const endBtn = component.find('[data-test-subj="superDatePickerendDatePopoverButton"]');

expect(endBtn.text()).toBe('~ 15 minutes ago');

expect(customHistory.push).toHaveBeenCalledWith({
pathname: '/',
search: 'dateRangeStart=now-30m&dateRangeEnd=now-15m',
});
});

it('should use url date range even if shared date range is present', () => {
const customHistory = createMemoryHistory({
initialEntries: ['/?g=%22%22&dateRangeStart=now-10m&dateRangeEnd=now'],
});

jest.spyOn(customHistory, 'push');

const component = mountWithRouterRedux(
<UptimeStartupPluginsContextProvider
{...((startPlugins as unknown) as Partial<ClientPluginsStart>)}
>
<UptimeDatePicker />
</UptimeStartupPluginsContextProvider>,
{ customHistory }
);

const showDateBtn = component.find('[data-test-subj="superDatePickerShowDatesButton"]');

expect(showDateBtn.childAt(0).text()).toBe('Last 10 minutes');

// it should update shared state

expect(startPlugins.data.query.timefilter.timefilter.setTime).toHaveBeenCalledWith({
from: 'now-10m',
to: 'now',
});
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -4,24 +4,59 @@
* you may not use this file except in compliance with the Elastic License.
*/

import React, { useContext } from 'react';
import React, { useContext, useEffect } from 'react';
import { EuiSuperDatePicker } from '@elastic/eui';
import { useUrlParams } from '../../hooks';
import { CLIENT_DEFAULTS } from '../../../common/constants';
import { UptimeRefreshContext, UptimeSettingsContext } from '../../contexts';
import {
UptimeRefreshContext,
UptimeSettingsContext,
UptimeStartupPluginsContext,
} from '../../contexts';

export interface CommonlyUsedRange {
from: string;
to: string;
display: string;
}

const isUptimeDefaultDateRange = (dateRangeStart: string, dateRangeEnd: string) => {
const { DATE_RANGE_START, DATE_RANGE_END } = CLIENT_DEFAULTS;

return dateRangeStart === DATE_RANGE_START && dateRangeEnd === DATE_RANGE_END;
};

export const UptimeDatePicker = () => {
const [getUrlParams, updateUrl] = useUrlParams();
const { autorefreshInterval, autorefreshIsPaused, dateRangeStart, dateRangeEnd } = getUrlParams();
const { commonlyUsedRanges } = useContext(UptimeSettingsContext);
const { refreshApp } = useContext(UptimeRefreshContext);

const { data } = useContext(UptimeStartupPluginsContext);

// read time from state and update the url
const sharedTimeState = data?.query.timefilter.timefilter.getTime();

const {
autorefreshInterval,
autorefreshIsPaused,
dateRangeStart: start,
dateRangeEnd: end,
} = getUrlParams();

useEffect(() => {
const { from, to } = sharedTimeState ?? {};
// if it's uptime default range, and we have shared state from kibana, let's use that
if (isUptimeDefaultDateRange(start, end) && (from !== start || to !== end)) {
updateUrl({ dateRangeStart: from, dateRangeEnd: to });
} else if (from !== start || to !== end) {
// if it's coming url. let's update shared state
data?.query.timefilter.timefilter.setTime({ from: start, to: end });
}

// only need at start, rest date picker on change fucn will take care off
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);

const euiCommonlyUsedRanges = commonlyUsedRanges
? commonlyUsedRanges.map(
({ from, to, display }: { from: string; to: string; display: string }) => {
Expand All @@ -36,13 +71,17 @@ export const UptimeDatePicker = () => {

return (
<EuiSuperDatePicker
start={dateRangeStart}
end={dateRangeEnd}
start={start}
end={end}
commonlyUsedRanges={euiCommonlyUsedRanges}
isPaused={autorefreshIsPaused}
refreshInterval={autorefreshInterval}
onTimeChange={({ start, end }) => {
updateUrl({ dateRangeStart: start, dateRangeEnd: end });
onTimeChange={({ start: startN, end: endN }) => {
if (data?.query?.timefilter?.timefilter) {
data?.query.timefilter.timefilter.setTime({ from: startN, to: endN });
}

updateUrl({ dateRangeStart: startN, dateRangeEnd: endN });
refreshApp();
}}
onRefresh={refreshApp}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
/*
* 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.
*/

interface InputTimeRange {
from: string;
to: string;
}

export const startPlugins = {
data: {
query: {
timefilter: {
timefilter: {
getTime: () => ({ to: 'now-15m', from: 'now-30m' }),
setTime: jest.fn(({ from, to }: InputTimeRange) => {}),
},
},
},
},
};
15 changes: 6 additions & 9 deletions x-pack/plugins/uptime/public/lib/helper/helper_with_router.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,22 +20,19 @@ const helperWithRouter: <R>(
wrapReduxStore?: boolean,
storeState?: AppState
) => R = (helper, component, customHistory, wrapReduxStore, storeState) => {
if (customHistory) {
customHistory.location.key = 'TestKeyForTesting';
return helper(<Router history={customHistory}>{component}</Router>);
}
const history = createMemoryHistory();
const history = customHistory ?? createMemoryHistory();

history.location.key = 'TestKeyForTesting';

const routerWrapper = <Router history={history}>{component}</Router>;

if (wrapReduxStore) {
return helper(
<MountWithReduxProvider store={storeState}>
<Router history={history}>{component}</Router>
</MountWithReduxProvider>
<MountWithReduxProvider store={storeState}>{routerWrapper}</MountWithReduxProvider>
);
}

return helper(<Router history={history}>{component}</Router>);
return helper(routerWrapper);
};

export const renderWithRouter = (component: ReactElement, customHistory?: MemoryHistory) => {
Expand Down

0 comments on commit 252dd62

Please sign in to comment.