[DataViews] Remove some usage of any (#135767)

* fix editor warning

* use UrlFormatEditorFormatParams

* remove unnecessary any

* remove any from FieldFormatEditorFactory

* remove usage of any from src/plugins/data_view_field_editor

* remove usage of any from data_views/server/fetcher

* fix ts

* fix more ts

* back off changes in src/plugins/data_views/server/fetcher/

* pretty

* remove some unknown

* pretty

* fix ts

* retain null-ability

* fix lint

* fix test

* cleanup

* fixes in FieldFormatEditorFactory

* cleanup

* fix FieldFormatEditorStart

* revert functional diff

* knock out a few small any

* fix lint

* set up generic FieldFormatParams, SerializedFieldFormat, FormatFactory

* revert comment

* fix mistake

* use FormatEditorServiceSetup, FormatEditorServiceStart

* make defaultFieldFormatEditorFactories more type safe

* simplify types

* type fixes

* roll back re-leveling of fieldFormatEditors

* review feedback item

* public api correction

Co-authored-by: Matt Kime <matt@mattki.me>
Co-authored-by: Kibana Machine <42973632+kibanamachine@users.noreply.github.com>
This commit is contained in:
Tim Sullivan 2022-07-13 08:55:06 -07:00 committed by GitHub
parent dec18895eb
commit ca2d1d6975
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
47 changed files with 218 additions and 180 deletions

View file

@ -41,12 +41,12 @@ const ExampleCurrencyFormatEditor: FieldFormatEditor<{ currency: string }> = (pr
ExampleCurrencyFormatEditor.formatId = ExampleCurrencyFormat.id; ExampleCurrencyFormatEditor.formatId = ExampleCurrencyFormat.id;
// 3. Wrap editor component in a factory. This is needed to support and encourage code-splitting. // 3. Wrap editor component in a factory. This is needed to support and encourage code-splitting.
const ExampleCurrencyFormatEditorFactory: FieldFormatEditorFactory<{ const ExampleCurrencyFormatEditorFactory = async () => ExampleCurrencyFormatEditor;
currency: string;
}> = async () => ExampleCurrencyFormatEditor;
ExampleCurrencyFormatEditorFactory.formatId = ExampleCurrencyFormatEditor.formatId; ExampleCurrencyFormatEditorFactory.formatId = ExampleCurrencyFormatEditor.formatId;
export function registerExampleFormatEditor(indexPatternFieldEditor: IndexPatternFieldEditorSetup) { export function registerExampleFormatEditor(indexPatternFieldEditor: IndexPatternFieldEditorSetup) {
// 4. Register a field editor. This should happen in setup plugin lifecycle phase. // 4. Register a field editor. This should happen in setup plugin lifecycle phase.
indexPatternFieldEditor.fieldFormatEditors.register(ExampleCurrencyFormatEditorFactory); indexPatternFieldEditor.fieldFormatEditors.register(
ExampleCurrencyFormatEditorFactory as FieldFormatEditorFactory
);
} }

View file

@ -9,7 +9,6 @@
import { sortBy } from 'lodash'; import { sortBy } from 'lodash';
import { HttpStart } from '@kbn/core/public'; import { HttpStart } from '@kbn/core/public';
import { i18n } from '@kbn/i18n'; import { i18n } from '@kbn/i18n';
import { IEsSearchResponse } from '@kbn/data-plugin/public';
import { Tag, INDEX_PATTERN_TYPE } from '../types'; import { Tag, INDEX_PATTERN_TYPE } from '../types';
import { MatchedItem, ResolveIndexResponse, ResolveIndexResponseItemIndexAttrs } from '../types'; import { MatchedItem, ResolveIndexResponse, ResolveIndexResponseItemIndexAttrs } from '../types';
@ -41,35 +40,6 @@ const getIndexTags = (isRollupIndex: (indexName: string) => boolean) => (indexNa
] ]
: []; : [];
export const searchResponseToArray =
(getTags: (indexName: string) => Tag[], showAllIndices: boolean) =>
(response: IEsSearchResponse<any>) => {
const { rawResponse } = response;
if (!rawResponse.aggregations) {
return [];
} else {
// @ts-expect-error @elastic/elasticsearch no way to declare a type for aggregation in the search response
return rawResponse.aggregations.indices.buckets
.map((bucket: { key: string }) => {
return bucket.key;
})
.filter((indexName: string) => {
if (showAllIndices) {
return true;
} else {
return !indexName.startsWith('.');
}
})
.map((indexName: string) => {
return {
name: indexName,
tags: getTags(indexName),
item: {},
};
});
}
};
export const getIndicesViaResolve = async ({ export const getIndicesViaResolve = async ({
http, http,
pattern, pattern,

View file

@ -7,8 +7,9 @@
*/ */
import { formatId } from './constants'; import { formatId } from './constants';
import { FieldFormatEditorFactory } from '../types'; import { FieldFormatEditorFactory } from '../types';
import { NumberFormatEditorParams } from '../number/number';
export type { BytesFormatEditor } from './bytes'; export type { BytesFormatEditor } from './bytes';
export const bytesFormatEditorFactory: FieldFormatEditorFactory = () => export const bytesFormatEditorFactory: FieldFormatEditorFactory<NumberFormatEditorParams> = () =>
import('./bytes').then((m) => m.BytesFormatEditor); import('./bytes').then((m) => m.BytesFormatEditor);
bytesFormatEditorFactory.formatId = formatId; bytesFormatEditorFactory.formatId = formatId;

View file

@ -29,7 +29,7 @@ interface IndexedColor extends Color {
index: number; index: number;
} }
interface ColorFormatEditorFormatParams { export interface ColorFormatEditorFormatParams {
colors: Color[]; colors: Color[];
} }
@ -38,8 +38,8 @@ export class ColorFormatEditor extends DefaultFormatEditor<ColorFormatEditorForm
constructor(props: FormatEditorProps<ColorFormatEditorFormatParams>) { constructor(props: FormatEditorProps<ColorFormatEditorFormatParams>) {
super(props); super(props);
this.onChange({ this.onChange({
fieldType: props.fieldType, fieldType: props.fieldType, // FIXME: why add `fieldType` as an EditorFormatParam?
}); } as unknown as ColorFormatEditorFormatParams);
} }
onColorChange = (newColorParams: Partial<Color>, index: number) => { onColorChange = (newColorParams: Partial<Color>, index: number) => {

View file

@ -7,9 +7,11 @@
*/ */
import { FieldFormatEditorFactory } from '../types'; import { FieldFormatEditorFactory } from '../types';
import { ColorFormatEditorFormatParams } from './color';
import { formatId } from './constants'; import { formatId } from './constants';
export type { ColorFormatEditor } from './color'; export type { ColorFormatEditor } from './color';
export const colorFormatEditorFactory: FieldFormatEditorFactory = () => export const colorFormatEditorFactory: FieldFormatEditorFactory<
import('./color').then((m) => m.ColorFormatEditor); ColorFormatEditorFormatParams
> = () => import('./color').then((m) => m.ColorFormatEditor);
colorFormatEditorFactory.formatId = formatId; colorFormatEditorFactory.formatId = formatId;

View file

@ -17,7 +17,7 @@ import { formatId } from './constants';
import { FormatEditorSamples } from '../../samples'; import { FormatEditorSamples } from '../../samples';
interface DateFormatEditorFormatParams { export interface DateFormatEditorFormatParams {
pattern: string; pattern: string;
} }

View file

@ -8,8 +8,9 @@
import { FieldFormatEditorFactory } from '../types'; import { FieldFormatEditorFactory } from '../types';
import { formatId } from './constants'; import { formatId } from './constants';
import { DateFormatEditorFormatParams } from './date';
export type { DateFormatEditor } from './date'; export type { DateFormatEditor } from './date';
export const dateFormatEditorFactory: FieldFormatEditorFactory = () => export const dateFormatEditorFactory: FieldFormatEditorFactory<DateFormatEditorFormatParams> = () =>
import('./date').then((m) => m.DateFormatEditor); import('./date').then((m) => m.DateFormatEditor);
dateFormatEditorFactory.formatId = formatId; dateFormatEditorFactory.formatId = formatId;

View file

@ -16,7 +16,7 @@ import { formatId } from './constants';
import { FormatEditorSamples } from '../../samples'; import { FormatEditorSamples } from '../../samples';
interface DateNanosFormatEditorFormatParams { export interface DateNanosFormatEditorFormatParams {
pattern: string; pattern: string;
} }

View file

@ -8,8 +8,10 @@
import { FieldFormatEditorFactory } from '../types'; import { FieldFormatEditorFactory } from '../types';
import { formatId } from './constants'; import { formatId } from './constants';
import { DateNanosFormatEditorFormatParams } from './date_nanos';
export type { DateNanosFormatEditor } from './date_nanos'; export type { DateNanosFormatEditor } from './date_nanos';
export const dateNanosFormatEditorFactory: FieldFormatEditorFactory = () => export const dateNanosFormatEditorFactory: FieldFormatEditorFactory<
import('./date_nanos').then((m) => m.DateNanosFormatEditor); DateNanosFormatEditorFormatParams
> = () => import('./date_nanos').then((m) => m.DateNanosFormatEditor);
dateNanosFormatEditorFactory.formatId = formatId; dateNanosFormatEditorFactory.formatId = formatId;

View file

@ -6,10 +6,9 @@
* Side Public License, v 1. * Side Public License, v 1.
*/ */
import React, { PureComponent, ReactText } from 'react';
import { i18n } from '@kbn/i18n';
import type { FieldFormatsContentType } from '@kbn/field-formats-plugin/common'; import type { FieldFormatsContentType } from '@kbn/field-formats-plugin/common';
import { i18n } from '@kbn/i18n';
import React, { PureComponent, ReactText } from 'react';
import type { Sample, SampleInput } from '../../types'; import type { Sample, SampleInput } from '../../types';
import type { FormatEditorProps } from '../types'; import type { FormatEditorProps } from '../types';
import { formatId } from './constants'; import { formatId } from './constants';
@ -80,7 +79,7 @@ export class DefaultFormatEditor<P = {}, S = {}> extends PureComponent<
return output; return output;
} }
onChange = (newParams = {}) => { onChange = (newParams = {} as Partial<FormatEditorProps<P>['formatParams']>) => {
const { onChange, formatParams } = this.props; const { onChange, formatParams } = this.props;
onChange({ onChange({

View file

@ -33,8 +33,8 @@ interface OutputFormat {
text: string; text: string;
} }
interface DurationFormatEditorFormatParams { export interface DurationFormatEditorFormatParams {
outputPrecision: number; outputPrecision: number | null;
inputFormat: string; inputFormat: string;
outputFormat: string; outputFormat: string;
showSuffix?: boolean; showSuffix?: boolean;
@ -60,9 +60,11 @@ export class DurationFormatEditor extends DefaultFormatEditor<
const output = super.getDerivedStateFromProps(nextProps, state); const output = super.getDerivedStateFromProps(nextProps, state);
let error = null; let error = null;
const { outputPrecision } = nextProps.formatParams;
if ( if (
!(nextProps.format as DurationFormat).isHuman() && !(nextProps.format as DurationFormat).isHuman() &&
nextProps.formatParams.outputPrecision > 20 outputPrecision != null &&
outputPrecision > 20
) { ) {
error = i18n.translate('indexPatternFieldEditor.durationErrorMessage', { error = i18n.translate('indexPatternFieldEditor.durationErrorMessage', {
defaultMessage: 'Decimal places must be between 0 and 20', defaultMessage: 'Decimal places must be between 0 and 20',
@ -156,7 +158,7 @@ export class DurationFormatEditor extends DefaultFormatEditor<
error={hasDecimalError ? error : null} error={hasDecimalError ? error : null}
> >
<EuiFieldNumber <EuiFieldNumber
value={formatParams.outputPrecision} value={formatParams.outputPrecision ?? undefined}
min={0} min={0}
max={20} max={20}
onChange={(e) => { onChange={(e) => {

View file

@ -8,8 +8,10 @@
import { FieldFormatEditorFactory } from '../types'; import { FieldFormatEditorFactory } from '../types';
import { formatId } from './constants'; import { formatId } from './constants';
import { DurationFormatEditorFormatParams } from './duration';
export type { DurationFormatEditor } from './duration'; export type { DurationFormatEditor } from './duration';
export const durationFormatEditorFactory: FieldFormatEditorFactory = () => export const durationFormatEditorFactory: FieldFormatEditorFactory<
import('./duration').then((m) => m.DurationFormatEditor); DurationFormatEditorFormatParams
> = () => import('./duration').then((m) => m.DurationFormatEditor);
durationFormatEditorFactory.formatId = formatId; durationFormatEditorFactory.formatId = formatId;

View file

@ -17,7 +17,7 @@ import { DefaultFormatEditor, defaultState } from '../default/default';
import { FormatEditorSamples } from '../../samples'; import { FormatEditorSamples } from '../../samples';
import { formatId } from './constants'; import { formatId } from './constants';
interface GeoPointFormatEditorFormatParams { export interface GeoPointFormatEditorFormatParams {
transform: string; transform: string;
} }

View file

@ -8,8 +8,10 @@
import { FieldFormatEditorFactory } from '../types'; import { FieldFormatEditorFactory } from '../types';
import { formatId } from './constants'; import { formatId } from './constants';
import { GeoPointFormatEditorFormatParams } from './geo_point';
export type { GeoPointFormatEditor } from './geo_point'; export type { GeoPointFormatEditor } from './geo_point';
export const geoPointFormatEditorFactory: FieldFormatEditorFactory = () => export const geoPointFormatEditorFactory: FieldFormatEditorFactory<
import('./geo_point').then((m) => m.GeoPointFormatEditor); GeoPointFormatEditorFormatParams
> = () => import('./geo_point').then((m) => m.GeoPointFormatEditor);
geoPointFormatEditorFactory.formatId = formatId; geoPointFormatEditorFactory.formatId = formatId;

View file

@ -67,7 +67,7 @@ export class HistogramFormatEditor extends DefaultFormatEditor<HistogramFormatEd
options={numberOptions} options={numberOptions}
value={formatParams.id || 'number'} value={formatParams.id || 'number'}
onChange={(e) => { onChange={(e) => {
this.onChange({ id: e.target.value }); this.onChange({ id: e.target.value as HistogramFormatEditorParams['id'] });
}} }}
/> />
</EuiFormRow> </EuiFormRow>

View file

@ -8,8 +8,10 @@
import { FieldFormatEditorFactory } from '../types'; import { FieldFormatEditorFactory } from '../types';
import { formatId } from './constants'; import { formatId } from './constants';
import { HistogramFormatEditorParams } from './histogram';
export type { HistogramFormatEditor } from './histogram'; export type { HistogramFormatEditor } from './histogram';
export const histogramFormatEditorFactory: FieldFormatEditorFactory = () => export const histogramFormatEditorFactory: FieldFormatEditorFactory<
import('./histogram').then((m) => m.HistogramFormatEditor); HistogramFormatEditorParams
> = () => import('./histogram').then((m) => m.HistogramFormatEditor);
histogramFormatEditorFactory.formatId = formatId; histogramFormatEditorFactory.formatId = formatId;

View file

@ -6,20 +6,21 @@
* Side Public License, v 1. * Side Public License, v 1.
*/ */
export type { DefaultFormatEditor } from './default';
export type { FieldFormatEditor, FieldFormatEditorFactory, FormatEditorProps } from './types'; export type { FieldFormatEditor, FieldFormatEditorFactory, FormatEditorProps } from './types';
export type { UrlFormatEditorFormatParams } from './url';
export { DefaultFormatEditor, defaultFormatEditorFactory } from './default';
export { BytesFormatEditor, bytesFormatEditorFactory } from './bytes'; export { BytesFormatEditor, bytesFormatEditorFactory } from './bytes';
export { ColorFormatEditor, colorFormatEditorFactory } from './color'; export { ColorFormatEditor, colorFormatEditorFactory } from './color';
export { DateFormatEditor, dateFormatEditorFactory } from './date'; export { DateFormatEditor, dateFormatEditorFactory } from './date';
export { DateNanosFormatEditor, dateNanosFormatEditorFactory } from './date_nanos'; export { DateNanosFormatEditor, dateNanosFormatEditorFactory } from './date_nanos';
export { defaultFormatEditorFactory } from './default';
export { DurationFormatEditor, durationFormatEditorFactory } from './duration'; export { DurationFormatEditor, durationFormatEditorFactory } from './duration';
export { GeoPointFormatEditor, geoPointFormatEditorFactory } from './geo_point'; export { GeoPointFormatEditor, geoPointFormatEditorFactory } from './geo_point';
export { HistogramFormatEditor, histogramFormatEditorFactory } from './histogram';
export { NumberFormatEditor, numberFormatEditorFactory } from './number'; export { NumberFormatEditor, numberFormatEditorFactory } from './number';
export { PercentFormatEditor, percentFormatEditorFactory } from './percent'; export { PercentFormatEditor, percentFormatEditorFactory } from './percent';
export { StaticLookupFormatEditor, staticLookupFormatEditorFactory } from './static_lookup'; export { StaticLookupFormatEditor, staticLookupFormatEditorFactory } from './static_lookup';
export { StringFormatEditor, stringFormatEditorFactory } from './string'; export { StringFormatEditor, stringFormatEditorFactory } from './string';
export { TruncateFormatEditor, truncateFormatEditorFactory } from './truncate'; export { TruncateFormatEditor, truncateFormatEditorFactory } from './truncate';
export { UrlFormatEditor, urlFormatEditorFactory } from './url'; export { UrlFormatEditor, urlFormatEditorFactory } from './url';
export { HistogramFormatEditor, histogramFormatEditorFactory } from './histogram';

View file

@ -8,8 +8,9 @@
import { FieldFormatEditorFactory } from '../types'; import { FieldFormatEditorFactory } from '../types';
import { formatId } from './constants'; import { formatId } from './constants';
import { NumberFormatEditorParams } from './number';
export type { NumberFormatEditor } from './number'; export type { NumberFormatEditor } from './number';
export const numberFormatEditorFactory: FieldFormatEditorFactory = () => export const numberFormatEditorFactory: FieldFormatEditorFactory<NumberFormatEditorParams> = () =>
import('./number').then((m) => m.NumberFormatEditor); import('./number').then((m) => m.NumberFormatEditor);
numberFormatEditorFactory.formatId = formatId; numberFormatEditorFactory.formatId = formatId;

View file

@ -6,10 +6,11 @@
* Side Public License, v 1. * Side Public License, v 1.
*/ */
import { NumberFormatEditorParams } from '../number/number';
import { FieldFormatEditorFactory } from '../types'; import { FieldFormatEditorFactory } from '../types';
import { formatId } from './constants'; import { formatId } from './constants';
export type { PercentFormatEditor } from './percent'; export type { PercentFormatEditor } from './percent';
export const percentFormatEditorFactory: FieldFormatEditorFactory = () => export const percentFormatEditorFactory: FieldFormatEditorFactory<NumberFormatEditorParams> = () =>
import('./percent').then((m) => m.PercentFormatEditor); import('./percent').then((m) => m.PercentFormatEditor);
percentFormatEditorFactory.formatId = formatId; percentFormatEditorFactory.formatId = formatId;

View file

@ -8,8 +8,10 @@
import { FieldFormatEditorFactory } from '../types'; import { FieldFormatEditorFactory } from '../types';
import { formatId } from './constants'; import { formatId } from './constants';
import { StaticLookupFormatEditorFormatParams } from './static_lookup';
export type { StaticLookupFormatEditor } from './static_lookup'; export type { StaticLookupFormatEditor } from './static_lookup';
export const staticLookupFormatEditorFactory: FieldFormatEditorFactory = () => export const staticLookupFormatEditorFactory: FieldFormatEditorFactory<
import('./static_lookup').then((m) => m.StaticLookupFormatEditor); StaticLookupFormatEditorFormatParams
> = () => import('./static_lookup').then((m) => m.StaticLookupFormatEditor);
staticLookupFormatEditorFactory.formatId = formatId; staticLookupFormatEditorFactory.formatId = formatId;

View file

@ -20,6 +20,11 @@ export interface StaticLookupFormatEditorFormatParams {
unknownKeyValue: string; unknownKeyValue: string;
} }
interface LookupItem {
key: string;
value: string;
}
interface StaticLookupItem { interface StaticLookupItem {
key: string; key: string;
value: string; value: string;
@ -42,7 +47,7 @@ export class StaticLookupFormatEditor extends DefaultFormatEditor<StaticLookupFo
addLookup = () => { addLookup = () => {
const lookupEntries = [...(this.props.formatParams.lookupEntries || [])]; const lookupEntries = [...(this.props.formatParams.lookupEntries || [])];
this.onChange({ this.onChange({
lookupEntries: [...lookupEntries, {}], lookupEntries: [...lookupEntries, {} as LookupItem],
}); });
}; };

View file

@ -8,8 +8,10 @@
import { FieldFormatEditorFactory } from '../types'; import { FieldFormatEditorFactory } from '../types';
import { formatId } from './constants'; import { formatId } from './constants';
import { StringFormatEditorFormatParams } from './string';
export type { StringFormatEditor } from './string'; export type { StringFormatEditor } from './string';
export const stringFormatEditorFactory: FieldFormatEditorFactory = () => export const stringFormatEditorFactory: FieldFormatEditorFactory<
import('./string').then((m) => m.StringFormatEditor); StringFormatEditorFormatParams
> = () => import('./string').then((m) => m.StringFormatEditor);
stringFormatEditorFactory.formatId = formatId; stringFormatEditorFactory.formatId = formatId;

View file

@ -17,7 +17,7 @@ import { DefaultFormatEditor, defaultState } from '../default/default';
import { FormatEditorSamples } from '../../samples'; import { FormatEditorSamples } from '../../samples';
import { formatId } from './constants'; import { formatId } from './constants';
interface StringFormatEditorFormatParams { export interface StringFormatEditorFormatParams {
transform: string; transform: string;
} }

View file

@ -8,8 +8,10 @@
import { formatId } from './constants'; import { formatId } from './constants';
import { FieldFormatEditorFactory } from '../types'; import { FieldFormatEditorFactory } from '../types';
import { TruncateFormatEditorFormatParams } from './truncate';
export type { TruncateFormatEditor } from './truncate'; export type { TruncateFormatEditor } from './truncate';
export const truncateFormatEditorFactory: FieldFormatEditorFactory = () => export const truncateFormatEditorFactory: FieldFormatEditorFactory<
import('./truncate').then((m) => m.TruncateFormatEditor); TruncateFormatEditorFormatParams
> = () => import('./truncate').then((m) => m.TruncateFormatEditor);
truncateFormatEditorFactory.formatId = formatId; truncateFormatEditorFactory.formatId = formatId;

View file

@ -18,8 +18,8 @@ import { FormatEditorSamples } from '../../samples';
import { sample } from './sample'; import { sample } from './sample';
import { formatId } from './constants'; import { formatId } from './constants';
interface TruncateFormatEditorFormatParams { export interface TruncateFormatEditorFormatParams {
fieldLength: number; fieldLength: number | null;
} }
export class TruncateFormatEditor extends DefaultFormatEditor<TruncateFormatEditorFormatParams> { export class TruncateFormatEditor extends DefaultFormatEditor<TruncateFormatEditorFormatParams> {
@ -46,7 +46,7 @@ export class TruncateFormatEditor extends DefaultFormatEditor<TruncateFormatEdit
error={error} error={error}
> >
<EuiFieldNumber <EuiFieldNumber
defaultValue={formatParams.fieldLength} defaultValue={formatParams.fieldLength ?? undefined}
min={1} min={1}
data-test-subj={'truncateEditorLength'} data-test-subj={'truncateEditorLength'}
onChange={(e) => { onChange={(e) => {

View file

@ -6,8 +6,8 @@
* Side Public License, v 1. * Side Public License, v 1.
*/ */
import type { FieldFormat, FieldFormatParams } from '@kbn/field-formats-plugin/common';
import type { ComponentType } from 'react'; import type { ComponentType } from 'react';
import type { FieldFormat } from '@kbn/field-formats-plugin/common';
import type { FormatSelectEditorProps } from '../field_format_editor'; import type { FormatSelectEditorProps } from '../field_format_editor';
/** /**
@ -18,7 +18,7 @@ export interface FormatEditorProps<P> {
fieldType: string; fieldType: string;
format: FieldFormat; format: FieldFormat;
formatParams: { type?: string } & P; formatParams: { type?: string } & P;
onChange: (newParams: { [key: string]: any }) => void; onChange: (newParams: FieldFormatParams) => void;
onError: FormatSelectEditorProps['onError']; onError: FormatSelectEditorProps['onError'];
} }
@ -34,7 +34,7 @@ export type FieldFormatEditor<FormatParams = {}> = ComponentType<
* A factory for registering field format editor for a field format with `formatId` * A factory for registering field format editor for a field format with `formatId`
* @public * @public
*/ */
export type FieldFormatEditorFactory<FormatParams = any> = (() => Promise< export type FieldFormatEditorFactory<FormatParams = {}> = (() => Promise<
FieldFormatEditor<FormatParams> FieldFormatEditor<FormatParams>
>) & { >) & {
formatId: string; formatId: string;

View file

@ -7,9 +7,10 @@
*/ */
import { formatId } from './constants'; import { formatId } from './constants';
import { FieldFormatEditorFactory } from '../types'; import { FieldFormatEditorFactory } from '../types';
import { UrlFormatEditorFormatParams } from './url';
export type { UrlFormatEditor } from './url'; export type { UrlFormatEditor, UrlFormatEditorFormatParams } from './url';
export const urlFormatEditorFactory: FieldFormatEditorFactory = () => export const urlFormatEditorFactory: FieldFormatEditorFactory<UrlFormatEditorFormatParams> = () =>
import('./url').then((m) => m.UrlFormatEditor); import('./url').then((m) => m.UrlFormatEditor);
urlFormatEditorFactory.formatId = formatId; urlFormatEditorFactory.formatId = formatId;

View file

@ -9,11 +9,12 @@
import React from 'react'; import React from 'react';
import type { FieldFormat } from '@kbn/field-formats-plugin/common'; import type { FieldFormat } from '@kbn/field-formats-plugin/common';
import { __IntlProvider as IntlProvider } from '@kbn/i18n-react'; import { __IntlProvider as IntlProvider } from '@kbn/i18n-react';
import { UrlFormatEditor } from './url'; import { UrlFormatEditor, UrlFormatEditorFormatParams } from './url';
import { coreMock } from '@kbn/core/public/mocks'; import { coreMock } from '@kbn/core/public/mocks';
import { createKibanaReactContext } from '@kbn/kibana-react-plugin/public'; import { createKibanaReactContext } from '@kbn/kibana-react-plugin/public';
import { render } from '@testing-library/react'; import { render } from '@testing-library/react';
import userEvent from '@testing-library/user-event'; import userEvent from '@testing-library/user-event';
import { Serializable } from '@kbn/utility-types';
const fieldType = 'string'; const fieldType = 'string';
const format = { const format = {
@ -28,7 +29,7 @@ const format = {
], ],
}, },
} as unknown as FieldFormat; } as unknown as FieldFormat;
const formatParams = { const formatParams: UrlFormatEditorFormatParams = {
openLinkInCurrentTab: true, openLinkInCurrentTab: true,
urlTemplate: '', urlTemplate: '',
labelTemplate: '', labelTemplate: '',
@ -85,7 +86,7 @@ describe('UrlFormatEditor', () => {
}); });
it('should append base path to preview images', async () => { it('should append base path to preview images', async () => {
let sampleImageUrlTemplate = ''; let sampleImageUrlTemplate: Serializable = '';
const { getByLabelText } = renderWithContext( const { getByLabelText } = renderWithContext(
<UrlFormatEditor <UrlFormatEditor
fieldType={fieldType} fieldType={fieldType}

View file

@ -6,26 +6,22 @@
* Side Public License, v 1. * Side Public License, v 1.
*/ */
import React, { Fragment } from 'react';
import { import {
EuiFieldNumber,
EuiFieldText, EuiFieldText,
EuiFormRow, EuiFormRow,
EuiLink, EuiLink,
EuiSelect, EuiSelect,
EuiSwitch, EuiSwitch,
EuiFieldNumber,
} from '@elastic/eui'; } from '@elastic/eui';
import { UrlFormat } from '@kbn/field-formats-plugin/common';
import { FormattedMessage } from '@kbn/i18n-react'; import { FormattedMessage } from '@kbn/i18n-react';
import { context as contextType } from '@kbn/kibana-react-plugin/public'; import { context as contextType } from '@kbn/kibana-react-plugin/public';
import { UrlFormat } from '@kbn/field-formats-plugin/common'; import React, { Fragment } from 'react';
import { DefaultFormatEditor } from '../default/default';
import { FormatEditorSamples } from '../../samples'; import { FormatEditorSamples } from '../../samples';
import { formatId } from './constants'; import { DefaultFormatEditor } from '../default/default';
import { FormatEditorProps } from '../types'; import { FormatEditorProps } from '../types';
import { formatId } from './constants';
interface OnChangeParam { interface OnChangeParam {
type: string; type: string;
@ -34,12 +30,13 @@ interface OnChangeParam {
urlTemplate?: string; urlTemplate?: string;
} }
interface UrlFormatEditorFormatParams { export interface UrlFormatEditorFormatParams {
openLinkInCurrentTab: boolean; openLinkInCurrentTab: boolean;
urlTemplate: string; urlTemplate: string;
labelTemplate: string; labelTemplate: string;
width: string; width: string;
height: string; height: string;
type?: string;
} }
interface UrlFormatEditorFormatState { interface UrlFormatEditorFormatState {

View file

@ -6,20 +6,19 @@
* Side Public License, v 1. * Side Public License, v 1.
*/ */
import React, { PureComponent } from 'react';
import { EuiCode, EuiFormRow, EuiSelect } from '@elastic/eui'; import { EuiCode, EuiFormRow, EuiSelect } from '@elastic/eui';
import { FormattedMessage } from '@kbn/i18n-react';
import { i18n } from '@kbn/i18n';
import { KBN_FIELD_TYPES, ES_FIELD_TYPES } from '@kbn/data-plugin/public';
import type { FieldFormatInstanceType } from '@kbn/field-formats-plugin/common';
import { CoreStart } from '@kbn/core/public'; import { CoreStart } from '@kbn/core/public';
import { castEsToKbnFieldTypeName } from '@kbn/field-types'; import { ES_FIELD_TYPES, KBN_FIELD_TYPES } from '@kbn/data-plugin/public';
import { FieldFormatsStart } from '@kbn/field-formats-plugin/public';
import { DataView } from '@kbn/data-views-plugin/public'; import { DataView } from '@kbn/data-views-plugin/public';
import { FormatEditor } from './format_editor'; import type { FieldFormatInstanceType, FieldFormatParams } from '@kbn/field-formats-plugin/common';
import { FieldFormatsStart } from '@kbn/field-formats-plugin/public';
import { castEsToKbnFieldTypeName } from '@kbn/field-types';
import { i18n } from '@kbn/i18n';
import { FormattedMessage } from '@kbn/i18n-react';
import React, { PureComponent } from 'react';
import { FormatEditorServiceStart } from '../../service'; import { FormatEditorServiceStart } from '../../service';
import { FieldFormatConfig } from '../../types'; import { FieldFormatConfig } from '../../types';
import { FormatEditor } from './format_editor';
export interface FormatSelectEditorProps { export interface FormatSelectEditorProps {
esTypes: ES_FIELD_TYPES[]; esTypes: ES_FIELD_TYPES[];
@ -40,7 +39,6 @@ interface FieldTypeFormat {
export interface FormatSelectEditorState { export interface FormatSelectEditorState {
fieldTypeFormats: FieldTypeFormat[]; fieldTypeFormats: FieldTypeFormat[];
fieldFormatId?: string; fieldFormatId?: string;
fieldFormatParams?: { [key: string]: unknown };
kbnType: KBN_FIELD_TYPES; kbnType: KBN_FIELD_TYPES;
} }
@ -88,7 +86,7 @@ export class FormatSelectEditor extends PureComponent<
kbnType, kbnType,
}; };
} }
onFormatChange = (formatId: string, params?: any) => onFormatChange = (formatId: string, params?: FieldFormatParams) =>
this.props.onChange( this.props.onChange(
formatId formatId
? { ? {
@ -98,7 +96,7 @@ export class FormatSelectEditor extends PureComponent<
: undefined : undefined
); );
onFormatParamsChange = (newParams: { [key: string]: any }) => { onFormatParamsChange = (newParams: FieldFormatParams) => {
const { fieldFormatId } = this.state; const { fieldFormatId } = this.state;
this.onFormatChange(fieldFormatId as string, newParams); this.onFormatChange(fieldFormatId as string, newParams);
}; };

View file

@ -7,18 +7,19 @@
*/ */
import { EuiDelayRender, EuiLoadingContent } from '@elastic/eui'; import { EuiDelayRender, EuiLoadingContent } from '@elastic/eui';
import type { FieldFormat, FieldFormatParams } from '@kbn/field-formats-plugin/common';
import { memoize } from 'lodash'; import { memoize } from 'lodash';
import React, { PureComponent, LazyExoticComponent } from 'react'; import React, { LazyExoticComponent, PureComponent } from 'react';
import type { FieldFormat } from '@kbn/field-formats-plugin/common'; import { FormatEditorServiceStart } from '../../service';
import { FieldFormatEditorFactory, FieldFormatEditor } from './editors'; import { FieldFormatEditor, FieldFormatEditorFactory } from './editors';
export interface FormatEditorProps { export interface FormatEditorProps {
fieldType: string; fieldType: string;
fieldFormat: FieldFormat; fieldFormat: FieldFormat;
fieldFormatId: string; fieldFormatId: string;
fieldFormatParams: { [key: string]: unknown }; fieldFormatParams: FieldFormatParams;
fieldFormatEditors: any; fieldFormatEditors: FormatEditorServiceStart['fieldFormatEditors'];
onChange: (change: { [key: string]: any }) => void; onChange: (change: FieldFormatParams) => void;
onError: (error?: string) => void; onError: (error?: string) => void;
} }
@ -39,13 +40,15 @@ export class FormatEditor extends PureComponent<FormatEditorProps, FormatEditorS
constructor(props: FormatEditorProps) { constructor(props: FormatEditorProps) {
super(props); super(props);
this.state = { this.state = {
EditorComponent: unwrapEditor(props.fieldFormatEditors.getById(props.fieldFormatId)), EditorComponent: unwrapEditor(props.fieldFormatEditors.getById(props.fieldFormatId) ?? null),
}; };
} }
static getDerivedStateFromProps(nextProps: FormatEditorProps) { static getDerivedStateFromProps(nextProps: FormatEditorProps) {
return { return {
EditorComponent: unwrapEditor(nextProps.fieldFormatEditors.getById(nextProps.fieldFormatId)), EditorComponent: unwrapEditor(
nextProps.fieldFormatEditors.getById(nextProps.fieldFormatId) ?? null
),
}; };
} }

View file

@ -32,5 +32,6 @@ export function plugin() {
} }
// Expose types // Expose types
export type { FormatEditorServiceStart } from './service';
export type { OpenFieldEditorOptions } from './open_editor'; export type { OpenFieldEditorOptions } from './open_editor';
export type { OpenFieldDeleteModalOptions } from './open_delete_modal'; export type { OpenFieldDeleteModalOptions } from './open_delete_modal';

View file

@ -20,7 +20,7 @@ export const initApi = (httpClient: HttpSetup) => {
index: string; index: string;
context: PainlessExecuteContext; context: PainlessExecuteContext;
script: { source: string } | null; script: { source: string } | null;
document: Record<string, any>; document: Record<string, unknown>;
}) => { }) => {
return sendRequest<FieldPreviewResponse>(httpClient, { return sendRequest<FieldPreviewResponse>(httpClient, {
path: `${API_BASE_PATH}/field_preview`, path: `${API_BASE_PATH}/field_preview`,

View file

@ -7,11 +7,14 @@
*/ */
import { FieldFormatEditorFactory } from '../../components/field_format_editor'; import { FieldFormatEditorFactory } from '../../components/field_format_editor';
import { FormatEditorServiceSetup, FormatEditorServiceStart } from '../format_editor_service';
export class FieldFormatEditors { export class FieldFormatEditors {
private editors: FieldFormatEditorFactory[] = []; private editors: FieldFormatEditorFactory[] = [];
public setup(defaultFieldEditors: FieldFormatEditorFactory[] = []) { public setup(
defaultFieldEditors: FieldFormatEditorFactory[] = []
): FormatEditorServiceSetup['fieldFormatEditors'] {
this.editors = defaultFieldEditors; this.editors = defaultFieldEditors;
return { return {
@ -21,11 +24,13 @@ export class FieldFormatEditors {
}; };
} }
public start() { public start(): FormatEditorServiceStart['fieldFormatEditors'] {
return { return {
getAll: () => [...this.editors], getAll: () => [...this.editors],
getById: (id: string) => { getById: <P>(id: string) => {
return this.editors.find((editor) => editor.formatId === id); return this.editors.find((editor) => editor.formatId === id) as
| FieldFormatEditorFactory<P>
| undefined;
}, },
}; };
} }

View file

@ -38,7 +38,7 @@ export class FormatEditorService {
} }
public setup() { public setup() {
const defaultFieldFormatEditorFactories: FieldFormatEditorFactory[] = [ const defaultFieldFormatEditorFactories = [
bytesFormatEditorFactory, bytesFormatEditorFactory,
colorFormatEditorFactory, colorFormatEditorFactory,
dateFormatEditorFactory, dateFormatEditorFactory,
@ -52,7 +52,7 @@ export class FormatEditorService {
truncateFormatEditorFactory, truncateFormatEditorFactory,
urlFormatEditorFactory, urlFormatEditorFactory,
histogramFormatEditorFactory, histogramFormatEditorFactory,
]; ] as FieldFormatEditorFactory[];
const fieldFormatEditorsSetup = this.fieldFormatEditors.setup( const fieldFormatEditorsSetup = this.fieldFormatEditors.setup(
defaultFieldFormatEditorFactories defaultFieldFormatEditorFactories
@ -75,5 +75,16 @@ export class FormatEditorService {
} }
/** @internal */ /** @internal */
export type FormatEditorServiceSetup = ReturnType<FormatEditorService['setup']>; export interface FormatEditorServiceSetup {
export type FormatEditorServiceStart = ReturnType<FormatEditorService['start']>; fieldFormatEditors: {
register: (editor: FieldFormatEditorFactory) => void;
};
}
/** @internal */
export interface FormatEditorServiceStart {
fieldFormatEditors: {
getAll: () => FieldFormatEditorFactory[];
getById: <P>(id: string) => FieldFormatEditorFactory<P> | undefined;
};
}

View file

@ -24,7 +24,7 @@ interface IndexedFieldsTableProps {
deleteField: (fieldName: string) => void; deleteField: (fieldName: string) => void;
getFieldInfo: (indexPattern: DataView, field: DataViewField) => string[]; getFieldInfo: (indexPattern: DataView, field: DataViewField) => string[];
}; };
fieldWildcardMatcher: (filters: any[]) => (val: any) => boolean; fieldWildcardMatcher: (filters: string[] | undefined) => (val: string) => boolean;
userEditPermission: boolean; userEditPermission: boolean;
openModal: OverlayStart['openModal']; openModal: OverlayStart['openModal'];
theme: ThemeServiceStart; theme: ThemeServiceStart;
@ -57,8 +57,7 @@ export class IndexedFieldsTable extends Component<
mapFields(fields: DataViewField[]): IndexedFieldItem[] { mapFields(fields: DataViewField[]): IndexedFieldItem[] {
const { indexPattern, fieldWildcardMatcher, helpers, userEditPermission } = this.props; const { indexPattern, fieldWildcardMatcher, helpers, userEditPermission } = this.props;
const sourceFilters = const sourceFilters =
indexPattern.sourceFilters && indexPattern.sourceFilters && indexPattern.sourceFilters.map((f) => f.value);
indexPattern.sourceFilters.map((f: Record<string, any>) => f.value);
const fieldWildcardMatch = fieldWildcardMatcher(sourceFilters || []); const fieldWildcardMatch = fieldWildcardMatcher(sourceFilters || []);
return ( return (
@ -83,10 +82,11 @@ export class IndexedFieldsTable extends Component<
getFilteredFields = createSelector( getFilteredFields = createSelector(
(state: IndexedFieldsTableState) => state.fields, (state: IndexedFieldsTableState) => state.fields,
(state: IndexedFieldsTableState, props: IndexedFieldsTableProps) => props.fieldFilter, (_state: IndexedFieldsTableState, props: IndexedFieldsTableProps) => props.fieldFilter,
(state: IndexedFieldsTableState, props: IndexedFieldsTableProps) => (_state: IndexedFieldsTableState, props: IndexedFieldsTableProps) =>
props.indexedFieldTypeFilter, props.indexedFieldTypeFilter,
(state: IndexedFieldsTableState, props: IndexedFieldsTableProps) => props.schemaFieldTypeFilter, (_state: IndexedFieldsTableState, props: IndexedFieldsTableProps) =>
props.schemaFieldTypeFilter,
(fields, fieldFilter, indexedFieldTypeFilter, schemaFieldTypeFilter) => { (fields, fieldFilter, indexedFieldTypeFilter, schemaFieldTypeFilter) => {
if (fieldFilter) { if (fieldFilter) {
const normalizedFieldFilter = fieldFilter.toLowerCase(); const normalizedFieldFilter = fieldFilter.toLowerCase();

View file

@ -73,7 +73,7 @@ export interface TableProps {
items: SourceFiltersTableFilter[]; items: SourceFiltersTableFilter[];
deleteFilter: Function; deleteFilter: Function;
fieldWildcardMatcher: Function; fieldWildcardMatcher: Function;
saveFilter: (filter: SourceFiltersTableFilter) => any; saveFilter: (filter: SourceFiltersTableFilter) => void;
isSaving: boolean; isSaving: boolean;
} }
@ -150,7 +150,7 @@ export class Table extends Component<TableProps, TableState> {
]); ]);
const matches = indexPattern const matches = indexPattern
.getNonScriptedFields() .getNonScriptedFields()
.map((currentFilter: any) => currentFilter.name) .map((currentFilter) => currentFilter.name)
.filter(wildcardMatcher) .filter(wildcardMatcher)
.sort(); .sort();

View file

@ -23,7 +23,7 @@ export interface SourceFiltersTableProps {
} }
export interface SourceFiltersTableState { export interface SourceFiltersTableState {
filterToDelete: any; filterToDelete: SourceFiltersTableFilter | undefined;
isDeleteConfirmationModalVisible: boolean; isDeleteConfirmationModalVisible: boolean;
isSaving: boolean; isSaving: boolean;
filters: SourceFiltersTableFilter[]; filters: SourceFiltersTableFilter[];
@ -56,7 +56,7 @@ export class SourceFiltersTable extends Component<
updateFilters = () => { updateFilters = () => {
const sourceFilters = this.props.indexPattern.sourceFilters; const sourceFilters = this.props.indexPattern.sourceFilters;
const filters = (sourceFilters || []).map((sourceFilter: any) => ({ const filters = (sourceFilters || []).map((sourceFilter) => ({
...sourceFilter, ...sourceFilter,
clientId: ++this.clientSideId, clientId: ++this.clientSideId,
})); }));
@ -66,7 +66,7 @@ export class SourceFiltersTable extends Component<
getFilteredFilters = createSelector( getFilteredFilters = createSelector(
(state: SourceFiltersTableState) => state.filters, (state: SourceFiltersTableState) => state.filters,
(state: SourceFiltersTableState, props: SourceFiltersTableProps) => props.filterFilter, (_state: SourceFiltersTableState, props: SourceFiltersTableProps) => props.filterFilter,
(filters, filterFilter) => { (filters, filterFilter) => {
if (filterFilter) { if (filterFilter) {
const filterFilterToLowercase = filterFilter.toLowerCase(); const filterFilterToLowercase = filterFilter.toLowerCase();
@ -98,7 +98,7 @@ export class SourceFiltersTable extends Component<
const { filterToDelete, filters } = this.state; const { filterToDelete, filters } = this.state;
indexPattern.sourceFilters = filters.filter((filter) => { indexPattern.sourceFilters = filters.filter((filter) => {
return filter.clientId !== filterToDelete.clientId; return filter.clientId !== filterToDelete?.clientId;
}); });
this.setState({ isSaving: true }); this.setState({ isSaving: true });

View file

@ -141,7 +141,6 @@ export function Tabs({
saveIndexPattern, saveIndexPattern,
fields, fields,
history, history,
location,
refreshFields, refreshFields,
relationships, relationships,
allowedTypes, allowedTypes,
@ -158,7 +157,10 @@ export function Tabs({
savedObjectsManagement, savedObjectsManagement,
} = useKibana<IndexPatternManagmentContext>().services; } = useKibana<IndexPatternManagmentContext>().services;
const [fieldFilter, setFieldFilter] = useState<string>(''); const [fieldFilter, setFieldFilter] = useState<string>('');
const [syncingStateFunc, setSyncingStateFunc] = useState<any>({ const [syncingStateFunc, setSyncingStateFunc] = useState<{
getCurrentTab: () => string;
setCurrentTab?: (newTab: string) => { tab: string };
}>({
getCurrentTab: () => TAB_INDEXED_FIELDS, getCurrentTab: () => TAB_INDEXED_FIELDS,
}); });
const [scriptedFieldLanguageFilter, setScriptedFieldLanguageFilter] = useState<string[]>([]); const [scriptedFieldLanguageFilter, setScriptedFieldLanguageFilter] = useState<string[]>([]);
@ -260,7 +262,7 @@ export function Tabs({
}, [closeFieldEditor]); }, [closeFieldEditor]);
const fieldWildcardMatcherDecorated = useCallback( const fieldWildcardMatcherDecorated = useCallback(
(filters: string[]) => fieldWildcardMatcher(filters, uiSettings.get(META_FIELDS)), (filters: string[] | undefined) => fieldWildcardMatcher(filters, uiSettings.get(META_FIELDS)),
[uiSettings] [uiSettings]
); );
@ -600,7 +602,7 @@ export function Tabs({
selectedTab={euiTabs.find((tab) => tab.id === selectedTabId)} selectedTab={euiTabs.find((tab) => tab.id === selectedTabId)}
onTabClick={(tab) => { onTabClick={(tab) => {
setSelectedTabId(tab.id); setSelectedTabId(tab.id);
syncingStateFunc.setCurrentTab(tab.id); syncingStateFunc.setCurrentTab?.(tab.id);
}} }}
/> />
); );

View file

@ -6,11 +6,11 @@
* Side Public License, v 1. * Side Public License, v 1.
*/ */
import React, { PureComponent } from 'react'; import { FormatEditorServiceStart } from '@kbn/data-view-field-editor-plugin/public/service';
import { shallow } from 'enzyme';
import { FieldFormatEditor } from './field_format_editor';
import type { FieldFormat } from '@kbn/field-formats-plugin/common'; import type { FieldFormat } from '@kbn/field-formats-plugin/common';
import { shallow } from 'enzyme';
import React, { PureComponent } from 'react';
import { FieldFormatEditor } from './field_format_editor';
class TestEditor extends PureComponent { class TestEditor extends PureComponent {
render() { render() {
@ -21,12 +21,11 @@ class TestEditor extends PureComponent {
} }
} }
const formatEditors = { const formatEditors: FormatEditorServiceStart['fieldFormatEditors'] = {
byFormatId: { getById: jest.fn(
ip: TestEditor, () => () => Promise.resolve(TestEditor)
number: TestEditor, ) as unknown as FormatEditorServiceStart['fieldFormatEditors']['getById'],
}, getAll: jest.fn(),
getById: jest.fn(() => () => Promise.resolve(TestEditor)),
}; };
describe('FieldFormatEditor', () => { describe('FieldFormatEditor', () => {

View file

@ -6,32 +6,35 @@
* Side Public License, v 1. * Side Public License, v 1.
*/ */
import React, { LazyExoticComponent, PureComponent } from 'react';
import { memoize } from 'lodash';
import { EuiDelayRender, EuiLoadingContent } from '@elastic/eui'; import { EuiDelayRender, EuiLoadingContent } from '@elastic/eui';
import type { import type {
FieldFormatEditorFactory,
FieldFormatEditor as InnerFieldFormatEditor, FieldFormatEditor as InnerFieldFormatEditor,
FieldFormatEditorFactory,
} from '@kbn/data-view-field-editor-plugin/public'; } from '@kbn/data-view-field-editor-plugin/public';
import type { FieldFormat } from '@kbn/field-formats-plugin/common'; import { FormatEditorServiceStart } from '@kbn/data-view-field-editor-plugin/public';
import type { FieldFormat, FieldFormatParams } from '@kbn/field-formats-plugin/common';
import { memoize } from 'lodash';
import React, { LazyExoticComponent, PureComponent } from 'react';
export interface FieldFormatEditorProps { export interface FieldFormatEditorProps {
fieldType: string; fieldType: string;
fieldFormat: FieldFormat; fieldFormat: FieldFormat;
fieldFormatId: string; fieldFormatId: string;
fieldFormatParams: { [key: string]: unknown }; fieldFormatParams: FieldFormatParams<{ type?: string }>;
fieldFormatEditors: any; fieldFormatEditors: FormatEditorServiceStart['fieldFormatEditors'];
onChange: (change: { [key: string]: any }) => void; onChange: (change: FieldFormatParams) => void;
onError: (error?: string) => void; onError: (error?: string) => void;
} }
interface FieldFormatEditorState { interface FieldFormatEditorState {
EditorComponent: LazyExoticComponent<InnerFieldFormatEditor> | null; EditorComponent: LazyExoticComponent<InnerFieldFormatEditor<FieldFormatParams>> | null;
} }
// use memoize to get stable reference // use memoize to get stable reference
const unwrapEditor = memoize( const unwrapEditor = memoize(
(editorFactory: FieldFormatEditorFactory | null): FieldFormatEditorState['EditorComponent'] => { (
editorFactory: FieldFormatEditorFactory<FieldFormatParams> | undefined
): FieldFormatEditorState['EditorComponent'] => {
if (!editorFactory) return null; if (!editorFactory) return null;
return React.lazy(() => editorFactory().then((editor) => ({ default: editor }))); return React.lazy(() => editorFactory().then((editor) => ({ default: editor })));
} }

View file

@ -105,7 +105,7 @@ export class TestScript extends Component<TestScriptProps, TestScriptState> {
this.setState({ this.setState({
isLoading: false, isLoading: false,
previewData: scriptResponse.hits?.hits.map((hit: any) => ({ previewData: scriptResponse.hits?.hits.map((hit) => ({
_id: hit._id, _id: hit._id,
...hit._source, ...hit._source,
...hit.fields, ...hit.fields,

View file

@ -33,10 +33,19 @@ import {
import { i18n } from '@kbn/i18n'; import { i18n } from '@kbn/i18n';
import { FormattedMessage } from '@kbn/i18n-react'; import { FormattedMessage } from '@kbn/i18n-react';
import { PainlessLang } from '@kbn/monaco'; import { PainlessLang } from '@kbn/monaco';
import type { FieldFormatInstanceType, FieldFormatParams } from '@kbn/field-formats-plugin/common'; import type {
FieldFormat,
FieldFormatInstanceType,
FieldFormatParams,
} from '@kbn/field-formats-plugin/common';
import type { FieldFormatsStart } from '@kbn/field-formats-plugin/public'; import type { FieldFormatsStart } from '@kbn/field-formats-plugin/public';
import { KBN_FIELD_TYPES, ES_FIELD_TYPES } from '@kbn/field-types'; import { KBN_FIELD_TYPES, ES_FIELD_TYPES } from '@kbn/field-types';
import { DataView, DataViewField, DataViewsPublicPluginStart } from '@kbn/data-views-plugin/public'; import {
DataView,
DataViewField,
DataViewsPublicPluginStart,
FieldSpec,
} from '@kbn/data-views-plugin/public';
import { context as contextType, CodeEditor } from '@kbn/kibana-react-plugin/public'; import { context as contextType, CodeEditor } from '@kbn/kibana-react-plugin/public';
import { import {
getEnabledScriptingLanguages, getEnabledScriptingLanguages,
@ -97,14 +106,14 @@ export interface FieldEditorState {
fieldTypeFormats: FieldTypeFormat[]; fieldTypeFormats: FieldTypeFormat[];
existingFieldNames: string[]; existingFieldNames: string[];
fieldFormatId?: string; fieldFormatId?: string;
fieldFormatParams: FieldFormatParams; fieldFormatParams?: FieldFormatParams;
showScriptingHelp: boolean; showScriptingHelp: boolean;
showDeleteModal: boolean; showDeleteModal: boolean;
hasFormatError: boolean; hasFormatError: boolean;
hasScriptError: boolean; hasScriptError: boolean;
isSaving: boolean; isSaving: boolean;
errors?: string[]; errors?: string[];
format: any; format: FieldFormat;
spec: DataViewField['spec']; spec: DataViewField['spec'];
customLabel: string; customLabel: string;
} }
@ -196,9 +205,9 @@ export class FieldEditor extends PureComponent<FieldEdiorProps, FieldEditorState
}); });
} }
onFieldChange = (fieldName: string, value: string | number) => { onFieldChange = (fieldName: keyof FieldSpec, value: string | number) => {
const { spec } = this.state; const { spec } = this.state;
(spec as any)[fieldName] = value; (spec[fieldName] as string | number) = value;
this.forceUpdate(); this.forceUpdate();
}; };
@ -227,7 +236,7 @@ export class FieldEditor extends PureComponent<FieldEdiorProps, FieldEditorState
}); });
}; };
onFormatChange = (formatId: string, params?: any) => { onFormatChange = (formatId: string, params?: FieldFormatParams) => {
const { fieldTypeFormats } = this.state; const { fieldTypeFormats } = this.state;
const { uiSettings, fieldFormats } = this.context.services; const { uiSettings, fieldFormats } = this.context.services;
@ -244,7 +253,7 @@ export class FieldEditor extends PureComponent<FieldEdiorProps, FieldEditorState
}); });
}; };
onFormatParamsChange = (newParams: { [key: string]: any }) => { onFormatParamsChange = (newParams: FieldFormatParams) => {
const { fieldFormatId } = this.state; const { fieldFormatId } = this.state;
this.onFormatChange(fieldFormatId as string, newParams); this.onFormatChange(fieldFormatId as string, newParams);
}; };

View file

@ -9,6 +9,7 @@
import { ReactText } from 'react'; import { ReactText } from 'react';
import { Query } from '@kbn/es-query'; import { Query } from '@kbn/es-query';
import { HttpStart } from '@kbn/core/public'; import { HttpStart } from '@kbn/core/public';
import { estypes } from '@elastic/elasticsearch';
export type SampleInput = ReactText | ReactText[] | Record<string, ReactText | ReactText[]>; export type SampleInput = ReactText | ReactText[] | Record<string, ReactText | ReactText[]>;
export interface Sample { export interface Sample {
@ -27,8 +28,8 @@ export interface ExecuteScriptParams {
export interface ExecuteScriptResult { export interface ExecuteScriptResult {
status: number; status: number;
hits?: { hits: any[] }; hits?: { hits: Array<estypes.SearchHit<object>> };
error?: any; error?: unknown;
} }
export type ExecuteScript = (params: ExecuteScriptParams) => Promise<ExecuteScriptResult>; export type ExecuteScript = (params: ExecuteScriptParams) => Promise<ExecuteScriptResult>;

View file

@ -6,15 +6,16 @@
* Side Public License, v 1. * Side Public License, v 1.
*/ */
import { estypes } from '@elastic/elasticsearch';
import { schema } from '@kbn/config-schema'; import { schema } from '@kbn/config-schema';
import { import {
IRouter, IRouter,
StartServicesAccessor,
RequestHandler, RequestHandler,
RouteValidatorFullConfig, RouteValidatorFullConfig,
StartServicesAccessor,
} from '@kbn/core/server'; } from '@kbn/core/server';
import type { DataViewsServerPluginStart, DataViewsServerPluginStartDependencies } from '../types';
import { IndexPatternsFetcher } from '../fetcher'; import { IndexPatternsFetcher } from '../fetcher';
import type { DataViewsServerPluginStart, DataViewsServerPluginStartDependencies } from '../types';
const parseMetaFields = (metaFields: string | string[]) => { const parseMetaFields = (metaFields: string | string[]) => {
let parsedFields: string[] = []; let parsedFields: string[] = [];
@ -28,7 +29,7 @@ const parseMetaFields = (metaFields: string | string[]) => {
const path = '/api/index_patterns/_fields_for_wildcard'; const path = '/api/index_patterns/_fields_for_wildcard';
type IBody = { index_filter?: any } | undefined; type IBody = { index_filter?: estypes.QueryDslQueryContainer } | undefined;
interface IQuery { interface IQuery {
pattern: string; pattern: string;
meta_fields: string[]; meta_fields: string[];

View file

@ -9,7 +9,10 @@
import { flow, omit } from 'lodash'; import { flow, omit } from 'lodash';
import { SavedObjectMigrationFn } from '@kbn/core/server'; import { SavedObjectMigrationFn } from '@kbn/core/server';
const migrateAttributeTypeAndAttributeTypeMeta: SavedObjectMigrationFn<any, any> = (doc) => ({ const migrateAttributeTypeAndAttributeTypeMeta: SavedObjectMigrationFn<
{ type?: string; typeMeta?: string },
unknown
> = (doc) => ({
...doc, ...doc,
attributes: { attributes: {
...doc.attributes, ...doc.attributes,
@ -18,11 +21,14 @@ const migrateAttributeTypeAndAttributeTypeMeta: SavedObjectMigrationFn<any, any>
}, },
}); });
const migrateSubTypeAndParentFieldProperties: SavedObjectMigrationFn<any, any> = (doc) => { const migrateSubTypeAndParentFieldProperties: SavedObjectMigrationFn<
{ fields?: string },
unknown
> = (doc) => {
if (!doc.attributes.fields) return doc; if (!doc.attributes.fields) return doc;
const fieldsString = doc.attributes.fields; const fieldsString = doc.attributes.fields;
const fields = JSON.parse(fieldsString) as any[]; const fields = JSON.parse(fieldsString) as Array<{ subType?: string; parent?: string }>;
const migratedFields = fields.map((field) => { const migratedFields = fields.map((field) => {
if (field.subType === 'multi') { if (field.subType === 'multi') {
return { return {
@ -43,7 +49,7 @@ const migrateSubTypeAndParentFieldProperties: SavedObjectMigrationFn<any, any> =
}; };
}; };
const addAllowNoIndex: SavedObjectMigrationFn<any, any> = (doc) => ({ const addAllowNoIndex: SavedObjectMigrationFn<{}, unknown> = (doc) => ({
...doc, ...doc,
attributes: { attributes: {
...doc.attributes, ...doc.attributes,

View file

@ -132,7 +132,7 @@ export type FieldFormatInstanceType = (new (
* TODO: support strict typing for params depending on format type * TODO: support strict typing for params depending on format type
* https://github.com/elastic/kibana/issues/108158 * https://github.com/elastic/kibana/issues/108158
*/ */
export type FieldFormatParams = SerializableRecord; export type FieldFormatParams<P = {}> = SerializableRecord & P;
/** /**
* Params provided by the registry to every field formatter * Params provided by the registry to every field formatter
@ -157,9 +157,12 @@ export type FieldFormatsStartCommon = Omit<FieldFormatsRegistry, 'init' | 'regis
* @public * @public
*/ */
// eslint-disable-next-line @typescript-eslint/consistent-type-definitions // eslint-disable-next-line @typescript-eslint/consistent-type-definitions
export type SerializedFieldFormat<TParams extends FieldFormatParams = FieldFormatParams> = { export type SerializedFieldFormat<
P = {},
TParams extends FieldFormatParams<P> = FieldFormatParams<P>
> = {
id?: string; id?: string;
params?: TParams; params?: TParams;
}; };
export type FormatFactory = (mapping?: SerializedFieldFormat) => IFieldFormat; export type FormatFactory = <P = {}>(mapping?: SerializedFieldFormat<P>) => IFieldFormat;