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

fix(select): select component sort functionality on certain options #17638

Merged
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,7 @@ const groupByControl: SharedControlConfig<'SelectControl', ColumnMeta> = {
'One or many columns to group by. High cardinality groupings should include a sort by metric ' +
'and series limit to limit the number of fetched and rendered series.',
),
sortOptions: true,
optionRenderer: c => <ColumnOption showType column={c} />,
valueRenderer: c => <ColumnOption column={c} />,
valueKey: 'column_name',
Expand Down
69 changes: 47 additions & 22 deletions superset-frontend/src/components/Select/Select.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,9 @@ export interface SelectProps extends PickedSelectProps {
* Works in async mode only (See the options property).
*/
onError?: (error: string) => void;
sortByProperty?: string;
sortComparator?: (a: AntdLabeledValue, b: AntdLabeledValue) => number;
sortOptions?: boolean;
}

const StyledContainer = styled.div`
Expand Down Expand Up @@ -232,15 +234,27 @@ const Error = ({ error }: { error: string }) => (
</StyledError>
);

const defaultSortComparator = (a: AntdLabeledValue, b: AntdLabeledValue) => {
if (typeof a.label === 'string' && typeof b.label === 'string') {
return a.label.localeCompare(b.label);
}
if (typeof a.value === 'string' && typeof b.value === 'string') {
return a.value.localeCompare(b.value);
}
return (a.value as number) - (b.value as number);
};
// Not sure if this is necessary anymore? Seems like all options being
// passed in are being formatted to have a string label
// -----------------------------------------
// const defaultSortComparator = (a: AntdLabeledValue, b: AntdLabeledValue) => {
// if (typeof a.label === 'string' && typeof b.label === 'string') {
// return a.label.localeCompare(b.label);
// }
// if (typeof a.value === 'string' && typeof b.value === 'string') {
// return a.value.localeCompare(b.value);
// }
// return (a.value as number) - (b.value as number);
// };
// -----------------------------------------

const getInitialIndexes = (options: OptionsType) =>
options.reduce((a, c, i) => ({ ...a, [c.value]: i }), {});

const sortByInitialIndexes = (
options: OptionsType,
originals: { value?: number },
) => options.sort((a, b) => originals[a.value] - originals[b.value]);

/**
* It creates a comparator to check for a specific property.
Expand Down Expand Up @@ -289,17 +303,20 @@ const Select = ({
pageSize = DEFAULT_PAGE_SIZE,
placeholder = t('Select ...'),
showSearch = true,
sortComparator = defaultSortComparator,
sortByProperty = 'label',
sortComparator = propertyComparator(sortByProperty),
sortOptions = false,
corbinrobb marked this conversation as resolved.
Show resolved Hide resolved
value,
...props
}: SelectProps) => {
const isAsync = typeof options === 'function';
const isSingleMode = mode === 'single';
const shouldShowSearch = isAsync || allowNewOptions ? true : showSearch;
const initialOptions =
options && Array.isArray(options) ? options : EMPTY_OPTIONS;
const [selectOptions, setSelectOptions] =
useState<OptionsType>(initialOptions);
options && Array.isArray(options) ? [...options] : EMPTY_OPTIONS;
const [selectOptions, setSelectOptions] = useState<OptionsType>(
sortOptions ? initialOptions.sort(sortComparator) : initialOptions,
corbinrobb marked this conversation as resolved.
Show resolved Hide resolved
);
const shouldUseChildrenOptions = !!selectOptions.find(
opt => opt?.customLabel,
);
Expand All @@ -319,6 +336,7 @@ const Select = ({
: allowNewOptions
? 'tags'
: 'multiple';
const optionsInitialOrder = useRef(getInitialIndexes(initialOptions));

// TODO: Don't assume that isAsync is always labelInValue
const handleTopOptions = useCallback(
Expand All @@ -328,7 +346,6 @@ const Select = ({
const isLabeledValue = isAsync || labelInValue;
const topOptions: OptionsType = [];
const otherOptions: OptionsType = [];

selectOptions.forEach(opt => {
let found = false;
if (Array.isArray(selectedValue)) {
Expand Down Expand Up @@ -378,20 +395,23 @@ const Select = ({
});
}
const sortedOptions = [
...topOptions.sort(sortComparator),
...otherOptions.sort(sortComparator),
...sortByInitialIndexes(topOptions, optionsInitialOrder.current),
...sortByInitialIndexes(otherOptions, optionsInitialOrder.current),
];
if (!isEqual(sortedOptions, selectOptions)) {
setSelectOptions(sortedOptions);
}
} else {
const sortedOptions = [...selectOptions].sort(sortComparator);
const sortedOptions = sortByInitialIndexes(
[...selectOptions],
optionsInitialOrder.current,
);
if (!isEqual(sortedOptions, selectOptions)) {
setSelectOptions(sortedOptions);
}
}
},
[isAsync, isSingleMode, labelInValue, selectOptions, sortComparator],
[isAsync, isSingleMode, labelInValue, selectOptions],
);

const handleOnSelect = (
Expand Down Expand Up @@ -457,7 +477,6 @@ const Select = ({
data.forEach(option =>
dataValues.add(String(option.value).toLocaleLowerCase()),
);

// merges with existing and creates unique options
setSelectOptions(prevOptions => {
mergedData = [
Expand All @@ -469,13 +488,15 @@ const Select = ({
),
...data,
];
mergedData.sort(sortComparator);

if (sortOptions) mergedData.sort(sortComparator);
optionsInitialOrder.current = getInitialIndexes(mergedData);
return mergedData;
});
}
return mergedData;
},
[sortComparator],
[sortComparator, sortOptions],
);

const handlePaginatedFetch = useMemo(
Expand Down Expand Up @@ -662,7 +683,11 @@ const Select = ({
}
});
if (options.length > 0) {
setSelectOptions([...options, ...selectOptions]);
const sortedOriginal = sortByInitialIndexes(
selectOptions,
optionsInitialOrder.current,
);
setSelectOptions([...options, ...sortedOriginal]);
}
}
}, [labelInValue, isAsync, selectOptions, selectValue]);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
* under the License.
*/
import React, { RefObject } from 'react';
import Select, { propertyComparator } from 'src/components/Select/Select';
import Select from 'src/components/Select/Select';
import { t, styled } from '@superset-ui/core';
import Alert from 'src/components/Alert';
import Button from 'src/components/Button';
Expand Down Expand Up @@ -120,7 +120,8 @@ class RefreshIntervalModal extends React.PureComponent<
options={options}
value={refreshFrequency}
onChange={this.handleFrequencyChange}
sortComparator={propertyComparator('value')}
sortByProperty="value"
sortOptions
/>
{showRefreshWarning && (
<RefreshWarningContainer>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
import React from 'react';
import { styled, t } from '@superset-ui/core';
import { Form, FormItem, FormProps } from 'src/components/Form';
import Select, { propertyComparator } from 'src/components/Select/Select';
import Select from 'src/components/Select/Select';
import { Col, InputNumber, Row } from 'src/common/components';
import Button from 'src/components/Button';
import {
Expand Down Expand Up @@ -129,7 +129,8 @@ const operatorField = (
<Select
ariaLabel={t('Operator')}
options={operatorOptions}
sortComparator={propertyComparator('order')}
sortByProperty="order"
sortOptions
/>
</FormItem>
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ import Label, { Type } from 'src/components/Label';
import Popover from 'src/components/Popover';
import { Divider } from 'src/common/components';
import Icons from 'src/components/Icons';
import Select, { propertyComparator } from 'src/components/Select/Select';
import Select from 'src/components/Select/Select';
import { Tooltip } from 'src/components/Tooltip';
import { DEFAULT_TIME_RANGE } from 'src/explore/constants';
import { useDebouncedEffect } from 'src/explore/exploreUtils';
Expand Down Expand Up @@ -295,7 +295,8 @@ export default function DateFilterLabel(props: DateFilterControlProps) {
options={FRAME_OPTIONS}
value={frame}
onChange={onChangeFrame}
sortComparator={propertyComparator('order')}
sortByProperty="order"
sortOptions
/>
{frame !== 'No filter' && <Divider />}
{frame === 'Common' && (
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ import { isInteger } from 'lodash';
import { Col, InputNumber, Row } from 'src/common/components';
import { DatePicker } from 'src/components/DatePicker';
import { Radio } from 'src/components/Radio';
import Select, { propertyComparator } from 'src/components/Select/Select';
import Select from 'src/components/Select/Select';
import { InfoTooltipWithTrigger } from '@superset-ui/chart-controls';
import {
SINCE_GRAIN_OPTIONS,
Expand All @@ -41,8 +41,6 @@ import {
FrameComponentProps,
} from 'src/explore/components/controls/DateFilterControl/types';

const sortComparator = propertyComparator('order');

export function CustomFrame(props: FrameComponentProps) {
const { customRange, matchedFlag } = customTimeRangeDecode(props.value);
if (!matchedFlag) {
Expand Down Expand Up @@ -123,7 +121,8 @@ export function CustomFrame(props: FrameComponentProps) {
options={SINCE_MODE_OPTIONS}
value={sinceMode}
onChange={(value: string) => onChange('sinceMode', value)}
sortComparator={sortComparator}
sortByProperty="order"
sortOptions
/>
{sinceMode === 'specific' && (
<Row>
Expand Down Expand Up @@ -158,7 +157,8 @@ export function CustomFrame(props: FrameComponentProps) {
options={SINCE_GRAIN_OPTIONS}
value={sinceGrain}
onChange={(value: string) => onChange('sinceGrain', value)}
sortComparator={sortComparator}
sortByProperty="order"
sortOptions
/>
</Col>
</Row>
Expand All @@ -177,7 +177,8 @@ export function CustomFrame(props: FrameComponentProps) {
options={UNTIL_MODE_OPTIONS}
value={untilMode}
onChange={(value: string) => onChange('untilMode', value)}
sortComparator={sortComparator}
sortByProperty="order"
sortOptions
/>
{untilMode === 'specific' && (
<Row>
Expand Down Expand Up @@ -211,7 +212,8 @@ export function CustomFrame(props: FrameComponentProps) {
options={UNTIL_GRAIN_OPTIONS}
value={untilGrain}
onChange={(value: string) => onChange('untilGrain', value)}
sortComparator={sortComparator}
sortByProperty="order"
sortOptions
/>
</Col>
</Row>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -240,6 +240,8 @@ export default class SelectControl extends React.PureComponent {
optionRenderer,
options: this.state.options,
placeholder,
sortByProperty: this.props.sortByProperty,
sortOptions: this.props.sortOptions,
value: getValue(),
};

Expand Down
8 changes: 5 additions & 3 deletions superset-frontend/src/views/CRUD/alert/AlertReportModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ import { Switch } from 'src/components/Switch';
import Modal from 'src/components/Modal';
import TimezoneSelector from 'src/components/TimezoneSelector';
import { Radio } from 'src/components/Radio';
import Select, { propertyComparator } from 'src/components/Select/Select';
import Select from 'src/components/Select/Select';
import { FeatureFlag, isFeatureEnabled } from 'src/featureFlags';
import withToasts from 'src/components/MessageToasts/withToasts';
import Owner from 'src/types/Owner';
Expand Down Expand Up @@ -1177,7 +1177,8 @@ const AlertReportModal: FunctionComponent<AlertReportModalProps> = ({
currentAlert?.validator_config_json?.op || undefined
}
options={CONDITIONS}
sortComparator={propertyComparator('order')}
sortByProperty="order"
sortOptions
/>
</div>
</StyledInputContainer>
Expand Down Expand Up @@ -1249,7 +1250,8 @@ const AlertReportModal: FunctionComponent<AlertReportModalProps> = ({
: DEFAULT_RETENTION
}
options={RETENTION_OPTIONS}
sortComparator={propertyComparator('value')}
sortByProperty="value"
sortOptions
/>
</div>
</StyledInputContainer>
Expand Down