codeant-ai-for-open-source[bot] commented on code in PR #45599:
URL: https://github.com/apache/superset/pull/45599#discussion_r4344068481


##########
superset-frontend/src/filters/components/Condition/utils.ts:
##########
@@ -0,0 +1,218 @@
+/**
+ * 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 {
+  ExtraFormData,
+  QueryObjectFilterClause,
+  ensureIsArray,
+} from '@superset-ui/core';
+import { GenericDataType } from '@apache-superset/core/common';
+import { t } from '@apache-superset/core/translation';
+import {
+  CONDITION_OPERATORS,
+  ConditionOperator,
+  ConditionScalar,
+  ConditionValue,
+  SET_CONDITION_OPERATORS,
+  UNARY_CONDITION_OPERATORS,
+} from './types';
+
+export const isConditionOperator = (op: unknown): op is ConditionOperator =>
+  (CONDITION_OPERATORS as readonly unknown[]).includes(op);
+
+export const isUnaryConditionOperator = (op: ConditionOperator) =>
+  (UNARY_CONDITION_OPERATORS as readonly string[]).includes(op);
+
+export const isSetConditionOperator = (op: ConditionOperator) =>
+  (SET_CONDITION_OPERATORS as readonly string[]).includes(op);
+
+const isBlank = (val: unknown) =>
+  val === undefined || val === null || val === '';
+
+/**
+ * Operators that make sense for a column's generic type. The type comes from
+ * the filter's own query result, so it follows the column if its type changes
+ * in the dataset editor or a semantic layer. An unknown type allows everything
+ * and leaves validation to the database.
+ */
+const OPERATORS_BY_TYPE: Record<GenericDataType, ConditionOperator[]> = {
+  [GenericDataType.String]: [
+    '==',
+    '!=',
+    'IN',
+    'NOT IN',
+    'LIKE',
+    'IS NULL',
+    'IS NOT NULL',
+  ],
+  [GenericDataType.Numeric]: [
+    '==',
+    '!=',
+    '>',
+    '<',
+    '>=',
+    '<=',
+    'IN',
+    'NOT IN',
+    'IS NULL',
+    'IS NOT NULL',
+  ],
+  [GenericDataType.Temporal]: [
+    '==',
+    '!=',
+    '>',
+    '<',
+    '>=',
+    '<=',
+    'IS NULL',
+    'IS NOT NULL',
+  ],
+  [GenericDataType.Boolean]: ['==', '!=', 'IS NULL', 'IS NOT NULL'],
+  [GenericDataType.MultiValue]: ['IS NULL', 'IS NOT NULL'],
+};
+
+export function getAllowedOperators(
+  coltype?: GenericDataType | null,
+): ConditionOperator[] {
+  if (coltype === undefined || coltype === null) {
+    return [...CONDITION_OPERATORS];
+  }
+  return OPERATORS_BY_TYPE[coltype] ?? [...CONDITION_OPERATORS];
+}
+
+/**
+ * A condition is complete when it has everything needed to build a clause:
+ * unary operators need nothing, set operators need at least one value and
+ * every other operator needs a single non-blank value.
+ */
+export function isConditionComplete(
+  value?: ConditionValue | null,
+): value is ConditionValue {
+  if (!value || !isConditionOperator(value.op)) {
+    return false;
+  }
+  if (isUnaryConditionOperator(value.op)) {
+    return true;
+  }
+  if (isSetConditionOperator(value.op)) {
+    return ensureIsArray(value.val).some(val => !isBlank(val));
+  }
+  return !Array.isArray(value.val) && !isBlank(value.val);
+}
+
+/**
+ * Values typed into the filter arrive as strings. Cast them to numbers for
+ * numeric columns so comparisons like `>` behave numerically, and true/false
+ * to booleans for boolean columns. LIKE patterns are always left as strings.
+ */
+export function coerceConditionValue(
+  val: ConditionScalar,
+  op: ConditionOperator,
+  coltype?: GenericDataType,
+): ConditionScalar {
+  if (
+    op !== 'LIKE' &&
+    coltype === GenericDataType.Numeric &&
+    typeof val === 'string' &&
+    val.trim() !== '' &&
+    !Number.isNaN(Number(val))
+  ) {
+    return Number(val);
+  }
+  if (coltype === GenericDataType.Boolean && typeof val === 'string') {
+    const lower = val.trim().toLowerCase();
+    if (lower === 'true' || lower === 'false') {
+      return lower === 'true';
+    }
+  }
+  return val;
+}
+
+const isNumeric = (val: unknown) =>
+  typeof val === 'number' ||
+  (typeof val === 'string' && val.trim() !== '' && !Number.isNaN(Number(val)));

Review Comment:
   ✅ **CodeAnt verified this suggestion was addressed in subsequent commits and 
marked this thread resolved** as of `ce07afa`.
   
   Numeric strings are now checked with `Number.isFinite(Number(val))`, so 
values such as `'1e309'` fail validation instead of being coerced to infinity.
   
   <sub>If that's not right, unresolve this thread and CodeAnt will leave it 
open.</sub>
   
   <!-- codeant-auto-resolve-reply -->



##########
superset-frontend/src/filters/components/Condition/ConditionFilterPlugin.tsx:
##########
@@ -0,0 +1,347 @@
+/**
+ * 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 { t } from '@apache-superset/core/translation';
+import {
+  AppSection,
+  ensureIsArray,
+  finestTemporalGrainFormatter,
+  getColumnLabel,
+} from '@superset-ui/core';
+import { GenericDataType } from '@apache-superset/core/common';
+import { styled } from '@apache-superset/core/theme';
+import { useCallback, useEffect, useMemo, useState } from 'react';
+import { FormItem, Input, Select } from '@superset-ui/core/components';
+import { FilterBarOrientation } from 'src/dashboard/types';
+import { getDataRecordFormatter } from '../../utils';
+import { FilterPluginStyle, StatusMessage } from '../common';
+import {
+  ConditionOperator,
+  ConditionValue,
+  PluginFilterConditionProps,
+} from './types';
+import {
+  getAllowedOperators,
+  getConditionError,
+  getConditionExtraFormData,
+  getConditionLabel,
+  isConditionComplete,
+  isSetConditionOperator,
+  isUnaryConditionOperator,
+} from './utils';
+
+const OPERATOR_LABELS: Record<ConditionOperator, string> = {
+  '==': '=',
+  '!=': '!=',
+  '>': '>',
+  '<': '<',
+  '>=': '>=',
+  '<=': '<=',
+  LIKE: 'LIKE',
+  IN: 'IN',
+  'NOT IN': 'NOT IN',
+  'IS NULL': 'IS NULL',
+  'IS NOT NULL': 'IS NOT NULL',
+};
+
+// Operators that pick from the column's existing values. The rest are
+// free text (comparisons and LIKE patterns rarely match an existing value).
+const PICKER_OPERATORS: ConditionOperator[] = ['==', '!=', 'IN', 'NOT IN'];
+
+// The Select only takes string or number values. Booleans are shown as
+// strings and cast back by coerceConditionValue.
+const toSelectValue = (value: unknown): string | number =>
+  typeof value === 'number' ? value : String(value);
+
+const Wrapper = styled.div<{ horizontal: boolean }>`
+  display: flex;
+  flex-direction: ${({ horizontal }) => (horizontal ? 'row' : 'column')};
+  gap: ${({ theme }) => theme.sizeUnit * 2}px;
+  width: 100%;
+
+  .condition-operator {
+    min-width: ${({ theme }) => theme.sizeUnit * 30}px;
+  }
+
+  .condition-value {
+    flex: 1;
+    min-width: ${({ theme }) => theme.sizeUnit * 40}px;
+  }
+`;
+
+export default function ConditionFilterPlugin(
+  props: PluginFilterConditionProps,
+) {
+  const {
+    data,
+    coltype,
+    formData,
+    height,
+    width,
+    setDataMask,
+    setFocusedFilter,
+    unsetFocusedFilter,
+    setHoveredFilter,
+    unsetHoveredFilter,
+    setFilterActive,
+    filterState,
+    inputRef,
+    appSection,
+    filterBarOrientation = FilterBarOrientation.Vertical,
+    isOverflowingFilterBar,
+    clearAllTrigger,
+    onClearAllComplete,
+  } = props;
+  const { groupby, enableEmptyFilter, defaultValue } = formData;
+  const [col = ''] = ensureIsArray(groupby).map(getColumnLabel);
+
+  const [condition, setCondition] = useState<ConditionValue>(
+    filterState.value ??
+      defaultValue ?? { op: getAllowedOperators(coltype)[0] },
+  );
+
+  // The filter bar overrides validateStatus with its own required-value
+  // check, so errors about the condition itself are computed and shown here.
+  const conditionError = getConditionError(condition, coltype);
+
+  const updateDataMask = useCallback(
+    (next: ConditionValue, { restored = false } = {}) => {
+      if (getConditionError(next, coltype)) {
+        // While the user is typing, keep the last valid condition so Apply
+        // can't silently drop the filter. A restored condition that no longer
+        // fits the column type is cleared so the charts don't receive it.
+        if (restored) {
+          setDataMask({
+            extraFormData: {},
+            filterState: { value: null, label: '', validateStatus: undefined },
+          });
+        }
+        return;
+      }
+      if (isConditionComplete(next)) {
+        setDataMask({
+          extraFormData: getConditionExtraFormData(col, next, coltype),
+          filterState: {
+            value: next,
+            label: getConditionLabel(col, next),
+            validateStatus: undefined,
+          },
+        });
+      } else if (enableEmptyFilter) {
+        setDataMask({
+          extraFormData: {},
+          filterState: {
+            value: null,
+            label: '',
+            validateStatus: 'error',
+            validateMessage: t('Please enter a condition'),
+          },
+        });
+      } else {
+        setDataMask({
+          extraFormData: {},
+          filterState: { value: null, label: '', validateStatus: undefined },
+        });
+      }
+    },
+    [col, coltype, enableEmptyFilter, setDataMask],
+  );
+
+  const handleChange = useCallback(
+    (next: ConditionValue) => {
+      setCondition(next);
+      updateDataMask(next);
+    },
+    [updateDataMask],
+  );
+
+  // Keep local state in sync with external changes (defaults, "Clear all",
+  // permalinks) and make sure a restored value is applied to the charts.
+  useEffect(() => {
+    const value = filterState.value as ConditionValue | null | undefined;
+    if (isConditionComplete(value)) {
+      setCondition(value);
+      updateDataMask(value, { restored: true });
+    } else if (value === null || value === undefined) {
+      // Cleared from outside: keep the chosen operator, drop the value.
+      setCondition(prev => ({ op: prev.op }));

Review Comment:
   ✅ **CodeAnt verified this suggestion was addressed in subsequent commits and 
marked this thread resolved** as of `ce07afa`.
   
   When `filterState.value` is undefined and Clear All is not active, the 
effect now restores a complete `defaultValue` to local state and applies it to 
the charts.
   
   <sub>If that's not right, unresolve this thread and CodeAnt will leave it 
open.</sub>
   
   <!-- codeant-auto-resolve-reply -->



-- 
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]

Reply via email to