sadpandajoe commented on code in PR #44276:
URL: https://github.com/apache/superset/pull/44276#discussion_r4138305687


##########
superset-frontend/src/core/dashboard/index.ts:
##########
@@ -0,0 +1,214 @@
+/**
+ * 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 { updateComponents } from 'src/dashboard/actions/dashboardLayout';
+import { dashboardInfoChanged } from 'src/dashboard/actions/dashboardInfo';
+import { applySavedFilterChanges } from 'src/dashboard/actions/nativeFilters';
+import type { SaveFilterChangesType } from 
'src/dashboard/components/nativeFilters/FiltersConfigModal/types';
+import { updateDataMask } 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 } : {};
+
+const getActiveTabs: typeof dashboardApi.getActiveTabs = () =>
+  isDashboardActive() ? [...(getState().dashboardState.activeTabs ?? [])] : [];
+
+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);
+  applySavedFilterChanges(
+    store.dispatch,
+    filterChanges,
+    response.result,
+    currentFilters,
+  );
+};
+
+const refreshChart: typeof dashboardApi.refreshChart = async (
+  chartId: number,
+) => {
+  const dashboardId = requireDashboardId();
+  if (!getState().charts[chartId]) {
+    throw new Error(`Chart ${chartId} is not on the current dashboard`);
+  }
+
+  const { json } = await SupersetClient.get({
+    endpoint: `/api/v1/dashboard/${dashboardId}/charts`,
+  });
+  const chartEntity = (
+    json?.result as { id: number; form_data?: JsonObject }[]
+  )?.find(({ id }) => id === chartId);
+  if (!chartEntity?.form_data) {
+    throw new Error(`Could not load chart ${chartId}'s current configuration`);
+  }
+
+  const formData = applyDefaultFormData({
+    ...chartEntity.form_data,
+    url_params: {
+      ...(chartEntity.form_data.url_params as JsonObject),
+      ...extractUrlParams('regular'),
+    },
+  } as Parameters<typeof applyDefaultFormData>[0]) as QueryFormData;
+
+  store.dispatch(setChartFormData(formData, chartId));
+  store.dispatch(triggerQuery(true, chartId));

Review Comment:
   `refreshChart()` resolves immediately after dispatching this action, 
although the public contract says its promise resolves once the chart has 
re-queried and re-rendered. An extension awaiting it before reading or 
capturing the chart can still observe stale output; can this wait for the query 
lifecycle instead?



##########
superset-frontend/src/core/explore/index.ts:
##########
@@ -0,0 +1,137 @@
+/**
+ * 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 { explore as exploreApi } from '@apache-superset/core';
+import type {
+  ChartDataResponseResult,
+  JsonObject,
+  QueryFormData,
+} from '@superset-ui/core';
+import { setControlValue } from 'src/explore/actions/exploreActions';
+import { getVisibleFormDataFromControls } from 'src/explore/controlUtils';
+import { requestChartDataResolved } from 'src/components/Chart/chartAction';
+import { store, RootState } from 'src/views/store';
+import { navigation } from '../navigation';
+
+const getExploreState = () => (store.getState() as RootState).explore;
+
+// The Redux slice below is retained across an in-SPA navigation, so
+// checking it alone can't tell a still-active chart from a stale one left
+// over from before the user navigated to another page.
+const isExploreActive = (): boolean => navigation.getPage() === 'explore';
+
+const getChartId: typeof exploreApi.getChartId = () =>
+  isExploreActive()
+    ? (getExploreState().slice?.slice_id ?? undefined)
+    : undefined;
+
+const getControlValues: typeof exploreApi.getControlValues = () =>
+  isExploreActive()
+    ? { ...(getExploreState().form_data as Record<string, unknown>) }
+    : {};
+
+const getControlValue: typeof exploreApi.getControlValue = (name: string) =>
+  isExploreActive()
+    ? (getExploreState().form_data as Record<string, unknown>)[name]
+    : undefined;
+
+// Explore queries with the form data derived from the current `controls`
+// state (see ExploreViewContainer's mapStateToProps), not the 
pre-normalization
+// `form_data` slice, which can lag behind controls filled in by defaults or by
+// mapStateToProps. Sharing getVisibleFormDataFromControls with
+// mapStateToProps keeps getQuery()/getChartData() describing the same data
+// as the chart on screen.
+const getCurrentFormData = (): QueryFormData => {
+  const { controls, hiddenFormData } = getExploreState();
+  return getVisibleFormDataFromControls(controls ?? {}, hiddenFormData);
+};
+
+// Mirrors the currently-applied server-side state (e.g. a Table chart's
+// current page) that Explore keeps in `dataMask` rather than `form_data`, so
+// a paginated chart's exported query/data matches what's on screen.
+const getOwnState = (chartId: number | undefined): JsonObject | undefined =>
+  chartId != null
+    ? (store.getState() as RootState).dataMask[chartId]?.ownState
+    : undefined;
+
+const requireFormData = (): QueryFormData => {
+  const formData = getCurrentFormData();
+  if (!isExploreActive() || !formData?.datasource) {
+    throw new Error('No chart is currently loaded in Explore');
+  }
+  return formData;
+};
+
+const setControlValues: typeof exploreApi.setControlValues = async (
+  values: Record<string, unknown>,
+) => {
+  requireFormData();
+  Object.entries(values).forEach(([controlName, value]) => {
+    store.dispatch(
+      setControlValue(controlName, value, undefined, { programmatic: true }),
+    );
+  });
+};
+
+const getQuery: typeof exploreApi.getQuery = async () => {
+  const formData = requireFormData();
+  // With GLOBAL_ASYNC_QUERIES enabled, an uncached request comes back as a
+  // 202 job envelope rather than the result array, so this must go through
+  // the same async-response handling as a normal chart query.
+  const results = await requestChartDataResolved({
+    formData,
+    resultFormat: 'json',
+    resultType: 'query',
+    ownState: getOwnState(getChartId()),
+  });
+  const result = results?.[0] as ChartDataResponseResult | undefined;
+  if (!result || result.error) {
+    throw new Error(result?.error ?? 'Failed to retrieve the query');
+  }
+  return result.query;
+};
+
+const getChartData: typeof exploreApi.getChartData = async () => {
+  const formData = requireFormData();
+  // With GLOBAL_ASYNC_QUERIES enabled, an uncached request comes back as a
+  // 202 job envelope rather than the result array, so this must go through
+  // the same async-response handling as a normal chart query.
+  const results = await requestChartDataResolved({
+    formData,
+    resultFormat: 'json',
+    resultType: 'full',
+    ownState: getOwnState(getChartId()),
+  });
+  const result = results?.[0] as ChartDataResponseResult | undefined;

Review Comment:
   This drops every result after `results[0]`, so an extension reading a Mixed 
Timeseries chart can silently omit a series and miss an error returned by its 
second query. Could this API either represent all query results or reject 
charts whose data cannot be represented by this return type?



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