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
fix: grid Map Pins Offset in PDF Export (#68751)
Maksym Yakubych38bf8580ea5f
diff --git a/.loki/reference/chrome_laptop_viz_GridMapPdfExport_Grid_Map_Pdf_Export.png b/.loki/reference/chrome_laptop_viz_GridMapPdfExport_Grid_Map_Pdf_Export.pngnew file mode 100644index 00000000000..e5d2de33d0cBinary files /dev/null and b/.loki/reference/chrome_laptop_viz_GridMapPdfExport_Grid_Map_Pdf_Export.png differdiff --git a/frontend/src/metabase/visualizations/lib/save-dashboard-pdf.ts b/frontend/src/metabase/visualizations/lib/save-dashboard-pdf.tsindex 15ef015b3b2..53f4ddc9dbf 100644--- a/frontend/src/metabase/visualizations/lib/save-dashboard-pdf.ts+++ b/frontend/src/metabase/visualizations/lib/save-dashboard-pdf.ts@@ -2,6 +2,8 @@ import Color from "color";import { t } from "ttag";import { DASHBOARD_HEADER_PARAMETERS_PDF_EXPORT_NODE_ID } from "metabase/dashboard/constants";+import { isStorybookActive } from "metabase/env";+import { openImageBlobOnStorybook } from "metabase/lib/loki-utils";import type { Dashboard } from "metabase-types/api";import {@@ -272,6 +274,17 @@ export const saveDashboardPdf = async ({},});+ // For Storybook/Loki visual testing, display the canvas as an image and skip PDF generation+ if (isStorybookActive) {+ const blob = await new Promise<Blob | null>((resolve) =>+ image.toBlob(resolve, "image/png"),+ );+ if (blob) {+ openImageBlobOnStorybook({ canvas: image, blob });+ }+ return;+ }+const { default: jspdf } = await import("jspdf");// Page page height cannot be smaller than page width otherwise the content will be cut offdiff --git a/frontend/src/metabase/visualizations/visualizations/Map/GridMapPdfExport.stories.tsx b/frontend/src/metabase/visualizations/visualizations/Map/GridMapPdfExport.stories.tsxnew file mode 100644index 00000000000..b730f4e5115--- /dev/null+++ b/frontend/src/metabase/visualizations/visualizations/Map/GridMapPdfExport.stories.tsx@@ -0,0 +1,211 @@+// @ts-expect-error There is no type definition+import createAsyncCallback from "@loki/create-async-callback";+import type { StoryContext, StoryFn } from "@storybook/react";+import { userEvent, within } from "@storybook/test";+import { HttpResponse, http } from "msw";++import { getStore } from "__support__/entities-store";+import { createWaitForResizeToStopDecorator } from "__support__/storybook";+import { getNextId } from "__support__/utils";+import { Api } from "metabase/api";+import { DASHBOARD_DISPLAY_ACTIONS } from "metabase/dashboard/components/DashboardHeader/DashboardHeaderButtonRow/constants";+import { MetabaseReduxProvider } from "metabase/lib/redux";+import MetabaseSettings from "metabase/lib/settings";+import { PublicOrEmbeddedDashboardView } from "metabase/public/containers/PublicOrEmbeddedDashboard/PublicOrEmbeddedDashboardView";+import {+ MockDashboardContext,+ type MockDashboardContextProps,+} from "metabase/public/containers/PublicOrEmbeddedDashboard/mock-context";+import { publicReducers } from "metabase/reducers-public";+import { registerVisualization } from "metabase/visualizations";+import type { Dashboard } from "metabase-types/api";+import {+ createMockCard,+ createMockColumn,+ createMockDashboard,+ createMockDashboardCard,+ createMockDatabase,+ createMockDataset,+ createMockDatasetData,+} from "metabase-types/api/mocks";+import {+ createMockDashboardState,+ createMockSettingsState,+ createMockState,+} from "metabase-types/store/mocks";++import { Map } from "./index";++// @ts-expect-error: incompatible prop types with registerVisualization+registerVisualization(Map);++// Initialize MetabaseSettings with required values for map rendering+MetabaseSettings.set(+ "map-tile-server-url",+ "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",+);++export default {+ title: "viz/GridMapPdfExport",+ component: PublicOrEmbeddedDashboardView,+ decorators: [ReduxDecorator, createWaitForResizeToStopDecorator(2000)],+ parameters: {+ layout: "fullscreen",+ msw: {+ handlers: [+ http.get("*/api/database", () =>+ HttpResponse.json(createMockDatabase()),+ ),+ ],+ },+ },+};++const DASHBOARD_ID = getNextId();+const DASHCARD_MAP_ID = getNextId();+const CARD_MAP_ID = getNextId();++function ReduxDecorator(Story: StoryFn, context: StoryContext) {+ const dashboard = (context.args.dashboard as Dashboard) ?? createDashboard();+ const initialState = createMockState({+ currentUser: null,+ settings: createMockSettingsState({+ "hide-embed-branding?": false,+ }),+ dashboard: createMockDashboardState({+ dashboardId: dashboard.id,+ dashboards: {+ [dashboard.id]: {+ ...dashboard,+ dashcards: dashboard.dashcards.map((dashcard) => dashcard.id),+ },+ },+ dashcards: Object.fromEntries(+ dashboard.dashcards.map((dc) => [dc.id, dc]),+ ),+ dashcardData: {+ [DASHCARD_MAP_ID]: {+ [CARD_MAP_ID]: createMockDataset({+ data: createMockDatasetData({+ cols: [+ createMockColumn({+ name: "Latitude",+ display_name: "Latitude",+ base_type: "type/Float",+ semantic_type: "type/Latitude",+ source: "native",+ }),+ createMockColumn({+ name: "Longitude",+ display_name: "Longitude",+ base_type: "type/Float",+ semantic_type: "type/Longitude",+ source: "native",+ }),+ createMockColumn({+ name: "metric",+ display_name: "metric",+ base_type: "type/Integer",+ semantic_type: "type/Quantity",+ source: "native",+ }),+ ],+ rows: [+ [20, -110, 1],+ [70, -170, 5],+ ],+ }),+ }),+ },+ },+ }),+ });+ const store = getStore(publicReducers, initialState, [Api.middleware]);+ return (+ <MetabaseReduxProvider store={store}>+ <Story />+ </MetabaseReduxProvider>+ );+}++function createDashboard() {+ return createMockDashboard({+ id: DASHBOARD_ID,+ name: "Grid Map Dashboard",+ width: "full",+ dashcards: [+ createMockDashboardCard({+ id: DASHCARD_MAP_ID,+ card: createMockCard({+ id: CARD_MAP_ID,+ name: "Grid Map",+ display: "map",+ }),+ size_x: 12,+ size_y: 8,+ visualization_settings: {+ "map.type": "grid",+ "map.latitude_column": "Latitude",+ "map.longitude_column": "Longitude",+ "map.metric_column": "metric",+ },+ }),+ ],+ });+}++const Template: StoryFn<MockDashboardContextProps> = (+ args: MockDashboardContextProps,+) => (+ <MockDashboardContext+ {...args}+ dashboardId={args.dashboardId ?? args.dashboard?.id}+ dashboardActions={DASHBOARD_DISPLAY_ACTIONS}+ >+ <PublicOrEmbeddedDashboardView />+ </MockDashboardContext>+);++const defaultArgs: Partial<MockDashboardContextProps> = {+ dashboard: createDashboard(),+ downloadsEnabled: { pdf: true, results: true },+ titled: true,+ bordered: true,+ background: true,+ slowCards: {},+ selectedTabId: null,+ withFooter: true,+};++const triggerPdfExport = async (+ canvasElement: HTMLElement,+ asyncCallback: () => void,+) => {+ const canvas = within(canvasElement);++ // Wait for the embed frame to render+ await canvas.findByTestId("embed-frame", {}, { timeout: 10000 });++ // Find and click the "Download as PDF" button+ const documentElement = within(document.documentElement);+ const pdfButton = await documentElement.findByTestId(+ "export-as-pdf-button",+ {},+ { timeout: 5000 },+ );+ await userEvent.click(pdfButton);++ // Wait for the image to be rendered (this is set by openImageBlobOnStorybook)+ await canvas.findByTestId("image-downloaded", {}, { timeout: 30000 });+ asyncCallback();+};++export const GridMapPdfExport = {+ render: Template,+ args: defaultArgs,++ play: async ({ canvasElement }: { canvasElement: HTMLCanvasElement }) => {+ const asyncCallback = createAsyncCallback();+ await triggerPdfExport(canvasElement, asyncCallback);+ },+};diff --git a/loki.config.js b/loki.config.jsindex 3e7123716b9..d64b3d5cb1d 100644--- a/loki.config.js+++ b/loki.config.js@@ -18,6 +18,7 @@ module.exports = {"^Components/Table","^App/Palette","^EmbeddingSDK/SdkQuestion/ChartTypeDropdownInner",+ "^viz/GridMapPdfExport",].join("|"),configurations: {"chrome.laptop": {diff --git a/patches/html2canvas-pro+1.5.0.patch b/patches/html2canvas-pro+1.5.0.patchindex fa00dbc13c5..e4882af9cb6 100644--- a/patches/html2canvas-pro+1.5.0.patch+++ b/patches/html2canvas-pro+1.5.0.patch@@ -1,5 +1,5 @@diff --git a/node_modules/html2canvas-pro/dist/html2canvas-pro.js b/node_modules/html2canvas-pro/dist/html2canvas-pro.js-index 86a610e..c74cc94 100644+index 86a610e..79c8cc6 100644--- a/node_modules/html2canvas-pro/dist/html2canvas-pro.js+++ b/node_modules/html2canvas-pro/dist/html2canvas-pro.js@@ -802,6 +802,7 @@@@ -10,7 +10,16 @@ index 86a610e..c74cc94 100644var Break = /** @class */ (function () {function Break(codePoints, lineBreak, start, end) {this.codePoints = codePoints;-@@ -6060,6 +6061,11 @@+@@ -5347,6 +5348,8 @@+ function SVGElementContainer(context, img) {+ var _this = _super.call(this, context, img) || this;+ var s = new XMLSerializer();++ // Remove transform to prevent double-application (transform is already accounted for in bounds/positioning)++ img.style.transform = "none";+ var bounds = parseBounds(context, img);+ img.setAttribute('width', bounds.width + "px");+ img.setAttribute('height', bounds.height + "px");+@@ -6060,6 +6063,11 @@documentClone.write(serializeDoctype(document.doctype) + "<html></html>");// Chrome scrolls the parent document for some reason after the write to the cloned window???restoreOwnerScroll(this.referenceElement.ownerDocument, scrollX, scrollY);@@ -22,7 +31,7 @@ index 86a610e..c74cc94 100644documentClone.replaceChild(documentClone.adoptNode(this.documentElement), documentClone.documentElement);documentClone.close();return iframeLoad;-@@ -6188,6 +6194,11 @@+@@ -6188,6 +6196,11 @@(!isScriptElement(child) &&!child.hasAttribute(IGNORE_ATTRIBUTE) &&(typeof this.options.ignoreElements !== 'function' || !this.options.ignoreElements(child)))) {@@ -34,7 +43,7 @@ index 86a610e..c74cc94 100644if (!this.options.copyStyles || !isElementNode(child) || !isStyleElement(child)) {clone.appendChild(this.cloneNode(child, copyStyles));}-@@ -6464,6 +6475,9 @@+@@ -6464,6 +6477,9 @@var document = body.ownerDocument;if (document) {var style = document.createElement('style');@@ -44,7 +53,17 @@ index 86a610e..c74cc94 100644style.textContent = styles;body.appendChild(style);}-@@ -8570,6 +8584,7 @@+@@ -6923,7 +6939,8 @@+ if (this.container.styles.opacity < 1) {+ this.effects.push(new OpacityEffect(this.container.styles.opacity));+ }+- if (this.container.styles.transform !== null) {++ // Skip TransformEffect for SVG elements - their transform is already baked into bounds++ if (this.container.styles.transform !== null && !(this.container instanceof SVGElementContainer)) {+ var offsetX = this.container.bounds.left + this.container.styles.transformOrigin[0].number;+ var offsetY = this.container.bounds.top + this.container.styles.transformOrigin[1].number;+ var matrix = this.container.styles.transform;+@@ -8570,6 +8587,7 @@var html2canvas = function (element, options) {if (options === void 0) { options = {}; }