The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
Add a Refresh button to the embedded question when automatic reruns are off (#83732)
Sébastiendb875cbd2a7a
diff --git a/docs/embedding/question-reference.md b/docs/embedding/question-reference.mdindex 9956c831c2e..f7b4c176085 100644--- a/docs/embedding/question-reference.md+++ b/docs/embedding/question-reference.md@@ -82,6 +82,7 @@ These components are available via the `InteractiveQuestion` namespace (like `<I- [InteractiveQuestion.QuestionSettings](./sdk/api/InteractiveQuestion.html#questionsettings)- [InteractiveQuestion.QuestionSettingsDropdown](./sdk/api/InteractiveQuestion.html#questionsettingsdropdown)- [InteractiveQuestion.QuestionVisualization](./sdk/api/InteractiveQuestion.html#questionvisualization)+- [InteractiveQuestion.RefreshButton](./sdk/api/InteractiveQuestion.html#refreshbutton)- [InteractiveQuestion.ResetButton](./sdk/api/InteractiveQuestion.html#resetbutton)- [InteractiveQuestion.SaveButton](./sdk/api/InteractiveQuestion.html#savebutton)- [InteractiveQuestion.SaveQuestionForm](./sdk/api/InteractiveQuestion.html#savequestionform)diff --git a/enterprise/frontend/src/embedding-sdk-package/components/public/InteractiveQuestion/InteractiveQuestion.tsx b/enterprise/frontend/src/embedding-sdk-package/components/public/InteractiveQuestion/InteractiveQuestion.tsxindex 612db98857e..86f7eb8db52 100644--- a/enterprise/frontend/src/embedding-sdk-package/components/public/InteractiveQuestion/InteractiveQuestion.tsx+++ b/enterprise/frontend/src/embedding-sdk-package/components/public/InteractiveQuestion/InteractiveQuestion.tsx@@ -26,6 +26,11 @@ const subComponents: InteractiveQuestionComponents = {getWindow()?.METABASE_EMBEDDING_SDK_BUNDLE?.InteractiveQuestion?.FilterDropdown,),+ RefreshButton: createComponent(+ () =>+ getWindow()?.METABASE_EMBEDDING_SDK_BUNDLE?.InteractiveQuestion+ ?.RefreshButton,+ ),ResetButton: createComponent(() =>getWindow()?.METABASE_EMBEDDING_SDK_BUNDLE?.InteractiveQuestiondiff --git a/enterprise/frontend/src/embedding-sdk-package/components/public/StaticQuestion/StaticQuestion.tsx b/enterprise/frontend/src/embedding-sdk-package/components/public/StaticQuestion/StaticQuestion.tsxindex cefb53e981c..5615d3abb99 100644--- a/enterprise/frontend/src/embedding-sdk-package/components/public/StaticQuestion/StaticQuestion.tsx+++ b/enterprise/frontend/src/embedding-sdk-package/components/public/StaticQuestion/StaticQuestion.tsx@@ -15,6 +15,10 @@ const subComponents: StaticQuestionComponents = {getWindow()?.METABASE_EMBEDDING_SDK_BUNDLE?.StaticQuestion?.FilterDropdown,),+ RefreshButton: createComponent(+ () =>+ getWindow()?.METABASE_EMBEDDING_SDK_BUNDLE?.StaticQuestion?.RefreshButton,+ ),ResetButton: createComponent(() =>getWindow()?.METABASE_EMBEDDING_SDK_BUNDLE?.StaticQuestion?.ResetButton,diff --git a/enterprise/frontend/src/embedding-sdk-package/index.ts b/enterprise/frontend/src/embedding-sdk-package/index.tsindex ba8509dc4ef..5dc30ed0e56 100644--- a/enterprise/frontend/src/embedding-sdk-package/index.ts+++ b/enterprise/frontend/src/embedding-sdk-package/index.ts@@ -84,6 +84,7 @@ export {type InteractiveQuestionQuestionSettingsProps,type InteractiveQuestionQuestionSettingsDropdownProps,type InteractiveQuestionQuestionVisualizationProps,+ type InteractiveQuestionRefreshButtonProps,type InteractiveQuestionResetButtonProps,type InteractiveQuestionSaveButtonProps,type InteractiveQuestionSaveQuestionFormProps,diff --git a/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/components/RefreshButton/RefreshButton.tsx b/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/components/RefreshButton/RefreshButton.tsxnew file mode 100644index 00000000000..c72e293cc25--- /dev/null+++ b/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/components/RefreshButton/RefreshButton.tsx@@ -0,0 +1,63 @@+import type { MouseEvent, MouseEventHandler } from "react";+import { t } from "ttag";++import { useSdkSelector } from "embedding-sdk-bundle/store";+import { getIsGuestEmbed } from "embedding-sdk-bundle/store/selectors";+import type { CommonStylingProps } from "embedding-sdk-bundle/types/props";+import { transformSdkQuestion } from "metabase/embedding-sdk/lib/transform-question";+import { Button, Icon, Tooltip } from "metabase/ui";++import { useSdkQuestionContext } from "../../context";++/**+ * @interface+ * @expand+ * @category InteractiveQuestion+ */+export type RefreshButtonProps = CommonStylingProps & {+ /**+ * Callback function to be called when the button is clicked+ */+ onClick?: MouseEventHandler<HTMLButtonElement>;+};++/**+ * Button to run the current query. Only appears when automatic reruns are turned off for the database.+ *+ * @function+ * @category InteractiveQuestion+ * @param props+ */+export const RefreshButton = ({+ onClick,+ className,+ style,+}: RefreshButtonProps = {}) => {+ const { question, queryQuestion, isQueryRunning, onRun } =+ useSdkQuestionContext();+ const isGuestEmbed = useSdkSelector(getIsGuestEmbed);++ if (!question || isGuestEmbed || question.canAutoRun()) {+ return null;+ }++ const handleClick = async (e: MouseEvent<HTMLButtonElement>) => {+ onClick?.(e);+ const nextQuestion = await queryQuestion({ ignoreCache: true });+ onRun?.(nextQuestion && transformSdkQuestion(nextQuestion));+ };++ return (+ <Tooltip label={t`Refresh`}>+ <Button+ className={className}+ style={style}+ leftSection={<Icon name="refresh" />}+ aria-label={t`Refresh`}+ data-testid="refresh-button"+ disabled={isQueryRunning}+ onClick={handleClick}+ />+ </Tooltip>+ );+};diff --git a/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/components/RefreshButton/index.ts b/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/components/RefreshButton/index.tsnew file mode 100644index 00000000000..c5e53a26dce--- /dev/null+++ b/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/components/RefreshButton/index.ts@@ -0,0 +1 @@+export * from "./RefreshButton";diff --git a/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/components/index.ts b/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/components/index.tsindex 2a73b5fc2b4..42d2adf3f3e 100644--- a/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/components/index.ts+++ b/frontend/src/embedding-sdk-bundle/components/private/SdkQuestion/components/index.ts@@ -6,6 +6,7 @@ export * from "./DownloadWidget";export * from "./Filter";export * from "./Editor";export * from "./EditorButton";+export * from "./RefreshButton";export * from "./ResetButton";export * from "./SaveButton";export * from "./SdkSaveQuestionForm";diff --git a/frontend/src/embedding-sdk-bundle/components/private/SdkQuestionDefaultView/SdkQuestionDefaultView.tsx b/frontend/src/embedding-sdk-bundle/components/private/SdkQuestionDefaultView/SdkQuestionDefaultView.tsxindex b4f53dce190..cf203fbe6d2 100644--- a/frontend/src/embedding-sdk-bundle/components/private/SdkQuestionDefaultView/SdkQuestionDefaultView.tsx+++ b/frontend/src/embedding-sdk-bundle/components/private/SdkQuestionDefaultView/SdkQuestionDefaultView.tsx@@ -45,6 +45,7 @@ import { Editor } from "../SdkQuestion/components/Editor";import { EditorButton } from "../SdkQuestion/components/EditorButton/EditorButton";import { FilterDropdown } from "../SdkQuestion/components/Filter/FilterDropdown";import { QuestionSettingsDropdown } from "../SdkQuestion/components/QuestionSettings";+import { RefreshButton } from "../SdkQuestion/components/RefreshButton";import { ResultToolbar } from "../SdkQuestion/components/ResultToolbar/ResultToolbar";import {SaveButton,@@ -273,6 +274,7 @@ export const SdkQuestionDefaultView = ({<QuestionAlertsButton /></>)}+ {!isEditorOpen && <RefreshButton />}{withEditorButton && (<EditorButton isOpen={isEditorOpen} onClick={toggleEditor} />)}diff --git a/frontend/src/embedding-sdk-bundle/components/public/InteractiveQuestion/InteractiveQuestion.tsx b/frontend/src/embedding-sdk-bundle/components/public/InteractiveQuestion/InteractiveQuestion.tsxindex 3c234145b20..89a8525c9e0 100644--- a/frontend/src/embedding-sdk-bundle/components/public/InteractiveQuestion/InteractiveQuestion.tsx+++ b/frontend/src/embedding-sdk-bundle/components/public/InteractiveQuestion/InteractiveQuestion.tsx@@ -21,6 +21,7 @@ import {QuestionSettings,QuestionSettingsDropdown,QuestionVisualization,+ RefreshButton,SaveButton,SdkSaveQuestionForm,SqlParametersList,@@ -78,6 +79,7 @@ export type InteractiveQuestionComponents = {Filter: typeof Filter;FilterDropdown: typeof FilterDropdown;ResetButton: typeof QuestionResetButton;+ RefreshButton: typeof RefreshButton;Title: typeof Title;Summarize: typeof Summarize;SummarizeDropdown: typeof SummarizeDropdown;@@ -179,6 +181,7 @@ const subComponents: InteractiveQuestionComponents = {Filter: Filter,FilterDropdown: FilterDropdown,ResetButton: QuestionResetButton,+ RefreshButton: RefreshButton,Title: Title,Summarize: Summarize,SummarizeDropdown: SummarizeDropdown,diff --git a/frontend/src/embedding-sdk-bundle/components/public/SdkQuestion/SdkQuestion.RefreshButton.unit.spec.tsx b/frontend/src/embedding-sdk-bundle/components/public/SdkQuestion/SdkQuestion.RefreshButton.unit.spec.tsxnew file mode 100644index 00000000000..9f46e0f67c7--- /dev/null+++ b/frontend/src/embedding-sdk-bundle/components/public/SdkQuestion/SdkQuestion.RefreshButton.unit.spec.tsx@@ -0,0 +1,128 @@+import userEvent from "@testing-library/user-event";+import fetchMock from "fetch-mock";++import {+ setupAlertsEndpoints,+ setupCardEndpoints,+ setupCardQueryEndpoints,+ setupCardQueryMetadataEndpoint,+ setupCollectionByIdEndpoint,+ setupDatabaseEndpoints,+ setupTableEndpoints,+} from "__support__/server-mocks";+import { screen, waitFor } from "__support__/ui";+import { renderWithSDKProviders } from "embedding-sdk-bundle/test/__support__/ui";+import { createMockSdkConfig } from "embedding-sdk-bundle/test/mocks/config";+import { setupSdkState } from "embedding-sdk-bundle/test/server-mocks/sdk-init";+import {+ createMockCard,+ createMockCardQueryMetadata,+ createMockCollection,+ createMockColumn,+ createMockDatabase,+ createMockDataset,+ createMockDatasetData,+ createMockTable,+ createMockUser,+} from "metabase-types/api/mocks";++import { SdkQuestion } from "./SdkQuestion";++const TEST_USER = createMockUser();+const TEST_DB_ID = 1;++const TEST_TABLE_ID = 1;+const TEST_TABLE = createMockTable({ id: TEST_TABLE_ID, db_id: TEST_DB_ID });++const TEST_COLUMN = createMockColumn({+ display_name: "Test Column",+ name: "Test Column",+});++const TEST_DATASET = createMockDataset({+ data: createMockDatasetData({+ cols: [TEST_COLUMN],+ rows: [["Test Row"]],+ }),+});++const setup = ({ autoRunQueries }: { autoRunQueries: boolean }) => {+ const onRun = jest.fn();+ const testDb = createMockDatabase({+ id: TEST_DB_ID,+ auto_run_queries: autoRunQueries,+ });+ const { state } = setupSdkState({+ currentUser: TEST_USER,+ });++ const card = createMockCard({ enable_embedding: true });++ setupCardEndpoints(card);+ setupCardQueryMetadataEndpoint(+ card,+ createMockCardQueryMetadata({+ databases: [testDb],+ tables: [TEST_TABLE],+ }),+ );+ setupAlertsEndpoints(card, []);+ setupDatabaseEndpoints(testDb);+ setupTableEndpoints(TEST_TABLE);+ setupCardQueryEndpoints(card, TEST_DATASET);+ setupCollectionByIdEndpoint({+ collections: [createMockCollection({ id: 1, can_write: true })],+ });++ const queryPath = `path:/api/card/${card.id}/query`;++ renderWithSDKProviders(+ <SdkQuestion questionId={card.id} onRun={onRun}>+ <SdkQuestion.Title />+ <SdkQuestion.RefreshButton />+ </SdkQuestion>,+ {+ componentProviderProps: {+ authConfig: createMockSdkConfig(),+ },+ storeInitialState: state,+ },+ );++ const lastQueryBody = async () => {+ const [lastCall] = fetchMock.callHistory.calls(queryPath).slice(-1);+ return lastCall?.request?.clone().json();+ };++ return {+ onRun,+ lastQueryBody,+ queryCalls: () => fetchMock.callHistory.calls(queryPath).length,+ };+};++describe("SdkQuestion.RefreshButton", () => {+ it("should not render when automatic reruns are on", async () => {+ setup({ autoRunQueries: true });++ expect(await screen.findByText("Question")).toBeInTheDocument();+ expect(screen.queryByTestId("refresh-button")).not.toBeInTheDocument();+ });++ it("should rerun the query when automatic reruns are off", async () => {+ const { queryCalls, onRun, lastQueryBody } = setup({+ autoRunQueries: false,+ });++ const button = await screen.findByTestId("refresh-button");+ await waitFor(() => expect(queryCalls()).toBe(1));++ expect(onRun).not.toHaveBeenCalled();++ await userEvent.click(button);++ await waitFor(() => expect(queryCalls()).toBe(2));+ await waitFor(() => expect(onRun).toHaveBeenCalledTimes(1));+ expect(await lastQueryBody()).toMatchObject({ ignore_cache: true });+ });+});diff --git a/frontend/src/embedding-sdk-bundle/components/public/SdkQuestion/SdkQuestion.tsx b/frontend/src/embedding-sdk-bundle/components/public/SdkQuestion/SdkQuestion.tsxindex 8d39f201992..87e36b5d3e9 100644--- a/frontend/src/embedding-sdk-bundle/components/public/SdkQuestion/SdkQuestion.tsx+++ b/frontend/src/embedding-sdk-bundle/components/public/SdkQuestion/SdkQuestion.tsx@@ -18,6 +18,7 @@ import {QuestionSettings,QuestionSettingsDropdown,QuestionVisualization,+ RefreshButton,SaveButton,SdkSaveQuestionForm,SqlParametersList,@@ -101,6 +102,7 @@ export type SdkQuestionComponents = {Filter: typeof Filter;FilterDropdown: typeof FilterDropdown;ResetButton: typeof QuestionResetButton;+ RefreshButton: typeof RefreshButton;Title: typeof Title;Summarize: typeof Summarize;SummarizeDropdown: typeof SummarizeDropdown;@@ -240,6 +242,7 @@ const subComponents: SdkQuestionComponents = {Filter: Filter,FilterDropdown: FilterDropdown,ResetButton: QuestionResetButton,+ RefreshButton: RefreshButton,Title: Title,Summarize: Summarize,SummarizeDropdown: SummarizeDropdown,diff --git a/frontend/src/embedding-sdk-bundle/components/public/SdkQuestion/index.ts b/frontend/src/embedding-sdk-bundle/components/public/SdkQuestion/index.tsindex 3cfb87c69c7..a1a24bee389 100644--- a/frontend/src/embedding-sdk-bundle/components/public/SdkQuestion/index.ts+++ b/frontend/src/embedding-sdk-bundle/components/public/SdkQuestion/index.ts@@ -12,6 +12,7 @@ export {type QuestionSettingsProps as InteractiveQuestionQuestionSettingsProps,type QuestionSettingsDropdownProps as InteractiveQuestionQuestionSettingsDropdownProps,type QuestionVisualizationProps as InteractiveQuestionQuestionVisualizationProps,+ type RefreshButtonProps as InteractiveQuestionRefreshButtonProps,type ResetButtonProps as InteractiveQuestionResetButtonProps,type SaveButtonProps as InteractiveQuestionSaveButtonProps,type SaveQuestionFormProps as InteractiveQuestionSaveQuestionFormProps,diff --git a/frontend/src/embedding-sdk-bundle/components/public/StaticQuestion/StaticQuestion.tsx b/frontend/src/embedding-sdk-bundle/components/public/StaticQuestion/StaticQuestion.tsxindex cf7bfad1c32..691c3e0ea49 100644--- a/frontend/src/embedding-sdk-bundle/components/public/StaticQuestion/StaticQuestion.tsx+++ b/frontend/src/embedding-sdk-bundle/components/public/StaticQuestion/StaticQuestion.tsx@@ -17,6 +17,7 @@ import {QuestionSettings,QuestionSettingsDropdown,QuestionVisualization,+ RefreshButton,SqlParametersList,Summarize,SummarizeDropdown,@@ -89,6 +90,7 @@ export type StaticQuestionComponents = {Filter: typeof Filter;FilterDropdown: typeof FilterDropdown;ResetButton: typeof QuestionResetButton;+ RefreshButton: typeof RefreshButton;Title: typeof Title;Summarize: typeof Summarize;SummarizeDropdown: typeof SummarizeDropdown;@@ -240,6 +242,7 @@ const subComponents: StaticQuestionComponents = {Filter: Filter,FilterDropdown: FilterDropdown,ResetButton: QuestionResetButton,+ RefreshButton: RefreshButton,Title: Title,Summarize: Summarize,SummarizeDropdown: SummarizeDropdown,diff --git a/frontend/src/embedding-sdk-bundle/hooks/private/use-load-question.ts b/frontend/src/embedding-sdk-bundle/hooks/private/use-load-question.tsindex f9779f17af0..d17c59a23b0 100644--- a/frontend/src/embedding-sdk-bundle/hooks/private/use-load-question.ts+++ b/frontend/src/embedding-sdk-bundle/hooks/private/use-load-question.ts@@ -39,7 +39,9 @@ export interface LoadQuestionHookResult {isQuestionLoading: boolean;isQueryRunning: boolean;- queryQuestion(): Promise<Question | undefined>;+ queryQuestion(options?: {+ ignoreCache?: boolean;+ }): Promise<Question | undefined>;loadAndQueryQuestion(): LoadQuestionResult;@@ -197,32 +199,36 @@ export function useLoadQuestion({initialVisualization,]);- const [runQuestionState, queryQuestion] = useAsyncFn(async () => {- if (!question) {- return;- }+ const [runQuestionState, queryQuestion] = useAsyncFn(+ async (options?: { ignoreCache?: boolean }) => {+ if (!question) {+ return;+ }- const state = await runQuestionQuerySdk({+ const state = await runQuestionQuerySdk({+ question,+ isGuestEmbed,+ token,+ originalQuestion,+ parameterValues,+ signal: nextSignal(),+ dispatch,+ ignoreCache: options?.ignoreCache,+ });++ mergeQuestionState(state);++ return state.question;+ },+ [+ dispatch,question,isGuestEmbed,token,originalQuestion,parameterValues,- signal: nextSignal(),- dispatch,- });-- mergeQuestionState(state);-- return state.question;- }, [- dispatch,- question,- isGuestEmbed,- token,- originalQuestion,- parameterValues,- ]);+ ],+ );const [updateQuestionState, updateQuestion] = useAsyncFn(async (nextQuestion: Question, options: { run?: boolean }) => {diff --git a/frontend/src/embedding-sdk-bundle/lib/sdk-question/run-question-query.ts b/frontend/src/embedding-sdk-bundle/lib/sdk-question/run-question-query.tsindex d44430e08b9..c0cc9c24293 100644--- a/frontend/src/embedding-sdk-bundle/lib/sdk-question/run-question-query.ts+++ b/frontend/src/embedding-sdk-bundle/lib/sdk-question/run-question-query.ts@@ -21,6 +21,7 @@ interface RunQuestionQueryParams {signal?: AbortSignal;dispatch: Dispatch;initialVisualization?: QueryVisualizationDisplayType;+ ignoreCache?: boolean;}export async function runQuestionQuerySdk(@@ -35,6 +36,7 @@ export async function runQuestionQuerySdk(signal,dispatch,initialVisualization,+ ignoreCache = false,} = params;if (question.isSaved()) {@@ -92,7 +94,7 @@ export async function runQuestionQuerySdk(runQuestionQuery(question, {dispatch,signal,- ignoreCache: false,+ ignoreCache,isDirty: isQueryDirty,token,...(isGuestEmbed && {