Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Lens] Refactor field select component as shared #134773

Merged
merged 11 commits into from
Jul 7, 2022
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ import { trackUiEvent } from '../lens_ui_telemetry';
import { loadIndexPatterns, syncExistingFields } from './loader';
import { fieldExists } from './pure_helpers';
import { Loader } from '../loader';
import { LensFieldIcon } from './lens_field_icon';
import { LensFieldIcon } from '../shared_components/field_picker/lens_field_icon';
import { FieldGroups, FieldList } from './field_list';

export type Props = Omit<DatasourceDataPanelProps<IndexPatternPrivateState>, 'core'> & {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,49 +7,34 @@

import './field_select.scss';
import { partition } from 'lodash';
import React, { useMemo, useRef } from 'react';
import React, { useMemo } from 'react';
import { i18n } from '@kbn/i18n';
import useEffectOnce from 'react-use/lib/useEffectOnce';
import {
EuiComboBox,
EuiFlexGroup,
EuiFlexItem,
EuiComboBoxOptionOption,
EuiComboBoxProps,
} from '@elastic/eui';
import classNames from 'classnames';
import { LensFieldIcon } from '../lens_field_icon';
import { EuiComboBoxOptionOption, EuiComboBoxProps } from '@elastic/eui';
import { trackUiEvent } from '../../lens_ui_telemetry';
import { fieldExists } from '../pure_helpers';
import { TruncatedLabel } from './truncated_label';
import type { OperationType } from '../indexpattern';
import type { DataType } from '../../types';
import type { OperationSupportMatrix } from './operation_support';
import type { IndexPattern, IndexPatternPrivateState } from '../types';
export interface FieldChoice {
type: 'field';
field: string;
import { FieldOption, FieldOptionValue, FieldPicker } from '../../shared_components/field_picker';

export type FieldChoiceWithOperationType = FieldOptionValue & {
operationType: OperationType;
}
};

export interface FieldSelectProps extends EuiComboBoxProps<EuiComboBoxOptionOption['value']> {
currentIndexPattern: IndexPattern;
selectedOperationType?: OperationType;
selectedField?: string;
incompleteOperation?: OperationType;
operationByField: OperationSupportMatrix['operationByField'];
onChoose: (choice: FieldChoice) => void;
onChoose: (choice: FieldChoiceWithOperationType) => void;
onDeleteColumn?: () => void;
existingFields: IndexPatternPrivateState['existingFields'];
fieldIsInvalid: boolean;
markAllFieldsCompatible?: boolean;
'data-test-subj'?: string;
}

const DEFAULT_COMBOBOX_WIDTH = 305;
const COMBOBOX_PADDINGS = 90;
const DEFAULT_FONT = '14px Inter';

export function FieldSelect({
currentIndexPattern,
incompleteOperation,
Expand Down Expand Up @@ -105,10 +90,6 @@ export function FieldSelect({
},
exists,
compatible,
className: classNames({
'lnFieldSelect__option--incompatible': !compatible,
'lnFieldSelect__option--nonExistant': !exists,
}),
'data-test-subj': `lns-fieldOption${compatible ? '' : 'Incompatible'}-${field}`,
};
})
Expand Down Expand Up @@ -162,91 +143,31 @@ export function FieldSelect({
existingFields,
markAllFieldsCompatible,
]);
const comboBoxRef = useRef<HTMLInputElement>(null);
const [labelProps, setLabelProps] = React.useState<{
width: number;
font: string;
}>({
width: DEFAULT_COMBOBOX_WIDTH - COMBOBOX_PADDINGS,
font: DEFAULT_FONT,
});

const computeStyles = (_e: UIEvent | undefined, shouldRecomputeAll = false) => {
if (comboBoxRef.current) {
const current = {
...labelProps,
width: comboBoxRef.current?.clientWidth - COMBOBOX_PADDINGS,
};
if (shouldRecomputeAll) {
current.font = window.getComputedStyle(comboBoxRef.current).font;
}
setLabelProps(current);
}
};

useEffectOnce(() => {
if (comboBoxRef.current) {
computeStyles(undefined, true);
}
window.addEventListener('resize', computeStyles);
});

return (
<div ref={comboBoxRef}>
<EuiComboBox
fullWidth
compressed
isClearable={false}
data-test-subj={dataTestSub ?? 'indexPattern-dimension-field'}
placeholder={i18n.translate('xpack.lens.indexPattern.fieldPlaceholder', {
defaultMessage: 'Field',
})}
options={memoizedFieldOptions as unknown as EuiComboBoxOptionOption[]}
isInvalid={Boolean(incompleteOperation || fieldIsInvalid)}
selectedOptions={
(selectedOperationType && selectedField
? [
{
label: fieldIsInvalid
? selectedField
: currentIndexPattern.getFieldByName(selectedField)?.displayName ??
selectedField,
value: { type: 'field', field: selectedField },
},
]
: []) as unknown as EuiComboBoxOptionOption[]
<FieldPicker<FieldChoiceWithOperationType>
selectedOptions={
(selectedOperationType && selectedField
? [
{
label: fieldIsInvalid
? selectedField
: currentIndexPattern.getFieldByName(selectedField)?.displayName ?? selectedField,
value: { type: 'field', field: selectedField },
},
]
: []) as unknown as Array<FieldOption<FieldChoiceWithOperationType>>
}
options={memoizedFieldOptions as Array<FieldOption<FieldChoiceWithOperationType>>}
onChoose={(choice) => {
if (choice && choice.field !== selectedField) {
trackUiEvent('indexpattern_dimension_field_changed');
onChoose(choice);
}
singleSelection={{ asPlainText: true }}
onChange={(choices) => {
if (choices.length === 0) {
onDeleteColumn?.();
return;
}

const choice = choices[0].value as unknown as FieldChoice;

if (choice.field !== selectedField) {
trackUiEvent('indexpattern_dimension_field_changed');
onChoose(choice);
}
}}
renderOption={(option, searchValue) => {
return (
<EuiFlexGroup gutterSize="s" alignItems="center" responsive={false}>
<EuiFlexItem grow={null}>
<LensFieldIcon
type={(option.value as unknown as { dataType: DataType }).dataType}
fill="none"
/>
</EuiFlexItem>
<EuiFlexItem>
<TruncatedLabel {...labelProps} label={option.label} search={searchValue} />
</EuiFlexItem>
</EuiFlexGroup>
);
}}
{...rest}
/>
</div>
}}
onDelete={onDeleteColumn}
fieldIsInvalid={Boolean(incompleteOperation || fieldIsInvalid)}
data-test-subj={dataTestSub ?? 'indexPattern-dimension-field'}
/>
);
}
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ import { DragDrop, DragDropIdentifier } from '../drag_drop';
import { DatasourceDataPanelProps, DataType } from '../types';
import { BucketedAggregation, DOCUMENT_FIELD_NAME, FieldStatsResponse } from '../../common';
import { IndexPattern, IndexPatternField, DraggedField } from './types';
import { LensFieldIcon } from './lens_field_icon';
import { LensFieldIcon } from '../shared_components/field_picker/lens_field_icon';
import { trackUiEvent } from '../lens_ui_telemetry';
import { VisualizeGeoFieldButton } from './visualize_geo_field_button';
import { getVisualizeGeoFieldMessage } from '../utils';
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
.lnFieldPicker__option--incompatible {
color: $euiColorLightShade;
}

.lnFieldPicker__option--nonExistant {
background-color: $euiColorLightestShade;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
/*
* 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; you may not use this file except in compliance with the Elastic License
* 2.0.
*/

import './field_picker.scss';
import React, { useRef } from 'react';
import { i18n } from '@kbn/i18n';
import useEffectOnce from 'react-use/lib/useEffectOnce';
import { EuiComboBox, EuiComboBoxProps, EuiFlexGroup, EuiFlexItem } from '@elastic/eui';
import classNames from 'classnames';
import { DataType } from '../../types';
import { LensFieldIcon } from './lens_field_icon';
import { TruncatedLabel } from './truncated_label';
import type { FieldOptionValue, FieldOption } from './types';

export interface FieldPickerProps<T extends FieldOptionValue>
extends EuiComboBoxProps<FieldOption<T>['value']> {
options: Array<FieldOption<T>>;
selectedField?: string;
onChoose: (choice: T | undefined) => void;
onDelete?: () => void;
fieldIsInvalid: boolean;
'data-test-subj'?: string;
}

const DEFAULT_COMBOBOX_WIDTH = 305;
const COMBOBOX_PADDINGS = 90;
const DEFAULT_FONT = '14px Inter';

export function FieldPicker<T extends FieldOptionValue>({
selectedOptions,
options,
onChoose,
onDelete,
fieldIsInvalid,
['data-test-subj']: dataTestSub,
...rest
}: FieldPickerProps<T>) {
const styledOptions = options?.map(({ compatible, exists, ...otherAttr }) => ({
...otherAttr,
compatible,
exists,
className: classNames({
'lnFieldPicker__option--incompatible': !compatible,
'lnFieldPicker__option--nonExistant': !exists,
Copy link
Contributor

@MichaelMarcialis MichaelMarcialis Jun 24, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Are these classes being applied in the appropriate circumstances? When running locally, I noticed that some items in the field selector weren't being given these classes and accompanying color styling that they would have been given previously.

For example, in the screenshot below, I'd expect @timestamp and agent.keyword fields to be given the incompatible treatment (as the "Median" function was selected).

image

}),
}));
const comboBoxRef = useRef<HTMLInputElement>(null);
const [labelProps, setLabelProps] = React.useState<{
width: number;
font: string;
}>({
width: DEFAULT_COMBOBOX_WIDTH - COMBOBOX_PADDINGS,
font: DEFAULT_FONT,
});

const computeStyles = (_e: UIEvent | undefined, shouldRecomputeAll = false) => {
if (comboBoxRef.current) {
const current = {
...labelProps,
width: comboBoxRef.current?.clientWidth - COMBOBOX_PADDINGS,
};
if (shouldRecomputeAll) {
current.font = window.getComputedStyle(comboBoxRef.current).font;
}
setLabelProps(current);
}
};

useEffectOnce(() => {
if (comboBoxRef.current) {
computeStyles(undefined, true);
}
window.addEventListener('resize', computeStyles);
});

return (
<div ref={comboBoxRef}>
<EuiComboBox
fullWidth
compressed
isClearable={false}
data-test-subj={dataTestSub ?? 'indexPattern-dimension-field'}
placeholder={i18n.translate('xpack.lens.fieldPicker.fieldPlaceholder', {
defaultMessage: 'Field',
})}
options={styledOptions}
isInvalid={fieldIsInvalid}
selectedOptions={selectedOptions}
singleSelection={{ asPlainText: true }}
onChange={(choices) => {
if (choices.length === 0) {
onDelete?.();
return;
}
onChoose(choices[0].value);
}}
renderOption={(option, searchValue) => {
return (
<EuiFlexGroup gutterSize="s" alignItems="center" responsive={false}>
<EuiFlexItem grow={null}>
<LensFieldIcon
type={(option.value as unknown as { dataType: DataType }).dataType}
fill="none"
/>
</EuiFlexItem>
<EuiFlexItem>
<TruncatedLabel {...labelProps} label={option.label} search={searchValue} />
</EuiFlexItem>
</EuiFlexGroup>
);
}}
{...rest}
/>
</div>
);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
/*
* 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; you may not use this file except in compliance with the Elastic License
* 2.0.
*/

export { LensFieldIcon } from './lens_field_icon';
export { FieldPicker } from './field_picker';
export { TruncatedLabel } from './truncated_label';
export type { FieldOptionValue, FieldOption } from './types';
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@

import React from 'react';
import { FieldIcon, FieldIconProps } from '@kbn/react-field';
import { DataType } from '../types';
import { normalizeOperationDataType } from './pure_utils';
import { DataType } from '../../types';
import { normalizeOperationDataType } from '../../indexpattern_datasource/pure_utils';

export function LensFieldIcon({ type, ...rest }: FieldIconProps & { type: DataType }) {
return (
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
/*
* 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; you may not use this file except in compliance with the Elastic License
* 2.0.
*/
import type { EuiComboBoxOptionOption } from '@elastic/eui';
import type { DataType } from '../../types';

export interface FieldOptionValue {
type: 'field';
field: string;
dataType?: DataType;
}

export interface FieldOption<T extends FieldOptionValue> extends EuiComboBoxOptionOption<T> {
label: string;
value: T;
exists: boolean;
compatible: number | boolean;
'data-test-subj'?: string;
}
2 changes: 2 additions & 0 deletions x-pack/plugins/lens/public/shared_components/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ export type { ToolbarPopoverProps } from './toolbar_popover';
export { ToolbarPopover } from './toolbar_popover';
export { LegendSettingsPopover } from './legend_settings_popover';
export { PalettePicker } from './palette_picker';
export { FieldPicker, LensFieldIcon, TruncatedLabel } from './field_picker';
export type { FieldOption, FieldOptionValue } from './field_picker';
export { RangeInputField } from './range_input_field';
export {
BucketAxisBoundsControl,
Expand Down