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
import {
type CSSProperties,
type PropsWithChildren,
type ReactNode,
useCallback,
useEffect,
useId,
useMemo,
useRef,
useState,
} from "react";
import { useUnmount } from "react-use";
import { match } from "ts-pattern";
import { t } from "ttag";
import { isEqual } from "underscore";
import {
DashboardNotFoundError,
SdkError,
SdkLoader,
withPublicComponentWrapper,
} from "embedding-sdk-bundle/components/private/PublicComponentWrapper";
import { SdkAdHocQuestion } from "embedding-sdk-bundle/components/private/SdkAdHocQuestion";
import { useSdkInternalNavigationOptional } from "embedding-sdk-bundle/components/private/SdkInternalNavigation/context";
import { SdkQuestion } from "embedding-sdk-bundle/components/public/SdkQuestion/SdkQuestion";
import { DashboardSubscriptionsButton } from "embedding-sdk-bundle/components/public/notifications/DashboardSubscriptionsButton";
import { useDashboardLoadHandlers } from "embedding-sdk-bundle/hooks/private/use-dashboard-load-handlers";
import { useExtractResourceIdFromJwtToken } from "embedding-sdk-bundle/hooks/private/use-extract-resource-id-from-jwt-token";
import { useSdkBreadcrumbs } from "embedding-sdk-bundle/hooks/private/use-sdk-breadcrumb";
import { useSdkControlledParameters } from "embedding-sdk-bundle/hooks/private/use-sdk-controlled-parameters";
import {
type SdkDashboardDisplayProps,
useSdkDashboardParams,
} from "embedding-sdk-bundle/hooks/private/use-sdk-dashboard-params";
import { useSetupContentTranslations } from "embedding-sdk-bundle/hooks/private/use-setup-content-translations";
import { useWarnConflictingParameterProps } from "embedding-sdk-bundle/hooks/private/use-warn-conflicting-parameter-props";
import { getEffectiveParameterValues } from "embedding-sdk-bundle/lib/controlled-parameters";
import { useSdkDispatch, useSdkSelector } from "embedding-sdk-bundle/store";
import {
clearGuestToken,
setInitialGuestToken,
} from "embedding-sdk-bundle/store/guest-embed";
import {
getGuestTokenForMount,
getIsGuestEmbed,
getPlugins,
getSessionTokenState,
} from "embedding-sdk-bundle/store/selectors";
import type { MetabaseQuestion } from "embedding-sdk-bundle/types";
import type {
DashboardEventHandlersProps,
ParameterChangePayload,
SdkDashboardId,
} from "embedding-sdk-bundle/types/dashboard";
import type {
NavigatedEntityParameterChangePayload,
NavigatedEntityParameters,
} from "embedding-sdk-bundle/types/navigation";
import type { MetabasePluginsConfig } from "embedding-sdk-bundle/types/plugins";
import { useConfirmation } from "metabase/common/hooks";
import { useLocale } from "metabase/common/hooks/use-locale";
import {
closeSidebarIfSubscriptionsSidebarOpen,
setEditingDashboard,
toggleSidebar,
updateDashboardAndCards,
} from "metabase/dashboard/actions";
import { Dashboard } from "metabase/dashboard/components/Dashboard/Dashboard";
import { SIDEBAR_NAME } from "metabase/dashboard/constants";
import {
type DashboardContextProps,
DashboardContextProvider,
type DashboardContextProviderHandle,
useDashboardContext,
} from "metabase/dashboard/context";
import {
getDashboardComplete,
getIsDirty,
getIsEditing,
} from "metabase/dashboard/selectors";
import type { RefreshPeriod } from "metabase/dashboard/types";
import type { ParameterValues } from "metabase/embedding-sdk/types/dashboard";
import { EmbeddingEntityContextProvider } from "metabase/embedding/context";
import EmbedFrameS from "metabase/embedding/theme.module.css";
import { useSelector } from "metabase/redux";
import { resetErrorPage, setErrorPage } from "metabase/redux/app";
import { dismissAllUndo } from "metabase/redux/undo";
import { getErrorPage } from "metabase/selectors/app";
import { isStaticEmbeddingEntityLoadingError } from "metabase/utils/errors/is-static-embedding-entity-loading-error";
import type { CardDisplayType } from "metabase-types/api";
import type {
DrillThroughQuestionProps,
SdkQuestionProps,
} from "../SdkQuestion";
import { SdkDashboardStyledWrapper } from "./SdkDashboardStyleWrapper";
import { SdkDashboardProvider } from "./context";
import { useCommonDashboardParams } from "./use-common-dashboard-params";
const MaybeStyledWrapper = ({
skip,
className,
style,
fullHeight,
children,
}: {
skip: boolean;
className?: string;
style?: React.CSSProperties;
fullHeight?: boolean;
children: React.ReactNode;
}) =>
skip ? (
<>{children}</>
) : (
<SdkDashboardStyledWrapper
className={className}
style={style}
fullHeight={fullHeight}
>
{children}
</SdkDashboardStyledWrapper>
);
/**
* @interface
* @inline
* @category Dashboard
*/
export type SdkDashboardProps = PropsWithChildren<
{
/**
* Additional mapper function to override or add drill-down menu. See the implementing custom actions section for more details.
*/
plugins?: MetabasePluginsConfig;
// @todo pass the question context to the question view component,
// once we have a public-facing question context.
/**
* A custom React component to render the question layout.
* Use namespaced InteractiveQuestion components to build the layout.
*/
renderDrillThroughQuestion?: () => ReactNode;
/**
* Height of a question component when drilled from the dashboard to a question level.
*/
drillThroughQuestionHeight?: CSSProperties["height"];
/**
* Props of a question component when drilled from the dashboard to a question level.
*/
drillThroughQuestionProps?: DrillThroughQuestionProps;
/**
* The ID of the dashboard.
* <br/>
* This is either:
* <br/>
* - the numerical ID when accessing a dashboard link, i.e. `http://localhost:3000/dashboard/1-my-dashboard` where the ID is `1`
* <br/>
* - the string ID found in the `entity_id` key of the dashboard object when using the API directly or using the SDK Collection Browser to return data
*/
dashboardId: SdkDashboardId;
/**
* The interval between auto refreshes on the dashboard, in seconds.
*/
autoRefreshInterval?: number;
/**
* Initial values for query parameters, slug-keyed. Applied once on mount; user widget edits afterwards are not reflected back to the host.
* <br/>
* For each parameter:
* <br/>
* - set to a value (string for a single option, array of strings for multiple): that value is applied.
* <br/>
* - set to `null`: strictly cleared, ignoring the parameter's default.
* <br/>
* - omitted (or set to `undefined`): falls back to the parameter's default (or `null` if it has no default).
* <br/>
* <br/>
* - Combining {@link SdkDashboardProps.initialParameters | initialParameters} and {@link SdkDashboardDisplayProps.hiddenParameters | hiddenParameters} to filter data on the frontend is a [security risk](https://www.metabase.com/docs/latest/embedding/authentication#security-warning-each-end-user-must-have-their-own-metabase-account).
* <br/>
* - Combining {@link SdkDashboardProps.initialParameters | initialParameters} and {@link SdkDashboardDisplayProps.hiddenParameters | hiddenParameters} to declutter the user interface is fine.
*/
initialParameters?: ParameterValues;
/**
* Controlled parameter values, slug-keyed. On every render, this object replaces the dashboard's parameter values:
* <br/>
* - a parameter set to a value uses that value.
* <br/>
* - a parameter set to `null` is cleared, even if it has a default.
* <br/>
* - a parameter omitted from the object (or set to `undefined`) uses its default (or `null` if it has no default).
* <br/>
* <br/>
* Pair with {@link SdkDashboardProps.onParametersChange | onParametersChange} to stay in sync with user edits.
* <br/>
* - Combining {@link SdkDashboardProps.parameters | parameters} and {@link SdkDashboardDisplayProps.hiddenParameters | hiddenParameters} to filter data on the frontend is a [security risk](https://www.metabase.com/docs/latest/embedding/authentication#security-warning-each-end-user-must-have-their-own-metabase-account).
* <br/>
* - Combining {@link SdkDashboardProps.parameters | parameters} and {@link SdkDashboardDisplayProps.hiddenParameters | hiddenParameters} to declutter the user interface is fine.
*/
parameters?: ParameterValues;
/**
* Fires on parameters change. The payload's `source` distinguishes the initial state on load (`'initial-state'`), user edits in the UI (`'manual-change'`), and auto-updates (`'auto-change'`).
*/
onParametersChange?: (payload: ParameterChangePayload) => void;
/**
* Parameter values for entities the user reaches through entity navigation, keyed by the `navigationId` that {@link SdkDashboardProps.onNavigatedEntityParametersChange | onNavigatedEntityParametersChange} reports.
* <br/>
* Each navigation gets a new `navigationId`, and going back keeps it. So an entry applies only to the visit it was written for, never to a later visit of the same entity.
* <br/>
* Inside each entry, keys are filter slugs for a dashboard and template tag names for a SQL question. Each entry works like {@link SdkDashboardProps.parameters | parameters} on the root and replaces the values of that visit: keys you omit use their default. Use `null` to clear a value.
* <br/>
* To keep the values the click set, start from the `clickParameters` of {@link SdkDashboardProps.onNavigatedEntityParametersChange | onNavigatedEntityParametersChange}.
* <br/>
* Questions built with the query builder have no named parameters, so they cannot be controlled.
* <br/>
* A visit without an entry keeps the click-behavior values and is not controlled.
* <br/>
* Requires {@link SdkDashboardDisplayProps.enableEntityNavigation | enableEntityNavigation}.
*/
navigatedEntityParameters?: NavigatedEntityParameters;
/**
* Fires on parameters change on entities the user reaches through entity navigation. The root dashboard keeps reporting through {@link SdkDashboardProps.onParametersChange | onParametersChange}.
* <br/>
* The payload's `navigationId` identifies the visit, `entityType` and `entityId` the entity. `source` has the same meaning as in `onParametersChange`: `'initial-state'` fires after each navigation to the entity, also when the user comes back to it. It reports parameter values, it is not a navigation event.
* <br/>
* `clickParameters` holds the values the click behavior set. To compose your own values, do it on the first `'initial-state'` of a `navigationId` only, so going back keeps the user's edits.
* <br/>
* Dashboards without filters send `parameters: {}`. SQL questions without template tags and questions built with the query builder send no event.
*/
onNavigatedEntityParametersChange?: (
payload: NavigatedEntityParameterChangePayload,
) => void;
} & SdkDashboardDisplayProps &
DashboardEventHandlersProps
>;
type RenderMode = "dashboard" | "question" | "queryBuilder";
/**
* Despite being a prop for a specific component, to avoid circular dependencies, the type is defined here.
* @interface
* @inline
*/
export type EditableDashboardOwnProps = {
/**
* Additional props to pass to the query builder rendered by `InteractiveQuestion` when creating a new dashboard question.
*
* Set `dataPicker: "staged"` to always get the staged data picker. By default, Metabase shows a simple dropdown menu with tables and models, and only switches to the staged picker when there are 100 or more data sources. `entityTypes: ["question"]` only takes effect in the staged picker.
*/
dataPickerProps?: Pick<SdkQuestionProps, "entityTypes" | "dataPicker">;
};
export type SdkDashboardInnerProps = SdkDashboardProps &
EditableDashboardOwnProps &
Partial<
Pick<
DashboardContextProps,
| "clickActionMode"
| "dashboardActions"
| "dashcardMenu"
| "navigateToNewCardFromDashboard"
>
>;
const SdkDashboardInner = ({
dashboardId: rawDashboardId,
token: rawToken,
autoRefreshInterval,
initialParameters,
parameters,
onParametersChange,
withTitle = true,
withCardTitle = true,
withDownloads = false,
withSubscriptions = false,
hiddenParameters = [],
enableEntityNavigation = false, // SDK defaults to false (core app defaults to true)
drillThroughQuestionHeight,
plugins,
onLoad,
onLoadWithoutCards,
drillThroughQuestionProps = {
title: withTitle,
height: drillThroughQuestionHeight,
plugins: plugins,
},
renderDrillThroughQuestion: AdHocQuestionView,
dashboardActions,
dashcardMenu,
clickActionMode,
navigateToNewCardFromDashboard,
className,
style,
children,
dataPickerProps,
onVisualizationChange,
}: SdkDashboardInnerProps) => {
const isGuestEmbed = useSdkSelector(getIsGuestEmbed);
const dispatch = useSdkDispatch();
const [isFirstRender, setIsFirstRender] = useState(true);
// Stable per-mount id: keeps this mount's guest token isolated from any
// other guest StaticQuestion/StaticDashboard sharing the same MetabaseProvider.
const mountId = useId();
useWarnConflictingParameterProps({
initialParameters,
parameters,
initialParameterPropName: "initialParameters",
parameterPropName: "parameters",
});
const effectiveInitialParameters = getEffectiveParameterValues(
parameters,
initialParameters,
);
useSdkControlledParameters({
parameters,
onParametersChange,
});
const { error: tokenFetchError } = useSdkSelector(getSessionTokenState);
const tokenFromStore = useSdkSelector((state) =>
getGuestTokenForMount(state, mountId),
);
// Store token so the refresh handler can check expiry. No need to await — not used here.
useEffect(() => {
if (rawToken && isGuestEmbed) {
dispatch(setInitialGuestToken({ mountId, token: rawToken }));
}
}, [rawToken, isGuestEmbed, dispatch, mountId]);
// Own effect: folding this into the one above would clear the token on every
// rawToken change, leaving a window with no token for the refresh handler.
useEffect(
() => () => {
dispatch(clearGuestToken(mountId));
},
[dispatch, mountId],
);
useEffect(() => {
setIsFirstRender(false);
}, []);
const {
resourceId: dashboardId,
token,
tokenError,
} = useExtractResourceIdFromJwtToken({
isGuestEmbed,
resourceId: rawDashboardId,
// Skip stale Redux token on first render (e.g. wizard re-issuing a token when toggling parameters); rawToken prop takes precedence.
// From the next render onward, tokenFromStore is used and the value is from a refreshed token.
token: (!isFirstRender ? tokenFromStore : null) ?? rawToken ?? undefined,
});
useSetupContentTranslations({ token });
const { handleLoad, handleLoadWithoutCards } = useDashboardLoadHandlers({
onLoad,
onLoadWithoutCards,
});
const { isLocaleLoading } = useLocale();
const { isBreadcrumbEnabled, reportLocation } = useSdkBreadcrumbs();
const { displayOptions } = useSdkDashboardParams({
withDownloads,
withSubscriptions,
withTitle,
withCardTitle,
hiddenParameters,
});
const {
adhocQuestionUrl,
onNavigateBackToDashboard,
onEditQuestion,
onNavigateToNewCardFromDashboard: baseOnNavigateToNewCardFromDashboard,
} = useCommonDashboardParams({
dashboardId,
});
// `dashboardCardMenu` can be supplied either directly on the dashboard via
// `plugins`, or globally through `MetabaseProvider` (stored in the SDK Redux
// state). The local prop takes precedence, then the global plugin, and
// finally the component's built-in default menu.
const globalPlugins = useSdkSelector(getPlugins);
const finalDashcardMenu =
plugins?.dashboard?.dashboardCardMenu ??
globalPlugins?.dashboard?.dashboardCardMenu ??
dashcardMenu;
const [renderModeState, setRenderMode] = useState<
"dashboard" | "queryBuilder"
>("dashboard");
const finalRenderMode: RenderMode = adhocQuestionUrl
? "question"
: renderModeState;
// Now only used when rerendering the dashboard after creating a new question from the dashboard.
const dashboardContextProviderRef =
useRef<DashboardContextProviderHandle>(undefined);
const [newDashboardQuestionId, setNewDashboardQuestionId] =
useState<number>();
const dashboard = useSelector(getDashboardComplete);
const isEditing = useSelector(getIsEditing);
const autoScrollToDashcardId = useMemo(
() =>
dashboard?.dashcards.find(
(dashcard) => dashcard.card_id === newDashboardQuestionId,
)?.id,
[dashboard?.dashcards, newDashboardQuestionId],
);
useEffect(() => {
if (dashboard && isBreadcrumbEnabled && finalRenderMode === "dashboard") {
reportLocation({
type: "dashboard",
id: dashboard.id,
name: dashboard.name,
onNavigate: onNavigateBackToDashboard,
});
}
}, [
dashboard,
isBreadcrumbEnabled,
reportLocation,
finalRenderMode,
onNavigateBackToDashboard,
]);
const errorPage = useSdkSelector(getErrorPage);
useEffect(() => {
if (dashboardId) {
dispatch(resetErrorPage());
}
}, [dispatch, dashboardId]);
useEffect(() => {
if (!withSubscriptions) {
dispatch(closeSidebarIfSubscriptionsSidebarOpen());
}
}, [dispatch, withSubscriptions]);
const { modalContent, show } = useConfirmation();
const isDashboardDirty = useSelector(getIsDirty);
const sdkNavigation = useSdkInternalNavigationOptional();
// When this SdkDashboard renders below a nav-stack push, the outer
// SdkInternalNavigationProvider already wraps with SdkDashboardStyledWrapper
// carrying user style/className. Skip our own wrapper to avoid double
// wrapping (which drops user height/sticky/scroll behavior).
const skipStyledWrapper = !!sdkNavigation?.hasNavigatedToEntity;
// Initialize navigation stack with dashboard entry when we have the name
useEffect(() => {
if (dashboard && sdkNavigation) {
sdkNavigation.initWithDashboard({
id: dashboard.id,
name: dashboard.name,
});
}
}, [dashboard, sdkNavigation]);
// Wrap the navigation handler to push a virtual entry for back button support
const onNavigateToNewCardFromDashboard = useCallback(
(opts: Parameters<typeof baseOnNavigateToNewCardFromDashboard>[0]) => {
baseOnNavigateToNewCardFromDashboard(opts);
// If the id and query are the same, it means we're opening a card after having clicked its title
const isClickingOnCardTitle =
opts.nextCard.id === opts.previousCard.id &&
isEqual(opts.nextCard.dataset_query, opts.previousCard.dataset_query);
if (!isClickingOnCardTitle) {
// For drills, only push if not already a question drill
// One press of back button should undo all of them
const currentEntry = sdkNavigation?.stack.at(-1);
if (currentEntry?.type !== "question-drill") {
sdkNavigation?.push({
type: "question-drill",
virtual: true,
name: opts.previousCard.name ?? t`Question`,
onPop: () => onNavigateBackToDashboard(),
});
}
} else {
sdkNavigation?.push({
type: "open-card",
virtual: true,
name: opts.previousCard.name ?? t`Question`,
onPop: () => onNavigateBackToDashboard(),
});
}
},
[
baseOnNavigateToNewCardFromDashboard,
sdkNavigation,
onNavigateBackToDashboard,
],
);
// "Edit question" opens the card via adhocQuestionUrl without going through
// onNavigateToNewCardFromDashboard, so it never pushes to the navigation stack
// and the back button stays hidden. Push a virtual entry here so the question
// view renders a back button to the dashboard, matching the drill-in flow.
const onEditQuestionWithNav = useCallback(
(question: Parameters<typeof onEditQuestion>[0]) => {
sdkNavigation?.push({
type: "open-card",
virtual: true,
name: question.displayName() ?? t`Question`,
onPop: () => onNavigateBackToDashboard(),
});
onEditQuestion(question);
},
[onEditQuestion, sdkNavigation, onNavigateBackToDashboard],
);
if (isLocaleLoading) {
return (
<MaybeStyledWrapper
skip={skipStyledWrapper}
className={className}
style={style}
>
<SdkLoader />
</MaybeStyledWrapper>
);
}
if (tokenError) {
return (
<MaybeStyledWrapper
skip={skipStyledWrapper}
className={className}
style={style}
>
<SdkError message={tokenError} />;
</MaybeStyledWrapper>
);
}
if (tokenFetchError) {
return <SdkError message={tokenFetchError.message} />;
}
if (isStaticEmbeddingEntityLoadingError(errorPage, { isGuestEmbed })) {
return (
<MaybeStyledWrapper
skip={skipStyledWrapper}
className={className}
style={style}
>
<SdkError message={errorPage.data ?? t`Something's gone wrong`} />
</MaybeStyledWrapper>
);
}
// Passing an invalid entity ID format results in a 400 Bad Request.
// We can show this as a generic "not found" error on the frontend.
const isDashboardNotFound =
errorPage?.status === 404 || errorPage?.status === 400;
if (!dashboardId || isDashboardNotFound) {
return (
<MaybeStyledWrapper
skip={skipStyledWrapper}
className={className}
style={style}
>
<DashboardNotFoundError id={dashboardId ?? ""} />
</MaybeStyledWrapper>
);
}
if (errorPage) {
return (
<MaybeStyledWrapper
skip={skipStyledWrapper}
className={className}
style={style}
>
<SdkError message={errorPage.message ?? t`Something's gone wrong`} />
</MaybeStyledWrapper>
);
}
return (
<EmbeddingEntityContextProvider uuid={null} token={token}>
<DashboardContextProvider
ref={dashboardContextProviderRef}
dashboardId={dashboardId}
isGuestEmbed={isGuestEmbed}
parameterQueryParams={effectiveInitialParameters}
navigateToNewCardFromDashboard={
navigateToNewCardFromDashboard !== undefined
? navigateToNewCardFromDashboard
: onNavigateToNewCardFromDashboard
}
onEditQuestion={onEditQuestionWithNav}
onNewQuestion={() => {
if (isDashboardDirty) {
show({
title: t`Save your changes?`,
message: t`You’ll need to save your changes before leaving to create a new question.`,
confirmButtonText: t`Save changes`,
onConfirm: async () => {
/**
* Dispatch the same actions as in the DashboardLeaveConfirmationModal.
* @see {@link https://github.com/metabase/metabase/blob/4453fa8363eb37062a159f398050d050d91397a9/frontend/src/metabase/dashboard/components/DashboardLeaveConfirmationModal/DashboardLeaveConfirmationModal.tsx#L30-L34}
*/
sdkNavigation?.push({
type: "new-question",
virtual: true,
onPop: () => setRenderMode("dashboard"),
});
setRenderMode("queryBuilder");
dispatch(dismissAllUndo());
await dispatch(updateDashboardAndCards());
// After saving the dashboard, it will exit the editing mode.
dispatch(setEditingDashboard(dashboard));
},
confirmButtonProps: {
color: "brand",
},
});
} else {
sdkNavigation?.push({
type: "new-question",
virtual: true,
onPop: () => setRenderMode("dashboard"),
});
setRenderMode("queryBuilder");
}
}}
downloadsEnabled={displayOptions.downloadsEnabled}
withSubscriptions={displayOptions.withSubscriptions}
background={displayOptions.background}
bordered={displayOptions.bordered}
hideParameters={displayOptions.hideParameters}
titled={displayOptions.titled}
cardTitled={displayOptions.cardTitled}
theme={displayOptions.theme}
onLoad={handleLoad}
onLoadWithoutCards={handleLoadWithoutCards}
onError={(error) => dispatch(setErrorPage(error))}
clickActionMode={clickActionMode}
dashcardMenu={finalDashcardMenu}
dashboardActions={dashboardActions}
onAddQuestion={(dashboard) => {
dispatch(setEditingDashboard(dashboard));
dispatch(toggleSidebar(SIDEBAR_NAME.addQuestion));
}}
autoScrollToDashcardId={autoScrollToDashcardId}
enableEntityNavigation={enableEntityNavigation}
>
{match({ finalRenderMode, isGuestEmbed })
.with({ finalRenderMode: "question" }, () => (
<MaybeStyledWrapper
skip={skipStyledWrapper}
className={className}
style={style}
>
<SdkAdHocQuestion
// `adhocQuestionUrl` would have value if renderMode is "question"
questionPath={adhocQuestionUrl!}
onNavigateBack={onNavigateBackToDashboard}
{...drillThroughQuestionProps}
onVisualizationChange={onVisualizationChange}
>
{AdHocQuestionView && <AdHocQuestionView />}
</SdkAdHocQuestion>
</MaybeStyledWrapper>
))
.with({ finalRenderMode: "dashboard" }, () => (
<SdkDashboardProvider plugins={plugins}>
{children ?? (
<MaybeStyledWrapper
skip={skipStyledWrapper}
className={className}
style={style}
fullHeight={isEditing}
>
<Dashboard className={EmbedFrameS.EmbedFrame} />
<AutoRefreshController refreshPeriod={autoRefreshInterval} />
</MaybeStyledWrapper>
)}
</SdkDashboardProvider>
))
.with({ finalRenderMode: "queryBuilder" }, ({ isGuestEmbed }) =>
isGuestEmbed ? (
<MaybeStyledWrapper
skip={skipStyledWrapper}
className={className}
style={style}
>
<SdkError
message={t`You can't save questions in Guest Embed mode`}
/>
</MaybeStyledWrapper>
) : (
<MaybeStyledWrapper
skip={skipStyledWrapper}
className={className}
style={style}
fullHeight
>
<DashboardQueryBuilder
onCreate={(question) => {
setNewDashboardQuestionId(question.id);
sdkNavigation?.pop(); // onPop handles setRenderMode("dashboard")
dashboardContextProviderRef.current?.refetchDashboard();
}}
onNavigateBack={() => {
sdkNavigation?.pop(); // onPop handles setRenderMode("dashboard")
}}
dataPickerProps={dataPickerProps}
onVisualizationChange={onVisualizationChange}
/>
</MaybeStyledWrapper>
),
)
.exhaustive()}
{modalContent}
</DashboardContextProvider>
</EmbeddingEntityContextProvider>
);
};
// Unjustified type cast. FIXME
export const SdkDashboard = withPublicComponentWrapper(SdkDashboardInner, {
supportsGuestEmbed: true,
}) as typeof SdkDashboardInner &
Pick<
typeof Dashboard,
| "Grid"
| "Header"
| "Title"
| "Tabs"
| "ParametersList"
| "FullscreenButton"
| "ExportAsPdfButton"
| "InfoButton"
| "RefreshPeriod"
> & {
SubscriptionsButton: typeof DashboardSubscriptionsButton;
};
SdkDashboard.Grid = Dashboard.Grid;
SdkDashboard.Header = Dashboard.Header;
SdkDashboard.Title = Dashboard.Title;
SdkDashboard.Tabs = Dashboard.Tabs;
SdkDashboard.ParametersList = Dashboard.ParametersList;
SdkDashboard.FullscreenButton = Dashboard.FullscreenButton;
SdkDashboard.ExportAsPdfButton = Dashboard.ExportAsPdfButton;
SdkDashboard.SubscriptionsButton = DashboardSubscriptionsButton;
SdkDashboard.InfoButton = Dashboard.InfoButton;
SdkDashboard.RefreshPeriod = Dashboard.RefreshPeriod;
type DashboardQueryBuilderProps = {
onCreate: (question: MetabaseQuestion) => void;
onNavigateBack: () => void;
dataPickerProps: EditableDashboardOwnProps["dataPickerProps"];
onVisualizationChange?: (display: CardDisplayType) => void;
};
/**
* The sole reason this is extracted into a separate component is to access the dashboard context
*/
function DashboardQueryBuilder({
onCreate,
onNavigateBack,
dataPickerProps,
onVisualizationChange,
}: DashboardQueryBuilderProps) {
const { dashboard, selectTab, setEditingDashboard } = useDashboardContext();
/**
* This won't happen at this point in time. As `DashboardQueryBuilder` is guaranteed to be rendered
* while under the dashboard context, after a dashboard has already been loaded.
*
* I added this condition just to satisfy TypeScript, so that below this, the dashboard value isn't null.
*/
if (!dashboard) {
return null;
}
return (
<SdkQuestion
questionId="new"
targetDashboardId={dashboard.id}
onSave={(question, { isNewQuestion, dashboardTabId }) => {
if (isNewQuestion) {
onCreate(question);
if (dashboardTabId) {
selectTab({ tabId: dashboardTabId });
}
setEditingDashboard(dashboard);
}
}}
onNavigateBack={onNavigateBack}
backToDashboard={{
model: "dashboard",
id: dashboard.id,
name: dashboard.name,
}}
entityTypes={dataPickerProps?.entityTypes}
dataPicker={dataPickerProps?.dataPicker}
withChartTypeSelector
// Fill the available space so the query builder matches the dashboard's
// sizing instead of a fixed height that leaves whitespace / scrolls.
height="100%"
onVisualizationChange={onVisualizationChange}
/>
);
}
interface AutoRefreshControllerProps {
refreshPeriod: RefreshPeriod | undefined;
}
function AutoRefreshController({ refreshPeriod }: AutoRefreshControllerProps) {
const { onRefreshPeriodChange } = useDashboardContext();
useEffect(() => {
const normalizedRefreshPeriod =
refreshPeriod != null && refreshPeriod >= 0 ? refreshPeriod : null;
onRefreshPeriodChange(normalizedRefreshPeriod);
}, [refreshPeriod, onRefreshPeriodChange]);
useUnmount(() => {
onRefreshPeriodChange(null);
});
return null;
}