From ed7ac3916b024547329910c2111c3108b621d177 Mon Sep 17 00:00:00 2001 From: Liza Katz Date: Tue, 24 Sep 2019 17:35:24 +0300 Subject: [PATCH] =?UTF-8?q?Move=20timefilter=20and=20timehistory=20instant?= =?UTF-8?q?iation=20=E2=87=92=20data=20plugin=20(#44783)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Create timefilter service * Pass timehistory as a dependency to query bar * Updated timefilter tests and mocks * Fix jest test * Fixed bad import path * updated xpack test * make history optional on query bar * Fixed chart_utils test * Fixed page.test by mocking timefilter * Fixed explorer_charts_container_service test by mocking timefilter * Fixed explorer_chart_distribution test by mocking timefilter * Fixed explorer_chart_single_metric test by mocking timefilter * Fixed explorer_charts_container test by mocking timefilter and removing some unneeded initialization * Fixed explorer_swimlane tesy by mocking timefilter * Added missing functions to uiTimefilterMock to fix top_nav test * Fixed timeseries_chart test by mocking timefilter * remove bad merge * mock field formats * mock field formats * rename timefilter boolean getters * fix ml mocks * ml mocks --- .../filter_manager/filter_manager.test.ts | 14 +-- .../filter/filter_manager/filter_manager.ts | 17 +-- .../filter_state_manager.test.ts | 14 +-- ...ter.test.js => change_time_filter.test.ts} | 50 ++++---- ...e_time_filter.js => change_time_filter.ts} | 5 +- ..._time_filter.js => extract_time_filter.ts} | 7 +- .../data/public/filter/filter_service.ts | 6 +- src/legacy/core_plugins/data/public/index.ts | 2 + src/legacy/core_plugins/data/public/mocks.ts | 7 +- src/legacy/core_plugins/data/public/plugin.ts | 9 ++ .../components/query_bar_top_row.test.tsx | 15 +++ .../components/query_bar_top_row.tsx | 35 +++--- .../search_bar/components/search_bar.test.tsx | 10 ++ .../search_bar/components/search_bar.tsx | 3 + .../data/public/timefilter/index.ts | 7 +- .../timefilter/lib/diff_time_picker_vals.ts | 2 +- .../data/public/timefilter/time_history.ts | 4 +- .../data/public/timefilter/timefilter.test.ts | 39 +++--- .../data/public/timefilter/timefilter.ts | 118 +++++++++--------- .../timefilter/timefilter_service.mock.ts | 76 +++++++++++ .../public/timefilter/timefilter_service.ts | 60 +++++++++ .../types.ts} | 26 ++-- .../public/dashboard/dashboard_state.test.ts | 47 ++++--- .../discover/embeddable/search_embeddable.ts | 8 +- .../public/top_nav_menu/top_nav_menu.test.tsx | 7 ++ .../public/top_nav_menu/top_nav_menu.tsx | 11 +- .../ui/public/kbn_top_nav/kbn_top_nav.js | 4 + src/legacy/ui/public/timefilter/index.ts | 20 +-- .../ui/public/timefilter/setup_router.ts | 4 +- .../vis/vis_filters/brush_event.test.js | 20 --- .../loader/embedded_visualize_handler.test.ts | 8 +- .../navigation_menu/top_nav/top_nav.tsx | 8 +- .../ml/public/contexts/ui/__mocks__/mocks.ts | 14 ++- .../transform_management/page.test.mocks.ts | 12 +- .../explorer_chart_distribution.test.mocks.ts | 12 +- ...explorer_chart_single_metric.test.mocks.ts | 12 +- .../explorer_charts_container.test.js | 24 ---- .../explorer_charts_container.test.mocks.ts | 12 +- ...rer_charts_container_service.test.mocks.ts | 12 +- .../explorer/explorer_swimlane.test.mocks.ts | 12 +- .../timeseries_chart.test.mocks.ts | 12 +- .../ml/public/util/chart_utils.test.js | 45 ++++--- .../ml/public/util/chart_utils.test.mocks.ts | 15 --- .../public/views/__tests__/base_controller.js | 20 +-- .../views/__tests__/base_table_controller.js | 8 +- 45 files changed, 490 insertions(+), 383 deletions(-) rename src/legacy/core_plugins/data/public/filter/filter_manager/lib/__tests__/{change_time_filter.test.js => change_time_filter.test.ts} (67%) rename src/legacy/core_plugins/data/public/filter/filter_manager/lib/{change_time_filter.js => change_time_filter.ts} (88%) rename src/legacy/core_plugins/data/public/filter/filter_manager/lib/{extract_time_filter.js => extract_time_filter.ts} (82%) create mode 100644 src/legacy/core_plugins/data/public/timefilter/timefilter_service.mock.ts create mode 100644 src/legacy/core_plugins/data/public/timefilter/timefilter_service.ts rename src/legacy/core_plugins/data/public/{filter/filter_manager/lib/__tests__/change_time_filter.test.mocks.ts => timefilter/types.ts} (63%) delete mode 100644 x-pack/legacy/plugins/ml/public/util/chart_utils.test.mocks.ts diff --git a/src/legacy/core_plugins/data/public/filter/filter_manager/filter_manager.test.ts b/src/legacy/core_plugins/data/public/filter/filter_manager/filter_manager.test.ts index a6700dc37e8d..5eaa6744216c 100644 --- a/src/legacy/core_plugins/data/public/filter/filter_manager/filter_manager.test.ts +++ b/src/legacy/core_plugins/data/public/filter/filter_manager/filter_manager.test.ts @@ -35,18 +35,13 @@ import { getFiltersArray } from './test_helpers/get_filters_array'; import { coreMock } from '../../../../../../core/public/mocks'; const setupMock = coreMock.createSetup(); +import { timefilterServiceMock } from '../../timefilter/timefilter_service.mock'; +const timefilterSetupMock = timefilterServiceMock.createSetupContract(); + setupMock.uiSettings.get.mockImplementation((key: string) => { return true; }); -jest.mock('ui/timefilter', () => { - return { - timefilter: { - setTime: jest.fn(), - }, - }; -}); - describe('filter_manager', () => { let appStateStub: StubState; let globalStateStub: StubState; @@ -66,7 +61,8 @@ describe('filter_manager', () => { indexPatterns = new StubIndexPatterns(); filterManager = new FilterManager( (indexPatterns as unknown) as IndexPatterns, - setupMock.uiSettings + setupMock.uiSettings, + timefilterSetupMock.timefilter ); readyFilters = getFiltersArray(); diff --git a/src/legacy/core_plugins/data/public/filter/filter_manager/filter_manager.ts b/src/legacy/core_plugins/data/public/filter/filter_manager/filter_manager.ts index f230b035de35..1605c647a267 100644 --- a/src/legacy/core_plugins/data/public/filter/filter_manager/filter_manager.ts +++ b/src/legacy/core_plugins/data/public/filter/filter_manager/filter_manager.ts @@ -29,16 +29,13 @@ import { compareFilters } from './lib/compare_filters'; import { mapAndFlattenFilters } from './lib/map_and_flatten_filters'; // @ts-ignore import { uniqFilters } from './lib/uniq_filters'; -// @ts-ignore + import { extractTimeFilter } from './lib/extract_time_filter'; -// @ts-ignore import { changeTimeFilter } from './lib/change_time_filter'; - import { onlyDisabledFiltersChanged } from './lib/only_disabled'; - import { PartitionedFilters } from './partitioned_filters'; - import { IndexPatterns } from '../../index_patterns'; +import { TimefilterContract } from '../../timefilter'; export class FilterManager { private indexPatterns: IndexPatterns; @@ -46,10 +43,16 @@ export class FilterManager { private updated$: Subject = new Subject(); private fetch$: Subject = new Subject(); private uiSettings: UiSettingsClientContract; + private timefilter: TimefilterContract; - constructor(indexPatterns: IndexPatterns, uiSettings: UiSettingsClientContract) { + constructor( + indexPatterns: IndexPatterns, + uiSettings: UiSettingsClientContract, + timefilter: TimefilterContract + ) { this.indexPatterns = indexPatterns; this.uiSettings = uiSettings; + this.timefilter = timefilter; } private mergeIncomingFilters(partitionedFilters: PartitionedFilters): Filter[] { @@ -191,7 +194,7 @@ export class FilterManager { public async addFiltersAndChangeTimeFilter(filters: Filter[]) { const timeFilter = await extractTimeFilter(this.indexPatterns, filters); - if (timeFilter) changeTimeFilter(timeFilter); + if (timeFilter) changeTimeFilter(this.timefilter, timeFilter); return this.addFilters(filters.filter(filter => filter !== timeFilter)); } diff --git a/src/legacy/core_plugins/data/public/filter/filter_manager/filter_state_manager.test.ts b/src/legacy/core_plugins/data/public/filter/filter_manager/filter_state_manager.test.ts index a4345018aa83..a4826e059fa2 100644 --- a/src/legacy/core_plugins/data/public/filter/filter_manager/filter_state_manager.test.ts +++ b/src/legacy/core_plugins/data/public/filter/filter_manager/filter_state_manager.test.ts @@ -31,18 +31,13 @@ import { StubIndexPatterns } from './test_helpers/stub_index_pattern'; import { coreMock } from '../../../../../../core/public/mocks'; const setupMock = coreMock.createSetup(); +import { timefilterServiceMock } from '../../timefilter/timefilter_service.mock'; +const timefilterSetupMock = timefilterServiceMock.createSetupContract(); + setupMock.uiSettings.get.mockImplementation((key: string) => { return true; }); -jest.mock('ui/timefilter', () => { - return { - timefilter: { - setTime: jest.fn(), - }, - }; -}); - describe('filter_state_manager', () => { let appStateStub: StubState; let globalStateStub: StubState; @@ -55,7 +50,8 @@ describe('filter_state_manager', () => { const indexPatterns = new StubIndexPatterns(); filterManager = new FilterManager( (indexPatterns as unknown) as IndexPatterns, - setupMock.uiSettings + setupMock.uiSettings, + timefilterSetupMock.timefilter ); }); diff --git a/src/legacy/core_plugins/data/public/filter/filter_manager/lib/__tests__/change_time_filter.test.js b/src/legacy/core_plugins/data/public/filter/filter_manager/lib/__tests__/change_time_filter.test.ts similarity index 67% rename from src/legacy/core_plugins/data/public/filter/filter_manager/lib/__tests__/change_time_filter.test.js rename to src/legacy/core_plugins/data/public/filter/filter_manager/lib/__tests__/change_time_filter.test.ts index 3a3cc176308c..d3d05d20e9fb 100644 --- a/src/legacy/core_plugins/data/public/filter/filter_manager/lib/__tests__/change_time_filter.test.js +++ b/src/legacy/core_plugins/data/public/filter/filter_manager/lib/__tests__/change_time_filter.test.ts @@ -16,50 +16,42 @@ * specific language governing permissions and limitations * under the License. */ - -import './change_time_filter.test.mocks'; - -jest.mock('ui/chrome', - () => ({ - getBasePath: () => `/some/base/path`, - getUiSettingsClient: () => { - return { - get: (key) => { - switch(key) { - case 'timepicker:timeDefaults': - return { from: 'now-15m', to: 'now' }; - case 'timepicker:refreshIntervalDefaults': - return { pause: false, value: 0 }; - default: - throw new Error(`Unexpected config key: ${key}`); - } - } - }; - }, - }), { virtual: true }); - import expect from '@kbn/expect'; import { changeTimeFilter } from '../change_time_filter'; -import { timefilter } from 'ui/timefilter'; +import { TimeRange } from 'src/plugins/data/public'; + +import { timefilterServiceMock } from '../../../../timefilter/timefilter_service.mock'; +const timefilterMock = timefilterServiceMock.createSetupContract(); +const timefilter = timefilterMock.timefilter; -describe('changeTimeFilter()', function () { +let _time: TimeRange | undefined; +timefilter.setTime.mockImplementation((time: any) => { + _time = { + from: time.from.toISOString(), + to: time.to.toISOString(), + }; +}); +timefilter.getTime.mockImplementation(() => { + return _time!; +}); + +describe('changeTimeFilter()', function() { const gt = 1388559600000; const lt = 1388646000000; - test('should change the timefilter to match the range gt/lt', function () { + test('should change the timefilter to match the range gt/lt', function() { const filter = { range: { '@timestamp': { gt, lt } } }; - changeTimeFilter(filter); + changeTimeFilter(timefilter, filter); const { to, from } = timefilter.getTime(); expect(to).to.be(new Date(lt).toISOString()); expect(from).to.be(new Date(gt).toISOString()); }); - test('should change the timefilter to match the range gte/lte', function () { + test('should change the timefilter to match the range gte/lte', function() { const filter = { range: { '@timestamp': { gte: gt, lte: lt } } }; - changeTimeFilter(filter); + changeTimeFilter(timefilter, filter); const { to, from } = timefilter.getTime(); expect(to).to.be(new Date(lt).toISOString()); expect(from).to.be(new Date(gt).toISOString()); }); - }); diff --git a/src/legacy/core_plugins/data/public/filter/filter_manager/lib/change_time_filter.js b/src/legacy/core_plugins/data/public/filter/filter_manager/lib/change_time_filter.ts similarity index 88% rename from src/legacy/core_plugins/data/public/filter/filter_manager/lib/change_time_filter.js rename to src/legacy/core_plugins/data/public/filter/filter_manager/lib/change_time_filter.ts index eae71d244f88..6c6ed775951c 100644 --- a/src/legacy/core_plugins/data/public/filter/filter_manager/lib/change_time_filter.js +++ b/src/legacy/core_plugins/data/public/filter/filter_manager/lib/change_time_filter.ts @@ -19,14 +19,13 @@ import moment from 'moment'; import _ from 'lodash'; -import { timefilter } from 'ui/timefilter'; +import { TimefilterContract } from '../../../timefilter'; -export function changeTimeFilter(filter) { +export function changeTimeFilter(timefilter: TimefilterContract, filter: any) { const key = _.keys(filter.range)[0]; const values = filter.range[key]; timefilter.setTime({ from: moment(values.gt || values.gte), to: moment(values.lt || values.lte), - mode: 'absolute', }); } diff --git a/src/legacy/core_plugins/data/public/filter/filter_manager/lib/extract_time_filter.js b/src/legacy/core_plugins/data/public/filter/filter_manager/lib/extract_time_filter.ts similarity index 82% rename from src/legacy/core_plugins/data/public/filter/filter_manager/lib/extract_time_filter.js rename to src/legacy/core_plugins/data/public/filter/filter_manager/lib/extract_time_filter.ts index 3d3fb9204650..e6fea9cccd8f 100644 --- a/src/legacy/core_plugins/data/public/filter/filter_manager/lib/extract_time_filter.js +++ b/src/legacy/core_plugins/data/public/filter/filter_manager/lib/extract_time_filter.ts @@ -18,16 +18,17 @@ */ import _ from 'lodash'; +import { IndexPatterns } from '../../../index_patterns'; -export async function extractTimeFilter(indexPatterns, filters) { +export async function extractTimeFilter(indexPatterns: IndexPatterns, filters: any) { // Assume all the index patterns are the same since they will be added // from the same visualization. - const id = _.get(filters, '[0].meta.index'); + const id: string = _.get(filters, '[0].meta.index'); if (id == null) return; const indexPattern = await indexPatterns.get(id); - const filter = _.find(filters, function (obj) { + const filter = _.find(filters, function(obj: any) { const key = _.keys(obj.range)[0]; return key === indexPattern.timeFieldName; }); diff --git a/src/legacy/core_plugins/data/public/filter/filter_service.ts b/src/legacy/core_plugins/data/public/filter/filter_service.ts index 063b69c175b2..8853fae455c1 100644 --- a/src/legacy/core_plugins/data/public/filter/filter_service.ts +++ b/src/legacy/core_plugins/data/public/filter/filter_service.ts @@ -20,6 +20,7 @@ import { UiSettingsClientContract } from 'src/core/public'; import { IndexPatterns } from '../index_patterns'; import { FilterManager } from './filter_manager'; +import { TimefilterContract } from '../timefilter'; /** * Filter Service @@ -29,12 +30,13 @@ import { FilterManager } from './filter_manager'; export interface FilterServiceDependencies { indexPatterns: IndexPatterns; uiSettings: UiSettingsClientContract; + timefilter: TimefilterContract; } export class FilterService { - public setup({ indexPatterns, uiSettings }: FilterServiceDependencies) { + public setup({ indexPatterns, uiSettings, timefilter }: FilterServiceDependencies) { return { - filterManager: new FilterManager(indexPatterns, uiSettings), + filterManager: new FilterManager(indexPatterns, uiSettings, timefilter), }; } diff --git a/src/legacy/core_plugins/data/public/index.ts b/src/legacy/core_plugins/data/public/index.ts index 9c95ef7a82ab..d96e3be8d7e3 100644 --- a/src/legacy/core_plugins/data/public/index.ts +++ b/src/legacy/core_plugins/data/public/index.ts @@ -65,3 +65,5 @@ export { mockFields, mockIndexPattern, } from './index_patterns'; + +export { TimeHistoryContract, TimefilterContract, getTime, InputTimeRange } from './timefilter'; diff --git a/src/legacy/core_plugins/data/public/mocks.ts b/src/legacy/core_plugins/data/public/mocks.ts index 0ca0b4947d53..2a82927bb3eb 100644 --- a/src/legacy/core_plugins/data/public/mocks.ts +++ b/src/legacy/core_plugins/data/public/mocks.ts @@ -17,19 +17,18 @@ * under the License. */ -import { DataSetup } from '.'; import { filterServiceMock } from './filter/filter_service.mock'; import { indexPatternsServiceMock } from './index_patterns/index_patterns_service.mock'; import { queryServiceMock } from './query/query_service.mock'; +import { timefilterServiceMock } from './timefilter/timefilter_service.mock'; function createDataSetupMock() { - const mock: MockedKeys> = { + return { filter: filterServiceMock.createSetupContract(), indexPatterns: indexPatternsServiceMock.createSetupContract(), query: queryServiceMock.createSetupContract(), + timefilter: timefilterServiceMock.createSetupContract(), }; - - return mock; } function createDataStartMock() { diff --git a/src/legacy/core_plugins/data/public/plugin.ts b/src/legacy/core_plugins/data/public/plugin.ts index ee4ecd984109..aec97b02bc2b 100644 --- a/src/legacy/core_plugins/data/public/plugin.ts +++ b/src/legacy/core_plugins/data/public/plugin.ts @@ -21,6 +21,7 @@ import { CoreSetup, CoreStart, Plugin } from '../../../../core/public'; import { SearchService, SearchSetup } from './search'; import { QueryService, QuerySetup } from './query'; import { FilterService, FilterSetup } from './filter'; +import { TimefilterService, TimefilterSetup } from './timefilter'; import { IndexPatternsService, IndexPatternsSetup } from './index_patterns'; import { LegacyDependenciesPluginSetup } from './shim/legacy_dependencies_plugin'; @@ -43,6 +44,7 @@ export interface DataSetup { filter: FilterSetup; query: QuerySetup; search: SearchSetup; + timefilter: TimefilterSetup; } /** @@ -62,6 +64,7 @@ export class DataPlugin implements Plugin { + return []; +}); + startMock.uiSettings.get.mockImplementation((key: string) => { switch (key) { case 'timepicker:quickRanges': @@ -100,6 +107,7 @@ describe('QueryBarTopRowTopRow', () => { { { { { { { { { public onSubmit = ({ query, dateRange }: { query?: Query; dateRange: DateRange }) => { this.handleLuceneSyntaxWarning(); - timeHistory.add(dateRange); + + if (this.props.timeHistory) { + this.props.timeHistory.add(dateRange); + } this.props.onSubmit({ query, dateRange }); }; @@ -266,14 +268,17 @@ export class QueryBarTopRowUI extends Component { return null; } - const recentlyUsedRanges = timeHistory - .get() - .map(({ from, to }: { from: string; to: string }) => { - return { - start: from, - end: to, - }; - }); + let recentlyUsedRanges; + if (this.props.timeHistory) { + recentlyUsedRanges = this.props.timeHistory + .get() + .map(({ from, to }: { from: string; to: string }) => { + return { + start: from, + end: to, + }; + }); + } const commonlyUsedRanges = this.props.uiSettings .get('timepicker:quickRanges') diff --git a/src/legacy/core_plugins/data/public/search/search_bar/components/search_bar.test.tsx b/src/legacy/core_plugins/data/public/search/search_bar/components/search_bar.test.tsx index 1b73531ec41e..a52229415a4f 100644 --- a/src/legacy/core_plugins/data/public/search/search_bar/components/search_bar.test.tsx +++ b/src/legacy/core_plugins/data/public/search/search_bar/components/search_bar.test.tsx @@ -25,6 +25,9 @@ import { IndexPattern } from '../../../index_patterns'; import { coreMock } from '../../../../../../../../src/core/public/mocks'; const startMock = coreMock.createStart(); +import { timefilterServiceMock } from '../../../timefilter/timefilter_service.mock'; +const timefilterSetupMock = timefilterServiceMock.createSetupContract(); + jest.mock('../../../../../data/public', () => { return { FilterBar: () =>
, @@ -98,6 +101,7 @@ describe('SearchBar', () => { { { { { { { it('Should render query bar and filter bar', () => { const component = mountWithIntl( void; + timeHistory: TimeHistoryContract; // Filter bar showFilterBar?: boolean; filters?: Filter[]; @@ -378,6 +380,7 @@ class SearchBarUI extends Component { ; constructor() { const historyOptions = { @@ -52,3 +52,5 @@ export class TimeHistory { return this.history.get(); } } + +export type TimeHistoryContract = PublicMethodsOf; diff --git a/src/legacy/core_plugins/data/public/timefilter/timefilter.test.ts b/src/legacy/core_plugins/data/public/timefilter/timefilter.test.ts index 47896189aa08..0c6b0faf3e39 100644 --- a/src/legacy/core_plugins/data/public/timefilter/timefilter.test.ts +++ b/src/legacy/core_plugins/data/public/timefilter/timefilter.test.ts @@ -17,26 +17,6 @@ * under the License. */ -import './timefilter.test.mocks'; - -jest.mock('ui/chrome', () => ({ - getBasePath: () => `/some/base/path`, - getUiSettingsClient: () => { - return { - get: (key: string) => { - switch (key) { - case 'timepicker:timeDefaults': - return { from: 'now-15m', to: 'now' }; - case 'timepicker:refreshIntervalDefaults': - return { pause: false, value: 0 }; - default: - throw new Error(`Unexpected config key: ${key}`); - } - }, - }; - }, -})); - jest.mock('./lib/parse_querystring', () => ({ parseQueryString: () => { return { @@ -50,10 +30,19 @@ jest.mock('./lib/parse_querystring', () => ({ import sinon from 'sinon'; import expect from '@kbn/expect'; import moment from 'moment'; -import { timefilter } from 'ui/timefilter'; +import { Timefilter } from './timefilter'; import { Subscription } from 'rxjs'; import { TimeRange, RefreshInterval } from 'src/plugins/data/public'; +import { timefilterServiceMock } from './timefilter_service.mock'; +const timefilterSetupMock = timefilterServiceMock.createSetupContract(); + +const timefilterConfig = { + timeDefaults: { from: 'now-15m', to: 'now' }, + refreshIntervalDefaults: { pause: false, value: 0 }, +}; +const timefilter = new Timefilter(timefilterConfig, timefilterSetupMock.history); + function stubNowTime(nowTime: any) { // @ts-ignore global.nowTime = nowTime; @@ -242,13 +231,13 @@ describe('isTimeRangeSelectorEnabled', () => { test('should emit updated when disabled', () => { timefilter.disableTimeRangeSelector(); - expect(timefilter.isTimeRangeSelectorEnabled).to.be(false); + expect(timefilter.isTimeRangeSelectorEnabled()).to.be(false); expect(update.called).to.be(true); }); test('should emit updated when enabled', () => { timefilter.enableTimeRangeSelector(); - expect(timefilter.isTimeRangeSelectorEnabled).to.be(true); + expect(timefilter.isTimeRangeSelectorEnabled()).to.be(true); expect(update.called).to.be(true); }); }); @@ -268,13 +257,13 @@ describe('isAutoRefreshSelectorEnabled', () => { test('should emit updated when disabled', () => { timefilter.disableAutoRefreshSelector(); - expect(timefilter.isAutoRefreshSelectorEnabled).to.be(false); + expect(timefilter.isAutoRefreshSelectorEnabled()).to.be(false); expect(update.called).to.be(true); }); test('should emit updated when enabled', () => { timefilter.enableAutoRefreshSelector(); - expect(timefilter.isAutoRefreshSelectorEnabled).to.be(true); + expect(timefilter.isAutoRefreshSelectorEnabled()).to.be(true); expect(update.called).to.be(true); }); }); diff --git a/src/legacy/core_plugins/data/public/timefilter/timefilter.ts b/src/legacy/core_plugins/data/public/timefilter/timefilter.ts index 5a1aaac0f104..c08ea9043da9 100644 --- a/src/legacy/core_plugins/data/public/timefilter/timefilter.ts +++ b/src/legacy/core_plugins/data/public/timefilter/timefilter.ts @@ -19,26 +19,13 @@ import _ from 'lodash'; import { Subject, BehaviorSubject } from 'rxjs'; -import moment, { Moment } from 'moment'; +import moment from 'moment'; import { RefreshInterval, TimeRange } from 'src/plugins/data/public'; -import { IndexPattern } from 'src/legacy/core_plugins/data/public'; -import { TimeHistory } from './time_history'; +import { IndexPattern, TimeHistoryContract } from '../index'; import { areRefreshIntervalsDifferent, areTimeRangesDifferent } from './lib/diff_time_picker_vals'; import { parseQueryString } from './lib/parse_querystring'; import { calculateBounds, getTime } from './get_time'; - -export interface TimefilterConfig { - timeDefaults: TimeRange; - refreshIntervalDefaults: RefreshInterval; -} - -// Timefilter accepts moment input but always returns string output -export type InputTimeRange = - | TimeRange - | { - from: Moment; - to: Moment; - }; +import { TimefilterConfig, InputTimeRange } from './types'; export class Timefilter { // Fired when isTimeRangeSelectorEnabled \ isAutoRefreshSelectorEnabled are toggled @@ -53,38 +40,46 @@ export class Timefilter { private _time: TimeRange; private _refreshInterval!: RefreshInterval; - private _history: TimeHistory; + private _history: TimeHistoryContract; - public isTimeRangeSelectorEnabled: boolean = false; - public isAutoRefreshSelectorEnabled: boolean = false; + private _isTimeRangeSelectorEnabled: boolean = false; + private _isAutoRefreshSelectorEnabled: boolean = false; - constructor(config: TimefilterConfig, timeHistory: TimeHistory) { + constructor(config: TimefilterConfig, timeHistory: TimeHistoryContract) { this._history = timeHistory; this._time = config.timeDefaults; this.setRefreshInterval(config.refreshIntervalDefaults); } - getEnabledUpdated$ = () => { + public isTimeRangeSelectorEnabled() { + return this._isTimeRangeSelectorEnabled; + } + + public isAutoRefreshSelectorEnabled() { + return this._isAutoRefreshSelectorEnabled; + } + + public getEnabledUpdated$ = () => { return this.enabledUpdated$.asObservable(); }; - getTimeUpdate$ = () => { + public getTimeUpdate$ = () => { return this.timeUpdate$.asObservable(); }; - getRefreshIntervalUpdate$ = () => { + public getRefreshIntervalUpdate$ = () => { return this.refreshIntervalUpdate$.asObservable(); }; - getAutoRefreshFetch$ = () => { + public getAutoRefreshFetch$ = () => { return this.autoRefreshFetch$.asObservable(); }; - getFetch$ = () => { + public getFetch$ = () => { return this.fetch$.asObservable(); }; - getTime = (): TimeRange => { + public getTime = (): TimeRange => { const { from, to } = this._time; return { ...this._time, @@ -100,7 +95,7 @@ export class Timefilter { * @property {string|moment} time.from * @property {string|moment} time.to */ - setTime = (time: InputTimeRange) => { + public setTime = (time: InputTimeRange) => { // Object.assign used for partially composed updates const newTime = Object.assign(this.getTime(), time); if (areTimeRangesDifferent(this.getTime(), newTime)) { @@ -114,7 +109,7 @@ export class Timefilter { } }; - getRefreshInterval = () => { + public getRefreshInterval = () => { return _.clone(this._refreshInterval); }; @@ -124,7 +119,7 @@ export class Timefilter { * @property {number} time.value Refresh interval in milliseconds. Positive integer * @property {boolean} time.pause */ - setRefreshInterval = (refreshInterval: Partial) => { + public setRefreshInterval = (refreshInterval: Partial) => { const prevRefreshInterval = this.getRefreshInterval(); const newRefreshInterval = { ...prevRefreshInterval, ...refreshInterval }; // If the refresh interval is <= 0 handle that as a paused refresh @@ -149,39 +144,19 @@ export class Timefilter { } }; - toggleRefresh = () => { - this.setRefreshInterval({ - pause: !this._refreshInterval.pause, - value: this._refreshInterval.value, - }); - }; - - createFilter = (indexPattern: IndexPattern, timeRange?: TimeRange) => { + public createFilter = (indexPattern: IndexPattern, timeRange?: TimeRange) => { return getTime(indexPattern, timeRange ? timeRange : this._time, this.getForceNow()); }; - getBounds = () => { + public getBounds = () => { return this.calculateBounds(this._time); }; - getForceNow = () => { - const forceNow = parseQueryString().forceNow as string; - if (!forceNow) { - return; - } - - const ticks = Date.parse(forceNow); - if (isNaN(ticks)) { - throw new Error(`forceNow query parameter, ${forceNow}, can't be parsed by Date.parse`); - } - return new Date(ticks); - }; - - calculateBounds = (timeRange: TimeRange) => { + public calculateBounds = (timeRange: TimeRange) => { return calculateBounds(timeRange, { forceNow: this.getForceNow() }); }; - getActiveBounds = () => { + public getActiveBounds = () => { if (this.isTimeRangeSelectorEnabled) { return this.getBounds(); } @@ -190,36 +165,55 @@ export class Timefilter { /** * Show the time bounds selector part of the time filter */ - enableTimeRangeSelector = () => { - this.isTimeRangeSelectorEnabled = true; + public enableTimeRangeSelector = () => { + this._isTimeRangeSelectorEnabled = true; this.enabledUpdated$.next(true); }; /** * Hide the time bounds selector part of the time filter */ - disableTimeRangeSelector = () => { - this.isTimeRangeSelectorEnabled = false; + public disableTimeRangeSelector = () => { + this._isTimeRangeSelectorEnabled = false; this.enabledUpdated$.next(false); }; /** * Show the auto refresh part of the time filter */ - enableAutoRefreshSelector = () => { - this.isAutoRefreshSelectorEnabled = true; + public enableAutoRefreshSelector = () => { + this._isAutoRefreshSelectorEnabled = true; this.enabledUpdated$.next(true); }; /** * Hide the auto refresh part of the time filter */ - disableAutoRefreshSelector = () => { - this.isAutoRefreshSelectorEnabled = false; + public disableAutoRefreshSelector = () => { + this._isAutoRefreshSelectorEnabled = false; this.enabledUpdated$.next(false); }; - notifyShouldFetch = () => { + /** + * Added to allow search_poll to trigger an auto refresh event. + * Before this change, search_poll used to access a now private member of this instance. + */ + public notifyShouldFetch = () => { this.autoRefreshFetch$.next(); }; + + private getForceNow = () => { + const forceNow = parseQueryString().forceNow as string; + if (!forceNow) { + return; + } + + const ticks = Date.parse(forceNow); + if (isNaN(ticks)) { + throw new Error(`forceNow query parameter, ${forceNow}, can't be parsed by Date.parse`); + } + return new Date(ticks); + }; } + +export type TimefilterContract = PublicMethodsOf; diff --git a/src/legacy/core_plugins/data/public/timefilter/timefilter_service.mock.ts b/src/legacy/core_plugins/data/public/timefilter/timefilter_service.mock.ts new file mode 100644 index 000000000000..fad4217acd21 --- /dev/null +++ b/src/legacy/core_plugins/data/public/timefilter/timefilter_service.mock.ts @@ -0,0 +1,76 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { TimefilterService, TimeHistoryContract, TimefilterContract } from '.'; + +export type TimefilterServiceClientContract = PublicMethodsOf; + +const createSetupContractMock = () => { + const timefilterMock: jest.Mocked = { + isAutoRefreshSelectorEnabled: jest.fn(), + isTimeRangeSelectorEnabled: jest.fn(), + getEnabledUpdated$: jest.fn(), + getTimeUpdate$: jest.fn(), + getRefreshIntervalUpdate$: jest.fn(), + getAutoRefreshFetch$: jest.fn(), + getFetch$: jest.fn(), + getTime: jest.fn(), + setTime: jest.fn(), + setRefreshInterval: jest.fn(), + getRefreshInterval: jest.fn(), + getActiveBounds: jest.fn(), + disableAutoRefreshSelector: jest.fn(), + disableTimeRangeSelector: jest.fn(), + enableAutoRefreshSelector: jest.fn(), + enableTimeRangeSelector: jest.fn(), + getBounds: jest.fn(), + calculateBounds: jest.fn(), + notifyShouldFetch: jest.fn(), + createFilter: jest.fn(), + }; + + const historyMock: jest.Mocked = { + add: jest.fn(), + get: jest.fn(), + }; + + const setupContract = { + timefilter: timefilterMock, + history: historyMock, + }; + + return setupContract; +}; + +const createMock = () => { + const mocked: jest.Mocked = { + setup: jest.fn(), + start: jest.fn(), + stop: jest.fn(), + }; + + mocked.setup.mockReturnValue(createSetupContractMock()); + return mocked; +}; + +export const timefilterServiceMock = { + create: createMock, + createSetupContract: createSetupContractMock, + createStartContract: createSetupContractMock, +}; diff --git a/src/legacy/core_plugins/data/public/timefilter/timefilter_service.ts b/src/legacy/core_plugins/data/public/timefilter/timefilter_service.ts new file mode 100644 index 000000000000..96c490a195d3 --- /dev/null +++ b/src/legacy/core_plugins/data/public/timefilter/timefilter_service.ts @@ -0,0 +1,60 @@ +/* + * Licensed to Elasticsearch B.V. under one or more contributor + * license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright + * ownership. Elasticsearch B.V. licenses this file to you under + * the Apache License, Version 2.0 (the "License"); you may + * not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { UiSettingsClientContract } from 'src/core/public'; +import { TimeHistory, Timefilter, TimeHistoryContract, TimefilterContract } from './index'; + +/** + * Filter Service + * @internal + */ + +export interface TimeFilterServiceDependencies { + uiSettings: UiSettingsClientContract; +} + +export class TimefilterService { + public setup({ uiSettings }: TimeFilterServiceDependencies): TimefilterSetup { + const timefilterConfig = { + timeDefaults: uiSettings.get('timepicker:timeDefaults'), + refreshIntervalDefaults: uiSettings.get('timepicker:refreshIntervalDefaults'), + }; + const history = new TimeHistory(); + const timefilter = new Timefilter(timefilterConfig, history); + + return { + timefilter, + history, + }; + } + + public start() { + // nothing to do here yet + } + + public stop() { + // nothing to do here yet + } +} + +/** @public */ +export interface TimefilterSetup { + timefilter: TimefilterContract; + history: TimeHistoryContract; +} diff --git a/src/legacy/core_plugins/data/public/filter/filter_manager/lib/__tests__/change_time_filter.test.mocks.ts b/src/legacy/core_plugins/data/public/timefilter/types.ts similarity index 63% rename from src/legacy/core_plugins/data/public/filter/filter_manager/lib/__tests__/change_time_filter.test.mocks.ts rename to src/legacy/core_plugins/data/public/timefilter/types.ts index add054c49251..879776cee178 100644 --- a/src/legacy/core_plugins/data/public/filter/filter_manager/lib/__tests__/change_time_filter.test.mocks.ts +++ b/src/legacy/core_plugins/data/public/timefilter/types.ts @@ -16,13 +16,23 @@ * specific language governing permissions and limitations * under the License. */ +import { Moment } from 'moment'; +import { RefreshInterval, TimeRange } from 'src/plugins/data/public'; -import { chromeServiceMock } from '../../../../../../../../core/public/mocks'; +export interface TimefilterConfig { + timeDefaults: TimeRange; + refreshIntervalDefaults: RefreshInterval; +} -jest.doMock('ui/new_platform', () => ({ - npStart: { - core: { - chrome: chromeServiceMock.createStartContract(), - }, - }, -})); +// Timefilter accepts moment input but always returns string output +export type InputTimeRange = + | TimeRange + | { + from: Moment; + to: Moment; + }; + +export interface TimeRangeBounds { + min: Moment | undefined; + max: Moment | undefined; +} diff --git a/src/legacy/core_plugins/kibana/public/dashboard/dashboard_state.test.ts b/src/legacy/core_plugins/kibana/public/dashboard/dashboard_state.test.ts index be76f498c891..d7847c8338cd 100644 --- a/src/legacy/core_plugins/kibana/public/dashboard/dashboard_state.test.ts +++ b/src/legacy/core_plugins/kibana/public/dashboard/dashboard_state.test.ts @@ -24,36 +24,31 @@ import { getAppStateMock, getSavedDashboardMock } from './__tests__'; import { AppStateClass } from 'ui/state_management/app_state'; import { DashboardAppState } from './types'; import { TimeRange } from 'src/plugins/data/public'; -import { Timefilter } from 'ui/timefilter'; import { ViewMode } from '../../../embeddable_api/public/np_ready/public'; +import { InputTimeRange } from 'ui/timefilter'; + +jest.mock('ui/registry/field_formats', () => ({ + fieldFormats: { + getDefaultInstance: jest.fn(), + }, +})); + +import { dataPluginMock } from '../../../../core_plugins/data/public/mocks'; +const dataSetupMock = dataPluginMock.createSetup(); describe('DashboardState', function() { let dashboardState: DashboardStateManager; const savedDashboard = getSavedDashboardMock(); let mockTime: TimeRange = { to: 'now', from: 'now-15m' }; - const mockTimefilter: Partial = { - setTime(time) { - mockTime = time as TimeRange; - }, - getTime() { - return mockTime; - }, - disableAutoRefreshSelector: jest.fn(), - setRefreshInterval: jest.fn(), - getRefreshInterval: jest.fn(), - disableTimeRangeSelector: jest.fn(), - enableAutoRefreshSelector: jest.fn(), - getActiveBounds: jest.fn(), - enableTimeRangeSelector: () => {}, - isAutoRefreshSelectorEnabled: true, - isTimeRangeSelectorEnabled: true, - getAutoRefreshFetch$: jest.fn(), - getEnabledUpdated$: jest.fn(), - getRefreshIntervalUpdate$: jest.fn(), - getFetch$: jest.fn(), - getTimeUpdate$: jest.fn(), - }; + const mockTimefilter = dataSetupMock.timefilter!.timefilter; + + mockTimefilter.setTime.mockImplementation((time: InputTimeRange) => { + mockTime = time as TimeRange; + }); + mockTimefilter.getTime.mockImplementation(() => { + return mockTime; + }); function initDashboardState() { dashboardState = new DashboardStateManager({ @@ -73,7 +68,7 @@ describe('DashboardState', function() { mockTime.to = '2015-09-29 06:31:44.000'; initDashboardState(); - dashboardState.syncTimefilterWithDashboard(mockTimefilter as Timefilter); + dashboardState.syncTimefilterWithDashboard(mockTimefilter); expect(mockTime.to).toBe('now/w'); expect(mockTime.from).toBe('now/w'); @@ -88,7 +83,7 @@ describe('DashboardState', function() { mockTime.to = '2015-09-29 06:31:44.000'; initDashboardState(); - dashboardState.syncTimefilterWithDashboard(mockTimefilter as Timefilter); + dashboardState.syncTimefilterWithDashboard(mockTimefilter); expect(mockTime.to).toBe('now'); expect(mockTime.from).toBe('now-13d'); @@ -103,7 +98,7 @@ describe('DashboardState', function() { mockTime.to = 'now/w'; initDashboardState(); - dashboardState.syncTimefilterWithDashboard(mockTimefilter as Timefilter); + dashboardState.syncTimefilterWithDashboard(mockTimefilter); expect(mockTime.to).toBe(savedDashboard.timeTo); expect(mockTime.from).toBe(savedDashboard.timeFrom); diff --git a/src/legacy/core_plugins/kibana/public/discover/embeddable/search_embeddable.ts b/src/legacy/core_plugins/kibana/public/discover/embeddable/search_embeddable.ts index 01c3adaec000..d5bf868f3bf7 100644 --- a/src/legacy/core_plugins/kibana/public/discover/embeddable/search_embeddable.ts +++ b/src/legacy/core_plugins/kibana/public/discover/embeddable/search_embeddable.ts @@ -35,10 +35,10 @@ import { Filter, FilterStateStore } from '@kbn/es-query'; import chrome from 'ui/chrome'; import { i18n } from '@kbn/i18n'; import { toastNotifications } from 'ui/notify'; -import { timefilter, getTime } from 'ui/timefilter'; import { TimeRange } from 'src/plugins/data/public'; import { TExecuteTriggerActions } from 'src/plugins/ui_actions/public'; -import { Query, onlyDisabledFiltersChanged } from '../../../../data/public'; +import { setup as data } from '../../../../data/public/legacy'; +import { Query, onlyDisabledFiltersChanged, getTime } from '../../../../data/public'; import { APPLY_FILTER_TRIGGER, Embeddable, @@ -141,7 +141,9 @@ export class SearchEmbeddable extends Embeddable requests: new RequestAdapter(), }; this.initializeSearchScope(); - this.autoRefreshFetchSubscription = timefilter.getAutoRefreshFetch$().subscribe(this.fetch); + this.autoRefreshFetchSubscription = data.timefilter.timefilter + .getAutoRefreshFetch$() + .subscribe(this.fetch); this.subscription = Rx.merge(this.getOutput$(), this.getInput$()).subscribe(() => { this.panelTitle = this.output.title || ''; diff --git a/src/legacy/core_plugins/kibana_react/public/top_nav_menu/top_nav_menu.test.tsx b/src/legacy/core_plugins/kibana_react/public/top_nav_menu/top_nav_menu.test.tsx index 6f26f43a805b..e4e9dd7dd731 100644 --- a/src/legacy/core_plugins/kibana_react/public/top_nav_menu/top_nav_menu.test.tsx +++ b/src/legacy/core_plugins/kibana_react/public/top_nav_menu/top_nav_menu.test.tsx @@ -25,6 +25,9 @@ import { shallowWithIntl } from 'test_utils/enzyme_helpers'; import { coreMock } from '../../../../../core/public/mocks'; const startMock = coreMock.createStart(); +import { timefilterServiceMock } from '../../../../core_plugins/data/public/timefilter/timefilter_service.mock'; +const timefilterSetupMock = timefilterServiceMock.createSetupContract(); + jest.mock('../../../../core_plugins/data/public', () => { return { SearchBar: () =>
, @@ -57,6 +60,7 @@ describe('TopNavMenu', () => { const component = shallowWithIntl( { const component = shallowWithIntl( { const component = shallowWithIntl( { const component = shallowWithIntl( & { name: string; uiSettings: UiSettingsClientContract; savedObjectsClient: SavedObjectsClientContract; + timeHistory: TimeHistoryContract; toasts: CoreStart['notifications']['toasts']; config?: TopNavMenuData[]; showSearchBar?: boolean; @@ -58,9 +63,11 @@ export function TopNavMenu(props: Props) { function renderSearchBar() { // Validate presense of all required fields - if (!props.showSearchBar || !props.savedObjectsClient || !props.http) return; + if (!props.showSearchBar || !props.savedObjectsClient || !props.timeHistory || !props.http) + return; return ( { const localStorage = new Storage(window.localStorage); child.setAttribute('http', 'http'); child.setAttribute('store', 'store'); + child.setAttribute('time-history', 'timeHistory'); child.setAttribute('ui-settings', 'uiSettings'); child.setAttribute('saved-objects-client', 'savedObjectsClient'); @@ -58,6 +60,7 @@ module.directive('kbnTopNav', () => { $scope.store = localStorage; $scope.http = npSetup.core.http; $scope.uiSettings = npSetup.core.uiSettings; + $scope.timeHistory = data.timefilter.history; $scope.savedObjectsClient = chrome.getSavedObjectsClient(); // Watch config changes @@ -102,6 +105,7 @@ module.directive('kbnTopNavHelper', (reactDirective) => { ['uiSettings', { watchDepth: 'reference' }], ['savedObjectsClient', { watchDepth: 'reference' }], ['intl', { watchDepth: 'reference' }], + ['timeHistory', { watchDepth: 'reference' }], ['store', { watchDepth: 'reference' }], ['http', { watchDepth: 'reference' }], diff --git a/src/legacy/ui/public/timefilter/index.ts b/src/legacy/ui/public/timefilter/index.ts index 34f2a367a217..d579148bd755 100644 --- a/src/legacy/ui/public/timefilter/index.ts +++ b/src/legacy/ui/public/timefilter/index.ts @@ -18,14 +18,20 @@ */ import uiRoutes from 'ui/routes'; -import { registerTimefilterWithGlobalState, getTimefilterConfig } from './setup_router'; -import { Timefilter, TimeHistory } from '../../../core_plugins/data/public/timefilter'; +import { TimefilterContract, TimeHistoryContract } from '../../../core_plugins/data/public'; +import { registerTimefilterWithGlobalState } from './setup_router'; +import { setup as data } from '../../../core_plugins/data/public/legacy'; -const config = getTimefilterConfig(); - -export { Timefilter, TimeHistory, getTime } from '../../../core_plugins/data/public/timefilter'; -export const timeHistory = new TimeHistory(); -export const timefilter = new Timefilter(config, timeHistory); +export { + getTime, + InputTimeRange, + TimeHistoryContract, + TimefilterContract, +} from '../../../core_plugins/data/public'; +export type Timefilter = TimefilterContract; +export type TimeHistory = TimeHistoryContract; +export const timeHistory = data.timefilter.history; +export const timefilter = data.timefilter.timefilter; uiRoutes.addSetupWork((globalState, $rootScope) => { return registerTimefilterWithGlobalState(timefilter, globalState, $rootScope); diff --git a/src/legacy/ui/public/timefilter/setup_router.ts b/src/legacy/ui/public/timefilter/setup_router.ts index cbd03df455da..3c81fde89149 100644 --- a/src/legacy/ui/public/timefilter/setup_router.ts +++ b/src/legacy/ui/public/timefilter/setup_router.ts @@ -23,7 +23,7 @@ import moment from 'moment'; import { subscribeWithScope } from 'ui/utils/subscribe_with_scope'; import chrome from 'ui/chrome'; import { RefreshInterval, TimeRange } from 'src/plugins/data/public'; -import { Timefilter } from '../../../core_plugins/data/public/timefilter'; +import { TimefilterContract } from '../../../core_plugins/data/public/timefilter'; // TODO // remove everything underneath once globalState is no longer an angular service @@ -46,7 +46,7 @@ export function getTimefilterConfig() { // This function is exposed for applications that do not use uiRoutes like APM // Kibana issue https://github.com/elastic/kibana/issues/19110 tracks the removal of this dependency on uiRouter export const registerTimefilterWithGlobalState = _.once( - (timefilter: Timefilter, globalState: any, $rootScope: IScope) => { + (timefilter: TimefilterContract, globalState: any, $rootScope: IScope) => { // settings have to be re-fetched here, to make sure that settings changed by overrideLocalDefault are taken into account. const config = getTimefilterConfig(); timefilter.setTime(_.defaults(globalState.time || {}, config.timeDefaults)); diff --git a/src/legacy/ui/public/vis/vis_filters/brush_event.test.js b/src/legacy/ui/public/vis/vis_filters/brush_event.test.js index df515430888c..6d548a7309d5 100644 --- a/src/legacy/ui/public/vis/vis_filters/brush_event.test.js +++ b/src/legacy/ui/public/vis/vis_filters/brush_event.test.js @@ -17,26 +17,6 @@ * under the License. */ -import './brush_event.test.mocks'; - -jest.mock('ui/chrome', - () => ({ - getBasePath: () => `/some/base/path`, - getUiSettingsClient: () => { - return { - get: (key) => { - switch (key) { - case 'timepicker:timeDefaults': - return { from: 'now-15m', to: 'now' }; - case 'timepicker:refreshIntervalDefaults': - return { pause: false, value: 0 }; - default: - throw new Error(`Unexpected config key: ${key}`); - } - } - }; - }, - }), { virtual: true }); import _ from 'lodash'; import moment from 'moment'; diff --git a/src/legacy/ui/public/visualize/loader/embedded_visualize_handler.test.ts b/src/legacy/ui/public/visualize/loader/embedded_visualize_handler.test.ts index 51ba983bd9a5..9d6b56c32f1c 100644 --- a/src/legacy/ui/public/visualize/loader/embedded_visualize_handler.test.ts +++ b/src/legacy/ui/public/visualize/loader/embedded_visualize_handler.test.ts @@ -16,6 +16,8 @@ * specific language governing permissions and limitations * under the License. */ +jest.mock('ui/new_platform'); + import { mockDataLoaderFetch, timefilter } from './embedded_visualize_handler.test.mocks'; import _ from 'lodash'; @@ -27,7 +29,11 @@ import { Inspector } from '../../inspector'; import { EmbeddedVisualizeHandler, RequestHandlerParams } from './embedded_visualize_handler'; import { AggConfigs } from 'ui/agg_types/agg_configs'; -jest.mock('ui/new_platform'); +jest.mock('plugins/interpreter/interpreter', () => ({ + getInterpreter: () => { + return Promise.resolve(); + }, +})); jest.mock('../../../../core_plugins/interpreter/public/registries', () => ({ registries: { diff --git a/x-pack/legacy/plugins/ml/public/components/navigation_menu/top_nav/top_nav.tsx b/x-pack/legacy/plugins/ml/public/components/navigation_menu/top_nav/top_nav.tsx index 12517c55f7f3..523970dfe12f 100644 --- a/x-pack/legacy/plugins/ml/public/components/navigation_menu/top_nav/top_nav.tsx +++ b/x-pack/legacy/plugins/ml/public/components/navigation_menu/top_nav/top_nav.tsx @@ -37,10 +37,10 @@ export const TopNav: FC = () => { const [time, setTime] = useState(timefilter.getTime()); const [recentlyUsedRanges, setRecentlyUsedRanges] = useState(getRecentlyUsedRanges()); const [isAutoRefreshSelectorEnabled, setIsAutoRefreshSelectorEnabled] = useState( - timefilter.isAutoRefreshSelectorEnabled + timefilter.isAutoRefreshSelectorEnabled() ); const [isTimeRangeSelectorEnabled, setIsTimeRangeSelectorEnabled] = useState( - timefilter.isTimeRangeSelectorEnabled + timefilter.isTimeRangeSelectorEnabled() ); const dateFormat = chrome.getUiSettingsClient().get('dateFormat'); @@ -64,8 +64,8 @@ export const TopNav: FC = () => { function timefilterUpdateListener() { setTime(timefilter.getTime()); setRefreshInterval(timefilter.getRefreshInterval()); - setIsAutoRefreshSelectorEnabled(timefilter.isAutoRefreshSelectorEnabled); - setIsTimeRangeSelectorEnabled(timefilter.isTimeRangeSelectorEnabled); + setIsAutoRefreshSelectorEnabled(timefilter.isAutoRefreshSelectorEnabled()); + setIsTimeRangeSelectorEnabled(timefilter.isTimeRangeSelectorEnabled()); } function updateFilter({ start, end }: Duration) { diff --git a/x-pack/legacy/plugins/ml/public/contexts/ui/__mocks__/mocks.ts b/x-pack/legacy/plugins/ml/public/contexts/ui/__mocks__/mocks.ts index e6e51f0bdecf..785daec0ab36 100644 --- a/x-pack/legacy/plugins/ml/public/contexts/ui/__mocks__/mocks.ts +++ b/x-pack/legacy/plugins/ml/public/contexts/ui/__mocks__/mocks.ts @@ -37,11 +37,17 @@ const time = { }; export const uiTimefilterMock = { + isAutoRefreshSelectorEnabled() { + return this._isAutoRefreshSelectorEnabled; + }, + isTimeRangeSelectorEnabled() { + return this._isTimeRangeSelectorEnabled; + }, enableAutoRefreshSelector() { - this.isAutoRefreshSelectorEnabled = true; + this._isAutoRefreshSelectorEnabled = true; }, enableTimeRangeSelector() { - this.isTimeRangeSelectorEnabled = true; + this._isTimeRangeSelectorEnabled = true; }, getEnabledUpdated$() { return { subscribe: jest.fn() }; @@ -56,8 +62,8 @@ export const uiTimefilterMock = { getTimeUpdate$() { return { subscribe: jest.fn() }; }, - isAutoRefreshSelectorEnabled: false, - isTimeRangeSelectorEnabled: false, + _isAutoRefreshSelectorEnabled: false, + _isTimeRangeSelectorEnabled: false, refreshInterval: { value: 0, pause: true }, on: (event: string, reload: () => void) => {}, setRefreshInterval(refreshInterval: RefreshInterval) { diff --git a/x-pack/legacy/plugins/ml/public/data_frame/pages/transform_management/page.test.mocks.ts b/x-pack/legacy/plugins/ml/public/data_frame/pages/transform_management/page.test.mocks.ts index fd3b04b2332d..46178a7d0297 100644 --- a/x-pack/legacy/plugins/ml/public/data_frame/pages/transform_management/page.test.mocks.ts +++ b/x-pack/legacy/plugins/ml/public/data_frame/pages/transform_management/page.test.mocks.ts @@ -4,12 +4,6 @@ * you may not use this file except in compliance with the Elastic License. */ -import { chromeServiceMock } from '../../../../../../../../src/core/public/mocks'; - -jest.doMock('ui/new_platform', () => ({ - npStart: { - core: { - chrome: chromeServiceMock.createStartContract(), - }, - }, -})); +jest.mock('ui/timefilter', () => { + return {}; +}); diff --git a/x-pack/legacy/plugins/ml/public/explorer/explorer_charts/explorer_chart_distribution.test.mocks.ts b/x-pack/legacy/plugins/ml/public/explorer/explorer_charts/explorer_chart_distribution.test.mocks.ts index d3d1305fa6ff..46178a7d0297 100644 --- a/x-pack/legacy/plugins/ml/public/explorer/explorer_charts/explorer_chart_distribution.test.mocks.ts +++ b/x-pack/legacy/plugins/ml/public/explorer/explorer_charts/explorer_chart_distribution.test.mocks.ts @@ -4,12 +4,6 @@ * you may not use this file except in compliance with the Elastic License. */ -import { chromeServiceMock } from '../../../../../../../src/core/public/mocks'; - -jest.doMock('ui/new_platform', () => ({ - npStart: { - core: { - chrome: chromeServiceMock.createStartContract(), - }, - }, -})); +jest.mock('ui/timefilter', () => { + return {}; +}); diff --git a/x-pack/legacy/plugins/ml/public/explorer/explorer_charts/explorer_chart_single_metric.test.mocks.ts b/x-pack/legacy/plugins/ml/public/explorer/explorer_charts/explorer_chart_single_metric.test.mocks.ts index d3d1305fa6ff..46178a7d0297 100644 --- a/x-pack/legacy/plugins/ml/public/explorer/explorer_charts/explorer_chart_single_metric.test.mocks.ts +++ b/x-pack/legacy/plugins/ml/public/explorer/explorer_charts/explorer_chart_single_metric.test.mocks.ts @@ -4,12 +4,6 @@ * you may not use this file except in compliance with the Elastic License. */ -import { chromeServiceMock } from '../../../../../../../src/core/public/mocks'; - -jest.doMock('ui/new_platform', () => ({ - npStart: { - core: { - chrome: chromeServiceMock.createStartContract(), - }, - }, -})); +jest.mock('ui/timefilter', () => { + return {}; +}); diff --git a/x-pack/legacy/plugins/ml/public/explorer/explorer_charts/explorer_charts_container.test.js b/x-pack/legacy/plugins/ml/public/explorer/explorer_charts/explorer_charts_container.test.js index 6b18a761e564..0c410f418b2a 100644 --- a/x-pack/legacy/plugins/ml/public/explorer/explorer_charts/explorer_charts_container.test.js +++ b/x-pack/legacy/plugins/ml/public/explorer/explorer_charts/explorer_charts_container.test.js @@ -37,32 +37,8 @@ jest.mock('ui/chrome', getBasePath: () => { return ''; }, - getUiSettingsClient: () => { - return { - get: (key) => { - switch (key) { - case 'timepicker:timeDefaults': - return { from: 'now-15m', to: 'now', mode: 'quick' }; - case 'timepicker:refreshIntervalDefaults': - return { pause: false, value: 0 }; - default: - throw new Error(`Unexpected config key: ${key}`); - } - } - }; - }, }), { virtual: true }); -import moment from 'moment'; -import { timefilter } from 'ui/timefilter'; - -timefilter.enableTimeRangeSelector(); -timefilter.enableAutoRefreshSelector(); -timefilter.setTime({ - from: moment(seriesConfig.selectedEarliest).toISOString(), - to: moment(seriesConfig.selectedLatest).toISOString() -}); - import { shallowWithIntl, mountWithIntl } from 'test_utils/enzyme_helpers'; import React from 'react'; diff --git a/x-pack/legacy/plugins/ml/public/explorer/explorer_charts/explorer_charts_container.test.mocks.ts b/x-pack/legacy/plugins/ml/public/explorer/explorer_charts/explorer_charts_container.test.mocks.ts index d3d1305fa6ff..46178a7d0297 100644 --- a/x-pack/legacy/plugins/ml/public/explorer/explorer_charts/explorer_charts_container.test.mocks.ts +++ b/x-pack/legacy/plugins/ml/public/explorer/explorer_charts/explorer_charts_container.test.mocks.ts @@ -4,12 +4,6 @@ * you may not use this file except in compliance with the Elastic License. */ -import { chromeServiceMock } from '../../../../../../../src/core/public/mocks'; - -jest.doMock('ui/new_platform', () => ({ - npStart: { - core: { - chrome: chromeServiceMock.createStartContract(), - }, - }, -})); +jest.mock('ui/timefilter', () => { + return {}; +}); diff --git a/x-pack/legacy/plugins/ml/public/explorer/explorer_charts/explorer_charts_container_service.test.mocks.ts b/x-pack/legacy/plugins/ml/public/explorer/explorer_charts/explorer_charts_container_service.test.mocks.ts index d3d1305fa6ff..46178a7d0297 100644 --- a/x-pack/legacy/plugins/ml/public/explorer/explorer_charts/explorer_charts_container_service.test.mocks.ts +++ b/x-pack/legacy/plugins/ml/public/explorer/explorer_charts/explorer_charts_container_service.test.mocks.ts @@ -4,12 +4,6 @@ * you may not use this file except in compliance with the Elastic License. */ -import { chromeServiceMock } from '../../../../../../../src/core/public/mocks'; - -jest.doMock('ui/new_platform', () => ({ - npStart: { - core: { - chrome: chromeServiceMock.createStartContract(), - }, - }, -})); +jest.mock('ui/timefilter', () => { + return {}; +}); diff --git a/x-pack/legacy/plugins/ml/public/explorer/explorer_swimlane.test.mocks.ts b/x-pack/legacy/plugins/ml/public/explorer/explorer_swimlane.test.mocks.ts index c7c7960b72d6..46178a7d0297 100644 --- a/x-pack/legacy/plugins/ml/public/explorer/explorer_swimlane.test.mocks.ts +++ b/x-pack/legacy/plugins/ml/public/explorer/explorer_swimlane.test.mocks.ts @@ -4,12 +4,6 @@ * you may not use this file except in compliance with the Elastic License. */ -import { chromeServiceMock } from '../../../../../../src/core/public/mocks'; - -jest.doMock('ui/new_platform', () => ({ - npStart: { - core: { - chrome: chromeServiceMock.createStartContract(), - }, - }, -})); +jest.mock('ui/timefilter', () => { + return {}; +}); diff --git a/x-pack/legacy/plugins/ml/public/timeseriesexplorer/components/timeseries_chart/timeseries_chart.test.mocks.ts b/x-pack/legacy/plugins/ml/public/timeseriesexplorer/components/timeseries_chart/timeseries_chart.test.mocks.ts index fd3b04b2332d..46178a7d0297 100644 --- a/x-pack/legacy/plugins/ml/public/timeseriesexplorer/components/timeseries_chart/timeseries_chart.test.mocks.ts +++ b/x-pack/legacy/plugins/ml/public/timeseriesexplorer/components/timeseries_chart/timeseries_chart.test.mocks.ts @@ -4,12 +4,6 @@ * you may not use this file except in compliance with the Elastic License. */ -import { chromeServiceMock } from '../../../../../../../../src/core/public/mocks'; - -jest.doMock('ui/new_platform', () => ({ - npStart: { - core: { - chrome: chromeServiceMock.createStartContract(), - }, - }, -})); +jest.mock('ui/timefilter', () => { + return {}; +}); diff --git a/x-pack/legacy/plugins/ml/public/util/chart_utils.test.js b/x-pack/legacy/plugins/ml/public/util/chart_utils.test.js index eea6691c944b..aaec5e412c4c 100644 --- a/x-pack/legacy/plugins/ml/public/util/chart_utils.test.js +++ b/x-pack/legacy/plugins/ml/public/util/chart_utils.test.js @@ -4,9 +4,35 @@ * you may not use this file except in compliance with the Elastic License. */ -import './chart_utils.test.mocks'; import seriesConfig from '../explorer/explorer_charts/__mocks__/mock_series_config_filebeat'; +jest.mock('ui/registry/field_formats', () => ({ + fieldFormats: { + getDefaultInstance: jest.fn(), + }, +})); + +jest.mock('ui/timefilter', () => { + const dateMath = require('@elastic/datemath'); + const { dataPluginMock } = require('../../../../../../src/legacy/core_plugins/data/public/mocks'); + const dataSetup = dataPluginMock.createSetup(); + const { timefilter } = dataSetup.timefilter; + let _time = undefined; + timefilter.setTime.mockImplementation((time) => { + _time = time; + }); + timefilter.getActiveBounds.mockImplementation(() => { + return { + min: dateMath.parse(_time.from), + max: dateMath.parse(_time.to), + }; + }); + return { + timefilter, + }; +}); +import { timefilter } from 'ui/timefilter'; + // A copy of these mocks for ui/chrome and ui/timefilter are also // used in explorer_charts_container.test.js. // TODO: Refactor the involved tests to avoid this duplication @@ -15,20 +41,6 @@ jest.mock('ui/chrome', getBasePath: () => { return ''; }, - getUiSettingsClient: () => { - return { - get: (key) => { - switch (key) { - case 'timepicker:timeDefaults': - return { from: 'now-15m', to: 'now', mode: 'quick' }; - case 'timepicker:refreshIntervalDefaults': - return { pause: false, value: 0 }; - default: - throw new Error(`Unexpected config key: ${key}`); - } - } - }; - }, }), { virtual: true }); import d3 from 'd3'; @@ -36,7 +48,6 @@ import moment from 'moment'; import { mount } from 'enzyme'; import React from 'react'; -import { timefilter } from 'ui/timefilter'; import { getExploreSeriesLink, @@ -46,8 +57,6 @@ import { removeLabelOverlap } from './chart_utils'; -timefilter.enableTimeRangeSelector(); -timefilter.enableAutoRefreshSelector(); timefilter.setTime({ from: moment(seriesConfig.selectedEarliest).toISOString(), to: moment(seriesConfig.selectedLatest).toISOString() diff --git a/x-pack/legacy/plugins/ml/public/util/chart_utils.test.mocks.ts b/x-pack/legacy/plugins/ml/public/util/chart_utils.test.mocks.ts deleted file mode 100644 index c7c7960b72d6..000000000000 --- a/x-pack/legacy/plugins/ml/public/util/chart_utils.test.mocks.ts +++ /dev/null @@ -1,15 +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 { chromeServiceMock } from '../../../../../../src/core/public/mocks'; - -jest.doMock('ui/new_platform', () => ({ - npStart: { - core: { - chrome: chromeServiceMock.createStartContract(), - }, - }, -})); diff --git a/x-pack/legacy/plugins/monitoring/public/views/__tests__/base_controller.js b/x-pack/legacy/plugins/monitoring/public/views/__tests__/base_controller.js index 22949286f50e..4523c5db5846 100644 --- a/x-pack/legacy/plugins/monitoring/public/views/__tests__/base_controller.js +++ b/x-pack/legacy/plugins/monitoring/public/views/__tests__/base_controller.js @@ -124,8 +124,8 @@ describe('MonitoringViewBaseController', function () { describe('time filter', () => { it('enables timepicker and auto refresh #1', () => { - expect(timefilter.isTimeRangeSelectorEnabled).to.be(true); - expect(timefilter.isAutoRefreshSelectorEnabled).to.be(true); + expect(timefilter.isTimeRangeSelectorEnabled()).to.be(true); + expect(timefilter.isAutoRefreshSelectorEnabled()).to.be(true); }); it('enables timepicker and auto refresh #2', () => { @@ -135,8 +135,8 @@ describe('MonitoringViewBaseController', function () { }; ctrl = new MonitoringViewBaseController(opts); - expect(timefilter.isTimeRangeSelectorEnabled).to.be(true); - expect(timefilter.isAutoRefreshSelectorEnabled).to.be(true); + expect(timefilter.isTimeRangeSelectorEnabled()).to.be(true); + expect(timefilter.isAutoRefreshSelectorEnabled()).to.be(true); }); it('disables timepicker and enables auto refresh', () => { @@ -146,8 +146,8 @@ describe('MonitoringViewBaseController', function () { }; ctrl = new MonitoringViewBaseController(opts); - expect(timefilter.isTimeRangeSelectorEnabled).to.be(false); - expect(timefilter.isAutoRefreshSelectorEnabled).to.be(true); + expect(timefilter.isTimeRangeSelectorEnabled()).to.be(false); + expect(timefilter.isAutoRefreshSelectorEnabled()).to.be(true); }); it('enables timepicker and disables auto refresh', () => { @@ -157,8 +157,8 @@ describe('MonitoringViewBaseController', function () { }; ctrl = new MonitoringViewBaseController(opts); - expect(timefilter.isTimeRangeSelectorEnabled).to.be(true); - expect(timefilter.isAutoRefreshSelectorEnabled).to.be(false); + expect(timefilter.isTimeRangeSelectorEnabled()).to.be(true); + expect(timefilter.isAutoRefreshSelectorEnabled()).to.be(false); }); it('disables timepicker and auto refresh', () => { @@ -171,8 +171,8 @@ describe('MonitoringViewBaseController', function () { }; ctrl = new MonitoringViewBaseController(opts); - expect(timefilter.isTimeRangeSelectorEnabled).to.be(false); - expect(timefilter.isAutoRefreshSelectorEnabled).to.be(false); + expect(timefilter.isTimeRangeSelectorEnabled()).to.be(false); + expect(timefilter.isAutoRefreshSelectorEnabled()).to.be(false); }); it('disables timepicker and auto refresh', (done) => { diff --git a/x-pack/legacy/plugins/monitoring/public/views/__tests__/base_table_controller.js b/x-pack/legacy/plugins/monitoring/public/views/__tests__/base_table_controller.js index 5c2791d781f4..8cf68a6f2a13 100644 --- a/x-pack/legacy/plugins/monitoring/public/views/__tests__/base_table_controller.js +++ b/x-pack/legacy/plugins/monitoring/public/views/__tests__/base_table_controller.js @@ -22,8 +22,8 @@ describe('MonitoringViewBaseTableController', function () { timefilter = { enableTimeRangeSelector: spy(), enableAutoRefreshSelector: spy(), - isTimeRangeSelectorEnabled: true, - isAutoRefreshSelectorEnabled: true + isTimeRangeSelectorEnabled: () => true, + isAutoRefreshSelectorEnabled: () => true, }; titleService = spy(); executorService = { @@ -76,8 +76,8 @@ describe('MonitoringViewBaseTableController', function () { }); it('enables timepicker', () => { - expect(timefilter.isTimeRangeSelectorEnabled).to.be(true); - expect(timefilter.isAutoRefreshSelectorEnabled).to.be(true); + expect(timefilter.isTimeRangeSelectorEnabled()).to.be(true); + expect(timefilter.isAutoRefreshSelectorEnabled()).to.be(true); }); it('sets page title', () => {