diff --git a/x-pack/legacy/plugins/siem/public/apps/plugin.tsx b/x-pack/legacy/plugins/siem/public/apps/plugin.tsx index 1f19841788ddb..700fec2557b1b 100644 --- a/x-pack/legacy/plugins/siem/public/apps/plugin.tsx +++ b/x-pack/legacy/plugins/siem/public/apps/plugin.tsx @@ -15,6 +15,12 @@ import template from './template.html'; export const ROOT_ELEMENT_ID = 'react-siem-root'; +export type StartCore = LegacyCoreStart; +export type StartPlugins = Required< + Pick<PluginsStart, 'data' | 'embeddable' | 'inspector' | 'uiActions'> +>; +export type StartServices = StartCore & StartPlugins; + export class Plugin { constructor( // @ts-ignore this is added to satisfy the New Platform typing constraint, @@ -25,7 +31,7 @@ export class Plugin { this.chrome = chrome; } - public start(core: LegacyCoreStart, plugins: PluginsStart) { + public start(core: StartCore, plugins: StartPlugins) { // @ts-ignore improper type description this.chrome.setRootTemplate(template); const checkForRoot = () => { diff --git a/x-pack/legacy/plugins/siem/public/apps/start_app.tsx b/x-pack/legacy/plugins/siem/public/apps/start_app.tsx index 4549db946b815..6b7e3a7b8084f 100644 --- a/x-pack/legacy/plugins/siem/public/apps/start_app.tsx +++ b/x-pack/legacy/plugins/siem/public/apps/start_app.tsx @@ -9,8 +9,6 @@ import React, { memo, FC } from 'react'; import { ApolloProvider } from 'react-apollo'; import { Provider as ReduxStoreProvider } from 'react-redux'; import { ThemeProvider } from 'styled-components'; -import { LegacyCoreStart } from 'kibana/public'; -import { PluginsStart } from 'ui/new_platform/new_platform'; import { EuiErrorBoundary } from '@elastic/eui'; import euiDarkVars from '@elastic/eui/dist/eui_theme_dark.json'; @@ -19,16 +17,14 @@ import { BehaviorSubject } from 'rxjs'; import { pluck } from 'rxjs/operators'; import { I18nContext } from 'ui/i18n'; -import { KibanaContextProvider } from '../../../../../../src/plugins/kibana_react/public'; +import { KibanaContextProvider, useUiSetting$ } from '../lib/kibana'; import { Storage } from '../../../../../../src/plugins/kibana_utils/public'; import { DEFAULT_DARK_MODE } from '../../common/constants'; import { ErrorToastDispatcher } from '../components/error_toast_dispatcher'; import { compose } from '../lib/compose/kibana_compose'; import { AppFrontendLibs } from '../lib/lib'; -import { KibanaCoreContextProvider } from '../lib/compose/kibana_core'; -import { KibanaPluginsContextProvider } from '../lib/compose/kibana_plugins'; -import { useKibanaUiSetting } from '../lib/settings/use_kibana_ui_setting'; +import { StartCore, StartPlugins } from './plugin'; import { PageRouter } from '../routes'; import { createStore } from '../store'; import { GlobalToaster, ManageGlobalToaster } from '../components/toasters'; @@ -44,7 +40,7 @@ const StartApp: FC<AppFrontendLibs> = memo(libs => { const store = createStore(undefined, libs$.pipe(pluck('apolloClient'))); const AppPluginRoot = memo(() => { - const [darkMode] = useKibanaUiSetting(DEFAULT_DARK_MODE); + const [darkMode] = useUiSetting$<boolean>(DEFAULT_DARK_MODE); return ( <EuiErrorBoundary> <I18nContext> @@ -77,21 +73,15 @@ const StartApp: FC<AppFrontendLibs> = memo(libs => { export const ROOT_ELEMENT_ID = 'react-siem-root'; -export const SiemApp = memo<{ core: LegacyCoreStart; plugins: PluginsStart }>( - ({ core, plugins }) => ( - <KibanaContextProvider - services={{ - appName: 'siem', - data: plugins.data, - storage: new Storage(localStorage), - ...core, - }} - > - <KibanaCoreContextProvider core={core}> - <KibanaPluginsContextProvider plugins={plugins}> - <StartApp {...compose()} /> - </KibanaPluginsContextProvider> - </KibanaCoreContextProvider> - </KibanaContextProvider> - ) -); +export const SiemApp = memo<{ core: StartCore; plugins: StartPlugins }>(({ core, plugins }) => ( + <KibanaContextProvider + services={{ + appName: 'siem', + data: plugins.data, + storage: new Storage(localStorage), + ...core, + }} + > + <StartApp {...compose()} /> + </KibanaContextProvider> +)); diff --git a/x-pack/legacy/plugins/siem/public/components/bytes/index.test.tsx b/x-pack/legacy/plugins/siem/public/components/bytes/index.test.tsx index 2321b06c07cc0..6816bff24f1cd 100644 --- a/x-pack/legacy/plugins/siem/public/components/bytes/index.test.tsx +++ b/x-pack/legacy/plugins/siem/public/components/bytes/index.test.tsx @@ -12,8 +12,6 @@ import { useMountAppended } from '../../utils/use_mount_appended'; import { Bytes } from '.'; -jest.mock('../../lib/settings/use_kibana_ui_setting'); - describe('Bytes', () => { const mount = useMountAppended(); diff --git a/x-pack/legacy/plugins/siem/public/components/charts/areachart.test.tsx b/x-pack/legacy/plugins/siem/public/components/charts/areachart.test.tsx index 25bd2a9d56059..2b99efc05fd8c 100644 --- a/x-pack/legacy/plugins/siem/public/components/charts/areachart.test.tsx +++ b/x-pack/legacy/plugins/siem/public/components/charts/areachart.test.tsx @@ -11,6 +11,8 @@ import { AreaChartBaseComponent, AreaChartComponent } from './areachart'; import { ChartSeriesData } from './common'; import { ScaleType, AreaSeries, Axis } from '@elastic/charts'; +jest.mock('../../lib/kibana'); + const customHeight = '100px'; const customWidth = '120px'; const chartDataSets = [ diff --git a/x-pack/legacy/plugins/siem/public/components/charts/areachart.tsx b/x-pack/legacy/plugins/siem/public/components/charts/areachart.tsx index c644d148cc1c3..297563c8e31cf 100644 --- a/x-pack/legacy/plugins/siem/public/components/charts/areachart.tsx +++ b/x-pack/legacy/plugins/siem/public/components/charts/areachart.tsx @@ -21,7 +21,6 @@ import { getOr, get, isNull, isNumber } from 'lodash/fp'; import { AutoSizer } from '../auto_sizer'; import { ChartPlaceHolder } from './chart_place_holder'; import { - browserTimezone, chartDefaultSettings, ChartSeriesConfigs, ChartSeriesData, @@ -29,6 +28,8 @@ import { getChartWidth, getSeriesStyle, WrappedByAutoSizer, + useTheme, + useBrowserTimeZone, } from './common'; // custom series styles: https://ela.st/areachart-styling @@ -72,12 +73,15 @@ export const AreaChartBaseComponent = ({ height: string | null | undefined; configs?: ChartSeriesConfigs | undefined; }) => { + const theme = useTheme(); + const timeZone = useBrowserTimeZone(); const xTickFormatter = get('configs.axis.xTickFormatter', chartConfigs); const yTickFormatter = get('configs.axis.yTickFormatter', chartConfigs); const xAxisId = getAxisId(`group-${data[0].key}-x`); const yAxisId = getAxisId(`group-${data[0].key}-y`); const settings = { ...chartDefaultSettings, + theme, ...get('configs.settings', chartConfigs), }; return chartConfigs.width && chartConfigs.height ? ( @@ -95,7 +99,7 @@ export const AreaChartBaseComponent = ({ data={series.value || undefined} xScaleType={getOr(ScaleType.Linear, 'configs.series.xScaleType', chartConfigs)} yScaleType={getOr(ScaleType.Linear, 'configs.series.yScaleType', chartConfigs)} - timeZone={browserTimezone} + timeZone={timeZone} xAccessor="x" yAccessors={['y']} areaSeriesStyle={getSeriesLineStyle()} diff --git a/x-pack/legacy/plugins/siem/public/components/charts/barchart.test.tsx b/x-pack/legacy/plugins/siem/public/components/charts/barchart.test.tsx index e28d330d31ba9..506b1ceb5ed83 100644 --- a/x-pack/legacy/plugins/siem/public/components/charts/barchart.test.tsx +++ b/x-pack/legacy/plugins/siem/public/components/charts/barchart.test.tsx @@ -11,6 +11,8 @@ import { BarChartBaseComponent, BarChartComponent } from './barchart'; import { ChartSeriesData } from './common'; import { BarSeries, ScaleType, Axis } from '@elastic/charts'; +jest.mock('../../lib/kibana'); + const customHeight = '100px'; const customWidth = '120px'; const chartDataSets = [ diff --git a/x-pack/legacy/plugins/siem/public/components/charts/barchart.tsx b/x-pack/legacy/plugins/siem/public/components/charts/barchart.tsx index 99ad995e48852..ee8b4eaf6b08c 100644 --- a/x-pack/legacy/plugins/siem/public/components/charts/barchart.tsx +++ b/x-pack/legacy/plugins/siem/public/components/charts/barchart.tsx @@ -19,16 +19,17 @@ import { getOr, get, isNumber } from 'lodash/fp'; import { AutoSizer } from '../auto_sizer'; import { ChartPlaceHolder } from './chart_place_holder'; import { - browserTimezone, chartDefaultSettings, ChartSeriesConfigs, ChartSeriesData, checkIfAllValuesAreZero, - getSeriesStyle, getChartHeight, getChartWidth, + getSeriesStyle, SeriesType, WrappedByAutoSizer, + useBrowserTimeZone, + useTheme, } from './common'; const checkIfAllTheDataInTheSeriesAreValid = (series: ChartSeriesData): series is ChartSeriesData => @@ -53,6 +54,8 @@ export const BarChartBaseComponent = ({ height: string | null | undefined; configs?: ChartSeriesConfigs | undefined; }) => { + const theme = useTheme(); + const timeZone = useBrowserTimeZone(); const xTickFormatter = get('configs.axis.xTickFormatter', chartConfigs); const yTickFormatter = get('configs.axis.yTickFormatter', chartConfigs); const tickSize = getOr(0, 'configs.axis.tickSize', chartConfigs); @@ -60,6 +63,7 @@ export const BarChartBaseComponent = ({ const yAxisId = getAxisId(`stat-items-barchart-${data[0].key}-y`); const settings = { ...chartDefaultSettings, + theme, ...get('configs.settings', chartConfigs), }; @@ -79,7 +83,7 @@ export const BarChartBaseComponent = ({ yScaleType={getOr(ScaleType.Linear, 'configs.series.yScaleType', chartConfigs)} xAccessor="x" yAccessors={['y']} - timeZone={browserTimezone} + timeZone={timeZone} splitSeriesAccessors={['g']} data={series.value!} stackAccessors={get('configs.series.stackAccessors', chartConfigs)} diff --git a/x-pack/legacy/plugins/siem/public/components/charts/common.test.tsx b/x-pack/legacy/plugins/siem/public/components/charts/common.test.tsx index 0bb4da69a978a..e9df0d3885a18 100644 --- a/x-pack/legacy/plugins/siem/public/components/charts/common.test.tsx +++ b/x-pack/legacy/plugins/siem/public/components/charts/common.test.tsx @@ -5,23 +5,27 @@ */ import { shallow } from 'enzyme'; import React from 'react'; +import { renderHook } from '@testing-library/react-hooks'; + +import { useUiSetting } from '../../lib/kibana'; import { checkIfAllValuesAreZero, defaultChartHeight, getChartHeight, getChartWidth, getSeriesStyle, - getTheme, SeriesType, WrappedByAutoSizer, ChartSeriesData, + useTheme, } from './common'; -import { mergeWithDefaultTheme, LIGHT_THEME } from '@elastic/charts'; + +jest.mock('../../lib/kibana'); jest.mock('@elastic/charts', () => { return { + ...jest.requireActual('@elastic/charts'), getSpecId: jest.fn(() => {}), - mergeWithDefaultTheme: jest.fn(), }; }); @@ -57,21 +61,6 @@ describe('getSeriesStyle', () => { }); }); -describe('getTheme', () => { - it('should merge custom theme with default theme', () => { - const defaultTheme = { - chartMargins: { bottom: 0, left: 0, right: 0, top: 4 }, - chartPaddings: { bottom: 0, left: 0, right: 0, top: 0 }, - scales: { - barsPadding: 0.05, - }, - }; - getTheme(); - expect((mergeWithDefaultTheme as jest.Mock).mock.calls[0][0]).toMatchObject(defaultTheme); - expect((mergeWithDefaultTheme as jest.Mock).mock.calls[0][1]).toEqual(LIGHT_THEME); - }); -}); - describe('getChartHeight', () => { it('should render customHeight', () => { const height = getChartHeight(10, 100); @@ -197,4 +186,23 @@ describe('checkIfAllValuesAreZero', () => { expect(result).toBeTruthy(); }); }); + + describe('useTheme', () => { + it('merges our spacing with the default theme', () => { + const { result } = renderHook(() => useTheme()); + + expect(result.current).toEqual( + expect.objectContaining({ chartMargins: expect.objectContaining({ top: 4, bottom: 0 }) }) + ); + }); + + it('returns a different theme depending on user settings', () => { + const { result: defaultResult } = renderHook(() => useTheme()); + (useUiSetting as jest.Mock).mockImplementation(() => true); + + const { result: darkResult } = renderHook(() => useTheme()); + + expect(defaultResult.current).not.toMatchObject(darkResult.current); + }); + }); }); diff --git a/x-pack/legacy/plugins/siem/public/components/charts/common.tsx b/x-pack/legacy/plugins/siem/public/components/charts/common.tsx index 7ac91437920e5..dfb201fc3d927 100644 --- a/x-pack/legacy/plugins/siem/public/components/charts/common.tsx +++ b/x-pack/legacy/plugins/siem/public/components/charts/common.tsx @@ -4,7 +4,6 @@ * you may not use this file except in compliance with the Elastic License. */ -import chrome from 'ui/chrome'; import { CustomSeriesColorsMap, DARK_THEME, @@ -21,6 +20,7 @@ import { } from '@elastic/charts'; import moment from 'moment-timezone'; import styled from 'styled-components'; +import { useUiSetting } from '../../lib/kibana'; import { DEFAULT_DATE_FORMAT_TZ, DEFAULT_DARK_MODE } from '../../../common/constants'; export const defaultChartHeight = '100%'; @@ -95,27 +95,28 @@ export const getSeriesStyle = ( }; // Apply margins and paddings: https://ela.st/charts-spacing -export const getTheme = () => { - const theme: PartialTheme = { - chartMargins: { - left: 0, - right: 0, - // Apply some paddings to the top to avoid chopping the y tick https://ela.st/chopping-edge - top: 4, - bottom: 0, - }, - chartPaddings: { - left: 0, - right: 0, - top: 0, - bottom: 0, - }, - scales: { - barsPadding: 0.05, - }, - }; - const isDarkMode: boolean = chrome.getUiSettingsClient().get(DEFAULT_DARK_MODE); +const theme: PartialTheme = { + chartMargins: { + left: 0, + right: 0, + // Apply some paddings to the top to avoid chopping the y tick https://ela.st/chopping-edge + top: 4, + bottom: 0, + }, + chartPaddings: { + left: 0, + right: 0, + top: 0, + bottom: 0, + }, + scales: { + barsPadding: 0.05, + }, +}; +export const useTheme = () => { + const isDarkMode = useUiSetting<boolean>(DEFAULT_DARK_MODE); const defaultTheme = isDarkMode ? DARK_THEME : LIGHT_THEME; + return mergeWithDefaultTheme(theme, defaultTheme); }; @@ -126,11 +127,12 @@ export const chartDefaultSettings = { showLegend: false, showLegendDisplayValue: false, debug: false, - theme: getTheme(), }; -const kibanaTimezone: string = chrome.getUiSettingsClient().get(DEFAULT_DATE_FORMAT_TZ); -export const browserTimezone = kibanaTimezone === 'Browser' ? moment.tz.guess() : kibanaTimezone; +export const useBrowserTimeZone = () => { + const kibanaTimezone = useUiSetting<string>(DEFAULT_DATE_FORMAT_TZ); + return kibanaTimezone === 'Browser' ? moment.tz.guess() : kibanaTimezone; +}; export const getChartHeight = (customHeight?: number, autoSizerHeight?: number): string => { const height = customHeight || autoSizerHeight; diff --git a/x-pack/legacy/plugins/siem/public/components/detection_engine/utility_bar/utility_bar.test.tsx b/x-pack/legacy/plugins/siem/public/components/detection_engine/utility_bar/utility_bar.test.tsx index 68522377bd847..a5eac381f9215 100644 --- a/x-pack/legacy/plugins/siem/public/components/detection_engine/utility_bar/utility_bar.test.tsx +++ b/x-pack/legacy/plugins/siem/public/components/detection_engine/utility_bar/utility_bar.test.tsx @@ -9,7 +9,6 @@ import { mount, shallow } from 'enzyme'; import toJson from 'enzyme-to-json'; import React from 'react'; -import '../../../mock/ui_settings'; import { TestProviders } from '../../../mock'; import { UtilityBar, @@ -19,8 +18,6 @@ import { UtilityBarText, } from './index'; -jest.mock('../../../lib/settings/use_kibana_ui_setting'); - describe('UtilityBar', () => { test('it renders', () => { const wrapper = shallow( diff --git a/x-pack/legacy/plugins/siem/public/components/detection_engine/utility_bar/utility_bar_action.test.tsx b/x-pack/legacy/plugins/siem/public/components/detection_engine/utility_bar/utility_bar_action.test.tsx index 7921c1ef42200..2610fb44532f5 100644 --- a/x-pack/legacy/plugins/siem/public/components/detection_engine/utility_bar/utility_bar_action.test.tsx +++ b/x-pack/legacy/plugins/siem/public/components/detection_engine/utility_bar/utility_bar_action.test.tsx @@ -8,12 +8,9 @@ import { mount, shallow } from 'enzyme'; import toJson from 'enzyme-to-json'; import React from 'react'; -import '../../../mock/ui_settings'; import { TestProviders } from '../../../mock'; import { UtilityBarAction } from './index'; -jest.mock('../../../lib/settings/use_kibana_ui_setting'); - describe('UtilityBarAction', () => { test('it renders', () => { const wrapper = shallow( diff --git a/x-pack/legacy/plugins/siem/public/components/detection_engine/utility_bar/utility_bar_group.test.tsx b/x-pack/legacy/plugins/siem/public/components/detection_engine/utility_bar/utility_bar_group.test.tsx index 294d27fa95b3d..59ef7021d4049 100644 --- a/x-pack/legacy/plugins/siem/public/components/detection_engine/utility_bar/utility_bar_group.test.tsx +++ b/x-pack/legacy/plugins/siem/public/components/detection_engine/utility_bar/utility_bar_group.test.tsx @@ -8,12 +8,9 @@ import { shallow } from 'enzyme'; import toJson from 'enzyme-to-json'; import React from 'react'; -import '../../../mock/ui_settings'; import { TestProviders } from '../../../mock'; import { UtilityBarGroup, UtilityBarText } from './index'; -jest.mock('../../../lib/settings/use_kibana_ui_setting'); - describe('UtilityBarGroup', () => { test('it renders', () => { const wrapper = shallow( diff --git a/x-pack/legacy/plugins/siem/public/components/detection_engine/utility_bar/utility_bar_section.test.tsx b/x-pack/legacy/plugins/siem/public/components/detection_engine/utility_bar/utility_bar_section.test.tsx index e0e0acc3a71c9..baa4331ced8f8 100644 --- a/x-pack/legacy/plugins/siem/public/components/detection_engine/utility_bar/utility_bar_section.test.tsx +++ b/x-pack/legacy/plugins/siem/public/components/detection_engine/utility_bar/utility_bar_section.test.tsx @@ -8,12 +8,9 @@ import { shallow } from 'enzyme'; import toJson from 'enzyme-to-json'; import React from 'react'; -import '../../../mock/ui_settings'; import { TestProviders } from '../../../mock'; import { UtilityBarGroup, UtilityBarSection, UtilityBarText } from './index'; -jest.mock('../../../lib/settings/use_kibana_ui_setting'); - describe('UtilityBarSection', () => { test('it renders', () => { const wrapper = shallow( diff --git a/x-pack/legacy/plugins/siem/public/components/detection_engine/utility_bar/utility_bar_text.test.tsx b/x-pack/legacy/plugins/siem/public/components/detection_engine/utility_bar/utility_bar_text.test.tsx index 29e1844bb2d4f..794f207fd88e3 100644 --- a/x-pack/legacy/plugins/siem/public/components/detection_engine/utility_bar/utility_bar_text.test.tsx +++ b/x-pack/legacy/plugins/siem/public/components/detection_engine/utility_bar/utility_bar_text.test.tsx @@ -8,12 +8,9 @@ import { shallow } from 'enzyme'; import toJson from 'enzyme-to-json'; import React from 'react'; -import '../../../mock/ui_settings'; import { TestProviders } from '../../../mock'; import { UtilityBarText } from './index'; -jest.mock('../../../lib/settings/use_kibana_ui_setting'); - describe('UtilityBarText', () => { test('it renders', () => { const wrapper = shallow( diff --git a/x-pack/legacy/plugins/siem/public/components/embeddables/__snapshots__/embedded_map.test.tsx.snap b/x-pack/legacy/plugins/siem/public/components/embeddables/__snapshots__/embedded_map.test.tsx.snap index 2444fd0bc2b7d..d5de7ab508a73 100644 --- a/x-pack/legacy/plugins/siem/public/components/embeddables/__snapshots__/embedded_map.test.tsx.snap +++ b/x-pack/legacy/plugins/siem/public/components/embeddables/__snapshots__/embedded_map.test.tsx.snap @@ -9,7 +9,7 @@ exports[`EmbeddedMapComponent renders correctly against snapshot 1`] = ` size="xs" > <EuiLink - href="undefinedguide/en/siem/guide/undefined/conf-map-ui.html" + href="https://www.elastic.co/guide/en/siem/guide/mocked-test-branch/conf-map-ui.html" target="_blank" > Map configuration help diff --git a/x-pack/legacy/plugins/siem/public/components/embeddables/__snapshots__/index_patterns_missing_prompt.test.tsx.snap b/x-pack/legacy/plugins/siem/public/components/embeddables/__snapshots__/index_patterns_missing_prompt.test.tsx.snap index 6794aab205703..2eefdf767dce1 100644 --- a/x-pack/legacy/plugins/siem/public/components/embeddables/__snapshots__/index_patterns_missing_prompt.test.tsx.snap +++ b/x-pack/legacy/plugins/siem/public/components/embeddables/__snapshots__/index_patterns_missing_prompt.test.tsx.snap @@ -21,7 +21,7 @@ exports[`IndexPatternsMissingPrompt renders correctly against snapshot 1`] = ` values={ Object { "beats": <a - href="https://www.elastic.coguide/en/beats/libbeat/current/getting-started.html" + href="https://www.elastic.co/guide/en/beats/libbeat/mocked-test-branch/getting-started.html" rel="noopener noreferrer" target="_blank" > diff --git a/x-pack/legacy/plugins/siem/public/components/embeddables/embeddable.test.tsx b/x-pack/legacy/plugins/siem/public/components/embeddables/embeddable.test.tsx index c0d70754e78bd..884d5bc348d6f 100644 --- a/x-pack/legacy/plugins/siem/public/components/embeddables/embeddable.test.tsx +++ b/x-pack/legacy/plugins/siem/public/components/embeddables/embeddable.test.tsx @@ -8,11 +8,8 @@ import { shallow } from 'enzyme'; import toJson from 'enzyme-to-json'; import React from 'react'; -import '../../mock/ui_settings'; import { Embeddable } from './embeddable'; -jest.mock('../../lib/settings/use_kibana_ui_setting'); - describe('Embeddable', () => { test('it renders', () => { const wrapper = shallow( diff --git a/x-pack/legacy/plugins/siem/public/components/embeddables/embeddable_header.test.tsx b/x-pack/legacy/plugins/siem/public/components/embeddables/embeddable_header.test.tsx index 6387de30aa265..aa247b69eb4eb 100644 --- a/x-pack/legacy/plugins/siem/public/components/embeddables/embeddable_header.test.tsx +++ b/x-pack/legacy/plugins/siem/public/components/embeddables/embeddable_header.test.tsx @@ -8,12 +8,9 @@ import { mount, shallow } from 'enzyme'; import toJson from 'enzyme-to-json'; import React from 'react'; -import '../../mock/ui_settings'; import { TestProviders } from '../../mock'; import { EmbeddableHeader } from './embeddable_header'; -jest.mock('../../lib/settings/use_kibana_ui_setting'); - describe('EmbeddableHeader', () => { test('it renders', () => { const wrapper = shallow(<EmbeddableHeader title="Test title" />); diff --git a/x-pack/legacy/plugins/siem/public/components/embeddables/embedded_map.test.tsx b/x-pack/legacy/plugins/siem/public/components/embeddables/embedded_map.test.tsx index 1ed1075542f71..007916595fd6a 100644 --- a/x-pack/legacy/plugins/siem/public/components/embeddables/embedded_map.test.tsx +++ b/x-pack/legacy/plugins/siem/public/components/embeddables/embedded_map.test.tsx @@ -7,10 +7,10 @@ import { shallow } from 'enzyme'; import toJson from 'enzyme-to-json'; import * as React from 'react'; + +import { useIndexPatterns } from '../../hooks/use_index_patterns'; import { EmbeddedMapComponent } from './embedded_map'; import { SetQuery } from './types'; -import { useKibanaCore } from '../../lib/compose/kibana_core'; -import { useIndexPatterns } from '../../hooks/use_index_patterns'; jest.mock('../search_bar', () => ({ siemFilterManager: { @@ -22,22 +22,7 @@ const mockUseIndexPatterns = useIndexPatterns as jest.Mock; jest.mock('../../hooks/use_index_patterns'); mockUseIndexPatterns.mockImplementation(() => [true, []]); -const mockUseKibanaCore = useKibanaCore as jest.Mock; -jest.mock('../../lib/compose/kibana_core'); -mockUseKibanaCore.mockImplementation(() => ({ - uiSettings: { - get$: () => 'world', - }, - injectedMetadata: { - getKibanaVersion: () => '8.0.0', - }, -})); - -jest.mock('../../lib/compose/kibana_plugins'); - -jest.mock('ui/vis/lib/timezone', () => ({ - timezoneProvider: () => () => 'America/New_York', -})); +jest.mock('../../lib/kibana'); describe('EmbeddedMapComponent', () => { let setQuery: SetQuery; diff --git a/x-pack/legacy/plugins/siem/public/components/embeddables/embedded_map.tsx b/x-pack/legacy/plugins/siem/public/components/embeddables/embedded_map.tsx index e33539af0bfe8..b39d43cc01b42 100644 --- a/x-pack/legacy/plugins/siem/public/components/embeddables/embedded_map.tsx +++ b/x-pack/legacy/plugins/siem/public/components/embeddables/embedded_map.tsx @@ -8,16 +8,12 @@ import { EuiLink, EuiText } from '@elastic/eui'; import React, { useEffect, useState } from 'react'; import { createPortalNode, InPortal } from 'react-reverse-portal'; import styled, { css } from 'styled-components'; -import { ELASTIC_WEBSITE_URL, DOC_LINK_VERSION } from 'ui/documentation_links'; import { EmbeddablePanel } from '../../../../../../../src/legacy/core_plugins/embeddable_api/public/np_ready/public'; import { start } from '../../../../../../../src/legacy/core_plugins/embeddable_api/public/np_ready/public/legacy'; import { DEFAULT_INDEX_KEY } from '../../../common/constants'; import { getIndexPatternTitleIdMapping } from '../../hooks/api/helpers'; import { useIndexPatterns } from '../../hooks/use_index_patterns'; -import { useKibanaCore } from '../../lib/compose/kibana_core'; -import { useKibanaPlugins } from '../../lib/compose/kibana_plugins'; -import { useKibanaUiSetting } from '../../lib/settings/use_kibana_ui_setting'; import { Loader } from '../loader'; import { useStateToaster } from '../toasters'; import { Embeddable } from './embeddable'; @@ -28,6 +24,7 @@ import { MapToolTip } from './map_tool_tip/map_tool_tip'; import * as i18n from './translations'; import { MapEmbeddable, SetQuery } from './types'; import { Query, esFilters } from '../../../../../../../src/plugins/data/public'; +import { useKibana, useUiSetting$ } from '../../lib/kibana'; import { SavedObjectFinderProps, SavedObjectFinderUi, @@ -96,7 +93,7 @@ export const EmbeddedMapComponent = ({ const [, dispatchToaster] = useStateToaster(); const [loadingKibanaIndexPatterns, kibanaIndexPatterns] = useIndexPatterns(); - const [siemDefaultIndices] = useKibanaUiSetting(DEFAULT_INDEX_KEY); + const [siemDefaultIndices] = useUiSetting$<string[]>(DEFAULT_INDEX_KEY); // This portalNode provided by react-reverse-portal allows us re-parent the MapToolTip within our // own component tree instead of the embeddables (default). This is necessary to have access to @@ -104,8 +101,7 @@ export const EmbeddedMapComponent = ({ // Search InPortal/OutPortal for implementation touch points const portalNode = React.useMemo(() => createPortalNode(), []); - const plugins = useKibanaPlugins(); - const core = useKibanaCore(); + const { services } = useKibana(); // Initial Load useEffect useEffect(() => { @@ -131,7 +127,7 @@ export const EmbeddedMapComponent = ({ endDate, setQuery, portalNode, - plugins.embeddable + services.embeddable ); if (isSubscribed) { setEmbeddable(embeddableObject); @@ -180,7 +176,11 @@ export const EmbeddedMapComponent = ({ }, [startDate, endDate]); const SavedObjectFinder = (props: SavedObjectFinderProps) => ( - <SavedObjectFinderUi {...props} savedObjects={core.savedObjects} uiSettings={core.uiSettings} /> + <SavedObjectFinderUi + {...props} + savedObjects={services.savedObjects} + uiSettings={services.uiSettings} + /> ); return isError ? null : ( @@ -188,7 +188,7 @@ export const EmbeddedMapComponent = ({ <EmbeddableHeader title={i18n.EMBEDDABLE_HEADER_TITLE}> <EuiText size="xs"> <EuiLink - href={`${ELASTIC_WEBSITE_URL}guide/en/siem/guide/${DOC_LINK_VERSION}/conf-map-ui.html`} + href={`${services.docLinks.ELASTIC_WEBSITE_URL}guide/en/siem/guide/${services.docLinks.DOC_LINK_VERSION}/conf-map-ui.html`} target="_blank" > {i18n.EMBEDDABLE_HEADER_HELP} @@ -205,12 +205,12 @@ export const EmbeddedMapComponent = ({ <EmbeddablePanel data-test-subj="embeddable-panel" embeddable={embeddable} - getActions={plugins.uiActions.getTriggerCompatibleActions} + getActions={services.uiActions.getTriggerCompatibleActions} getEmbeddableFactory={start.getEmbeddableFactory} getAllEmbeddableFactories={start.getEmbeddableFactories} - notifications={core.notifications} - overlays={core.overlays} - inspector={plugins.inspector} + notifications={services.notifications} + overlays={services.overlays} + inspector={services.inspector} SavedObjectFinder={SavedObjectFinder} /> ) : !isLoading && isIndexError ? ( diff --git a/x-pack/legacy/plugins/siem/public/components/embeddables/embedded_map_helpers.test.tsx b/x-pack/legacy/plugins/siem/public/components/embeddables/embedded_map_helpers.test.tsx index b4b2b98ddb8d6..4e5fcee439827 100644 --- a/x-pack/legacy/plugins/siem/public/components/embeddables/embedded_map_helpers.test.tsx +++ b/x-pack/legacy/plugins/siem/public/components/embeddables/embedded_map_helpers.test.tsx @@ -9,7 +9,6 @@ import { createUiNewPlatformMock } from 'ui/new_platform/__mocks__/helpers'; import { createPortalNode } from 'react-reverse-portal'; jest.mock('ui/new_platform'); -jest.mock('../../lib/settings/use_kibana_ui_setting'); jest.mock('uuid', () => { return { diff --git a/x-pack/legacy/plugins/siem/public/components/embeddables/index_patterns_missing_prompt.test.tsx b/x-pack/legacy/plugins/siem/public/components/embeddables/index_patterns_missing_prompt.test.tsx index d32b62900431c..d04329edff475 100644 --- a/x-pack/legacy/plugins/siem/public/components/embeddables/index_patterns_missing_prompt.test.tsx +++ b/x-pack/legacy/plugins/siem/public/components/embeddables/index_patterns_missing_prompt.test.tsx @@ -7,12 +7,10 @@ import { shallow } from 'enzyme'; import toJson from 'enzyme-to-json'; import * as React from 'react'; + import { IndexPatternsMissingPromptComponent } from './index_patterns_missing_prompt'; -jest.mock('ui/documentation_links', () => ({ - ELASTIC_WEBSITE_URL: 'https://www.elastic.co', - DOC_LINK_VERSION: 'current', -})); +jest.mock('../../lib/kibana'); describe('IndexPatternsMissingPrompt', () => { test('renders correctly against snapshot', () => { diff --git a/x-pack/legacy/plugins/siem/public/components/embeddables/index_patterns_missing_prompt.tsx b/x-pack/legacy/plugins/siem/public/components/embeddables/index_patterns_missing_prompt.tsx index 6533be49c3430..798e3d2c10f97 100644 --- a/x-pack/legacy/plugins/siem/public/components/embeddables/index_patterns_missing_prompt.tsx +++ b/x-pack/legacy/plugins/siem/public/components/embeddables/index_patterns_missing_prompt.tsx @@ -8,66 +8,70 @@ import { EuiButton, EuiCode, EuiEmptyPrompt } from '@elastic/eui'; import { FormattedMessage } from '@kbn/i18n/react'; import * as React from 'react'; import chrome from 'ui/chrome'; -import { ELASTIC_WEBSITE_URL, DOC_LINK_VERSION } from 'ui/documentation_links'; +import { useKibana } from '../../lib/kibana'; import * as i18n from './translations'; -export const IndexPatternsMissingPromptComponent = () => ( - <EuiEmptyPrompt - iconType="gisApp" - title={<h2>{i18n.ERROR_TITLE}</h2>} - titleSize="xs" - body={ - <> - <p> - <FormattedMessage - defaultMessage="To display map data, you must define SIEM indices ({defaultIndex}) and Kibana index patterns with identical names or glob patterns. When using {beats}, you can run the {setup} command on your hosts to automatically create the index patterns. For example: {example}." - id="xpack.siem.components.embeddables.indexPatternsMissingPrompt.errorDescription1" - values={{ - defaultIndex: ( - <a - href={`${chrome.getBasePath()}/app/kibana#/management/kibana/settings`} - rel="noopener noreferrer" - target="_blank" - > - {'siem:defaultIndex'} - </a> - ), - beats: ( - <a - href={`${ELASTIC_WEBSITE_URL}guide/en/beats/libbeat/${DOC_LINK_VERSION}/getting-started.html`} - rel="noopener noreferrer" - target="_blank" - > - {'beats'} - </a> - ), - setup: <EuiCode>{'setup'}</EuiCode>, - example: <EuiCode>{'./packetbeat setup'}</EuiCode>, - }} - /> - </p> +export const IndexPatternsMissingPromptComponent = () => { + const docLinks = useKibana().services.docLinks; - <p> - <FormattedMessage - defaultMessage="You can also configure index patterns manually in Kibana." - id="xpack.siem.components.embeddables.indexPatternsMissingPrompt.errorDescription2" - /> - </p> - </> - } - actions={ - <EuiButton - href={`${chrome.getBasePath()}/app/kibana#/management/kibana/index_patterns`} - color="primary" - target="_blank" - fill - > - {i18n.ERROR_BUTTON} - </EuiButton> - } - /> -); + return ( + <EuiEmptyPrompt + iconType="gisApp" + title={<h2>{i18n.ERROR_TITLE}</h2>} + titleSize="xs" + body={ + <> + <p> + <FormattedMessage + defaultMessage="To display map data, you must define SIEM indices ({defaultIndex}) and Kibana index patterns with identical names or glob patterns. When using {beats}, you can run the {setup} command on your hosts to automatically create the index patterns. For example: {example}." + id="xpack.siem.components.embeddables.indexPatternsMissingPrompt.errorDescription1" + values={{ + defaultIndex: ( + <a + href={`${chrome.getBasePath()}/app/kibana#/management/kibana/settings`} + rel="noopener noreferrer" + target="_blank" + > + {'siem:defaultIndex'} + </a> + ), + beats: ( + <a + href={`${docLinks.ELASTIC_WEBSITE_URL}guide/en/beats/libbeat/${docLinks.DOC_LINK_VERSION}/getting-started.html`} + rel="noopener noreferrer" + target="_blank" + > + {'beats'} + </a> + ), + setup: <EuiCode>{'setup'}</EuiCode>, + example: <EuiCode>{'./packetbeat setup'}</EuiCode>, + }} + /> + </p> + + <p> + <FormattedMessage + defaultMessage="You can also configure index patterns manually in Kibana." + id="xpack.siem.components.embeddables.indexPatternsMissingPrompt.errorDescription2" + /> + </p> + </> + } + actions={ + <EuiButton + href={`${chrome.getBasePath()}/app/kibana#/management/kibana/index_patterns`} + color="primary" + target="_blank" + fill + > + {i18n.ERROR_BUTTON} + </EuiButton> + } + /> + ); +}; IndexPatternsMissingPromptComponent.displayName = 'IndexPatternsMissingPromptComponent'; diff --git a/x-pack/legacy/plugins/siem/public/components/event_details/event_details.test.tsx b/x-pack/legacy/plugins/siem/public/components/event_details/event_details.test.tsx index f1e96392d6afc..d97da7797bb45 100644 --- a/x-pack/legacy/plugins/siem/public/components/event_details/event_details.test.tsx +++ b/x-pack/legacy/plugins/siem/public/components/event_details/event_details.test.tsx @@ -16,8 +16,6 @@ import { mockBrowserFields } from '../../containers/source/mock'; import { defaultHeaders } from '../../mock/header'; import { useMountAppended } from '../../utils/use_mount_appended'; -jest.mock('../../lib/settings/use_kibana_ui_setting'); - describe('EventDetails', () => { const mount = useMountAppended(); diff --git a/x-pack/legacy/plugins/siem/public/components/event_details/event_fields_browser.test.tsx b/x-pack/legacy/plugins/siem/public/components/event_details/event_fields_browser.test.tsx index 2c28ab8696f0e..25f95bfa1d383 100644 --- a/x-pack/legacy/plugins/siem/public/components/event_details/event_fields_browser.test.tsx +++ b/x-pack/legacy/plugins/siem/public/components/event_details/event_fields_browser.test.tsx @@ -14,7 +14,7 @@ import { mockBrowserFields } from '../../containers/source/mock'; import { defaultHeaders } from '../../mock/header'; import { useMountAppended } from '../../utils/use_mount_appended'; -jest.mock('../../lib/settings/use_kibana_ui_setting'); +jest.mock('../../lib/kibana'); describe('EventFieldsBrowser', () => { const mount = useMountAppended(); diff --git a/x-pack/legacy/plugins/siem/public/components/events_viewer/events_viewer.test.tsx b/x-pack/legacy/plugins/siem/public/components/events_viewer/events_viewer.test.tsx index 5ddf17bd77d74..b44d83c27a60d 100644 --- a/x-pack/legacy/plugins/siem/public/components/events_viewer/events_viewer.test.tsx +++ b/x-pack/legacy/plugins/siem/public/components/events_viewer/events_viewer.test.tsx @@ -8,25 +8,17 @@ import React from 'react'; import { MockedProvider } from 'react-apollo/test-utils'; import { mockIndexPattern, TestProviders } from '../../mock'; -import { mockUiSettings } from '../../mock/ui_settings'; import { wait } from '../../lib/helpers'; import { mockEventViewerResponse } from './mock'; import { StatefulEventsViewer } from '.'; import { defaultHeaders } from './default_headers'; -import { useKibanaCore } from '../../lib/compose/kibana_core'; import { useFetchIndexPatterns } from '../../containers/detection_engine/rules/fetch_index_patterns'; import { mockBrowserFields } from '../../containers/source/mock'; import { eventsDefaultModel } from './default_model'; import { useMountAppended } from '../../utils/use_mount_appended'; -jest.mock('../../lib/settings/use_kibana_ui_setting'); - -const mockUseKibanaCore = useKibanaCore as jest.Mock; -jest.mock('../../lib/compose/kibana_core'); -mockUseKibanaCore.mockImplementation(() => ({ - uiSettings: mockUiSettings, -})); +jest.mock('../../lib/kibana'); const mockUseFetchIndexPatterns: jest.Mock = useFetchIndexPatterns as jest.Mock; jest.mock('../../containers/detection_engine/rules/fetch_index_patterns'); diff --git a/x-pack/legacy/plugins/siem/public/components/events_viewer/events_viewer.tsx b/x-pack/legacy/plugins/siem/public/components/events_viewer/events_viewer.tsx index 9878194a17826..36d6604343345 100644 --- a/x-pack/legacy/plugins/siem/public/components/events_viewer/events_viewer.tsx +++ b/x-pack/legacy/plugins/siem/public/components/events_viewer/events_viewer.tsx @@ -12,7 +12,7 @@ import styled from 'styled-components'; import { BrowserFields } from '../../containers/source'; import { TimelineQuery } from '../../containers/timeline'; import { Direction } from '../../graphql/types'; -import { useKibanaCore } from '../../lib/compose/kibana_core'; +import { useKibana } from '../../lib/kibana'; import { KqlMode } from '../../store/timeline/model'; import { AutoSizer } from '../auto_sizer'; import { HeaderSection } from '../header_section'; @@ -91,9 +91,9 @@ export const EventsViewer = React.memo<Props>( utilityBar, }) => { const columnsHeader = isEmpty(columns) ? defaultHeaders : columns; - const core = useKibanaCore(); + const kibana = useKibana(); const combinedQueries = combineQueries({ - config: esQuery.getEsQueryConfig(core.uiSettings), + config: esQuery.getEsQueryConfig(kibana.services.uiSettings), dataProviders, indexPattern, browserFields, diff --git a/x-pack/legacy/plugins/siem/public/components/events_viewer/index.test.tsx b/x-pack/legacy/plugins/siem/public/components/events_viewer/index.test.tsx index e46153c18c2b5..27c3abf7f6824 100644 --- a/x-pack/legacy/plugins/siem/public/components/events_viewer/index.test.tsx +++ b/x-pack/legacy/plugins/siem/public/components/events_viewer/index.test.tsx @@ -7,10 +7,8 @@ import React from 'react'; import { MockedProvider } from 'react-apollo/test-utils'; -import { useKibanaCore } from '../../lib/compose/kibana_core'; import { wait } from '../../lib/helpers'; import { mockIndexPattern, TestProviders } from '../../mock'; -import { mockUiSettings } from '../../mock/ui_settings'; import { useMountAppended } from '../../utils/use_mount_appended'; import { mockEventViewerResponse } from './mock'; @@ -19,13 +17,7 @@ import { useFetchIndexPatterns } from '../../containers/detection_engine/rules/f import { mockBrowserFields } from '../../containers/source/mock'; import { eventsDefaultModel } from './default_model'; -jest.mock('../../lib/settings/use_kibana_ui_setting'); - -const mockUseKibanaCore = useKibanaCore as jest.Mock; -jest.mock('../../lib/compose/kibana_core'); -mockUseKibanaCore.mockImplementation(() => ({ - uiSettings: mockUiSettings, -})); +jest.mock('../../lib/kibana'); const mockUseFetchIndexPatterns: jest.Mock = useFetchIndexPatterns as jest.Mock; jest.mock('../../containers/detection_engine/rules/fetch_index_patterns'); diff --git a/x-pack/legacy/plugins/siem/public/components/events_viewer/index.tsx b/x-pack/legacy/plugins/siem/public/components/events_viewer/index.tsx index b614776cd90cf..265095ec593d2 100644 --- a/x-pack/legacy/plugins/siem/public/components/events_viewer/index.tsx +++ b/x-pack/legacy/plugins/siem/public/components/events_viewer/index.tsx @@ -8,7 +8,6 @@ import { isEqual } from 'lodash/fp'; import React, { useCallback, useEffect, useState, useMemo } from 'react'; import { connect } from 'react-redux'; import { ActionCreator } from 'typescript-fsa'; -import chrome from 'ui/chrome'; import { inputsModel, inputsSelectors, State, timelineSelectors } from '../../store'; import { inputsActions, timelineActions } from '../../store/actions'; import { KqlMode, SubsetTimelineModel, TimelineModel } from '../../store/timeline/model'; @@ -18,6 +17,7 @@ import { Sort } from '../timeline/body/sort'; import { OnChangeItemsPerPage } from '../timeline/events'; import { esFilters, Query } from '../../../../../../../src/plugins/data/public'; +import { useUiSetting } from '../../lib/kibana'; import { EventsViewer } from './events_viewer'; import { InputsModelId } from '../../store/inputs/constants'; import { useFetchIndexPatterns } from '../../containers/detection_engine/rules/fetch_index_patterns'; @@ -110,7 +110,7 @@ const StatefulEventsViewerComponent = React.memo<Props>( }) => { const [showInspect, setShowInspect] = useState(false); const [{ browserFields, indexPatterns }] = useFetchIndexPatterns( - defaultIndices ?? chrome.getUiSettingsClient().get(DEFAULT_INDEX_KEY) + defaultIndices ?? useUiSetting<string[]>(DEFAULT_INDEX_KEY) ); useEffect(() => { diff --git a/x-pack/legacy/plugins/siem/public/components/flyout/index.test.tsx b/x-pack/legacy/plugins/siem/public/components/flyout/index.test.tsx index 86a8952a10efa..be7e8fac70bf5 100644 --- a/x-pack/legacy/plugins/siem/public/components/flyout/index.test.tsx +++ b/x-pack/legacy/plugins/siem/public/components/flyout/index.test.tsx @@ -20,8 +20,6 @@ import { FlyoutButton } from './button'; const testFlyoutHeight = 980; const usersViewing = ['elastic']; -jest.mock('../../lib/settings/use_kibana_ui_setting'); - describe('Flyout', () => { const state: State = mockGlobalState; diff --git a/x-pack/legacy/plugins/siem/public/components/flyout/pane/index.test.tsx b/x-pack/legacy/plugins/siem/public/components/flyout/pane/index.test.tsx index 66e9bc700b3a1..246261035508b 100644 --- a/x-pack/legacy/plugins/siem/public/components/flyout/pane/index.test.tsx +++ b/x-pack/legacy/plugins/siem/public/components/flyout/pane/index.test.tsx @@ -8,26 +8,15 @@ import { mount, shallow } from 'enzyme'; import toJson from 'enzyme-to-json'; import * as React from 'react'; -import { flyoutHeaderHeight } from '../'; -import { useKibanaCore } from '../../../lib/compose/kibana_core'; import { TestProviders } from '../../../mock'; -import { mockUiSettings } from '../../../mock/ui_settings'; +import { flyoutHeaderHeight } from '..'; import { Pane } from '.'; const testFlyoutHeight = 980; const testWidth = 640; const usersViewing = ['elastic']; -const mockUseKibanaCore = useKibanaCore as jest.Mock; -jest.mock('ui/new_platform'); -jest.mock('../../../lib/compose/kibana_core'); -mockUseKibanaCore.mockImplementation(() => ({ - uiSettings: mockUiSettings, -})); - -jest.mock('ui/vis/lib/timezone', () => ({ - timezoneProvider: () => () => 'America/New_York', -})); +jest.mock('../../../lib/kibana'); describe('Pane', () => { test('renders correctly against snapshot', () => { diff --git a/x-pack/legacy/plugins/siem/public/components/formatted_bytes/index.test.tsx b/x-pack/legacy/plugins/siem/public/components/formatted_bytes/index.test.tsx index a517820361f9f..8c27a55d3a6b0 100644 --- a/x-pack/legacy/plugins/siem/public/components/formatted_bytes/index.test.tsx +++ b/x-pack/legacy/plugins/siem/public/components/formatted_bytes/index.test.tsx @@ -8,27 +8,25 @@ import { mount, shallow } from 'enzyme'; import toJson from 'enzyme-to-json'; import * as React from 'react'; -import { useKibanaUiSetting } from '../../lib/settings/use_kibana_ui_setting'; import { mockFrameworks, getMockKibanaUiSetting } from '../../mock'; +import { useUiSetting$ } from '../../lib/kibana'; import { PreferenceFormattedBytesComponent } from '.'; -const mockUseKibanaUiSetting: jest.Mock = useKibanaUiSetting as jest.Mock; -jest.mock('../../lib/settings/use_kibana_ui_setting', () => ({ - useKibanaUiSetting: jest.fn(), -})); +jest.mock('../../lib/kibana'); +const mockUseUiSetting$ = useUiSetting$ as jest.Mock; describe('formatted_bytes', () => { describe('PreferenceFormattedBytes', () => { describe('rendering', () => { beforeEach(() => { - mockUseKibanaUiSetting.mockClear(); + mockUseUiSetting$.mockClear(); }); const bytes = '2806422'; test('renders correctly against snapshot', () => { - mockUseKibanaUiSetting.mockImplementation( + mockUseUiSetting$.mockImplementation( getMockKibanaUiSetting(mockFrameworks.default_browser) ); const wrapper = shallow(<PreferenceFormattedBytesComponent value={bytes} />); @@ -36,13 +34,13 @@ describe('formatted_bytes', () => { }); test('it renders bytes to hardcoded format when no configuration exists', () => { - mockUseKibanaUiSetting.mockImplementation(() => [null]); + mockUseUiSetting$.mockImplementation(() => [null]); const wrapper = mount(<PreferenceFormattedBytesComponent value={bytes} />); expect(wrapper.text()).toEqual('2.7MB'); }); test('it renders bytes according to the default format', () => { - mockUseKibanaUiSetting.mockImplementation( + mockUseUiSetting$.mockImplementation( getMockKibanaUiSetting(mockFrameworks.default_browser) ); const wrapper = mount(<PreferenceFormattedBytesComponent value={bytes} />); @@ -50,7 +48,7 @@ describe('formatted_bytes', () => { }); test('it renders bytes supplied as a number according to the default format', () => { - mockUseKibanaUiSetting.mockImplementation( + mockUseUiSetting$.mockImplementation( getMockKibanaUiSetting(mockFrameworks.default_browser) ); const wrapper = mount(<PreferenceFormattedBytesComponent value={+bytes} />); @@ -58,9 +56,7 @@ describe('formatted_bytes', () => { }); test('it renders bytes according to new format', () => { - mockUseKibanaUiSetting.mockImplementation( - getMockKibanaUiSetting(mockFrameworks.bytes_short) - ); + mockUseUiSetting$.mockImplementation(getMockKibanaUiSetting(mockFrameworks.bytes_short)); const wrapper = mount(<PreferenceFormattedBytesComponent value={bytes} />); expect(wrapper.text()).toEqual('3MB'); }); diff --git a/x-pack/legacy/plugins/siem/public/components/formatted_bytes/index.tsx b/x-pack/legacy/plugins/siem/public/components/formatted_bytes/index.tsx index 408e8d7ad4d80..003ce0879b7b5 100644 --- a/x-pack/legacy/plugins/siem/public/components/formatted_bytes/index.tsx +++ b/x-pack/legacy/plugins/siem/public/components/formatted_bytes/index.tsx @@ -8,10 +8,10 @@ import * as React from 'react'; import numeral from '@elastic/numeral'; import { DEFAULT_BYTES_FORMAT } from '../../../common/constants'; -import { useKibanaUiSetting } from '../../lib/settings/use_kibana_ui_setting'; +import { useUiSetting$ } from '../../lib/kibana'; export const PreferenceFormattedBytesComponent = ({ value }: { value: string | number }) => { - const [bytesFormat] = useKibanaUiSetting(DEFAULT_BYTES_FORMAT); + const [bytesFormat] = useUiSetting$<string>(DEFAULT_BYTES_FORMAT); return ( <>{bytesFormat ? numeral(value).format(bytesFormat) : numeral(value).format('0,0.[0]b')}</> ); diff --git a/x-pack/legacy/plugins/siem/public/components/formatted_date/index.test.tsx b/x-pack/legacy/plugins/siem/public/components/formatted_date/index.test.tsx index df361a06d3805..dad1d5feb5c6e 100644 --- a/x-pack/legacy/plugins/siem/public/components/formatted_date/index.test.tsx +++ b/x-pack/legacy/plugins/siem/public/components/formatted_date/index.test.tsx @@ -9,24 +9,18 @@ import toJson from 'enzyme-to-json'; import moment from 'moment-timezone'; import * as React from 'react'; -import { useKibanaUiSetting } from '../../lib/settings/use_kibana_ui_setting'; +import { useUiSetting$ } from '../../lib/kibana'; import { mockFrameworks, TestProviders, MockFrameworks, getMockKibanaUiSetting } from '../../mock'; - -import { PreferenceFormattedDate, FormattedDate, FormattedRelativePreferenceDate } from '.'; import { getEmptyString, getEmptyValue } from '../empty_value'; +import { PreferenceFormattedDate, FormattedDate, FormattedRelativePreferenceDate } from '.'; -const mockUseKibanaUiSetting: jest.Mock = useKibanaUiSetting as jest.Mock; -jest.mock('../../lib/settings/use_kibana_ui_setting', () => ({ - useKibanaUiSetting: jest.fn(), -})); +jest.mock('../../lib/kibana'); +const mockUseUiSetting$ = useUiSetting$ as jest.Mock; describe('formatted_date', () => { describe('PreferenceFormattedDate', () => { describe('rendering', () => { - beforeEach(() => { - mockUseKibanaUiSetting.mockClear(); - }); const isoDateString = '2019-02-25T22:27:05.000Z'; const isoDate = new Date(isoDateString); const configFormattedDateString = (dateString: string, config: MockFrameworks): string => @@ -38,21 +32,19 @@ describe('formatted_date', () => { .format(config.dateFormat); test('renders correctly against snapshot', () => { - mockUseKibanaUiSetting.mockImplementation(() => [null]); + mockUseUiSetting$.mockImplementation(() => [null]); const wrapper = mount(<PreferenceFormattedDate value={isoDate} />); expect(toJson(wrapper)).toMatchSnapshot(); }); test('it renders the UTC ISO8601 date string supplied when no configuration exists', () => { - mockUseKibanaUiSetting.mockImplementation(() => [null]); + mockUseUiSetting$.mockImplementation(() => [null]); const wrapper = mount(<PreferenceFormattedDate value={isoDate} />); expect(wrapper.text()).toEqual(isoDateString); }); test('it renders the UTC ISO8601 date supplied when the default configuration exists', () => { - mockUseKibanaUiSetting.mockImplementation( - getMockKibanaUiSetting(mockFrameworks.default_UTC) - ); + mockUseUiSetting$.mockImplementation(getMockKibanaUiSetting(mockFrameworks.default_UTC)); const wrapper = mount(<PreferenceFormattedDate value={isoDate} />); expect(wrapper.text()).toEqual( @@ -61,7 +53,7 @@ describe('formatted_date', () => { }); test('it renders the correct tz when the default browser configuration exists', () => { - mockUseKibanaUiSetting.mockImplementation( + mockUseUiSetting$.mockImplementation( getMockKibanaUiSetting(mockFrameworks.default_browser) ); const wrapper = mount(<PreferenceFormattedDate value={isoDate} />); @@ -71,9 +63,7 @@ describe('formatted_date', () => { }); test('it renders the correct tz when a non-UTC configuration exists', () => { - mockUseKibanaUiSetting.mockImplementation( - getMockKibanaUiSetting(mockFrameworks.default_MT) - ); + mockUseUiSetting$.mockImplementation(getMockKibanaUiSetting(mockFrameworks.default_MT)); const wrapper = mount(<PreferenceFormattedDate value={isoDate} />); expect(wrapper.text()).toEqual( configFormattedDateString(isoDateString, mockFrameworks.default_MT) @@ -84,30 +74,20 @@ describe('formatted_date', () => { describe('FormattedDate', () => { describe('rendering', () => { - beforeEach(() => { - mockUseKibanaUiSetting.mockClear(); - }); - test('it renders against a numeric epoch', () => { - mockUseKibanaUiSetting.mockImplementation( - getMockKibanaUiSetting(mockFrameworks.default_UTC) - ); + mockUseUiSetting$.mockImplementation(getMockKibanaUiSetting(mockFrameworks.default_UTC)); const wrapper = mount(<FormattedDate fieldName="@timestamp" value={1559079339000} />); expect(wrapper.text()).toEqual('May 28, 2019 @ 21:35:39.000'); }); test('it renders against a string epoch', () => { - mockUseKibanaUiSetting.mockImplementation( - getMockKibanaUiSetting(mockFrameworks.default_UTC) - ); + mockUseUiSetting$.mockImplementation(getMockKibanaUiSetting(mockFrameworks.default_UTC)); const wrapper = mount(<FormattedDate fieldName="@timestamp" value={'1559079339000'} />); expect(wrapper.text()).toEqual('May 28, 2019 @ 21:35:39.000'); }); test('it renders against a ISO string', () => { - mockUseKibanaUiSetting.mockImplementation( - getMockKibanaUiSetting(mockFrameworks.default_UTC) - ); + mockUseUiSetting$.mockImplementation(getMockKibanaUiSetting(mockFrameworks.default_UTC)); const wrapper = mount( <FormattedDate fieldName="@timestamp" value={'2019-05-28T22:04:49.957Z'} /> ); @@ -115,9 +95,7 @@ describe('formatted_date', () => { }); test('it renders against an empty string as an empty string placeholder', () => { - mockUseKibanaUiSetting.mockImplementation( - getMockKibanaUiSetting(mockFrameworks.default_UTC) - ); + mockUseUiSetting$.mockImplementation(getMockKibanaUiSetting(mockFrameworks.default_UTC)); const wrapper = mount( <TestProviders> <FormattedDate fieldName="@timestamp" value={''} /> @@ -127,9 +105,7 @@ describe('formatted_date', () => { }); test('it renders against an null as a EMPTY_VALUE', () => { - mockUseKibanaUiSetting.mockImplementation( - getMockKibanaUiSetting(mockFrameworks.default_UTC) - ); + mockUseUiSetting$.mockImplementation(getMockKibanaUiSetting(mockFrameworks.default_UTC)); const wrapper = mount( <TestProviders> <FormattedDate fieldName="@timestamp" value={null} /> @@ -139,9 +115,7 @@ describe('formatted_date', () => { }); test('it renders against an undefined as a EMPTY_VALUE', () => { - mockUseKibanaUiSetting.mockImplementation( - getMockKibanaUiSetting(mockFrameworks.default_UTC) - ); + mockUseUiSetting$.mockImplementation(getMockKibanaUiSetting(mockFrameworks.default_UTC)); const wrapper = mount( <TestProviders> <FormattedDate fieldName="@timestamp" value={undefined} /> @@ -151,9 +125,7 @@ describe('formatted_date', () => { }); test('it renders against an invalid date time as just the string its self', () => { - mockUseKibanaUiSetting.mockImplementation( - getMockKibanaUiSetting(mockFrameworks.default_UTC) - ); + mockUseUiSetting$.mockImplementation(getMockKibanaUiSetting(mockFrameworks.default_UTC)); const wrapper = mount( <TestProviders> <FormattedDate fieldName="@timestamp" value={'Rebecca Evan Braden'} /> diff --git a/x-pack/legacy/plugins/siem/public/components/formatted_date/index.tsx b/x-pack/legacy/plugins/siem/public/components/formatted_date/index.tsx index 37bf3653f3b62..19e8ec3f95d26 100644 --- a/x-pack/legacy/plugins/siem/public/components/formatted_date/index.tsx +++ b/x-pack/legacy/plugins/siem/public/components/formatted_date/index.tsx @@ -8,20 +8,21 @@ import moment from 'moment-timezone'; import * as React from 'react'; import { FormattedRelative } from '@kbn/i18n/react'; +import { useUiSetting$ } from '../../lib/kibana'; + import { DEFAULT_DATE_FORMAT, DEFAULT_DATE_FORMAT_TZ, DEFAULT_TIMEZONE_BROWSER, } from '../../../common/constants'; -import { useKibanaUiSetting } from '../../lib/settings/use_kibana_ui_setting'; import { getOrEmptyTagFromValue } from '../empty_value'; import { LocalizedDateTooltip } from '../localized_date_tooltip'; import { getMaybeDate } from './maybe_date'; export const PreferenceFormattedDate = React.memo<{ value: Date }>(({ value }) => { - const [dateFormat] = useKibanaUiSetting(DEFAULT_DATE_FORMAT); - const [dateFormatTz] = useKibanaUiSetting(DEFAULT_DATE_FORMAT_TZ); - const [timezone] = useKibanaUiSetting(DEFAULT_TIMEZONE_BROWSER); + const [dateFormat] = useUiSetting$<string>(DEFAULT_DATE_FORMAT); + const [dateFormatTz] = useUiSetting$<string>(DEFAULT_DATE_FORMAT_TZ); + const [timezone] = useUiSetting$<string>(DEFAULT_TIMEZONE_BROWSER); return ( <> diff --git a/x-pack/legacy/plugins/siem/public/components/header_global/index.test.tsx b/x-pack/legacy/plugins/siem/public/components/header_global/index.test.tsx index b3eb599af9407..a45bed87829bf 100644 --- a/x-pack/legacy/plugins/siem/public/components/header_global/index.test.tsx +++ b/x-pack/legacy/plugins/siem/public/components/header_global/index.test.tsx @@ -9,10 +9,9 @@ import toJson from 'enzyme-to-json'; import React from 'react'; import '../../mock/match_media'; -import '../../mock/ui_settings'; import { HeaderGlobal } from './index'; -jest.mock('../../lib/settings/use_kibana_ui_setting'); +jest.mock('ui/new_platform'); // Test will fail because we will to need to mock some core services to make the test work // For now let's forget about SiemSearchBar diff --git a/x-pack/legacy/plugins/siem/public/components/header_page/index.test.tsx b/x-pack/legacy/plugins/siem/public/components/header_page/index.test.tsx index 5644a344f91d6..633ff90524de6 100644 --- a/x-pack/legacy/plugins/siem/public/components/header_page/index.test.tsx +++ b/x-pack/legacy/plugins/siem/public/components/header_page/index.test.tsx @@ -10,12 +10,9 @@ import toJson from 'enzyme-to-json'; import React from 'react'; import { TestProviders } from '../../mock'; -import '../../mock/ui_settings'; import { HeaderPage } from './index'; import { useMountAppended } from '../../utils/use_mount_appended'; -jest.mock('../../lib/settings/use_kibana_ui_setting'); - describe('HeaderPage', () => { const mount = useMountAppended(); diff --git a/x-pack/legacy/plugins/siem/public/components/header_section/index.test.tsx b/x-pack/legacy/plugins/siem/public/components/header_section/index.test.tsx index 8606758c68d2c..fbd8642c01fac 100644 --- a/x-pack/legacy/plugins/siem/public/components/header_section/index.test.tsx +++ b/x-pack/legacy/plugins/siem/public/components/header_section/index.test.tsx @@ -10,11 +10,8 @@ import toJson from 'enzyme-to-json'; import React from 'react'; import { TestProviders } from '../../mock'; -import '../../mock/ui_settings'; import { HeaderSection } from './index'; -jest.mock('../../lib/settings/use_kibana_ui_setting'); - describe('HeaderSection', () => { test('it renders', () => { const wrapper = shallow(<HeaderSection title="Test title" />); diff --git a/x-pack/legacy/plugins/siem/public/components/last_event_time/index.test.tsx b/x-pack/legacy/plugins/siem/public/components/last_event_time/index.test.tsx index e2ada4682fdec..dcecc636d9f0f 100644 --- a/x-pack/legacy/plugins/siem/public/components/last_event_time/index.test.tsx +++ b/x-pack/legacy/plugins/siem/public/components/last_event_time/index.test.tsx @@ -13,7 +13,6 @@ import { mockLastEventTimeQuery } from '../../containers/events/last_event_time/ import { useMountAppended } from '../../utils/use_mount_appended'; import { useLastEventTimeQuery } from '../../containers/events/last_event_time'; import { TestProviders } from '../../mock'; -import '../../mock/ui_settings'; import { LastEventTime } from '.'; diff --git a/x-pack/legacy/plugins/siem/public/components/link_icon/index.test.tsx b/x-pack/legacy/plugins/siem/public/components/link_icon/index.test.tsx index 7f9133a0de7c0..87761a51a431f 100644 --- a/x-pack/legacy/plugins/siem/public/components/link_icon/index.test.tsx +++ b/x-pack/legacy/plugins/siem/public/components/link_icon/index.test.tsx @@ -9,11 +9,8 @@ import toJson from 'enzyme-to-json'; import React from 'react'; import { TestProviders } from '../../mock'; -import '../../mock/ui_settings'; import { LinkIcon } from './index'; -jest.mock('../../lib/settings/use_kibana_ui_setting'); - describe('LinkIcon', () => { test('it renders', () => { const wrapper = shallow( diff --git a/x-pack/legacy/plugins/siem/public/components/matrix_histogram/index.test.tsx b/x-pack/legacy/plugins/siem/public/components/matrix_histogram/index.test.tsx index bdd8a0c544ed8..87d4e072e4299 100644 --- a/x-pack/legacy/plugins/siem/public/components/matrix_histogram/index.test.tsx +++ b/x-pack/legacy/plugins/siem/public/components/matrix_histogram/index.test.tsx @@ -9,12 +9,7 @@ import * as React from 'react'; import { MatrixHistogram } from '.'; -jest.mock('@elastic/eui', () => { - return { - EuiPanel: (children: JSX.Element) => <>{children}</>, - EuiLoadingContent: () => <div className="euiLoadingContent" />, - }; -}); +jest.mock('../../lib/kibana'); jest.mock('../loader', () => { return { @@ -22,10 +17,6 @@ jest.mock('../loader', () => { }; }); -jest.mock('../../lib/settings/use_kibana_ui_setting', () => { - return { useKibanaUiSetting: () => [false] }; -}); - jest.mock('../header_section', () => { return { HeaderSection: () => <div className="headerSection" />, diff --git a/x-pack/legacy/plugins/siem/public/components/matrix_histogram/index.tsx b/x-pack/legacy/plugins/siem/public/components/matrix_histogram/index.tsx index e1ccfd79a89a0..c29b5282e13af 100644 --- a/x-pack/legacy/plugins/siem/public/components/matrix_histogram/index.tsx +++ b/x-pack/legacy/plugins/siem/public/components/matrix_histogram/index.tsx @@ -14,7 +14,7 @@ import { BarChart } from '../charts/barchart'; import { HeaderSection } from '../header_section'; import { ChartSeriesData } from '../charts/common'; import { DEFAULT_DARK_MODE } from '../../../common/constants'; -import { useKibanaUiSetting } from '../../lib/settings/use_kibana_ui_setting'; +import { useUiSetting$ } from '../../lib/kibana'; import { Loader } from '../loader'; import { Panel } from '../panel'; import { getBarchartConfigs, getCustomChartData } from './utils'; @@ -45,7 +45,7 @@ export const MatrixHistogram = ({ showLegend, }); const [showInspect, setShowInspect] = useState(false); - const [darkMode] = useKibanaUiSetting(DEFAULT_DARK_MODE); + const [darkMode] = useUiSetting$<boolean>(DEFAULT_DARK_MODE); const [loadingInitial, setLoadingInitial] = useState(false); const barChartData: ChartSeriesData[] = getCustomChartData(data, mapping); diff --git a/x-pack/legacy/plugins/siem/public/components/ml/anomaly/use_anomalies_table_data.ts b/x-pack/legacy/plugins/siem/public/components/ml/anomaly/use_anomalies_table_data.ts index 130c326339b1b..bce99c943c7a5 100644 --- a/x-pack/legacy/plugins/siem/public/components/ml/anomaly/use_anomalies_table_data.ts +++ b/x-pack/legacy/plugins/siem/public/components/ml/anomaly/use_anomalies_table_data.ts @@ -14,7 +14,7 @@ import { useStateToaster } from '../../toasters'; import { errorToToaster } from '../api/error_to_toaster'; import * as i18n from './translations'; -import { useKibanaUiSetting } from '../../../lib/settings/use_kibana_ui_setting'; +import { useUiSetting$ } from '../../../lib/kibana'; import { DEFAULT_ANOMALY_SCORE, DEFAULT_TIMEZONE_BROWSER, @@ -67,9 +67,9 @@ export const useAnomaliesTableData = ({ const capabilities = useContext(MlCapabilitiesContext); const userPermissions = hasMlUserPermissions(capabilities); const [, dispatchToaster] = useStateToaster(); - const [timezone] = useKibanaUiSetting(DEFAULT_TIMEZONE_BROWSER); - const [anomalyScore] = useKibanaUiSetting(DEFAULT_ANOMALY_SCORE); - const [kbnVersion] = useKibanaUiSetting(DEFAULT_KBN_VERSION); + const [timezone] = useUiSetting$<string>(DEFAULT_TIMEZONE_BROWSER); + const [anomalyScore] = useUiSetting$<number>(DEFAULT_ANOMALY_SCORE); + const [kbnVersion] = useUiSetting$<string>(DEFAULT_KBN_VERSION); const siemJobIds = siemJobs.filter(job => job.isInstalled).map(job => job.id); diff --git a/x-pack/legacy/plugins/siem/public/components/ml/permissions/ml_capabilities_provider.tsx b/x-pack/legacy/plugins/siem/public/components/ml/permissions/ml_capabilities_provider.tsx index 352f39a75ded1..b8d6908df464e 100644 --- a/x-pack/legacy/plugins/siem/public/components/ml/permissions/ml_capabilities_provider.tsx +++ b/x-pack/legacy/plugins/siem/public/components/ml/permissions/ml_capabilities_provider.tsx @@ -11,7 +11,7 @@ import { getMlCapabilities } from '../api/get_ml_capabilities'; import { emptyMlCapabilities } from '../empty_ml_capabilities'; import { errorToToaster } from '../api/error_to_toaster'; import { useStateToaster } from '../../toasters'; -import { useKibanaUiSetting } from '../../../lib/settings/use_kibana_ui_setting'; +import { useUiSetting$ } from '../../../lib/kibana'; import { DEFAULT_KBN_VERSION } from '../../../../common/constants'; import * as i18n from './translations'; @@ -36,7 +36,7 @@ export const MlCapabilitiesProvider = React.memo<{ children: JSX.Element }>(({ c emptyMlCapabilitiesProvider ); const [, dispatchToaster] = useStateToaster(); - const [kbnVersion] = useKibanaUiSetting(DEFAULT_KBN_VERSION); + const [kbnVersion] = useUiSetting$<string>(DEFAULT_KBN_VERSION); useEffect(() => { let isSubscribed = true; diff --git a/x-pack/legacy/plugins/siem/public/components/ml/score/anomaly_score.test.tsx b/x-pack/legacy/plugins/siem/public/components/ml/score/anomaly_score.test.tsx index f7d9052b19a2f..cf24d6c02a138 100644 --- a/x-pack/legacy/plugins/siem/public/components/ml/score/anomaly_score.test.tsx +++ b/x-pack/legacy/plugins/siem/public/components/ml/score/anomaly_score.test.tsx @@ -17,8 +17,6 @@ import { Anomalies } from '../types'; const endDate: number = new Date('3000-01-01T00:00:00.000Z').valueOf(); const narrowDateRange = jest.fn(); -jest.mock('../../../lib/settings/use_kibana_ui_setting'); - describe('anomaly_scores', () => { let anomalies: Anomalies = cloneDeep(mockAnomalies); const mount = useMountAppended(); diff --git a/x-pack/legacy/plugins/siem/public/components/ml/score/anomaly_scores.test.tsx b/x-pack/legacy/plugins/siem/public/components/ml/score/anomaly_scores.test.tsx index f01df38138456..759e84e36f4ac 100644 --- a/x-pack/legacy/plugins/siem/public/components/ml/score/anomaly_scores.test.tsx +++ b/x-pack/legacy/plugins/siem/public/components/ml/score/anomaly_scores.test.tsx @@ -18,8 +18,6 @@ import { useMountAppended } from '../../../utils/use_mount_appended'; const endDate: number = new Date('3000-01-01T00:00:00.000Z').valueOf(); const narrowDateRange = jest.fn(); -jest.mock('../../../lib/settings/use_kibana_ui_setting'); - describe('anomaly_scores', () => { let anomalies: Anomalies = cloneDeep(mockAnomalies); const mount = useMountAppended(); diff --git a/x-pack/legacy/plugins/siem/public/components/ml/score/create_descriptions_list.test.tsx b/x-pack/legacy/plugins/siem/public/components/ml/score/create_descriptions_list.test.tsx index d55c6972d5cac..f00fb62d74ac3 100644 --- a/x-pack/legacy/plugins/siem/public/components/ml/score/create_descriptions_list.test.tsx +++ b/x-pack/legacy/plugins/siem/public/components/ml/score/create_descriptions_list.test.tsx @@ -12,7 +12,7 @@ import { createDescriptionList } from './create_description_list'; import { EuiDescriptionList } from '@elastic/eui'; import { Anomaly } from '../types'; -jest.mock('../../../lib/settings/use_kibana_ui_setting'); +jest.mock('../../../lib/kibana'); const endDate: number = new Date('3000-01-01T00:00:00.000Z').valueOf(); diff --git a/x-pack/legacy/plugins/siem/public/components/ml_popover/hooks/use_siem_jobs.tsx b/x-pack/legacy/plugins/siem/public/components/ml_popover/hooks/use_siem_jobs.tsx index 0bef34a7edc44..f9d110d711d07 100644 --- a/x-pack/legacy/plugins/siem/public/components/ml_popover/hooks/use_siem_jobs.tsx +++ b/x-pack/legacy/plugins/siem/public/components/ml_popover/hooks/use_siem_jobs.tsx @@ -12,7 +12,7 @@ import { hasMlUserPermissions } from '../../ml/permissions/has_ml_user_permissio import { MlCapabilitiesContext } from '../../ml/permissions/ml_capabilities_provider'; import { useStateToaster } from '../../toasters'; import { errorToToaster } from '../../ml/api/error_to_toaster'; -import { useKibanaUiSetting } from '../../../lib/settings/use_kibana_ui_setting'; +import { useUiSetting$ } from '../../../lib/kibana'; import { DEFAULT_INDEX_KEY, DEFAULT_KBN_VERSION } from '../../../../common/constants'; import * as i18n from './translations'; @@ -33,8 +33,8 @@ export const useSiemJobs = (refetchData: boolean): Return => { const [loading, setLoading] = useState(true); const capabilities = useContext(MlCapabilitiesContext); const userPermissions = hasMlUserPermissions(capabilities); - const [siemDefaultIndex] = useKibanaUiSetting(DEFAULT_INDEX_KEY); - const [kbnVersion] = useKibanaUiSetting(DEFAULT_KBN_VERSION); + const [siemDefaultIndex] = useUiSetting$<string[]>(DEFAULT_INDEX_KEY); + const [kbnVersion] = useUiSetting$<string>(DEFAULT_KBN_VERSION); const [, dispatchToaster] = useStateToaster(); useEffect(() => { diff --git a/x-pack/legacy/plugins/siem/public/components/ml_popover/ml_popover.test.tsx b/x-pack/legacy/plugins/siem/public/components/ml_popover/ml_popover.test.tsx index 1a8360fe82c58..987c63be3f7be 100644 --- a/x-pack/legacy/plugins/siem/public/components/ml_popover/ml_popover.test.tsx +++ b/x-pack/legacy/plugins/siem/public/components/ml_popover/ml_popover.test.tsx @@ -9,7 +9,8 @@ import { mountWithIntl } from 'test_utils/enzyme_helpers'; import { MlPopover } from './ml_popover'; -jest.mock('../../lib/settings/use_kibana_ui_setting'); +jest.mock('ui/new_platform'); +jest.mock('../../lib/kibana'); jest.mock('../ml/permissions/has_ml_admin_permissions', () => ({ hasMlAdminPermissions: () => true, diff --git a/x-pack/legacy/plugins/siem/public/components/ml_popover/ml_popover.tsx b/x-pack/legacy/plugins/siem/public/components/ml_popover/ml_popover.tsx index 0b33ab83d2a47..c34ed51d22994 100644 --- a/x-pack/legacy/plugins/siem/public/components/ml_popover/ml_popover.tsx +++ b/x-pack/legacy/plugins/siem/public/components/ml_popover/ml_popover.tsx @@ -9,10 +9,9 @@ import { FormattedMessage } from '@kbn/i18n/react'; import moment from 'moment'; import React, { useContext, useReducer, useState } from 'react'; import styled from 'styled-components'; -import { DOC_LINK_VERSION, ELASTIC_WEBSITE_URL } from 'ui/documentation_links'; import { DEFAULT_KBN_VERSION } from '../../../common/constants'; -import { useKibanaUiSetting } from '../../lib/settings/use_kibana_ui_setting'; +import { useKibana, useUiSetting$ } from '../../lib/kibana'; import { METRIC_TYPE, TELEMETRY_EVENT, trackUiAction as track } from '../../lib/track_usage'; import { errorToToaster } from '../ml/api/error_to_toaster'; import { hasMlAdminPermissions } from '../ml/permissions/has_ml_admin_permissions'; @@ -98,10 +97,11 @@ export const MlPopover = React.memo(() => { const [isPopoverOpen, setIsPopoverOpen] = useState(false); const [filterProperties, setFilterProperties] = useState(defaultFilterProps); - const [kbnVersion] = useKibanaUiSetting(DEFAULT_KBN_VERSION); + const [kbnVersion] = useUiSetting$<string>(DEFAULT_KBN_VERSION); const [isLoadingSiemJobs, siemJobs] = useSiemJobs(refreshToggle); const [, dispatchToaster] = useStateToaster(); const capabilities = useContext(MlCapabilitiesContext); + const docLinks = useKibana().services.docLinks; // Enable/Disable Job & Datafeed -- passed to JobsTable for use as callback on JobSwitch const enableDatafeed = async (job: SiemJob, latestTimestampMs: number, enable: boolean) => { @@ -226,7 +226,7 @@ export const MlPopover = React.memo(() => { values={{ mlDocs: ( <a - href={`${ELASTIC_WEBSITE_URL}guide/en/siem/guide/${DOC_LINK_VERSION}/machine-learning.html`} + href={`${docLinks.ELASTIC_WEBSITE_URL}guide/en/siem/guide/${docLinks.DOC_LINK_VERSION}/machine-learning.html`} rel="noopener noreferrer" target="_blank" > diff --git a/x-pack/legacy/plugins/siem/public/components/ml_popover/types.ts b/x-pack/legacy/plugins/siem/public/components/ml_popover/types.ts index 88481e140cb03..f8794c1963961 100644 --- a/x-pack/legacy/plugins/siem/public/components/ml_popover/types.ts +++ b/x-pack/legacy/plugins/siem/public/components/ml_popover/types.ts @@ -13,7 +13,7 @@ export interface Group { } export interface CheckRecognizerProps { - indexPatternName: string; + indexPatternName: string[]; kbnVersion: string; signal: AbortSignal; } diff --git a/x-pack/legacy/plugins/siem/public/components/netflow/index.test.tsx b/x-pack/legacy/plugins/siem/public/components/netflow/index.test.tsx index 2d8c201e41462..22531983b2399 100644 --- a/x-pack/legacy/plugins/siem/public/components/netflow/index.test.tsx +++ b/x-pack/legacy/plugins/siem/public/components/netflow/index.test.tsx @@ -57,8 +57,6 @@ import { } from '../source_destination/field_names'; import { useMountAppended } from '../../utils/use_mount_appended'; -jest.mock('../../lib/settings/use_kibana_ui_setting'); - const getNetflowInstance = () => ( <Netflow contextId="test" diff --git a/x-pack/legacy/plugins/siem/public/components/open_timeline/index.test.tsx b/x-pack/legacy/plugins/siem/public/components/open_timeline/index.test.tsx index 0f5aafe661d0e..c9f52d9d204ae 100644 --- a/x-pack/legacy/plugins/siem/public/components/open_timeline/index.test.tsx +++ b/x-pack/legacy/plugins/siem/public/components/open_timeline/index.test.tsx @@ -19,7 +19,7 @@ import { StatefulOpenTimeline } from '.'; import { NotePreviews } from './note_previews'; import { OPEN_TIMELINE_CLASS_NAME } from './helpers'; -jest.mock('../../lib/settings/use_kibana_ui_setting'); +jest.mock('../../lib/kibana'); describe('StatefulOpenTimeline', () => { const theme = () => ({ eui: euiDarkVars, darkMode: true }); diff --git a/x-pack/legacy/plugins/siem/public/components/open_timeline/open_timeline.test.tsx b/x-pack/legacy/plugins/siem/public/components/open_timeline/open_timeline.test.tsx index 690e8877b5019..dbc7199aac725 100644 --- a/x-pack/legacy/plugins/siem/public/components/open_timeline/open_timeline.test.tsx +++ b/x-pack/legacy/plugins/siem/public/components/open_timeline/open_timeline.test.tsx @@ -17,7 +17,7 @@ import { mockTimelineResults } from '../../mock/timeline_results'; import { OpenTimeline } from './open_timeline'; import { DEFAULT_SORT_DIRECTION, DEFAULT_SORT_FIELD } from './constants'; -jest.mock('../../lib/settings/use_kibana_ui_setting'); +jest.mock('../../lib/kibana'); describe('OpenTimeline', () => { const theme = () => ({ eui: euiDarkVars, darkMode: true }); diff --git a/x-pack/legacy/plugins/siem/public/components/open_timeline/open_timeline_modal/index.test.tsx b/x-pack/legacy/plugins/siem/public/components/open_timeline/open_timeline_modal/index.test.tsx index 03383a6cb6612..e3dc6d974b5e0 100644 --- a/x-pack/legacy/plugins/siem/public/components/open_timeline/open_timeline_modal/index.test.tsx +++ b/x-pack/legacy/plugins/siem/public/components/open_timeline/open_timeline_modal/index.test.tsx @@ -16,7 +16,7 @@ import { mockOpenTimelineQueryResults } from '../../../mock/timeline_results'; import { OpenTimelineModal } from '.'; -jest.mock('../../../lib/settings/use_kibana_ui_setting'); +jest.mock('../../../lib/kibana'); jest.mock('../../../utils/apollo_context', () => ({ useApolloClient: () => ({}), })); diff --git a/x-pack/legacy/plugins/siem/public/components/open_timeline/open_timeline_modal/open_timeline_modal_body.test.tsx b/x-pack/legacy/plugins/siem/public/components/open_timeline/open_timeline_modal/open_timeline_modal_body.test.tsx index 4237caf8f3c51..a5abb42c2e3b6 100644 --- a/x-pack/legacy/plugins/siem/public/components/open_timeline/open_timeline_modal/open_timeline_modal_body.test.tsx +++ b/x-pack/legacy/plugins/siem/public/components/open_timeline/open_timeline_modal/open_timeline_modal_body.test.tsx @@ -17,7 +17,7 @@ import { mockTimelineResults } from '../../../mock/timeline_results'; import { OpenTimelineModalBody } from './open_timeline_modal_body'; import { DEFAULT_SORT_DIRECTION, DEFAULT_SORT_FIELD } from '../constants'; -jest.mock('../../../lib/settings/use_kibana_ui_setting'); +jest.mock('../../../lib/kibana'); describe('OpenTimelineModal', () => { const theme = () => ({ eui: euiDarkVars, darkMode: true }); diff --git a/x-pack/legacy/plugins/siem/public/components/open_timeline/open_timeline_modal/open_timeline_modal_button.test.tsx b/x-pack/legacy/plugins/siem/public/components/open_timeline/open_timeline_modal/open_timeline_modal_button.test.tsx index a5e436c73f93b..9a70fd476e89e 100644 --- a/x-pack/legacy/plugins/siem/public/components/open_timeline/open_timeline_modal/open_timeline_modal_button.test.tsx +++ b/x-pack/legacy/plugins/siem/public/components/open_timeline/open_timeline_modal/open_timeline_modal_button.test.tsx @@ -17,8 +17,6 @@ import * as i18n from '../translations'; import { OpenTimelineModalButton } from './open_timeline_modal_button'; -jest.mock('../../../lib/settings/use_kibana_ui_setting'); - describe('OpenTimelineModalButton', () => { const theme = () => ({ eui: euiDarkVars, darkMode: true }); diff --git a/x-pack/legacy/plugins/siem/public/components/open_timeline/timelines_table/actions_columns.test.tsx b/x-pack/legacy/plugins/siem/public/components/open_timeline/timelines_table/actions_columns.test.tsx index 30a02a974ba92..749ba8672abea 100644 --- a/x-pack/legacy/plugins/siem/public/components/open_timeline/timelines_table/actions_columns.test.tsx +++ b/x-pack/legacy/plugins/siem/public/components/open_timeline/timelines_table/actions_columns.test.tsx @@ -17,7 +17,7 @@ import { OpenTimelineResult } from '../types'; import { TimelinesTable } from '.'; import { DEFAULT_SORT_DIRECTION, DEFAULT_SORT_FIELD } from '../constants'; -jest.mock('../../../lib/settings/use_kibana_ui_setting'); +jest.mock('../../../lib/kibana'); describe('#getActionsColumns', () => { const theme = () => ({ eui: euiDarkVars, darkMode: true }); diff --git a/x-pack/legacy/plugins/siem/public/components/open_timeline/timelines_table/common_columns.test.tsx b/x-pack/legacy/plugins/siem/public/components/open_timeline/timelines_table/common_columns.test.tsx index ae68019c2fe69..fa08df1df4785 100644 --- a/x-pack/legacy/plugins/siem/public/components/open_timeline/timelines_table/common_columns.test.tsx +++ b/x-pack/legacy/plugins/siem/public/components/open_timeline/timelines_table/common_columns.test.tsx @@ -21,7 +21,7 @@ import { TimelinesTable } from '.'; import * as i18n from '../translations'; import { DEFAULT_SORT_DIRECTION, DEFAULT_SORT_FIELD } from '../constants'; -jest.mock('../../../lib/settings/use_kibana_ui_setting'); +jest.mock('../../../lib/kibana'); describe('#getCommonColumns', () => { const theme = () => ({ eui: euiDarkVars, darkMode: true }); diff --git a/x-pack/legacy/plugins/siem/public/components/open_timeline/timelines_table/extended_columns.test.tsx b/x-pack/legacy/plugins/siem/public/components/open_timeline/timelines_table/extended_columns.test.tsx index bf5adc8aca533..13362e0f43a28 100644 --- a/x-pack/legacy/plugins/siem/public/components/open_timeline/timelines_table/extended_columns.test.tsx +++ b/x-pack/legacy/plugins/siem/public/components/open_timeline/timelines_table/extended_columns.test.tsx @@ -20,7 +20,7 @@ import { TimelinesTable } from '.'; import * as i18n from '../translations'; import { DEFAULT_SORT_DIRECTION, DEFAULT_SORT_FIELD } from '../constants'; -jest.mock('../../../lib/settings/use_kibana_ui_setting'); +jest.mock('../../../lib/kibana'); describe('#getExtendedColumns', () => { const theme = () => ({ eui: euiDarkVars, darkMode: true }); diff --git a/x-pack/legacy/plugins/siem/public/components/open_timeline/timelines_table/icon_header_columns.test.tsx b/x-pack/legacy/plugins/siem/public/components/open_timeline/timelines_table/icon_header_columns.test.tsx index e5047662eef67..b6048b85eea75 100644 --- a/x-pack/legacy/plugins/siem/public/components/open_timeline/timelines_table/icon_header_columns.test.tsx +++ b/x-pack/legacy/plugins/siem/public/components/open_timeline/timelines_table/icon_header_columns.test.tsx @@ -16,7 +16,7 @@ import { TimelinesTable } from '.'; import { OpenTimelineResult } from '../types'; import { DEFAULT_SORT_DIRECTION, DEFAULT_SORT_FIELD } from '../constants'; -jest.mock('../../../lib/settings/use_kibana_ui_setting'); +jest.mock('../../../lib/kibana'); describe('#getActionsColumns', () => { const theme = () => ({ eui: euiDarkVars, darkMode: true }); diff --git a/x-pack/legacy/plugins/siem/public/components/open_timeline/timelines_table/index.test.tsx b/x-pack/legacy/plugins/siem/public/components/open_timeline/timelines_table/index.test.tsx index 6cf56ad6a770f..d75863d1ccb8b 100644 --- a/x-pack/legacy/plugins/siem/public/components/open_timeline/timelines_table/index.test.tsx +++ b/x-pack/legacy/plugins/siem/public/components/open_timeline/timelines_table/index.test.tsx @@ -18,7 +18,7 @@ import { TimelinesTable, TimelinesTableProps } from '.'; import * as i18n from '../translations'; import { DEFAULT_SORT_DIRECTION, DEFAULT_SORT_FIELD } from '../constants'; -jest.mock('../../../lib/settings/use_kibana_ui_setting'); +jest.mock('../../../lib/kibana'); describe('TimelinesTable', () => { const theme = () => ({ eui: euiDarkVars, darkMode: true }); diff --git a/x-pack/legacy/plugins/siem/public/components/page/detection_engine/histogram_signals/index.test.tsx b/x-pack/legacy/plugins/siem/public/components/page/detection_engine/histogram_signals/index.test.tsx index c0d0feca5d53c..ad1d80a761854 100644 --- a/x-pack/legacy/plugins/siem/public/components/page/detection_engine/histogram_signals/index.test.tsx +++ b/x-pack/legacy/plugins/siem/public/components/page/detection_engine/histogram_signals/index.test.tsx @@ -8,12 +8,9 @@ import { shallow } from 'enzyme'; import toJson from 'enzyme-to-json'; import React from 'react'; -import '../../../../mock/ui_settings'; import { TestProviders } from '../../../../mock'; import { HistogramSignals } from './index'; -jest.mock('../../../../lib/settings/use_kibana_ui_setting'); - describe('HistogramSignals', () => { test('it renders', () => { const wrapper = shallow( diff --git a/x-pack/legacy/plugins/siem/public/components/page/hosts/first_last_seen_host/index.test.tsx b/x-pack/legacy/plugins/siem/public/components/page/hosts/first_last_seen_host/index.test.tsx index 6c3ab04849236..35c1eded18f15 100644 --- a/x-pack/legacy/plugins/siem/public/components/page/hosts/first_last_seen_host/index.test.tsx +++ b/x-pack/legacy/plugins/siem/public/components/page/hosts/first_last_seen_host/index.test.tsx @@ -12,26 +12,25 @@ import { render, act } from '@testing-library/react'; import { mockFirstLastSeenHostQuery } from '../../../../containers/hosts/first_last_seen/mock'; import { wait } from '../../../../lib/helpers'; import { TestProviders } from '../../../../mock'; -import '../../../../mock/ui_settings'; import { FirstLastSeenHost, FirstLastSeenHostType } from '.'; -jest.mock('../../../../lib/settings/use_kibana_ui_setting'); - -// Suppress warnings about "react-apollo" until we migrate to apollo@3 -/* eslint-disable no-console */ -const originalError = console.error; -beforeAll(() => { - console.error = jest.fn(); -}); -afterAll(() => { - console.error = originalError; -}); +jest.mock('../../../../lib/kibana'); describe('FirstLastSeen Component', () => { const firstSeen = 'Apr 8, 2019 @ 16:09:40.692'; const lastSeen = 'Apr 8, 2019 @ 18:35:45.064'; + // Suppress warnings about "react-apollo" until we migrate to apollo@3 + /* eslint-disable no-console */ + const originalError = console.error; + beforeAll(() => { + console.error = jest.fn(); + }); + afterAll(() => { + console.error = originalError; + }); + test('Loading', async () => { const { container } = render( <TestProviders> diff --git a/x-pack/legacy/plugins/siem/public/components/page/hosts/host_overview/index.tsx b/x-pack/legacy/plugins/siem/public/components/page/hosts/host_overview/index.tsx index 437d14edeb5c8..9e3f8f91d5cf7 100644 --- a/x-pack/legacy/plugins/siem/public/components/page/hosts/host_overview/index.tsx +++ b/x-pack/legacy/plugins/siem/public/components/page/hosts/host_overview/index.tsx @@ -12,7 +12,7 @@ import React, { useContext, useState, useCallback } from 'react'; import { DEFAULT_DARK_MODE } from '../../../../../common/constants'; import { DescriptionList } from '../../../../../common/utility_types'; -import { useKibanaUiSetting } from '../../../../lib/settings/use_kibana_ui_setting'; +import { useUiSetting$ } from '../../../../lib/kibana'; import { getEmptyTagValue } from '../../../empty_value'; import { DefaultFieldRenderer, hostIdRenderer } from '../../../field_renderers/field_renderers'; import { InspectButton } from '../../../inspect'; @@ -59,7 +59,7 @@ export const HostOverview = React.memo<HostSummaryProps>( const [showInspect, setShowInspect] = useState(false); const capabilities = useContext(MlCapabilitiesContext); const userPermissions = hasMlUserPermissions(capabilities); - const [darkMode] = useKibanaUiSetting(DEFAULT_DARK_MODE); + const [darkMode] = useUiSetting$<boolean>(DEFAULT_DARK_MODE); const getDefaultRenderer = (fieldName: string, fieldData: HostItem) => ( <DefaultFieldRenderer diff --git a/x-pack/legacy/plugins/siem/public/components/page/hosts/hosts_table/index.test.tsx b/x-pack/legacy/plugins/siem/public/components/page/hosts/hosts_table/index.test.tsx index 8c27f86d78884..4728925eb741a 100644 --- a/x-pack/legacy/plugins/siem/public/components/page/hosts/hosts_table/index.test.tsx +++ b/x-pack/legacy/plugins/siem/public/components/page/hosts/hosts_table/index.test.tsx @@ -17,19 +17,11 @@ import { TestProviders, } from '../../../../mock'; import { useMountAppended } from '../../../../utils/use_mount_appended'; -import { mockUiSettings } from '../../../../mock/ui_settings'; -import { useKibanaCore } from '../../../../lib/compose/kibana_core'; import { createStore, hostsModel, State } from '../../../../store'; import { HostsTableType } from '../../../../store/hosts/model'; import { HostsTable } from './index'; import { mockData } from './mock'; -const mockUseKibanaCore = useKibanaCore as jest.Mock; -jest.mock('../../../../lib/compose/kibana_core'); -mockUseKibanaCore.mockImplementation(() => ({ - uiSettings: mockUiSettings, -})); - // Test will fail because we will to need to mock some core services to make the test work // For now let's forget about SiemSearchBar and QueryBar jest.mock('../../../search_bar', () => ({ diff --git a/x-pack/legacy/plugins/siem/public/components/page/network/ip_overview/index.tsx b/x-pack/legacy/plugins/siem/public/components/page/network/ip_overview/index.tsx index 8cb55f0d0fb58..0c4e594399517 100644 --- a/x-pack/legacy/plugins/siem/public/components/page/network/ip_overview/index.tsx +++ b/x-pack/legacy/plugins/siem/public/components/page/network/ip_overview/index.tsx @@ -11,7 +11,7 @@ import React, { useContext, useState, useCallback } from 'react'; import { DEFAULT_DARK_MODE } from '../../../../../common/constants'; import { DescriptionList } from '../../../../../common/utility_types'; -import { useKibanaUiSetting } from '../../../../lib/settings/use_kibana_ui_setting'; +import { useUiSetting$ } from '../../../../lib/kibana'; import { FlowTarget, IpOverviewData, Overview } from '../../../../graphql/types'; import { networkModel } from '../../../../store'; import { getEmptyTagValue } from '../../../empty_value'; @@ -74,7 +74,7 @@ export const IpOverview = React.memo<IpOverviewProps>( const [showInspect, setShowInspect] = useState(false); const capabilities = useContext(MlCapabilitiesContext); const userPermissions = hasMlUserPermissions(capabilities); - const [darkMode] = useKibanaUiSetting(DEFAULT_DARK_MODE); + const [darkMode] = useUiSetting$<boolean>(DEFAULT_DARK_MODE); const typeData: Overview = data[flowTarget]!; const column: DescriptionList[] = [ { diff --git a/x-pack/legacy/plugins/siem/public/components/page/network/network_dns_table/index.test.tsx b/x-pack/legacy/plugins/siem/public/components/page/network/network_dns_table/index.test.tsx index 0537b95ca6cf7..b88653bcadde8 100644 --- a/x-pack/legacy/plugins/siem/public/components/page/network/network_dns_table/index.test.tsx +++ b/x-pack/legacy/plugins/siem/public/components/page/network/network_dns_table/index.test.tsx @@ -18,8 +18,6 @@ import { useMountAppended } from '../../../../utils/use_mount_appended'; import { NetworkDnsTable } from '.'; import { mockData } from './mock'; -jest.mock('../../../../lib/settings/use_kibana_ui_setting'); - describe('NetworkTopNFlow Table Component', () => { const loadPage = jest.fn(); const state: State = mockGlobalState; diff --git a/x-pack/legacy/plugins/siem/public/components/page/network/network_http_table/index.test.tsx b/x-pack/legacy/plugins/siem/public/components/page/network/network_http_table/index.test.tsx index 50d64817f81f8..81e0c7fad7b39 100644 --- a/x-pack/legacy/plugins/siem/public/components/page/network/network_http_table/index.test.tsx +++ b/x-pack/legacy/plugins/siem/public/components/page/network/network_http_table/index.test.tsx @@ -18,8 +18,6 @@ import { createStore, networkModel, State } from '../../../../store'; import { NetworkHttpTable } from '.'; import { mockData } from './mock'; -jest.mock('../../../../lib/settings/use_kibana_ui_setting'); - describe('NetworkHttp Table Component', () => { const loadPage = jest.fn(); const state: State = mockGlobalState; diff --git a/x-pack/legacy/plugins/siem/public/components/page/network/network_top_countries_table/index.test.tsx b/x-pack/legacy/plugins/siem/public/components/page/network/network_top_countries_table/index.test.tsx index eb4179a040431..8fd245b077243 100644 --- a/x-pack/legacy/plugins/siem/public/components/page/network/network_top_countries_table/index.test.tsx +++ b/x-pack/legacy/plugins/siem/public/components/page/network/network_top_countries_table/index.test.tsx @@ -24,7 +24,6 @@ import { createStore, networkModel, State } from '../../../../store'; import { NetworkTopCountriesTable } from '.'; import { mockData } from './mock'; -jest.mock('../../../../lib/settings/use_kibana_ui_setting'); describe('NetworkTopCountries Table Component', () => { const loadPage = jest.fn(); const state: State = mockGlobalState; diff --git a/x-pack/legacy/plugins/siem/public/components/page/network/network_top_n_flow_table/index.test.tsx b/x-pack/legacy/plugins/siem/public/components/page/network/network_top_n_flow_table/index.test.tsx index 3157847b32376..5c4aa862283f2 100644 --- a/x-pack/legacy/plugins/siem/public/components/page/network/network_top_n_flow_table/index.test.tsx +++ b/x-pack/legacy/plugins/siem/public/components/page/network/network_top_n_flow_table/index.test.tsx @@ -24,8 +24,6 @@ import { createStore, networkModel, State } from '../../../../store'; import { NetworkTopNFlowTable } from '.'; import { mockData } from './mock'; -jest.mock('../../../../lib/settings/use_kibana_ui_setting'); - describe('NetworkTopNFlow Table Component', () => { const loadPage = jest.fn(); const state: State = mockGlobalState; diff --git a/x-pack/legacy/plugins/siem/public/components/page/network/tls_table/index.test.tsx b/x-pack/legacy/plugins/siem/public/components/page/network/tls_table/index.test.tsx index 4313c455a0df1..920d1cd8210e5 100644 --- a/x-pack/legacy/plugins/siem/public/components/page/network/tls_table/index.test.tsx +++ b/x-pack/legacy/plugins/siem/public/components/page/network/tls_table/index.test.tsx @@ -18,8 +18,6 @@ import { createStore, networkModel, State } from '../../../../store'; import { TlsTable } from '.'; import { mockTlsData } from './mock'; -jest.mock('../../../../lib/settings/use_kibana_ui_setting'); - describe('Tls Table Component', () => { const loadPage = jest.fn(); const state: State = mockGlobalState; diff --git a/x-pack/legacy/plugins/siem/public/components/page/network/users_table/index.test.tsx b/x-pack/legacy/plugins/siem/public/components/page/network/users_table/index.test.tsx index d6b9ec24de0aa..d01923f01543f 100644 --- a/x-pack/legacy/plugins/siem/public/components/page/network/users_table/index.test.tsx +++ b/x-pack/legacy/plugins/siem/public/components/page/network/users_table/index.test.tsx @@ -19,8 +19,6 @@ import { createStore, networkModel, State } from '../../../../store'; import { UsersTable } from '.'; import { mockUsersData } from './mock'; -jest.mock('../../../../lib/settings/use_kibana_ui_setting'); - jest.mock('../../../search_bar', () => ({ siemFilterManager: { addFilters: jest.fn(), diff --git a/x-pack/legacy/plugins/siem/public/components/progress_inline/index.test.tsx b/x-pack/legacy/plugins/siem/public/components/progress_inline/index.test.tsx index d99a4201c4c72..8ecc50402cef1 100644 --- a/x-pack/legacy/plugins/siem/public/components/progress_inline/index.test.tsx +++ b/x-pack/legacy/plugins/siem/public/components/progress_inline/index.test.tsx @@ -8,11 +8,8 @@ import { shallow } from 'enzyme'; import toJson from 'enzyme-to-json'; import React from 'react'; -import '../../mock/ui_settings'; import { ProgressInline } from './index'; -jest.mock('../../lib/settings/use_kibana_ui_setting'); - describe('ProgressInline', () => { test('it renders', () => { const wrapper = shallow( diff --git a/x-pack/legacy/plugins/siem/public/components/query_bar/index.test.tsx b/x-pack/legacy/plugins/siem/public/components/query_bar/index.test.tsx index 10b769e2a791c..e403963cbbe20 100644 --- a/x-pack/legacy/plugins/siem/public/components/query_bar/index.test.tsx +++ b/x-pack/legacy/plugins/siem/public/components/query_bar/index.test.tsx @@ -7,23 +7,16 @@ import { mount } from 'enzyme'; import React from 'react'; -import { FilterManager, SearchBar } from '../../../../../../../src/plugins/data/public'; -import { uiSettingsServiceMock } from '../../../../../../../src/core/public/ui_settings/ui_settings_service.mock'; -import { useKibanaCore } from '../../lib/compose/kibana_core'; import { TestProviders, mockIndexPattern } from '../../mock'; -import { QueryBar, QueryBarComponentProps } from '.'; +import { createKibanaCoreStartMock } from '../../mock/kibana_core'; import { DEFAULT_FROM, DEFAULT_TO } from '../../../common/constants'; -import { mockUiSettings } from '../../mock/ui_settings'; +import { FilterManager, SearchBar } from '../../../../../../../src/plugins/data/public'; +import { QueryBar, QueryBarComponentProps } from '.'; +import { createKibanaContextProviderMock } from '../../mock/kibana_react'; -jest.mock('ui/new_platform'); +jest.mock('../../lib/kibana'); -const mockUseKibanaCore = useKibanaCore as jest.Mock; -const mockUiSettingsForFilterManager = uiSettingsServiceMock.createSetupContract(); -jest.mock('../../lib/compose/kibana_core'); -mockUseKibanaCore.mockImplementation(() => ({ - uiSettings: mockUiSettings, - savedObjects: {}, -})); +const mockUiSettingsForFilterManager = createKibanaCoreStartMock().uiSettings; describe('QueryBar ', () => { // We are doing that because we need to wrapped this component with redux @@ -196,9 +189,13 @@ describe('QueryBar ', () => { describe('#onQueryChange', () => { test(' is the only reference that changed when filterQueryDraft props get updated', () => { + const KibanaWithStorageProvider = createKibanaContextProviderMock(); + const Proxy = (props: QueryBarComponentProps) => ( <TestProviders> - <QueryBar {...props} /> + <KibanaWithStorageProvider services={{ storage: { get: jest.fn() } }}> + <QueryBar {...props} /> + </KibanaWithStorageProvider> </TestProviders> ); diff --git a/x-pack/legacy/plugins/siem/public/components/query_bar/index.tsx b/x-pack/legacy/plugins/siem/public/components/query_bar/index.tsx index 9f706790bec67..b2843348cc2e3 100644 --- a/x-pack/legacy/plugins/siem/public/components/query_bar/index.tsx +++ b/x-pack/legacy/plugins/siem/public/components/query_bar/index.tsx @@ -6,7 +6,6 @@ import { isEqual } from 'lodash/fp'; import React, { memo, useState, useEffect, useMemo, useCallback } from 'react'; -import { IndexPattern } from 'ui/index_patterns'; import { esFilters, @@ -118,7 +117,7 @@ export const QueryBar = memo<QueryBarComponentProps>( ); const CustomButton = <>{null}</>; - const indexPatterns = useMemo(() => [indexPattern as IndexPattern], [indexPattern]); + const indexPatterns = useMemo(() => [indexPattern], [indexPattern]); const searchBarProps = savedQuery != null ? { savedQuery } : {}; diff --git a/x-pack/legacy/plugins/siem/public/components/search_bar/index.tsx b/x-pack/legacy/plugins/siem/public/components/search_bar/index.tsx index 3d02cff7b72e8..089bade4a4144 100644 --- a/x-pack/legacy/plugins/siem/public/components/search_bar/index.tsx +++ b/x-pack/legacy/plugins/siem/public/components/search_bar/index.tsx @@ -10,7 +10,6 @@ import { connect } from 'react-redux'; import { Dispatch } from 'redux'; import { Subscription } from 'rxjs'; import styled from 'styled-components'; -import { IndexPattern } from 'ui/index_patterns'; import { IIndexPattern } from 'src/plugins/data/public'; import { SavedQuery } from 'src/legacy/core_plugins/data/public'; @@ -254,7 +253,7 @@ const SearchBarComponent = memo<SiemSearchBarProps & SiemSearchBarRedux & SiemSe subscriptions.unsubscribe(); }; }, []); - const indexPatterns = useMemo(() => [indexPattern as IndexPattern], [indexPattern]); + const indexPatterns = useMemo(() => [indexPattern], [indexPattern]); return ( <SearchBarContainer data-test-subj={`${id}DatePicker`}> <SearchBar diff --git a/x-pack/legacy/plugins/siem/public/components/source_destination/index.test.tsx b/x-pack/legacy/plugins/siem/public/components/source_destination/index.test.tsx index 1679795951a56..c437994145d63 100644 --- a/x-pack/legacy/plugins/siem/public/components/source_destination/index.test.tsx +++ b/x-pack/legacy/plugins/siem/public/components/source_destination/index.test.tsx @@ -47,8 +47,6 @@ import { NETWORK_TRANSPORT_FIELD_NAME, } from './field_names'; -jest.mock('../../lib/settings/use_kibana_ui_setting'); - const getSourceDestinationInstance = () => ( <SourceDestination contextId="test" diff --git a/x-pack/legacy/plugins/siem/public/components/source_destination/source_destination_ip.test.tsx b/x-pack/legacy/plugins/siem/public/components/source_destination/source_destination_ip.test.tsx index d42d34c85a4da..463373b5894f1 100644 --- a/x-pack/legacy/plugins/siem/public/components/source_destination/source_destination_ip.test.tsx +++ b/x-pack/legacy/plugins/siem/public/components/source_destination/source_destination_ip.test.tsx @@ -35,8 +35,6 @@ import { SOURCE_GEO_REGION_NAME_FIELD_NAME, } from './geo_fields'; -jest.mock('../../lib/settings/use_kibana_ui_setting'); - describe('SourceDestinationIp', () => { const mount = useMountAppended(); diff --git a/x-pack/legacy/plugins/siem/public/components/subtitle/index.test.tsx b/x-pack/legacy/plugins/siem/public/components/subtitle/index.test.tsx index b54f3133de472..3424c05f32d63 100644 --- a/x-pack/legacy/plugins/siem/public/components/subtitle/index.test.tsx +++ b/x-pack/legacy/plugins/siem/public/components/subtitle/index.test.tsx @@ -8,12 +8,9 @@ import { mount, shallow } from 'enzyme'; import toJson from 'enzyme-to-json'; import React from 'react'; -import '../../mock/ui_settings'; import { TestProviders } from '../../mock'; import { Subtitle } from './index'; -jest.mock('../../lib/settings/use_kibana_ui_setting'); - describe('Subtitle', () => { test('it renders', () => { const wrapper = shallow(<Subtitle items="Test subtitle" />); diff --git a/x-pack/legacy/plugins/siem/public/components/super_date_picker/index.test.tsx b/x-pack/legacy/plugins/siem/public/components/super_date_picker/index.test.tsx index 011e2ddcdbde7..013104da7c612 100644 --- a/x-pack/legacy/plugins/siem/public/components/super_date_picker/index.test.tsx +++ b/x-pack/legacy/plugins/siem/public/components/super_date_picker/index.test.tsx @@ -8,13 +8,69 @@ import { mount } from 'enzyme'; import * as React from 'react'; import { Provider as ReduxStoreProvider } from 'react-redux'; +import { useUiSetting$ } from '../../lib/kibana'; import { apolloClientObservable, mockGlobalState } from '../../mock'; +import { createUseUiSetting$Mock } from '../../mock/kibana_react'; import { createStore, State } from '../../store'; import { SuperDatePicker, makeMapStateToProps } from '.'; import { cloneDeep } from 'lodash/fp'; - -jest.mock('../../lib/settings/use_kibana_ui_setting'); +import { DEFAULT_TIMEPICKER_QUICK_RANGES } from '../../../common/constants'; + +jest.mock('../../lib/kibana'); +const mockUseUiSetting$ = useUiSetting$ as jest.Mock; +const timepickerRanges = [ + { + from: 'now/d', + to: 'now/d', + display: 'Today', + }, + { + from: 'now/w', + to: 'now/w', + display: 'This week', + }, + { + from: 'now-15m', + to: 'now', + display: 'Last 15 minutes', + }, + { + from: 'now-30m', + to: 'now', + display: 'Last 30 minutes', + }, + { + from: 'now-1h', + to: 'now', + display: 'Last 1 hour', + }, + { + from: 'now-24h', + to: 'now', + display: 'Last 24 hours', + }, + { + from: 'now-7d', + to: 'now', + display: 'Last 7 days', + }, + { + from: 'now-30d', + to: 'now', + display: 'Last 30 days', + }, + { + from: 'now-90d', + to: 'now', + display: 'Last 90 days', + }, + { + from: 'now-1y', + to: 'now', + display: 'Last 1 year', + }, +]; describe('SIEM Super Date Picker', () => { describe('#SuperDatePicker', () => { @@ -24,6 +80,13 @@ describe('SIEM Super Date Picker', () => { beforeEach(() => { jest.clearAllMocks(); store = createStore(state, apolloClientObservable); + mockUseUiSetting$.mockImplementation((key, defaultValue) => { + const useUiSetting$Mock = createUseUiSetting$Mock(); + + return key === DEFAULT_TIMEPICKER_QUICK_RANGES + ? [timepickerRanges, jest.fn()] + : useUiSetting$Mock(key, defaultValue); + }); }); describe('Pick Relative Date', () => { diff --git a/x-pack/legacy/plugins/siem/public/components/super_date_picker/index.tsx b/x-pack/legacy/plugins/siem/public/components/super_date_picker/index.tsx index a2e190da0f7bc..0877906c721ce 100644 --- a/x-pack/legacy/plugins/siem/public/components/super_date_picker/index.tsx +++ b/x-pack/legacy/plugins/siem/public/components/super_date_picker/index.tsx @@ -18,7 +18,7 @@ import { connect } from 'react-redux'; import { Dispatch } from 'redux'; import { DEFAULT_TIMEPICKER_QUICK_RANGES } from '../../../common/constants'; -import { useKibanaUiSetting } from '../../lib/settings/use_kibana_ui_setting'; +import { useUiSetting$ } from '../../lib/kibana'; import { inputsModel, State } from '../../store'; import { inputsActions, timelineActions } from '../../store/actions'; import { InputsModelId } from '../../store/inputs/constants'; @@ -38,6 +38,12 @@ import { InputsRange, Policy } from '../../store/inputs/model'; const MAX_RECENTLY_USED_RANGES = 9; +interface Range { + from: string; + to: string; + display: string; +} + interface SuperDatePickerStateRedux { duration: number; end: number; @@ -196,10 +202,10 @@ export const SuperDatePickerComponent = React.memo<SuperDatePickerProps>( const endDate = kind === 'relative' ? toStr : new Date(end).toISOString(); const startDate = kind === 'relative' ? fromStr : new Date(start).toISOString(); - const [quickRanges] = useKibanaUiSetting(DEFAULT_TIMEPICKER_QUICK_RANGES); + const [quickRanges] = useUiSetting$<Range[]>(DEFAULT_TIMEPICKER_QUICK_RANGES); const commonlyUsedRanges = isEmpty(quickRanges) ? [] - : quickRanges.map(({ from, to, display }: { from: string; to: string; display: string }) => ({ + : quickRanges.map(({ from, to, display }) => ({ start: from, end: to, label: display, diff --git a/x-pack/legacy/plugins/siem/public/components/timeline/body/index.test.tsx b/x-pack/legacy/plugins/siem/public/components/timeline/body/index.test.tsx index a4ed5571bb0da..cdd828fb21d5c 100644 --- a/x-pack/legacy/plugins/siem/public/components/timeline/body/index.test.tsx +++ b/x-pack/legacy/plugins/siem/public/components/timeline/body/index.test.tsx @@ -17,8 +17,6 @@ import { Sort } from './sort'; import { wait } from '../../../lib/helpers'; import { useMountAppended } from '../../../utils/use_mount_appended'; -jest.mock('../../../lib/settings/use_kibana_ui_setting'); - const testBodyHeight = 700; const mockGetNotesByIds = (eventId: string[]) => []; const mockSort: Sort = { diff --git a/x-pack/legacy/plugins/siem/public/components/timeline/body/renderers/formatted_field.test.tsx b/x-pack/legacy/plugins/siem/public/components/timeline/body/renderers/formatted_field.test.tsx index 3f27abfd2176c..5c54e5be3374c 100644 --- a/x-pack/legacy/plugins/siem/public/components/timeline/body/renderers/formatted_field.test.tsx +++ b/x-pack/legacy/plugins/siem/public/components/timeline/body/renderers/formatted_field.test.tsx @@ -18,7 +18,7 @@ import { useMountAppended } from '../../../../utils/use_mount_appended'; import { FormattedFieldValue } from './formatted_field'; import { HOST_NAME_FIELD_NAME } from './constants'; -jest.mock('../../../../lib/settings/use_kibana_ui_setting'); +jest.mock('../../../../lib/kibana'); describe('Events', () => { const theme = () => ({ eui: euiDarkVars, darkMode: true }); diff --git a/x-pack/legacy/plugins/siem/public/components/timeline/body/renderers/netflow/netflow_row_renderer.test.tsx b/x-pack/legacy/plugins/siem/public/components/timeline/body/renderers/netflow/netflow_row_renderer.test.tsx index 9f73d86dec402..6ba8f3f28dae8 100644 --- a/x-pack/legacy/plugins/siem/public/components/timeline/body/renderers/netflow/netflow_row_renderer.test.tsx +++ b/x-pack/legacy/plugins/siem/public/components/timeline/body/renderers/netflow/netflow_row_renderer.test.tsx @@ -25,8 +25,6 @@ export const justIdAndTimestamp: Ecs = { timestamp: '2018-11-12T19:03:25.936Z', }; -jest.mock('../../../../../lib/settings/use_kibana_ui_setting'); - describe('netflowRowRenderer', () => { const mount = useMountAppended(); diff --git a/x-pack/legacy/plugins/siem/public/components/timeline/body/renderers/plain_column_renderer.test.tsx b/x-pack/legacy/plugins/siem/public/components/timeline/body/renderers/plain_column_renderer.test.tsx index 96865fd928216..008885b5264c8 100644 --- a/x-pack/legacy/plugins/siem/public/components/timeline/body/renderers/plain_column_renderer.test.tsx +++ b/x-pack/legacy/plugins/siem/public/components/timeline/body/renderers/plain_column_renderer.test.tsx @@ -18,7 +18,7 @@ import { useMountAppended } from '../../../../utils/use_mount_appended'; import { plainColumnRenderer } from './plain_column_renderer'; import { getValues, deleteItemIdx, findItem } from './helpers'; -jest.mock('../../../../lib/settings/use_kibana_ui_setting'); +jest.mock('../../../../lib/kibana'); const mockFramework = mockFrameworks.default_UTC; diff --git a/x-pack/legacy/plugins/siem/public/components/timeline/body/renderers/system/generic_row_renderer.test.tsx b/x-pack/legacy/plugins/siem/public/components/timeline/body/renderers/system/generic_row_renderer.test.tsx index 3727e82c1d2a0..b2dbdb6b0e45c 100644 --- a/x-pack/legacy/plugins/siem/public/components/timeline/body/renderers/system/generic_row_renderer.test.tsx +++ b/x-pack/legacy/plugins/siem/public/components/timeline/body/renderers/system/generic_row_renderer.test.tsx @@ -49,7 +49,7 @@ import { } from './generic_row_renderer'; import * as i18n from './translations'; -jest.mock('../../../../../lib/settings/use_kibana_ui_setting'); +jest.mock('../../../../../lib/kibana'); describe('GenericRowRenderer', () => { const mount = useMountAppended(); diff --git a/x-pack/legacy/plugins/siem/public/components/timeline/header/index.test.tsx b/x-pack/legacy/plugins/siem/public/components/timeline/header/index.test.tsx index 977764803acbb..4527e39128f89 100644 --- a/x-pack/legacy/plugins/siem/public/components/timeline/header/index.test.tsx +++ b/x-pack/legacy/plugins/siem/public/components/timeline/header/index.test.tsx @@ -9,21 +9,14 @@ import toJson from 'enzyme-to-json'; import * as React from 'react'; import { Direction } from '../../../graphql/types'; -import { useKibanaCore } from '../../../lib/compose/kibana_core'; import { mockIndexPattern } from '../../../mock'; import { TestProviders } from '../../../mock/test_providers'; -import { mockUiSettings } from '../../../mock/ui_settings'; import { mockDataProviders } from '../data_providers/mock/mock_data_providers'; import { useMountAppended } from '../../../utils/use_mount_appended'; import { TimelineHeaderComponent } from '.'; -const mockUseKibanaCore = useKibanaCore as jest.Mock; -jest.mock('../../../lib/compose/kibana_core'); -mockUseKibanaCore.mockImplementation(() => ({ - uiSettings: mockUiSettings, - savedObjects: {}, -})); +jest.mock('../../../lib/kibana'); describe('Header', () => { const indexPattern = mockIndexPattern; diff --git a/x-pack/legacy/plugins/siem/public/components/timeline/properties/index.test.tsx b/x-pack/legacy/plugins/siem/public/components/timeline/properties/index.test.tsx index eb82241b04124..bc05204cc47fe 100644 --- a/x-pack/legacy/plugins/siem/public/components/timeline/properties/index.test.tsx +++ b/x-pack/legacy/plugins/siem/public/components/timeline/properties/index.test.tsx @@ -8,22 +8,12 @@ import { mount } from 'enzyme'; import * as React from 'react'; import { Provider as ReduxStoreProvider } from 'react-redux'; -import { useKibanaCore } from '../../../lib/compose/kibana_core'; import { mockGlobalState, apolloClientObservable } from '../../../mock'; -import { mockUiSettings } from '../../../mock/ui_settings'; import { createStore, State } from '../../../store'; import { Properties, showDescriptionThreshold, showNotesThreshold } from '.'; -const mockUseKibanaCore = useKibanaCore as jest.Mock; -jest.mock('../../../lib/compose/kibana_core'); -mockUseKibanaCore.mockImplementation(() => ({ - uiSettings: mockUiSettings, -})); - -jest.mock('ui/vis/lib/timezone', () => ({ - timezoneProvider: () => () => 'America/New_York', -})); +jest.mock('../../../lib/kibana'); describe('Properties', () => { const usersViewing = ['elastic']; diff --git a/x-pack/legacy/plugins/siem/public/components/timeline/query_bar/index.test.tsx b/x-pack/legacy/plugins/siem/public/components/timeline/query_bar/index.test.tsx index b78691fabdcbf..b978ef3d478d8 100644 --- a/x-pack/legacy/plugins/siem/public/components/timeline/query_bar/index.test.tsx +++ b/x-pack/legacy/plugins/siem/public/components/timeline/query_bar/index.test.tsx @@ -9,22 +9,15 @@ import React from 'react'; import { DEFAULT_FROM, DEFAULT_TO } from '../../../../common/constants'; import { mockBrowserFields } from '../../../containers/source/mock'; -import { useKibanaCore } from '../../../lib/compose/kibana_core'; import { convertKueryToElasticSearchQuery } from '../../../lib/keury'; import { mockIndexPattern, TestProviders } from '../../../mock'; -import { mockUiSettings } from '../../../mock/ui_settings'; import { QueryBar } from '../../query_bar'; import { mockDataProviders } from '../data_providers/mock/mock_data_providers'; import { buildGlobalQuery } from '../helpers'; import { QueryBarTimeline, QueryBarTimelineComponentProps, getDataProviderFilter } from './index'; -const mockUseKibanaCore = useKibanaCore as jest.Mock; -jest.mock('../../../lib/compose/kibana_core'); -mockUseKibanaCore.mockImplementation(() => ({ - uiSettings: mockUiSettings, - savedObjects: {}, -})); +jest.mock('../../../lib/kibana'); describe('Timeline QueryBar ', () => { // We are doing that because we need to wrapped this component with redux diff --git a/x-pack/legacy/plugins/siem/public/components/timeline/query_bar/index.tsx b/x-pack/legacy/plugins/siem/public/components/timeline/query_bar/index.tsx index c55ead5e2d5d5..c3b46c6cd0f72 100644 --- a/x-pack/legacy/plugins/siem/public/components/timeline/query_bar/index.tsx +++ b/x-pack/legacy/plugins/siem/public/components/timeline/query_bar/index.tsx @@ -19,7 +19,7 @@ import { import { BrowserFields } from '../../../containers/source'; import { convertKueryToElasticSearchQuery } from '../../../lib/keury'; -import { useKibanaCore } from '../../../lib/compose/kibana_core'; +import { useKibana } from '../../../lib/kibana'; import { KueryFilterQuery, KueryFilterQueryKind } from '../../../store'; import { KqlMode } from '../../../store/timeline/model'; import { useSavedQueryServices } from '../../../utils/saved_query_services'; @@ -92,8 +92,8 @@ export const QueryBarTimeline = memo<QueryBarTimelineComponentProps>( const [dataProvidersDsl, setDataProvidersDsl] = useState<string>( convertKueryToElasticSearchQuery(buildGlobalQuery(dataProviders, browserFields), indexPattern) ); - const core = useKibanaCore(); - const [filterManager] = useState<FilterManager>(new FilterManager(core.uiSettings)); + const kibana = useKibana(); + const [filterManager] = useState<FilterManager>(new FilterManager(kibana.services.uiSettings)); const savedQueryServices = useSavedQueryServices(); diff --git a/x-pack/legacy/plugins/siem/public/components/timeline/timeline.test.tsx b/x-pack/legacy/plugins/siem/public/components/timeline/timeline.test.tsx index 180af88f21e4d..bb500de239da7 100644 --- a/x-pack/legacy/plugins/siem/public/components/timeline/timeline.test.tsx +++ b/x-pack/legacy/plugins/siem/public/components/timeline/timeline.test.tsx @@ -12,10 +12,8 @@ import { MockedProvider } from 'react-apollo/test-utils'; import { timelineQuery } from '../../containers/timeline/index.gql_query'; import { mockBrowserFields } from '../../containers/source/mock'; import { Direction } from '../../graphql/types'; -import { useKibanaCore } from '../../lib/compose/kibana_core'; import { defaultHeaders, mockTimelineData, mockIndexPattern } from '../../mock'; import { TestProviders } from '../../mock/test_providers'; -import { mockUiSettings } from '../../mock/ui_settings'; import { flyoutHeaderHeight } from '../flyout'; import { @@ -30,12 +28,7 @@ import { useMountAppended } from '../../utils/use_mount_appended'; const testFlyoutHeight = 980; -const mockUseKibanaCore = useKibanaCore as jest.Mock; -jest.mock('../../lib/compose/kibana_core'); -mockUseKibanaCore.mockImplementation(() => ({ - uiSettings: mockUiSettings, - savedObjects: {}, -})); +jest.mock('../../lib/kibana'); describe('Timeline', () => { const sort: Sort = { diff --git a/x-pack/legacy/plugins/siem/public/components/timeline/timeline.tsx b/x-pack/legacy/plugins/siem/public/components/timeline/timeline.tsx index ec7d10d2373d4..5646b26428bf8 100644 --- a/x-pack/legacy/plugins/siem/public/components/timeline/timeline.tsx +++ b/x-pack/legacy/plugins/siem/public/components/timeline/timeline.tsx @@ -12,7 +12,7 @@ import styled from 'styled-components'; import { BrowserFields } from '../../containers/source'; import { TimelineQuery } from '../../containers/timeline'; import { Direction } from '../../graphql/types'; -import { useKibanaCore } from '../../lib/compose/kibana_core'; +import { useKibana } from '../../lib/kibana'; import { KqlMode } from '../../store/timeline/model'; import { AutoSizer } from '../auto_sizer'; import { ColumnHeader } from './body/column_headers/column_header'; @@ -113,9 +113,9 @@ export const TimelineComponent = ({ sort, toggleColumn, }: Props) => { - const core = useKibanaCore(); + const kibana = useKibana(); const combinedQueries = combineQueries({ - config: esQuery.getEsQueryConfig(core.uiSettings), + config: esQuery.getEsQueryConfig(kibana.services.uiSettings), dataProviders, indexPattern, browserFields, diff --git a/x-pack/legacy/plugins/siem/public/components/wrapper_page/index.test.tsx b/x-pack/legacy/plugins/siem/public/components/wrapper_page/index.test.tsx index 3ea243fe5cfe7..5d73e9bcf8e71 100644 --- a/x-pack/legacy/plugins/siem/public/components/wrapper_page/index.test.tsx +++ b/x-pack/legacy/plugins/siem/public/components/wrapper_page/index.test.tsx @@ -9,11 +9,8 @@ import toJson from 'enzyme-to-json'; import React from 'react'; import { TestProviders } from '../../mock'; -import '../../mock/ui_settings'; import { WrapperPage } from './index'; -jest.mock('../../lib/settings/use_kibana_ui_setting'); - describe('WrapperPage', () => { test('it renders', () => { const wrapper = shallow( diff --git a/x-pack/legacy/plugins/siem/public/containers/anomalies/anomalies_query_tab_body/index.tsx b/x-pack/legacy/plugins/siem/public/containers/anomalies/anomalies_query_tab_body/index.tsx index 917f4dbcc211b..f2c00cbae1a74 100644 --- a/x-pack/legacy/plugins/siem/public/containers/anomalies/anomalies_query_tab_body/index.tsx +++ b/x-pack/legacy/plugins/siem/public/containers/anomalies/anomalies_query_tab_body/index.tsx @@ -12,7 +12,7 @@ import { AnomaliesOverTimeHistogram } from '../../../components/anomalies_over_t import { AnomaliesOverTimeQuery } from '../anomalies_over_time'; import { getAnomaliesFilterQuery } from './utils'; import { useSiemJobs } from '../../../components/ml_popover/hooks/use_siem_jobs'; -import { useKibanaUiSetting } from '../../../lib/settings/use_kibana_ui_setting'; +import { useUiSetting$ } from '../../../lib/kibana'; import { DEFAULT_ANOMALY_SCORE } from '../../../../common/constants'; const AnomaliesOverTimeManage = manageQuery(AnomaliesOverTimeHistogram); @@ -33,7 +33,7 @@ export const AnomaliesQueryTabBody = ({ ip, }: AnomaliesQueryTabBodyProps) => { const [siemJobsLoading, siemJobs] = useSiemJobs(true); - const [anomalyScore] = useKibanaUiSetting(DEFAULT_ANOMALY_SCORE); + const [anomalyScore] = useUiSetting$<number>(DEFAULT_ANOMALY_SCORE); const mergedFilterQuery = getAnomaliesFilterQuery( filterQuery, diff --git a/x-pack/legacy/plugins/siem/public/containers/authentications/authentications_over_time/index.tsx b/x-pack/legacy/plugins/siem/public/containers/authentications/authentications_over_time/index.tsx index 1d6d96869b6a9..8f363d49f1851 100644 --- a/x-pack/legacy/plugins/siem/public/containers/authentications/authentications_over_time/index.tsx +++ b/x-pack/legacy/plugins/siem/public/containers/authentications/authentications_over_time/index.tsx @@ -8,10 +8,11 @@ import { getOr } from 'lodash/fp'; import React from 'react'; import { Query } from 'react-apollo'; import { connect } from 'react-redux'; +import { compose } from 'redux'; -import chrome from 'ui/chrome'; import { DEFAULT_INDEX_KEY } from '../../../../common/constants'; import { inputsModel, State, inputsSelectors, hostsModel } from '../../../store'; +import { withKibana, WithKibanaProps } from '../../../lib/kibana'; import { createFilter, getDefaultFetchPolicy } from '../../helpers'; import { QueryTemplate, QueryTemplateProps } from '../../query_template'; @@ -43,7 +44,9 @@ export interface AuthenticationsOverTimeComponentReduxProps { isInspected: boolean; } -type AuthenticationsOverTimeProps = OwnProps & AuthenticationsOverTimeComponentReduxProps; +type AuthenticationsOverTimeProps = OwnProps & + AuthenticationsOverTimeComponentReduxProps & + WithKibanaProps; class AuthenticationsOverTimeComponentQuery extends QueryTemplate< AuthenticationsOverTimeProps, @@ -56,6 +59,7 @@ class AuthenticationsOverTimeComponentQuery extends QueryTemplate< filterQuery, id = ID, isInspected, + kibana, sourceId, startDate, endDate, @@ -73,7 +77,7 @@ class AuthenticationsOverTimeComponentQuery extends QueryTemplate< from: startDate!, to: endDate!, }, - defaultIndex: chrome.getUiSettingsClient().get(DEFAULT_INDEX_KEY), + defaultIndex: kibana.services.uiSettings.get<string[]>(DEFAULT_INDEX_KEY), inspect: isInspected, }} > @@ -108,6 +112,7 @@ const makeMapStateToProps = () => { return mapStateToProps; }; -export const AuthenticationsOverTimeQuery = connect(makeMapStateToProps)( - AuthenticationsOverTimeComponentQuery -); +export const AuthenticationsOverTimeQuery = compose<React.ComponentClass<OwnProps>>( + connect(makeMapStateToProps), + withKibana +)(AuthenticationsOverTimeComponentQuery); diff --git a/x-pack/legacy/plugins/siem/public/containers/authentications/index.tsx b/x-pack/legacy/plugins/siem/public/containers/authentications/index.tsx index 6f896cfd95901..6d4a88c45a768 100644 --- a/x-pack/legacy/plugins/siem/public/containers/authentications/index.tsx +++ b/x-pack/legacy/plugins/siem/public/containers/authentications/index.tsx @@ -8,8 +8,8 @@ import { getOr } from 'lodash/fp'; import React from 'react'; import { Query } from 'react-apollo'; import { connect } from 'react-redux'; +import { compose } from 'redux'; -import chrome from 'ui/chrome'; import { DEFAULT_INDEX_KEY } from '../../../common/constants'; import { AuthenticationsEdges, @@ -19,6 +19,7 @@ import { import { hostsModel, hostsSelectors, inputsModel, State, inputsSelectors } from '../../store'; import { createFilter, getDefaultFetchPolicy } from '../helpers'; import { generateTablePaginationOptions } from '../../components/paginated_table/helpers'; +import { withKibana, WithKibanaProps } from '../../lib/kibana'; import { QueryTemplatePaginated, QueryTemplatePaginatedProps } from '../query_template_paginated'; import { authenticationsQuery } from './index.gql_query'; @@ -48,7 +49,7 @@ export interface AuthenticationsComponentReduxProps { limit: number; } -type AuthenticationsProps = OwnProps & AuthenticationsComponentReduxProps; +type AuthenticationsProps = OwnProps & AuthenticationsComponentReduxProps & WithKibanaProps; class AuthenticationsComponentQuery extends QueryTemplatePaginated< AuthenticationsProps, @@ -63,6 +64,7 @@ class AuthenticationsComponentQuery extends QueryTemplatePaginated< filterQuery, id = ID, isInspected, + kibana, limit, skip, sourceId, @@ -77,7 +79,7 @@ class AuthenticationsComponentQuery extends QueryTemplatePaginated< }, pagination: generateTablePaginationOptions(activePage, limit), filterQuery: createFilter(filterQuery), - defaultIndex: chrome.getUiSettingsClient().get(DEFAULT_INDEX_KEY), + defaultIndex: kibana.services.uiSettings.get<string[]>(DEFAULT_INDEX_KEY), inspect: isInspected, }; return ( @@ -142,4 +144,7 @@ const makeMapStateToProps = () => { return mapStateToProps; }; -export const AuthenticationsQuery = connect(makeMapStateToProps)(AuthenticationsComponentQuery); +export const AuthenticationsQuery = compose<React.ComponentClass<OwnProps>>( + connect(makeMapStateToProps), + withKibana +)(AuthenticationsComponentQuery); diff --git a/x-pack/legacy/plugins/siem/public/containers/detection_engine/rules/persist_rule.tsx b/x-pack/legacy/plugins/siem/public/containers/detection_engine/rules/persist_rule.tsx index 371d28aebf7f7..82490991236de 100644 --- a/x-pack/legacy/plugins/siem/public/containers/detection_engine/rules/persist_rule.tsx +++ b/x-pack/legacy/plugins/siem/public/containers/detection_engine/rules/persist_rule.tsx @@ -6,7 +6,7 @@ import { useEffect, useState, Dispatch } from 'react'; -import { useKibanaUiSetting } from '../../../lib/settings/use_kibana_ui_setting'; +import { useUiSetting$ } from '../../../lib/kibana'; import { DEFAULT_KBN_VERSION } from '../../../../common/constants'; import { useStateToaster } from '../../../components/toasters'; import { errorToToaster } from '../../../components/ml/api/error_to_toaster'; @@ -26,7 +26,7 @@ export const usePersistRule = (): Return => { const [rule, setRule] = useState<NewRule | null>(null); const [isSaved, setIsSaved] = useState(false); const [isLoading, setIsLoading] = useState(false); - const [kbnVersion] = useKibanaUiSetting(DEFAULT_KBN_VERSION); + const [kbnVersion] = useUiSetting$<string>(DEFAULT_KBN_VERSION); const [, dispatchToaster] = useStateToaster(); useEffect(() => { diff --git a/x-pack/legacy/plugins/siem/public/containers/detection_engine/rules/use_rules.tsx b/x-pack/legacy/plugins/siem/public/containers/detection_engine/rules/use_rules.tsx index 2b8bb986a296a..66285c804aa28 100644 --- a/x-pack/legacy/plugins/siem/public/containers/detection_engine/rules/use_rules.tsx +++ b/x-pack/legacy/plugins/siem/public/containers/detection_engine/rules/use_rules.tsx @@ -6,7 +6,7 @@ import { useEffect, useState } from 'react'; -import { useKibanaUiSetting } from '../../../lib/settings/use_kibana_ui_setting'; +import { useUiSetting$ } from '../../../lib/kibana'; import { DEFAULT_KBN_VERSION } from '../../../../common/constants'; import { FetchRulesResponse, FilterOptions, PaginationOptions } from './types'; import { useStateToaster } from '../../../components/toasters'; @@ -35,7 +35,7 @@ export const useRules = ( data: [], }); const [loading, setLoading] = useState(true); - const [kbnVersion] = useKibanaUiSetting(DEFAULT_KBN_VERSION); + const [kbnVersion] = useUiSetting$<string>(DEFAULT_KBN_VERSION); const [, dispatchToaster] = useStateToaster(); useEffect(() => { diff --git a/x-pack/legacy/plugins/siem/public/containers/events/events_over_time/index.tsx b/x-pack/legacy/plugins/siem/public/containers/events/events_over_time/index.tsx index 77ce98e180ab0..e102cd11f108e 100644 --- a/x-pack/legacy/plugins/siem/public/containers/events/events_over_time/index.tsx +++ b/x-pack/legacy/plugins/siem/public/containers/events/events_over_time/index.tsx @@ -8,12 +8,13 @@ import { getOr } from 'lodash/fp'; import React from 'react'; import { Query } from 'react-apollo'; import { connect } from 'react-redux'; +import { compose } from 'redux'; -import chrome from 'ui/chrome'; import { DEFAULT_INDEX_KEY } from '../../../../common/constants'; import { inputsModel, State, inputsSelectors, hostsModel } from '../../../store'; import { createFilter, getDefaultFetchPolicy } from '../../helpers'; import { QueryTemplate, QueryTemplateProps } from '../../query_template'; +import { withKibana, WithKibanaProps } from '../../../lib/kibana'; import { EventsOverTimeGqlQuery } from './events_over_time.gql_query'; import { GetEventsOverTimeQuery, MatrixOverTimeHistogramData } from '../../../graphql/types'; @@ -40,7 +41,7 @@ export interface EventsOverTimeComponentReduxProps { isInspected: boolean; } -type EventsOverTimeProps = OwnProps & EventsOverTimeComponentReduxProps; +type EventsOverTimeProps = OwnProps & EventsOverTimeComponentReduxProps & WithKibanaProps; class EventsOverTimeComponentQuery extends QueryTemplate< EventsOverTimeProps, @@ -54,6 +55,7 @@ class EventsOverTimeComponentQuery extends QueryTemplate< filterQuery, id = ID, isInspected, + kibana, sourceId, startDate, } = this.props; @@ -70,7 +72,7 @@ class EventsOverTimeComponentQuery extends QueryTemplate< from: startDate!, to: endDate!, }, - defaultIndex: chrome.getUiSettingsClient().get(DEFAULT_INDEX_KEY), + defaultIndex: kibana.services.uiSettings.get<string[]>(DEFAULT_INDEX_KEY), inspect: isInspected, }} > @@ -105,4 +107,7 @@ const makeMapStateToProps = () => { return mapStateToProps; }; -export const EventsOverTimeQuery = connect(makeMapStateToProps)(EventsOverTimeComponentQuery); +export const EventsOverTimeQuery = compose<React.ComponentClass<OwnProps>>( + connect(makeMapStateToProps), + withKibana +)(EventsOverTimeComponentQuery); diff --git a/x-pack/legacy/plugins/siem/public/containers/events/last_event_time/index.ts b/x-pack/legacy/plugins/siem/public/containers/events/last_event_time/index.ts index 3bfdbae8d30f7..9cae503d30940 100644 --- a/x-pack/legacy/plugins/siem/public/containers/events/last_event_time/index.ts +++ b/x-pack/legacy/plugins/siem/public/containers/events/last_event_time/index.ts @@ -7,11 +7,11 @@ import { get } from 'lodash/fp'; import React, { useEffect, useState } from 'react'; -import chrome from 'ui/chrome'; import { DEFAULT_INDEX_KEY } from '../../../../common/constants'; import { GetLastEventTimeQuery, LastEventIndexKey, LastTimeDetails } from '../../../graphql/types'; import { inputsModel } from '../../../store'; import { QueryTemplateProps } from '../../query_template'; +import { useUiSetting$ } from '../../../lib/kibana'; import { LastEventTimeGqlQuery } from './last_event_time.gql_query'; import { useApolloClient } from '../../../utils/apollo_context'; @@ -38,6 +38,7 @@ export function useLastEventTimeQuery<TCache = object>( const [lastSeen, updateLastSeen] = useState<number | null>(null); const [errorMessage, updateErrorMessage] = useState<string | null>(null); const [currentIndexKey, updateCurrentIndexKey] = useState<LastEventIndexKey | null>(null); + const [defaultIndex] = useUiSetting$<string[]>(DEFAULT_INDEX_KEY); const apolloClient = useApolloClient(); async function fetchLastEventTime(signal: AbortSignal) { updateLoading(true); @@ -50,7 +51,7 @@ export function useLastEventTimeQuery<TCache = object>( sourceId, indexKey, details, - defaultIndex: chrome.getUiSettingsClient().get(DEFAULT_INDEX_KEY), + defaultIndex, }, context: { fetchOptions: { diff --git a/x-pack/legacy/plugins/siem/public/containers/hosts/first_last_seen/index.ts b/x-pack/legacy/plugins/siem/public/containers/hosts/first_last_seen/index.ts index 042de56fbd99d..e36da5bfbe4ee 100644 --- a/x-pack/legacy/plugins/siem/public/containers/hosts/first_last_seen/index.ts +++ b/x-pack/legacy/plugins/siem/public/containers/hosts/first_last_seen/index.ts @@ -8,7 +8,7 @@ import ApolloClient from 'apollo-client'; import { get } from 'lodash/fp'; import React, { useEffect, useState } from 'react'; -import chrome from 'ui/chrome'; +import { useUiSetting$ } from '../../../lib/kibana'; import { DEFAULT_INDEX_KEY } from '../../../../common/constants'; import { GetHostFirstLastSeenQuery } from '../../../graphql/types'; import { inputsModel } from '../../../store'; @@ -39,6 +39,7 @@ export function useFirstLastSeenHostQuery<TCache = object>( const [firstSeen, updateFirstSeen] = useState<Date | null>(null); const [lastSeen, updateLastSeen] = useState<Date | null>(null); const [errorMessage, updateErrorMessage] = useState<string | null>(null); + const [defaultIndex] = useUiSetting$<string[]>(DEFAULT_INDEX_KEY); async function fetchFirstLastSeenHost(signal: AbortSignal) { updateLoading(true); @@ -49,7 +50,7 @@ export function useFirstLastSeenHostQuery<TCache = object>( variables: { sourceId, hostName, - defaultIndex: chrome.getUiSettingsClient().get(DEFAULT_INDEX_KEY), + defaultIndex, }, context: { fetchOptions: { diff --git a/x-pack/legacy/plugins/siem/public/containers/hosts/index.tsx b/x-pack/legacy/plugins/siem/public/containers/hosts/index.tsx index d2be29e3e9e29..733c2224d840a 100644 --- a/x-pack/legacy/plugins/siem/public/containers/hosts/index.tsx +++ b/x-pack/legacy/plugins/siem/public/containers/hosts/index.tsx @@ -9,8 +9,8 @@ import memoizeOne from 'memoize-one'; import React from 'react'; import { Query } from 'react-apollo'; import { connect } from 'react-redux'; +import { compose } from 'redux'; -import chrome from 'ui/chrome'; import { DEFAULT_INDEX_KEY } from '../../../common/constants'; import { Direction, @@ -22,6 +22,7 @@ import { import { hostsModel, hostsSelectors, inputsModel, State, inputsSelectors } from '../../store'; import { createFilter, getDefaultFetchPolicy } from '../helpers'; import { QueryTemplatePaginated, QueryTemplatePaginatedProps } from '../query_template_paginated'; +import { withKibana, WithKibanaProps } from '../../lib/kibana'; import { HostsTableQuery } from './hosts_table.gql_query'; import { generateTablePaginationOptions } from '../../components/paginated_table/helpers'; @@ -57,7 +58,7 @@ export interface HostsComponentReduxProps { direction: Direction; } -type HostsProps = OwnProps & HostsComponentReduxProps; +type HostsProps = OwnProps & HostsComponentReduxProps & WithKibanaProps; class HostsComponentQuery extends QueryTemplatePaginated< HostsProps, @@ -83,12 +84,14 @@ class HostsComponentQuery extends QueryTemplatePaginated< direction, filterQuery, endDate, + kibana, limit, startDate, skip, sourceId, sortField, } = this.props; + const defaultIndex = kibana.services.uiSettings.get<string[]>(DEFAULT_INDEX_KEY); const variables: GetHostsTableQuery.Variables = { sourceId, @@ -103,7 +106,7 @@ class HostsComponentQuery extends QueryTemplatePaginated< }, pagination: generateTablePaginationOptions(activePage, limit), filterQuery: createFilter(filterQuery), - defaultIndex: chrome.getUiSettingsClient().get(DEFAULT_INDEX_KEY), + defaultIndex, inspect: isInspected, }; return ( @@ -174,4 +177,7 @@ const makeMapStateToProps = () => { return mapStateToProps; }; -export const HostsQuery = connect(makeMapStateToProps)(HostsComponentQuery); +export const HostsQuery = compose<React.ComponentClass<OwnProps>>( + connect(makeMapStateToProps), + withKibana +)(HostsComponentQuery); diff --git a/x-pack/legacy/plugins/siem/public/containers/hosts/overview/index.tsx b/x-pack/legacy/plugins/siem/public/containers/hosts/overview/index.tsx index a9223143462fd..5057e872b5313 100644 --- a/x-pack/legacy/plugins/siem/public/containers/hosts/overview/index.tsx +++ b/x-pack/legacy/plugins/siem/public/containers/hosts/overview/index.tsx @@ -7,12 +7,14 @@ import { getOr } from 'lodash/fp'; import React from 'react'; import { Query } from 'react-apollo'; -import chrome from 'ui/chrome'; import { connect } from 'react-redux'; +import { compose } from 'redux'; + import { DEFAULT_INDEX_KEY } from '../../../../common/constants'; import { inputsModel, inputsSelectors, State } from '../../../store'; import { getDefaultFetchPolicy } from '../../helpers'; import { QueryTemplate, QueryTemplateProps } from '../../query_template'; +import { withKibana, WithKibanaProps } from '../../../lib/kibana'; import { HostOverviewQuery } from './host_overview.gql_query'; import { GetHostOverviewQuery, HostItem } from '../../../graphql/types'; @@ -40,8 +42,10 @@ export interface OwnProps extends QueryTemplateProps { endDate: number; } +type HostsOverViewProps = OwnProps & HostOverviewReduxProps & WithKibanaProps; + class HostOverviewByNameComponentQuery extends QueryTemplate< - OwnProps & HostOverviewReduxProps, + HostsOverViewProps, GetHostOverviewQuery.Query, GetHostOverviewQuery.Variables > { @@ -51,6 +55,7 @@ class HostOverviewByNameComponentQuery extends QueryTemplate< isInspected, children, hostName, + kibana, skip, sourceId, startDate, @@ -70,7 +75,7 @@ class HostOverviewByNameComponentQuery extends QueryTemplate< from: startDate, to: endDate, }, - defaultIndex: chrome.getUiSettingsClient().get(DEFAULT_INDEX_KEY), + defaultIndex: kibana.services.uiSettings.get<string[]>(DEFAULT_INDEX_KEY), inspect: isInspected, }} > @@ -102,6 +107,7 @@ const makeMapStateToProps = () => { return mapStateToProps; }; -export const HostOverviewByNameQuery = connect(makeMapStateToProps)( - HostOverviewByNameComponentQuery -); +export const HostOverviewByNameQuery = compose<React.ComponentClass<OwnProps>>( + connect(makeMapStateToProps), + withKibana +)(HostOverviewByNameComponentQuery); diff --git a/x-pack/legacy/plugins/siem/public/containers/ip_overview/index.tsx b/x-pack/legacy/plugins/siem/public/containers/ip_overview/index.tsx index 003032493fca2..9576c66c4c9a5 100644 --- a/x-pack/legacy/plugins/siem/public/containers/ip_overview/index.tsx +++ b/x-pack/legacy/plugins/siem/public/containers/ip_overview/index.tsx @@ -9,10 +9,10 @@ import React from 'react'; import { Query } from 'react-apollo'; import { connect } from 'react-redux'; -import chrome from 'ui/chrome'; import { DEFAULT_INDEX_KEY } from '../../../common/constants'; import { GetIpOverviewQuery, IpOverviewData } from '../../graphql/types'; import { networkModel, inputsModel, inputsSelectors, State } from '../../store'; +import { useUiSetting } from '../../lib/kibana'; import { createFilter, getDefaultFetchPolicy } from '../helpers'; import { QueryTemplateProps } from '../query_template'; @@ -49,7 +49,7 @@ const IpOverviewComponentQuery = React.memo<IpOverviewProps & IpOverviewReduxPro sourceId, filterQuery: createFilter(filterQuery), ip, - defaultIndex: chrome.getUiSettingsClient().get(DEFAULT_INDEX_KEY), + defaultIndex: useUiSetting<string[]>(DEFAULT_INDEX_KEY), inspect: isInspected, }} > diff --git a/x-pack/legacy/plugins/siem/public/containers/kpi_host_details/index.tsx b/x-pack/legacy/plugins/siem/public/containers/kpi_host_details/index.tsx index 20ed7fa991d15..501bc8472b5e2 100644 --- a/x-pack/legacy/plugins/siem/public/containers/kpi_host_details/index.tsx +++ b/x-pack/legacy/plugins/siem/public/containers/kpi_host_details/index.tsx @@ -8,11 +8,11 @@ import { getOr } from 'lodash/fp'; import React from 'react'; import { Query } from 'react-apollo'; import { connect } from 'react-redux'; -import chrome from 'ui/chrome'; import { DEFAULT_INDEX_KEY } from '../../../common/constants'; import { KpiHostDetailsData, GetKpiHostDetailsQuery } from '../../graphql/types'; import { inputsModel, inputsSelectors, State } from '../../store'; +import { useUiSetting } from '../../lib/kibana'; import { createFilter, getDefaultFetchPolicy } from '../helpers'; import { QueryTemplateProps } from '../query_template'; @@ -51,7 +51,7 @@ const KpiHostDetailsComponentQuery = React.memo<QueryKpiHostDetailsProps & KpiHo to: endDate!, }, filterQuery: createFilter(filterQuery), - defaultIndex: chrome.getUiSettingsClient().get(DEFAULT_INDEX_KEY), + defaultIndex: useUiSetting<string[]>(DEFAULT_INDEX_KEY), inspect: isInspected, }} > diff --git a/x-pack/legacy/plugins/siem/public/containers/kpi_hosts/index.tsx b/x-pack/legacy/plugins/siem/public/containers/kpi_hosts/index.tsx index f8aa8aa38e8e1..32472ba6deedf 100644 --- a/x-pack/legacy/plugins/siem/public/containers/kpi_hosts/index.tsx +++ b/x-pack/legacy/plugins/siem/public/containers/kpi_hosts/index.tsx @@ -8,11 +8,11 @@ import { getOr } from 'lodash/fp'; import React from 'react'; import { Query } from 'react-apollo'; import { connect } from 'react-redux'; -import chrome from 'ui/chrome'; import { DEFAULT_INDEX_KEY } from '../../../common/constants'; import { GetKpiHostsQuery, KpiHostsData } from '../../graphql/types'; import { inputsModel, inputsSelectors, State } from '../../store'; +import { useUiSetting } from '../../lib/kibana'; import { createFilter, getDefaultFetchPolicy } from '../helpers'; import { QueryTemplateProps } from '../query_template'; @@ -51,7 +51,7 @@ const KpiHostsComponentQuery = React.memo<KpiHostsProps & KpiHostsReducer>( to: endDate!, }, filterQuery: createFilter(filterQuery), - defaultIndex: chrome.getUiSettingsClient().get(DEFAULT_INDEX_KEY), + defaultIndex: useUiSetting<string[]>(DEFAULT_INDEX_KEY), inspect: isInspected, }} > diff --git a/x-pack/legacy/plugins/siem/public/containers/kpi_network/index.tsx b/x-pack/legacy/plugins/siem/public/containers/kpi_network/index.tsx index 269c3593d4d73..52b8814958ba0 100644 --- a/x-pack/legacy/plugins/siem/public/containers/kpi_network/index.tsx +++ b/x-pack/legacy/plugins/siem/public/containers/kpi_network/index.tsx @@ -8,11 +8,11 @@ import { getOr } from 'lodash/fp'; import React from 'react'; import { Query } from 'react-apollo'; import { connect } from 'react-redux'; -import chrome from 'ui/chrome'; import { DEFAULT_INDEX_KEY } from '../../../common/constants'; import { GetKpiNetworkQuery, KpiNetworkData } from '../../graphql/types'; import { inputsModel, inputsSelectors, State } from '../../store'; +import { useUiSetting } from '../../lib/kibana'; import { createFilter, getDefaultFetchPolicy } from '../helpers'; import { QueryTemplateProps } from '../query_template'; @@ -51,7 +51,7 @@ const KpiNetworkComponentQuery = React.memo<KpiNetworkProps & KpiNetworkReducer> to: endDate!, }, filterQuery: createFilter(filterQuery), - defaultIndex: chrome.getUiSettingsClient().get(DEFAULT_INDEX_KEY), + defaultIndex: useUiSetting<string[]>(DEFAULT_INDEX_KEY), inspect: isInspected, }} > diff --git a/x-pack/legacy/plugins/siem/public/containers/kuery_autocompletion/index.tsx b/x-pack/legacy/plugins/siem/public/containers/kuery_autocompletion/index.tsx index d06f4f6fbbbfa..6361f7abcf977 100644 --- a/x-pack/legacy/plugins/siem/public/containers/kuery_autocompletion/index.tsx +++ b/x-pack/legacy/plugins/siem/public/containers/kuery_autocompletion/index.tsx @@ -9,7 +9,7 @@ import { AutocompleteSuggestion, IIndexPattern, } from '../../../../../../../src/plugins/data/public'; -import { useKibanaPlugins } from '../../lib/compose/kibana_plugins'; +import { useKibana } from '../../lib/kibana'; type RendererResult = React.ReactElement<JSX.Element> | null; type RendererFunction<RenderArgs, Result = RendererResult> = (args: RenderArgs) => Result; @@ -34,13 +34,13 @@ export const KueryAutocompletion = React.memo<KueryAutocompletionLifecycleProps> null ); const [suggestions, setSuggestions] = useState<AutocompleteSuggestion[]>([]); - const plugins = useKibanaPlugins(); + const kibana = useKibana(); const loadSuggestions = async ( expression: string, cursorPosition: number, maxSuggestions?: number ) => { - const autocompletionProvider = plugins.data.autocomplete.getProvider('kuery'); + const autocompletionProvider = kibana.services.data.autocomplete.getProvider('kuery'); const config = { get: () => true, }; diff --git a/x-pack/legacy/plugins/siem/public/containers/network_dns/index.tsx b/x-pack/legacy/plugins/siem/public/containers/network_dns/index.tsx index 592fe43b9873f..b5ebf3deacd0a 100644 --- a/x-pack/legacy/plugins/siem/public/containers/network_dns/index.tsx +++ b/x-pack/legacy/plugins/siem/public/containers/network_dns/index.tsx @@ -8,8 +8,8 @@ import { getOr } from 'lodash/fp'; import React from 'react'; import { Query } from 'react-apollo'; import { connect } from 'react-redux'; +import { compose } from 'redux'; -import chrome from 'ui/chrome'; import { DEFAULT_INDEX_KEY } from '../../../common/constants'; import { GetNetworkDnsQuery, @@ -19,6 +19,7 @@ import { MatrixOverOrdinalHistogramData, } from '../../graphql/types'; import { inputsModel, networkModel, networkSelectors, State, inputsSelectors } from '../../store'; +import { withKibana, WithKibanaProps } from '../../lib/kibana'; import { generateTablePaginationOptions } from '../../components/paginated_table/helpers'; import { createFilter, getDefaultFetchPolicy } from '../helpers'; import { QueryTemplatePaginated, QueryTemplatePaginatedProps } from '../query_template_paginated'; @@ -53,7 +54,7 @@ export interface NetworkDnsComponentReduxProps { limit: number; } -type NetworkDnsProps = OwnProps & NetworkDnsComponentReduxProps; +type NetworkDnsProps = OwnProps & NetworkDnsComponentReduxProps & WithKibanaProps; export class NetworkDnsComponentQuery extends QueryTemplatePaginated< NetworkDnsProps, @@ -70,13 +71,14 @@ export class NetworkDnsComponentQuery extends QueryTemplatePaginated< id = ID, isInspected, isPtrIncluded, + kibana, limit, skip, sourceId, startDate, } = this.props; const variables: GetNetworkDnsQuery.Variables = { - defaultIndex: chrome.getUiSettingsClient().get(DEFAULT_INDEX_KEY), + defaultIndex: kibana.services.uiSettings.get<string[]>(DEFAULT_INDEX_KEY), filterQuery: createFilter(filterQuery), inspect: isInspected, isPtrIncluded, @@ -172,7 +174,12 @@ const makeMapHistogramStateToProps = () => { return mapStateToProps; }; -export const NetworkDnsQuery = connect(makeMapStateToProps)(NetworkDnsComponentQuery); -export const NetworkDnsHistogramQuery = connect(makeMapHistogramStateToProps)( - NetworkDnsComponentQuery -); +export const NetworkDnsQuery = compose<React.ComponentClass<OwnProps>>( + connect(makeMapStateToProps), + withKibana +)(NetworkDnsComponentQuery); + +export const NetworkDnsHistogramQuery = compose<React.ComponentClass<OwnProps>>( + connect(makeMapHistogramStateToProps), + withKibana +)(NetworkDnsComponentQuery); diff --git a/x-pack/legacy/plugins/siem/public/containers/network_http/index.tsx b/x-pack/legacy/plugins/siem/public/containers/network_http/index.tsx index d76ab53b2de3a..bf4e64f63d559 100644 --- a/x-pack/legacy/plugins/siem/public/containers/network_http/index.tsx +++ b/x-pack/legacy/plugins/siem/public/containers/network_http/index.tsx @@ -9,7 +9,6 @@ import React from 'react'; import { Query } from 'react-apollo'; import { connect } from 'react-redux'; import { compose } from 'redux'; -import chrome from 'ui/chrome'; import { DEFAULT_INDEX_KEY } from '../../../common/constants'; import { @@ -19,6 +18,7 @@ import { PageInfoPaginated, } from '../../graphql/types'; import { inputsModel, inputsSelectors, networkModel, networkSelectors, State } from '../../store'; +import { withKibana, WithKibanaProps } from '../../lib/kibana'; import { generateTablePaginationOptions } from '../../components/paginated_table/helpers'; import { createFilter, getDefaultFetchPolicy } from '../helpers'; import { QueryTemplatePaginated, QueryTemplatePaginatedProps } from '../query_template_paginated'; @@ -52,7 +52,7 @@ export interface NetworkHttpComponentReduxProps { sort: NetworkHttpSortField; } -type NetworkHttpProps = OwnProps & NetworkHttpComponentReduxProps; +type NetworkHttpProps = OwnProps & NetworkHttpComponentReduxProps & WithKibanaProps; class NetworkHttpComponentQuery extends QueryTemplatePaginated< NetworkHttpProps, @@ -68,6 +68,7 @@ class NetworkHttpComponentQuery extends QueryTemplatePaginated< id = ID, ip, isInspected, + kibana, limit, skip, sourceId, @@ -75,7 +76,7 @@ class NetworkHttpComponentQuery extends QueryTemplatePaginated< startDate, } = this.props; const variables: GetNetworkHttpQuery.Variables = { - defaultIndex: chrome.getUiSettingsClient().get(DEFAULT_INDEX_KEY), + defaultIndex: kibana.services.uiSettings.get<string[]>(DEFAULT_INDEX_KEY), filterQuery: createFilter(filterQuery), inspect: isInspected, ip, @@ -150,5 +151,6 @@ const makeMapStateToProps = () => { }; export const NetworkHttpQuery = compose<React.ComponentClass<OwnProps>>( - connect(makeMapStateToProps) + connect(makeMapStateToProps), + withKibana )(NetworkHttpComponentQuery); diff --git a/x-pack/legacy/plugins/siem/public/containers/network_top_countries/index.tsx b/x-pack/legacy/plugins/siem/public/containers/network_top_countries/index.tsx index b179745dafa51..bd1e1a002bbcd 100644 --- a/x-pack/legacy/plugins/siem/public/containers/network_top_countries/index.tsx +++ b/x-pack/legacy/plugins/siem/public/containers/network_top_countries/index.tsx @@ -10,7 +10,6 @@ import { Query } from 'react-apollo'; import { connect } from 'react-redux'; import { compose } from 'redux'; -import chrome from 'ui/chrome'; import { DEFAULT_INDEX_KEY } from '../../../common/constants'; import { FlowTargetSourceDest, @@ -20,6 +19,7 @@ import { PageInfoPaginated, } from '../../graphql/types'; import { inputsModel, inputsSelectors, networkModel, networkSelectors, State } from '../../store'; +import { withKibana, WithKibanaProps } from '../../lib/kibana'; import { generateTablePaginationOptions } from '../../components/paginated_table/helpers'; import { createFilter, getDefaultFetchPolicy } from '../helpers'; import { QueryTemplatePaginated, QueryTemplatePaginatedProps } from '../query_template_paginated'; @@ -54,7 +54,7 @@ export interface NetworkTopCountriesComponentReduxProps { sort: NetworkTopTablesSortField; } -type NetworkTopCountriesProps = OwnProps & NetworkTopCountriesComponentReduxProps; +type NetworkTopCountriesProps = OwnProps & NetworkTopCountriesComponentReduxProps & WithKibanaProps; class NetworkTopCountriesComponentQuery extends QueryTemplatePaginated< NetworkTopCountriesProps, @@ -68,6 +68,7 @@ class NetworkTopCountriesComponentQuery extends QueryTemplatePaginated< endDate, flowTarget, filterQuery, + kibana, id = `${ID}-${flowTarget}`, ip, isInspected, @@ -78,7 +79,7 @@ class NetworkTopCountriesComponentQuery extends QueryTemplatePaginated< sort, } = this.props; const variables: GetNetworkTopCountriesQuery.Variables = { - defaultIndex: chrome.getUiSettingsClient().get(DEFAULT_INDEX_KEY), + defaultIndex: kibana.services.uiSettings.get<string[]>(DEFAULT_INDEX_KEY), filterQuery: createFilter(filterQuery), flowTarget, inspect: isInspected, @@ -154,5 +155,6 @@ const makeMapStateToProps = () => { }; export const NetworkTopCountriesQuery = compose<React.ComponentClass<OwnProps>>( - connect(makeMapStateToProps) + connect(makeMapStateToProps), + withKibana )(NetworkTopCountriesComponentQuery); diff --git a/x-pack/legacy/plugins/siem/public/containers/network_top_n_flow/index.tsx b/x-pack/legacy/plugins/siem/public/containers/network_top_n_flow/index.tsx index 239576a48c49f..f0f1f8257f29f 100644 --- a/x-pack/legacy/plugins/siem/public/containers/network_top_n_flow/index.tsx +++ b/x-pack/legacy/plugins/siem/public/containers/network_top_n_flow/index.tsx @@ -9,7 +9,6 @@ import React from 'react'; import { Query } from 'react-apollo'; import { connect } from 'react-redux'; import { compose } from 'redux'; -import chrome from 'ui/chrome'; import { DEFAULT_INDEX_KEY } from '../../../common/constants'; import { @@ -19,6 +18,7 @@ import { NetworkTopTablesSortField, PageInfoPaginated, } from '../../graphql/types'; +import { withKibana, WithKibanaProps } from '../../lib/kibana'; import { inputsModel, inputsSelectors, networkModel, networkSelectors, State } from '../../store'; import { generateTablePaginationOptions } from '../../components/paginated_table/helpers'; import { createFilter, getDefaultFetchPolicy } from '../helpers'; @@ -54,7 +54,7 @@ export interface NetworkTopNFlowComponentReduxProps { sort: NetworkTopTablesSortField; } -type NetworkTopNFlowProps = OwnProps & NetworkTopNFlowComponentReduxProps; +type NetworkTopNFlowProps = OwnProps & NetworkTopNFlowComponentReduxProps & WithKibanaProps; class NetworkTopNFlowComponentQuery extends QueryTemplatePaginated< NetworkTopNFlowProps, @@ -68,6 +68,7 @@ class NetworkTopNFlowComponentQuery extends QueryTemplatePaginated< endDate, flowTarget, filterQuery, + kibana, id = `${ID}-${flowTarget}`, ip, isInspected, @@ -78,7 +79,7 @@ class NetworkTopNFlowComponentQuery extends QueryTemplatePaginated< sort, } = this.props; const variables: GetNetworkTopNFlowQuery.Variables = { - defaultIndex: chrome.getUiSettingsClient().get(DEFAULT_INDEX_KEY), + defaultIndex: kibana.services.uiSettings.get<string[]>(DEFAULT_INDEX_KEY), filterQuery: createFilter(filterQuery), flowTarget, inspect: isInspected, @@ -154,5 +155,6 @@ const makeMapStateToProps = () => { }; export const NetworkTopNFlowQuery = compose<React.ComponentClass<OwnProps>>( - connect(makeMapStateToProps) + connect(makeMapStateToProps), + withKibana )(NetworkTopNFlowComponentQuery); diff --git a/x-pack/legacy/plugins/siem/public/containers/overview/overview_host/index.tsx b/x-pack/legacy/plugins/siem/public/containers/overview/overview_host/index.tsx index 6ef0ee7b33589..36cadd7872cc8 100644 --- a/x-pack/legacy/plugins/siem/public/containers/overview/overview_host/index.tsx +++ b/x-pack/legacy/plugins/siem/public/containers/overview/overview_host/index.tsx @@ -8,10 +8,10 @@ import { getOr } from 'lodash/fp'; import React from 'react'; import { Query } from 'react-apollo'; import { connect } from 'react-redux'; -import chrome from 'ui/chrome'; import { DEFAULT_INDEX_KEY } from '../../../../common/constants'; import { GetOverviewHostQuery, OverviewHostData } from '../../../graphql/types'; +import { useUiSetting } from '../../../lib/kibana'; import { inputsModel, inputsSelectors } from '../../../store/inputs'; import { State } from '../../../store'; import { createFilter, getDefaultFetchPolicy } from '../../helpers'; @@ -53,7 +53,7 @@ const OverviewHostComponentQuery = React.memo<OverviewHostProps & OverviewHostRe to: endDate, }, filterQuery: createFilter(filterQuery), - defaultIndex: chrome.getUiSettingsClient().get(DEFAULT_INDEX_KEY), + defaultIndex: useUiSetting<string[]>(DEFAULT_INDEX_KEY), inspect: isInspected, }} > diff --git a/x-pack/legacy/plugins/siem/public/containers/overview/overview_network/index.tsx b/x-pack/legacy/plugins/siem/public/containers/overview/overview_network/index.tsx index 677d96c10eee2..9e7d59de0e546 100644 --- a/x-pack/legacy/plugins/siem/public/containers/overview/overview_network/index.tsx +++ b/x-pack/legacy/plugins/siem/public/containers/overview/overview_network/index.tsx @@ -9,9 +9,9 @@ import React from 'react'; import { Query } from 'react-apollo'; import { connect } from 'react-redux'; -import chrome from 'ui/chrome'; import { DEFAULT_INDEX_KEY } from '../../../../common/constants'; import { GetOverviewNetworkQuery, OverviewNetworkData } from '../../../graphql/types'; +import { useUiSetting } from '../../../lib/kibana'; import { State } from '../../../store'; import { inputsModel, inputsSelectors } from '../../../store/inputs'; import { createFilter, getDefaultFetchPolicy } from '../../helpers'; @@ -55,7 +55,7 @@ export const OverviewNetworkComponentQuery = React.memo< to: endDate, }, filterQuery: createFilter(filterQuery), - defaultIndex: chrome.getUiSettingsClient().get(DEFAULT_INDEX_KEY), + defaultIndex: useUiSetting<string[]>(DEFAULT_INDEX_KEY), inspect: isInspected, }} > diff --git a/x-pack/legacy/plugins/siem/public/containers/source/index.test.tsx b/x-pack/legacy/plugins/siem/public/containers/source/index.test.tsx index 7d6ac73357b15..d1a183a402e37 100644 --- a/x-pack/legacy/plugins/siem/public/containers/source/index.test.tsx +++ b/x-pack/legacy/plugins/siem/public/containers/source/index.test.tsx @@ -11,11 +11,11 @@ import { MockedProvider } from 'react-apollo/test-utils'; import { wait } from '../../lib/helpers'; -import '../../mock/ui_settings'; - import { WithSource, indicesExistOrDataTemporarilyUnavailable } from '.'; import { mockBrowserFields, mockIndexFields, mocksSource } from './mock'; +jest.mock('../../lib/kibana'); + describe('Index Fields & Browser Fields', () => { test('Index Fields', async () => { mount( diff --git a/x-pack/legacy/plugins/siem/public/containers/source/index.tsx b/x-pack/legacy/plugins/siem/public/containers/source/index.tsx index 8bddbd14a367c..94524dedbcd59 100644 --- a/x-pack/legacy/plugins/siem/public/containers/source/index.tsx +++ b/x-pack/legacy/plugins/siem/public/containers/source/index.tsx @@ -10,7 +10,7 @@ import { Query } from 'react-apollo'; import React, { useEffect, useState } from 'react'; import memoizeOne from 'memoize-one'; import { IIndexPattern } from 'src/plugins/data/public'; -import chrome from 'ui/chrome'; +import { useUiSetting$ } from '../../lib/kibana'; import { DEFAULT_INDEX_KEY } from '../../../common/constants'; import { IndexField, SourceQuery } from '../../graphql/types'; @@ -82,6 +82,7 @@ export const getBrowserFields = memoizeOne( ); export const WithSource = React.memo<WithSourceProps>(({ children, sourceId }) => { + const [defaultIndex] = useUiSetting$<string[]>(DEFAULT_INDEX_KEY); return ( <Query<SourceQuery.Query, SourceQuery.Variables> query={sourceQuery} @@ -89,20 +90,14 @@ export const WithSource = React.memo<WithSourceProps>(({ children, sourceId }) = notifyOnNetworkStatusChange variables={{ sourceId, - defaultIndex: chrome.getUiSettingsClient().get(DEFAULT_INDEX_KEY), + defaultIndex, }} > {({ data }) => children({ indicesExist: get('source.status.indicesExist', data), browserFields: getBrowserFields(get('source.status.indexFields', data)), - indexPattern: getIndexFields( - chrome - .getUiSettingsClient() - .get(DEFAULT_INDEX_KEY) - .join(), - get('source.status.indexFields', data) - ), + indexPattern: getIndexFields(defaultIndex.join(), get('source.status.indexFields', data)), }) } </Query> diff --git a/x-pack/legacy/plugins/siem/public/containers/timeline/details/index.tsx b/x-pack/legacy/plugins/siem/public/containers/timeline/details/index.tsx index cfb3f8bd8dc77..721cfefe01780 100644 --- a/x-pack/legacy/plugins/siem/public/containers/timeline/details/index.tsx +++ b/x-pack/legacy/plugins/siem/public/containers/timeline/details/index.tsx @@ -8,10 +8,10 @@ import { getOr } from 'lodash/fp'; import memoizeOne from 'memoize-one'; import React from 'react'; import { Query } from 'react-apollo'; -import chrome from 'ui/chrome'; import { DEFAULT_INDEX_KEY } from '../../../../common/constants'; import { DetailItem, GetTimelineDetailsQuery } from '../../../graphql/types'; +import { useUiSetting } from '../../../lib/kibana'; import { timelineDetailsQuery } from './index.gql_query'; @@ -38,7 +38,7 @@ export const TimelineDetailsComponentQuery = React.memo<TimelineDetailsProps>( sourceId, indexName, eventId, - defaultIndex: chrome.getUiSettingsClient().get(DEFAULT_INDEX_KEY), + defaultIndex: useUiSetting<string[]>(DEFAULT_INDEX_KEY), }; return executeQuery ? ( <Query<GetTimelineDetailsQuery.Query, GetTimelineDetailsQuery.Variables> diff --git a/x-pack/legacy/plugins/siem/public/containers/timeline/index.tsx b/x-pack/legacy/plugins/siem/public/containers/timeline/index.tsx index 40ed3b3747c10..f7c2d067a29f5 100644 --- a/x-pack/legacy/plugins/siem/public/containers/timeline/index.tsx +++ b/x-pack/legacy/plugins/siem/public/containers/timeline/index.tsx @@ -8,9 +8,9 @@ import { getOr } from 'lodash/fp'; import memoizeOne from 'memoize-one'; import React from 'react'; import { Query } from 'react-apollo'; - -import chrome from 'ui/chrome'; +import { compose } from 'redux'; import { connect } from 'react-redux'; + import { DEFAULT_INDEX_KEY } from '../../../common/constants'; import { GetTimelineQuery, @@ -20,6 +20,7 @@ import { TimelineItem, } from '../../graphql/types'; import { inputsModel, inputsSelectors, State } from '../../store'; +import { withKibana, WithKibanaProps } from '../../lib/kibana'; import { createFilter } from '../helpers'; import { QueryTemplate, QueryTemplateProps } from '../query_template'; @@ -50,7 +51,7 @@ export interface OwnProps extends QueryTemplateProps { sortField: SortField; fields: string[]; } -type TimelineQueryProps = OwnProps & TimelineQueryReduxProps; +type TimelineQueryProps = OwnProps & TimelineQueryReduxProps & WithKibanaProps; class TimelineQueryComponent extends QueryTemplate< TimelineQueryProps, @@ -71,6 +72,7 @@ class TimelineQueryComponent extends QueryTemplate< id, indexPattern, isInspected, + kibana, limit, fields, filterQuery, @@ -84,7 +86,8 @@ class TimelineQueryComponent extends QueryTemplate< pagination: { limit, cursor: null, tiebreaker: null }, sortField, defaultIndex: - indexPattern?.title.split(',') ?? chrome.getUiSettingsClient().get(DEFAULT_INDEX_KEY), + indexPattern?.title.split(',') ?? + kibana.services.uiSettings.get<string[]>(DEFAULT_INDEX_KEY), inspect: isInspected, }; return ( @@ -158,4 +161,7 @@ const makeMapStateToProps = () => { return mapStateToProps; }; -export const TimelineQuery = connect(makeMapStateToProps)(TimelineQueryComponent); +export const TimelineQuery = compose<React.ComponentClass<OwnProps>>( + connect(makeMapStateToProps), + withKibana +)(TimelineQueryComponent); diff --git a/x-pack/legacy/plugins/siem/public/containers/tls/index.tsx b/x-pack/legacy/plugins/siem/public/containers/tls/index.tsx index 7abe14ae745c5..3738355c8846e 100644 --- a/x-pack/legacy/plugins/siem/public/containers/tls/index.tsx +++ b/x-pack/legacy/plugins/siem/public/containers/tls/index.tsx @@ -10,7 +10,6 @@ import { Query } from 'react-apollo'; import { connect } from 'react-redux'; import { compose } from 'redux'; -import chrome from 'ui/chrome'; import { DEFAULT_INDEX_KEY } from '../../../common/constants'; import { PageInfoPaginated, @@ -20,6 +19,7 @@ import { FlowTargetSourceDest, } from '../../graphql/types'; import { inputsModel, networkModel, networkSelectors, State, inputsSelectors } from '../../store'; +import { withKibana, WithKibanaProps } from '../../lib/kibana'; import { createFilter, getDefaultFetchPolicy } from '../helpers'; import { generateTablePaginationOptions } from '../../components/paginated_table/helpers'; import { QueryTemplatePaginated, QueryTemplatePaginatedProps } from '../query_template_paginated'; @@ -53,7 +53,7 @@ export interface TlsComponentReduxProps { sort: TlsSortField; } -type TlsProps = OwnProps & TlsComponentReduxProps; +type TlsProps = OwnProps & TlsComponentReduxProps & WithKibanaProps; class TlsComponentQuery extends QueryTemplatePaginated< TlsProps, @@ -70,6 +70,7 @@ class TlsComponentQuery extends QueryTemplatePaginated< id = ID, ip, isInspected, + kibana, limit, skip, sourceId, @@ -77,7 +78,7 @@ class TlsComponentQuery extends QueryTemplatePaginated< sort, } = this.props; const variables: GetTlsQuery.Variables = { - defaultIndex: chrome.getUiSettingsClient().get(DEFAULT_INDEX_KEY), + defaultIndex: kibana.services.uiSettings.get<string[]>(DEFAULT_INDEX_KEY), filterQuery: createFilter(filterQuery), flowTarget, inspect: isInspected, @@ -152,6 +153,7 @@ const makeMapStateToProps = () => { }; }; -export const TlsQuery = compose<React.ComponentClass<OwnProps>>(connect(makeMapStateToProps))( - TlsComponentQuery -); +export const TlsQuery = compose<React.ComponentClass<OwnProps>>( + connect(makeMapStateToProps), + withKibana +)(TlsComponentQuery); diff --git a/x-pack/legacy/plugins/siem/public/containers/uncommon_processes/index.tsx b/x-pack/legacy/plugins/siem/public/containers/uncommon_processes/index.tsx index e623110fb7178..520ade954eb5c 100644 --- a/x-pack/legacy/plugins/siem/public/containers/uncommon_processes/index.tsx +++ b/x-pack/legacy/plugins/siem/public/containers/uncommon_processes/index.tsx @@ -8,8 +8,8 @@ import { getOr } from 'lodash/fp'; import React from 'react'; import { Query } from 'react-apollo'; import { connect } from 'react-redux'; +import { compose } from 'redux'; -import chrome from 'ui/chrome'; import { DEFAULT_INDEX_KEY } from '../../../common/constants'; import { GetUncommonProcessesQuery, @@ -17,6 +17,7 @@ import { UncommonProcessesEdges, } from '../../graphql/types'; import { hostsModel, hostsSelectors, inputsModel, State, inputsSelectors } from '../../store'; +import { withKibana, WithKibanaProps } from '../../lib/kibana'; import { generateTablePaginationOptions } from '../../components/paginated_table/helpers'; import { createFilter, getDefaultFetchPolicy } from '../helpers'; import { QueryTemplatePaginated, QueryTemplatePaginatedProps } from '../query_template_paginated'; @@ -48,7 +49,7 @@ export interface UncommonProcessesComponentReduxProps { limit: number; } -type UncommonProcessesProps = OwnProps & UncommonProcessesComponentReduxProps; +type UncommonProcessesProps = OwnProps & UncommonProcessesComponentReduxProps & WithKibanaProps; class UncommonProcessesComponentQuery extends QueryTemplatePaginated< UncommonProcessesProps, @@ -63,13 +64,14 @@ class UncommonProcessesComponentQuery extends QueryTemplatePaginated< filterQuery, id = ID, isInspected, + kibana, limit, skip, sourceId, startDate, } = this.props; const variables: GetUncommonProcessesQuery.Variables = { - defaultIndex: chrome.getUiSettingsClient().get(DEFAULT_INDEX_KEY), + defaultIndex: kibana.services.uiSettings.get<string[]>(DEFAULT_INDEX_KEY), filterQuery: createFilter(filterQuery), inspect: isInspected, pagination: generateTablePaginationOptions(activePage, limit), @@ -142,4 +144,7 @@ const makeMapStateToProps = () => { return mapStateToProps; }; -export const UncommonProcessesQuery = connect(makeMapStateToProps)(UncommonProcessesComponentQuery); +export const UncommonProcessesQuery = compose<React.ComponentClass<OwnProps>>( + connect(makeMapStateToProps), + withKibana +)(UncommonProcessesComponentQuery); diff --git a/x-pack/legacy/plugins/siem/public/containers/users/index.tsx b/x-pack/legacy/plugins/siem/public/containers/users/index.tsx index ea6453b5c5dd4..ece73b7b10ff0 100644 --- a/x-pack/legacy/plugins/siem/public/containers/users/index.tsx +++ b/x-pack/legacy/plugins/siem/public/containers/users/index.tsx @@ -8,8 +8,8 @@ import { getOr } from 'lodash/fp'; import React from 'react'; import { Query } from 'react-apollo'; import { connect } from 'react-redux'; +import { compose } from 'redux'; -import chrome from 'ui/chrome'; import { DEFAULT_INDEX_KEY } from '../../../common/constants'; import { GetUsersQuery, @@ -19,6 +19,7 @@ import { UsersSortField, } from '../../graphql/types'; import { inputsModel, networkModel, networkSelectors, State, inputsSelectors } from '../../store'; +import { withKibana, WithKibanaProps } from '../../lib/kibana'; import { createFilter, getDefaultFetchPolicy } from '../helpers'; import { generateTablePaginationOptions } from '../../components/paginated_table/helpers'; import { QueryTemplatePaginated, QueryTemplatePaginatedProps } from '../query_template_paginated'; @@ -53,7 +54,7 @@ export interface UsersComponentReduxProps { sort: UsersSortField; } -type UsersProps = OwnProps & UsersComponentReduxProps; +type UsersProps = OwnProps & UsersComponentReduxProps & WithKibanaProps; class UsersComponentQuery extends QueryTemplatePaginated< UsersProps, @@ -70,6 +71,7 @@ class UsersComponentQuery extends QueryTemplatePaginated< id = ID, ip, isInspected, + kibana, limit, skip, sourceId, @@ -77,7 +79,7 @@ class UsersComponentQuery extends QueryTemplatePaginated< sort, } = this.props; const variables: GetUsersQuery.Variables = { - defaultIndex: chrome.getUiSettingsClient().get(DEFAULT_INDEX_KEY), + defaultIndex: kibana.services.uiSettings.get<string[]>(DEFAULT_INDEX_KEY), filterQuery: createFilter(filterQuery), flowTarget, inspect: isInspected, @@ -154,4 +156,7 @@ const makeMapStateToProps = () => { return mapStateToProps; }; -export const UsersQuery = connect(makeMapStateToProps)(UsersComponentQuery); +export const UsersQuery = compose<React.ComponentClass<OwnProps>>( + connect(makeMapStateToProps), + withKibana +)(UsersComponentQuery); diff --git a/x-pack/legacy/plugins/siem/public/hooks/use_index_patterns.tsx b/x-pack/legacy/plugins/siem/public/hooks/use_index_patterns.tsx index 091315df314d9..f5b595b0d01c6 100644 --- a/x-pack/legacy/plugins/siem/public/hooks/use_index_patterns.tsx +++ b/x-pack/legacy/plugins/siem/public/hooks/use_index_patterns.tsx @@ -10,7 +10,7 @@ import { DEFAULT_KBN_VERSION } from '../../common/constants'; import { useStateToaster } from '../components/toasters'; import { errorToToaster } from '../components/ml/api/error_to_toaster'; import { IndexPatternSavedObject } from '../components/ml_popover/types'; -import { useKibanaUiSetting } from '../lib/settings/use_kibana_ui_setting'; +import { useUiSetting$ } from '../lib/kibana'; import { getIndexPatterns } from './api/api'; import * as i18n from './translations'; @@ -21,7 +21,7 @@ export const useIndexPatterns = (refreshToggle = false): Return => { const [indexPatterns, setIndexPatterns] = useState<IndexPatternSavedObject[]>([]); const [isLoading, setIsLoading] = useState(true); const [, dispatchToaster] = useStateToaster(); - const [kbnVersion] = useKibanaUiSetting(DEFAULT_KBN_VERSION); + const [kbnVersion] = useUiSetting$<string>(DEFAULT_KBN_VERSION); useEffect(() => { let isSubscribed = true; diff --git a/x-pack/legacy/plugins/siem/public/lib/compose/__mocks__/kibana_core.ts b/x-pack/legacy/plugins/siem/public/lib/compose/__mocks__/kibana_core.ts deleted file mode 100644 index 7511f65dfb309..0000000000000 --- a/x-pack/legacy/plugins/siem/public/lib/compose/__mocks__/kibana_core.ts +++ /dev/null @@ -1,13 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import { createUiNewPlatformMock } from 'ui/new_platform/__mocks__/helpers'; - -const npStart = createUiNewPlatformMock().npStart; - -export function useKibanaCore() { - return npStart.core; -} diff --git a/x-pack/legacy/plugins/siem/public/lib/compose/__mocks__/kibana_plugins.ts b/x-pack/legacy/plugins/siem/public/lib/compose/__mocks__/kibana_plugins.ts deleted file mode 100644 index ab255f7c73a06..0000000000000 --- a/x-pack/legacy/plugins/siem/public/lib/compose/__mocks__/kibana_plugins.ts +++ /dev/null @@ -1,13 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import { createUiNewPlatformMock } from 'ui/new_platform/__mocks__/helpers'; - -const npStart = createUiNewPlatformMock().npStart; - -export function useKibanaPlugins() { - return npStart.plugins; -} diff --git a/x-pack/legacy/plugins/siem/public/lib/compose/kibana_core.tsx b/x-pack/legacy/plugins/siem/public/lib/compose/kibana_core.tsx deleted file mode 100644 index f2fa261bf3eb4..0000000000000 --- a/x-pack/legacy/plugins/siem/public/lib/compose/kibana_core.tsx +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import React, { createContext, useContext } from 'react'; -import { LegacyCoreStart } from 'src/core/public'; - -interface CoreMountContext { - core: LegacyCoreStart; -} - -// TODO: Replace CoreStart/CoreSetup with AppMountContext -// see: https://github.com/elastic/kibana/pull/41007 - -export const KibanaCoreContext = createContext({} as CoreMountContext['core']); - -export const KibanaCoreContextProvider: React.FC<{ core: CoreMountContext['core'] }> = props => ( - <KibanaCoreContext.Provider {...props} value={props.core} children={props.children} /> -); - -export function useKibanaCore() { - return useContext(KibanaCoreContext); -} diff --git a/x-pack/legacy/plugins/siem/public/lib/compose/kibana_plugins.tsx b/x-pack/legacy/plugins/siem/public/lib/compose/kibana_plugins.tsx deleted file mode 100644 index 7d1f1bc01edd3..0000000000000 --- a/x-pack/legacy/plugins/siem/public/lib/compose/kibana_plugins.tsx +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import React, { createContext, useContext } from 'react'; -import { PluginsStart } from 'ui/new_platform/new_platform'; - -interface PluginsMountContext { - plugins: PluginsStart; -} - -// TODO: Replace CoreStart/CoreSetup with AppMountContext -// see: https://github.com/elastic/kibana/pull/41007 - -export const KibanaPluginsContext = createContext({} as PluginsMountContext['plugins']); - -export const KibanaPluginsContextProvider: React.FC<{ - plugins: PluginsMountContext['plugins']; -}> = props => ( - <KibanaPluginsContext.Provider {...props} value={props.plugins} children={props.children} /> -); - -export function useKibanaPlugins() { - return useContext(KibanaPluginsContext); -} diff --git a/x-pack/legacy/plugins/siem/public/lib/kibana/__mocks__/index.ts b/x-pack/legacy/plugins/siem/public/lib/kibana/__mocks__/index.ts new file mode 100644 index 0000000000000..93fd37c4d14cb --- /dev/null +++ b/x-pack/legacy/plugins/siem/public/lib/kibana/__mocks__/index.ts @@ -0,0 +1,19 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { + createKibanaContextProviderMock, + createUseUiSettingMock, + createUseUiSetting$Mock, + createUseKibanaMock, + createWithKibanaMock, +} from '../../../mock/kibana_react'; + +export const useKibana = jest.fn(createUseKibanaMock()); +export const useUiSetting = jest.fn(createUseUiSettingMock()); +export const useUiSetting$ = jest.fn(createUseUiSetting$Mock()); +export const withKibana = jest.fn(createWithKibanaMock()); +export const KibanaContextProvider = jest.fn(createKibanaContextProviderMock()); diff --git a/x-pack/legacy/plugins/siem/public/lib/kibana/index.ts b/x-pack/legacy/plugins/siem/public/lib/kibana/index.ts new file mode 100644 index 0000000000000..96d9c8330d265 --- /dev/null +++ b/x-pack/legacy/plugins/siem/public/lib/kibana/index.ts @@ -0,0 +1,31 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { + KibanaContextProvider, + KibanaReactContextValue, + useKibana, + useUiSetting, + useUiSetting$, + withKibana, +} from '../../../../../../../src/plugins/kibana_react/public'; +import { StartServices } from '../../apps/plugin'; + +export type KibanaContext = KibanaReactContextValue<StartServices>; +export interface WithKibanaProps { + kibana: KibanaContext; +} + +// eslint-disable-next-line react-hooks/rules-of-hooks +const typedUseKibana = () => useKibana<StartServices>(); + +export { + KibanaContextProvider, + typedUseKibana as useKibana, + useUiSetting, + useUiSetting$, + withKibana, +}; diff --git a/x-pack/legacy/plugins/siem/public/lib/settings/__mocks__/use_kibana_ui_setting.ts b/x-pack/legacy/plugins/siem/public/lib/settings/__mocks__/use_kibana_ui_setting.ts deleted file mode 100644 index 9f5639ce19997..0000000000000 --- a/x-pack/legacy/plugins/siem/public/lib/settings/__mocks__/use_kibana_ui_setting.ts +++ /dev/null @@ -1,13 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import { mockFrameworks, getMockKibanaUiSetting } from '../../../mock'; - -type GenericValue = string | boolean | number; - -export const useKibanaUiSetting = (key: string, defaultValue?: GenericValue) => { - return getMockKibanaUiSetting(mockFrameworks.default_UTC)(key); -}; diff --git a/x-pack/legacy/plugins/siem/public/lib/settings/use_kibana_ui_setting.ts b/x-pack/legacy/plugins/siem/public/lib/settings/use_kibana_ui_setting.ts deleted file mode 100644 index 0a89edb85e6ea..0000000000000 --- a/x-pack/legacy/plugins/siem/public/lib/settings/use_kibana_ui_setting.ts +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import { useCallback, useMemo } from 'react'; -// @ts-ignore: path dynamic for kibana -import { timezoneProvider } from 'ui/vis/lib/timezone'; - -import { DEFAULT_KBN_VERSION, DEFAULT_TIMEZONE_BROWSER } from '../../../common/constants'; -import { useKibanaCore } from '../compose/kibana_core'; -import { useObservable } from './use_observable'; - -type GenericValue = string | boolean | number; - -/** - * This hook behaves like a `useState` hook in that it provides a requested - * setting value (with an optional default) from the Kibana UI settings (also - * known as "advanced settings") and a setter to change that setting: - * - * ``` - * const [darkMode, setDarkMode] = useKibanaUiSetting('theme:darkMode'); - * ``` - * - * This is not just a static consumption of the value, but will reactively - * update when the underlying setting subscription of the `UiSettingsClient` - * notifies of a change. - * - * Unlike the `useState`, it doesn't give type guarantees for the value, - * because the underlying `UiSettingsClient` doesn't support that. - */ -export const useKibanaUiSetting = (key: string, defaultValue?: GenericValue) => { - const core = useKibanaCore(); - const uiSettingsClient = core.uiSettings; - const uiInjectedMetadata = core.injectedMetadata; - - if (key === DEFAULT_KBN_VERSION) { - return [uiInjectedMetadata.getKibanaVersion()]; - } - - /* eslint-disable react-hooks/rules-of-hooks */ - if (key === DEFAULT_TIMEZONE_BROWSER) { - return [useMemo(() => timezoneProvider(uiSettingsClient)(), [uiSettingsClient])]; - } - - const uiSetting$ = useMemo(() => uiSettingsClient.get$(key, defaultValue), [uiSettingsClient]); - const uiSetting = useObservable(uiSetting$); - const setUiSetting = useCallback((value: GenericValue) => uiSettingsClient.set(key, value), [ - uiSettingsClient, - ]); - /* eslint-enable react-hooks/rules-of-hooks */ - - return [uiSetting, setUiSetting]; -}; diff --git a/x-pack/legacy/plugins/siem/public/lib/settings/use_kibana_ui_settings.test.tsx b/x-pack/legacy/plugins/siem/public/lib/settings/use_kibana_ui_settings.test.tsx deleted file mode 100644 index 9af4759b25608..0000000000000 --- a/x-pack/legacy/plugins/siem/public/lib/settings/use_kibana_ui_settings.test.tsx +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ -import * as React from 'react'; - -import { DEFAULT_KBN_VERSION, DEFAULT_TIMEZONE_BROWSER } from '../../../common/constants'; -import { HookWrapper } from '../../mock/hook_wrapper'; -import { useKibanaCore } from '../compose/kibana_core'; -import { useKibanaUiSetting } from './use_kibana_ui_setting'; -import { mount } from 'enzyme'; - -const mockUseKibanaCore = useKibanaCore as jest.Mock; -jest.mock('../compose/kibana_core'); -mockUseKibanaCore.mockImplementation(() => ({ - injectedMetadata: { - getKibanaVersion: () => '8.0.0', - }, - uiSettings: { - get$: () => 'world', - }, -})); - -jest.mock('ui/vis/lib/timezone', () => ({ - timezoneProvider: () => () => 'America/New_York', -})); - -jest.mock('./use_observable', () => ({ - useObservable: (val: string) => val, -})); - -describe('useKibanaUiSetting', () => { - test('getKibanaVersion', () => { - const wrapper = mount(<HookWrapper hook={() => useKibanaUiSetting(DEFAULT_KBN_VERSION)} />); - expect(wrapper.text()).toEqual('["8.0.0"]'); - }); - - test('getTimezone', () => { - const wrapper = mount( - <HookWrapper hook={() => useKibanaUiSetting(DEFAULT_TIMEZONE_BROWSER)} /> - ); - expect(wrapper.text()).toEqual('["America/New_York"]'); - }); - - test('get any ui settings', () => { - const wrapper = mount(<HookWrapper hook={() => useKibanaUiSetting('hello')} />); - expect(wrapper.text()).toEqual('["world",null]'); - }); -}); diff --git a/x-pack/legacy/plugins/siem/public/lib/settings/use_observable.ts b/x-pack/legacy/plugins/siem/public/lib/settings/use_observable.ts deleted file mode 100644 index 536b6b2723ae0..0000000000000 --- a/x-pack/legacy/plugins/siem/public/lib/settings/use_observable.ts +++ /dev/null @@ -1,21 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import { useEffect, useState } from 'react'; -import { Observable } from 'rxjs'; - -export function useObservable<T>(observable$: Observable<T>): T | undefined; -export function useObservable<T>(observable$: Observable<T>, initialValue: T): T; -export function useObservable<T>(observable$: Observable<T>, initialValue?: T): T | undefined { - const [value, update] = useState<T | undefined>(initialValue); - - useEffect(() => { - const s = observable$.subscribe(update); - return () => s.unsubscribe(); - }, [observable$]); - - return value; -} diff --git a/x-pack/legacy/plugins/siem/public/lib/theme/use_eui_theme.tsx b/x-pack/legacy/plugins/siem/public/lib/theme/use_eui_theme.tsx index b1defcb34066d..1696001203bc8 100644 --- a/x-pack/legacy/plugins/siem/public/lib/theme/use_eui_theme.tsx +++ b/x-pack/legacy/plugins/siem/public/lib/theme/use_eui_theme.tsx @@ -8,9 +8,9 @@ import darkTheme from '@elastic/eui/dist/eui_theme_dark.json'; import lightTheme from '@elastic/eui/dist/eui_theme_light.json'; import { DEFAULT_DARK_MODE } from '../../../common/constants'; -import { useKibanaUiSetting } from '../settings/use_kibana_ui_setting'; +import { useUiSetting$ } from '../kibana'; export const useEuiTheme = () => { - const [darkMode] = useKibanaUiSetting(DEFAULT_DARK_MODE); + const [darkMode] = useUiSetting$<boolean>(DEFAULT_DARK_MODE); return darkMode ? darkTheme : lightTheme; }; diff --git a/x-pack/legacy/plugins/siem/public/mock/kibana_core.ts b/x-pack/legacy/plugins/siem/public/mock/kibana_core.ts new file mode 100644 index 0000000000000..cf3523a6260bb --- /dev/null +++ b/x-pack/legacy/plugins/siem/public/mock/kibana_core.ts @@ -0,0 +1,13 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import { createUiNewPlatformMock } from 'ui/new_platform/__mocks__/helpers'; + +export const createKibanaCoreSetupMock = () => createUiNewPlatformMock().npSetup.core; +export const createKibanaPluginsSetupMock = () => createUiNewPlatformMock().npSetup.plugins; + +export const createKibanaCoreStartMock = () => createUiNewPlatformMock().npStart.core; +export const createKibanaPluginsStartMock = () => createUiNewPlatformMock().npStart.plugins; diff --git a/x-pack/legacy/plugins/siem/public/mock/kibana_react.ts b/x-pack/legacy/plugins/siem/public/mock/kibana_react.ts new file mode 100644 index 0000000000000..15944df1822b3 --- /dev/null +++ b/x-pack/legacy/plugins/siem/public/mock/kibana_react.ts @@ -0,0 +1,95 @@ +/* + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one + * or more contributor license agreements. Licensed under the Elastic License; + * you may not use this file except in compliance with the Elastic License. + */ + +import React from 'react'; +import { KibanaContextProvider } from '../../../../../../src/plugins/kibana_react/public'; + +import { + DEFAULT_SIEM_TIME_RANGE, + DEFAULT_SIEM_REFRESH_INTERVAL, + DEFAULT_INDEX_KEY, + DEFAULT_DATE_FORMAT, + DEFAULT_DATE_FORMAT_TZ, + DEFAULT_DARK_MODE, + DEFAULT_TIME_RANGE, + DEFAULT_REFRESH_RATE_INTERVAL, + DEFAULT_FROM, + DEFAULT_TO, + DEFAULT_INTERVAL_PAUSE, + DEFAULT_INTERVAL_VALUE, + DEFAULT_TIMEZONE_BROWSER, +} from '../../common/constants'; +import { defaultIndexPattern } from '../../default_index_pattern'; +import { createKibanaCoreStartMock, createKibanaPluginsStartMock } from './kibana_core'; + +// eslint-disable-next-line @typescript-eslint/no-explicit-any +export const mockUiSettings: Record<string, any> = { + [DEFAULT_TIME_RANGE]: { from: 'now-15m', to: 'now', mode: 'quick' }, + [DEFAULT_REFRESH_RATE_INTERVAL]: { pause: false, value: 0 }, + [DEFAULT_SIEM_TIME_RANGE]: { + from: DEFAULT_FROM, + to: DEFAULT_TO, + }, + [DEFAULT_SIEM_REFRESH_INTERVAL]: { + pause: DEFAULT_INTERVAL_PAUSE, + value: DEFAULT_INTERVAL_VALUE, + }, + [DEFAULT_INDEX_KEY]: defaultIndexPattern, + [DEFAULT_DATE_FORMAT_TZ]: 'UTC', + [DEFAULT_TIMEZONE_BROWSER]: 'America/New_York', + [DEFAULT_DATE_FORMAT]: 'MMM D, YYYY @ HH:mm:ss.SSS', + [DEFAULT_DARK_MODE]: false, +}; + +export const createUseUiSettingMock = () => <T extends unknown = string>( + key: string, + defaultValue?: T +): T => { + const result = mockUiSettings[key]; + + if (typeof result != null) return result; + + if (defaultValue != null) { + return defaultValue; + } + + throw new Error(`Unexpected config key: ${key}`); +}; + +export const createUseUiSetting$Mock = () => { + const useUiSettingMock = createUseUiSettingMock(); + + return <T extends unknown = string>( + key: string, + defaultValue?: T + ): [T, () => void] | undefined => [useUiSettingMock(key, defaultValue), jest.fn()]; +}; + +export const createUseKibanaMock = () => { + const services = { ...createKibanaCoreStartMock(), ...createKibanaPluginsStartMock() }; + + return () => ({ services }); +}; + +export const createWithKibanaMock = () => { + const kibana = createUseKibanaMock()(); + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return (Component: any) => (props: any) => { + return React.createElement(Component, { ...props, kibana }); + }; +}; + +export const createKibanaContextProviderMock = () => { + const kibana = createUseKibanaMock()(); + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return ({ services, ...rest }: any) => + React.createElement(KibanaContextProvider, { + ...rest, + services: { ...kibana.services, ...services }, + }); +}; diff --git a/x-pack/legacy/plugins/siem/public/mock/test_providers.tsx b/x-pack/legacy/plugins/siem/public/mock/test_providers.tsx index d4c06d998c5a2..6c0a85e3ef778 100644 --- a/x-pack/legacy/plugins/siem/public/mock/test_providers.tsx +++ b/x-pack/legacy/plugins/siem/public/mock/test_providers.tsx @@ -17,12 +17,9 @@ import { Store } from 'redux'; import { BehaviorSubject } from 'rxjs'; import { ThemeProvider } from 'styled-components'; -import { CoreStart } from 'src/core/public'; -import { KibanaContextProvider } from '../../../../../../src/plugins/kibana_react/public'; - import { createStore, State } from '../store'; import { mockGlobalState } from './global_state'; -import { mockUiSettings } from './ui_settings'; +import { createKibanaContextProviderMock } from './kibana_react'; jest.mock('ui/new_platform'); @@ -41,29 +38,6 @@ export const apolloClient = new ApolloClient({ export const apolloClientObservable = new BehaviorSubject(apolloClient); -const services = { - uiSettings: mockUiSettings, - savedObjects: {} as CoreStart['savedObjects'], - notifications: {} as CoreStart['notifications'], - docLinks: { - links: { - query: { - kueryQuerySyntax: '', - }, - }, - } as CoreStart['docLinks'], - http: {} as CoreStart['http'], - overlays: {} as CoreStart['overlays'], - storage: { - get: () => {}, - }, - data: { - query: { - savedQueries: {}, - }, - }, -}; - const localStorageMock = () => { let store: Record<string, unknown> = {}; @@ -84,11 +58,13 @@ Object.defineProperty(window, 'localStorage', { value: localStorageMock(), }); +const MockKibanaContextProvider = createKibanaContextProviderMock(); + /** A utility for wrapping children in the providers required to run most tests */ export const TestProviders = React.memo<Props>( ({ children, store = createStore(state, apolloClientObservable), onDragEnd = jest.fn() }) => ( <I18nProvider> - <KibanaContextProvider services={services}> + <MockKibanaContextProvider> <ApolloProvider client={apolloClient}> <ReduxStoreProvider store={store}> <ThemeProvider theme={() => ({ eui: euiDarkVars, darkMode: true })}> @@ -96,7 +72,7 @@ export const TestProviders = React.memo<Props>( </ThemeProvider> </ReduxStoreProvider> </ApolloProvider> - </KibanaContextProvider> + </MockKibanaContextProvider> </I18nProvider> ) ); diff --git a/x-pack/legacy/plugins/siem/public/mock/ui_settings.ts b/x-pack/legacy/plugins/siem/public/mock/ui_settings.ts deleted file mode 100644 index 6c6411c6bda53..0000000000000 --- a/x-pack/legacy/plugins/siem/public/mock/ui_settings.ts +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one - * or more contributor license agreements. Licensed under the Elastic License; - * you may not use this file except in compliance with the Elastic License. - */ - -import chrome from 'ui/chrome'; -import { - DEFAULT_SIEM_TIME_RANGE, - DEFAULT_SIEM_REFRESH_INTERVAL, - DEFAULT_INDEX_KEY, - DEFAULT_DATE_FORMAT, - DEFAULT_DATE_FORMAT_TZ, - DEFAULT_DARK_MODE, - DEFAULT_TIME_RANGE, - DEFAULT_REFRESH_RATE_INTERVAL, - DEFAULT_FROM, - DEFAULT_TO, - DEFAULT_INTERVAL_PAUSE, - DEFAULT_INTERVAL_VALUE, -} from '../../common/constants'; -import { defaultIndexPattern } from '../../default_index_pattern'; - -chrome.getUiSettingsClient().get.mockImplementation((key: string) => { - switch (key) { - case DEFAULT_TIME_RANGE: - return { from: 'now-15m', to: 'now', mode: 'quick' }; - case DEFAULT_REFRESH_RATE_INTERVAL: - return { pause: false, value: 0 }; - case DEFAULT_SIEM_TIME_RANGE: - return { - from: DEFAULT_FROM, - to: DEFAULT_TO, - }; - case DEFAULT_SIEM_REFRESH_INTERVAL: - return { - pause: DEFAULT_INTERVAL_PAUSE, - value: DEFAULT_INTERVAL_VALUE, - }; - case DEFAULT_INDEX_KEY: - return defaultIndexPattern; - case DEFAULT_DATE_FORMAT_TZ: - return 'Asia/Taipei'; - case DEFAULT_DATE_FORMAT: - return 'MMM D, YYYY @ HH:mm:ss.SSS'; - case DEFAULT_DARK_MODE: - return false; - default: - throw new Error(`Unexpected config key: ${key}`); - } -}); - -export interface MockNpSetUp { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - core: { uiSettings: any }; -} - -type Config = - | 'query:allowLeadingWildcards' - | 'query:queryString:options' - | 'courier:ignoreFilterIfFieldNotInIndex' - | 'dateFormat:tz'; - -export const mockUiSettings = { - get: (item: Config) => { - return mockUiSettings[item]; - }, - get$: () => ({ - subscribe: jest.fn(), - }), - 'query:allowLeadingWildcards': true, - 'query:queryString:options': {}, - 'courier:ignoreFilterIfFieldNotInIndex': true, - 'dateFormat:tz': 'Browser', -}; diff --git a/x-pack/legacy/plugins/siem/public/pages/detection_engine/create_rule/components/query_bar/index.tsx b/x-pack/legacy/plugins/siem/public/pages/detection_engine/create_rule/components/query_bar/index.tsx index 8dc402f00e621..8c099652d4d29 100644 --- a/x-pack/legacy/plugins/siem/public/pages/detection_engine/create_rule/components/query_bar/index.tsx +++ b/x-pack/legacy/plugins/siem/public/pages/detection_engine/create_rule/components/query_bar/index.tsx @@ -20,7 +20,7 @@ import { } from '../../../../../../../../../../src/plugins/data/public'; import { QueryBar } from '../../../../../components/query_bar'; -import { useKibanaCore } from '../../../../../lib/compose/kibana_core'; +import { useKibana } from '../../../../../lib/kibana'; import { useSavedQueryServices } from '../../../../../utils/saved_query_services'; import { FieldHook, getFieldValidityAndErrorMessage } from '../shared_imports'; @@ -68,8 +68,8 @@ export const QueryBarDefineRule = ({ const [queryDraft, setQueryDraft] = useState<Query>({ query: '', language: 'kuery' }); const { isInvalid, errorMessage } = getFieldValidityAndErrorMessage(field); - const core = useKibanaCore(); - const [filterManager] = useState<FilterManager>(new FilterManager(core.uiSettings)); + const kibana = useKibana(); + const [filterManager] = useState<FilterManager>(new FilterManager(kibana.services.uiSettings)); const savedQueryServices = useSavedQueryServices(); diff --git a/x-pack/legacy/plugins/siem/public/pages/detection_engine/create_rule/components/step_define_rule/index.tsx b/x-pack/legacy/plugins/siem/public/pages/detection_engine/create_rule/components/step_define_rule/index.tsx index 6954bd6bf733f..7a21f265717e5 100644 --- a/x-pack/legacy/plugins/siem/public/pages/detection_engine/create_rule/components/step_define_rule/index.tsx +++ b/x-pack/legacy/plugins/siem/public/pages/detection_engine/create_rule/components/step_define_rule/index.tsx @@ -11,7 +11,7 @@ import React, { memo, useCallback, useState } from 'react'; import { IIndexPattern } from '../../../../../../../../../../src/plugins/data/public'; import { useFetchIndexPatterns } from '../../../../../containers/detection_engine/rules/fetch_index_patterns'; import { DEFAULT_INDEX_KEY } from '../../../../../../common/constants'; -import { useKibanaUiSetting } from '../../../../../lib/settings/use_kibana_ui_setting'; +import { useUiSetting$ } from '../../../../../lib/kibana'; import * as CreateRuleI18n from '../../translations'; import { DefineStepRule, RuleStep, RuleStepProps } from '../../types'; import { StepRuleDescription } from '../description_step'; @@ -29,7 +29,7 @@ export const StepDefineRule = memo<RuleStepProps>( { indexPatterns: indexPatternQueryBar, isLoading: indexPatternLoadingQueryBar }, setIndices, ] = useFetchIndexPatterns(); - const [indicesConfig] = useKibanaUiSetting(DEFAULT_INDEX_KEY); + const [indicesConfig] = useUiSetting$<string[]>(DEFAULT_INDEX_KEY); const [myStepData, setMyStepData] = useState<DefineStepRule>({ index: indicesConfig || [], isNew: true, diff --git a/x-pack/legacy/plugins/siem/public/pages/detection_engine/detection_engine_empty_page.tsx b/x-pack/legacy/plugins/siem/public/pages/detection_engine/detection_engine_empty_page.tsx index cb3e690615395..a217fd6a737e7 100644 --- a/x-pack/legacy/plugins/siem/public/pages/detection_engine/detection_engine_empty_page.tsx +++ b/x-pack/legacy/plugins/siem/public/pages/detection_engine/detection_engine_empty_page.tsx @@ -6,8 +6,8 @@ import React from 'react'; import chrome from 'ui/chrome'; -import { documentationLinks } from 'ui/documentation_links'; +import { useKibana } from '../../lib/kibana'; import { EmptyPage } from '../../components/empty_page'; import * as i18n from './translations'; @@ -21,7 +21,7 @@ export const DetectionEngineEmptyPage = React.memo(() => ( actionSecondaryIcon="popout" actionSecondaryLabel={i18n.EMPTY_ACTION_SECONDARY} actionSecondaryTarget="_blank" - actionSecondaryUrl={documentationLinks.siem} + actionSecondaryUrl={useKibana().services.docLinks.links.siem} data-test-subj="empty-page" title={i18n.EMPTY_TITLE} /> diff --git a/x-pack/legacy/plugins/siem/public/pages/detection_engine/rules/all_rules/index.tsx b/x-pack/legacy/plugins/siem/public/pages/detection_engine/rules/all_rules/index.tsx index a73ebeb61db3c..89d1ec6b1bcef 100644 --- a/x-pack/legacy/plugins/siem/public/pages/detection_engine/rules/all_rules/index.tsx +++ b/x-pack/legacy/plugins/siem/public/pages/detection_engine/rules/all_rules/index.tsx @@ -30,7 +30,7 @@ import { getBatchItems } from './batch_actions'; import { EuiBasicTableOnChange, TableData } from '../types'; import { allRulesReducer, State } from './reducer'; import * as i18n from '../translations'; -import { useKibanaUiSetting } from '../../../../lib/settings/use_kibana_ui_setting'; +import { useUiSetting$ } from '../../../../lib/kibana'; import { DEFAULT_KBN_VERSION } from '../../../../../common/constants'; import { JSONDownloader } from '../components/json_downloader'; import { useStateToaster } from '../../../../components/toasters'; @@ -77,7 +77,7 @@ export const AllRules = React.memo<{ importCompleteToggle: boolean }>(importComp const [isInitialLoad, setIsInitialLoad] = useState(true); const [isLoadingRules, rulesData] = useRules(pagination, filterOptions, refreshToggle); - const [kbnVersion] = useKibanaUiSetting(DEFAULT_KBN_VERSION); + const [kbnVersion] = useUiSetting$<string>(DEFAULT_KBN_VERSION); const [, dispatchToaster] = useStateToaster(); const getBatchItemsPopoverContent = useCallback( diff --git a/x-pack/legacy/plugins/siem/public/pages/detection_engine/rules/components/import_rule_modal/index.test.tsx b/x-pack/legacy/plugins/siem/public/pages/detection_engine/rules/components/import_rule_modal/index.test.tsx index 8dcce36e1a409..381a3138bf617 100644 --- a/x-pack/legacy/plugins/siem/public/pages/detection_engine/rules/components/import_rule_modal/index.test.tsx +++ b/x-pack/legacy/plugins/siem/public/pages/detection_engine/rules/components/import_rule_modal/index.test.tsx @@ -8,20 +8,11 @@ import { shallow } from 'enzyme'; import toJson from 'enzyme-to-json'; import * as React from 'react'; import { ImportRuleModalComponent } from './index'; -import { useKibanaUiSetting } from '../../../../../lib/settings/use_kibana_ui_setting'; -import { getMockKibanaUiSetting, MockFrameworks } from '../../../../../mock'; -import { DEFAULT_KBN_VERSION } from '../../../../../../common/constants'; -const mockUseKibanaUiSetting: jest.Mock = useKibanaUiSetting as jest.Mock; -jest.mock('../../../../../lib/settings/use_kibana_ui_setting', () => ({ - useKibanaUiSetting: jest.fn(), -})); +jest.mock('../../../../../lib/kibana'); describe('ImportRuleModal', () => { test('renders correctly against snapshot', () => { - mockUseKibanaUiSetting.mockImplementation( - getMockKibanaUiSetting((DEFAULT_KBN_VERSION as unknown) as MockFrameworks) - ); const wrapper = shallow( <ImportRuleModalComponent showModal={true} diff --git a/x-pack/legacy/plugins/siem/public/pages/detection_engine/rules/components/import_rule_modal/index.tsx b/x-pack/legacy/plugins/siem/public/pages/detection_engine/rules/components/import_rule_modal/index.tsx index 4c0f477ab525e..cc97954c931ac 100644 --- a/x-pack/legacy/plugins/siem/public/pages/detection_engine/rules/components/import_rule_modal/index.tsx +++ b/x-pack/legacy/plugins/siem/public/pages/detection_engine/rules/components/import_rule_modal/index.tsx @@ -28,7 +28,7 @@ import { fold } from 'fp-ts/lib/Either'; import uuid from 'uuid'; import * as i18n from './translations'; import { duplicateRules } from '../../../../../containers/detection_engine/rules/api'; -import { useKibanaUiSetting } from '../../../../../lib/settings/use_kibana_ui_setting'; +import { useUiSetting$ } from '../../../../../lib/kibana'; import { DEFAULT_KBN_VERSION } from '../../../../../../common/constants'; import { ndjsonToJSON } from '../json_downloader'; import { RulesSchema } from '../../../../../containers/detection_engine/rules/types'; @@ -54,7 +54,7 @@ export const ImportRuleModalComponent = ({ }: ImportRuleModalProps) => { const [selectedFiles, setSelectedFiles] = useState<FileList | null>(null); const [isImporting, setIsImporting] = useState(false); - const [kbnVersion] = useKibanaUiSetting(DEFAULT_KBN_VERSION); + const [kbnVersion] = useUiSetting$<string>(DEFAULT_KBN_VERSION); const [, dispatchToaster] = useStateToaster(); const cleanupAndCloseModal = () => { diff --git a/x-pack/legacy/plugins/siem/public/pages/hosts/details/details_tabs.test.tsx b/x-pack/legacy/plugins/siem/public/pages/hosts/details/details_tabs.test.tsx index 8d45bbbe34d33..092c2463419d1 100644 --- a/x-pack/legacy/plugins/siem/public/pages/hosts/details/details_tabs.test.tsx +++ b/x-pack/legacy/plugins/siem/public/pages/hosts/details/details_tabs.test.tsx @@ -10,21 +10,13 @@ import { MemoryRouter } from 'react-router-dom'; import { mockIndexPattern } from '../../../mock/index_pattern'; import { TestProviders } from '../../../mock/test_providers'; -import { mockUiSettings } from '../../../mock/ui_settings'; import { HostDetailsTabs } from './details_tabs'; import { SetAbsoluteRangeDatePicker } from './types'; import { hostDetailsPagePath } from '../types'; import { type } from './utils'; -import { useKibanaCore } from '../../../lib/compose/kibana_core'; import { useMountAppended } from '../../../utils/use_mount_appended'; -jest.mock('../../../lib/settings/use_kibana_ui_setting'); - -const mockUseKibanaCore = useKibanaCore as jest.Mock; -jest.mock('../../../lib/compose/kibana_core'); -mockUseKibanaCore.mockImplementation(() => ({ - uiSettings: mockUiSettings, -})); +jest.mock('../../../lib/kibana'); jest.mock('../../../containers/source', () => ({ indicesExistOrDataTemporarilyUnavailable: () => true, diff --git a/x-pack/legacy/plugins/siem/public/pages/hosts/details/index.tsx b/x-pack/legacy/plugins/siem/public/pages/hosts/details/index.tsx index e062e65bde496..b548d91615d19 100644 --- a/x-pack/legacy/plugins/siem/public/pages/hosts/details/index.tsx +++ b/x-pack/legacy/plugins/siem/public/pages/hosts/details/index.tsx @@ -28,7 +28,7 @@ import { HostOverviewByNameQuery } from '../../../containers/hosts/overview'; import { KpiHostDetailsQuery } from '../../../containers/kpi_host_details'; import { indicesExistOrDataTemporarilyUnavailable, WithSource } from '../../../containers/source'; import { LastEventIndexKey } from '../../../graphql/types'; -import { useKibanaCore } from '../../../lib/compose/kibana_core'; +import { useKibana } from '../../../lib/kibana'; import { convertToBuildEsQuery } from '../../../lib/keury'; import { inputsSelectors, State } from '../../../store'; import { setHostDetailsTablesActivePageToZero as dispatchHostDetailsTablesActivePageToZero } from '../../../store/hosts/actions'; @@ -63,7 +63,7 @@ const HostDetailsComponent = React.memo<HostDetailsComponentProps>( setHostDetailsTablesActivePageToZero(null); }, [setHostDetailsTablesActivePageToZero, detailName]); const capabilities = useContext(MlCapabilitiesContext); - const core = useKibanaCore(); + const kibana = useKibana(); const hostDetailsPageFilters: esFilters.Filter[] = [ { meta: { @@ -100,7 +100,7 @@ const HostDetailsComponent = React.memo<HostDetailsComponentProps>( <WithSource sourceId="default"> {({ indicesExist, indexPattern }) => { const filterQuery = convertToBuildEsQuery({ - config: esQuery.getEsQueryConfig(core.uiSettings), + config: esQuery.getEsQueryConfig(kibana.services.uiSettings), indexPattern, queries: [query], filters: getFilters(), diff --git a/x-pack/legacy/plugins/siem/public/pages/hosts/hosts.test.tsx b/x-pack/legacy/plugins/siem/public/pages/hosts/hosts.test.tsx index f08cee824afa7..00dcb5908a98b 100644 --- a/x-pack/legacy/plugins/siem/public/pages/hosts/hosts.test.tsx +++ b/x-pack/legacy/plugins/siem/public/pages/hosts/hosts.test.tsx @@ -12,30 +12,15 @@ import { MockedProvider } from 'react-apollo/test-utils'; import { ActionCreator } from 'typescript-fsa'; import '../../mock/match_media'; - -import { SiemNavigation } from '../../components/navigation'; import { mocksSource } from '../../containers/source/mock'; import { wait } from '../../lib/helpers'; import { TestProviders } from '../../mock'; -import { mockUiSettings } from '../../mock/ui_settings'; import { InputsModelId } from '../../store/inputs/constants'; +import { SiemNavigation } from '../../components/navigation'; import { HostsComponentProps } from './types'; import { Hosts } from './hosts'; -import { useKibanaCore } from '../../lib/compose/kibana_core'; - -jest.mock('../../lib/settings/use_kibana_ui_setting'); -const mockUseKibanaCore = useKibanaCore as jest.Mock; -jest.mock('../../lib/compose/kibana_core'); -mockUseKibanaCore.mockImplementation(() => ({ - uiSettings: mockUiSettings, -})); - -jest.mock('ui/documentation_links', () => ({ - documentationLinks: { - kibana: 'http://www.example.com', - }, -})); +jest.mock('../../lib/kibana'); // Test will fail because we will to need to mock some core services to make the test work // For now let's forget about SiemSearchBar and QueryBar diff --git a/x-pack/legacy/plugins/siem/public/pages/hosts/hosts.tsx b/x-pack/legacy/plugins/siem/public/pages/hosts/hosts.tsx index 6d217a9301884..6b69f06b97b83 100644 --- a/x-pack/legacy/plugins/siem/public/pages/hosts/hosts.tsx +++ b/x-pack/legacy/plugins/siem/public/pages/hosts/hosts.tsx @@ -25,7 +25,7 @@ import { GlobalTimeArgs } from '../../containers/global_time'; import { KpiHostsQuery } from '../../containers/kpi_hosts'; import { indicesExistOrDataTemporarilyUnavailable, WithSource } from '../../containers/source'; import { LastEventIndexKey } from '../../graphql/types'; -import { useKibanaCore } from '../../lib/compose/kibana_core'; +import { useKibana } from '../../lib/kibana'; import { convertToBuildEsQuery } from '../../lib/keury'; import { inputsSelectors, State, hostsModel } from '../../store'; import { setAbsoluteRangeDatePicker as dispatchSetAbsoluteRangeDatePicker } from '../../store/inputs/actions'; @@ -54,7 +54,7 @@ const HostsComponent = React.memo<HostsComponentProps>( hostsPagePath, }) => { const capabilities = React.useContext(MlCapabilitiesContext); - const core = useKibanaCore(); + const kibana = useKibana(); const { tabName } = useParams(); const hostsFilters = React.useMemo(() => { @@ -75,7 +75,7 @@ const HostsComponent = React.memo<HostsComponentProps>( <WithSource sourceId="default"> {({ indicesExist, indexPattern }) => { const filterQuery = convertToBuildEsQuery({ - config: esQuery.getEsQueryConfig(core.uiSettings), + config: esQuery.getEsQueryConfig(kibana.services.uiSettings), indexPattern, queries: [query], filters: hostsFilters, diff --git a/x-pack/legacy/plugins/siem/public/pages/hosts/hosts_empty_page.tsx b/x-pack/legacy/plugins/siem/public/pages/hosts/hosts_empty_page.tsx index ecd1e4f378cc5..1d2a3f83e8808 100644 --- a/x-pack/legacy/plugins/siem/public/pages/hosts/hosts_empty_page.tsx +++ b/x-pack/legacy/plugins/siem/public/pages/hosts/hosts_empty_page.tsx @@ -6,26 +6,30 @@ import React from 'react'; import chrome from 'ui/chrome'; -import { documentationLinks } from 'ui/documentation_links'; import { EmptyPage } from '../../components/empty_page'; +import { useKibana } from '../../lib/kibana'; import * as i18n from './translations'; const basePath = chrome.getBasePath(); -export const HostsEmptyPage = React.memo(() => ( - <EmptyPage - actionPrimaryIcon="gear" - actionPrimaryLabel={i18n.EMPTY_ACTION_PRIMARY} - actionPrimaryUrl={`${basePath}/app/kibana#/home/tutorial_directory/siem`} - actionSecondaryIcon="popout" - actionSecondaryLabel={i18n.EMPTY_ACTION_SECONDARY} - actionSecondaryTarget="_blank" - actionSecondaryUrl={documentationLinks.siem} - data-test-subj="empty-page" - title={i18n.EMPTY_TITLE} - /> -)); +export const HostsEmptyPage = React.memo(() => { + const docLinks = useKibana().services.docLinks; + + return ( + <EmptyPage + actionPrimaryIcon="gear" + actionPrimaryLabel={i18n.EMPTY_ACTION_PRIMARY} + actionPrimaryUrl={`${basePath}/app/kibana#/home/tutorial_directory/siem`} + actionSecondaryIcon="popout" + actionSecondaryLabel={i18n.EMPTY_ACTION_SECONDARY} + actionSecondaryTarget="_blank" + actionSecondaryUrl={docLinks.links.siem} + data-test-subj="empty-page" + title={i18n.EMPTY_TITLE} + /> + ); +}); HostsEmptyPage.displayName = 'HostsEmptyPage'; diff --git a/x-pack/legacy/plugins/siem/public/pages/network/ip_details/index.test.tsx b/x-pack/legacy/plugins/siem/public/pages/network/ip_details/index.test.tsx index 72f7858847649..d624631c1feae 100644 --- a/x-pack/legacy/plugins/siem/public/pages/network/ip_details/index.test.tsx +++ b/x-pack/legacy/plugins/siem/public/pages/network/ip_details/index.test.tsx @@ -16,27 +16,19 @@ import '../../../mock/match_media'; import { mocksSource } from '../../../containers/source/mock'; import { FlowTarget } from '../../../graphql/types'; -import { useKibanaCore } from '../../../lib/compose/kibana_core'; import { apolloClientObservable, mockGlobalState, TestProviders } from '../../../mock'; import { useMountAppended } from '../../../utils/use_mount_appended'; -import { mockUiSettings } from '../../../mock/ui_settings'; import { createStore, State } from '../../../store'; import { InputsModelId } from '../../../store/inputs/constants'; import { IPDetailsComponent, IPDetails } from './index'; -jest.mock('../../../lib/settings/use_kibana_ui_setting'); - type Action = 'PUSH' | 'POP' | 'REPLACE'; const pop: Action = 'POP'; type GlobalWithFetch = NodeJS.Global & { fetch: jest.Mock }; -const mockUseKibanaCore = useKibanaCore as jest.Mock; -jest.mock('../../../lib/compose/kibana_core'); -mockUseKibanaCore.mockImplementation(() => ({ - uiSettings: mockUiSettings, -})); +jest.mock('../../../lib/kibana'); // Test will fail because we will to need to mock some core services to make the test work // For now let's forget about SiemSearchBar and QueryBar @@ -106,12 +98,6 @@ const getMockProps = (ip: string) => ({ setIpDetailsTablesActivePageToZero: (jest.fn() as unknown) as ActionCreator<null>, }); -jest.mock('ui/documentation_links', () => ({ - documentationLinks: { - siem: 'http://www.example.com', - }, -})); - describe('Ip Details', () => { const mount = useMountAppended(); diff --git a/x-pack/legacy/plugins/siem/public/pages/network/ip_details/index.tsx b/x-pack/legacy/plugins/siem/public/pages/network/ip_details/index.tsx index 97db422b539e8..99ca12292a52c 100644 --- a/x-pack/legacy/plugins/siem/public/pages/network/ip_details/index.tsx +++ b/x-pack/legacy/plugins/siem/public/pages/network/ip_details/index.tsx @@ -24,7 +24,7 @@ import { WrapperPage } from '../../../components/wrapper_page'; import { IpOverviewQuery } from '../../../containers/ip_overview'; import { indicesExistOrDataTemporarilyUnavailable, WithSource } from '../../../containers/source'; import { FlowTargetSourceDest, LastEventIndexKey } from '../../../graphql/types'; -import { useKibanaCore } from '../../../lib/compose/kibana_core'; +import { useKibana } from '../../../lib/kibana'; import { decodeIpv6 } from '../../../lib/helpers'; import { convertToBuildEsQuery } from '../../../lib/keury'; import { ConditionalFlexGroup } from '../../../pages/network/navigation/conditional_flex_group'; @@ -70,7 +70,7 @@ export const IPDetailsComponent = ({ }, [setAbsoluteRangeDatePicker] ); - const core = useKibanaCore(); + const kibana = useKibana(); useEffect(() => { setIpDetailsTablesActivePageToZero(null); @@ -82,7 +82,7 @@ export const IPDetailsComponent = ({ {({ indicesExist, indexPattern }) => { const ip = decodeIpv6(detailName); const filterQuery = convertToBuildEsQuery({ - config: esQuery.getEsQueryConfig(core.uiSettings), + config: esQuery.getEsQueryConfig(kibana.services.uiSettings), indexPattern, queries: [query], filters, diff --git a/x-pack/legacy/plugins/siem/public/pages/network/network.test.tsx b/x-pack/legacy/plugins/siem/public/pages/network/network.test.tsx index 327b0fb4c1e5b..335bb62c5c852 100644 --- a/x-pack/legacy/plugins/siem/public/pages/network/network.test.tsx +++ b/x-pack/legacy/plugins/siem/public/pages/network/network.test.tsx @@ -13,24 +13,10 @@ import { MockedProvider } from 'react-apollo/test-utils'; import '../../mock/match_media'; import { mocksSource } from '../../containers/source/mock'; -import { useKibanaCore } from '../../lib/compose/kibana_core'; import { TestProviders } from '../../mock'; -import { mockUiSettings } from '../../mock/ui_settings'; import { Network } from './network'; -jest.mock('../../lib/settings/use_kibana_ui_setting'); - -jest.mock('ui/documentation_links', () => ({ - documentationLinks: { - kibana: 'http://www.example.com', - }, -})); - -const mockUseKibanaCore = useKibanaCore as jest.Mock; -jest.mock('../../lib/compose/kibana_core'); -mockUseKibanaCore.mockImplementation(() => ({ - uiSettings: mockUiSettings, -})); +jest.mock('../../lib/kibana'); // Test will fail because we will to need to mock some core services to make the test work // For now let's forget about SiemSearchBar and QueryBar diff --git a/x-pack/legacy/plugins/siem/public/pages/network/network.tsx b/x-pack/legacy/plugins/siem/public/pages/network/network.tsx index 0d8d3a6753c59..c39935742a2e0 100644 --- a/x-pack/legacy/plugins/siem/public/pages/network/network.tsx +++ b/x-pack/legacy/plugins/siem/public/pages/network/network.tsx @@ -23,7 +23,7 @@ import { WrapperPage } from '../../components/wrapper_page'; import { KpiNetworkQuery } from '../../containers/kpi_network'; import { indicesExistOrDataTemporarilyUnavailable, WithSource } from '../../containers/source'; import { LastEventIndexKey } from '../../graphql/types'; -import { useKibanaCore } from '../../lib/compose/kibana_core'; +import { useKibana } from '../../lib/kibana'; import { convertToBuildEsQuery } from '../../lib/keury'; import { networkModel, State, inputsSelectors } from '../../store'; import { setAbsoluteRangeDatePicker as dispatchSetAbsoluteRangeDatePicker } from '../../store/inputs/actions'; @@ -51,7 +51,7 @@ const NetworkComponent = React.memo<NetworkComponentProps>( hasMlUserPermissions, capabilitiesFetched, }) => { - const core = useKibanaCore(); + const kibana = useKibana(); const { tabName } = useParams(); const networkFilters = useMemo(() => { @@ -72,7 +72,7 @@ const NetworkComponent = React.memo<NetworkComponentProps>( <WithSource sourceId={sourceId}> {({ indicesExist, indexPattern }) => { const filterQuery = convertToBuildEsQuery({ - config: esQuery.getEsQueryConfig(core.uiSettings), + config: esQuery.getEsQueryConfig(kibana.services.uiSettings), indexPattern, queries: [query], filters: networkFilters, diff --git a/x-pack/legacy/plugins/siem/public/pages/network/network_empty_page.tsx b/x-pack/legacy/plugins/siem/public/pages/network/network_empty_page.tsx index 34e7f49bd9bd5..e22802fd29d49 100644 --- a/x-pack/legacy/plugins/siem/public/pages/network/network_empty_page.tsx +++ b/x-pack/legacy/plugins/siem/public/pages/network/network_empty_page.tsx @@ -6,26 +6,29 @@ import React from 'react'; import chrome from 'ui/chrome'; -import { documentationLinks } from 'ui/documentation_links'; +import { useKibana } from '../../lib/kibana'; import { EmptyPage } from '../../components/empty_page'; - import * as i18n from './translations'; const basePath = chrome.getBasePath(); -export const NetworkEmptyPage = React.memo(() => ( - <EmptyPage - actionPrimaryIcon="gear" - actionPrimaryLabel={i18n.EMPTY_ACTION_PRIMARY} - actionPrimaryUrl={`${basePath}/app/kibana#/home/tutorial_directory/siem`} - actionSecondaryIcon="popout" - actionSecondaryLabel={i18n.EMPTY_ACTION_SECONDARY} - actionSecondaryTarget="_blank" - actionSecondaryUrl={documentationLinks.siem} - data-test-subj="empty-page" - title={i18n.EMPTY_TITLE} - /> -)); +export const NetworkEmptyPage = React.memo(() => { + const docLinks = useKibana().services.docLinks; + + return ( + <EmptyPage + actionPrimaryIcon="gear" + actionPrimaryLabel={i18n.EMPTY_ACTION_PRIMARY} + actionPrimaryUrl={`${basePath}/app/kibana#/home/tutorial_directory/siem`} + actionSecondaryIcon="popout" + actionSecondaryLabel={i18n.EMPTY_ACTION_SECONDARY} + actionSecondaryTarget="_blank" + actionSecondaryUrl={docLinks.links.siem} + data-test-subj="empty-page" + title={i18n.EMPTY_TITLE} + /> + ); +}); NetworkEmptyPage.displayName = 'NetworkEmptyPage'; diff --git a/x-pack/legacy/plugins/siem/public/pages/overview/overview.test.tsx b/x-pack/legacy/plugins/siem/public/pages/overview/overview.test.tsx index 833030e0dc8a1..300df4a742adf 100644 --- a/x-pack/legacy/plugins/siem/public/pages/overview/overview.test.tsx +++ b/x-pack/legacy/plugins/siem/public/pages/overview/overview.test.tsx @@ -10,17 +10,11 @@ import * as React from 'react'; import { MockedProvider } from 'react-apollo/test-utils'; import { MemoryRouter } from 'react-router-dom'; -import { Overview } from './index'; - -import '../../mock/ui_settings'; -import { mocksSource } from '../../containers/source/mock'; import { TestProviders } from '../../mock'; +import { mocksSource } from '../../containers/source/mock'; +import { Overview } from './index'; -jest.mock('ui/documentation_links', () => ({ - documentationLinks: { - kibana: 'http://www.example.com', - }, -})); +jest.mock('../../lib/kibana'); let localSource: Array<{ request: {}; diff --git a/x-pack/legacy/plugins/siem/public/pages/overview/overview.tsx b/x-pack/legacy/plugins/siem/public/pages/overview/overview.tsx index de976b1a5c5a3..a0e94431054cc 100644 --- a/x-pack/legacy/plugins/siem/public/pages/overview/overview.tsx +++ b/x-pack/legacy/plugins/siem/public/pages/overview/overview.tsx @@ -8,8 +8,8 @@ import { EuiFlexGroup } from '@elastic/eui'; import moment from 'moment'; import React from 'react'; import chrome from 'ui/chrome'; -import { documentationLinks } from 'ui/documentation_links'; +import { useKibana } from '../../lib/kibana'; import { EmptyPage } from '../../components/empty_page'; import { HeaderPage } from '../../components/header_page'; import { OverviewHost } from '../../components/page/overview/overview_host'; @@ -24,6 +24,7 @@ import * as i18n from './translations'; const basePath = chrome.getBasePath(); export const OverviewComponent = React.memo(() => { + const docLinks = useKibana().services.docLinks; const dateEnd = Date.now(); const dateRange = moment.duration(24, 'hours').asMilliseconds(); const dateStart = dateEnd - dateRange; @@ -62,7 +63,7 @@ export const OverviewComponent = React.memo(() => { actionSecondaryIcon="popout" actionSecondaryLabel={i18n.EMPTY_ACTION_SECONDARY} actionSecondaryTarget="_blank" - actionSecondaryUrl={documentationLinks.siem} + actionSecondaryUrl={docLinks.links.siem} data-test-subj="empty-page" title={i18n.EMPTY_TITLE} /> diff --git a/x-pack/legacy/plugins/siem/public/pages/overview/summary.tsx b/x-pack/legacy/plugins/siem/public/pages/overview/summary.tsx index 7fd8f84129d89..51cfcbe9374ab 100644 --- a/x-pack/legacy/plugins/siem/public/pages/overview/summary.tsx +++ b/x-pack/legacy/plugins/siem/public/pages/overview/summary.tsx @@ -4,73 +4,81 @@ * you may not use this file except in compliance with the Elastic License. */ +import React from 'react'; import { EuiFlexItem, EuiLink, EuiText } from '@elastic/eui'; import { FormattedMessage } from '@kbn/i18n/react'; -import React from 'react'; -import { documentationLinks } from 'ui/documentation_links'; -export const Summary = React.memo(() => ( - <EuiFlexItem> - <EuiText> - <h2> - <FormattedMessage id="xpack.siem.overview.startedTitle" defaultMessage="Getting started" /> - </h2> +import { useKibana } from '../../lib/kibana'; + +export const Summary = React.memo(() => { + const docLinks = useKibana().services.docLinks; + + return ( + <EuiFlexItem> + <EuiText> + <h2> + <FormattedMessage + id="xpack.siem.overview.startedTitle" + defaultMessage="Getting started" + /> + </h2> - <p> - <FormattedMessage - id="xpack.siem.overview.startedText" - defaultMessage="Welcome to Security Information & Event Management (SIEM). Get started by reviewing our {docs} or {data}. For information about upcoming features and tutorials, be sure to check out our {siemSolution} page." - values={{ - docs: ( - <EuiLink href={documentationLinks.siem} target="blank"> - <FormattedMessage - id="xpack.siem.overview.startedText.docsLinkText" - defaultMessage="documentation" - /> - </EuiLink> - ), - data: ( - <EuiLink href="kibana#home/tutorial_directory/siem"> - <FormattedMessage - id="xpack.siem.overview.startedText.dataLinkText" - defaultMessage="ingesting data" - /> - </EuiLink> - ), - siemSolution: ( - <EuiLink href="https://www.elastic.co/solutions/siem" target="blank"> - <FormattedMessage - id="xpack.siem.overview.startedText.siemSolutionLinkText" - defaultMessage="SIEM solution" - /> - </EuiLink> - ), - }} - /> - </p> + <p> + <FormattedMessage + id="xpack.siem.overview.startedText" + defaultMessage="Welcome to Security Information & Event Management (SIEM). Get started by reviewing our {docs} or {data}. For information about upcoming features and tutorials, be sure to check out our {siemSolution} page." + values={{ + docs: ( + <EuiLink href={docLinks.links.siem} target="blank"> + <FormattedMessage + id="xpack.siem.overview.startedText.docsLinkText" + defaultMessage="documentation" + /> + </EuiLink> + ), + data: ( + <EuiLink href="kibana#home/tutorial_directory/siem"> + <FormattedMessage + id="xpack.siem.overview.startedText.dataLinkText" + defaultMessage="ingesting data" + /> + </EuiLink> + ), + siemSolution: ( + <EuiLink href="https://www.elastic.co/solutions/siem" target="blank"> + <FormattedMessage + id="xpack.siem.overview.startedText.siemSolutionLinkText" + defaultMessage="SIEM solution" + /> + </EuiLink> + ), + }} + /> + </p> - <h2> - <FormattedMessage id="xpack.siem.overview.feedbackTitle" defaultMessage="Feedback" /> - </h2> + <h2> + <FormattedMessage id="xpack.siem.overview.feedbackTitle" defaultMessage="Feedback" /> + </h2> - <p> - <FormattedMessage - id="xpack.siem.overview.feedbackText" - defaultMessage="If you have input or suggestions regarding your experience with Elastic SIEM, please feel free to {feedback}." - values={{ - feedback: ( - <EuiLink href="https://discuss.elastic.co/c/siem" target="blank"> - <FormattedMessage - id="xpack.siem.overview.feedbackText.feedbackLinkText" - defaultMessage="submit feedback online" - /> - </EuiLink> - ), - }} - /> - </p> - </EuiText> - </EuiFlexItem> -)); + <p> + <FormattedMessage + id="xpack.siem.overview.feedbackText" + defaultMessage="If you have input or suggestions regarding your experience with Elastic SIEM, please feel free to {feedback}." + values={{ + feedback: ( + <EuiLink href="https://discuss.elastic.co/c/siem" target="blank"> + <FormattedMessage + id="xpack.siem.overview.feedbackText.feedbackLinkText" + defaultMessage="submit feedback online" + /> + </EuiLink> + ), + }} + /> + </p> + </EuiText> + </EuiFlexItem> + ); +}); Summary.displayName = 'Summary'; diff --git a/x-pack/legacy/plugins/siem/public/utils/saved_query_services/index.tsx b/x-pack/legacy/plugins/siem/public/utils/saved_query_services/index.tsx index cda6882fe1714..a8ee10ba2b801 100644 --- a/x-pack/legacy/plugins/siem/public/utils/saved_query_services/index.tsx +++ b/x-pack/legacy/plugins/siem/public/utils/saved_query_services/index.tsx @@ -10,16 +10,18 @@ import { createSavedQueryService, } from '../../../../../../../src/plugins/data/public'; -import { useKibanaCore } from '../../lib/compose/kibana_core'; +import { useKibana } from '../../lib/kibana'; export const useSavedQueryServices = () => { - const core = useKibanaCore(); + const kibana = useKibana(); + const client = kibana.services.savedObjects.client; + const [savedQueryService, setSavedQueryService] = useState<SavedQueryService>( - createSavedQueryService(core.savedObjects.client) + createSavedQueryService(client) ); useEffect(() => { - setSavedQueryService(createSavedQueryService(core.savedObjects.client)); - }, [core.savedObjects.client]); + setSavedQueryService(createSavedQueryService(client)); + }, [client]); return savedQueryService; };