Skip to content

Commit

Permalink
refactor context initilization
Browse files Browse the repository at this point in the history
  • Loading branch information
shahzad31 committed Jan 10, 2020
1 parent b3c517c commit b9f9432
Show file tree
Hide file tree
Showing 8 changed files with 26 additions and 89 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -10,17 +10,17 @@ import { UptimeDatePicker } from '../uptime_date_picker';

describe('UptimeDatePicker component', () => {
it('validates props with shallow render', () => {
const component = shallowWithIntl(<UptimeDatePicker refreshApp={jest.fn()} />);
const component = shallowWithIntl(<UptimeDatePicker />);
expect(component).toMatchSnapshot();
});

it('renders properly with mock data', () => {
const component = renderWithIntl(<UptimeDatePicker refreshApp={jest.fn()} />);
const component = renderWithIntl(<UptimeDatePicker />);
expect(component).toMatchSnapshot();
});

it('renders properly without commonlyUsedRanges prop', () => {
const component = renderWithIntl(<UptimeDatePicker refreshApp={jest.fn()} />);
const component = renderWithIntl(<UptimeDatePicker />);
expect(component).toMatchSnapshot();
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
import React, { useContext } from 'react';
import { EuiHealth, EuiSpacer } from '@elastic/eui';
import { FormattedMessage } from '@kbn/i18n/react';
import { UptimeSettingsContext } from '../../../../contexts';
import { UptimeThemeContext } from '../../../../contexts';
import { UNNAMED_LOCATION, UP } from './monitor_status_list';

interface MonitorStatusRowProps {
Expand All @@ -24,7 +24,7 @@ interface MonitorStatusRowProps {
export const MonitorStatusRow = ({ locationNames, status }: MonitorStatusRowProps) => {
const {
colors: { success, danger },
} = useContext(UptimeSettingsContext);
} = useContext(UptimeThemeContext);

const color = status === UP ? success : danger;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { EuiSuperDatePicker } from '@elastic/eui';
import React, { useContext } from 'react';
import { useUrlParams } from '../../hooks';
import { CLIENT_DEFAULTS } from '../../../common/constants';
import { UptimeSettingsContext } from '../../contexts';
import { UptimeRefreshContext, UptimeSettingsContext } from '../../contexts';

// TODO: when EUI exports types for this, this should be replaced
interface SuperDateRangePickerRangeChangedEvent {
Expand All @@ -27,14 +27,11 @@ export interface CommonlyUsedRange {
display: string;
}

interface UptimeDatePickerProps {
refreshApp: () => void;
}

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

const euiCommonlyUsedRanges = commonlyUsedRanges
? commonlyUsedRanges.map(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,39 +5,25 @@
*/

import React, { createContext, useMemo, useState } from 'react';
import { History } from 'history';
import { useHistory, useLocation } from 'react-router-dom';
import { store } from '../state';
import { triggerAppRefresh } from '../state/actions';

interface Location {
pathname: string;
search: string;
}

interface UMRefreshContext {
lastRefresh: number;
history: History | undefined;
location: Location | undefined;
refreshApp: () => void;
}

const defaultContext: UMRefreshContext = {
lastRefresh: 0,
history: undefined,
location: undefined,
refreshApp: () => {
throw new Error('App refresh was not initialized, set it when you invoke the context');
},
};

export const UptimeRefreshContext = createContext(defaultContext);

interface ContextProps {
lastRefresh: number;
}

export const UptimeRefreshContextProvider: React.FC<ContextProps> = ({ children }) => {
export const UptimeRefreshContextProvider: React.FC = ({ children }) => {
const history = useHistory();
const location = useLocation();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,13 @@
* you may not use this file except in compliance with the Elastic License.
*/

import DateMath from '@elastic/datemath';
import React, { createContext, useMemo } from 'react';
import { useParams } from 'react-router-dom';
import { UptimeAppProps } from '../uptime_app';
import { CONTEXT_DEFAULTS } from '../../common/constants';
import { CommonlyUsedRange } from '../components/functional/uptime_date_picker';

export interface UMSettingsContextValues {
absoluteStartDate: number;
absoluteEndDate: number;
autorefreshIsPaused: boolean;
autorefreshInterval: number;
basePath: string;
dateRangeStart: string;
dateRangeEnd: string;
Expand All @@ -25,27 +20,13 @@ export interface UMSettingsContextValues {
commonlyUsedRanges?: CommonlyUsedRange[];
}

const {
AUTOREFRESH_IS_PAUSED,
AUTOREFRESH_INTERVAL,
BASE_PATH,
DATE_RANGE_START,
DATE_RANGE_END,
} = CONTEXT_DEFAULTS;
const parsedStart = DateMath.parse(DATE_RANGE_START);
const parsedEnd = DateMath.parse(DATE_RANGE_END);
const DEFAULT_ABSOLUTE_START_DATE = parsedStart ? parsedStart.valueOf() : 0;
const DEFAULT_ABSOLUTE_END_DATE = parsedEnd ? parsedEnd.valueOf() : 1;
const { BASE_PATH, DATE_RANGE_START, DATE_RANGE_END } = CONTEXT_DEFAULTS;

/**
* These are default values for the context. These defaults are typically
* overwritten by the Uptime App upon its invocation.
*/
const defaultContext: UMSettingsContextValues = {
absoluteStartDate: DEFAULT_ABSOLUTE_START_DATE,
absoluteEndDate: DEFAULT_ABSOLUTE_END_DATE,
autorefreshIsPaused: AUTOREFRESH_IS_PAUSED,
autorefreshInterval: AUTOREFRESH_INTERVAL,
basePath: BASE_PATH,
dateRangeStart: DATE_RANGE_START,
dateRangeEnd: DATE_RANGE_END,
Expand All @@ -58,33 +39,18 @@ export const UptimeSettingsContext = createContext(defaultContext);
export const UptimeSettingsContextProvider: React.FC<UptimeAppProps> = ({ children, ...props }) => {
const { basePath, isApmAvailable, isInfraAvailable, isLogsAvailable } = props;

const { autorefreshInterval, autorefreshIsPaused, dateRangeStart, dateRangeEnd } = useParams();
const { dateRangeStart, dateRangeEnd } = useParams();

const value = useMemo(() => {
const absoluteStartDate = DateMath.parse(dateRangeStart ?? '');
const absoluteEndDate = DateMath.parse(dateRangeEnd ?? '');
return {
absoluteStartDate: absoluteStartDate ? absoluteStartDate.valueOf() : 0,
absoluteEndDate: absoluteEndDate ? absoluteEndDate.valueOf() : 1,
autorefreshInterval,
autorefreshIsPaused,
basePath,
dateRangeStart,
dateRangeEnd,
isApmAvailable,
isInfraAvailable,
isLogsAvailable,
dateRangeStart: dateRangeStart ?? DATE_RANGE_START,
dateRangeEnd: dateRangeEnd ?? DATE_RANGE_END,
};
}, [
autorefreshInterval,
autorefreshIsPaused,
dateRangeStart,
dateRangeEnd,
basePath,
isApmAvailable,
isInfraAvailable,
isLogsAvailable,
]);
}, [basePath, isApmAvailable, isInfraAvailable, isLogsAvailable, dateRangeStart, dateRangeEnd]);

return <UptimeSettingsContext.Provider value={value} children={children} />;
};
Original file line number Diff line number Diff line change
Expand Up @@ -67,9 +67,7 @@ describe('useUrlParams', () => {

it('accepts router props, updates URL params, and returns the current params', () => {
const component = mountWithIntl(
<UptimeRefreshContext.Provider
value={{ lastRefresh: 123, history: mockRouter.history, location: mockRouter.location }}
>
<UptimeRefreshContext.Provider value={{ lastRefresh: 123, refreshApp: jest.fn() }}>
<UseUrlParamsTestComponent hook={useUrlParams} />
</UptimeRefreshContext.Provider>
);
Expand All @@ -88,11 +86,7 @@ describe('useUrlParams', () => {
<UptimeRefreshContext.Provider
value={{
lastRefresh: 123,
history: mockRouter.history,
location: {
...mockRouter.location,
search: 'g=%22%22&dateRangeStart=now-19d&dateRangeEnd=now-1m',
},
refreshApp: jest.fn(),
}}
>
<UseUrlParamsTestComponent hook={useUrlParams} />
Expand All @@ -111,8 +105,7 @@ describe('useUrlParams', () => {
<UptimeRefreshContext.Provider
value={{
lastRefresh: 123,
history: mockRouter.history,
location: mockRouter.location,
refreshApp: jest.fn(),
}}
>
<UseUrlParamsTestComponent hook={useUrlParams} updateParams={{ pagination: '' }} />
Expand Down
17 changes: 7 additions & 10 deletions x-pack/legacy/plugins/uptime/public/hooks/use_url_params.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,7 @@
*/

import qs from 'querystring';
import { useContext } from 'react';
import { UptimeRefreshContext } from '../contexts';
import { useLocation, useHistory } from 'react-router-dom';
import { UptimeUrlParams, getSupportedUrlParams } from '../lib/helper';

type GetUrlParams = () => UptimeUrlParams;
Expand All @@ -15,24 +14,22 @@ type UpdateUrlParams = (updatedParams: { [key: string]: string | number | boolea
export type UptimeUrlParamsHook = () => [GetUrlParams, UpdateUrlParams];

export const useUrlParams: UptimeUrlParamsHook = () => {
const refreshContext = useContext(UptimeRefreshContext);
const location = useLocation();
const history = useHistory();

const getUrlParams: GetUrlParams = () => {
let search: string | undefined;
if (refreshContext.location) {
search = refreshContext.location.search;
if (location) {
search = location.search;
}

const params = search ? { ...qs.parse(search[0] === '?' ? search.slice(1) : search) } : {};
return getSupportedUrlParams(params);
};

const updateUrlParams: UpdateUrlParams = updatedParams => {
if (!refreshContext.history || !refreshContext.location) return;
const {
history,
location: { pathname, search },
} = refreshContext;
if (!history || !location) return;
const { pathname, search } = location;
const currentParams: any = qs.parse(search[0] === '?' ? search.slice(1) : search);
const mergedParams = {
...currentParams,
Expand Down
6 changes: 2 additions & 4 deletions x-pack/legacy/plugins/uptime/public/pages/page_header.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
*/

import { EuiTitle, EuiFlexGroup, EuiFlexItem, EuiSpacer } from '@elastic/eui';
import React, { useEffect, useState, useContext } from 'react';
import React, { useEffect, useState } from 'react';
import { connect } from 'react-redux';
import { useRouteMatch, useParams } from 'react-router-dom';
import { i18n } from '@kbn/i18n';
Expand All @@ -14,7 +14,6 @@ import { AppState } from '../state';
import { selectSelectedMonitor } from '../state/selectors';
import { getMonitorPageBreadcrumb, getOverviewPageBreadcrumbs } from '../breadcrumbs';
import { stringifyUrlParams } from '../lib/helper/stringify_url_params';
import { UptimeSettingsContext } from '../contexts';
import { getTitle } from '../lib/helper/get_title';
import { UMUpdateBreadcrumbs } from '../lib/lib';
import { MONITOR_ROUTE } from '../routes';
Expand All @@ -28,7 +27,6 @@ export const PageHeaderComponent = ({ monitorStatus, setBreadcrumbs }: PageHeade
const monitorPage = useRouteMatch({
path: MONITOR_ROUTE,
});
const { refreshApp } = useContext(UptimeSettingsContext);

const { absoluteDateRangeStart, absoluteDateRangeEnd, ...params } = useParams();

Expand Down Expand Up @@ -74,7 +72,7 @@ export const PageHeaderComponent = ({ monitorStatus, setBreadcrumbs }: PageHeade
</EuiTitle>
</EuiFlexItem>
<EuiFlexItem grow={false}>
<UptimeDatePicker refreshApp={refreshApp} />
<UptimeDatePicker />
</EuiFlexItem>
</EuiFlexGroup>
<EuiSpacer size="s" />
Expand Down

0 comments on commit b9f9432

Please sign in to comment.