You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@superset.apache.org by GitBox <gi...@apache.org> on 2022/07/19 19:46:02 UTC

[GitHub] [superset] ktmud commented on a diff in pull request #20743: feat: Pass dashboard context to explore through local storage

ktmud commented on code in PR #20743:
URL: https://github.com/apache/superset/pull/20743#discussion_r923611803


##########
superset-frontend/src/explore/ExplorePage.tsx:
##########
@@ -57,6 +67,58 @@ const fetchExploreData = async (exploreUrlParams: URLSearchParams) => {
   }
 };
 
+const getDashboardContextFormData = () => {
+  const dashboardTabId = getUrlParam(URL_PARAMS.dashboardTabId);
+  const sliceId = getUrlParam(URL_PARAMS.sliceId) || 0;
+  let dashboardContextWithFilters = {};
+  if (dashboardTabId) {
+    const {
+      labelColors,
+      sharedLabelColors,
+      colorScheme,
+      chartConfiguration,
+      nativeFilters,

Review Comment:
   Is `nativeFilters` the full metadata of all native filters? Do we really need to carry all this information to the Explore page? I don't see it being used here.



##########
superset-frontend/src/dashboard/components/SliceHeaderControls/index.tsx:
##########
@@ -306,13 +307,14 @@ class SliceHeaderControls extends React.PureComponent<
         )}
 
         {this.props.supersetCanExplore && (
-          <Menu.Item
-            key={MENU_KEYS.EXPLORE_CHART}
-            onClick={({ domEvent }) => this.props.onExploreChart(domEvent)}
-          >
-            <Tooltip title={getSliceHeaderTooltip(this.props.slice.slice_name)}>
-              {t('Edit chart')}
-            </Tooltip>
+          <Menu.Item key={MENU_KEYS.EXPLORE_CHART}>
+            <Link to={this.props.exploreUrl ?? '#'}>

Review Comment:
   Instead of `?? '#'` why not just remove the whole link in case url is not available?



##########
superset-frontend/src/dashboard/containers/DashboardPage.tsx:
##########
@@ -82,12 +90,95 @@ type PageProps = {
   idOrSlug: string;
 };
 
+const getDashboardContextLocalStorage = () => {
+  const dashboardsContexts = getItem(
+    LocalStorageKeys.dashboard__explore_context,
+    {},
+  );
+  return Object.fromEntries(
+    Object.entries(dashboardsContexts).filter(
+      ([, value]) => !value.isRedundant,
+    ),
+  );
+};
+
+const updateDashboardTabLocalStorage = (
+  dashboardTabId: string,
+  payload?: Record<string, any>,
+) => {
+  const dashboardsContexts = getDashboardContextLocalStorage();
+  setItem(LocalStorageKeys.dashboard__explore_context, {
+    ...dashboardsContexts,
+    [dashboardTabId]: payload,
+  });
+};
+
+const useSyncDashboardStateWithLocalStorage = () => {
+  const labelColors = useSelector<RootState, JsonObject>(
+    state => state.dashboardInfo?.metadata?.label_colors || {},
+  );
+  const sharedLabelColors = useSelector<RootState, JsonObject>(
+    state => state.dashboardInfo?.metadata?.shared_label_colors || {},
+  );
+  const colorScheme = useSelector<RootState, string>(
+    state => state.dashboardState?.colorScheme,
+  );
+  const chartConfiguration = useSelector<RootState, JsonObject>(
+    state => state.dashboardInfo.metadata?.chart_configuration,
+  );
+  const nativeFilters = useSelector<RootState, Filters>(
+    state => state.nativeFilters.filters,
+  );
+  const dataMask = useSelector<RootState, DataMaskStateWithId>(
+    state => state.dataMask,
+  );
+  const dashboardId = useSelector<RootState, number>(
+    state => state.dashboardInfo.id,
+  );
+  const filterBoxFilters = useSelector<RootState, Record<string, any>>(() =>
+    getActiveFilters(),
+  );
+  const dashboardTabId = useMemo(() => shortid.generate(), []);

Review Comment:
   Can we rename this to `dashboardPageId` to avoid confusion with dashboard tabs?



##########
superset-frontend/src/dashboard/containers/DashboardPage.tsx:
##########
@@ -82,12 +90,95 @@ type PageProps = {
   idOrSlug: string;
 };
 
+const getDashboardContextLocalStorage = () => {
+  const dashboardsContexts = getItem(
+    LocalStorageKeys.dashboard__explore_context,
+    {},
+  );
+  return Object.fromEntries(
+    Object.entries(dashboardsContexts).filter(
+      ([, value]) => !value.isRedundant,
+    ),
+  );
+};
+
+const updateDashboardTabLocalStorage = (
+  dashboardTabId: string,
+  payload?: Record<string, any>,
+) => {
+  const dashboardsContexts = getDashboardContextLocalStorage();
+  setItem(LocalStorageKeys.dashboard__explore_context, {
+    ...dashboardsContexts,
+    [dashboardTabId]: payload,
+  });
+};
+
+const useSyncDashboardStateWithLocalStorage = () => {
+  const labelColors = useSelector<RootState, JsonObject>(
+    state => state.dashboardInfo?.metadata?.label_colors || {},
+  );
+  const sharedLabelColors = useSelector<RootState, JsonObject>(
+    state => state.dashboardInfo?.metadata?.shared_label_colors || {},
+  );
+  const colorScheme = useSelector<RootState, string>(
+    state => state.dashboardState?.colorScheme,
+  );
+  const chartConfiguration = useSelector<RootState, JsonObject>(
+    state => state.dashboardInfo.metadata?.chart_configuration,
+  );
+  const nativeFilters = useSelector<RootState, Filters>(
+    state => state.nativeFilters.filters,
+  );
+  const dataMask = useSelector<RootState, DataMaskStateWithId>(
+    state => state.dataMask,
+  );
+  const dashboardId = useSelector<RootState, number>(
+    state => state.dashboardInfo.id,
+  );
+  const filterBoxFilters = useSelector<RootState, Record<string, any>>(() =>
+    getActiveFilters(),
+  );
+  const dashboardTabId = useMemo(() => shortid.generate(), []);
+
+  useEffect(() => {
+    const payload = {
+      labelColors,
+      sharedLabelColors,
+      colorScheme,
+      chartConfiguration,
+      nativeFilters,
+      dataMask,
+      dashboardId,
+      filterBoxFilters,
+    };
+    updateDashboardTabLocalStorage(dashboardTabId, payload);
+    return () => {
+      updateDashboardTabLocalStorage(dashboardTabId, {
+        ...payload,
+        isRedundant: true,
+      });

Review Comment:
   Instead of adding a `isRedundant` flag, can we just remove it?



##########
superset-frontend/src/dashboard/components/SliceHeader/index.tsx:
##########
@@ -97,6 +98,7 @@ const SliceHeader: FC<SliceHeaderProps> = ({
 }) => {
   const dispatch = useDispatch();
   const uiConfig = useUiConfig();
+  const dashboardTabId = useContext(DashboardTabIdContext);

Review Comment:
   Why do we use a new ReactContext for this? Can this be a Redux state?



##########
superset-frontend/src/dashboard/containers/DashboardPage.tsx:
##########
@@ -82,12 +90,95 @@ type PageProps = {
   idOrSlug: string;
 };
 
+const getDashboardContextLocalStorage = () => {
+  const dashboardsContexts = getItem(
+    LocalStorageKeys.dashboard__explore_context,
+    {},
+  );
+  return Object.fromEntries(
+    Object.entries(dashboardsContexts).filter(
+      ([, value]) => !value.isRedundant,
+    ),
+  );
+};
+
+const updateDashboardTabLocalStorage = (
+  dashboardTabId: string,
+  payload?: Record<string, any>,
+) => {
+  const dashboardsContexts = getDashboardContextLocalStorage();
+  setItem(LocalStorageKeys.dashboard__explore_context, {
+    ...dashboardsContexts,
+    [dashboardTabId]: payload,
+  });
+};
+
+const useSyncDashboardStateWithLocalStorage = () => {
+  const labelColors = useSelector<RootState, JsonObject>(
+    state => state.dashboardInfo?.metadata?.label_colors || {},
+  );
+  const sharedLabelColors = useSelector<RootState, JsonObject>(
+    state => state.dashboardInfo?.metadata?.shared_label_colors || {},
+  );
+  const colorScheme = useSelector<RootState, string>(
+    state => state.dashboardState?.colorScheme,
+  );
+  const chartConfiguration = useSelector<RootState, JsonObject>(
+    state => state.dashboardInfo.metadata?.chart_configuration,
+  );
+  const nativeFilters = useSelector<RootState, Filters>(
+    state => state.nativeFilters.filters,
+  );
+  const dataMask = useSelector<RootState, DataMaskStateWithId>(
+    state => state.dataMask,
+  );
+  const dashboardId = useSelector<RootState, number>(
+    state => state.dashboardInfo.id,
+  );
+  const filterBoxFilters = useSelector<RootState, Record<string, any>>(() =>
+    getActiveFilters(),
+  );

Review Comment:
   Can we consolidate all these into one single state object, and maybe reuse [DashboardPermalinkState](https://github.com/apache/superset/blob/2a705406e1883834bb6696c1585ef65f787ce7b3/superset-frontend/src/dashboard/types.ts#L142-L147) (or at least extend from / consolidate variable names) for it? We can rename it to something like `PersistableDashboardState` if necessary.



##########
superset-frontend/src/explore/controlUtils/getFormDataWithDashboardContext.ts:
##########
@@ -0,0 +1,146 @@
+/**
+ * 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 {
+  EXTRA_FORM_DATA_OVERRIDE_REGULAR_MAPPINGS,
+  EXTRA_FORM_DATA_OVERRIDE_EXTRA_KEYS,
+  isDefined,
+  JsonObject,
+  ensureIsArray,
+  QueryObjectFilterClause,
+  SimpleAdhocFilter,
+} from '@superset-ui/core';
+import { NO_TIME_RANGE } from '../constants';
+
+const simpleFilterToAdhoc = (
+  filterClause: QueryObjectFilterClause,
+  clause = 'where',
+) => {
+  const result = {
+    clause: clause.toUpperCase(),
+    expressionType: 'SIMPLE',
+    operator: filterClause.op,
+    subject: filterClause.col,
+    comparator: 'val' in filterClause ? filterClause.val : undefined,
+  } as SimpleAdhocFilter;
+  if (filterClause.isExtra) {
+    Object.assign(result, {
+      isExtra: true,
+      filterOptionName: `filter_${Math.random()
+        .toString(36)
+        .substring(2, 15)}_${Math.random().toString(36).substring(2, 15)}`,
+    });
+  }
+
+  return result;
+};
+
+const mergeFilterBoxToFormData = (formData: Record<string, any>) => {
+  const dateColumns = {
+    __time_range: 'time_range',
+    __time_col: 'granularity_sqla',
+    __time_grain: 'time_grain_sqla',
+    __granularity: 'granularity',
+  };
+  const appliedTimeExtras = {};
+
+  const newFormData = { ...formData };
+  ensureIsArray(newFormData.extra_filters).forEach(filter => {
+    if (dateColumns[filter.col]) {
+      if (filter.val !== NO_TIME_RANGE) {
+        newFormData[dateColumns[filter.col]] = filter.val;
+        appliedTimeExtras[filter.col] = filter.val;
+      }
+    } else {
+      const adhocFilter = simpleFilterToAdhoc({
+        ...(filter as QueryObjectFilterClause),
+        isExtra: true,
+      });
+      if (!Array.isArray(newFormData.adhocFilters)) {
+        newFormData.adhoc_filters = [adhocFilter];
+      } else if (
+        newFormData.adhoc_filters.some(
+          (existingFilter: SimpleAdhocFilter) =>
+            existingFilter.operator === adhocFilter.operator &&
+            existingFilter.subject === adhocFilter.subject &&
+            ((!('comparator' in existingFilter) &&
+              !('comparator' in adhocFilter)) ||
+              ('comparator' in existingFilter &&
+                'comparator' in adhocFilter &&
+                existingFilter.comparator === adhocFilter.comparator)),
+        )
+      ) {
+        newFormData.adhoc_filters.push(adhocFilter);
+      }
+    }
+  });
+  newFormData.applied_time_extras = appliedTimeExtras;
+  delete newFormData.extra_filters;
+  return newFormData;
+};
+
+export const getFormDataFromDashboardContext = (formData: JsonObject) => {

Review Comment:
   I like this util function!



##########
superset-frontend/src/explore/ExplorePage.tsx:
##########
@@ -57,6 +67,58 @@ const fetchExploreData = async (exploreUrlParams: URLSearchParams) => {
   }
 };
 
+const getDashboardContextFormData = () => {
+  const dashboardTabId = getUrlParam(URL_PARAMS.dashboardTabId);
+  const sliceId = getUrlParam(URL_PARAMS.sliceId) || 0;
+  let dashboardContextWithFilters = {};
+  if (dashboardTabId) {
+    const {
+      labelColors,
+      sharedLabelColors,
+      colorScheme,
+      chartConfiguration,
+      nativeFilters,
+      filterBoxFilters,
+      dataMask,
+      dashboardId,
+    } =
+      getItem(LocalStorageKeys.dashboard__explore_context, {})[
+        dashboardTabId
+      ] || {};
+    dashboardContextWithFilters = getFormDataWithExtraFilters({
+      chart: { id: sliceId },
+      filters: Object.fromEntries(
+        (
+          Object.entries(filterBoxFilters) as [
+            string,
+            {
+              scope: number[];
+              values: DataRecordValue[];
+            },
+          ][]
+        )
+          .filter(([, filter]) => filter.scope.includes(sliceId))
+          .map(([key, filter]) => [
+            getChartIdAndColumnFromFilterKey(key).column,
+            filter.values,
+          ]),

Review Comment:
   Can L90 to L104 be of its own utility function? 



##########
superset-frontend/src/dashboard/components/SliceHeaderControls/index.tsx:
##########
@@ -352,12 +354,10 @@ class SliceHeaderControls extends React.PureComponent<
                 />
               }
               modalFooter={
-                <Button
-                  buttonStyle="secondary"
-                  buttonSize="small"
-                  onClick={this.props.onExploreChart}
-                >
-                  {t('Edit chart')}
+                <Button buttonStyle="secondary" buttonSize="small">
+                  <Link to={this.props.exploreUrl ?? '#'}>
+                    {t('Edit chart')}
+                  </Link>

Review Comment:
   Would `<Link >` actually add an `<a>` inside a button element?
   
   Should we use react-router-dom's `useHistory` instead?
   https://v5.reactrouter.com/web/api/Hooks/usehistory



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org