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
Expose a DateRangePopover in the data-app SDK namespace (#82291)
Timofey Kachalov82d075c73c7d
diff --git a/enterprise/frontend/src/embedding-sdk-package/components/public/DataAppLink/DataAppLink.tsx b/enterprise/frontend/src/embedding-sdk-package/components/public/DataAppLink/DataAppLink.tsxindex e9c9ff2eeb2..bfa5013ea23 100644--- a/enterprise/frontend/src/embedding-sdk-package/components/public/DataAppLink/DataAppLink.tsx+++ b/enterprise/frontend/src/embedding-sdk-package/components/public/DataAppLink/DataAppLink.tsx@@ -1,21 +1,74 @@-import type { DataAppLinkProps } from "embedding-sdk-bundle/lib/data-app/router";-import { getWindow } from "embedding-sdk-shared/lib/get-window";+import type { AnchorHTMLAttributes, MouseEvent, ReactNode } from "react";-export const DataAppLink = ({ to, children, ...rest }: DataAppLinkProps) => {- const BundleDataAppLink =- getWindow()?.METABASE_EMBEDDING_SDK_BUNDLE?.DataAppLink;+import {+ getBasename,+ navigate,+} from "embedding-sdk-package/lib/private/data-app-routing";- if (!BundleDataAppLink) {- return (- <a href={to} {...rest}>- {children}- </a>- );- }+export interface DataAppLinkProps extends Omit<+ AnchorHTMLAttributes<HTMLAnchorElement>,+ "href"+> {+ to: string;+ children?: ReactNode;+}++/**+ * Internal-only navigation link inside a data app.+ *+ * Renders a plain anchor rather than a router `<Link>`: a data app is mounted+ * outside the app's route tree, so it has no router context to read.+ */+export const DataAppLink = ({+ to,+ children,+ onClick,+ target,+ rel,+ ...rest+}: DataAppLinkProps) => {+ const href = getBasename() + to;++ const isExternalTarget = target != null && target !== "_self";+ const resolvedRel = rel ?? (isExternalTarget ? "noopener noreferrer" : rel);++ const handleClick = (event: MouseEvent<HTMLAnchorElement>) => {+ onClick?.(event);++ if (event.defaultPrevented) {+ return;+ }++ if (isExternalTarget) {+ // Explicit `target="_blank"` etc. — let the browser handle it.+ return;+ }++ if (+ event.button !== 0 ||+ event.metaKey ||+ event.ctrlKey ||+ event.shiftKey ||+ event.altKey+ ) {+ // Modifier keys / middle / right click — the browser handles it (new tab,+ // download, etc.). Don't preventDefault; the native action is wanted.+ return;+ }++ event.preventDefault();+ navigate(to);+ };return (- <BundleDataAppLink to={to} {...rest}>+ <a+ href={href}+ target={target}+ rel={resolvedRel}+ onClick={handleClick}+ {...rest}+ >{children}- </BundleDataAppLink>+ </a>);};diff --git a/enterprise/frontend/src/embedding-sdk-package/components/public/DataAppLink/index.ts b/enterprise/frontend/src/embedding-sdk-package/components/public/DataAppLink/index.tsindex b1cd7e1db26..8964240b72e 100644--- a/enterprise/frontend/src/embedding-sdk-package/components/public/DataAppLink/index.ts+++ b/enterprise/frontend/src/embedding-sdk-package/components/public/DataAppLink/index.ts@@ -1 +1 @@-export { DataAppLink } from "./DataAppLink";+export { DataAppLink, type DataAppLinkProps } from "./DataAppLink";diff --git a/enterprise/frontend/src/embedding-sdk-package/components/public/DataAppRouter/DataAppRouter.tsx b/enterprise/frontend/src/embedding-sdk-package/components/public/DataAppRouter/DataAppRouter.tsxindex 0774fdb73c5..0039192ae8c 100644--- a/enterprise/frontend/src/embedding-sdk-package/components/public/DataAppRouter/DataAppRouter.tsx+++ b/enterprise/frontend/src/embedding-sdk-package/components/public/DataAppRouter/DataAppRouter.tsx@@ -1,14 +1,17 @@import type { ReactNode } from "react";-import { getWindow } from "embedding-sdk-shared/lib/get-window";+export interface DataAppRouterProps {+ children?: ReactNode;+}-export const DataAppRouter = ({ children }: { children?: ReactNode }) => {- const BundleDataAppRouter =- getWindow()?.METABASE_EMBEDDING_SDK_BUNDLE?.DataAppRouter;-- if (!BundleDataAppRouter) {- return <>{children}</>;- }-- return <BundleDataAppRouter>{children}</BundleDataAppRouter>;-};+/**+ * Wrap your data-app tree once. Inside, use `<DataAppLink to="…">` for+ * navigation and `useDataAppLocation()` to read the current path.+ *+ * No `basename` prop: it is auto-detected from the iframe URL+ * (`/embed/apps/<name>`). In the dev preview, where there is no prefix, the+ * basename resolves to `""` and the sub-path is just the raw pathname.+ */+export const DataAppRouter = ({ children }: DataAppRouterProps) => (+ <>{children}</>+);diff --git a/enterprise/frontend/src/embedding-sdk-package/components/public/DataAppRouter/index.ts b/enterprise/frontend/src/embedding-sdk-package/components/public/DataAppRouter/index.tsindex a4931dd7dcb..0f6c387893a 100644--- a/enterprise/frontend/src/embedding-sdk-package/components/public/DataAppRouter/index.ts+++ b/enterprise/frontend/src/embedding-sdk-package/components/public/DataAppRouter/index.ts@@ -1 +1 @@-export { DataAppRouter } from "./DataAppRouter";+export { DataAppRouter, type DataAppRouterProps } from "./DataAppRouter";diff --git a/enterprise/frontend/src/embedding-sdk-package/components/public/DateRangeCalendar/DateRangeCalendar.tsx b/enterprise/frontend/src/embedding-sdk-package/components/public/DateRangeCalendar/DateRangeCalendar.tsxnew file mode 100644index 00000000000..c1a4fbd9818--- /dev/null+++ b/enterprise/frontend/src/embedding-sdk-package/components/public/DateRangeCalendar/DateRangeCalendar.tsx@@ -0,0 +1,7 @@+import type { DateRangeCalendarProps } from "embedding-sdk-bundle/components/public/DateRangeCalendar/DateRangeCalendar";+import { createComponent } from "embedding-sdk-package/components/private/ComponentWrapper/ComponentWrapper";+import { getWindow } from "embedding-sdk-shared/lib/get-window";++export const DateRangeCalendar = createComponent<DateRangeCalendarProps>(+ () => getWindow()?.METABASE_EMBEDDING_SDK_BUNDLE?.DateRangeCalendar,+);diff --git a/enterprise/frontend/src/embedding-sdk-package/components/public/DateRangeCalendar/index.ts b/enterprise/frontend/src/embedding-sdk-package/components/public/DateRangeCalendar/index.tsnew file mode 100644index 00000000000..d1f1e66405a--- /dev/null+++ b/enterprise/frontend/src/embedding-sdk-package/components/public/DateRangeCalendar/index.ts@@ -0,0 +1 @@+export { DateRangeCalendar } from "./DateRangeCalendar";diff --git a/enterprise/frontend/src/embedding-sdk-package/components/public/DateRangePopover/DateRangePopover.tsx b/enterprise/frontend/src/embedding-sdk-package/components/public/DateRangePopover/DateRangePopover.tsxnew file mode 100644index 00000000000..a3422606961--- /dev/null+++ b/enterprise/frontend/src/embedding-sdk-package/components/public/DateRangePopover/DateRangePopover.tsx@@ -0,0 +1,7 @@+import type { DateRangePopoverProps } from "embedding-sdk-bundle/components/public/DateRangePopover/DateRangePopover";+import { createComponent } from "embedding-sdk-package/components/private/ComponentWrapper/ComponentWrapper";+import { getWindow } from "embedding-sdk-shared/lib/get-window";++export const DateRangePopover = createComponent<DateRangePopoverProps>(+ () => getWindow()?.METABASE_EMBEDDING_SDK_BUNDLE?.DateRangePopover,+);diff --git a/enterprise/frontend/src/embedding-sdk-package/components/public/DateRangePopover/index.ts b/enterprise/frontend/src/embedding-sdk-package/components/public/DateRangePopover/index.tsnew file mode 100644index 00000000000..a591efec5d4--- /dev/null+++ b/enterprise/frontend/src/embedding-sdk-package/components/public/DateRangePopover/index.ts@@ -0,0 +1 @@+export { DateRangePopover } from "./DateRangePopover";diff --git a/enterprise/frontend/src/embedding-sdk-package/data-app.ts b/enterprise/frontend/src/embedding-sdk-package/data-app.tsindex a37a1c4e06b..46ab149e8a2 100644--- a/enterprise/frontend/src/embedding-sdk-package/data-app.ts+++ b/enterprise/frontend/src/embedding-sdk-package/data-app.ts@@ -10,10 +10,37 @@ EMBEDDING_SDK_CONFIG.isEmbeddingSdk = true;defineBuildInfo("METABASE_EMBEDDING_SDK_PACKAGE_BUILD_INFO");defineGlobalDependencies();-export { DataAppRouter } from "./components/public/DataAppRouter";-export { DataAppLink } from "./components/public/DataAppLink";+export {+ DataAppRouter,+ type DataAppRouterProps,+} from "./components/public/DataAppRouter";+export {+ DataAppLink,+ type DataAppLinkProps,+} from "./components/public/DataAppLink";+export { DateRangeCalendar } from "./components/public/DateRangeCalendar";+export { DateRangePopover } from "./components/public/DateRangePopover";+export type {+ DateRangeCalendarProps,+ DateRangeValue,+} from "embedding-sdk-bundle/components/public/DateRangeCalendar/DateRangeCalendar";+export type {+ DateRangePopoverPosition,+ DateRangePopoverProps,+} from "embedding-sdk-bundle/components/public/DateRangePopover/DateRangePopover";+export {+ useDateFormatter,+ type DateFormatter,+} from "./hooks/public/use-date-formatter";+export type {+ FormatDateOptions,+ FormatDateRangeOptions,+} from "embedding-sdk-bundle/lib/format-date-range";export { copy } from "./lib/public/copy";-export { useDataAppLocation } from "./hooks/public/use-data-app-location";+export {+ useDataAppLocation,+ type UseDataAppLocationResult,+} from "./hooks/public/use-data-app-location";export { defineQuery } from "./hooks/public/use-metabase-query/define-query";export { defineAction } from "./hooks/public/use-action/define-action";export {diff --git a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-data-app-location/use-data-app-location.ts b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-data-app-location/use-data-app-location.tsindex 0ce18d5a65d..36bc1b69646 100644--- a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-data-app-location/use-data-app-location.ts+++ b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-data-app-location/use-data-app-location.ts@@ -1,13 +1,10 @@-import {- useCallback,- useEffect,- useMemo,- useState,- useSyncExternalStore,-} from "react";+import { useEffect, useMemo, useState } from "react";-import { SDK_BUNDLE_LOADED } from "embedding-sdk-shared/constants/event-names";-import { getWindow } from "embedding-sdk-shared/lib/get-window";+import {+ getBasename,+ navigate,+ subscribeToDataAppRouting,+} from "embedding-sdk-package/lib/private/data-app-routing";export type UseDataAppLocationResult = {pathname: string;@@ -28,47 +25,24 @@ const computeSubPath = (basename: string): string => {return subPath || "/";};-const useDataAppRouting = () =>- useSyncExternalStore(- (notify) => {- const target = typeof document !== "undefined" ? document : null;- const handler = () => notify();- target?.addEventListener(SDK_BUNDLE_LOADED, handler);- return () => {- target?.removeEventListener(SDK_BUNDLE_LOADED, handler);- };- },- () => getWindow()?.METABASE_EMBEDDING_SDK_BUNDLE?.dataAppRouting,- () => undefined,- );-+/**+ * The current data-app sub-path and a `navigate` function.+ *+ * Paths are relative to the data-app root: `/`, `/customers/42`, etc.+ * `navigate(to)` switches sub-path without a full reload.+ */export const useDataAppLocation = (): UseDataAppLocationResult => {- const dataAppRouting = useDataAppRouting();-- const basename = useMemo(- () => dataAppRouting?.getBasename() ?? "",- [dataAppRouting],- );-+ // Never changes after mount: the iframe doesn't navigate to a different+ // `<name>` — that is a parent-level route change, which remounts the iframe.+ const basename = useMemo(() => getBasename(), []);const [pathname, setPathname] = useState(() => computeSubPath(basename));- useEffect(() => {- if (!dataAppRouting) {- return;- }-- setPathname(computeSubPath(dataAppRouting.getBasename()));-- return dataAppRouting.subscribe(() => {- setPathname(computeSubPath(dataAppRouting.getBasename()));- });- }, [dataAppRouting]);-- const navigate = useCallback(- (to: string) => {- dataAppRouting?.navigate(to);- },- [dataAppRouting],+ useEffect(+ () =>+ subscribeToDataAppRouting(() => {+ setPathname(computeSubPath(basename));+ }),+ [basename],);return { pathname, navigate };diff --git a/frontend/src/embedding-sdk-bundle/lib/data-app/router/useDataAppLocation.unit.spec.tsx b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-data-app-location/use-data-app-location.unit.spec.tsxsimilarity index 59%rename from frontend/src/embedding-sdk-bundle/lib/data-app/router/useDataAppLocation.unit.spec.tsxrename to enterprise/frontend/src/embedding-sdk-package/hooks/public/use-data-app-location/use-data-app-location.unit.spec.tsxindex b564ff602d2..cee6f59b650 100644--- a/frontend/src/embedding-sdk-bundle/lib/data-app/router/useDataAppLocation.unit.spec.tsx+++ b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-data-app-location/use-data-app-location.unit.spec.tsx@@ -1,11 +1,10 @@import { act, renderHook } from "@testing-library/react";-import { useDataAppLocation } from "./useDataAppLocation";+import { useDataAppLocation } from "./use-data-app-location";-// The data-app bundle mounts no router, so this navigation runs on the dedicated-// browser history `getRawBrowserHistory()` returns, not the app's router history.-// Regression guard: when it read the app router history (null outside a router),-// every `navigate` was a silent no-op.+// A data app mounts no router, so navigation runs on the native history and+// `pushState` fires no event: `navigate` has to notify subscribers itself, and+// every consumer must hear about it.describe("useDataAppLocation", () => {it("navigate() updates the sub-path and the iframe URL", () => {const { result } = renderHook(() => useDataAppLocation());@@ -29,4 +28,15 @@ describe("useDataAppLocation", () => {expect(firstResult.current.pathname).toBe("/orders/42");expect(secondResult.current.pathname).toBe("/orders/42");});++ it("follows browser back/forward", () => {+ const { result } = renderHook(() => useDataAppLocation());++ act(() => {+ window.history.pushState(null, "", "/orders/7");+ window.dispatchEvent(new PopStateEvent("popstate"));+ });++ expect(result.current.pathname).toBe("/orders/7");+ });});diff --git a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-date-formatter/index.ts b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-date-formatter/index.tsnew file mode 100644index 00000000000..ea846690e21--- /dev/null+++ b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-date-formatter/index.ts@@ -0,0 +1 @@+export { useDateFormatter, type DateFormatter } from "./use-date-formatter";diff --git a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-date-formatter/use-date-formatter.ts b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-date-formatter/use-date-formatter.tsnew file mode 100644index 00000000000..559d30fd52d--- /dev/null+++ b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-date-formatter/use-date-formatter.ts@@ -0,0 +1,38 @@+import type { DateRangeValue } from "embedding-sdk-bundle/components/public/DateRangeCalendar/DateRangeCalendar";+import type {+ FormatDateOptions,+ FormatDateRangeOptions,+} from "embedding-sdk-bundle/lib/format-date-range";+import { useSdkLoadingState } from "embedding-sdk-shared/hooks/use-sdk-loading-state";+import { getWindow } from "embedding-sdk-shared/lib/get-window";++export type DateFormatter = {+ formatDate: (+ value: string | null | undefined,+ options?: FormatDateOptions,+ ) => string;+ formatDateRange: (+ value: DateRangeValue | null | undefined,+ options?: FormatDateRangeOptions,+ ) => string;+};++const NOT_LOADED: DateFormatter = {+ formatDate: () => "",+ formatDateRange: () => "",+};++export const useDateFormatter = (): DateFormatter => {+ useSdkLoadingState();++ const bundle = getWindow()?.METABASE_EMBEDDING_SDK_BUNDLE;++ if (!bundle?.formatDate || !bundle.formatDateRange) {+ return NOT_LOADED;+ }++ return {+ formatDate: bundle.formatDate,+ formatDateRange: bundle.formatDateRange,+ };+};diff --git a/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-date-formatter/use-date-formatter.unit.spec.ts b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-date-formatter/use-date-formatter.unit.spec.tsnew file mode 100644index 00000000000..39e64da48ee--- /dev/null+++ b/enterprise/frontend/src/embedding-sdk-package/hooks/public/use-date-formatter/use-date-formatter.unit.spec.ts@@ -0,0 +1,70 @@+import { act, renderHook } from "@testing-library/react";++import type { MetabaseEmbeddingSdkBundleExports } from "embedding-sdk-bundle/types/sdk-bundle";+import { ensureMetabaseProviderPropsStore } from "embedding-sdk-shared/lib/ensure-metabase-provider-props-store";+import { SdkLoadingState } from "embedding-sdk-shared/types/sdk-loading";++import { useDateFormatter } from "./use-date-formatter";++const formatDate = jest.fn(() => "one");+const formatDateRange = jest.fn(() => "both");++const setBundleGlobal = () => {+ // Only the two exports the hook reaches for; the rest of the contract is+ // irrelevant here.+ window.METABASE_EMBEDDING_SDK_BUNDLE = {+ formatDate,+ formatDateRange,+ } as unknown as MetabaseEmbeddingSdkBundleExports;+};++const markBundleLoaded = () => {+ ensureMetabaseProviderPropsStore().updateInternalProps({+ loadingState: SdkLoadingState.Loaded,+ });+};++afterEach(() => {+ delete window.METABASE_EMBEDDING_SDK_BUNDLE;+ ensureMetabaseProviderPropsStore().cleanup();+ jest.clearAllMocks();+});++describe("useDateFormatter", () => {+ it("formats nothing until the bundle is loaded", () => {+ const { result } = renderHook(() => useDateFormatter());++ expect(result.current.formatDate("2026-09-01")).toBe("");+ expect(result.current.formatDateRange(["2026-09-01", null])).toBe("");+ });++ it("delegates to the bundle's formatters once loaded", () => {+ setBundleGlobal();+ markBundleLoaded();++ const { result } = renderHook(() => useDateFormatter());++ expect(result.current.formatDate("2026-09-01", { format: "MMM D" })).toBe(+ "one",+ );+ expect(formatDate).toHaveBeenCalledWith("2026-09-01", { format: "MMM D" });+ expect(result.current.formatDateRange(["2026-09-01", "2026-09-10"])).toBe(+ "both",+ );+ });++ // The label is computed in the caller's render, so the hook has to bring the+ // caller back when the bundle lands — not leave it on the empty string.+ it("re-renders the caller with the real formatter when the bundle lands", () => {+ const { result } = renderHook(() => useDateFormatter());++ expect(result.current.formatDateRange(["2026-09-01", null])).toBe("");++ act(() => {+ setBundleGlobal();+ markBundleLoaded();+ });++ expect(result.current.formatDateRange(["2026-09-01", null])).toBe("both");+ });+});diff --git a/enterprise/frontend/src/embedding-sdk-package/index.ts b/enterprise/frontend/src/embedding-sdk-package/index.tsindex 102fa371ec9..47d8d8bc412 100644--- a/enterprise/frontend/src/embedding-sdk-package/index.ts+++ b/enterprise/frontend/src/embedding-sdk-package/index.ts@@ -45,9 +45,18 @@ export type {export { defineMetabaseAuthConfig } from "./lib/public/define-metabase-auth-config";export { defineMetabaseTheme } from "./lib/public/define-metabase-theme";-export { DataAppRouter } from "./components/public/DataAppRouter";-export { DataAppLink } from "./components/public/DataAppLink";-export { useDataAppLocation } from "./hooks/public/use-data-app-location";+export {+ DataAppRouter,+ type DataAppRouterProps,+} from "./components/public/DataAppRouter";+export {+ DataAppLink,+ type DataAppLinkProps,+} from "./components/public/DataAppLink";+export {+ useDataAppLocation,+ type UseDataAppLocationResult,+} from "./hooks/public/use-data-app-location";export {type CollectionBrowserProps,diff --git a/enterprise/frontend/src/embedding-sdk-package/lib/private/data-app-routing.ts b/enterprise/frontend/src/embedding-sdk-package/lib/private/data-app-routing.tsnew file mode 100644index 00000000000..ca6d301041d--- /dev/null+++ b/enterprise/frontend/src/embedding-sdk-package/lib/private/data-app-routing.ts@@ -0,0 +1,64 @@+// eslint-disable-next-line metabase/no-external-references-for-sdk-package-code+import { DATA_APP_EMBED_PREFIX } from "metabase/urls/data-apps";++const escapeRegExp = (str: string): string =>+ str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");++// Captures everything from the start of `pathname` up to and including the+// data-app `:name` segment. Tolerates a Metabase subpath install+// (`/mb/embed/apps/sales/…`) by allowing arbitrary characters before the+// `DATA_APP_EMBED_PREFIX` literal.+const DATA_APP_BASENAME_RE = new RegExp(+ `^(.*?${escapeRegExp(DATA_APP_EMBED_PREFIX)}/[^/]+)`,+);++/**+ * The iframe URL's data-app prefix, including any Metabase subpath install root.+ * `""` outside the iframe (the dev preview), where the sub-path is the raw pathname.+ *+ * `/embed/apps/sales/customers/42` -> `/embed/apps/sales`+ * `/mb/embed/apps/sales/customers/42` -> `/mb/embed/apps/sales`+ * `/customers/42` -> `""`+ */+export const getBasename = (): string =>+ typeof window === "undefined"+ ? ""+ : (window.location.pathname.match(DATA_APP_BASENAME_RE)?.[1] ?? "");++const subscribers = new Set<() => void>();+let detachPopstate: (() => void) | undefined;++const notify = () => subscribers.forEach((subscriber) => subscriber());++/**+ * Notifies on every in-app navigation: `<DataAppLink>` clicks, `navigate()` calls,+ * and browser back/forward. `pushState` fires no event of its own, so `navigate`+ * notifies explicitly; `popstate` covers the rest.+ */+export const subscribeToDataAppRouting = (callback: () => void) => {+ subscribers.add(callback);++ if (!detachPopstate) {+ window.addEventListener("popstate", notify);+ detachPopstate = () => window.removeEventListener("popstate", notify);+ }++ return () => {+ subscribers.delete(callback);++ if (subscribers.size === 0) {+ detachPopstate?.();+ detachPopstate = undefined;+ }+ };+};++/**+ * Switches to a bundle-relative sub-path (`/customers/42`) without a reload.+ * Goes through the native `pushState` on purpose: the host mirrors the iframe+ * URL into the parent's address bar by patching exactly that method.+ */+export const navigate = (to: string) => {+ window.history.pushState(null, "", getBasename() + to);+ notify();+};diff --git a/frontend/src/embedding-sdk-bundle/components/public/DateRangeCalendar/DateRangeCalendar.tsx b/frontend/src/embedding-sdk-bundle/components/public/DateRangeCalendar/DateRangeCalendar.tsxnew file mode 100644index 00000000000..7321af466c9--- /dev/null+++ b/frontend/src/embedding-sdk-bundle/components/public/DateRangeCalendar/DateRangeCalendar.tsx@@ -0,0 +1,54 @@+import type { CSSProperties } from "react";++import { PublicComponentStylesWrapper } from "embedding-sdk-bundle/components/private/PublicComponentStylesWrapper";+import { DatePicker } from "metabase/ui";++export type DateRangeValue = [string | null, string | null];++export interface DateRangeCalendarProps {+ value?: DateRangeValue;+ defaultValue?: DateRangeValue;+ onChange?: (value: DateRangeValue) => void;+ minDate?: string;+ maxDate?: string;+ numberOfColumns?: number;+ className?: string;+ style?: CSSProperties;+}++export const DateRangeCalendar = ({+ value,+ defaultValue,+ onChange,+ minDate,+ maxDate,+ numberOfColumns = 2,+ className,+ style,+}: DateRangeCalendarProps) => (+ // Mantine scopes its CSS variables to `.mb-wrapper`, which this wrapper+ // carries. Without it the calendar renders unstyled inside a data app.+ <PublicComponentStylesWrapper+ className={className}+ style={{+ display: "inline-block",+ width: "fit-content",+ height: "auto",+ ...style,+ }}+ >+ <DatePicker+ type="range"+ value={value}+ defaultValue={defaultValue}+ // The bare calendar opens on today's month whatever the value is; start it+ // on the selected range instead, so a reopened popover shows the pick.+ defaultDate={value?.[0] ?? defaultValue?.[0] ?? undefined}+ onChange={onChange}+ minDate={minDate}+ maxDate={maxDate}+ numberOfColumns={numberOfColumns}+ allowSingleDateInRange+ />+ </PublicComponentStylesWrapper>+);diff --git a/frontend/src/embedding-sdk-bundle/components/public/DateRangeCalendar/DateRangeCalendar.unit.spec.tsx b/frontend/src/embedding-sdk-bundle/components/public/DateRangeCalendar/DateRangeCalendar.unit.spec.tsxnew file mode 100644index 00000000000..32ac988cb21--- /dev/null+++ b/frontend/src/embedding-sdk-bundle/components/public/DateRangeCalendar/DateRangeCalendar.unit.spec.tsx@@ -0,0 +1,43 @@+import userEvent from "@testing-library/user-event";++import { renderWithProviders, screen } from "__support__/ui";++import { DateRangeCalendar, type DateRangeValue } from "./DateRangeCalendar";++const setup = (value: DateRangeValue) => {+ const onChange = jest.fn();++ renderWithProviders(+ <DateRangeCalendar value={value} onChange={onChange} numberOfColumns={1} />,+ );++ return { onChange };+};++// The public contract is `YYYY-MM-DD` strings on both ends — what the data-app+// query filters take — so these pin the value shape, not the calendar's looks.+describe("DateRangeCalendar", () => {+ it("completes a half-picked range with YYYY-MM-DD strings", async () => {+ const { onChange } = setup(["2026-03-10", null]);++ await userEvent.click(screen.getByText("20"));++ expect(onChange).toHaveBeenCalledWith(["2026-03-10", "2026-03-20"]);+ });++ it("reports a half-picked range when a new range is started", async () => {+ const { onChange } = setup(["2026-03-10", "2026-03-20"]);++ await userEvent.click(screen.getByText("15"));++ expect(onChange).toHaveBeenCalledWith(["2026-03-15", null]);+ });++ it("allows a single day as a range", async () => {+ const { onChange } = setup(["2026-03-10", null]);++ await userEvent.click(screen.getByText("10"));++ expect(onChange).toHaveBeenCalledWith(["2026-03-10", "2026-03-10"]);+ });+});diff --git a/frontend/src/embedding-sdk-bundle/components/public/DateRangePopover/DateRangePopover.tsx b/frontend/src/embedding-sdk-bundle/components/public/DateRangePopover/DateRangePopover.tsxnew file mode 100644index 00000000000..fc54cae7396--- /dev/null+++ b/frontend/src/embedding-sdk-bundle/components/public/DateRangePopover/DateRangePopover.tsx@@ -0,0 +1,107 @@+import {+ Children,+ type MouseEvent,+ type ReactElement,+ cloneElement,+ isValidElement,+ useState,+} from "react";++import { Popover } from "metabase/ui";++import {+ DateRangeCalendar,+ type DateRangeCalendarProps,+ type DateRangeValue,+} from "../DateRangeCalendar/DateRangeCalendar";++/**+ * Where the calendar opens relative to the trigger. Spelled out rather than+ * derived from Mantine's `Popover` props: this interface is published in the+ * `/data-app` declarations, and a data app has no `@mantine/core` to resolve.+ */+export type DateRangePopoverPosition =+ | "top"+ | "top-start"+ | "top-end"+ | "right"+ | "right-start"+ | "right-end"+ | "bottom"+ | "bottom-start"+ | "bottom-end"+ | "left"+ | "left-start"+ | "left-end";++export interface DateRangePopoverProps extends Omit<+ DateRangeCalendarProps,+ "className" | "style"+> {+ /**+ * The trigger. Must be a single DOM element or a `forwardRef` component: the+ * popover attaches a ref and a click handler to it.+ */+ children: ReactElement<{ onClick?: (event: MouseEvent) => void }>;+ opened?: boolean;+ onOpenedChange?: (opened: boolean) => void;+ /** Close once both ends of the range are picked. Defaults to true. */+ closeOnSelect?: boolean;+ position?: DateRangePopoverPosition;+}++export const DateRangePopover = ({+ children,+ opened,+ onOpenedChange,+ closeOnSelect = true,+ position = "bottom-start",+ onChange,+ ...calendarProps+}: DateRangePopoverProps) => {+ const [internalOpened, setInternalOpened] = useState(false);+ const isOpened = opened ?? internalOpened;++ const setOpened = (next: boolean) => {+ setInternalOpened(next);+ onOpenedChange?.(next);+ };++ const handleChange = (next: DateRangeValue) => {+ onChange?.(next);++ const [start, end] = next;++ if (closeOnSelect && start && end) {+ setOpened(false);+ }+ };++ const trigger = Children.only(children);++ if (!isValidElement(trigger)) {+ return null;+ }++ return (+ <Popover+ opened={isOpened}+ onChange={setOpened}+ position={position}+ withinPortal+ >+ <Popover.Target>+ {cloneElement(trigger, {+ onClick: (event: MouseEvent) => {+ trigger.props.onClick?.(event);+ setOpened(!isOpened);+ },+ })}+ </Popover.Target>++ <Popover.Dropdown p="md">+ <DateRangeCalendar {...calendarProps} onChange={handleChange} />+ </Popover.Dropdown>+ </Popover>+ );+};diff --git a/frontend/src/embedding-sdk-bundle/components/public/DateRangePopover/DateRangePopover.unit.spec.tsx b/frontend/src/embedding-sdk-bundle/components/public/DateRangePopover/DateRangePopover.unit.spec.tsxnew file mode 100644index 00000000000..828dff88cc3--- /dev/null+++ b/frontend/src/embedding-sdk-bundle/components/public/DateRangePopover/DateRangePopover.unit.spec.tsx@@ -0,0 +1,108 @@+import userEvent from "@testing-library/user-event";+import { useState } from "react";++import { renderWithProviders, screen, waitFor } from "__support__/ui";++import type { DateRangeValue } from "../DateRangeCalendar/DateRangeCalendar";++import {+ DateRangePopover,+ type DateRangePopoverProps,+} from "./DateRangePopover";++type SetupOpts = Pick<+ DateRangePopoverProps,+ "opened" | "onOpenedChange" | "closeOnSelect"+> & {+ value: DateRangeValue;+};++const setup = ({ value, ...popoverProps }: SetupOpts) => {+ const onChange = jest.fn();+ const onTriggerClick = jest.fn();++ // Controlled so a completed range shows in the calendar the way it would in+ // an app, where `onChange` writes straight back into `value`.+ const Wrapper = () => {+ const [range, setRange] = useState(value);++ return (+ <DateRangePopover+ {...popoverProps}+ value={range}+ numberOfColumns={1}+ onChange={(next) => {+ onChange(next);+ setRange(next);+ }}+ >+ <button onClick={onTriggerClick}>Custom</button>+ </DateRangePopover>+ );+ };++ renderWithProviders(<Wrapper />);++ return { onChange, onTriggerClick };+};++const trigger = () => screen.getByRole("button", { name: "Custom" });++// The calendar header is the least ambiguous sign the dropdown is mounted —+// day numbers appear in every month, and nothing else on the page shows one.+const calendar = () => screen.queryByText("March 2026");++describe("DateRangePopover", () => {+ it("opens on the trigger and calls the trigger's own handler", async () => {+ const { onTriggerClick } = setup({ value: ["2026-03-10", null] });++ expect(calendar()).not.toBeInTheDocument();++ await userEvent.click(trigger());++ expect(await screen.findByText("March 2026")).toBeInTheDocument();+ expect(onTriggerClick).toHaveBeenCalledTimes(1);+ });++ it("stays open on a half-picked range and closes once both ends are set", async () => {+ const { onChange } = setup({ value: ["2026-03-10", "2026-03-20"] });++ await userEvent.click(trigger());+ await userEvent.click(await screen.findByText("15"));++ expect(onChange).toHaveBeenLastCalledWith(["2026-03-15", null]);+ expect(calendar()).toBeInTheDocument();++ await userEvent.click(screen.getByText("25"));++ expect(onChange).toHaveBeenLastCalledWith(["2026-03-15", "2026-03-25"]);+ await waitFor(() => expect(calendar()).not.toBeInTheDocument());+ });++ it("keeps the popover open when closeOnSelect is off", async () => {+ const { onChange } = setup({+ value: ["2026-03-10", null],+ closeOnSelect: false,+ });++ await userEvent.click(trigger());+ await userEvent.click(await screen.findByText("20"));++ expect(onChange).toHaveBeenLastCalledWith(["2026-03-10", "2026-03-20"]);+ expect(calendar()).toBeInTheDocument();+ });++ // Mantine's `Popover.Target` adds its own toggling `onClick` only to an+ // uncontrolled popover; this one is always controlled, so the cloned handler+ // is the single toggle. One click, one transition — not two.+ it("reports exactly one transition per click when controlled", async () => {+ const onOpenedChange = jest.fn();+ setup({ value: ["2026-03-10", null], opened: false, onOpenedChange });++ await userEvent.click(trigger());++ expect(onOpenedChange).toHaveBeenCalledTimes(1);+ expect(onOpenedChange).toHaveBeenCalledWith(true);+ expect(calendar()).not.toBeInTheDocument();+ });+});diff --git a/frontend/src/embedding-sdk-bundle/lib/data-app/router/DataAppLink.tsx b/frontend/src/embedding-sdk-bundle/lib/data-app/router/DataAppLink.tsxdeleted file mode 100644index 210349d95b4..00000000000--- a/frontend/src/embedding-sdk-bundle/lib/data-app/router/DataAppLink.tsx+++ /dev/null@@ -1,73 +0,0 @@-import type { AnchorHTMLAttributes, MouseEvent, ReactNode } from "react";--import { getRawBrowserHistory } from "metabase/router";--import { getBasename } from "./DataAppRouter";--export interface DataAppLinkProps extends Omit<- AnchorHTMLAttributes<HTMLAnchorElement>,- "href"-> {- to: string;- children?: ReactNode;-}--/**- * Internal-only navigation link inside a data app.- *- * Renders a plain anchor rather than the router's `<Link>`: a data app is- * mounted outside the app's route tree, so it has no router context to read.- */-export const DataAppLink = ({- to,- children,- onClick,- target,- rel,- ...rest-}: DataAppLinkProps) => {- const href = getBasename() + to;-- const isExternalTarget = target != null && target !== "_self";- const resolvedRel = rel ?? (isExternalTarget ? "noopener noreferrer" : rel);-- const handleClick = (event: MouseEvent<HTMLAnchorElement>) => {- onClick?.(event);-- if (event.defaultPrevented) {- return;- }-- if (isExternalTarget) {- // Explicit `target="_blank"` etc. — let the browser handle it.- return;- }-- if (- event.button !== 0 ||- event.metaKey ||- event.ctrlKey ||- event.shiftKey ||- event.altKey- ) {- // Modifier keys / middle / right click → browser handles it (new tab,- // download, etc.). Don't preventDefault — we want the native action.- return;- }-- event.preventDefault();- getRawBrowserHistory().push(href);- };-- return (- <a- href={href}- target={target}- rel={resolvedRel}- onClick={handleClick}- {...rest}- >- {children}- </a>- );-};diff --git a/frontend/src/embedding-sdk-bundle/lib/data-app/router/DataAppRouter.tsx b/frontend/src/embedding-sdk-bundle/lib/data-app/router/DataAppRouter.tsxdeleted file mode 100644index c35505ece29..00000000000--- a/frontend/src/embedding-sdk-bundle/lib/data-app/router/DataAppRouter.tsx+++ /dev/null@@ -1,54 +0,0 @@-import type { ReactNode } from "react";--// Deep import (not the `metabase/urls` barrel) to keep the SDK bundle lean —-// `data-apps.ts` is a leaf with no transitive deps.-import { DATA_APP_EMBED_PREFIX } from "metabase/urls/data-apps";--/**- * Escape a string for safe use as a literal inside a `RegExp`. The- * embed-prefix constant doesn't currently contain regex metacharacters,- * but escaping makes the regex robust against future changes to the- * constant.- */-const escapeRegExp = (str: string): string =>- str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");--// Captures everything from the start of `pathname` up to and including the-// data-app `:name` segment. Tolerates a Metabase subpath install-// (`/mb/embed/apps/sales/…`) by allowing arbitrary characters before-// the `DATA_APP_EMBED_PREFIX` literal. In root installs (no subpath) the-// pre-segment is empty and the match becomes `${DATA_APP_EMBED_PREFIX}/<name>`.-const DATA_APP_BASENAME_RE = new RegExp(- `^(.*?${escapeRegExp(DATA_APP_EMBED_PREFIX)}/[^/]+)`,-);--/**- * Returns the iframe URL's data-app prefix — including any Metabase- * subpath install root — so consumers can strip it before exposing the- * sub-path to the bundle. Returns `""` for non-iframe contexts (the dev- * preview).- *- * Examples:- * `/embed/apps/sales/customers/42` → `/embed/apps/sales`- * `/mb/embed/apps/sales/customers/42` → `/mb/embed/apps/sales`- * `/customers/42` → `""`- */-export const getBasename = (): string =>- window.location.pathname.match(DATA_APP_BASENAME_RE)?.[1] ?? "";--interface DataAppRouterProps {- children?: ReactNode;-}--/**- * Wrap your data-app tree once. Inside, use `<DataAppLink to="…">` for- * navigation and `useDataAppLocation()` to read the current path.- *- * No `basename` prop: the basename is auto-detected from the iframe URL- * (`/embed/apps/<name>`). In the dev preview where there's no prefix,- * the same code works — `basename` resolves to `""` and the sub-path is- * just the raw pathname.- */-export const DataAppRouter = ({ children }: DataAppRouterProps) => (- <>{children}</>-);diff --git a/frontend/src/embedding-sdk-bundle/lib/data-app/router/dataAppRouting.ts b/frontend/src/embedding-sdk-bundle/lib/data-app/router/dataAppRouting.tsdeleted file mode 100644index e8e0bedd775..00000000000--- a/frontend/src/embedding-sdk-bundle/lib/data-app/router/dataAppRouting.ts+++ /dev/null@@ -1,30 +0,0 @@-import { getRawBrowserHistory } from "metabase/router";--import { getBasename } from "./DataAppRouter";--const subscribers = new Set<() => void>();-let unsubscribeFromHistory: (() => void) | undefined;--export const subscribeToDataAppRouting = (callback: () => void) => {- subscribers.add(callback);-- unsubscribeFromHistory ??= getRawBrowserHistory().listen(() => {- subscribers.forEach((subscriber) => subscriber());- });-- return () => {- subscribers.delete(callback);-- if (subscribers.size === 0) {- unsubscribeFromHistory?.();- unsubscribeFromHistory = undefined;- }- };-};--/** Routing helpers exposed on the bundle, for data apps to consume. */-export const dataAppRouting = {- getBasename,- navigate: (to: string) => getRawBrowserHistory().push(getBasename() + to),- subscribe: subscribeToDataAppRouting,-};diff --git a/frontend/src/embedding-sdk-bundle/lib/data-app/router/index.ts b/frontend/src/embedding-sdk-bundle/lib/data-app/router/index.tsdeleted file mode 100644index ab663243dd5..00000000000--- a/frontend/src/embedding-sdk-bundle/lib/data-app/router/index.ts+++ /dev/null@@ -1,6 +0,0 @@-import { DataAppRouter, getBasename } from "./DataAppRouter";--export { DataAppRouter, getBasename };-export { DataAppLink, type DataAppLinkProps } from "./DataAppLink";-export { useDataAppLocation } from "./useDataAppLocation";-export { dataAppRouting } from "./dataAppRouting";diff --git a/frontend/src/embedding-sdk-bundle/lib/data-app/router/useDataAppLocation.ts b/frontend/src/embedding-sdk-bundle/lib/data-app/router/useDataAppLocation.tsdeleted file mode 100644index 39e0c237f6b..00000000000--- a/frontend/src/embedding-sdk-bundle/lib/data-app/router/useDataAppLocation.ts+++ /dev/null@@ -1,52 +0,0 @@-import { useCallback, useEffect, useMemo, useState } from "react";--import { getRawBrowserHistory } from "metabase/router";--import { getBasename } from "./DataAppRouter";-import { subscribeToDataAppRouting } from "./dataAppRouting";--const computeSubPath = (basename: string): string => {- const pathname = window.location.pathname;- const subPath =- basename && pathname.startsWith(basename)- ? pathname.slice(basename.length)- : pathname;-- return subPath || "/";-};--/**- * Returns the current data-app sub-path and a `navigate` function.- *- * Path is relative to the data-app root: `/`, `/customers/42`, etc.- * `navigate(to)` switches to a new sub-path without a full reload.- */-export const useDataAppLocation = (): {- pathname: string;- navigate: (to: string) => void;-} => {- // Basename never changes after mount: the iframe doesn't navigate to a- // different `<name>`; that'd be a parent-level route change which- // re-mounts the iframe entirely.- const basename = useMemo(() => getBasename(), []);- const [pathname, setPathname] = useState(() => computeSubPath(basename));-- useEffect(() => {- // `listen` fires for every navigation: `<Link>` clicks, imperative `push`- // calls, and browser back/forward. One subscription covers all of them.- return subscribeToDataAppRouting(() => {- setPathname(computeSubPath(basename));- });- }, [basename]);-- const navigate = useCallback(- (to: string) => {- // `to` is bundle-relative (e.g. "/customers/42"). The real URL is- // `basename + to`.- getRawBrowserHistory().push(basename + to);- },- [basename],- );-- return { pathname, navigate };-};diff --git a/frontend/src/embedding-sdk-bundle/lib/format-date-range.ts b/frontend/src/embedding-sdk-bundle/lib/format-date-range.tsnew file mode 100644index 00000000000..d2deaca3fb7--- /dev/null+++ b/frontend/src/embedding-sdk-bundle/lib/format-date-range.ts@@ -0,0 +1,51 @@+import type { DateRangeValue } from "embedding-sdk-bundle/components/public/DateRangeCalendar/DateRangeCalendar";+import { dayjs } from "metabase/dayjs";+import { getFormattedDate } from "metabase/ui";++export interface FormatDateOptions {+ format?: string;+}++export interface FormatDateRangeOptions extends FormatDateOptions {+ separator?: string;+}++const DEFAULT_FORMAT = "MMMM D, YYYY";+const DEFAULT_SEPARATOR = "–";++const locale = () => dayjs().locale();++const isDate = (value: string | null | undefined): value is string =>+ !!value && dayjs(value).isValid();++export const formatDate = (+ value: string | null | undefined,+ { format = DEFAULT_FORMAT }: FormatDateOptions = {},+): string =>+ isDate(value)+ ? getFormattedDate({+ type: "default",+ date: value,+ locale: locale(),+ format,+ labelSeparator: DEFAULT_SEPARATOR,+ })+ : "";++export const formatDateRange = (+ value: DateRangeValue | null | undefined,+ {+ format = DEFAULT_FORMAT,+ separator = DEFAULT_SEPARATOR,+ }: FormatDateRangeOptions = {},+): string => {+ const [start, end] = value ?? [null, null];++ return getFormattedDate({+ type: "range",+ date: [isDate(start) ? start : null, isDate(end) ? end : null],+ locale: locale(),+ format,+ labelSeparator: separator,+ });+};diff --git a/frontend/src/embedding-sdk-bundle/lib/format-date-range.unit.spec.ts b/frontend/src/embedding-sdk-bundle/lib/format-date-range.unit.spec.tsnew file mode 100644index 00000000000..0d462f8ba80--- /dev/null+++ b/frontend/src/embedding-sdk-bundle/lib/format-date-range.unit.spec.ts@@ -0,0 +1,51 @@+import { formatDate, formatDateRange } from "./format-date-range";++describe("formatDate", () => {+ it("formats a date string in local time", () => {+ expect(formatDate("2026-09-01")).toBe("September 1, 2026");+ });++ it("takes a dayjs format", () => {+ expect(formatDate("2026-09-01", { format: "MMM D" })).toBe("Sep 1");+ });++ it("is empty for a missing or unparseable value", () => {+ expect(formatDate(null)).toBe("");+ expect(formatDate(undefined)).toBe("");+ expect(formatDate("")).toBe("");+ expect(formatDate("not a date")).toBe("");+ });+});++describe("formatDateRange", () => {+ it("joins both ends", () => {+ expect(formatDateRange(["2026-09-01", "2026-09-10"])).toBe(+ "September 1, 2026 – September 10, 2026",+ );+ });++ it("shows a half-picked range with a trailing separator", () => {+ expect(formatDateRange(["2026-09-01", null])).toBe("September 1, 2026 – ");+ });++ it("is empty when nothing is picked", () => {+ expect(formatDateRange([null, null])).toBe("");+ expect(formatDateRange(null)).toBe("");+ expect(formatDateRange(undefined)).toBe("");+ });++ it("takes a format and a separator", () => {+ expect(+ formatDateRange(["2026-09-01", "2026-09-10"], {+ format: "MMM D",+ separator: "to",+ }),+ ).toBe("Sep 1 to Sep 10");+ });++ it("drops an unparseable end rather than labelling it", () => {+ expect(formatDateRange(["2026-09-01", "not a date"])).toBe(+ "September 1, 2026 – ",+ );+ });+});diff --git a/frontend/src/embedding-sdk-bundle/sdk-bundle-exports.ts b/frontend/src/embedding-sdk-bundle/sdk-bundle-exports.tsindex bd764695422..189a3e04f92 100644--- a/frontend/src/embedding-sdk-bundle/sdk-bundle-exports.ts+++ b/frontend/src/embedding-sdk-bundle/sdk-bundle-exports.ts@@ -32,11 +32,12 @@ import { resolveDatasetQuery } from "embedding-sdk-bundle/lib/create-metabase-quimport { queryDataset } from "embedding-sdk-bundle/lib/query-dataset";import { queryQuestion } from "embedding-sdk-bundle/lib/query-question";import { validateFunctionSchema } from "embedding-sdk-bundle/lib/validate-function-schema";+import { DateRangeCalendar } from "embedding-sdk-bundle/components/public/DateRangeCalendar/DateRangeCalendar";import {- DataAppLink,- DataAppRouter,- dataAppRouting,-} from "embedding-sdk-bundle/lib/data-app/router";+ formatDate,+ formatDateRange,+} from "embedding-sdk-bundle/lib/format-date-range";+import { DateRangePopover } from "embedding-sdk-bundle/components/public/DateRangePopover/DateRangePopover";/*** IMPORTANT!@@ -47,8 +48,8 @@ export const sdkBundleExports: MetabaseEmbeddingSdkBundleExports = {CollectionBrowser,CreateDashboardModal,CreateQuestion,- DataAppLink,- DataAppRouter,+ DateRangeCalendar,+ DateRangePopover,EditableDashboard,InteractiveDashboard,InteractiveQuestion,@@ -71,6 +72,7 @@ export const sdkBundleExports: MetabaseEmbeddingSdkBundleExports = {SdkThemeProviderWithStore,queryDataset,queryQuestion,- dataAppRouting,executeAction,+ formatDate,+ formatDateRange,};diff --git a/frontend/src/embedding-sdk-bundle/types/sdk-bundle.ts b/frontend/src/embedding-sdk-bundle/types/sdk-bundle.tsindex 2fdbec9e45e..df78f2cfc63 100644--- a/frontend/src/embedding-sdk-bundle/types/sdk-bundle.ts+++ b/frontend/src/embedding-sdk-bundle/types/sdk-bundle.ts@@ -6,6 +6,8 @@ import type { CollectionBrowser } from "embedding-sdk-bundle/components/public/Cimport type { ComponentProvider } from "embedding-sdk-bundle/components/public/ComponentProvider";import type { CreateDashboardModal } from "embedding-sdk-bundle/components/public/CreateDashboardModal";import type { CreateQuestion } from "embedding-sdk-bundle/components/public/CreateQuestion";+import type { DateRangeCalendar } from "embedding-sdk-bundle/components/public/DateRangeCalendar/DateRangeCalendar";+import type { DateRangePopover } from "embedding-sdk-bundle/components/public/DateRangePopover/DateRangePopover";import type { InteractiveQuestion } from "embedding-sdk-bundle/components/public/InteractiveQuestion/InteractiveQuestion";import type { MetabotQuestion } from "embedding-sdk-bundle/components/public/MetabotQuestion";import type { SdkDebugInfo } from "embedding-sdk-bundle/components/public/SdkDebugInfo/SdkDebugInfo";@@ -14,14 +16,14 @@ import type { EditableDashboard } from "embedding-sdk-bundle/components/public/dimport type { InteractiveDashboard } from "embedding-sdk-bundle/components/public/dashboard/InteractiveDashboard";import type { StaticDashboard } from "embedding-sdk-bundle/components/public/dashboard/StaticDashboard";import type { ResolveDatasetQuery } from "embedding-sdk-bundle/lib/create-metabase-query";-import type {- DataAppLink,- DataAppRouter,-} from "embedding-sdk-bundle/lib/data-app/router";import type {ExecuteActionParams,ExecuteActionResult,} from "embedding-sdk-bundle/lib/execute-action";+import type {+ formatDate,+ formatDateRange,+} from "embedding-sdk-bundle/lib/format-date-range";import type {QueryDatasetParams,QueryDatasetResult,@@ -60,14 +62,14 @@ export type MetabaseEmbeddingSdkBundleExports = PublicExports &InternalHooksExports &SchemaValidationUtils &InternalComponentExports &- DataAppRoutingExports;+ DateFormattingExports;type PublicExports = {CollectionBrowser: InternalComponent<typeof CollectionBrowser>;CreateDashboardModal: InternalComponent<typeof CreateDashboardModal>;CreateQuestion: InternalComponent<typeof CreateQuestion>;- DataAppLink: typeof DataAppLink;- DataAppRouter: typeof DataAppRouter;+ DateRangeCalendar: typeof DateRangeCalendar;+ DateRangePopover: typeof DateRangePopover;EditableDashboard: InternalComponent<typeof EditableDashboard>;InteractiveDashboard: InternalComponent<typeof InteractiveDashboard>;InteractiveQuestion: InternalComponent<typeof InteractiveQuestion>;@@ -78,14 +80,6 @@ type PublicExports = {StaticQuestion: InternalComponent<typeof StaticQuestion>;};-type DataAppRoutingExports = {- dataAppRouting: {- getBasename: () => string;- navigate: (to: string) => void;- subscribe: (callback: () => void) => () => void;- };-};-type ReduxStoreExports = {getSdkStore: ReduxStoreFactory;};@@ -126,6 +120,11 @@ type SchemaValidationUtils = {) => FunctionSchemaValidationResult<unknown[], unknown>;};+type DateFormattingExports = {+ formatDate: typeof formatDate;+ formatDateRange: typeof formatDateRange;+};+type InternalComponentExports = {MetabotSubscriber: typeof MetabotSubscriber;SdkThemeProviderWithStore: typeof SdkThemeProviderWithStore;diff --git a/frontend/src/metabase/router/index.ts b/frontend/src/metabase/router/index.tsindex 78de6f81109..62e7575982d 100644--- a/frontend/src/metabase/router/index.ts+++ b/frontend/src/metabase/router/index.ts@@ -37,4 +37,3 @@ export {notifyLocationListeners,subscribeLocation,} from "./navigator";-export { getRawBrowserHistory } from "./raw-history";diff --git a/frontend/src/metabase/router/raw-history.ts b/frontend/src/metabase/router/raw-history.tsdeleted file mode 100644index f5b6318590c..00000000000--- a/frontend/src/metabase/router/raw-history.ts+++ /dev/null@@ -1,22 +0,0 @@-import {- type HistoryRouterProps,- UNSAFE_createBrowserHistory as createBrowserHistory,-} from "react-router";--// react-router does not export the `History` interface directly, so pull it off-// the history prop of `unstable_HistoryRouter`.-type History = HistoryRouterProps["history"];--let rawBrowserHistory: History | null = null;--/**- * A plain browser history for imperative navigation outside the app's router- * tree, replacing v3's global `browserHistory` singleton. The SDK data-app bundle- * mounts no router, so it drives its iframe URL through this instead. Created- * lazily on first use, so it never exists in the main app, where a second history- * would fight the mounted router over `popstate`.- */-export function getRawBrowserHistory(): History {- rawBrowserHistory ??= createBrowserHistory({ v5Compat: true });- return rawBrowserHistory;-}diff --git a/frontend/src/metabase/ui/components/inputs/DatePicker/index.ts b/frontend/src/metabase/ui/components/inputs/DatePicker/index.tsindex b30c9b2c475..5b48af413e4 100644--- a/frontend/src/metabase/ui/components/inputs/DatePicker/index.ts+++ b/frontend/src/metabase/ui/components/inputs/DatePicker/index.ts@@ -1,3 +1,3 @@-export { DatePicker } from "@mantine/dates";+export { DatePicker, getFormattedDate } from "@mantine/dates";export type { DatePickerProps } from "@mantine/dates";export { datePickerOverrides } from "./DatePicker.config";diff --git a/skills/metabase-data-app-semantic-layer/SKILL.md b/skills/metabase-data-app-semantic-layer/SKILL.mdindex 339f1a2e0bd..0f64f6f1148 100644--- a/skills/metabase-data-app-semantic-layer/SKILL.md+++ b/skills/metabase-data-app-semantic-layer/SKILL.md@@ -23,9 +23,10 @@ Keep the semantic layer and presentation layer separate.- Do not hardcode categorical filter option values. A generated schema field only proves the field exists, not which values exist; query options from Metabase at runtime using the same generated schema field that the filter applies.- Dashboard-level filters should visibly affect every compatible card, table, KPI, and trend. If a filter can only apply to one query, make that scope obvious in the UI; do not show duplicate or no-op date controls.- Entity filters, where the stored value is an id/key and the UI shows a label, must use a single searchable combobox. Click/focus must open the option list immediately, before typing. Query options at runtime, search labels, and store the raw value. Never render entity filters as `<select>`; plain selects are only for short closed enums explicitly provided by the user.-- Do not use native `<input type="date">` for data-app filter bars. Its placeholder and calendar popover are browser-controlled, often show `mm/dd/yyyy`, and cannot be reliably themed. If the repo already has a date picker component or component library, use that. Otherwise install `react-datepicker` for custom date selection.-- Import `react-datepicker/dist/react-datepicker.css`, then add small CSS overrides for the app's visual style if needed.-- Date bars must include Custom last by default: duration presets, All time, then Custom. Omit Custom only when the user explicitly asks for fixed presets only or no date range control. Date pickers must receive `Date | null`, never `new Date("")` or another invalid date for incomplete ranges; type strict callback parameters explicitly, such as `onChange={(date: Date | null) => ...}`.+- Use `DateRangePopover` from `@metabase/embedding-sdk-react/data-app` for custom date ranges: it wraps the app's own trigger element and opens a Metabase-styled range calendar under it. The trigger stays the app's — style it like the other filter controls — and `useDateFormatter()` from the same entry produces its label. It ships with the SDK and needs no dependency and no CSS import. `DateRangeCalendar` is the same calendar inline, for when the app already has a container. Do not install a date picker library for a range — not `react-datepicker`, `react-day-picker`, `flatpickr`, or a UI suite's picker (`@mui/x-date-pickers`, `antd`, `rsuite`, …). Do not use native `<input type="date">` either: its placeholder and calendar popover are browser-controlled, often show `mm/dd/yyyy`, and cannot be reliably themed.+- Never build a date label with `new Date("YYYY-MM-DD")` — a date-only string parses as UTC and shows the previous day west of Greenwich. Use `formatDateRange` / `formatDate` from `useDateFormatter()`, which parse in local time and format in the instance's locale.+- Reach for a third-party date picker only for what the SDK calendar does not cover, such as single-date or date-time selection; `react-datepicker` is the default pick. Then import its stylesheet (`react-datepicker/dist/react-datepicker.css`), add small CSS overrides for the app's visual style if needed, and pass `Date | null` — never `new Date("")` or another invalid date for incomplete ranges; type strict callback parameters explicitly, such as `onChange={(date: Date | null) => ...}`.+- Date bars must include Custom last by default: duration presets, All time, then Custom. Omit Custom only when the user explicitly asks for fixed presets only or no date range control.- Never invent aggregation or measure objects such as `{ name: "count" }` or `{ name: "sum", field: ... }`. Use generated table measures or exported aggregation helpers.- Only render values returned by Metabase or deterministic transforms of returned values. Do not invent KPI values, trends, labels, statuses, ratings, timestamps, rankings, insights, segments, or chart series.- Do not custom-render ambiguous business fields such as `margin`, `rate`, `score`, `percent`, `health`, `risk`, or `efficiency`. Do not add `%`, multiply by 100, color-code, or render stars unless semantic-layer units explicitly support it; use an SDK table/chart, omit the field, or ask for curation.@@ -575,26 +576,24 @@ For the common memoized date/category filter shape:type DatePreset = "30d" | "90d" | "custom" | "all";const [datePreset, setDatePreset] = useState<DatePreset>("all");-const [customStart, setCustomStart] = useState<Date | null>(null);-const [customEnd, setCustomEnd] = useState<Date | null>(null);+const [customRange, setCustomRange] = useState<[string | null, string | null]>([+ null,+ null,+]);const [status, setStatus] = useState("all");-const toLocalDateString = (date: Date) =>- `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`;-const dateRange = useMemo((): readonly [string, string] | null => {if (datePreset === "all") {return null;}if (datePreset === "custom") {- return customStart && customEnd- ? [toLocalDateString(customStart), toLocalDateString(customEnd)]- : null;+ const [start, end] = customRange;+ return start && end ? [start, end] : null;}return getPresetDateRange(datePreset);-}, [datePreset, customStart, customEnd]);+}, [datePreset, customRange]);const orderFilters = useMemo(() => [@@ -609,7 +608,7 @@ const orderFilters = useMemo();```-When date picker state uses `Date | null`, convert selected dates with a local `YYYY-MM-DD` formatter before passing them to `filter(..., "between", range)`. Do not use `date.toISOString().split("T")[0]` for local date filters.+`customRange` above is what `<DateRangePopover value={customRange} onChange={setCustomRange}>` stores, so there is nothing to convert. When a fallback picker's state uses `Date | null`, convert selected dates with a local `YYYY-MM-DD` formatter before passing them to `filter(..., "between", range)`. Do not use `date.toISOString().split("T")[0]` for local date filters.## Result Shape And Charts@@ -686,7 +685,8 @@ If no curated schema entry supports the intended UI, leave the section out or as- Shipping a date preset bar with no Custom range option, or Custom before All time.- Charting opaque IDs such as `franchise_id` when a user-facing name is available.- Rendering an entity filter in a plain `<select>`, even if the current runtime option list is short.-- Using native `<input type="date">` and shipping browser-controlled `mm/dd/yyyy` placeholders or unthemed calendar popovers.+- Reaching for native `<input type="date">` or any date picker dependency (`react-datepicker`, `react-day-picker`, a UI suite's picker) for a date range instead of `DateRangePopover`, and shipping browser-controlled `mm/dd/yyyy` placeholders or unthemed calendar popovers.+- Labelling a date trigger with `new Date("YYYY-MM-DD").toLocaleDateString()` instead of `useDateFormatter()`, so the label is a day early for users west of Greenwich.- Assuming `filter(...)` fully validates value types.- Letting a `null` bucket become the latest time-series point.- Hardcoding business values, labels, timestamps, or rankings.diff --git a/skills/metabase-data-app-semantic-layer/references/filter-ui-patterns.md b/skills/metabase-data-app-semantic-layer/references/filter-ui-patterns.mdindex a774ddabd76..29f043dcb28 100644--- a/skills/metabase-data-app-semantic-layer/references/filter-ui-patterns.md+++ b/skills/metabase-data-app-semantic-layer/references/filter-ui-patterns.md@@ -127,21 +127,59 @@ Style this to match the app. If accessibility, keyboard behavior, or popover posDate ranges should use ISO `YYYY-MM-DD` strings for query values. Never use `type="date"`.-For custom date pickers:+Include a Custom range option in date preset bars by default. Omit it only when the user explicitly asks for fixed presets only or no date range control. Order presets as durations first, then All time, then Custom last.-- Include a Custom range option in date preset bars by default. Omit it only when the user explicitly asks for fixed presets only or no date range control. Order presets as durations first, then All time, then Custom last.-- First check whether the repo already has a date picker component or component library. If it does, use the existing component.-- If the repo has no existing date picker, install `react-datepicker`. The default data-app template only includes React, React DOM, and the Metabase SDK.-- Do not install a large UI suite just for one data-app date filter.-- Type strict `react-datepicker` callbacks explicitly, for example `onChange={(date: Date | null) => ...}` for single-date pickers.-- For custom date ranges, use `selectsRange` with local `Date | null` start/end state, but only commit the query range when both dates are selected.-- If the custom range control should look like the other preset buttons, use `customInput` with a `forwardRef` button, spread react-datepicker's injected props, and call its injected `onClick` so the popover still opens.-- Convert selected dates to ISO `YYYY-MM-DD` strings with local date getters (`getFullYear`, `getMonth`, `getDate`) rather than `toISOString()`.-- For date-picker `selected` props, parse saved strings defensively and pass `null` for empty or invalid values. Never pass `new Date("")`.-- Recent `react-datepicker` packages include their own TypeScript types; do not add `@types/react-datepicker` unless the installed version actually needs it.+### Use the built-in `DateRangePopover`++`DateRangePopover` wraps the app's own trigger and opens a Metabase-styled range calendar under it. The trigger is yours — a button styled exactly like the preset buttons beside it — and the SDK owns the calendar, the popover positioning, outside-click and Escape. No dependency to install, no CSS to import.++```tsx+import {+ DateRangePopover,+ useDateFormatter,+} from "@metabase/embedding-sdk-react/data-app";++const { formatDateRange } = useDateFormatter();+const [range, setRange] = useState<[string | null, string | null]>([+ null,+ null,+]);+const [start, end] = range;++const dateFilters =+ start && end+ ? [filter(ordersTable.fields.createdAt, "between", [start, end])]+ : [];++<DateRangePopover value={range} onChange={setRange}>+ <button className="filter-button">+ {formatDateRange(range) || "Custom"}+ </button>+</DateRangePopover>;+```++Both ends are `YYYY-MM-DD` strings — the same shape `filter(...)` takes, so there is no `Date` conversion and no time zone to get wrong.-Install `react-datepicker` only when the repo does not already have a date picker:+- The trigger must be a single DOM element or a `forwardRef` component; the popover attaches a ref and a click handler to it. Give it the same class as the other filter controls so it matches them.+- Label the trigger with `formatDateRange(range)` from `useDateFormatter()`. It is the same formatter Mantine's date input draws its own label with, in the instance's locale, so the trigger reads exactly as the built-in input would; it returns `""` until the SDK bundle has loaded and re-renders the trigger when it has. Never use `new Date("YYYY-MM-DD")` — a date-only string parses as UTC and shows the previous day west of Greenwich. The three states are `""`, `"September 1, 2026 – "`, and `"September 1, 2026 – September 10, 2026"`; `formatDate` does one end. Options: `format` (a dayjs format) and `separator`.+- `onChange` fires on every calendar click, so it reports half-picked ranges as `[start, null]`. Build the filter only when both ends are set; a half-picked range means no date filter, not a sentinel date.+- The popover closes itself once both ends are picked (`closeOnSelect`, default true). Pass `opened` / `onOpenedChange` to drive it yourself.+- Other props: `defaultValue`, `minDate`, `maxDate` (`YYYY-MM-DD`), `numberOfColumns` (months side by side, default 2), `position` (default `bottom-start`).+- `DateRangeCalendar` is the same calendar with no popover, for rendering inline in a container the app already has. Same value props, plus `className` / `style`.++### Falling back to a third-party picker++Only for what the SDK calendar does not cover, such as single-date or date-time selection. Nothing else justifies a picker dependency — `react-datepicker`, `react-day-picker`, `flatpickr`, `@mui/x-date-pickers`, `antd` and `rsuite` are all the same mistake for a plain date range. The default data-app template ships React, React DOM, and the Metabase SDK, so this adds a dependency:```bashnpm install react-datepicker```++`react-datepicker` is the default pick; the rest of this section assumes it.++- Do not install a large UI suite just for one data-app date filter.+- Import `react-datepicker/dist/react-datepicker.css`, then add small CSS overrides for the app's visual style if needed.+- Type strict `react-datepicker` callbacks explicitly, for example `onChange={(date: Date | null) => ...}` for single-date pickers.+- Convert selected dates to ISO `YYYY-MM-DD` strings with local date getters (`getFullYear`, `getMonth`, `getDate`) rather than `toISOString()`.+- For date-picker `selected` props, parse saved strings defensively and pass `null` for empty or invalid values. Never pass `new Date("")`.+- Recent `react-datepicker` packages include their own TypeScript types; do not add `@types/react-datepicker` unless the installed version actually needs it.diff --git a/skills/metabase-data-app-setup/SKILL.md b/skills/metabase-data-app-setup/SKILL.mdindex b79125aaf3f..44b65bc1d1d 100644--- a/skills/metabase-data-app-setup/SKILL.md+++ b/skills/metabase-data-app-setup/SKILL.md@@ -209,7 +209,7 @@ There is intentionally **no escape hatch** for extra Vite plugins, aliases, or `**After every meaningful round of edits, run `npm run typecheck`.** It runs `tsc --noEmit` over `src/` and `vite.config.ts` — catches wrong prop shapes against the SDK types, broken refactors, missing imports, etc. The Vite dev server does NOT typecheck (it only transpiles), so errors that would fail a production CI run can sit invisibly in a passing `npm run dev` session. Run it before declaring a task complete.-**Before handoff, re-check package hygiene.** `@metabase/embedding-sdk-react` should use the expected data-app SDK source/tag for the target environment, and `@types/react-datepicker` should not be installed unless the chosen `react-datepicker` version actually needs it.+**Before handoff, re-check package hygiene.** `@metabase/embedding-sdk-react` should use the expected data-app SDK source/tag for the target environment. No date picker dependency should be installed when the app only needs date ranges — not `react-datepicker`, `react-day-picker`, `flatpickr`, or a UI suite's picker (`@mui/x-date-pickers`, `antd`, `rsuite`, …); that is `DateRangePopover` from `@metabase/embedding-sdk-react/data-app`. `@types/react-datepicker` should not be installed unless the chosen `react-datepicker` version actually needs it.## Reading the diagnostics feed@@ -435,6 +435,7 @@ The bundle imports React hooks/JSX, SDK components from `@metabase/embedding-sdk| `CreateDashboardModal` | Modal for new-dashboard flow. || `CollectionBrowser` | Collection picker. || `@metabase/embedding-sdk-react/data-app` exports | Data-app-only helpers for routing, schema-backed data reads, actions, clipboard, and sandbox-safe integration. Treat schema-backed queries, generated schema files, filters, metrics, actions, and other data-layer behavior as existing-data-app editing work; use skill discovery before authoring that code. |+| `DateRangePopover`, `DateRangeCalendar`, `useDateFormatter` (from `@metabase/embedding-sdk-react/data-app`) | Date range selection for filter bars. `DateRangePopover` wraps the app's own trigger element and opens a Metabase-styled range calendar under it; `DateRangeCalendar` is that calendar inline. `value`/`onChange` are `[start, end]` pairs of `YYYY-MM-DD` strings, `null` on either end while half-picked. `useDateFormatter().formatDateRange(value)` makes the trigger's label in the instance's locale, without the UTC-parsing bug of `new Date("YYYY-MM-DD")`. Use these instead of `<input type="date">` or a third-party picker — no dependency, no CSS import. |### Blocked APIs@@ -450,7 +451,7 @@ The Near Membrane sandbox throws at runtime on these globals. Use the endowed re| **Other `navigator.*` device APIs** — `geolocation`, etc. | Not available. || **Global `document`/`window` listeners** for typing/clipboard events — `keydown`, `keyup`, `keypress`, `beforeinput`, `input`, `paste`, `copy`, `cut`, `before*paste/copy/cut`, `compositionstart/update/end`, `storage` | Attach the listener to your own element, or use the React handler (`onKeyDown`, `onPaste`, …) on the specific input/container. The same listener on a script-owned element still works. |-**Rule of thumb:** if you're about to touch `window.X`, `document.X`, `navigator.X`, `history.X`, or any storage global, stop and pick the endowed replacement above. The endowed surface (React + React DOM + SDK components + data hooks + `useAction` + DataAppRouter + `copy`) covers every routine need; anything outside it is intentionally unreachable.+**Rule of thumb:** if you're about to touch `window.X`, `document.X`, `navigator.X`, `history.X`, or any storage global, stop and pick the endowed replacement above. The endowed surface (React + React DOM + SDK components + data hooks + `useAction` + DataAppRouter + `DateRangePopover` + `copy`) covers every routine need; anything outside it is intentionally unreachable.### Rendering a chart: Metabase first