codeant-ai-for-open-source[bot] commented on code in PR #42330: URL: https://github.com/apache/superset/pull/42330#discussion_r3636156073
########## superset-frontend/src/filters/components/CustomFilter/CustomFilterPlugin.tsx: ########## @@ -0,0 +1,253 @@ +/** + * 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. + */ +/* eslint-disable no-param-reassign */ +import { useCallback, useEffect, useMemo, useState } from 'react'; +import { t } from '@apache-superset/core/translation'; +import { + ensureIsArray, + getColumnLabel, + JsonObject, +} from '@superset-ui/core'; +import { styled } from '@apache-superset/core/theme'; +import { GenericDataType } from '@apache-superset/core/common'; +import { Select } from '@superset-ui/core/components'; +import { Checkbox, Radio } from 'antd'; +import { FilterPluginStyle } from '../common'; +import { PluginFilterCustomFilterQueryFormData, DEFAULT_FORM_DATA } from './types'; + +interface CustomFilterPluginProps { + data: { [key: string]: any }[]; + formData: PluginFilterCustomFilterQueryFormData; + coltypeMap: Record<string, GenericDataType>; + width: number; + height: number; + filterState: { value?: any[] }; + setDataMask: (arg: JsonObject) => void; + setHoveredFilter: (arg: string) => void; + unsetHoveredFilter: () => void; + setFocusedFilter: (arg: string) => void; + unsetFocusedFilter: () => void; + setFilterActive: (arg: boolean) => void; + inputRef: React.RefObject<HTMLInputElement>; + isRefreshing: boolean; + appSection: string; +} + +const StyledCheckboxGroup = styled.div` + display: flex; + flex-direction: column; + gap: 8px; + max-height: ${({ height }: { height: number }) => height - 40}px; + overflow-y: auto; + padding: 8px; +`; + +const StyledRadioGroup = styled.div` + display: flex; + flex-direction: column; + gap: 8px; + max-height: ${({ height }: { height: number }) => height - 40}px; + overflow-y: auto; + padding: 8px; +`; + +export default function CustomFilterPlugin( + props: CustomFilterPluginProps, +) { + const { + data, + formData, + _coltypeMap, + width, + height, + filterState, + setDataMask, + setHoveredFilter, + unsetHoveredFilter, + setFocusedFilter, + unsetFocusedFilter, + _setFilterActive, + inputRef, + isRefreshing, + } = props; + + const { + groupby, + controlType = 'dropdown', + multiSelect = true, + _enableEmptyFilter = false, + inverseSelection = false, + defaultToFirstItem = false, + sortAscending = true, + } = { ...DEFAULT_FORM_DATA, ...formData }; + + const column = useMemo(() => getColumnLabel(groupby?.[0]), [groupby]); + const values = useMemo( + () => + data + .map(d => d[column]) + .filter(v => v !== null && v !== undefined) + .sort((a, b) => { + if (sortAscending) { + return String(a).localeCompare(String(b)); + } + return String(b).localeCompare(String(a)); + }), + [data, column, sortAscending], + ); + + const [filterValue, setFilterValue] = useState<any[]>( + filterState.value || (defaultToFirstItem && values.length > 0 ? [values[0]] : []), + ); + + const handleChange = useCallback( + (selectedValues: any[]) => { + const value = ensureIsArray(selectedValues); + setFilterValue(value); + + const dataMask = { + extraFormData: { + filters: + value.length > 0 + ? [ + { + col: column, + op: inverseSelection ? 'NOT IN' : 'IN', + val: value, + }, + ] + : [], + }, + filterState: { + value, + }, + }; + setDataMask(dataMask); + }, + [column, inverseSelection, setDataMask], + ); + + useEffect(() => { + if (filterState.value !== undefined) { + setFilterValue(filterState.value); + } + }, [filterState.value]); + + useEffect(() => { + if (defaultToFirstItem && values.length > 0 && filterValue.length === 0) { + handleChange([values[0]]); + } + }, [defaultToFirstItem, values, filterValue.length, handleChange]); + + const handleHover = useCallback( + (isHovered: boolean) => { + if (isHovered) { + setHoveredFilter(column); + } else { + unsetHoveredFilter(); + } + }, + [column, setHoveredFilter, unsetHoveredFilter], + ); + + const handleFocus = useCallback( + (isFocused: boolean) => { + if (isFocused) { + setFocusedFilter(column); + } else { + unsetFocusedFilter(); + } + }, + [column, setFocusedFilter, unsetFocusedFilter], + ); + + const options = values.map(value => ({ + label: String(value), + value, + })); + + if (controlType === 'checkbox') { + return ( + <FilterPluginStyle width={width} height={height}> + <StyledCheckboxGroup + height={height} + onMouseEnter={() => handleHover(true)} + onMouseLeave={() => handleHover(false)} + > + <Checkbox.Group + value={filterValue} + onChange={handleChange as any} + disabled={isRefreshing} + > + {values.map(value => ( + <div key={value}> + <Checkbox value={value}>{String(value)}</Checkbox> + </div> + ))} + </Checkbox.Group> + </StyledCheckboxGroup> + </FilterPluginStyle> + ); + } + + if (controlType === 'radio') { + return ( + <FilterPluginStyle width={width} height={height}> + <StyledRadioGroup + height={height} + onMouseEnter={() => handleHover(true)} + onMouseLeave={() => handleHover(false)} + > + <Radio.Group + value={filterValue[0]} + onChange={e => handleChange([e.target.value])} + disabled={isRefreshing} + > + {values.map(value => ( + <div key={value}> + <Radio value={value}>{String(value)}</Radio> + </div> + ))} + </Radio.Group> + </StyledRadioGroup> + </FilterPluginStyle> + ); + } + + return ( + <FilterPluginStyle width={width} height={height}> + <Select + mode={multiSelect ? 'multiple' : undefined} + value={filterValue} Review Comment: **Suggestion:** When single-select mode is used, the select component still receives an array as its controlled value. AntD expects a scalar value in non-multiple mode, so this shape mismatch can cause incorrect rendering/selection behavior and controlled-component warnings. Store and pass a scalar in single-select mode (or branch value handling by mode). [logic error] <details> <summary><b>Severity Level:</b> Major ⚠️</summary> ```mdx - ❌ Single-select dropdown filter may not reflect user selection. - ⚠️ React console logs controlled component warnings. - ⚠️ Potential future regressions upgrading Select/AntD component. ``` </details> <details> <summary><b>Steps of Reproduction ✅ </b></summary> ```mdx 1. Open CustomFilterPlugin in superset-frontend/src/filters/components/CustomFilter/CustomFilterPlugin.tsx, where the main React component is defined around lines 70-253. 2. Render CustomFilterPlugin with props where controlType is left as the default 'dropdown', multiSelect is set to false, and formData.groupby is configured so that the query populates data with at least one non-null value for the chosen column (column computed at line 100). 3. On initial render, filterValue is initialized as an array at lines 115-117 (for example ['US']), and handleChange at lines 119-143 always normalizes selections into an array via ensureIsArray. 4. When controlType is 'dropdown' and multiSelect is false, Select at lines 235-237 renders with mode undefined but value set to filterValue (an array), so the single-select Select from @superset-ui/core/components receives an array where it expects a scalar, leading to inconsistent selection behaviour and React console warnings when the user interacts with the filter. ``` </details> [](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=0991cd15efbf46ce81b2b26971dedd33&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) [](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=0991cd15efbf46ce81b2b26971dedd33&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) *(Use Cmd/Ctrl + Click for best experience)* <details> <summary><b>Prompt for AI Agent 🤖 </b></summary> ```mdx This is a comment left during a code review. **Path:** superset-frontend/src/filters/components/CustomFilter/CustomFilterPlugin.tsx **Line:** 236:237 **Comment:** *Logic Error: When single-select mode is used, the select component still receives an array as its controlled value. AntD expects a scalar value in non-multiple mode, so this shape mismatch can cause incorrect rendering/selection behavior and controlled-component warnings. Store and pass a scalar in single-select mode (or branch value handling by mode). Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise. Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix ``` </details> <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F42330&comment_hash=627cb2e27f308cfca326dbf5087854e478ecdaacce9c4260a936273feb61f861&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F42330&comment_hash=627cb2e27f308cfca326dbf5087854e478ecdaacce9c4260a936273feb61f861&reaction=dislike'>👎</a> -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
