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 a6700dc37e8d80..5eaa6744216c41 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 f230b035de3527..1605c647a2672d 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 a4345018aa8308..a4826e059fa22d 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 3a3cc176308c69..d3d05d20e9fbaa 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 eae71d244f8883..6c6ed775951c87 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 3d3fb92046507e..e6fea9cccd8f0f 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 063b69c175b203..8853fae455c1d0 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 9c95ef7a82ab83..d96e3be8d7e380 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 0ca0b4947d538a..2a82927bb3ebfb 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 ee4ecd98410958..aec97b02bc2b9f 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 1b73531ec41e3f..a52229415a4f98 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 47896189aa0801..0c6b0faf3e397d 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 5a1aaac0f104cf..c08ea9043da927 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 00000000000000..fad4217acd2158 --- /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 00000000000000..96c490a195d3dd --- /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 add054c4925108..879776cee178e7 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 be76f498c89115..d7847c8338cd2d 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 01c3adaec00048..d5bf868f3bf727 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 6f26f43a805bb1..e4e9dd7dd73168 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 34f2a367a217c5..d579148bd755ad 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 cbd03df455da3f..3c81fde89149b1 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 df515430888c0c..6d548a7309d5cc 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 51ba983bd9a528..9d6b56c32f1cb7 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 12517c55f7f359..523970dfe12f8a 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 e6e51f0bdecf4c..785daec0ab369d 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 fd3b04b2332d86..46178a7d029775 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 d3d1305fa6ffa6..46178a7d029775 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 d3d1305fa6ffa6..46178a7d029775 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 6b18a761e5642c..0c410f418b2afc 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 d3d1305fa6ffa6..46178a7d029775 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 d3d1305fa6ffa6..46178a7d029775 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 c7c7960b72d6e7..46178a7d029775 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 fd3b04b2332d86..46178a7d029775 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 eea6691c944b89..aaec5e412c4cb3 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 c7c7960b72d6e7..00000000000000 --- 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 22949286f50e3d..4523c5db584640 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 5c2791d781f4d7..8cf68a6f2a13e5 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', () => {