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

Add url overflow handling to KP #67899

Merged
merged 9 commits into from
Jun 8, 2020
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
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
6 changes: 6 additions & 0 deletions docs/development/core/public/kibana-plugin-core-public.md
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,12 @@ The plugin integrates with the core system via lifecycle events: `setup`<!-- -->
| [URLMeaningfulParts](./kibana-plugin-core-public.urlmeaningfulparts.md) | We define our own typings because the current version of @<!-- -->types/node declares properties to be optional "hostname?: string". Although, parse call returns "hostname: null \| string". |
| [UserProvidedValues](./kibana-plugin-core-public.userprovidedvalues.md) | Describes the values explicitly set by user. |

## Variables

| Variable | Description |
| --- | --- |
| [URL\_MAX\_LENGTH](./kibana-plugin-core-public.url_max_length.md) | The max URL length allowed by the current browser. Should be used to display warnings to users when query parameters cause URL to exceed this limit. |

## Type Aliases

| Type Alias | Description |
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<!-- Do not edit this file. It is automatically generated by API Documenter. -->

[Home](./index.md) &gt; [kibana-plugin-core-public](./kibana-plugin-core-public.md) &gt; [URL\_MAX\_LENGTH](./kibana-plugin-core-public.url_max_length.md)

## URL\_MAX\_LENGTH variable

The max URL length allowed by the current browser. Should be used to display warnings to users when query parameters cause URL to exceed this limit.

<b>Signature:</b>

```typescript
URL_MAX_LENGTH: number
```
24 changes: 24 additions & 0 deletions src/core/public/application/application_service.mock.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
* under the License.
*/

import { History } from 'history';
import { BehaviorSubject, Subject } from 'rxjs';

import { capabilitiesServiceMock } from './capabilities/capabilities_service.mock';
Expand Down Expand Up @@ -57,6 +58,28 @@ const createStartContractMock = (): jest.Mocked<ApplicationStart> => {
};
};

const createHistoryMock = (): jest.Mocked<History> => {
return {
block: jest.fn(),
createHref: jest.fn(),
go: jest.fn(),
goBack: jest.fn(),
goForward: jest.fn(),
listen: jest.fn(),
push: jest.fn(),
replace: jest.fn(),
action: 'PUSH',
length: 1,
location: {
pathname: '/',
search: '',
hash: '',
key: '',
state: undefined,
},
};
};

const createInternalStartContractMock = (): jest.Mocked<InternalApplicationStart> => {
const currentAppId$ = new Subject<string | undefined>();

Expand All @@ -69,6 +92,7 @@ const createInternalStartContractMock = (): jest.Mocked<InternalApplicationStart
navigateToApp: jest.fn().mockImplementation((appId) => currentAppId$.next(appId)),
navigateToUrl: jest.fn(),
registerMountContext: jest.fn(),
history: createHistoryMock(),
};
};

Expand Down
1 change: 1 addition & 0 deletions src/core/public/application/application_service.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -301,6 +301,7 @@ export class ApplicationService {
distinctUntilChanged(),
takeUntil(this.stop$)
),
history: this.history,
registerMountContext: this.mountContext.registerContext,
getUrlForApp: (
appId,
Expand Down
1 change: 1 addition & 0 deletions src/core/public/application/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,5 +43,6 @@ export {
PublicAppInfo,
PublicLegacyAppInfo,
// Internal types
InternalApplicationSetup,
InternalApplicationStart,
} from './types';
7 changes: 7 additions & 0 deletions src/core/public/application/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
*/

import { Observable } from 'rxjs';
import { History } from 'history';

import { Capabilities } from './capabilities';
import { ChromeStart } from '../chrome';
Expand Down Expand Up @@ -766,6 +767,12 @@ export interface InternalApplicationStart extends Omit<ApplicationStart, 'regist

// Internal APIs
getComponent(): JSX.Element | null;

/**
* The global history instance, exposed only to Core. Undefined when rendering a legacy application.
* @internal
*/
history: History<unknown> | undefined;
}

/** @internal */
Expand Down
83 changes: 83 additions & 0 deletions src/core/public/core_app/core_app.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/

import { UnregisterCallback } from 'history';
import {
InternalApplicationSetup,
InternalApplicationStart,
AppNavLinkStatus,
AppMountParameters,
} from '../application';
import { HttpSetup, HttpStart } from '../http';
import { CoreContext } from '../core_system';
import { renderApp, setupUrlOverflowDetection } from './errors';
import { NotificationsStart } from '../notifications';
import { IUiSettingsClient } from '../ui_settings';

interface SetupDeps {
application: InternalApplicationSetup;
http: HttpSetup;
}

interface StartDeps {
application: InternalApplicationStart;
http: HttpStart;
notifications: NotificationsStart;
uiSettings: IUiSettingsClient;
}

export class CoreApp {
private stopHistoryListening?: UnregisterCallback;

constructor(private readonly coreContext: CoreContext) {}

public setup({ http, application }: SetupDeps) {
application.register(this.coreContext.coreId, {
id: 'error',
title: 'App Error',
navLinkStatus: AppNavLinkStatus.hidden,
mount(params: AppMountParameters) {
// Do not use an async import here in order to ensure that network failures
// cannot prevent the error UI from displaying. This UI is tiny so an async
// import here is probably not useful anyways.
return renderApp(params, { basePath: http.basePath });
},
});
}

public start({ application, http, notifications, uiSettings }: StartDeps) {
if (!application.history) {
return;
}

this.stopHistoryListening = setupUrlOverflowDetection({
basePath: http.basePath,
history: application.history,
toasts: notifications.toasts,
uiSettings,
});
}

public stop() {
if (this.stopHistoryListening) {
this.stopHistoryListening();
this.stopHistoryListening = undefined;
}
}
}
59 changes: 59 additions & 0 deletions src/core/public/core_app/errors/error_application.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/

import { act } from 'react-dom/test-utils';
import { History, createMemoryHistory } from 'history';
import { IBasePath } from '../../http';
import { BasePath } from '../../http/base_path';

import { renderApp } from './error_application';

describe('renderApp', () => {
let basePath: IBasePath;
let element: HTMLDivElement;
let history: History;
let unmount: any;

beforeEach(() => {
basePath = new BasePath();
element = document.createElement('div');
history = createMemoryHistory();
unmount = renderApp({ element, history } as any, { basePath });
});

afterEach(() => unmount());

it('renders generic errors', () => {
act(() => {
history.push('/app/error');
});
// innerText not working in jsdom, so use innerHTML
expect(element.querySelector('.euiTitle')!.innerHTML).toMatchInlineSnapshot(
`"Application error"`
);
});

it('renders urlOverflow errors', () => {
act(() => {
history.push('/app/error?errorType=urlOverflow');
});
expect(element.querySelector('.euiTitle')!.innerHTML).toMatchInlineSnapshot(`"Woah there!"`);
expect(element.innerHTML).toMatch("That's a big URL you have there");
});
});
102 changes: 102 additions & 0 deletions src/core/public/core_app/errors/error_application.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/

import React, { ReactChild, useState, useLayoutEffect } from 'react';
import ReactDOM from 'react-dom';
import { History } from 'history';
import { i18n } from '@kbn/i18n';
import { I18nProvider } from '@kbn/i18n/react';

import { EuiEmptyPrompt, EuiPage, EuiPageBody, EuiPageContent } from '@elastic/eui';
import { UrlOverflowUi } from './url_overflow_ui';
import { IBasePath } from '../../http';
import { AppMountParameters } from '../../application';

interface Props {
title?: string;
children?: ReactChild;
}

const ErrorPage: React.FC<Props> = ({ title, children }) => {
title =
title ??
i18n.translate('core.application.appRenderError.defaultTitle', {
defaultMessage: 'Application error',
});

return (
<EuiPage style={{ minHeight: '100%' }} data-test-subj="appRenderErrorPageContent">
<EuiPageBody>
<EuiPageContent verticalPosition="center" horizontalPosition="center">
<EuiEmptyPrompt
iconType="alert"
iconColor="danger"
title={<h2>{title}</h2>}
body={children}
/>
</EuiPageContent>
</EuiPageBody>
</EuiPage>
);
};

const ErrorApp: React.FC<{ basePath: IBasePath; history: History }> = ({ basePath, history }) => {
const [currentLocation, setCurrentLocation] = useState(history.location);
useLayoutEffect(() => {
return history.listen((location) => setCurrentLocation(location));
}, [history]);

const searchParams = new URLSearchParams(currentLocation.search);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

URLSearchParams is not compatible with IE11: https://caniuse.com/#search=URLSearchParams (unless we have a shim?) Maybe use the 'query-string' module instead?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There is a core-js polyfill, but I will double check it works in IE 👍

const errorType = searchParams.get('errorType');

if (errorType === 'urlOverflow') {
return (
<ErrorPage
title={i18n.translate('core.ui.errorUrlOverflow.errorTitle', {
defaultMessage: 'Woah there!',
})}
>
<UrlOverflowUi basePath={basePath} />
</ErrorPage>
);
}

return <ErrorPage />;
};

interface Deps {
basePath: IBasePath;
}

/**
* Renders UI for displaying error messages.
* @internal
*/
export const renderApp = ({ element, history }: AppMountParameters, { basePath }: Deps) => {
ReactDOM.render(
<I18nProvider>
<ErrorApp history={history} basePath={basePath} />
</I18nProvider>,
element
);

return () => {
ReactDOM.unmountComponentAtNode(element);
};
};
21 changes: 21 additions & 0 deletions src/core/public/core_app/errors/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/

export { renderApp } from './error_application';
export { setupUrlOverflowDetection, URL_MAX_LENGTH } from './url_overflow';
Loading