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(native-filters): Setting default value #12465

Closed
Closed
Show file tree
Hide file tree
Changes from 7 commits
Commits
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,105 @@
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import React, { useCallback } from 'react';
import { FormInstance } from 'antd/lib/form';
import { useChangeEffect } from 'src/common/hooks/useChangeEffect';
import { AsyncSelect } from 'src/components/Select';
import { getChartDataRequest } from 'src/chart/chartAction';
import { NativeFiltersForm } from './types';

type SelectOption = {
label: string;
value: string;
};

interface DefaultValueSelectProps {
form: FormInstance<NativeFiltersForm>;
filterId: string;
datasetId?: number | null | undefined;
column?: SelectOption | string | null;
value?: SelectOption | null;
onChange?: (value: SelectOption | null) => void;
}

// eslint-disable-next-line import/prefer-default-export
export function DefaultValueSelect({
form,
filterId,
datasetId,
column,
value,
onChange,
}: DefaultValueSelectProps) {
const resetFieldValue = useCallback(() => {
form.setFields([
{
name: ['filters', filterId, 'defaultValue'],
touched: false,
value: null,
},
]);
}, [form, filterId]);

useChangeEffect(datasetId, previous => {
if (previous != null) {
Copy link
Contributor

Choose a reason for hiding this comment

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

may better use strict comparison like: === to process correctly 0 or empty string?

resetFieldValue();
}
});

useChangeEffect(column, previous => {
if (previous != null) {
Copy link
Contributor

Choose a reason for hiding this comment

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

and same here

resetFieldValue();
}
});

async function loadOptions() {
if (datasetId == null || !column) return [];

const formData = {
datasource: `${datasetId}__table`,
groupby: [column],
metrics: ['count'],
row_limit: 10000,
viz_type: 'filter_select',
};

const response = await getChartDataRequest({
formData,
force: false,
requestParams: { dashboardId: 0 },
});

return response.result[0].data.map((el: any) => el[column as string]);
}

return (
<AsyncSelect
// "key" prop makes react render a new instance of the select whenever the dataset changes
key={`${datasetId}-${column}`}
isDisabled={datasetId == null}
value={value}
onChange={onChange}
isMulti={false}
loadOptions={loadOptions}
defaultOptions // load options on render
cacheOptions
isClearable
/>
);
}
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import {
ExtraFormData,
} from '@superset-ui/core';
import React, { useState, useEffect, useMemo, useCallback } from 'react';
import { mapValues } from 'lodash';
import { useSelector } from 'react-redux';
import cx from 'classnames';
import { Form } from 'src/common/components';
Expand All @@ -39,6 +40,7 @@ import FilterConfigurationLink from './FilterConfigurationLink';
import {
useCascadingFilters,
useFilterConfiguration,
useFiltersState,
useSetExtraFormData,
} from './state';
import { Filter, CascadeFilter } from './types';
Expand Down Expand Up @@ -212,7 +214,6 @@ const FilterValue: React.FC<FilterProps> = ({
inverseSelection,
targets,
currentValue,
defaultValue,
} = filter;
const cascadingFilters = useCascadingFilters(id);
const [loading, setLoading] = useState<boolean>(true);
Expand All @@ -239,7 +240,7 @@ const FilterValue: React.FC<FilterProps> = ({
time_range_endpoints: ['inclusive', 'exclusive'],
url_params: {},
viz_type: 'filter_select',
defaultValues: currentValue || defaultValue || [],
defaultValues: currentValue || [],
});

useEffect(() => {
Expand Down Expand Up @@ -364,6 +365,7 @@ const FilterBar: React.FC<FiltersBarProps> = ({
);
const setExtraFormData = useSetExtraFormData();
const filterConfigs = useFilterConfiguration();
const filtersState = useFiltersState();
const canEdit = useSelector<any, boolean>(
({ dashboardInfo }) => dashboardInfo.dash_edit_perm,
);
Expand All @@ -373,8 +375,17 @@ const FilterBar: React.FC<FiltersBarProps> = ({
if (filterConfigs.length === 0 && filtersOpen) {
toggleFiltersBar(false);
}
setFilterData({});
}, [filterConfigs]);

useEffect(() => {
const extraFormData = mapValues(
filtersState,
filter => filter.extraFormData || {},
);
setFilterData(filterData => ({ ...extraFormData, ...filterData }));
}, [filtersState]);

const getFilterValue = useCallback(
(filter: Filter): (string | number | boolean)[] | null => {
const filters = filterData[filter.id]?.append_form_data?.filters;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ import SupersetResourceSelect, {
import { addDangerToast } from 'src/messageToasts/actions';
import { ClientErrorObject } from 'src/utils/getClientErrorObject';
import { ColumnSelect } from './ColumnSelect';
import { DefaultValueSelect } from './DefaultValueSelect';
import { Filter, NativeFiltersForm } from './types';
import FilterScope from './FilterScope';

Expand Down Expand Up @@ -103,6 +104,9 @@ export const FilterConfigForm: React.FC<FilterConfigFormProps> = ({
? { label: '', value: filterToEdit?.targets[0].datasetId }
: undefined,
);
const [column, setColumn] = useState<Value<string> | string | null>(
filterToEdit?.targets[0]?.column?.name || null,
);

const onDatasetSelectError = useCallback(
({ error, message }: ClientErrorObject) => {
Expand Down Expand Up @@ -177,6 +181,19 @@ export const FilterConfigForm: React.FC<FilterConfigFormProps> = ({
form={form}
filterId={filterId}
datasetId={dataset?.value}
onChange={setColumn}
/>
</StyledFormItem>
<StyledFormItem
name={['filters', filterId, 'defaultValue']}
label={<StyledLabel>{t('Default Value')}</StyledLabel>}
initialValue={filterToEdit?.defaultValue}
>
<DefaultValueSelect
form={form}
filterId={filterId}
datasetId={dataset?.value}
column={column}
/>
</StyledFormItem>
<StyledFormItem
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,12 @@ export function useFilterConfigMap() {
);
}

export function useFiltersState() {
return useSelector<any, { [id: string]: FilterState }>(
state => state.nativeFilters.filtersState,
);
}

export function useFilterState(id: string) {
return useSelector<any, FilterState>(
state => state.nativeFilters.filtersState[id] || getInitialFilterState(id),
Expand Down
26 changes: 23 additions & 3 deletions superset-frontend/src/dashboard/reducers/nativeFilters.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,18 +22,36 @@ import {
SET_FILTER_CONFIG_COMPLETE,
} from 'src/dashboard/actions/nativeFilters';
import {
Filter,
FilterConfiguration,
FilterState,
NativeFiltersState,
} from 'src/dashboard/components/nativeFilters/types';
import { getSelectExtraFormData } from 'src/filters/utils';

export function getInitialFilterState(id: string): FilterState {
export function getInitialFilterState(
id: string,
extraFormData = {},
): FilterState {
return {
id,
extraFormData: {},
extraFormData,
};
}

function getInitialExtraFormData(filter: Filter) {
if (filter?.defaultValue) {
const [target] = filter.targets;
return getSelectExtraFormData(
target.column.name,
[filter.defaultValue],
false,
filter.inverseSelection,
);
}
return {};
}

export function getInitialState(
filterConfig: FilterConfiguration,
prevFiltersState: { [filterId: string]: FilterState },
Expand All @@ -44,7 +62,9 @@ export function getInitialState(
filterConfig.forEach(filter => {
const { id } = filter;
filters[id] = filter;
filtersState[id] = prevFiltersState?.[id] || getInitialFilterState(id);
filtersState[id] =
prevFiltersState?.[id] ||
getInitialFilterState(id, getInitialExtraFormData(filter));
});
return state;
}
Expand Down