Skip to content

Commit

Permalink
[TSVB] Technical debt - remove default_index_pattern and default_time…
Browse files Browse the repository at this point in the history
…field from model (elastic#95925)

* [TSVB] Technical debt - remove default_index_pattern and default_timefield from model

* Update vis_editor.tsx

Co-authored-by: Kibana Machine <42973632+kibanamachine@users.noreply.github.com>
  • Loading branch information
alexwizp and kibanamachine committed Apr 7, 2021
1 parent 1bf810c commit 0de9e5e
Show file tree
Hide file tree
Showing 17 changed files with 145 additions and 73 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ describe('extractIndexPatterns', () => {
});

test('should return index patterns', () => {
expect(extractIndexPatternValues(panel, '')).toEqual([
expect(extractIndexPatternValues(panel, null)).toEqual([
'*',
'example-1-*',
'example-2-*',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

import { uniq } from 'lodash';
import { PanelSchema, IndexPatternValue, FetchedIndexPattern } from '../common/types';
import { IndexPatternsService } from '../../data/common';
import { IIndexPattern, IndexPatternsService } from '../../data/common';

export const isStringTypeIndexPattern = (
indexPatternValue: IndexPatternValue
Expand All @@ -19,7 +19,7 @@ export const getIndexPatternKey = (indexPatternValue: IndexPatternValue) =>

export const extractIndexPatternValues = (
panel: PanelSchema,
defaultIndex?: PanelSchema['default_index_pattern']
defaultIndex: IIndexPattern | null
) => {
const patterns: IndexPatternValue[] = [];

Expand All @@ -43,8 +43,8 @@ export const extractIndexPatternValues = (
});
}

if (patterns.length === 0 && defaultIndex) {
patterns.push(defaultIndex);
if (patterns.length === 0 && defaultIndex?.id) {
patterns.push({ id: defaultIndex.id });
}

return uniq<IndexPatternValue>(patterns).sort();
Expand Down
2 changes: 0 additions & 2 deletions src/plugins/vis_type_timeseries/common/vis_schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -213,8 +213,6 @@ export const panel = schema.object({
bar_color_rules: schema.maybe(arrayNullable),
background_color: stringOptionalNullable,
background_color_rules: schema.maybe(schema.arrayOf(backgroundColorRulesItems)),
default_index_pattern: stringOptionalNullable,
default_timefield: stringOptionalNullable,
drilldown_url: stringOptional,
drop_last_bucket: numberIntegerOptional,
filter: schema.maybe(queryObject),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ import { YesNo } from './yes_no';
import { LastValueModePopover } from './last_value_mode_popover';
import { KBN_FIELD_TYPES } from '../../../../data/public';
import { FormValidationContext } from '../contexts/form_validation_context';
import { DefaultIndexPatternContext } from '../contexts/default_index_context';
import { isGteInterval, validateReInterval, isAutoInterval } from './lib/get_interval';
import { i18n } from '@kbn/i18n';
import { FormattedMessage } from '@kbn/i18n/react';
Expand Down Expand Up @@ -76,6 +77,7 @@ export const IndexPattern = ({
const intervalName = `${prefix}interval`;
const maxBarsName = `${prefix}max_bars`;
const dropBucketName = `${prefix}drop_last_bucket`;
const defaultIndex = useContext(DefaultIndexPatternContext);
const updateControlValidity = useContext(FormValidationContext);
const uiRestrictions = get(useContext(VisDataContext), 'uiRestrictions');
const maxBarsUiSettings = config.get(UI_SETTINGS.HISTOGRAM_MAX_BARS);
Expand Down Expand Up @@ -110,7 +112,6 @@ export const IndexPattern = ({
];

const defaults = {
default_index_pattern: '',
[indexPatternName]: '',
[intervalName]: AUTO_INTERVAL,
[dropBucketName]: 1,
Expand All @@ -120,7 +121,6 @@ export const IndexPattern = ({

const model = { ...defaults, ..._model };

const isDefaultIndexPatternUsed = model.default_index_pattern && !model[indexPatternName];
const intervalValidation = validateIntervalValue(model[intervalName]);
const selectedTimeRangeOption = timeRangeOptions.find(
({ value }) => model[TIME_RANGE_MODE_KEY] === value
Expand Down Expand Up @@ -205,7 +205,7 @@ export const IndexPattern = ({
onChange={handleSelectChange(timeFieldName)}
indexPattern={model[indexPatternName]}
fields={fields}
placeholder={isDefaultIndexPatternUsed ? model.default_timefield : undefined}
placeholder={defaultIndex?.timeFieldName}
/>
</EuiFormRow>
</EuiFlexItem>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import { FieldTextSelect } from './field_text_select';
import { ComboBoxSelect } from './combo_box_select';

import type { IndexPatternValue, FetchedIndexPattern } from '../../../../../common/types';
import { DefaultIndexPatternContext } from '../../../contexts/default_index_context';

const USE_KIBANA_INDEXES_KEY = 'use_kibana_indexes';

Expand Down Expand Up @@ -61,6 +62,8 @@ export const IndexPatternSelect = ({
}: IndexPatternSelectProps) => {
const htmlId = htmlIdGenerator();
const panelModel = useContext(PanelModelContext);
const defaultIndex = useContext(DefaultIndexPatternContext);

const [fetchedIndex, setFetchedIndex] = useState<FetchedIndexPattern | null>();
const useKibanaIndices = Boolean(panelModel?.[USE_KIBANA_INDEXES_KEY]);
const Component = useKibanaIndices ? ComboBoxSelect : FieldTextSelect;
Expand Down Expand Up @@ -146,7 +149,7 @@ export const IndexPatternSelect = ({
allowSwitchMode={allowIndexSwitchingMode}
onIndexChange={onIndexChange}
onModeChange={onModeChange}
placeholder={panelModel?.default_index_pattern ?? ''}
placeholder={defaultIndex?.title ?? ''}
data-test-subj="metricsIndexPatternInput"
/>
</EuiFormRow>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,7 @@ export class GaugePanelConfig extends Component<
onChange={(filter) => {
this.props.onChange({ filter });
}}
indexPatterns={[model.index_pattern || model.default_index_pattern || '']}
indexPatterns={[model.index_pattern]}
/>
</EuiFormRow>
</EuiFlexItem>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,7 @@ export class MarkdownPanelConfig extends Component<
onChange={(filter) => {
this.props.onChange({ filter });
}}
indexPatterns={[model.index_pattern || model.default_index_pattern || '']}
indexPatterns={[model.index_pattern]}
/>
</EuiFormRow>
</EuiFlexItem>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ export class MetricPanelConfig extends Component<
onChange={(filter) => {
this.props.onChange({ filter });
}}
indexPatterns={[model.index_pattern || model.default_index_pattern || '']}
indexPatterns={[model.index_pattern]}
/>
</EuiFormRow>
</EuiFlexItem>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -244,7 +244,7 @@ export class TablePanelConfig extends Component<
onChange={(filter) => {
this.props.onChange({ filter });
}}
indexPatterns={[model.index_pattern || model.default_index_pattern || '']}
indexPatterns={[model.index_pattern]}
/>
</EuiFormRow>
</EuiFlexItem>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -207,7 +207,7 @@ export class TimeseriesPanelConfig extends Component<
onChange={(filter) => {
this.props.onChange({ filter });
}}
indexPatterns={[model.index_pattern || model.default_index_pattern || '']}
indexPatterns={[model.index_pattern]}
/>
</EuiFormRow>
</EuiFlexItem>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ export class TopNPanelConfig extends Component<
onChange={(filter: PanelConfigProps['model']['filter']) => {
this.props.onChange({ filter });
}}
indexPatterns={[model.index_pattern || model.default_index_pattern || '']}
indexPatterns={[model.index_pattern]}
/>
</EuiFormRow>
</EuiFlexItem>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import React, { useContext, useEffect, useState } from 'react';

import { CoreStartContext } from '../contexts/query_input_bar_context';
import { DefaultIndexPatternContext } from '../contexts/default_index_context';
import { IndexPatternValue } from '../../../common/types';

import { QueryStringInput, QueryStringInputProps } from '../../../../../plugins/data/public';
Expand All @@ -24,27 +25,32 @@ export function QueryBarWrapper({ query, onChange, indexPatterns }: QueryBarWrap
const [indexes, setIndexes] = useState<QueryStringInputProps['indexPatterns']>([]);

const coreStartContext = useContext(CoreStartContext);
const defaultIndex = useContext(DefaultIndexPatternContext);

useEffect(() => {
async function fetchIndexes() {
const i: QueryStringInputProps['indexPatterns'] = [];

for (const index of indexPatterns ?? []) {
if (isStringTypeIndexPattern(index)) {
i.push(index);
} else if (index?.id) {
const fetchedIndex = await fetchIndexPattern(index, indexPatternsService);

if (fetchedIndex.indexPattern) {
i.push(fetchedIndex.indexPattern);
if (index) {
if (isStringTypeIndexPattern(index)) {
i.push(index);
} else if (index?.id) {
const { indexPattern } = await fetchIndexPattern(index, indexPatternsService);

if (indexPattern) {
i.push(indexPattern);
}
}
} else if (defaultIndex) {
i.push(defaultIndex);
}
}
setIndexes(i);
}

fetchIndexes();
}, [indexPatterns, indexPatternsService]);
}, [indexPatterns, indexPatternsService, defaultIndex]);

return (
<QueryStringInput
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ export class Series extends Component {
togglePanelActivation={this.togglePanelActivation}
visible={this.state.visible}
dragHandleProps={this.props.dragHandleProps}
indexPatternForQuery={panel.index_pattern || panel.default_index_pattern}
indexPatternForQuery={panel.index_pattern}
/>
);
}}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,17 +12,19 @@ import { share } from 'rxjs/operators';
import { isEqual, isEmpty, debounce } from 'lodash';
import { EventEmitter } from 'events';

import { IUiSettingsClient } from 'kibana/public';
import { TimeRange } from 'src/plugins/data/public';
import type { IUiSettingsClient } from 'kibana/public';
import {
Vis,
PersistedState,
VisualizeEmbeddableContract,
} from 'src/plugins/visualizations/public';
import { IndexPatternValue, TimeseriesVisData } from 'src/plugins/vis_type_timeseries/common/types';
} from '../../../../../plugins/visualizations/public';
import { KibanaContextProvider } from '../../../../../plugins/kibana_react/public';
import { DefaultIndexPatternContext } from '../contexts/default_index_context';
import { Storage } from '../../../../../plugins/kibana_utils/public';

import type { IIndexPattern, TimeRange } from '../../../../../plugins/data/public';
import type { IndexPatternValue, TimeseriesVisData } from '../../../common/types';

// @ts-expect-error
import { VisEditorVisualization } from './vis_editor_visualization';
import { PanelConfig } from './panel_config';
Expand All @@ -48,6 +50,7 @@ export interface TimeseriesEditorProps {
interface TimeseriesEditorState {
autoApply: boolean;
dirty: boolean;
defaultIndex: IIndexPattern | null;
extractedIndexPatterns: IndexPatternValue[];
model: TimeseriesVisParams;
visFields?: VisFields;
Expand All @@ -65,6 +68,7 @@ export class VisEditor extends Component<TimeseriesEditorProps, TimeseriesEditor
this.state = {
autoApply: true,
dirty: false,
defaultIndex: null,
model: {
// we should set default value for 'time_range_mode' in model so that when user save visualization
// we set right mode in savedObject
Expand Down Expand Up @@ -96,7 +100,7 @@ export class VisEditor extends Component<TimeseriesEditorProps, TimeseriesEditor

const extractedIndexPatterns = extractIndexPatternValues(
this.state.model,
this.state.model.default_index_pattern
this.state.defaultIndex
);
if (!isEqual(this.state.extractedIndexPatterns, extractedIndexPatterns)) {
this.abortableFetchFields(extractedIndexPatterns).then((visFields) => {
Expand Down Expand Up @@ -175,35 +179,37 @@ export class VisEditor extends Component<TimeseriesEditorProps, TimeseriesEditor
...getCoreStart(),
}}
>
<div className="tvbEditor" data-test-subj="tvbVisEditor">
<div className="tvbEditor--hideForReporting">
<VisPicker currentVisType={model.type} onChange={this.handleChange} />
</div>
<VisEditorVisualization
dirty={this.state.dirty}
autoApply={this.state.autoApply}
model={model}
embeddableHandler={this.props.embeddableHandler}
eventEmitter={this.props.eventEmitter}
vis={this.props.vis}
timeRange={this.props.timeRange}
uiState={this.props.uiState}
onCommit={this.handleCommit}
onToggleAutoApply={this.handleAutoApplyToggle}
title={this.props.vis.title}
description={this.props.vis.description}
onDataChange={this.onDataChange}
/>
<div className="tvbEditor--hideForReporting">
<PanelConfig
fields={visFields}
<DefaultIndexPatternContext.Provider value={this.state.defaultIndex}>
<div className="tvbEditor" data-test-subj="tvbVisEditor">
<div className="tvbEditor--hideForReporting">
<VisPicker currentVisType={model.type} onChange={this.handleChange} />
</div>
<VisEditorVisualization
dirty={this.state.dirty}
autoApply={this.state.autoApply}
model={model}
visData$={this.visData$}
onChange={this.handleChange}
getConfig={this.getConfig}
embeddableHandler={this.props.embeddableHandler}
eventEmitter={this.props.eventEmitter}
vis={this.props.vis}
timeRange={this.props.timeRange}
uiState={this.props.uiState}
onCommit={this.handleCommit}
onToggleAutoApply={this.handleAutoApplyToggle}
title={this.props.vis.title}
description={this.props.vis.description}
onDataChange={this.onDataChange}
/>
<div className="tvbEditor--hideForReporting">
<PanelConfig
fields={visFields}
model={model}
visData$={this.visData$}
onChange={this.handleChange}
getConfig={this.getConfig}
/>
</div>
</div>
</div>
</DefaultIndexPatternContext.Provider>
</KibanaContextProvider>
);
}
Expand All @@ -212,24 +218,13 @@ export class VisEditor extends Component<TimeseriesEditorProps, TimeseriesEditor
const dataStart = getDataStart();

dataStart.indexPatterns.getDefault().then(async (index) => {
const defaultIndexTitle = index?.title ?? '';
const indexPatterns = extractIndexPatternValues(this.props.vis.params, defaultIndexTitle);
const indexPatterns = extractIndexPatternValues(this.props.vis.params, index);
const visFields = await fetchFields(indexPatterns);

this.setState((state) => ({
model: {
...state.model,
/** @legacy
* please use IndexPatterns service instead
* **/
default_index_pattern: defaultIndexTitle,
/** @legacy
* please use IndexPatterns service instead
* **/
default_timefield: index?.timeFieldName ?? '',
},
this.setState({
defaultIndex: index,
visFields,
}));
});
});

this.props.eventEmitter.on('updateEditor', this.updateModel);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/

import React from 'react';
import { IIndexPattern } from '../../../../data/public';

export const DefaultIndexPatternContext = React.createContext<IIndexPattern | null>(null);
Loading

0 comments on commit 0de9e5e

Please sign in to comment.