bito-code-review[bot] commented on code in PR #44276:
URL: https://github.com/apache/superset/pull/44276#discussion_r4052118233


##########
superset-frontend/src/components/Chart/chartReducer.ts:
##########
@@ -138,6 +138,9 @@ export default function chartReducer(
     [actions.UPDATE_QUERY_FORM_DATA](state) {
       return { ...state, latestQueryFormData: action.value };
     },
+    [actions.SET_CHART_FORM_DATA](state) {
+      return { ...state, form_data: action.formData };
+    },

Review Comment:
   <div>
   
   
   <div id="suggestion">
   <div id="issue"><b>State type/contract gap</b></div>
   <div id="fix">
   
   The reducer writes `form_data` into a `ChartState` that doesn't declare that 
field (src/explore/types.ts:50-66); it compiles only because the spread 
suppresses excess-property checks. The dashboard `Chart` type 
(src/dashboard/types.ts:72) does declare `form_data`, so the write is consumed, 
but the reducer's `charts` param is `Record<string, ChartState>` — the produced 
shape is untyped. Add `form_data?: QueryFormData` to `ChartState` so the write 
is type-checked.
   </div>
   
   
   </div>
   
   
   
   
   <small><i>Code Review Run #0a767c</i></small>
   </div>
   
   ---
   Should Bito avoid suggestions like this for future reviews? (<a 
href=https://alpha.bito.ai/home/ai-agents/review-rules>Manage Rules</a>)
   - [ ] Yes, avoid them



##########
superset-frontend/src/core/dashboard/index.ts:
##########
@@ -0,0 +1,229 @@
+/**
+ * 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 { dashboard as dashboardApi } from '@apache-superset/core';
+import { isNativeFilter, makeApi, SupersetClient } from '@superset-ui/core';
+import type {
+  DataMask,
+  Divider,
+  Filter,
+  JsonObject,
+  QueryFormData,
+} from '@superset-ui/core';
+import { omit } from 'lodash-es';
+import { updateComponents } from 'src/dashboard/actions/dashboardLayout';
+import {
+  dashboardInfoChanged,
+  nativeFiltersConfigChanged,
+} from 'src/dashboard/actions/dashboardInfo';
+import { SET_NATIVE_FILTERS_CONFIG_COMPLETE } from 
'src/dashboard/actions/nativeFilters';
+import type { SaveFilterChangesType } from 
'src/dashboard/components/nativeFilters/FiltersConfigModal/types';
+import {
+  updateDataMask,
+  setDataMaskForFilterChangesComplete,
+} from 'src/dataMask/actions';
+import {
+  setChartFormData,
+  triggerQuery,
+} from 'src/components/Chart/chartAction';
+import { applyDefaultFormData } from 'src/explore/store';
+import extractUrlParams from 'src/dashboard/util/extractUrlParams';
+import { store, RootState } from 'src/views/store';
+import { navigation } from '../navigation';
+
+const getState = () => store.getState() as RootState;
+
+// The Redux slices below are retained across an in-SPA navigation, so
+// checking them alone can't tell a still-active dashboard from a stale one
+// left over from before the user navigated to another page.
+const isDashboardActive = (): boolean => navigation.getPage() === 'dashboard';
+
+const requireDashboardId = (): number => {
+  const { id } = getState().dashboardInfo;
+  if (!isDashboardActive() || id == null) {
+    throw new Error('No dashboard is currently active');
+  }
+  return id;
+};
+
+const getDashboardId: typeof dashboardApi.getDashboardId = () =>
+  isDashboardActive() ? (getState().dashboardInfo.id ?? undefined) : undefined;
+
+const getLayout: typeof dashboardApi.getLayout = () =>
+  isDashboardActive()
+    ? { ...(getState().dashboardLayout.present as Record<string, unknown>) }
+    : {};
+
+const updateLayoutNode: typeof dashboardApi.updateLayoutNode = async (
+  nodeId: string,
+  meta: Record<string, unknown>,
+) => {
+  requireDashboardId();
+  const node = getState().dashboardLayout.present[nodeId];
+  if (!node) {
+    throw new Error(`Layout node "${nodeId}" not found`);
+  }
+  // UPDATE_COMPONENTS replaces each keyed entry wholesale (it's not a deep
+  // merge), so the node's other fields must be carried through alongside
+  // the merged meta.
+  store.dispatch(
+    updateComponents({
+      [nodeId]: { ...node, meta: { ...node.meta, ...meta } },
+    }) as any,
+  );
+};
+
+const getCss: typeof dashboardApi.getCss = () =>
+  isDashboardActive() ? (getState().dashboardInfo.css ?? '') : '';
+
+const setCss: typeof dashboardApi.setCss = async (css: string) => {
+  requireDashboardId();
+  store.dispatch(dashboardInfoChanged({ css }));
+};
+
+const getFilters: typeof dashboardApi.getFilters = () => {
+  if (!isDashboardActive()) return [];
+  const { nativeFilters, dataMask } = getState();
+  const filterElements = Object.values(nativeFilters.filters) as Array<
+    Filter | Divider
+  >;
+  return filterElements.filter(isNativeFilter).map(filter => {
+    const mask = dataMask[filter.id];
+    return {
+      id: filter.id,
+      name: filter.name,
+      filterType: filter.filterType,
+      targets: filter.targets,
+      extraFormData: mask?.extraFormData,
+      filterState: mask?.filterState,
+    };
+  });
+};
+
+const updateFilters: typeof dashboardApi.updateFilters = async (
+  updates: dashboardApi.FilterValueUpdate[],
+) => {
+  requireDashboardId();
+  updates.forEach(({ filterId, extraFormData, filterState }) => {
+    const dataMask: DataMask = {};
+    if (extraFormData !== undefined) {
+      dataMask.extraFormData = extraFormData;
+    }
+    if (filterState !== undefined) {
+      dataMask.filterState = filterState;
+    }
+    store.dispatch(updateDataMask(filterId, dataMask));
+  });
+};
+
+const saveFilters: typeof dashboardApi.saveFilters = async (
+  updates: dashboardApi.FilterConfigUpdate[],
+  deletedFilterIds: string[] = [],
+) => {
+  const dashboardId = requireDashboardId();
+  const { filters: currentFilters } = getState().nativeFilters;
+
+  const modified = updates.map(
+    ({ filterId, name, targets, defaultDataMask }) => {
+      const existing = currentFilters[filterId];
+      if (!existing) {
+        throw new Error(`Filter "${filterId}" not found on this dashboard`);
+      }
+      return {
+        ...existing,
+        ...(name !== undefined && { name }),
+        ...(targets !== undefined && { targets }),
+        ...(defaultDataMask !== undefined && { defaultDataMask }),
+      };
+    },
+  ) as SaveFilterChangesType['modified'];
+
+  if (modified.length === 0 && deletedFilterIds.length === 0) {
+    return;
+  }
+
+  const filterChanges: SaveFilterChangesType = {
+    modified,
+    deleted: deletedFilterIds,
+    reordered: [],
+  };
+
+  const putFilters = makeApi<SaveFilterChangesType, { result: Filter[] }>({
+    method: 'PUT',
+    endpoint: `/api/v1/dashboard/${dashboardId}/filters`,
+  });
+  const response = await putFilters(filterChanges);
+  // chartsInScope/tabsInScope are derived from the live layout, not this
+  // save's payload, so keep whatever calculateScopes already computed for
+  // this session instead of overwriting them with the server's copy.
+  const savedFilters = response.result.map(
+    filter => omit(filter, ['chartsInScope', 'tabsInScope']) as Filter,
+  );
+
+  store.dispatch({
+    type: SET_NATIVE_FILTERS_CONFIG_COMPLETE,
+    filterChanges: savedFilters,
+    deletedIds: deletedFilterIds,
+  });
+  store.dispatch(nativeFiltersConfigChanged(savedFilters));
+  store.dispatch(
+    setDataMaskForFilterChangesComplete(filterChanges, currentFilters),
+  );

Review Comment:
   <div>
   
   
   <div id="suggestion">
   <div id="issue"><b>Duplicated save-apply flow</b></div>
   <div id="fix">
   
   The success path here (PUT via `makeApi`, `omit` of 
`chartsInScope`/`tabsInScope`, then the `SET_NATIVE_FILTERS_CONFIG_COMPLETE`, 
`nativeFiltersConfigChanged`, and `setDataMaskForFilterChangesComplete` 
dispatches) duplicates `setFilterConfiguration` in 
`src/dashboard/actions/nativeFilters.ts:87-107` line-for-line, including the 
explanatory comment. Extracting a shared apply-saved-filters helper would keep 
the two save paths from silently diverging.
   </div>
   
   
   </div>
   
   
   
   
   <small><i>Code Review Run #0a767c</i></small>
   </div>
   
   ---
   Should Bito avoid suggestions like this for future reviews? (<a 
href=https://alpha.bito.ai/home/ai-agents/review-rules>Manage Rules</a>)
   - [ ] Yes, avoid them



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