Skip to content

The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:

2.6 KB
Raw Blame
import { runQuestionQuerySdk } from "embedding-sdk-bundle/lib/sdk-question/run-question-query";
import type {
  NavigateToNewCardParams,
  SdkQuestionState,
} from "embedding-sdk-bundle/types/question";
import { cardIsEquivalent } from "metabase/common/utils/card";
import { selectQuestionFromCard } from "metabase/metadata-store";
import { loadCard } from "metabase/query_builder";
import { loadMetadataForCard } from "metabase/questions/actions";
import type { Dispatch, GetState } from "metabase/redux/store";
import { getCardAfterVisualizationClick } from "metabase/viz-core";
import type Question from "metabase-lib/v1/Question";
import type { ParameterValuesMap } from "metabase-types/api";
import type { EntityToken } from "metabase-types/api/entity";

interface RunQuestionOnNavigateParams extends NavigateToNewCardParams {
  originalQuestion?: Question;
  parameterValues?: ParameterValuesMap;
  isGuestEmbed: boolean;
  token: EntityToken | null | undefined;
  onQuestionChange: (question: Question) => void;
  onClearQueryResults: () => void;
}

export const runQuestionOnNavigateSdk =
  (params: RunQuestionOnNavigateParams) =>
  async (
    dispatch: Dispatch,
    getState: GetState,
  ): Promise<SdkQuestionState | null> => {
    let {
      isGuestEmbed,
      token,
      nextCard,
      previousCard,
      originalQuestion,
      parameterValues,
      signal,
      onQuestionChange,
      onClearQueryResults,
    } = params;

    // Do not reload questions with breakouts when clicking on a legend item
    if (previousCard === nextCard) {
      return null;
    }

    // Fallback when a visualization legend is clicked
    if (cardIsEquivalent(previousCard, nextCard)) {
      // Reload the canonical card only for saved questions. Ad-hoc questions
      // have no id, so keep the card as-is rather than firing
      // `GET /api/card/undefined`.
      if (nextCard.id !== null && nextCard.id !== undefined) {
        nextCard = await loadCard(
          { cardId: nextCard.id },
          { dispatch, getState },
        );
      }
    } else {
      nextCard = getCardAfterVisualizationClick(nextCard, previousCard);
      onClearQueryResults();
    }

    // Optimistic update the UI before we re-fetch the query metadata.
    onQuestionChange(selectQuestionFromCard(getState(), nextCard));

    await dispatch(loadMetadataForCard(nextCard, { token }));

    const state = await runQuestionQuerySdk({
      question: selectQuestionFromCard(getState(), nextCard),
      originalQuestion,
      parameterValues,
      signal,
      isGuestEmbed,
      token,
      dispatch,
    });

    return state;
  };