Skip to content

Commit

Permalink
[Lens] Refactor field select component as shared (#134773)
Browse files Browse the repository at this point in the history
* ♻️ Refactor field select component as shared

* 🚨 Fix linting + types issues

* 🐛 Fix issue with classes

* 🏷️ Fix type issue

Co-authored-by: Joe Reuter <johannes.reuter@elastic.co>
Co-authored-by: Kibana Machine <42973632+kibanamachine@users.noreply.github.com>
  • Loading branch information
3 people authored Jul 7, 2022
1 parent 0060abf commit 05b5c91
Show file tree
Hide file tree
Showing 15 changed files with 222 additions and 118 deletions.
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 @@ -61,8 +61,8 @@ import { FieldInput } from './field_input';
import { NameInput } from '../../shared_components';
import { ParamEditorProps } from '../operations/definitions';
import { WrappingHelpPopover } from '../help_popover';
import { FieldChoice } from './field_select';
import { isColumn } from '../operations/definitions/helpers';
import { FieldChoiceWithOperationType } from './field_select';

export interface DimensionEditorProps extends IndexPatternDimensionEditorProps {
selectedColumn?: GenericIndexPatternColumn;
Expand Down Expand Up @@ -606,7 +606,7 @@ export function DimensionEditor(props: DimensionEditorProps) {
})
);
}}
onChooseField={(choice: FieldChoice) => {
onChooseField={(choice: FieldChoiceWithOperationType) => {
trackUiEvent('indexpattern_dimension_field_changed');
updateLayer(
insertOrReplaceColumn({
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 @@ -104,10 +89,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 @@ -161,92 +142,33 @@ 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:
(selectedOperationType &&
selectedField &&
currentIndexPattern.getFieldByName(selectedField)?.displayName) ??
selectedField,
value: { type: 'field', field: selectedField },
},
]
: []) as unknown as EuiComboBoxOptionOption[]
<FieldPicker<FieldChoiceWithOperationType>
selectedOptions={
(selectedOperationType && selectedField
? [
{
label:
(selectedOperationType &&
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 @@ -25,7 +25,7 @@ import {
IncompleteColumn,
GenericOperationDefinition,
} from '../operations';
import { FieldChoice, FieldSelect } from './field_select';
import { FieldChoiceWithOperationType, FieldSelect } from './field_select';
import { hasField } from '../pure_utils';
import type {
IndexPattern,
Expand Down Expand Up @@ -96,7 +96,7 @@ export interface ReferenceEditorProps {
| ((prevLayer: IndexPatternLayer) => IndexPatternLayer)
| GenericIndexPatternColumn
) => void;
onChooseField: (choice: FieldChoice) => void;
onChooseField: (choice: FieldChoiceWithOperationType) => void;
onDeleteColumn: () => void;
onChooseFunction: (operationType: string, field?: IndexPatternField) => void;

Expand Down
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,136 @@
/*
* 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 }) => {
if (otherAttr.options) {
return {
...otherAttr,
compatible,
exists,
options: otherAttr.options.map((fieldOption) => ({
...fieldOption,
className: classNames({
'lnFieldPicker__option--incompatible': !fieldOption.compatible,
'lnFieldPicker__option--nonExistant': !fieldOption.exists,
}),
})),
};
}
return {
...otherAttr,
compatible,
exists,
className: classNames({
'lnFieldPicker__option--incompatible': !compatible,
'lnFieldPicker__option--nonExistant': !exists,
}),
};
});
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>
);
}
11 changes: 11 additions & 0 deletions x-pack/plugins/lens/public/shared_components/field_picker/index.ts
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';
Loading

0 comments on commit 05b5c91

Please sign in to comment.