Skip to content

Commit

Permalink
[Uptime] Modify router to use ScopedHistory (#76421)
Browse files Browse the repository at this point in the history
* Remove hashbang and modify router to use ScopedHistory.

* Update test to conform to refactored API.

* Update test snapshots.

* Fix broken type check.

* Remove unneeded prop.

* Prevent full page reload for breadcrumbs.

* Fix outdated test.

* Fix type errors.

* Add default value for focusConnectorField url param.

* Make stringify function support focusFieldConnector empty values.

* Avoid unnecessary text in breadcrumb href.

* Refresh test snapshot.

Co-authored-by: Elastic Machine <[email protected]>
  • Loading branch information
justinkambic and elasticmachine authored Sep 8, 2020
1 parent 728dfb4 commit 4afa2d6
Show file tree
Hide file tree
Showing 15 changed files with 68 additions and 40 deletions.
1 change: 1 addition & 0 deletions x-pack/plugins/uptime/common/constants/client_defaults.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ export const CLIENT_DEFAULTS = {
* The end of the default date range is now.
*/
DATE_RANGE_END: 'now',
FOCUS_CONNECTOR_FIELD: false,
FILTERS: '',
MONITOR_LIST_PAGE_INDEX: 0,
MONITOR_LIST_PAGE_SIZE: 20,
Expand Down
1 change: 0 additions & 1 deletion x-pack/plugins/uptime/common/constants/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ export const PLUGIN = {
NAME: i18n.translate('xpack.uptime.featureRegistry.uptimeFeatureName', {
defaultMessage: 'Uptime',
}),
ROUTER_BASE_NAME: '/app/uptime#',
TITLE: i18n.translate('xpack.uptime.uptimeFeatureCatalogueTitle', {
defaultMessage: 'Uptime',
}),
Expand Down
3 changes: 1 addition & 2 deletions x-pack/plugins/uptime/public/apps/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ export class UptimePlugin
title: PLUGIN.TITLE,
description: PLUGIN.DESCRIPTION,
icon: 'uptimeApp',
path: '/app/uptime#/',
path: '/app/uptime',
showOnHomePage: false,
category: FeatureCatalogueCategory.DATA,
});
Expand All @@ -84,7 +84,6 @@ export class UptimePlugin
});

core.application.register({
appRoute: '/app/uptime#/',
id: PLUGIN.ID,
euiIconType: 'uptimeApp',
order: 8400,
Expand Down
5 changes: 2 additions & 3 deletions x-pack/plugins/uptime/public/apps/render_app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,12 @@ import {
} from '../../common/constants';
import { UptimeApp, UptimeAppProps } from './uptime_app';
import { ClientPluginsSetup, ClientPluginsStart } from './plugin';
import { PLUGIN } from '../../common/constants/plugin';

export function renderApp(
core: CoreStart,
plugins: ClientPluginsSetup,
startPlugins: ClientPluginsStart,
{ element }: AppMountParameters
{ element, history }: AppMountParameters
) {
const {
application: { capabilities },
Expand All @@ -48,6 +47,7 @@ export function renderApp(
basePath: basePath.get(),
darkMode: core.uiSettings.get(DEFAULT_DARK_MODE),
commonlyUsedRanges: core.uiSettings.get(DEFAULT_TIMEPICKER_QUICK_RANGES),
history,
isApmAvailable: apm,
isInfraAvailable: infrastructure,
isLogsAvailable: logs,
Expand All @@ -67,7 +67,6 @@ export function renderApp(
},
],
}),
routerBasename: basePath.prepend(PLUGIN.ROUTER_BASE_NAME),
setBadge,
setBreadcrumbs: core.chrome.setBreadcrumbs,
};
Expand Down
8 changes: 4 additions & 4 deletions x-pack/plugins/uptime/public/apps/uptime_app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { EuiPage, EuiErrorBoundary } from '@elastic/eui';
import { i18n } from '@kbn/i18n';
import React, { useEffect } from 'react';
import { Provider as ReduxProvider } from 'react-redux';
import { BrowserRouter as Router } from 'react-router-dom';
import { Router } from 'react-router-dom';
import { I18nStart, ChromeBreadcrumb, CoreStart } from 'kibana/public';
import {
KibanaContextProvider,
Expand All @@ -31,6 +31,7 @@ import {
} from '../components/overview/alerts';
import { store } from '../state';
import { kibanaService } from '../state/kibana_service';
import { ScopedHistory } from '../../../../../src/core/public';

export interface UptimeAppColors {
danger: string;
Expand All @@ -46,13 +47,13 @@ export interface UptimeAppProps {
canSave: boolean;
core: CoreStart;
darkMode: boolean;
history: ScopedHistory;
i18n: I18nStart;
isApmAvailable: boolean;
isInfraAvailable: boolean;
isLogsAvailable: boolean;
plugins: ClientPluginsSetup;
startPlugins: ClientPluginsStart;
routerBasename: string;
setBadge: UMUpdateBadge;
renderGlobalHelpControls(): void;
commonlyUsedRanges: CommonlyUsedRange[];
Expand All @@ -68,7 +69,6 @@ const Application = (props: UptimeAppProps) => {
i18n: i18nCore,
plugins,
renderGlobalHelpControls,
routerBasename,
setBadge,
startPlugins,
} = props;
Expand Down Expand Up @@ -99,7 +99,7 @@ const Application = (props: UptimeAppProps) => {
<i18nCore.Context>
<ReduxProvider store={store}>
<KibanaContextProvider services={{ ...core, ...plugins }}>
<Router basename={routerBasename}>
<Router history={props.history}>
<UptimeRefreshContextProvider>
<UptimeSettingsContextProvider {...props}>
<UptimeThemeContextProvider darkMode={darkMode}>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ async function fetchUptimeOverviewData({
const pings = await fetchPingHistogram({ dateStart: start, dateEnd: end, bucketSize });

const response: UptimeFetchDataResponse = {
appLink: `/app/uptime#/?dateRangeStart=${relativeTime.start}&dateRangeEnd=${relativeTime.end}`,
appLink: `/app/uptime?dateRangeStart=${relativeTime.start}&dateRangeEnd=${relativeTime.end}`,
stats: {
monitors: {
type: 'number',
Expand Down

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ export const DataOrIndexMissing = ({ headingMessage, settings }: DataMissingProp
</EuiButton>
</EuiFlexItem>
<EuiFlexItem>
<EuiButton color="primary" href={`${basePath}/app/uptime#/settings`}>
<EuiButton color="primary" href={`${basePath}/app/uptime/settings`}>
<FormattedMessage
id="xpack.uptime.emptyState.updateIndexPattern"
defaultMessage="Update index pattern settings"
Expand Down

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,11 @@ describe('useBreadcrumbs', () => {
);

const urlParams: UptimeUrlParams = getSupportedUrlParams({});
expect(getBreadcrumbs()).toStrictEqual([makeBaseBreadcrumb(urlParams)].concat(expectedCrumbs));
expect(JSON.stringify(getBreadcrumbs())).toEqual(
JSON.stringify(
[makeBaseBreadcrumb('/app/uptime', jest.fn(), urlParams)].concat(expectedCrumbs)
)
);
});
});

Expand All @@ -54,6 +58,10 @@ const mockCore: () => [() => ChromeBreadcrumb[], any] = () => {
return breadcrumbObj;
};
const core = {
application: {
getUrlForApp: () => '/app/uptime',
navigateToUrl: jest.fn(),
},
chrome: {
setBreadcrumbs: (newBreadcrumbs: ChromeBreadcrumb[]) => {
breadcrumbObj = newBreadcrumbs;
Expand Down
29 changes: 23 additions & 6 deletions x-pack/plugins/uptime/public/hooks/use_breadcrumbs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,35 +7,52 @@
import { ChromeBreadcrumb } from 'kibana/public';
import { i18n } from '@kbn/i18n';
import { useEffect } from 'react';
import { EuiBreadcrumb } from '@elastic/eui';
import { UptimeUrlParams } from '../lib/helper';
import { stringifyUrlParams } from '../lib/helper/stringify_url_params';
import { useKibana } from '../../../../../src/plugins/kibana_react/public';
import { useUrlParams } from '.';
import { PLUGIN } from '../../common/constants/plugin';

export const makeBaseBreadcrumb = (params?: UptimeUrlParams): ChromeBreadcrumb => {
let href = '#/';
const EMPTY_QUERY = '?';

export const makeBaseBreadcrumb = (
href: string,
navigateToHref?: (url: string) => Promise<void>,
params?: UptimeUrlParams
): EuiBreadcrumb => {
if (params) {
const crumbParams: Partial<UptimeUrlParams> = { ...params };
// We don't want to encode this values because they are often set to Date.now(), the relative
// values in dateRangeStart are better for a URL.
delete crumbParams.absoluteDateRangeStart;
delete crumbParams.absoluteDateRangeEnd;
href += stringifyUrlParams(crumbParams, true);
const query = stringifyUrlParams(crumbParams, true);
href += query === EMPTY_QUERY ? '' : query;
}
return {
text: i18n.translate('xpack.uptime.breadcrumbs.overviewBreadcrumbText', {
defaultMessage: 'Uptime',
}),
href,
onClick: (event) => {
if (href && navigateToHref) {
event.preventDefault();
navigateToHref(href);
}
},
};
};

export const useBreadcrumbs = (extraCrumbs: ChromeBreadcrumb[]) => {
const params = useUrlParams()[0]();
const setBreadcrumbs = useKibana().services.chrome?.setBreadcrumbs;
const kibana = useKibana();
const setBreadcrumbs = kibana.services.chrome?.setBreadcrumbs;
const appPath = kibana.services.application?.getUrlForApp(PLUGIN.ID) ?? '';
const navigate = kibana.services.application?.navigateToUrl;
useEffect(() => {
if (setBreadcrumbs) {
setBreadcrumbs([makeBaseBreadcrumb(params)].concat(extraCrumbs));
setBreadcrumbs([makeBaseBreadcrumb(appPath, navigate, params)].concat(extraCrumbs));
}
}, [extraCrumbs, params, setBreadcrumbs]);
}, [appPath, extraCrumbs, navigate, params, setBreadcrumbs]);
};

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,14 @@ describe('stringifyUrlParams', () => {
dateRangeStart: 'now-15m',
dateRangeEnd: 'now',
filters: 'monitor.id: bar',
focusConnectorField: true,
search: 'monitor.id: foo',
selectedPingStatus: 'down',
statusFilter: 'up',
});
expect(result).toMatchSnapshot();
expect(result).toMatchInlineSnapshot(
`"?autorefreshInterval=50000&autorefreshIsPaused=false&dateRangeStart=now-15m&dateRangeEnd=now&filters=monitor.id%3A%20bar&focusConnectorField=true&search=monitor.id%3A%20foo&selectedPingStatus=down&statusFilter=up"`
);
});

it('creates expected string value when ignore empty is true', () => {
Expand All @@ -29,14 +32,17 @@ describe('stringifyUrlParams', () => {
dateRangeStart: 'now-15m',
dateRangeEnd: 'now',
filters: 'monitor.id: bar',
focusConnectorField: false,
search: undefined,
selectedPingStatus: undefined,
statusFilter: '',
pagination: undefined,
},
true
);
expect(result).toMatchSnapshot();
expect(result).toMatchInlineSnapshot(
`"?autorefreshInterval=50000&filters=monitor.id%3A%20bar"`
);

expect(result.includes('pagination')).toBeFalsy();
expect(result.includes('search')).toBeFalsy();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ const {
AUTOREFRESH_IS_PAUSED,
DATE_RANGE_START,
DATE_RANGE_END,
FOCUS_CONNECTOR_FIELD,
} = CLIENT_DEFAULTS;

export const stringifyUrlParams = (params: Partial<UptimeUrlParams>, ignoreEmpty = false) => {
Expand All @@ -36,6 +37,9 @@ export const stringifyUrlParams = (params: Partial<UptimeUrlParams>, ignoreEmpty
if (key === 'autorefreshInterval' && val === AUTOREFRESH_INTERVAL) {
delete params[key];
}
if (key === 'focusConnectorField' && val === FOCUS_CONNECTOR_FIELD) {
delete params[key];
}
});
}
return `?${stringify(params, { sort: false })}`;
Expand Down

0 comments on commit 4afa2d6

Please sign in to comment.