msyavuz commented on code in PR #35343:
URL: https://github.com/apache/superset/pull/35343#discussion_r2413667129


##########
superset-frontend/plugins/plugin-chart-ag-grid-table/src/AgGridTable/index.tsx:
##########
@@ -257,6 +318,24 @@ const AgGridDataTable: FunctionComponent<AgGridTableProps> 
= memo(
     const onGridReady = (params: GridReadyEvent) => {
       // This will make columns fill the grid width
       params.api.sizeColumnsToFit();
+
+      // Restore saved AG Grid state from permalink if available
+      if (savedAgGridState && params.api) {
+        try {
+          if (savedAgGridState.columnState) {
+            params.api.applyColumnState?.({
+              state: savedAgGridState.columnState as any,
+              applyOrder: true,
+            });
+          }
+
+          if (savedAgGridState.filterModel) {
+            params.api.setFilterModel?.(savedAgGridState.filterModel);
+          }
+        } catch (error) {
+          console.warn('Error restoring AG Grid state:', error);

Review Comment:
   Should user be notified of this?



##########
superset-frontend/src/dashboard/components/menu/ShareMenuItems/index.tsx:
##########
@@ -58,20 +58,39 @@ export const useShareMenuItems = (props: 
ShareMenuItemProps): MenuItem => {
     disabled,
     ...rest
   } = props;
-  const { dataMask, activeTabs } = useSelector(
+  const { dataMask, activeTabs, chartStates, sliceEntities } = useSelector(
     (state: RootState) => ({
       dataMask: state.dataMask,
       activeTabs: state.dashboardState.activeTabs,
+      chartStates: state.dashboardState.chartStates,
+      sliceEntities: state.sliceEntities,
     }),
     shallowEqual,
   );
 
   async function generateUrl() {
+    // Check if dashboard has AG Grid tables
+    const hasAgGridTables =
+      sliceEntities &&
+      Object.values(sliceEntities).some(
+        slice =>
+          slice &&
+          typeof slice === 'object' &&
+          'viz_type' in slice &&
+          slice.viz_type === 'ag_grid_table',
+      );
+

Review Comment:
   That was used before, can we extract it out to a seperate function?



##########
superset-frontend/plugins/plugin-chart-ag-grid-table/src/buildQuery.ts:
##########
@@ -218,15 +218,79 @@ const buildQuery: BuildQuery<TableChartFormData> = (
       sortByFromOwnState = [[sortByItem?.key, !sortByItem?.desc]];
     }
 
+    // Note: In Superset, "columns" are dimensions and "metrics" are measures,
+    // but AG Grid treats them all as "columns" in the UI
+    let orderedColumns = columns;
+    let orderedMetrics = metrics;
+
+    if (
+      isDownloadQuery &&
+      ownState.columnOrder &&
+      Array.isArray(ownState.columnOrder)
+    ) {
+      const orderedCols: typeof columns = [];
+      const orderedMets: typeof metrics = [];
+
+      ownState.columnOrder.forEach((colId: string) => {
+        const matchingCol = columns.find(col => {
+          if (typeof col === 'string') {
+            return col === colId;
+          }
+          return col?.sqlExpression === colId || col?.label === colId;
+        });
+
+        if (matchingCol && !orderedCols.includes(matchingCol)) {
+          orderedCols.push(matchingCol);
+          return;
+        }
+
+        const matchingMetric = metrics?.find(met => {
+          if (typeof met === 'string') {
+            return met === colId;
+          }
+          return getMetricLabel(met) === colId || met?.label === colId;
+        });
+
+        if (matchingMetric && !orderedMets.includes(matchingMetric)) {
+          orderedMets.push(matchingMetric);
+        }
+      });
+
+      columns.forEach(col => {
+        if (!orderedCols.includes(col)) {
+          orderedCols.push(col);
+        }
+      });
+
+      metrics?.forEach(met => {
+        if (!orderedMets.includes(met)) {
+          orderedMets.push(met);
+        }
+      });
+
+      orderedColumns = orderedCols;
+      orderedMetrics = orderedMets;
+    }

Review Comment:
   It looks like there might be some improvements that we can do here. Maybe 
using maps and drying up a bit could identify some improvements?



##########
superset-frontend/plugins/plugin-chart-ag-grid-table/src/AgGridTable/index.tsx:
##########
@@ -313,7 +392,14 @@ const AgGridDataTable: FunctionComponent<AgGridTableProps> 
= memo(
           rowSelection="multiple"
           animateRows
           onCellClicked={handleCrossFilter}
+          onDragStopped={handleGridStateChange}
+          onColumnResized={handleGridStateChange}
+          onSortChanged={handleGridStateChange}
+          onFilterChanged={handleGridStateChange}
+          onColumnVisible={handleGridStateChange}
+          onColumnPinned={handleGridStateChange}

Review Comment:
   Is there no general onChange prop for this?



##########
superset-frontend/src/embedded/api.tsx:
##########
@@ -46,28 +48,49 @@ const getDashboardPermalink = async ({
   anchor: string;
 }): Promise<string> => {
   const state = store?.getState();
-  const { dashboardId, dataMask, activeTabs } = {
+  const { dashboardId, dataMask, activeTabs, chartStates, sliceEntities } = {
     dashboardId:
       state?.dashboardInfo?.id || bootstrapData?.embedded!.dashboard_id,
     dataMask: state?.dataMask,
     activeTabs: state.dashboardState?.activeTabs,
+    chartStates: state.dashboardState?.chartStates,
+    sliceEntities: state?.sliceEntities,
   };
 
+  const hasAgGridTables =
+    sliceEntities &&
+    Object.values(sliceEntities).some(
+      slice =>
+        slice &&
+        typeof slice === 'object' &&
+        'viz_type' in slice &&
+        slice.viz_type === 'ag_grid_table',
+    );

Review Comment:
   Yep, this is the third usage so we should definitely extract this out



##########
superset-frontend/src/dashboard/components/gridComponents/Chart/Chart.jsx:
##########
@@ -378,20 +392,139 @@ const Chart = props => {
         slice_id: slice.slice_id,
         is_cached: isCached,
       });
+
+      let ownState = dataMask[props.id]?.ownState || {};
+
+      // For AG Grid tables, convert AG Grid state to backend-compatible format
+      if (slice.viz_type === 'ag-grid-table' && chartStates[props.id]?.state) {
+        const agGridState = chartStates[props.id].state;
+
+        // Convert AG Grid sortModel to backend sortBy format
+        if (agGridState.sortModel && agGridState.sortModel.length > 0) {
+          const sortItem = agGridState.sortModel[0];
+          ownState = {
+            ...ownState,
+            sortBy: [
+              {
+                id: sortItem.colId,
+                key: sortItem.colId,
+                desc: sortItem.sort === 'desc',
+              },
+            ],
+          };
+        }
+
+        // Store column order for backend processing
+        if (agGridState.columnState && agGridState.columnState.length > 0) {
+          ownState = {
+            ...ownState,
+            columnOrder: agGridState.columnState.map(col => col.colId),
+          };
+        }
+
+        if (
+          agGridState.filterModel &&
+          Object.keys(agGridState.filterModel).length > 0
+        ) {
+          const agGridFilters = [];
+
+          Object.keys(agGridState.filterModel).forEach(colId => {
+            const filter = agGridState.filterModel[colId];
+
+            // Text filter
+            if (filter.filterType === 'text' && filter.filter) {
+              const clause = {
+                expressionType: 'SIMPLE',
+                subject: colId,
+                operator:
+                  filter.type === 'equals'
+                    ? '=='
+                    : filter.type === 'notEqual'
+                      ? '!='
+                      : filter.type === 'contains'
+                        ? 'ILIKE'
+                        : filter.type === 'notContains'
+                          ? 'NOT ILIKE'
+                          : filter.type === 'startsWith'
+                            ? 'ILIKE'
+                            : filter.type === 'endsWith'
+                              ? 'ILIKE'
+                              : 'ILIKE',
+                comparator:
+                  filter.type === 'contains' || filter.type === 'notContains'
+                    ? `%${filter.filter}%`
+                    : filter.type === 'startsWith'
+                      ? `${filter.filter}%`
+                      : filter.type === 'endsWith'
+                        ? `%${filter.filter}`
+                        : filter.filter,
+              };
+              agGridFilters.push(clause);
+            } else if (
+              filter.filterType === 'number' &&
+              filter.filter !== undefined
+            ) {
+              const clause = {
+                expressionType: 'SIMPLE',
+                subject: colId,
+                operator:
+                  filter.type === 'equals'
+                    ? '=='
+                    : filter.type === 'notEqual'
+                      ? '!='
+                      : filter.type === 'lessThan'
+                        ? '<'
+                        : filter.type === 'lessThanOrEqual'
+                          ? '<='
+                          : filter.type === 'greaterThan'
+                            ? '>'
+                            : filter.type === 'greaterThanOrEqual'
+                              ? '>='
+                              : '==',
+                comparator: filter.filter,
+              };
+              agGridFilters.push(clause);
+            } else if (
+              filter.filterType === 'set' &&
+              Array.isArray(filter.values) &&
+              filter.values.length > 0
+            ) {
+              const clause = {
+                expressionType: 'SIMPLE',
+                subject: colId,
+                operator: 'IN',
+                comparator: filter.values,
+              };
+              agGridFilters.push(clause);
+            }
+          });
+
+          if (agGridFilters.length > 0) {
+            ownState = {
+              ...ownState,
+              agGridFilters,
+            };
+          }
+        }
+      }

Review Comment:
   Should this be on the backend instead?



##########
superset-frontend/src/dashboard/types/chartState.ts:
##########
@@ -0,0 +1,65 @@
+/**
+ * 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.
+ */
+
+export interface AgGridColumnState {
+  colId: string;
+  width?: number;
+  hide?: boolean;
+  pinned?: 'left' | 'right' | null;
+  sort?: 'asc' | 'desc' | null;
+  sortIndex?: number;
+  aggFunc?: string;
+}
+
+export interface AgGridSortModel {
+  colId: string;
+  sort: 'asc' | 'desc';
+  sortIndex?: number;
+}
+
+export interface AgGridFilterModel {
+  [colId: string]: {
+    filterType: string;
+    type?: string;
+    filter?: any;
+    condition1?: any;
+    condition2?: any;
+    operator?: string;
+  };
+}
+
+export interface AgGridChartState {
+  columnState: AgGridColumnState[];
+  sortModel: AgGridSortModel[];
+  filterModel: AgGridFilterModel;
+  columnOrder?: string[];
+  pageSize?: number;
+  currentPage?: number;
+}
+
+export interface ChartState {
+  chartId: number;
+  vizType: string;
+  state: AgGridChartState;
+  lastModified?: number;
+}

Review Comment:
   Agree with the bot on this one. Maybe we should call `state` type some 
generic interface instead of `AgGridChartState`?



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