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

[Dashboard] [Controls] Add excludes toggle to options list #142780

Merged
Merged
Show file tree
Hide file tree
Changes from 17 commits
Commits
Show all changes
22 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
@@ -0,0 +1,64 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/

import deepEqual from 'fast-deep-equal';
import { omit, isEqual } from 'lodash';
import { OptionsListEmbeddableInput, OPTIONS_LIST_CONTROL } from '../options_list/types';
import { RANGE_SLIDER_CONTROL } from '../range_slider/types';
import { TIME_SLIDER_CONTROL } from '../time_slider/types';

import { ControlGroupDiffSystem, ControlPanelState } from './types';

interface DiffSystem {
getPanelIsEqual: (initialInput: ControlPanelState, newInput: ControlPanelState) => boolean;
}

const genericControlPanelDiffSystem: DiffSystem = {
getPanelIsEqual: (initialInput, newInput) => {
return deepEqual(initialInput, newInput);
},
};

export const ControlPanelDiffSystems: {
[key in ControlGroupDiffSystem]: DiffSystem;
} = {
Copy link
Contributor Author

@Heenawter Heenawter Oct 19, 2022

Choose a reason for hiding this comment

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

This ControlPanelDiffSystems should be temporary and will be removed/cleaned up as part of the Portable Dashboards project (already discussed with @ThomThomson to confirm).

Basically, if we had access to the ControlGroupContainer during the dashboard diff process rather than just PersistableControlGroupInput, we could then make use of the embeddable getExplicitInputIsEqual function for each child embeddable of the control group. However, this is a fairly large refactor that does not fit in to this PR, so the ControlPanelDiffSystems serves as a temporary workaround.

Copy link
Contributor

Choose a reason for hiding this comment

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

Nice usage of function registry type architecture! It's temporary, but it's set up like a microcosm of the actual embeddable diffing system, so it'll be super easy to migrate over, even if we end up needing diffing systems for multiple control types in the meantime.

Note to self: I was thinking about when to move this into the embeddable, and I think it makes the most sense to do so when we tackle Control Group as a Panel, so let's keep that in mind when we write up that issue.

[OPTIONS_LIST_CONTROL]: {
getPanelIsEqual: (initialInput, newInput) => {
if (!deepEqual(omit(initialInput, 'explicitInput'), omit(newInput, 'explicitInput')))
return false;
Heenawter marked this conversation as resolved.
Show resolved Hide resolved

const {
exclude: excludeA,
selectedOptions: selectedA,
singleSelect: singleSelectA,
allowExclude: allowExcludeA,
runPastTimeout: runPastTimeoutA,
...inputA
}: Partial<OptionsListEmbeddableInput> = initialInput.explicitInput;
const {
exclude: excludeB,
selectedOptions: selectedB,
singleSelect: singleSelectB,
allowExclude: allowExcludeB,
runPastTimeout: runPastTimeoutB,
...inputB
}: Partial<OptionsListEmbeddableInput> = newInput.explicitInput;

return (
Boolean(excludeA) === Boolean(excludeB) &&
Boolean(singleSelectA) === Boolean(singleSelectB) &&
Boolean(allowExcludeA) === Boolean(allowExcludeB) &&
Boolean(runPastTimeoutA) === Boolean(runPastTimeoutB) &&
Heenawter marked this conversation as resolved.
Show resolved Hide resolved
isEqual(selectedA ?? [], selectedB ?? []) &&
Heenawter marked this conversation as resolved.
Show resolved Hide resolved
deepEqual(inputA, inputB)
);
},
},
[RANGE_SLIDER_CONTROL]: genericControlPanelDiffSystem,
Heenawter marked this conversation as resolved.
Show resolved Hide resolved
[TIME_SLIDER_CONTROL]: genericControlPanelDiffSystem,
};
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,19 @@
import { SerializableRecord } from '@kbn/utility-types';
import deepEqual from 'fast-deep-equal';

import { pick } from 'lodash';
import { pick, omit, xor } from 'lodash';
import { ControlGroupInput } from '..';
import {
DEFAULT_CONTROL_GROW,
DEFAULT_CONTROL_STYLE,
DEFAULT_CONTROL_WIDTH,
} from './control_group_constants';
import { PersistableControlGroupInput, RawControlGroupAttributes } from './types';
import {
ControlGroupDiffSystem,
PersistableControlGroupInput,
RawControlGroupAttributes,
} from './types';
import { ControlPanelDiffSystems } from './control_group_panel_diff_system';

const safeJSONParse = <OutType>(jsonString?: string): OutType | undefined => {
if (!jsonString && typeof jsonString !== 'string') return;
Expand Down Expand Up @@ -54,10 +59,38 @@ export const persistableControlGroupInputIsEqual = (
...defaultInput,
...pick(b, ['panels', 'chainingSystem', 'controlStyle', 'ignoreParentSettings']),
};
if (deepEqual(inputA, inputB)) return true;

if (
getPanelsAreEqual(inputA.panels, inputB.panels) &&
deepEqual(omit(inputA, 'panels'), omit(inputB, 'panels'))
)
return true;

return false;
};

const getPanelsAreEqual = (
originalPanels: PersistableControlGroupInput['panels'],
newPanels: PersistableControlGroupInput['panels']
) => {
const originalPanelIds = Object.keys(originalPanels);
const newPanelIds = Object.keys(newPanels);
const panelIdDiff = xor(originalPanelIds, newPanelIds);
if (panelIdDiff.length > 0) {
return false;
}

for (const panelId of newPanelIds) {
const newPanelType = newPanels[panelId].type as ControlGroupDiffSystem;
const panelIsEqual = ControlPanelDiffSystems[newPanelType].getPanelIsEqual(
originalPanels[panelId],
newPanels[panelId]
);
if (!panelIsEqual) return false;
}
return true;
};

export const controlGroupInputToRawControlGroupAttributes = (
controlGroupInput: Omit<ControlGroupInput, 'id'>
): RawControlGroupAttributes => {
Expand Down
6 changes: 6 additions & 0 deletions src/plugins/controls/common/control_group/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

import { EmbeddableInput, PanelState } from '@kbn/embeddable-plugin/common/types';
import { SerializableRecord } from '@kbn/utility-types';
import { OPTIONS_LIST_CONTROL, RANGE_SLIDER_CONTROL, TIME_SLIDER_CONTROL } from '..';
import { ControlInput, ControlStyle, ControlWidth } from '../types';

export const CONTROL_GROUP_TYPE = 'control_group';
Expand All @@ -21,6 +22,11 @@ export interface ControlPanelState<TEmbeddableInput extends ControlInput = Contr

export type ControlGroupChainingSystem = 'HIERARCHICAL' | 'NONE';

export type ControlGroupDiffSystem =
Heenawter marked this conversation as resolved.
Show resolved Hide resolved
| typeof OPTIONS_LIST_CONTROL
| typeof RANGE_SLIDER_CONTROL
| typeof TIME_SLIDER_CONTROL;

export interface ControlsPanels {
[panelId: string]: ControlPanelState;
}
Expand Down
2 changes: 2 additions & 0 deletions src/plugins/controls/common/options_list/mocks.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ const mockOptionsListEmbeddableInput = {
selectedOptions: [],
runPastTimeout: false,
singleSelect: false,
allowExclude: false,
exclude: false,
} as OptionsListEmbeddableInput;

const mockOptionsListOutput = {
Expand Down
2 changes: 2 additions & 0 deletions src/plugins/controls/common/options_list/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ export interface OptionsListEmbeddableInput extends DataControlInput {
selectedOptions?: string[];
runPastTimeout?: boolean;
singleSelect?: boolean;
allowExclude?: boolean;
exclude?: boolean;
Copy link
Contributor Author

Choose a reason for hiding this comment

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

exclude should be treated the same as selectedOptions - i.e. toggling its value should trigger unsaved changes, the author should be able to save in a default value for a given control, etc. Hence, why it's part of explicitInput and not just component state.

}

export type OptionsListField = FieldSpec & {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,13 @@ import classNames from 'classnames';
import { debounce, isEmpty } from 'lodash';
import React, { useCallback, useEffect, useMemo, useState, useRef } from 'react';

import { EuiFilterButton, EuiFilterGroup, EuiPopover, useResizeObserver } from '@elastic/eui';
import {
EuiFilterButton,
EuiFilterGroup,
EuiPopover,
EuiTextColor,
useResizeObserver,
} from '@elastic/eui';
import { useReduxEmbeddableContext } from '@kbn/presentation-util-plugin/public';

import { OptionsListStrings } from './options_list_strings';
Expand Down Expand Up @@ -43,6 +49,7 @@ export const OptionsListControl = ({ typeaheadSubject }: { typeaheadSubject: Sub
const controlStyle = select((state) => state.explicitInput.controlStyle);
const singleSelect = select((state) => state.explicitInput.singleSelect);
const id = select((state) => state.explicitInput.id);
const exclude = select((state) => state.explicitInput.exclude);

const loading = select((state) => state.output.loading);

Expand Down Expand Up @@ -75,6 +82,11 @@ export const OptionsListControl = ({ typeaheadSubject }: { typeaheadSubject: Sub
validSelectionsCount: validSelections?.length,
selectionDisplayNode: (
<>
{exclude && (
<EuiTextColor color="danger">
<b>{OptionsListStrings.control.getNegate()}</b>{' '}
Heenawter marked this conversation as resolved.
Show resolved Hide resolved
</EuiTextColor>
)}
{validSelections && (
<span>{validSelections?.join(OptionsListStrings.control.getSeparator())}</span>
)}
Expand All @@ -86,7 +98,7 @@ export const OptionsListControl = ({ typeaheadSubject }: { typeaheadSubject: Sub
</>
),
};
}, [validSelections, invalidSelections]);
}, [exclude, validSelections, invalidSelections]);

const button = (
<div className="optionsList--filterBtnWrapper" ref={resizeRef}>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import { ControlEditorProps, OptionsListEmbeddableInput } from '../..';
interface OptionsListEditorState {
singleSelect?: boolean;
runPastTimeout?: boolean;
allowExclude?: boolean;
}

export const OptionsListEditorOptions = ({
Expand All @@ -25,11 +26,12 @@ export const OptionsListEditorOptions = ({
const [state, setState] = useState<OptionsListEditorState>({
singleSelect: initialInput?.singleSelect,
runPastTimeout: initialInput?.runPastTimeout,
allowExclude: initialInput?.allowExclude,
});

return (
<>
<EuiFormRow>
<EuiFormRow display="columnCompressedSwitch">
<EuiSwitch
label={OptionsListStrings.editor.getAllowMultiselectTitle()}
checked={!state.singleSelect}
Expand All @@ -39,6 +41,16 @@ export const OptionsListEditorOptions = ({
}}
/>
</EuiFormRow>
<EuiFormRow display="columnCompressedSwitch">
<EuiSwitch
label={OptionsListStrings.editor.getAllowExclude()}
checked={!state.allowExclude}
onChange={() => {
onChange({ allowExclude: !state.allowExclude });
setState((s) => ({ ...s, allowExclude: !s.allowExclude }));
}}
/>
</EuiFormRow>
<EuiFormRow>
<EuiSwitch
label={OptionsListStrings.editor.getRunPastTimeoutTitle()}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -97,4 +97,22 @@ describe('Options list popover', () => {
expect(child.text()).toBe(selections[i]);
});
});

test('should default to exclude = false', () => {
const popover = mountComponent();
const includeButton = findTestSubject(popover, 'optionsList__includeResults');
const excludeButton = findTestSubject(popover, 'optionsList__excludeResults');
expect(includeButton.prop('checked')).toBe(true);
expect(excludeButton.prop('checked')).toBeFalsy();
});

test('if exclude = true, select appropriate button in button group', () => {
const popover = mountComponent({
explicitInput: { exclude: true },
});
const includeButton = findTestSubject(popover, 'optionsList__includeResults');
const excludeButton = findTestSubject(popover, 'optionsList__excludeResults');
expect(includeButton.prop('checked')).toBeFalsy();
expect(excludeButton.prop('checked')).toBe(true);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,11 @@ import {
EuiBadge,
EuiIcon,
EuiTitle,
EuiPopoverFooter,
EuiButtonGroup,
useEuiBackgroundColor,
} from '@elastic/eui';
import { css } from '@emotion/react';
import { useReduxEmbeddableContext } from '@kbn/presentation-util-plugin/public';

import { optionsListReducers } from '../options_list_reducers';
Expand All @@ -34,12 +38,23 @@ export interface OptionsListPopoverProps {
updateSearchString: (newSearchString: string) => void;
}

const aggregationToggleButtons = [
{
id: 'optionsList__includeResults',
label: OptionsListStrings.popover.getIncludeLabel(),
},
{
id: 'optionsList__excludeResults',
label: OptionsListStrings.popover.getExcludeLabel(),
},
];

export const OptionsListPopover = ({ width, updateSearchString }: OptionsListPopoverProps) => {
// Redux embeddable container Context
const {
useEmbeddableDispatch,
useEmbeddableSelector: select,
actions: { selectOption, deselectOption, clearSelections, replaceSelection },
actions: { selectOption, deselectOption, clearSelections, replaceSelection, setExclude },
} = useReduxEmbeddableContext<OptionsListReduxState, typeof optionsListReducers>();

const dispatch = useEmbeddableDispatch();
Expand All @@ -52,8 +67,10 @@ export const OptionsListPopover = ({ width, updateSearchString }: OptionsListPop
const field = select((state) => state.componentState.field);

const selectedOptions = select((state) => state.explicitInput.selectedOptions);
const allowExclude = select((state) => state.explicitInput.allowExclude);
const singleSelect = select((state) => state.explicitInput.singleSelect);
const title = select((state) => state.explicitInput.title);
const exclude = select((state) => state.explicitInput.exclude);

const loading = select((state) => state.output.loading);

Expand All @@ -65,6 +82,7 @@ export const OptionsListPopover = ({ width, updateSearchString }: OptionsListPop
);

const [showOnlySelected, setShowOnlySelected] = useState(false);
const euiBackgroundColor = useEuiBackgroundColor('subdued');

return (
<>
Expand All @@ -77,6 +95,7 @@ export const OptionsListPopover = ({ width, updateSearchString }: OptionsListPop
direction="row"
justifyContent="spaceBetween"
alignItems="center"
responsive={false}
Heenawter marked this conversation as resolved.
Show resolved Hide resolved
>
<EuiFlexItem>
<EuiFieldSearch
Expand Down Expand Up @@ -248,6 +267,25 @@ export const OptionsListPopover = ({ width, updateSearchString }: OptionsListPop
</>
)}
</div>
{!allowExclude && (
<EuiPopoverFooter
paddingSize="s"
css={css`
background-color: ${euiBackgroundColor};
`}
>
<EuiButtonGroup
legend={OptionsListStrings.popover.getIncludeExcludeLegend()}
options={aggregationToggleButtons}
idSelected={exclude ? 'optionsList__excludeResults' : 'optionsList__includeResults'}
onChange={(optionId) =>
dispatch(setExclude(optionId === 'optionsList__excludeResults'))
}
buttonSize="compressed"
data-test-subj="optionsList__includeExcludeButtonGroup"
/>
</EuiPopoverFooter>
)}
</>
);
};
Loading