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

[Controls] Options List Redux & Selection Management #115122

Merged
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,16 @@

import { ControlsService } from '../controls_service';
import { InputControlFactory } from '../../../services/controls';
import { flightFields, getEuiSelectableOptions } from './flights';
import { flightFields, getFlightSearchOptions } from './flights';
import { OptionsListEmbeddableFactory } from '../control_types/options_list';

export const getControlsServiceStub = () => {
const controlsServiceStub = new ControlsService();

const optionsListFactoryStub = new OptionsListEmbeddableFactory(
({ field, search }) =>
new Promise((r) => setTimeout(() => r(getEuiSelectableOptions(field, search)), 500)),
() => Promise.resolve(['demo data flights']),
new Promise((r) => setTimeout(() => r(getFlightSearchOptions(field.name, search)), 120)),
() => Promise.resolve([{ title: 'demo data flights', fields: [] }]),
() => Promise.resolve(flightFields)
);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,22 +7,17 @@
*/

import { map, uniq } from 'lodash';
import { EuiSelectableOption } from '@elastic/eui';

import { flights } from '../../fixtures/flights';

export type Flight = typeof flights[number];
export type FlightField = keyof Flight;

export const getOptions = (field: string) => uniq(map(flights, field)).sort();
export const getFlightOptions = (field: string) => uniq(map(flights, field)).sort();

export const getEuiSelectableOptions = (field: string, search?: string): EuiSelectableOption[] => {
const options = getOptions(field)
.map((option) => ({
label: option + '',
searchableLabel: option + '',
}))
.filter((option) => !search || option.label.toLowerCase().includes(search.toLowerCase()));
export const getFlightSearchOptions = (field: string, search?: string): string[] => {
const options = getFlightOptions(field)
.map((option) => option + '')
.filter((option) => !search || option.toLowerCase().includes(search.toLowerCase()));
if (options.length > 10) options.length = 10;
return options;
};
Expand Down Expand Up @@ -57,4 +52,8 @@ export const flightFieldLabels: Record<FlightField, string> = {
timestamp: 'Timestamp',
};

export const flightFields = Object.keys(flightFieldLabels) as FlightField[];
export const flightFields = Object.keys(flightFieldLabels).map((field) => ({
name: field,
type: 'string',
aggregatable: true,
}));
Original file line number Diff line number Diff line change
Expand Up @@ -64,9 +64,15 @@ export const ConfiguredControlGroupStory = () => (
explicitInput: {
title: 'Origin City',
id: 'optionsList1',
indexPattern: 'demo data flights',
field: 'OriginCityName',
defaultSelections: ['Toronto'],
indexPattern: {
title: 'demo data flights',
},
field: {
name: 'OriginCityName',
type: 'string',
aggregatable: true,
},
selectedOptions: ['Toronto'],
} as OptionsListEmbeddableInput,
},
optionsList2: {
Expand All @@ -76,9 +82,15 @@ export const ConfiguredControlGroupStory = () => (
explicitInput: {
title: 'Destination City',
id: 'optionsList2',
indexPattern: 'demo data flights',
field: 'DestCityName',
defaultSelections: ['London'],
indexPattern: {
title: 'demo data flights',
},
field: {
name: 'DestCityName',
type: 'string',
aggregatable: true,
},
selectedOptions: ['London'],
} as OptionsListEmbeddableInput,
},
optionsList3: {
Expand All @@ -88,8 +100,14 @@ export const ConfiguredControlGroupStory = () => (
explicitInput: {
title: 'Carrier',
id: 'optionsList3',
indexPattern: 'demo data flights',
field: 'Carrier',
indexPattern: {
title: 'demo data flights',
},
field: {
name: 'Carrier',
type: 'string',
aggregatable: true,
},
} as OptionsListEmbeddableInput,
},
}}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
* Side Public License, v 1.
*/

import { flightFields, getEuiSelectableOptions } from './flights';
import { flightFields, getFlightSearchOptions } from './flights';
import { OptionsListEmbeddableFactory } from '../control_types/options_list';
import { InputControlFactory, PresentationControlsService } from '../../../services/controls';

Expand All @@ -15,8 +15,14 @@ export const populateStorybookControlFactories = (
) => {
const optionsListFactoryStub = new OptionsListEmbeddableFactory(
({ field, search }) =>
new Promise((r) => setTimeout(() => r(getEuiSelectableOptions(field, search)), 500)),
() => Promise.resolve(['demo data flights']),
new Promise((r) => setTimeout(() => r(getFlightSearchOptions(field.name, search)), 120)),
() =>
Promise.resolve([
{
title: 'demo data flights',
fields: [],
},
]),
() => Promise.resolve(flightFields)
);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import { EditControlButton } from '../editor/edit_control';
import { useChildEmbeddable } from '../../hooks/use_child_embeddable';
import { useReduxContainerContext } from '../../../redux_embeddables/redux_embeddable_context';
import { ControlGroupStrings } from '../control_group_strings';
import { pluginServices } from '../../../../services';

export interface ControlFrameProps {
customPrepend?: JSX.Element;
Expand All @@ -36,6 +37,10 @@ export const ControlFrame = ({ customPrepend, enableActions, embeddableId }: Con
} = useReduxContainerContext<ControlGroupInput>();
const { controlStyle } = useEmbeddableSelector((state) => state);

// Presentation Services Context
const { overlays } = pluginServices.getHooks();
const { openConfirm } = overlays.useService();

const embeddable = useChildEmbeddable({ untilEmbeddableLoaded, embeddableId });

const [title, setTitle] = useState<string>();
Expand Down Expand Up @@ -63,7 +68,18 @@ export const ControlFrame = ({ customPrepend, enableActions, embeddableId }: Con
<EuiToolTip content={ControlGroupStrings.floatingActions.getRemoveButtonTitle()}>
<EuiButtonIcon
aria-label={ControlGroupStrings.floatingActions.getRemoveButtonTitle()}
onClick={() => removeEmbeddable(embeddableId)}
onClick={() =>
openConfirm(ControlGroupStrings.management.deleteControls.getSubtitle(), {
confirmButtonText: ControlGroupStrings.management.deleteControls.getConfirm(),
cancelButtonText: ControlGroupStrings.management.deleteControls.getCancel(),
title: ControlGroupStrings.management.deleteControls.getDeleteTitle(),
buttonColor: 'danger',
}).then((confirmed) => {
if (confirmed) {
removeEmbeddable(embeddableId);
}
})
}
iconType="cross"
color="danger"
/>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import { ControlGroupStrings } from '../control_group_strings';
import { controlGroupReducers } from '../state/control_group_reducers';
import { EmbeddableFactoryNotFoundError } from '../../../../../../embeddable/public';
import { useReduxContainerContext } from '../../../redux_embeddables/redux_embeddable_context';
import { InputControlInput } from '../../../../services/controls';

export const EditControlButton = ({ embeddableId }: { embeddableId: string }) => {
// Presentation Services Context
Expand Down Expand Up @@ -54,13 +55,18 @@ export const EditControlButton = ({ embeddableId }: { embeddableId: string }) =>
const factory = getControlFactory(panel.type);
const embeddable = await untilEmbeddableLoaded(embeddableId);

let inputToReturn: Partial<InputControlInput> = {};

if (!factory) throw new EmbeddableFactoryNotFoundError(panel.type);

let removed = false;
const onCancel = (ref: OverlayRef) => {
if (
removed ||
(isEqual(latestPanelState.current.explicitInput, panel.explicitInput) &&
(isEqual(latestPanelState.current.explicitInput, {
...panel.explicitInput,
...inputToReturn,
}) &&
isEqual(latestPanelState.current.width, panel.width))
) {
ref.close();
Expand All @@ -73,7 +79,6 @@ export const EditControlButton = ({ embeddableId }: { embeddableId: string }) =>
buttonColor: 'danger',
}).then((confirmed) => {
if (confirmed) {
updateInputForChild(embeddableId, panel.explicitInput);
dispatch(setControlWidth({ width: panel.width, embeddableId }));
ref.close();
}
Expand All @@ -99,13 +104,18 @@ export const EditControlButton = ({ embeddableId }: { embeddableId: string }) =>
}
});
}}
updateTitle={(newTitle) => updateInputForChild(embeddableId, { title: newTitle })}
updateTitle={(newTitle) => (inputToReturn.title = newTitle)}
controlEditorComponent={(factory as IEditableControlFactory).getControlEditor?.({
onChange: (partialInput) => updateInputForChild(embeddableId, partialInput),
onChange: (partialInput) => {
inputToReturn = { ...inputToReturn, ...partialInput };
},
initialInput: embeddable.getInput(),
})}
onCancel={() => onCancel(flyoutInstance)}
onSave={() => flyoutInstance.close()}
onSave={() => {
updateInputForChild(embeddableId, inputToReturn);
flyoutInstance.close();
}}
updateWidth={(newWidth) => dispatch(setControlWidth({ width: newWidth, embeddableId }))}
/>,
reduxContainerContext
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,24 @@
height: 100%;
}

.optionsList--loadingOverlay {
top: 0;
left: 0;
width: 100%;
height: 100%;
display: flex;
position: absolute;
align-items: center;
justify-content: center;
background-color: $euiColorEmptyShade;
}

.optionsList--items {
@include euiScrollBar;

overflow-y: auto;
position: relative;
min-height: $euiSize * 5;
max-height: $euiSize * 30;
width: $euiSize * 25;
max-width: 100%;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,48 +6,74 @@
* Side Public License, v 1.
*/

import React, { useState } from 'react';
import { EuiFilterButton, EuiFilterGroup, EuiPopover } from '@elastic/eui';
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import classNames from 'classnames';

import { EuiFilterButton, EuiFilterGroup, EuiPopover, EuiSelectableOption } from '@elastic/eui';
import { Subject } from 'rxjs';
import { OptionsListStrings } from './options_list_strings';

import { useReduxEmbeddableContext } from '../../../redux_embeddables/redux_embeddable_context';
import { OptionsListEmbeddableInput } from './options_list_embeddable';
import { OptionsListPopover } from './options_list_popover_component';
import { optionsListReducers } from './options_list_reducers';
import { OptionsListStrings } from './options_list_strings';

import './options_list.scss';
import { useStateObservable } from '../../hooks/use_state_observable';

// Availableoptions and loading state is controled by the embeddable, but is not considered embeddable input.
export interface OptionsListComponentState {
availableOptions?: EuiSelectableOption[];
selectedOptionsString?: string;
selectedOptionsCount?: number;
twoLineLayout?: boolean;
searchString?: string;
availableOptions?: string[];
loading: boolean;
}

export const OptionsListComponent = ({
componentStateSubject,
typeaheadSubject,
updateOption,
componentStateSubject,
}: {
componentStateSubject: Subject<OptionsListComponentState>;
typeaheadSubject: Subject<string>;
updateOption: (index: number) => void;
componentStateSubject: Subject<OptionsListComponentState>;
}) => {
const [isPopoverOpen, setIsPopoverOpen] = useState(false);
const optionsListState = useStateObservable<OptionsListComponentState>(componentStateSubject, {
loading: true,
});
const [searchString, setSearchString] = useState('');

// Redux embeddable Context to get state from Embeddable input
const {
selectedOptionsString,
selectedOptionsCount,
availableOptions,
twoLineLayout,
searchString,
loading,
} = optionsListState;
useEmbeddableDispatch,
useEmbeddableSelector,
actions: { replaceSelection },
} = useReduxEmbeddableContext<OptionsListEmbeddableInput, typeof optionsListReducers>();
const dispatch = useEmbeddableDispatch();
const { twoLineLayout, selectedOptions, singleSelect } = useEmbeddableSelector((state) => state);

// useStateObservable to get component state from Embeddable
const { availableOptions, loading } = useStateObservable<OptionsListComponentState>(
componentStateSubject,
{
loading: true,
}
);

// remove all other selections if this control is single select
useEffect(() => {
if (singleSelect && selectedOptions && selectedOptions?.length > 1) {
dispatch(replaceSelection(selectedOptions[0]));
}
}, [selectedOptions, singleSelect, dispatch, replaceSelection]);

const updateSearchString = useCallback(
(newSearchString: string) => {
typeaheadSubject.next(newSearchString);
setSearchString(newSearchString);
},
[typeaheadSubject]
);

const { selectedOptionsCount, selectedOptionsString } = useMemo(() => {
return {
selectedOptionsCount: selectedOptions?.length,
selectedOptionsString: selectedOptions?.join(OptionsListStrings.summary.getSeparator()),
};
}, [selectedOptions]);

const button = (
<EuiFilterButton
Expand All @@ -58,9 +84,9 @@ export const OptionsListComponent = ({
})}
onClick={() => setIsPopoverOpen((openState) => !openState)}
isSelected={isPopoverOpen}
numFilters={availableOptions?.length ?? 0}
hasActiveFilters={(selectedOptionsCount ?? 0) > 0}
numFilters={availableOptions?.length ?? 0} // Remove this once https://github.com/elastic/eui/pull/5268 is in an EUI release
numActiveFilters={selectedOptionsCount}
hasActiveFilters={(selectedOptionsCount ?? 0) > 0}
>
{!selectedOptionsCount ? OptionsListStrings.summary.getPlaceholder() : selectedOptionsString}
</EuiFilterButton>
Expand All @@ -79,15 +105,14 @@ export const OptionsListComponent = ({
anchorClassName="optionsList--anchorOverride"
closePopover={() => setIsPopoverOpen(false)}
panelPaddingSize="none"
anchorPosition="upLeft"
anchorPosition="downCenter"
ownFocus
repositionOnScroll
>
<OptionsListPopover
loading={loading}
updateOption={updateOption}
searchString={searchString}
typeaheadSubject={typeaheadSubject}
updateSearchString={updateSearchString}
availableOptions={availableOptions}
/>
</EuiPopover>
Expand Down
Loading