Skip to content

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

fix(documents): add proper rendering optimizations of the cards (#70832)

Uladzimir Havenchykf77ee419ccf0
diff --git a/frontend/src/metabase-types/api/mocks/comment.ts b/frontend/src/metabase-types/api/mocks/comment.ts
index ed5932163d5..f125fdd2dc6 100644
--- a/frontend/src/metabase-types/api/mocks/comment.ts
+++ b/frontend/src/metabase-types/api/mocks/comment.ts
@@ -7,8 +7,6 @@ import { createMockUser } from "./user";
export function createMockComment(comment?: Partial<Comment>): Comment {
return {
- ...comment,
-
id: getNextId(),
parent_comment_id: null,
@@ -28,5 +26,7 @@ export function createMockComment(comment?: Partial<Comment>): Comment {
reactions: [],
version: 1,
+
+ ...comment,
};
}
diff --git a/frontend/src/metabase/api/public.ts b/frontend/src/metabase/api/public.ts
index 4d251b83ea8..06bf040e19f 100644
--- a/frontend/src/metabase/api/public.ts
+++ b/frontend/src/metabase/api/public.ts
@@ -19,6 +19,11 @@ export type PublicDashcardQueryRequest = {
ignore_cache?: boolean;
};
+export type PublicDocumentCardQueryRequest = {
+ uuid: string;
+ cardId: CardId;
+};
+
const PIVOT_PREFIX = `${publicBase}/pivot`;
export const publicApi = Api.injectEndpoints({
@@ -58,6 +63,18 @@ export const publicApi = Api.injectEndpoints({
}),
keepUnusedDataFor: 0,
}),
+ // Unlike the endpoints above this one keeps the default cache window:
+ // public document cards subscribe only while near the viewport, so
+ // dropping data on unsubscribe would refetch on every scroll back.
+ getPublicDocumentCardQuery: builder.query<
+ Dataset,
+ PublicDocumentCardQueryRequest
+ >({
+ query: ({ uuid, cardId }) => ({
+ method: "GET",
+ url: `${publicBase}/document/${uuid}/card/${cardId}`,
+ }),
+ }),
}),
});
@@ -66,4 +83,5 @@ export const {
useGetPublicCardQueryPivotQuery,
useGetPublicDashcardQueryQuery,
useGetPublicDashcardQueryPivotQuery,
+ useGetPublicDocumentCardQueryQuery,
} = publicApi;
diff --git a/frontend/src/metabase/common/components/ExplicitSize/ExplicitSize.tsx b/frontend/src/metabase/common/components/ExplicitSize/ExplicitSize.tsx
index ede150a8f74..d6700f34a4c 100644
--- a/frontend/src/metabase/common/components/ExplicitSize/ExplicitSize.tsx
+++ b/frontend/src/metabase/common/components/ExplicitSize/ExplicitSize.tsx
@@ -223,22 +223,49 @@ export function ExplicitSize<T>({
);
}
- __updateSize = () => {
+ __updateSize = (entry?: ResizeObserverEntry) => {
const element = this._getElement();
- if (element) {
- const { width, height } = element.getBoundingClientRect();
+ if (!element) {
+ return;
+ }
- if (!width && !height) {
- // cypress raises lots of errors in timeline trying to call setState
- // on the unmounted element, so we're just ignoring
- return;
- }
+ let width: number;
+ let height: number;
- if (this.state.width !== width || this.state.height !== height) {
- this.setState({ width, height }, () =>
- this.props?.onUpdateSize?.(),
- );
- }
+ // ResizeObserver entry's dimensions free to read, prefer it over
+ // getBoundingClientRect() which forces re-layout.
+ if (entry && entry.target === element) {
+ const box = entry.borderBoxSize?.[0];
+ width = box ? box.inlineSize : entry.contentRect.width;
+ height = box ? box.blockSize : entry.contentRect.height;
+ } else {
+ const rect = element.getBoundingClientRect();
+ width = rect.width;
+ height = rect.height;
+ }
+
+ if (!width && !height) {
+ // cypress raises lots of errors in timeline trying to call setState
+ // on the unmounted element, so we're just ignoring
+ return;
+ }
+
+ const { width: prevWidth, height: prevHeight } = this.state;
+
+ // The two measurement sources report sub-pixel sizes with different
+ // precision: @juggle/resize-observer (used in the SDK) rounds box
+ // sizes to three decimals while getBoundingClientRect() does not.
+ // Ignore sub-pixel deltas so alternating sources don't produce
+ // spurious size updates — each one re-renders charts, and an echarts
+ // resize dismisses any open tooltip.
+ const hasChanged =
+ prevWidth === null ||
+ prevHeight === null ||
+ Math.abs(prevWidth - width) >= 1 ||
+ Math.abs(prevHeight - height) >= 1;
+
+ if (hasChanged) {
+ this.setState({ width, height }, () => this.props?.onUpdateSize?.());
}
};
render() {
diff --git a/frontend/src/metabase/common/components/ExplicitSize/ExplicitSize.unit.spec.tsx b/frontend/src/metabase/common/components/ExplicitSize/ExplicitSize.unit.spec.tsx
new file mode 100644
index 00000000000..b4b0e237a37
--- /dev/null
+++ b/frontend/src/metabase/common/components/ExplicitSize/ExplicitSize.unit.spec.tsx
@@ -0,0 +1,134 @@
+import { act, render, screen } from "@testing-library/react";
+import { forwardRef } from "react";
+
+import resizeObserver from "metabase/utils/resize-observer";
+
+import { ExplicitSize } from "./ExplicitSize";
+
+jest.mock("metabase/utils/resize-observer", () => {
+ const callbacks = new Map<
+ Element,
+ (entry: Partial<ResizeObserverEntry>) => void
+ >();
+
+ return {
+ __esModule: true,
+ default: {
+ subscribe: (
+ target: Element,
+ callback: (entry: Partial<ResizeObserverEntry>) => void,
+ ) => {
+ callbacks.set(target, callback);
+ },
+ unsubscribe: (target: Element) => {
+ callbacks.delete(target);
+ },
+ _trigger: (target: Element, entry: Partial<ResizeObserverEntry>) => {
+ callbacks.get(target)?.(entry);
+ },
+ },
+ };
+});
+
+const triggerResize = (
+ target: Element,
+ entry: Partial<ResizeObserverEntry>,
+) => {
+ act(() => {
+ (
+ resizeObserver as unknown as {
+ _trigger: (
+ target: Element,
+ entry: Partial<ResizeObserverEntry>,
+ ) => void;
+ }
+ )._trigger(target, entry);
+ // flush the trailing call of the throttled size update
+ jest.advanceTimersByTime(500);
+ });
+};
+
+const renderSpy = jest.fn();
+
+const Base = forwardRef<
+ HTMLDivElement,
+ { width: number | null; height: number | null }
+>(function Base({ width, height }, ref) {
+ renderSpy();
+ return (
+ <div ref={ref} data-testid="sized">
+ {String(width)}x{String(height)}
+ </div>
+ );
+});
+
+const SizedComponent = ExplicitSize<{
+ width: number | null;
+ height: number | null;
+}>()(Base);
+
+const createEntry = (
+ target: Element,
+ inlineSize: number,
+ blockSize: number,
+): Partial<ResizeObserverEntry> =>
+ ({
+ target,
+ borderBoxSize: [{ inlineSize, blockSize }],
+ contentRect: {
+ width: inlineSize,
+ height: blockSize,
+ },
+ }) as unknown as Partial<ResizeObserverEntry>;
+
+describe("ExplicitSize", () => {
+ beforeEach(() => {
+ jest.useFakeTimers();
+ renderSpy.mockClear();
+ });
+
+ afterEach(() => {
+ jest.useRealTimers();
+ });
+
+ it("should pass the size from resize observer entries to the wrapped component", () => {
+ render(<SizedComponent />);
+ const element = screen.getByTestId("sized");
+
+ triggerResize(element, createEntry(element, 400, 866.812));
+
+ expect(screen.getByTestId("sized")).toHaveTextContent("400x866.812");
+ });
+
+ it("should ignore sub-pixel size changes between measurement sources", () => {
+ render(<SizedComponent />);
+ const element = screen.getByTestId("sized");
+
+ triggerResize(element, createEntry(element, 400, 866.812));
+ renderSpy.mockClear();
+
+ // getBoundingClientRect reports full-precision values, while
+ // @juggle/resize-observer rounds box sizes to three decimals
+ jest.spyOn(element, "getBoundingClientRect").mockReturnValue({
+ width: 400,
+ height: 866.8125,
+ } as DOMRect);
+
+ // an entry for another element falls back to getBoundingClientRect()
+ triggerResize(element, { target: document.body });
+
+ expect(renderSpy).not.toHaveBeenCalled();
+ expect(screen.getByTestId("sized")).toHaveTextContent("400x866.812");
+ });
+
+ it("should re-render when the size changes by a pixel or more", () => {
+ render(<SizedComponent />);
+ const element = screen.getByTestId("sized");
+
+ triggerResize(element, createEntry(element, 400, 866.812));
+
+ triggerResize(element, createEntry(element, 400, 868));
+
+ expect(screen.getByTestId("sized")).toHaveTextContent("400x868");
+ });
+});
diff --git a/frontend/src/metabase/common/hooks/use-is-prefetch-allowed.ts b/frontend/src/metabase/common/hooks/use-is-prefetch-allowed.ts
new file mode 100644
index 00000000000..0a928dba28a
--- /dev/null
+++ b/frontend/src/metabase/common/hooks/use-is-prefetch-allowed.ts
@@ -0,0 +1,10 @@
+import { useNetwork } from "@mantine/hooks";
+
+/**
+ * Returns false when the user has explicitly opted into Data Saver mode
+ * (`navigator.connection.saveData`)
+ */
+export function useIsPrefetchAllowed(): boolean {
+ const { saveData } = useNetwork();
+ return saveData !== true;
+}
diff --git a/frontend/src/metabase/documents/components/DocumentHeader.tsx b/frontend/src/metabase/documents/components/DocumentHeader.tsx
index e8414348bab..f477d0c6ead 100644
--- a/frontend/src/metabase/documents/components/DocumentHeader.tsx
+++ b/frontend/src/metabase/documents/components/DocumentHeader.tsx
@@ -8,7 +8,9 @@ import {
getFormattedTime,
} from "metabase/common/components/DateTime";
import { useSetting } from "metabase/common/hooks";
+import { waitUntilNextFramePainted } from "metabase/common/utils/wait-until-next-frame-paints";
import CS from "metabase/css/core/index.css";
+import { usePrintContext } from "metabase/documents/contexts/PrintContext";
import { useSelector } from "metabase/redux";
import { getUserIsAdmin } from "metabase/selectors/user";
import {
@@ -17,6 +19,7 @@ import {
Button,
Flex,
Icon,
+ Loader,
Menu,
Text,
TextInput,
@@ -85,10 +88,34 @@ export const DocumentHeader = ({
const hasPublicLink = !!document?.public_uuid;
- const handlePrint = useCallback(() => {
+ const { prepareForPrint } = usePrintContext();
+
+ const [isMenuOpen, setIsMenuOpen] = useState(false);
+ const [isPreparingForPrint, setIsPreparingForPrint] = useState(false);
+
+ const handlePrint = useCallback(async () => {
+ setIsPreparingForPrint(true);
+ try {
+ await prepareForPrint();
+ } finally {
+ setIsPreparingForPrint(false);
+ }
+ setIsMenuOpen(false);
+ await waitUntilNextFramePainted();
window.print();
trackDocumentPrint(document);
- }, [document]);
+ }, [document, prepareForPrint]);
+
+ const handleMenuChange = useCallback(
+ (opened: boolean) => {
+ if (!opened && isPreparingForPrint) {
+ return;
+ }
+
+ setIsMenuOpen(opened);
+ },
+ [isPreparingForPrint],
+ );
return (
<Flex
@@ -184,7 +211,11 @@ export const DocumentHeader = ({
</Tooltip>
)}
{!document?.archived && (
- <Menu position="bottom-end">
+ <Menu
+ position="bottom-end"
+ opened={isMenuOpen}
+ onChange={handleMenuChange}
+ >
<Menu.Target>
<ActionIcon
variant="subtle"
@@ -197,7 +228,15 @@ export const DocumentHeader = ({
</Menu.Target>
<Menu.Dropdown>
<Menu.Item
- leftSection={<Icon name="document" />}
+ leftSection={
+ isPreparingForPrint ? (
+ <Loader size="xs" />
+ ) : (
+ <Icon name="document" />
+ )
+ }
+ closeMenuOnClick={false}
+ disabled={isPreparingForPrint}
onClick={handlePrint}
>
{t`Print Document`}
diff --git a/frontend/src/metabase/documents/components/DocumentHeader.unit.spec.tsx b/frontend/src/metabase/documents/components/DocumentHeader.unit.spec.tsx
index 2e2825e0664..3d48134b8f5 100644
--- a/frontend/src/metabase/documents/components/DocumentHeader.unit.spec.tsx
+++ b/frontend/src/metabase/documents/components/DocumentHeader.unit.spec.tsx
@@ -1,7 +1,11 @@
import userEvent from "@testing-library/user-event";
import { setupCommentEndpoints } from "__support__/server-mocks";
-import { renderWithProviders, screen } from "__support__/ui";
+import { renderWithProviders, screen, waitFor } from "__support__/ui";
+import {
+ PrintContext,
+ type PrintContextValue,
+} from "metabase/documents/contexts/PrintContext";
import { createMockDocument, createMockUser } from "metabase-types/api/mocks";
import { DOCUMENT_TITLE_MAX_LENGTH } from "../constants";
@@ -29,6 +33,7 @@ const setup = ({
onToggleBookmark = jest.fn(),
onArchive = jest.fn(),
onShowHistory = jest.fn(),
+ printContext = undefined as PrintContextValue | undefined,
} = {}) => {
const props = {
document,
@@ -51,7 +56,15 @@ const setup = ({
target_id: document.id,
});
- renderWithProviders(<DocumentHeader {...props} />, {
+ const header = printContext ? (
+ <PrintContext.Provider value={printContext}>
+ <DocumentHeader {...props} />
+ </PrintContext.Provider>
+ ) : (
+ <DocumentHeader {...props} />
+ );
+
+ renderWithProviders(header, {
storeInitialState: {
currentUser: createMockUser({ is_superuser: isAdmin }),
settings: {
@@ -138,7 +151,63 @@ describe("DocumentHeader", () => {
await userEvent.click(screen.getByLabelText("More options"));
await userEvent.click(screen.getByText("Print Document"));
- expect(window.print).toHaveBeenCalled();
+ await waitFor(() => expect(window.print).toHaveBeenCalled());
+
+ window.print = originalPrint;
+ });
+
+ it("should close the menu before opening the print dialog", async () => {
+ const originalPrint = window.print;
+ let menuExpandedAtPrintTime: string | null = null;
+ window.print = jest.fn(() => {
+ menuExpandedAtPrintTime = screen
+ .getByLabelText("More options")
+ .getAttribute("aria-expanded");
+ });
+
+ setup();
+
+ await userEvent.click(screen.getByLabelText("More options"));
+ await userEvent.click(screen.getByText("Print Document"));
+ await waitFor(() => expect(window.print).toHaveBeenCalled());
+
+ // The menu must already be closed when window.print() blocks the
+ // renderer, so no stale spinner frame is shown while the dialog is
+ // open or after it closes.
+ expect(menuExpandedAtPrintTime).toBe("false");
+
+ window.print = originalPrint;
+ });
+
+ it("should disable the print option only while preparing for print", async () => {
+ const originalPrint = window.print;
+ window.print = jest.fn();
+ let resolvePrepare: () => void = () => {};
+ const prepareForPrint = jest.fn(
+ () =>
+ new Promise<void>((resolve) => {
+ resolvePrepare = resolve;
+ }),
+ );
+
+ setup({ printContext: { isPrinting: false, prepareForPrint } });
+
+ await userEvent.click(screen.getByLabelText("More options"));
+ await userEvent.click(screen.getByText("Print Document"));
+
+ // Preparation is in progress: the item is disabled with a spinner.
+ expect(
+ screen.getByRole("menuitem", { name: /Print Document/ }),
+ ).toBeDisabled();
+ expect(window.print).not.toHaveBeenCalled();
+
+ resolvePrepare();
+
+ // Once preparation resolves, the menu closes and printing starts.
+ await waitFor(() => expect(window.print).toHaveBeenCalled());
+ expect(
+ screen.queryByRole("menuitem", { name: /Print Document/ }),
+ ).not.toBeInTheDocument();
window.print = originalPrint;
});
diff --git a/frontend/src/metabase/documents/components/DocumentPage.tsx b/frontend/src/metabase/documents/components/DocumentPage.tsx
index a699ded1f3f..39e7516bf41 100644
--- a/frontend/src/metabase/documents/components/DocumentPage.tsx
+++ b/frontend/src/metabase/documents/components/DocumentPage.tsx
@@ -57,6 +57,12 @@ import {
trackDocumentUnsavedChangesWarningDisplayed,
trackDocumentUpdated,
} from "../analytics";
+import {
+ PrefetchQueueProvider,
+ usePrefetchQueue,
+} from "../contexts/PrefetchQueueContext";
+import { PrintContext } from "../contexts/PrintContext";
+import { ScrollContainerProvider } from "../contexts/ScrollContainerContext";
import {
clearDraftCards,
openVizSettingsSidebar,
@@ -67,6 +73,7 @@ import {
setIsHistorySidebarOpen,
} from "../documents.slice";
import { useDocumentState } from "../hooks/use-document-state";
+import { usePrintContextValue } from "../hooks/use-print-context-value";
import { useRegisterDocumentMetabotContext } from "../hooks/use-register-document-metabot-context";
import { useScrollToAnchor } from "../hooks/use-scroll-to-anchor";
import {
@@ -84,6 +91,29 @@ import { DocumentRevisionHistorySidebar } from "./DocumentRevisionHistorySidebar
import { Editor } from "./Editor";
import { EmbedQuestionSettingsSidebar } from "./EmbedQuestionSettingsSidebar";
+// The prefetch queue tracks every card embed's in-flight load, so it doubles
+// as the print-readiness signal: printing waits until nothing is loading.
+const DocumentPrintContextProvider = ({
+ children,
+}: {
+ children: ReactNode;
+}) => {
+ const prefetchQueue = usePrefetchQueue();
+ const areDocumentCardsReadyForPrint = useCallback(
+ () => !prefetchQueue?.hasInflightLoads(),
+ [prefetchQueue],
+ );
+ const printContextValue = usePrintContextValue({
+ isReady: areDocumentCardsReadyForPrint,
+ });
+
+ return (
+ <PrintContext.Provider value={printContextValue}>
+ {children}
+ </PrintContext.Provider>
+ );
+};
+
export const DocumentPage = ({
params,
route,
@@ -102,6 +132,7 @@ export const DocumentPage = ({
const previousLocationKey = usePrevious(location.key);
const forceUpdate = useForceUpdate();
const dispatch = useDispatch();
+
const selectedQuestionId = useSelector(getSelectedQuestionId);
const selectedEmbedIndex = useSelector(getSelectedEmbedIndex);
const draftCards = useSelector(getDraftCards);
@@ -110,6 +141,9 @@ export const DocumentPage = ({
null,
);
const editorContainerRef = useRef<HTMLDivElement>(null);
+ const [mainContentEl, setMainContentEl] = useState<HTMLDivElement | null>(
+ null,
+ );
const hasUnsavedEditorChanges = useSelector(getHasUnsavedChanges);
const [createDocument, { isLoading: isCreating }] =
useCreateDocumentMutation();
@@ -471,164 +505,177 @@ export const DocumentPage = ({
}, [isLeaveConfirmModalOpen, documentData]);
return (
- <Box className={styles.documentPage}>
- {documentData?.archived && <DocumentArchivedEntityBanner />}
- <Box className={styles.contentArea}>
- <Box className={styles.mainContent}>
- <Box className={styles.documentContainer}>
- <DocumentHeader
- document={documentData}
- documentTitle={documentTitle}
- isNewDocument={isNewDocument}
- canWrite={canWrite ?? false}
- showSaveButton={showSaveButton ?? false}
- isBookmarked={isBookmarked}
- onTitleChange={setDocumentTitle}
- onTitleSubmit={focusEditorBody}
- onSave={() => {
- if (isNewDocument) {
- setCollectionPickerMode("save");
- } else {
- handleSave();
+ <PrefetchQueueProvider>
+ <DocumentPrintContextProvider>
+ <Box className={styles.documentPage}>
+ {documentData?.archived && <DocumentArchivedEntityBanner />}
+ <Box className={styles.contentArea}>
+ <Box className={styles.mainContent} ref={setMainContentEl}>
+ <ScrollContainerProvider value={mainContentEl}>
+ <Box className={styles.documentContainer}>
+ <DocumentHeader
+ document={documentData}
+ documentTitle={documentTitle}
+ isNewDocument={isNewDocument}
+ canWrite={canWrite ?? false}
+ showSaveButton={showSaveButton ?? false}
+ isBookmarked={isBookmarked}
+ onTitleChange={setDocumentTitle}
+ onTitleSubmit={focusEditorBody}
+ onSave={() => {
+ if (isNewDocument) {
+ setCollectionPickerMode("save");
+ } else {
+ handleSave();
+ }
+ }}
+ onMove={() => setCollectionPickerMode("move")}
+ onDuplicate={handleDuplicate}
+ onToggleBookmark={handleToggleBookmark}
+ onArchive={() => handleUpdate({ archived: true })}
+ onShowHistory={handleShowHistory}
+ />
+ <Editor
+ onEditorReady={setEditorInstance}
+ onCardEmbedsChange={updateCardEmbeds}
+ onQuestionSelect={handleQuestionSelect}
+ initialContent={documentContent}
+ onChange={handleChange}
+ editable={canWrite && !isSaving}
+ isLoading={isDocumentLoading}
+ editorContainerRef={editorContainerRef}
+ />
+ </Box>
+ </ScrollContainerProvider>
+ </Box>
+
+ {selectedQuestionId &&
+ selectedEmbedIndex !== null &&
+ editorInstance && (
+ <Box
+ className={styles.sidebar}
+ data-testid="document-card-sidebar"
+ >
+ <EmbedQuestionSettingsSidebar
+ cardId={selectedQuestionId}
+ editorInstance={editorInstance}
+ />
+ </Box>
+ )}
+
+ {collectionPickerMode && (
+ <CollectionPickerModal
+ title={t`Where should we save this document?`}
+ onClose={() => setCollectionPickerMode(null)}
+ entityType="document"
+ value={{
+ id: documentData?.collection_id ?? "root",
+ model: "collection",
+ }}
+ onChange={(collection) => {
+ if (collectionPickerMode === "save") {
+ handleSave(canonicalCollectionId(collection.id));
+ setCollectionPickerMode(null);
+ } else if (collectionPickerMode === "move") {
+ handleUpdate({
+ collection_id: canonicalCollectionId(collection.id),
+ });
+ }
+ }}
+ />
+ )}
+
+ {duplicateModalMode === "duplicate" && documentData && (
+ <CopyModal
+ entityType="documents"
+ onClose={() => setDuplicateModalMode(null)}
+ onSaved={(document) => {
+ setDuplicateModalMode(null);
+ scheduleNavigation(() => {
+ dispatch(push(Urls.document(document)));
+ });
+ }}
+ entityObject={documentData}
+ title={t`Duplicate "${documentData?.name}"`}
+ overwriteOnInitialValuesChange
+ copy={async (object) => {
+ if (!documentData?.id) {
+ throw new Error(
+ "Cannot duplicate document that has not been saved",
+ );
+ }
+
+ const response = await copyDocument({
+ ...object,
+ id: documentData.id,
+ });
+
+ if (!response.data) {
+ throw (
+ response.error ??
+ new Error("Failed to duplicate document")
+ );
+ }
+
+ const _document = response.data;
+ trackDocumentDuplicated(_document);
+ return _document;
+ }}
+ />
+ )}
+
+ {children}
+
+ <LeaveRouteConfirmModal
+ // `key` remounts this modal when navigating between different documents or to a new document.
+ // The `route` doesn't change in that scenario which prevents the modal from closing when you confirm you want to discard your changes.
+ key={location.key}
+ isEnabled={hasUnsavedChanges() && !isNavigationScheduled}
+ route={route}
+ onOpenChange={(open) => {
+ if (open) {
+ trackDocumentUnsavedChangesWarningDisplayed(documentData);
}
}}
- onMove={() => setCollectionPickerMode("move")}
- onDuplicate={handleDuplicate}
- onToggleBookmark={handleToggleBookmark}
- onArchive={() => handleUpdate({ archived: true })}
- onShowHistory={handleShowHistory}
/>
- <Editor
- onEditorReady={setEditorInstance}
- onCardEmbedsChange={updateCardEmbeds}
- onQuestionSelect={handleQuestionSelect}
- initialContent={documentContent}
- onChange={handleChange}
- editable={canWrite && !isSaving}
- isLoading={isDocumentLoading}
- editorContainerRef={editorContainerRef}
+
+ <LeaveConfirmModal
+ // only applies when going from /new -> /new
+ opened={isLeaveConfirmModalOpen}
+ onConfirm={resetDocument}
+ onClose={() => forceUpdate()}
/>
- </Box>
- </Box>
- {selectedQuestionId &&
- selectedEmbedIndex !== null &&
- editorInstance && (
- <Box className={styles.sidebar} data-testid="document-card-sidebar">
- <EmbedQuestionSettingsSidebar
- cardId={selectedQuestionId}
- editorInstance={editorInstance}
+ <ConfirmModal
+ // only applies when trying to duplicate a document that has unsaved changes
+ opened={duplicateModalMode === "leave"}
+ confirmButtonText={t`Save changes`}
+ confirmButtonProps={{ color: "brand" }}
+ data-testid="save-confirmation"
+ message={t`You need to save before you can duplicate this document.`}
+ title={t`Save your changes first`}
+ onConfirm={async () => {
+ if ((await handleSave())?.error) {
+ throw new Error("Failed to save document");
+ }
+ setDuplicateModalMode("duplicate");
+ }}
+ onClose={() => setDuplicateModalMode(null)}
+ />
+ </Box>
+ {isHistorySidebarOpen && documentData && (
+ <Box
+ className={styles.sidebar}
+ data-testid="document-history-sidebar"
+ >
+ <DocumentRevisionHistorySidebar
+ document={documentData}
+ onClose={() => dispatch(setIsHistorySidebarOpen(false))}
/>
</Box>
)}
-
- {collectionPickerMode && (
- <CollectionPickerModal
- title={t`Where should we save this document?`}
- onClose={() => setCollectionPickerMode(null)}
- entityType="document"
- value={{
- id: documentData?.collection_id ?? "root",
- model: "collection",
- }}
- onChange={(collection) => {
- if (collectionPickerMode === "save") {
- handleSave(canonicalCollectionId(collection.id));
- setCollectionPickerMode(null);
- } else if (collectionPickerMode === "move") {
- handleUpdate({
- collection_id: canonicalCollectionId(collection.id),
- });
- }
- }}
- />
- )}
-
- {duplicateModalMode === "duplicate" && documentData && (
- <CopyModal
- entityType="documents"
- onClose={() => setDuplicateModalMode(null)}
- onSaved={(document) => {
- setDuplicateModalMode(null);
- scheduleNavigation(() => {
- dispatch(push(Urls.document(document)));
- });
- }}
- entityObject={documentData}
- title={t`Duplicate "${documentData?.name}"`}
- overwriteOnInitialValuesChange
- copy={async (object) => {
- if (!documentData?.id) {
- throw new Error(
- "Cannot duplicate document that has not been saved",
- );
- }
-
- const response = await copyDocument({
- ...object,
- id: documentData.id,
- });
-
- if (!response.data) {
- throw (
- response.error ?? new Error("Failed to duplicate document")
- );
- }
-
- const _document = response.data;
- trackDocumentDuplicated(_document);
- return _document;
- }}
- />
- )}
-
- {children}
-
- <LeaveRouteConfirmModal
- // `key` remounts this modal when navigating between different documents or to a new document.
- // The `route` doesn't change in that scenario which prevents the modal from closing when you confirm you want to discard your changes.
- key={location.key}
- isEnabled={hasUnsavedChanges() && !isNavigationScheduled}
- route={route}
- onOpenChange={(open) => {
- if (open) {
- trackDocumentUnsavedChangesWarningDisplayed(documentData);
- }
- }}
- />
-
- <LeaveConfirmModal
- // only applies when going from /new -> /new
- opened={isLeaveConfirmModalOpen}
- onConfirm={resetDocument}
- onClose={() => forceUpdate()}
- />
-
- <ConfirmModal
- // only applies when trying to duplicate a document that has unsaved changes
- opened={duplicateModalMode === "leave"}
- confirmButtonText={t`Save changes`}
- confirmButtonProps={{ color: "brand" }}
- data-testid="save-confirmation"
- message={t`You need to save before you can duplicate this document.`}
- title={t`Save your changes first`}
- onConfirm={async () => {
- if ((await handleSave())?.error) {
- throw new Error("Failed to save document");
- }
- setDuplicateModalMode("duplicate");
- }}
- onClose={() => setDuplicateModalMode(null)}
- />
- </Box>
- {isHistorySidebarOpen && documentData && (
- <Box className={styles.sidebar} data-testid="document-history-sidebar">
- <DocumentRevisionHistorySidebar
- document={documentData}
- onClose={() => dispatch(setIsHistorySidebarOpen(false))}
- />
</Box>
- )}
- </Box>
+ </DocumentPrintContextProvider>
+ </PrefetchQueueProvider>
);
};
diff --git a/frontend/src/metabase/documents/components/Editor/Editor.stories.tsx b/frontend/src/metabase/documents/components/Editor/Editor.stories.tsx
index 0cb5ce50892..ddc27f24286 100644
--- a/frontend/src/metabase/documents/components/Editor/Editor.stories.tsx
+++ b/frontend/src/metabase/documents/components/Editor/Editor.stories.tsx
@@ -6,6 +6,10 @@ import _ from "underscore";
import { getStore } from "__support__/entities-store";
import { mockSettings } from "__support__/settings";
import { createMockEntitiesState } from "__support__/store";
+import {
+ ForceDocumentCardRenderDecorator,
+ createWaitForChartsDecorator,
+} from "__support__/storybook";
import { Api } from "metabase/api";
import { commonReducers } from "metabase/reducers-common";
import { MetabaseReduxProvider } from "metabase/redux";
@@ -127,4 +131,9 @@ export const CardEmbed = {
args: {
initialContent: Data.cardEmbed,
},
+ // Render the cards eagerly, then hold the snapshot until both charts paint.
+ decorators: [
+ ForceDocumentCardRenderDecorator,
+ createWaitForChartsDecorator({ count: 2 }),
+ ],
};
diff --git a/frontend/src/metabase/documents/contexts/ExternalCardDataContext.tsx b/frontend/src/metabase/documents/contexts/ExternalCardDataContext.tsx
index c5a1ba6eab8..75fcb2e7395 100644
--- a/frontend/src/metabase/documents/contexts/ExternalCardDataContext.tsx
+++ b/frontend/src/metabase/documents/contexts/ExternalCardDataContext.tsx
@@ -1,14 +1,12 @@
import { createContext, useContext } from "react";
-import type { Card, Dataset } from "metabase-types/api";
+import type { Card } from "metabase-types/api";
export interface ExternalCardDataContextValue {
/** Pre-loaded card metadata, keyed by card ID */
cards: Record<number, Card>;
/** Identifier for the external source (e.g., public document UUID) */
documentUuid: string;
- /** Load query results for a card from the external source */
- loadCardQuery: (cardId: number) => Promise<Dataset>;
}
const ExternalCardDataContext =
diff --git a/frontend/src/metabase/documents/contexts/PrefetchQueueContext.tsx b/frontend/src/metabase/documents/contexts/PrefetchQueueContext.tsx
new file mode 100644
index 00000000000..95b887107c2
--- /dev/null
+++ b/frontend/src/metabase/documents/contexts/PrefetchQueueContext.tsx
@@ -0,0 +1,38 @@
+import {
+ type ReactNode,
+ createContext,
+ useContext,
+ useEffect,
+ useMemo,
+} from "react";
+
+import { useIsPrefetchAllowed } from "metabase/common/hooks/use-is-prefetch-allowed";
+import {
+ type PrefetchQueue,
+ PrefetchQueueStore,
+} from "metabase/documents/utils/prefetch-queue";
+
+const PrefetchQueueContext = createContext<PrefetchQueue | null>(null);
+
+export function PrefetchQueueProvider({ children }: { children: ReactNode }) {
+ const store = useMemo(() => new PrefetchQueueStore(), []);
+ const isAllowed = useIsPrefetchAllowed();
+
+ useEffect(() => {
+ store.setEnabled(isAllowed);
+ }, [store, isAllowed]);
+
+ useEffect(() => {
+ return () => store.destroy();
+ }, [store]);
+
+ return (
+ <PrefetchQueueContext.Provider value={store}>
+ {children}
+ </PrefetchQueueContext.Provider>
+ );
+}
+
+export function usePrefetchQueue(): PrefetchQueue | null {
+ return useContext(PrefetchQueueContext);
+}
diff --git a/frontend/src/metabase/documents/contexts/PrintContext.ts b/frontend/src/metabase/documents/contexts/PrintContext.ts
new file mode 100644
index 00000000000..5f061b3f893
--- /dev/null
+++ b/frontend/src/metabase/documents/contexts/PrintContext.ts
@@ -0,0 +1,15 @@
+import { createContext, useContext } from "react";
+
+export type PrintContextValue = {
+ isPrinting: boolean;
+ prepareForPrint: () => Promise<void>;
+};
+
+export const PrintContext = createContext<PrintContextValue>({
+ isPrinting: false,
+ prepareForPrint: async () => {},
+});
+
+export function usePrintContext(): PrintContextValue {
+ return useContext(PrintContext);
+}
diff --git a/frontend/src/metabase/documents/contexts/ScrollContainerContext.ts b/frontend/src/metabase/documents/contexts/ScrollContainerContext.ts
new file mode 100644
index 00000000000..85e018dd996
--- /dev/null
+++ b/frontend/src/metabase/documents/contexts/ScrollContainerContext.ts
@@ -0,0 +1,9 @@
+import { createContext, useContext } from "react";
+
+export const ScrollContainerContext = createContext<HTMLElement | null>(null);
+
+export const ScrollContainerProvider = ScrollContainerContext.Provider;
+
+export function useScrollContainer(): HTMLElement | null {
+ return useContext(ScrollContainerContext);
+}
diff --git a/frontend/src/metabase/documents/hooks/use-block-menus.ts b/frontend/src/metabase/documents/hooks/use-block-menus.ts
index b54ebdba5e2..2c280b64c50 100644
--- a/frontend/src/metabase/documents/hooks/use-block-menus.ts
+++ b/frontend/src/metabase/documents/hooks/use-block-menus.ts
@@ -1,7 +1,9 @@
import { autoUpdate, useFloating } from "@floating-ui/react";
+import { useMergedRef } from "@mantine/hooks";
import type { Editor, NodeViewProps } from "@tiptap/core";
-import { useCallback, useEffect, useState } from "react";
+import { useEffect, useState } from "react";
+import { useNodeInViewport } from "metabase/documents/hooks/use-node-in-viewport";
import { useUnresolvedCommentsCount } from "metabase/documents/hooks/use-unresolved-comments-count";
import {
getChildTargetId,
@@ -38,7 +40,11 @@ export function useBlockMenus({
const document = useSelector(getCurrentDocument);
const { _id } = node.attrs;
- const unresolvedCommentsCount = useUnresolvedCommentsCount(_id);
+ const { ref: viewportRef, isInViewport } = useNodeInViewport();
+
+ const unresolvedCommentsCount = useUnresolvedCommentsCount(_id, {
+ skip: !isInViewport,
+ });
const [hovered, setHovered] = useState(false);
const [rendered, setRendered] = useState(false);
@@ -46,12 +52,14 @@ export function useBlockMenus({
const isOpen = childTargetId === _id;
const isHovered = hoveredChildTargetId === _id;
+ const floatingOpen = rendered && isInViewport;
+
const { refs: commentsRefs, floatingStyles: commentsFloatingStyles } =
useFloating({
placement: "right-start",
whileElementsMounted: autoUpdate,
strategy: "fixed",
- open: rendered,
+ open: floatingOpen,
});
const { refs: anchorRefs, floatingStyles: anchorFloatingStyles } =
@@ -59,7 +67,7 @@ export function useBlockMenus({
placement: "left",
whileElementsMounted: autoUpdate,
strategy: "fixed",
- open: rendered,
+ open: floatingOpen,
});
useEffect(() => {
@@ -73,22 +81,19 @@ export function useBlockMenus({
const shouldShowMenus =
document &&
rendered &&
+ isInViewport &&
!shouldHideMenus &&
isTopLevelBlock &&
!isWithinIframe() &&
hasContent;
const anchorUrl = document ? documentWithAnchor(document, _id) : "";
- // Note: refs.setReference is stable (memoized internally by floating-ui),
- // but the refs object itself is recreated each render. Depend on the
- // stable setReference functions directly to avoid unnecessary re-renders.
- const setReferenceElement = useCallback(
- (el: HTMLElement | null) => {
- commentsRefs.setReference(el);
- anchorRefs.setReference(el);
- },
- // eslint-disable-next-line react-hooks/exhaustive-deps
- [commentsRefs.setReference, anchorRefs.setReference],
+ // Merges the viewport IntersectionObserver ref with the floating-ui
+ // reference setters into a single stable callback ref.
+ const setReferenceElement = useMergedRef<HTMLElement>(
+ viewportRef,
+ commentsRefs.setReference,
+ anchorRefs.setReference,
);
return {
diff --git a/frontend/src/metabase/documents/hooks/use-block-menus.unit.spec.ts b/frontend/src/metabase/documents/hooks/use-block-menus.unit.spec.ts
new file mode 100644
index 00000000000..08312d23732
--- /dev/null
+++ b/frontend/src/metabase/documents/hooks/use-block-menus.unit.spec.ts
@@ -0,0 +1,92 @@
+import fetchMock from "fetch-mock";
+
+import { setupMockIntersectionObserver } from "__support__/intersection-observer";
+import { setupCommentEndpoints } from "__support__/server-mocks";
+import { act, renderHookWithProviders, waitFor } from "__support__/ui";
+import { delay } from "__support__/utils";
+import { initialState as documentsInitialState } from "metabase/documents/documents.slice";
+import {
+ createMockNodeViewProps,
+ createMockProseMirrorNode,
+} from "metabase/rich_text_editing/tiptap/extensions/MetabotEmbed/__support__/node-view-mocks";
+import type { Comment } from "metabase-types/api";
+import { createMockDocument } from "metabase-types/api/mocks";
+import { createMockComment } from "metabase-types/api/mocks/comment";
+
+import { useBlockMenus } from "./use-block-menus";
+
+const NODE_ID = "test-id";
+const mockDocument = createMockDocument({ id: 1 });
+
+const nodeViewProps = createMockNodeViewProps({
+ node: createMockProseMirrorNode({
+ attrs: { _id: NODE_ID },
+ textContent: "test content",
+ }),
+});
+
+describe("useBlockMenus", () => {
+ const { setIntersecting } = setupMockIntersectionObserver();
+
+ function setup({ comments }: { comments: Comment[] }) {
+ setupCommentEndpoints(comments, {
+ target_type: "document",
+ target_id: mockDocument.id,
+ });
+
+ const { result } = renderHookWithProviders(
+ () =>
+ useBlockMenus({
+ node: nodeViewProps.node,
+ editor: nodeViewProps.editor,
+ getPos: nodeViewProps.getPos,
+ }),
+ {
+ storeInitialState: {
+ documents: {
+ ...documentsInitialState,
+ currentDocument: mockDocument,
+ },
+ },
+ },
+ );
+
+ // Attach a reference element so the IntersectionObserver starts observing.
+ act(() => {
+ result.current.setReferenceElement(document.createElement("div"));
+ });
+
+ return { result };
+ }
+
+ it("does not fetch comments or show menus while off-screen", async () => {
+ const { result } = setup({
+ comments: [createMockComment({ child_target_id: NODE_ID })],
+ });
+
+ setIntersecting(false);
+ // Give a potential (unwanted) comments request a chance to fire.
+ await delay(0);
+
+ expect(fetchMock.callHistory.calls()).toHaveLength(0);
+ expect(result.current.unresolvedCommentsCount).toBe(0);
+ expect(result.current.shouldShowMenus).toBeFalsy();
+ });
+
+ it("fetches the unresolved comments count and shows menus when in viewport", async () => {
+ const { result } = setup({
+ comments: [
+ createMockComment({ child_target_id: NODE_ID }),
+ createMockComment({ child_target_id: NODE_ID, is_resolved: true }),
+ createMockComment({ child_target_id: "another-node" }),
+ ],
+ });
+
+ setIntersecting(true);
+
+ await waitFor(() => {
+ expect(result.current.unresolvedCommentsCount).toBe(1);
+ });
+ expect(result.current.shouldShowMenus).toBe(true);
+ });
+});
diff --git a/frontend/src/metabase/documents/hooks/use-card-data.ts b/frontend/src/metabase/documents/hooks/use-card-data.ts
index 7af763c3179..c8cb727fb54 100644
--- a/frontend/src/metabase/documents/hooks/use-card-data.ts
+++ b/frontend/src/metabase/documents/hooks/use-card-data.ts
@@ -16,6 +16,7 @@ import { getCardWithDraft } from "../selectors";
interface UseCardDataProps {
id: number;
+ skip?: boolean;
}
export interface UseCardDataResult {
@@ -83,9 +84,12 @@ function selectIsLoadingDataset(
return isLoadingDraft;
}
-export function useCardData({ id }: UseCardDataProps): UseCardDataResult {
+export function useCardData({
+ id,
+ skip = false,
+}: UseCardDataProps): UseCardDataResult {
const isDraft = id < 0;
- const shouldSkipSavedCard = !id || isDraft;
+ const shouldSkipSavedCard = !id || isDraft || skip;
const {
data: card,
@@ -116,8 +120,8 @@ export function useCardData({ id }: UseCardDataProps): UseCardDataResult {
}
}, [isDraft, isPivotTable, cardToUse, metadata]);
- const shouldSkipRegularQuery = !id || isDraft || !card;
- const canQueryDraftCard = isDraft && cardToUse?.dataset_query;
+ const shouldSkipRegularQuery = !id || isDraft || !card || skip;
+ const canQueryDraftCard = isDraft && cardToUse?.dataset_query && !skip;
const shouldQueryDraftNonPivot = canQueryDraftCard && !isPivotTable;
const shouldQueryDraftPivot = canQueryDraftCard && isPivotTable && metadata;
diff --git a/frontend/src/metabase/documents/hooks/use-external-card-data.ts b/frontend/src/metabase/documents/hooks/use-external-card-data.ts
index ea64b424551..4959f1307fe 100644
--- a/frontend/src/metabase/documents/hooks/use-external-card-data.ts
+++ b/frontend/src/metabase/documents/hooks/use-external-card-data.ts
@@ -1,11 +1,11 @@
import { useMemo } from "react";
-import { useAsync } from "react-use";
+import { skipToken, useGetPublicDocumentCardQueryQuery } from "metabase/api";
import { useExternalCardData } from "metabase/documents/contexts/ExternalCardDataContext";
import { useSelector } from "metabase/redux";
import { getMetadata } from "metabase/selectors/metadata";
import Question from "metabase-lib/v1/Question";
-import type { Card, Dataset, RawSeries } from "metabase-types/api";
+import type { Card, CardId, Dataset, RawSeries } from "metabase-types/api";
import type { UseCardDataResult } from "./use-card-data";
@@ -19,31 +19,25 @@ function buildSeries(card: Card, dataset: Dataset): RawSeries {
];
}
-export function useExternalCardDataLoader(cardId: number): UseCardDataResult {
+export function useExternalCardDataLoader(
+ cardId: CardId,
+ { skip = false }: { skip?: boolean } = {},
+): UseCardDataResult {
const context = useExternalCardData();
const metadata = useSelector(getMetadata);
const card = context?.cards?.[cardId];
-
const documentUuid = context?.documentUuid;
- const loadCardQuery = context?.loadCardQuery;
+
+ const shouldSkip = skip || !cardId || !card || !documentUuid;
const {
- value: dataset,
- loading: isLoadingDataset,
+ data: dataset,
+ isLoading: isLoadingDataset,
error: datasetError,
- } = useAsync(async () => {
- if (!loadCardQuery || !cardId || !documentUuid || !card) {
- return undefined;
- }
-
- try {
- return await loadCardQuery(cardId);
- } catch (error) {
- console.error("Failed to load external document card data:", error);
- throw error;
- }
- }, [cardId, documentUuid, card]);
+ } = useGetPublicDocumentCardQueryQuery(
+ shouldSkip ? skipToken : { uuid: documentUuid, cardId },
+ );
const question = useMemo(
() => (card ? new Question(card, metadata) : undefined),
diff --git a/frontend/src/metabase/documents/hooks/use-node-in-viewport.ts b/frontend/src/metabase/documents/hooks/use-node-in-viewport.ts
new file mode 100644
index 00000000000..6d2b780f53d
--- /dev/null
+++ b/frontend/src/metabase/documents/hooks/use-node-in-viewport.ts
@@ -0,0 +1,93 @@
+import { useIntersection, useMergedRef } from "@mantine/hooks";
+import { useCallback, useEffect, useRef, useSyncExternalStore } from "react";
+
+import { useCurrentRef } from "metabase/common/hooks/use-current-ref";
+import { usePrefetchQueue } from "metabase/documents/contexts/PrefetchQueueContext";
+import { usePrintContext } from "metabase/documents/contexts/PrintContext";
+import { useScrollContainer } from "metabase/documents/contexts/ScrollContainerContext";
+
+const noopSubscribe = () => () => {};
+
+/**
+ * Detects whether a node view element is near the viewport (always true while
+ * printing). With an `id`, the node also joins the prefetch queue
+ */
+export function useNodeInViewport(id?: string) {
+ const scrollContainer = useScrollContainer();
+ const { isPrinting } = usePrintContext();
+ const prefetchQueue = usePrefetchQueue();
+
+ const { ref: ioRef, entry } = useIntersection({
+ root: scrollContainer,
+ // 200% margin: IO fires when the card is up to 2 viewport heights
+ // away from visible, giving React + ECharts time to mount before
+ // the user can see the card during normal scrolling. Trade-off:
+ // more visualizations stay mounted in the buffer, but bounded
+ // (~5-8 cards in a typical doc).
+ rootMargin: "200%",
+ threshold: 0,
+ });
+
+ const elementRef = useRef<HTMLElement | null>(null);
+ const ref = useMergedRef(elementRef, ioRef);
+
+ const ioIntersecting = entry?.isIntersecting ?? false;
+
+ // Only nodes with an id can hold prefetch tickets, so id-less nodes
+ // (text blocks) skip the store subscription instead of being notified
+ // on every ticket grant.
+ const subscribe = useCallback(
+ (onChange: () => void) =>
+ id != null && prefetchQueue
+ ? prefetchQueue.subscribe(onChange)
+ : noopSubscribe(),
+ [prefetchQueue, id],
+ );
+ const hasPrefetchTicket = useSyncExternalStore(
+ subscribe,
+ () => (id != null && prefetchQueue ? prefetchQueue.hasTicket(id) : false),
+ () => false,
+ );
+
+ const isInViewport = isPrinting || ioIntersecting;
+ const isInViewportRef = useCurrentRef(isInViewport);
+
+ useEffect(() => {
+ if (!prefetchQueue || id == null) {
+ return;
+ }
+ return prefetchQueue.register({
+ id,
+ getElement: () => elementRef.current,
+ isInViewport: () => isInViewportRef.current,
+ });
+ }, [prefetchQueue, id, isInViewportRef]);
+
+ // Re-run the idle prefetch pass whenever any node's intersection state
+ // changes, so the coordinator can re-rank candidates by distance.
+ useEffect(() => {
+ prefetchQueue?.notifyViewportChange();
+ }, [prefetchQueue, ioIntersecting]);
+
+ const shouldLoadData = isInViewport || hasPrefetchTicket;
+
+ return { ref, isInViewport, shouldLoadData };
+}
+
+/**
+ * Companion to `useNodeInViewport`: reports the node's data-fetch state to
+ * the prefetch coordinator so it can limit concurrent prefetches and answer
+ * "is anything still loading?" for print readiness. Any node view that
+ * fetches data gated by `shouldLoadData` must also call this.
+ */
+export function useReportPrefetchLoading(id: string, isLoading: boolean) {
+ const prefetchQueue = usePrefetchQueue();
+
+ useEffect(() => {
+ if (!prefetchQueue) {
+ return;
+ }
+ prefetchQueue.reportLoading(id, isLoading);
+ return () => prefetchQueue.reportLoading(id, false);
+ }, [prefetchQueue, id, isLoading]);
+}
diff --git a/frontend/src/metabase/documents/hooks/use-node-in-viewport.unit.spec.tsx b/frontend/src/metabase/documents/hooks/use-node-in-viewport.unit.spec.tsx
new file mode 100644
index 00000000000..689bbb2b96c
--- /dev/null
+++ b/frontend/src/metabase/documents/hooks/use-node-in-viewport.unit.spec.tsx
@@ -0,0 +1,127 @@
+import { renderHook } from "@testing-library/react";
+import type { ReactNode } from "react";
+
+import { setupMockIntersectionObserver } from "__support__/intersection-observer";
+import { PrintContext } from "metabase/documents/contexts/PrintContext";
+import type { PrefetchQueue } from "metabase/documents/utils/prefetch-queue";
+
+import { useNodeInViewport } from "./use-node-in-viewport";
+
+function stubQueue(overrides: Partial<PrefetchQueue> = {}): PrefetchQueue {
+ return {
+ setEnabled: () => {},
+ register: () => () => {},
+ reportLoading: () => {},
+ notifyViewportChange: () => {},
+ hasTicket: () => false,
+ hasInflightLoads: () => false,
+ subscribe: () => () => {},
+ destroy: () => {},
+ ...overrides,
+ };
+}
+
+const mockUsePrefetchQueue = jest.fn();
+jest.mock("metabase/documents/contexts/PrefetchQueueContext", () => ({
+ usePrefetchQueue: () => mockUsePrefetchQueue(),
+}));
+
+const printingWrapper = ({ children }: { children: ReactNode }) => (
+ <PrintContext.Provider
+ value={{ isPrinting: true, prepareForPrint: async () => {} }}
+ >
+ {children}
+ </PrintContext.Provider>
+);
+
+describe("useNodeInViewport", () => {
+ const { setIntersecting, getObserverOptions } =
+ setupMockIntersectionObserver();
+
+ beforeEach(() => {
+ jest.clearAllMocks();
+ mockUsePrefetchQueue.mockReturnValue(null);
+ });
+
+ function setup(id?: string, options?: { isPrinting?: boolean }) {
+ const view = renderHook(() => useNodeInViewport(id), {
+ wrapper: options?.isPrinting ? printingWrapper : undefined,
+ });
+ // The observer is only created once the ref attaches to an element.
+ view.result.current.ref(document.createElement("div"));
+ return view;
+ }
+
+ it("treats null entry (initial state) as out-of-viewport so queries are deferred", () => {
+ const { result } = setup();
+
+ expect(result.current.isInViewport).toBe(false);
+ });
+
+ it("returns true when entry is intersecting", () => {
+ const { result } = setup();
+
+ setIntersecting(true);
+
+ expect(result.current.isInViewport).toBe(true);
+ });
+
+ it("returns false when entry is not intersecting", () => {
+ const { result } = setup();
+
+ setIntersecting(false);
+
+ expect(result.current.isInViewport).toBe(false);
+ });
+
+ it("returns true when printing regardless of intersection entry", () => {
+ const { result } = setup(undefined, { isPrinting: true });
+
+ setIntersecting(false);
+
+ expect(result.current.isInViewport).toBe(true);
+ });
+
+ it("observes with a 200% rootMargin", () => {
+ setup();
+
+ expect(getObserverOptions()).toEqual(
+ expect.objectContaining({
+ rootMargin: "200%",
+ threshold: 0,
+ }),
+ );
+ });
+
+ describe("shouldLoadData", () => {
+ it("matches isInViewport when no prefetch queue is provided", () => {
+ const { result } = setup("node-1");
+
+ setIntersecting(true);
+
+ expect(result.current.shouldLoadData).toBe(true);
+ });
+
+ it("is false when off-screen and queue has not granted a ticket", () => {
+ mockUsePrefetchQueue.mockReturnValue(
+ stubQueue({ hasTicket: () => false }),
+ );
+
+ const { result } = setup("node-1");
+ setIntersecting(false);
+
+ expect(result.current.shouldLoadData).toBe(false);
+ });
+
+ it("is true when off-screen but queue has granted a prefetch ticket", () => {
+ mockUsePrefetchQueue.mockReturnValue(
+ stubQueue({ hasTicket: () => true }),
+ );
+
+ const { result } = setup("node-1");
+ setIntersecting(false);
+
+ expect(result.current.shouldLoadData).toBe(true);
+ });
+ });
+});
diff --git a/frontend/src/metabase/documents/hooks/use-print-context-value.ts b/frontend/src/metabase/documents/hooks/use-print-context-value.ts
new file mode 100644
index 00000000000..e7c6e1bf1a9
--- /dev/null
+++ b/frontend/src/metabase/documents/hooks/use-print-context-value.ts
@@ -0,0 +1,40 @@
+import { useWindowEvent } from "@mantine/hooks";
+import { useCallback, useMemo, useState } from "react";
+
+import { waitUntilNextFramePainted } from "metabase/common/utils/wait-until-next-frame-paints";
+import type { PrintContextValue } from "metabase/documents/contexts/PrintContext";
+import { delay } from "metabase/utils/promise";
+
+const READINESS_TIMEOUT_MS = 15_000;
+const POLL_INTERVAL_MS = 100;
+
+type UsePrintContextValueOptions = {
+ isReady?: () => boolean;
+};
+
+export function usePrintContextValue({
+ isReady,
+}: UsePrintContextValueOptions = {}): PrintContextValue {
+ const [isPrinting, setIsPrinting] = useState(false);
+
+ useWindowEvent("beforeprint", () => setIsPrinting(true));
+ useWindowEvent("afterprint", () => setIsPrinting(false));
+
+ const prepareForPrint = useCallback(async () => {
+ setIsPrinting(true);
+
+ // Wait for the print flag to paint so lazy card queries start (and
+ // register as in-flight) before we poll readiness and call window.print().
+ await waitUntilNextFramePainted();
+
+ const deadline = Date.now() + READINESS_TIMEOUT_MS;
+ while (isReady && !isReady() && Date.now() < deadline) {
+ await delay(POLL_INTERVAL_MS);
+ }
+ }, [isReady]);
+
+ return useMemo(
+ () => ({ isPrinting, prepareForPrint }),
+ [isPrinting, prepareForPrint],
+ );
+}
diff --git a/frontend/src/metabase/documents/hooks/use-print-context-value.unit.spec.ts b/frontend/src/metabase/documents/hooks/use-print-context-value.unit.spec.ts
new file mode 100644
index 00000000000..72715dfb82c
--- /dev/null
+++ b/frontend/src/metabase/documents/hooks/use-print-context-value.unit.spec.ts
@@ -0,0 +1,107 @@
+import { act, renderHook } from "@testing-library/react";
+
+import { usePrintContextValue } from "./use-print-context-value";
+
+describe("usePrintContextValue", () => {
+ beforeEach(() => {
+ jest.useFakeTimers();
+ });
+
+ afterEach(() => {
+ jest.useRealTimers();
+ });
+
+ // Modern fake timers fake requestAnimationFrame, which jsdom schedules ~16ms
+ // apart, so advancing by one frame runs a single pending rAF callback.
+ async function advanceFrame() {
+ await act(() => jest.advanceTimersByTimeAsync(16));
+ }
+
+ it("sets and clears printing state from browser print events", () => {
+ const { result } = renderHook(() => usePrintContextValue());
+
+ expect(result.current.isPrinting).toBe(false);
+
+ act(() => window.dispatchEvent(new Event("beforeprint")));
+ expect(result.current.isPrinting).toBe(true);
+
+ act(() => window.dispatchEvent(new Event("afterprint")));
+ expect(result.current.isPrinting).toBe(false);
+ });
+
+ it("sets printing state and waits two animation frames before resolving", async () => {
+ const { result } = renderHook(() => usePrintContextValue());
+ let resolved = false;
+ let promise: Promise<void> | undefined;
+
+ act(() => {
+ promise = result.current.prepareForPrint().then(() => {
+ resolved = true;
+ });
+ });
+
+ expect(result.current.isPrinting).toBe(true);
+ expect(resolved).toBe(false);
+
+ await advanceFrame();
+ expect(resolved).toBe(false);
+
+ await advanceFrame();
+ await promise;
+ expect(resolved).toBe(true);
+ });
+
+ it("waits until the optional readiness predicate passes", async () => {
+ let ready = false;
+ const isReady = jest.fn(() => ready);
+ const { result } = renderHook(() => usePrintContextValue({ isReady }));
+ let resolved = false;
+ let promise: Promise<void> | undefined;
+
+ act(() => {
+ promise = result.current.prepareForPrint().then(() => {
+ resolved = true;
+ });
+ });
+
+ await advanceFrame();
+ await advanceFrame();
+
+ expect(isReady).toHaveBeenCalled();
+ expect(resolved).toBe(false);
+
+ ready = true;
+ await act(async () => {
+ jest.advanceTimersByTime(100);
+ await promise;
+ });
+
+ expect(resolved).toBe(true);
+ });
+
+ it("stops waiting when the readiness timeout expires", async () => {
+ const isReady = jest.fn(() => false);
+ const { result } = renderHook(() => usePrintContextValue({ isReady }));
+ let resolved = false;
+ let promise: Promise<void> | undefined;
+
+ act(() => {
+ promise = result.current.prepareForPrint().then(() => {
+ resolved = true;
+ });
+ });
+
+ await advanceFrame();
+ await advanceFrame();
+ expect(resolved).toBe(false);
+
+ await act(async () => {
+ // Push the faked clock past the 15s readiness deadline; the next poll
+ // tick then exits the wait loop even though isReady still returns false.
+ jest.advanceTimersByTime(16_000);
+ await promise;
+ });
+
+ expect(resolved).toBe(true);
+ });
+});
diff --git a/frontend/src/metabase/documents/hooks/use-unresolved-comments-count.ts b/frontend/src/metabase/documents/hooks/use-unresolved-comments-count.ts
index b82c04bdaf5..0d7714abcad 100644
--- a/frontend/src/metabase/documents/hooks/use-unresolved-comments-count.ts
+++ b/frontend/src/metabase/documents/hooks/use-unresolved-comments-count.ts
@@ -1,27 +1,29 @@
-import { useListCommentsQuery } from "metabase/api";
+import { skipToken, useListCommentsQuery } from "metabase/api";
import { getTargetChildCommentThreads } from "metabase/comments/utils";
import { getUnresolvedComments } from "metabase/documents/components/Editor/CommentsMenu";
import { getCurrentDocument } from "metabase/documents/selectors";
import { getListCommentsQuery } from "metabase/documents/utils/api";
import { useSelector } from "metabase/redux";
-export function useUnresolvedCommentsCount(targetId: string) {
+export function useUnresolvedCommentsCount(
+ targetId: string,
+ { skip = false }: { skip?: boolean } = {},
+) {
const document = useSelector(getCurrentDocument);
- const { unresolvedCommentsCount } = useListCommentsQuery(
- getListCommentsQuery(document),
- {
- selectFromResult: ({ data: commentsData }) => {
- const threads = getTargetChildCommentThreads(
- commentsData?.comments,
- targetId,
- );
- return {
- unresolvedCommentsCount: getUnresolvedComments(threads).length,
- };
- },
+ const query = skip ? skipToken : getListCommentsQuery(document);
+
+ const { unresolvedCommentsCount } = useListCommentsQuery(query, {
+ selectFromResult: ({ data: commentsData }) => {
+ const threads = getTargetChildCommentThreads(
+ commentsData?.comments,
+ targetId,
+ );
+ return {
+ unresolvedCommentsCount: getUnresolvedComments(threads).length,
+ };
},
- );
+ });
return unresolvedCommentsCount;
}
diff --git a/frontend/src/metabase/documents/utils/prefetch-queue.ts b/frontend/src/metabase/documents/utils/prefetch-queue.ts
new file mode 100644
index 00000000000..a6551fd68a3
--- /dev/null
+++ b/frontend/src/metabase/documents/utils/prefetch-queue.ts
@@ -0,0 +1,174 @@
+export const MAX_CONCURRENT_PREFETCHES = 3;
+
+const IDLE_TIMEOUT_MS = 2000;
+
+// Fallback delay when requestIdleCallback is unavailable (e.g. Safari < 16.4).
+const FALLBACK_DELAY_MS = 200;
+
+type Registration = {
+ id: string;
+ getElement: () => HTMLElement | null;
+ isInViewport: () => boolean;
+};
+
+type Listener = () => void;
+
+export type IdleScheduler = {
+ schedule: (cb: () => void) => number;
+ cancel: (handle: number) => void;
+};
+
+export interface PrefetchQueue {
+ setEnabled(enabled: boolean): void;
+ register(reg: Registration): () => void;
+ reportLoading(id: string, loading: boolean): void;
+ notifyViewportChange(): void;
+ hasTicket(id: string): boolean;
+ hasInflightLoads(): boolean;
+ subscribe(cb: Listener): () => void;
+ destroy(): void;
+}
+
+function defaultScheduler(): IdleScheduler {
+ if (typeof requestIdleCallback === "function") {
+ return {
+ schedule: (cb) => requestIdleCallback(cb, { timeout: IDLE_TIMEOUT_MS }),
+ cancel: (handle) => cancelIdleCallback(handle),
+ };
+ }
+ return {
+ schedule: (cb) => window.setTimeout(cb, FALLBACK_DELAY_MS),
+ cancel: (handle) => window.clearTimeout(handle),
+ };
+}
+
+export class PrefetchQueueStore implements PrefetchQueue {
+ private registrations = new Map<string, Registration>();
+ private inflightLoads = new Set<string>();
+ private prefetchedIds = new Set<string>();
+ private isEnabled = true;
+ private listeners = new Set<Listener>();
+ private idleHandle: number | null = null;
+ private scheduler: IdleScheduler;
+
+ constructor(scheduler: IdleScheduler = defaultScheduler()) {
+ this.scheduler = scheduler;
+ }
+
+ setEnabled(enabled: boolean): void {
+ if (this.isEnabled === enabled) {
+ return;
+ }
+ this.isEnabled = enabled;
+ this.scheduleTick();
+ }
+
+ register(reg: Registration): () => void {
+ this.registrations.set(reg.id, reg);
+ this.scheduleTick();
+ return () => {
+ this.registrations.delete(reg.id);
+ this.prefetchedIds.delete(reg.id);
+ this.inflightLoads.delete(reg.id);
+ this.scheduleTick();
+ };
+ }
+
+ reportLoading(id: string, loading: boolean): void {
+ const had = this.inflightLoads.has(id);
+ if (loading) {
+ this.inflightLoads.add(id);
+ } else {
+ this.inflightLoads.delete(id);
+ }
+ if (had !== loading) {
+ this.scheduleTick();
+ }
+ }
+
+ notifyViewportChange(): void {
+ this.scheduleTick();
+ }
+
+ hasTicket(id: string): boolean {
+ return this.prefetchedIds.has(id);
+ }
+
+ hasInflightLoads(): boolean {
+ return this.inflightLoads.size > 0;
+ }
+
+ subscribe(cb: Listener): () => void {
+ this.listeners.add(cb);
+ return () => {
+ this.listeners.delete(cb);
+ };
+ }
+
+ destroy(): void {
+ if (this.idleHandle !== null) {
+ this.scheduler.cancel(this.idleHandle);
+ this.idleHandle = null;
+ }
+ }
+
+ private scheduleTick(): void {
+ if (this.idleHandle !== null) {
+ return;
+ }
+ this.idleHandle = this.scheduler.schedule(() => {
+ this.idleHandle = null;
+ this.recompute();
+ });
+ }
+
+ private recompute(): void {
+ if (!this.isEnabled) {
+ return;
+ }
+
+ const slotsAvailable = MAX_CONCURRENT_PREFETCHES - this.inflightLoads.size;
+ if (slotsAvailable <= 0) {
+ return;
+ }
+
+ const viewportCenter =
+ typeof window !== "undefined" ? window.innerHeight / 2 : 0;
+
+ const candidates: Array<{ id: string; distance: number }> = [];
+ for (const [id, reg] of this.registrations) {
+ if (this.prefetchedIds.has(id) || reg.isInViewport()) {
+ continue;
+ }
+ const el = reg.getElement();
+ if (!el) {
+ continue;
+ }
+ const rect = el.getBoundingClientRect();
+ const distance = Math.min(
+ Math.abs(rect.top - viewportCenter),
+ Math.abs(rect.bottom - viewportCenter),
+ );
+ candidates.push({ id, distance });
+ }
+
+ if (candidates.length === 0) {
+ return;
+ }
+
+ candidates.sort((a, b) => a.distance - b.distance);
+
+ const idsToPrefetch = candidates.slice(0, slotsAvailable);
+ for (const { id } of idsToPrefetch) {
+ this.prefetchedIds.add(id);
+ }
+
+ this.notify();
+ }
+
+ private notify(): void {
+ for (const cb of this.listeners) {
+ cb();
+ }
+ }
+}
diff --git a/frontend/src/metabase/documents/utils/prefetch-queue.unit.spec.ts b/frontend/src/metabase/documents/utils/prefetch-queue.unit.spec.ts
new file mode 100644
index 00000000000..dba780c3443
--- /dev/null
+++ b/frontend/src/metabase/documents/utils/prefetch-queue.unit.spec.ts
@@ -0,0 +1,162 @@
+import {
+ MAX_CONCURRENT_PREFETCHES,
+ PrefetchQueueStore,
+} from "./prefetch-queue";
+
+function makeElement(top: number, height = 100): HTMLElement {
+ const el = document.createElement("div");
+ el.getBoundingClientRect = () => new DOMRect(0, top, 100, height);
+ return el;
+}
+
+/**
+ * A synchronous fake idle scheduler: each scheduled callback runs
+ * immediately when `flush()` is invoked, mirroring what
+ * requestIdleCallback would eventually do.
+ */
+function makeFakeScheduler() {
+ let nextHandle = 1;
+ const pending = new Map<number, () => void>();
+
+ return {
+ schedule(cb: () => void) {
+ const handle = nextHandle++;
+ pending.set(handle, cb);
+ return handle;
+ },
+ cancel(handle: number) {
+ pending.delete(handle);
+ },
+ flush() {
+ const cbs = Array.from(pending.values());
+ pending.clear();
+ for (const cb of cbs) {
+ cb();
+ }
+ },
+ get pendingCount() {
+ return pending.size;
+ },
+ };
+}
+
+describe("PrefetchQueueStore", () => {
+ let scheduler: ReturnType<typeof makeFakeScheduler>;
+ let queue: PrefetchQueueStore;
+
+ beforeEach(() => {
+ Object.defineProperty(window, "innerHeight", {
+ configurable: true,
+ value: 1000,
+ });
+ scheduler = makeFakeScheduler();
+ queue = new PrefetchQueueStore(scheduler);
+ });
+
+ function register(id: string, top: number, isInViewport = false) {
+ const el = makeElement(top);
+ return queue.register({
+ id,
+ getElement: () => el,
+ isInViewport: () => isInViewport,
+ });
+ }
+
+ it("grants tickets only after the idle scheduler fires", () => {
+ register("a", 2000);
+ expect(queue.hasTicket("a")).toBe(false);
+ scheduler.flush();
+ expect(queue.hasTicket("a")).toBe(true);
+ });
+
+ it("sorts off-screen candidates by distance to viewport center", () => {
+ register("far", 10_000);
+ register("near", 1200);
+ register("farthest", 20_000);
+ register("middle", 5000);
+ scheduler.flush();
+
+ expect(queue.hasTicket("near")).toBe(true);
+ expect(queue.hasTicket("middle")).toBe(true);
+ expect(queue.hasTicket("far")).toBe(true);
+ expect(queue.hasTicket("farthest")).toBe(false);
+ });
+
+ it("caps tickets at MAX_CONCURRENT_PREFETCHES per idle tick when no slots are taken", () => {
+ const ids = Array.from(
+ { length: MAX_CONCURRENT_PREFETCHES + 2 },
+ (_, i) => `card-${i}`,
+ );
+ ids.forEach((id, i) => register(id, 2000 + i * 1000));
+ scheduler.flush();
+
+ const granted = ids.filter((id) => queue.hasTicket(id));
+ expect(granted).toHaveLength(MAX_CONCURRENT_PREFETCHES);
+ });
+
+ it("skips cards that are currently in viewport", () => {
+ register("in-view", 500, true);
+ register("off-screen", 2000);
+ scheduler.flush();
+
+ expect(queue.hasTicket("in-view")).toBe(false);
+ expect(queue.hasTicket("off-screen")).toBe(true);
+ });
+
+ it("respects loading slots: in-flight loads reduce available slots", () => {
+ const ids = Array.from(
+ { length: MAX_CONCURRENT_PREFETCHES + 2 },
+ (_, i) => `card-${i}`,
+ );
+ ids.forEach((id, i) => register(id, 2000 + i * 1000));
+ queue.reportLoading("loading-1", true);
+ queue.reportLoading("loading-2", true);
+ queue.reportLoading("loading-3", true);
+ scheduler.flush();
+
+ const granted = ids.filter((id) => queue.hasTicket(id));
+ expect(granted).toHaveLength(0);
+ });
+
+ it("does nothing when network gating disables prefetching", () => {
+ register("a", 2000);
+ queue.setEnabled(false);
+ scheduler.flush();
+
+ expect(queue.hasTicket("a")).toBe(false);
+ });
+
+ it("notifies subscribers when tickets change", () => {
+ const listener = jest.fn();
+ queue.subscribe(listener);
+ register("a", 2000);
+ scheduler.flush();
+ expect(listener).toHaveBeenCalled();
+ });
+
+ it("releases ticket on unregister", () => {
+ const unregister = register("a", 2000);
+ scheduler.flush();
+ expect(queue.hasTicket("a")).toBe(true);
+ unregister();
+ expect(queue.hasTicket("a")).toBe(false);
+ });
+
+ it("coalesces multiple state changes into a single idle tick", () => {
+ register("a", 2000);
+ register("b", 3000);
+ queue.notifyViewportChange();
+ queue.reportLoading("a", false);
+
+ expect(scheduler.pendingCount).toBe(1);
+ });
+
+ it("re-schedules a new tick after the previous one runs", () => {
+ register("a", 2000);
+ scheduler.flush();
+ expect(scheduler.pendingCount).toBe(0);
+
+ register("b", 3000);
+ expect(scheduler.pendingCount).toBe(1);
+ });
+});
diff --git a/frontend/src/metabase/public/containers/PublicDocument/PublicDocument.tsx b/frontend/src/metabase/public/containers/PublicDocument/PublicDocument.tsx
index f8db7671f89..a9ac4efc473 100644
--- a/frontend/src/metabase/public/containers/PublicDocument/PublicDocument.tsx
+++ b/frontend/src/metabase/public/containers/PublicDocument/PublicDocument.tsx
@@ -26,7 +26,7 @@ import { getSetting } from "metabase/selectors/settings";
import { PublicApi } from "metabase/services";
import { Box } from "metabase/ui";
import { initializeIframeResizer } from "metabase/utils/dom";
-import type { Dataset, Document } from "metabase-types/api";
+import type { Document } from "metabase-types/api";
import S from "./PublicDocument.module.css";
@@ -125,8 +125,6 @@ export const PublicDocument = ({ location, params }: PublicDocumentProps) => {
() => ({
cards: document?.cards ?? {},
documentUuid: uuid,
- loadCardQuery: (cardId: number) =>
- PublicApi.documentCardQuery({ uuid, cardId }) as Promise<Dataset>,
}),
[document?.cards, uuid],
);
diff --git a/frontend/src/metabase/rich_text_editing/tiptap/extensions/CardEmbed/CardEmbedNode.tsx b/frontend/src/metabase/rich_text_editing/tiptap/extensions/CardEmbed/CardEmbedNode.tsx
index 4da3842ae94..817915c5e74 100644
--- a/frontend/src/metabase/rich_text_editing/tiptap/extensions/CardEmbed/CardEmbedNode.tsx
+++ b/frontend/src/metabase/rich_text_editing/tiptap/extensions/CardEmbed/CardEmbedNode.tsx
@@ -1,3 +1,4 @@
+import { useMergedRef } from "@mantine/hooks";
import {
Node,
findParentNodeClosestToPos,
@@ -31,6 +32,10 @@ import {
} from "metabase/documents/documents.slice";
import { useCardData } from "metabase/documents/hooks/use-card-data";
import { useExternalCardDataLoader } from "metabase/documents/hooks/use-external-card-data";
+import {
+ useNodeInViewport,
+ useReportPrefetchLoading,
+} from "metabase/documents/hooks/use-node-in-viewport";
import { useUnresolvedCommentsCount } from "metabase/documents/hooks/use-unresolved-comments-count";
import {
getChildTargetId,
@@ -175,12 +180,19 @@ export const CardEmbedComponent = memo(
getPos,
deleteNode,
}: NodeViewProps) => {
+ const { _id } = node.attrs;
+ const {
+ ref: viewportRef,
+ isInViewport,
+ shouldLoadData,
+ } = useNodeInViewport(_id);
const childTargetId = useSelector(getChildTargetId);
const hoveredChildTargetId = useSelector(getHoveredChildTargetId);
const document = useSelector(getCurrentDocument);
const externalCardData = useExternalCardData();
- const { _id } = node.attrs;
- const unresolvedCommentsCount = useUnresolvedCommentsCount(_id);
+ const unresolvedCommentsCount = useUnresolvedCommentsCount(_id, {
+ skip: !isInViewport,
+ });
const hasUnsavedChanges = useSelector(getHasUnsavedChanges);
const isOpen = childTargetId === _id;
@@ -204,13 +216,17 @@ export const CardEmbedComponent = memo(
// Use external hook when viewing an externally-rendered document (e.g. public), otherwise use regular hook
const isExternalDocument = externalCardData != null;
- const regularCardData = useCardData({ id });
- const externalCardDataResult = useExternalCardDataLoader(id);
+ const regularCardData = useCardData({ id, skip: !shouldLoadData });
+ const externalCardDataResult = useExternalCardDataLoader(id, {
+ skip: !shouldLoadData,
+ });
const { card, dataset, isLoading, series, error } = isExternalDocument
? externalCardDataResult
: regularCardData;
+ useReportPrefetchLoading(_id, isLoading);
+
const metadata = useSelector(getMetadata);
const datasetError = dataset && getDatasetError(dataset);
const [isEditingTitle, setIsEditingTitle] = useState(false);
@@ -220,6 +236,8 @@ export const CardEmbedComponent = memo(
const [isReplaceModalOpen, setIsReplaceModalOpen] = useState(false);
const [menuView, setMenuView] = useState<string | null>(null);
+ const setRef = useMergedRef<HTMLDivElement>(viewportRef, cardEmbedRef);
+
const shouldAllowAddingSupportingText = () => {
const pos = getPos();
if (!pos) {
@@ -501,7 +519,7 @@ export const CardEmbedComponent = memo(
</>
)}
<Box
- ref={cardEmbedRef}
+ ref={setRef}
className={cx(styles.cardEmbed, EDITOR_STYLE_BOUNDARY_CLASS, {
[styles.selected]: selected,
})}
@@ -643,7 +661,7 @@ export const CardEmbedComponent = memo(
</Flex>
</Box>
)}
- {series ? (
+ {series && isInViewport ? (
<>
<Box className={styles.questionResults}>
<ExplicitSizeRefreshModeContext.Provider value="layout">
diff --git a/frontend/src/metabase/rich_text_editing/tiptap/extensions/MetabotEmbed/__support__/editor-mocks.ts b/frontend/src/metabase/rich_text_editing/tiptap/extensions/MetabotEmbed/__support__/editor-mocks.ts
index 0b1de28ca2d..50c1d4c4386 100644
--- a/frontend/src/metabase/rich_text_editing/tiptap/extensions/MetabotEmbed/__support__/editor-mocks.ts
+++ b/frontend/src/metabase/rich_text_editing/tiptap/extensions/MetabotEmbed/__support__/editor-mocks.ts
@@ -13,7 +13,7 @@ export const createMockEditor = (overrides: Partial<Editor> = {}): Editor =>
},
state: {
selection: { $from: {}, empty: true },
- doc: { nodeAt: jest.fn(), resolve: jest.fn() },
+ doc: { nodeAt: jest.fn(), resolve: jest.fn(() => ({ depth: 0 })) },
},
options: {
editable: true,
diff --git a/frontend/src/metabase/rich_text_editing/tiptap/extensions/SupportingText/SupportingText.tsx b/frontend/src/metabase/rich_text_editing/tiptap/extensions/SupportingText/SupportingText.tsx
index 02db4fbe4c8..b0d7d4e4e82 100644
--- a/frontend/src/metabase/rich_text_editing/tiptap/extensions/SupportingText/SupportingText.tsx
+++ b/frontend/src/metabase/rich_text_editing/tiptap/extensions/SupportingText/SupportingText.tsx
@@ -14,6 +14,7 @@ import cx from "classnames";
import { push } from "react-router-redux";
import { t } from "ttag";
+import { useNodeInViewport } from "metabase/documents/hooks/use-node-in-viewport";
import { useUnresolvedCommentsCount } from "metabase/documents/hooks/use-unresolved-comments-count";
import {
getChildTargetId,
@@ -136,10 +137,13 @@ const SupportingTextComponent = ({
node,
selected,
}: NodeViewProps) => {
+ const { ref: viewportRef, isInViewport } = useNodeInViewport();
const childTargetId = useSelector(getChildTargetId);
const document = useSelector(getCurrentDocument);
const { _id } = node.attrs;
- const unresolvedCommentsCount = useUnresolvedCommentsCount(_id);
+ const unresolvedCommentsCount = useUnresolvedCommentsCount(_id, {
+ skip: !isInViewport,
+ });
const isOpen = childTargetId === _id;
const commentsPath = document
? `/document/${document.id}/comments/${_id}`
@@ -160,6 +164,7 @@ const SupportingTextComponent = ({
return (
<NodeViewWrapper
+ ref={viewportRef}
className={cx(S.wrapper, { [S.selected]: selected })}
data-testid="document-card-supporting-text"
data-type={SUPPORTING_TEXT_NODE_NAME}
diff --git a/frontend/src/metabase/services.js b/frontend/src/metabase/services.js
index 092d81c09b8..83bc2cb89fb 100644
--- a/frontend/src/metabase/services.js
+++ b/frontend/src/metabase/services.js
@@ -50,7 +50,6 @@ export const PublicApi = {
`${publicBase}/dashboard/:dashboardId/dashcard/:dashcardId/execute`,
),
document: GET(`/api/public/document/:uuid`),
- documentCardQuery: GET(`/api/public/document/:uuid/card/:cardId`),
};
export const EmbedApi = {
diff --git a/frontend/test/__support__/custom-viz-fixtures/CalendarHeatmap.document.stories.tsx b/frontend/test/__support__/custom-viz-fixtures/CalendarHeatmap.document.stories.tsx
index ffdd4f9f1cd..b8ee9fd6d5a 100644
--- a/frontend/test/__support__/custom-viz-fixtures/CalendarHeatmap.document.stories.tsx
+++ b/frontend/test/__support__/custom-viz-fixtures/CalendarHeatmap.document.stories.tsx
@@ -1,14 +1,16 @@
-// @ts-expect-error There is no type definition
-import createAsyncCallback from "@loki/create-async-callback";
import type { StoryFn } from "@storybook/react";
import type { JSONContent } from "@tiptap/react";
import { HttpResponse, http } from "msw";
-import { type ReactNode, useEffect, useMemo } from "react";
+import { type ReactNode, useMemo } from "react";
import _ from "underscore";
import { getStore } from "__support__/entities-store";
import { mockSettings } from "__support__/settings";
import { createMockEntitiesState } from "__support__/store";
+import {
+ ForceDocumentCardRenderDecorator,
+ createWaitForChartsDecorator,
+} from "__support__/storybook";
import { getNextId } from "__support__/utils";
import { AppColorSchemeProvider } from "metabase/AppColorSchemeProvider";
import { Api } from "metabase/api";
@@ -95,17 +97,8 @@ function DocumentProviders({
}
const Template: StoryFn<{ theme: "light" | "dark" }> = ({ theme }) => {
- const asyncCallback = useMemo(() => createAsyncCallback(), []);
const ready = useHeatmapPlugin();
- useEffect(() => {
- if (!ready) {
- return;
- }
- const id = setTimeout(asyncCallback, HEATMAP_SNAPSHOT_DELAY_MS);
- return () => clearTimeout(id);
- }, [ready, asyncCallback]);
-
return (
<DocumentProviders theme={theme}>
{ready ? (
@@ -115,6 +108,15 @@ const Template: StoryFn<{ theme: "light" | "dark" }> = ({ theme }) => {
);
};
+// Render the card eagerly, then hold the snapshot until the heatmap paints.
+const decorators = [
+ ForceDocumentCardRenderDecorator,
+ createWaitForChartsDecorator({
+ count: 1,
+ settleMs: HEATMAP_SNAPSHOT_DELAY_MS,
+ }),
+];
+
export default {
title: "viz/CustomViz/CalendarHeatmap/Document",
render: Template,
@@ -137,9 +139,11 @@ export default {
export const Light = {
render: Template,
args: { theme: "light" as const },
+ decorators,
};
export const Dark = {
render: Template,
args: { theme: "dark" as const },
+ decorators,
};
diff --git a/frontend/test/__support__/intersection-observer.ts b/frontend/test/__support__/intersection-observer.ts
new file mode 100644
index 00000000000..0e4bb1c973c
--- /dev/null
+++ b/frontend/test/__support__/intersection-observer.ts
@@ -0,0 +1,66 @@
+import { act } from "@testing-library/react";
+
+/**
+ * Replaces the default no-op IntersectionObserver stub (see
+ * frontend/test/jest-setup.js) with a mock that captures the observer
+ * callback so tests can drive intersection events.
+ *
+ * Call inside a `describe` block — it registers beforeEach/afterEach hooks
+ * that install the mock and restore the original observer.
+ */
+export function setupMockIntersectionObserver() {
+ const originalIntersectionObserver = globalThis.IntersectionObserver;
+
+ let intersectionCallback: IntersectionObserverCallback | null = null;
+ let observerOptions: IntersectionObserverInit | undefined;
+ const observeMock = jest.fn();
+ const disconnectMock = jest.fn();
+
+ beforeEach(() => {
+ intersectionCallback = null;
+ observerOptions = undefined;
+ observeMock.mockClear();
+ disconnectMock.mockClear();
+
+ globalThis.IntersectionObserver = class MockIntersectionObserver implements IntersectionObserver {
+ constructor(
+ callback: IntersectionObserverCallback,
+ options?: IntersectionObserverInit,
+ ) {
+ intersectionCallback = callback;
+ observerOptions = options;
+ }
+
+ root: Element | null = null;
+ rootMargin = "";
+ scrollMargin = "";
+ thresholds: ReadonlyArray<number> = [];
+ observe = observeMock;
+ disconnect = disconnectMock;
+ unobserve() {}
+ takeRecords(): IntersectionObserverEntry[] {
+ return [];
+ }
+ };
+ });
+
+ afterEach(() => {
+ globalThis.IntersectionObserver = originalIntersectionObserver;
+ });
+
+ function setIntersecting(isIntersecting: boolean) {
+ act(() => {
+ intersectionCallback?.(
+ [{ isIntersecting } as IntersectionObserverEntry],
+ {} as IntersectionObserver,
+ );
+ });
+ }
+
+ return {
+ setIntersecting,
+ observe: observeMock,
+ disconnect: disconnectMock,
+ getObserverOptions: () => observerOptions,
+ };
+}
diff --git a/frontend/test/__support__/storybook.tsx b/frontend/test/__support__/storybook.tsx
index da6b6776a80..3ed37aaf535 100644
--- a/frontend/test/__support__/storybook.tsx
+++ b/frontend/test/__support__/storybook.tsx
@@ -5,6 +5,7 @@ import type { StoryFn } from "@storybook/react";
import { useEffect, useMemo } from "react";
import { SdkThemeProvider } from "embedding-sdk-bundle/components/private/SdkThemeProvider";
+import { PrintContext } from "metabase/documents/contexts/PrintContext";
import type { MetabaseTheme } from "metabase/embedding-sdk/theme";
import { mainReducers } from "metabase/reducers-main";
import { MetabaseReduxProvider } from "metabase/redux";
@@ -148,3 +149,98 @@ export function createWaitForResizeToStopDecorator(timeoutMs: number = 1000) {
return <Story />;
};
}
+
+/**
+ * Loki decorator that defers the snapshot until the expected number of
+ * visualizations have rendered and painted.
+ *
+ * Once a card's data query resolves the visualization still needs a tick
+ * to mount and ECharts a few more to paint, so a fixed delay races that
+ * chain. Instead we poll for the expected number of `visualization-root`
+ * nodes, then settle for `settleMs` so charts can finish their entry
+ * animation before the screenshot.
+ *
+ * Polling uses `setTimeout`, not `requestAnimationFrame`: rAF does not
+ * fire reliably in Loki's headless Chrome, which would strand the async
+ * callback and hang the run. For the same reason the callback is fired
+ * exactly once and is also flushed on unmount — a never-resolved Loki
+ * async callback crashes the whole test run, not just one story.
+ *
+ * `timeoutMs` is a hard cap: the callback always resolves, so a story
+ * that never renders its chart fails loudly with a screenshot instead
+ * of hanging.
+ */
+export function createWaitForChartsDecorator({
+ count,
+ settleMs = 1000,
+ timeoutMs = 20000,
+}: {
+ count: number;
+ settleMs?: number;
+ timeoutMs?: number;
+}) {
+ return function WaitForChartsDecorator(Story: StoryFn) {
+ const asyncCallback = useMemo(() => createAsyncCallback(), []);
+
+ useEffect(() => {
+ const startedAt = Date.now();
+ let pollTimer: ReturnType<typeof setTimeout> | undefined;
+ let settleTimer: ReturnType<typeof setTimeout> | undefined;
+ let resolved = false;
+
+ const resolve = () => {
+ if (resolved) {
+ return;
+ }
+ resolved = true;
+ asyncCallback();
+ };
+
+ const poll = () => {
+ const renderedCount = document.querySelectorAll(
+ '[data-testid="visualization-root"]',
+ ).length;
+ const timedOut = Date.now() - startedAt > timeoutMs;
+
+ if (renderedCount >= count || timedOut) {
+ settleTimer = setTimeout(resolve, settleMs);
+ return;
+ }
+ pollTimer = setTimeout(poll, 100);
+ };
+ poll();
+
+ return () => {
+ clearTimeout(pollTimer);
+ clearTimeout(settleTimer);
+ // Never leave the Loki async callback unresolved, even if the
+ // story unmounts mid-wait — an orphaned callback hangs the run.
+ resolve();
+ };
+ }, [asyncCallback]);
+
+ return <Story />;
+ };
+}
+
+/**
+ * Loki decorator that forces document card embeds to render eagerly.
+ *
+ * Card embeds defer their visualization until an IntersectionObserver
+ * reports them on-screen (see `useNodeInViewport`). IO callbacks are only
+ * delivered on rendered frames, and Loki's headless Chrome produces none
+ * on an idle page — so a card would stay a skeleton forever. Providing
+ * `isPrinting: true` makes `isInViewport` true unconditionally, rendering
+ * the card immediately without the observer. The `@media print` rules
+ * that hide `[data-hide-on-print]` are keyed on the print media query,
+ * not this flag, so the snapshot is unaffected.
+ */
+export function ForceDocumentCardRenderDecorator(Story: StoryFn) {
+ return (
+ <PrintContext.Provider
+ value={{ isPrinting: true, prepareForPrint: async () => {} }}
+ >
+ <Story />
+ </PrintContext.Provider>
+ );
+}
diff --git a/frontend/test/jest-setup.js b/frontend/test/jest-setup.js
index 752a07a4bae..a65ab17ba61 100644
--- a/frontend/test/jest-setup.js
+++ b/frontend/test/jest-setup.js
@@ -115,3 +115,21 @@ Element.prototype.getClientRects =
// Mock elementFromPoint for ProseMirror/TipTap compatibility in tests
document.elementFromPoint = document.elementFromPoint || (() => null);
document.elementsFromPoint = document.elementsFromPoint || (() => []);
+
+// IntersectionObserver is not available in jsdom. Default to a no-op stub so
+// hooks like useNodeInViewport don't crash. Tests that need to drive
+// intersection events can override globalThis.IntersectionObserver locally.
+globalThis.IntersectionObserver =
+ globalThis.IntersectionObserver ||
+ class IntersectionObserver {
+ constructor() {}
+ root = null;
+ rootMargin = "0px";
+ thresholds = [0];
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+ takeRecords() {
+ return [];
+ }
+ };