[7.x] [new-platform] Simplify the frontend integration with the legacy platform (#37734) (#38172)

This commit is contained in:
Josh Dover 2019-06-06 14:49:08 -05:00 committed by GitHub
parent fc978c9f2c
commit 8c24bfc6a5
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
76 changed files with 446 additions and 946 deletions

View file

@ -1,84 +1,18 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`#setup() load order useLegacyTestHarness = false loads ui/modules before ui/chrome, and both before legacy files 1`] = `
Array [
"ui/metadata",
"ui/i18n",
"ui/notify/fatal_error",
"ui/notify/toasts",
"ui/chrome/api/loading_count",
"ui/chrome/api/base_path",
"ui/chrome/api/ui_settings",
"ui/chrome/api/injected_vars",
"ui/chrome/api/controls",
"ui/chrome/api/help_extension",
"ui/chrome/api/theme",
"ui/chrome/api/breadcrumbs",
"ui/chrome/services/global_nav_state",
"ui/chrome",
"legacy files",
]
`;
exports[`#setup() load order useLegacyTestHarness = true loads ui/modules before ui/test_harness, and both before legacy files 1`] = `
Array [
"ui/metadata",
"ui/i18n",
"ui/notify/fatal_error",
"ui/notify/toasts",
"ui/chrome/api/loading_count",
"ui/chrome/api/base_path",
"ui/chrome/api/ui_settings",
"ui/chrome/api/injected_vars",
"ui/chrome/api/controls",
"ui/chrome/api/help_extension",
"ui/chrome/api/theme",
"ui/chrome/api/breadcrumbs",
"ui/chrome/services/global_nav_state",
"ui/test_harness",
"legacy files",
]
`;
exports[`#start() load order useLegacyTestHarness = false loads ui/modules before ui/chrome, and both before legacy files 1`] = `
Array [
"ui/metadata",
"ui/i18n",
"ui/notify/fatal_error",
"ui/notify/toasts",
"ui/chrome/api/loading_count",
"ui/chrome/api/base_path",
"ui/chrome/api/ui_settings",
"ui/chrome/api/injected_vars",
"ui/chrome/api/controls",
"ui/chrome/api/help_extension",
"ui/chrome/api/theme",
"ui/chrome/api/breadcrumbs",
"ui/chrome/services/global_nav_state",
"ui/new_platform",
"ui/chrome",
"legacy files",
"ui/capabilities",
]
`;
exports[`#start() load order useLegacyTestHarness = true loads ui/modules before ui/test_harness, and both before legacy files 1`] = `
Array [
"ui/metadata",
"ui/i18n",
"ui/notify/fatal_error",
"ui/notify/toasts",
"ui/chrome/api/loading_count",
"ui/chrome/api/base_path",
"ui/chrome/api/ui_settings",
"ui/chrome/api/injected_vars",
"ui/chrome/api/controls",
"ui/chrome/api/help_extension",
"ui/chrome/api/theme",
"ui/chrome/api/breadcrumbs",
"ui/chrome/services/global_nav_state",
"ui/new_platform",
"ui/test_harness",
"legacy files",
"ui/capabilities",
]
`;

View file

@ -21,11 +21,13 @@ import angular from 'angular';
const mockLoadOrder: string[] = [];
const mockUiMetadataInit = jest.fn();
jest.mock('ui/metadata', () => {
mockLoadOrder.push('ui/metadata');
const mockUiNewPlatformSetup = jest.fn();
const mockUiNewPlatformStart = jest.fn();
jest.mock('ui/new_platform', () => {
mockLoadOrder.push('ui/new_platform');
return {
__newPlatformSetup__: mockUiMetadataInit,
__setup__: mockUiNewPlatformSetup,
__start__: mockUiNewPlatformStart,
};
});
@ -45,110 +47,6 @@ jest.mock('ui/test_harness', () => {
};
});
const mockI18nContextInit = jest.fn();
jest.mock('ui/i18n', () => {
mockLoadOrder.push('ui/i18n');
return {
__newPlatformSetup__: mockI18nContextInit,
};
});
const mockUICapabilitiesInit = jest.fn();
jest.mock('ui/capabilities', () => {
mockLoadOrder.push('ui/capabilities');
return {
__newPlatformStart__: mockUICapabilitiesInit,
};
});
const mockFatalErrorInit = jest.fn();
jest.mock('ui/notify/fatal_error', () => {
mockLoadOrder.push('ui/notify/fatal_error');
return {
__newPlatformSetup__: mockFatalErrorInit,
};
});
const mockNotifyToastsInit = jest.fn();
jest.mock('ui/notify/toasts', () => {
mockLoadOrder.push('ui/notify/toasts');
return {
__newPlatformSetup__: mockNotifyToastsInit,
};
});
const mockHttpInit = jest.fn();
jest.mock('ui/chrome/api/loading_count', () => {
mockLoadOrder.push('ui/chrome/api/loading_count');
return {
__newPlatformSetup__: mockHttpInit,
};
});
const mockBasePathInit = jest.fn();
jest.mock('ui/chrome/api/base_path', () => {
mockLoadOrder.push('ui/chrome/api/base_path');
return {
__newPlatformSetup__: mockBasePathInit,
};
});
const mockUiSettingsInit = jest.fn();
jest.mock('ui/chrome/api/ui_settings', () => {
mockLoadOrder.push('ui/chrome/api/ui_settings');
return {
__newPlatformSetup__: mockUiSettingsInit,
};
});
const mockInjectedVarsInit = jest.fn();
jest.mock('ui/chrome/api/injected_vars', () => {
mockLoadOrder.push('ui/chrome/api/injected_vars');
return {
__newPlatformSetup__: mockInjectedVarsInit,
};
});
const mockChromeControlsInit = jest.fn();
jest.mock('ui/chrome/api/controls', () => {
mockLoadOrder.push('ui/chrome/api/controls');
return {
__newPlatformSetup__: mockChromeControlsInit,
};
});
const mockChromeHelpExtensionInit = jest.fn();
jest.mock('ui/chrome/api/help_extension', () => {
mockLoadOrder.push('ui/chrome/api/help_extension');
return {
__newPlatformSetup__: mockChromeHelpExtensionInit,
};
});
const mockChromeThemeInit = jest.fn();
jest.mock('ui/chrome/api/theme', () => {
mockLoadOrder.push('ui/chrome/api/theme');
return {
__newPlatformSetup__: mockChromeThemeInit,
};
});
const mockChromeBreadcrumbsInit = jest.fn();
jest.mock('ui/chrome/api/breadcrumbs', () => {
mockLoadOrder.push('ui/chrome/api/breadcrumbs');
return {
__newPlatformSetup__: mockChromeBreadcrumbsInit,
};
});
const mockGlobalNavStateInit = jest.fn();
jest.mock('ui/chrome/services/global_nav_state', () => {
mockLoadOrder.push('ui/chrome/services/global_nav_state');
return {
__newPlatformSetup__: mockGlobalNavStateInit,
};
});
import { chromeServiceMock } from '../chrome/chrome_service.mock';
import { fatalErrorsServiceMock } from '../fatal_errors/fatal_errors_service.mock';
import { httpServiceMock } from '../http/http_service.mock';
@ -219,187 +117,21 @@ afterEach(() => {
describe('#setup()', () => {
describe('default', () => {
it('passes legacy metadata from injectedVars to ui/metadata', () => {
const legacyMetadata = { nav: [], isLegacyMetadata: true };
injectedMetadataSetup.getLegacyMetadata.mockReturnValueOnce(legacyMetadata as any);
it('initializes ui/new_platform with core APIs', () => {
const legacyPlatform = new LegacyPlatformService({
...defaultParams,
});
legacyPlatform.setup(defaultSetupDeps);
expect(mockUiMetadataInit).toHaveBeenCalledTimes(1);
expect(mockUiMetadataInit).toHaveBeenCalledWith(legacyMetadata);
});
it('passes i18n.Context to ui/i18n', () => {
const legacyPlatform = new LegacyPlatformService({
...defaultParams,
});
legacyPlatform.setup(defaultSetupDeps);
expect(mockI18nContextInit).toHaveBeenCalledTimes(1);
expect(mockI18nContextInit).toHaveBeenCalledWith(i18nSetup.Context);
});
it('passes fatalErrors service to ui/notify/fatal_errors', () => {
const legacyPlatform = new LegacyPlatformService({
...defaultParams,
});
legacyPlatform.setup(defaultSetupDeps);
expect(mockFatalErrorInit).toHaveBeenCalledTimes(1);
expect(mockFatalErrorInit).toHaveBeenCalledWith(fatalErrorsSetup);
});
it('passes toasts service to ui/notify/toasts', () => {
const legacyPlatform = new LegacyPlatformService({
...defaultParams,
});
legacyPlatform.setup(defaultSetupDeps);
expect(mockNotifyToastsInit).toHaveBeenCalledTimes(1);
expect(mockNotifyToastsInit).toHaveBeenCalledWith(notificationsSetup.toasts);
});
it('passes http service to ui/chrome/api/loading_count', () => {
const legacyPlatform = new LegacyPlatformService({
...defaultParams,
});
legacyPlatform.setup(defaultSetupDeps);
expect(mockHttpInit).toHaveBeenCalledTimes(1);
expect(mockHttpInit).toHaveBeenCalledWith(httpSetup);
});
it('passes basePath service to ui/chrome/api/base_path', () => {
const legacyPlatform = new LegacyPlatformService({
...defaultParams,
});
legacyPlatform.setup(defaultSetupDeps);
expect(mockBasePathInit).toHaveBeenCalledTimes(1);
expect(mockBasePathInit).toHaveBeenCalledWith(httpSetup);
});
it('passes basePath service to ui/chrome/api/ui_settings', () => {
const legacyPlatform = new LegacyPlatformService({
...defaultParams,
});
legacyPlatform.setup(defaultSetupDeps);
expect(mockUiSettingsInit).toHaveBeenCalledTimes(1);
expect(mockUiSettingsInit).toHaveBeenCalledWith(uiSettingsSetup);
});
it('passes injectedMetadata service to ui/chrome/api/injected_vars', () => {
const legacyPlatform = new LegacyPlatformService({
...defaultParams,
});
legacyPlatform.setup(defaultSetupDeps);
expect(mockInjectedVarsInit).toHaveBeenCalledTimes(1);
expect(mockInjectedVarsInit).toHaveBeenCalledWith(injectedMetadataSetup);
});
it('passes chrome service to ui/chrome/api/controls', () => {
const legacyPlatform = new LegacyPlatformService({
...defaultParams,
});
legacyPlatform.setup(defaultSetupDeps);
expect(mockChromeControlsInit).toHaveBeenCalledTimes(1);
expect(mockChromeControlsInit).toHaveBeenCalledWith(chromeSetup);
});
it('passes chrome service to ui/chrome/api/help_extension', () => {
const legacyPlatform = new LegacyPlatformService({
...defaultParams,
});
legacyPlatform.setup(defaultSetupDeps);
expect(mockChromeHelpExtensionInit).toHaveBeenCalledTimes(1);
expect(mockChromeHelpExtensionInit).toHaveBeenCalledWith(chromeSetup);
});
it('passes chrome service to ui/chrome/api/theme', () => {
const legacyPlatform = new LegacyPlatformService({
...defaultParams,
});
legacyPlatform.setup(defaultSetupDeps);
expect(mockChromeThemeInit).toHaveBeenCalledTimes(1);
expect(mockChromeThemeInit).toHaveBeenCalledWith(chromeSetup);
});
it('passes chrome service to ui/chrome/api/breadcrumbs', () => {
const legacyPlatform = new LegacyPlatformService({
...defaultParams,
});
legacyPlatform.setup(defaultSetupDeps);
expect(mockChromeBreadcrumbsInit).toHaveBeenCalledTimes(1);
expect(mockChromeBreadcrumbsInit).toHaveBeenCalledWith(chromeSetup);
});
it('passes chrome service to ui/chrome/api/global_nav_state', () => {
const legacyPlatform = new LegacyPlatformService({
...defaultParams,
});
legacyPlatform.setup(defaultSetupDeps);
expect(mockGlobalNavStateInit).toHaveBeenCalledTimes(1);
expect(mockGlobalNavStateInit).toHaveBeenCalledWith(chromeSetup);
});
});
describe('load order', () => {
describe('useLegacyTestHarness = false', () => {
it('loads ui/modules before ui/chrome, and both before legacy files', () => {
const legacyPlatform = new LegacyPlatformService({
...defaultParams,
});
expect(mockLoadOrder).toEqual([]);
legacyPlatform.setup(defaultSetupDeps);
expect(mockLoadOrder).toMatchSnapshot();
});
});
describe('useLegacyTestHarness = true', () => {
it('loads ui/modules before ui/test_harness, and both before legacy files', () => {
const legacyPlatform = new LegacyPlatformService({
...defaultParams,
useLegacyTestHarness: true,
});
expect(mockLoadOrder).toEqual([]);
legacyPlatform.setup(defaultSetupDeps);
expect(mockLoadOrder).toMatchSnapshot();
});
expect(mockUiNewPlatformSetup).toHaveBeenCalledTimes(1);
expect(mockUiNewPlatformSetup).toHaveBeenCalledWith(defaultSetupDeps.core, {});
});
});
});
describe('#start()', () => {
it('passes uiCapabilities to ui/capabilities', () => {
it('initializes ui/new_platform with core APIs', () => {
const legacyPlatform = new LegacyPlatformService({
...defaultParams,
});
@ -407,8 +139,8 @@ describe('#start()', () => {
legacyPlatform.setup(defaultSetupDeps);
legacyPlatform.start(defaultStartDeps);
expect(mockUICapabilitiesInit).toHaveBeenCalledTimes(1);
expect(mockUICapabilitiesInit).toHaveBeenCalledWith(applicationStart.capabilities);
expect(mockUiNewPlatformStart).toHaveBeenCalledTimes(1);
expect(mockUiNewPlatformStart).toHaveBeenCalledWith(defaultStartDeps.core, {});
});
describe('useLegacyTestHarness = false', () => {

View file

@ -55,37 +55,12 @@ export class LegacyPlatformService {
constructor(private readonly params: LegacyPlatformParams) {}
public setup({ core, plugins }: SetupDeps) {
const {
application,
i18n,
injectedMetadata,
fatalErrors,
notifications,
http,
uiSettings,
chrome,
} = core;
// Inject parts of the new platform into parts of the legacy platform
// so that legacy APIs/modules can mimic their new platform counterparts
require('ui/new_platform').__newPlatformSetup__(core, plugins);
require('ui/metadata').__newPlatformSetup__(injectedMetadata.getLegacyMetadata());
require('ui/i18n').__newPlatformSetup__(i18n.Context);
require('ui/notify/fatal_error').__newPlatformSetup__(fatalErrors);
require('ui/kfetch').__newPlatformSetup__(http);
require('ui/notify/toasts').__newPlatformSetup__(notifications.toasts);
require('ui/chrome/api/loading_count').__newPlatformSetup__(http);
require('ui/chrome/api/base_path').__newPlatformSetup__(http);
require('ui/chrome/api/ui_settings').__newPlatformSetup__(uiSettings);
require('ui/chrome/api/injected_vars').__newPlatformSetup__(injectedMetadata);
require('ui/chrome/api/controls').__newPlatformSetup__(chrome);
require('ui/chrome/api/help_extension').__newPlatformSetup__(chrome);
require('ui/chrome/api/theme').__newPlatformSetup__(chrome);
require('ui/chrome/api/badge').__newPlatformSetup__(chrome);
require('ui/chrome/api/breadcrumbs').__newPlatformSetup__(chrome);
require('ui/chrome/services/global_nav_state').__newPlatformSetup__(chrome);
require('ui/new_platform').__setup__(core, plugins);
injectedMetadata.getLegacyMetadata().nav.forEach((navLink: any) =>
application.registerLegacyApp({
core.injectedMetadata.getLegacyMetadata().nav.forEach((navLink: any) =>
core.application.registerLegacyApp({
id: navLink.id,
order: navLink.order,
title: navLink.title,
@ -96,6 +71,12 @@ export class LegacyPlatformService {
linkToLastSubUrl: navLink.linkToLastSubUrl,
})
);
}
public start({ core, targetDomElement, plugins }: StartDeps) {
// Inject parts of the new platform into parts of the legacy platform
// so that legacy APIs/modules can mimic their new platform counterparts
require('ui/new_platform').__start__(core, plugins);
// Load the bootstrap module before loading the legacy platform files so that
// the bootstrap module can modify the environment a bit first
@ -103,18 +84,13 @@ export class LegacyPlatformService {
// require the files that will tie into the legacy platform
this.params.requireLegacyFiles();
}
public start({ core, targetDomElement, plugins }: StartDeps) {
if (!this.bootstrapModule) {
throw new Error('Bootstrap module must be loaded before `start`');
}
this.targetDomElement = targetDomElement;
require('ui/new_platform').__newPlatformStart__(core, plugins);
require('ui/capabilities').__newPlatformStart__(core.application.capabilities);
this.bootstrapModule.bootstrap(this.targetDomElement);
}

View file

@ -16,11 +16,13 @@
* specific language governing permissions and limitations
* under the License.
*/
import { Observable } from 'rxjs';
import { ToastsSetup } from './toasts_service';
const createToastsApiMock = () => {
const api: jest.Mocked<PublicMethodsOf<ToastsSetup>> = {
get$: jest.fn(),
get$: jest.fn(() => new Observable()),
add: jest.fn(),
remove: jest.fn(),
addSuccess: jest.fn(),

View file

@ -0,0 +1,32 @@
/*
* 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 {
fatalErrorsServiceMock,
notificationServiceMock,
} from '../../../../../../../core/public/mocks';
jest.doMock('ui/new_platform', () => ({
npSetup: {
core: {
fatalErrors: fatalErrorsServiceMock.createSetupContract(),
notifications: notificationServiceMock.createSetupContract(),
},
},
}));

View file

@ -21,6 +21,7 @@ import { mockPersistedLogFactory } from './query_bar_input.test.mocks';
import React from 'react';
import { shallowWithIntl } from 'test_utils/enzyme_helpers';
import './query_bar.test.mocks';
import { QueryBar } from './query_bar';
const noop = () => {

View file

@ -87,7 +87,6 @@ jest.mock('ui/autocomplete_providers', () => ({
getAutocompleteProvider: mockGetAutocompleteProvider,
}));
jest.mock('ui/kfetch', () => ({
__newPlatformSetup__: jest.fn(),
kfetch: mockKfetch,
}));

View file

@ -26,7 +26,7 @@ import { i18n } from '@kbn/i18n';
import './app';
import contextAppRouteTemplate from './index.html';
import { getRootBreadcrumbs } from '../discover/breadcrumbs';
import { getNewPlatform } from 'ui/new_platform';
import { npStart } from 'ui/new_platform';
uiRoutes
.when('/context/:indexPatternId/:type/:id*', {
@ -90,7 +90,7 @@ function ContextAppRouteController(
this.anchorType = $routeParams.type;
this.anchorId = $routeParams.id;
this.indexPattern = indexPattern;
this.discoverUrl = getNewPlatform().start.core.chrome.navLinks.get('kibana:discover').url;
this.discoverUrl = npStart.core.chrome.navLinks.get('kibana:discover').url;
this.filters = _.cloneDeep(queryFilter.getFilters());
}

View file

@ -21,7 +21,7 @@ import expect from '@kbn/expect';
import sinon from 'sinon';
import { hideEmptyDevTools } from '../hide_empty_tools';
import { getNewPlatform } from 'ui/new_platform';
import { npStart } from 'ui/new_platform';
describe('hide dev tools', function () {
let updateNavLink;
@ -39,7 +39,7 @@ describe('hide dev tools', function () {
}
beforeEach(function () {
const coreNavLinks = getNewPlatform().start.core.chrome.navLinks;
const coreNavLinks = npStart.core.chrome.navLinks;
updateNavLink = sinon.spy(coreNavLinks, 'update');
});

View file

@ -19,12 +19,12 @@
import { uiModules } from 'ui/modules';
import { DevToolsRegistryProvider } from 'ui/registry/dev_tools';
import { getNewPlatform } from 'ui/new_platform';
import { npStart } from 'ui/new_platform';
export function hideEmptyDevTools(Private) {
const hasTools = !!Private(DevToolsRegistryProvider).length;
if (!hasTools) {
getNewPlatform().start.core.chrome.navLinks.update('kibana:dev_tools', {
npStart.core.chrome.navLinks.update('kibana:dev_tools', {
hidden: true
});
}

View file

@ -22,7 +22,7 @@ import React, { Fragment } from 'react';
import { uiModules } from 'ui/modules';
import { wrapInI18nContext } from 'ui/i18n';
import { FormattedMessage } from '@kbn/i18n/react';
import { getNewPlatform } from 'ui/new_platform';
import { npStart } from 'ui/new_platform';
import {
EuiFlexGroup,
@ -40,7 +40,7 @@ const DiscoverFetchError = ({ fetchError }) => {
let body;
if (fetchError.lang === 'painless') {
const managementUrl = getNewPlatform().start.core.chrome.navLinks.get('kibana:management').url;
const managementUrl = npStart.core.chrome.navLinks.get('kibana:management').url;
const url = `${managementUrl}/kibana/index_patterns`;
body = (

View file

@ -32,6 +32,15 @@ jest.mock(
{ virtual: true }
);
jest.mock(
'ui/capabilities',
() => ({
catalogue: {},
management: {},
navLinks: {}
})
);
describe('home', () => {
let defaultProps;

View file

@ -28,7 +28,7 @@ import { render, unmountComponentAtNode } from 'react-dom';
import { ObjectsTable } from './components/objects_table';
import { I18nContext } from 'ui/i18n';
import { get } from 'lodash';
import { getNewPlatform } from 'ui/new_platform';
import { npStart } from 'ui/new_platform';
import { getIndexBreadcrumbs } from './breadcrumbs';
@ -44,7 +44,7 @@ function updateObjectsTable($scope, $injector) {
const savedObjectsClient = Private(SavedObjectsClientProvider);
const services = savedObjectManagementRegistry.all().map(obj => $injector.get(obj.service));
const uiCapabilites = getNewPlatform().start.core.application.capabilities;
const uiCapabilites = npStart.core.application.capabilities;
$scope.$$postDigest(() => {
const node = document.getElementById(REACT_OBJECTS_TABLE_DOM_ELEMENT_ID);

View file

@ -52,7 +52,7 @@ import { getUnhashableStatesProvider } from 'ui/state_management/state_hashing';
import { showSaveModal } from 'ui/saved_objects/show_saved_object_save_modal';
import { SavedObjectSaveModal } from 'ui/saved_objects/components/saved_object_save_modal';
import { getEditBreadcrumbs, getCreateBreadcrumbs } from '../breadcrumbs';
import { getNewPlatform } from 'ui/new_platform';
import { npStart } from 'ui/new_platform';
uiRoutes
@ -505,7 +505,7 @@ function VisEditor(
// url, not the unsaved one.
chrome.trackSubUrlForApp('kibana:visualize', savedVisualizationParsedUrl);
const lastDashboardAbsoluteUrl = getNewPlatform().start.core.chrome.navLinks.get('kibana:dashboard').url;
const lastDashboardAbsoluteUrl = npStart.core.chrome.navLinks.get('kibana:dashboard').url;
const dashboardParsedUrl = absoluteToParsedUrl(lastDashboardAbsoluteUrl, chrome.getBasePath());
dashboardParsedUrl.addQueryParameter(DashboardConstants.NEW_VISUALIZATION_ID_PARAM, savedVis.id);
kbnUrl.change(dashboardParsedUrl.appPath);

View file

@ -17,16 +17,9 @@
* under the License.
*/
import './load_status.test.mocks';
import loadStatus from './load_status';
// Make importing the ui/notify module work in jest
jest.mock('ui/metadata', () => ({
metadata: {
branch: 'my-metadata-branch',
version: 'my-metadata-version'
}
}));
// A faked response to the `fetch` call
const mockFetch = async () => ({
status: 200,

View file

@ -0,0 +1,37 @@
/*
* 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 { fatalErrorsServiceMock, notificationServiceMock } from '../../../../../core/public/mocks';
jest.doMock('ui/new_platform', () => ({
npSetup: {
core: {
fatalErrors: fatalErrorsServiceMock.createSetupContract(),
notifications: notificationServiceMock.createSetupContract(),
}
},
}));
// Make importing the ui/notify module work in jest
jest.doMock('ui/metadata', () => ({
metadata: {
branch: 'my-metadata-branch',
version: 'my-metadata-version'
}
}));

View file

@ -20,12 +20,10 @@
import 'ui/autoload/styles';
import 'ui/i18n';
import chrome from 'ui/chrome';
import { onStart } from 'ui/new_platform';
import { npStart } from 'ui/new_platform';
import { destroyStatusPage, renderStatusPage } from './components/render';
onStart(({ core }) => {
core.chrome.navLinks.enableForcedAppSwitcherNavigation();
});
npStart.core.chrome.navLinks.enableForcedAppSwitcherNavigation();
chrome
.setRootTemplate(require('plugins/status_page/status_page.html'))

View file

@ -34,7 +34,8 @@ const findSourceFiles = async (patterns, cwd = fromRoot('.')) => {
'node_modules/**/*',
'bower_components/**/*',
'**/_*.js',
'**/*.test.js'
'**/*.test.js',
'**/*.test.mocks.js',
],
symlinks: findSourceFiles.symlinks,
statCache: findSourceFiles.statCache,

View file

@ -17,11 +17,9 @@
* under the License.
*/
import { onStart } from 'ui/new_platform';
import { npStart } from 'ui/new_platform';
onStart(({ core }) => {
const timelionUiEnabled = core.injectedMetadata.getInjectedVar('timelionUiEnabled');
if (timelionUiEnabled === false) {
core.chrome.navLinks.update('timelion', { hidden: true });
}
});
const timelionUiEnabled = npStart.core.injectedMetadata.getInjectedVar('timelionUiEnabled');
if (timelionUiEnabled === false) {
npStart.core.chrome.navLinks.update('timelion', { hidden: true });
}

View file

@ -17,27 +17,13 @@
* under the License.
*/
import { npStart } from 'ui/new_platform';
import { Capabilities as UICapabilities } from '../../../../core/public';
export { UICapabilities };
let uiCapabilities: UICapabilities;
export function __newPlatformStart__(capabilities: UICapabilities) {
if (uiCapabilities) {
throw new Error('ui/capabilities already initialized with new platform apis');
}
uiCapabilities = capabilities;
}
export const capabilities = {
get() {
if (!uiCapabilities) {
throw new Error(
`UI Capabilities are only available in the legacy platform once Angular has booted.`
);
}
return uiCapabilities;
return npStart.core.application.capabilities;
},
};

View file

@ -22,7 +22,7 @@ import sinon from 'sinon';
import { initChromeNavApi } from '../nav';
import { StubBrowserStorage } from 'test_utils/stub_browser_storage';
import { getNewPlatform } from 'ui/new_platform';
import { npStart } from 'ui/new_platform';
import { absoluteToParsedUrl } from '../../../url/absolute_to_parsed_url';
const basePath = '/someBasePath';
@ -52,7 +52,7 @@ describe('chrome nav apis', function () {
}());
beforeEach(() => {
coreNavLinks = getNewPlatform().start.core.chrome.navLinks;
coreNavLinks = npStart.core.chrome.navLinks;
sinon.stub(coreNavLinks, 'update').callsFake((linkId, updateAttrs) => {
const link = fakedLinks.find(({ id }) => id === linkId);
for (const key of Object.keys(updateAttrs)) {

View file

@ -0,0 +1,27 @@
/*
* 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 { chromeServiceMock } from '../../../../../core/public/mocks';
export const newPlatformChrome = chromeServiceMock.createSetupContract();
jest.doMock('ui/new_platform', () => ({
npSetup: {
core: { chrome: newPlatformChrome },
},
}));

View file

@ -20,12 +20,8 @@
import * as Rx from 'rxjs';
import { ChromeBadge } from 'src/core/public/chrome';
import { chromeServiceMock } from '../../../../../core/public/mocks';
import { __newPlatformSetup__, initChromeBadgeApi } from './badge';
const newPlatformChrome = chromeServiceMock.createSetupContract();
__newPlatformSetup__(newPlatformChrome);
import { newPlatformChrome } from './badge.test.mocks';
import { initChromeBadgeApi } from './badge';
function setup() {
const getBadge$ = new Rx.BehaviorSubject<ChromeBadge | undefined>(undefined);

View file

@ -18,19 +18,13 @@
*/
import { Chrome } from 'ui/chrome';
import { ChromeBadge, ChromeSetup } from '../../../../../core/public';
import { npSetup } from 'ui/new_platform';
import { ChromeBadge } from '../../../../../core/public';
export type Badge = ChromeBadge;
export type BadgeApi = ReturnType<typeof createBadgeApi>['badge'];
let newPlatformChrome: ChromeSetup;
export function __newPlatformSetup__(instance: ChromeSetup) {
if (newPlatformChrome) {
throw new Error('ui/chrome/api/badge is already initialized');
}
newPlatformChrome = instance;
}
const newPlatformChrome = npSetup.core.chrome;
function createBadgeApi() {
return {

View file

@ -0,0 +1,27 @@
/*
* 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 { httpServiceMock } from '../../../../../core/public/mocks';
export const newPlatformHttp = httpServiceMock.createSetupContract();
jest.doMock('ui/new_platform', () => ({
npSetup: {
core: { http: newPlatformHttp },
},
}));

View file

@ -17,8 +17,8 @@
* under the License.
*/
import { httpServiceMock } from '../../../../../core/public/mocks';
import { __newPlatformSetup__, initChromeBasePathApi } from './base_path';
import { newPlatformHttp } from './base_path.test.mocks';
import { initChromeBasePathApi } from './base_path';
function initChrome() {
const chrome: any = {};
@ -26,9 +26,6 @@ function initChrome() {
return chrome;
}
const newPlatformHttp = httpServiceMock.createSetupContract();
__newPlatformSetup__(newPlatformHttp);
newPlatformHttp.getBasePath.mockImplementation(() => 'gotBasePath');
newPlatformHttp.prependBasePath.mockImplementation(() => 'addedToPath');
newPlatformHttp.removeBasePath.mockImplementation(() => 'removedFromPath');

View file

@ -17,17 +17,9 @@
* under the License.
*/
import { HttpSetup } from '../../../../../core/public';
import { npSetup } from 'ui/new_platform';
let newPlatformHttp: HttpSetup;
export function __newPlatformSetup__(instance: HttpSetup) {
if (newPlatformHttp) {
throw new Error('ui/chrome/api/http is already initialized');
}
newPlatformHttp = instance;
}
const newPlatformHttp = npSetup.core.http;
export function initChromeBasePathApi(chrome: { [key: string]: any }) {
chrome.getBasePath = newPlatformHttp.getBasePath.bind(newPlatformHttp);

View file

@ -17,19 +17,13 @@
* under the License.
*/
import { ChromeBreadcrumb, ChromeSetup } from '../../../../../core/public';
import { npSetup } from 'ui/new_platform';
import { ChromeBreadcrumb } from '../../../../../core/public';
export type Breadcrumb = ChromeBreadcrumb;
export type BreadcrumbsApi = ReturnType<typeof createBreadcrumbsApi>['breadcrumbs'];
let newPlatformChrome: ChromeSetup;
export function __newPlatformSetup__(instance: ChromeSetup) {
if (newPlatformChrome) {
throw new Error('ui/chrome/api/breadcrumbs is already initialized');
}
newPlatformChrome = instance;
}
const newPlatformChrome = npSetup.core.chrome;
function createBreadcrumbsApi(chrome: { [key: string]: any }) {
let currentBreadcrumbs: Breadcrumb[] = [];

View file

@ -0,0 +1,27 @@
/*
* 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 { chromeServiceMock } from '../../../../../core/public/mocks';
export const newPlatformChrome = chromeServiceMock.createSetupContract();
jest.doMock('ui/new_platform', () => ({
npSetup: {
core: { chrome: newPlatformChrome },
},
}));

View file

@ -19,12 +19,8 @@
import * as Rx from 'rxjs';
import { chromeServiceMock } from '../../../../../core/public/mocks';
import { __newPlatformSetup__, initChromeControlsApi } from './controls';
const newPlatformChrome = chromeServiceMock.createSetupContract();
__newPlatformSetup__(newPlatformChrome);
import { newPlatformChrome } from './controls.test.mocks';
import { initChromeControlsApi } from './controls';
function setup() {
const isVisible$ = new Rx.BehaviorSubject(true);

View file

@ -18,17 +18,9 @@
*/
import * as Rx from 'rxjs';
import { ChromeSetup } from '../../../../../core/public';
import { npSetup } from 'ui/new_platform';
let newPlatformChrome: ChromeSetup;
export function __newPlatformSetup__(instance: ChromeSetup) {
if (newPlatformChrome) {
throw new Error('ui/chrome/api/controls is already initialized');
}
newPlatformChrome = instance;
}
const newPlatformChrome = npSetup.core.chrome;
export function initChromeControlsApi(chrome: { [key: string]: any }) {
// cache of chrome visibility state

View file

@ -17,16 +17,10 @@
* under the License.
*/
import { ChromeHelpExtension, ChromeSetup } from '../../../../../core/public';
import { npSetup } from 'ui/new_platform';
import { ChromeHelpExtension } from '../../../../../core/public';
let newPlatformChrome: ChromeSetup;
export function __newPlatformSetup__(instance: ChromeSetup) {
if (newPlatformChrome) {
throw new Error('ui/chrome/api/help_extension is already initialized');
}
newPlatformChrome = instance;
}
const newPlatformChrome = npSetup.core.chrome;
export type HelpExtensionApi = ReturnType<typeof createHelpExtensionApi>['helpExtension'];
export type HelpExtension = ChromeHelpExtension;

View file

@ -0,0 +1,28 @@
/*
* 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 const newPlatformInjectedMetadata: any = {
getInjectedVars: jest.fn(),
getInjectedVar: jest.fn(),
};
jest.doMock('ui/new_platform', () => ({
npSetup: {
core: { injectedMetadata: newPlatformInjectedMetadata },
},
}));

View file

@ -17,7 +17,8 @@
* under the License.
*/
import { __newPlatformSetup__, initChromeInjectedVarsApi } from './injected_vars';
import { newPlatformInjectedMetadata } from './injected_vars.test.mocks';
import { initChromeInjectedVarsApi } from './injected_vars';
function initChrome() {
const chrome: any = {};
@ -25,12 +26,6 @@ function initChrome() {
return chrome;
}
const newPlatformInjectedMetadata: any = {
getInjectedVars: jest.fn(),
getInjectedVar: jest.fn(),
};
__newPlatformSetup__(newPlatformInjectedMetadata);
beforeEach(() => {
jest.resetAllMocks();
});

View file

@ -18,17 +18,9 @@
*/
import { cloneDeep } from 'lodash';
import { InternalCoreSetup } from '../../../../../core/public';
import { npSetup } from 'ui/new_platform';
let newPlatformInjectedVars: InternalCoreSetup['injectedMetadata'];
export function __newPlatformSetup__(instance: InternalCoreSetup['injectedMetadata']) {
if (newPlatformInjectedVars) {
throw new Error('ui/chrome/api/injected_vars is already initialized');
}
newPlatformInjectedVars = instance;
}
const newPlatformInjectedVars = npSetup.core.injectedMetadata;
export function initChromeInjectedVarsApi(chrome: { [key: string]: any }) {
chrome.getInjected = (name?: string, defaultValue?: any) =>

View file

@ -18,15 +18,9 @@
*/
import * as Rx from 'rxjs';
import { npSetup } from 'ui/new_platform';
let newPlatformHttp;
export function __newPlatformSetup__(instance) {
if (newPlatformHttp) {
throw new Error('ui/chrome/api/loading_count already initialized with new platform apis');
}
newPlatformHttp = instance;
}
const newPlatformHttp = npSetup.core.http;
export function initLoadingCountApi(chrome) {
const manualCount$ = new Rx.BehaviorSubject(0);

View file

@ -19,8 +19,8 @@
import { KibanaParsedUrl } from 'ui/url/kibana_parsed_url';
import { absoluteToParsedUrl } from '../../url/absolute_to_parsed_url';
import { onStart } from '../../new_platform';
import { ChromeStart, ChromeNavLink } from '../../../../../core/public';
import { npStart } from '../../new_platform';
import { ChromeNavLink } from '../../../../../core/public';
import { relativeToAbsolute } from '../../url/relative_to_absolute';
export interface ChromeNavLinks {
@ -34,8 +34,7 @@ interface NavInternals {
}
export function initChromeNavApi(chrome: any, internals: NavInternals) {
let coreNavLinks: ChromeStart['navLinks'];
onStart(({ core }) => (coreNavLinks = core.chrome.navLinks));
const coreNavLinks = npStart.core.chrome.navLinks;
/**
* Clear last url for deleted saved objects to avoid loading pages with "Could not locate..."
@ -145,15 +144,14 @@ export function initChromeNavApi(chrome: any, internals: NavInternals) {
// simulate a possible change in url to initialize the
// link.active and link.lastUrl properties
onStart(({ core }) => {
core.chrome.navLinks
.getAll()
.filter(link => link.subUrlBase)
.forEach(link => {
core.chrome.navLinks.update(link.id, {
subUrlBase: relativeToAbsolute(chrome.addBasePath(link.subUrlBase)),
});
coreNavLinks
.getAll()
.filter(link => link.subUrlBase)
.forEach(link => {
coreNavLinks.update(link.id, {
subUrlBase: relativeToAbsolute(chrome.addBasePath(link.subUrlBase)),
});
internals.trackPossibleSubUrl(document.location.href);
});
});
internals.trackPossibleSubUrl(document.location.href);
}

View file

@ -21,7 +21,6 @@ import {
getUnhashableStatesProvider,
unhashUrl,
} from '../../state_management/state_hashing';
import { onStart } from '../../new_platform';
export function registerSubUrlHooks(angularModule, internals) {
angularModule.run(($rootScope, Private) => {
@ -42,7 +41,7 @@ export function registerSubUrlHooks(angularModule, internals) {
$rootScope.$on('$routeChangeSuccess', onRouteChange);
$rootScope.$on('$routeUpdate', onRouteChange);
onStart(updateSubUrls); // initialize sub urls
updateSubUrls();
});
}

View file

@ -0,0 +1,27 @@
/*
* 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 { chromeServiceMock } from '../../../../../core/public/mocks';
export const newPlatformChrome = chromeServiceMock.createSetupContract();
jest.doMock('ui/new_platform', () => ({
npSetup: {
core: { chrome: newPlatformChrome },
},
}));

View file

@ -19,12 +19,8 @@
import * as Rx from 'rxjs';
import { chromeServiceMock } from '../../../../../core/public/mocks';
import { __newPlatformSetup__, initChromeThemeApi } from './theme';
const newPlatformChrome = chromeServiceMock.createSetupContract();
__newPlatformSetup__(newPlatformChrome);
import { newPlatformChrome } from './theme.test.mocks';
import { initChromeThemeApi } from './theme';
function setup() {
const brand$ = new Rx.BehaviorSubject({ logo: 'foo', smallLogo: 'foo' });

View file

@ -19,17 +19,10 @@
import * as Rx from 'rxjs';
import { ChromeBrand, ChromeSetup } from '../../../../../core/public';
import { npSetup } from 'ui/new_platform';
import { ChromeBrand } from '../../../../../core/public';
let newPlatformChrome: ChromeSetup;
export function __newPlatformSetup__(instance: ChromeSetup) {
if (newPlatformChrome) {
throw new Error('ui/chrome/api/theme is already initialized');
}
newPlatformChrome = instance;
}
const newPlatformChrome = npSetup.core.chrome;
export function initChromeThemeApi(chrome: { [key: string]: any }) {
const brandCache$ = new Rx.BehaviorSubject<ChromeBrand>({});

View file

@ -17,15 +17,9 @@
* under the License.
*/
let newPlatformUiSettingsClient;
import { npSetup } from 'ui/new_platform';
export function __newPlatformSetup__(instance) {
if (newPlatformUiSettingsClient) {
throw new Error('ui/chrome/api/ui_settings already initialized');
}
newPlatformUiSettingsClient = instance;
}
const newPlatformUiSettingsClient = npSetup.core.uiSettings;
export function initUiSettingsApi(chrome) {
chrome.getUiSettingsClient = function () {

View file

@ -22,7 +22,7 @@ import { uiModules } from '../../../modules';
import { Header } from './components/header';
import { wrapInI18nContext } from 'ui/i18n';
import { chromeHeaderNavControlsRegistry } from 'ui/registry/chrome_header_nav_controls';
import { getNewPlatform } from '../../../new_platform';
import { npStart } from '../../../new_platform';
const module = uiModules.get('kibana');
@ -30,8 +30,6 @@ module.directive('headerGlobalNav', (reactDirective, chrome, Private, uiCapabili
const { recentlyAccessed } = require('ui/persisted_log');
const navControls = Private(chromeHeaderNavControlsRegistry);
const homeHref = chrome.addBasePath('/app/kibana#/home');
const newPlatform = getNewPlatform();
const newPlatformStart = newPlatform.start.core;
return reactDirective(wrapInI18nContext(Header), [
// scope accepted by directive, passed in as React props
@ -44,9 +42,9 @@ module.directive('headerGlobalNav', (reactDirective, chrome, Private, uiCapabili
badge$: chrome.badge.get$(),
breadcrumbs$: chrome.breadcrumbs.get$(),
helpExtension$: chrome.helpExtension.get$(),
navLinks$: newPlatformStart.chrome.navLinks.getNavLinks$(),
navLinks$: npStart.core.chrome.navLinks.getNavLinks$(),
recentlyAccessed$: recentlyAccessed.get$(),
forceAppSwitcherNavigation$: newPlatformStart.chrome.navLinks.getForceAppSwitcherNavigation$(),
forceAppSwitcherNavigation$: npStart.core.chrome.navLinks.getForceAppSwitcherNavigation$(),
navControls,
homeHref,
uiCapabilities,

View file

@ -18,16 +18,10 @@
*/
import { distinctUntilChanged } from 'rxjs/operators';
import { npSetup } from 'ui/new_platform';
import { uiModules } from '../../modules';
let newPlatformChrome;
export function __newPlatformSetup__(instance) {
if (newPlatformChrome) {
throw new Error('ui/chrome/global_nav_state is already initialized');
}
newPlatformChrome = instance;
}
const newPlatformChrome = npSetup.core.chrome;
uiModules.get('kibana')
.service('globalNavState', ($rootScope) => {

View file

@ -18,17 +18,13 @@
*/
// @ts-ignore
import './error_auto_create_index.test.mocks';
import fetchMock from 'fetch-mock/es5/client';
import { __newPlatformSetup__, kfetch } from '../kfetch';
import { setup } from '../../../../test_utils/public/http_test_setup';
import { kfetch } from '../kfetch';
import { isAutoCreateIndexError } from './error_auto_create_index';
describe('isAutoCreateIndexError correctly handles KFetchError thrown by kfetch', () => {
beforeAll(() => {
__newPlatformSetup__(setup().http);
});
describe('404', () => {
beforeEach(() => {
fetchMock.post({

View file

@ -17,11 +17,7 @@
* under the License.
*/
declare class Metadata {
public branch: string;
public version: string;
}
declare const metadata: Metadata;
import { setup } from '../../../../test_utils/public/http_test_setup';
export { metadata };
jest.doMock('ui/new_platform', () => ({ npSetup: { core: setup() } }));

View file

@ -28,11 +28,11 @@ import { mapAndFlattenFilters } from './lib/map_and_flatten_filters';
import { extractTimeFilter } from './lib/extract_time_filter';
import { changeTimeFilter } from './lib/change_time_filter';
import { getNewPlatform } from 'ui/new_platform';
import { npSetup } from 'ui/new_platform';
export function FilterBarQueryFilterProvider(Promise, indexPatterns, $rootScope, getAppState, globalState) {
const queryFilter = {};
const { uiSettings } = getNewPlatform().setup.core;
const { uiSettings } = npSetup.core;
const update$ = new Subject();
const fetch$ = new Subject();

View file

@ -21,12 +21,18 @@ import { render } from 'enzyme';
import PropTypes from 'prop-types';
import React from 'react';
import { __newPlatformSetup__, wrapInI18nContext } from '.';
jest.mock('ui/new_platform', () => ({
npSetup: {
core: {
i18n: { Context: ({ children }: any) => <div>Context: {children}</div> },
},
},
}));
import { wrapInI18nContext } from '.';
describe('ui/i18n', () => {
test('renders children and forwards properties', () => {
__newPlatformSetup__(({ children }) => <div>Context: {children}</div>);
const mockPropTypes = {
stringProp: PropTypes.string.isRequired,
numberProp: PropTypes.number,

View file

@ -22,16 +22,9 @@ import React from 'react';
import { i18nDirective, i18nFilter, I18nProvider } from '@kbn/i18n/angular';
// @ts-ignore
import { uiModules } from 'ui/modules';
import { I18nSetup } from '../../../../core/public';
import { npSetup } from 'ui/new_platform';
export let I18nContext: I18nSetup['Context'] = null!;
export function __newPlatformSetup__(context: typeof I18nContext) {
if (I18nContext) {
throw new Error('ui/i18n already initialized with new platform apis');
}
I18nContext = context;
}
export const I18nContext = npSetup.core.i18n.Context;
export function wrapInI18nContext<P>(ComponentToWrap: React.ComponentType<P>) {
const ContextWrapper: React.SFC<P> = props => {

View file

@ -29,15 +29,13 @@ jest.mock('./ui/inspector_panel', () => ({
jest.mock('ui/i18n', () => ({ I18nContext: ({ children }) => children }));
jest.mock('ui/new_platform', () => ({
getNewPlatform: () => ({
start: {
core: {
overlay: {
openFlyout: jest.fn(),
},
}
npStart: {
core: {
overlay: {
openFlyout: jest.fn(),
},
}
}),
},
}));
import { viewRegistry } from './view_registry';

View file

@ -20,7 +20,7 @@ import React from 'react';
import { i18n } from '@kbn/i18n';
import { OverlayRef } from '../../../../core/public';
import { getNewPlatform } from '../new_platform';
import { npStart } from '../new_platform';
import { Adapters } from './types';
import { InspectorPanel } from './ui/inspector_panel';
import { viewRegistry } from './view_registry';
@ -73,7 +73,7 @@ function open(adapters: Adapters, options: InspectorOptions = {}): InspectorSess
if an inspector can be shown.`);
}
return getNewPlatform().start.core.overlays.openFlyout(
return npStart.core.overlays.openFlyout(
<InspectorPanel views={views} adapters={adapters} title={options.title} />,
{
'data-test-subj': 'inspectorPanel',

View file

@ -17,22 +17,11 @@
* under the License.
*/
import { npSetup } from 'ui/new_platform';
import { createKfetch, KFetchKibanaOptions, KFetchOptions } from './kfetch';
export { addInterceptor, KFetchOptions, KFetchQuery } from './kfetch';
import { HttpSetup } from '../../../../core/public';
let http: HttpSetup;
let kfetchInstance: (options: KFetchOptions, kfetchOptions?: KFetchKibanaOptions) => any;
export function __newPlatformSetup__(httpSetup: HttpSetup) {
if (http) {
throw new Error('ui/kfetch already initialized with New Platform APIs');
}
http = httpSetup;
kfetchInstance = createKfetch(http);
}
const kfetchInstance = createKfetch(npSetup.core.http);
export const kfetch = (options: KFetchOptions, kfetchOptions?: KFetchKibanaOptions) => {
return kfetchInstance(options, kfetchOptions);

View file

@ -17,12 +17,10 @@
* under the License.
*/
export let metadata = null;
import { setup } from '../../../../test_utils/public/http_test_setup';
export function __newPlatformSetup__(legacyMetadata) {
if (metadata === null) {
metadata = legacyMetadata;
} else {
throw new Error('ui/metadata can only be initialized once');
}
}
jest.doMock('ui/new_platform', () => ({
npSetup: {
core: setup(),
},
}));

View file

@ -19,18 +19,14 @@
// @ts-ignore
import fetchMock from 'fetch-mock/es5/client';
import './kfetch.test.mocks';
import { readFileSync } from 'fs';
import { join } from 'path';
import { __newPlatformSetup__, addInterceptor, kfetch, KFetchOptions } from '.';
import { addInterceptor, kfetch, KFetchOptions } from '.';
import { Interceptor, resetInterceptors, withDefaultOptions } from './kfetch';
import { KFetchError } from './kfetch_error';
import { setup } from '../../../../test_utils/public/http_test_setup';
describe('kfetch', () => {
beforeAll(() => {
__newPlatformSetup__(setup().http);
});
afterEach(() => {
fetchMock.restore();
resetInterceptors();

View file

@ -41,7 +41,7 @@ import { capabilities } from 'ui/capabilities';
import { modifyUrl } from 'ui/url';
// @ts-ignore
import { UrlOverflowServiceProvider } from '../error_url_overflow';
import { getNewPlatform } from '../new_platform';
import { npSetup } from '../new_platform';
import { toastNotifications } from '../notify';
// @ts-ignore
import { isSystemApiRequest } from '../system_api';
@ -49,7 +49,7 @@ import { isSystemApiRequest } from '../system_api';
const URL_LIMIT_WARN_WITHIN = 1000;
export const configureAppAngularModule = (angularModule: IModule) => {
const newPlatform = getNewPlatform().setup.core;
const newPlatform = npSetup.core;
const legacyMetadata = newPlatform.injectedMetadata.getLegacyMetadata();
forOwn(newPlatform.injectedMetadata.getInjectedVars(), (val, name) => {

View file

@ -0,0 +1,25 @@
/*
* 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 { npSetup } from 'ui/new_platform';
export const metadata: {
branch: string;
version: string;
} = npSetup.core.injectedMetadata.getLegacyMetadata();

View file

@ -16,10 +16,4 @@
* specific language governing permissions and limitations
* under the License.
*/
export {
__newPlatformSetup__,
__newPlatformStart__,
getNewPlatform,
onSetup,
onStart,
} from './new_platform';
export { __setup__, __start__, npSetup, npStart } from './new_platform';

View file

@ -1,146 +0,0 @@
/*
* 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 {
__newPlatformSetup__,
__newPlatformStart__,
__reset__,
onSetup,
onStart,
} from './new_platform';
describe('onSetup', () => {
afterEach(() => __reset__());
it('resolves callbacks registered before setup', async () => {
const aCallback = jest.fn(() => 1);
const bCallback = jest.fn(() => 2);
const a = onSetup(aCallback);
const b = onSetup(bCallback);
const coreSetup = { fake: true } as any;
__newPlatformSetup__(coreSetup, {});
expect(await Promise.all([a, b])).toEqual([1, 2]);
expect(aCallback).toHaveBeenCalledWith({ core: { fake: true }, plugins: {} });
expect(bCallback).toHaveBeenCalledWith({ core: { fake: true }, plugins: {} });
});
it('resolves callbacks registered after setup', async () => {
const callback = jest.fn(() => 3);
const coreSetup = { fake: true } as any;
__newPlatformSetup__(coreSetup, {});
expect(await onSetup(callback)).toEqual(3);
expect(callback).toHaveBeenCalledWith({ core: { fake: true }, plugins: {} });
});
it('rejects errors in callbacks registered before setup', async () => {
const aCallback = jest.fn(() => {
throw new Error('a error!');
});
const bCallback = jest.fn(() => {
throw new Error('b error!');
});
const cCallback = jest.fn(() => 3);
const a = onSetup(aCallback);
const b = onSetup(bCallback);
const c = onSetup(cCallback);
const coreSetup = { fake: true } as any;
__newPlatformSetup__(coreSetup, {});
await expect(a).rejects.toThrowError('a error!');
await expect(b).rejects.toThrowError('b error!');
// make sure one exception doesn't stop other callbacks from running
await expect(c).resolves.toEqual(3);
});
it('rejects errors in callbacks registered after setup', async () => {
const callback = jest.fn(() => {
throw new Error('a error!');
});
const coreSetup = { fake: true } as any;
__newPlatformSetup__(coreSetup, {});
await expect(onSetup(callback)).rejects.toThrowError('a error!');
});
});
describe('onStart', () => {
afterEach(() => __reset__());
it('resolves callbacks registered before start', async () => {
const aCallback = jest.fn(() => 1);
const bCallback = jest.fn(() => 2);
const a = onStart(aCallback);
const b = onStart(bCallback);
const coreStart = { fake: true } as any;
__newPlatformStart__(coreStart, {});
expect(await Promise.all([a, b])).toEqual([1, 2]);
expect(aCallback).toHaveBeenCalledWith({ core: { fake: true }, plugins: {} });
expect(bCallback).toHaveBeenCalledWith({ core: { fake: true }, plugins: {} });
});
it('resolves callbacks registered after start', async () => {
const callback = jest.fn(() => 3);
const coreStart = { fake: true } as any;
__newPlatformStart__(coreStart, {});
expect(await onStart(callback)).toEqual(3);
expect(callback).toHaveBeenCalledWith({ core: { fake: true }, plugins: {} });
});
it('rejects errors in callbacks registered before start', async () => {
const aCallback = jest.fn(() => {
throw new Error('a error!');
});
const bCallback = jest.fn(() => {
throw new Error('b error!');
});
const cCallback = jest.fn(() => 3);
const a = onStart(aCallback);
const b = onStart(bCallback);
const c = onStart(cCallback);
const coreStart = { fake: true } as any;
__newPlatformStart__(coreStart, {});
await expect(a).rejects.toThrowError('a error!');
await expect(b).rejects.toThrowError('b error!');
// make sure one exception doesn't stop other callbacks from running
await expect(c).resolves.toEqual(3);
});
it('rejects errors in callbacks registered after start', async () => {
const callback = jest.fn(() => {
throw new Error('a error!');
});
const coreStart = { fake: true } as any;
__newPlatformStart__(coreStart, {});
await expect(onStart(callback)).rejects.toThrowError('a error!');
});
});

View file

@ -18,15 +18,14 @@
*/
import { InternalCoreSetup, InternalCoreStart } from '../../../../core/public';
const runtimeContext = {
setup: {
core: (null as unknown) as InternalCoreSetup,
plugins: {} as Record<string, unknown>,
},
start: {
core: (null as unknown) as InternalCoreStart,
plugins: {} as Record<string, unknown>,
},
export const npSetup = {
core: (null as unknown) as InternalCoreSetup,
plugins: {} as Record<string, unknown>,
};
export const npStart = {
core: (null as unknown) as InternalCoreStart,
plugins: {} as Record<string, unknown>,
};
/**
@ -34,95 +33,14 @@ const runtimeContext = {
* @internal
*/
export function __reset__() {
runtimeContext.setup.core = (null as unknown) as InternalCoreSetup;
runtimeContext.start.core = (null as unknown) as InternalCoreStart;
npSetup.core = (null as unknown) as InternalCoreSetup;
npStart.core = (null as unknown) as InternalCoreStart;
}
export async function __newPlatformSetup__(
core: InternalCoreSetup,
plugins: Record<string, unknown>
) {
if (runtimeContext.setup.core) {
throw new Error('New platform core api was already set up');
}
runtimeContext.setup.core = core;
runtimeContext.setup.plugins = plugins;
// Process any pending onSetup callbacks
while (onSetupCallbacks.length) {
const cb = onSetupCallbacks.shift()!;
await cb(runtimeContext.setup);
}
export function __setup__(coreSetup: InternalCoreSetup) {
npSetup.core = coreSetup;
}
export async function __newPlatformStart__(
core: InternalCoreStart,
plugins: Record<string, unknown>
) {
if (runtimeContext.start.core) {
throw new Error('New platform core api was already started');
}
runtimeContext.start.core = core;
runtimeContext.start.plugins = plugins;
// Process any pending onStart callbacks
while (onStartCallbacks.length) {
const cb = onStartCallbacks.shift()!;
await cb(runtimeContext.start);
}
}
export function getNewPlatform() {
if (runtimeContext.setup.core === null || runtimeContext.start.core === null) {
throw new Error('runtimeContext is not initialized yet');
}
return runtimeContext;
}
type SetupCallback<T> = (startContext: typeof runtimeContext['setup']) => T;
type StartCallback<T> = (startContext: typeof runtimeContext['start']) => T;
const onSetupCallbacks: Array<SetupCallback<Promise<unknown>>> = [];
const onStartCallbacks: Array<StartCallback<Promise<unknown>>> = [];
/**
* Register a callback to be called once the new platform is in the
* `setup` lifecycle event. Resolves to the return value of the callback.
*/
export async function onSetup<T>(callback: SetupCallback<T>): Promise<T> {
if (runtimeContext.setup.core !== null) {
return callback(runtimeContext.setup);
}
return new Promise((resolve, reject) => {
onSetupCallbacks.push(async (setupContext: typeof runtimeContext['setup']) => {
try {
resolve(await callback(setupContext));
} catch (e) {
reject(e);
}
});
});
}
/**
* Register a callback to be called once the new platform is in the
* `start` lifecycle event. Resolves to the return value of the callback.
*/
export async function onStart<T>(callback: StartCallback<T>): Promise<T> {
if (runtimeContext.start.core !== null) {
return callback(runtimeContext.start);
}
return new Promise((resolve, reject) => {
onStartCallbacks.push(async (startContext: typeof runtimeContext['start']) => {
try {
resolve(await callback(startContext));
} catch (e) {
reject(e);
}
});
});
export function __start__(coreStart: InternalCoreStart) {
npStart.core = coreStart;
}

View file

@ -17,22 +17,14 @@
* under the License.
*/
import { FatalErrorsSetup } from '../../../../core/public';
import { npSetup } from 'ui/new_platform';
import {
AngularHttpError,
formatAngularHttpError,
isAngularHttpError,
} from './lib/format_angular_http_error';
let newPlatformFatalErrors: FatalErrorsSetup;
export function __newPlatformSetup__(instance: FatalErrorsSetup) {
if (newPlatformFatalErrors) {
throw new Error('ui/notify/fatal_error already initialized with new platform apis');
}
newPlatformFatalErrors = instance;
}
const newPlatformFatalErrors = npSetup.core.fatalErrors;
export function addFatalErrorCallback(callback: () => void) {
newPlatformFatalErrors.get$().subscribe(() => {

View file

@ -17,5 +17,5 @@
* under the License.
*/
export { toastNotifications, __newPlatformSetup__ } from './toasts';
export { toastNotifications } from './toasts';
export { Toast, ToastInput } from './toast_notifications';

View file

@ -17,7 +17,12 @@
* under the License.
*/
import { ErrorToastOptions, Toast, ToastInput, ToastsApi } from '../../../../../core/public';
import {
ErrorToastOptions,
NotificationsSetup,
Toast,
ToastInput,
} from '../../../../../core/public';
export { Toast, ToastInput };
@ -26,7 +31,7 @@ export class ToastNotifications {
private onChangeCallback?: () => void;
constructor(private readonly toasts: ToastsApi) {
constructor(private readonly toasts: NotificationsSetup['toasts']) {
toasts.get$().subscribe(list => {
this.list = list;

View file

@ -17,15 +17,7 @@
* under the License.
*/
import { ToastsApi } from '../../../../../core/public';
import { npSetup } from 'ui/new_platform';
import { ToastNotifications } from './toast_notifications';
export let toastNotifications: ToastNotifications;
export function __newPlatformSetup__(toasts: ToastsApi) {
if (toastNotifications) {
throw new Error('ui/notify/toasts already initialized with new platform apis');
}
toastNotifications = new ToastNotifications(toasts);
}
export const toastNotifications = new ToastNotifications(npSetup.core.notifications.toasts);

View file

@ -18,7 +18,7 @@
*/
import { EuiFlyoutBody, EuiFlyoutHeader, EuiTitle } from '@elastic/eui';
import React from 'react';
import { getNewPlatform } from 'ui/new_platform';
import { npStart } from 'ui/new_platform';
import {
ContextMenuAction,
@ -44,7 +44,7 @@ class SamplePanelAction extends ContextMenuAction {
if (!embeddable) {
return;
}
getNewPlatform().start.core.overlays.openFlyout(
npStart.core.overlays.openFlyout(
<React.Fragment>
<EuiFlyoutHeader>
<EuiTitle size="m" data-test-subj="samplePanelActionTitle">

View file

@ -10,8 +10,8 @@ import { resolve } from 'path';
import {
InternalCoreSetup,
PluginInitializerContext
} from 'src/core/server/index.js';
import { LegacyPluginInitializer } from 'src/legacy/types';
} from '../../../src/core/server';
import { LegacyPluginInitializer } from '../../../src/legacy/types';
import mappings from './mappings.json';
import { plugin } from './server/new-platform/index';

View file

@ -4,11 +4,11 @@
* you may not use this file except in compliance with the Elastic License.
*/
import { onStart } from 'ui/new_platform';
import { npStart } from 'ui/new_platform';
onStart(({ core }) => {
const apmUiEnabled = core.injectedMetadata.getInjectedVar('apmUiEnabled');
if (apmUiEnabled === false) {
core.chrome.navLinks.update('apm', { hidden: true });
}
});
const apmUiEnabled = npStart.core.injectedMetadata.getInjectedVar(
'apmUiEnabled'
);
if (apmUiEnabled === false) {
npStart.core.chrome.navLinks.update('apm', { hidden: true });
}

View file

@ -4,11 +4,9 @@
* you may not use this file except in compliance with the Elastic License.
*/
import { onStart } from 'ui/new_platform';
import { npStart } from 'ui/new_platform';
onStart(({ core }) => {
const codeUiEnabled = core.injectedMetadata.getInjectedVar('codeUiEnabled');
if (codeUiEnabled === false) {
core.chrome.navLinks.update('code', { hidden: true });
}
});
const codeUiEnabled = npStart.core.injectedMetadata.getInjectedVar('codeUiEnabled');
if (codeUiEnabled === false) {
npStart.core.chrome.navLinks.update('code', { hidden: true });
}

View file

@ -37,7 +37,7 @@ import 'ui/agg_response';
import 'ui/agg_types';
import 'ui/timepicker';
import 'leaflet';
import { getNewPlatform } from 'ui/new_platform';
import { npStart } from 'ui/new_platform';
import { showAppRedirectNotification } from 'ui/notify';
import { DashboardConstants, createDashboardEditUrl } from 'plugins/kibana/dashboard/dashboard_constants';
@ -50,7 +50,7 @@ routes.otherwise({ redirectTo: defaultUrl() });
chrome
.setRootController('kibana', function () {
getNewPlatform().start.core.chrome.navLinks.showOnly('kibana:dashboard');
npStart.core.chrome.navLinks.showOnly('kibana:dashboard');
});
uiModules.get('kibana').run(showAppRedirectNotification);

View file

@ -27,7 +27,7 @@ import { notify, addAppRedirectMessageToUrl, fatalError, toastNotifications } fr
import { IndexPatternsProvider } from 'ui/index_patterns/index_patterns';
import { SavedObjectsClientProvider } from 'ui/saved_objects';
import { KibanaParsedUrl } from 'ui/url/kibana_parsed_url';
import { getNewPlatform } from 'ui/new_platform';
import { npStart } from 'ui/new_platform';
import { XPackInfoProvider } from 'plugins/xpack_main/services/xpack_info';
@ -770,7 +770,7 @@ app.controller('graphuiPlugin', function (
.on('zoom', redraw));
const managementUrl = getNewPlatform().start.core.chrome.navLinks.get('kibana:management').url;
const managementUrl = npStart.core.chrome.navLinks.get('kibana:management').url;
const url = `${managementUrl}/kibana/index_patterns`;
if ($scope.indices.length === 0) {

View file

@ -5,7 +5,7 @@
*/
import { uiModules } from 'ui/modules';
import { onStart } from 'ui/new_platform';
import { npStart } from 'ui/new_platform';
import { XPackInfoProvider } from 'plugins/xpack_main/services/xpack_info';
@ -22,5 +22,5 @@ uiModules.get('xpack/graph')
navLinkUpdates.tooltip = xpackInfo.get('features.graph.message');
}
onStart(({ core }) => core.chrome.navLinks.update('graph', navLinkUpdates));
npStart.core.chrome.navLinks.update('graph', navLinkUpdates);
});

View file

@ -6,7 +6,7 @@
import { useCallback, useMemo } from 'react';
import { getNewPlatform } from 'ui/new_platform';
import { npSetup } from 'ui/new_platform';
import { useObservable } from './use_observable';
/**
@ -26,7 +26,7 @@ import { useObservable } from './use_observable';
* because the underlying `UiSettingsClient` doesn't support that.
*/
export const useKibanaUiSetting = (key: string, defaultValue?: any) => {
const uiSettingsClient = useMemo(() => getNewPlatform().setup.core.uiSettings, [getNewPlatform]);
const uiSettingsClient = npSetup.core.uiSettings;
const uiSetting$ = useMemo(() => uiSettingsClient.get$(key, defaultValue), [uiSettingsClient]);
const uiSetting = useObservable(uiSetting$);

View file

@ -7,6 +7,10 @@ import React from 'react';
import { TelemetryOptIn } from '../public/components/telemetry_opt_in';
import { mountWithIntl } from '../../../test_utils/enzyme_helpers';
jest.mock('ui/capabilities', () => ({
get: jest.fn(),
}));
describe('TelemetryOptIn', () => {
test('should display when telemetry not opted in', () => {
const telemetry = require('../public/lib/telemetry');

View file

@ -7,6 +7,10 @@
import { mountWithIntl } from 'test_utils/enzyme_helpers';
import React from 'react';
jest.mock('ui/i18n', () => ({
I18nContext: jest.fn()
}));
import { FieldTitleBar } from './field_title_bar';
// helper to let PropTypes throw errors instead of just doing console.error()

View file

@ -8,7 +8,7 @@
import { XPackInfoProvider } from 'plugins/xpack_main/services/xpack_info';
import { uiModules } from 'ui/modules';
import { onStart } from 'ui/new_platform';
import { npStart } from 'ui/new_platform';
uiModules.get('xpack/ml').run((Private) => {
const xpackInfo = Private(XPackInfoProvider);
@ -21,5 +21,5 @@ uiModules.get('xpack/ml').run((Private) => {
disabled: !showAppLink || (showAppLink && !xpackInfo.get('features.ml.isAvailable', false))
};
onStart(({ core }) => core.chrome.navLinks.update('ml', navLinkUpdates));
npStart.core.chrome.navLinks.update('ml', navLinkUpdates);
});

View file

@ -5,12 +5,12 @@
*/
import { uiModules } from 'ui/modules';
import { onStart } from 'ui/new_platform';
import { npStart } from 'ui/new_platform';
uiModules.get('monitoring/hacks').run((monitoringUiEnabled) => {
if (monitoringUiEnabled) {
return;
}
onStart(({ core }) => core.chrome.navLinks.update('monitoring', { hidden: true }));
npStart.core.chrome.navLinks.update('monitoring', { hidden: true });
});

View file

@ -19,7 +19,7 @@ import {
EuiButton,
} from '@elastic/eui';
import { downloadReport } from '../lib/download_report';
import { getNewPlatform } from 'ui/new_platform';
import { npStart } from 'ui/new_platform';
/**
* Poll for changes to reports. Inform the user of changes when the license is active.
@ -59,13 +59,13 @@ uiModules.get('kibana')
let seeReportLink;
const core = getNewPlatform().start.core;
const { chrome } = npStart.core;
// In-case the license expired/changed between the time they queued the job and the time that
// the job completes, that way we don't give the user a toast to download their report if they can't.
// NOTE: this should be looking at configuration rather than the existence of a navLink
if (core.chrome.navLinks.has('kibana:management')) {
const managementUrl = core.chrome.navLinks.get('kibana:management').url;
if (chrome.navLinks.has('kibana:management')) {
const managementUrl = chrome.navLinks.get('kibana:management').url;
const reportingSectionUrl = `${managementUrl}/kibana/reporting`;
seeReportLink = (
<p>