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
Explorations summary document (#78848)
Kevin Kelleherfc487f06c9a8
diff --git a/.clj-kondo/config/modules/config.edn b/.clj-kondo/config/modules/config.ednindex 2bcdd8491f4..8dc9ec8c12e 100644--- a/.clj-kondo/config/modules/config.edn+++ b/.clj-kondo/config/modules/config.edn@@ -626,6 +626,7 @@:uses #{apiapp-dbcollections+ documentseid-translationeventslib-be@@ -654,6 +655,7 @@comments{:team "UX West":api #{metabase.comments.api+ metabase.comments.coremetabase.comments.init}:uses #{analyticsapi@@ -1030,7 +1032,9 @@apiapp-dbcollections+ commentscontextual-interestingness+ documentseventsinterestingnesslib@@ -1055,6 +1059,7 @@:model-imports #{:model/Card:model/Collection:model/Comment+ :model/Document:model/Segment:model/StoredResult:model/StoredResultUse@@ -1919,6 +1924,8 @@:model/Collection:model/Dashboard:model/Database+ :model/StoredResult+ :model/StoredResultUse:model/Table}}query-permissions@@ -1960,6 +1967,7 @@metabase.query-processor.pipelinemetabase.query-processor.pivotmetabase.query-processor.preprocess+ metabase.query-processor.result-serializationmetabase.query-processor.schemametabase.query-processor.setupmetabase.query-processor.storediff --git a/dev/src/dev.clj b/dev/src/dev.cljindex d83c9803ebd..7d75edd3f09 100644--- a/dev/src/dev.clj+++ b/dev/src/dev.clj@@ -396,7 +396,7 @@"#tap, but to use in pipelines like `(-> 1 inc dev/tap prn inc)`."[form](u/prog1 form- (tap> <>)))+ (tap> <>)))(defn- tests-in-var-ns [test-var](->> test-var meta :ns ns-interns valsdiff --git a/dev/src/dev/coverage.clj b/dev/src/dev/coverage.cljindex d5004098b29..9f8841c88d2 100644--- a/dev/src/dev/coverage.clj+++ b/dev/src/dev/coverage.clj@@ -26,7 +26,6 @@(let [coverage-pairs (atom #{})current-test (atom nil)original-fns (atom {})]-;; Store original functions and wrap them (both public and private)(doseq [ns-sym code-namespaces](require ns-sym :reload)@@ -37,10 +36,8 @@(instance? clojure.lang.MultiFn @var-obj)))(let [original-fn @var-objfull-name (symbol (str ns-sym) (str var-name))]-;; Store original function(swap! original-fns assoc full-name original-fn)-;; Replace with tracking wrapper(alter-var-root var-obj(constantly@@ -48,7 +45,6 @@(when-let [test @current-test](swap! coverage-pairs conj [full-name test]))(apply original-fn args)))))))))-;; Run tests, tracking which test is running(doseq [test-ns test-namespaces](require test-ns :reload)@@ -59,14 +55,12 @@(let [test-name (symbol (str test-ns) (name (.sym test-var)))](reset! current-test test-name)(t/test-var test-var)))))-;; Restore original functions(doseq [ns-sym code-namespaces](let [ns-obj (find-ns ns-sym)](doseq [[var-name var-obj] (ns-interns ns-obj)](when-let [original-fn (get @original-fns (symbol (str ns-sym) (str var-name)))](alter-var-root var-obj (constantly original-fn))))))-;; Return set of [function, test] tuples(let [all-fns (set (keys @original-fns))coverage @coverage-pairs@@ -263,14 +257,12 @@original-fn @var-objoriginal-meta (meta var-obj)results (atom {:killed [] :survived []})]-;; Test each mutation(doseq [[idx mutation] (map-indexed vector (:mutations mutation-data))](try;; Evaluate the mutated function to replace the original(binding [*ns* (find-ns ns-sym)](eval (read-string (:mutation mutation))))-;; Run tests until one fails (early termination)(let [result (loop [test-names test-names](cond@@ -283,7 +275,6 @@:else(recur (rest test-names))))](swap! results update result conj mutation))-(catch Exception _e;; Mutation caused compilation/runtime error - count as killed(swap! results update :killed conj mutation))@@ -291,7 +282,6 @@;; Restore the original function AND var metadata(alter-var-root var-obj (constantly original-fn))(alter-meta! var-obj (constantly original-meta)))))-(assoc @results :original-source (:original-source mutation-data)))))(defn- index-by [f coll]@@ -340,7 +330,6 @@(println "Namespace:" target-ns)(println)(println "Test namespaces:" (str/join ", " (sort test-ns-s)))-(when (seq uncovered)(println)(println "## Uncovered Functions")@@ -353,7 +342,6 @@(println "```")(println original-source)(println "```")))-(when (seq partially-covered)(println)(println "## Partially Covered Functions")@@ -375,7 +363,6 @@(println "```")(println mutation)(println "```"))))-(when (seq fully-covered)(println)(println "## Fully Covered Functions")diff --git a/dev/src/user.clj b/dev/src/user.cljindex 39c32a0eedd..2b2662aa58a 100644--- a/dev/src/user.clj+++ b/dev/src/user.clj@@ -118,7 +118,7 @@;; We sometimes need to run cmd stuffs like `clojure -M:migrate rollback n 3` and these;; libraries might not be available in the classpath(u/ignore-exceptions- ;; make sure stuff like `=?` and what not are loaded+ ;; make sure stuff like `=?` and what not are loaded(classloader/require 'mb.hawk.assert-exprs))(u/ignore-exceptions@@ -130,9 +130,9 @@(u/ignore-exceptions(classloader/require 'pjstadig.humane-test-output)- ;; Initialize Humane Test Output if it's not already initialized. Don't enable humane-test-output when running tests- ;; from the CLI, it breaks diffs. This uses [[env/env]] rather than [[metabase.config.core]] so we don't load that- ;; namespace before we load [[metabase.core.bootstrap]]+ ;; Initialize Humane Test Output if it's not already initialized. Don't enable humane-test-output when running tests+ ;; from the CLI, it breaks diffs. This uses [[env/env]] rather than [[metabase.config.core]] so we don't load that+ ;; namespace before we load [[metabase.core.bootstrap]](when-not (= (env/env :mb-run-mode) "test")((resolve 'pjstadig.humane-test-output/activate!))))diff --git a/e2e/support/helpers/api/createComment.ts b/e2e/support/helpers/api/createComment.tsindex 50fa27996e6..4120a5fc91d 100644--- a/e2e/support/helpers/api/createComment.ts+++ b/e2e/support/helpers/api/createComment.ts@@ -6,6 +6,7 @@ export const createComment = ({child_target_id,parent_comment_id = null,content,+ context,}: Partial<CreateCommentRequest>): Cypress.Chainable<Cypress.Response<Comment>> => {@@ -15,5 +16,6 @@ export const createComment = ({child_target_id,parent_comment_id,content,+ context,});};diff --git a/e2e/support/helpers/api/createTimelineWithEvents.ts b/e2e/support/helpers/api/createTimelineWithEvents.tsindex d8db34cd0d7..75bd64285b0 100644--- a/e2e/support/helpers/api/createTimelineWithEvents.ts+++ b/e2e/support/helpers/api/createTimelineWithEvents.ts@@ -15,7 +15,7 @@ export const createTimelineWithEvents = ({events,}: {timeline: CreateTimelineRequest;- events: CreateTimelineEventRequest[];+ events: Omit<CreateTimelineEventRequest, "timeline_id">[];}): {timeline: Timeline;events: TimelineEvent[];diff --git a/e2e/test/scenarios/documents/documents.cy.spec.ts b/e2e/test/scenarios/documents/documents.cy.spec.tsindex 6e074a57e92..9cfa5296dab 100644--- a/e2e/test/scenarios/documents/documents.cy.spec.ts+++ b/e2e/test/scenarios/documents/documents.cy.spec.ts@@ -1,6 +1,7 @@import {NO_SQL_PERSONAL_COLLECTION_ID,ORDERS_BY_YEAR_QUESTION_ID,+ ORDERS_COUNT_QUESTION_ID,ORDERS_QUESTION_ID,READ_ONLY_PERSONAL_COLLECTION_ID,} from "e2e/support/cypress_sample_instance_data";@@ -10,6 +11,7 @@ import type {} from "e2e/support/helpers/api";import {ACCOUNTS_COUNT_BY_CREATED_AT,+ ORDERS_COUNT_BY_CREATED_AT,ORDERS_COUNT_BY_PRODUCT_CATEGORY,PIVOT_TABLE_CARD,PRODUCTS_AVERAGE_BY_CATEGORY,@@ -1918,8 +1920,196 @@ describe("documents", () => {H.undoToast().should("contain.text", "Cannot revert: missing document");});});++ describe("timeline events on chart embeds", () => {+ const TIMESERIES_CARD_1 = "Orders, Count, Grouped by Created At (year)";+ const NON_TIMESERIES_CARD = "Orders, Count";+ const TIMESERIES_CARD_3 = "Orders by Created At (Month)";+ const TIMELINE_NAME = "Releases";+ const TIMELINE_EVENT_NAME = "RC1";++ it("should show the Events menu only on timeseries charts and manage per-chart timeline selection", () => {+ H.createTimelineWithEvents({+ timeline: { name: TIMELINE_NAME },+ events: [+ {+ name: TIMELINE_EVENT_NAME,+ timestamp: "2026-06-01T00:00:00Z",+ icon: "star",+ timezone: "UTC",+ },+ ],+ });++ H.createQuestion(ORDERS_COUNT_BY_CREATED_AT).then(+ ({ body: { id: timeseriesCard3Id } }) => {+ H.createDocument({+ name: "Timeline events document",+ document: {+ type: "doc",+ content: [+ {+ type: "resizeNode",+ attrs: { height: 350, minHeight: 280, _id: "1" },+ content: [+ {+ type: "cardEmbed",+ attrs: {+ id: ORDERS_BY_YEAR_QUESTION_ID,+ name: null,+ _id: "1a",+ },+ },+ ],+ },+ { type: "paragraph", attrs: { _id: "2" } },+ {+ type: "resizeNode",+ attrs: { height: 350, minHeight: 280, _id: "3" },+ content: [+ {+ type: "cardEmbed",+ attrs: {+ id: ORDERS_COUNT_QUESTION_ID,+ name: null,+ _id: "3a",+ },+ },+ ],+ },+ { type: "paragraph", attrs: { _id: "4" } },+ {+ type: "resizeNode",+ attrs: { height: 350, minHeight: 280, _id: "5" },+ content: [+ {+ type: "cardEmbed",+ attrs: {+ id: timeseriesCard3Id,+ name: null,+ _id: "5a",+ },+ },+ ],+ },+ { type: "paragraph", attrs: { _id: "6" } },+ ],+ },+ collection_id: null,+ idAlias: "timelineDocumentId",+ });+ },+ );++ cy.intercept("POST", "/api/card/*/query").as("cardQuery");++ H.visitDocument("@timelineDocumentId");++ cy.wait(["@cardQuery", "@cardQuery", "@cardQuery"]);++ H.getDocumentCard(TIMESERIES_CARD_1)+ .findByTestId("chart-container")+ .should("exist");+ H.getDocumentCard(NON_TIMESERIES_CARD)+ .findByTestId("visualization-root")+ .should("exist");+ H.getDocumentCard(TIMESERIES_CARD_3)+ .findByTestId("chart-container")+ .should("exist");++ cy.log("Events menu appears for timeseries chart 1, not for chart 2");+ H.openDocumentCardMenu(TIMESERIES_CARD_1);+ H.popover()+ .findByRole("menuitem", { name: /Events/ })+ .should("be.visible");+ cy.realPress("Escape");++ H.openDocumentCardMenu(NON_TIMESERIES_CARD);+ H.popover()+ .findByRole("menuitem", { name: /Edit Visualization/ })+ .should("be.visible");+ H.popover()+ .findByRole("menuitem", { name: /Events/ })+ .should("not.exist");+ cy.realPress("Escape");++ cy.log("Add timeline to chart 1");+ H.openDocumentCardMenu(TIMESERIES_CARD_1);+ H.popover()+ .findByRole("menuitem", { name: /Events/ })+ .click();++ documentTimelineSidebar().should("be.visible");+ documentTimelineHeaderCheckbox(TIMELINE_NAME)+ .should("not.be.checked")+ .click();+ documentTimelineHeaderCheckbox(TIMELINE_NAME).should("be.checked");++ documentCardTimelineEventChip(+ TIMESERIES_CARD_1,+ TIMELINE_EVENT_NAME,+ ).should("be.visible");++ cy.log("Open timeline sidebar by clicking event chip");+ closeDocumentTimelineSidebar();+ documentTimelineSidebar().should("not.exist");++ H.getDocumentCard(TIMESERIES_CARD_1)+ .findByTestId("timeline-event-chip")+ .click();++ documentTimelineSidebar().should("be.visible");++ cy.log("Chart 3 has independent timeline state");+ selectDocumentCard(TIMESERIES_CARD_3);++ documentTimelineHeaderCheckbox(TIMELINE_NAME).should("not.be.checked");+ documentCardTimelineEventChip(+ TIMESERIES_CARD_3,+ TIMELINE_EVENT_NAME,+ ).should("not.exist");++ cy.log("Remove timeline from chart 1");+ selectDocumentCard(TIMESERIES_CARD_1);++ documentTimelineHeaderCheckbox(TIMELINE_NAME)+ .should("be.checked")+ .click();+ documentTimelineHeaderCheckbox(TIMELINE_NAME).should("not.be.checked");+ documentCardTimelineEventChip(+ TIMESERIES_CARD_1,+ TIMELINE_EVENT_NAME,+ ).should("not.exist");+ });+ });});+function documentTimelineSidebar() {+ return cy.findByTestId("document-timeline-sidebar");+}++function documentTimelineHeaderCheckbox(timelineName: string) {+ return documentTimelineSidebar()+ .findAllByLabelText("Timeline card header")+ .filter((_, el) => el.textContent?.includes(timelineName) ?? false)+ .should("have.length", 1)+ .findByRole("checkbox");+}++function closeDocumentTimelineSidebar() {+ return documentTimelineSidebar().findByLabelText("Close").click();+}++function selectDocumentCard(cardName: string) {+ return H.getDocumentCard(cardName).click("top");+}++function documentCardTimelineEventChip(cardName: string, eventName: string) {+ return H.getDocumentCard(cardName).findByRole("button", {+ name: eventName,+ });+}+const assertOnlyOneOptionActive = (name: string | RegExp,dialog: "command" | "mention" | "metabot" = "command",diff --git a/e2e/test/scenarios/explorations/explorations.cy.spec.ts b/e2e/test/scenarios/explorations/explorations.cy.spec.tsindex d943c48b03d..de249fb5698 100644--- a/e2e/test/scenarios/explorations/explorations.cy.spec.ts+++ b/e2e/test/scenarios/explorations/explorations.cy.spec.ts@@ -366,77 +366,6 @@ describe("scenarios > explorations > detail page", () => {H.expectNoBadSnowplowEvents();});- it("auto-selects the top-ranked sidebar row on first load", () => {- H.createExplorationViaApi({ name: "Auto-select fixture" }).then((id) => {- visitExplorationUntilSettled(id, 2);-- // Auto-selection follows the interestingness-sorted tree the backend's- // scores produce: the top page row is selected on load. The- // ArrowRight/ArrowLeft and click selection mechanics are unit-tested- // in ExplorationSidebar.unit.spec.tsx.- cy.findAllByRole("treeitem", { timeout: 15000 })- .first()- .should("have.attr", "aria-selected", "true");- cy.findAllByRole("treeitem")- .filter('[aria-selected="true"]')- .should("have.length", 1);- });- });-- it("groups sidebar rows under their metric heading, ordered by interestingness", () => {- createTwoPageExploration("Sidebar grouping fixture").then(- ({ explorationId, metricName, pageNames }) => {- visitExplorationUntilSettled(explorationId, pageNames.length);-- // Deliberately no `.within()` here: a `within` captures the sidebar- // node once, and background refetches can remount it (or its rows) —- // after which every inner query runs against the detached old node- // and times out. Fresh root-based chains re-query on every retry.- const sidebarScope = () => cy.findByTestId("exploration-page-sidebar");-- sidebarScope()- .findByRole("group", { name: metricName })- .should("be.visible");- for (const pageName of pageNames) {- sidebarScope().findByText(pageName).should("be.visible");- }-- // Row order is backend-driven: pages sort by their queries' highest- // interestingness score. Collapse/expand click mechanics are- // unit-tested in ExplorationSidebar.unit.spec.tsx.- cy.request("GET", `/api/exploration/${explorationId}`).then(- ({ body }) => {- // Unjustified type cast. FIXME- const exploration = body as Exploration;- const thread = exploration.threads?.[0];- const queries = thread?.queries ?? [];- const pages = (thread?.blocks ?? []).flatMap(- (block) => block.pages ?? [],- );- const scoreOf = (page: { query_ids: number[] }) =>- Math.max(- ...page.query_ids.map(- (queryId) =>- queries.find((query) => query.id === queryId)- ?.interestingness_score ?? -Infinity,- ),- );- const expectedOrder = [...pages]- .sort((a, b) => scoreOf(b) - scoreOf(a))- .map((page) => page.name);-- sidebarScope()- .findAllByRole("treeitem")- .then(($rows) => {- const rowTexts = [...$rows].map((el) => el.textContent?.trim());- expect(rowTexts).to.deep.eq(expectedOrder);- });- },- );- },- );- });-it("changes sidebar selection on click and shows the corresponding visualization area", () => {H.createExplorationViaApi({ name: "Click selection fixture" }).then((id) => {@@ -447,7 +376,7 @@ describe("scenarios > explorations > detail page", () => {// row that is NOT selected and assert the selection moves to it.cy.findAllByRole("treeitem").filter('[aria-selected="false"]')- .first()+ .eq(1) // first treeitem is the summary document.invoke("attr", "href").then((href) => {cy.get(`[role="treeitem"][href="${href}"]`).click();@@ -658,7 +587,7 @@ describe("scenarios > explorations > sidebar triage", () => {cy.log("Star the selected page with the s shortcut");cy.findByRole("radio", { name: "All" }).click({ force: true });- cy.findAllByRole("treeitem").should("have.length", 2);+ cy.findAllByRole("treeitem").should("have.length", 3); // summary document + 2 pagessidebar().findByText(pageNames[0]).click();selectedRows().should("contain.text", pageNames[0]);cy.intercept("PUT", "/api/exploration/page/*/starred").as("setStarred");@@ -739,7 +668,7 @@ describe("scenarios > explorations > sidebar triage", () => {// orders pages by interestingness — so which of the two// dimension-named pages is selected is data-dependent; derive it// from the DOM instead of assuming.- cy.findAllByRole("treeitem").should("have.length", 2);+ cy.findAllByRole("treeitem").should("have.length", 3); // summary document + 2 pagesselectedRows().should("have.length", 1);selectedRows().first()@@ -768,7 +697,7 @@ describe("scenarios > explorations > sidebar triage", () => {cy.log("Auto-advance moves the selection to the remaining page");selectedRows().should("contain.text", secondPageName);- cy.findAllByRole("treeitem").should("have.length", 1);+ cy.findAllByRole("treeitem").should("have.length", 2); // summary document + 1 non-hidden pagesidebar().findByText(firstPageName).should("not.exist");cy.log("Show hidden items reveals the page with a Hidden marker");@@ -777,7 +706,7 @@ describe("scenarios > explorations > sidebar triage", () => {sidebar().findByText(firstPageName).should("be.visible");sidebar().findAllByLabelText("Hidden").should("have.length", 1);toggleShowHiddenItems();- cy.findAllByRole("treeitem").should("have.length", 1);+ cy.findAllByRole("treeitem").should("have.length", 2);sidebar().findByText(firstPageName).should("not.exist");});@@ -794,19 +723,16 @@ describe("scenarios > explorations > sidebar triage", () => {.findByText(`${metricName} hidden`).should("be.visible");- cy.log("All-hidden note is visible");- cy.findByText("All items have been hidden.").should("be.visible");- cy.findAllByRole("treeitem").should("not.exist");+ cy.log("Everything but the summary document is hidden");+ cy.findAllByRole("treeitem").should("have.length", 1);cy.log("Hidden state is persisted server-side across a reload");cy.reload();- cy.findByText("All items have been hidden.", { timeout: 15000 }).should(- "be.visible",- );+ cy.findAllByRole("treeitem").should("have.length", 1);cy.log("Show hidden items + the group Show action restore the pages");toggleShowHiddenItems();- cy.findAllByRole("treeitem").should("have.length", 2);+ cy.findAllByRole("treeitem").should("have.length", 3);sidebar().findAllByLabelText("Hidden").should("have.length", 2);sidebar().findByRole("group", { name: metricName })@@ -816,12 +742,12 @@ describe("scenarios > explorations > sidebar triage", () => {cy.wait("@setPagesHidden").its("request.body.hidden").should("eq", false);- cy.findAllByRole("treeitem").should("have.length", 2);+ cy.findAllByRole("treeitem").should("have.length", 3);sidebar().findAllByLabelText("Hidden").should("not.exist");cy.log("Hiding the group with every page visible sends both page ids");toggleShowHiddenItems();- cy.findAllByRole("treeitem").should("have.length", 2);+ cy.findAllByRole("treeitem").should("have.length", 3);sidebar().findByRole("group", { name: metricName }).findByRole("button", { name: "Group actions" })@@ -831,7 +757,7 @@ describe("scenarios > explorations > sidebar triage", () => {expect(request.body.hidden).to.eq(true);expect(request.body.page_ids).to.have.length(2);});- cy.findByText("All items have been hidden.").should("be.visible");+ cy.findAllByRole("treeitem").should("have.length", 1);cy.log("Undo on the group-hidden toast restores the whole group");H.undoToastListContainer()@@ -843,8 +769,7 @@ describe("scenarios > explorations > sidebar triage", () => {cy.wait("@setPagesHidden").its("request.body.hidden").should("eq", false);- cy.findAllByRole("treeitem").should("have.length", 2);- cy.findByText("All items have been hidden.").should("not.exist");+ cy.findAllByRole("treeitem").should("have.length", 3);},);});@@ -1032,7 +957,7 @@ describe("scenarios > explorations > chart click-through", () => {});});- it("brushing a timeseries cartesian chart opens Explore further only, posts between explore_filters, and navigates from the new-thread toast", () => {+ it("brushing a timeseries cartesian chart opens Explore further only, posts between explore_filters, navigates from the new-thread toast, and Add to Summary preserves filter pills", () => {cy.request<GetExplorationDataResponse>("GET","/api/exploration/dimensions",@@ -1146,12 +1071,159 @@ describe("scenarios > explorations > chart click-through", () => {cy.findByTestId("filter-pill").should("be.visible").invoke("text")- .should("match", /–/);+ .should("match", /–/)+ .as("exploreFilterPillText");++ cy.intercept(+ "POST",+ `/api/exploration/${explorationId}/summary/append`,+ ).as("appendSummary");++ cy.findByRole("button", { name: "Add to Summary" }).click();+ cy.wait("@appendSummary");++ H.undoToastListContainer().within(() => {+ cy.findByText(/Added to/).should("be.visible");+ cy.findByRole("button", { name: "View" }).click();+ });++ cy.location("pathname").should(+ "eq",+ `/question/research/${explorationId}/summary`,+ );+ cy.findByTestId("document-card-embed", { timeout: 15000 })+ .should("be.visible")+ .findByTestId("filter-pill")+ .should("be.visible")+ .invoke("text")+ .then((text) => {+ cy.get("@exploreFilterPillText").should("eq", text);+ });});});});});+describe("scenarios > explorations > Summary document", () => {+ beforeEach(() => {+ cy.task("stopMockLlmServer");+ H.restore();+ cy.signInAsAdmin();+ H.enableExplorations();+ seedMetrics();+ });++ it("auto-creates Summary at the top of the tree, keeps pages selected initially, supports Add to Summary, and mirrors comments both ways", () => {+ H.createExplorationViaApi({ name: "Summary fixture" }).then(+ (explorationId) => {+ cy.request("GET", `/api/exploration/${explorationId}`).then(+ ({ body }) => {+ // api returns an Exploration+ const exploration = body as Exploration;+ expect(exploration.document, "BE auto-creates a Summary document")+ .to.exist;+ expect(exploration.document?.name).to.eq("Summary");+ expect(exploration.document?.is_placeholder).to.eq(true);+ },+ );++ visitExplorationUntilSettled(explorationId, 1);++ // Summary is pinned at the top of the tree but not initially selected+ // while it is still a placeholder.+ cy.findAllByRole("treeitem")+ .first()+ .should("contain.text", "Summary")+ .and("have.attr", "aria-selected", "false");++ // Capture the settled page id from the auto-selected sidebar row+ // (pages only exist after settlement), then click through+ cy.findAllByRole("treeitem")+ .filter('[aria-selected="true"]')+ .should("have.length", 1)+ .and("not.contain.text", "Summary")+ .invoke("attr", "href")+ .should("match", /\/page\/\d+/)+ .then((href) => {+ const pageId = Number(/\/page\/(\d+)/.exec(href!)![1]);+ cy.wrap(pageId).as("pageId");+ cy.get(`[role="treeitem"][href="${href}"]`).click();+ });++ cy.location("pathname").should("match", /\/page\/\d+$/);+ cy.findByTestId("exploration-chart-grid").should("be.visible");++ cy.intercept(+ "POST",+ `/api/exploration/${explorationId}/summary/append`,+ ).as("appendSummary");++ cy.findByRole("button", { name: "Add to Summary" }).click();+ cy.wait("@appendSummary").then(({ response }) => {+ expect(response?.statusCode).to.eq(200);+ expect(response?.body?.is_placeholder).to.eq(false);+ });++ H.undoToastListContainer()+ .findByText(/Added to/)+ .should("be.visible");+ H.undoToast().findByRole("button", { name: "View" }).click();++ cy.location("pathname").should(+ "eq",+ `/question/research/${explorationId}/summary`,+ );+ cy.findByTestId("document-card-embed", { timeout: 15000 }).should(+ "be.visible",+ );++ // Seed a page comment via API+ cy.get<number>("@pageId").then((pageId) => {+ H.createComment({+ target_type: "exploration",+ target_id: explorationId,+ child_target_id: String(pageId),+ parent_comment_id: null,+ content: {+ type: "doc",+ content: [+ {+ type: "paragraph",+ content: [{ type: "text", text: "Shared comment" }],+ },+ ],+ },+ });+ });++ // Cold-load the Summary with the comments query param — the panel+ // must open without a prior click (the deep-link regression).+ cy.get<number>("@pageId").then((pageId) => {+ cy.visit(+ `/question/research/${explorationId}/summary?comments=${pageId}`,+ );+ cy.findByTestId("exploration-summary-comments", {+ timeout: 15000,+ })+ .should("be.visible")+ .and("contain.text", "Shared comment");+ });++ cy.get<number>("@pageId").then((pageId) => {+ cy.visit(+ `/question/research/${explorationId}/page/${pageId}?comments=${pageId}`,+ );+ });++ cy.findByTestId("exploration-comments", { timeout: 15000 }).should(+ "contain.text",+ "Shared comment",+ );+ },+ );+ });+});+describe("scenarios > explorations > collection placement + archive", () => {beforeEach(() => {cy.task("stopMockLlmServer");diff --git a/enterprise/backend/src/metabase_enterprise/remote_sync/spec.clj b/enterprise/backend/src/metabase_enterprise/remote_sync/spec.cljindex e7a23cce83a..5d1a82ee982 100644--- a/enterprise/backend/src/metabase_enterprise/remote_sync/spec.clj+++ b/enterprise/backend/src/metabase_enterprise/remote_sync/spec.clj@@ -124,6 +124,7 @@:tracking {:select-fields [:name :collection_id]:field-mappings {:model_name :name:model_collection_id :collection_id}}+ :conditions {:exploration_id nil} ; exclude exploration Summary docs from sync:removal {:statuses #{"removed"}:scope-key :collection_id}:enabled? true}@@ -757,7 +758,7 @@(defn- object-matches-conditions?"True if `object` satisfies every column-value pair in `conditions` (or if no conditions are set).A key MISSING from `object` does not match, even against a nil condition value — eligibility needs- positive evidence the condition holds (e.g. the snippet spec's `{:built_in_type nil}` must+ positive evidence the condition holds (e.g. the Document spec's `{:exploration_id nil}` mustsee an explicit nil, not an absent key), so a partial payload can't sneak conditioned rows intosync scope.NOTE: only handles scalar values — non-scalar `:conditions` (e.g. `[:not= ...]`) are not supported here.diff --git a/enterprise/backend/test/metabase_enterprise/remote_sync/impl_test.clj b/enterprise/backend/test/metabase_enterprise/remote_sync/impl_test.cljindex f753474b7a3..83a91c67f90 100644--- a/enterprise/backend/test/metabase_enterprise/remote_sync/impl_test.clj+++ b/enterprise/backend/test/metabase_enterprise/remote_sync/impl_test.clj@@ -1491,6 +1491,26 @@ serdes/meta:(is (some #(= :library-conflict (:type %)) (:conflict-details result))"Should have library-conflict type in details"))))))+(deftest remove-unsynced!-preserves-exploration-documents-test+ (testing "remove-unsynced! does not delete local exploration documents in remote-synced collections (UXW-4091)"+ (mt/with-temp [:model/Collection {coll-id :id} {:name "Synced"+ :location "/"+ :is_remote_synced true}+ :model/User {user-id :id} {:email "[email protected]"}+ :model/Exploration {explo-id :id} {:name "Explo" :creator_id user-id}+ :model/Document {plain-doc-id :id} {:name "Plain Doc"+ :creator_id user-id+ :collection_id coll-id}+ :model/Document {explo-doc-id :id} {:name "Exploration Doc"+ :creator_id user-id+ :collection_id coll-id+ :exploration_id explo-id}]+ (#'impl/remove-unsynced! [coll-id] {:by-entity-id {}})+ (is (not (t2/exists? :model/Document :id plain-doc-id))+ "plain doc should be deleted because it's not in the imported set")+ (is (t2/exists? :model/Document :id explo-doc-id)+ "exploration doc should be preserved by the :exploration_id condition"))))+(deftest import!-transforms-conflict-test(testing "import! detects transforms conflict when local has transforms and import has transforms"(let [task-id (t2/insert-returning-pk! :model/RemoteSyncTask {:sync_task_type "import" :initiated_by (mt/user->id :rasta)})]diff --git a/enterprise/backend/test/metabase_enterprise/remote_sync/spec_test.clj b/enterprise/backend/test/metabase_enterprise/remote_sync/spec_test.cljindex 9f048733e1e..583a226d488 100644--- a/enterprise/backend/test/metabase_enterprise/remote_sync/spec_test.clj+++ b/enterprise/backend/test/metabase_enterprise/remote_sync/spec_test.clj@@ -473,6 +473,25 @@(is (= {:entity_id [:not= transforms-python/builtin-entity-id]}(spec/removal-conditions spec))))))+(deftest document-spec-excludes-explorations-test+ (testing "Document spec filters out exploration Summary documents via :conditions (UXW-4091)"+ (let [spec (spec/spec-for-model-key :model/Document)]+ (is (= {:exploration_id nil} (:conditions spec))+ "Document :conditions should require exploration_id IS NULL")+ (is (= {:exploration_id nil} (spec/export-conditions spec)))+ (is (= {:exploration_id nil} (spec/removal-conditions spec)))))+ (testing "check-eligibility returns false for an exploration document, even in a remote-synced collection"+ (mt/with-temp [:model/Collection {coll-id :id} {:name "Synced" :location "/" :is_remote_synced true}]+ (let [spec (spec/spec-for-model-key :model/Document)+ plain-doc {:id 1 :collection_id coll-id :exploration_id nil}+ explo-doc {:id 2 :collection_id coll-id :exploration_id 42}+ partial-doc {:id 3 :collection_id coll-id}]+ (is (true? (spec/check-eligibility spec plain-doc)))+ (is (false? (spec/check-eligibility spec explo-doc)))+ (testing "a payload MISSING the conditioned key does not match the nil condition (fail closed)"+ (is (false? (spec/check-eligibility spec partial-doc))+ "eligibility needs an explicit nil, not an absent key — a partial payload must not sneak an exploration Summary into sync scope"))))))+(deftest transform-tag-spec-uses-conditions-test(testing "TransformTag spec still uses :conditions (not split)"(let [spec (spec/spec-for-model-key :model/TransformTag)]diff --git a/enterprise/backend/test/metabase_enterprise/semantic_search/appdb_pgvector_mode_test.clj b/enterprise/backend/test/metabase_enterprise/semantic_search/appdb_pgvector_mode_test.cljindex e6a0c155597..cda9fcd43f2 100644--- a/enterprise/backend/test/metabase_enterprise/semantic_search/appdb_pgvector_mode_test.clj+++ b/enterprise/backend/test/metabase_enterprise/semantic_search/appdb_pgvector_mode_test.clj@@ -119,31 +119,42 @@(is (nil? @semantic.db.datasource/data-source)"the shared pool must never land in the module's own pool atom")(is (= "semantic_search" (:schema (semantic.env/get-index-metadata)))))- (let [pgvector (semantic.env/get-pgvector-datasource!)- index-metadata (semantic.env/get-index-metadata)- public-before (tables-in-schema app-db "public")]- (semantic.pgvector-api/init-semantic-search! pgvector index-metadata- (semantic.env/get-configured-embedding-model))- (semantic.pgvector-api/index-documents! pgvector index-metadata (semantic.tu/mock-documents))- (testing "every module table lives inside the semantic_search schema"- (let [tables (tables-in-schema app-db "semantic_search")]- (is (contains? tables "migration"))- (is (contains? tables "index_metadata"))- (is (contains? tables "index_control"))- (is (contains? tables "index_gate"))- (is (contains? tables (semantic.index/model-table-name semantic.tu/mock-embedding-model)))- (is (some #(str/starts-with? % "dlq_") tables))))- (testing "search round-trips through the app-db pool"- ;; results are reconstructed from legacy_input, so the mock card comes back as model+id- (is (= [{:model "card" :id 123}]- (->> (mt/with-test-user :crowberto- (semantic.pgvector-api/query pgvector index-metadata- {:search-string "puppy" :archived? false}))- :results- (filter (comp #{"card"} :model))- (mapv #(select-keys % [:model :id]))))))- (testing "the application schema is untouched"- (is (= public-before (tables-in-schema app-db "public")))))+ ;; The permission filter resolves a Card result to its row (`mi/can-read?` on a Card+ ;; consults its `document_id`, so Cards are off the collection-id-only fast path), and+ ;; drops one it cannot find. Back the indexed card with a real row so the round trip+ ;; measures the round trip rather than the absence of a fixture.+ (mt/with-temp [:model/Card {card-id :id} {:name "Dog Training Guide"}]+ (let [pgvector (semantic.env/get-pgvector-datasource!)+ index-metadata (semantic.env/get-index-metadata)+ public-before (tables-in-schema app-db "public")+ documents (mapv (fn [doc]+ (cond-> doc+ (= "card" (:model doc))+ (-> (assoc :id card-id)+ (assoc-in [:legacy_input :id] card-id))))+ (semantic.tu/mock-documents))]+ (semantic.pgvector-api/init-semantic-search! pgvector index-metadata+ (semantic.env/get-configured-embedding-model))+ (semantic.pgvector-api/index-documents! pgvector index-metadata documents)+ (testing "every module table lives inside the semantic_search schema"+ (let [tables (tables-in-schema app-db "semantic_search")]+ (is (contains? tables "migration"))+ (is (contains? tables "index_metadata"))+ (is (contains? tables "index_control"))+ (is (contains? tables "index_gate"))+ (is (contains? tables (semantic.index/model-table-name semantic.tu/mock-embedding-model)))+ (is (some #(str/starts-with? % "dlq_") tables))))+ (testing "search round-trips through the app-db pool"+ ;; results are reconstructed from legacy_input, so the mock card comes back as model+id+ (is (= [{:model "card" :id card-id}]+ (->> (mt/with-test-user :crowberto+ (semantic.pgvector-api/query pgvector index-metadata+ {:search-string "puppy" :archived? false}))+ :results+ (filter (comp #{"card"} :model))+ (mapv #(select-keys % [:model :id]))))))+ (testing "the application schema is untouched"+ (is (= public-before (tables-in-schema app-db "public"))))))(finally(jdbc/execute! app-db ["DROP SCHEMA IF EXISTS semantic_search CASCADE"])))))))))@@ -178,22 +189,33 @@semantic.embedding/get-configured-model (constantly in-process-embedding-model)](let [app-db (mdb/data-source)](try- (let [pgvector (semantic.env/get-pgvector-datasource!)- index-metadata (semantic.env/get-index-metadata)- documents (mapv #(assoc % :archived false) (semantic.tu/mock-documents))]- (is (semantic.core/supported?) "the semantic search engine accepts the registered provider")- (semantic.pgvector-api/init-semantic-search! pgvector index-metadata- (semantic.env/get-configured-embedding-model))- (semantic.pgvector-api/index-documents! pgvector index-metadata documents)- (testing "real in-process embeddings flow through indexing and semantic querying"- (is (= {:model "card" :id 123}- (-> (semantic.tu/with-weights {:semantic-distance 1}- (mt/with-test-user :crowberto- (semantic.pgvector-api/query pgvector index-metadata- {:search-string "puppy"- :vector-search-strategy :brute-force})))- :results- first- (select-keys [:model :id]))))))+ ;; As in the mock-embedder round trip above: `mi/can-read?` on a Card consults its+ ;; `document_id`, which keeps Cards off the collection-id-only fast path, so the permission+ ;; filter resolves each Card result to its row and drops one it cannot find. Back the indexed+ ;; card with a real row, or the only surviving result is the dashboard and this test measures+ ;; the missing fixture rather than the embeddings.+ (mt/with-temp [:model/Card {card-id :id} {:name "Dog Training Guide"}]+ (let [pgvector (semantic.env/get-pgvector-datasource!)+ index-metadata (semantic.env/get-index-metadata)+ documents (mapv (fn [doc]+ (cond-> (assoc doc :archived false)+ (= "card" (:model doc))+ (-> (assoc :id card-id)+ (assoc-in [:legacy_input :id] card-id))))+ (semantic.tu/mock-documents))]+ (is (semantic.core/supported?) "the semantic search engine accepts the registered provider")+ (semantic.pgvector-api/init-semantic-search! pgvector index-metadata+ (semantic.env/get-configured-embedding-model))+ (semantic.pgvector-api/index-documents! pgvector index-metadata documents)+ (testing "real in-process embeddings flow through indexing and semantic querying"+ (is (= {:model "card" :id card-id}+ (-> (semantic.tu/with-weights {:semantic-distance 1}+ (mt/with-test-user :crowberto+ (semantic.pgvector-api/query pgvector index-metadata+ {:search-string "puppy"+ :vector-search-strategy :brute-force})))+ :results+ first+ (select-keys [:model :id])))))))(finally(jdbc/execute! app-db ["DROP SCHEMA IF EXISTS semantic_search CASCADE"]))))))))diff --git a/enterprise/backend/test/metabase_enterprise/semantic_search/index_test.clj b/enterprise/backend/test/metabase_enterprise/semantic_search/index_test.cljindex 098d71c1d3b..434385e3a12 100644--- a/enterprise/backend/test/metabase_enterprise/semantic_search/index_test.clj+++ b/enterprise/backend/test/metabase_enterprise/semantic_search/index_test.clj@@ -768,16 +768,34 @@(let [result (#'semantic.index/filter-read-permitted docs)](is (= 1 (count result)))(is (= "1:123" (:id (first result)))))))))- (testing "card/metric/dataset/dashboard docs use the same fast path"- (doseq [model ["card" "metric" "dataset" "dashboard"]]+ (testing "dashboard docs use the same fast path"+ ;; Fast-path docs are adjudicated from the index row's denormalized `:collection_id` alone, so+ ;; these fabricated ids never have to correspond to real rows. That is the whole point of the+ ;; path — and the reason card/metric/dataset, which now take the slow path, need real rows below.+ (let [docs [{:id 1 :model "dashboard" :collection_id readable-coll-id}+ {:id 2 :model "dashboard" :collection_id unreadable-coll-id}+ {:id 3 :model "dashboard" :collection_id nil}]]+ (binding [api/*current-user-permissions-set* (atom #{(format "/collection/%d/read/" readable-coll-id)})]+ (let [result (#'semantic.index/filter-read-permitted docs)]+ (is (= [1] (map :id result))+ "only the doc whose denormalized collection_id is readable survives")))))+ (testing "card/metric/dataset docs take the slow path"+ ;; `:model/Card` left the collection-id-only registry once a Card could be scoped to a Document+ ;; and gated by it rather than by its collection. The slow path loads the real row and runs+ ;; `mi/can-read?` on it, so the verdict must still track the *collection* for an ordinary Card —+ ;; and it must ignore a `:collection_id` on the index row that disagrees with the database.+ (doseq [[model card-type] [["card" :question] ["metric" :metric] ["dataset" :model]]](testing (str "model=" model)- (let [docs [{:id 1 :model model :collection_id readable-coll-id}- {:id 2 :model model :collection_id unreadable-coll-id}- {:id 3 :model model :collection_id nil}]]+ (mt/with-temp [:model/Card {readable-id :id} {:type card-type :collection_id readable-coll-id}+ :model/Card {unreadable-id :id} {:type card-type :collection_id unreadable-coll-id}](binding [api/*current-user-permissions-set* (atom #{(format "/collection/%d/read/" readable-coll-id)})]- (let [result (#'semantic.index/filter-read-permitted docs)]- (is (= [1] (map :id result))- "only the doc whose denormalized collection_id is readable survives")))))))+ (let [result (#'semantic.index/filter-read-permitted+ [{:id readable-id :model model :collection_id readable-coll-id}+ {:id unreadable-id :model model :collection_id unreadable-coll-id}+ ;; a stale index row claiming a readable collection must not win:+ ;; the slow path reads the live row, not the denormalized copy+ {:id unreadable-id :model model :collection_id readable-coll-id}])]+ (is (= [readable-id] (map :id result)))))))))(testing "memoizes permission check per collection_id across docs"(let [calls (atom 0)real-helper perms/can-read-via-parent-collection?]@@ -794,7 +812,13 @@(deftest collection-id-only-search-models-derived-correctly-test(testing "derived set includes every collection-id-only search-model plus indexed-entity";; Update the expected set when `define-collection-based-visibility!` is added to or removed from a model.- (is (= #{"card" "metric" "dataset" "dashboard" "indexed-entity"}+ ;;+ ;; "card"/"dataset"/"metric" are deliberately absent: a Card scoped to a Document is gated by that+ ;; Document rather than by its collection (see `metabase.queries.models.card/parent-document-permits?`),+ ;; so `:model/Card` no longer meets the macro's collection-id-only contract and dropped its+ ;; registration. Cards take `filter-read-permitted`'s slow path — one batched `t2/select` per result+ ;; page — which is the price of adjudicating them correctly.+ (is (= #{"dashboard" "indexed-entity"}@@#'semantic.index/collection-id-only-search-models))))(deftest collection-based-visibility-search-model-claims-verified-test@@ -847,7 +871,7 @@;; The derivation must call `search/specifications` before reading either registry — `t2/resolve-model`;; inside `specifications` loads the model namespaces that populate them.;; If the order flips, cold start caches an empty set for the JVM lifetime. Both the t2-model registry- ;; (card/metric/dataset/dashboard) and the search-model registry (indexed-entity) must be covered.+ ;; (dashboard) and the search-model registry (indexed-entity) must be covered.(let [real-specs (var-get #'search/specifications)real-t2-registry perms/collection-id-only-read-modelsreal-search-registry perms/collection-based-visibility-search-models@@ -864,9 +888,8 @@(real-search-registry){}))](let [result (#'semantic.index/compute-collection-id-only-search-models)]- (is (contains? result "card"))- (is (contains? result "dashboard"))- (is (contains? result "indexed-entity")))))))+ (is (contains? result "dashboard") "keyword-form registry populated")+ (is (contains? result "indexed-entity") "search-model registry populated"))))))(deftest to-boolean-test(testing "to-boolean function correctly converts various input types to booleans"diff --git a/enterprise/backend/test/metabase_enterprise/semantic_search/vector_strategy_matrix_test.clj b/enterprise/backend/test/metabase_enterprise/semantic_search/vector_strategy_matrix_test.cljindex c152431875a..922140c799b 100644--- a/enterprise/backend/test/metabase_enterprise/semantic_search/vector_strategy_matrix_test.clj+++ b/enterprise/backend/test/metabase_enterprise/semantic_search/vector_strategy_matrix_test.clj@@ -113,13 +113,20 @@adversarial for post-filtering strategies. The adversarial filter must be a column with no supportingbtree: a :models filter would be served exactly by the (model, model_id) unique constraint at this tablesize, bypassing the HNSW scan the matrix is exercising.- - :decoy lies beyond the cutoff and must never be returned."- [{:band :restricted :n 8 :model "card" :d0 0.020 :dstep 0.005}- {:band :core :n 180 :model "card" :d0 0.100 :dstep 0.0015}- {:band :mid :n 74 :model "card" :d0 0.400 :dstep 0.0008}- {:band :pinned :n 6 :model "card" :d0 0.465 :dstep 0.002 :pinned true}- {:band :rare :n 12 :model "card" :d0 0.550 :dstep 0.008 :verified true}- {:band :decoy :n 20 :model "card" :d0 0.750 :dstep 0.007}])+ - :decoy lies beyond the cutoff and must never be returned.++ The model is `dashboard` because [[permission-under-fetch-matrix-test]] exercises the real+ permission filter against these synthetic docs, and only a model on `filter-read-permitted`'s+ collection-id-only fast path is adjudicated from the doc's denormalized `:collection_id` without+ loading a row. A slow-path model (`card`, since a Card can be scoped to a Document and gated by+ it) would have every one of these 300 ids miss in `report_card` and be dropped, collapsing the+ measurement to zero. Nothing else here depends on which model it is."+ [{:band :restricted :n 8 :model "dashboard" :d0 0.020 :dstep 0.005}+ {:band :core :n 180 :model "dashboard" :d0 0.100 :dstep 0.0015}+ {:band :mid :n 74 :model "dashboard" :d0 0.400 :dstep 0.0008}+ {:band :pinned :n 6 :model "dashboard" :d0 0.465 :dstep 0.002 :pinned true}+ {:band :rare :n 12 :model "dashboard" :d0 0.550 :dstep 0.008 :verified true}+ {:band :decoy :n 20 :model "dashboard" :d0 0.750 :dstep 0.007}])(defn- vector-at-distance"A unit `dims`-d vector at exact cosine distance `d` (pgvector `<=>`) from the probe `[1 0 0 ...]`."diff --git a/frontend/lint/module-boundaries.mjs b/frontend/lint/module-boundaries.mjsindex 3da10acfc69..a4beaa34a61 100644--- a/frontend/lint/module-boundaries.mjs+++ b/frontend/lint/module-boundaries.mjs@@ -271,7 +271,7 @@ const elements = [createElement({ type: "feature", name: "admin" }),createElement({ type: "feature", name: "dashboard" }),createElement({ type: "feature", name: "data-studio" }),- createElement({ type: "feature", name: "documents" }),+ createElement({ type: "shared", name: "documents" }),// EE plugin-bootstrap files that only wire app-tier SDK modules into plugin// slots, so they're app tier, not feature/enterprise. Tagged by which embedding// product they belong to. Must precede the feature/enterprise element belowdiff --git a/frontend/src/metabase-types/api/card.ts b/frontend/src/metabase-types/api/card.tsindex 4c2ce268fd6..6093b7606f8 100644--- a/frontend/src/metabase-types/api/card.ts+++ b/frontend/src/metabase-types/api/card.ts@@ -28,6 +28,7 @@ import type { DownloadPermission } from "./permissions";import type { DatasetQuery, FieldReference, PublicDatasetQuery } from "./query";import type { CollectionEssentials } from "./search";import type { Table, TableId } from "./table";+import type { TimelineEventId, TimelineId } from "./timeline";import type { UserInfo } from "./user";import type { CardDisplayType, VisualizationDisplay } from "./visualization";import type {@@ -407,6 +408,10 @@ export type VisualizationSettings = {/** Explicit order, labels, colors, and enabled state for breakout series. */"graph.series_order"?: SeriesOrderSetting[];+ // Timeline events settings+ "timeline.selected_timeline_ids"?: TimelineId[];+ "timeline.excluded_timeline_event_ids"?: TimelineEventId[];+/** Result numeric column name used to size scatter plot bubbles. */"scatter.bubble"?: string;@@ -682,12 +687,20 @@ export type InvalidCardRequest = {collection_id?: CollectionId | null;} & PaginationRequest;+export type StoredResultSort =+ | "value_asc"+ | "value_desc"+ | "label_asc"+ | "label_desc";+export type CardQueryRequest = {cardId: CardId;dashboardId?: DashboardId;collection_preview?: boolean;ignore_cache?: boolean;parameters?: unknown[];+ stored_result_id?: number;+ sort?: StoredResultSort;};export type GetPublicCard = Pick<Card, "id" | "name" | "public_uuid">;diff --git a/frontend/src/metabase-types/api/comments.ts b/frontend/src/metabase-types/api/comments.tsindex f85d1eca763..516780f5d0f 100644--- a/frontend/src/metabase-types/api/comments.ts+++ b/frontend/src/metabase-types/api/comments.ts@@ -1,4 +1,6 @@+import type { RowValue } from "./dataset";import type { DocumentContent } from "./document";+import type { ExplorationQueryId } from "./exploration";import type { TimelineId } from "./timeline";import type { BaseUser, User, UserId } from "./user";@@ -8,10 +10,17 @@ export type CommentEntityType = "document" | "exploration";export type EntityId = string | number;-export interface CommentContext {- timeline_id?: TimelineId;- [key: string]: unknown;-}+export type CommentHighlight = {+ columnName?: string;+ dimensions?: { value: RowValue; columnName: string }[];+};++export type CommentContext = {+ timeline_id?: TimelineId | null;+ exploration_query_ids?: ExplorationQueryId[];+ highlighted?: CommentHighlight;+ highlight_label?: string;+};export interface Comment {id: CommentId;diff --git a/frontend/src/metabase-types/api/document.ts b/frontend/src/metabase-types/api/document.tsindex a4868357997..26625e7e5f8 100644--- a/frontend/src/metabase-types/api/document.ts+++ b/frontend/src/metabase-types/api/document.ts@@ -28,6 +28,8 @@ export type Document = {made_public_by_id?: UserId | null;cards?: Record<number, Card>; // Map of card ID -> card metadata, hydrated for public documentsview_count?: number;+ exploration_id?: number | null;+ is_placeholder?: boolean;};export type GetDocumentRequest = { id: DocumentId };diff --git a/frontend/src/metabase-types/api/exploration.ts b/frontend/src/metabase-types/api/exploration.tsindex 83d1e635ed9..418492fbe16 100644--- a/frontend/src/metabase-types/api/exploration.ts+++ b/frontend/src/metabase-types/api/exploration.ts@@ -1,6 +1,7 @@-import type { CardId } from "./card";+import type { CardId, VisualizationSettings } from "./card";import type { Collection, CollectionId } from "./collection";import type { RowValue } from "./dataset";+import type { DocumentId } from "./document";import type {DimensionId,DimensionMapping,@@ -12,6 +13,7 @@ import type { DatasetQuery, DimensionReference } from "./query";import type { SegmentId } from "./segment";import type { Timeline, TimelineEvent, TimelineId } from "./timeline";import type { UserId } from "./user";+import type { VisualizationDisplay } from "./visualization";export type GetExplorationDataRequest = {q?: string;@@ -391,6 +393,29 @@ export interface ExplorationCreator {last_name?: string | null;}+/**+ * Lightweight Summary document hydrated on an exploration payload.+ * Full body is fetched separately via GET /api/document/:id.+ */+export interface ExplorationDocument {+ id: DocumentId;+ name: string;+ exploration_id: ExplorationId;+ creator_id: UserId;+ content_type: string;+ is_placeholder: boolean;+ created_at: string;+ updated_at: string;+ archived?: boolean;+}++export interface AppendChartToSummaryRequest {+ explorationId: ExplorationId;+ exploration_query_ids: ExplorationQueryId[];+ display: VisualizationDisplay;+ visualization_settings: VisualizationSettings;+}+export interface ExplorationSummary {id: ExplorationId;name: string;@@ -426,6 +451,7 @@ export interface Exploration {creator?: ExplorationCreator;threads?: ExplorationThread[];can_write: boolean;+ document?: ExplorationDocument | null;}export function getExplorationPages(diff --git a/frontend/src/metabase/api/exploration.ts b/frontend/src/metabase/api/exploration.tsindex 1476582ea81..e18e4898a8b 100644--- a/frontend/src/metabase/api/exploration.ts+++ b/frontend/src/metabase/api/exploration.ts@@ -1,9 +1,11 @@import type {+ AppendChartToSummaryRequest,CancelExplorationThreadRequest,CancelExplorationThreadResponse,CreateExplorationRequest,Dataset,Exploration,+ ExplorationDocument,ExplorationId,ExplorationQueryId,ExploreFurtherRequest,@@ -195,6 +197,21 @@ export const explorationApi = Api.injectEndpoints({}},}),+ appendChartToSummary: builder.mutation<+ ExplorationDocument,+ AppendChartToSummaryRequest+ >({+ query: ({ explorationId, ...body }) => ({+ method: "POST",+ url: `/api/exploration/${explorationId}/summary/append`,+ body,+ }),+ invalidatesTags: (result, error) =>+ invalidateTags(error, [+ ...(result ? [idTag("document", result.id)] : []),+ listTag("revision"),+ ]),+ }),}),});@@ -210,4 +227,5 @@ export const {useCancelExplorationThreadMutation,useSetPageStarredMutation,useSetPagesHiddenMutation,+ useAppendChartToSummaryMutation,} = explorationApi;diff --git a/frontend/src/metabase/app/nav/AppBar.tsx b/frontend/src/metabase/app/nav/AppBar.tsxindex 66bc47f2f37..d0724aaa583 100644--- a/frontend/src/metabase/app/nav/AppBar.tsx+++ b/frontend/src/metabase/app/nav/AppBar.tsx@@ -13,10 +13,7 @@ import {} from "metabase/app/selectors";import { useInitialCollectionId } from "metabase/common/collections/hooks";import { getUser } from "metabase/current-user";-import {- getCommentSidebarOpen,- getSidebarOpen,-} from "metabase/documents/selectors";+import { getIsSidebarOpen } from "metabase/documents/selectors";import { getMetabotVisible } from "metabase/metabot/state";import { AppBar as AppBarView } from "metabase/nav/components/AppBar";import { CollectionBreadcrumbs } from "metabase/nav/containers/CollectionBreadcrumbs";@@ -72,8 +69,7 @@ export function AppBarContainer() {const isMetabotVisible = useSelector((state) =>getMetabotVisible(state, "omnibot"),);- const isDocumentSidebarOpen = useSelector(getSidebarOpen);- const isCommentSidebarOpen = useSelector(getCommentSidebarOpen);+ const isDocumentSidebarOpen = useSelector(getIsSidebarOpen);const isLogoVisible = useSelector(getIsLogoVisible);const isSearchVisible = useSelector(getIsSearchVisible);const isEmbeddingIframe = isWithinIframe();@@ -129,7 +125,6 @@ export function AppBarContainer() {isNavBarEnabled={isNavBarEnabled}isMetabotVisible={isMetabotVisible}isDocumentSidebarOpen={isDocumentSidebarOpen}- isCommentSidebarOpen={isCommentSidebarOpen}isLogoVisible={isLogoVisible}isSearchVisible={isSearchVisible}isEmbeddingIframe={isEmbeddingIframe}diff --git a/frontend/src/metabase/comments/components/Comments/Comments.tsx b/frontend/src/metabase/comments/components/Comments/Comments.tsxindex 19a9662e79d..a9392ec0b83 100644--- a/frontend/src/metabase/comments/components/Comments/Comments.tsx+++ b/frontend/src/metabase/comments/components/Comments/Comments.tsx@@ -40,7 +40,7 @@ type SidesheetTab = "open" | "resolved";interface CommentsProps {commentTarget: CommentTarget;childTargetId: string;- onOpenComments?: () => void;+ useCommentUrl: (opts: { childTargetId: string | null }) => string;onCloseComments?: () => void;title?: string;showCloseButton?: boolean;@@ -53,7 +53,7 @@ interface CommentsProps {export const Comments = ({commentTarget,childTargetId,- onOpenComments,+ useCommentUrl,onCloseComments,title,showCloseButton = true,@@ -91,10 +91,6 @@ export const Comments = ({onCloseComments?.();}, [onCloseComments]);- useEffect(() => {- onOpenComments?.();- }, [onOpenComments]);-const resolvedComments = useMemo(() =>targetComments@@ -232,6 +228,7 @@ export const Comments = ({onHoverChange={onHoverChange}targetId={commentTarget.target_id}targetType={commentTarget.target_type}+ useCommentUrl={useCommentUrl}renderExtra={renderExtra}/>)}@@ -275,6 +272,7 @@ export const Comments = ({comments={resolvedComments}targetId={commentTarget.target_id}targetType={commentTarget.target_type}+ useCommentUrl={useCommentUrl}renderExtra={renderExtra}/></Tabs.Panel>diff --git a/frontend/src/metabase/comments/components/Discussion/Discussion.tsx b/frontend/src/metabase/comments/components/Discussion/Discussion.tsxindex c45a4255c6e..c234b95ee1a 100644--- a/frontend/src/metabase/comments/components/Discussion/Discussion.tsx+++ b/frontend/src/metabase/comments/components/Discussion/Discussion.tsx@@ -7,7 +7,6 @@ import {useToggleReactionMutation,useUpdateCommentMutation,} from "metabase/api";-import { useCommentUrl } from "metabase/comments/hooks/use-comment-url";import type { CommentExtraRenderer } from "metabase/comments/types";import { getCommentNodeId } from "metabase/comments/utils";import { useToast } from "metabase/common/hooks";@@ -31,6 +30,7 @@ export interface DiscussionProps {comments: Comment[];targetId: EntityId;targetType: CommentEntityType;+ useCommentUrl: (opts: { childTargetId: string | null }) => string;onHoverChange?: (childTargetId: string | undefined) => void;renderExtra?: CommentExtraRenderer;}@@ -40,6 +40,7 @@ export const Discussion = ({comments,targetId,targetType,+ useCommentUrl,onHoverChange,renderExtra,}: DiscussionProps) => {@@ -54,7 +55,9 @@ export const Discussion = ({const [deleteComment] = useDeleteCommentMutation();const [toggleReaction] = useToggleReactionMutation();- const commentsUrl = useCommentUrl({ childTargetId: effectiveChildTargetId });+ const commentsUrl = useCommentUrl({+ childTargetId: effectiveChildTargetId,+ });const handleSubmit = async (doc: DocumentContent) => {const { error } = await createComment({diff --git a/frontend/src/metabase/comments/components/Discussions/Discussions.tsx b/frontend/src/metabase/comments/components/Discussions/Discussions.tsxindex 3bccf006455..ec9250f3340 100644--- a/frontend/src/metabase/comments/components/Discussions/Discussions.tsx+++ b/frontend/src/metabase/comments/components/Discussions/Discussions.tsx@@ -7,11 +7,12 @@ import type { Comment } from "metabase-types/api/comments";import { Discussion } from "../Discussion";-export interface DiscussionProps {+export interface DiscussionsProps {childTargetId: Comment["child_target_id"];comments: Comment[];targetId: Comment["target_id"];targetType: Comment["target_type"];+ useCommentUrl: (opts: { childTargetId: string | null }) => string;onHoverChange?: (childTargetId: string | undefined) => void;renderExtra?: CommentExtraRenderer;}@@ -21,9 +22,10 @@ export const Discussions = ({comments,targetId,targetType,+ useCommentUrl,onHoverChange,renderExtra,-}: DiscussionProps) => {+}: DiscussionsProps) => {const threads = useMemo(() => getCommentThreads(comments, childTargetId),[comments, childTargetId],@@ -39,6 +41,7 @@ export const Discussions = ({comments={thread.comments}targetId={targetId}targetType={targetType}+ useCommentUrl={useCommentUrl}onHoverChange={onHoverChange}renderExtra={renderExtra}/>diff --git a/frontend/src/metabase/comments/hooks/use-comment-url.ts b/frontend/src/metabase/comments/hooks/use-comment-url.tsdeleted file mode 100644index 1a8ec212ca9..00000000000--- a/frontend/src/metabase/comments/hooks/use-comment-url.ts+++ /dev/null@@ -1,32 +0,0 @@-import { useMaybeLocation } from "metabase/router";-import { isExplorationUrl } from "metabase/urls";-import type { EntityId } from "metabase-types/api/comments";--interface UseCommentUrlOptions {- childTargetId?: EntityId | null;-}--export function useCommentUrl({ childTargetId }: UseCommentUrlOptions) {- const location = useMaybeLocation();- const pathname = location?.pathname;- const locationSearch = location?.search ?? "";- if (!pathname) {- return "";- }- if (isExplorationUrl(pathname)) {- const search = new URLSearchParams(locationSearch);- search.set("comments", "true");- const basePathname = pathname.replace(/\/page\/[^/]*$/, "");- const pinnedPathname =- childTargetId != null- ? `${basePathname}/page/${encodeURIComponent(String(childTargetId))}`- : pathname;- return `${pinnedPathname}?${search.toString()}`;- }- const existingCommentIndex = pathname.lastIndexOf("/comments");- const nextPathname =- existingCommentIndex !== -1- ? pathname.slice(0, existingCommentIndex)- : pathname;- return `${nextPathname}/comments${childTargetId ? `/${childTargetId}` : ""}${locationSearch}`;-}diff --git a/frontend/src/metabase/comments/hooks/use-comment-url.unit.spec.tsx b/frontend/src/metabase/comments/hooks/use-comment-url.unit.spec.tsxdeleted file mode 100644index e0f3b4947f9..00000000000--- a/frontend/src/metabase/comments/hooks/use-comment-url.unit.spec.tsx+++ /dev/null@@ -1,56 +0,0 @@-import { renderWithProviders, screen } from "__support__/ui";-import { Route } from "metabase/router";--import { useCommentUrl } from "./use-comment-url";--function Probe({ childTargetId }: { childTargetId: string }) {- const url = useCommentUrl({ childTargetId });- return <div data-testid="comment-url">{url}</div>;-}--function setup(initialRoute: string, childTargetId = "9") {- renderWithProviders(- <Route path="*" element={<Probe childTargetId={childTargetId} />} />,- { withRouter: true, initialRoute },- );- return screen.getByTestId("comment-url").textContent;-}--describe("useCommentUrl", () => {- it("returns an empty string when rendered outside a router (storybook / custom-viz fixtures)", () => {- renderWithProviders(<Probe childTargetId="9" />);- expect(screen.getByTestId("comment-url")).toHaveTextContent("");- });-- it("appends a /comments segment on routes with a comments child route", () => {- expect(setup("/document/1")).toBe("/document/1/comments/9");- });-- it("replaces an existing /comments segment instead of nesting", () => {- expect(setup("/document/1/comments/4")).toBe("/document/1/comments/9");- });-- it("uses the ?comments=true search param on exploration routes (no /comments child route exists)", () => {- expect(setup("/question/research/1/page/19?timeline=1", "19")).toBe(- "/question/research/1/page/19?timeline=1&comments=true",- );- });-- it("keeps a single comments param when the exploration sidebar is already open", () => {- expect(- setup("/question/research/1/page/19?comments=true&timeline=1", "19"),- ).toBe("/question/research/1/page/19?comments=true&timeline=1");- });-- it("pins the comment's page into a bare exploration URL, where the page is otherwise auto-selected", () => {- expect(setup("/question/research/1?timeline=1", "19")).toBe(- "/question/research/1/page/19?timeline=1&comments=true",- );- });-- it("repins the path to the comment's own page when a different page is in the URL", () => {- expect(setup("/question/research/1/page/4", "19")).toBe(- "/question/research/1/page/19?comments=true",- );- });-});diff --git a/frontend/src/metabase/common/components/SidebarHeader/SidebarHeader.tsx b/frontend/src/metabase/common/components/SidebarHeader/SidebarHeader.tsxindex 9a5bf721ad9..c748c5c998d 100644--- a/frontend/src/metabase/common/components/SidebarHeader/SidebarHeader.tsx+++ b/frontend/src/metabase/common/components/SidebarHeader/SidebarHeader.tsx@@ -88,8 +88,12 @@ export function SidebarHeader({<Flex align="center" gap="sm">{actions}{onClose && (- <a className={SidebarHeaderS.CloseButton} onClick={onClose}>- <Icon name="close" size={18} />+ <a+ className={SidebarHeaderS.CloseButton}+ aria-label={t`Close`}+ onClick={onClose}+ >+ <Icon name="close" size={18} aria-hidden /></a>)}</Flex>diff --git a/frontend/src/metabase/documents/analytics.ts b/frontend/src/metabase/documents/analytics.tsindex 6329940ccf5..9a1c5a3685f 100644--- a/frontend/src/metabase/documents/analytics.ts+++ b/frontend/src/metabase/documents/analytics.ts@@ -1,6 +1,8 @@import { trackSimpleEvent } from "metabase/analytics";import type { Document } from "metabase-types/api";+export type DocumentTriggerSource = "standalone" | "exploration";+export const trackDocumentCreated = (document: Document) => {trackSimpleEvent({event: "document_created",@@ -8,10 +10,14 @@ export const trackDocumentCreated = (document: Document) => {});};-export const trackDocumentUpdated = (document: Document) => {+export const trackDocumentUpdated = (+ document: Pick<Document, "id">,+ triggeredFrom: DocumentTriggerSource,+) => {trackSimpleEvent({event: "document_saved",target_id: document.id,+ triggered_from: triggeredFrom,});};diff --git a/frontend/src/metabase/documents/components/CommentsSidesheet/CommentsSidesheet.tsx b/frontend/src/metabase/documents/components/CommentsSidesheet/CommentsSidesheet.tsxindex 3d976f75254..d6f2644a953 100644--- a/frontend/src/metabase/documents/components/CommentsSidesheet/CommentsSidesheet.tsx+++ b/frontend/src/metabase/documents/components/CommentsSidesheet/CommentsSidesheet.tsx@@ -4,7 +4,7 @@ import { t } from "ttag";import { Comments } from "metabase/comments/components/Comments";import Animation from "metabase/css/core/animation.module.css";import { setHoveredChildTargetId } from "metabase/documents/documents.slice";-import { useDocumentState } from "metabase/documents/hooks/use-document-state";+import { useDocumentCommentUrl } from "metabase/documents/hooks/use-document-comment-url";import { getCurrentDocument } from "metabase/documents/selectors";import { useDispatch, useSelector } from "metabase/redux";import { Box } from "metabase/ui";@@ -18,15 +18,9 @@ interface Props {export const CommentsSidesheet = ({ params, onClose }: Props) => {const childTargetId = params?.childTargetId;- const { openCommentSidebar, closeCommentSidebar } = useDocumentState();const document = useSelector(getCurrentDocument);const dispatch = useDispatch();- const closeSidebar = useCallback(() => {- closeCommentSidebar();- onClose();- }, [closeCommentSidebar, onClose]);-const handleHoverChange = useCallback((hoveredChildTargetId: string | undefined) => {dispatch(setHoveredChildTargetId(hoveredChildTargetId));@@ -56,8 +50,8 @@ export const CommentsSidesheet = ({ params, onClose }: Props) => {target_type: "document",}}childTargetId={childTargetId}- onOpenComments={openCommentSidebar}- onCloseComments={closeSidebar}+ useCommentUrl={useDocumentCommentUrl}+ onCloseComments={onClose}title={childTargetId === "all" ? t`All comments` : t`Comments about this`}diff --git a/frontend/src/metabase/documents/components/DocumentPage.tsx b/frontend/src/metabase/documents/components/DocumentPage.tsxindex e1a89d9b430..41883d78404 100644--- a/frontend/src/metabase/documents/components/DocumentPage.tsx+++ b/frontend/src/metabase/documents/components/DocumentPage.tsx@@ -1,40 +1,28 @@import { useForceUpdate } from "@mantine/hooks";-import type { JSONContent, Editor as TiptapEditor } from "@tiptap/core";-import type { Node as ProseMirrorNode } from "@tiptap/pm/model";import {type ReactNode,useCallback,useEffect,useMemo,- useRef,useState,} from "react";-import { usePrevious, useUnmount } from "react-use";-import useBeforeUnload from "react-use/lib/useBeforeUnload";+import { usePrevious } from "react-use";import { t } from "ttag";-import _ from "underscore";import {- skipToken,useCopyDocumentMutation,useCreateBookmarkMutation,- useCreateDocumentMutation,useDeleteBookmarkMutation,- useGetDocumentQuery,useListBookmarksQuery,- useUpdateDocumentMutation,} from "metabase/api";import { canonicalCollectionId } from "metabase/common/collections/utils";import { ConfirmModal } from "metabase/common/components/ConfirmModal";import { CopyModal } from "metabase/common/components/CopyModal";-import { getFormattedTime } from "metabase/common/components/DateTime";import {LeaveConfirmModal,LeaveRouteConfirmModal,} from "metabase/common/components/LeaveConfirmModal";import { CollectionPickerModal } from "metabase/common/components/Pickers/CollectionPicker";-import { useToast } from "metabase/common/hooks";-import { useCallbackEffect } from "metabase/common/hooks/use-callback-effect";import { usePageTitle } from "metabase/hooks/use-page-title";import { useDispatch, useSelector } from "metabase/redux";import { setErrorPage } from "metabase/redux/app";@@ -42,11 +30,6 @@ import { Outlet, useLocation, useNavigate, useParams } from "metabase/router";import { Box } from "metabase/ui";import { extractEntityId } from "metabase/urls";import * as Urls from "metabase/urls";-import type {- Card,- CollectionId,- RegularCollectionId,-} from "metabase-types/api";import {trackDocumentBookmark,@@ -62,24 +45,19 @@ import {import { PrintContext } from "../contexts/PrintContext";import { ScrollContainerProvider } from "../contexts/ScrollContainerContext";import {- clearDraftCards,- openVizSettingsSidebar,+ closeSidebar,+ openHistorySidebar,resetDocuments,setChildTargetId,- setCurrentDocument,setHasUnsavedChanges,- setIsHistorySidebarOpen,} from "../documents.slice";-import { useDocumentState } from "../hooks/use-document-state";+import { useDocumentEditor } from "../hooks/use-document-editor";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 { useSyncCommentsSidebar } from "../hooks/use-sync-comments-sidebar";import {- getDraftCards,- getHasUnsavedChanges,- getIsHistorySidebarOpen,getSelectedEmbedIndex,getSelectedQuestionId,+ getSidebarMode,} from "../selectors";import { DocumentArchivedEntityBanner } from "./DocumentArchivedEntityBanner";@@ -88,6 +66,7 @@ import styles from "./DocumentPage.module.css";import { DocumentRevisionHistorySidebar } from "./DocumentRevisionHistorySidebar";import { Editor } from "./Editor";import { EmbedQuestionSettingsSidebar } from "./EmbedQuestionSettingsSidebar";+import { EmbedTimelineSidebar } from "./EmbedTimelineSidebar";// 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.@@ -125,32 +104,48 @@ export const DocumentPage = () => {const selectedQuestionId = useSelector(getSelectedQuestionId);const selectedEmbedIndex = useSelector(getSelectedEmbedIndex);- const draftCards = useSelector(getDraftCards);- const isHistorySidebarOpen = useSelector(getIsHistorySidebarOpen);- const [editorInstance, setEditorInstance] = useState<TiptapEditor | null>(- null,- );- const editorContainerRef = useRef<HTMLDivElement>(null);+ const sidebarMode = useSelector(getSidebarMode);const [mainContentEl, setMainContentEl] = useState<HTMLDivElement | null>(null,);- const hasUnsavedEditorChanges = useSelector(getHasUnsavedChanges);- const [createDocument, { isLoading: isCreating }] =- useCreateDocumentMutation();- const [updateDocument, { isLoading: isUpdating }] =- useUpdateDocumentMutation();const [copyDocument] = useCopyDocumentMutation();- const [collectionPickerMode, setCollectionPickerMode] = useState<- "save" | "move" | null- >(null);const [duplicateModalMode, setDuplicateModalMode] = useState<"duplicate" | "leave" | null>(null);- const [sendToast] = useToast();const documentId = entityId === "new" ? "new" : extractEntityId(entityId);- const [isNavigationScheduled, scheduleNavigation] = useCallbackEffect();- const isNewDocument = documentId === "new";++ const {+ editorInstance,+ setEditorInstance,+ collectionPickerMode,+ setCollectionPickerMode,+ editorContainerRef,+ isNavigationScheduled,+ scheduleNavigation,+ isNewDocument,+ isSaving,+ documentData,+ isDocumentLoading,+ error,+ canWrite,+ documentTitle,+ setDocumentTitle,+ documentContent,+ setDocumentContent,+ updateCardEmbeds,+ hasUnsavedChanges,+ showSaveButton,+ handleChange,+ handleSave,+ handleUpdate,+ handleQuestionSelect,+ } = useDocumentEditor({+ documentId,+ onDocumentCreated: trackDocumentCreated,+ onDocumentUpdated: (document) =>+ trackDocumentUpdated(document, "standalone"),+ });const { data: bookmarks = [] } = useListBookmarksQuery(undefined, {skip: isNewDocument,@@ -164,45 +159,12 @@ export const DocumentPage = () => {),);- let {- data: documentData,- isLoading: isDocumentLoading,- error,- } = useGetDocumentQuery(- documentId && !isNewDocument ? { id: documentId } : skipToken,- );- if (documentId !== documentData?.id) {- documentData = undefined;- }-- const canWrite =- !documentData?.archived && (isNewDocument || documentData?.can_write);-useEffect(() => {if (error) {dispatch(setErrorPage(error));}}, [dispatch, error]);- const {- documentTitle,- setDocumentTitle,- documentContent,- setDocumentContent,- updateCardEmbeds,- } = useDocumentState(documentData);-- // This is important as it will affect collection breadcrumbs in the appbar- useUnmount(() => {- dispatch(resetDocuments());- });-- useRegisterDocumentMetabotContext();- useBeforeUnload(() => {- // warn if you try to navigate away with unsaved changes- return hasUnsavedChanges();- });-// Reset state when we navigate back to /newconst resetDocument = useCallback(() => {setDocumentTitle("");@@ -213,86 +175,18 @@ export const DocumentPage = () => {dispatch(resetDocuments());}, [dispatch, editorInstance, setDocumentContent, setDocumentTitle]);- // Reset dirty state when document content loads from API- useEffect(() => {- if (documentContent && !isNewDocument) {- dispatch(setHasUnsavedChanges(false));- }- }, [dispatch, documentContent, isNewDocument]);-- useEffect(() => {- // Set current document when document loads (includes collection_id and all other data)- if (documentData && !isNewDocument) {- dispatch(setCurrentDocument(documentData));- } else if (isNewDocument) {- dispatch(setCurrentDocument(null));- }- }, [documentData, documentId, dispatch, isNewDocument]);-useEffect(() => {dispatch(setChildTargetId(paramsChildTargetId));}, [dispatch, paramsChildTargetId]);- // Scroll to anchor block when navigating with URL hash- const blockId = location.hash ? location.hash.slice(1) : null;- useScrollToAnchor({- blockId,- editorContainerRef,- isLoading: isDocumentLoading,- });-- const hasUnsavedChanges = useCallback(() => {- const currentTitle = documentTitle.trim();- const originalTitle = documentData?.name || "";- // We call .trim() on documentTitle to ensure that no one can push the save button- // with a document name that is all whitespace, the API will reject it. However,- // when comparing saved with current titles, we need to use unmofidied values- const titleChanged = documentTitle !== originalTitle;-- // Check if there are any draft cards- const hasDraftCards = Object.keys(draftCards).length > 0;-- // For new documents, show Save if there's title or editor changes or draft cards- if (isNewDocument) {- return (- currentTitle.length > 0 || hasUnsavedEditorChanges || hasDraftCards- );- }+ const handleCloseComments = useCallback(() => {+ navigate(".", { relative: "route" }); // remove the "/comments" path+ }, [navigate]);- // For existing documents, use simple change tracking- return titleChanged || hasUnsavedEditorChanges || hasDraftCards;- }, [- documentTitle,- isNewDocument,- documentData,- hasUnsavedEditorChanges,- draftCards,- ]);-- const isSaving = isCreating || isUpdating;- const showSaveButton = hasUnsavedChanges() && canWrite && !isSaving;-- const handleChange = useCallback(- (content: JSONContent) => {- // For new documents, any content means changes- if (isNewDocument) {- // when navigating to `/new`, handleChange is fired but the editor instance hasn't been set yet- dispatch(- setHasUnsavedChanges(!!editorInstance && !editorInstance.isEmpty),- );- return;- }-- // Compare current content with original content- const currentContent = content;- const originalContent = documentContent;-- // For existing documents, compare with original content- const hasChanges = !_.isEqual(currentContent, originalContent);- dispatch(setHasUnsavedChanges(hasChanges));- },- [dispatch, editorInstance, documentContent, isNewDocument],- );+ useSyncCommentsSidebar({+ areCommentsOpen: paramsChildTargetId != null,+ onCloseComments: handleCloseComments,+ });const handleDuplicate = useCallback(() => {if (hasUnsavedChanges()) {@@ -319,166 +213,13 @@ export const DocumentPage = () => {}, [isBookmarked, deleteBookmark, createBookmark, documentId]);const handleShowHistory = useCallback(() => {- dispatch(setIsHistorySidebarOpen(true));+ dispatch(openHistorySidebar());}, [dispatch]);- const handleSave = useCallback(- async (collectionId: RegularCollectionId | null = null) => {- if (!editorInstance || isSaving) {- return;- }-- try {- const cardsToSave: Record<number, Card> = {};- const processedCardIds = new Set<number>();-- editorInstance.state.doc.descendants((node: ProseMirrorNode) => {- if (node.type.name === "cardEmbed") {- const cardId = node.attrs.id;- if (!processedCardIds.has(cardId)) {- processedCardIds.add(cardId);-- if (cardId < 0 && draftCards[cardId]) {- cardsToSave[cardId] = draftCards[cardId];- }- }- }- });-- const documentAst = editorInstance.getJSON();- const name =- documentTitle ||- t`Untitled document - ${getFormattedTime(new Date(), "day", { local: true })}`;-- const newDocumentData = {- name,- document: documentAst,- cards: Object.keys(cardsToSave).length > 0 ? cardsToSave : undefined,- };-- const result = await (documentData?.id- ? updateDocument({ ...newDocumentData, id: documentData.id }).then(- (response) => {- if (response.data) {- const _document = response.data;- trackDocumentUpdated(_document);- scheduleNavigation(() => {- navigate(Urls.document(_document));- });- }- return response;- },- )- : createDocument({- ...newDocumentData,- collection_id: collectionId || undefined,- }).then((response) => {- if (response.data) {- const _document = response.data;- trackDocumentCreated(_document);- scheduleNavigation(() => {- navigate(Urls.document(_document), { replace: true });- });- }- return response;- }));-- if (result.data) {- sendToast({- message: documentData?.id ? t`Document saved` : t`Document created`,- });- dispatch(clearDraftCards());- // Mark document as clean- dispatch(setHasUnsavedChanges(false));- return {- document: result.data,- };- } else if (result.error) {- throw result.error;- }- } catch (error) {- console.error("Failed to save document:", error);- sendToast({ message: t`Error saving document`, icon: "warning" });- return {- error: error,- };- }- },- [- editorInstance,- isSaving,- documentTitle,- draftCards,- documentData?.id,- updateDocument,- createDocument,- scheduleNavigation,- dispatch,- sendToast,- navigate,- ],- );-const focusEditorBody = useCallback(() => {editorInstance?.commands.focus("start");}, [editorInstance]);- const handleUpdate = async (payload: {- collection_id?: CollectionId | null;- archived?: boolean;- }) => {- if (documentData?.id) {- await updateDocument({ id: documentData.id, ...payload });- setCollectionPickerMode(null);- }- };-- useEffect(() => {- const handleKeyDown = (event: KeyboardEvent) => {- // Save shortcut: Cmd+S (Mac) or Ctrl+S (Windows/Linux)- if ((event.metaKey || event.ctrlKey) && event.key === "s") {- event.preventDefault();- if (!hasUnsavedChanges() || !canWrite) {- return;- }-- if (isNewDocument) {- setCollectionPickerMode("save");- } else {- handleSave();- }- }- };-- document.addEventListener("keydown", handleKeyDown);-- return () => {- document.removeEventListener("keydown", handleKeyDown);- };- }, [- hasUnsavedChanges,- handleSave,- isNewDocument,- setCollectionPickerMode,- canWrite,- ]);-- const handleQuestionSelect = useCallback(- (cardId: number | null, embedIndex?: number | null) => {- if (- cardId !== null &&- embedIndex !== null &&- embedIndex !== undefined &&- embedIndex >= 0 &&- selectedEmbedIndex !== null- ) {- // Only update the selected embed index if the sidebar is already open- dispatch(openVizSettingsSidebar({ embedIndex }));- }- },- [dispatch, selectedEmbedIndex],- );-usePageTitle(documentData?.name || t`New document`, { titleIndex: 1 });// A "New document" click from `/document/new` targets the URL we are already@@ -543,7 +284,8 @@ export const DocumentPage = () => {</ScrollContainerProvider></Box>- {selectedQuestionId &&+ {sidebarMode === "viz-settings" &&+ selectedQuestionId &&selectedEmbedIndex !== null &&editorInstance && (<Box@@ -557,6 +299,23 @@ export const DocumentPage = () => {</Box>)}+ {sidebarMode === "timeline-events" &&+ selectedQuestionId &&+ selectedEmbedIndex !== null &&+ editorInstance && (+ <Box+ className={styles.sidebar}+ data-testid="document-timeline-sidebar"+ >+ <EmbedTimelineSidebar+ cardId={selectedQuestionId}+ selectedEmbedIndex={selectedEmbedIndex}+ editorInstance={editorInstance}+ collectionId={documentData?.collection_id ?? null}+ />+ </Box>+ )}+{collectionPickerMode && (<CollectionPickerModaltitle={t`Where should we save this document?`}@@ -618,7 +377,7 @@ export const DocumentPage = () => {/>)}- <Outlet />+ {sidebarMode === "comments" && <Outlet />}<LeaveRouteConfirmModal// `key` remounts this modal when navigating between different documents or to a new document.@@ -656,14 +415,14 @@ export const DocumentPage = () => {onClose={() => setDuplicateModalMode(null)}/></Box>- {isHistorySidebarOpen && documentData && (+ {sidebarMode === "history" && documentData && (<BoxclassName={styles.sidebar}data-testid="document-history-sidebar"><DocumentRevisionHistorySidebardocument={documentData}- onClose={() => dispatch(setIsHistorySidebarOpen(false))}+ onClose={() => dispatch(closeSidebar())}/></Box>)}diff --git a/frontend/src/metabase/documents/components/DocumentPage.unit.spec.tsx b/frontend/src/metabase/documents/components/DocumentPage.unit.spec.tsxindex 18231e09d26..5c29b350608 100644--- a/frontend/src/metabase/documents/components/DocumentPage.unit.spec.tsx+++ b/frontend/src/metabase/documents/components/DocumentPage.unit.spec.tsx@@ -4,6 +4,7 @@ import {setupBookmarksEndpoints,setupCommentEndpoints,setupDocumentEndpoints,+ setupTimelinesEndpoints,} from "__support__/server-mocks";import { act, renderWithProviders, screen, waitFor } from "__support__/ui";import { Route } from "metabase/router";@@ -21,6 +22,7 @@ const setup = () => {}),);setupCommentEndpoints([], { target_type: "document", target_id: 1 });+ setupTimelinesEndpoints([]);renderWithProviders(<>@@ -35,6 +37,7 @@ const setup = () => {const setupNewDocument = () => {setupBookmarksEndpoints([]);+ setupTimelinesEndpoints([]);return renderWithProviders(<Route path="/document/:entityId" element={<DocumentPage />} />,diff --git a/frontend/src/metabase/documents/components/Editor/CommentsMenu/CommentsMenu.tsx b/frontend/src/metabase/documents/components/Editor/CommentsMenu/CommentsMenu.tsxindex 28cca928608..492d8ca8fd1 100644--- a/frontend/src/metabase/documents/components/Editor/CommentsMenu/CommentsMenu.tsx+++ b/frontend/src/metabase/documents/components/Editor/CommentsMenu/CommentsMenu.tsx@@ -2,17 +2,16 @@ import cx from "classnames";import { type CSSProperties, forwardRef } from "react";import { createPortal } from "react-dom";-import { useCommentUrl } from "metabase/comments/hooks/use-comment-url";import { ForwardRefLink } from "metabase/common/components/Link";+import { useEditorHost } from "metabase/rich_text_editing/tiptap/EditorHost";import { CommentsButton } from "metabase/rich_text_editing/tiptap/components/CommentsButton";import { Box, rem } from "metabase/ui";-import type { EntityId } from "metabase-types/api/comments";import S from "./CommentsMenu.module.css";interface Props {active: boolean;- childTargetId: EntityId;+ childTargetId: string;show: boolean;style: CSSProperties;unresolvedCommentsCount: number;@@ -23,8 +22,9 @@ export const CommentsMenu = forwardRef<HTMLDivElement, Props>({ active, childTargetId, show, style, unresolvedCommentsCount }: Props,ref,) {+ const host = useEditorHost();const hasUnresolvedComments = unresolvedCommentsCount > 0;- const commentUrl = useCommentUrl({+ const commentUrl = host.useCommentUrl({childTargetId,});diff --git a/frontend/src/metabase/documents/components/Editor/CommentsMenu/CommentsMenu.unit.spec.tsx b/frontend/src/metabase/documents/components/Editor/CommentsMenu/CommentsMenu.unit.spec.tsxindex 4cd3c3b2f06..425449b0fca 100644--- a/frontend/src/metabase/documents/components/Editor/CommentsMenu/CommentsMenu.unit.spec.tsx+++ b/frontend/src/metabase/documents/components/Editor/CommentsMenu/CommentsMenu.unit.spec.tsx@@ -1,4 +1,5 @@import { renderWithProviders, screen } from "__support__/ui";+import { DocumentEditorHostProvider } from "metabase/documents/components/Editor/DocumentEditorHost";import { Route } from "metabase/router";import { CommentsMenu } from "./CommentsMenu";@@ -10,13 +11,15 @@ function setup(initialRoute: string) {<Routepath="*"element={- <CommentsMenu- active={false}- childTargetId="block-123"- show- style={defaultStyle}- unresolvedCommentsCount={0}- />+ <DocumentEditorHostProvider>+ <CommentsMenu+ active={false}+ childTargetId="block-123"+ show+ style={defaultStyle}+ unresolvedCommentsCount={0}+ />+ </DocumentEditorHostProvider>}/>,{ withRouter: true, initialRoute },diff --git a/frontend/src/metabase/documents/components/Editor/DocumentEditorHost.tsx b/frontend/src/metabase/documents/components/Editor/DocumentEditorHost.tsxindex d4517dcb691..019d4f157ab 100644--- a/frontend/src/metabase/documents/components/Editor/DocumentEditorHost.tsx+++ b/frontend/src/metabase/documents/components/Editor/DocumentEditorHost.tsx@@ -1,10 +1,18 @@-import type { ReactNode } from "react";+import { type ReactNode, useMemo } from "react";-import { useCommentUrl } from "metabase/comments/hooks/use-comment-url";import {+ DEFAULT_EDITOR_CAPABILITIES,+ EMPTY_CARD_EMBED_SLOTS,type EditorHost,EditorHostProvider,+ useEditorHost,} from "metabase/rich_text_editing/tiptap/EditorHost";+import type {+ ClickActionsMode,+ HighlightedObject,+ QueryClickActionsMode,+} from "metabase/visualizations/types";+import type { Series } from "metabase-types/api";import { navigateToCardFromDocument } from "../../actions";import {@@ -16,13 +24,17 @@ import {} from "../../analytics";import {createDraftCard,+ deselectTimelineEvents,generateDraftCardId,loadMetadataForDocumentCard,+ openTimelineEventsSidebar,openVizSettingsSidebar,+ selectTimelineEvents,updateMentionsCache,updateVizSettings,} from "../../documents.slice";import { useCardData } from "../../hooks/use-card-data";+import { useDocumentCommentUrl } from "../../hooks/use-document-comment-url";import { useDraftCardOperations } from "../../hooks/use-draft-card-operations";import { useExternalCardDataLoader } from "../../hooks/use-external-card-data";import {@@ -35,25 +47,52 @@ import {getCurrentDocument,getHasUnsavedChanges,getHoveredChildTargetId,+ getSelectedEmbedIndex,+ getSelectedTimelineEventIds,} from "../../selectors";+import { DocumentMode } from "./DocumentMode";++/**+ * {@link EditorHost} plus the visualization contracts CardEmbed needs.+ * Lives in `documents` so `rich_text_editing` does not import visualizations.+ */+export type DocumentEditorHost = EditorHost & {+ useHighlighted: (+ childTargetId: string,+ series: Series | null,+ hostData?: Record<string, unknown> | null,+ ) => HighlightedObject | null;+ useVisualizationMode: (opts: {+ childTargetId: string;+ hostData?: Record<string, unknown> | null;+ }) => ClickActionsMode | QueryClickActionsMode | undefined;+};+/**- * Concrete {@link EditorHost} that wires the document editor's state, actions,- * analytics and data hooks into the document-agnostic `rich_text_editing`- * extensions. Defined at module scope so its identity is stable.+ * Concrete {@link DocumentEditorHost} that wires the document editor's state,+ * actions, analytics and data hooks into the document-agnostic+ * `rich_text_editing` extensions. Defined at module scope so its identity is+ * stable.*/-export const documentEditorHost: EditorHost = {+export const documentEditorHost: DocumentEditorHost = {+ capabilities: DEFAULT_EDITOR_CAPABILITIES,selectors: {getCurrentDocument,getChildTargetId,getHoveredChildTargetId,getHasUnsavedChanges,+ getSelectedEmbedIndex,+ getSelectedTimelineEventIds,},actions: {createDraftCard,generateDraftCardId,loadMetadataForDocumentCard,openVizSettingsSidebar,+ openTimelineEventsSidebar,+ selectTimelineEvents,+ deselectTimelineEvents,updateVizSettings,updateMentionsCache,},@@ -67,17 +106,31 @@ export const documentEditorHost: EditorHost = {navigateToCard: navigateToCardFromDocument,useCardData,useExternalCardDataLoader,- useCommentUrl,+ useCommentUrl: useDocumentCommentUrl,useUnresolvedCommentsCount: useUnresolvedDocumentCommentsCount,+ useHighlighted: () => null,+ useVisualizationMode: () => DocumentMode,+ useCardEmbedSlots: () => EMPTY_CARD_EMBED_SLOTS,useNodeInViewport,useReportPrefetchLoading,useDraftCardOperations,};+export const useDocumentEditorHost = (): DocumentEditorHost => {+ // CardEmbed only mounts under DocumentEditorHostProvider+ return useEditorHost() as DocumentEditorHost;+};+export const DocumentEditorHostProvider = ({+ hostOverride,children,}: {+ hostOverride?: Partial<DocumentEditorHost>;children: ReactNode;-}) => (- <EditorHostProvider value={documentEditorHost}>{children}</EditorHostProvider>-);+}) => {+ const host = useMemo(+ () => ({ ...documentEditorHost, ...hostOverride }),+ [hostOverride],+ );+ return <EditorHostProvider value={host}>{children}</EditorHostProvider>;+};diff --git a/frontend/src/metabase/documents/components/editor-extensions/CardEmbed/DocumentMode.ts b/frontend/src/metabase/documents/components/Editor/DocumentMode.tssimilarity index 100%rename from frontend/src/metabase/documents/components/editor-extensions/CardEmbed/DocumentMode.tsrename to frontend/src/metabase/documents/components/Editor/DocumentMode.tsdiff --git a/frontend/src/metabase/documents/components/Editor/Editor.tsx b/frontend/src/metabase/documents/components/Editor/Editor.tsxindex cf14834cda9..499638d0897 100644--- a/frontend/src/metabase/documents/components/Editor/Editor.tsx+++ b/frontend/src/metabase/documents/components/Editor/Editor.tsx@@ -42,7 +42,10 @@ import { CardEmbed } from "../editor-extensions/CardEmbed/CardEmbedNode";import { DocumentBlockShell } from "./DocumentBlockShell";import { DocumentCommandSuggestion } from "./DocumentCommandSuggestion";-import { DocumentEditorHostProvider } from "./DocumentEditorHost";+import {+ type DocumentEditorHost,+ DocumentEditorHostProvider,+} from "./DocumentEditorHost";import DropCursorS from "./DropCursor.module.css";import S from "./Editor.module.css";import { createChartPasteExtension } from "./chart-paste-extension";@@ -90,11 +93,16 @@ export interface EditorProps {onCardEmbedsChange?: (refs: CardEmbedRef[]) => void;initialContent?: JSONContent | null;onChange?: (content: JSONContent) => void;- onQuestionSelect?: (cardId: number | null) => void;+ onQuestionSelect?: (+ cardId: number | null,+ embedIndex?: number | null,+ ) => void;editable?: boolean;isLoading?: boolean;/** Ref to the editor container for external access (e.g., anchor scrolling) */editorContainerRef?: React.RefObject<HTMLDivElement>;+ hostOverride?: Partial<DocumentEditorHost>;+ placeholder?: string;}export const Editor: React.FC<EditorProps> = React.memo(@@ -107,6 +115,8 @@ export const Editor: React.FC<EditorProps> = React.memo(onQuestionSelect,isLoading = false,editorContainerRef,+ hostOverride,+ placeholder,}) => {const siteUrl = useSelector((state) => getSetting(state, "site-url"));const { getState } = useStore();@@ -138,7 +148,9 @@ export const Editor: React.FC<EditorProps> = React.memo(defaultProtocol: "https",}),Placeholder.configure({- placeholder: t`Start writing, type "/" to list commands, or "@" to mention an item...`,+ placeholder:+ placeholder ??+ t`Start writing, type "/" to list commands, or "@" to mention an item...`,}),CardEmbed,FlexContainer,@@ -169,7 +181,7 @@ export const Editor: React.FC<EditorProps> = React.memo(HandleEditorDrop,createChartPasteExtension(dispatch),],- [siteUrl, getState, dispatch],+ [siteUrl, getState, dispatch, placeholder],);const editor = useEditor(@@ -237,7 +249,7 @@ export const Editor: React.FC<EditorProps> = React.memo(}return (- <DocumentEditorHostProvider>+ <DocumentEditorHostProvider hostOverride={hostOverride}><Box className={cx(S.editor, DND_IGNORE_CLASS_NAME)}><BoxclassName={S.editorContent}diff --git a/frontend/src/metabase/documents/components/Editor/hooks/useCardEmbedsTracking.ts b/frontend/src/metabase/documents/components/Editor/hooks/useCardEmbedsTracking.tsindex ae3b45614c5..bf78c2581a1 100644--- a/frontend/src/metabase/documents/components/Editor/hooks/useCardEmbedsTracking.ts+++ b/frontend/src/metabase/documents/components/Editor/hooks/useCardEmbedsTracking.ts@@ -21,6 +21,8 @@ const extractCardEmbeds = (editor: TiptapEditor): CardEmbedRef[] => {refs.push({id: node.attrs.id,name: node.attrs.name,+ stored_result_id: node.attrs.stored_result_id,+ sort: node.attrs.sort,});}});diff --git a/frontend/src/metabase/documents/components/EmbedQuestionSettingsSidebar.tsx b/frontend/src/metabase/documents/components/EmbedQuestionSettingsSidebar.tsxindex 1472844de24..89e24ea02f9 100644--- a/frontend/src/metabase/documents/components/EmbedQuestionSettingsSidebar.tsx+++ b/frontend/src/metabase/documents/components/EmbedQuestionSettingsSidebar.tsx@@ -28,7 +28,7 @@ import {} from "../documents.slice";import { useCardData } from "../hooks/use-card-data";import { useDraftCardOperations } from "../hooks/use-draft-card-operations";-import { getSelectedEmbedIndex } from "../selectors";+import { getSelectedCardEmbed, getSelectedEmbedIndex } from "../selectors";import { useVisualizationOptions } from "../utils/visualizationUtils";import S from "./EmbedQuestionSettingsSidebar.module.css";@@ -44,6 +44,7 @@ export const EmbedQuestionSettingsSidebar = ({}: EmbedQuestionSettingsSidebarProps) => {const dispatch = useDispatch();const selectedEmbedIndex = useSelector(getSelectedEmbedIndex);+ const selectedCardEmbed = useSelector(getSelectedCardEmbed);const {card,@@ -53,7 +54,11 @@ export const EmbedQuestionSettingsSidebar = ({question,draftCard,regularDataset,- } = useCardData({ id: cardId });+ } = useCardData({+ id: cardId,+ storedResultId: selectedCardEmbed?.stored_result_id ?? undefined,+ storedResultSort: selectedCardEmbed?.sort ?? undefined,+ });const { sensibleItems, nonsensibleItems, selectedElem } =useVisualizationOptions(dataset, card?.display);diff --git a/frontend/src/metabase/documents/components/EmbedTimelineSidebar.module.css b/frontend/src/metabase/documents/components/EmbedTimelineSidebar.module.cssnew file mode 100644index 00000000000..ad5ff8331be--- /dev/null+++ b/frontend/src/metabase/documents/components/EmbedTimelineSidebar.module.css@@ -0,0 +1,31 @@+.container {+ height: 100%;+ display: flex;+ align-items: stretch;+ flex-direction: column;+ background-color: var(--mb-color-background-primary);+}++.loadingContainer {+ height: 100%;+}++.loadingContent {+ display: flex;+ align-items: center;+ justify-content: center;+ flex: 1;+ flex-direction: column;+ gap: var(--mantine-spacing-md);+}++.errorContainer {+ height: 100%;+}++.errorContent {+ display: flex;+ align-items: center;+ justify-content: center;+ flex: 1;+}diff --git a/frontend/src/metabase/documents/components/EmbedTimelineSidebar.tsx b/frontend/src/metabase/documents/components/EmbedTimelineSidebar.tsxnew file mode 100644index 00000000000..1d13745da95--- /dev/null+++ b/frontend/src/metabase/documents/components/EmbedTimelineSidebar.tsx@@ -0,0 +1,186 @@+import type { Editor } from "@tiptap/react";+import { useCallback, useMemo } from "react";+import { t } from "ttag";++import { useListTimelinesQuery } from "metabase/api";+import { useDispatch, useSelector } from "metabase/redux";+import { TimelineSidebar } from "metabase/timelines/questions/components/TimelineSidebar";+import { Box, Loader, Stack, Text } from "metabase/ui";+import { getTimelineEventSettings } from "metabase/visualizations/lib/settings/timelineEvents";+import type {+ CollectionId,+ TimelineEvent,+ TimelineEventId,+} from "metabase-types/api";++import {+ clearFocusedTimelineEvents,+ closeSidebar,+ deselectTimelineEvents,+ selectTimelineEvents,+ updateVizSettings,+} from "../documents.slice";+import { useCardData } from "../hooks/use-card-data";+import { useDraftCardOperations } from "../hooks/use-draft-card-operations";+import {+ getFocusedTimelineEventIds,+ getSelectedTimelineEventIds,+} from "../selectors";++import S from "./EmbedTimelineSidebar.module.css";++interface EmbedTimelineSidebarProps {+ cardId: number;+ selectedEmbedIndex: number;+ editorInstance?: Editor;+ collectionId: CollectionId | null;+}++export function EmbedTimelineSidebar({+ cardId,+ selectedEmbedIndex,+ editorInstance,+ collectionId,+}: EmbedTimelineSidebarProps) {+ const dispatch = useDispatch();+ const selectedTimelineEventIds = useSelector(getSelectedTimelineEventIds);+ const focusedTimelineEventIds = useSelector(getFocusedTimelineEventIds);++ const {+ data: timelineData = [],+ isLoading,+ isError,+ } = useListTimelinesQuery({+ include: "events",+ });++ const timelines = useMemo(+ () => timelineData.filter((timeline) => (timeline.events?.length ?? 0) > 0),+ [timelineData],+ );++ const { card, draftCard, regularDataset } = useCardData({+ id: cardId,+ });++ const { ensureDraftCard } = useDraftCardOperations(+ draftCard,+ card,+ cardId,+ editorInstance,+ selectedEmbedIndex,+ regularDataset,+ );++ const visibleTimelineEventIds = useMemo(() => {+ const selectedTimelineIds = new Set(+ card?.visualization_settings["timeline.selected_timeline_ids"] ?? [],+ );+ const excludedTimelineEventIds = new Set(+ card?.visualization_settings["timeline.excluded_timeline_event_ids"] ??+ [],+ );++ return timelines.flatMap((timeline) => {+ if (!selectedTimelineIds.has(timeline.id)) {+ return [];+ }+ return (timeline.events ?? [])+ .filter((event) => !excludedTimelineEventIds.has(event.id))+ .map((event) => event.id);+ });+ }, [card, timelines]);++ const updateTimelineVizSettings = useCallback(+ (newTimelineEventIds: TimelineEventId[]) => {+ const draftId = ensureDraftCard({}, true);+ dispatch(+ updateVizSettings({+ cardId: draftId,+ settings: getTimelineEventSettings(timelines, newTimelineEventIds),+ }),+ );+ },+ [dispatch, ensureDraftCard, timelines],+ );++ const handleShowTimelineEvents = useCallback(+ (timelineEvents: TimelineEvent[]) => {+ const newVisibleTimelineEventIds = [+ ...visibleTimelineEventIds,+ ...timelineEvents.map((event) => event.id),+ ];+ updateTimelineVizSettings(newVisibleTimelineEventIds);+ },+ [updateTimelineVizSettings, visibleTimelineEventIds],+ );++ const handleHideTimelineEvents = useCallback(+ (timelineEvents: TimelineEvent[]) => {+ const eventIdsToHide = new Set(timelineEvents.map((event) => event.id));+ const newVisibleTimelineEventIds = visibleTimelineEventIds.filter(+ (eventId) => !eventIdsToHide.has(eventId),+ );+ updateTimelineVizSettings(newVisibleTimelineEventIds);+ },+ [updateTimelineVizSettings, visibleTimelineEventIds],+ );++ const handleClose = useCallback(() => {+ dispatch(closeSidebar());+ }, [dispatch]);++ const handleSelectTimelineEvents = useCallback(+ (timelineEvents: TimelineEvent[]) => {+ dispatch(selectTimelineEvents(timelineEvents));+ },+ [dispatch],+ );++ const handleDeselectTimelineEvents = useCallback(() => {+ dispatch(deselectTimelineEvents());+ }, [dispatch]);++ const handleShowAllEvents = useCallback(() => {+ dispatch(clearFocusedTimelineEvents());+ }, [dispatch]);++ if (isLoading) {+ return (+ <Stack gap="lg" p="lg" className={S.loadingContainer}>+ <Box className={S.loadingContent}>+ <Loader size="lg" />+ <Text>{t`Loading timeline events...`}</Text>+ </Box>+ </Stack>+ );+ }++ if (isError) {+ return (+ <Stack gap="lg" p="lg" className={S.errorContainer}>+ <Box className={S.errorContent}>+ <Text c="error">{t`Failed to load timeline events`}</Text>+ </Box>+ </Stack>+ );+ }++ return (+ <Box className={S.container}>+ <TimelineSidebar+ collectionId={collectionId}+ timelines={timelines}+ visibleTimelineEventIds={visibleTimelineEventIds}+ selectedTimelineEventIds={selectedTimelineEventIds}+ focusedTimelineEventIds={focusedTimelineEventIds}+ onShowTimelineEvents={handleShowTimelineEvents}+ onHideTimelineEvents={handleHideTimelineEvents}+ onSelectTimelineEvents={handleSelectTimelineEvents}+ onDeselectTimelineEvents={handleDeselectTimelineEvents}+ onShowAllEvents={handleShowAllEvents}+ onClose={handleClose}+ />+ </Box>+ );+}diff --git a/frontend/src/metabase/documents/components/editor-extensions/CardEmbed/CardEmbedMenuDropdown.tsx b/frontend/src/metabase/documents/components/editor-extensions/CardEmbed/CardEmbedMenuDropdown.tsxindex f9161485860..3216881f3c6 100644--- a/frontend/src/metabase/documents/components/editor-extensions/CardEmbed/CardEmbedMenuDropdown.tsx+++ b/frontend/src/metabase/documents/components/editor-extensions/CardEmbed/CardEmbedMenuDropdown.tsx@@ -15,6 +15,7 @@ export interface CardEmbedMenuContext {isNativeQuestion: boolean | undefined;commentsPath: string;hasUnsavedChanges: boolean;+ isStatic: boolean;}export interface CardEmbedMenuActions {@@ -24,6 +25,8 @@ export interface CardEmbedMenuActions {enablePivot: boolean;}) => Promise<void>;handleEditVisualizationSettings: () => void;+ shouldShowTimelineEventsMenu?: boolean;+ handleEditTimelineEvents?: () => void;setIsModifyModalOpen: (open: boolean) => void;handleReplaceQuestion: () => void;handleRemoveNode: () => void;@@ -47,9 +50,12 @@ export const CardEmbedMenuDropdown = ({isNativeQuestion,commentsPath,hasUnsavedChanges,+ isStatic,+ shouldShowTimelineEventsMenu,// ActionshandleDownload,handleEditVisualizationSettings,+ handleEditTimelineEvents,setIsModifyModalOpen,handleReplaceQuestion,handleRemoveNode,@@ -104,23 +110,36 @@ export const CardEmbedMenuDropdown = ({>{t`Edit Visualization`}</Menu.Item>- <Menu.Item- onClick={() => setIsModifyModalOpen(true)}- leftSection={- <Icon name={isNativeQuestion ? "sql" : "notebook"} size={14} />- }- disabled={!canWrite}- >- {t`Edit Query`}- </Menu.Item>- <Menu.Item- onClick={handleReplaceQuestion}- leftSection={<Icon name="refresh" size={14} />}- disabled={!canWrite}- >- {t`Replace`}- </Menu.Item>- {canDownloadResults(dataset) && (+ {shouldShowTimelineEventsMenu && (+ <Menu.Item+ leftSection={<Icon name="calendar" size={14} />}+ onClick={handleEditTimelineEvents}+ disabled={!canWrite}+ >+ {t`Events`}+ </Menu.Item>+ )}+ {!isStatic && (+ <Menu.Item+ onClick={() => setIsModifyModalOpen(true)}+ leftSection={+ <Icon name={isNativeQuestion ? "sql" : "notebook"} size={14} />+ }+ disabled={!canWrite}+ >+ {t`Edit Query`}+ </Menu.Item>+ )}+ {!isStatic && (+ <Menu.Item+ onClick={handleReplaceQuestion}+ leftSection={<Icon name="refresh" size={14} />}+ disabled={!canWrite}+ >+ {t`Replace`}+ </Menu.Item>+ )}+ {!isStatic && canDownloadResults(dataset) && (<Menu.ItemleftSection={<Icon name="download" aria-hidden />}aria-label={isDownloadingData ? t`Downloading…` : t`Download results`}diff --git a/frontend/src/metabase/documents/components/editor-extensions/CardEmbed/CardEmbedNode.tsx b/frontend/src/metabase/documents/components/editor-extensions/CardEmbed/CardEmbedNode.tsxindex 270b05e3c54..726b6c31a53 100644--- a/frontend/src/metabase/documents/components/editor-extensions/CardEmbed/CardEmbedNode.tsx+++ b/frontend/src/metabase/documents/components/editor-extensions/CardEmbed/CardEmbedNode.tsx@@ -12,13 +12,13 @@ import {import cx from "classnames";import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";import { t } from "ttag";+import { noop } from "underscore";import { ExplicitSizeRefreshModeContext } from "metabase/common/components/ExplicitSize/ExplicitSize";import { QuestionPickerModal } from "metabase/common/components/Pickers";import type { QuestionPickerValueItem } from "metabase/common/components/Pickers/QuestionPicker/types";import { useDownloadData } from "metabase/common/components/QuestionDownloadWidget/use-download-data";import { useDispatch, useSelector } from "metabase/redux";-import { useEditorHost } from "metabase/rich_text_editing/tiptap/EditorHost";import { CommentsButton } from "metabase/rich_text_editing/tiptap/components/CommentsButton";import { CardEmbedLoadingState } from "metabase/rich_text_editing/tiptap/extensions/CardEmbed/CardEmbedLoadingState";import {@@ -48,16 +48,27 @@ import {TextInput,} from "metabase/ui";import * as Urls from "metabase/urls";+import {+ extractRemappings,+ getVisualizationTransformed,+} from "metabase/visualizations";import Visualization from "metabase/visualizations/components/Visualization";import { ErrorView } from "metabase/visualizations/components/Visualization/ErrorView/ErrorView";import ChartSkeleton from "metabase/visualizations/components/skeletons/ChartSkeleton";import { getDatasetError } from "metabase/visualizations/lib/errors";+import { isTimeseries } from "metabase/visualizations/lib/renderer_utils";+import { getComputedSettingsForSeries } from "metabase/visualizations/lib/settings/visualization";import Question from "metabase-lib/v1/Question";-import type { CardDisplayType } from "metabase-types/api";+import type {+ CardDisplayType,+ StoredResultSort,+ TimelineEvent,+} from "metabase-types/api";++import { useDocumentEditorHost } from "../../Editor/DocumentEditorHost";import { CardEmbedMenuDropdown } from "./CardEmbedMenuDropdown";import styles from "./CardEmbedNode.module.css";-import { DocumentMode } from "./DocumentMode";import { useExternalCardData } from "./ExternalCardDataContext";import { ExternalDocumentCardMenu } from "./ExternalDocumentCardMenu";import { ModifyQuestionModal } from "./modals/ModifyQuestionModal";@@ -65,6 +76,16 @@ import { NativeQueryModal } from "./modals/NativeQueryModal";import { useUpdateCardOperations } from "./use-update-card-operations";import { getEmbedIndex } from "./utils";+const STATIC_CARD_SORTS: ReadonlyArray<StoredResultSort> = [+ "value_asc",+ "value_desc",+ "label_asc",+ "label_desc",+];++const isStaticCardSort = (value: unknown): value is StoredResultSort =>+ typeof value === "string" && STATIC_CARD_SORTS.some((sort) => sort === value);+function formatCardEmbed(attrs: CardEmbedAttributes): string {if (attrs.name) {return `{% card id=${attrs.id} name="${attrs.name}" %}`;@@ -77,6 +98,11 @@ export interface CardEmbedAttributes {id?: number;name?: string;class?: string;+ stored_result_id?: number | null; // When set, the embed renders in static mode: data is pulled from the cached `stored_result` snapshot+ sort?: string | null; // Sort to apply in-memory when reading a static snapshot. Static-mode only+ chart_href?: string | null; // Override URL for the embed's title click+ child_target_id?: string | null; // when set, comments on this embed use this child target instead of `_id`+ host_data?: Record<string, unknown> | null; // opaque host-specific data}export const CardEmbed: Node<{HTMLAttributes: CardEmbedAttributes;@@ -104,6 +130,53 @@ export const CardEmbed: Node<{default: null,parseHTML: (element) => element.getAttribute("data-name"),},+ stored_result_id: {+ default: null,+ parseHTML: (element) => {+ const raw = element.getAttribute("data-stored-result-id");+ if (!raw) {+ return null;+ }+ const parsed = parseInt(raw, 10);+ return Number.isFinite(parsed) ? parsed : null;+ },+ },+ sort: {+ default: null,+ parseHTML: (element) => element.getAttribute("data-sort"),+ },+ chart_href: {+ default: null,+ parseHTML: (element) => element.getAttribute("data-chart-href"),+ },+ child_target_id: {+ default: null,+ parseHTML: (element) =>+ element.getAttribute("data-child-target-id") || null,+ },+ host_data: {+ default: null,+ parseHTML: (element) => {+ const raw = element.getAttribute("data-host-data");+ if (!raw) {+ return null;+ }+ try {+ const parsed: unknown = JSON.parse(raw);+ if (+ parsed != null &&+ typeof parsed === "object" &&+ !Array.isArray(parsed)+ ) {+ // JSON.parse of an object literal is a plain Record; TipTap attrs are untyped JSON.+ return parsed as Record<string, unknown>;+ }+ } catch {+ return null;+ }+ return null;+ },+ },...createIdAttribute(),};},@@ -125,6 +198,17 @@ export const CardEmbed: Node<{"data-type": CardEmbed.name,"data-id": node.attrs.id,"data-name": node.attrs.name,+ "data-stored-result-id":+ node.attrs.stored_result_id != null+ ? String(node.attrs.stored_result_id)+ : null,+ "data-sort": node.attrs.sort ?? null,+ "data-chart-href": node.attrs.chart_href ?? null,+ "data-child-target-id": node.attrs.child_target_id ?? null,+ "data-host-data":+ node.attrs.host_data != null+ ? JSON.stringify(node.attrs.host_data)+ : null,},this.options.HTMLAttributes,),@@ -153,9 +237,15 @@ export const CardEmbedComponent = memo(editor,getPos,deleteNode,+ // eslint-disable-next-line complexity}: NodeViewProps) => {const { _id, id, name } = node.attrs;- const host = useEditorHost();+ const storedResultId = node.attrs.stored_result_id;+ const isStatic = storedResultId != null;+ const staticSort = isStaticCardSort(node.attrs.sort)+ ? node.attrs.sort+ : undefined;+ const host = useDocumentEditorHost();const {ref: viewportRef,isInViewport,@@ -167,15 +257,34 @@ export const CardEmbedComponent = memo();const document = useSelector(host.selectors.getCurrentDocument);const externalCardData = useExternalCardData();- const unresolvedCommentsCount = host.useUnresolvedCommentsCount(_id, {- skip: !isInViewport,+ const hostData = node.attrs.host_data ?? null;+ const commentChildTargetId = node.attrs.child_target_id ?? _id;+ const unresolvedCommentsCount = host.useUnresolvedCommentsCount(+ commentChildTargetId,+ {+ skip: !isInViewport,+ },+ );+ const visualizationMode = host.useVisualizationMode({+ childTargetId: commentChildTargetId,+ hostData,+ });+ const slots = host.useCardEmbedSlots({+ childTargetId: commentChildTargetId,+ hostData,});const hasUnsavedChanges = useSelector(host.selectors.getHasUnsavedChanges);- const isOpen = childTargetId === _id;- const isHovered = hoveredChildTargetId === _id;+ const selectedEmbedIndex = useSelector(+ host.selectors.getSelectedEmbedIndex,+ );+ const selectedTimelineEventIdsFromState = useSelector(+ host.selectors.getSelectedTimelineEventIds,+ );+ const isOpen = childTargetId === commentChildTargetId;+ const isHovered = hoveredChildTargetId === commentChildTargetId;const commentsPath = host.useCommentUrl({- childTargetId: _id,+ childTargetId: commentChildTargetId,});const dispatch = useDispatch();const navigate = useNavigate();@@ -190,9 +299,19 @@ export const CardEmbedComponent = memo(} = useDndHelpers({ editor, node, getPos });const embedIndex = getEmbedIndex(editor, getPos);+ const selectedTimelineEventIds =+ embedIndex === selectedEmbedIndex+ ? selectedTimelineEventIdsFromState+ : undefined;const isExternalDocument = externalCardData != null;- const regularCardData = host.useCardData({ id, skip: !shouldLoadData });+ const regularCardData = host.useCardData({+ id,+ skip: !shouldLoadData,+ ...(storedResultId != null+ ? { storedResultId, storedResultSort: staticSort }+ : {}),+ });const externalCardDataResult = host.useExternalCardDataLoader(id, {skip: !shouldLoadData,});@@ -201,6 +320,12 @@ export const CardEmbedComponent = memo(? externalCardDataResult: regularCardData;+ const highlighted = host.useHighlighted(+ commentChildTargetId,+ series ?? null,+ hostData,+ );+host.useReportPrefetchLoading(_id, isLoading);const metadata = useSelector(getMetadata);@@ -349,7 +474,57 @@ export const CardEmbedComponent = memo(}};+ const shouldShowTimelineEventsMenu = useMemo(() => {+ if (!series) {+ return false;+ }+ const transformed = getVisualizationTransformed(+ extractRemappings(series),+ );+ const settings = getComputedSettingsForSeries(transformed.series);+ return isTimeseries(settings);+ }, [series]);++ const handleEditTimelineEvents = () => {+ if (embedIndex !== -1) {+ dispatch(host.actions.openTimelineEventsSidebar({ embedIndex }));+ }+ };++ const handleOpenTimelines = useCallback(+ (eventIds?: number[]) => {+ if (embedIndex !== -1) {+ dispatch(+ host.actions.openTimelineEventsSidebar({+ embedIndex,+ focusedEventIds: eventIds,+ }),+ );+ }+ },+ [dispatch, embedIndex, host.actions],+ );++ const handleSelectTimelineEvents = useCallback(+ (events: TimelineEvent[]) => {+ dispatch(host.actions.selectTimelineEvents(events));+ },+ [dispatch, host.actions],+ );++ const handleDeselectTimelineEvents = useCallback(() => {+ dispatch(host.actions.deselectTimelineEvents());+ }, [dispatch, host.actions]);+const handleTitleClick = () => {+ const chartHref = node.attrs.chart_href;+ if (chartHref) {+ dispatch(host.navigateToCard(chartHref, document));+ return;+ }+ if (!host.capabilities.canOpenCardInQueryBuilder) {+ return;+ }if (card && metadata) {try {const isDraftCard = card.id < 0;@@ -615,6 +790,7 @@ export const CardEmbedComponent = memo(menuView={menuView}setMenuView={setMenuView}canWrite={canWrite}+ isStatic={isStatic}dataset={dataset}question={question}isNativeQuestion={isNativeQuestion}@@ -623,6 +799,10 @@ export const CardEmbedComponent = memo(handleEditVisualizationSettings={handleEditVisualizationSettings}+ shouldShowTimelineEventsMenu={+ shouldShowTimelineEventsMenu+ }+ handleEditTimelineEvents={handleEditTimelineEvents}handleAddSupportingText={handleAddSupportingText}setIsModifyModalOpen={setIsModifyModalOpen}handleReplaceQuestion={handleReplaceQuestion}@@ -634,6 +814,7 @@ export const CardEmbedComponent = memo(</Menu>) : null)}</Flex>+ {slots.belowTitle}</Box>)}{series && isInViewport ? (@@ -643,18 +824,32 @@ export const CardEmbedComponent = memo(<VisualizationrawSeries={series}metadata={metadata}- mode={DocumentMode}+ mode={visualizationMode}+ highlighted={highlighted}onChangeCardAndRun={- isExternalDocument ? undefined : handleChangeCardAndRun+ isStatic+ ? // A defined mode needs a truthy handler so the click-actions popover mounts+ visualizationMode != null+ ? noop+ : undefined+ : isExternalDocument+ ? undefined+ : handleChangeCardAndRun}onUpdateQuestion={- isExternalDocument ? undefined : handleUpdateQuestion+ isStatic || isExternalDocument+ ? undefined+ : handleUpdateQuestion}onUpdateVisualizationSettings={isExternalDocument? undefined: handleUpdateVisualizationSettings}+ onOpenTimelines={handleOpenTimelines}+ onSelectTimelineEvents={handleSelectTimelineEvents}+ onDeselectTimelineEvents={handleDeselectTimelineEvents}+ selectedTimelineEventIds={selectedTimelineEventIds}getExtraDataForClick={() => ({})}isEditing={false}isDashboard={false}@@ -717,6 +912,13 @@ export const CardEmbedComponent = memo(return (prevProps.node.attrs.id === nextProps.node.attrs.id &&prevProps.node.attrs.name === nextProps.node.attrs.name &&+ prevProps.node.attrs.stored_result_id ===+ nextProps.node.attrs.stored_result_id &&+ prevProps.node.attrs.sort === nextProps.node.attrs.sort &&+ prevProps.node.attrs.chart_href === nextProps.node.attrs.chart_href &&+ prevProps.node.attrs.child_target_id ===+ nextProps.node.attrs.child_target_id &&+ prevProps.node.attrs.host_data === nextProps.node.attrs.host_data &&prevProps.selected === nextProps.selected);},diff --git a/frontend/src/metabase/documents/components/editor-extensions/CardEmbed/CardEmbedNode.unit.spec.ts b/frontend/src/metabase/documents/components/editor-extensions/CardEmbed/CardEmbedNode.unit.spec.tsnew file mode 100644index 00000000000..da460fad8c5--- /dev/null+++ b/frontend/src/metabase/documents/components/editor-extensions/CardEmbed/CardEmbedNode.unit.spec.ts@@ -0,0 +1,153 @@+import { Editor } from "@tiptap/core";+import Document from "@tiptap/extension-document";+import Paragraph from "@tiptap/extension-paragraph";+import Text from "@tiptap/extension-text";++// The full Tiptap node imports a Redux-backed React component and a CSS+// module — neither matter for the schema-level round-trip. Stub+// `ReactNodeViewRenderer` to return a no-op node-view factory so the+// schema is created without dragging the React tree in.+jest.mock("@tiptap/react", () => {+ const noopNodeView = () => ({+ dom: document.createElement("div"),+ update: () => true,+ destroy: () => {},+ });+ return {+ __esModule: true,+ ReactNodeViewRenderer: () => () => noopNodeView(),+ NodeViewWrapper: () => null,+ };+});++// Sidecar CSS / module imports the real CardEmbedNode triggers — stub+// what `Node.create` needs but don't render anything.+jest.mock("./CardEmbedNode.module.css", () => ({}), { virtual: true });+jest.mock(+ "metabase/rich_text_editing/tiptap/extensions/CardEmbed/CardEmbedLoadingState",+ () => ({+ __esModule: true,+ CardEmbedLoadingState: () => null,+ }),+);+jest.mock("./CardEmbedMenuDropdown", () => ({+ __esModule: true,+ CardEmbedMenuDropdown: () => null,+}));+jest.mock("./ExternalDocumentCardMenu", () => ({+ __esModule: true,+ ExternalDocumentCardMenu: () => null,+}));+jest.mock("./modals/ModifyQuestionModal", () => ({+ __esModule: true,+ ModifyQuestionModal: () => null,+}));+jest.mock("./use-update-card-operations", () => ({+ __esModule: true,+ useUpdateCardOperations: () => ({}),+}));++import { CardEmbed } from "./CardEmbedNode";++function makeEditor() {+ return new Editor({+ extensions: [Document, Paragraph, Text, CardEmbed],+ });+}++describe("CardEmbed node — chart_href attr", () => {+ it("round-trips a `chart_href` through parseHTML ↔ renderHTML", () => {+ const editor = makeEditor();+ const href = "/question/research/7/group/auto%3A42%3Ad1";++ editor.commands.insertContent({+ type: "cardEmbed",+ attrs: {+ id: 77,+ name: null,+ stored_result_id: 99,+ chart_href: href,+ },+ });++ const html = editor.getHTML();+ expect(html).toContain(`data-chart-href="${href}"`);++ const editor2 = makeEditor();+ editor2.commands.setContent(html);++ const node = editor2.state.doc.firstChild;+ expect(node?.type.name).toBe("cardEmbed");+ expect(node?.attrs.id).toBe(77);+ expect(node?.attrs.stored_result_id).toBe(99);+ expect(node?.attrs.chart_href).toBe(href);++ editor.destroy();+ editor2.destroy();+ });++ it("round-trips `child_target_id` through parseHTML ↔ renderHTML", () => {+ const editor = makeEditor();++ editor.commands.insertContent({+ type: "cardEmbed",+ attrs: {+ id: 77,+ name: null,+ stored_result_id: 99,+ child_target_id: "12",+ },+ });++ const html = editor.getHTML();+ expect(html).toContain(`data-child-target-id="12"`);++ const editor2 = makeEditor();+ editor2.commands.setContent(html);++ const node = editor2.state.doc.firstChild;+ expect(node?.attrs.child_target_id).toBe("12");++ editor.destroy();+ editor2.destroy();+ });++ it("round-trips `host_data` through parseHTML ↔ renderHTML", () => {+ const editor = makeEditor();++ editor.commands.insertContent({+ type: "cardEmbed",+ attrs: {+ id: 77,+ name: null,+ stored_result_id: 99,+ child_target_id: "12",+ host_data: { query_ids: [101, 102] },+ },+ });++ const html = editor.getHTML();+ expect(html).toContain("data-host-data=");++ const editor2 = makeEditor();+ editor2.commands.setContent(html);++ const node = editor2.state.doc.firstChild;+ expect(node?.attrs.host_data).toEqual({ query_ids: [101, 102] });++ editor.destroy();+ editor2.destroy();+ });++ it("renders no `data-chart-href` attribute when null (non-exploration embeds stay clean)", () => {+ const editor = makeEditor();++ editor.commands.insertContent({+ type: "cardEmbed",+ attrs: { id: 42, name: null, stored_result_id: null, chart_href: null },+ });++ expect(editor.getHTML()).not.toContain("data-chart-href");+ editor.destroy();+ });+});diff --git a/frontend/src/metabase/documents/documents.slice.ts b/frontend/src/metabase/documents/documents.slice.tsindex 625a502dceb..b52dad825f1 100644--- a/frontend/src/metabase/documents/documents.slice.ts+++ b/frontend/src/metabase/documents/documents.slice.ts@@ -14,6 +14,8 @@ import type {import type {Card,Document,+ TimelineEvent,+ TimelineEventId,VisualizationDisplay,VisualizationSettings,} from "metabase-types/api";@@ -31,16 +33,15 @@ export const loadMetadataForDocumentCard = createAsyncThunk();export const initialState: DocumentsState = {- selectedEmbedIndex: null,+ sidebar: null,cardEmbeds: [],currentDocument: null,draftCards: {},+ draftCardOriginalIds: {},mentionsCache: {},- isCommentSidebarOpen: false,childTargetId: undefined,hoveredChildTargetId: undefined,hasUnsavedChanges: false,- isHistorySidebarOpen: false,};// eslint-disable-next-line @typescript-eslint/ban-ts-comment@@ -49,11 +50,68 @@ const documentsSlice = createSlice({name: "documents",initialState,reducers: {+ setSidebarEmbedIndex: (state, action: PayloadAction<number>) => {+ if (+ state.sidebar?.mode === "viz-settings" ||+ state.sidebar?.mode === "timeline-events"+ ) {+ if (state.sidebar.embedIndex === action.payload) {+ // avoid clearing selectedEventIds/focusedEventIds if the embedIndex didn't change+ return;+ }+ state.sidebar.embedIndex = action.payload;+ if (state.sidebar.mode === "timeline-events") {+ state.sidebar.selectedEventIds = [];+ state.sidebar.focusedEventIds = null;+ }+ }+ },openVizSettingsSidebar: (state,action: PayloadAction<{ embedIndex: number }>,) => {- state.selectedEmbedIndex = action.payload.embedIndex;+ state.sidebar = {+ mode: "viz-settings",+ embedIndex: action.payload.embedIndex,+ };+ },+ openTimelineEventsSidebar: (+ state,+ action: PayloadAction<{+ embedIndex: number;+ focusedEventIds?: TimelineEventId[];+ }>,+ ) => {+ const { embedIndex, focusedEventIds } = action.payload;+ state.sidebar = {+ mode: "timeline-events",+ embedIndex,+ focusedEventIds: focusedEventIds ?? null,+ selectedEventIds: focusedEventIds ?? [],+ };+ },+ openCommentsSidebar: (state) => {+ state.sidebar = { mode: "comments" };+ },+ openHistorySidebar: (state) => {+ state.sidebar = { mode: "history" };+ },+ selectTimelineEvents: (state, action: PayloadAction<TimelineEvent[]>) => {+ if (state.sidebar?.mode === "timeline-events") {+ state.sidebar.selectedEventIds = action.payload.map(+ (event) => event.id,+ );+ }+ },+ deselectTimelineEvents: (state) => {+ if (state.sidebar?.mode === "timeline-events") {+ state.sidebar.selectedEventIds = [];+ }+ },+ clearFocusedTimelineEvents: (state) => {+ if (state.sidebar?.mode === "timeline-events") {+ state.sidebar.focusedEventIds = null;+ }},updateVizSettings: (state,@@ -80,7 +138,7 @@ const documentsSlice = createSlice({}},closeSidebar: (state) => {- state.selectedEmbedIndex = null;+ state.sidebar = null;},setCardEmbeds: (state, action: PayloadAction<CardEmbedRef[]>) => {state.cardEmbeds = action.payload;@@ -108,9 +166,15 @@ const documentsSlice = createSlice({...modifiedData,id: draftId,} as Card;++ const originalCardId = originalCard?.id;+ if (originalCardId != null && originalCardId > 0) {+ state.draftCardOriginalIds[draftId] = originalCardId;+ }},clearDraftCards: (state) => {state.draftCards = {};+ state.draftCardOriginalIds = {};},updateMentionsCache: (state,@@ -118,9 +182,6 @@ const documentsSlice = createSlice({) => {state.mentionsCache[getMentionsCacheKey(payload)] = payload;},- setIsCommentSidebarOpen: (state, action: PayloadAction<boolean>) => {- state.isCommentSidebarOpen = action.payload;- },setChildTargetId: (state, action: PayloadAction<string | undefined>) => {state.childTargetId = action.payload;},@@ -133,14 +194,18 @@ const documentsSlice = createSlice({setHasUnsavedChanges: (state, action: PayloadAction<boolean>) => {state.hasUnsavedChanges = action.payload;},- setIsHistorySidebarOpen: (state, action: PayloadAction<boolean>) => {- state.isHistorySidebarOpen = action.payload;- },},});export const {+ setSidebarEmbedIndex,openVizSettingsSidebar,+ openTimelineEventsSidebar,+ openCommentsSidebar,+ openHistorySidebar,+ selectTimelineEvents,+ deselectTimelineEvents,+ clearFocusedTimelineEvents,updateVizSettings,updateVisualizationType,closeSidebar,@@ -150,11 +215,9 @@ export const {createDraftCard,clearDraftCards,updateMentionsCache,- setIsCommentSidebarOpen,setChildTargetId,setHoveredChildTargetId,setHasUnsavedChanges,- setIsHistorySidebarOpen,} = documentsSlice.actions;export const generateDraftCardId = (): number => {diff --git a/frontend/src/metabase/documents/hooks/use-block-menus.ts b/frontend/src/metabase/documents/hooks/use-block-menus.tsindex a614a72e98f..47abc7ebcf6 100644--- a/frontend/src/metabase/documents/hooks/use-block-menus.ts+++ b/frontend/src/metabase/documents/hooks/use-block-menus.ts@@ -3,14 +3,8 @@ import { useMergedRef } from "@mantine/hooks";import type { Editor, NodeViewProps } from "@tiptap/core";import { useEffect, useState } from "react";-import { useNodeInViewport } from "metabase/documents/hooks/use-node-in-viewport";-import { useUnresolvedDocumentCommentsCount } from "metabase/documents/hooks/use-unresolved-document-comments-count";-import {- getChildTargetId,- getCurrentDocument,- getHoveredChildTargetId,-} from "metabase/documents/selectors";import { useSelector } from "metabase/redux";+import { useEditorHost } from "metabase/rich_text_editing/tiptap/EditorHost";import { documentWithAnchor } from "metabase/urls";import { isWithinIframe } from "metabase/utils/iframe";@@ -34,14 +28,17 @@ export function useBlockMenus({getPos,shouldHideMenus = false,}: UseBlockMenusOptions) {- const childTargetId = useSelector(getChildTargetId);- const hoveredChildTargetId = useSelector(getHoveredChildTargetId);- const document = useSelector(getCurrentDocument);+ const host = useEditorHost();+ const childTargetId = useSelector(host.selectors.getChildTargetId);+ const hoveredChildTargetId = useSelector(+ host.selectors.getHoveredChildTargetId,+ );+ const document = useSelector(host.selectors.getCurrentDocument);const { _id } = node.attrs;- const { ref: viewportRef, isInViewport } = useNodeInViewport();+ const { ref: viewportRef, isInViewport } = host.useNodeInViewport();- const unresolvedCommentsCount = useUnresolvedDocumentCommentsCount(_id, {+ const unresolvedCommentsCount = host.useUnresolvedCommentsCount(_id, {skip: !isInViewport,});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.tsxsimilarity index 87%rename from frontend/src/metabase/documents/hooks/use-block-menus.unit.spec.tsrename to frontend/src/metabase/documents/hooks/use-block-menus.unit.spec.tsxindex 1029db1b33e..f451d4a08c8 100644--- a/frontend/src/metabase/documents/hooks/use-block-menus.unit.spec.ts+++ b/frontend/src/metabase/documents/hooks/use-block-menus.unit.spec.tsx@@ -1,11 +1,14 @@+import { renderHook } from "@testing-library/react";import { Schema } from "@tiptap/pm/model";import type { Editor, NodeViewProps } from "@tiptap/react";import fetchMock from "fetch-mock";+import type { ReactNode } from "react";import { setupMockIntersectionObserver } from "__support__/intersection-observer";import { setupCommentEndpoints } from "__support__/server-mocks";-import { act, renderHookWithProviders, waitFor } from "__support__/ui";+import { act, getTestStoreAndWrapper, waitFor } from "__support__/ui";import { delay } from "__support__/utils";+import { DocumentEditorHostProvider } from "metabase/documents/components/Editor/DocumentEditorHost";import { initialState as documentsInitialState } from "metabase/documents/documents.slice";import {createMockNodeViewProps,@@ -36,21 +39,32 @@ describe("useBlockMenus", () => {target_id: mockDocument.id,});- const { result } = renderHookWithProviders(+ const { wrapper: Providers } = getTestStoreAndWrapper({+ initialRoute: "/",+ storeInitialState: {+ documents: {+ ...documentsInitialState,+ currentDocument: mockDocument,+ },+ },+ });++ function Wrapper({ children }: { children: ReactNode }) {+ return (+ <Providers>+ <DocumentEditorHostProvider>{children}</DocumentEditorHostProvider>+ </Providers>+ );+ }++ const { result } = renderHook(() =>useBlockMenus({node: nodeViewProps.node,editor: nodeViewProps.editor,getPos: nodeViewProps.getPos,}),- {- storeInitialState: {- documents: {- ...documentsInitialState,- currentDocument: mockDocument,- },- },- },+ { wrapper: Wrapper },);// Attach a reference element so the IntersectionObserver starts observing.diff --git a/frontend/src/metabase/documents/hooks/use-card-data.ts b/frontend/src/metabase/documents/hooks/use-card-data.tsindex 884f59b5051..9d9dcab6abe 100644--- a/frontend/src/metabase/documents/hooks/use-card-data.ts+++ b/frontend/src/metabase/documents/hooks/use-card-data.ts@@ -10,14 +10,21 @@ import type { UseCardDataResult } from "metabase/rich_text_editing/tiptap/Editorimport { getMetadata } from "metabase/selectors/metadata";import Question from "metabase-lib/v1/Question";import { getPivotOptions } from "metabase-lib/v1/queries/utils/pivot-options";-import type { Card, Dataset, RawSeries } from "metabase-types/api";+import type {+ Card,+ Dataset,+ RawSeries,+ StoredResultSort,+} from "metabase-types/api";import { isObject } from "metabase-types/guards";-import { getCardWithDraft } from "../selectors";+import { getCardWithDraft, getDraftCardOriginalId } from "../selectors";interface UseCardDataProps {id: number;skip?: boolean;+ storedResultId?: number; // When set, the embed renders in static mode: data is pulled from the cached `stored_result` snapshot+ storedResultSort?: StoredResultSort; // Sort to apply in-memory when reading a static snapshot. Static-mode only}function buildAdhocQueryParams(card: Card) {@@ -77,6 +84,8 @@ function selectIsLoadingDataset(export function useCardData({id,skip = false,+ storedResultId,+ storedResultSort,}: UseCardDataProps): UseCardDataResult {const isDraft = id < 0;const shouldSkipSavedCard = !id || isDraft || skip;@@ -90,6 +99,9 @@ export function useCardData({const cardWithDraft = useSelector((state) =>getCardWithDraft(state, id, card),);+ const originalCardId = useSelector((state) =>+ getDraftCardOriginalId(state, id),+ );const cardToUse = cardWithDraft ?? card;@@ -97,8 +109,18 @@ export function useCardData({const isPivotTable = cardToUse?.display === "pivot";+ const shouldUseDraftQuery = isDraft && storedResultId == null;+ const queryCardId =+ storedResultId != null && originalCardId != null ? originalCardId : id;+ const shouldSkipRegularQuery =+ !queryCardId || queryCardId < 0 || shouldUseDraftQuery || skip;+ const canQueryDraftCard =+ shouldUseDraftQuery && cardToUse?.dataset_query && !skip;+ const shouldQueryDraftNonPivot = canQueryDraftCard && !isPivotTable;+ const shouldQueryDraftPivot = canQueryDraftCard && isPivotTable && metadata;+const pivotOptions = useMemo(() => {- if (!isDraft || !isPivotTable || !cardToUse || !metadata) {+ if (!shouldUseDraftQuery || !isPivotTable || !cardToUse || !metadata) {return null;}@@ -108,15 +130,18 @@ export function useCardData({} catch (error) {return null;}- }, [isDraft, isPivotTable, cardToUse, metadata]);-- const shouldSkipRegularQuery = !id || isDraft || !card || skip;- const canQueryDraftCard = isDraft && cardToUse?.dataset_query && !skip;- const shouldQueryDraftNonPivot = canQueryDraftCard && !isPivotTable;- const shouldQueryDraftPivot = canQueryDraftCard && isPivotTable && metadata;+ }, [shouldUseDraftQuery, isPivotTable, cardToUse, metadata]);const { data: regularDataset, isLoading: isLoadingRegularDataset } =- useGetCardQueryQuery({ cardId: id }, { skip: shouldSkipRegularQuery });+ useGetCardQueryQuery(+ {+ cardId: queryCardId,+ ...(storedResultId != null+ ? { stored_result_id: storedResultId, sort: storedResultSort }+ : {}),+ },+ { skip: shouldSkipRegularQuery },+ );const { data: draftDataset, isLoading: isLoadingDraftDataset } =useGetAdhocQueryQuery(@@ -134,7 +159,7 @@ export function useCardData({);const dataset = selectDataset(- isDraft,+ shouldUseDraftQuery,isPivotTable,regularDataset,draftDataset,@@ -142,7 +167,7 @@ export function useCardData({);const isLoadingDataset = selectIsLoadingDataset(- isDraft,+ shouldUseDraftQuery,isPivotTable,isLoadingRegularDataset,isLoadingDraftDataset,diff --git a/frontend/src/metabase/documents/hooks/use-document-comment-url.ts b/frontend/src/metabase/documents/hooks/use-document-comment-url.tsnew file mode 100644index 00000000000..5189384121c--- /dev/null+++ b/frontend/src/metabase/documents/hooks/use-document-comment-url.ts@@ -0,0 +1,23 @@+import { useMaybeLocation } from "metabase/router";++interface UseDocumentCommentUrlOptions {+ childTargetId?: string | null;+}++/** Document comments deep-link: `/comments/:childTargetId` path segment. */+export function useDocumentCommentUrl({+ childTargetId,+}: UseDocumentCommentUrlOptions) {+ const location = useMaybeLocation();+ const pathname = location?.pathname;+ const search = location?.search ?? "";+ if (!pathname) {+ return "";+ }+ const existingCommentIndex = pathname.lastIndexOf("/comments");+ const nextPathname =+ existingCommentIndex !== -1+ ? pathname.slice(0, existingCommentIndex)+ : pathname;+ return `${nextPathname}/comments${childTargetId ? `/${childTargetId}` : ""}${search}`;+}diff --git a/frontend/src/metabase/documents/hooks/use-document-comment-url.unit.spec.tsx b/frontend/src/metabase/documents/hooks/use-document-comment-url.unit.spec.tsxnew file mode 100644index 00000000000..f909e922d78--- /dev/null+++ b/frontend/src/metabase/documents/hooks/use-document-comment-url.unit.spec.tsx@@ -0,0 +1,33 @@+import { renderWithProviders, screen } from "__support__/ui";+import { Route } from "metabase/router";++import { useDocumentCommentUrl } from "./use-document-comment-url";++function Probe({ childTargetId }: { childTargetId: string }) {+ const url = useDocumentCommentUrl({ childTargetId });+ return <div data-testid="comment-url">{url}</div>;+}++function setup(initialRoute: string, childTargetId = "9") {+ renderWithProviders(+ <Route path="*" element={<Probe childTargetId={childTargetId} />} />,+ { withRouter: true, initialRoute },+ );+ return screen.getByTestId("comment-url").textContent;+}++describe("useDocumentCommentUrl", () => {+ it("appends a /comments segment on document routes", () => {+ expect(setup("/document/1")).toBe("/document/1/comments/9");+ });++ it("replaces an existing /comments segment instead of nesting", () => {+ expect(setup("/document/1/comments/4")).toBe("/document/1/comments/9");+ });++ it("preserves existing search params", () => {+ expect(setup("/document/1?timeline=5")).toBe(+ "/document/1/comments/9?timeline=5",+ );+ });+});diff --git a/frontend/src/metabase/documents/hooks/use-document-editor.ts b/frontend/src/metabase/documents/hooks/use-document-editor.tsnew file mode 100644index 00000000000..f873c2eadda--- /dev/null+++ b/frontend/src/metabase/documents/hooks/use-document-editor.ts@@ -0,0 +1,458 @@+import type { Node as ProseMirrorNode } from "@tiptap/pm/model";+import type { JSONContent, Editor as TiptapEditor } from "@tiptap/react";+import {+ type Dispatch,+ type RefObject,+ type SetStateAction,+ useCallback,+ useEffect,+ useRef,+ useState,+} from "react";+import useBeforeUnload from "react-use/lib/useBeforeUnload";+import { t } from "ttag";+import _ from "underscore";++import { skipToken } from "metabase/api";+import {+ useCreateDocumentMutation,+ useGetDocumentQuery,+ useUpdateDocumentMutation,+} from "metabase/api/document";+import { getFormattedTime } from "metabase/common/components/DateTime";+import { useToast } from "metabase/common/hooks";+import {+ type ScheduleCallback,+ useCallbackEffect,+} from "metabase/common/hooks/use-callback-effect";+import { useDispatch, useSelector } from "metabase/redux";+import type { CardEmbedRef } from "metabase/redux/store/documents";+import { useNavigate } from "metabase/router";+import * as Urls from "metabase/urls";+import type {+ Card,+ CollectionId,+ Document,+ DocumentId,+ RegularCollectionId,+} from "metabase-types/api";++import {+ clearDraftCards,+ resetDocuments,+ setCurrentDocument,+ setHasUnsavedChanges,+ setSidebarEmbedIndex,+} from "../documents.slice";+import { getDraftCards, getHasUnsavedChanges } from "../selectors";++import { useDocumentState } from "./use-document-state";+import { useRegisterDocumentMetabotContext } from "./use-register-document-metabot-context";+import { useScrollToAnchor } from "./use-scroll-to-anchor";++interface UseDocumentEditorParams {+ documentId: DocumentId | "new" | undefined;+ onDocumentCreated?: (document: Document) => void;+ onDocumentUpdated?: (document: Document) => void;+}++interface UseDocumentEditorResult {+ editorInstance: TiptapEditor | null;+ setEditorInstance: Dispatch<SetStateAction<TiptapEditor | null>>;+ collectionPickerMode: "save" | "move" | null;+ setCollectionPickerMode: Dispatch<SetStateAction<"save" | "move" | null>>;+ editorContainerRef: RefObject<HTMLDivElement>;+ isNavigationScheduled: boolean;+ scheduleNavigation: ScheduleCallback;+ isNewDocument: boolean;+ isSaving: boolean;+ documentData: Document | undefined;+ isDocumentLoading: boolean;+ error: unknown;+ canWrite: boolean;+ documentTitle: string;+ setDocumentTitle: (title: string) => void;+ documentContent: JSONContent | null;+ setDocumentContent: (content: JSONContent | null) => void;+ updateCardEmbeds: (embeds: CardEmbedRef[]) => void;+ hasUnsavedChanges: () => boolean;+ showSaveButton: boolean;+ handleChange: (content: JSONContent) => void;+ handleSave: (+ collectionId?: RegularCollectionId | null,+ ) => Promise<{ document?: Document; error?: unknown } | undefined>;+ handleUpdate: (payload: {+ collection_id?: CollectionId | null;+ archived?: boolean;+ }) => Promise<void>;+ handleQuestionSelect: (+ cardId: number | null,+ embedIndex?: number | null,+ ) => void;+}++export function useDocumentEditor({+ documentId,+ onDocumentCreated,+ onDocumentUpdated,+}: UseDocumentEditorParams): UseDocumentEditorResult {+ const dispatch = useDispatch();+ const navigate = useNavigate();+ const [sendToast] = useToast();++ const draftCards = useSelector(getDraftCards);+ const hasUnsavedEditorChanges = useSelector(getHasUnsavedChanges);++ const [editorInstance, setEditorInstance] = useState<TiptapEditor | null>(+ null,+ );+ const [collectionPickerMode, setCollectionPickerMode] = useState<+ "save" | "move" | null+ >(null);++ const editorContainerRef = useRef<HTMLDivElement>(null);++ const [isNavigationScheduled, scheduleNavigation] = useCallbackEffect();++ const [createDocument, { isLoading: isCreating }] =+ useCreateDocumentMutation();+ const [updateDocument, { isLoading: isUpdating }] =+ useUpdateDocumentMutation();++ const isNewDocument = documentId === "new";+ const isSaving = isCreating || isUpdating;++ let {+ data: documentData,+ isLoading: isDocumentLoading,+ error,+ } = useGetDocumentQuery(+ documentId && !isNewDocument ? { id: documentId } : skipToken,+ );+ if (documentId !== documentData?.id) {+ documentData = undefined;+ }++ const canWrite = Boolean(+ !documentData?.archived && (isNewDocument || documentData?.can_write),+ );++ const {+ documentTitle,+ setDocumentTitle,+ documentContent,+ setDocumentContent,+ documentNeedsMigration,+ updateCardEmbeds,+ } = useDocumentState(documentData);++ useEffect(() => {+ // Set current document when document loads (includes collection_id and all other data)+ if (documentData && !isNewDocument) {+ dispatch(setCurrentDocument(documentData));+ } else if (isNewDocument) {+ dispatch(setCurrentDocument(null));+ }+ }, [documentData, documentId, dispatch, isNewDocument]);++ // Clear documents redux state on unmount (breadcrumbs, sidebar, drafts, etc.)+ useEffect(() => {+ return () => {+ dispatch(resetDocuments());+ };+ }, [dispatch]);++ useRegisterDocumentMetabotContext();++ useBeforeUnload(() => {+ // warn if you try to navigate away with unsaved changes+ return hasUnsavedChanges();+ });++ // Track the "settled" editor content as the baseline for dirty checking.+ // When TipTap processes loaded content it applies default attributes (height,+ // minHeight) and schema corrections (trailing paragraph). We capture the+ // editor's output after it settles and compare against that, not the raw API JSON.+ // Missing `_id`s are not absorbed: they must be persisted so comments can+ // target nodes, so `documentNeedsMigration` forces dirty even after settling.+ const settledContentRef = useRef<JSONContent | null>(null);++ // while the title doesn't have the same problem as content,+ // when loading a new document, there is a render where the server state and local state are out of sync+ const isTitleSettlingRef = useRef(false);++ const prevDocumentIdRef = useRef<DocumentId | "new" | undefined>(undefined);+ if (+ documentId &&+ documentId !== prevDocumentIdRef.current &&+ !isNewDocument+ ) {+ prevDocumentIdRef.current = documentId;+ settledContentRef.current = null;+ isTitleSettlingRef.current = true;+ }++ useEffect(() => {+ if (documentContent && !isNewDocument) {+ settledContentRef.current = null;+ setTimeout(() => {+ const content = editorInstance?.getJSON();+ if (content) {+ settledContentRef.current = content;+ }+ }, 0);+ if (documentNeedsMigration) {+ dispatch(setHasUnsavedChanges(true));+ } else {+ dispatch(setHasUnsavedChanges(false));+ }+ }+ }, [+ dispatch,+ documentContent,+ isNewDocument,+ editorInstance,+ documentNeedsMigration,+ ]);++ // Scroll to anchor block when navigating with URL hash+ const blockId = location.hash ? location.hash.slice(1) : null;+ useScrollToAnchor({+ blockId,+ editorContainerRef,+ isLoading: isDocumentLoading,+ });++ const hasUnsavedChanges = useCallback(() => {+ const currentTitle = documentTitle.trim();+ const originalTitle = documentData?.name || "";+ // We call .trim() on documentTitle to ensure that no one can push the save button+ // with a document name that is all whitespace, the API will reject it. However,+ // when comparing saved with current titles, we need to use unmodified values+ const titleChanged =+ documentTitle !== originalTitle && !isTitleSettlingRef.current;++ // Check if there are any draft cards+ const hasDraftCards = Object.keys(draftCards).length > 0;++ // For new documents, show Save if there's title or editor changes or draft cards+ if (isNewDocument) {+ return (+ currentTitle.length > 0 || hasUnsavedEditorChanges || hasDraftCards+ );+ }++ // For existing documents, use simple change tracking+ return titleChanged || hasUnsavedEditorChanges || hasDraftCards;+ }, [+ documentTitle,+ isNewDocument,+ documentData,+ hasUnsavedEditorChanges,+ draftCards,+ ]);++ const showSaveButton = hasUnsavedChanges() && canWrite && !isSaving;++ const handleTitleChange = useCallback(+ (title: string) => {+ setDocumentTitle(title);+ isTitleSettlingRef.current = false;+ },+ [setDocumentTitle],+ );++ const handleChange = useCallback(+ (content: JSONContent) => {+ // For new documents, any content means changes+ if (isNewDocument) {+ // when navigating to `/new`, handleChange is fired but the editor instance hasn't been set yet+ dispatch(+ setHasUnsavedChanges(!!editorInstance && !editorInstance.isEmpty),+ );+ return;+ }++ if (documentNeedsMigration) {+ dispatch(setHasUnsavedChanges(true));+ return;+ }++ const baseline = settledContentRef.current;+ if (baseline) {+ dispatch(setHasUnsavedChanges(!_.isEqual(content, baseline)));+ }+ },+ [dispatch, editorInstance, isNewDocument, documentNeedsMigration],+ );++ const handleSave = useCallback(+ async (collectionId: RegularCollectionId | null = null) => {+ if (!editorInstance || isSaving) {+ return;+ }++ try {+ const cardsToSave: Record<number, Card> = {};+ const processedCardIds = new Set<number>();++ editorInstance.state.doc.descendants((node: ProseMirrorNode) => {+ if (node.type.name === "cardEmbed") {+ const cardId = node.attrs.id;+ if (!processedCardIds.has(cardId)) {+ processedCardIds.add(cardId);++ if (cardId < 0 && draftCards[cardId]) {+ cardsToSave[cardId] = draftCards[cardId];+ }+ }+ }+ });++ const documentAst = editorInstance.getJSON();+ const name =+ documentTitle ||+ t`Untitled document - ${getFormattedTime(new Date(), "day", { local: true })}`;++ const newDocumentData = {+ name,+ document: documentAst,+ cards: Object.keys(cardsToSave).length > 0 ? cardsToSave : undefined,+ };++ const result = await (documentData?.id+ ? updateDocument({ ...newDocumentData, id: documentData.id }).then(+ (response) => {+ if (response.data) {+ onDocumentUpdated?.(response.data);+ }+ return response;+ },+ )+ : createDocument({+ ...newDocumentData,+ collection_id: collectionId || undefined,+ }).then((response) => {+ if (response.data) {+ const _document = response.data;+ onDocumentCreated?.(_document);+ scheduleNavigation(() => {+ navigate(Urls.document(_document));+ });+ }+ return response;+ }));++ if (result.data) {+ sendToast({+ message: documentData?.id ? t`Document saved` : t`Document created`,+ });+ dispatch(clearDraftCards());+ dispatch(setHasUnsavedChanges(false));+ return {+ document: result.data,+ };+ } else if (result.error) {+ throw result.error;+ }+ } catch (error) {+ console.error("Failed to save document:", error);+ sendToast({ message: t`Error saving document`, icon: "warning" });+ return {+ error: error,+ };+ }+ },+ [+ editorInstance,+ isSaving,+ documentTitle,+ draftCards,+ documentData?.id,+ onDocumentCreated,+ onDocumentUpdated,+ updateDocument,+ createDocument,+ scheduleNavigation,+ dispatch,+ navigate,+ sendToast,+ ],+ );++ useEffect(() => {+ const handleKeyDown = (event: KeyboardEvent) => {+ // Save shortcut: Cmd+S (Mac) or Ctrl+S (Windows/Linux)+ if ((event.metaKey || event.ctrlKey) && event.key === "s") {+ event.preventDefault();+ if (!hasUnsavedChanges() || !canWrite) {+ return;+ }++ if (isNewDocument) {+ setCollectionPickerMode("save");+ } else {+ handleSave();+ }+ }+ };++ document.addEventListener("keydown", handleKeyDown);++ return () => {+ document.removeEventListener("keydown", handleKeyDown);+ };+ }, [+ hasUnsavedChanges,+ handleSave,+ isNewDocument,+ setCollectionPickerMode,+ canWrite,+ ]);++ const handleUpdate = async (payload: {+ collection_id?: CollectionId | null;+ archived?: boolean;+ }) => {+ if (documentData?.id) {+ await updateDocument({ id: documentData.id, ...payload });+ setCollectionPickerMode(null);+ }+ };++ const handleQuestionSelect = useCallback(+ (cardId: number | null, embedIndex?: number | null) => {+ if (cardId !== null && embedIndex != null && embedIndex >= 0) {+ dispatch(setSidebarEmbedIndex(embedIndex));+ }+ },+ [dispatch],+ );++ return {+ editorInstance,+ setEditorInstance,+ collectionPickerMode,+ setCollectionPickerMode,+ editorContainerRef,+ isNavigationScheduled,+ scheduleNavigation,+ isNewDocument,+ isSaving,+ documentData,+ isDocumentLoading,+ error,+ canWrite,+ documentTitle,+ setDocumentTitle: handleTitleChange,+ documentContent,+ setDocumentContent,+ updateCardEmbeds,+ hasUnsavedChanges,+ showSaveButton,+ handleChange,+ handleSave,+ handleUpdate,+ handleQuestionSelect,+ };+}diff --git a/frontend/src/metabase/documents/hooks/use-document-state.ts b/frontend/src/metabase/documents/hooks/use-document-state.tsindex 6b801e39f30..f7beae51f1a 100644--- a/frontend/src/metabase/documents/hooks/use-document-state.ts+++ b/frontend/src/metabase/documents/hooks/use-document-state.ts@@ -5,7 +5,8 @@ import { useDispatch } from "metabase/redux";import type { CardEmbedRef } from "metabase/redux/store/documents";import type { DocumentContent } from "metabase-types/api";-import { setCardEmbeds, setIsCommentSidebarOpen } from "../documents.slice";+import { setCardEmbeds } from "../documents.slice";+import { doesDocumentNeedMigration } from "../utils/editorNodeUtils";export function useDocumentState(documentData?: {name: string;@@ -16,14 +17,19 @@ export function useDocumentState(documentData?: {const [documentContent, setDocumentContent] = useState<JSONContent | null>(null,);+ const [documentNeedsMigration, setDocumentNeedsMigration] = useState(false);const previousEmbedsRef = useRef<CardEmbedRef[]>([]);useEffect(() => {if (documentData) {setDocumentTitle(documentData.name);setDocumentContent(documentData.document);+ setDocumentNeedsMigration(+ doesDocumentNeedMigration(documentData.document),+ );} else {setDocumentContent(null);+ setDocumentNeedsMigration(false);}}, [documentData]);@@ -36,7 +42,9 @@ export function useDocumentState(documentData?: {(embed, index) =>!prevEmbeds[index] ||embed.id !== prevEmbeds[index].id ||- embed.name !== prevEmbeds[index].name,+ embed.name !== prevEmbeds[index].name ||+ embed.stored_result_id !== prevEmbeds[index].stored_result_id ||+ embed.sort !== prevEmbeds[index].sort,);if (hasChanged) {@@ -47,21 +55,12 @@ export function useDocumentState(documentData?: {[dispatch],);- const openCommentSidebar = useCallback(() => {- dispatch(setIsCommentSidebarOpen(true));- }, [dispatch]);-- const closeCommentSidebar = useCallback(() => {- dispatch(setIsCommentSidebarOpen(false));- }, [dispatch]);-return {documentTitle,setDocumentTitle,documentContent,setDocumentContent,+ documentNeedsMigration,updateCardEmbeds,- openCommentSidebar,- closeCommentSidebar,};}diff --git a/frontend/src/metabase/documents/hooks/use-sync-comments-sidebar.ts b/frontend/src/metabase/documents/hooks/use-sync-comments-sidebar.tsnew file mode 100644index 00000000000..8f63b4d5862--- /dev/null+++ b/frontend/src/metabase/documents/hooks/use-sync-comments-sidebar.ts@@ -0,0 +1,46 @@+import { useEffect } from "react";+import { usePrevious } from "react-use";++import { useDispatch, useSelector } from "metabase/redux";++import { closeSidebar, openCommentsSidebar } from "../documents.slice";+import { getSidebarMode } from "../selectors";++interface UseSyncCommentsSidebarParams {+ areCommentsOpen: boolean;+ onCloseComments: () => void;+}++export const useSyncCommentsSidebar = ({+ areCommentsOpen,+ onCloseComments,+}: UseSyncCommentsSidebarParams) => {+ const dispatch = useDispatch();+ const sidebarMode = useSelector(getSidebarMode);+ const wereCommentsOpen = usePrevious(areCommentsOpen);++ useEffect(() => {+ // comments opened in URL - sync to Redux sidebar state+ if (!wereCommentsOpen && areCommentsOpen) {+ dispatch(openCommentsSidebar());+ return;+ }++ // comments closed in URL - sync to Redux sidebar state+ if (wereCommentsOpen && !areCommentsOpen && sidebarMode === "comments") {+ dispatch(closeSidebar());+ return;+ }++ // a different sidebar opened - sync to URL by removing the "/comments" path+ if (areCommentsOpen && sidebarMode !== "comments") {+ onCloseComments();+ }+ }, [+ wereCommentsOpen,+ areCommentsOpen,+ dispatch,+ sidebarMode,+ onCloseComments,+ ]);+};diff --git a/frontend/src/metabase/documents/selectors.ts b/frontend/src/metabase/documents/selectors.tsindex cd2ffd2255f..b0ca3ce9010 100644--- a/frontend/src/metabase/documents/selectors.ts+++ b/frontend/src/metabase/documents/selectors.ts@@ -1,42 +1,70 @@import { createSelector } from "@reduxjs/toolkit";import type { State } from "metabase/redux/store";-import type { Card, CardId } from "metabase-types/api";+import type { Card, CardId, TimelineEventId } from "metabase-types/api";import { initialState } from "./documents.slice";+const EMPTY_TIMELINE_EVENT_IDS: TimelineEventId[] = [];+export const getDocumentsState = (state: State) =>state.documents || initialState;-export const getSelectedQuestionId = createSelector(+export const getSidebar = createSelector(getDocumentsState,- (documents): CardId | null => {- const { selectedEmbedIndex, cardEmbeds } = documents;- if (selectedEmbedIndex === null || !cardEmbeds[selectedEmbedIndex]) {- return null;- }- return cardEmbeds[selectedEmbedIndex].id;- },+ (documents) => documents.sidebar,);-export const getSidebarOpen = createSelector(- getDocumentsState,- (state) => state.selectedEmbedIndex !== null,+export const getSidebarMode = createSelector(+ getSidebar,+ (sidebar) => sidebar?.mode ?? null,+);++export const getIsSidebarOpen = createSelector(+ getSidebar,+ (sidebar) => sidebar !== null,);-export const getCommentSidebarOpen = createSelector(+export const getSelectedEmbedIndex = createSelector(+ getSidebar,+ (sidebar): number | null => {+ if (+ sidebar?.mode === "viz-settings" ||+ sidebar?.mode === "timeline-events"+ ) {+ return sidebar.embedIndex;+ }+ return null;+ },+);++export const getSelectedQuestionId = createSelector(getDocumentsState,- (state) => state.isCommentSidebarOpen,+ (documents): CardId | null => {+ const { sidebar, cardEmbeds } = documents;+ if (+ sidebar?.mode !== "viz-settings" &&+ sidebar?.mode !== "timeline-events"+ ) {+ return null;+ }+ return cardEmbeds[sidebar.embedIndex]?.id ?? null;+ },);export const getCardEmbeds = createSelector(getDocumentsState,- (documents) => documents?.cardEmbeds ?? [],+ (documents) => documents.cardEmbeds,);-export const getSelectedEmbedIndex = createSelector(- getDocumentsState,- (documents): number | null => documents.selectedEmbedIndex,+export const getSelectedCardEmbed = createSelector(+ [getCardEmbeds, getSelectedEmbedIndex],+ (cardEmbeds, selectedEmbedIndex) => {+ if (selectedEmbedIndex === null) {+ return null;+ }+ return cardEmbeds[selectedEmbedIndex];+ },);export const getCurrentDocument = createSelector(@@ -56,6 +84,17 @@ export const getDraftCardById = createSelector((draftCards, cardId) => draftCards[cardId],);+export const getDraftCardOriginalIds = createSelector(+ getDocumentsState,+ (documents) => documents?.draftCardOriginalIds ?? {},+);++/** Positive saved-card id a draft was forked from, if any. */+export const getDraftCardOriginalId = createSelector(+ [getDraftCardOriginalIds, (_state, draftId: number) => draftId],+ (originalIds, draftId): CardId | undefined => originalIds[draftId],+);+export const getCardWithDraft = createSelector([getDraftCards,@@ -91,7 +130,22 @@ export const getHasUnsavedChanges = createSelector((documents) => documents.hasUnsavedChanges,);-export const getIsHistorySidebarOpen = createSelector(- getDocumentsState,- (documents) => documents.isHistorySidebarOpen,+export const getSelectedTimelineEventIds = createSelector(+ getSidebar,+ (sidebar): TimelineEventId[] => {+ if (sidebar?.mode === "timeline-events") {+ return sidebar.selectedEventIds;+ }+ return EMPTY_TIMELINE_EVENT_IDS;+ },+);++export const getFocusedTimelineEventIds = createSelector(+ getSidebar,+ (sidebar): TimelineEventId[] | null => {+ if (sidebar?.mode === "timeline-events") {+ return sidebar.focusedEventIds;+ }+ return null;+ },);diff --git a/frontend/src/metabase/documents/utils/editorNodeUtils.ts b/frontend/src/metabase/documents/utils/editorNodeUtils.tsindex 49b772fb243..488c4bf83a4 100644--- a/frontend/src/metabase/documents/utils/editorNodeUtils.ts+++ b/frontend/src/metabase/documents/utils/editorNodeUtils.ts@@ -1,6 +1,6 @@import type { Node as ProseMirrorNode } from "@tiptap/pm/model";import type { EditorState } from "@tiptap/pm/state";-import type { Editor } from "@tiptap/react";+import type { Editor, JSONContent } from "@tiptap/react";/*** Updates a card embed node's ID in the ProseMirror editor@@ -43,3 +43,29 @@ export function updateCardEmbedNodeId(export const isMetabotBlock = (state: EditorState): boolean =>state.selection.$head.parent.type.name === "metabot";++// Commentable node types that existed before `_id` was required+const NODES_WITH_ID = new Set([+ "paragraph",+ "heading",+ "bulletList",+ "orderedList",+ "blockquote",+ "codeBlock",+ "cardEmbed",+ "supportingText",+]);++/**+ * Checks if a document needs a schema migration, in which case it should be considered dirty.+ * Commentable nodes need a persisted `_id` so comments can target them across reloads.+ */+export function doesDocumentNeedMigration(node: JSONContent): boolean {+ if (node.type && NODES_WITH_ID.has(node.type) && !node.attrs?._id) {+ return true;+ }+ if (node.content) {+ return node.content.some((child) => doesDocumentNeedMigration(child));+ }+ return false;+}diff --git a/frontend/src/metabase/documents/utils/editorNodeUtils.unit.spec.ts b/frontend/src/metabase/documents/utils/editorNodeUtils.unit.spec.tsnew file mode 100644index 00000000000..ff7c537d79f--- /dev/null+++ b/frontend/src/metabase/documents/utils/editorNodeUtils.unit.spec.ts@@ -0,0 +1,114 @@+import { doesDocumentNeedMigration } from "./editorNodeUtils";++describe("doesDocumentNeedMigration", () => {+ it("returns false for an empty doc", () => {+ expect(+ doesDocumentNeedMigration({+ type: "doc",+ content: [],+ }),+ ).toBe(false);+ });++ it("returns false when all commentable nodes have _id attributes", () => {+ expect(+ doesDocumentNeedMigration({+ type: "doc",+ content: [+ {+ type: "paragraph",+ attrs: { _id: "paragraph-1" },+ content: [{ type: "text", text: "Hello" }],+ },+ {+ type: "heading",+ attrs: { _id: "heading-1", level: 1 },+ content: [{ type: "text", text: "Title" }],+ },+ ],+ }),+ ).toBe(false);+ });++ it("returns true when a top-level paragraph is missing _id", () => {+ expect(+ doesDocumentNeedMigration({+ type: "doc",+ content: [+ {+ type: "paragraph",+ content: [{ type: "text", text: "Hello" }],+ },+ ],+ }),+ ).toBe(true);+ });++ it("returns true when a commentable list node is missing _id", () => {+ expect(+ doesDocumentNeedMigration({+ type: "doc",+ content: [+ {+ type: "bulletList",+ content: [+ {+ type: "listItem",+ content: [+ {+ type: "paragraph",+ attrs: { _id: "paragraph-1" },+ content: [{ type: "text", text: "Item" }],+ },+ ],+ },+ ],+ },+ ],+ }),+ ).toBe(true);+ });++ it("returns true when a nested commentable node is missing _id", () => {+ expect(+ doesDocumentNeedMigration({+ type: "doc",+ content: [+ {+ type: "blockquote",+ attrs: { _id: "blockquote-1" },+ content: [+ {+ type: "paragraph",+ content: [{ type: "text", text: "Quote" }],+ },+ ],+ },+ ],+ }),+ ).toBe(true);+ });++ it("returns true when a card embed is missing _id", () => {+ expect(+ doesDocumentNeedMigration({+ type: "doc",+ content: [+ {+ type: "cardEmbed",+ attrs: { id: 42 },+ },+ ],+ }),+ ).toBe(true);+ });++ it("returns false for text-only nodes", () => {+ expect(+ doesDocumentNeedMigration({+ type: "text",+ text: "Hello",+ }),+ ).toBe(false);+ });+});diff --git a/frontend/src/metabase/explorations/components/ExplorationSidebar/ExplorationSidebar.tsx b/frontend/src/metabase/explorations/components/ExplorationSidebar/ExplorationSidebar.tsxindex b1a53d86eba..4d8e2719049 100644--- a/frontend/src/metabase/explorations/components/ExplorationSidebar/ExplorationSidebar.tsx+++ b/frontend/src/metabase/explorations/components/ExplorationSidebar/ExplorationSidebar.tsx@@ -40,9 +40,11 @@ import {ExplorationTreeNode,} from "./ExplorationTreeNode";import {+ EXPLORATION_SUMMARY_TREE_ID,type ExplorationSidebarContentMode,type ExplorationSidebarTabsInfo,type ExplorationTreeNode as ExplorationTreeNodeDataType,+ type SelectedSidebarEntity,flattenTree,} from "./utils";@@ -52,8 +54,9 @@ interface ExplorationSidebarProps {selectedSidebarTab: ExplorationSidebarTab;getSelectedSidebarTabUrl: (tab: ExplorationSidebarTab) => string;tree: ITreeNodeItem<ExplorationTreeNodeDataType>[];- selectedPageId: ExplorationPageNodeId | null;+ selectedEntity: SelectedSidebarEntity | null;getSelectedPageUrl: (pageId: ExplorationPageNodeId) => string;+ getSelectedSummaryUrl: () => string;shouldScrollSelectionRef: React.MutableRefObject<boolean>;isOpen: boolean;readPageIds: ReadonlySet<string>;@@ -73,8 +76,9 @@ export function ExplorationSidebar({selectedSidebarTab,getSelectedSidebarTabUrl,tree,- selectedPageId,+ selectedEntity,getSelectedPageUrl,+ getSelectedSummaryUrl,shouldScrollSelectionRef,isOpen,readPageIds,@@ -88,9 +92,15 @@ export function ExplorationSidebar({onPrefetchPage,}: ExplorationSidebarProps) {const navigate = useNavigate();+ const selectedTreeId =+ selectedEntity?.type === "page"+ ? selectedEntity.id+ : selectedEntity?.type === "summary"+ ? EXPLORATION_SUMMARY_TREE_ID+ : undefined;const treeController = useTree({data: tree,- selectedId: selectedPageId ?? undefined,+ selectedId: selectedTreeId,freezeAutoExpandOnManualToggle: true,});@@ -106,17 +116,18 @@ export function ExplorationSidebar({// the tree to reveal the selected item. useTree's auto-expand is frozen// after a manual chevron toggle, so we bypass it here.useEffect(() => {- if (shouldScrollSelectionRef.current && selectedPageId) {+ if (shouldScrollSelectionRef.current && selectedTreeId) {setExpandedIds((prev) =>- new Set([...prev, ...getInitialExpandedIds(selectedPageId, tree)]),+ new Set([...prev, ...getInitialExpandedIds(selectedTreeId, tree)]),);}- }, [selectedPageId, shouldScrollSelectionRef, setExpandedIds, tree]);+ }, [selectedTreeId, shouldScrollSelectionRef, setExpandedIds, tree]);useEffect(() => {const handleKeyDown = (event: KeyboardEvent) => {- if (selectedPageId == null) {+ // Arrow keys skip the Summary (flattenTree is page-only).+ if (selectedEntity?.type !== "page") {return;}if (event.key !== "ArrowRight" && event.key !== "ArrowLeft") {@@ -126,10 +137,10 @@ export function ExplorationSidebar({return;}const direction = event.key === "ArrowRight" ? 1 : -1;- const nextItem = getAdjacentById(flatItems, selectedPageId, direction);+ const nextItem = getAdjacentById(flatItems, selectedEntity.id, direction);if (nextItem == null ||- nextItem.id === selectedPageId ||+ nextItem.id === selectedEntity.id ||nextItem.data?.type !== "page") {return;@@ -147,7 +158,9 @@ export function ExplorationSidebar({new Set([...prev, ...getInitialExpandedIds(nextItem.id, tree)]),);// if we moved into a different folder, collapse the previous folder- const currentItem = flatItems.find((item) => item.id === selectedPageId);+ const currentItem = flatItems.find(+ (item) => item.id === selectedEntity.id,+ );if (currentItem?.data?.parent_id &¤tItem.data.parent_id !== nextItem?.data?.parent_id@@ -160,9 +173,9 @@ export function ExplorationSidebar({}, [flatItems,tree,- selectedPageId,onPreviousPage,onNextPage,+ selectedEntity,setExpandedIds,collapse,exploration.id,@@ -176,6 +189,7 @@ export function ExplorationSidebar({onPrefetchPage,shouldScrollSelectionRef,getSelectedPageUrl,+ getSelectedSummaryUrl,readPageIds,}),[@@ -184,6 +198,7 @@ export function ExplorationSidebar({onPrefetchPage,shouldScrollSelectionRef,getSelectedPageUrl,+ getSelectedSummaryUrl,readPageIds,],);diff --git a/frontend/src/metabase/explorations/components/ExplorationSidebar/ExplorationSidebar.unit.spec.tsx b/frontend/src/metabase/explorations/components/ExplorationSidebar/ExplorationSidebar.unit.spec.tsxindex 23341707dd2..95786c8eee0 100644--- a/frontend/src/metabase/explorations/components/ExplorationSidebar/ExplorationSidebar.unit.spec.tsx+++ b/frontend/src/metabase/explorations/components/ExplorationSidebar/ExplorationSidebar.unit.spec.tsx@@ -157,8 +157,9 @@ describe("ExplorationSidebar", () => {selectedSidebarTab={selectedSidebarTab}getSelectedSidebarTabUrl={getSelectedSidebarTabUrl}tree={tree}- selectedPageId="2"+ selectedEntity={{ type: "page", id: "2" }}getSelectedPageUrl={(pageId) => `${path}/page/${pageId}`}+ getSelectedSummaryUrl={() => path}shouldScrollSelectionRef={{ current: false }}isOpenreadPageIds={readPageIds}@@ -519,8 +520,9 @@ describe("ExplorationSidebar", () => {selectedSidebarTab={selectedSidebarTab}getSelectedSidebarTabUrl={getSelectedSidebarTabUrl}tree={tree}- selectedPageId={String(REVENUE_PAGE_ID)}+ selectedEntity={{ type: "page", id: String(REVENUE_PAGE_ID) }}getSelectedPageUrl={() => path}+ getSelectedSummaryUrl={() => path}shouldScrollSelectionRef={shouldScrollSelectionRef}isOpenreadPageIds={new Set<string>()}@@ -628,8 +630,9 @@ describe("ExplorationSidebar", () => {selectedSidebarTab={selectedSidebarTab}getSelectedSidebarTabUrl={getSelectedSidebarTabUrl}tree={tree}- selectedPageId={selectedId}+ selectedEntity={{ type: "page", id: selectedId }}getSelectedPageUrl={() => path}+ getSelectedSummaryUrl={() => path}shouldScrollSelectionRef={shouldScrollSelectionRef}isOpenreadPageIds={new Set<string>()}@@ -1155,8 +1158,9 @@ describe("ExplorationSidebar", () => {selectedSidebarTab={selectedSidebarTab}getSelectedSidebarTabUrl={getSelectedSidebarTabUrl}tree={tree}- selectedPageId={String(PAGE_ID)}+ selectedEntity={{ type: "page", id: String(PAGE_ID) }}getSelectedPageUrl={() => path}+ getSelectedSummaryUrl={() => path}shouldScrollSelectionRef={shouldScrollSelectionRef}isOpenreadPageIds={new Set<string>()}diff --git a/frontend/src/metabase/explorations/components/ExplorationSidebar/ExplorationTreeNode.tsx b/frontend/src/metabase/explorations/components/ExplorationSidebar/ExplorationTreeNode.tsxindex 79d03a9f55e..996febb5efa 100644--- a/frontend/src/metabase/explorations/components/ExplorationSidebar/ExplorationTreeNode.tsx+++ b/frontend/src/metabase/explorations/components/ExplorationSidebar/ExplorationTreeNode.tsx@@ -49,7 +49,9 @@ import { ExplorationErrorMarker } from "./ExplorationErrorMarker";import { ExplorationLastActivity } from "./ExplorationLastActivity";import S from "./ExplorationTreeNode.module.css";import {+ EXPLORATION_SUMMARY_TREE_ID,type ExplorationHeadingKind,+ type ExplorationTreeDocument,type ExplorationTreeHeading,type ExplorationTreeNode,type ExplorationTreePage,@@ -72,6 +74,7 @@ export interface ExplorationTreeContextValue {onPrefetchPage: (pageId: ExplorationPageNodeId) => void;shouldScrollSelectionRef: React.MutableRefObject<boolean>;getSelectedPageUrl: (pageId: ExplorationPageNodeId) => string;+ getSelectedSummaryUrl: () => string;readPageIds: ReadonlySet<string>;}@@ -90,6 +93,9 @@ export function ExplorationTreeNode(props: TreeNodeProps<ExplorationTreeNode>) {if (isExplorationTreeHeadingProps(nodeProps)) {return <ExplorationTreeHeading {...nodeProps} />;}+ if (isExplorationTreeDocumentProps(nodeProps)) {+ return <ExplorationTreeDocumentItem {...nodeProps} />;+ }if (isExplorationTreeItemProps(nodeProps)) {return <ExplorationTreeItem {...nodeProps} />;}@@ -346,12 +352,67 @@ interface ExplorationTreeItemProps extends ExplorationTreeNodeProps {item: ITreeNodeItem<ExplorationTreePage>;}+interface ExplorationTreeDocumentItemProps extends ExplorationTreeNodeProps {+ item: ITreeNodeItem<ExplorationTreeDocument>;+}+function isExplorationTreeItemProps(props: ExplorationTreeNodeProps,): props is ExplorationTreeItemProps {return props.item.data?.type === "page";}+function isExplorationTreeDocumentProps(+ props: ExplorationTreeNodeProps,+): props is ExplorationTreeDocumentItemProps {+ return props.item.data?.type === "document";+}++function ExplorationTreeDocumentItem({+ item,+ isSelected,+ depth,+ shouldScrollSelectionRef,+ getSelectedSummaryUrl,+}: ExplorationTreeDocumentItemProps) {+ const itemRef = useRef<HTMLAnchorElement>(null);++ useEffect(() => {+ if (isSelected && shouldScrollSelectionRef.current) {+ itemRef.current?.scrollIntoView({+ block: "nearest",+ });+ shouldScrollSelectionRef.current = false;+ }+ }, [isSelected, shouldScrollSelectionRef]);++ const iconProps: IconProps = {+ color: isSelected ? "brand" : "icon-secondary",+ name: typeof item.icon === "string" ? item.icon : item.icon.name,+ };++ return (+ <ForwardRefLink+ ref={itemRef}+ to={getSelectedSummaryUrl()}+ role="treeitem"+ aria-selected={isSelected}+ className={cx(S.treeRow, {+ [S.treeRowSelected]: isSelected,+ [S.treeRowNested]: depth > 0,+ })}+ // custom css var used for tree styles+ style={{ "--tree-depth": depth } as React.CSSProperties}+ data-testid={`exploration-tree-item-${EXPLORATION_SUMMARY_TREE_ID}`}+ >+ <Icon {...iconProps} aria-label={t`Summary`} />+ <Ellipsified flex={1} size="md" lh="1rem" fw={500}>+ {item.name}+ </Ellipsified>+ </ForwardRefLink>+ );+}+function ExplorationTreeItem({item,isSelected,diff --git a/frontend/src/metabase/explorations/components/ExplorationSidebar/ExplorationTreeNode.unit.spec.tsx b/frontend/src/metabase/explorations/components/ExplorationSidebar/ExplorationTreeNode.unit.spec.tsxindex ea2b506d757..f12ffaad6ad 100644--- a/frontend/src/metabase/explorations/components/ExplorationSidebar/ExplorationTreeNode.unit.spec.tsx+++ b/frontend/src/metabase/explorations/components/ExplorationSidebar/ExplorationTreeNode.unit.spec.tsx@@ -806,8 +806,9 @@ describe("ExplorationTreeNode", () => {selectedSidebarTab={selectedSidebarTab}getSelectedSidebarTabUrl={getSelectedSidebarTabUrl}tree={getTree()}- selectedPageId={String(PAGE_ID)}+ selectedEntity={{ type: "page", id: String(PAGE_ID) }}getSelectedPageUrl={() => path}+ getSelectedSummaryUrl={() => path}shouldScrollSelectionRef={shouldScrollSelectionRef}isOpenreadPageIds={new Set<string>()}diff --git a/frontend/src/metabase/explorations/components/ExplorationSidebar/test-utils.tsx b/frontend/src/metabase/explorations/components/ExplorationSidebar/test-utils.tsxindex 596dbf308cd..f1e7115192a 100644--- a/frontend/src/metabase/explorations/components/ExplorationSidebar/test-utils.tsx+++ b/frontend/src/metabase/explorations/components/ExplorationSidebar/test-utils.tsx@@ -136,6 +136,7 @@ export function setup({const getSelectedPageUrl = (pageId: string) =>`${Urls.exploration(exploration.id)}/page/${encodeURIComponent(pageId)}`;+ const getSelectedSummaryUrl = () => Urls.explorationSummary(exploration.id);const explorationPath = Urls.exploration(exploration.id);const {@@ -157,8 +158,11 @@ export function setup({selectedSidebarTab={selectedSidebarTab}getSelectedSidebarTabUrl={getSelectedSidebarTabUrl}tree={displayTree}- selectedPageId={resolvedPageId}+ selectedEntity={+ resolvedPageId != null ? { type: "page", id: resolvedPageId } : null+ }getSelectedPageUrl={getSelectedPageUrl}+ getSelectedSummaryUrl={getSelectedSummaryUrl}shouldScrollSelectionRef={{ current: true }}isOpenreadPageIds={readPageIds}@@ -184,6 +188,7 @@ export function setup({onToggleShowHidden,onChangeSortOrder,getSelectedPageUrl,+ getSelectedSummaryUrl,exploration,};}diff --git a/frontend/src/metabase/explorations/components/ExplorationSidebar/utils.ts b/frontend/src/metabase/explorations/components/ExplorationSidebar/utils.tsindex 232f23d3db3..0e06fa42070 100644--- a/frontend/src/metabase/explorations/components/ExplorationSidebar/utils.ts+++ b/frontend/src/metabase/explorations/components/ExplorationSidebar/utils.ts@@ -7,6 +7,7 @@ import type { ExplorationSidebarTab } from "metabase/explorations/types";import type {Comment,Exploration,+ ExplorationDocument,ExplorationId,ExplorationPageNodeId,ExplorationQuery,@@ -27,6 +28,9 @@ import {type ExplorationSortOrder,} from "../../sidebar-preferences";+/** Stable tree id for the Summary document node prepended to the sidebar. */+export const EXPLORATION_SUMMARY_TREE_ID = "summary";+// Distinguishes the kinds of heading rows in the sidebar so each can carry its// own icon and reinforce where the user is in the investigation:// - "root": the initial investigation thread (the origin of everything)@@ -59,6 +63,10 @@ export interface ExplorationTreePage {hidden: boolean;}+export interface ExplorationTreeDocument {+ type: "document";+}+function isExplorationTreePage(node: ITreeNodeItem<ExplorationTreeNode>,): node is ITreeNodeItem<ExplorationTreePage> {@@ -90,7 +98,15 @@ export function isHiddenTreeItem(return isExplorationTreePage(node) && node.data?.hidden === true;}-export type ExplorationTreeNode = ExplorationTreePage | ExplorationTreeHeading;+export type ExplorationTreeItem = ExplorationTreePage | ExplorationTreeDocument;++export type ExplorationTreeNode = ExplorationTreeItem | ExplorationTreeHeading;++export type InitialSidebarEntity =+ | { type: "page"; id: ExplorationPageNodeId }+ | { type: "summary" };++export type SelectedSidebarEntity = InitialSidebarEntity;type TreeItemFilter = (treeItem: ITreeNodeItem<ExplorationTreeNode>) => boolean;@@ -113,6 +129,22 @@ function getHeadingHideState(nodes: ITreeNodeItem<ExplorationTreeNode>[]): {};}+function getSummaryDocumentNode(+ document: ExplorationDocument | null | undefined,+): ITreeNodeItem<ExplorationTreeDocument> | null {+ if (document == null) {+ return null;+ }+ return {+ id: EXPLORATION_SUMMARY_TREE_ID,+ name: document.name || t`Summary`,+ icon: "document",+ data: {+ type: "document",+ },+ };+}+export function getExplorationSidebarTree(exploration: Exploration,treeItemFilter: TreeItemFilter,@@ -213,7 +245,13 @@ export function getExplorationSidebarTree(}});- return pruneEmptyHeadings(topLevel, keepEmptyRestartableThreads);+ const pruned = pruneEmptyHeadings(topLevel, keepEmptyRestartableThreads);++ const summaryNode = getSummaryDocumentNode(exploration.document);+ if (summaryNode != null && treeItemFilter(summaryNode)) {+ return [summaryNode, ...pruned];+ }+ return pruned;}type PageKey = string;@@ -493,6 +531,10 @@ export function flattenTree();}+/**+ * Depth-first first page in the tree. Kept as a page-only walk so heading+ * "copy link" and similar callers never land on the Summary node.+ */export function pickInitialSidebarPage(nodes: ITreeNodeItem<ExplorationTreeNode>[],): ExplorationPageNodeId | null {@@ -589,6 +631,25 @@ export function getExplorationSidebarModel({return { tree, contentMode };}+/**+ * Initial sidebar selection. Prefer the Summary once it has been curated+ * (`is_placeholder === false`); otherwise fall back to the first page.+ */+export function pickInitialSidebarEntity(+ nodes: ITreeNodeItem<ExplorationTreeNode>[],+ document?: Pick<ExplorationDocument, "is_placeholder"> | null,+): InitialSidebarEntity | null {+ if (+ document != null &&+ !document.is_placeholder &&+ nodes.some((node) => node.data?.type === "document")+ ) {+ return { type: "summary" };+ }+ const pageId = pickInitialSidebarPage(nodes);+ return pageId != null ? { type: "page", id: pageId } : null;+}+export type ExplorationSidebarTabsInfo = Record<ExplorationSidebarTab,{diff --git a/frontend/src/metabase/explorations/components/ExplorationSidebar/utils.unit.spec.ts b/frontend/src/metabase/explorations/components/ExplorationSidebar/utils.unit.spec.tsindex f8842822472..4f03f1e7dad 100644--- a/frontend/src/metabase/explorations/components/ExplorationSidebar/utils.unit.spec.ts+++ b/frontend/src/metabase/explorations/components/ExplorationSidebar/utils.unit.spec.ts@@ -12,12 +12,14 @@ import { createMockComment } from "metabase-types/api/mocks/comment";import type { ExplorationTreeNode, ExplorationTreePage } from "./utils";import {+ EXPLORATION_SUMMARY_TREE_ID,getCompactRelativeTime,getExplorationSidebarModel,getExplorationSidebarTabsInfo,getExplorationSidebarTree,getShimmerDelayStyle,isHiddenTreeItem,+ pickInitialSidebarEntity,pickInitialSidebarPage,} from "./utils";@@ -74,6 +76,15 @@ function getAllPageIds(return ids;}+function hasSummaryNode(+ tree: ReturnType<typeof getExplorationSidebarTree>,+): boolean {+ return tree.some(+ (node) =>+ node.id === EXPLORATION_SUMMARY_TREE_ID || node.data?.type === "document",+ );+}+function getFilteredSidebarTree(exploration: ReturnType<typeof createExploration>,tab: keyof ReturnType<typeof getExplorationSidebarTabsInfo>,@@ -684,6 +695,73 @@ describe("pickInitialSidebarPage", () => {});});+describe("pickInitialSidebarEntity", () => {+ const METRIC_A_BLOCK_ID = 10;++ function treeWithSummary(isPlaceholder: boolean) {+ const done = createQuery({+ id: 3,+ name: "Done page",+ status: "done",+ interestingness_score: 0.2,+ });+ const exploration = createExploration({+ queries: [done],+ blocks: [+ createBlock({+ id: METRIC_A_BLOCK_ID,+ name: "Metric A",+ position: 0,+ pages: [+ createPage({+ id: 3,+ name: "Done page",+ position: 0,+ query_ids: [done.id],+ }),+ ],+ }),+ ],+ });+ exploration.document = {+ id: 99,+ name: "Summary",+ exploration_id: exploration.id,+ creator_id: 1,+ content_type: "application/json+vnd.prose-mirror",+ is_placeholder: isPlaceholder,+ created_at: "2026-01-01T00:00:00Z",+ updated_at: "2026-01-01T00:00:00Z",+ };+ return {+ tree: getExplorationSidebarTree(exploration, () => true),+ document: exploration.document,+ };+ }++ it("prefers Summary when is_placeholder is false", () => {+ const { tree, document } = treeWithSummary(false);+ expect(pickInitialSidebarEntity(tree, document)).toEqual({+ type: "summary",+ });+ });++ it("falls back to the first page while Summary is still a placeholder", () => {+ const { tree, document } = treeWithSummary(true);+ expect(pickInitialSidebarEntity(tree, document)).toEqual({+ type: "page",+ id: "3",+ });+ });++ it("prepends Summary as the first tree node", () => {+ const { tree } = treeWithSummary(true);+ expect(tree[0]?.data?.type).toBe("document");+ expect(tree[0]?.id).toBe(EXPLORATION_SUMMARY_TREE_ID);+ expect(tree[0]?.name).toBe("Summary");+ });+});+describe("getExplorationSidebarTree inherits a heading status from its pages", () => {const METRIC_BLOCK_ID = 10;@@ -945,6 +1023,73 @@ describe("getExplorationSidebarTabsInfo", () => {).toEqual([]);});});++ describe("summary document visibility", () => {+ function explorationWithSummary() {+ const exploration = createExploration({+ queries: [starredQuery, discussedQuery],+ blocks: [+ createBlock({+ id: BLOCK_ID,+ name: "Revenue",+ position: 0,+ pages: [+ createPage({+ id: STARRED_PAGE_ID,+ name: "Starred",+ position: 0,+ query_ids: [starredQuery.id],+ starred: true,+ }),+ createPage({+ id: DISCUSSED_PAGE_ID,+ name: "Discussed",+ position: 1,+ query_ids: [discussedQuery.id],+ }),+ ],+ }),+ ],+ });+ exploration.document = {+ id: 99,+ name: "Summary",+ exploration_id: exploration.id,+ creator_id: 1,+ content_type: "application/json+vnd.prose-mirror",+ is_placeholder: false,+ created_at: "2026-01-01T00:00:00Z",+ updated_at: "2026-01-01T00:00:00Z",+ };+ return exploration;+ }++ it("includes Summary on the All tab", () => {+ const tree = getFilteredSidebarTree(explorationWithSummary(), "all");+ expect(hasSummaryNode(tree)).toBe(true);+ expect(tree[0]?.id).toBe(EXPLORATION_SUMMARY_TREE_ID);+ });++ it("excludes Summary from the Stars tab", () => {+ const tree = getFilteredSidebarTree(explorationWithSummary(), "stars");+ expect(hasSummaryNode(tree)).toBe(false);+ expect(getAllPageIds(tree)).toEqual([String(STARRED_PAGE_ID)]);+ });++ it("excludes Summary from the Discussions tab", () => {+ const exploration = explorationWithSummary();+ const comments = [+ createMockComment({+ target_type: "exploration",+ target_id: exploration.id,+ child_target_id: String(DISCUSSED_PAGE_ID),+ }),+ ];+ const tree = getFilteredSidebarTree(exploration, "discussions", comments);+ expect(hasSummaryNode(tree)).toBe(false);+ expect(getAllPageIds(tree)).toEqual([String(DISCUSSED_PAGE_ID)]);+ });+ });});describe("hidden pages", () => {diff --git a/frontend/src/metabase/explorations/components/ExplorationSummary/ExplorationEditorHost.tsx b/frontend/src/metabase/explorations/components/ExplorationSummary/ExplorationEditorHost.tsxnew file mode 100644index 00000000000..374145373f7--- /dev/null+++ b/frontend/src/metabase/explorations/components/ExplorationSummary/ExplorationEditorHost.tsx@@ -0,0 +1,166 @@+import { useMemo, useState } from "react";++import { useUnresolvedCommentsCount } from "metabase/comments/hooks/use-unresolved-comments-count";+import {+ type DocumentEditorHost,+ documentEditorHost,+} from "metabase/documents/components/Editor/DocumentEditorHost";+import { useExplorationClickActionsMode } from "metabase/explorations/hooks/useExplorationClickActionsMode";+import { useExplorationCommentUrl } from "metabase/explorations/hooks/useExplorationCommentUrl";+import {+ getCurrentExploration,+ getHighlightedForChildTarget,+ getQueriesById,+} from "metabase/explorations/selectors";+import type { CommentDrafts } from "metabase/explorations/types";+import { useSelector } from "metabase/redux";+import type {+ CardEmbedSlotContext,+ CardEmbedSlots,+} from "metabase/rich_text_editing/tiptap/EditorHost";+import { navigate } from "metabase/router";+import { Box } from "metabase/ui";+import * as Urls from "metabase/urls";+import type { HighlightedObject } from "metabase/visualizations/types";+import type { ExplorationQueryId, Series } from "metabase-types/api";++import { resolveHighlightForSeries } from "../ExplorationVisualization/utils";+import {+ ExploreFilterPills,+ parseExploreFilterPills,+} from "../ExploreFilterPills";++// preserve the search params when navigating to CardEmbed's chart_href+function navigateToCardFromExploration(url: string) {+ return () => {+ const pathname = url.split("?")[0] ?? url;+ const destination = Urls.isExplorationUrl(pathname)+ ? Urls.explorationPathWithSearch(pathname, window.location.search)+ : url;+ navigate(destination);+ };+}++function useExplorationSummaryCommentUrl({+ childTargetId,+}: {+ childTargetId: string | null;+}) {+ return useExplorationCommentUrl({ childTargetId, view: "summary" });+}++function useUnresolvedExplorationCommentsCount(+ childTargetId: string,+ { skip = false }: { skip?: boolean } = {},+) {+ const exploration = useSelector(getCurrentExploration);+ const explorationId = exploration?.id;+ const { unresolvedCommentsCount } = useUnresolvedCommentsCount({+ target:+ explorationId != null+ ? {+ target_id: explorationId,+ target_type: "exploration",+ }+ : undefined,+ childTargetId,+ skip: skip || explorationId == null,+ });+ return unresolvedCommentsCount;+}++function parseHostQueryIds(+ hostData: Record<string, unknown> | null | undefined,+): ExplorationQueryId[] {+ const raw = hostData?.query_ids;+ if (+ !Array.isArray(raw) ||+ !raw.every((id): id is number => typeof id === "number")+ ) {+ return [];+ }+ return raw;+}++function useExplorationCardEmbedSlots({+ hostData,+}: CardEmbedSlotContext): CardEmbedSlots {+ return useMemo(() => {+ const filters = parseExploreFilterPills(hostData?.explore_filters);+ if (filters.length === 0) {+ return {};+ }+ return {+ belowTitle: (+ <Box mt="sm">+ <ExploreFilterPills filters={filters} />+ </Box>+ ),+ };+ }, [hostData]);+}++function useExplorationHighlighted(+ childTargetId: string,+ series: Series | null,+ hostData?: Record<string, unknown> | null,+): HighlightedObject | null {+ const highlightedCommentState = useSelector((state) =>+ getHighlightedForChildTarget(state, childTargetId),+ );+ const queriesById = useSelector(getQueriesById);+ const seriesQueryIds = useMemo(() => parseHostQueryIds(hostData), [hostData]);+ return useMemo(+ () =>+ resolveHighlightForSeries(+ highlightedCommentState,+ series ?? [],+ seriesQueryIds,+ queriesById,+ ),+ [highlightedCommentState, series, seriesQueryIds, queriesById],+ );+}++function useExplorationVisualizationMode({+ childTargetId,+ hostData,+}: {+ childTargetId: string;+ hostData?: Record<string, unknown> | null;+}) {+ const exploration = useSelector(getCurrentExploration);+ const queriesById = useSelector(getQueriesById);+ const seriesQueryIds = useMemo(() => parseHostQueryIds(hostData), [hostData]);+ const parsedPageId = Number(childTargetId);+ const [commentDrafts, setCommentDrafts] = useState<CommentDrafts>({});++ return useExplorationClickActionsMode({+ explorationId: exploration?.id,+ pageId: Number.isFinite(parsedPageId) ? parsedPageId : undefined,+ commentDrafts,+ setCommentDrafts,+ seriesQueryIds,+ queriesById,+ });+}++/**+ * Document editor host wired for an exploration Summary: comments resolve+ * against `target_type: "exploration"` so cardEmbeds (keyed by page id) and+ * prose blocks (keyed by `_id` uuid) share the exploration comment stream.+ */+export const explorationEditorHost: DocumentEditorHost = {+ ...documentEditorHost,+ capabilities: {+ canEmbedCharts: false,+ canUseMetabot: false,+ canOpenCardInQueryBuilder: false,+ },+ navigateToCard: navigateToCardFromExploration,+ useCommentUrl: useExplorationSummaryCommentUrl,+ useUnresolvedCommentsCount: useUnresolvedExplorationCommentsCount,+ useHighlighted: useExplorationHighlighted,+ useVisualizationMode: useExplorationVisualizationMode,+ useCardEmbedSlots: useExplorationCardEmbedSlots,+};diff --git a/frontend/src/metabase/explorations/components/ExplorationSummary/ExplorationEditorHost.unit.spec.tsx b/frontend/src/metabase/explorations/components/ExplorationSummary/ExplorationEditorHost.unit.spec.tsxnew file mode 100644index 00000000000..f0085c9403d--- /dev/null+++ b/frontend/src/metabase/explorations/components/ExplorationSummary/ExplorationEditorHost.unit.spec.tsx@@ -0,0 +1,34 @@+import { renderHook } from "@testing-library/react";++import { renderWithProviders, screen } from "__support__/ui";++import { explorationEditorHost } from "./ExplorationEditorHost";++describe("explorationEditorHost.useCardEmbedSlots", () => {+ it("renders explore filter pills from host_data.explore_filters", () => {+ const { result } = renderHook(() =>+ explorationEditorHost.useCardEmbedSlots({+ childTargetId: "12",+ hostData: {+ query_ids: [101],+ explore_filters: [{ display_value: "TX", dimension_name: "State" }],+ },+ }),+ );++ expect(result.current.belowTitle).toBeTruthy();+ renderWithProviders(<>{result.current.belowTitle}</>);+ expect(screen.getByTestId("filter-pill")).toHaveTextContent("State: TX");+ });++ it("returns no belowTitle when host_data has no explore_filters", () => {+ const { result } = renderHook(() =>+ explorationEditorHost.useCardEmbedSlots({+ childTargetId: "12",+ hostData: { query_ids: [101] },+ }),+ );++ expect(result.current.belowTitle).toBeUndefined();+ });+});diff --git a/frontend/src/metabase/explorations/components/ExplorationSummary/ExplorationSummary.module.css b/frontend/src/metabase/explorations/components/ExplorationSummary/ExplorationSummary.module.cssnew file mode 100644index 00000000000..3a3931d9572--- /dev/null+++ b/frontend/src/metabase/explorations/components/ExplorationSummary/ExplorationSummary.module.css@@ -0,0 +1,13 @@+.sidebar {+ height: 100%;+ width: 23rem;+ flex-shrink: 0;+ background-color: var(--mb-color-background-secondary);+ border-left: 1px solid var(--mb-color-border);+ overflow-y: auto;+}++.commentsSidebar {+ width: 23rem;+ border-left: 1px solid var(--mb-color-border);+}diff --git a/frontend/src/metabase/explorations/components/ExplorationSummary/ExplorationSummary.tsx b/frontend/src/metabase/explorations/components/ExplorationSummary/ExplorationSummary.tsxnew file mode 100644index 00000000000..7a43495d41d--- /dev/null+++ b/frontend/src/metabase/explorations/components/ExplorationSummary/ExplorationSummary.tsx@@ -0,0 +1,240 @@+import { useCallback, useEffect } from "react";+import { t } from "ttag";++import { EditableText } from "metabase/common/components/EditableText";+import { LeaveRouteConfirmModal } from "metabase/common/components/LeaveConfirmModal";+import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";+import { trackDocumentUpdated } from "metabase/documents/analytics";+import { DocumentRevisionHistorySidebar } from "metabase/documents/components/DocumentRevisionHistorySidebar";+import { Editor } from "metabase/documents/components/Editor";+import { EmbedQuestionSettingsSidebar } from "metabase/documents/components/EmbedQuestionSettingsSidebar";+import { EmbedTimelineSidebar } from "metabase/documents/components/EmbedTimelineSidebar";+import { DOCUMENT_TITLE_MAX_LENGTH } from "metabase/documents/constants";+import {+ closeSidebar,+ openHistorySidebar,+ setChildTargetId,+} from "metabase/documents/documents.slice";+import { useDocumentEditor } from "metabase/documents/hooks/use-document-editor";+import { useSyncCommentsSidebar } from "metabase/documents/hooks/use-sync-comments-sidebar";+import {+ getSelectedEmbedIndex,+ getSelectedQuestionId,+ getSidebarMode,+} from "metabase/documents/selectors";+import { useDispatch, useSelector } from "metabase/redux";+import {+ ActionIcon,+ Box,+ Button,+ Center,+ Group,+ Icon,+ Stack,+ Tooltip,+} from "metabase/ui";+import type {+ ExplorationDocument,+ ExplorationId,+ Timeline,+} from "metabase-types/api";++import { ExplorationComments } from "../ExplorationVisualization/ExplorationComments";++import { explorationEditorHost } from "./ExplorationEditorHost";+import S from "./ExplorationSummary.module.css";+import { ExplorationSummarySkeleton } from "./ExplorationSummarySkeleton";++interface ExplorationSummaryProps {+ document: ExplorationDocument;+ explorationId: ExplorationId;+ commentsChildTargetId?: string;+ onCloseCommentsSidebar: () => void;+ timelines?: Timeline[];+}++export function ExplorationSummary({+ document,+ explorationId,+ commentsChildTargetId,+ onCloseCommentsSidebar,+ timelines,+}: ExplorationSummaryProps) {+ const dispatch = useDispatch();++ useEffect(() => {+ dispatch(setChildTargetId(commentsChildTargetId));+ }, [commentsChildTargetId, dispatch]);++ const {+ editorInstance,+ setEditorInstance,+ editorContainerRef,+ isDocumentLoading,+ error,+ canWrite,+ isSaving,+ documentTitle,+ setDocumentTitle,+ documentData,+ documentContent,+ updateCardEmbeds,+ handleChange,+ showSaveButton,+ handleSave,+ handleQuestionSelect,+ } = useDocumentEditor({+ documentId: document.id,+ onDocumentUpdated: (document) =>+ trackDocumentUpdated(document, "exploration"),+ });++ const selectedQuestionId = useSelector(getSelectedQuestionId);+ const selectedEmbedIndex = useSelector(getSelectedEmbedIndex);+ const sidebarMode = useSelector(getSidebarMode);++ useSyncCommentsSidebar({+ areCommentsOpen: commentsChildTargetId != null,+ onCloseComments: onCloseCommentsSidebar,+ });++ const handleShowHistory = useCallback(() => {+ dispatch(openHistorySidebar());+ }, [dispatch]);++ if (error) {+ return (+ <Center w="100%" mih="20rem">+ <LoadingAndErrorWrapper error={error} />+ </Center>+ );+ }++ if (isDocumentLoading) {+ return <ExplorationSummarySkeleton />;+ }++ const showCommentsSidebar =+ sidebarMode === "comments" && commentsChildTargetId != null;++ return (+ <>+ <Box flex={1} h="100%" pb="3rem" pr="1rem">+ <Box bg="background-primary" bd="1px solid border" bdrs="md" h="100%">+ <Group gap={0} h="100%">+ <Stack+ h="100%"+ flex={1}+ p="lg"+ pr={sidebarMode != null ? "5rem" : "lg"}+ pt="3rem"+ gap={0}+ style={{ overflowY: "auto" }}+ >+ <Group h="2.5rem" w="100%" maw="42.5rem" mx="auto">+ <EditableText+ initialValue={documentTitle}+ onContentChange={setDocumentTitle}+ placeholder={t`Summary`}+ fw="bold"+ fz="h3"+ lh="h3"+ isDisabled={true}+ p={0}+ flex={1}+ maxLength={DOCUMENT_TITLE_MAX_LENGTH}+ />+ {showSaveButton && (+ <Button+ variant="filled"+ onClick={() => handleSave()}+ data-hide-on-print+ >{t`Save`}</Button>+ )}+ {documentData && (+ <Tooltip label={t`Revision history`}>+ <ActionIcon+ size="md"+ aria-label={t`Revision history`}+ onClick={handleShowHistory}+ data-hide-on-print+ >+ <Icon name="history" c="icon-primary" />+ </ActionIcon>+ </Tooltip>+ )}+ </Group>+ <Box w="100%" maw="42.5rem" mx="auto">+ <Editor+ placeholder={t`Document your research findings here. You can add interesting charts to this summary by clicking "Add to Summary" from the chart's page...`}+ hostOverride={explorationEditorHost}+ onEditorReady={setEditorInstance}+ onCardEmbedsChange={updateCardEmbeds}+ onQuestionSelect={handleQuestionSelect}+ initialContent={documentContent}+ onChange={handleChange}+ editable={canWrite && !isSaving}+ isLoading={isDocumentLoading}+ editorContainerRef={editorContainerRef}+ />+ </Box>+ </Stack>+ {showCommentsSidebar && (+ <Box+ h="100%"+ className={S.commentsSidebar}+ data-testid="exploration-summary-comments"+ >+ <ExplorationComments+ explorationId={explorationId}+ pageId={commentsChildTargetId}+ view="summary"+ onClose={onCloseCommentsSidebar}+ timelines={timelines}+ />+ </Box>+ )}+ {sidebarMode === "viz-settings" &&+ selectedQuestionId &&+ selectedEmbedIndex !== null &&+ editorInstance && (+ <Box className={S.sidebar} data-testid="document-card-sidebar">+ <EmbedQuestionSettingsSidebar+ cardId={selectedQuestionId}+ editorInstance={editorInstance}+ />+ </Box>+ )}+ {sidebarMode === "timeline-events" &&+ selectedQuestionId &&+ selectedEmbedIndex !== null &&+ editorInstance && (+ <Box+ className={S.sidebar}+ data-testid="document-timeline-sidebar"+ >+ <EmbedTimelineSidebar+ cardId={selectedQuestionId}+ selectedEmbedIndex={selectedEmbedIndex}+ editorInstance={editorInstance}+ collectionId={documentData?.collection_id ?? null}+ />+ </Box>+ )}+ </Group>+ </Box>+ </Box>++ <LeaveRouteConfirmModal isEnabled={showSaveButton} />++ {sidebarMode === "history" && documentData && (+ <Box data-testid="document-history-sidebar">+ <DocumentRevisionHistorySidebar+ document={documentData}+ onClose={() => dispatch(closeSidebar())}+ />+ </Box>+ )}+ </>+ );+}diff --git a/frontend/src/metabase/explorations/components/ExplorationSummary/ExplorationSummarySkeleton.tsx b/frontend/src/metabase/explorations/components/ExplorationSummary/ExplorationSummarySkeleton.tsxnew file mode 100644index 00000000000..3cba835f667--- /dev/null+++ b/frontend/src/metabase/explorations/components/ExplorationSummary/ExplorationSummarySkeleton.tsx@@ -0,0 +1,46 @@+import { Box, Skeleton, Stack } from "metabase/ui";++const SKELETON_LINE_WIDTHS = [+ "100%",+ "94%",+ "98%",+ "62%",+ "100%",+ "91%",+ "96%",+ "88%",+ "47%",+];++export function ExplorationSummarySkeleton() {+ return (+ <Stack+ data-testid="exploration-summary-skeleton"+ flex={1}+ h="100%"+ py="3rem"+ pr="3rem"+ align="center"+ style={{ overflowY: "auto" }}+ >+ <Stack+ flex={1}+ w="100%"+ bg="background-primary"+ bd="1px solid border"+ bdrs="md"+ p="lg"+ gap={0}+ >+ <Box h="2.5rem" w="100%" maw="42.5rem" mx="auto">+ <Skeleton h="1.5rem" w="45%" radius="sm" />+ </Box>+ <Stack w="100%" maw="42.5rem" mx="auto" mt="lg" gap="md">+ {SKELETON_LINE_WIDTHS.map((width, index) => (+ <Skeleton key={index} h="0.75rem" w={width} radius="sm" />+ ))}+ </Stack>+ </Stack>+ </Stack>+ );+}diff --git a/frontend/src/metabase/explorations/components/ExplorationSummary/index.ts b/frontend/src/metabase/explorations/components/ExplorationSummary/index.tsnew file mode 100644index 00000000000..b82a1e91294--- /dev/null+++ b/frontend/src/metabase/explorations/components/ExplorationSummary/index.ts@@ -0,0 +1,2 @@+export { ExplorationSummary } from "./ExplorationSummary";+export { ExplorationSummarySkeleton } from "./ExplorationSummarySkeleton";diff --git a/frontend/src/metabase/explorations/components/ExplorationVisualization/ActionToolbar.tsx b/frontend/src/metabase/explorations/components/ExplorationVisualization/ActionToolbar.tsxindex d8db844dad0..8ee56b88a14 100644--- a/frontend/src/metabase/explorations/components/ExplorationVisualization/ActionToolbar.tsx+++ b/frontend/src/metabase/explorations/components/ExplorationVisualization/ActionToolbar.tsx@@ -6,15 +6,17 @@ import {useMemo,useState,} from "react";-import { t } from "ttag";+import { c, t } from "ttag";import { useCreateCommentMutation } from "metabase/api/comment";import {+ useAppendChartToSummaryMutation,useSetPageStarredMutation,useSetPagesHiddenMutation,} from "metabase/api/exploration";import { ToolbarButton } from "metabase/common/components/ToolbarButton";import { useToast } from "metabase/common/hooks";+import { trackDocumentUpdated } from "metabase/documents/analytics";import {trackExplorationCommentCreated,trackExplorationPageHiddenToggled,@@ -35,6 +37,7 @@ import {Popover,Tooltip,} from "metabase/ui";+import { getTimelineEventSettings } from "metabase/visualizations/lib/settings/timelineEvents";import type {DocumentContent,ExplorationId,@@ -48,12 +51,16 @@ import type { CommentDrafts } from "../../types";import S from "./ActionToolbar.module.css";import { ExplorationCommentEditor } from "./ExplorationCommentEditor";+import type { ExplorationChartForDocumentEmbed } from "./utils";const TRIAGE_TOOLTIP_OPEN_DELAY = 500;interface ActionToolbarProps {explorationId: ExplorationId;page: ExplorationPageNode;+ charts: ExplorationChartForDocumentEmbed[];+ canAddToSummary: boolean;+ setSelectedSummary: (options?: { scrollIntoView?: boolean }) => void;commentDrafts: CommentDrafts;setCommentDrafts: Dispatch<SetStateAction<CommentDrafts>>;showTimelineDropdown: boolean;@@ -67,6 +74,9 @@ interface ActionToolbarProps {export function ActionToolbar({explorationId,page,+ charts,+ canAddToSummary,+ setSelectedSummary,commentDrafts,setCommentDrafts,showTimelineDropdown,@@ -78,8 +88,10 @@ export function ActionToolbar({}: ActionToolbarProps) {const [setPageStarred] = useSetPageStarredMutation();const [setPagesHidden] = useSetPagesHiddenMutation();+ const [appendChartToSummary] = useAppendChartToSummaryMutation();const [isCommentEditorOpen, setCommentEditorOpen] = useState(false);+ const [isAddToSummaryMenuOpen, setAddToSummaryMenuOpen] = useState(false);const [isMoreActionsOpen, setMoreActionsOpen] = useState(false);const [createComment] = useCreateCommentMutation();@@ -160,6 +172,55 @@ export function ActionToolbar({}}, [page.hidden, page.name, setHidden, sendToast, onNextPage]);+ const showAddToSummary = canAddToSummary && charts.length > 0;++ const handleAddToSummary = useCallback(+ async (chart: ExplorationChartForDocumentEmbed) => {+ const timelineSettings =+ selectedTimelineId != null+ ? getTimelineEventSettings(+ availableTimelines,+ (+ availableTimelines.find((t) => t.id === selectedTimelineId)+ ?.events ?? []+ ).map((event) => event.id),+ )+ : {};+ const { data: document, error } = await appendChartToSummary({+ explorationId,+ exploration_query_ids: chart.queryIds,+ display: chart.display,+ visualization_settings: {+ ...chart.visualization_settings,+ ...timelineSettings,+ },+ });+ if (error || !document) {+ sendToast({+ message: t`Failed to add to Summary`,+ icon: "warning_triangle_filled",+ iconColor: "warning",+ });+ return;+ }+ trackDocumentUpdated(document, "exploration");+ sendToast({+ message: c("{0} is the document name").t`Added to ${document.name}`,+ icon: "document",+ actionLabel: t`View`,+ action: () => setSelectedSummary({ scrollIntoView: true }),+ });+ },+ [+ appendChartToSummary,+ availableTimelines,+ explorationId,+ selectedTimelineId,+ sendToast,+ setSelectedSummary,+ ],+ );+const copyLink = useCopyLink();useEffect(() => {@@ -199,6 +260,15 @@ export function ActionToolbar({event.preventDefault();}+ if (event.key === "a" && showAddToSummary) {+ if (charts.length === 1) {+ handleAddToSummary(charts[0]);+ } else {+ setAddToSummaryMenuOpen(true);+ }+ event.preventDefault();+ }+if (event.key === "l") {copyLink(window.location.href);event.preventDefault();@@ -214,6 +284,10 @@ export function ActionToolbar({handleToggleStarred,handleToggleHidden,setCommentEditorOpen,+ showAddToSummary,+ charts,+ handleAddToSummary,+ setAddToSummaryMenuOpen,copyLink,]);@@ -347,6 +421,43 @@ export function ActionToolbar({/></Popover.Dropdown></Popover>+ {showAddToSummary &&+ (charts.length === 1 ? (+ <ToolbarButton+ icon="document"+ tooltipLabel={t`Add to Summary`}+ iconProps={{+ size: "1.125rem",+ }}+ onClick={() => handleAddToSummary(charts[0])}+ />+ ) : (+ <Menu+ position="top"+ opened={isAddToSummaryMenuOpen}+ onChange={setAddToSummaryMenuOpen}+ >+ <Menu.Target>+ <ToolbarButton+ icon="document"+ tooltipLabel={t`Add to Summary`}+ iconProps={{+ size: "1.125rem",+ }}+ />+ </Menu.Target>+ <Menu.Dropdown>+ {charts.map((chart) => (+ <Menu.Item+ key={chart.queryIds.join(",")}+ onClick={() => handleAddToSummary(chart)}+ >+ {chart.label}+ </Menu.Item>+ ))}+ </Menu.Dropdown>+ </Menu>+ ))}<Menuposition="top-end"offset={8}diff --git a/frontend/src/metabase/explorations/components/ExplorationVisualization/ActionToolbar.unit.spec.tsx b/frontend/src/metabase/explorations/components/ExplorationVisualization/ActionToolbar.unit.spec.tsxindex 7e8a789108c..2fe226245a0 100644--- a/frontend/src/metabase/explorations/components/ExplorationVisualization/ActionToolbar.unit.spec.tsx+++ b/frontend/src/metabase/explorations/components/ExplorationVisualization/ActionToolbar.unit.spec.tsx@@ -14,11 +14,15 @@ import type {Timeline,TimelineId,} from "metabase-types/api";-import { createMockTimeline } from "metabase-types/api/mocks";+import {+ createMockTimeline,+ createMockTimelineEvent,+} from "metabase-types/api/mocks";import { createMockComment } from "metabase-types/api/mocks/comment";import { createMockDocumentContent } from "metabase-types/api/mocks/document";import { ActionToolbar } from "./ActionToolbar";+import type { ExplorationChartForDocumentEmbed } from "./utils";const { trackSimpleEvent } = jest.requireMock("metabase/analytics");@@ -60,6 +64,8 @@ interface SetupOpts {selectedTimelineId?: TimelineId | null;showTimelineDropdown?: boolean;withUndos?: boolean;+ charts?: ExplorationChartForDocumentEmbed[];+ canAddToSummary?: boolean;onPreviousPage?: () => void;onNextPage?: () => void;}@@ -70,16 +76,22 @@ function setup({selectedTimelineId = null,showTimelineDropdown = true,withUndos = false,+ charts = [],+ canAddToSummary = false,onPreviousPage,onNextPage,}: SetupOpts = {}) {const onSelectTimelineId = jest.fn();const setCommentDrafts = jest.fn();+ const setSelectedSummary = jest.fn();renderWithProviders(<ActionToolbarexplorationId={EXPLORATION_ID}page={page}+ charts={charts}+ canAddToSummary={canAddToSummary}+ setSelectedSummary={setSelectedSummary}commentDrafts={{}}setCommentDrafts={setCommentDrafts}showTimelineDropdown={showTimelineDropdown}@@ -92,7 +104,13 @@ function setup({{ withUndos },);- return { onSelectTimelineId, setCommentDrafts, onPreviousPage, onNextPage };+ return {+ onSelectTimelineId,+ setCommentDrafts,+ setSelectedSummary,+ onPreviousPage,+ onNextPage,+ };}async function openTimelineMenu() {@@ -686,4 +704,148 @@ describe("ActionToolbar", () => {expect(await screen.findByText("Copied link")).toBeInTheDocument();});});++ describe("Add to Summary", () => {+ const chart: ExplorationChartForDocumentEmbed = {+ queryIds: [101],+ label: "Revenue",+ display: "line",+ visualization_settings: { "graph.split_panels": true },+ };++ it("is hidden when canAddToSummary is false", () => {+ setup({ charts: [chart], canAddToSummary: false });++ expect(+ screen.queryByRole("button", { name: "Add to Summary" }),+ ).not.toBeInTheDocument();+ });++ it("appends a single chart directly from the toolbar button", async () => {+ fetchMock.post(`path:/api/exploration/${EXPLORATION_ID}/summary/append`, {+ id: 9,+ name: "Summary",+ exploration_id: EXPLORATION_ID,+ });++ const { setSelectedSummary } = setup({+ charts: [chart],+ canAddToSummary: true,+ withUndos: true,+ });++ await userEvent.click(+ screen.getByRole("button", { name: "Add to Summary" }),+ );++ await waitFor(() => {+ const calls = fetchMock.callHistory.calls(+ `path:/api/exploration/${EXPLORATION_ID}/summary/append`,+ { method: "POST" },+ );+ expect(calls).toHaveLength(1);+ // Body is a JSON string from fetch-mock; parse to assert the payload.+ expect(JSON.parse(String(calls[0].options?.body))).toEqual({+ exploration_query_ids: [101],+ display: "line",+ visualization_settings: { "graph.split_panels": true },+ });+ });++ expect(await screen.findByText(/Added to/)).toBeInTheDocument();+ await userEvent.click(screen.getByRole("button", { name: "View" }));+ expect(setSelectedSummary).toHaveBeenCalledWith({ scrollIntoView: true });+ });++ it("seeds timeline selection into visualization_settings on append", async () => {+ fetchMock.post(`path:/api/exploration/${EXPLORATION_ID}/summary/append`, {+ id: 9,+ name: "Summary",+ exploration_id: EXPLORATION_ID,+ });++ const event = createMockTimelineEvent({+ id: 7,+ timeline_id: releases.id,+ });+ setup({+ charts: [chart],+ canAddToSummary: true,+ withUndos: true,+ timelines: [+ createMockTimeline({+ ...releases,+ events: [event],+ }),+ ],+ selectedTimelineId: releases.id,+ });++ await userEvent.click(+ screen.getByRole("button", { name: "Add to Summary" }),+ );++ await waitFor(() => {+ const calls = fetchMock.callHistory.calls(+ `path:/api/exploration/${EXPLORATION_ID}/summary/append`,+ { method: "POST" },+ );+ expect(calls).toHaveLength(1);+ expect(JSON.parse(String(calls[0].options?.body))).toEqual({+ exploration_query_ids: [101],+ display: "line",+ visualization_settings: {+ "graph.split_panels": true,+ "timeline.selected_timeline_ids": [releases.id],+ "timeline.excluded_timeline_event_ids": [],+ },+ });+ });+ });++ it("opens a chart picker menu for multi-chart pages", async () => {+ fetchMock.post(`path:/api/exploration/${EXPLORATION_ID}/summary/append`, {+ id: 9,+ name: "Summary",+ exploration_id: EXPLORATION_ID,+ });++ setup({+ charts: [+ chart,+ {+ queryIds: [201],+ label: "Sessions (US)",+ display: "map",+ visualization_settings: {},+ },+ ],+ canAddToSummary: true,+ });++ await userEvent.click(+ screen.getByRole("button", { name: "Add to Summary" }),+ );++ expect(+ await screen.findByRole("menuitem", { name: "Revenue" }),+ ).toBeInTheDocument();+ await userEvent.click(+ screen.getByRole("menuitem", { name: "Sessions (US)" }),+ );++ await waitFor(() => {+ const calls = fetchMock.callHistory.calls(+ `path:/api/exploration/${EXPLORATION_ID}/summary/append`,+ { method: "POST" },+ );+ expect(calls).toHaveLength(1);+ // Body is a JSON string from fetch-mock; parse to assert the payload.+ expect(JSON.parse(String(calls[0].options?.body))).toMatchObject({+ exploration_query_ids: [201],+ display: "map",+ });+ });+ });+ });});diff --git a/frontend/src/metabase/explorations/components/ExplorationVisualization/ExplorationComments.module.css b/frontend/src/metabase/explorations/components/ExplorationVisualization/ExplorationComments.module.cssindex dc5b3809171..c0bae3af406 100644--- a/frontend/src/metabase/explorations/components/ExplorationVisualization/ExplorationComments.module.css+++ b/frontend/src/metabase/explorations/components/ExplorationVisualization/ExplorationComments.module.css@@ -3,6 +3,23 @@overflow-anchor: none;}+.commentBadge {+ background-color: var(--mb-color-background-brand);++ &:hover {+ background-color: var(--mb-color-background-hover);+ }+}++.commentBadgeLabel {+ background-color: var(--mb-color-background-brand);+ cursor: default;+}++.commentTagArrow {+ transform: scaleY(-1);+}+/* User mentions (SmartLink user nodes) read as plain colored text here, not* bold — scoped so document comments keep their own styling. */.stream :global([data-type="smart-link"] > span) {diff --git a/frontend/src/metabase/explorations/components/ExplorationVisualization/ExplorationComments.tsx b/frontend/src/metabase/explorations/components/ExplorationVisualization/ExplorationComments.tsxindex db18a5adc84..84a29675fbb 100644--- a/frontend/src/metabase/explorations/components/ExplorationVisualization/ExplorationComments.tsx+++ b/frontend/src/metabase/explorations/components/ExplorationVisualization/ExplorationComments.tsx@@ -1,6 +1,11 @@import { useDisclosure, useWindowEvent } from "@mantine/hooks";import cx from "classnames";-import { type ReactNode, useEffect, useMemo, useRef } from "react";+import {+ type ComponentPropsWithoutRef,+ useEffect,+ useMemo,+ useRef,+} from "react";import { useLocation } from "react-use";import { t } from "ttag";import { noop } from "underscore";@@ -17,7 +22,6 @@ import { CommentEditor } from "metabase/comments/components";import DiscussionS from "metabase/comments/components/Discussion/Discussion.module.css";import { DiscussionActionPanel } from "metabase/comments/components/Discussion/DiscussionActionPanel";import { DiscussionReactions } from "metabase/comments/components/Discussion/DiscussionReactions";-import { useCommentUrl } from "metabase/comments/hooks/use-comment-url";import {formatCommentDate,getCommentNodeId,@@ -27,26 +31,44 @@ import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrimport { useToast } from "metabase/common/hooks";import { getUser } from "metabase/current-user";import { trackExplorationCommentCreated } from "metabase/explorations/analytics";-import { useSelector } from "metabase/redux";-import { Avatar, Box, Group, Stack, Text, Title, Tooltip } from "metabase/ui";+import { setHighlightedComment } from "metabase/explorations/explorations.slice";+import {+ type ExplorationCommentView,+ useExplorationCommentUrl,+} from "metabase/explorations/hooks/useExplorationCommentUrl";+import { useDispatch, useSelector } from "metabase/redux";+import {+ ActionIcon,+ Avatar,+ Box,+ Group,+ Icon,+ Stack,+ Text,+ Title,+ Tooltip,+ UnstyledButton,+} from "metabase/ui";import type {Comment,CommentContext,DocumentContent,ExplorationId,+ Timeline,+ TimelineId,} from "metabase-types/api";import S from "./ExplorationComments.module.css";-export type CommentTagsRenderer = (comment: Comment) => ReactNode;-interface ExplorationCommentsProps {explorationId: ExplorationId;pageId: string;+ view: ExplorationCommentView;context?: CommentContext;disableAutoFocus?: boolean;onClose: () => void;- renderCommentTags?: CommentTagsRenderer;+ timelines?: Timeline[];+ onSelectTimelineId?: (timelineId: TimelineId | null) => void;}const TOOLTIP_DATE_FORMAT = new Intl.DateTimeFormat(undefined, {@@ -57,11 +79,14 @@ const TOOLTIP_DATE_FORMAT = new Intl.DateTimeFormat(undefined, {export function ExplorationComments({explorationId,pageId,+ view,context,disableAutoFocus = false,onClose,- renderCommentTags,+ timelines = [],+ onSelectTimelineId,}: ExplorationCommentsProps) {+ const dispatch = useDispatch();const {data: commentsData,isLoading,@@ -141,6 +166,12 @@ export function ExplorationComments({};}, [commentsStream.length, hasHashTarget, hash]);+ useEffect(() => {+ return () => {+ dispatch(setHighlightedComment(null));+ };+ }, [dispatch, pageId]);+useWindowEvent("keydown", (event) => {if (event.key === "Escape" && !event.defaultPrevented) {onClose();@@ -174,9 +205,18 @@ export function ExplorationComments({return (<Stack gap={0} h="100%" data-testid="exploration-comments">- <Box px="lg" pt="1.25rem" pb="sm">+ <Group+ px="lg"+ pt="1.25rem"+ pb="sm"+ justify="space-between"+ align="center"+ ><Title order={3}>{t`Comments`}</Title>- </Box>+ <ActionIcon aria-label={t`Close`} onClick={onClose}>+ <Icon name="close" c="icon-primary" />+ </ActionIcon>+ </Group><Box ref={streamRef} flex={1} px="md" py="sm" className={S.stream}><Stack ref={streamContentRef} gap="md">{commentsStream.map((comment) => (@@ -184,14 +224,16 @@ export function ExplorationComments({key={comment.id}comment={comment}pageId={pageId}- renderCommentTags={renderCommentTags}+ view={view}+ timelines={timelines}+ onSelectTimelineId={onSelectTimelineId}/>))}</Stack></Box><Box px="lg" pb="lg" pt="xs" className={S.composer}><CommentEditor- autoFocus={commentsStream.length === 0 && !disableAutoFocus}+ autoFocus={!disableAutoFocus}data-testid="new-thread-editor"placeholder={t`Add a comment…`}onSubmit={handleSubmit}@@ -204,13 +246,17 @@ export function ExplorationComments({interface ExplorationCommentProps {comment: Comment;pageId: string;- renderCommentTags?: CommentTagsRenderer;+ view: ExplorationCommentView;+ timelines: Timeline[];+ onSelectTimelineId?: (timelineId: TimelineId | null) => void;}function ExplorationComment({comment,pageId,- renderCommentTags,+ view,+ timelines,+ onSelectTimelineId,}: ExplorationCommentProps) {const currentUser = useSelector(getUser);const [isEditing, editingHandler] = useDisclosure(false);@@ -218,7 +264,10 @@ function ExplorationComment({const [deleteComment] = useDeleteCommentMutation();const [toggleReaction] = useToggleReactionMutation();const [sendToast] = useToast();- const commentsUrl = useCommentUrl({ childTargetId: pageId });+ const commentsUrl = useExplorationCommentUrl({+ childTargetId: pageId,+ view,+ });const location = useLocation();const commentNodeId = getCommentNodeId(comment);@@ -340,11 +389,14 @@ function ExplorationComment({</Text></Tooltip></Group>- {renderCommentTags && (- <ErrorBoundary errorComponent={() => null}>- <CommentTags renderTags={renderCommentTags} comment={comment} />- </ErrorBoundary>- )}+ <ErrorBoundary errorComponent={() => null}>+ <CommentTags+ comment={comment}+ pageId={pageId}+ timelines={timelines}+ onSelectTimelineId={onSelectTimelineId}+ />+ </ErrorBoundary><Box><CommentEditorautoFocus@@ -368,14 +420,114 @@ function ExplorationComment({);}-// A component (rather than calling the renderer inline) so a throwing renderer-// is caught by the surrounding ErrorBoundary instead of crashing the comment.function CommentTags({- renderTags,comment,+ pageId,+ timelines,+ onSelectTimelineId,}: {- renderTags: CommentTagsRenderer;comment: Comment;+ pageId: string;+ timelines: Timeline[];+ onSelectTimelineId?: (timelineId: TimelineId | null) => void;}) {- return <>{renderTags(comment)}</>;+ const dispatch = useDispatch();+ const context = comment.context;++ // `highlight_label` is formatted by the client that created the comment, since only it knows+ // the chart's column settings; the server stores it verbatim and gates it with the rest of the+ // context, so an absent context here means the viewer is not allowed the values it carried.+ const highlightLabel = context?.highlight_label;+ const highlighted = context?.highlighted;+ const explorationQueryIds = context?.exploration_query_ids ?? [];+ const timelineId = context?.timeline_id ?? undefined;+ const timeline =+ timelineId != null+ ? timelines.find((entry) => entry.id === timelineId)+ : undefined;++ if (!highlightLabel && !timeline) {+ return null;+ }++ return (+ <Group gap="xs" wrap="wrap">+ <Icon+ name="corner_up_right"+ size={12}+ c="text-secondary"+ className={S.commentTagArrow}+ aria-hidden+ />+ {highlightLabel && (+ <CommentBadge+ label={highlightLabel}+ buttonProps={{+ onMouseEnter: () => {+ if (highlighted && explorationQueryIds.length > 0) {+ dispatch(+ setHighlightedComment({+ childTargetId: pageId,+ highlighted,+ explorationQueryIds,+ }),+ );+ }+ },+ onMouseLeave: () => dispatch(setHighlightedComment(null)),+ }}+ />+ )}+ {timeline &&+ (onSelectTimelineId != null ? (+ <CommentBadge+ label={timeline.name}+ buttonProps={{+ onClick: () => {+ onSelectTimelineId(timelineId ?? null);+ },+ }}+ />+ ) : (+ <CommentBadge label={timeline.name} />+ ))}+ </Group>+ );+}++interface CommentBadgeProps {+ label: string;+ buttonProps?: ComponentPropsWithoutRef<typeof UnstyledButton>;+}++function CommentBadge({ label, buttonProps }: CommentBadgeProps) {+ if (buttonProps == null) {+ return (+ <Text+ bdrs="md"+ py="xs"+ px="sm"+ fz="sm"+ c="text-primary"+ className={S.commentBadgeLabel}+ component="span"+ >+ {label}+ </Text>+ );+ }++ return (+ <UnstyledButton+ bdrs="md"+ py="xs"+ px="sm"+ fz="sm"+ c="text-primary"+ className={S.commentBadge}+ {...buttonProps}+ >+ {label}+ </UnstyledButton>+ );}diff --git a/frontend/src/metabase/explorations/components/ExplorationVisualization/ExplorationComments.unit.spec.tsx b/frontend/src/metabase/explorations/components/ExplorationVisualization/ExplorationComments.unit.spec.tsxindex c3a20f054c7..9b144ca84da 100644--- a/frontend/src/metabase/explorations/components/ExplorationVisualization/ExplorationComments.unit.spec.tsx+++ b/frontend/src/metabase/explorations/components/ExplorationVisualization/ExplorationComments.unit.spec.tsx@@ -8,10 +8,11 @@ import {waitFor,within,} from "__support__/ui";+import { getHighlightedComment } from "metabase/explorations/selectors";import { createMockState } from "metabase/redux/store/mocks";import { Route } from "metabase/router";-import type { Comment, CommentContext } from "metabase-types/api";-import { createMockUser } from "metabase-types/api/mocks";+import type { Comment, CommentContext, Timeline } from "metabase-types/api";+import { createMockTimeline, createMockUser } from "metabase-types/api/mocks";import { createMockComment } from "metabase-types/api/mocks/comment";import { createMockDocumentContent } from "metabase-types/api/mocks/document";@@ -66,25 +67,35 @@ function commentWithText(text: string, comment?: Partial<Comment>): Comment {interface SetupOpts {comments?: Comment[];context?: CommentContext;- renderCommentTags?: (comment: Comment) => React.ReactNode;+ timelines?: Timeline[];+ onSelectTimelineId?: (timelineId: number | null) => void;+ pageId?: string;}-function setup({ comments = [], context, renderCommentTags }: SetupOpts = {}) {+function setup({+ comments = [],+ context,+ timelines = [],+ onSelectTimelineId,+ pageId = PAGE_ID,+}: SetupOpts = {}) {fetchMock.get("path:/api/comment", { comments });fetchMock.post("path:/api/comment", 200);const onClose = jest.fn();- renderWithProviders(+ const view = renderWithProviders(<Routepath="*"element={<ExplorationCommentsexplorationId={EXPLORATION_ID}- pageId={PAGE_ID}+ pageId={pageId}+ view="page"context={context}onClose={onClose}- renderCommentTags={renderCommentTags}+ timelines={timelines}+ onSelectTimelineId={onSelectTimelineId}/>}/>,@@ -97,7 +108,7 @@ function setup({ comments = [], context, renderCommentTags }: SetupOpts = {}) {},);- return { onClose };+ return { onClose, store: view.store };}describe("ExplorationComments", () => {@@ -202,20 +213,122 @@ describe("ExplorationComments", () => {});});- it("renders metadata tags between the author line and the comment body", async () => {+ it("renders highlight and timeline badges between the author line and the comment body", async () => {setup({- comments: [commentWithText("Tagged comment", { id: 1 })],- renderCommentTags: () => (- <div data-testid="comment-tag">Marketing Events, on Sunday</div>- ),+ comments: [+ commentWithText("Tagged comment", {+ id: 1,+ context: {+ highlight_label: "Gadget, EU",+ exploration_query_ids: [102],+ highlighted: {+ dimensions: [{ columnName: "category", value: "Gadget" }],+ },+ timeline_id: 42,+ },+ }),+ ],+ timelines: [createMockTimeline({ id: 42, name: "Releases" })],+ onSelectTimelineId: jest.fn(),});const row = await screen.findByTestId("discussion-comment");- const tag = within(row).getByTestId("comment-tag");+ const highlightBadge = within(row).getByRole("button", {+ name: "Gadget, EU",+ });+ const timelineBadge = within(row).getByRole("button", { name: "Releases" });const body = within(row).getByText("Tagged comment");expect(- tag.compareDocumentPosition(body) & Node.DOCUMENT_POSITION_FOLLOWING,+ highlightBadge.compareDocumentPosition(body) &+ Node.DOCUMENT_POSITION_FOLLOWING,).toBeTruthy();+ expect(timelineBadge).toBeInTheDocument();+ });++ it("dispatches highlightedComment on highlight badge hover", async () => {+ const { store } = setup({+ comments: [+ commentWithText("Hover me", {+ id: 1,+ context: {+ highlight_label: "Gadget",+ exploration_query_ids: [101],+ highlighted: {+ dimensions: [{ columnName: "category", value: "Gadget" }],+ },+ },+ }),+ ],+ });++ const badge = await screen.findByRole("button", { name: "Gadget" });+ fireEvent.mouseEnter(badge);++ expect(getHighlightedComment(store.getState())).toEqual({+ childTargetId: PAGE_ID,+ explorationQueryIds: [101],+ highlighted: {+ dimensions: [{ columnName: "category", value: "Gadget" }],+ },+ });++ fireEvent.mouseLeave(badge);+ expect(getHighlightedComment(store.getState())).toBeNull();+ });++ it("calls onSelectTimelineId when a timeline badge is clicked", async () => {+ const onSelectTimelineId = jest.fn();+ setup({+ comments: [+ commentWithText("Timeline", {+ id: 1,+ context: { timeline_id: 42 },+ }),+ ],+ timelines: [createMockTimeline({ id: 42, name: "Releases" })],+ onSelectTimelineId,+ });++ await userEvent.click(+ await screen.findByRole("button", { name: "Releases" }),+ );++ expect(onSelectTimelineId).toHaveBeenCalledWith(42);+ });++ it("renders the timeline badge as a plain label when onSelectTimelineId is omitted", async () => {+ setup({+ comments: [+ commentWithText("Timeline", {+ id: 1,+ context: { timeline_id: 42 },+ }),+ ],+ timelines: [createMockTimeline({ id: 42, name: "Releases" })],+ });++ expect(await screen.findByText("Releases")).toBeInTheDocument();+ expect(+ screen.queryByRole("button", { name: "Releases" }),+ ).not.toBeInTheDocument();+ });++ it("renders no tags and does not throw when the child target is a prose uuid", async () => {+ const proseId = "a1b2c3d4-e5f6-7890-abcd-ef1234567890";+ setup({+ pageId: proseId,+ comments: [+ commentWithText("Prose note", {+ id: 1,+ child_target_id: proseId,+ context: {},+ }),+ ],+ });++ expect(await screen.findByText("Prose note")).toBeInTheDocument();+ // No highlight/timeline tags — only the action-panel chrome buttons remain.+ expect(screen.queryByText("Gadget")).not.toBeInTheDocument();});it("keeps reactions on stream comments", async () => {diff --git a/frontend/src/metabase/explorations/components/ExplorationVisualization/ExplorationGroupVisualization.module.css b/frontend/src/metabase/explorations/components/ExplorationVisualization/ExplorationGroupVisualization.module.cssindex 799e2e09ab3..0f4781b67a2 100644--- a/frontend/src/metabase/explorations/components/ExplorationVisualization/ExplorationGroupVisualization.module.css+++ b/frontend/src/metabase/explorations/components/ExplorationVisualization/ExplorationGroupVisualization.module.css@@ -43,15 +43,3 @@.commentsSidebar {border-left: 1px solid var(--mb-color-border-neutral);}--.commentBadge {- background-color: var(--mb-color-background-brand);-- &:hover {- background-color: var(--mb-color-background-hover);- }-}--.commentTagArrow {- transform: scaleY(-1);-}diff --git a/frontend/src/metabase/explorations/components/ExplorationVisualization/ExplorationGroupVisualization.tsx b/frontend/src/metabase/explorations/components/ExplorationVisualization/ExplorationGroupVisualization.tsxindex aa7e19721c0..388fda445cd 100644--- a/frontend/src/metabase/explorations/components/ExplorationVisualization/ExplorationGroupVisualization.tsx+++ b/frontend/src/metabase/explorations/components/ExplorationVisualization/ExplorationGroupVisualization.tsx@@ -1,4 +1,4 @@-import type { ComponentPropsWithoutRef, Dispatch, SetStateAction } from "react";+import type { Dispatch, SetStateAction } from "react";import { useCallback, useEffect, useMemo, useState } from "react";import { shallowEqual } from "react-redux";import { t } from "ttag";@@ -18,20 +18,17 @@ import {type IconProps,Stack,Text,- UnstyledButton,} from "metabase/ui";import { is403Error } from "metabase/utils/errors";import { isCartesianChart } from "metabase/visualizations";import Visualization from "metabase/visualizations/components/Visualization";import { LEGEND_ITEM_FONT_SIZE } from "metabase/visualizations/components/legend/LegendItem.styled";-import { getComputedSettingsForSeries } from "metabase/visualizations/lib/settings/visualization";import type {ClickActionsMode,HighlightedObject,OnBrush,} from "metabase/visualizations/types";import type {- Comment,ExplorationBlockNodeType,ExplorationId,ExplorationPageNode,@@ -46,6 +43,7 @@ import type {import { isSettledExplorationQueryStatus } from "metabase-types/api";import { useExplorationClickActionsMode } from "../../hooks/useExplorationClickActionsMode";+import { getHighlightedForChildTarget } from "../../selectors";import type { CommentDrafts } from "../../types";import { ActionToolbar } from "./ActionToolbar";@@ -57,8 +55,8 @@ import { TimelineEventsSidebar } from "./TimelineEventsSidebar";import {type LegendItem,buildSeriesGroup,- getCommentLabel,- getHighlightedWithShouldShowTooltip,+ composeChartsForGroup,+ resolveHighlightForSeries,} from "./utils";interface ExplorationGroupVisualizationProps {@@ -76,6 +74,8 @@ interface ExplorationGroupVisualizationProps {isCommentsSidebarOpen: boolean;wasCommentsSidebarOpen: boolean;onCloseCommentsSidebar: () => void;+ canAddToSummary?: boolean;+ setSelectedSummary: (options?: { scrollIntoView?: boolean }) => void;onPreviousPage?: () => void;onNextPage?: () => void;}@@ -90,15 +90,8 @@ export function ExplorationGroupVisualization(const groupName = props.page.long_name ?? props.page.name ?? "";return (- <Stack flex={1} h="100%" pb="3rem" pr="1rem" align="center">- <Box- flex={1}- w="100%"- bg="background-primary"- bd="1px solid border"- bdrs="md"- h="100%"- >+ <Box flex={1} h="100%" pb="3rem" pr="1rem">+ <Box bg="background-primary" bd="1px solid border" bdrs="md" h="100%"><ErrorBoundaryerrorComponent={() => (<Message@@ -111,7 +104,7 @@ export function ExplorationGroupVisualization(<ExplorationGroupVisualizationBody groupName={groupName} {...props} /></ErrorBoundary></Box>- </Stack>+ </Box>);}@@ -173,11 +166,19 @@ function ExplorationGroupVisualizationChart({isCommentsSidebarOpen,wasCommentsSidebarOpen,onCloseCommentsSidebar,+ canAddToSummary = false,+ setSelectedSummary,onPreviousPage,onNextPage,}: ExplorationGroupVisualizationWithGroupNameProps) {const dispatch = useDispatch();+ const queryIds = useMemo(() => queries.map((q) => q.id), [queries]);+ const queriesById = useMemo(+ () => Object.fromEntries(queries.map((query) => [query.id, query])),+ [queries],+ );+const clickActionsMode = useExplorationClickActionsMode({explorationId,pageId: page.id,@@ -185,9 +186,11 @@ function ExplorationGroupVisualizationChart({queryType: queries[0].query_type,commentDrafts,setCommentDrafts,+ seriesQueryIds: queryIds,+ queriesById,});- const queryIds = useMemo(() => queries.map((q) => q.id), [queries]);+ const pageChildTargetId = String(page.id);useEffect(() => {const subscriptions = queryIds.map((id) =>@@ -235,6 +238,13 @@ function ExplorationGroupVisualizationChart({// eslint-disable-next-line react-hooks/exhaustive-deps}, [queries, ...datasets]);+ const chartsForSummary = useMemo(() => {+ if (!seriesGroup) {+ return [];+ }+ return composeChartsForGroup(seriesGroup);+ }, [seriesGroup]);+const showTimelineDropdown = useMemo(() => {return (seriesGroup?.isTimeseries &&@@ -244,16 +254,18 @@ function ExplorationGroupVisualizationChart({);}, [seriesGroup, availableTimelines]);- const computedSettings = useMemo(- () =>- seriesGroup- ? getComputedSettingsForSeries(seriesGroup.series)- : undefined,- [seriesGroup],+ const highlightedCommentState = useSelector((state) =>+ getHighlightedForChildTarget(state, pageChildTargetId),);-- const [highlighted, setHighlighted] = useState<HighlightedObject | null>(- null,+ const highlighted = useMemo(+ () =>+ resolveHighlightForSeries(+ highlightedCommentState,+ seriesGroup?.series ?? [],+ seriesGroup?.queryIds ?? [],+ queriesById,+ ),+ [highlightedCommentState, seriesGroup, queriesById],);const [seeAllEvents, setSeeAllEvents] = useState<TimelineEvent[]>([]);@@ -280,79 +292,6 @@ function ExplorationGroupVisualizationChart({[onCloseCommentsSidebar],);- const renderCommentTags = useCallback(- (comment: Comment) => {- const context = comment.context;-- const commentHighlight = getHighlightedWithShouldShowTooltip(- // comment context is an untyped JSON blob; `highlighted` is written by- // us as a HighlightedObject when the comment captures a chart point- context?.highlighted as HighlightedObject | undefined,- seriesGroup,- );- const commentLabel = getCommentLabel(- commentHighlight,- seriesGroup,- computedSettings,- );-- const timelineId =- typeof context?.timeline_id === "number"- ? context.timeline_id- : undefined;- const timeline =- timelineId != null- ? availableTimelines.find((t) => t.id === timelineId)- : undefined;-- if (!commentLabel && !timeline) {- return null;- }-- return (- <Group gap="xs" wrap="wrap">- <Icon- name="corner_up_right"- size={12}- c="text-secondary"- className={S.commentTagArrow}- aria-hidden- />- {commentLabel && (- <CommentBadge- label={commentLabel}- buttonProps={{- onMouseEnter: () => {- if (commentHighlight) {- setHighlighted(commentHighlight);- }- },- onMouseLeave: () => setHighlighted(null),- }}- />- )}- {timeline && (- <CommentBadge- label={timeline.name}- buttonProps={{- onClick: () => {- onSelectTimelineId(timelineId ?? null);- },- }}- />- )}- </Group>- );- },- [- availableTimelines,- computedSettings,- onSelectTimelineId,- setHighlighted,- seriesGroup,- ],- );-if (!seriesGroup) {if (datasetError) {if (is403Error(datasetError)) {@@ -430,6 +369,9 @@ function ExplorationGroupVisualizationChart({<ActionToolbarexplorationId={explorationId}page={page}+ charts={chartsForSummary}+ canAddToSummary={canAddToSummary}+ setSelectedSummary={setSelectedSummary}commentDrafts={commentDrafts}setCommentDrafts={setCommentDrafts}showTimelineDropdown={showTimelineDropdown ?? false}@@ -454,12 +396,14 @@ function ExplorationGroupVisualizationChart({// so we only allow autofocus if the sidebar is truly opening, not just remountingdisableAutoFocus={wasCommentsSidebarOpen}explorationId={explorationId}- pageId={String(page.id)}+ pageId={pageChildTargetId}+ view="page"onClose={onCloseCommentsSidebar}context={{timeline_id: selectedTimelineId ?? undefined,}}- renderCommentTags={renderCommentTags}+ timelines={availableTimelines}+ onSelectTimelineId={onSelectTimelineId}/></Box>)}@@ -661,24 +605,3 @@ function Message({ groupName, message, iconProps }: MessageProps) {</Stack>);}--interface CommentBadgeProps {- label: string;- buttonProps?: ComponentPropsWithoutRef<typeof UnstyledButton>;-}--function CommentBadge({ label, buttonProps }: CommentBadgeProps) {- return (- <UnstyledButton- bdrs="md"- py="xs"- px="sm"- fz="sm"- c="text-primary"- className={S.commentBadge}- {...buttonProps}- >- {label}- </UnstyledButton>- );-}diff --git a/frontend/src/metabase/explorations/components/ExplorationVisualization/ExplorationGroupVisualization.unit.spec.tsx b/frontend/src/metabase/explorations/components/ExplorationVisualization/ExplorationGroupVisualization.unit.spec.tsxindex 3316e1fd2bb..ab8aa857222 100644--- a/frontend/src/metabase/explorations/components/ExplorationVisualization/ExplorationGroupVisualization.unit.spec.tsx+++ b/frontend/src/metabase/explorations/components/ExplorationVisualization/ExplorationGroupVisualization.unit.spec.tsx@@ -2,19 +2,13 @@ import { act } from "@testing-library/react";import userEvent from "@testing-library/user-event";import { useState } from "react";-import {- fireEvent,- renderWithProviders,- screen,- waitFor,- within,-} from "__support__/ui";+import { renderWithProviders, screen, waitFor, within } from "__support__/ui";+import { setHighlightedComment } from "metabase/explorations/explorations.slice";import { createPage, createQuery } from "metabase/explorations/test-utils";import { Route } from "metabase/router";import { registerVisualizations } from "metabase/visualizations/register";import type { ClickObject } from "metabase/visualizations/types";import type {- Comment,Dataset,ExplorationBlockNodeType,ExplorationPageNode,@@ -30,7 +24,6 @@ import {createMockTimeline,createMockTimelineEvent,} from "metabase-types/api/mocks";-import { createMockComment } from "metabase-types/api/mocks/comment";import { ExplorationGroupVisualization } from "./ExplorationGroupVisualization";@@ -57,9 +50,6 @@ const sampleClickObject: ClickObject = {cardId: 101,};-let mockComments: Comment[] = [- createMockComment({ id: 1, context: { timeline_id: 42 } }),-];let lastVisualizationProps: Record<string, unknown> | undefined;let visualizationCommitCount = 0;@@ -90,11 +80,9 @@ jest.mock("metabase/visualizations/components/Visualization", () => {jest.mock("./ExplorationComments", () => ({ExplorationComments: ({- renderCommentTags,disableAutoFocus,onClose,}: {- renderCommentTags?: (comment: Comment) => React.ReactNode;disableAutoFocus?: boolean;onClose?: () => void;}) => (@@ -103,9 +91,6 @@ jest.mock("./ExplorationComments", () => ({data-disable-autofocus={disableAutoFocus ? "true" : "false"}><button data-testid="comments-stub-close" onClick={onClose} />- {mockComments.map((comment) => (- <div key={comment.id}>{renderCommentTags?.(comment)}</div>- ))}</div>),}));@@ -148,6 +133,7 @@ jest.mock("metabase/api/exploration", () => ({useSetPageStarredMutation: () => [mockMutationTrigger()],useSetPagesHiddenMutation: () => [mockMutationTrigger()],useExploreFurtherMutation: () => [mockMutationTrigger()],+ useAppendChartToSummaryMutation: () => [mockMutationTrigger()],}));jest.mock("metabase/api/comment", () => ({@@ -292,6 +278,7 @@ function setup({isCommentsSidebarOpen={isCommentsSidebarOpen}wasCommentsSidebarOpen={wasCommentsSidebarOpen}onCloseCommentsSidebar={onCloseCommentsSidebar}+ setSelectedSummary={jest.fn()}/>}/>,@@ -325,7 +312,6 @@ function captureSeeAllEvents(): (events: TimelineEvent[]) => void {describe("ExplorationGroupVisualization", () => {beforeEach(() => {- mockComments = [createMockComment({ id: 1, context: { timeline_id: 42 } })];lastVisualizationProps = undefined;visualizationCommitCount = 0;});@@ -613,6 +599,7 @@ describe("ExplorationGroupVisualization", () => {isCommentsSidebarOpen={commentsOpen}wasCommentsSidebarOpen={false}onCloseCommentsSidebar={jest.fn()}+ setSelectedSummary={jest.fn()}/></>);@@ -736,78 +723,38 @@ describe("ExplorationGroupVisualization", () => {);});- it("calls onSelectTimelineId when a comment timeline badge is clicked", async () => {- const onSelectTimelineId = jest.fn();- setup({+ it("resolves highlightedComment from redux onto the visualization", () => {+ const { store } = setup({...timeseriesSetup,isCommentsSidebarOpen: true,- onSelectTimelineId,});- await userEvent.click(screen.getByRole("button", { name: "Releases" }));-- expect(onSelectTimelineId).toHaveBeenCalledWith(42);- });-- it("renders filter and timeline badges together", () => {- mockComments = [- createMockComment({- id: 1,- context: {- timeline_id: 42,+ act(() => {+ store.dispatch(+ setHighlightedComment({+ childTargetId: "1",+ explorationQueryIds: [101],highlighted: {- cardId: 101,columnName: "count",dimensions: [{ columnName: "ts", value: "2025-01-01" }],},- },- }),- ];-- setup({- ...timeseriesSetup,- isCommentsSidebarOpen: true,- });-- expect(- screen.getByRole("button", { name: "Releases" }),- ).toBeInTheDocument();- expect(screen.getByRole("button", { name: /Jan/ })).toBeInTheDocument();- });-- it("sets highlighted on the visualization when hovering the filter badge", async () => {- mockComments = [- createMockComment({- id: 1,- context: {- highlighted: {- cardId: 101,- columnName: "count",- dimensions: [{ columnName: "ts", value: "2025-01-01" }],- },- },- }),- ];-- setup({- ...timeseriesSetup,- isCommentsSidebarOpen: true,+ }),+ );});- const filterBadge = screen.getByRole("button", { name: /Jan/ });- fireEvent.mouseEnter(filterBadge);-expect(screen.getByTestId("visualization-stub")).toHaveAttribute("data-highlighted",JSON.stringify({- cardId: 101,columnName: "count",dimensions: [{ columnName: "ts", value: "2025-01-01" }],+ cardId: 101,shouldShowTooltip: true,}),);- fireEvent.mouseLeave(filterBadge);+ act(() => {+ store.dispatch(setHighlightedComment(null));+ });expect(screen.getByTestId("visualization-stub")).toHaveAttribute("data-highlighted","null",diff --git a/frontend/src/metabase/explorations/components/ExplorationVisualization/ExplorationVisualizationHeader.tsx b/frontend/src/metabase/explorations/components/ExplorationVisualization/ExplorationVisualizationHeader.tsxindex d6247ebd391..59b9dc77b50 100644--- a/frontend/src/metabase/explorations/components/ExplorationVisualization/ExplorationVisualizationHeader.tsx+++ b/frontend/src/metabase/explorations/components/ExplorationVisualization/ExplorationVisualizationHeader.tsx@@ -2,7 +2,6 @@ import { t } from "ttag";import { useUnresolvedCommentsCount } from "metabase/comments/hooks/use-unresolved-comments-count";import { ToolbarButton } from "metabase/common/components/ToolbarButton";-import { FilterPill } from "metabase/querying/filters/components/FilterPanel/FilterPill";import { type Path, useLocation, useNavigate } from "metabase/router";import { Ellipsified, Group, Indicator, Stack } from "metabase/ui";import type {@@ -11,6 +10,8 @@ import type {HydratedExplorationExploreFilter,} from "metabase-types/api";+import { ExploreFilterPills } from "../ExploreFilterPills";+interface ExplorationVisualizationHeaderProps {name: string;exploreFilters?: HydratedExplorationExploreFilter[] | null;@@ -30,7 +31,7 @@ export function ExplorationVisualizationHeader({}: ExplorationVisualizationHeaderProps) {const navigate = useNavigate();const location = useLocation();- const nextCommentsUrl = getNextCommentsUrl(location);+ const nextCommentsUrl = getNextCommentsUrl(location, pageId);const { allCommentsCount } = useUnresolvedCommentsCount({target:explorationId != null@@ -60,17 +61,6 @@ export function ExplorationVisualizationHeader({/>) : null;- const filterPills =- exploreFilters != null && exploreFilters.length > 0 ? (- <Group gap="sm" wrap="wrap">- {exploreFilters.map((filter, index) => (- <FilterPill key={index} readOnly>- {getExploreFilterPillLabel(filter)}- </FilterPill>- ))}- </Group>- ) : null;-return (<Stack gap="sm" style={{ flexShrink: 0 }}><Group h="2rem" justify="space-between" wrap="nowrap" miw={0}>@@ -87,24 +77,20 @@ export function ExplorationVisualizationHeader({)}</Group></Group>- {filterPills}+ <ExploreFilterPills filters={exploreFilters ?? []} /></Stack>);}-function getExploreFilterPillLabel(- filter: HydratedExplorationExploreFilter,-): string {- if (filter.dimension_name) {- return `${filter.dimension_name}: ${filter.display_value}`;- }- return filter.display_value;-}--function getNextCommentsUrl(location: Pick<Path, "pathname" | "search">) {+function getNextCommentsUrl(+ location: Pick<Path, "pathname" | "search">,+ pageId?: ExplorationPageNodeId,+) {const search = new URLSearchParams(location.search);- if (search.get("comments") === "true") {+ if (search.get("comments") != null) {search.delete("comments");+ } else if (pageId != null) {+ search.set("comments", String(pageId));} else {search.set("comments", "true");}diff --git a/frontend/src/metabase/explorations/components/ExplorationVisualization/utils.ts b/frontend/src/metabase/explorations/components/ExplorationVisualization/utils.tsindex b9722e3614e..61557aa3bc7 100644--- a/frontend/src/metabase/explorations/components/ExplorationVisualization/utils.ts+++ b/frontend/src/metabase/explorations/components/ExplorationVisualization/utils.ts@@ -2,7 +2,15 @@ import { t } from "ttag";import { createSeriesCard } from "metabase/common/utils/series";import { dayjs } from "metabase/dayjs";-import { OTHER_BUCKET_LABEL } from "metabase/explorations/constants";+import {+ CARTESIAN_SERIES_COL_NAME,+ HEAT_MAP_SEGMENT_COL_NAME,+ OTHER_BUCKET_LABEL,+ fallbackSegmentName,+ heatMapSegmentDisplayName,+ isDiscriminatorColumnName,+} from "metabase/explorations/constants";+import type { HighlightedCommentState } from "metabase/redux/store/explorations";import { getColorsForValues } from "metabase/ui/colors/charts";import { getAccentColors } from "metabase/ui/colors/groups";import { NULL_DISPLAY_VALUE } from "metabase/utils/constants";@@ -38,6 +46,7 @@ import type {ExplorationBlockNodeType,ExplorationExploreFilter,ExplorationQuery,+ ExplorationQueryId,ExplorationQueryType,RowValue,RowValues,@@ -67,6 +76,7 @@ export interface LegendItem {export interface SeriesGroup {series: SingleSeries[];+ queryIds: ExplorationQueryId[];isTimeseries: boolean;stackCount?: number;legendItems: LegendItem[];@@ -82,8 +92,8 @@ export function buildSeriesGroup({(queryWithDataset) => queryWithDataset.dataset.data.rows.length > 0,);- const segmentNames = nonEmptyQueriesWithDatasets.map(- (q) => q.segment_name ?? t`(All)`,+ const segmentNames = nonEmptyQueriesWithDatasets.map((q) =>+ segmentNameForQuery(q),);const colors = getColorsForValues(segmentNames);const legendItems: LegendItem[] = segmentNames.map((name) => ({@@ -95,6 +105,8 @@ export function buildSeriesGroup({(query) => query.segment_id != null,).length;+ const queryIds = nonEmptyQueriesWithDatasets.map((q) => q.id);+const series = nonEmptyQueriesWithDatasets.map((queryWithDataset, i) => {const { dataset, ...query } = queryWithDataset;@@ -142,6 +154,7 @@ export function buildSeriesGroup({return {series: getFinalSeries({ series, legendItems }),+ queryIds,isTimeseries,stackCount,legendItems,@@ -363,8 +376,8 @@ export function getHeatMapSeries({}: GetFinalSeriesParams): SingleSeries[] {const { card, data } = series[0];const segmentCol: DatasetColumn = {- name: "Segment",- display_name: "Segment",+ name: HEAT_MAP_SEGMENT_COL_NAME,+ display_name: heatMapSegmentDisplayName(),source: "breakout",};const cols = [...data.cols, segmentCol];@@ -604,9 +617,12 @@ export function getExploreFurtherFilters(export function canExploreFurther(clicked: ClickObject,- blockType: ExplorationBlockNodeType,- queryType: ExplorationQueryType,+ blockType?: ExplorationBlockNodeType,+ queryType?: ExplorationQueryType,): boolean {+ if (blockType == null || queryType == null) {+ return false;+ }// disable for dimension blocks - every query in a dimension block is cut by the same dimension// so filtering on a single dimension value doesn't provide a new view of the dataif (blockType === "dimension") {@@ -631,69 +647,299 @@ export function canExploreFurther(return true;}-export function getHighlightedWithShouldShowTooltip(- highlighted?: HighlightedObject,- seriesGroup?: SeriesGroup,+function segmentNameForQuery(query: ExplorationQuery): string {+ return query.segment_name ?? fallbackSegmentName();+}++type HighlightDimension = NonNullable<HighlightedObject["dimensions"]>[number];++/** Drop discriminator dims the target series does not have (e.g. Series on a page). */+function dimensionsForTarget(+ dimensions: HighlightedObject["dimensions"],+ cols: { name: string }[],+): HighlightDimension[] {+ return (dimensions ?? []).filter(+ (dimension) =>+ !isDiscriminatorColumnName(dimension.columnName) ||+ cols.some((col) => col.name === dimension.columnName),+ );+}++/**+ * Comments are shared between an exploration page and the Summary document.+ * For highlights to work in both we have to handle:+ * 1. card IDs don't match between the page and the document+ * 2. the BE may compose multiple exploration queries into one embed series+ *+ * Identity is `exploration_query_ids` on the comment (usually one id), not cardId.+ */+export function resolveHighlightForSeries(+ highlightedCommentState: HighlightedCommentState | null,+ series: SingleSeries[],+ seriesQueryIds: ExplorationQueryId[],+ queriesById: Readonly<Record<ExplorationQueryId, ExplorationQuery>>,): HighlightedObject | null {- if (!highlighted || !seriesGroup) {+ if (+ highlightedCommentState == null ||+ series.length === 0 ||+ seriesQueryIds.length === 0+ ) {return null;}- const { series } = seriesGroup;- const firstSeries = series[0];- if (!firstSeries) {+ const { highlighted, explorationQueryIds: commentQueryIds } =+ highlightedCommentState;+ if (commentQueryIds.length === 0) {return null;}++ const firstSeries = series[0];const {card: { display },data: { cols },} = firstSeries;- const hasMultipleSeries = series.length > 1;- const hasBreakout = cols.length > 2;const shouldShowTooltip =- display === "line" && !hasMultipleSeries && !hasBreakout;- return {- ...highlighted,- shouldShowTooltip,- };-}+ display === "line" && series.length === 1 && cols.length <= 2;++ // if we have only a single series, simply check if the query ids are the same+ if (+ series.length === 1 &&+ areQueryIdsEqual(seriesQueryIds, commentQueryIds)+ ) {+ return {+ ...highlighted,+ dimensions: dimensionsForTarget(highlighted.dimensions, cols),+ cardId: firstSeries.card.id,+ shouldShowTooltip,+ };+ }-export function getCommentLabel(- highlighted?: HighlightedObject | null,- seriesGroup?: SeriesGroup,- computedSettings?: ComputedVisualizationSettings,-): string | null | undefined {- if (!highlighted || !seriesGroup) {+ // if we have multiple series, find the series that matches the comment's query ID+ // only a single comment query ID is supported in this case+ if (+ series.length > 1 &&+ series.length === seriesQueryIds.length &&+ commentQueryIds.length === 1+ ) {+ for (let i = 0; i < series.length; i++) {+ if (seriesQueryIds[i] === commentQueryIds[0]) {+ return {+ ...highlighted,+ dimensions: dimensionsForTarget(+ highlighted.dimensions,+ series[i].data.cols,+ ),+ cardId: series[i].card.id,+ shouldShowTooltip,+ };+ }+ }return null;}- const seriesIndex =- seriesGroup.series.length === 1- ? 0- : seriesGroup.series.findIndex((s) => s.card.id === highlighted.cardId);- const series = seriesGroup.series[seriesIndex];- if (!series) {+ // composite series case - a composite series has a discriminator column built using segment names+ // if the comment was created on a non-composite series, we need to add a discriminator column to the highlighted object's dimensions+ if (+ series.length === 1 &&+ seriesQueryIds.length > 1 &&+ commentQueryIds.length === 1 &&+ seriesQueryIds.includes(commentQueryIds[0])+ ) {+ const dimensions = dimensionsForTarget(highlighted.dimensions, cols);+ const discriminatorCol = cols.find((col) =>+ isDiscriminatorColumnName(col.name),+ );+ if (!discriminatorCol) {+ return null;+ }+ const hasDiscriminatorDimension = dimensions.some(+ (dimension) => dimension.columnName === discriminatorCol.name,+ );+ if (!hasDiscriminatorDimension) {+ const commentQuery = queriesById[commentQueryIds[0]];+ if (!commentQuery) {+ return null;+ }+ dimensions.push({+ columnName: discriminatorCol.name,+ value: segmentNameForQuery(commentQuery),+ });+ }+ return {+ ...highlighted,+ dimensions,+ cardId: firstSeries.card.id,+ shouldShowTooltip,+ };+ }++ return null;+}++export function areQueryIdsEqual(+ queryIds1: ExplorationQueryId[],+ queryIds2: ExplorationQueryId[],+): boolean {+ const queryIds1Set = new Set(queryIds1);+ return (+ queryIds1.length === queryIds2.length &&+ queryIds2.every((id) => queryIds1Set.has(id))+ );+}++/** Narrow a chart click to the single exploration query it refers to */+export function resolveExplorationQueryIdForClick(+ clicked: ClickObject,+ seriesQueryIds: ExplorationQueryId[],+ queriesById: Readonly<Record<ExplorationQueryId, ExplorationQuery>>,+): ExplorationQueryId | null {+ if (seriesQueryIds.length === 1) {+ return seriesQueryIds[0];+ }++ const discriminatorDimension = clicked.dimensions?.find((dimension) =>+ isDiscriminatorColumnName(dimension.column.name),+ );+ if (discriminatorDimension != null) {+ const match = seriesQueryIds.find((id) => {+ const query = queriesById[id];+ return (+ query != null &&+ segmentNameForQuery(query) === discriminatorDimension.value+ );+ });+ return match ?? null;+ }++ // for an exploration page, we set cardId to the exploration query id+ // for the summary document, we don't control the cardId+ // but it either has a single query ID or has a discriminator column, so is handled above+ if (clicked.cardId != null && seriesQueryIds.includes(clicked.cardId)) {+ return clicked.cardId;+ }++ return null;+}++export function buildCommentHighlightContext(+ clicked: ClickObject,+ seriesQueryIds: ExplorationQueryId[],+ queriesById: Readonly<Record<ExplorationQueryId, ExplorationQuery>>,+ settings?: ComputedVisualizationSettings,+): {+ highlighted: HighlightedObject;+ exploration_query_ids: ExplorationQueryId[];+ highlight_label?: string;+} | null {+ const queryId = resolveExplorationQueryIdForClick(+ clicked,+ seriesQueryIds,+ queriesById,+ );+ if (queryId == null) {return null;}+ const query = queriesById[queryId];+ const hasDiscriminatorDimension = clicked.dimensions?.some((dimension) =>+ isDiscriminatorColumnName(dimension.column.name),+ );+ const segmentName =+ !hasDiscriminatorDimension && seriesQueryIds.length > 1 && query != null+ ? segmentNameForQuery(query)+ : null;++ return {+ highlighted: {+ columnName: clicked.column?.name,+ dimensions: clicked.dimensions?.map((dimension) => ({+ value: dimension.value,+ columnName: dimension.column.name,+ })),+ },+ exploration_query_ids: [queryId],+ highlight_label:+ buildHighlightLabel(clicked, settings, segmentName) ?? undefined,+ };+}++export function buildHighlightLabel(+ clicked: ClickObject,+ settings?: ComputedVisualizationSettings,+ segmentName?: string | null,+): string | null {const labels: string[] = [];- for (const dimension of highlighted.dimensions ?? []) {- const column = series.data.cols.find(- (col) => col.name === dimension.columnName,+ for (const dimension of clicked.dimensions ?? []) {+ const columnSettings = settings?.column?.(dimension.column) ?? {+ column: dimension.column,+ };+ labels.push(+ formatColumnValue(dimension.value, dimension.column, columnSettings),);- if (!column) {- continue;- }- const columnSettings = computedSettings?.column?.(column) ?? { column };- labels.push(formatColumnValue(dimension.value, column, columnSettings));}- if (highlighted.cardId && seriesGroup.series.length > 1) {- const segmentName = seriesGroup.legendItems[seriesIndex].name;- if (segmentName) {- labels.push(segmentName);+ const hasDiscriminatorDimension = clicked.dimensions?.some((dimension) =>+ isDiscriminatorColumnName(dimension.column.name),+ );+ if (!hasDiscriminatorDimension && segmentName) {+ labels.push(segmentName);+ }++ return labels.length > 0 ? labels.join(", ") : null;+}++export interface ExplorationChartForDocumentEmbed {+ queryIds: ExplorationQueryId[];+ label: string;+ display: VisualizationDisplay;+ visualization_settings: VisualizationSettings;+}++/**+ * Build the chart entries a page offers for "Add to Summary".+ *+ * Maps render one `<Visualization>` per series side-by-side (no+ * `graph.split_panels` analogue), so the user perceives each map as a+ * standalone chart. Expand a multi-series map group into N picker+ * entries — each appends a single-snapshot embed (the N=1+ * pass-through path through `composite/combine` server-side).+ * Everything else adds the whole page as one composite.+ */+export function composeChartsForGroup(+ group: SeriesGroup,+): ExplorationChartForDocumentEmbed[] {+ const firstSeries = group.series[0];+ if (!firstSeries) {+ return [];+ }+ const display = firstSeries.card.display;+ const { queryIds } = group;++ if (display === "map" && group.series.length > 1) {+ return group.series.map((s, i) => ({+ queryIds: [queryIds[i]],+ label: s.card.name ?? t`Chart`,+ display: s.card.display,+ visualization_settings: s.card.visualization_settings ?? {},+ }));+ }++ const label = firstSeries.card.name ?? t`Chart`;+ let visualization_settings: VisualizationSettings =+ firstSeries.card.visualization_settings ?? {};++ if (group.series.length > 1 && isCartesianChart(display)) {+ // The BE will append a "Series" column. Pin `graph.dimensions` so+ // the rendered chart reads the new column as the series breakout.+ const cols = firstSeries.data.cols;+ const xCol = cols.find(isDate)?.name ?? cols[0]?.name;+ if (xCol) {+ visualization_settings = {+ ...visualization_settings,+ "graph.dimensions": [xCol, CARTESIAN_SERIES_COL_NAME],+ };}}- return labels.join(", ");+ return [{ queryIds, label, display, visualization_settings }];}diff --git a/frontend/src/metabase/explorations/components/ExplorationVisualization/utils.unit.spec.ts b/frontend/src/metabase/explorations/components/ExplorationVisualization/utils.unit.spec.tsindex b2e08cb06d2..d81acb44c34 100644--- a/frontend/src/metabase/explorations/components/ExplorationVisualization/utils.unit.spec.ts+++ b/frontend/src/metabase/explorations/components/ExplorationVisualization/utils.unit.spec.ts@@ -1,9 +1,16 @@-import { OTHER_BUCKET_LABEL } from "metabase/explorations/constants";+import {+ CARTESIAN_SERIES_COL_NAME,+ HEAT_MAP_SEGMENT_COL_NAME,+ OTHER_BUCKET_LABEL,+ fallbackSegmentName,+} from "metabase/explorations/constants";import { createQuery } from "metabase/explorations/test-utils";+import type { HighlightedCommentState } from "metabase/redux/store/explorations";import { NULL_DISPLAY_VALUE } from "metabase/utils/constants";import { registerVisualizations } from "metabase/visualizations/register";import type {ClickObject,+ ComputedVisualizationSettings,HighlightedObject,} from "metabase/visualizations/types";import type {@@ -21,12 +28,14 @@ import {} from "metabase-types/api/mocks";import {- type SeriesGroup,+ buildCommentHighlightContext,+ buildHighlightLabel,buildSeriesGroup,canExploreFurther,- getCommentLabel,+ composeChartsForGroup,getExploreFurtherFilters,getHeatMapSeries,+ resolveHighlightForSeries,} from "./utils";registerVisualizations();@@ -167,6 +176,11 @@ function makeClickObject(}describe("canExploreFurther", () => {+ it("returns false when blockType or queryType is omitted", () => {+ expect(canExploreFurther(makeClickObject())).toBe(false);+ expect(canExploreFurther(makeClickObject(), "metric")).toBe(false);+ });+it("returns false when there are no dimensions", () => {expect(canExploreFurther(@@ -519,153 +533,500 @@ describe("getExploreFurtherFilters", () => {});});-describe("getCommentLabel", () => {+describe("resolveHighlightForSeries", () => {const categoryColumn = createMockColumn({name: "category",base_type: "type/Text",});- const tsColumn = createMockColumn({- name: "ts",- base_type: "type/DateTime",- unit: "month",+ const countColumn = createMockColumn({+ name: "count",+ source: "aggregation",+ });+ const seriesColumn = createMockColumn({+ name: CARTESIAN_SERIES_COL_NAME,+ source: "breakout",});+ const segmentColumn = createMockColumn({+ name: HEAT_MAP_SEGMENT_COL_NAME,+ source: "breakout",+ });++ const queries = [+ makeQuery({ id: 101, segment_name: "US" }),+ makeQuery({ id: 102, segment_name: "EU" }),+ ];+ const queriesById = Object.fromEntries(queries.map((q) => [q.id, q]));- function makeSeriesGroup(- series: SingleSeries[],- legendItems: SeriesGroup["legendItems"],- ): SeriesGroup {+ function commentState(+ queryIds: number[],+ highlighted: HighlightedObject = {+ columnName: "count",+ dimensions: [{ columnName: "category", value: "Gadget" }],+ },+ ): HighlightedCommentState {return {- series,- legendItems,- isTimeseries: false,+ childTargetId: "7",+ highlighted,+ explorationQueryIds: queryIds,};}- it("returns null when highlighted or series group is missing", () => {- const group = makeSeriesGroup([], []);- expect(getCommentLabel(undefined, group)).toBeNull();+ function pageSeries(cardIds: number[]): SingleSeries[] {+ return cardIds.map((id) => ({+ card: createMockCard({ id, display: "line" }),+ data: createMockDatasetData({+ cols: [categoryColumn, countColumn],+ rows: [["Gadget", 10]],+ }),+ }));+ }++ function embedSeries(+ display: "line" | "bar" | "table",+ discriminator: "Series" | "Segment",+ ): SingleSeries[] {+ const discCol = discriminator === "Series" ? seriesColumn : segmentColumn;+ return [+ {+ card: createMockCard({ id: 999, display }),+ data: createMockDatasetData({+ cols: [categoryColumn, countColumn, discCol],+ rows: [["Gadget", 10, "EU"]],+ }),+ },+ ];+ }++ it("returns null when state or series is missing", () => {+ expect(+ resolveHighlightForSeries(null, pageSeries([101]), [101], queriesById),+ ).toBeNull();expect(- // Unjustified type cast. FIXME- getCommentLabel({ cardId: 1 } as HighlightedObject, undefined),+ resolveHighlightForSeries(commentState([101]), [], [101], queriesById),).toBeNull();});- it("formats a single-series label from dimension values", () => {- const card = createMockCard({ id: 101, name: "Revenue" });- const seriesGroup = makeSeriesGroup(- [- {- card,- data: createMockDatasetData({- cols: [categoryColumn, createMockColumn({ name: "count" })],- rows: [["Gadget", 10]],- }),- },- ],- [{ name: "(All)", color: "#000" }],- );- const highlighted: HighlightedObject = {- cardId: 101,+ it("sets the target cardId for a matching single-query chart", () => {+ expect(+ resolveHighlightForSeries(+ commentState([101]),+ pageSeries([101]),+ [101],+ queriesById,+ ),+ ).toEqual({columnName: "count",dimensions: [{ columnName: "category", value: "Gadget" }],- };+ cardId: 101,+ shouldShowTooltip: true,+ });+ });- expect(getCommentLabel(highlighted, seriesGroup)).toBe("Gadget");+ it("picks the matching series on a multi-series page", () => {+ expect(+ resolveHighlightForSeries(+ commentState([102]),+ pageSeries([101, 102]),+ [101, 102],+ queriesById,+ ),+ ).toEqual({+ columnName: "count",+ dimensions: [{ columnName: "category", value: "Gadget" }],+ cardId: 102,+ shouldShowTooltip: false,+ });});- it("appends the segment name for multi-series groups", () => {- const seriesGroup = makeSeriesGroup(- [- {- card: createMockCard({ id: 101, name: "US" }),- data: createMockDatasetData({- cols: [categoryColumn, createMockColumn({ name: "count" })],- rows: [["Gadget", 10]],- }),- },- {- card: createMockCard({ id: 102, name: "EU" }),- data: createMockDatasetData({- cols: [categoryColumn, createMockColumn({ name: "count" })],- rows: [["Gadget", 20]],- }),- },- ],- [- { name: "US", color: "#111" },- { name: "EU", color: "#222" },+ it("synthesizes a Series dimension for a composite embed", () => {+ expect(+ resolveHighlightForSeries(+ commentState([102]),+ embedSeries("bar", "Series"),+ [101, 102],+ queriesById,+ ),+ ).toEqual({+ columnName: "count",+ dimensions: [+ { columnName: "category", value: "Gadget" },+ { columnName: CARTESIAN_SERIES_COL_NAME, value: "EU" },],- );+ cardId: 999,+ shouldShowTooltip: false,+ });+ });- const highlighted: HighlightedObject = {- cardId: 102,+ it("strips a Series dimension when resolving onto a page series", () => {+ expect(+ resolveHighlightForSeries(+ commentState([102], {+ columnName: "count",+ dimensions: [+ { columnName: "category", value: "Gadget" },+ { columnName: CARTESIAN_SERIES_COL_NAME, value: "EU" },+ ],+ }),+ pageSeries([101, 102]),+ [101, 102],+ queriesById,+ ),+ ).toEqual({columnName: "count",dimensions: [{ columnName: "category", value: "Gadget" }],+ cardId: 102,+ shouldShowTooltip: false,+ });+ });++ it("keeps a Segment dimension on a heatmap composite", () => {+ const highlighted: HighlightedObject = {+ columnName: "count",+ dimensions: [+ { columnName: "category", value: "Gadget" },+ { columnName: HEAT_MAP_SEGMENT_COL_NAME, value: "EU" },+ ],};- expect(getCommentLabel(highlighted, seriesGroup)).toBe("Gadget, EU");+ expect(+ resolveHighlightForSeries(+ commentState([102], highlighted),+ embedSeries("table", "Segment"),+ [101, 102],+ queriesById,+ ),+ ).toEqual({+ columnName: "count",+ dimensions: highlighted.dimensions,+ cardId: 999,+ shouldShowTooltip: false,+ });});- it("formats dates and null values for display", () => {- const seriesGroup = makeSeriesGroup(- [- {- card: createMockCard({ id: 101 }),- data: createMockDatasetData({- cols: [tsColumn, createMockColumn({ name: "count" })],- rows: [["2025-01-01T00:00:00Z", 10]],- }),- },- ],- [{ name: "(All)", color: "#000" }],- );+ it("falls back to (All) when synthesizing without segment_name", () => {+ const noSegmentQueries = {+ 101: makeQuery({ id: 101 }),+ 102: makeQuery({ id: 102 }),+ };expect(- getCommentLabel(- {- cardId: 101,- columnName: "count",- dimensions: [{ columnName: "ts", value: "2025-01-01T00:00:00Z" }],- },- seriesGroup,+ resolveHighlightForSeries(+ commentState([101]),+ embedSeries("bar", "Series"),+ [101, 102],+ noSegmentQueries,+ )?.dimensions,+ ).toEqual([+ { columnName: "category", value: "Gadget" },+ { columnName: CARTESIAN_SERIES_COL_NAME, value: fallbackSegmentName() },+ ]);+ });++ it("returns null for a sibling map embed with a different query id", () => {+ expect(+ resolveHighlightForSeries(+ commentState([102]),+ pageSeries([999]),+ [101],+ queriesById,),- ).toMatch(/Jan/);+ ).toBeNull();+ });++ it("returns null when composite synthesis cannot find the discriminator", () => {+ const noDiscriminator: SingleSeries[] = [+ {+ card: createMockCard({ id: 999, display: "bar" }),+ data: createMockDatasetData({+ cols: [categoryColumn, countColumn],+ rows: [["Gadget", 10]],+ }),+ },+ ];expect(- getCommentLabel(- {- cardId: 101,- columnName: "count",- dimensions: [{ columnName: "ts", value: null }],- },- seriesGroup,+ resolveHighlightForSeries(+ commentState([102]),+ noDiscriminator,+ [101, 102],+ queriesById,),- ).toBe("(empty)");+ ).toBeNull();});- it("skips missing columns and unknown card ids", () => {- const seriesGroup = makeSeriesGroup(- [- {- card: createMockCard({ id: 101 }),- data: createMockDatasetData({- cols: [categoryColumn],- rows: [["Gadget"]],- }),- },+ it("derives shouldShowTooltip from the target display", () => {+ const lineTarget = pageSeries([101]);+ const barTarget = [+ {+ card: createMockCard({ id: 101, display: "bar" }),+ data: createMockDatasetData({+ cols: [categoryColumn, countColumn],+ rows: [["Gadget", 10]],+ }),+ },+ ];++ expect(+ resolveHighlightForSeries(+ commentState([101]),+ lineTarget,+ [101],+ queriesById,+ )?.shouldShowTooltip,+ ).toBe(true);+ expect(+ resolveHighlightForSeries(+ commentState([101]),+ barTarget,+ [101],+ queriesById,+ )?.shouldShowTooltip,+ ).toBe(false);+ });+});++describe("comment highlight create ↔ resolve contract", () => {+ const categoryColumn = createMockColumn({+ name: "category",+ base_type: "type/Text",+ source: "breakout",+ });+ const countColumn = createMockColumn({+ name: "count",+ source: "aggregation",+ });+ const seriesColumn = createMockColumn({+ name: CARTESIAN_SERIES_COL_NAME,+ source: "breakout",+ });++ const queries = [+ makeQuery({ id: 101, segment_name: "US" }),+ makeQuery({ id: 102, segment_name: "EU" }),+ ];+ const queriesById = Object.fromEntries(queries.map((q) => [q.id, q]));+ const seriesQueryIds = [101, 102];++ function pageSeries(): SingleSeries[] {+ return seriesQueryIds.map((id) => ({+ card: createMockCard({ id, display: "line" }),+ data: createMockDatasetData({+ cols: [categoryColumn, countColumn],+ rows: [["Gadget", 10]],+ }),+ }));+ }++ function compositeEmbed(): SingleSeries[] {+ return [+ {+ card: createMockCard({ id: 999, display: "bar" }),+ data: createMockDatasetData({+ cols: [categoryColumn, countColumn, seriesColumn],+ rows: [["Gadget", 10, "EU"]],+ }),+ },+ ];+ }++ function toState(+ ctx: NonNullable<ReturnType<typeof buildCommentHighlightContext>>,+ ): HighlightedCommentState {+ return {+ childTargetId: "7",+ highlighted: ctx.highlighted,+ explorationQueryIds: ctx.exploration_query_ids,+ };+ }++ it("stores a single query id from a page click and resolves on the composite embed", () => {+ const clicked: ClickObject = {+ value: 10,+ column: countColumn,+ dimensions: [{ column: categoryColumn, value: "Gadget" }],+ settings: {},+ cardId: 102,+ };+ const ctx = buildCommentHighlightContext(+ clicked,+ seriesQueryIds,+ queriesById,+ );++ expect(ctx?.exploration_query_ids).toEqual([102]);+ expect(ctx?.highlighted.cardId).toBeUndefined();+ expect(ctx?.highlight_label).toBe("Gadget, EU");++ expect(+ resolveHighlightForSeries(+ toState(ctx!),+ compositeEmbed(),+ seriesQueryIds,+ queriesById,+ ),+ ).toEqual({+ columnName: "count",+ dimensions: [+ { columnName: "category", value: "Gadget" },+ { columnName: CARTESIAN_SERIES_COL_NAME, value: "EU" },],- [{ name: "(All)", color: "#000" }],+ cardId: 999,+ shouldShowTooltip: false,+ });+ });++ it("stores a single query id from a composite click and resolves on the page", () => {+ const clicked: ClickObject = {+ value: 10,+ column: countColumn,+ dimensions: [+ { column: categoryColumn, value: "Gadget" },+ { column: seriesColumn, value: "EU" },+ ],+ settings: {},+ cardId: 999,+ };+ const ctx = buildCommentHighlightContext(+ clicked,+ seriesQueryIds,+ queriesById,);+ expect(ctx?.exploration_query_ids).toEqual([102]);+ expect(ctx?.highlighted.cardId).toBeUndefined();+expect(- getCommentLabel(- {- cardId: 999,- dimensions: [{ columnName: "missing", value: "x" }],- },- seriesGroup,+ resolveHighlightForSeries(+ toState(ctx!),+ pageSeries(),+ seriesQueryIds,+ queriesById,),- ).toBe("");+ ).toEqual({+ columnName: "count",+ dimensions: [{ columnName: "category", value: "Gadget" }],+ cardId: 102,+ shouldShowTooltip: false,+ });+ });++ it("stores the embed query id even when clicked.cardId is ephemeral", () => {+ const clicked: ClickObject = {+ value: 10,+ column: countColumn,+ dimensions: [{ column: categoryColumn, value: "Gadget" }],+ settings: {},+ cardId: 999,+ };+ const ctx = buildCommentHighlightContext(clicked, [101], {+ 101: queriesById[101],+ });++ expect(ctx?.exploration_query_ids).toEqual([101]);+ expect(+ resolveHighlightForSeries(+ toState(ctx!),+ [+ {+ card: createMockCard({ id: 999, display: "line" }),+ data: createMockDatasetData({+ cols: [categoryColumn, countColumn],+ rows: [["Gadget", 10]],+ }),+ },+ ],+ [101],+ { 101: queriesById[101] },+ )?.cardId,+ ).toBe(999);+ });+});++describe("buildHighlightLabel", () => {+ const categoryColumn = createMockColumn({+ name: "category",+ base_type: "type/Text",+ });+ const tsColumn = createMockColumn({+ name: "ts",+ base_type: "type/DateTime",+ unit: "month",+ });+ const totalColumn = createMockColumn({+ name: "total",+ base_type: "type/Float",+ semantic_type: "type/Currency",+ });++ it("formats dimension values from the click", () => {+ const clicked: ClickObject = {+ value: 10,+ column: createMockColumn({ name: "count", source: "aggregation" }),+ dimensions: [{ column: categoryColumn, value: "Gadget" }],+ settings: {},+ cardId: 101,+ };++ expect(buildHighlightLabel(clicked)).toBe("Gadget");+ });++ it("formats through the chart's column settings, not the raw value", () => {+ const clicked: ClickObject = {+ value: 10,+ column: createMockColumn({ name: "count", source: "aggregation" }),+ dimensions: [{ column: totalColumn, value: 0 }],+ settings: {},+ cardId: 101,+ };++ // `buildHighlightLabel` only ever reaches for `.column`, so a stub of that one accessor stands+ // in for the ~100-key computed settings object a real chart would hand it.+ const settings = {+ column: () => ({+ column: totalColumn,+ currency: "USD",+ currency_style: "symbol",+ number_style: "currency",+ }),+ } as unknown as ComputedVisualizationSettings;++ // the bug this guards: without the settings the label is the bare "0" the server would derive+ expect(buildHighlightLabel(clicked, undefined)).toBe("0");+ expect(buildHighlightLabel(clicked, settings)).toBe("$0");+ });++ it("appends a segment name for multi-series pages", () => {+ const clicked: ClickObject = {+ value: 10,+ column: createMockColumn({ name: "count", source: "aggregation" }),+ dimensions: [{ column: categoryColumn, value: "Gadget" }],+ settings: {},+ cardId: 102,+ };++ expect(buildHighlightLabel(clicked, undefined, "EU")).toBe("Gadget, EU");+ });++ it("formats dates and null values", () => {+ expect(+ buildHighlightLabel({+ value: 10,+ column: createMockColumn({ name: "count" }),+ dimensions: [{ column: tsColumn, value: "2025-01-01T00:00:00Z" }],+ settings: {},+ cardId: 101,+ }),+ ).toMatch(/Jan/);++ expect(+ buildHighlightLabel({+ value: 10,+ column: createMockColumn({ name: "count" }),+ dimensions: [{ column: tsColumn, value: null }],+ settings: {},+ cardId: 101,+ }),+ ).toBe("(empty)");});});@@ -794,6 +1155,7 @@ describe("buildSeriesGroup", () => {});expect(seriesGroup.series).toHaveLength(1);+ expect(seriesGroup.queryIds).toEqual([2]);expect(seriesGroup.legendItems.map((item) => item.name)).toEqual(["EU"]);});@@ -818,3 +1180,100 @@ describe("buildSeriesGroup", () => {expect(group.series[0].card.display).toBe("row");});});++describe("composeChartsForGroup", () => {+ it("expands a multi-series map group into one entry per map", () => {+ const group = buildSeriesGroup({+ queriesWithDatasets: [+ {+ ...makeQuery({ id: 101, name: "US sessions", segment_id: 1 }),+ dataset: stateDataset,+ },+ {+ ...makeQuery({ id: 102, name: "EU sessions", segment_id: 2 }),+ dataset: stateDataset,+ },+ {+ ...makeQuery({ id: 103, name: "APAC sessions", segment_id: 3 }),+ dataset: stateDataset,+ },+ ],+ });++ const charts = composeChartsForGroup(group);++ expect(charts).toHaveLength(3);+ expect(charts.map((c) => c.queryIds)).toEqual([[101], [102], [103]]);+ expect(charts.map((c) => c.display)).toEqual(["map", "map", "map"]);+ });++ it("keeps a multi-series cartesian group as one composite entry", () => {+ const group = buildSeriesGroup({+ queriesWithDatasets: [+ {+ ...makeQuery({ id: 1, name: "Q1", segment_id: 1 }),+ dataset: tsDataset,+ },+ {+ ...makeQuery({ id: 2, name: "Q2", segment_id: 2 }),+ dataset: tsDataset,+ },+ ],+ });++ const charts = composeChartsForGroup(group);++ expect(charts).toHaveLength(1);+ expect(charts[0].queryIds).toEqual([1, 2]);+ expect(charts[0].display).toBe("line");+ expect(charts[0].visualization_settings["graph.dimensions"]).toEqual([+ "ts",+ "Series",+ ]);+ });++ it("keeps a single-series map as one entry", () => {+ const group = buildSeriesGroup({+ queriesWithDatasets: [+ {+ ...makeQuery({ id: 42, name: "World sessions" }),+ dataset: stateDataset,+ },+ ],+ });++ const charts = composeChartsForGroup(group);++ expect(charts).toHaveLength(1);+ expect(charts[0]).toMatchObject({+ queryIds: [42],+ display: "map",+ });+ });++ it("skips empty datasets when expanding multi-series maps", () => {+ const emptyDataset = makeDataset([STATE_COL, COUNT_COL], []);+ const group = buildSeriesGroup({+ queriesWithDatasets: [+ {+ ...makeQuery({ id: 1, name: "Empty", segment_id: 1 }),+ dataset: emptyDataset,+ },+ {+ ...makeQuery({ id: 2, name: "US", segment_id: 2 }),+ dataset: stateDataset,+ },+ {+ ...makeQuery({ id: 3, name: "EU", segment_id: 3 }),+ dataset: stateDataset,+ },+ ],+ });++ const charts = composeChartsForGroup(group);++ expect(charts).toHaveLength(2);+ expect(charts.map((c) => c.queryIds)).toEqual([[2], [3]]);+ expect(charts.map((c) => c.label)).toEqual(["US", "EU"]);+ });+});diff --git a/frontend/src/metabase/explorations/components/ExploreFilterPills/ExploreFilterPills.tsx b/frontend/src/metabase/explorations/components/ExploreFilterPills/ExploreFilterPills.tsxnew file mode 100644index 00000000000..7226358fb07--- /dev/null+++ b/frontend/src/metabase/explorations/components/ExploreFilterPills/ExploreFilterPills.tsx@@ -0,0 +1,54 @@+import { FilterPill } from "metabase/querying/filters/components/FilterPanel/FilterPill";+import { Group } from "metabase/ui";+import type { HydratedExplorationExploreFilter } from "metabase-types/api";++export type ExploreFilterPill = Pick<+ HydratedExplorationExploreFilter,+ "display_value" | "dimension_name"+>;++export function ExploreFilterPills({+ filters,+}: {+ filters: ExploreFilterPill[];+}) {+ if (filters.length === 0) {+ return null;+ }+ return (+ <Group gap="sm" wrap="wrap">+ {filters.map((filter, index) => (+ <FilterPill key={index} readOnly>+ {exploreFilterPillLabel(filter)}+ </FilterPill>+ ))}+ </Group>+ );+}++export function parseExploreFilterPills(value: unknown): ExploreFilterPill[] {+ if (!Array.isArray(value) || !value.every(isExploreFilterPill)) {+ return [];+ }+ return value;+}++function isExploreFilterPill(value: unknown): value is ExploreFilterPill {+ if (value == null || typeof value !== "object" || Array.isArray(value)) {+ return false;+ }+ if (!("display_value" in value) || typeof value.display_value !== "string") {+ return false;+ }+ if (!("dimension_name" in value) || value.dimension_name == null) {+ return true;+ }+ return typeof value.dimension_name === "string";+}++function exploreFilterPillLabel(filter: ExploreFilterPill): string {+ if (filter.dimension_name) {+ return `${filter.dimension_name}: ${filter.display_value}`;+ }+ return filter.display_value;+}diff --git a/frontend/src/metabase/explorations/components/ExploreFilterPills/ExploreFilterPills.unit.spec.tsx b/frontend/src/metabase/explorations/components/ExploreFilterPills/ExploreFilterPills.unit.spec.tsxnew file mode 100644index 00000000000..3f8d1b42642--- /dev/null+++ b/frontend/src/metabase/explorations/components/ExploreFilterPills/ExploreFilterPills.unit.spec.tsx@@ -0,0 +1,48 @@+import { renderWithProviders, screen } from "__support__/ui";++import {+ type ExploreFilterPill,+ ExploreFilterPills,+ parseExploreFilterPills,+} from "./ExploreFilterPills";++const stateFilter: ExploreFilterPill = {+ display_value: "TX",+ dimension_name: "State",+};++describe("ExploreFilterPills", () => {+ it("labels a filter with dimension name and display value", () => {+ renderWithProviders(<ExploreFilterPills filters={[stateFilter]} />);++ expect(screen.getByTestId("filter-pill")).toHaveTextContent("State: TX");+ });++ it("falls back to display_value when dimension_name is missing", () => {+ renderWithProviders(+ <ExploreFilterPills filters={[{ display_value: "TX" }]} />,+ );++ expect(screen.getByTestId("filter-pill")).toHaveTextContent("TX");+ });++ it("renders nothing for an empty list", () => {+ renderWithProviders(<ExploreFilterPills filters={[]} />);++ expect(screen.queryByTestId("filter-pill")).not.toBeInTheDocument();+ });+});++describe("parseExploreFilterPills", () => {+ it("returns pills that have a string display_value", () => {+ expect(parseExploreFilterPills([stateFilter])).toEqual([stateFilter]);+ });++ it("returns an empty list for missing or malformed values", () => {+ expect(parseExploreFilterPills(undefined)).toEqual([]);+ expect(parseExploreFilterPills([{ display_value: 1 }])).toEqual([]);+ expect(+ parseExploreFilterPills([{ display_value: "TX", dimension_name: 1 }]),+ ).toEqual([]);+ });+});diff --git a/frontend/src/metabase/explorations/components/ExploreFilterPills/index.ts b/frontend/src/metabase/explorations/components/ExploreFilterPills/index.tsnew file mode 100644index 00000000000..e6877cc4c5a--- /dev/null+++ b/frontend/src/metabase/explorations/components/ExploreFilterPills/index.ts@@ -0,0 +1,5 @@+export {+ ExploreFilterPills,+ parseExploreFilterPills,+ type ExploreFilterPill,+} from "./ExploreFilterPills";diff --git a/frontend/src/metabase/explorations/constants.ts b/frontend/src/metabase/explorations/constants.tsindex b9a2cba4b9e..cf549e82e84 100644--- a/frontend/src/metabase/explorations/constants.ts+++ b/frontend/src/metabase/explorations/constants.ts@@ -20,3 +20,25 @@ export function getDefaultExplorationName() {// keep in sync with backend other-bucket-labelexport const OTHER_BUCKET_LABEL = "(Other)";++/** Discriminator column names written by `composite.clj` / `getHeatMapSeries`+ * / multi-series cartesian combine. Keep in sync with the BE. */+export const HEAT_MAP_SEGMENT_COL_NAME = "Segment";+export const CARTESIAN_SERIES_COL_NAME = "Series";++const DISCRIMINATOR_COL_NAMES = new Set([+ HEAT_MAP_SEGMENT_COL_NAME,+ CARTESIAN_SERIES_COL_NAME,+]);++export function heatMapSegmentDisplayName(): string {+ return t`Segment`;+}++export function isDiscriminatorColumnName(columnName: string): boolean {+ return DISCRIMINATOR_COL_NAMES.has(columnName);+}++export function fallbackSegmentName(): string {+ return t`(All)`;+}diff --git a/frontend/src/metabase/explorations/explorations.slice.ts b/frontend/src/metabase/explorations/explorations.slice.tsindex 866ba77b294..c07b28b5e4c 100644--- a/frontend/src/metabase/explorations/explorations.slice.ts+++ b/frontend/src/metabase/explorations/explorations.slice.ts@@ -1,10 +1,14 @@import { type PayloadAction, createSlice } from "@reduxjs/toolkit";-import type { ExplorationsState } from "metabase/redux/store/explorations";+import type {+ ExplorationsState,+ HighlightedCommentState,+} from "metabase/redux/store/explorations";import type { Exploration } from "metabase-types/api";const initialState: ExplorationsState = {currentExploration: undefined,+ highlightedComment: null,};const explorationsSlice = createSlice({@@ -18,10 +22,20 @@ const explorationsSlice = createSlice({// eslint-disable-next-line @typescript-eslint/ban-ts-comment// @ts-ignore - possibly infinite type errorstate.currentExploration = action.payload;+ if (action.payload == null) {+ state.highlightedComment = null;+ }+ },+ setHighlightedComment: (+ state,+ action: PayloadAction<HighlightedCommentState | null>,+ ) => {+ state.highlightedComment = action.payload;},},});-export const { setCurrentExploration } = explorationsSlice.actions;+export const { setCurrentExploration, setHighlightedComment } =+ explorationsSlice.actions;export const explorationsReducer = explorationsSlice.reducer;diff --git a/frontend/src/metabase/explorations/hooks/useExplorationClickActionsMode.tsx b/frontend/src/metabase/explorations/hooks/useExplorationClickActionsMode.tsxindex b2a37781f23..edb0661cf0d 100644--- a/frontend/src/metabase/explorations/hooks/useExplorationClickActionsMode.tsx+++ b/frontend/src/metabase/explorations/hooks/useExplorationClickActionsMode.tsx@@ -8,12 +8,17 @@ import {trackExplorationCommentCreated,trackExplorationExploreFurtherClicked,} from "metabase/explorations/analytics";+import {+ buildCommentHighlightContext,+ canExploreFurther,+ getExploreFurtherFilters,+} from "metabase/explorations/components/ExplorationVisualization/utils";import type {ClickAction,ClickActionPopoverProps,ClickActionsMode,ClickObject,- HighlightedObject,+ ComputedVisualizationSettings,} from "metabase/visualizations/types";import { isBrushClickObject } from "metabase/visualizations/types";import type {@@ -21,23 +26,23 @@ import type {ExplorationBlockNodeType,ExplorationId,ExplorationPageId,+ ExplorationQuery,+ ExplorationQueryId,ExplorationQueryType,} from "metabase-types/api";import { ExplorationCommentEditor } from "../components/ExplorationVisualization/ExplorationCommentEditor";-import {- canExploreFurther,- getExploreFurtherFilters,-} from "../components/ExplorationVisualization/utils";import type { CommentDrafts } from "../types";interface UseExplorationClickActionsModeParams {- explorationId: ExplorationId;- pageId: ExplorationPageId;- blockType: ExplorationBlockNodeType;- queryType: ExplorationQueryType;+ explorationId?: ExplorationId;+ pageId?: ExplorationPageId;+ blockType?: ExplorationBlockNodeType;+ queryType?: ExplorationQueryType;commentDrafts: CommentDrafts;setCommentDrafts: Dispatch<SetStateAction<CommentDrafts>>;+ seriesQueryIds: ExplorationQueryId[];+ queriesById: Readonly<Record<ExplorationQueryId, ExplorationQuery>>;}export function useExplorationClickActionsMode({@@ -47,6 +52,8 @@ export function useExplorationClickActionsMode({queryType,commentDrafts,setCommentDrafts,+ seriesQueryIds,+ queriesById,}: UseExplorationClickActionsModeParams): ClickActionsMode {const [exploreFurther] = useExploreFurtherMutation();const [createComment] = useCreateCommentMutation();@@ -59,9 +66,16 @@ export function useExplorationClickActionsMode({const mode = useMemo(() => {return {- actionsForClick: (clicked: ClickObject) => {+ actionsForClick: (+ clicked: ClickObject,+ settings?: ComputedVisualizationSettings,+ ) => {const actions: ClickAction[] = [];+ if (explorationId == null || pageId == null) {+ return actions;+ }+if (canExploreFurther(clicked, blockType, queryType)) {const handleExploreFurther = async () => {const exploreFilters = getExploreFurtherFilters(clicked);@@ -102,23 +116,19 @@ export function useExplorationClickActionsMode({content: DocumentContent,onClose: () => void,) => {- const highlighted: HighlightedObject = {- cardId: clicked.cardId,- columnName: clicked.column?.name,- dimensions: clicked.dimensions?.map((d) => ({- value: d.value,- columnName: d.column.name,- })),- };+ const highlightContext = buildCommentHighlightContext(+ clicked,+ seriesQueryIds,+ queriesById,+ settings,+ );const { error } = await createComment({target_id: explorationId,target_type: "exploration",child_target_id: String(pageId),parent_comment_id: null,content,- context: {- highlighted,- },+ context: highlightContext,});if (error) {sendToast({@@ -166,6 +176,8 @@ export function useExplorationClickActionsMode({exploreFurther,createComment,sendToast,+ seriesQueryIds,+ queriesById,]);return mode;diff --git a/frontend/src/metabase/explorations/hooks/useExplorationClickActionsMode.unit.spec.tsx b/frontend/src/metabase/explorations/hooks/useExplorationClickActionsMode.unit.spec.tsxindex 888f7692e70..875b2a7ea79 100644--- a/frontend/src/metabase/explorations/hooks/useExplorationClickActionsMode.unit.spec.tsx+++ b/frontend/src/metabase/explorations/hooks/useExplorationClickActionsMode.unit.spec.tsx@@ -7,6 +7,7 @@ import {trackExplorationCommentCreated,trackExplorationExploreFurtherClicked,} from "metabase/explorations/analytics";+import { createQuery } from "metabase/explorations/test-utils";import type {ClickActionPopoverProps,ClickObject,@@ -18,6 +19,15 @@ import type { CommentDrafts } from "../types";import { useExplorationClickActionsMode } from "./useExplorationClickActionsMode";+const defaultQuery = createQuery({+ id: 101,+ name: "q-101",+ status: "done",+ segment_name: null,+});+const defaultQueryIds = [101];+const defaultQueriesById = { 101: defaultQuery };+const exploreFurtherMock = jest.fn();const createCommentMock = jest.fn();const sendToastMock = jest.fn();@@ -105,6 +115,8 @@ function renderMode(queryType: "default",commentDrafts,setCommentDrafts,+ seriesQueryIds: defaultQueryIds,+ queriesById: defaultQueriesById,...overrides,}),{@@ -228,7 +240,7 @@ describe("useExplorationClickActionsMode", () => {);});- it("creates a comment with highlighted context and closes on success", async () => {+ it("creates a comment with highlighted context, highlight_label, and closes on success", async () => {const onClose = jest.fn();const { result } = renderMode();const Popover = getAddCommentPopover(@@ -252,10 +264,11 @@ describe("useExplorationClickActionsMode", () => {child_target_id: "7",context: {highlighted: {- cardId: 101,columnName: "count",dimensions: [{ columnName: "category", value: "Gadget" }],},+ exploration_query_ids: [101],+ highlight_label: "Gadget",},}),);@@ -266,6 +279,16 @@ describe("useExplorationClickActionsMode", () => {);});+ it("offers add-comment but not explore-further when blockType/queryType are omitted", () => {+ const { result } = renderMode({+ blockType: undefined,+ queryType: undefined,+ });+ const actions = result.current.actionsForClick(makeClicked());++ expect(actions.map((action) => action.name)).toEqual(["add-comment"]);+ });+it("shows an error toast when comment creation fails", async () => {createCommentMock.mockResolvedValue({ error: { status: 500 } });const onClose = jest.fn();diff --git a/frontend/src/metabase/explorations/hooks/useExplorationCommentUrl.ts b/frontend/src/metabase/explorations/hooks/useExplorationCommentUrl.tsnew file mode 100644index 00000000000..50f80a4c4a0--- /dev/null+++ b/frontend/src/metabase/explorations/hooks/useExplorationCommentUrl.ts@@ -0,0 +1,57 @@+import { useLocation } from "metabase/router";+import * as Urls from "metabase/urls";++export type ExplorationCommentView = "page" | "summary";++interface UseExplorationCommentUrlOptions {+ childTargetId?: string | null;+ view: ExplorationCommentView;+}++function parseExplorationId(pathname: string): number | null {+ const prefix = `/${Urls.EXPLORATION_BASE_PATH}/`;+ if (!pathname.startsWith(prefix)) {+ return null;+ }+ const idSegment = pathname.slice(prefix.length).split("/")[0];+ const id = Number(idSegment);+ return Number.isFinite(id) ? id : null;+}++/**+ * Builds an exploration comments deep-link: `?comments=<childTargetId>` plus+ * a pinned pathname so the main pane matches the comment's target. Without+ * the pin, bare exploration URLs re-derive selection via auto-tracking and+ * copied links can open the wrong page.+ */+export function useExplorationCommentUrl({+ childTargetId,+ view,+}: UseExplorationCommentUrlOptions): string {+ const { pathname, search: locationSearch } = useLocation();+ if (!pathname) {+ return "";+ }++ const explorationId = parseExplorationId(pathname);+ if (explorationId == null) {+ return "";+ }++ const search = new URLSearchParams(locationSearch);+ if (childTargetId) {+ search.set("comments", childTargetId);+ } else {+ search.delete("comments");+ }++ const pinnedPath =+ view === "summary"+ ? Urls.explorationSummary(explorationId)+ : childTargetId != null+ ? Urls.explorationPage(explorationId, childTargetId)+ : Urls.exploration(explorationId);++ const query = search.toString();+ return query ? `${pinnedPath}?${query}` : pinnedPath;+}diff --git a/frontend/src/metabase/explorations/hooks/useExplorationCommentUrl.unit.spec.tsx b/frontend/src/metabase/explorations/hooks/useExplorationCommentUrl.unit.spec.tsxnew file mode 100644index 00000000000..fc58003876c--- /dev/null+++ b/frontend/src/metabase/explorations/hooks/useExplorationCommentUrl.unit.spec.tsx@@ -0,0 +1,66 @@+import { renderWithProviders, screen } from "__support__/ui";+import { Route } from "metabase/router";++import {+ type ExplorationCommentView,+ useExplorationCommentUrl,+} from "./useExplorationCommentUrl";++function Probe({+ childTargetId,+ view,+}: {+ childTargetId: string;+ view: ExplorationCommentView;+}) {+ const url = useExplorationCommentUrl({ childTargetId, view });+ return <div data-testid="comment-url">{url}</div>;+}++function setup(+ initialRoute: string,+ childTargetId: string,+ view: ExplorationCommentView = "page",+) {+ renderWithProviders(+ <Route+ path="*"+ element={<Probe childTargetId={childTargetId} view={view} />}+ />,+ { withRouter: true, initialRoute },+ );+ return screen.getByTestId("comment-url").textContent;+}++describe("useExplorationCommentUrl", () => {+ it("uses the ?comments=<childTargetId> search param and keeps a pinned page path", () => {+ expect(setup("/question/research/1/page/19?timeline=1", "19")).toBe(+ "/question/research/1/page/19?timeline=1&comments=19",+ );+ });++ it("pins the comment's page into a bare exploration URL, where the page is otherwise auto-selected", () => {+ expect(setup("/question/research/1?timeline=1", "19")).toBe(+ "/question/research/1/page/19?timeline=1&comments=19",+ );+ });++ it("repins the path to the comment's own page when a different page is in the URL", () => {+ expect(setup("/question/research/1/page/4", "19")).toBe(+ "/question/research/1/page/19?comments=19",+ );+ });++ it("deep-links Summary block comments with the node id on /summary", () => {+ const nodeId = "550e8400-e29b-41d4-a716-446655440000";+ expect(setup("/question/research/1/summary", nodeId, "summary")).toBe(+ `/question/research/1/summary?comments=${nodeId}`,+ );+ });++ it("pins the summary in a bare exploration URL", () => {+ expect(setup("/question/research/1", "19", "summary")).toBe(+ `/question/research/1/summary?comments=19`,+ );+ });+});diff --git a/frontend/src/metabase/explorations/pages/ExplorationPage.tsx b/frontend/src/metabase/explorations/pages/ExplorationPage.tsxindex 46bd3dbc107..92aecd0b8f1 100644--- a/frontend/src/metabase/explorations/pages/ExplorationPage.tsx+++ b/frontend/src/metabase/explorations/pages/ExplorationPage.tsx@@ -36,11 +36,13 @@ import {ExplorationTitle,} from "../components/ExplorationSidebar";import {+ type SelectedSidebarEntity,flattenTree,getExplorationSidebarModel,getExplorationSidebarTabsInfo,- pickInitialSidebarPage,+ pickInitialSidebarEntity,} from "../components/ExplorationSidebar/utils";+import { ExplorationSummary } from "../components/ExplorationSummary";import {ExplorationChartAreaSkeleton,ExplorationGroupVisualization,@@ -97,13 +99,19 @@ function activeThreadStaleDeadlines(});}-export function ExplorationPage() {+type ExplorationPageView = "summary";++interface ExplorationPageProps {+ view?: ExplorationPageView;+}++export function ExplorationPage({ view }: ExplorationPageProps) {const params = useParams<ExplorationPageParams>();- return <ExplorationPageForId key={params.id} />;+ return <ExplorationPageForId key={params.id} view={view} />;}-function ExplorationPageForId() {+function ExplorationPageForId({ view }: ExplorationPageProps) {const dispatch = useDispatch();const navigate = useNavigate();const { id = "", pageId } = useParams<ExplorationPageParams>();@@ -114,7 +122,12 @@ function ExplorationPageForId() {[location.search],);- const isCommentsSidebarOpen = searchParams.get("comments") === "true";+ // `?comments=<childTargetId>` opens the panel; `"true"` is accepted as a+ // legacy alias and resolves to the current page id when on a page route.+ const commentsParam = searchParams.get("comments") ?? undefined;+ const commentsChildTargetId =+ commentsParam === "true" ? pageId : commentsParam;+ const isCommentsSidebarOpen = commentsParam != null;const wasCommentsSidebarOpen = usePrevious(isCommentsSidebarOpen);const selectedSidebarTab = useMemo<ExplorationSidebarTab>(() => {@@ -148,30 +161,68 @@ function ExplorationPageForId() {const getSelectedPageUrl = useCallback((- pageId: ExplorationPageNodeId,+ nextPageId: ExplorationPageNodeId,options?: { tab?: ExplorationSidebarTab },) => {const search = new URLSearchParams(location.search);if (options?.tab) {search.set("tab", options.tab);}+ // Keep the comments panel open across page navigations, but retarget it+ // to the destination page so the query param stays accurate.+ if (search.has("comments")) {+ search.set("comments", String(nextPageId));+ }const searchString = search.toString();- return `${Urls.exploration(parseInt(params.id, 10))}/page/${encodeURIComponent(pageId)}${searchString ? `?${searchString}` : ""}`;+ return `${Urls.exploration(parseInt(params.id, 10))}/page/${encodeURIComponent(nextPageId)}${searchString ? `?${searchString}` : ""}`;},[params.id, location.search],);- const setSelectedPageId = useCallback(+ const getSelectedSummaryUrl = useCallback(+ (options?: { tab?: ExplorationSidebarTab }) => {+ const search = new URLSearchParams(location.search);+ if (options?.tab) {+ search.set("tab", options.tab);+ }+ const searchString = search.toString();+ return `${Urls.explorationSummary(parseInt(params.id, 10))}${searchString ? `?${searchString}` : ""}`;+ },+ [params.id, location.search],+ );++ const setSelectedEntity = useCallback((- pageId: ExplorationPageNodeId,+ entity: SelectedSidebarEntity,options?: { tab?: ExplorationSidebarTab; scrollIntoView?: boolean },) => {if (options?.scrollIntoView) {shouldScrollSelectionRef.current = true;}- navigate(getSelectedPageUrl(pageId, options));+ const url =+ entity.type === "summary"+ ? getSelectedSummaryUrl(options)+ : getSelectedPageUrl(entity.id, options);+ navigate(url);},- [navigate, getSelectedPageUrl],+ [navigate, getSelectedPageUrl, getSelectedSummaryUrl],+ );++ const setSelectedPageId = useCallback(+ (+ pageId: ExplorationPageNodeId,+ options?: { tab?: ExplorationSidebarTab; scrollIntoView?: boolean },+ ) => {+ setSelectedEntity({ type: "page", id: pageId }, options);+ },+ [setSelectedEntity],+ );++ const setSelectedSummary = useCallback(+ (options?: { tab?: ExplorationSidebarTab; scrollIntoView?: boolean }) => {+ setSelectedEntity({ type: "summary" }, options);+ },+ [setSelectedEntity],);// Poll the exploration while any query is still in a non-terminal state.@@ -278,40 +329,39 @@ function ExplorationPageForId() {sortOrder,]);- // Selection comes from the URL. When the URL has no page yet- // (e.g. user landed on `/explorations/:id` directly), fall back to- // the first query so the sidebar highlight, the scroll anchor, and- // the right-pane chart all agree on the very first paint — without- // waiting for the URL-sync effect below to navigate().- //- // Once the URL update lands the fallback drops out (params take- // precedence) and the URL becomes authoritative again.// Selection model://// - The URL is the "pinned by the user" indicator. Only user- // clicks call `setSelectedPageId`, which pushes the page- // into the URL. Once the URL carries a page, that's+ // clicks call `setSelectedEntity`, which pushes the entity+ // into the URL. Once the URL carries a page or summary, that's// authoritative — no more auto-tracking.//// - Until then, every render (including ones triggered by polling// bringing in fresh interestingness scores) re-derives the// selection from the current top of the sidebar via- // `pickInitialSidebarPage`. This is what makes the right pane+ // `pickInitialSidebarEntity`. This is what makes the right pane// and the sidebar follow the "first, most interesting chart"- // as new data lands.+ // as new data lands — until the Summary is curated, at which+ // point newcomers land on the Summary.//// We deliberately do NOT push the auto-derived selection into the// URL: doing so would freeze the selection at the first auto-pick// and prevent it from following subsequent data updates.- const selectedPageId: ExplorationPageNodeId | null = useMemo(() => {+ const selectedEntity: SelectedSidebarEntity | null = useMemo(() => {+ if (view === "summary") {+ return { type: "summary" };+ }if (params.pageId) {// Page ids are opaque strings (the page's numeric PK stringified, the// same value comments anchor to) — we URL-encode them on push and// decode them here.- return decodeURIComponent(params.pageId);+ return { type: "page", id: decodeURIComponent(params.pageId) };}- return pickInitialSidebarPage(tree);- }, [params.pageId, tree]);+ return pickInitialSidebarEntity(tree, exploration?.document);+ }, [view, params.pageId, tree, exploration?.document]);++ const selectedPageId =+ selectedEntity?.type === "page" ? selectedEntity.id : null;const pageIdToPageAndQueries: Map<ExplorationPageNodeId,@@ -554,8 +604,9 @@ function ExplorationPageForId() {selectedSidebarTab={selectedSidebarTab}getSelectedSidebarTabUrl={getSelectedSidebarTabUrl}tree={tree}- selectedPageId={selectedPageId}+ selectedEntity={selectedEntity}getSelectedPageUrl={getSelectedPageUrl}+ getSelectedSummaryUrl={getSelectedSummaryUrl}shouldScrollSelectionRef={shouldScrollSelectionRef}isOpen={isSidebarOpen}readPageIds={readPageIds}@@ -568,6 +619,15 @@ function ExplorationPageForId() {onNextPage={goToNextPage}onPrefetchPage={prefetchPage}/>+ {selectedEntity?.type === "summary" && exploration.document && (+ <ExplorationSummary+ document={exploration.document}+ explorationId={exploration.id}+ commentsChildTargetId={commentsChildTargetId}+ onCloseCommentsSidebar={closeCommentsSidebar}+ timelines={allTimelines}+ />+ )}{selectedPage && (<ExplorationGroupVisualization// Key on page id so the component remounts when the user@@ -589,13 +649,19 @@ function ExplorationPageForId() {isCommentsSidebarOpen={isCommentsSidebarOpen}wasCommentsSidebarOpen={wasCommentsSidebarOpen ?? false}onCloseCommentsSidebar={closeCommentsSidebar}+ canAddToSummary={+ exploration.can_write && exploration.document != null+ }+ setSelectedSummary={setSelectedSummary}onPreviousPage={previousPageId != null ? goToPreviousPage : undefined}onNextPage={nextPageId != null ? goToNextPage : undefined}/>)}- {!selectedPage && shouldPoll && <ExplorationChartAreaSkeleton />}+ {!selectedPage &&+ selectedEntity?.type !== "summary" &&+ shouldPoll && <ExplorationChartAreaSkeleton />}</Group></Stack></Group>diff --git a/frontend/src/metabase/explorations/routes.tsx b/frontend/src/metabase/explorations/routes.tsxindex 3c5d0058e5a..5c8afa68c1c 100644--- a/frontend/src/metabase/explorations/routes.tsx+++ b/frontend/src/metabase/explorations/routes.tsx@@ -26,10 +26,12 @@ const newExplorationPlanPage = () =>Component: NewExplorationPlanPage,}));-const explorationPage = () =>+const explorationPage = (view?: "summary") => () =>import(/* webpackChunkName: "explorations" */ "./pages/ExplorationPage").then(({ ExplorationPage }) => ({- Component: ExplorationPage,+ Component: function ExplorationPageRoute() {+ return <ExplorationPage view={view} />;+ },}),);@@ -42,8 +44,9 @@ export const getRoutes = () => {<Route index lazy={newExplorationPage} /><Route path="plan" lazy={newExplorationPlanPage} /></Route>- <Route path=":id" lazy={explorationPage} />- <Route path=":id/page/:pageId" lazy={explorationPage} />+ <Route path=":id" lazy={explorationPage()} />+ <Route path=":id/page/:pageId" lazy={explorationPage()} />+ <Route path=":id/summary" lazy={explorationPage("summary")} /></Route>);};diff --git a/frontend/src/metabase/explorations/routes.unit.spec.tsx b/frontend/src/metabase/explorations/routes.unit.spec.tsxindex c93f2577689..d8c352b7539 100644--- a/frontend/src/metabase/explorations/routes.unit.spec.tsx+++ b/frontend/src/metabase/explorations/routes.unit.spec.tsx@@ -6,7 +6,7 @@ describe("explorations routes", () => {it("resolves every page", async () => {const loaders = lazyLoaders(getExplorationsRoutes());- expect(loaders).toHaveLength(5);+ expect(loaders).toHaveLength(6);for (const load of loaders) {expect((await load()).Component).toBeDefined();diff --git a/frontend/src/metabase/explorations/selectors.ts b/frontend/src/metabase/explorations/selectors.tsindex db4495e2089..05bf8cd5852 100644--- a/frontend/src/metabase/explorations/selectors.ts+++ b/frontend/src/metabase/explorations/selectors.ts@@ -1,4 +1,43 @@+import { createSelector } from "@reduxjs/toolkit";+import type { State } from "metabase/redux/store";+import type { HighlightedCommentState } from "metabase/redux/store/explorations";+import type { ExplorationQuery, ExplorationQueryId } from "metabase-types/api";export const getCurrentExploration = (state: State) =>state.explorations.currentExploration;++export const getHighlightedComment = (state: State) =>+ state.explorations.highlightedComment;++export function getHighlightedForChildTarget(+ state: State,+ childTargetId: string,+): HighlightedCommentState | null {+ const comment = state.explorations.highlightedComment;+ if (comment == null || comment.childTargetId !== childTargetId) {+ return null;+ }+ return comment;+}++const EMPTY_QUERIES_BY_ID: Readonly<+ Record<ExplorationQueryId, ExplorationQuery>+> = {};++export const getQueriesById = createSelector(+ [getCurrentExploration],+ (exploration): Readonly<Record<ExplorationQueryId, ExplorationQuery>> => {+ const threads = exploration?.threads ?? [];+ if (threads.length === 0) {+ return EMPTY_QUERIES_BY_ID;+ }+ const record: Record<ExplorationQueryId, ExplorationQuery> = {};+ for (const thread of threads) {+ for (const query of thread.queries ?? []) {+ record[query.id] = query;+ }+ }+ return record;+ },+);diff --git a/frontend/src/metabase/explorations/selectors.unit.spec.ts b/frontend/src/metabase/explorations/selectors.unit.spec.tsnew file mode 100644index 00000000000..5d8fd1cc64e--- /dev/null+++ b/frontend/src/metabase/explorations/selectors.unit.spec.ts@@ -0,0 +1,114 @@+import { setHighlightedComment } from "metabase/explorations/explorations.slice";+import {+ createBlock,+ createExploration,+ createPage,+ createQuery,+} from "metabase/explorations/test-utils";+import { createMockState } from "metabase/redux/store/mocks";++import { getHighlightedForChildTarget, getQueriesById } from "./selectors";++describe("getHighlightedForChildTarget", () => {+ it("returns a stable null for non-matching child targets", () => {+ const state = createMockState({+ explorations: {+ highlightedComment: {+ childTargetId: "7",+ highlighted: { columnName: "count" },+ explorationQueryIds: [101],+ },+ },+ });++ const first = getHighlightedForChildTarget(state, "99");+ const second = getHighlightedForChildTarget(state, "88");++ expect(first).toBeNull();+ expect(second).toBeNull();+ expect(first).toBe(second);+ });++ it("returns the same state for two consumers sharing one child target id", () => {+ const highlightedComment = {+ childTargetId: "7",+ highlighted: { columnName: "count" },+ explorationQueryIds: [101],+ };+ const state = createMockState({+ explorations: { highlightedComment },+ });++ expect(getHighlightedForChildTarget(state, "7")).toBe(highlightedComment);+ expect(getHighlightedForChildTarget(state, "7")).toBe(highlightedComment);+ });++ it("clears when setHighlightedComment(null) is reflected in state", () => {+ const withHighlight = createMockState({+ explorations: {+ highlightedComment: {+ childTargetId: "7",+ highlighted: { columnName: "count" },+ explorationQueryIds: [101],+ },+ },+ });+ expect(getHighlightedForChildTarget(withHighlight, "7")).toEqual({+ childTargetId: "7",+ highlighted: { columnName: "count" },+ explorationQueryIds: [101],+ });++ const cleared = createMockState({+ explorations: { highlightedComment: null },+ });+ expect(getHighlightedForChildTarget(cleared, "7")).toBeNull();++ // Keep the action import exercised so the slice contract stays visible.+ expect(setHighlightedComment(null).type).toBe(+ "explorations/setHighlightedComment",+ );+ });+});++describe("getQueriesById", () => {+ it("returns all queries from the current exploration", () => {+ const queries = [+ createQuery({ id: 101, name: "US", status: "done" }),+ createQuery({ id: 102, name: "EU", status: "done" }),+ ];+ const state = createMockState({+ explorations: {+ currentExploration: createExploration({+ queries,+ blocks: [+ createBlock({+ id: 1,+ pages: [+ createPage({+ id: 7,+ name: "Page",+ query_ids: queries.map((query) => query.id),+ }),+ ],+ }),+ ],+ }),+ highlightedComment: null,+ },+ });++ expect(Object.keys(getQueriesById(state)).map(Number).sort()).toEqual([+ 101, 102,+ ]);+ expect(getQueriesById(state)[101]?.id).toBe(101);+ });++ it("returns a stable empty record when there is no exploration", () => {+ const state = createMockState({+ explorations: { highlightedComment: null },+ });+ expect(getQueriesById(state)).toEqual({});+ expect(getQueriesById(state)).toBe(getQueriesById(state));+ });+});diff --git a/frontend/src/metabase/nav/components/AppBar/AppBar.tsx b/frontend/src/metabase/nav/components/AppBar/AppBar.tsxindex ddaeacb4b34..ec1ae399bb8 100644--- a/frontend/src/metabase/nav/components/AppBar/AppBar.tsx+++ b/frontend/src/metabase/nav/components/AppBar/AppBar.tsx@@ -17,7 +17,6 @@ export interface AppBarProps {isNavBarOpen?: boolean;isNavBarEnabled?: boolean;isMetabotVisible?: boolean;- isCommentSidebarOpen?: boolean;isDocumentSidebarOpen?: boolean;isLogoVisible?: boolean;isSearchVisible?: boolean;diff --git a/frontend/src/metabase/nav/components/AppBar/AppBarLarge.tsx b/frontend/src/metabase/nav/components/AppBar/AppBarLarge.tsxindex b2bf3524611..36680a7137d 100644--- a/frontend/src/metabase/nav/components/AppBar/AppBarLarge.tsx+++ b/frontend/src/metabase/nav/components/AppBar/AppBarLarge.tsx@@ -25,7 +25,6 @@ export interface AppBarLargeProps {isNavBarEnabled?: boolean;isMetabotVisible?: boolean;isDocumentSidebarOpen?: boolean;- isCommentSidebarOpen?: boolean;isLogoVisible?: boolean;isSearchVisible?: boolean;isEmbeddingIframe?: boolean;@@ -47,7 +46,6 @@ export const AppBarLarge = ({isNavBarEnabled,isMetabotVisible,isDocumentSidebarOpen,- isCommentSidebarOpen,isLogoVisible,isSearchVisible,isEmbeddingIframe,@@ -74,7 +72,6 @@ export const AppBarLarge = ({isNavBarVisible ||isMetabotVisible ||isDocumentSidebarOpen ||- isCommentSidebarOpen ||isMetricsViewer}>diff --git a/frontend/src/metabase/query_builder/components/QueryModals/QueryModals.tsx b/frontend/src/metabase/query_builder/components/QueryModals/QueryModals.tsxindex 9d16c0e3e1e..d1f7d9819bc 100644--- a/frontend/src/metabase/query_builder/components/QueryModals/QueryModals.tsx+++ b/frontend/src/metabase/query_builder/components/QueryModals/QueryModals.tsx@@ -14,9 +14,6 @@ import { setArchivedQuestion } from "metabase/query_builder/actions";import { updateUrl } from "metabase/query_builder/actions/url";import { ImpossibleToCreateModelModal } from "metabase/query_builder/components/ImpossibleToCreateModelModal";import { NewDatasetModal } from "metabase/query_builder/components/NewDatasetModal";-import EditEventModal from "metabase/query_builder/components/timelines/containers/EditEventModal";-import MoveEventModal from "metabase/query_builder/components/timelines/containers/MoveEventModal";-import NewEventModal from "metabase/query_builder/components/timelines/containers/NewEventModal";import { PreviewQueryModal } from "metabase/query_builder/components/view/PreviewQueryModal";import {getQuestionWithoutComposing,@@ -28,6 +25,9 @@ import { MoveCardModal } from "metabase/questions/components/MoveCardModal";import { useDispatch, useSelector } from "metabase/redux";import type { QueryBuilderMode } from "metabase/redux/store";import { useNavigate } from "metabase/router";+import EditEventModal from "metabase/timelines/questions/containers/EditEventModal";+import MoveEventModal from "metabase/timelines/questions/containers/MoveEventModal";+import NewEventModal from "metabase/timelines/questions/containers/NewEventModal";import { Modal, Text } from "metabase/ui";import * as Urls from "metabase/urls";import Question from "metabase-lib/v1/Question";diff --git a/frontend/src/metabase/query_builder/components/view/View/NativeQueryRightSidebar/NativeQueryRightSidebar.tsx b/frontend/src/metabase/query_builder/components/view/View/NativeQueryRightSidebar/NativeQueryRightSidebar.tsxindex b9a2d388543..21c959927ab 100644--- a/frontend/src/metabase/query_builder/components/view/View/NativeQueryRightSidebar/NativeQueryRightSidebar.tsx+++ b/frontend/src/metabase/query_builder/components/view/View/NativeQueryRightSidebar/NativeQueryRightSidebar.tsx@@ -121,6 +121,7 @@ export const NativeQueryRightSidebar = (.with({ isShowingTimelineSidebar: true }, () => (<TimelineSidebar{...props}+ collectionId={question.collectionId()}onShowTimelineEvents={showTimelineEvents}onHideTimelineEvents={hideTimelineEvents}onSelectTimelineEvents={selectTimelineEvents}diff --git a/frontend/src/metabase/query_builder/components/view/View/StructuredQueryRightSidebar/StructuredQueryRightSidebar.tsx b/frontend/src/metabase/query_builder/components/view/View/StructuredQueryRightSidebar/StructuredQueryRightSidebar.tsxindex 512bff50951..805b6956fd8 100644--- a/frontend/src/metabase/query_builder/components/view/View/StructuredQueryRightSidebar/StructuredQueryRightSidebar.tsx+++ b/frontend/src/metabase/query_builder/components/view/View/StructuredQueryRightSidebar/StructuredQueryRightSidebar.tsx@@ -77,7 +77,7 @@ export const StructuredQueryRightSidebar = ({).with({ isShowingTimelineSidebar: true }, () => (<TimelineSidebar- question={question}+ collectionId={question.collectionId()}timelines={timelines}visibleTimelineEventIds={visibleTimelineEventIds}selectedTimelineEventIds={selectedTimelineEventIds}diff --git a/frontend/src/metabase/query_builder/components/view/sidebars/TimelineSidebar/TimelineSidebar.tsx b/frontend/src/metabase/query_builder/components/view/sidebars/TimelineSidebar/TimelineSidebar.tsxindex c9a0d6ce7f0..1f36b585e11 100644--- a/frontend/src/metabase/query_builder/components/view/sidebars/TimelineSidebar/TimelineSidebar.tsx+++ b/frontend/src/metabase/query_builder/components/view/sidebars/TimelineSidebar/TimelineSidebar.tsx@@ -1,195 +1,58 @@-import { useCallback, useMemo } from "react";-import { t } from "ttag";+import { useCallback } from "react";-import { SidebarContent } from "metabase/common/components/SidebarContent";-import { type Dayjs, type OpUnitType, dayjs } from "metabase/dayjs";-import TimelinePanel from "metabase/query_builder/components/timelines/containers/TimelinePanel";import {getTimeseriesDataInterval,getUiControls,} from "metabase/query_builder/selectors";-import { MODAL_TYPES, type QueryModalType } from "metabase/querying/constants";import { useDispatch, useSelector } from "metabase/redux";import { onOpenTimelines } from "metabase/redux/query-builder";-import { Box, Button, Icon } from "metabase/ui";-import { formatDateTimeWithUnit } from "metabase/value-formatting";-import type { CartesianChartDateTimeAbsoluteUnit } from "metabase/visualizations/echarts/cartesian/model/types";-import type Question from "metabase-lib/v1/Question";-import type { DatetimeUnit, Timeline, TimelineEvent } from "metabase-types/api";+import {+ TimelineSidebar as SharedTimelineSidebar,+ type TimelineSidebarProps as SharedTimelineSidebarProps,+} from "metabase/timelines/questions/components/TimelineSidebar";-export interface TimelineSidebarProps {- question: Question;- timelines: Timeline[];- visibleTimelineEventIds: number[];- selectedTimelineEventIds: number[];- xDomain?: [Dayjs, Dayjs];- onShowTimelineEvents: (timelineEvent: TimelineEvent[]) => void;- onHideTimelineEvents: (timelineEvent: TimelineEvent[]) => void;- onSelectTimelineEvents?: (timelineEvents: TimelineEvent[]) => void;- onDeselectTimelineEvents?: () => void;- onOpenModal?: (modal: QueryModalType, modalContext?: unknown) => void;- onClose?: () => void;-}+export type TimelineSidebarProps = Omit<+ SharedTimelineSidebarProps,+ "focusedTimelineEventIds" | "dataInterval" | "onShowAllEvents"+>;export const TimelineSidebar = ({- question,+ collectionId,timelines,visibleTimelineEventIds,selectedTimelineEventIds,xDomain,- onOpenModal,onShowTimelineEvents,onHideTimelineEvents,onSelectTimelineEvents,onDeselectTimelineEvents,+ onOpenModal,onClose,}: TimelineSidebarProps) => {const dispatch = useDispatch();const { focusedTimelineEventIds } = useSelector(getUiControls);const dataInterval = useSelector(getTimeseriesDataInterval);- const displayedTimelines = useMemo(- () => getFocusedTimelines(timelines, focusedTimelineEventIds),- [timelines, focusedTimelineEventIds],- );-- const focusedXDomain = useMemo(- () =>- focusedTimelineEventIds != null- ? getEventsXDomain(displayedTimelines)- : undefined,- [focusedTimelineEventIds, displayedTimelines],- );-- const title = focusedXDomain- ? formatTitle(focusedXDomain, toDatetimeUnit(dataInterval?.unit))- : formatTitle(xDomain);-const handleShowAllEvents = useCallback(() => {dispatch(onOpenTimelines());}, [dispatch]);- const handleNewEvent = useCallback(() => {- onOpenModal?.(MODAL_TYPES.NEW_EVENT);- }, [onOpenModal]);-- const handleEditEvent = useCallback(- (event: TimelineEvent) => {- onOpenModal?.(MODAL_TYPES.EDIT_EVENT, event.id);- },- [onOpenModal],- );-- const handleMoveEvent = useCallback(- (event: TimelineEvent) => {- onOpenModal?.(MODAL_TYPES.MOVE_EVENT, event.id);- },- [onOpenModal],- );-- const handleToggleEventSelected = useCallback(- (event: TimelineEvent, isSelected: boolean) => {- if (isSelected) {- onSelectTimelineEvents?.([event]);- } else {- onDeselectTimelineEvents?.();- }- },- [onSelectTimelineEvents, onDeselectTimelineEvents],- );-return (- <SidebarContent title={title} onClose={onClose}>- {focusedTimelineEventIds != null && (- <Box mx="lg" mb="sm">- <Button- p={0}- variant="subtle"- leftSection={<Icon name="chevronleft" />}- onClick={handleShowAllEvents}- data-testid="timeline-sidebar-show-all"- >- {t`All events`}- </Button>- </Box>- )}- <TimelinePanel- timelines={displayedTimelines}- collectionId={question.collectionId()}- visibleEventIds={visibleTimelineEventIds}- selectedEventIds={selectedTimelineEventIds}- onNewEvent={handleNewEvent}- onEditEvent={handleEditEvent}- onMoveEvent={handleMoveEvent}- onToggleEventSelected={handleToggleEventSelected}- onShowTimelineEvents={onShowTimelineEvents}- onHideTimelineEvents={onHideTimelineEvents}- />- </SidebarContent>+ <SharedTimelineSidebar+ collectionId={collectionId}+ timelines={timelines}+ visibleTimelineEventIds={visibleTimelineEventIds}+ selectedTimelineEventIds={selectedTimelineEventIds}+ focusedTimelineEventIds={focusedTimelineEventIds}+ dataInterval={dataInterval}+ xDomain={xDomain}+ onShowTimelineEvents={onShowTimelineEvents}+ onHideTimelineEvents={onHideTimelineEvents}+ onSelectTimelineEvents={onSelectTimelineEvents}+ onDeselectTimelineEvents={onDeselectTimelineEvents}+ onShowAllEvents={handleShowAllEvents}+ onOpenModal={onOpenModal}+ onClose={onClose}+ />);};--export const getFocusedTimelines = (- timelines: Timeline[],- focusedTimelineEventIds: number[] | null,-): Timeline[] => {- if (focusedTimelineEventIds == null) {- return timelines;- }- const focusedIds = new Set(focusedTimelineEventIds);- return timelines- .map((timeline) => ({- ...timeline,- events: (timeline.events ?? []).filter((event) =>- focusedIds.has(event.id),- ),- }))- .filter((timeline) => timeline.events.length > 0);-};--export const getEventsXDomain = (- timelines: Timeline[],-): [Dayjs, Dayjs] | undefined => {- const timestamps = timelines- .flatMap((timeline) => timeline.events ?? [])- .map((event) => dayjs.utc(event.timestamp));-- if (timestamps.length === 0) {- return undefined;- }-- const min = timestamps.reduce((a, b) => (b.isBefore(a) ? b : a));- const max = timestamps.reduce((a, b) => (b.isAfter(a) ? b : a));- return [min, max];-};--const toDatetimeUnit = (- unit?: CartesianChartDateTimeAbsoluteUnit,-): DatetimeUnit | undefined =>- unit == null || unit === "second" || unit === "ms" ? undefined : unit;--const isPeriodUnit = (unit?: DatetimeUnit) =>- unit === "week" || unit === "month" || unit === "quarter" || unit === "year";--export const formatTitle = (xDomain?: [Dayjs, Dayjs], unit?: DatetimeUnit) => {- if (!xDomain) {- return t`Events`;- }- const startLabel = formatDate(xDomain[0], unit);- const endLabel = formatDate(xDomain[1], unit);- if (startLabel !== endLabel) {- return t`Events between ${startLabel} and ${endLabel}`;- }-- return isPeriodUnit(unit)- ? t`Events in ${startLabel}`- : t`Events on ${startLabel}`;-};--const formatDate = (date: Dayjs, unit?: DatetimeUnit) => {- if (unit == null) {- return date.format("ll");- }- // Unjustified type cast. FIXME- return formatDateTimeWithUnit(date.startOf(unit as OpUnitType), unit);-};diff --git a/frontend/src/metabase/redux/store/documents.ts b/frontend/src/metabase/redux/store/documents.tsindex 6d3efa15872..7357eec2b48 100644--- a/frontend/src/metabase/redux/store/documents.ts+++ b/frontend/src/metabase/redux/store/documents.ts@@ -1,8 +1,16 @@-import type { Card, Document } from "metabase-types/api";+import type {+ Card,+ CardId,+ Document,+ StoredResultSort,+ TimelineEventId,+} from "metabase-types/api";export interface CardEmbedRef {id: number;name?: string;+ stored_result_id?: number | null;+ sort?: StoredResultSort | null;}export interface MentionCacheItem {@@ -11,15 +19,25 @@ export interface MentionCacheItem {name: string;}+export type DocumentsSidebar =+ | { mode: "viz-settings"; embedIndex: number }+ | {+ mode: "timeline-events";+ embedIndex: number;+ focusedEventIds: TimelineEventId[] | null;+ selectedEventIds: TimelineEventId[];+ }+ | { mode: "comments" }+ | { mode: "history" };+export interface DocumentsState {- selectedEmbedIndex: number | null;+ sidebar: DocumentsSidebar | null;cardEmbeds: CardEmbedRef[];currentDocument: Document | null;draftCards: Record<number, Card>;+ draftCardOriginalIds: Record<number, CardId>;mentionsCache: Record<string, MentionCacheItem>;- isCommentSidebarOpen: boolean;childTargetId: string | undefined;hoveredChildTargetId: string | undefined;hasUnsavedChanges: boolean;- isHistorySidebarOpen: boolean;}diff --git a/frontend/src/metabase/redux/store/explorations.ts b/frontend/src/metabase/redux/store/explorations.tsindex 2e2d555e148..f96701032c7 100644--- a/frontend/src/metabase/redux/store/explorations.ts+++ b/frontend/src/metabase/redux/store/explorations.ts@@ -1,5 +1,13 @@-import type { Exploration } from "metabase-types/api";+import type { HighlightedObject } from "metabase/visualizations/types";+import type { Exploration, ExplorationQueryId } from "metabase-types/api";++export interface HighlightedCommentState {+ childTargetId: string;+ highlighted: HighlightedObject;+ explorationQueryIds: ExplorationQueryId[];+}export interface ExplorationsState {currentExploration?: Exploration;+ highlightedComment: HighlightedCommentState | null;}diff --git a/frontend/src/metabase/redux/store/mocks/explorations.ts b/frontend/src/metabase/redux/store/mocks/explorations.tsindex 4c5b1e7f090..c540838415c 100644--- a/frontend/src/metabase/redux/store/mocks/explorations.ts+++ b/frontend/src/metabase/redux/store/mocks/explorations.ts@@ -4,6 +4,7 @@ export const createMockExplorationsState = (opts?: Partial<ExplorationsState>,): ExplorationsState => {return {+ highlightedComment: null,...opts,};};diff --git a/frontend/src/metabase/rich_text_editing/tiptap/EditorHost.tsx b/frontend/src/metabase/rich_text_editing/tiptap/EditorHost.tsxindex b612353c951..a703a72ecfa 100644--- a/frontend/src/metabase/rich_text_editing/tiptap/EditorHost.tsx+++ b/frontend/src/metabase/rich_text_editing/tiptap/EditorHost.tsx@@ -1,5 +1,5 @@import type { Editor } from "@tiptap/react";-import { createContext, useContext } from "react";+import { type ReactNode, createContext, useContext } from "react";import type { State } from "metabase/redux/store";import type Question from "metabase-lib/v1/Question";@@ -7,8 +7,9 @@ import type {Card,Dataset,Document,- EntityId,RawSeries,+ StoredResultSort,+ TimelineEvent,VisualizationSettings,} from "metabase-types/api";@@ -55,6 +56,25 @@ type Selector<T> = (state: State) => T;*/type DispatchableAction = any;+/**+ * What the surrounding surface lets the editor do. Hosts declare these instead+ * of exposing a surface enum the editor has to branch on: a restricted surface+ * (e.g. exploration Summary) flips the relevant flag to false. Adding a new+ * surface is "provide a host with these flags", not "find every surface check".+ */+export interface EditorCapabilities {+ canEmbedCharts: boolean;+ canUseMetabot: boolean;+ canOpenCardInQueryBuilder: boolean;+}++/** Capabilities for an unrestricted surface (standalone documents, comments, …). */+export const DEFAULT_EDITOR_CAPABILITIES: EditorCapabilities = {+ canEmbedCharts: true,+ canUseMetabot: true,+ canOpenCardInQueryBuilder: true,+};+/** Document state read by most extensions, regardless of which are enabled. */export interface EditorDocumentHost {selectors: {@@ -63,6 +83,21 @@ export interface EditorDocumentHost {};}+/**+ * Host-contributed UI placed into named holes in CardEmbed's layout.+ * CardEmbed owns placement; hosts interpret `host_data` and fill slots.+ */+export type CardEmbedSlots = {+ belowTitle?: ReactNode;+};++export const EMPTY_CARD_EMBED_SLOTS: CardEmbedSlots = {};++export type CardEmbedSlotContext = {+ childTargetId: string;+ hostData?: Record<string, unknown> | null;+};+/** Embedding, rendering and authoring cards: the CardEmbed node, the* create/modify-question modals, and the Metabot embed. */export interface EditorCardHost {@@ -70,7 +105,12 @@ export interface EditorCardHost {url: string,document?: Document | null,) => DispatchableAction;- useCardData: (props: { id: number; skip?: boolean }) => UseCardDataResult;+ useCardData: (props: {+ id: number;+ skip?: boolean;+ storedResultId?: number;+ storedResultSort?: StoredResultSort;+ }) => UseCardDataResult;useExternalCardDataLoader: (cardId: number,opts?: { skip?: boolean },@@ -83,6 +123,7 @@ export interface EditorCardHost {selectedEmbedIndex: number | null,regularDataset: Dataset | null | undefined,) => DraftCardOperations;+ useCardEmbedSlots: (opts: CardEmbedSlotContext) => CardEmbedSlots;actions: {createDraftCard: (payload: {originalCard: Card | undefined;@@ -94,11 +135,21 @@ export interface EditorCardHost {openVizSettingsSidebar: (payload: {embedIndex: number;}) => DispatchableAction;+ openTimelineEventsSidebar: (payload: {+ embedIndex: number;+ focusedEventIds?: number[];+ }) => DispatchableAction;+ selectTimelineEvents: (payload: TimelineEvent[]) => DispatchableAction;+ deselectTimelineEvents: () => DispatchableAction;updateVizSettings: (payload: {cardId: number;settings: VisualizationSettings;}) => DispatchableAction;};+ selectors: {+ getSelectedEmbedIndex: Selector<number | null>;+ getSelectedTimelineEventIds: Selector<number[]>;+ };}/** Comment menus on blocks and card embeds. */@@ -107,7 +158,7 @@ export interface EditorCommentsHost {getChildTargetId: Selector<string | undefined>;getHoveredChildTargetId: Selector<string | undefined>;};- useCommentUrl: (opts: { childTargetId: EntityId | null }) => string;+ useCommentUrl: (opts: { childTargetId: string | null }) => string;useUnresolvedCommentsCount: (nodeId: string,opts?: { skip?: boolean },@@ -154,7 +205,9 @@ export type EditorHost = EditorDocumentHost &EditorCommentsHost &EditorViewportHost &EditorMentionsHost &- EditorAnalyticsHost;+ EditorAnalyticsHost & {+ capabilities: EditorCapabilities;+ };const noop = () => undefined;@@ -166,17 +219,23 @@ const noop = () => undefined;* provide one.*/export const DEFAULT_EDITOR_HOST: EditorHost = {+ capabilities: DEFAULT_EDITOR_CAPABILITIES,selectors: {getCurrentDocument: () => null,getChildTargetId: () => undefined,getHoveredChildTargetId: () => undefined,getHasUnsavedChanges: () => false,+ getSelectedEmbedIndex: () => null,+ getSelectedTimelineEventIds: () => [],},actions: {createDraftCard: () => ({ type: "@@editor-host/noop" }),generateDraftCardId: () => -1,loadMetadataForDocumentCard: () => ({ type: "@@editor-host/noop" }),openVizSettingsSidebar: () => ({ type: "@@editor-host/noop" }),+ openTimelineEventsSidebar: () => ({ type: "@@editor-host/noop" }),+ selectTimelineEvents: () => ({ type: "@@editor-host/noop" }),+ deselectTimelineEvents: () => ({ type: "@@editor-host/noop" }),updateVizSettings: () => ({ type: "@@editor-host/noop" }),updateMentionsCache: () => ({ type: "@@editor-host/noop" }),},@@ -199,6 +258,7 @@ export const DEFAULT_EDITOR_HOST: EditorHost = {}),useReportPrefetchLoading: () => undefined,useDraftCardOperations: () => ({ ensureDraftCard: () => -1 }),+ useCardEmbedSlots: () => EMPTY_CARD_EMBED_SLOTS,};const EditorHostContext = createContext<EditorHost>(DEFAULT_EDITOR_HOST);diff --git a/frontend/src/metabase/rich_text_editing/tiptap/extensions/Command/CommandSuggestion.tsx b/frontend/src/metabase/rich_text_editing/tiptap/extensions/Command/CommandSuggestion.tsxindex 94c30fe7896..cf99314e977 100644--- a/frontend/src/metabase/rich_text_editing/tiptap/extensions/Command/CommandSuggestion.tsx+++ b/frontend/src/metabase/rich_text_editing/tiptap/extensions/Command/CommandSuggestion.tsx@@ -129,9 +129,11 @@ export const CommandSuggestion = forwardRef<const itemRefs = useRef<(HTMLButtonElement | null)[]>([]);+ const { capabilities } = host;+const allCommandSections: CommandSection[] = useMemo(- () => getAllCommandSections(metabotCommand),- [metabotCommand],+ () => getAllCommandSections(metabotCommand, capabilities),+ [metabotCommand, capabilities],);const allCommandOptions = useMemo(@@ -169,7 +171,8 @@ export const CommandSuggestion = forwardRef<[newQuestionOptions],);- const areChartsAllowed = !editor.isActive("supportingText");+ const areChartsAllowed =+ !editor.isActive("supportingText") && capabilities.canEmbedCharts;const canBrowseAll = areChartsAllowed || viewMode === "linkTo";const canCreateNewQuestion =diff --git a/frontend/src/metabase/rich_text_editing/tiptap/extensions/Command/utils.ts b/frontend/src/metabase/rich_text_editing/tiptap/extensions/Command/utils.tsindex 3872927f4ff..1e1baf43fe0 100644--- a/frontend/src/metabase/rich_text_editing/tiptap/extensions/Command/utils.ts+++ b/frontend/src/metabase/rich_text_editing/tiptap/extensions/Command/utils.ts@@ -1,5 +1,7 @@import { t } from "ttag";+import type { EditorCapabilities } from "metabase/rich_text_editing/tiptap/EditorHost";+import type { CommandSection } from "./types";export type MetabotCommandConfig = {@@ -7,12 +9,13 @@ export type MetabotCommandConfig = {};export const getAllCommandSections = (- metabotCommand?: MetabotCommandConfig | null,+ metabotCommand: MetabotCommandConfig | null | undefined,+ capabilities: EditorCapabilities,): CommandSection[] => {return [{items: [- ...(metabotCommand+ ...(metabotCommand && capabilities.canUseMetabot? ([{icon: "metabot" as const,@@ -23,12 +26,17 @@ export const getAllCommandSections = (},] satisfies CommandSection["items"]): []),- {- icon: "lineandbar",- label: t`Chart`,- command: "embedQuestion",- isAllowedAtPosition: (editor) => !editor.isActive("supportingText"),- },+ ...(capabilities.canEmbedCharts+ ? ([+ {+ icon: "lineandbar",+ label: t`Chart`,+ command: "embedQuestion",+ isAllowedAtPosition: (editor) =>+ !editor.isActive("supportingText"),+ },+ ] satisfies CommandSection["items"])+ : []),{icon: "link",label: t`Link`,diff --git a/frontend/src/metabase/query_builder/components/timelines/components/EventCard/EventCard.styled.tsx b/frontend/src/metabase/timelines/questions/components/EventCard/EventCard.styled.tsxsimilarity index 100%rename from frontend/src/metabase/query_builder/components/timelines/components/EventCard/EventCard.styled.tsxrename to frontend/src/metabase/timelines/questions/components/EventCard/EventCard.styled.tsxdiff --git a/frontend/src/metabase/query_builder/components/timelines/components/EventCard/EventCard.tsx b/frontend/src/metabase/timelines/questions/components/EventCard/EventCard.tsxsimilarity index 86%rename from frontend/src/metabase/query_builder/components/timelines/components/EventCard/EventCard.tsxrename to frontend/src/metabase/timelines/questions/components/EventCard/EventCard.tsxindex 8bf9041728c..1fd648e5539 100644--- a/frontend/src/metabase/query_builder/components/timelines/components/EventCard/EventCard.tsx+++ b/frontend/src/metabase/timelines/questions/components/EventCard/EventCard.tsx@@ -107,17 +107,29 @@ const getMenuItems = (return [];}- return [- <Menu.Item key="edit-event" onClick={() => onEdit?.(event)}>- {t`Edit event`}- </Menu.Item>,- <Menu.Item key="move-event" onClick={() => onMove?.(event)}>- {t`Move event`}- </Menu.Item>,- <Menu.Item key="archive-event" onClick={() => onArchive?.(event)}>- {t`Archive event`}- </Menu.Item>,- ];+ const items = [];+ if (onEdit) {+ items.push(+ <Menu.Item key="edit-event" onClick={() => onEdit(event)}>+ {t`Edit event`}+ </Menu.Item>,+ );+ }+ if (onMove) {+ items.push(+ <Menu.Item key="move-event" onClick={() => onMove(event)}>+ {t`Move event`}+ </Menu.Item>,+ );+ }+ if (onArchive) {+ items.push(+ <Menu.Item key="archive-event" onClick={() => onArchive(event)}>+ {t`Archive event`}+ </Menu.Item>,+ );+ }+ return items;};// eslint-disable-next-line import/no-default-export -- deprecated usagediff --git a/frontend/src/metabase/query_builder/components/timelines/components/EventCard/EventCard.unit.spec.tsx b/frontend/src/metabase/timelines/questions/components/EventCard/EventCard.unit.spec.tsxsimilarity index 63%rename from frontend/src/metabase/query_builder/components/timelines/components/EventCard/EventCard.unit.spec.tsxrename to frontend/src/metabase/timelines/questions/components/EventCard/EventCard.unit.spec.tsxindex 7a719c67647..2d7de54e803 100644--- a/frontend/src/metabase/query_builder/components/timelines/components/EventCard/EventCard.unit.spec.tsx+++ b/frontend/src/metabase/timelines/questions/components/EventCard/EventCard.unit.spec.tsx@@ -2,6 +2,7 @@ import userEvent from "@testing-library/user-event";import { render, screen } from "__support__/ui";import {+ createMockCollection,createMockTimeline,createMockTimelineEvent,} from "metabase-types/api/mocks";@@ -53,6 +54,39 @@ describe("EventCard", () => {await userEvent.click(screen.getByRole("checkbox"));expect(props.onHideTimelineEvents).toHaveBeenCalled();});++ it("only shows menu items for handlers that are supplied", async () => {+ const onArchive = jest.fn();+ render(+ <EventCard+ {...getProps({+ timeline: createMockTimeline({+ collection: createMockCollection({ can_write: true }),+ }),+ onArchive,+ })}+ />,+ );++ await userEvent.click(screen.getByLabelText("Event menu"));+ expect(screen.getByText("Archive event")).toBeInTheDocument();+ expect(screen.queryByText("Edit event")).not.toBeInTheDocument();+ expect(screen.queryByText("Move event")).not.toBeInTheDocument();+ });++ it("hides the menu when no handlers are supplied", () => {+ render(+ <EventCard+ {...getProps({+ timeline: createMockTimeline({+ collection: createMockCollection({ can_write: true }),+ }),+ })}+ />,+ );++ expect(screen.queryByLabelText("Event menu")).not.toBeInTheDocument();+ });});const getProps = (opts?: Partial<EventCardProps>): EventCardProps => ({diff --git a/frontend/src/metabase/query_builder/components/timelines/components/EventCard/index.ts b/frontend/src/metabase/timelines/questions/components/EventCard/index.tssimilarity index 100%rename from frontend/src/metabase/query_builder/components/timelines/components/EventCard/index.tsrename to frontend/src/metabase/timelines/questions/components/EventCard/index.tsdiff --git a/frontend/src/metabase/query_builder/components/timelines/components/TimelineCard/TimelineCard.module.css b/frontend/src/metabase/timelines/questions/components/TimelineCard/TimelineCard.module.csssimilarity index 100%rename from frontend/src/metabase/query_builder/components/timelines/components/TimelineCard/TimelineCard.module.cssrename to frontend/src/metabase/timelines/questions/components/TimelineCard/TimelineCard.module.cssdiff --git a/frontend/src/metabase/query_builder/components/timelines/components/TimelineCard/TimelineCard.tsx b/frontend/src/metabase/timelines/questions/components/TimelineCard/TimelineCard.tsxsimilarity index 100%rename from frontend/src/metabase/query_builder/components/timelines/components/TimelineCard/TimelineCard.tsxrename to frontend/src/metabase/timelines/questions/components/TimelineCard/TimelineCard.tsxdiff --git a/frontend/src/metabase/query_builder/components/timelines/components/TimelineCard/TimelineCard.unit.spec.tsx b/frontend/src/metabase/timelines/questions/components/TimelineCard/TimelineCard.unit.spec.tsxsimilarity index 100%rename from frontend/src/metabase/query_builder/components/timelines/components/TimelineCard/TimelineCard.unit.spec.tsxrename to frontend/src/metabase/timelines/questions/components/TimelineCard/TimelineCard.unit.spec.tsxdiff --git a/frontend/src/metabase/query_builder/components/timelines/components/TimelineEmptyState/TimelineEmptyState.tsx b/frontend/src/metabase/timelines/questions/components/TimelineEmptyState/TimelineEmptyState.tsxsimilarity index 98%rename from frontend/src/metabase/query_builder/components/timelines/components/TimelineEmptyState/TimelineEmptyState.tsxrename to frontend/src/metabase/timelines/questions/components/TimelineEmptyState/TimelineEmptyState.tsxindex 6a12ac67a35..9b667dae667 100644--- a/frontend/src/metabase/query_builder/components/timelines/components/TimelineEmptyState/TimelineEmptyState.tsx+++ b/frontend/src/metabase/timelines/questions/components/TimelineEmptyState/TimelineEmptyState.tsx@@ -46,7 +46,7 @@ const TimelineEmptyState = ({: t`Events in ${applicationName} let you see important milestones, launches, or anything else, right alongside your data.`}</Text></Box>- {canWrite && (+ {canWrite && onNewEvent != null && (<Button variant="filled" w="12.5rem" onClick={onNewEvent}>{t`Create event`}</Button>diff --git a/frontend/src/metabase/query_builder/components/timelines/components/TimelineEmptyState/TimelineEmptyState.unit.spec.tsx b/frontend/src/metabase/timelines/questions/components/TimelineEmptyState/TimelineEmptyState.unit.spec.tsxsimilarity index 100%rename from frontend/src/metabase/query_builder/components/timelines/components/TimelineEmptyState/TimelineEmptyState.unit.spec.tsxrename to frontend/src/metabase/timelines/questions/components/TimelineEmptyState/TimelineEmptyState.unit.spec.tsxdiff --git a/frontend/src/metabase/query_builder/components/timelines/components/TimelineEmptyState/index.ts b/frontend/src/metabase/timelines/questions/components/TimelineEmptyState/index.tssimilarity index 100%rename from frontend/src/metabase/query_builder/components/timelines/components/TimelineEmptyState/index.tsrename to frontend/src/metabase/timelines/questions/components/TimelineEmptyState/index.tsdiff --git a/frontend/src/metabase/query_builder/components/timelines/components/TimelineList/TimelineList.tsx b/frontend/src/metabase/timelines/questions/components/TimelineList/TimelineList.tsxsimilarity index 92%rename from frontend/src/metabase/query_builder/components/timelines/components/TimelineList/TimelineList.tsxrename to frontend/src/metabase/timelines/questions/components/TimelineList/TimelineList.tsxindex 108d12a6a50..572ece353c0 100644--- a/frontend/src/metabase/query_builder/components/timelines/components/TimelineList/TimelineList.tsx+++ b/frontend/src/metabase/timelines/questions/components/TimelineList/TimelineList.tsx@@ -1,6 +1,7 @@-import { TimelineCard } from "metabase/query_builder/components/timelines/components/TimelineCard/TimelineCard";import type { Timeline, TimelineEvent } from "metabase-types/api";+import { TimelineCard } from "../TimelineCard/TimelineCard";+export interface TimelineListProps {timelines: Timeline[];visibleEventIds: number[];diff --git a/frontend/src/metabase/query_builder/components/timelines/components/TimelineList/TimelineList.unit.spec.tsx b/frontend/src/metabase/timelines/questions/components/TimelineList/TimelineList.unit.spec.tsxsimilarity index 100%rename from frontend/src/metabase/query_builder/components/timelines/components/TimelineList/TimelineList.unit.spec.tsxrename to frontend/src/metabase/timelines/questions/components/TimelineList/TimelineList.unit.spec.tsxdiff --git a/frontend/src/metabase/query_builder/components/timelines/components/TimelineList/index.ts b/frontend/src/metabase/timelines/questions/components/TimelineList/index.tssimilarity index 100%rename from frontend/src/metabase/query_builder/components/timelines/components/TimelineList/index.tsrename to frontend/src/metabase/timelines/questions/components/TimelineList/index.tsdiff --git a/frontend/src/metabase/query_builder/components/timelines/components/TimelinePanel/TimelinePanel.tsx b/frontend/src/metabase/timelines/questions/components/TimelinePanel/TimelinePanel.tsxsimilarity index 95%rename from frontend/src/metabase/query_builder/components/timelines/components/TimelinePanel/TimelinePanel.tsxrename to frontend/src/metabase/timelines/questions/components/TimelinePanel/TimelinePanel.tsxindex 4f4411ef216..7b3eda57cea 100644--- a/frontend/src/metabase/query_builder/components/timelines/components/TimelinePanel/TimelinePanel.tsx+++ b/frontend/src/metabase/timelines/questions/components/TimelinePanel/TimelinePanel.tsx@@ -35,10 +35,11 @@ const TimelinePanel = ({}: TimelinePanelProps): JSX.Element => {const isEmpty = timelines.length === 0;const canWrite = collection.can_write;+ const canCreateEvent = canWrite && onNewEvent != null;return (<Box mx="lg">- {!isEmpty && canWrite && (+ {!isEmpty && canCreateEvent && (<Box mb="md"><Button onClick={onNewEvent}>{t`Create event`}</Button></Box>diff --git a/frontend/src/metabase/query_builder/components/timelines/components/TimelinePanel/TimelinePanel.unit.spec.tsx b/frontend/src/metabase/timelines/questions/components/TimelinePanel/TimelinePanel.unit.spec.tsxsimilarity index 83%rename from frontend/src/metabase/query_builder/components/timelines/components/TimelinePanel/TimelinePanel.unit.spec.tsxrename to frontend/src/metabase/timelines/questions/components/TimelinePanel/TimelinePanel.unit.spec.tsxindex 91b5ea33a56..c88899c282a 100644--- a/frontend/src/metabase/query_builder/components/timelines/components/TimelinePanel/TimelinePanel.unit.spec.tsx+++ b/frontend/src/metabase/timelines/questions/components/TimelinePanel/TimelinePanel.unit.spec.tsx@@ -48,6 +48,18 @@ describe("TimelinePanel", () => {expect(screen.queryByText("Create event")).not.toBeInTheDocument();});++ it("should not allow creating events when onNewEvent is omitted", () => {+ const props = getProps({+ timelines: [createMockTimeline()],+ collection: createMockCollection({ can_write: true }),+ onNewEvent: undefined,+ });++ setup(props);++ expect(screen.queryByText("Create event")).not.toBeInTheDocument();+ });});const getProps = (opts?: Partial<TimelinePanelProps>): TimelinePanelProps => ({diff --git a/frontend/src/metabase/query_builder/components/timelines/components/TimelinePanel/index.ts b/frontend/src/metabase/timelines/questions/components/TimelinePanel/index.tssimilarity index 100%rename from frontend/src/metabase/query_builder/components/timelines/components/TimelinePanel/index.tsrename to frontend/src/metabase/timelines/questions/components/TimelinePanel/index.tsdiff --git a/frontend/src/metabase/timelines/questions/components/TimelineSidebar/TimelineSidebar.tsx b/frontend/src/metabase/timelines/questions/components/TimelineSidebar/TimelineSidebar.tsxnew file mode 100644index 00000000000..72ef3bdd5a4--- /dev/null+++ b/frontend/src/metabase/timelines/questions/components/TimelineSidebar/TimelineSidebar.tsx@@ -0,0 +1,270 @@+import { useCallback, useMemo, useState } from "react";+import { t } from "ttag";++import { SidebarContent } from "metabase/common/components/SidebarContent";+import { type Dayjs, type OpUnitType, dayjs } from "metabase/dayjs";+import { MODAL_TYPES, type QueryModalType } from "metabase/querying/constants";+import EditEventModal from "metabase/timelines/questions/containers/EditEventModal";+import MoveEventModal from "metabase/timelines/questions/containers/MoveEventModal";+import NewEventModal from "metabase/timelines/questions/containers/NewEventModal";+import TimelinePanel from "metabase/timelines/questions/containers/TimelinePanel";+import { Box, Button, Icon, Modal } from "metabase/ui";+import { formatDateTimeWithUnit } from "metabase/value-formatting";+import type {+ CartesianChartDateTimeAbsoluteUnit,+ TimeSeriesInterval,+} from "metabase/visualizations/echarts/cartesian/model/types";+import type {+ CollectionId,+ DatetimeUnit,+ Timeline,+ TimelineEvent,+} from "metabase-types/api";++type InternalModal =+ | { type: "new-event" }+ | { type: "edit-event"; eventId: number }+ | { type: "move-event"; eventId: number };++export interface TimelineSidebarProps {+ collectionId: CollectionId | null | undefined;+ timelines: Timeline[];+ visibleTimelineEventIds: number[];+ selectedTimelineEventIds: number[];+ focusedTimelineEventIds?: number[] | null;+ dataInterval?: TimeSeriesInterval | null;+ xDomain?: [Dayjs, Dayjs];+ onShowTimelineEvents: (timelineEvent: TimelineEvent[]) => void;+ onHideTimelineEvents: (timelineEvent: TimelineEvent[]) => void;+ onSelectTimelineEvents?: (timelineEvents: TimelineEvent[]) => void;+ onDeselectTimelineEvents?: () => void;+ onShowAllEvents?: () => void;+ onOpenModal?: (modal: QueryModalType, modalContext?: unknown) => void;+ onClose?: () => void;+}++export const TimelineSidebar = ({+ collectionId,+ timelines,+ visibleTimelineEventIds,+ selectedTimelineEventIds,+ focusedTimelineEventIds = null,+ dataInterval,+ xDomain,+ onOpenModal,+ onShowTimelineEvents,+ onHideTimelineEvents,+ onSelectTimelineEvents,+ onDeselectTimelineEvents,+ onShowAllEvents,+ onClose,+}: TimelineSidebarProps) => {+ const [internalModal, setInternalModal] = useState<InternalModal | null>(+ null,+ );+ const manageModalsInternally = onOpenModal == null;++ const displayedTimelines = useMemo(+ () => getFocusedTimelines(timelines, focusedTimelineEventIds),+ [timelines, focusedTimelineEventIds],+ );++ const focusedXDomain = useMemo(+ () =>+ focusedTimelineEventIds != null+ ? getEventsXDomain(displayedTimelines)+ : undefined,+ [focusedTimelineEventIds, displayedTimelines],+ );++ const title = focusedXDomain+ ? formatTitle(focusedXDomain, toDatetimeUnit(dataInterval?.unit))+ : formatTitle(xDomain);++ const handleShowAllEvents = useCallback(() => {+ onShowAllEvents?.();+ }, [onShowAllEvents]);++ const handleNewEvent = useCallback(() => {+ if (manageModalsInternally) {+ setInternalModal({ type: "new-event" });+ } else {+ onOpenModal?.(MODAL_TYPES.NEW_EVENT);+ }+ }, [manageModalsInternally, onOpenModal]);++ const handleEditEvent = useCallback(+ (event: TimelineEvent) => {+ if (manageModalsInternally) {+ setInternalModal({ type: "edit-event", eventId: event.id });+ } else {+ onOpenModal?.(MODAL_TYPES.EDIT_EVENT, event.id);+ }+ },+ [manageModalsInternally, onOpenModal],+ );++ const handleMoveEvent = useCallback(+ (event: TimelineEvent) => {+ if (manageModalsInternally) {+ setInternalModal({ type: "move-event", eventId: event.id });+ } else {+ onOpenModal?.(MODAL_TYPES.MOVE_EVENT, event.id);+ }+ },+ [manageModalsInternally, onOpenModal],+ );++ const handleCloseInternalModal = useCallback(() => {+ setInternalModal(null);+ }, []);++ const handleToggleEventSelected = useCallback(+ (event: TimelineEvent, isSelected: boolean) => {+ if (isSelected) {+ onSelectTimelineEvents?.([event]);+ } else {+ onDeselectTimelineEvents?.();+ }+ },+ [onSelectTimelineEvents, onDeselectTimelineEvents],+ );++ return (+ <SidebarContent title={title} onClose={onClose}>+ {focusedTimelineEventIds != null && (+ <Box mx="lg" mb="sm">+ <Button+ p={0}+ variant="subtle"+ leftSection={<Icon name="chevronleft" />}+ onClick={handleShowAllEvents}+ data-testid="timeline-sidebar-show-all"+ >+ {t`All events`}+ </Button>+ </Box>+ )}+ <TimelinePanel+ timelines={displayedTimelines}+ collectionId={collectionId}+ visibleEventIds={visibleTimelineEventIds}+ selectedEventIds={selectedTimelineEventIds}+ onNewEvent={handleNewEvent}+ onEditEvent={handleEditEvent}+ onMoveEvent={handleMoveEvent}+ onToggleEventSelected={handleToggleEventSelected}+ onShowTimelineEvents={onShowTimelineEvents}+ onHideTimelineEvents={onHideTimelineEvents}+ />+ {manageModalsInternally && internalModal?.type === "new-event" && (+ <Modal+ opened+ onClose={handleCloseInternalModal}+ size="lg"+ withCloseButton={false}+ padding="0"+ >+ <NewEventModal+ collectionId={collectionId}+ onClose={handleCloseInternalModal}+ />+ </Modal>+ )}+ {manageModalsInternally && internalModal?.type === "edit-event" && (+ <Modal+ opened+ onClose={handleCloseInternalModal}+ size="lg"+ withCloseButton={false}+ padding="0"+ >+ <EditEventModal+ eventId={internalModal.eventId}+ onClose={handleCloseInternalModal}+ />+ </Modal>+ )}+ {manageModalsInternally && internalModal?.type === "move-event" && (+ <Modal+ opened+ onClose={handleCloseInternalModal}+ size="lg"+ withCloseButton={false}+ padding="0"+ >+ <MoveEventModal+ eventId={internalModal.eventId}+ collectionId={collectionId}+ onClose={handleCloseInternalModal}+ />+ </Modal>+ )}+ </SidebarContent>+ );+};++export const getFocusedTimelines = (+ timelines: Timeline[],+ focusedTimelineEventIds: number[] | null,+): Timeline[] => {+ if (focusedTimelineEventIds == null) {+ return timelines;+ }+ const focusedIds = new Set(focusedTimelineEventIds);+ return timelines+ .map((timeline) => ({+ ...timeline,+ events: (timeline.events ?? []).filter((event) =>+ focusedIds.has(event.id),+ ),+ }))+ .filter((timeline) => timeline.events.length > 0);+};++export const getEventsXDomain = (+ timelines: Timeline[],+): [Dayjs, Dayjs] | undefined => {+ const timestamps = timelines+ .flatMap((timeline) => timeline.events ?? [])+ .map((event) => dayjs.utc(event.timestamp));++ if (timestamps.length === 0) {+ return undefined;+ }++ const min = timestamps.reduce((a, b) => (b.isBefore(a) ? b : a));+ const max = timestamps.reduce((a, b) => (b.isAfter(a) ? b : a));+ return [min, max];+};++const toDatetimeUnit = (+ unit?: CartesianChartDateTimeAbsoluteUnit,+): DatetimeUnit | undefined =>+ unit == null || unit === "second" || unit === "ms" ? undefined : unit;++const isPeriodUnit = (unit?: DatetimeUnit) =>+ unit === "week" || unit === "month" || unit === "quarter" || unit === "year";++export const formatTitle = (xDomain?: [Dayjs, Dayjs], unit?: DatetimeUnit) => {+ if (!xDomain) {+ return t`Events`;+ }+ const startLabel = formatDate(xDomain[0], unit);+ const endLabel = formatDate(xDomain[1], unit);+ if (startLabel !== endLabel) {+ return t`Events between ${startLabel} and ${endLabel}`;+ }++ return isPeriodUnit(unit)+ ? t`Events in ${startLabel}`+ : t`Events on ${startLabel}`;+};++const formatDate = (date: Dayjs, unit?: DatetimeUnit) => {+ if (unit == null) {+ return date.format("ll");+ }+ // Unjustified type cast. FIXME+ return formatDateTimeWithUnit(date.startOf(unit as OpUnitType), unit);+};diff --git a/frontend/src/metabase/query_builder/components/view/sidebars/TimelineSidebar/TimelineSidebar.unit.spec.ts b/frontend/src/metabase/timelines/questions/components/TimelineSidebar/TimelineSidebar.unit.spec.tsxsimilarity index 70%rename from frontend/src/metabase/query_builder/components/view/sidebars/TimelineSidebar/TimelineSidebar.unit.spec.tsrename to frontend/src/metabase/timelines/questions/components/TimelineSidebar/TimelineSidebar.unit.spec.tsxindex 6046ead5c66..cb6242ad18b 100644--- a/frontend/src/metabase/query_builder/components/view/sidebars/TimelineSidebar/TimelineSidebar.unit.spec.ts+++ b/frontend/src/metabase/timelines/questions/components/TimelineSidebar/TimelineSidebar.unit.spec.tsx@@ -1,10 +1,18 @@+import userEvent from "@testing-library/user-event";++import { setupCollectionByIdEndpoint } from "__support__/server-mocks/collection";+import { setupTimelinesEndpoints } from "__support__/server-mocks/timeline";+import { renderWithProviders, screen } from "__support__/ui";+import { ROOT_COLLECTION } from "metabase/common/collections/constants";import { dayjs } from "metabase/dayjs";import {+ createMockCollection,createMockTimeline,createMockTimelineEvent,} from "metabase-types/api/mocks";import {+ TimelineSidebar,formatTitle,getEventsXDomain,getFocusedTimelines,@@ -86,9 +94,9 @@ describe("getEventsXDomain", () => {});describe("formatTitle", () => {- const june3 = dayjs("2027-06-03T00:00:00Z");- const june27 = dayjs("2027-06-27T00:00:00Z");- const july5 = dayjs("2027-07-05T00:00:00Z");+ const june3 = dayjs.utc("2027-06-03T00:00:00Z");+ const june27 = dayjs.utc("2027-06-27T00:00:00Z");+ const july5 = dayjs.utc("2027-07-05T00:00:00Z");it("returns a generic title without a domain", () => {expect(formatTitle()).toBe("Events");@@ -124,3 +132,38 @@ describe("formatTitle", () => {);});});++describe("TimelineSidebar", () => {+ beforeEach(() => {+ setupCollectionByIdEndpoint({+ collections: [+ createMockCollection({ ...ROOT_COLLECTION, can_write: true }),+ ],+ });+ });++ it("renders Edit/Move/New modals internally when onOpenModal is absent", async () => {+ const timeline = createMockTimeline({+ id: 1,+ name: "Releases",+ collection: createMockCollection({ can_write: true }),+ events: [createMockTimelineEvent({ id: 1, name: "RC1", timeline_id: 1 })],+ });+ setupTimelinesEndpoints([timeline]);++ renderWithProviders(+ <TimelineSidebar+ collectionId="root"+ timelines={[timeline]}+ visibleTimelineEventIds={[1]}+ selectedTimelineEventIds={[]}+ onShowTimelineEvents={jest.fn()}+ onHideTimelineEvents={jest.fn()}+ />,+ );++ expect(await screen.findByText("Create event")).toBeInTheDocument();+ await userEvent.click(screen.getByText("Create event"));+ expect(await screen.findByRole("dialog")).toBeInTheDocument();+ });+});diff --git a/frontend/src/metabase/timelines/questions/components/TimelineSidebar/index.ts b/frontend/src/metabase/timelines/questions/components/TimelineSidebar/index.tsnew file mode 100644index 00000000000..a23cb21adc4--- /dev/null+++ b/frontend/src/metabase/timelines/questions/components/TimelineSidebar/index.ts@@ -0,0 +1 @@+export { TimelineSidebar, type TimelineSidebarProps } from "./TimelineSidebar";diff --git a/frontend/src/metabase/query_builder/components/timelines/containers/EditEventModal/EditEventModal.tsx b/frontend/src/metabase/timelines/questions/containers/EditEventModal/EditEventModal.tsxsimilarity index 100%rename from frontend/src/metabase/query_builder/components/timelines/containers/EditEventModal/EditEventModal.tsxrename to frontend/src/metabase/timelines/questions/containers/EditEventModal/EditEventModal.tsxdiff --git a/frontend/src/metabase/query_builder/components/timelines/containers/EditEventModal/index.ts b/frontend/src/metabase/timelines/questions/containers/EditEventModal/index.tssimilarity index 100%rename from frontend/src/metabase/query_builder/components/timelines/containers/EditEventModal/index.tsrename to frontend/src/metabase/timelines/questions/containers/EditEventModal/index.tsdiff --git a/frontend/src/metabase/query_builder/components/timelines/containers/MoveEventModal/MoveEventModal.tsx b/frontend/src/metabase/timelines/questions/containers/MoveEventModal/MoveEventModal.tsxsimilarity index 100%rename from frontend/src/metabase/query_builder/components/timelines/containers/MoveEventModal/MoveEventModal.tsxrename to frontend/src/metabase/timelines/questions/containers/MoveEventModal/MoveEventModal.tsxdiff --git a/frontend/src/metabase/query_builder/components/timelines/containers/MoveEventModal/index.ts b/frontend/src/metabase/timelines/questions/containers/MoveEventModal/index.tssimilarity index 100%rename from frontend/src/metabase/query_builder/components/timelines/containers/MoveEventModal/index.tsrename to frontend/src/metabase/timelines/questions/containers/MoveEventModal/index.tsdiff --git a/frontend/src/metabase/query_builder/components/timelines/containers/NewEventModal/NewEventModal.tsx b/frontend/src/metabase/timelines/questions/containers/NewEventModal/NewEventModal.tsxsimilarity index 100%rename from frontend/src/metabase/query_builder/components/timelines/containers/NewEventModal/NewEventModal.tsxrename to frontend/src/metabase/timelines/questions/containers/NewEventModal/NewEventModal.tsxdiff --git a/frontend/src/metabase/query_builder/components/timelines/containers/NewEventModal/index.ts b/frontend/src/metabase/timelines/questions/containers/NewEventModal/index.tssimilarity index 100%rename from frontend/src/metabase/query_builder/components/timelines/containers/NewEventModal/index.tsrename to frontend/src/metabase/timelines/questions/containers/NewEventModal/index.tsdiff --git a/frontend/src/metabase/query_builder/components/timelines/containers/TimelinePanel/TimelinePanel.tsx b/frontend/src/metabase/timelines/questions/containers/TimelinePanel/TimelinePanel.tsxsimilarity index 100%rename from frontend/src/metabase/query_builder/components/timelines/containers/TimelinePanel/TimelinePanel.tsxrename to frontend/src/metabase/timelines/questions/containers/TimelinePanel/TimelinePanel.tsxdiff --git a/frontend/src/metabase/query_builder/components/timelines/containers/TimelinePanel/index.ts b/frontend/src/metabase/timelines/questions/containers/TimelinePanel/index.tssimilarity index 100%rename from frontend/src/metabase/query_builder/components/timelines/containers/TimelinePanel/index.tsrename to frontend/src/metabase/timelines/questions/containers/TimelinePanel/index.tsdiff --git a/frontend/src/metabase/urls/explorations.ts b/frontend/src/metabase/urls/explorations.tsindex ac73cba148b..e2500f37312 100644--- a/frontend/src/metabase/urls/explorations.ts+++ b/frontend/src/metabase/urls/explorations.ts@@ -14,6 +14,42 @@ export function exploration(explorationId: ExplorationId): string {return `/${EXPLORATION_BASE_PATH}/${explorationId}`;}+export function explorationPage(+ explorationId: ExplorationId,+ pageId: string | number,+): string {+ return `${exploration(explorationId)}/page/${encodeURIComponent(String(pageId))}`;+}++export function explorationSummary(explorationId: ExplorationId): string {+ return `${exploration(explorationId)}/summary`;+}+export function isExplorationUrl(pathname: string): boolean {return pathname.startsWith(`/${EXPLORATION_BASE_PATH}/`);}++/**+ * Merges the current exploration search params onto a destination path.+ * When the comments panel is open and the destination is a page, retargets+ * `comments` to that page id — same behavior as sidebar page selection.+ */+export function explorationPathWithSearch(+ pathname: string,+ locationSearch: string,+): string {+ const path = pathname.split("?")[0] ?? pathname;+ const search = new URLSearchParams(locationSearch);++ const pagePrefix = "/page/";+ const pageIdx = path.lastIndexOf(pagePrefix);+ if (pageIdx !== -1 && search.has("comments")) {+ const pageId = decodeURIComponent(path.slice(pageIdx + pagePrefix.length));+ if (pageId) {+ search.set("comments", pageId);+ }+ }++ const query = search.toString();+ return query ? `${path}?${query}` : path;+}diff --git a/frontend/src/metabase/urls/explorations.unit.spec.ts b/frontend/src/metabase/urls/explorations.unit.spec.tsnew file mode 100644index 00000000000..e522553810b--- /dev/null+++ b/frontend/src/metabase/urls/explorations.unit.spec.ts@@ -0,0 +1,60 @@+import { explorationPathWithSearch, isExplorationUrl } from "./explorations";++describe("urls > explorations", () => {+ describe("isExplorationUrl", () => {+ it("matches exploration paths", () => {+ expect(isExplorationUrl("/question/research/1")).toBe(true);+ expect(isExplorationUrl("/question/research/1/page/19")).toBe(true);+ expect(isExplorationUrl("/question/research/1/summary")).toBe(true);+ });++ it("rejects non-exploration question paths", () => {+ expect(isExplorationUrl("/question/123")).toBe(false);+ expect(isExplorationUrl("/document/1")).toBe(false);+ });+ });++ describe("explorationPathWithSearch", () => {+ it("preserves search params on the destination path", () => {+ expect(+ explorationPathWithSearch(+ "/question/research/1/page/19",+ "?timeline=1&tab=outline",+ ),+ ).toBe("/question/research/1/page/19?timeline=1&tab=outline");+ });++ it("retargets an open comments panel to the destination page", () => {+ expect(+ explorationPathWithSearch(+ "/question/research/1/page/19",+ "?comments=550e8400-e29b-41d4-a716-446655440000&timeline=1",+ ),+ ).toBe("/question/research/1/page/19?comments=19&timeline=1");+ });++ it("leaves comments alone when the destination is not a page", () => {+ expect(+ explorationPathWithSearch(+ "/question/research/1/summary",+ "?comments=19&tab=outline",+ ),+ ).toBe("/question/research/1/summary?comments=19&tab=outline");+ });++ it("strips any query already on the pathname in favor of location search", () => {+ expect(+ explorationPathWithSearch(+ "/question/research/1/page/19?stale=1",+ "?timeline=1",+ ),+ ).toBe("/question/research/1/page/19?timeline=1");+ });++ it("returns the bare path when there is no search", () => {+ expect(+ explorationPathWithSearch("/question/research/1/page/19", ""),+ ).toBe("/question/research/1/page/19");+ });+ });+});diff --git a/frontend/src/metabase/visualizations/components/ChoroplethMap.tsx b/frontend/src/metabase/visualizations/components/ChoroplethMap.tsxindex 4997fd24aff..ded19af1a0f 100644--- a/frontend/src/metabase/visualizations/components/ChoroplethMap.tsx+++ b/frontend/src/metabase/visualizations/components/ChoroplethMap.tsx@@ -409,7 +409,9 @@ function ChoroplethMapInner(props: ChoroplethMapProps) {return value == null ? HEAT_MAP_ZERO_COLOR : colorScale(value);};- const isSeriesHighlighted = card.id === highlighted?.cardId;+ const isSeriesHighlighted =+ highlighted != null &&+ (highlighted.cardId == null || highlighted.cardId === card.id);const highlightedDimension = highlighted?.dimensions?.find((d) => d.columnName === dimensionColumn?.name,);diff --git a/frontend/src/metabase/visualizations/hooks/use-timeline-events.ts b/frontend/src/metabase/visualizations/hooks/use-timeline-events.tsnew file mode 100644index 00000000000..780b7bfcf06--- /dev/null+++ b/frontend/src/metabase/visualizations/hooks/use-timeline-events.ts@@ -0,0 +1,74 @@+import { useMemo } from "react";++import { skipToken, useListTimelinesQuery } from "metabase/api";+import type { VisualizationProps } from "metabase/visualizations/types";+import type { TimelineEvent } from "metabase-types/api";++type UseTimelineEventsProps = Pick<+ VisualizationProps,+ "timelineEvents" | "settings"+>;++interface UseTimelineEventsResult {+ timelineEvents: TimelineEvent[];+ isLoading: boolean;+ isError: boolean;+}++// stable reference to avoid triggering re-renders+const EMPTY_EVENTS: TimelineEvent[] = [];++export function useTimelineEvents({+ timelineEvents: timelineEventsProp,+ settings,+}: UseTimelineEventsProps): UseTimelineEventsResult {+ const selectedTimelineIds = settings["timeline.selected_timeline_ids"];+ const excludedTimelineEventIds =+ settings["timeline.excluded_timeline_event_ids"];++ const shouldFetch =+ !timelineEventsProp &&+ selectedTimelineIds != null &&+ selectedTimelineIds.length > 0;++ const {+ data: timelines = [],+ isLoading,+ isError,+ } = useListTimelinesQuery(+ shouldFetch+ ? {+ include: "events",+ }+ : skipToken,+ );++ const timelineEvents = useMemo(() => {+ if (timelineEventsProp) {+ return timelineEventsProp;+ }++ if (!selectedTimelineIds || selectedTimelineIds.length === 0) {+ return EMPTY_EVENTS;+ }++ const selectedSet = new Set(selectedTimelineIds);+ const excludedSet = new Set(excludedTimelineEventIds ?? []);++ return timelines.flatMap((timeline) => {+ if (!selectedSet.has(timeline.id)) {+ return [];+ }+ return (timeline.events ?? []).filter(+ (event) => !excludedSet.has(event.id),+ );+ });+ }, [+ timelineEventsProp,+ timelines,+ selectedTimelineIds,+ excludedTimelineEventIds,+ ]);++ return { timelineEvents, isLoading, isError };+}diff --git a/frontend/src/metabase/visualizations/lib/settings/timelineEvents.ts b/frontend/src/metabase/visualizations/lib/settings/timelineEvents.tsnew file mode 100644index 00000000000..12cee151198--- /dev/null+++ b/frontend/src/metabase/visualizations/lib/settings/timelineEvents.ts@@ -0,0 +1,63 @@+import type { VisualizationSettingsDefinitions } from "metabase/visualizations/types";+import type { Timeline, TimelineEventId, TimelineId } from "metabase-types/api";++export const TIMELINE_EVENTS_SETTINGS: VisualizationSettingsDefinitions = {+ "timeline.selected_timeline_ids": {+ hidden: true,+ getDefault: () => [],+ },+ "timeline.excluded_timeline_event_ids": {+ hidden: true,+ getDefault: () => [],+ },+};++export function getTimelineEventSettings(+ timelines: Timeline[],+ selectedTimelineEventIds: TimelineEventId[],+) {+ const timelineEventIdToTimelineId = new Map<TimelineEventId, TimelineId>();+ for (const timeline of timelines) {+ for (const event of timeline.events ?? []) {+ timelineEventIdToTimelineId.set(event.id, timeline.id);+ }+ }++ const timelineIdToSelectedTimelineEventIds = new Map<+ TimelineId,+ Set<TimelineEventId>+ >();+ for (const id of selectedTimelineEventIds) {+ const timelineId = timelineEventIdToTimelineId.get(id);+ if (timelineId) {+ const selectedTimelineEventIds =+ timelineIdToSelectedTimelineEventIds.get(timelineId);+ if (selectedTimelineEventIds) {+ selectedTimelineEventIds.add(id);+ } else {+ timelineIdToSelectedTimelineEventIds.set(timelineId, new Set([id]));+ }+ }+ }++ const selectedTimelineIds: TimelineId[] = [];+ const excludedTimelineEventIds: TimelineEventId[] = [];++ for (const timeline of timelines) {+ const selected = timelineIdToSelectedTimelineEventIds.get(timeline.id);+ if (!timeline.events || !selected || selected.size === 0) {+ continue;+ }+ selectedTimelineIds.push(timeline.id);+ for (const event of timeline.events) {+ if (!selected.has(event.id)) {+ excludedTimelineEventIds.push(event.id);+ }+ }+ }++ return {+ "timeline.selected_timeline_ids": selectedTimelineIds,+ "timeline.excluded_timeline_event_ids": excludedTimelineEventIds,+ };+}diff --git a/frontend/src/metabase/visualizations/lib/settings/timelineEvents.unit.spec.ts b/frontend/src/metabase/visualizations/lib/settings/timelineEvents.unit.spec.tsnew file mode 100644index 00000000000..aab251b3117--- /dev/null+++ b/frontend/src/metabase/visualizations/lib/settings/timelineEvents.unit.spec.ts@@ -0,0 +1,113 @@+import {+ createMockTimeline,+ createMockTimelineEvent,+} from "metabase-types/api/mocks";++import { getTimelineEventSettings } from "./timelineEvents";++const event1 = createMockTimelineEvent({ id: 101, timeline_id: 1 });+const event2 = createMockTimelineEvent({ id: 102, timeline_id: 1 });+const event3 = createMockTimelineEvent({ id: 103, timeline_id: 1 });++const event4 = createMockTimelineEvent({ id: 201, timeline_id: 2 });+const event5 = createMockTimelineEvent({ id: 202, timeline_id: 2 });++const timeline1 = createMockTimeline({+ id: 1,+ events: [event1, event2, event3],+});++const timeline2 = createMockTimeline({+ id: 2,+ events: [event4, event5],+});++const timelineNoEvents = createMockTimeline({+ id: 3,+ events: undefined,+});++describe("getTimelineEventSettings", () => {+ it("should return empty arrays when no events are selected", () => {+ expect(getTimelineEventSettings([timeline1, timeline2], [])).toEqual({+ "timeline.selected_timeline_ids": [],+ "timeline.excluded_timeline_event_ids": [],+ });+ });++ it("should return empty arrays when timelines are empty", () => {+ expect(getTimelineEventSettings([], [101, 201])).toEqual({+ "timeline.selected_timeline_ids": [],+ "timeline.excluded_timeline_event_ids": [],+ });+ });++ it("should select a timeline with no exclusions when all its events are selected", () => {+ const result = getTimelineEventSettings([timeline1], [101, 102, 103]);++ expect(result).toEqual({+ "timeline.selected_timeline_ids": [1],+ "timeline.excluded_timeline_event_ids": [],+ });+ });++ it("should exclude unselected events within a selected timeline", () => {+ const result = getTimelineEventSettings([timeline1], [101]);++ expect(result).toEqual({+ "timeline.selected_timeline_ids": [1],+ "timeline.excluded_timeline_event_ids": [102, 103],+ });+ });++ it("should handle multiple timelines independently", () => {+ const result = getTimelineEventSettings([timeline1, timeline2], [101, 201]);++ expect(result).toEqual({+ "timeline.selected_timeline_ids": [1, 2],+ "timeline.excluded_timeline_event_ids": [102, 103, 202],+ });+ });++ it("should skip timelines with no selected events", () => {+ const result = getTimelineEventSettings([timeline1, timeline2], [201, 202]);++ expect(result).toEqual({+ "timeline.selected_timeline_ids": [2],+ "timeline.excluded_timeline_event_ids": [],+ });+ });++ it("should skip timelines with undefined events", () => {+ const result = getTimelineEventSettings(+ [timelineNoEvents, timeline1],+ [101, 102, 103],+ );++ expect(result).toEqual({+ "timeline.selected_timeline_ids": [1],+ "timeline.excluded_timeline_event_ids": [],+ });+ });++ it("should ignore selected event IDs that don't belong to any timeline", () => {+ const result = getTimelineEventSettings([timeline1], [101, 999]);++ expect(result).toEqual({+ "timeline.selected_timeline_ids": [1],+ "timeline.excluded_timeline_event_ids": [102, 103],+ });+ });++ it("should select all timelines when all events across all timelines are selected", () => {+ const result = getTimelineEventSettings(+ [timeline1, timeline2],+ [101, 102, 103, 201, 202],+ );++ expect(result).toEqual({+ "timeline.selected_timeline_ids": [1, 2],+ "timeline.excluded_timeline_event_ids": [],+ });+ });+});diff --git a/frontend/src/metabase/visualizations/visualizations/CartesianChart/CartesianChart.tsx b/frontend/src/metabase/visualizations/visualizations/CartesianChart/CartesianChart.tsxindex 07e184d6b0e..08130c1e9f8 100644--- a/frontend/src/metabase/visualizations/visualizations/CartesianChart/CartesianChart.tsx+++ b/frontend/src/metabase/visualizations/visualizations/CartesianChart/CartesianChart.tsx@@ -14,6 +14,7 @@ import {useCartesianChartSeriesColorsClasses,useCloseTooltipOnScroll,} from "metabase/visualizations/echarts/tooltip";+import { useTimelineEvents } from "metabase/visualizations/hooks/use-timeline-events";import type { VisualizationProps } from "metabase/visualizations/types";import {CartesianChartLegendLayout,@@ -32,6 +33,8 @@ import {} from "./utils";function CartesianChartInner(props: VisualizationProps) {+ const { timelineEvents } = useTimelineEvents(props);+const containerRef = useRef<HTMLDivElement>(null);// The width and height from props reflect the dimensions of the entire container which includes legend,// however, for correct ECharts option calculation we need to use the dimensions of the chart viewport@@ -97,6 +100,7 @@ function CartesianChartInner(props: VisualizationProps) {height: chartSize.height,hiddenSeries,settings,+ timelineEvents,},containerRef,);diff --git a/frontend/src/metabase/visualizations/visualizations/CartesianChart/definition.ts b/frontend/src/metabase/visualizations/visualizations/CartesianChart/definition.tsindex 000cb1bc1bf..be8f73f75cd 100644--- a/frontend/src/metabase/visualizations/visualizations/CartesianChart/definition.ts+++ b/frontend/src/metabase/visualizations/visualizations/CartesianChart/definition.ts@@ -13,6 +13,7 @@ import {STACKABLE_SETTINGS,TOOLTIP_SETTINGS,} from "metabase/visualizations/lib/settings/graph";+import { TIMELINE_EVENTS_SETTINGS } from "metabase/visualizations/lib/settings/timelineEvents";import {validateBreakoutSeriesCount,validateChartDataSettings,@@ -127,4 +128,5 @@ export const COMBO_CHARTS_SETTINGS_DEFINITIONS: VisualizationSettingsDefinitions...GRAPH_DATA_SETTINGS,...TOOLTIP_SETTINGS,...LEGEND_SETTINGS,+ ...TIMELINE_EVENTS_SETTINGS,};diff --git a/frontend/src/metabase/visualizations/visualizations/ScatterPlot/definition.ts b/frontend/src/metabase/visualizations/visualizations/ScatterPlot/definition.tsindex 4b4847ae98c..fc4517b3433 100644--- a/frontend/src/metabase/visualizations/visualizations/ScatterPlot/definition.ts+++ b/frontend/src/metabase/visualizations/visualizations/ScatterPlot/definition.ts@@ -16,6 +16,7 @@ import {SPLIT_PANELS_SETTINGS,TOOLTIP_SETTINGS,} from "../../lib/settings/graph";+import { TIMELINE_EVENTS_SETTINGS } from "../../lib/settings/timelineEvents";import type { VisualizationDefinition } from "../../types";const ScatterViz: Omit<@@ -38,6 +39,7 @@ const ScatterViz: Omit<...GRAPH_DATA_SETTINGS,...SPLIT_PANELS_SETTINGS,...TOOLTIP_SETTINGS,+ ...TIMELINE_EVENTS_SETTINGS,},};diff --git a/frontend/src/metabase/visualizations/visualizations/WaterfallChart/definition.ts b/frontend/src/metabase/visualizations/visualizations/WaterfallChart/definition.tsindex 2adb1acf1ea..445617b81d3 100644--- a/frontend/src/metabase/visualizations/visualizations/WaterfallChart/definition.ts+++ b/frontend/src/metabase/visualizations/visualizations/WaterfallChart/definition.ts@@ -9,6 +9,7 @@ import {GRAPH_DISPLAY_VALUES_SETTINGS,TOOLTIP_SETTINGS,} from "metabase/visualizations/lib/settings/graph";+import { TIMELINE_EVENTS_SETTINGS } from "metabase/visualizations/lib/settings/timelineEvents";import {getDefaultSize,getMinSize,@@ -80,6 +81,7 @@ const WaterfallViz: Omit<VisualizationDefinition, "checkRenderable"> = {...GRAPH_DISPLAY_VALUES_SETTINGS,...GRAPH_DATA_SETTINGS,...TOOLTIP_SETTINGS,+ ...TIMELINE_EVENTS_SETTINGS,},};diff --git a/mage/src/mage/quick_test_runner.clj b/mage/src/mage/quick_test_runner.cljindex e78a7b48132..8a7dcc548cc 100644--- a/mage/src/mage/quick_test_runner.clj+++ b/mage/src/mage/quick_test_runner.clj@@ -93,7 +93,6 @@(c/cyan "mage run-tests "(when-let [p (:port options)] (format "--port %s " p))(str/join " " test-dirs)))-(let [out-data (try (edn/read-string out)(catch Exception _(println (c/red "Problem parsing output, raw output follows:"))diff --git a/resources/migrations/064/20260804_exploration_summary_document.yaml b/resources/migrations/064/20260804_exploration_summary_document.yamlnew file mode 100644index 00000000000..dda02fcd318--- /dev/null+++ b/resources/migrations/064/20260804_exploration_summary_document.yaml@@ -0,0 +1,98 @@+## Follow-on migrations for exploration Summary documents.++databaseChangeLog:+ - changeSet:+ id: v64.2026-08-04T10:00:00+ author: kevinkelleher12+ comment: Add stored_result_use.card_id for Card references to stored results+ changes:+ - addColumn:+ tableName: stored_result_use+ columns:+ - column:+ name: card_id+ type: int+ remarks: The referencing Card+ constraints:+ nullable: true++ - changeSet:+ id: v64.2026-08-04T10:00:01+ author: kevinkelleher12+ comment: Index on stored_result_use.card_id+ changes:+ - createIndex:+ tableName: stored_result_use+ indexName: idx_stored_result_use_card_id+ columns:+ - column:+ name: card_id++ - changeSet:+ id: v64.2026-08-04T10:00:02+ author: kevinkelleher12+ comment: FK stored_result_use.card_id -> report_card.id+ changes:+ - addForeignKeyConstraint:+ baseTableName: stored_result_use+ baseColumnNames: card_id+ referencedTableName: report_card+ referencedColumnNames: id+ constraintName: fk_stored_result_use_card_id+ onDelete: CASCADE++ - changeSet:+ id: v64.2026-08-04T10:00:03+ author: kevinkelleher12+ comment: Add document.exploration_id for the per-exploration Summary document+ changes:+ - addColumn:+ tableName: document+ columns:+ - column:+ name: exploration_id+ type: int+ remarks: Optional owning exploration. When set, this document is the exploration's Summary and is not first-class content (hidden from search, collections, recents).+ constraints:+ nullable: true++ - changeSet:+ id: v64.2026-08-04T10:00:04+ author: kevinkelleher12+ comment: Index on document.exploration_id+ changes:+ - createIndex:+ tableName: document+ indexName: idx_document_exploration_id+ columns:+ - column:+ name: exploration_id++ - changeSet:+ id: v64.2026-08-04T10:00:05+ author: kevinkelleher12+ comment: FK document.exploration_id -> exploration.id+ changes:+ - addForeignKeyConstraint:+ baseTableName: document+ baseColumnNames: exploration_id+ referencedTableName: exploration+ referencedColumnNames: id+ constraintName: fk_document_exploration_id+ onDelete: CASCADE++ - changeSet:+ id: v64.2026-08-04T10:00:06+ author: kevinkelleher12+ comment: Add document.is_placeholder — true until the first body save or chart append on an exploration Summary+ changes:+ - addColumn:+ tableName: document+ columns:+ - column:+ name: is_placeholder+ type: ${boolean.type}+ defaultValueBoolean: false+ remarks: True while the document is still an untouched auto-created placeholder (exploration Summary). Cleared on the first body save or chart append.+ constraints:+ nullable: falsediff --git a/src/metabase/activity_feed/models/recent_views.clj b/src/metabase/activity_feed/models/recent_views.cljindex 1d9ecd56227..ae3589ee752 100644--- a/src/metabase/activity_feed/models/recent_views.clj+++ b/src/metabase/activity_feed/models/recent_views.clj@@ -517,7 +517,10 @@[:= nil :coll.namespace];; exclude instance analytics for selects(when (contains? (set context) :selections)- [:or [:= nil :coll.type] [:not= :coll.type collection/instance-analytics-collection-type]])]]]+ [:or [:= nil :coll.type] [:not= :coll.type collection/instance-analytics-collection-type]])]]+ ;; exploration documents are accessible only through their owning Exploration;+ ;; hide them from recents to match search and collection-listing behavior.+ [:or [:!= :rv.model "document"] [:= :doc.exploration_id nil]]]:left-join [[:report_card :rc][:and;; only want to join on card_type if it's a card@@ -526,7 +529,11 @@[:collection :coll][:and[:= :rv.model "collection"]- [:= :coll.id :rv.model_id]]]+ [:= :coll.id :rv.model_id]]+ [:document :doc]+ [:and+ [:= :rv.model "document"]+ [:= :doc.id :rv.model_id]]]:order-by [[:rv.timestamp :desc]]})))(mu/defn- model->return-model [model :- :keyword]diff --git a/src/metabase/collections/models/collection.clj b/src/metabase/collections/models/collection.cljindex 72b7be4480a..13861ee046b 100644--- a/src/metabase/collections/models/collection.clj+++ b/src/metabase/collections/models/collection.clj@@ -2171,11 +2171,24 @@{["Dashboard" dash-id] {"Collection" id}}))cards (into {} (for [card-id (t2/select-pks-set :model/Card {:where [:and[:= :collection_id id]- (when skip-archived [:not :archived])]})]+ (when skip-archived [:not :archived])+ ;; Cards materialized by an exploration+ ;; Summary ride with that Summary, which is+ ;; excluded just below. Listing them here+ ;; would make them export targets whose+ ;; Document dependency is absent.+ [:or+ [:= :document_id nil]+ [:in :document_id+ ^:allow-subquery {:select [:id]+ :from [:document]+ :where [:= :exploration_id nil]}]]]})]{["Card" card-id] {"Collection" id}}))documents (when config/ee-available?(into {} (for [doc-id (t2/select-pks-set :model/Document {:where[:and [:= :collection_id id]+ ;; Exploration documents are user scratch space — exclude from serdes/remote-sync.+ [:= :exploration_id nil](when skip-archived [:not :archived])]})]{["Document" doc-id] {"Collection" id}})))timelines (into {} (for [timeline-id (t2/select-pks-set :model/Timeline {:where [:anddiff --git a/src/metabase/collections_rest/api.clj b/src/metabase/collections_rest/api.cljindex bfe78528f3e..4e88acb6440 100644--- a/src/metabase/collections_rest/api.clj+++ b/src/metabase/collections_rest/api.clj@@ -16,6 +16,7 @@[metabase.collections.core :as collections][metabase.collections.models.collection :as collection][metabase.collections.models.collection.root :as collection.root]+ [metabase.documents.core :as documents][metabase.eid-translation.core :as eid-translation][metabase.events.core :as events][metabase.lib-be.core :as lib-be]@@ -336,6 +337,7 @@(def ^:private CollectionChildrenOptions[:map[:show-dashboard-questions? :boolean]+ [:show-exploration-documents? :boolean][:collection-type {:optional true} [:maybe CollectionType]][:archived? :boolean][:include-library? {:optional true} [:maybe :boolean]]@@ -430,24 +432,27 @@(defmethod ^:private post-process-collection-children :document[_ _ collection rows]- (t2/hydrate (for [document rows]- (-> (t2/instance :model/Document document)- (assoc :location (or (when collection- (collection/children-location collection))- "/"))- (dissoc :namespace)- (update :archived api/bit->boolean)- (update :archived_directly api/bit->boolean)))- :can_write :can_restore :can_delete :is_remote_synced :collection_namespace))+ (documents/with-content-gate-cache+ (map #(dissoc % :exploration_id)+ (t2/hydrate (for [document rows]+ (-> (t2/instance :model/Document document)+ (assoc :location (or (when collection+ (collection/children-location collection))+ "/"))+ (dissoc :namespace)+ (update :archived api/bit->boolean)+ (update :archived_directly api/bit->boolean)))+ :can_write :can_restore :can_delete :is_remote_synced :collection_namespace))))(defmethod collection-children-query :document- [_ collection {:keys [archived? pinned-state]}]+ [_ collection {:keys [archived? pinned-state show-exploration-documents?]}](-> {:select [:document.id:document.name:document.collection_id:document.collection_position:document.archived:document.archived_directly+ :document.exploration_id[:u.id :last_edit_user][:u.email :last_edit_email][:u.first_name :last_edit_first_name]@@ -467,7 +472,12 @@[:and[:= :document.collection_id (:id collection)][:= :document.archived_directly false]])- [:= :document.archived (boolean archived?)]]}+ [:= :document.archived (boolean archived?)]+ ;; Hide exploration-attached documents - similar to Dashboard Questions, they're not visible in the+ ;; collection, but only through the Exploration they're in. Callers that want them (e.g. the+ ;; Trash view, embedding SDK) pass show-exploration-documents? to opt in.+ (when-not show-exploration-documents?+ [:= :document.exploration_id nil])]}(sql.helpers/where (pinned-state->clause pinned-state :document.collection_position))))(defmethod ^:private post-process-collection-children :exploration@@ -482,21 +492,35 @@:can_write :can_restore :can_delete))(def ^:private exploration-recent-edits-subquery- ;; Per-exploration latest edit, from the Exploration's own metadata revisions.- ;; `rn = 1` picks the winner.+ ;; Per-exploration latest edit, unioning the Exploration's own metadata revisions with+ ;; revisions of its Summary Document. `rn = 1` picks the winner.+ ;; The Exploration row is mostly inert post-creation; the meat of editing happens in+ ;; the attached Document, so "Last edited" must reflect both sources.^:allow-subquery{:select [:exploration_id:timestamp:user_id[[:over [[:row_number] ^:allow-subquery {:partition-by [:exploration_id]:order-by [[:timestamp :desc]]}]] :rn]]- :from [[^:allow-subquery {:select [[:r.model_id :exploration_id]- [:r.timestamp :timestamp]- [:r.user_id :user_id]]- :from [[:revision :r]]- :where [:and- [:= :r.model (h2x/literal "Exploration")]- [:= :r.most_recent true]]}+ :from [[^:allow-subquery {:union-all+ [^:allow-subquery+ {:select [[:r.model_id :exploration_id]+ [:r.timestamp :timestamp]+ [:r.user_id :user_id]]+ :from [[:revision :r]]+ :where [:and+ [:= :r.model (h2x/literal "Exploration")]+ [:= :r.most_recent true]]}+ ^:allow-subquery+ {:select [[:d.exploration_id :exploration_id]+ [:r.timestamp :timestamp]+ [:r.user_id :user_id]]+ :from [[:revision :r]]+ :join [[:document :d] [:= :d.id :r.model_id]]+ :where [:and+ [:= :r.model (h2x/literal "Document")]+ [:= :r.most_recent true]+ [:not= :d.exploration_id nil]]}]}:all_edits]]})(defmethod collection-children-query :exploration@@ -679,13 +703,23 @@(defn- post-process-card-row [row](-> (t2/instance :model/Card row)+ ;; `card-query` filters `[:= :c.document_id nil]` unconditionally, so every row here is known+ ;; not to belong to a Document. Say so on the instance: `mi/can-write?` consults `document_id`+ ;; (a Document-scoped Card is gated by its Document), and an instance that merely *omits* the+ ;; column makes it resolve one from the primary key instead — one extra query per row, on a+ ;; listing that renders a full page of them. Stamping it rather than selecting it keeps the+ ;; column out of `all-select-columns`, which every model's union arm would otherwise have to+ ;; pad, and out of the response body.+ (assoc :document_id nil)(update :dataset_query (:out lib-be/transform-query))(update :collection_preview api/bit->boolean)(update :archived api/bit->boolean)(update :archived_directly api/bit->boolean)))(defn- post-process-card-row-after-hydrate [row]- (-> (dissoc row :authority_level :icon :personal_owner_id :dataset_query :table_id :query_type :is_upload :namespace)+ (-> (dissoc row :authority_level :icon :personal_owner_id :dataset_query :table_id :query_type :is_upload :namespace+ ;; internal-only: stamped in `post-process-card-row` for the permission check+ :document_id)(update :dashboard #(when % (select-keys % [:id :name :moderation_status])))(assoc :fully_parameterized (queries/fully-parameterized? row))))@@ -1481,20 +1515,21 @@changed, that should too."[_route-params{:keys [models archived namespace pinned_state sort_column sort_direction official_collections_first- include_library collection_type- show_dashboard_questions q include_available_models]} :- [:map- [:models {:optional true} [:maybe Models]]- [:collection_type {:optional true} CollectionType]- [:archived {:default false} [:maybe ms/BooleanValue]]- [:namespace {:optional true} [:maybe ms/NonBlankString]]- [:include_library {:default false} [:maybe ms/BooleanValue]]- [:pinned_state {:optional true} [:maybe (into [:enum] valid-pinned-state-values)]]- [:sort_column {:optional true} [:maybe (into [:enum] valid-sort-columns)]]- [:sort_direction {:optional true} [:maybe (into [:enum] valid-sort-directions)]]- [:official_collections_first {:optional true} [:maybe ms/MaybeBooleanValue]]- [:show_dashboard_questions {:optional true} [:maybe ms/MaybeBooleanValue]]- [:q {:optional true} [:maybe :string]]- [:include_available_models {:default false} [:maybe ms/BooleanValue]]]]+ include_library collection_type show_dashboard_questions+ q include_available_models show_exploration_documents]} :- [:map+ [:models {:optional true} [:maybe Models]]+ [:collection_type {:optional true} CollectionType]+ [:archived {:default false} [:maybe ms/BooleanValue]]+ [:namespace {:optional true} [:maybe ms/NonBlankString]]+ [:include_library {:default false} [:maybe ms/BooleanValue]]+ [:pinned_state {:optional true} [:maybe (into [:enum] valid-pinned-state-values)]]+ [:sort_column {:optional true} [:maybe (into [:enum] valid-sort-columns)]]+ [:sort_direction {:optional true} [:maybe (into [:enum] valid-sort-directions)]]+ [:official_collections_first {:optional true} [:maybe ms/MaybeBooleanValue]]+ [:show_dashboard_questions {:optional true} [:maybe ms/MaybeBooleanValue]]+ [:q {:optional true} [:maybe :string]]+ [:include_available_models {:default false} [:maybe ms/BooleanValue]]+ [:show_exploration_documents {:optional true} [:maybe ms/MaybeBooleanValue]]]];; Return collection contents, including Collections that have an effective location of being in the Root;; Collection for the Current User.(let [root-collection (assoc collection/root-collection :namespace namespace)@@ -1505,6 +1540,7 @@#{:collection})options {:archived? (boolean archived):show-dashboard-questions? (boolean show_dashboard_questions)+ :show-exploration-documents? (boolean show_exploration_documents):collection-type collection_type:include-library? include_library:models (if-not (contains? namespaces-holding-non-collection-types namespace)@@ -1791,20 +1827,23 @@[{:keys [id]} :- [:map[:id [:or ms/PositiveInt ms/NanoIdString]]]{:keys [models archived pinned_state sort_column sort_direction official_collections_first- show_dashboard_questions q include_available_models]} :- [:map- [:models {:optional true} [:maybe Models]]- [:archived {:default false} [:maybe ms/BooleanValue]]- [:pinned_state {:optional true} [:maybe (into [:enum] valid-pinned-state-values)]]- [:sort_column {:optional true} [:maybe (into [:enum] valid-sort-columns)]]- [:sort_direction {:optional true} [:maybe (into [:enum] valid-sort-directions)]]- [:official_collections_first {:optional true} [:maybe ms/MaybeBooleanValue]]- [:show_dashboard_questions {:default false} [:maybe ms/BooleanValue]]- [:q {:optional true} [:maybe :string]]- [:include_available_models {:default false} [:maybe ms/BooleanValue]]]]+ show_dashboard_questions q include_available_models+ show_exploration_documents]} :- [:map+ [:models {:optional true} [:maybe Models]]+ [:archived {:default false} [:maybe ms/BooleanValue]]+ [:pinned_state {:optional true} [:maybe (into [:enum] valid-pinned-state-values)]]+ [:sort_column {:optional true} [:maybe (into [:enum] valid-sort-columns)]]+ [:sort_direction {:optional true} [:maybe (into [:enum] valid-sort-directions)]]+ [:official_collections_first {:optional true} [:maybe ms/MaybeBooleanValue]]+ [:show_dashboard_questions {:default false} [:maybe ms/BooleanValue]]+ [:show_exploration_documents {:default false} [:maybe ms/BooleanValue]]+ [:q {:optional true} [:maybe :string]]+ [:include_available_models {:default false} [:maybe ms/BooleanValue]]]](let [resolved-id (eid-translation/->id-or-404 :collection id)model-kwds (set (map keyword (u/one-or-many models)))collection (api/read-check :model/Collection resolved-id)options {:show-dashboard-questions? show_dashboard_questions+ :show-exploration-documents? show_exploration_documents:models model-kwds:include-library? true:archived? (or archived (:archived collection) (collection/is-trash? collection))diff --git a/src/metabase/comments/api.clj b/src/metabase/comments/api.cljindex 9386f589a8f..6240be62368 100644--- a/src/metabase/comments/api.clj+++ b/src/metabase/comments/api.clj@@ -63,15 +63,28 @@ms/Map](deferred-tru "Comment content must be valid JSON.")))+(def ^:private CommentHighlight+ "The chart point a comment is anchored to. Identity only — which column, and which dimension values+ pick out the point — so the client can re-find it in a result set it is separately authorized to+ read."+ [:map {:closed true}+ [:columnName {:optional true} [:maybe :string]]+ [:dimensions {:optional true}+ [:maybe [:sequential [:map {:closed true}+ [:columnName {:optional true} [:maybe :string]]+ [:value {:optional true} :any]]]]]])+(def CommentContext- "Context stored alongside a comment: a JSON blob whose shape depends on what was commented on. Only `timeline_id` is- read back, by [[metabase.comments.models.comment]] when building an exploration comment URL."+ "Context stored alongside a comment"(mu/with-api-error-message[:and{:error/message "Comment context must be a valid JSON object":json-schema {:type "object"}}- [:map {:closed false}- [:timeline_id {:optional true} ms/PositiveInt]]]+ [:map {:closed true}+ [:timeline_id {:optional true} [:maybe ms/PositiveInt]]+ [:exploration_query_ids {:optional true} [:maybe [:sequential ms/PositiveInt]]]+ [:highlighted {:optional true} [:maybe CommentHighlight]]+ [:highlight_label {:optional true} [:maybe [:string {:max 1000}]]]]](deferred-tru "Comment context must be a valid JSON object.")))(def CreateComment@@ -141,7 +154,10 @@[:= :target_id target_id]]:order-by [[:created_at :asc]]})(t2/hydrate :creator :reactions))]- {:comments (render-comments comments)})))+ ;; The read check above only proves the viewer may see the *target*, and for an exploration+ ;; that is collection permissions alone; the gate is what adjudicates the warehouse values a+ ;; `:context` carries (its dimension values and the `:highlight_label` summarizing them).+ {:comments (render-comments (comment/apply-context-gate target_type target_id comments))})))(defn- mentioned-ids-who-can-read"Restrict mentioned user ids to active users who can themselves read `entity`."diff --git a/src/metabase/comments/core.clj b/src/metabase/comments/core.cljindex 9b0b7a79cf3..964509df197 100644--- a/src/metabase/comments/core.clj+++ b/src/metabase/comments/core.clj@@ -1,8 +1,12 @@(ns metabase.comments.core+ "Public surface of the `comments` module."(:require- [metabase.comments.api :as api.comments]+ [metabase.comments.models.comment][potemkin :as p]))+(comment+ metabase.comments.models.comment/keep-me)+(p/import-vars- [api.comments- notify-comment-id!])+ [metabase.comments.models.comment+ register-context-gate!])diff --git a/src/metabase/comments/models/comment.clj b/src/metabase/comments/models/comment.cljindex e9f33f343d4..ee81cf04474 100644--- a/src/metabase/comments/models/comment.clj+++ b/src/metabase/comments/models/comment.clj@@ -48,15 +48,50 @@;;;+(defonce ^{:private true+ :doc "Filter applied to comments' `:context` before they are returned, installed at init.++ A comment's context describes what was commented on, and for an exploration that+ includes the identity of a chart data point — values read out of the creator's+ result set. The target's own read check cannot adjudicate that: an Exploration is+ read-checked on collection permissions alone, because its data-access gate is+ applied by its read endpoints rather than by `can-read?`. So the owning module+ registers the verdict here.++ `comments` cannot call that module directly — the module graph runs one way — so+ the consumer registers a callback."}+ context-gate+ (atom (fn [_target-type _target-id comments] comments)))++(defn register-context-gate!+ "Install the comment-context gate. Called once at the consuming module's+ init. `f` takes `[target-type target-id comments]` and returns the comments to serve."+ [f]+ (reset! context-gate f))++(defn apply-context-gate+ "Run the registered gate over `comments` for one target."+ [target-type target-id comments]+ (@context-gate target-type target-id comments))++(defn- page-id-child-target?+ "Whether `child_target_id` identifies an exploration page (decimal integer string) rather than+ a Summary prose-mirror node `_id` (uuid)."+ [child]+ (boolean (and child (re-matches #"\d+" (str child)))))+(defn- exploration-comment-url- "Build URL for an exploration comment using child_target_id (page ID) and context (JSON map with timeline etc.)."+ "Build URL for an exploration comment. Integer `child_target_id` values deep-link to the+ page; anything else (Summary block uuids) deep-links to the Summary view."[exploration-id comment](let [base (channel.urls/exploration-path exploration-id)child (:child_target_id comment)context (:context comment)](if child- (let [path (str base "/page/" (codec/url-encode (str child)))- params (cond-> {:comments "true"}+ (let [path (if (page-id-child-target? child)+ (str base "/page/" (codec/url-encode (str child)))+ (str base "/summary"))+ params (cond-> {:comments (str child)}(:timeline_id context) (assoc :timeline (:timeline_id context)))query-str (->> params(map (fn [[k v]] (str (codec/url-encode (name k))diff --git a/src/metabase/documents/api.clj b/src/metabase/documents/api.cljindex 0b31c7d91f9..5b73296e1e6 100644--- a/src/metabase/documents/api.clj+++ b/src/metabase/documents/api.clj@@ -1,10 +1,8 @@(ns metabase.documents.api"`/api/document/` routes"(:require- [metabase.api.util.handlers :as handlers][metabase.documents.api.document]))(def ^{:arglists '([request respond raise])} routes"`/api/document/` routes."- (handlers/routes- metabase.documents.api.document/routes))+ metabase.documents.api.document/routes)diff --git a/src/metabase/documents/api/document.clj b/src/metabase/documents/api/document.cljindex f0212049922..00cdbc16a95 100644--- a/src/metabase/documents/api/document.clj+++ b/src/metabase/documents/api/document.clj@@ -11,6 +11,7 @@[metabase.documents.schema :as documents.schema][metabase.events.core :as events][metabase.lib-be.schema :as lib-be.schema]+ [metabase.models.interface :as mi][metabase.parameters.params :as params][metabase.parameters.schema :as parameters.schema][metabase.public-sharing.validation :as public-sharing.validation]@@ -143,20 +144,21 @@- map of old-card-id -> cloned-card-id"[{:keys [id collection_id] :as document}](let [card-ids (prose-mirror/collect-ast document #(when (and (= prose-mirror/card-embed-type (:type %))- (pos? (-> % :attrs :id)))+ (pos-int? (-> % :attrs :id)))(-> % :attrs :id)))to-clone (when (seq card-ids)(t2/select :model/Card {:where [:and [:in :id card-ids][:or [:<> :document_id id][:= :document_id nil]]]}))]- (reduce (fn [accum card]- (api/read-check card)- (assoc accum- (:id card)- (:id (create-card! (assoc card :document_id id :collection_id collection_id)- @api/*current-user*))))- {}- to-clone)))+ (m.document/with-content-gate-cache+ (reduce (fn [accum card]+ (api/read-check card)+ (assoc accum+ (:id card)+ (:id (create-card! (assoc card :document_id id :collection_id collection_id)+ @api/*current-user*))))+ {}+ to-clone))))(defn get-document"Get document by id checking if the current user has permission to access and if the document exists.@@ -170,18 +172,44 @@{:object-id id:user-id api/*current-user-id*}))))+(defn- draft-stored-result-pairings+ "From the incoming document AST and a draft→new card-id map, collect distinct+ `[new-card-id stored-result-id]` pairs for draft embeds that carry a `stored_result_id`.++ Only negative keys from `card-id-map` are considered (the draft-created set); clone+ remappings are irrelevant here."+ [document content-type draft-card-id-map]+ (when (and (seq draft-card-id-map) document)+ (->> (prose-mirror/collect-ast+ {:document document :content_type content-type}+ (fn [{:keys [type attrs]}]+ (when (and (= prose-mirror/card-embed-type type)+ (contains? draft-card-id-map (:id attrs))+ (:stored_result_id attrs))+ [(get draft-card-id-map (:id attrs))+ (:stored_result_id attrs)])))+ distinct+ vec)))+(defn add-card-to-document!"Insert an embed for the already-created card with `card-id` into the prose-mirror ast of thedocument with `document-id` and persist it. `position` is a 0-based index among the document'stop-level blocks; `nil` appends the embed at the end and out-of-range indexes are clamped.- The caller is responsible for write-checking the document first. The document is re-read inside- the transaction so a concurrent edit cannot be overwritten. Returns the updated document."- [document-id card-id position]+ Optional kwargs:+ - `:extra-attrs` — map merged onto the `cardEmbed` attrs (e.g. `:stored_result_id`,+ `:chart_href`, `:child_target_id`, `:host_data`).++ Adding a card clears `:is_placeholder` when it was set. The caller is responsible for+ write-checking the document first. The document is re-read inside the transaction so a+ concurrent edit cannot be overwritten. Returns the updated document."+ [document-id card-id position & {:keys [extra-attrs]}](t2/with-transaction [_conn]- (let [document (api/check-404 (t2/select-one :model/Document :id document-id))]- (t2/update! :model/Document document-id- (select-keys (prose-mirror/insert-card-embed document card-id position) [:document]))+ (let [document (api/check-404 (t2/select-one :model/Document :id document-id))+ updated (prose-mirror/insert-card-embed document card-id position extra-attrs)+ updates (cond-> (select-keys updated [:document])+ (:is_placeholder document) (assoc :is_placeholder false))]+ (t2/update! :model/Document document-id updates)(collections/check-for-remote-sync-update document)))(get-document document-id :log-view? false))@@ -193,10 +221,16 @@"Gets existing `Documents`."[_route-params_query-params]- {:items (t2/hydrate (t2/select :model/Document {:where [:and- (collection/visible-collection-filter-clause)- [:= :archived false]]})- :creator :can_write :is_remote_synced)})+ {:items (as-> (t2/select :model/Document {:where [:and+ (collection/visible-collection-filter-clause)+ [:= :archived false]+ ;; Documents attached to an exploration are+ ;; internal to that exploration — every other listing+ ;; surface (search, recents, collection items)+ ;; excludes them too.+ [:= :exploration_id nil]]}) docs+ (filter mi/can-read? docs)+ (t2/hydrate docs :creator :can_write :is_remote_synced))});; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to;; use our API + we will need it when we make auto-TypeScript-signature generation happen@@ -272,16 +306,29 @@collection_id(:collection_id existing-document)):collection_position collection_position}))- (t2/update! :model/Document document-id- (cond-> document-updates- document (merge (update-cards-in-ast- {:document document- :content_type (:content_type existing-document)}- (merge- (clone-cards-in-document! (assoc existing-document :document document))- (when-not (empty? cards) (create-cards-for-document! cards document-id collection_id @api/*current-user*)))))- name (assoc :name name)- (contains? body :collection_id) (assoc :collection_id collection_id)))+ (let [card-id-map (when document+ (merge+ (clone-cards-in-document! (assoc existing-document :document document))+ (when-not (empty? cards)+ (create-cards-for-document! cards document-id collection_id @api/*current-user*))))+ draft-card-id-map (into {} (filter (comp neg? key) card-id-map))+ pairings (draft-stored-result-pairings document+ (:content_type existing-document)+ draft-card-id-map)]+ (t2/update! :model/Document document-id+ (cond-> document-updates+ document (merge (update-cards-in-ast+ {:document document+ :content_type (:content_type existing-document)}+ card-id-map))+ name (assoc :name name)+ (contains? body :collection_id) (assoc :collection_id collection_id)+ ;; First body save clears the auto-created Summary placeholder flag.+ (and (:is_placeholder existing-document)+ (contains? body :document))+ (assoc :is_placeholder false)))+ (when (seq pairings)+ (card/carry-pairings-for-document! document-id pairings)))(collections/check-for-remote-sync-update existing-document))(let [updated-document (get-document document-id)];; Publish appropriate eventsdiff --git a/src/metabase/documents/core.clj b/src/metabase/documents/core.cljindex 609c293bce2..975388dab6f 100644--- a/src/metabase/documents/core.clj+++ b/src/metabase/documents/core.clj@@ -1,14 +1,24 @@(ns metabase.documents.core(:require[metabase.documents.api.document]+ [metabase.documents.models.document]+ [metabase.documents.prose-mirror][metabase.documents.recent-views][potemkin :as p]))(commentmetabase.documents.api.document/keep-me+ metabase.documents.models.document/keep-me+ metabase.documents.prose-mirror/keep-memetabase.documents.recent-views/keep-me)(p/import-vars[metabase.documents.api.documentadd-card-to-document!- get-document])+ get-document]+ [metabase.documents.models.document+ register-doc-content-visibility-fn!+ with-content-gate-cache]+ [metabase.documents.prose-mirror+ insert-card-embed+ prose-mirror-content-type])diff --git a/src/metabase/documents/models/document.clj b/src/metabase/documents/models/document.cljindex d845d572f63..000056d9eb4 100644--- a/src/metabase/documents/models/document.clj+++ b/src/metabase/documents/models/document.clj@@ -35,6 +35,92 @@(derive :hook/timestamped?)(derive :hook/entity-id))+(defonce ^{:doc "Predicate gating a document's *content* (not merely its existence) below+ collection-read, for documents whose rendered body embeds data the viewer may not+ be entitled to see. Installed at init.++ The only user today is `explorations`: a Summary document belongs to an+ exploration (the `:exploration_id` FK on the document table) and embeds verbatim —+ possibly sandboxed/impersonated/routed — result values, so a collaborator whose+ data-access lens differs from the creator's must not read it.++ `documents` can't call the consumer directly — the module graph runs one way+ (`explorations -> documents`) — so the consumer registers a callback here."}+ doc-content-visibility-fn+ (atom (fn [_doc] true)))++(defn register-doc-content-visibility-fn!+ "Install the content-visibility gate (see [[doc-content-visibility-fn]]). Called once at the+ consuming module's init. `f` takes a document and returns whether the current user may see its+ rendered content."+ [f]+ (reset! doc-content-visibility-fn f))++(def ^:private ^:dynamic *content-gate-pending*+ "Document ids whose content gate is currently being evaluated on this thread.++ The gate is re-entrant by construction: adjudicating a document's content runs query-permission+ checks, and those read-check the source Cards of the queries involved — a Card scoped to a+ Document delegates back to that Document's gate. A document whose visibility depends on itself+ has no answer, so deny rather than recur into a stack overflow inside an authorization check."+ #{})++(def ^:dynamic *cache*+ "Cache atom bound by [[with-content-gate-cache]], or nil to adjudicate on every call."+ nil)++(defmacro with-content-gate-cache+ "Adjudicate each document's content at most once for the duration of `body`. Nesting reuses the+ enclosing cache.++ The verdict is a rollup over the owning exploration's threads and costs roughly twenty app-DB+ queries, so anything looping over documents — or over the Cards scoped to one, which all resolve+ to the same document and so to the same verdict — otherwise pays it once per row. Scope it around+ such a loop; everywhere else reads through."+ {:style/indent 0}+ [& body]+ `(binding [*cache* (or *cache* (atom {}))]+ ~@body))++(defn content-visible?+ "Run the registered content-visibility gate for `document`, guarding against re-entry and reusing+ a verdict already reached under [[with-content-gate-cache]]."+ [document]+ (let [id (:id document)+ ;; Keyed by viewer as well as document: a verdict is only ever valid for the user it was+ ;; computed for, so a cache that outlives or crosses a user binding misses rather than+ ;; handing back someone else's answer.+ k [api/*current-user-id* api/*is-superuser?* id]+ adjudge (fn []+ (if (contains? *content-gate-pending* id)+ false+ (binding [*content-gate-pending* (cond-> *content-gate-pending* id (conj id))]+ (boolean (@doc-content-visibility-fn document)))))]+ (if (and id *cache*)+ (if-some [cached (get @*cache* k)]+ cached+ (let [verdict (adjudge)]+ (swap! *cache* assoc k verdict)+ verdict))+ (adjudge))))++;; can-read?/can-write? compose the collection-permission policy with the content-visibility gate:+;; a document's rendered body can embed data the viewer isn't entitled to, so content access can be+;; narrower than collection access.+(defmethod mi/can-read? :model/Document+ ([instance]+ (and (mi/current-user-has-full-permissions? :read instance)+ (content-visible? instance)))+ ([model pk]+ (mi/can-read? (t2/select-one model pk))))++(defmethod mi/can-write? :model/Document+ ([instance]+ (and (mi/current-user-has-full-permissions? :write instance)+ (content-visible? instance)))+ ([model pk]+ (mi/can-write? (t2/select-one model pk))))+(def DocumentName"Validations for the name of a document"(mu/with-api-error-message@@ -149,6 +235,7 @@:attrs {:archived true:collection-id :collection_id:creator-id :creator_id+ :exploration-id :exploration_id:view-count :view_count:created-at :created_at:updated-at :updated_at@@ -184,10 +271,22 @@"dashboard" "Dashboard""table" "Table"})+(def ^:private non-portable-card-embed-attrs+ "`cardEmbed` attrs holding a raw local database id that serdes cannot rewrite into a portable+ reference, and so must not travel. `:stored_result_id` points at a `stored_result` row — an+ ephemeral cached-snapshot record, not a first-class serdes entity — so exporting the integer+ verbatim would, on import, either dangle or silently resolve to an unrelated instance's+ snapshot. Dropping it degrades a static (snapshot-backed) embed to a live embed of the Card,+ which is portable and renders the same query."+ [:stored_result_id])+(defn- id->entity-id[{{:keys [model] :or {model "card"}} :attrs type :type :as node}](let [id-key (if (= prose-mirror/smart-link-type type) :entityId :id)- id (prose-mirror/node-entity-id node)]+ id (prose-mirror/node-entity-id node)+ node (cond-> node+ (= prose-mirror/card-embed-type type)+ (update :attrs #(apply dissoc % non-portable-card-embed-attrs)))](if-let [db-model (and id (t2/select-one (ast-model->db-model model) :id id))](assoc-in node [:attrs id-key] (mapv #(dissoc % :label) (serdes/generate-path (model->serdes-model model) db-model)))(u/prog1 node@@ -202,32 +301,38 @@(u/prog1 node(log/warn "Model not found at path" (id-key attrs))))))+(defn- serdes-rewritable-node?+ "The AST nodes whose ids serdes rewrites between database ids and entity ids.++ Matches on node *type* only. The id itself cannot be part of this test, because the same predicate+ runs in both directions and the two directions see different shapes: on export `:id` is a raw+ database id, but on import it is a serdes path (a vector of `{:model :id}` maps). A guard that+ expected a positive integer would therefore pass on export and silently skip every node on import,+ leaving the path unresolved. The id-shape checks belong in the readers — [[id->entity-id]] guards+ on `prose-mirror/node-entity-id`, and [[entity-id->id]] on what `load-find-local` resolves to."+ [node]+ (contains? #{prose-mirror/smart-link-type prose-mirror/card-embed-type} (:type node)))+(defn- export-document-content- "Transform cardEmbed/smartLink nodes to use entity IDs instead of database IDs"+ "Transform cardEmbed / smartLink nodes to use entity IDs instead of database IDs"[document serdes-key _](serdes-key(if (= (:content_type document) prose-mirror/prose-mirror-content-type)- (prose-mirror/update-ast- document- #(contains? #{prose-mirror/smart-link-type prose-mirror/card-embed-type} (:type %))- id->entity-id)+ (prose-mirror/update-ast document serdes-rewritable-node? id->entity-id)document)))(defn- import-document-content- "Transform cardEmbed/smartLink nodes to use database IDs instead of entity IDs"+ "Transform live cardEmbed / smartLink nodes to use database IDs instead of entity IDs"[document serdes-key _](serdes-key(if (= (:content_type document) prose-mirror/prose-mirror-content-type)- (prose-mirror/update-ast- document- #(contains? #{prose-mirror/smart-link-type prose-mirror/card-embed-type} (:type %))- entity-id->id)+ (prose-mirror/update-ast document serdes-rewritable-node? entity-id->id)document)))(defmethod serdes/make-spec "Document"[_model-name _opts]{:copy [:archived :archived_directly :content_type :entity_id :name :collection_position]- :skip [:view_count :last_viewed_at :public_uuid :public_uuid_prefix :made_public_by_id]+ :skip [:view_count :last_viewed_at :public_uuid :public_uuid_prefix :made_public_by_id :exploration_id :is_placeholder]:transform {:created_at (serdes/date):updated_at (serdes/date):document {:export-with-context export-document-content@@ -237,6 +342,18 @@:defaults {:archived false:archived_directly false}})+(defmethod serdes/extract-query "Document"+ [model-name opts]+ ;; An exploration document is not first-class content: it is reachable only through its owning+ ;; exploration, its body embeds values computed under its creator's data-access lens, and+ ;; `:exploration_id` is in this spec's `:skip` list — so an exported document would import as an+ ;; ordinary, ungated document detached from any exploration.+ ((get-method serdes/extract-query :default)+ model-name+ (update opts :where (fn [where]+ (let [clause [:= :exploration_id nil]]+ (if where [:and where clause] clause))))))+(defn- document-deps[{:keys [content_type] :as document}](when (= content_type prose-mirror/prose-mirror-content-type)diff --git a/src/metabase/documents/prose_mirror.clj b/src/metabase/documents/prose_mirror.cljindex 99c2ad81b5e..68836a35051 100644--- a/src/metabase/documents/prose_mirror.clj+++ b/src/metabase/documents/prose_mirror.clj@@ -15,7 +15,9 @@[:type :string]])(def card-embed-type- "Type of a card-embed node"+ "Type of a card-embed node. Carries either `:id` (live Card reference) or+ `:stored_result_id` (cached snapshot in `stored_result`). Live-mode embeds render+ through the Card; static-mode embeds render from the cached blob and are read-only.""cardEmbed")(def smart-link-type@@ -94,7 +96,8 @@id)))(defn card-ids- "Get all card-ids"+ "Get the Card ids referenced by live-mode `cardEmbed` nodes (those with a positive `:id`).+ Static-mode embeds (with `:stored_result_id`) are skipped — they don't reference a Card."[document](collect-ast document #(when (and (= card-embed-type (:type %))(pos-int? (-> % :attrs :id)))@@ -106,23 +109,31 @@The embed is a `resizeNode`-wrapped `cardEmbed` node, the same shape the document editorproduces. `index` is a 0-based position among the ast's top-level blocks (0 inserts at thevery top); a `nil` index appends the embed at the end and out-of-range indexes are clamped.+ An `_id` uuid is stamped on the node for per-node identity. `extra-attrs` (optional) are+ merged onto the embed attrs after `:id` / `:_id` (e.g. `:stored_result_id`, `:chart_href`,+ `:child_target_id`, `:host_data` for static exploration embeds).Args:- doc - a :model/Document, this will check that the content-type is valid for prose mirror- card-id - the id of an existing card to embed- index - 0-based top-level block position, or nil to append+ - extra-attrs - optional map of additional attrs to merge onto the cardEmbedReturns:- the document with its :document ast updated"- [{:keys [document] :as doc} card-id index]- (assert-prose-mirror doc)- (let [blocks (vec (:content document))- at (if (int? index)- (-> index (max 0) (min (count blocks)))- (count blocks))- embed {:type "resizeNode"- :content [{:type card-embed-type- :attrs {:id card-id}}]}]- (assoc doc :document- (assoc (or document {:type "doc"})- :content (into (conj (subvec blocks 0 at) embed) (subvec blocks at))))))+ ([doc card-id index]+ (insert-card-embed doc card-id index nil))+ ([{:keys [document] :as doc} card-id index extra-attrs]+ (assert-prose-mirror doc)+ (let [blocks (vec (:content document))+ at (if (int? index)+ (-> index (max 0) (min (count blocks)))+ (count blocks))+ attrs (merge {:id card-id :_id (random-uuid)}+ extra-attrs)+ embed {:type "resizeNode"+ :content [{:type card-embed-type+ :attrs attrs}]}]+ (assoc doc :document+ (assoc (or document {:type "doc"})+ :content (into (conj (subvec blocks 0 at) embed) (subvec blocks at)))))))diff --git a/src/metabase/documents/view_log.clj b/src/metabase/documents/view_log.cljindex 2a4e270533e..e6a4fd4426a 100644--- a/src/metabase/documents/view_log.clj+++ b/src/metabase/documents/view_log.clj@@ -65,7 +65,10 @@(view-log/increment-view-counts! :model/Document object-id)(update-document-last-viewed-at! object-id)(view-log/record-views! (view-log/generate-view :model :model/Document event))- ;; Update recent views alongside existing view log functionality- (activity-feed/update-users-recent-views! user-id :model/Document object-id :view)+ ;; Exploration documents aren't first-class content — they're surfaced only through their+ ;; owning Exploration, and are hidden from search and collection listings. Skip recording+ ;; recent views for them so they don't crowd out real document views in the bucket cap.+ (when (nil? (t2/select-one-fn :exploration_id :model/Document :id object-id))+ (activity-feed/update-users-recent-views! user-id :model/Document object-id :view))(catch Throwable e(log/warnf "Failed to process document view event. %s: %s" topic (ex-message e))))))diff --git a/src/metabase/explorations/api.clj b/src/metabase/explorations/api.cljindex b89e0d77cfc..1ccc8fec217 100644--- a/src/metabase/explorations/api.clj+++ b/src/metabase/explorations/api.clj@@ -8,6 +8,7 @@[metabase.api.routes.common :refer [+auth]][metabase.app-db.core :as mdb][metabase.collections.models.collection :as collection]+ [metabase.documents.core :as documents][metabase.events.core :as events][metabase.explorations.blocks :as explorations.blocks][metabase.explorations.core :as explorations]@@ -54,6 +55,49 @@(api/write-check :model/Collection new-coll)(api/write-check collection/root-collection)))))+(def ^:private summary-document-name+ "Name for the auto-created Summary document on each exploration."+ "Summary")++(defn- cascade-collection-id-to-documents!+ "Propagate an Exploration's new `collection_id` to its Summary document.+ Mirrors the dashboard-question cascade in `dashboards_rest/api.clj`."+ [exploration-id new-coll-id]+ (t2/update! :model/Document+ :exploration_id exploration-id+ {:collection_id new-coll-id}))++(defn- cascade-archived-to-documents!+ "Propagate an Exploration's archive flip to its Summary document.+ Mirrors `dashboards_rest/api.clj` (parent-archive cascade for dashboard questions):+ on archive, flip every doc that wasn't already archived directly; on unarchive,+ flip every doc that was cascade-archived. Docs with `archived_directly=true`+ (user-archived) are never touched."+ [exploration-id new-archived?]+ (if new-archived?+ (t2/update! :model/Document+ :exploration_id exploration-id+ :archived false+ {:archived true :archived_directly false})+ (t2/update! :model/Document+ :exploration_id exploration-id+ :archived true+ :archived_directly false+ {:archived false})))++(defn- insert-summary-document!+ "Insert the auto-created Summary document for a newly created exploration. Explore-further+ must not call this — there is one Summary per exploration."+ [exploration-id coll-id]+ (t2/insert! :model/Document+ {:name summary-document-name+ :document {:type "doc" :content []}+ :content_type documents/prose-mirror-content-type+ :creator_id api/*current-user-id*+ :collection_id coll-id+ :exploration_id exploration-id+ :is_placeholder true}))+(defn- blocks-by-thread-id"The persisted blocks (`ExplorationBlock`) for `thread-ids`, in authoring order, grouped by`:exploration_thread_id`."@@ -188,7 +232,7 @@(defn- hydrate-exploration [exploration](-> exploration- (t2/hydrate :creator :can_write :collection+ (t2/hydrate :creator :can_write :collection :document[:threads :queries :timelines])(update :threads#(some->> %@@ -408,6 +452,19 @@[:maybe [:sequential ExploreFilterSpec]]][:pages [:sequential ::ExplorationPageNode]]])+(mr/def ::ExplorationDocument+ "Schema for the Summary document attached to an exploration."+ [:map+ [:id ms/PositiveInt]+ [:name :string]+ [:exploration_id ms/PositiveInt]+ [:creator_id ms/PositiveInt]+ [:content_type :string]+ [:is_placeholder :boolean]+ [:created_at ms/TemporalInstant]+ [:updated_at ms/TemporalInstant]+ [:archived {:optional true} :boolean]])+(mr/def ::HydratedThread"Schema for an Exploration thread with hydrated selections and queries."[:map@@ -453,6 +510,7 @@[:creator {:optional true} [:maybe :map]][:collection_id {:optional true} [:maybe ms/PositiveInt]][:archived {:optional true} :boolean]+ [:document {:optional true} [:maybe ::ExplorationDocument]][:threads {:optional true} [:maybe [:sequential ::HydratedThread]]][:created_at {:optional true} [:maybe :any]][:updated_at {:optional true} [:maybe :any]]])@@ -578,9 +636,10 @@(api.macros/defendpoint :post "/" :- ::HydratedExploration"Create a new exploration with a single thread, persist the user's selected metrics, dimensions,- and timelines, and stamp the thread as started. Actual planning is async; this endpoint returns- immediately with an empty queries list. Clients should poll `GET /:id` until the queries appear- and reach a terminal status.+ and timelines, and stamp the thread as started. Also auto-creates a placeholder Summary+ document in the same collection. Actual planning is async; this endpoint returns immediately+ with an empty queries list. Clients should poll `GET /:id` until the queries appear and reach+ a terminal status.Accepts the per-area `:blocks` payload (one entry per Research-plan block), persistedverbatim, plus a thread-scoped `:timeline_ids`."@@ -615,6 +674,7 @@tid (:id thread)](insert-blocks! tid blocks)(insert-thread-timelines! tid timeline_ids)+ (insert-summary-document! (:id exploration) collection_id)(explorations.queues/start-thread! tid)(t2/select-one :model/Exploration :id (:id exploration))))];; Published after the transaction commits (matching PUT) so listeners can never observe an@@ -733,10 +793,12 @@(defn- my-explorations-honeysql"HoneySQL for the explorations `user-id` created or edited, ordered by that user's most-recent- touch (descending). \"Touch\" is the union of two streams, all attributed to the user:+ touch (descending). \"Touch\" is the union of three streams, all attributed to the user:1. the user's `Exploration` revisions (metadata / structure edits),- 2. `exploration.created_at` for explorations the user created — creation is a touch, and+ 2. the user's `Document` revisions for the exploration's Summary document+ (mapped back via `document.exploration_id`),+ 3. `exploration.created_at` for explorations the user created — creation is a touch, and`created_at` stays reliable even after the creation revision ages out of the`revision/max-revisions` cap.@@ -752,6 +814,14 @@:from [:revision]:where [:and [:= :model "Exploration"] [:= :user_id user-id]]}^:allow-subquery+ {:select [[:d.exploration_id :eid] [:dr.timestamp :ts]]+ :from [[:revision :dr]]+ :join [[:document :d] [:= :d.id :dr.model_id]]+ :where [:and+ [:= :dr.model "Document"]+ [:= :dr.user_id user-id]+ [:not= :d.exploration_id nil]]}+ ^:allow-subquery{:select [[:id :eid] [:created_at :ts]]:from [:exploration]:where [:= :creator_id user-id]}]}@@ -779,10 +849,10 @@(api.macros/defendpoint :get "/mine" :- ::MineResponse"Explorations the current user created or edited, most-recently-touched first, paginated.- \"Touched\" composes the user's own edits to the exploration and its creation — see- [[my-explorations-honeysql]]. Explorations that were moved into a collection the user can no- longer read are excluded, as are archived ones. Returns the collection-items envelope:- `{:total :limit :offset :data}`."+ \"Touched\" composes the user's own edits to the exploration, to its Summary document, and its+ creation — see [[my-explorations-honeysql]]. Explorations that were moved into a collection the+ user can no longer read are excluded, as are archived ones. Returns the collection-items+ envelope: `{:total :limit :offset :data}`."[](let [limit (request/limit)offset (request/offset)@@ -804,7 +874,10 @@When `collection_id` changes, the caller must have write perms on the destination collection(or the root collection when `collection_id` is nil). Source perms are enforced by- `api/write-check` against the exploration itself via `:perms/use-parent-collection-perms`."+ `api/write-check` against the exploration itself via `:perms/use-parent-collection-perms`.+ Moving an exploration cascades the new `collection_id` onto its Summary document; flipping+ `archived` cascades to the same document (skipping any that were directly user-archived,+ mirroring the dashboard / dashboard-question cascade)."[{:keys [id]} :- [:map [:id ms/PositiveInt]]_query-paramsupdates :- UpdateExploration]@@ -815,7 +888,11 @@(check-destination-collection-perms! existing updates')(t2/with-transaction [_](when (seq updates')- (t2/update! :model/Exploration id updates')))+ (t2/update! :model/Exploration id updates')+ (when (contains? updates' :collection_id)+ (cascade-collection-id-to-documents! id (:collection_id updates')))+ (when (contains? updates' :archived)+ (cascade-archived-to-documents! id (:archived updates')))))(let [updated (t2/select-one :model/Exploration :id id)](when (seq updates')(events/publish-event! :event/exploration-update@@ -825,8 +902,8 @@(api.macros/defendpoint :delete "/:id" :- :nil"Hard-delete an exploration. Soft delete is `PUT /api/exploration/:id {archived: true}`.- Cascades to every `exploration_thread` and `exploration_query` via the on-delete-cascade- FKs configured in the explorations migration."+ Cascades to every `exploration_thread`, `exploration_query`, and attached Summary `document`+ via the on-delete-cascade FKs configured in the explorations migration."[{:keys [id]} :- [:map [:id ms/PositiveInt]]](let [existing (get-exploration-or-404 id)](api/write-check existing)@@ -989,6 +1066,100 @@(t2/update! :model/ExplorationPage :id [:in page_ids] {:hidden hidden}))nil)+(defn- summary-document-or-404+ "The non-archived Summary document for `exploration-id`, or 404."+ [exploration-id]+ (api/check-404 (t2/select-one :model/Document+ :exploration_id exploration-id+ :archived false)))++(defn- exploration-query-ids-belong-to-exploration?+ "True when every id in `eq-ids` refers to an `ExplorationQuery` whose thread belongs to+ `exploration-id`. Duplicate ids in the input still only need one matching row."+ [exploration-id eq-ids]+ (let [distinct-ids (distinct eq-ids)]+ (= (count distinct-ids)+ (t2/count :model/ExplorationQuery+ {:where [:and+ [:in :id distinct-ids]+ [:in :exploration_thread_id+ ^:allow-subquery {:select [:id]+ :from [:exploration_thread]+ :where [:= :exploration_id exploration-id]}]]}))))++(defn- document-summary+ "Project a Document onto the `::ExplorationDocument` wire shape."+ [doc-id]+ (t2/select-one [:model/Document+ :id :name :exploration_id :creator_id :content_type+ :created_at :updated_at :archived :is_placeholder]+ :id doc-id))++(defn- page-explore-filters+ "Hydrated explore-further filters on the block that owns `page-id`, or nil+ when the page is unfiltered."+ [page-id]+ (when-let [block-id (t2/select-one-fn :exploration_block_id+ :model/ExplorationPage+ :id page-id)]+ (-> (t2/select-one-fn :metrics :model/ExplorationBlock :id block-id)+ first+ :explore_filters+ not-empty)))++(api.macros/defendpoint :post "/:id/summary/append" :- ::ExplorationDocument+ "Append a static `cardEmbed` representing a *composite chart* — built from one or more+ `ExplorationQuery` snapshots combined into a single qp-result — to the exploration's+ Summary document.++ The body `:exploration_query_ids` is the FE-rendered SeriesGroup's full set (one entry+ for single-query charts; multiple for combined cartesian / heat-map charts). The BE+ combines those source snapshots (`metabase.explorations.composite/combine`) into one+ ephemeral `stored_result` and materializes one ephemeral `report_card` referencing it.+ The cardEmbed node remains single-card.++ - `chart_href` / `child_target_id` / `host_data` are written onto the node so the FE+ can deep-link the embed title back to the source page, share that page's comment+ stream (`child_target_id`), and resolve highlight hover and explore-further filter+ pills via opaque `host_data`.+ - `display` / `visualization_settings` are required FE-computed render settings (from+ `buildSeries` / `getDisplay`); the BE bakes them onto the ephemeral card.++ All source EQs must belong to a thread of this exploration. Appending clears+ `is_placeholder` when it was set."+ [{:keys [id]} :- [:map [:id ms/PositiveInt]]+ _query-params+ {:keys [exploration_query_ids display visualization_settings]}+ :- [:map+ [:exploration_query_ids [:sequential {:min 1} ms/PositiveInt]]+ [:display :string]+ [:visualization_settings ms/Map]]]+ (api/write-check (get-exploration-or-404 id))+ (let [doc (summary-document-or-404 id)]+ (api/check-404 (exploration-query-ids-belong-to-exploration? id exploration_query_ids))+ (t2/with-transaction [_conn]+ (let [{:keys [card-id stored-result-id primary-eq]}+ (eqr/create-ephemeral-card-for-exploration-queries!+ exploration_query_ids (:id doc) (:collection_id doc)+ @api/*current-user*+ {:display display+ :visualization-settings visualization_settings})+ page-id (:page_id primary-eq)+ chart-href (explorations.blocks/page-url id page-id)+ ;; Snapshot onto host_data so the Summary embed can render pills without a live lookup.+ explore-filters (page-explore-filters page-id)+ extra-attrs {:stored_result_id stored-result-id+ :chart_href chart-href+ ;; Comment stream key (page id). Distinct from `_id`,+ ;; which must stay unique per node for duplicate embeds.+ :child_target_id (str page-id)+ :host_data (cond-> {:query_ids exploration_query_ids}+ explore-filters (assoc :explore_filters explore-filters))}]+ (documents/add-card-to-document!+ (:id doc) card-id nil+ :extra-attrs extra-attrs)))+ (document-summary (:id doc))))+;;; ----------------------------------------- routes -----------------------------------------(def ^{:arglists '([request respond raise])} routesdiff --git a/src/metabase/explorations/blocks.clj b/src/metabase/explorations/blocks.cljindex 7c85eaf596f..dd030a08995 100644--- a/src/metabase/explorations/blocks.clj+++ b/src/metabase/explorations/blocks.clj@@ -13,6 +13,12 @@(set! *warn-on-reflection* true)+(defn page-url+ "Relative URL of a page in the exploration detail view. Used by the summary-append+ endpoint to deep-link a static `cardEmbed`'s title back to its page."+ [exploration-id page-id]+ (str "/question/research/" exploration-id "/page/" page-id))+;;; ------------------------------------------- names -------------------------------------------(defn- dimension-anchored?diff --git a/src/metabase/explorations/composite.clj b/src/metabase/explorations/composite.cljnew file mode 100644index 00000000000..19f98fd4150--- /dev/null+++ b/src/metabase/explorations/composite.clj@@ -0,0 +1,115 @@+(ns metabase.explorations.composite+ "Combine multiple per-query qp-result snapshots into a single composite+ qp-result that the ephemeral document-embed card can render through the+ standard single-Card pipeline.++ Driver: the FE-sent `visualization_settings`.++ Every multi-snapshot combine appends a discriminator column whose value+ identifies the source `ExplorationQuery` — its hydrated `:segment_name` (the+ FE shows the same value in its live-preview legend / pivot), falling back to+ the EQ's own `:name`, then to `(All)`. The values are then made unique: two+ sources sharing a label would otherwise collapse into a single series.++ - `N = 1` — pass-through; the lone qp-result is the composite.+ - `:table.pivot` truthy — treat as a heat-map combine. Append a+ `\"Segment\"` discriminator column. The FE hands us `:table.pivot`,+ `:table.pivot_column`, `:table.cell_column` settings that already+ reference the original cols, so they remain valid after the append.+ - Otherwise — multi-series cartesian combine. Append a `\"Series\"`+ discriminator column. The FE is expected to send+ `:graph.dimensions [<x-col> \"Series\"]` so the chart picks the new+ column up as the series breakout.++ This module is pure data — serialisation/persistence lives in+ `metabase.explorations.models.exploration-query-result`."+ (:require+ [metabase.util.i18n :refer [tru]]))++(defn- discriminator-col+ "Build the synthetic column we append to the right of the original+ cols. `:name` is the untranslated protocol key; `:display_name` is+ localized. `:source :breakout` mirrors the FE's `getHeatMapSeries`+ shape so downstream column-resolution code treats it like a real+ breakout.++ The composite result is handed to the FE verbatim, so this column has to carry+ the same type keys every real col does — the FE formats by `:base_type` and+ resolves a `graph.dimensions` entry to a column by `:field_ref`. The values+ are always the discriminator strings [[combine-rows]] appends, hence+ `:type/Text`; the `[:field \"name\" …]` ref is the shape a native query's cols+ use for a column that has no Field behind it."+ [col-name display-name]+ {:name col-name+ :display_name display-name+ :base_type :type/Text+ :effective_type :type/Text+ :field_ref [:field col-name {:base-type :type/Text}]+ :source :breakout})++(defn- discriminator-values+ "One discriminator value per eq-result, positionally aligned with `eq-results`.++ The label is the EQ's hydrated `:segment_name`, then its own `:name`, then+ `(All)`. Whatever the source, the values must be *distinct*: they are the+ series/pivot key, so two sources sharing one would render as a single series+ carrying both sources' rows. Only labels that actually repeat are suffixed+ with their 1-based position, which leaves the common shape — one unlabeled+ \"(All)\" query alongside named segments — reading exactly as before."+ [eq-results]+ (let [labels (mapv (fn [{:keys [eq]}]+ (or (not-empty (:segment_name eq))+ (not-empty (:name eq))+ (tru "(All)")))+ eq-results)+ dupes (into #{} (keep (fn [[label n]] (when (> n 1) label)))+ (frequencies labels))]+ (into []+ (map-indexed (fn [i label]+ (if (contains? dupes label)+ (str label " " (inc i))+ label)))+ labels)))++(defn- combine-rows+ "Union rows across the source qp-results, appending each source's+ discriminator value (see [[discriminator-values]]) to every one of its rows."+ [eq-results]+ (vec (mapcat (fn [{:keys [qp-result]} discriminator-value]+ (map #(conj (vec %) discriminator-value) (get-in qp-result [:data :rows])))+ eq-results+ (discriminator-values eq-results))))++(defn- combine-cols+ "Take the first eq-result's cols and append the discriminator column.+ All source qp-results share the same column shape upstream (they come+ from the same parent card with different filters/breakouts), so the+ first eq-result's cols are representative."+ [eq-results col-name display-name]+ (let [first-cols (get-in (first eq-results) [:qp-result :data :cols])]+ (conj (vec first-cols) (discriminator-col col-name display-name))))++(defn- combine-with-discriminator+ "Build a composite qp-result by appending a discriminator column to+ every row. The first eq-result supplies the structural scaffolding+ (`:status`, etc.); we replace `:data` with the merged cols + rows and+ refresh `:row_count` so downstream consumers see the new size."+ [eq-results col-name display-name]+ (let [first-qp (:qp-result (first eq-results))+ cols (combine-cols eq-results col-name display-name)+ rows (combine-rows eq-results)]+ (-> first-qp+ (assoc-in [:data :cols] cols)+ (assoc-in [:data :rows] rows)+ (assoc :row_count (count rows)))))++(defn combine+ "Combine `eq-results` (a sequence of `{:eq … :qp-result …}` maps,+ with at least one entry) into a single composite qp-result. `vs` is the+ FE-sent `visualization_settings` and drives which combine strategy to+ use."+ [eq-results vs]+ (cond+ (= 1 (count eq-results)) (:qp-result (first eq-results))+ (:table.pivot vs) (combine-with-discriminator eq-results "Segment" (tru "Segment"))+ :else (combine-with-discriminator eq-results "Series" (tru "Series"))))diff --git a/src/metabase/explorations/derived_perms.clj b/src/metabase/explorations/derived_perms.cljindex bfb3ca1ed73..1f89af1befc 100644--- a/src/metabase/explorations/derived_perms.clj+++ b/src/metabase/explorations/derived_perms.clj@@ -1,9 +1,9 @@(ns metabase.explorations.derived-perms"Decides whether the *current user* may see an exploration thread's derived read-data — its- queries, the block/page tree built from them, and the thread name. All of these embed verbatim- values from results computed under the exploration creator's data-access lens (sandboxing /- connection impersonation / database routing), so a viewer whose lens is incompatible with the- creator's must not see them.+ queries, the block/page tree built from them, the thread name, and the Summary document's+ content. All of these embed verbatim values from results computed under the exploration+ creator's data-access lens (sandboxing / connection impersonation / database routing), so a+ viewer whose lens is incompatible with the creator's must not see them.The per-artifact rule is exactly the gate the results themselves are streamed through([[metabase.queries.cached-result]]): superusers pass unconditionally; any other viewer must hold@@ -181,3 +181,65 @@(set/difference thread-ids(blocked-thread-ids (concat (finalized-queries thread-ids)(lens-stamped-threads thread-ids))))))))++(defn- exploration-content-visible?+ "The gate's verdict for a document owned by `exploration-id` (nil => not a Summary, unaffected)."+ [exploration-id]+ (if (nil? exploration-id)+ true+ (let [thread-ids (t2/select-pks-set :model/ExplorationThread :exploration_id exploration-id)]+ (or (empty? thread-ids)+ (= thread-ids (thread-ids-with-visible-derived-data thread-ids))))))++(defn doc-content-visible-to-current-user?+ "Content-visibility gate installed via+ [[metabase.documents.core/register-doc-content-visibility-fn!]] at init: a document owned by+ an exploration (the Summary) embeds verbatim result values, so its content follows the+ exploration's threads' derived-data visibility. Documents outside explorations are unaffected."+ [document]+ (cond+ (contains? document :exploration_id)+ (exploration-content-visible? (:exploration_id document))++ (:id document)+ (exploration-content-visible?+ (t2/select-one-fn :exploration_id :model/Document :id (:id document)))++ :else+ false))++(defn gate-comment-contexts+ "Withhold `:context` from `comments` on `exploration-id` whose data the current user may not see.++ A comment's context carries the identity of the chart point it is anchored to, including dimension+ values read out of the creator's result set — the same material+ [[metabase.explorations.api/gate-threads-derived-data]] redacts from the exploration itself. The+ comments endpoint cannot rely on its read check to cover that: an Exploration is read-checked on+ collection permissions alone, since the derived-data gate is applied by its read endpoints rather+ than by `can-read?`.++ The comment itself is left in place — conversations stay visible, only the values they carry are+ withheld. A comment anchored to a page of a thread the viewer can see keeps its context; anything+ else (a Summary block, an unanchored comment, or a page of a gated thread) loses it."+ [exploration-id comments]+ (let [thread-ids (t2/select-pks-set :model/ExplorationThread :exploration_id exploration-id)]+ (if (or (empty? thread-ids) (not-any? :context comments))+ comments+ (let [visible (thread-ids-with-visible-derived-data thread-ids)]+ (if (= thread-ids visible)+ comments+ (let [page->thread (into {}+ (map (juxt :id :thread_id))+ (t2/query {:select [[:p.id :id] [:b.exploration_thread_id :thread_id]]+ :from [[:exploration_page :p]]+ :join [[:exploration_block :b]+ [:= :b.id :p.exploration_block_id]]+ :where [:in :b.exploration_thread_id (vec thread-ids)]}))]+ (mapv (fn [comment]+ ;; A non-numeric `child_target_id` is a Summary block uuid, and a nil one is+ ;; unanchored; both parse to nil and so fall through to the deny branch.+ (let [thread-id (get page->thread (parse-long (str (:child_target_id comment))))]+ (if (contains? visible thread-id)+ comment+ (dissoc comment :context))))+ comments)))))))diff --git a/src/metabase/explorations/init.clj b/src/metabase/explorations/init.cljindex 25b9d11e060..a9a4f5fcd7c 100644--- a/src/metabase/explorations/init.clj+++ b/src/metabase/explorations/init.clj@@ -1,5 +1,8 @@(ns metabase.explorations.init(:require+ [metabase.comments.core :as comments]+ [metabase.documents.core :as documents]+ [metabase.explorations.derived-perms :as derived-perms][metabase.explorations.models.exploration][metabase.explorations.models.exploration-block][metabase.explorations.models.exploration-page]@@ -10,3 +13,17 @@[metabase.explorations.queues][metabase.explorations.settings][metabase.explorations.task.collect-orphaned-results]))++;; Install the content-visibility gate into the documents module's read/write path, so the+;; Summary doc's content is hidden from collaborators whose lens differs from the creator's.+(documents/register-doc-content-visibility-fn!+ derived-perms/doc-content-visible-to-current-user?)++;; Withhold the warehouse values a comment's context carries from viewers the exploration's+;; data-access gate excludes. Registered here for the same reason as the gate above: `comments`+;; cannot depend on `explorations`.+(comments/register-context-gate!+ (fn [target-type target-id comments]+ (if (= target-type "exploration")+ (derived-perms/gate-comment-contexts target-id comments)+ comments)))diff --git a/src/metabase/explorations/models/exploration.clj b/src/metabase/explorations/models/exploration.cljindex 7ed0ccbf633..ae5bc4ad896 100644--- a/src/metabase/explorations/models/exploration.clj+++ b/src/metabase/explorations/models/exploration.clj@@ -49,6 +49,29 @@:id{:default []}))+(methodical/defmethod t2/batched-hydrate [:model/Exploration :document]+ "Hydrate the Summary document attached to each exploration (at most one)."+ [_model k explorations]+ (mi/instances-with-hydrated-data+ explorations k+ #(into {}+ (map (fn [[eid docs]] [eid (first docs)]))+ (group-by :exploration_id+ (t2/select [:model/Document+ :id :name :exploration_id :creator_id :content_type+ :created_at :updated_at :archived :is_placeholder]+ :exploration_id [:in (map :id explorations)]+ {:order-by [[:created_at :asc] [:id :asc]]})))+ :id+ {:default nil}))++;; `:document` is a Toucan automagic-hydration key (FK `document_id` → `:model/Document`).+;; Explorations have no such FK; without this override the automagic path wins and always+;; returns nil, shadowing [[batched-hydrate]] above.+(methodical/defmethod t2/model-for-automagic-hydration [:model/Exploration :document]+ [_model _k]+ nil)+;;; ----------------------------------------------- Search ----------------------------------------------------------(search.spec/define-spec "exploration"@@ -58,11 +81,11 @@:creator-id :creator_id:created-at :created_at:updated-at :updated_at+ :exploration-id false:pinned [:> [:coalesce :collection_position [:inline 0]] [:inline 0]]}:search-terms [:name :description]:joins {:collection [:model/Collection [:= :collection.id :this.collection_id]]}:render-terms {:exploration-name :name- :exploration-id :id:collection-authority_level :collection.authority_level:collection-location :collection.location:collection-name :collection.namediff --git a/src/metabase/explorations/models/exploration_query_result.clj b/src/metabase/explorations/models/exploration_query_result.cljindex 50b6329d426..f634e58ca73 100644--- a/src/metabase/explorations/models/exploration_query_result.clj+++ b/src/metabase/explorations/models/exploration_query_result.clj@@ -1,11 +1,19 @@(ns metabase.explorations.models.exploration-query-result(:require[clojure.edn :as edn]+ [metabase.api.common :as api]+ [metabase.explorations.composite :as composite][metabase.models.interface :as mi]+ [metabase.queries.core :as queries]+ [metabase.query-permissions.core :as query-perms]+ [metabase.query-processor.core :as qp][metabase.util.encryption :as encryption]+ [metabase.util.i18n :refer [tru]][metabase.util.log :as log][methodical.core :as methodical]- [toucan2.core :as t2]))+ [toucan2.core :as t2])+ (:import+ (java.io ByteArrayInputStream)))(set! *warn-on-reflection* true)@@ -61,3 +69,147 @@(when-let [sr-id (t2/select-one-fn :stored_result_id :model/ExplorationQueryResult:exploration_query_id eq-id)](t2/select-one :model/StoredResult :id sr-id)))++(defn- deserialize-stored-result+ "Inverse of [[qp/do-with-serialization]] for a stored_result's+ single-frame nippy+gzip blob. Returns nil for missing/unreadable bytes."+ [^bytes result-bytes]+ (when result-bytes+ (with-open [is (ByteArrayInputStream. result-bytes)]+ (qp/with-reducible-deserialized-results [[qp-result _] is]+ qp-result))))++(defn- serialize-qp-result+ "Run `qp/do-with-serialization` on a single in-memory qp-result and return the+ gzipped+nippy byte array. The qp-result here comes from `composite/combine`, which+ builds on top of already-deserialised source snapshots — the `prepare-for-serialization`+ step the task runner does on a fresh QP result isn't needed (no metadata-provider atoms+ to strip), since whatever was strippable was already stripped at write time."+ ^bytes [qp-result]+ (qp/do-with-serialization+ (fn [in result-fn]+ (in qp-result)+ (result-fn))))++(defn- load-eq-results+ "For each `eq-id`, resolve the `{:eq … :eqr … :sr … :qp-result …}` map. Asserts the EQ+ exists and its stored_result_id is set + the snapshot bytes deserialise. Order is+ preserved from `eq-ids` — that ordering drives the composite snapshot row order."+ [eq-ids]+ (mapv+ (fn [eq-id]+ (let [eq (api/check-404 (t2/hydrate (t2/select-one :model/ExplorationQuery :id eq-id)+ :segment_name))+ eqr (api/check-404 (t2/select-one :model/ExplorationQueryResult+ :exploration_query_id eq-id))+ sr (api/check-404 (t2/select-one :model/StoredResult :id (:stored_result_id eqr)))+ qp-result (api/check-404 (deserialize-stored-result (:result_data sr)))]+ {:eq eq :eqr eqr :sr sr :qp-result qp-result}))+ eq-ids))++(defn- composite-data-access-token+ "The lens stamp for a composite snapshot built from `eq-results`.++ A `stored_result`'s `data_access_token` records the sandbox / impersonation / routing lens its+ rows were computed under, and the read gate denies any non-superuser whose own lens differs.++ Only one token can describe the row, so every source has to agree on it. A blend of two+ different lenses has no single honest stamp: whichever one was picked, half the rows would be+ served under a lens they were not computed under. Refuse instead of persisting a snapshot the+ gate cannot adjudicate."+ [eq-results]+ (let [tokens (into #{} (map (comp :data_access_token :sr)) eq-results)]+ (when (contains? tokens nil)+ (throw (ex-info (tru "Cannot combine these results: a source result has no recorded data-access context.")+ {:status-code 400})))+ (when (> (count tokens) 1)+ (throw (ex-info (tru "Cannot combine these results: they were computed under different data-access contexts.")+ {:status-code 400})))+ (first tokens)))++(defn create-ephemeral-card-for-exploration-queries!+ "Materialize an ephemeral `report_card` that represents a *composite chart* — possibly+ built from multiple `ExplorationQuery` snapshots combined into one — for a single document+ embed.++ - `eq-ids` Non-empty seq of `ExplorationQuery` ids; their stored_result snapshots+ are combined by `metabase.explorations.composite/combine` into one+ composite qp-result. The first id supplies metadata fallbacks (source+ card, dataset_query). A multi-id combine is persisted as a brand-new+ `stored_result` row; a single id reuses the source snapshot as-is (no+ duplicate row).+ - `document-id` Target document — the materialized card is scoped to it (`document_id`+ set + `collection_id` matched), which keeps it out of the regular+ collection-browser / data-picker pickers.+ - `collection-id` The document's collection (cards inherit perms).+ - `creator` Current user.+ - opts `:display` / `:visualization-settings` — required FE-computed values from+ `buildSeries` / `getDisplay`, baked onto the card verbatim.++ For a multi-id combine, inserts a `StoredResultUse` row for the new composite snapshot plus+ one per source stored_result, so GC of any source cascades through and the read gate can+ compare the viewer against every source.+ For a single id, inserts the one row tying the card to the (reused) source snapshot.++ Returns a map `{:card-id … :stored-result-id … :primary-eq …}` — `stored-result-id` is the+ new composite row for a combine, or the source snapshot id for a single-query embed;+ `primary-eq` is the first source `ExplorationQuery` (hydrated `:segment_name`), handed back so+ callers can build the chart deep link without re-fetching it."+ [eq-ids document-id collection-id creator+ {:keys [display visualization-settings]}]+ (let [eq-ids (distinct eq-ids)+ eq-results (load-eq-results eq-ids)+ first-eq (:eq (first eq-results))+ first-sr (:sr (first eq-results))+ src-card (when-let [card-id (:card_id first-eq)]+ (t2/select-one [:model/Card :name :description :display :visualization_settings]+ :id card-id))+ composite-qp (composite/combine eq-results (or visualization-settings {}))+ dataset-query (:dataset_query first-eq)+ creator-id (:id creator)]+ (doseq [dq (distinct (map (fn [{:keys [eq sr]}]+ (or (:dataset_query eq) (:dataset_query sr)))+ eq-results))]+ (query-perms/check-run-permissions-for-query dq))+ ;; Single-query embeds reuse the source snapshot as-is — `composite/combine` returned it+ ;; unchanged, so copying its bytes into a fresh stored_result would just duplicate them.+ ;; Only a genuine multi-snapshot combine produces new cols/rows that need their own row.+ (let [single? (= 1 (count eq-results))+ composite-bytes (when-not single? (serialize-qp-result composite-qp))]+ (t2/with-transaction [_conn]+ (let [stored-result-id (if single?+ (:id first-sr)+ (first (t2/insert-returning-pks!+ :model/StoredResult+ {:result_data composite-bytes+ :creator_id creator-id+ :database_id (or (:database_id first-sr)+ (-> dataset-query :database))+ :dataset_query dataset-query+ ;; `composite/combine` refreshed :row_count to the+ ;; combined row set's size.+ :row_count (:row_count composite-qp)+ ;; Without this the read gate denies the composite to+ ;; every non-superuser. See [[composite-data-access-token]].+ :data_access_token (composite-data-access-token eq-results)})))+ card-id (:id (queries/create-card!+ {:name (or (not-empty (:name first-eq))+ (not-empty (:name src-card))+ (tru "Chart"))+ :description (:description src-card)+ :type :question+ :dashboard_id nil+ :dataset_query dataset-query+ :display display+ :visualization_settings visualization-settings+ :document_id document-id+ :collection_id collection-id}+ creator))]+ ;; Record the (card -> stored_result) refs for lifecycle/GC tracking. For a combine we+ ;; reference the new composite snapshot plus every source, so a delete of any source+ ;; cascades; for a single-query embed the snapshot *is* the source, so one row covers it.+ (t2/insert! :model/StoredResultUse {:stored_result_id stored-result-id :card_id card-id})+ (when-not single?+ (doseq [{:keys [sr]} eq-results]+ (t2/insert! :model/StoredResultUse {:stored_result_id (:id sr) :card_id card-id})))+ {:card-id card-id :stored-result-id stored-result-id :primary-eq first-eq})))))diff --git a/src/metabase/explorations/task/collect_orphaned_results.clj b/src/metabase/explorations/task/collect_orphaned_results.cljindex e765e1f4cb8..18c7fe2d0c1 100644--- a/src/metabase/explorations/task/collect_orphaned_results.clj+++ b/src/metabase/explorations/task/collect_orphaned_results.clj@@ -9,14 +9,22 @@is refcount semantics — collect when the last referent goes — which SQL cannot expressdeclaratively, hence a sweep.- Reachability is what defines an orphan, and it runs through exactly one column:- `exploration_query_result.stored_result_id` (see- [[metabase.explorations.models.exploration-query-result/stored-results]], the only reader of the- blob). A row with no `exploration_query_result` referencing it is unreachable by any code path.- `stored_result_use` is bookkeeping rather than reachability, and is deliberately *not* consulted:- restarting a thread deletes its query rows — and with them the `exploration_query_result` rows —- while leaving `stored_result_use` behind, so treating a use row as a reason to keep would leak a- blob on every restart. Deleting the blob cascades those rows away."+ Reachability is what defines an orphan, and it runs through exactly two columns:++ 1. `exploration_query_result.stored_result_id` — the exploration's own charts (see+ [[metabase.explorations.models.exploration-query-result/stored-results]]).+ 2. `stored_result_use.card_id` — the ephemeral `report_card` behind a static `cardEmbed` in an+ exploration's Summary document, served by `POST /api/card/:card-id/query` with a+ `stored_result_id`. A composite embed combines several source snapshots into a *new* blob that+ no `exploration_query_result` ever points at, so without this arm the sweep would collect the+ Summary's chart out from under it one grace period after it was added.++ `stored_result_use.exploration_id` is bookkeeping rather than reachability, and is deliberately+ *not* consulted: restarting a thread deletes its query rows — and with them the+ `exploration_query_result` rows — while leaving the exploration's use rows behind, so treating one+ as a reason to keep would leak a blob on every restart. A `card_id` use row is different in kind:+ it is the embed's only reference, and it is cascade-deleted with the Card, so it releases the blob+ exactly when the last referent goes. Deleting the blob cascades every use row away."(:require[clojurewerkz.quartzite.jobs :as jobs][clojurewerkz.quartzite.schedule.cron :as cron]@@ -44,8 +52,9 @@500)(defn- orphaned-blob-ids- "Up to [[batch-size]] `stored_result` ids that no `exploration_query_result` references and that are- older than [[grace-period-minutes]]."+ "Up to [[batch-size]] `stored_result` ids that nothing reaches — neither an+ `exploration_query_result` nor a Summary embed's Card — and that are older+ than [[grace-period-minutes]]."[](mapv :id(t2/query@@ -55,6 +64,11 @@[:not [:exists ^:allow-subquery {:select [1]:from [[:exploration_query_result :eqr]]:where [:= :eqr.stored_result_id :sr.id]}]]+ [:not [:exists ^:allow-subquery {:select [1]+ :from [[:stored_result_use :sru]]+ :where [:and+ [:= :sru.stored_result_id :sr.id]+ [:not= :sru.card_id nil]]}]][:< :sr.created_at (t/minus (t/offset-date-time)(t/minutes grace-period-minutes))]]:order-by [[:sr.id :asc]]diff --git a/src/metabase/metabot/tools/resources.clj b/src/metabase/metabot/tools/resources.cljindex 7049489517a..9811aa3aba0 100644--- a/src/metabase/metabot/tools/resources.clj+++ b/src/metabase/metabot/tools/resources.clj@@ -420,34 +420,37 @@(entity-result (present-collection coll))))(defn- fetch-collection-items [id-str query-params]- (let [coll-id (parse-long id-str)- coll (api/read-check :model/Collection coll-id)- cards (->> (t2/select [:model/Card :id :name :type :description :card_schema- :collection_id :database_id :table_id]- {:where [:and [:= :collection_id coll-id] [:= :archived false]]- :order-by [[:%lower.name :asc]]})- (filter mi/can-read?))- dashboards (->> (t2/select [:model/Dashboard :id :name :description :collection_id]- :collection_id coll-id- :archived false- {:order-by [[:%lower.name :asc]]})- (filter mi/can-read?))- documents (->> (t2/select [:model/Document :id :name :collection_id]- :collection_id coll-id- :archived false- {:order-by [[:%lower.name :asc]]})- (filter mi/can-read?))- subcollections (->> (t2/select [:model/Collection :id :name :location :authority_level- :description :personal_owner_id]- :location (str (:location coll) coll-id "/")- :archived false- {:order-by [[:%lower.name :asc]]})- (filter mi/can-read?))- items (concat (map present-collection subcollections)- (map present-card cards)- (map present-dashboard dashboards)- (map present-document documents))]- (list-result :collection-items items query-params)))+ (documents/with-content-gate-cache+ (let [coll-id (parse-long id-str)+ coll (api/read-check :model/Collection coll-id)+ cards (->> (t2/select [:model/Card :id :name :type :description :card_schema+ :collection_id :database_id :table_id]+ {:where [:and [:= :collection_id coll-id] [:= :archived false]]+ :order-by [[:%lower.name :asc]]})+ (filter mi/can-read?))+ dashboards (->> (t2/select [:model/Dashboard :id :name :description :collection_id]+ :collection_id coll-id+ :archived false+ {:order-by [[:%lower.name :asc]]})+ (filter mi/can-read?))+ ;; Exploration Summary documents are only through their exploration — so they stay out of this listing+ documents (->> (t2/select [:model/Document :id :name :collection_id :exploration_id]+ :collection_id coll-id+ :archived false+ :exploration_id nil+ {:order-by [[:%lower.name :asc]]})+ (filter mi/can-read?))+ subcollections (->> (t2/select [:model/Collection :id :name :location :authority_level+ :description :personal_owner_id]+ :location (str (:location coll) coll-id "/")+ :archived false+ {:order-by [[:%lower.name :asc]]})+ (filter mi/can-read?))+ items (concat (map present-collection subcollections)+ (map present-card cards)+ (map present-dashboard dashboards)+ (map present-document documents))]+ (list-result :collection-items items query-params))))(defn- fetch-collection-subcollections [id-str query-params](let [coll-id (parse-long id-str)diff --git a/src/metabase/queries/cached_result.clj b/src/metabase/queries/cached_result.cljindex 8a358bac35d..dc2bfefa63d 100644--- a/src/metabase/queries/cached_result.clj+++ b/src/metabase/queries/cached_result.clj@@ -1,19 +1,35 @@(ns metabase.queries.cached-result- "Read-side permission gating for the `stored_result` snapshot table. The blob was computed+ "Read-side helpers for the `stored_result` snapshot table: permission gating,+ deserialization, in-memory sort, and the Dataset-shaped response. The blob was computedonce by its creator with their effective permissions baked in, so replaying it for anyother viewer must respect *that viewer's* data permissions and their sandboxing /impersonation / database-routing lens — otherwise we'd leak data the QP would have filteredout (or fetched from a different database entirely) if the viewer had executed the query- themselves. The one exemption: superusers may see every snapshot, by product decision."+ themselves. The one exemption: superusers may see every snapshot, by product decision.++ The cached blob is served through `POST /api/card/:card-id/query` when the body carries+ a `stored_result_id` — the cardEmbed node tracks the (card, stored_result) pairing and+ the card-query endpoint reuses this namespace for the cached path so callers go through+ one rendering pipeline whether the data is live or cached."(:require[metabase.api.common :as api][metabase.permissions.core :as perms][metabase.query-permissions.core :as query-perms]+ [metabase.query-processor.result-serialization :as qp.result-serialization]+ [metabase.util :as u][metabase.util.i18n :refer [tru]]- [metabase.util.log :as log]))+ [metabase.util.log :as log])+ (:import+ (java.io ByteArrayInputStream)))(set! *warn-on-reflection* true)+(def allowed-chart-sorts+ "Sort attribute values a cached cardEmbed read is allowed to request. Shared by the+ prompt-builder, the doc validators, and the read-time renderer so the LLM, the doc+ validator, and the renderer agree."+ #{"value_asc" "value_desc" "label_asc" "label_desc"})+(defn- viewer-lens-compatible?"True when the current user's effective data-access lens (sandbox / impersonation / routing) iscompatible with the lens the `stored-result` blob was computed under — i.e. the viewer may be@@ -109,3 +125,74 @@{:status-code 403:reason reason:stored-result-id (:id stored-result)}))))++(defn deserialize-cached-result+ "Pull the QP result map out of a worker-serialized blob produced by+ [[metabase.query-processor.result-serialization/do-with-serialization]]. Returns nil when+ the blob is missing or unreadable. Realizes rows fully — the caller may re-sort them in+ memory."+ [^bytes result-bytes]+ (when result-bytes+ (with-open [is (ByteArrayInputStream. result-bytes)]+ (qp.result-serialization/with-reducible-deserialized-results [[qp-result _] is]+ (when qp-result+ (let [data (:data qp-result)]+ (assoc qp-result :data (assoc data :rows (vec (or (:rows data) []))))))))))++(defn- col-index-by-source+ "Index of the first col whose `:source` matches `source` (`:breakout` or `:aggregation`).+ Falls back to `default-idx` when no col carries that source — pre-MLv2 cached blobs may not+ populate `:source` reliably."+ [cols source default-idx]+ (or (->> cols+ (map-indexed (fn [i c]+ (when (= source (or (:source c) (get c "source"))) i)))+ (some identity))+ default-idx))++(defn apply-sort+ "Re-sort the rows of a deserialized QP result in memory based on `sort` (one of the values+ in [[allowed-chart-sorts]]). The label column is the first `:breakout` col; the value column+ is the first `:aggregation` col. Cached blobs without explicit `:source` fall back to first+ col = label, last col = value. Any throw during sort falls back to the original row order+ with a warning — we never block a read on a sort hiccup."+ [qp-result sort]+ (if (or (nil? sort)+ (not (contains? allowed-chart-sorts sort)))+ qp-result+ (try+ (let [cols (get-in qp-result [:data :cols])+ rows (get-in qp-result [:data :rows])+ label-idx (col-index-by-source cols :breakout 0)+ value-idx (col-index-by-source cols :aggregation (max 0 (dec (count cols))))+ idx (case sort+ ("value_asc" "value_desc") value-idx+ ("label_asc" "label_desc") label-idx)+ cmp (case sort+ ("value_asc" "label_asc") compare+ ("value_desc" "label_desc") u/reverse-compare)+ sorted (vec (sort-by #(nth % idx nil)+ (fn [a b]+ (cond+ (and (nil? a) (nil? b)) 0+ (nil? a) 1+ (nil? b) -1+ :else (cmp a b)))+ rows))]+ (assoc-in qp-result [:data :rows] sorted))+ (catch Throwable e+ (log/warnf e "apply-sort: failed to apply %s; returning unsorted result" (pr-str sort))+ qp-result))))++(defn cached-dataset+ "Build the Dataset response shape (matching the `/api/card/:id/query` live-path output the+ FE already expects) from a stored_result row and an optional `sort` keyword. Returns nil+ when the blob is missing/unreadable so the caller can 404."+ [stored-result sort]+ (when-let [qp-result (deserialize-cached-result (:result_data stored-result))]+ (let [sorted (apply-sort qp-result sort)+ data (:data sorted)]+ {:status "completed"+ :data data+ :database_id (:database_id stored-result)+ :row_count (or (:row_count sorted) (count (:rows data)))})))diff --git a/src/metabase/queries/core.clj b/src/metabase/queries/core.cljindex 4b4d82c2381..9c92891d45e 100644--- a/src/metabase/queries/core.clj+++ b/src/metabase/queries/core.clj@@ -56,8 +56,13 @@query->database-and-table-idssave-queries-and-update-average-execution-times!][metabase.queries.cached-result+ allowed-chart-sortsassert-can-view-cached-result!- viewer-can-view-cached-result?])+ viewer-can-view-cached-result?+ cached-dataset]+ [metabase.queries.models.stored-result-use+ assert-can-view-card-snapshots!+ carry-pairings-for-document!])#_{:clj-kondo/ignore [:missing-docstring]}(p/import-def metabase.queries.models.card/populate-query-fields populate-card-query-fields)diff --git a/src/metabase/queries/models/card.clj b/src/metabase/queries/models/card.cljindex a22fe2966bc..23b5ff15cdb 100644--- a/src/metabase/queries/models/card.clj+++ b/src/metabase/queries/models/card.clj@@ -136,6 +136,58 @@(derive :hook/timestamped?)(derive :hook/entity-id))+(defn- parent-document-id+ "The `document_id` of `card`, or `::not-adjudicable` when the instance carries neither the column+ nor a primary key to resolve it from.++ A narrowed `t2/select` that dropped the column must not read as \"belongs to no document\" — that+ would let a caller widen access just by shortening its column list — so the column is resolved+ from the primary key rather than assumed. The one shape that cannot be resolved is the synthetic+ `{:collection_id …}` stub [[metabase.query-permissions.impl]] builds for source-card permission+ checks: it carries no identity at all. Those decide whether a query may *run*, have never been+ document-aware, and denying them would break every query with a source card — so they keep the+ collection-perms answer they have always had."+ [card]+ (cond+ (contains? card :document_id) (:document_id card)+ (:id card) (t2/select-one-fn :document_id :model/Card :id (:id card))+ :else ::not-adjudicable))++(defn- parent-document-permits?+ "Whether the parent Document of `card`, if it has one, grants `read-or-write` to the current user.++ A Card scoped to a Document is a child of it, and the Document — not the collection — is the+ authority on who may see it. An exploration Summary materializes ephemeral Cards whose `name` and+ `dataset_query` are copied from the `ExplorationQuery` they render, and those embed dimension+ values discovered under the *creator's* data-access lens (see+ [[metabase.explorations.derived-perms]]). Collection permissions alone cannot adjudicate that+ material — withholding it is the entire reason the Document's content gate exists — so a Card+ that carries those values must be gated exactly as the document embedding it is."+ [card read-or-write]+ (let [document-id (parent-document-id card)]+ (if (or (= ::not-adjudicable document-id) (nil? document-id))+ true+ (case read-or-write+ :read (mi/can-read? :model/Document document-id)+ :write (mi/can-write? :model/Document document-id)))))++;; NOTE: deliberately a plain `defmethod` rather than `perms/define-collection-based-visibility!`.+;; That macro's contract is "read perms are determined *fully* by `:collection_id`", which stopped+;; being true for Cards once a Card could be scoped to a Document (see [[parent-document-permits?]]).+;; Its docstring prescribes exactly this: drop the macro call and write the richer method by hand.+;; The collection half still delegates to the same helper the macro installed, so the audit-collection+;; rule it carries is preserved verbatim.+;;+;; Cost: Cards leave semantic search's collection-id-only fast path and take its slow path instead —+;; one batched `t2/select` per result page rather than none. The instances it selects are full rows,+;; so the document check below adds no further queries.+(defmethod mi/can-read? :model/Card+ ([instance]+ (and (perms/can-read-via-parent-collection? (:collection_id instance))+ (parent-document-permits? instance :read)))+ ([_ pk]+ (mi/can-read? (t2/select-one :model/Card :id pk))))+(defmethod mi/can-write? :model/Card([instance];; Cards in audit collection should not be writable.@@ -146,12 +198,11 @@(some? (:id (audit/default-audit-collection)));; Is a direct descendant of audit collection(= (:collection_id instance) (:id (audit/default-audit-collection)))))- (mi/current-user-has-full-permissions? (mi/perms-objects-set instance :write))))+ (mi/current-user-has-full-permissions? (mi/perms-objects-set instance :write))+ (parent-document-permits? instance :write)))([_ pk](mi/can-write? (t2/select-one :model/Card :id pk))))-(perms/define-collection-based-visibility! :model/Card)-(defn model?"Returns true if `card` is a model."[card]@@ -1500,6 +1551,30 @@(for [snippet-id snippets]{["NativeQuerySnippet" snippet-id] {"Card" id}})))))+(def ^:private not-in-exploration-document+ "HoneySQL predicate: this Card does not belong to an exploration Summary document.++ Such a Card is materialized by the Summary itself — its `name` and `dataset_query` are copied+ from the `ExplorationQuery` it renders, so they carry dimension values discovered under the+ creator's data-access lens. Its parent Document is never serialized (see+ `metabase.documents.models.document`'s `extract-query`), and this Card's+ `deserialization-dependencies` name that Document, so exporting the Card without it would leave a+ dangling reference even setting the lens question aside."+ [:or+ [:= :document_id nil]+ [:in :document_id ^:allow-subquery {:select [:id]+ :from [:document]+ :where [:= :exploration_id nil]}]])++(defmethod serdes/extract-query "Card"+ [model-name opts]+ ((get-method serdes/extract-query :default)+ model-name+ (update opts :where (fn [where]+ (if where+ [:and where not-in-exploration-document]+ not-in-exploration-document)))))+(defmethod serdes/serialization-dependencies "Card" [_model-name card](card-deps true card))diff --git a/src/metabase/queries/models/stored_result.clj b/src/metabase/queries/models/stored_result.cljindex 2decf0d0188..bbbc2d82881 100644--- a/src/metabase/queries/models/stored_result.clj+++ b/src/metabase/queries/models/stored_result.clj@@ -1,9 +1,11 @@(ns metabase.queries.models.stored-result"Cached query result snapshots. A `stored_result` row holds the serialized bytes a workerproduced for one execution of a `dataset_query`, plus the bookkeeping the read path needs- (`creator_id`, `database_id`, `dataset_query`) to gate cached-read permissions. Lives in the- queries module because the snapshot is tied to a query/card, not to any one feature that- produced it."+ (`creator_id`, `database_id`, `dataset_query`) to gate cached-read permissions. Many+ `report_card` rows — one per `cardEmbed` in a document — can render against the same+ snapshot; the (card, stored_result) pairing lives on the `cardEmbed` node, not in any DB+ table. Lives in the queries module because the snapshot is tied to a query/card, not to+ any one feature that produced it."(:require[metabase.models.interface :as mi][metabase.permissions.core :as perms]diff --git a/src/metabase/queries/models/stored_result_use.clj b/src/metabase/queries/models/stored_result_use.cljindex a022eea1409..1da9d32baec 100644--- a/src/metabase/queries/models/stored_result_use.clj+++ b/src/metabase/queries/models/stored_result_use.clj@@ -1,8 +1,15 @@(ns metabase.queries.models.stored-result-use- "Tracks references to a `stored_result` snapshot. Each row records the `exploration_id`- (the exploration that produced the snapshot). Used for lifecycle/GC — not for read- authorization. Lives in the queries module alongside `:model/StoredResult`."+ "Tracks references to a `stored_result` snapshot. Each row records one referencing entity:+ exactly one of `card_id` (a document cardEmbed's materialized Card) or `exploration_id`+ (the exploration that produced the snapshot) is set. Used for lifecycle/GC, by+ the cached card-query endpoint to validate that a client-supplied `stored_result_id` is actually+ paired with the card being read-checked, and by [[assert-can-view-card-snapshots!]] to enumerate+ every snapshot a Card renders from. Lives in the queries module alongside `:model/StoredResult`."(:require+ [metabase.queries.cached-result :as cached-result]+ [metabase.util.i18n :refer [tru]]+ [metabase.util.malli :as mu]+ [metabase.util.malli.schema :as ms][methodical.core :as methodical][toucan2.core :as t2]))@@ -14,7 +21,46 @@(t2/define-before-insert :model/StoredResultUse[row]- (when-not (:exploration_id row)- (throw (ex-info "stored_result_use requires :exploration_id to be set"- {:exploration_id (:exploration_id row)})))+ (when (= (some? (:card_id row)) (some? (:exploration_id row)))+ (throw (ex-info "stored_result_use requires exactly one of :card_id or :exploration_id to be set"+ {:card_id (:card_id row) :exploration_id (:exploration_id row)})))row)++(mu/defn carry-pairings-for-document!+ "Copy `(card_id, stored_result_id)` pairings onto newly created Cards for a document save.++ `pairs` is a seq of `[new-card-id stored-result-id]`. A pairing is inserted only when the+ snapshot is already reachable through this same document — i.e. a `stored_result_use` row+ exists for it against some Card whose `document_id` is `document-id`. That keeps the carry+ monotone: it can move an existing (document, snapshot) reachability onto another Card in that+ document, and can never widen a snapshot to a document that could not already read it."+ [document-id :- ms/PositiveInt+ pairs :- [:sequential [:tuple ms/PositiveInt ms/PositiveInt]]]+ (when (seq pairs)+ (let [distinct-pairs (distinct pairs)+ sr-ids (into #{} (map second) distinct-pairs)+ doc-card-ids (t2/select-pks-set :model/Card :document_id document-id)+ reachable (if (seq doc-card-ids)+ (t2/select-fn-set :stored_result_id+ :model/StoredResultUse+ :card_id [:in doc-card-ids]+ :stored_result_id [:in sr-ids])+ #{})]+ (doseq [[new-card-id sr-id] distinct-pairs+ :when (contains? reachable sr-id)]+ (t2/insert! :model/StoredResultUse+ {:stored_result_id sr-id+ :card_id new-card-id})))))++(mu/defn assert-can-view-card-snapshots!+ "Throw a 403 unless the current user may be served *every* `stored_result` Card `card-id` renders+ from."+ [card-id :- ms/PositiveInt]+ (let [snapshots (t2/select :model/StoredResult+ :id [:in ^:allow-subquery {:select [:stored_result_id]+ :from [:stored_result_use]+ :where [:= :card_id card-id]}])]+ (when (empty? snapshots)+ (throw (ex-info (tru "This card has no cached results.") {:status-code 404})))+ (doseq [snapshot snapshots]+ (cached-result/assert-can-view-cached-result! snapshot))))diff --git a/src/metabase/queries_rest/api/card.clj b/src/metabase/queries_rest/api/card.cljindex d299f589c40..b486b41b9bc 100644--- a/src/metabase/queries_rest/api/card.clj+++ b/src/metabase/queries_rest/api/card.clj@@ -900,37 +900,61 @@;; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to;; use our API + we will need it when we make auto-TypeScript-signature generation happen;;+(defn- serve-cached-stored-result+ "Cached branch of the card-query endpoint. Loads the stored_result, runs the cached-read+ perm gate, and returns the cached Dataset shape — same shape as a live query response, so+ the FE doesn't care which path served the data.++ The read-check on the URL card authorizes only snapshots actually materialized for that+ card, so the (card, stored_result) pairing must exist in `stored_result_use` — otherwise+ any readable card would serve as a skeleton key for arbitrary client-supplied snapshot+ ids. 404s (rather than 403s) on an unpaired id so it doesn't confirm the snapshot exists."+ [card-id stored-result-id sort]+ (api/check-exists? :model/StoredResultUse :card_id card-id :stored_result_id stored-result-id)+ (let [sr (api/check-404 (t2/select-one :model/StoredResult :id stored-result-id))]+ (queries/assert-can-view-card-snapshots! card-id)+ (api/check-404 (queries/cached-dataset sr sort))))+#_{:clj-kondo/ignore [:metabase/validate-defendpoint-has-response-schema]}(api.macros/defendpoint :post "/:card-id/query"- "Run the query associated with a Card."+ "Run the query associated with a Card. When `stored_result_id` is supplied, serve the cached snapshot instead of re-running the query+ and optionally re-sorts the rows via the `sort` body param."[{:keys [card-id]} :- [:map[:card-id [:or ms/PositiveInt ms/NanoIdString]]]_query-params- {:keys [parameters ignore_cache dashboard_id collection_preview]}+ {:keys [parameters ignore_cache dashboard_id collection_preview stored_result_id sort]}:- [:map[:ignore_cache {:default false} :boolean][:collection_preview {:optional true} [:maybe :boolean]][:dashboard_id {:optional true} [:maybe ms/PositiveInt]]- [:parameters {:optional true} [:maybe [:sequential ::parameters.schema/parameter-with-value]]]]]+ [:parameters {:optional true} [:maybe [:sequential ::parameters.schema/parameter-with-value]]]+ [:stored_result_id {:optional true} [:maybe ms/PositiveInt]]+ [:sort {:optional true}+ [:maybe [:enum "value_asc" "value_desc" "label_asc" "label_desc"]]]]](let [resolved-card-id (eid-translation/->id-or-404 :card card-id)card (api/check-404 (t2/select-one :model/Card resolved-card-id))]- (when dashboard_id- (api/read-check :model/Dashboard dashboard_id))- (qp.card/process-query-for-card- card :api- :parameters parameters- :ignore-cache ignore_cache- :dashboard-id dashboard_id- :card-transform (cond- ;; Collection previews start from the aggregate so no usable default stays scalar- collection_preview (comp qp.dashboard/card-with-default-metric-dimension- metric-card-without-query-breakouts)- dashboard_id qp.dashboard/card-with-default-metric-dimension)- :context (cond- collection_preview :collection- dashboard_id :dashboard- :else :question)- :middleware {:process-viz-settings? false})))+ (if stored_result_id+ (do+ (api/read-check card)+ (serve-cached-stored-result resolved-card-id stored_result_id sort))+ (do+ (when dashboard_id+ (api/read-check :model/Dashboard dashboard_id))+ (qp.card/process-query-for-card+ card :api+ :parameters parameters+ :ignore-cache ignore_cache+ :dashboard-id dashboard_id+ :card-transform (cond+ ;; Collection previews start from the aggregate so no usable default stays scalar+ collection_preview (comp qp.dashboard/card-with-default-metric-dimension+ metric-card-without-query-breakouts)+ dashboard_id qp.dashboard/card-with-default-metric-dimension)+ :context (cond+ collection_preview :collection+ dashboard_id :dashboard+ :else :question)+ :middleware {:process-viz-settings? false})))));; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to;; use our API + we will need it when we make auto-TypeScript-signature generation happendiff --git a/src/metabase/search/filter.clj b/src/metabase/search/filter.cljindex 1a4a3c2285f..f36f0645d1f 100644--- a/src/metabase/search/filter.clj+++ b/src/metabase/search/filter.clj@@ -204,11 +204,15 @@;; NOTE: we limit id-based search to only a subset of the models;; TODO this should just become part of the model spec e.g. :search-by-id?[:in :search_index.model ["card" "dataset" "metric" "dashboard" "action"]]]]])- [[:dashboard-questions [:or- ;; leverage the fact that only card-related models populate this attribute- [:= nil :search_index.dashboard_id]- (when (:include-dashboard-questions? search-context)- [:not= [:inline 0] [:coalesce :search_index.dashboardcard_count [:inline 0]]])]]]+ [[:dashboard-questions [:and+ [:or+ ;; leverage the fact that only card-related models populate this attribute+ [:= nil :search_index.dashboard_id]+ (when (:include-dashboard-questions? search-context)+ [:not= [:inline 0] [:coalesce :search_index.dashboardcard_count [:inline 0]]])]+ ;; documents with an exploration id are similar to a Dashboard Question - they aren't+ ;; searchable outside of their owning Exploration.+ [:= nil :search_index.exploration_id]]]](for [{t :type :keys [context-key required-feature supported-value? field]}(vals (dissoc search.config/filters :id :native-query)):let [v (get search-context context-key)]]diff --git a/src/metabase/search/impl.clj b/src/metabase/search/impl.cljindex b976aa2b3fd..46f4b4da93b 100644--- a/src/metabase/search/impl.clj+++ b/src/metabase/search/impl.clj@@ -219,6 +219,7 @@:all-scores:dataset_query:document+ :document_id:relevant-scores:collection_effective_ancestors:collection_id@@ -424,7 +425,13 @@(update :archived bit->boolean)(update :archived_directly bit->boolean);; Collections require some transformation before being scored and returned by search.- (cond-> (t2/instance-of? :model/Collection instance) map-collection))))+ (cond-> (t2/instance-of? :model/Collection instance) map-collection)+ ;; The Card search spec filters `[:= :this.document_id nil]`, so nothing Document-scoped is+ ;; ever indexed and every Card result is known not to belong to one. Say so on the instance:+ ;; the permission checks below consult `document_id` (a Document-scoped Card is gated by its+ ;; Document), and an instance that merely *omits* it makes that resolve one from the primary+ ;; key instead — one extra query per result row.+ (cond-> (t2/instance-of? :model/Card instance) (assoc :document_id nil)))))(defn check-result-permissions"Run the post-query permission check on a single raw engine result map (the rehydrated shape an engine'sdiff --git a/src/metabase/search/in_place/legacy.clj b/src/metabase/search/in_place/legacy.cljindex 52d9088a21c..d967e19509a 100644--- a/src/metabase/search/in_place/legacy.clj+++ b/src/metabase/search/in_place/legacy.clj@@ -604,6 +604,8 @@[:and[:= :bookmark.document_id :document.id][:= :bookmark.user_id (:current-user-id search-ctx)]])+ ;; documents in Explorations are never searchable+ (sql.helpers/where [:= nil :document.exploration_id])(add-collection-join-and-where-clauses model search-ctx)))(defmethod search-query-for-model "exploration"diff --git a/src/metabase/search/spec.clj b/src/metabase/search/spec.cljindex 6060688c1b9..cf6aadad63d 100644--- a/src/metabase/search/spec.clj+++ b/src/metabase/search/spec.clj@@ -90,7 +90,7 @@;; `:document` is the document model's prose-mirror body: it's indexed as searchable text (via;; ast->text) but the raw JSON should never be echoed back in the search response or bloat the index row.;; `:data_layer` also stays IN: Metabot surfaces it on table results so the LLM sees a table's data layer.- #{:pinned :view_count :last_viewed_at :native_query :dataset_query :document})+ #{:pinned :view_count :last_viewed_at :native_query :dataset_query :document :exploration_id})(def attr-types"The abstract types of each attribute."@@ -101,6 +101,7 @@:dashboard-id :int:dashboardcard-count :int:database-id :pk+ :exploration-id :int:id :text:last-edited-at :timestamp:last-editor-id :pk@@ -139,6 +140,7 @@:official-collection:dashboard-id:dashboardcard-count+ :exploration-id:last-viewed-at:pinned:verified ;; in addition to being a filter, this is also a rankerdiff --git a/test/metabase/cmd/dump_to_h2_test.clj b/test/metabase/cmd/dump_to_h2_test.cljindex 4754adb23e0..50e22a65d34 100644--- a/test/metabase/cmd/dump_to_h2_test.clj+++ b/test/metabase/cmd/dump_to_h2_test.clj@@ -42,8 +42,8 @@(is (false? (.exists (io/file filename))))))))))(deftest cmd-dump-to-h2-returns-code-from-dump-test- (with-redefs [dump-to-h2/dump-to-h2! #(throw (Exception. "err"))- cmd/system-exit! identity]+ (mt/with-dynamic-fn-redefs [dump-to-h2/dump-to-h2! #(throw (Exception. "err"))+ cmd/system-exit! identity](is (= 1 (cmd/dump-to-h2 "file1")))))(defn persistent-data-sourcediff --git a/test/metabase/cmd/rotate_encryption_key_test.clj b/test/metabase/cmd/rotate_encryption_key_test.cljindex 1d8ab4818c8..488c09ea77d 100644--- a/test/metabase/cmd/rotate_encryption_key_test.clj+++ b/test/metabase/cmd/rotate_encryption_key_test.clj@@ -36,8 +36,8 @@"select value from setting where setting.key=?;") keyy]))))(deftest cmd-rotate-encryption-key-errors-when-failed-test- (with-redefs [rotate-encryption-key! #(throw (Exception. "err"))- cmd/system-exit! identity]+ (mt/with-dynamic-fn-redefs [rotate-encryption-key! #(throw (Exception. "err"))+ cmd/system-exit! identity](is (= 1 (cmd/rotate-encryption-key"89ulvIGoiYw6mNELuOoEZphQafnF/zYe+3vT+v70D1A=")))))diff --git a/test/metabase/collections/models/collection_test.clj b/test/metabase/collections/models/collection_test.cljindex c5b71f8fe91..35d8f369606 100644--- a/test/metabase/collections/models/collection_test.clj+++ b/test/metabase/collections/models/collection_test.clj@@ -11,6 +11,7 @@[metabase.api.common :as api][metabase.audit-app.impl :as audit][metabase.collections.models.collection :as collection]+ [metabase.config.core :as config][metabase.models.interface :as mi][metabase.models.serialization :as serdes][metabase.permissions.core :as perms]@@ -3018,6 +3019,49 @@(is (contains? descendants-without-skip ["Card" (:id archived-card)]))(is (contains? descendants-without-skip ["Dashboard" (:id archived-dash)])))))))+(deftest serdes-descendants-excludes-exploration-documents-test+ (testing "Documents tied to an exploration are not included in Collection descendants (UXW-4091)"+ (mt/with-temp [:model/Collection coll {:name "Coll"}+ :model/User user {:email "[email protected]"}+ :model/Exploration explo {:name "Explo" :creator_id (:id user)}+ :model/Document plain-doc {:name "Plain Doc"+ :creator_id (:id user)+ :collection_id (:id coll)}+ :model/Document explo-doc {:name "Exploration Doc"+ :creator_id (:id user)+ :collection_id (:id coll)+ :exploration_id (:id explo)}]+ (when config/ee-available?+ (let [descendants (serdes/descendants "Collection" (:id coll) {:skip-archived true})]+ (is (contains? descendants ["Document" (:id plain-doc)])+ "plain documents should be included")+ (is (not (contains? descendants ["Document" (:id explo-doc)]))+ "exploration documents should be excluded"))))))++(deftest serdes-descendants-excludes-exploration-summary-cards-test+ (testing "Cards belonging to an exploration Summary document are not Collection descendants"+ (mt/with-temp [:model/Collection coll {:name "Coll"}+ :model/User user {:email "[email protected]"}+ :model/Exploration explo {:name "Explo" :creator_id (:id user)}+ :model/Document plain-doc {:name "Plain Doc" :creator_id (:id user)+ :collection_id (:id coll)}+ :model/Document explo-doc {:name "Exploration Doc"+ :creator_id (:id user)+ :collection_id (:id coll)+ :exploration_id (:id explo)}+ :model/Card plain-card {:collection_id (:id coll)}+ :model/Card doc-card {:collection_id (:id coll) :document_id (:id plain-doc)}+ :model/Card explo-card {:collection_id (:id coll) :document_id (:id explo-doc)}]+ (when config/ee-available?+ (let [descendants (serdes/descendants "Collection" (:id coll) {:skip-archived true})]+ (is (contains? descendants ["Card" (:id plain-card)])+ "ordinary cards are included")+ (is (contains? descendants ["Card" (:id doc-card)])+ "a card in an ordinary document is included, since that document is exported too")+ (is (not (contains? descendants ["Card" (:id explo-card)]))+ "a card in an exploration Summary is excluded — otherwise it is exported while the+ Document it depends on is not, leaving a dangling reference"))))))+(deftest serdes-extract-query-skip-archived-test(testing "Collection extract-query with skip-archived: true filters archived collections"(mt/with-temp [:model/Collection active-coll {:name "Active Collection" :archived false}diff --git a/test/metabase/collections_rest/api_test.clj b/test/metabase/collections_rest/api_test.cljindex 875bd37650c..89413edc639 100644--- a/test/metabase/collections_rest/api_test.clj+++ b/test/metabase/collections_rest/api_test.clj@@ -795,6 +795,35 @@(:data (mt/user-http-request :crowberto :get 200(str "collection/" (u/the-id collection) "/items"))))))))))+(deftest collection-items-card-permission-checks-do-not-scale-with-card-count-test+ (testing "listing a collection's cards issues no per-card query (#78848)"+ ;; `:can_write` hydration runs `mi/can-write?` on every row, which since Cards became+ ;; Document-scopable has to know each Card's `document_id`. If the listing query does not+ ;; select that column, `parent-document-id` resolves it from the primary key instead — one+ ;; extra `SELECT` per Card. Compare two collection sizes rather than asserting a fixed budget,+ ;; so the test pins the *shape* (constant) and not an incidental number.+ (let [items! (fn [coll-id]+ (mt/user-http-request :crowberto :get 200 (str "collection/" coll-id "/items")+ :models "card"))+ call-count (fn [n]+ (mt/with-temp [:model/Collection {coll-id :id} {}]+ (doseq [i (range n)]+ (t2/insert! :model/Card+ {:name (str "n1q card " i)+ :type :question+ :creator_id (mt/user->id :crowberto)+ :collection_id coll-id+ :database_id (mt/id)+ :dataset_query (mt/mbql-query venues)+ :display "table"+ :visualization_settings {}}))+ ;; warm any lazily-initialized caches the first request would otherwise pay for+ (items! coll-id)+ (t2/with-call-count [cc]+ (items! coll-id)+ (cc))))]+ (is (= (call-count 2) (call-count 6))))))+(deftest collection-items-based-on-upload-test(testing "GET /api/collection/:id/items"(testing "check that based_on_upload is returned for cards correctly"@@ -3914,4 +3943,40 @@(str "collection/" (:id coll) "/items")))(:id e))](is (some? item))- (is (nil? (:last-edit-info item))))))))+ (is (nil? (:last-edit-info item))))))+ (testing "Document attached to an exploration bumps the exploration's last-edit-info"+ (mt/with-temp [:model/Collection coll {}+ :model/Exploration e {:name "DocBumped"+ :creator_id (mt/user->id :crowberto)+ :collection_id (:id coll)}+ :model/Document doc {:name "notes"+ :collection_id (:id coll)+ :creator_id (mt/user->id :crowberto)+ :exploration_id (:id e)+ :document {:type "doc" :content []}}]+ ;; Older Exploration revision by :crowberto, newer Document revision by :rasta.+ ;; Insert directly so we control timestamps — within a `with-temp` transaction+ ;; the DB-side NOW() is frozen, so the standard push-revision! path would emit+ ;; identical timestamps and tiebreak non-deterministically.+ (let [t (java.time.OffsetDateTime/now)]+ (t2/insert! :model/Revision+ {:model "Exploration"+ :model_id (:id e)+ :user_id (mt/user->id :crowberto)+ :object (revision/serialize-instance :model/Exploration (:id e)+ (t2/select-one :model/Exploration :id (:id e)))+ :timestamp (.minusSeconds t 60)+ :is_creation true})+ (t2/insert! :model/Revision+ {:model "Document"+ :model_id (:id doc)+ :user_id (mt/user->id :rasta)+ :object (revision/serialize-instance :model/Document (:id doc)+ (t2/select-one :model/Document :id (:id doc)))+ :timestamp t}))+ (let [item (find-exploration (:data (mt/user-http-request :crowberto :get 200+ (str "collection/" (:id coll) "/items")))+ (:id e))]+ (is (some? item))+ (is (= (mt/user->id :rasta)+ (-> item :last-edit-info :id))))))))diff --git a/test/metabase/comments/api_test.clj b/test/metabase/comments/api_test.cljindex d4a6d6854ef..a416e1aef1c 100644--- a/test/metabase/comments/api_test.clj+++ b/test/metabase/comments/api_test.clj@@ -537,3 +537,63 @@(is (= "Not found."(mt/user-http-request :rasta :get 404 "comment/mentions"{:request-options {:headers {"x-metabase-client" "embedding-iframe"}}})))))))++(deftest comment-context-is-a-closed-set-of-identity-keys-test+ (testing "POST /api/comment/ context"+ (mt/with-temp [:model/Document {doc-id :id} {}]+ (let [content (tiptap [:p "hi"])+ post! (fn [status context]+ (mt/user-http-request :rasta :post status "comment/"+ {:target_type "document"+ :target_id doc-id+ :content content+ :context context}))]+ (testing "accepts the keys the product actually stores"+ (is (=? {:context {:timeline_id 1}} (post! 200 {:timeline_id 1})))+ (is (=? {:context {:exploration_query_ids [7]}}+ (post! 200 {:exploration_query_ids [7]})))+ (is (=? {:context {:highlighted {:columnName "CATEGORY"}}}+ (post! 200 {:highlighted {:columnName "CATEGORY"+ :dimensions [{:columnName "CATEGORY" :value "Gadget"}]}}))))+ ;; The closed schema makes `defendpoint` strip undeclared keys during decoding rather than+ ;; 400 — which is the safer of the two: the value cannot reach the row, and a client that+ ;; still sends one is not broken by the change.+ (testing "drops unknown keys, so the blob cannot quietly accrete new values"+ (let [created (post! 200 {:some_future_key "anything"})]+ (is (= {} (t2/select-one-fn :context :model/Comment :id (:id created))))))))))++(deftest comment-highlight-label-is-stored-as-the-client-formatted-it-test+ (testing "the label for a commented-on data point"+ (mt/with-temp [:model/Document {doc-id :id} {}]+ (let [highlighted {:columnName "TOTAL"+ :dimensions [{:columnName "TOTAL" :value 0}+ {:columnName "REGION" :value "EU"}]}+ post! (fn [context]+ (mt/user-http-request :rasta :post 200 "comment/"+ {:target_type "document"+ :target_id doc-id+ :content (tiptap [:p "hi"])+ :context context}))+ fetch (fn [comment-id]+ (->> (mt/user-http-request :rasta :get 200 "comment/"+ :target_type "document"+ :target_id doc-id)+ :comments+ (filter #(= comment-id (:id %)))+ first))]+ (testing "is stored as sent and round-trips verbatim — only the client knows the column+ formatting (binning, currency, date granularity) the point was rendered with, so a+ label rebuilt from the raw dimension values on read would not match the chart"+ (let [created (post! {:highlighted highlighted+ :highlight_label "$0 – $10, EU"})]+ (is (= "$0 – $10, EU" (get-in created [:context :highlight_label])))+ (is (= "$0 – $10, EU" (get-in (fetch (:id created)) [:context :highlight_label])))+ (is (= {:highlighted highlighted :highlight_label "$0 – $10, EU"}+ (t2/select-one-fn :context :model/Comment :id (:id created))))))+ (testing "is absent when the comment is not anchored to a data point"+ (let [plain (post! {:timeline_id 1})]+ (is (nil? (get-in plain [:context :highlight_label])))+ (is (nil? (get-in (fetch (:id plain)) [:context :highlight_label])))))+ (testing "is not derived on read for a comment that carries none"+ (let [created (post! {:highlighted highlighted})]+ (is (nil? (get-in (fetch (:id created)) [:context :highlight_label])))))))))diff --git a/test/metabase/comments/models/comment_test.clj b/test/metabase/comments/models/comment_test.cljindex 0bc0240ecc4..b645f4cca17 100644--- a/test/metabase/comments/models/comment_test.clj+++ b/test/metabase/comments/models/comment_test.clj@@ -6,21 +6,21 @@[toucan2.core :as t2]))(deftest exploration-comment-url-test- (testing "exploration comment URLs deep-link to the comment's page, with context as query params"+ (testing "integer child_target_id deep-links to the comment's page, with context as query params"(let [exploration (t2/instance :model/Exploration {:id 7})comment {:id 42:child_target_id "123":context {:timeline_id 3}}](is (= (str "/question/research/7/page/123"- "?comments=true&timeline=3#comment-42")+ "?comments=123&timeline=3#comment-42")(comment/url exploration comment)))))- (testing "context keys that are not deep-linked are omitted from the URL"+ (testing "uuid child_target_id deep-links to the Summary with the node id in comments"(let [exploration (t2/instance :model/Exploration {:id 7})comment {:id 42- :child_target_id "group-1"+ :child_target_id "550e8400-e29b-41d4-a716-446655440000":context {:timeline_id 3 :scroll_y 120}}]- (is (= (str "/question/research/7/page/group-1"- "?comments=true&timeline=3#comment-42")+ (is (= (str "/question/research/7/summary"+ "?comments=550e8400-e29b-41d4-a716-446655440000&timeline=3#comment-42")(comment/url exploration comment))))))(deftest comment-testdiff --git a/test/metabase/documents/api/collection_test.clj b/test/metabase/documents/api/collection_test.cljindex bd645354e3b..42eee7555d3 100644--- a/test/metabase/documents/api/collection_test.clj+++ b/test/metabase/documents/api/collection_test.clj@@ -112,6 +112,52 @@(testing "Non-archived documents do not appear in trash"(is (not (some #(= normal-doc-id (:id %)) trash-test-items)))))))))+(deftest archived-exploration-documents-appear-in-trash-with-flag+ (testing "Exploration documents are hidden from collection listings by default,"+ (testing "but appear in the Trash when show_exploration_documents=true (mirrors dashboard-questions behavior)."+ (mt/with-temp [:model/Exploration {expl-id :id} {:creator_id (mt/user->id :rasta)+ :name "Test Exploration"}+ :model/Document {expl-doc-id :id} {:collection_id nil+ :name "Trashed Exploration Doc"+ :exploration_id expl-id+ :archived true+ :archived_directly true}]+ (let [trash-id (collection/trash-collection-id)]+ (testing "Without the flag, the trashed exploration document is hidden"+ (let [items (mt/user-http-request :rasta :get 200+ (format "collection/%d/items" trash-id))]+ (is (not (some #(= expl-doc-id (:id %)) (:data items))))))+ (testing "With show_exploration_documents=true, it appears with restore/delete affordances"+ (let [items (mt/user-http-request :rasta :get 200+ (format "collection/%d/items?show_exploration_documents=true" trash-id))+ hit (first (filter #(= expl-doc-id (:id %)) (:data items)))]+ (is (some? hit))+ (is (= "document" (:model hit)))+ (is (true? (:can_restore hit)))+ (is (true? (:can_delete hit))))))))))++(deftest exploration-documents-stay-hidden-in-collections+ (testing "Non-archived exploration documents are hidden from a regular collection's items by default"+ (mt/with-temp [:model/Collection {coll-id :id} {}+ :model/Exploration {expl-id :id} {:creator_id (mt/user->id :rasta)+ :name "Coll Exploration"}+ :model/Document {plain-doc-id :id} {:collection_id coll-id+ :name "Plain Doc"}+ :model/Document {expl-doc-id :id} {:collection_id coll-id+ :name "Exploration Doc"+ :exploration_id expl-id}]+ (testing "Without the flag, only the plain document is listed"+ (let [items (mt/user-http-request :rasta :get 200 (format "collection/%d/items" coll-id))+ ids (set (map :id (:data items)))]+ (is (contains? ids plain-doc-id))+ (is (not (contains? ids expl-doc-id)))))+ (testing "With show_exploration_documents=true, both are listed"+ (let [items (mt/user-http-request :rasta :get 200+ (format "collection/%d/items?show_exploration_documents=true" coll-id))+ ids (set (map :id (:data items)))]+ (is (contains? ids plain-doc-id))+ (is (contains? ids expl-doc-id)))))))+(deftest document-pinning-collection-items(testing "GET /api/collection/:id/items supports pinned_state parameter for documents"(mt/with-temp [:model/Collection {coll-id :id} {}diff --git a/test/metabase/documents/api/document_test.clj b/test/metabase/documents/api/document_test.cljindex be53e876906..b73bb9bf3c6 100644--- a/test/metabase/documents/api/document_test.clj+++ b/test/metabase/documents/api/document_test.clj@@ -8,6 +8,8 @@[metabase.documents.prose-mirror :as prose-mirror][metabase.documents.test-util :as documents.test-util][metabase.events.core :as events]+ [metabase.lib.core :as lib]+ [metabase.lib.metadata :as lib.metadata][metabase.permissions.core :as perms][metabase.permissions.models.data-permissions :as data-perms][metabase.test :as mt]@@ -518,6 +520,32 @@(is (= "Updated Document with Generated Cards" (:name document)))(is (= col-id (:collection_id document)))))))))+(deftest put-document-adhoc-card-without-stored-result-inserts-no-pairings-test+ (testing "PUT /api/document/:id creating an ad-hoc card with no stored_result_id inserts no stored_result_use rows"+ (mt/with-temp [:model/Collection {col-id :id} {}+ :model/Document {document-id :id} {:name "Test Document"+ :document (documents.test-util/text->prose-mirror-ast "Initial Doc")+ :collection_id col-id}]+ (let [before (t2/count :model/StoredResultUse)+ result (mt/user-http-request :crowberto+ :put 200 (format "document/%s" document-id)+ {:name "Updated"+ :document {:type "doc"+ :content [{:type "cardEmbed"+ :attrs {:id -10}}]}+ :cards {-10 {:name "Ad hoc Card"+ ;; Lib, not the deprecated `mt/mbql-query`+ :dataset_query (lib/->legacy-MBQL+ (let [mp (mt/metadata-provider)]+ (lib/query mp (lib.metadata/table mp (mt/id :venues)))))+ :display :table+ :visualization_settings {}}}})+ new-card-id (-> result :document :content first :attrs :id)]+ (is (pos-int? new-card-id))+ (is (= before (t2/count :model/StoredResultUse))+ "no stored_result_use rows are created for a live ad-hoc embed")+ (is (zero? (t2/count :model/StoredResultUse :card_id new-card-id)))))))+(deftest cards-to-create-schema-validation-test(testing "POST /api/document/ - cards schema validation"(mt/with-model-cleanup [:model/Document]@@ -2520,3 +2548,25 @@{:name "Should Fail":document (documents.test-util/text->prose-mirror-ast "Should not be created"):collection_id personal-coll-id}))))))++(deftest document-list-excludes-exploration-documents-test+ (testing "GET /api/document excludes documents attached to an exploration"+ (mt/with-temp [:model/Collection {coll-id :id} {:name "Doc List Collection"}+ :model/Exploration {expl-id :id} {:name "List Exclusion Expl"+ :creator_id (mt/user->id :crowberto)+ :collection_id coll-id}+ :model/Document _ {:name "Standalone Doc"+ :document (documents.test-util/text->prose-mirror-ast "standalone")+ :collection_id coll-id}+ :model/Document _ {:name "Exploration Summary"+ :document (documents.test-util/text->prose-mirror-ast "attached")+ :collection_id coll-id+ :exploration_id expl-id}]+ (let [doc-names (->> (mt/user-http-request :crowberto :get 200 "document/")+ :items+ (map :name)+ set)]+ (testing "standalone documents are listed"+ (is (contains? doc-names "Standalone Doc")))+ (testing "exploration-attached documents are not (matching search / recents / collection items)"+ (is (not (contains? doc-names "Exploration Summary"))))))))diff --git a/test/metabase/documents/models/document_test.clj b/test/metabase/documents/models/document_test.cljindex 5087f2c738a..85060efbb07 100644--- a/test/metabase/documents/models/document_test.clj+++ b/test/metabase/documents/models/document_test.clj@@ -432,7 +432,7 @@(let [spec (serdes/make-spec "Document" {})](is (= [:archived :archived_directly :content_type :entity_id :name :collection_position](:copy spec)))- (is (= [:view_count :last_viewed_at :public_uuid :public_uuid_prefix :made_public_by_id] (:skip spec)))+ (is (= [:view_count :last_viewed_at :public_uuid :public_uuid_prefix :made_public_by_id :exploration_id :is_placeholder] (:skip spec)))(is (contains? (:transform spec) :created_at))(is (contains? (:transform spec) :document))(is (contains? (:transform spec) :updated_at))@@ -805,3 +805,89 @@(binding [mi/*deserializing?* true](t2/update! :model/Document doc-id {:name "Deserialized Name"}))(is (empty? @events-published))))))))++(defn- export-document-ast+ "Run a document row through the serdes `:document` export transform and return the exported AST."+ [document]+ ((get-in (serdes/make-spec "Document" {}) [:transform :document :export-with-context])+ document :document nil))++(deftest document-serdes-static-card-embed-test+ (testing "A static (snapshot-backed) cardEmbed"+ (mt/with-temp [:model/Collection {coll-id :id} {}+ :model/Card {card-id :id} {:collection_id coll-id}]+ (let [node (-> {:content_type "application/json+vnd.prose-mirror"+ :document {:type "doc"+ :content [{:type "cardEmbed"+ :attrs {:id card-id+ :stored_result_id 987654321}}]}}+ export-document-ast+ :content+ first)]+ (testing "still rewrites its Card :id to a portable serdes path — the ephemeral Card is a real serdes entity"+ (is (vector? (-> node :attrs :id)))+ (is (= "Card" (-> node :attrs :id first :model))))+ (testing "drops :stored_result_id — a raw local id for a row that is not a serdes entity, which would resolve to an unrelated snapshot on import"+ (is (not (contains? (:attrs node) :stored_result_id))))))))++(deftest document-serdes-live-card-embed-keeps-attrs-test+ (testing "A live cardEmbed exports its :id as a portable path and is otherwise untouched"+ (mt/with-temp [:model/Collection {coll-id :id} {}+ :model/Card {card-id :id} {:collection_id coll-id}]+ (let [node (-> {:content_type "application/json+vnd.prose-mirror"+ :document {:type "doc"+ :content [{:type "cardEmbed"+ :attrs {:id card-id :_id "abc"}}]}}+ export-document-ast+ :content+ first)]+ (is (= "Card" (-> node :attrs :id first :model)))+ (is (= "abc" (-> node :attrs :_id)))))))++(deftest serdes-extract-query-excludes-exploration-documents-test+ (testing "serdes never extracts an exploration Summary document"+ (mt/with-temp [:model/Collection {coll-id :id} {}+ :model/User {user-id :id} {:email "[email protected]"}+ :model/Exploration {expl-id :id} {:name "Explo" :creator_id user-id}+ :model/Document {plain-id :id} {:name "Plain" :creator_id user-id+ :collection_id coll-id}+ :model/Document {summary-id :id} {:name "Summary"+ :creator_id user-id+ :collection_id coll-id+ :exploration_id expl-id}]+ (let [eid #(t2/select-one-fn :entity_id :model/Document :id %)+ ;; A caller-supplied `:where` must still compose — this is also the shape a full+ ;; (untargeted) export takes, where the Collection descendants filter never runs.+ extracted (into #{}+ (map :entity_id)+ (serdes/extract-all "Document" {:where [:in :id [plain-id summary-id]]}))]+ (is (contains? extracted (eid plain-id))+ "an ordinary document is still exported")+ (is (not (contains? extracted (eid summary-id)))+ "a Summary document is never exported — it is not first-class content, and its body embeds+ values computed under its creator's data-access lens")))))++(defn- import-document-ast+ "Run an exported AST back through the serdes `:document` import transform."+ [document]+ ((get-in (serdes/make-spec "Document" {}) [:transform :document :import-with-context])+ document :document nil))++(deftest document-serdes-card-embed-round-trips-test+ (testing "a cardEmbed's Card id survives export and comes back on import"+ (mt/with-temp [:model/Collection {coll-id :id} {}+ :model/Card {card-id :id} {:collection_id coll-id}]+ (let [exported (export-document-ast+ {:content_type "application/json+vnd.prose-mirror"+ :document {:type "doc"+ :content [{:type "cardEmbed"+ :attrs {:id card-id}}]}})+ imported (import-document-ast+ {:content_type "application/json+vnd.prose-mirror"+ :document exported})]+ (testing "export rewrites the id to a portable path"+ (is (vector? (-> exported :content first :attrs :id))))+ (testing "import rewrites it back to this instance's Card id — on the serialized form the id+ is a serdes path, so any guard that expects a raw integer skips the node and leaves+ the path in place"+ (is (= card-id (-> imported :content first :attrs :id))))))))diff --git a/test/metabase/documents/prose_mirror_test.clj b/test/metabase/documents/prose_mirror_test.cljindex 829ee495fb3..27714cb39d2 100644--- a/test/metabase/documents/prose_mirror_test.clj+++ b/test/metabase/documents/prose_mirror_test.clj@@ -350,24 +350,43 @@:content [{:type "paragraph" :content [{:type "text" :text "one"}]}{:type "paragraph" :content [{:type "text" :text "two"}]}]}:content_type prose-mirror/prose-mirror-content-type}- embed {:type "resizeNode"- :content [{:type prose-mirror/card-embed-type :attrs {:id 42}}]}]+ embed-attrs (fn [node] (-> node :content first :attrs))](testing "a nil index appends the embed at the end"(let [result (prose-mirror/insert-card-embed doc 42 nil)](is (= 3 (count (get-in result [:document :content]))))- (is (= embed (get-in result [:document :content 2])))))+ (is (= "resizeNode" (get-in result [:document :content 2 :type])))+ (is (= 42 (:id (embed-attrs (get-in result [:document :content 2])))))+ (is (uuid? (:_id (embed-attrs (get-in result [:document :content 2])))))))(testing "an index inserts before the block currently at that index"(let [result (prose-mirror/insert-card-embed doc 42 1)]- (is (= embed (get-in result [:document :content 1])))+ (is (= 42 (:id (embed-attrs (get-in result [:document :content 1])))))(is (= "two" (get-in result [:document :content 2 :content 0 :text])))))(testing "index 0 inserts at the very top"- (is (= embed (-> (prose-mirror/insert-card-embed doc 42 0)- (get-in [:document :content 0])))))+ (is (= 42 (-> (prose-mirror/insert-card-embed doc 42 0)+ (get-in [:document :content 0])+ embed-attrs+ :id))))(testing "out-of-range indexes are clamped"- (is (= embed (-> (prose-mirror/insert-card-embed doc 42 99)- (get-in [:document :content 2]))))- (is (= embed (-> (prose-mirror/insert-card-embed doc 42 -5)- (get-in [:document :content 0])))))))+ (is (= 42 (-> (prose-mirror/insert-card-embed doc 42 99)+ (get-in [:document :content 2])+ embed-attrs+ :id)))+ (is (= 42 (-> (prose-mirror/insert-card-embed doc 42 -5)+ (get-in [:document :content 0])+ embed-attrs+ :id))))+ (testing "extra-attrs are merged onto the cardEmbed"+ (let [result (prose-mirror/insert-card-embed doc 42 nil {:stored_result_id 9+ :chart_href "/x"+ :child_target_id "3"+ :host_data {:query_ids [101 102]}})+ attrs (embed-attrs (get-in result [:document :content 2]))]+ (is (= 42 (:id attrs)))+ (is (= 9 (:stored_result_id attrs)))+ (is (= "/x" (:chart_href attrs)))+ (is (= "3" (:child_target_id attrs)))+ (is (= {:query_ids [101 102]} (:host_data attrs)))+ (is (uuid? (:_id attrs)))))))(deftest ^:parallel insert-card-embed-empty-document-test(testing "inserting into an empty or nil ast produces a doc with just the embed"@@ -375,11 +394,13 @@(let [result (prose-mirror/insert-card-embed{:document document:content_type prose-mirror/prose-mirror-content-type}- 7 nil)]- (is (= {:type "doc"- :content [{:type "resizeNode"- :content [{:type prose-mirror/card-embed-type :attrs {:id 7}}]}]}- (:document result)))))))+ 7 nil)+ attrs (-> result :document :content first :content first :attrs)]+ (is (= "doc" (get-in result [:document :type])))+ (is (= 1 (count (get-in result [:document :content]))))+ (is (= "resizeNode" (get-in result [:document :content 0 :type])))+ (is (= 7 (:id attrs)))+ (is (uuid? (:_id attrs)))))))(deftest ^:parallel insert-card-embed-invalid-content-type-test(testing "throws for non-prose-mirror documents"diff --git a/test/metabase/documents/recent_views_test.clj b/test/metabase/documents/recent_views_test.cljindex 023243d664d..43483ddc774 100644--- a/test/metabase/documents/recent_views_test.clj+++ b/test/metabase/documents/recent_views_test.clj@@ -163,3 +163,25 @@(= (:name %) "Test Document"))(:recents response))"Document should be present in recents when premium feature is enabled"))))))++(deftest recents-api-excludes-exploration-documents-test+ (testing "/recents API hides documents attached to an exploration"+ (mt/with-temp [:model/Collection {coll-id :id} {:name "Test Collection"}+ :model/Exploration {expl-id :id} {:name "Expl"+ :creator_id (mt/user->id :rasta)}+ :model/Document {plain-id :id} {:name "Plain Document"+ :collection_id coll-id+ :archived false}+ :model/Document {expl-doc :id} {:name "Exploration Document"+ :collection_id coll-id+ :exploration_id expl-id+ :archived false}]+ ;; Bypass the write-time filter to simulate historical rows already present in recent_views.+ (activity-feed/update-users-recent-views! (mt/user->id :rasta) :model/Document plain-id :view)+ (activity-feed/update-users-recent-views! (mt/user->id :rasta) :model/Document expl-doc :view)+ (let [recents (:recents (mt/user-http-request :rasta :get 200 "activity/recents" :context [:views]))+ ids (set (map :id (filter #(= (:model %) "document") recents)))]+ (is (contains? ids plain-id)+ "Plain document should appear in recents")+ (is (not (contains? ids expl-doc))+ "Exploration-attached document should be filtered out of recents")))))diff --git a/test/metabase/documents/search_test.clj b/test/metabase/documents/search_test.cljindex cfabdceadd4..04f4c9018cb 100644--- a/test/metabase/documents/search_test.clj+++ b/test/metabase/documents/search_test.clj@@ -176,3 +176,27 @@(testing "no longer found by the replaced body term"(let [results (mt/user-http-request :crowberto :get 200 "search" :q "initial" :models "document")](is (not (contains? (set (map :id (:data results))) doc-id)))))))))++(deftest exploration-document-search-exclusion-test+ (testing "Documents attached to an exploration are excluded from search"+ (let [tag (mt/random-name)]+ (search.tu/with-temp-index-table+ (mt/with-temp [:model/User u {}+ :model/Exploration e {:name "expl" :creator_id (:id u)}+ :model/Document exploration-doc {:name (str tag "-exploration")+ :document (documents.test-util/text->prose-mirror-ast "")+ :creator_id (:id u)+ :exploration_id (:id e)}+ :model/Document standalone {:name (str tag "-standalone")+ :document (documents.test-util/text->prose-mirror-ast "")+ :creator_id (:id u)}]+ (let [results (mt/user-http-request :crowberto :get 200 "search" :q tag :models "document")+ ids (set (map :id (:data results)))]+ (is (contains? ids (u/the-id standalone))+ "Standalone document should appear")+ (is (not (contains? ids (u/the-id exploration-doc)))+ "Exploration-attached document should NOT appear"))+ (testing "result rows don't leak the internal :exploration_id column"+ (let [results (mt/user-http-request :crowberto :get 200 "search" :q tag :models "document")]+ (is (every? (complement #(contains? % :exploration_id))+ (:data results))))))))))diff --git a/test/metabase/explorations/api_test.clj b/test/metabase/explorations/api_test.cljindex d941b4ca2eb..cf4aa694a32 100644--- a/test/metabase/explorations/api_test.clj+++ b/test/metabase/explorations/api_test.clj@@ -9,6 +9,7 @@[metabase.explorations.api][metabase.explorations.blocks :as explorations.blocks][metabase.explorations.derived-perms :as derived-perms]+ [metabase.explorations.models.exploration-query-result :as eqr][metabase.explorations.query-plan :as query-plan][metabase.explorations.query-plan.context :as qp.context][metabase.explorations.query-plan.variants :as qp.variants]@@ -18,6 +19,7 @@[metabase.lib.metadata :as lib.metadata][metabase.permissions.core :as perms][metabase.permissions.models.permissions-group :as perms-group]+ [metabase.queries.core :as queries][metabase.query-permissions.core :as query-perms][metabase.query-processor :as qp][metabase.query-processor.core :as qp.core]@@ -1409,6 +1411,8 @@new-block (-> new :blocks first)new-queries (:queries new)](is (= 2 (count threads)) "explore-further adds a thread; restart would keep 1")+ (is (= 1 (t2/count :model/Document :exploration_id expl-id))+ "explore-further does not create a second Summary document")(is (= (:id orig-thread) (:id orig)))(is (= 1 (:position new)))(testing "the drill thread records the page it was drilled from (sidebar nesting)"@@ -1543,7 +1547,7 @@(assoc body :explore_filters [])))))))(deftest exploration-cascade-delete-test- (testing "Deleting an exploration cascades to threads, selections, and queries"+ (testing "Deleting an exploration cascades to threads, selections, queries, and the Summary document"(mt/with-temp [:model/User u {:email "[email protected]"}:model/Card metric (valid-metric-card (:id u)):model/Timeline tl {:creator_id (:id u)}]@@ -1555,12 +1559,363 @@:dimension_mappings [{:dimension_id (duid "d1") :table_id 1 :target ["field" {} 1]}]}]:dimensions [{:dimension_id (duid "d1")}]}]})eid (:id resp)- tid (-> resp :threads first :id)]+ tid (-> resp :threads first :id)+ doc-id (-> resp :document :id)]+ (is (some? doc-id) "POST creates a Summary document")(t2/delete! :model/Exploration :id eid)(is (zero? (t2/count :model/ExplorationThread :exploration_id eid)))(is (zero? (t2/count :model/ExplorationBlock :exploration_thread_id tid)))(is (zero? (t2/count :model/ExplorationThreadTimeline :exploration_thread_id tid)))- (is (zero? (t2/count :model/ExplorationQuery :exploration_thread_id tid)))))))+ (is (zero? (t2/count :model/ExplorationQuery :exploration_thread_id tid)))+ (is (false? (t2/exists? :model/Document :id doc-id))+ "Summary document is cascade-deleted via exploration_id FK")))))++(deftest exploration-create-auto-creates-summary-document-test+ (testing "POST / auto-creates a placeholder Summary document owned by the exploration"+ (mt/with-temp [:model/User u {:email "[email protected]"}+ :model/Collection coll {:name "summary-coll"}]+ (let [resp (mt/user-http-request u :post 200 "exploration"+ {:name "x" :collection_id (:id coll)})+ doc (:document resp)+ docs (t2/select :model/Document :exploration_id (:id resp))]+ (is (= 1 (count docs)))+ (is (= "Summary" (:name doc)))+ (is (= (:id u) (:creator_id doc)))+ (is (= (:id resp) (:exploration_id doc)))+ (is (= (:id coll) (:collection_id (first docs))))+ (is (true? (:is_placeholder doc)))+ (testing "first body save clears is_placeholder"+ (mt/user-http-request u :put 200 (str "document/" (:id doc))+ {:document {:type "doc"+ :content [{:type "paragraph"+ :content [{:type "text" :text "curated"}]}]}})+ (is (false? (t2/select-one-fn :is_placeholder :model/Document :id (:id doc)))))))))++(def ^:private append-display+viz+ "Required display + visualization_settings for summary/append requests."+ {:display "bar"+ :visualization_settings {:graph.dimensions ["x"] :graph.metrics ["y"]}})++(deftest exploration-append-records-stored-result-use-test+ (testing "Appending a static cardEmbed records a stored_result_use row tying the snapshot to the new Card"+ (mt/with-temp [:model/User u {:email "[email protected]"}+ :model/Card metric (valid-metric-card (:id u))]+ (let [resp (create-exploration! u+ {:name "append-use"+ :metrics [{:card_id (:id metric)+ :dimension_mappings [{:dimension_id (duid "d1") :table_id (mt/id :venues) :target ["field" {} (mt/id :venues :price)]}]}]+ :dimensions [{:dimension_id (duid "d1") :display_name "Price" :effective_type "type/Number"}]})+ eid (:id resp)+ qid (-> resp :threads first :queries first :id)+ qp-out {:status :completed+ :data {:cols [{:name "x" :source :breakout}+ {:name "y" :source :aggregation}]+ :rows [["a" 3] ["b" 1]]}+ :row_count 2}]+ (store-fake-result! qid qp-out)+ (mark-done! qid)+ (t2/update! :model/ExplorationQuery qid {:dataset_query (:dataset_query metric)})+ (let [sr-id (t2/select-one-fn :stored_result_id :model/ExplorationQueryResult+ :exploration_query_id qid)+ before (t2/select :model/StoredResultUse :stored_result_id sr-id)+ doc (mt/user-http-request u :post 200+ (format "exploration/%d/summary/append" eid)+ (assoc append-display+viz :exploration_query_ids [qid]))+ card-id (-> (t2/select-one-fn :document :model/Document :id (:id doc))+ :content last :content first :attrs :id)+ use-row (t2/select-one :model/StoredResultUse :stored_result_id sr-id :card_id card-id)+ attrs (-> (t2/select-one-fn :document :model/Document :id (:id doc))+ :content last :content first :attrs)]+ (is (empty? before)+ "no card-use row exists before the append")+ (is (some? use-row)+ "appending records a stored_result_use row for the source snapshot")+ (is (nil? (:exploration_id use-row))+ "the card-use row has no exploration_id")+ (is (= sr-id (:stored_result_id attrs)))+ (is (string? (:chart_href attrs)))+ (is (string? (:child_target_id attrs)))+ (is (= [qid] (get-in attrs [:host_data :query_ids])))+ (is (nil? (get-in attrs [:host_data :explore_filters]))+ "unfiltered charts omit explore_filters from host_data")+ (is (uuid? (parse-uuid (str (:_id attrs))))+ "_id is stamped for per-node identity (string after JSON round-trip)")+ (is (false? (:is_placeholder doc))+ "first append clears is_placeholder"))))))++(deftest exploration-append-bakes-explore-filters-into-host-data-test+ (testing "Appending a chart from an explore-further thread snapshots explore_filters onto host_data"+ (mt/with-temp [:model/User u {:email "[email protected]"}+ :model/Card metric (venues-metric-card (:id u))]+ (let [filter-value 2+ field-ref ["field" {} (mt/id :venues :price)]+ created (create-exploration! u+ {:name "append-filters"+ :metrics [{:card_id (:id metric)+ :dimension_mappings (venues-dimension-mappings)}]+ :dimensions [{:dimension_id (duid "category") :display_name "Category"}+ {:dimension_id (duid "price") :display_name "Price"}]})+ expl-id (:id created)+ page-id (some :id (filter #(str/includes? (:name %) "Price")+ (-> created :threads first :blocks first :pages)))+ hydrated (explore-further-and-hydrate! u expl-id page-id+ [{:operator "="+ :field_ref field-ref+ :value filter-value+ :display_value "2"}])+ new-thread (->> hydrated :threads (sort-by :position) second)+ qid (-> new-thread :queries first :id)+ qp-out {:status :completed+ :data {:cols [{:name "x" :source :breakout}+ {:name "y" :source :aggregation}]+ :rows [["a" 3] ["b" 1]]}+ :row_count 2}]+ (store-fake-result! qid qp-out)+ (mark-done! qid)+ (t2/update! :model/ExplorationQuery qid {:dataset_query (:dataset_query metric)})+ (let [doc (mt/user-http-request u :post 200+ (format "exploration/%d/summary/append" expl-id)+ (assoc append-display+viz :exploration_query_ids [qid]))+ attrs (-> (t2/select-one-fn :document :model/Document :id (:id doc))+ :content last :content first :attrs)]+ (is (= [qid] (get-in attrs [:host_data :query_ids])))+ (is (=? [{:operator "="+ :value filter-value+ :dimension_name "Price"+ :display_value "2"}]+ (get-in attrs [:host_data :explore_filters]))))))))++(deftest exploration-append-rolls-back-on-failure-test+ (testing "When a write fails partway through, the composite StoredResult / Card / use rows all roll back — no orphans"+ (mt/with-temp [:model/User u {:email "[email protected]"}+ :model/Card metric (valid-metric-card (:id u))]+ (let [resp (create-exploration! u+ {:name "append-rollback"+ :metrics [{:card_id (:id metric)+ :dimension_mappings [{:dimension_id (duid "d1") :table_id 1 :target ["field" {} 1]}]}]+ :dimensions [{:dimension_id (duid "d1")}]})+ qid (-> resp :threads first :queries first :id)+ doc-id (-> resp :document :id)+ qp-out {:status :completed+ :data {:cols [{:name "x" :source :breakout}+ {:name "y" :source :aggregation}]+ :rows [["a" 3] ["b" 1]]}+ :row_count 2}]+ (store-fake-result! qid qp-out)+ (mark-done! qid)+ (let [doc (t2/select-one :model/Document :id doc-id)]+ ;; Stub the perms check (the EQ has no inline dataset_query here) and force `create-card!`+ ;; to blow up *after* the composite StoredResult has been inserted, exercising the rollback.+ (with-redefs [query-perms/check-run-permissions-for-query (fn [_] nil)+ queries/create-card! (fn [& _] (throw (ex-info "boom" {})))]+ (is (thrown? Throwable+ (eqr/create-ephemeral-card-for-exploration-queries!+ [qid] doc-id (:collection_id doc) u+ {:display "bar" :visualization-settings {}}))))+ (is (= 1 (t2/count :model/StoredResult :creator_id (:id u)))+ "only the source snapshot remains — no composite StoredResult leaks from the rolled-back append")+ (is (zero? (t2/count :model/Card :document_id doc-id))+ "no ephemeral Card leaks from the rolled-back append")+ (is (zero? (t2/count :model/StoredResultUse :stored_result_id+ (t2/select-one-fn :stored_result_id :model/ExplorationQueryResult+ :exploration_query_id qid)))+ "no stored_result_use rows leak from the rolled-back append"))))))++(deftest exploration-append-single-query-reuses-source-snapshot-test+ (testing "A single-query append reuses the source stored_result instead of duplicating its bytes into a fresh row"+ (mt/with-temp [:model/User u {:email "[email protected]"}+ :model/Card metric (valid-metric-card (:id u))]+ (let [resp (create-exploration! u+ {:name "append-single"+ :metrics [{:card_id (:id metric)+ :dimension_mappings [{:dimension_id (duid "d1") :table_id 1 :target ["field" {} 1]}]}]+ :dimensions [{:dimension_id (duid "d1")}]})+ qid (-> resp :threads first :queries first :id)+ doc-id (-> resp :document :id)+ qp-out {:status :completed+ :data {:cols [{:name "x" :source :breakout}+ {:name "y" :source :aggregation}]+ :rows [["a" 3] ["b" 1]]}+ :row_count 2}]+ (store-fake-result! qid qp-out)+ (mark-done! qid)+ ;; Give the EQ a real dataset_query so create-card! has a database_id to inherit.+ (t2/update! :model/ExplorationQuery qid {:dataset_query (:dataset_query metric)})+ (let [src-sr-id (t2/select-one-fn :stored_result_id :model/ExplorationQueryResult+ :exploration_query_id qid)+ doc (t2/select-one :model/Document :id doc-id)+ ;; Stub the perms check (the synthetic EQ has no inline dataset_query) so we exercise+ ;; the real create-card! / stored_result write path.+ result (with-redefs [query-perms/check-run-permissions-for-query (fn [_] nil)]+ (eqr/create-ephemeral-card-for-exploration-queries!+ [qid] doc-id (:collection_id doc) u+ {:display "bar" :visualization-settings {}}))+ use-rows (t2/select :model/StoredResultUse :card_id (:card-id result))]+ (is (= src-sr-id (:stored-result-id result))+ "the embed points back at the source stored_result rather than a fresh copy")+ (is (= 1 (t2/count :model/StoredResult :creator_id (:id u)))+ "only the reused source snapshot exists — no duplicate composite StoredResult is created for a single-query embed")+ (is (= [src-sr-id] (mapv :stored_result_id use-rows))+ "exactly one stored_result_use row, pointing at the source snapshot"))))))++(deftest exploration-summary-save-carries-stored-result-pairing-test+ (testing "PUT /api/document/:id carries (card, stored_result) pairings onto draft-created Cards so Summary embeds stay readable"+ (mt/with-temp [:model/User u {:email "[email protected]"}+ :model/Card metric (valid-metric-card (:id u))]+ (let [resp (create-exploration! u+ {:name "summary-carry"+ :metrics [{:card_id (:id metric)+ :dimension_mappings [{:dimension_id (duid "d1")+ :table_id (mt/id :venues)+ :target ["field" {} (mt/id :venues :price)]}]}]+ :dimensions [{:dimension_id (duid "d1") :display_name "Price"+ :effective_type "type/Number"}]})+ eid (:id resp)+ qid (-> resp :threads first :queries first :id)+ doc-id (-> resp :document :id)+ qp-out {:status :completed+ :data {:cols [{:name "x" :source :breakout}+ {:name "y" :source :aggregation}]+ :rows [["a" 3] ["b" 1]]}+ :row_count 2}]+ (store-fake-result! qid qp-out)+ (mark-done! qid)+ (t2/update! :model/ExplorationQuery qid {:dataset_query (:dataset_query metric)})+ (mt/user-http-request u :post 200+ (format "exploration/%d/summary/append" eid)+ (assoc append-display+viz :exploration_query_ids [qid]))+ (let [attrs (-> (t2/select-one-fn :document :model/Document :id doc-id)+ :content last :content first :attrs)+ sr-id (:stored_result_id attrs)+ old-card-id (:id attrs)+ draft-id -10+ ;; Simulate the editor forking the embed into a negative-id draft card on save.+ updated (mt/user-http-request u :put 200 (format "document/%d" doc-id)+ {:document {:type "doc"+ :content [{:type "cardEmbed"+ :attrs {:id draft-id+ :stored_result_id sr-id}}]}+ :cards {draft-id {:name "Edited Summary Chart"+ :dataset_query (:dataset_query metric)+ :display "bar"+ :visualization_settings {:graph.colors ["#509EE3"]}}}})+ new-card-id (-> updated :document :content first :attrs :id)]+ (is (pos-int? new-card-id)+ "draft id is rewritten to a real Card id")+ (is (not= old-card-id new-card-id)+ "save creates a brand-new Card rather than updating in place")+ (is (some? (t2/select-one :model/StoredResultUse+ :stored_result_id sr-id+ :card_id new-card-id))+ "pairing is carried onto the new Card")+ (is (=? {:status "completed" :row_count 2 :data {:rows [["a" 3] ["b" 1]]}}+ (mt/user-http-request u :post 200 (format "card/%d/query" new-card-id)+ {:stored_result_id sr-id}))+ "cached read against the new card id succeeds"))))))++(deftest ^:parallel page-url-test+ (testing "page-url builds a research deep link to a page by id"+ (is (= "/question/research/7/page/42"+ (explorations.blocks/page-url 7 42)))))++(deftest exploration-put-cascades-collection-id-to-documents-test+ (testing "Moving an exploration rewrites :collection_id on its Summary document."+ (mt/with-temp [:model/Collection src {}+ :model/Collection dest {}+ :model/Exploration e {:name "cascade"+ :creator_id (mt/user->id :crowberto)+ :collection_id (:id src)}+ :model/Document d {:name "Summary"+ :document {:type "doc" :content []}+ :content_type "application/json+vnd.prose-mirror"+ :creator_id (mt/user->id :crowberto)+ :collection_id (:id src)+ :exploration_id (:id e)}]+ (mt/user-http-request :crowberto :put 200 (format "exploration/%d" (:id e))+ {:collection_id (:id dest)})+ (is (= (:id dest) (t2/select-one-fn :collection_id :model/Document :id (:id d)))))))++(deftest exploration-put-archive-cascades-to-documents-test+ (testing "Archiving an exploration cascade-archives its Summary, except user-archived ones."+ (mt/with-temp [:model/Collection c {}+ :model/Exploration e {:name "to-archive"+ :creator_id (mt/user->id :crowberto)+ :collection_id (:id c)}+ :model/Document live {:name "Summary"+ :document {:type "doc" :content []}+ :content_type "application/json+vnd.prose-mirror"+ :creator_id (mt/user->id :crowberto)+ :collection_id (:id c)+ :exploration_id (:id e)}+ :model/Document user-archived {:name "user-archived"+ :document {:type "doc" :content []}+ :content_type "application/json+vnd.prose-mirror"+ :creator_id (mt/user->id :crowberto)+ :collection_id (:id c)+ :exploration_id (:id e)+ :archived true+ :archived_directly true}]+ (mt/user-http-request :crowberto :put 200 (format "exploration/%d" (:id e))+ {:archived true})+ (testing "live doc is cascade-archived (archived_directly=false marks it as cascade)"+ (let [d (t2/select-one :model/Document :id (:id live))]+ (is (true? (:archived d)))+ (is (false? (:archived_directly d)))))+ (testing "user-archived doc is left alone"+ (let [d (t2/select-one :model/Document :id (:id user-archived))]+ (is (true? (:archived d)))+ (is (true? (:archived_directly d))))))))++(deftest exploration-get-hydrates-summary-when-trashed-test+ (testing "GET /:id still hydrates the Summary after the exploration is trashed, so Trash view keeps the document."+ (mt/with-temp [:model/Collection c {}+ :model/Exploration e {:name "trashed"+ :creator_id (mt/user->id :crowberto)+ :collection_id (:id c)}+ :model/Document d {:name "Summary"+ :document {:type "doc" :content []}+ :content_type "application/json+vnd.prose-mirror"+ :creator_id (mt/user->id :crowberto)+ :collection_id (:id c)+ :exploration_id (:id e)}]+ (mt/user-http-request :crowberto :put 200 (format "exploration/%d" (:id e))+ {:archived true})+ (let [resp (mt/user-http-request :crowberto :get 200 (format "exploration/%d" (:id e)))]+ (is (= (:id d) (get-in resp [:document :id])))+ (is (true? (get-in resp [:document :archived])))))))++(deftest exploration-put-unarchive-cascades-to-documents-test+ (testing "Unarchiving restores cascade-archived docs but leaves user-archived docs archived."+ (mt/with-temp [:model/Collection c {}+ :model/Exploration e {:name "to-unarchive"+ :creator_id (mt/user->id :crowberto)+ :collection_id (:id c)+ :archived true+ :archived_directly true}+ :model/Document cascade-doc {:name "cascade-doc"+ :document {:type "doc" :content []}+ :content_type "application/json+vnd.prose-mirror"+ :creator_id (mt/user->id :crowberto)+ :collection_id (:id c)+ :exploration_id (:id e)+ :archived true+ :archived_directly false}+ :model/Document user-archived {:name "user-archived"+ :document {:type "doc" :content []}+ :content_type "application/json+vnd.prose-mirror"+ :creator_id (mt/user->id :crowberto)+ :collection_id (:id c)+ :exploration_id (:id e)+ :archived true+ :archived_directly true}]+ (mt/user-http-request :crowberto :put 200 (format "exploration/%d" (:id e))+ {:archived false})+ (testing "cascade-archived doc is restored"+ (is (false? (t2/select-one-fn :archived :model/Document :id (:id cascade-doc)))))+ (testing "user-archived doc stays archived"+ (let [d (t2/select-one :model/Document :id (:id user-archived))]+ (is (true? (:archived d)))+ (is (true? (:archived_directly d))))))))(deftest exploration-http-delete-returns-204-test(testing "DELETE /api/exploration/:id returns 204 and removes the row — guards a malli regression where returning the Ring response map `generic-204-no-content` instead of literal `nil` made the `:- :nil` schema reject the response and yield a 400"@@ -2033,6 +2388,11 @@{:model model :model_id id :user_id user-id :object {}:timestamp ts :is_creation false :is_reversion false :most_recent false}))+(defn- mine-names+ "Names in the order `GET /mine` returns them for `user`."+ [user & opts]+ (mapv :name (:data (apply mt/user-http-request user :get 200 "exploration/mine" opts))))+(defn- m-index-by"Index a `GET /mine` response's `:data` rows by `:name`."[resp]@@ -2073,6 +2433,30 @@(testing "rows don't leak the internal total_count column"(is (not (contains? (get by-name "created-by-me") :total_count)))))))))+(deftest mine-ordering-composes-document-edits-test+ (testing "GET /mine sorts by the caller's most-recent touch, counting Summary document edits"+ (mt/with-temp [:model/User me {:email "[email protected]"}+ :model/Collection coll {:name "order-coll"}+ ;; created-only: only touch is creation (no revisions)+ :model/Exploration _created-only {:name "created-only" :creator_id (:id me) :collection_id (:id coll)}+ ;; meta-edited: a later Exploration revision+ :model/Exploration meta-edited {:name "meta-edited" :creator_id (:id me) :collection_id (:id coll)}+ ;; doc-edited: a still-later Document (Summary) revision, even though its own+ ;; Exploration row was never edited after creation+ :model/Exploration doc-edited {:name "doc-edited" :creator_id (:id me) :collection_id (:id coll)}+ :model/Document doc {:name "Summary"+ :document {:type "doc" :content []}+ :content_type "application/json+vnd.prose-mirror"+ :creator_id (:id me)+ :collection_id (:id coll)+ :exploration_id (:id doc-edited)}]+ (let [now (t/offset-date-time)]+ (touch-revision! "Exploration" (:id meta-edited) (:id me) (t/plus now (t/days 1)))+ (touch-revision! "Document" (:id doc) (:id me) (t/plus now (t/days 2))))+ (testing "doc edit (newest touch) sorts above the metadata edit, which sorts above created-only"+ (is (= ["doc-edited" "meta-edited" "created-only"]+ (mine-names me)))))))+(deftest mine-pagination-test(testing "GET /mine pages with a stable order and a post-filter total"(mt/with-temp [:model/User me {:email "[email protected]"}@@ -2482,3 +2866,135 @@(is (nil? (:completed_at thread)))(is (nil? (:canceled_at thread)))(is (zero? (t2/count :model/ExplorationQuery :exploration_thread_id tid)))))))))++;;; ------------------------ composite (multi-query) Summary embeds ------------------------++(defn- two-ready-queries!+ "An exploration with (at least) two `done` ExplorationQueries, each backed by a fake snapshot and+ given the metric Card's real `dataset_query`. Returns `{:exploration-id :document-id :query-ids}`."+ [u metric]+ (let [resp (create-exploration! u+ {:name "composite"+ :metrics [{:card_id (:id metric)+ :dimension_mappings [{:dimension_id (duid "d1")+ :table_id (mt/id :venues)+ :target ["field" {} (mt/id :venues :price)]}+ {:dimension_id (duid "d2")+ :table_id (mt/id :venues)+ :target ["field" {} (mt/id :venues :name)]}]}]+ :dimensions [{:dimension_id (duid "d1") :display_name "Price"+ :effective_type "type/Number"}+ {:dimension_id (duid "d2") :display_name "Name"+ :effective_type "type/Text"}]})+ qids (->> resp :threads first :queries+ (filter #(= "default" (:query_type %)))+ (map :id) (take 2) vec)+ qp-out {:status :completed+ :data {:cols [{:name "x" :source :breakout}+ {:name "y" :source :aggregation}]+ :rows [["a" 3] ["b" 1]]}+ :row_count 2}]+ (assert (= 2 (count qids)) "fixture needs two exploration queries")+ (doseq [qid qids]+ (store-fake-result! qid qp-out)+ (mark-done! qid)+ (t2/update! :model/ExplorationQuery qid {:dataset_query (:dataset_query metric)}))+ {:exploration-id (:id resp) :document-id (-> resp :document :id) :query-ids qids}))++(defn- combine-with-perms-stubbed!+ "Run the composite build with the run-permissions check stubbed out. The temp users these tests+ create hold no data perms, and `create-card!` runs the same check — the existing single-query+ test stubs it for the same reason. Tests that are *about* the permission check don't use this."+ [& args]+ (with-redefs [query-perms/check-run-permissions-for-query (fn [_] nil)]+ (apply eqr/create-ephemeral-card-for-exploration-queries! args)))++(deftest composite-snapshot-carries-a-data-access-token-test+ (testing "A multi-query composite snapshot is stamped with its sources' data-access lens — without one the+ read gate denies the embed to every non-superuser, including the collaborators it was added for"+ (mt/with-temp [:model/User u {:email "[email protected]"}+ :model/Card metric (valid-metric-card (:id u))]+ (let [{:keys [document-id query-ids]} (two-ready-queries! u metric)+ doc (t2/select-one :model/Document :id document-id)+ result (combine-with-perms-stubbed!+ query-ids document-id (:collection_id doc) u+ {:display "bar" :visualization-settings {}})+ src-token (t2/select-one-fn :data_access_token :model/StoredResult+ :id (t2/select-one-fn :stored_result_id :model/ExplorationQueryResult+ :exploration_query_id (first query-ids)))]+ (is (not= (:stored-result-id result)+ (t2/select-one-fn :stored_result_id :model/ExplorationQueryResult+ :exploration_query_id (first query-ids)))+ "a genuine multi-snapshot combine writes its own composite row")+ (is (= src-token+ (t2/select-one-fn :data_access_token :model/StoredResult :id (:stored-result-id result)))+ "the composite carries the same lens its sources were computed under")))))++(deftest composite-refuses-to-blend-different-data-access-lenses-test+ (testing "Sources computed under different lenses have no single honest stamp, so the combine is refused+ rather than persisted under one of them"+ (mt/with-temp [:model/User u {:email "[email protected]"}+ :model/Card metric (valid-metric-card (:id u))]+ (let [{:keys [document-id query-ids]} (two-ready-queries! u metric)+ doc (t2/select-one :model/Document :id document-id)+ sr-2 (t2/select-one-fn :stored_result_id :model/ExplorationQueryResult+ :exploration_query_id (second query-ids))]+ (t2/update! :model/StoredResult sr-2 {:data_access_token {:sandbox {1 "deadbeef"}}})+ (is (thrown-with-msg?+ clojure.lang.ExceptionInfo #"different data-access contexts"+ (combine-with-perms-stubbed!+ query-ids document-id (:collection_id doc) u+ {:display "bar" :visualization-settings {}})))+ (testing "and a source with no recorded lens at all is refused too"+ (t2/update! :model/StoredResult sr-2 {:data_access_token nil})+ (is (thrown-with-msg?+ clojure.lang.ExceptionInfo #"no recorded data-access context"+ (combine-with-perms-stubbed!+ query-ids document-id (:collection_id doc) u+ {:display "bar" :visualization-settings {}}))))))))++(deftest composite-checks-run-permissions-for-every-source-query-test+ (testing "`combine` copies the rows of every source into the composite, so the permission check has to cover+ every source query — not just the first, which would let a caller materialize rows from a table+ they cannot read"+ (mt/with-temp [:model/User u {:email "[email protected]"}+ :model/Card metric (valid-metric-card (:id u))]+ (let [{:keys [document-id query-ids]} (two-ready-queries! u metric)+ doc (t2/select-one :model/Document :id document-id)+ ;; Lib rather than the deprecated `mt/mbql-query`; same idiom used elsewhere here.+ other-q (lib/->legacy-MBQL (let [mp (mt/metadata-provider)]+ (-> (lib/query mp (lib.metadata/table mp (mt/id :checkins)))+ (lib/aggregate (lib/count)))))]+ ;; Give the second source a genuinely different query, so "checked the first one" and+ ;; "checked them all" are distinguishable.+ (t2/update! :model/ExplorationQuery (second query-ids) {:dataset_query other-q})+ (let [checked (atom [])]+ (with-redefs [query-perms/check-run-permissions-for-query+ (fn [q] (swap! checked conj q) nil)]+ (eqr/create-ephemeral-card-for-exploration-queries!+ query-ids document-id (:collection_id doc) u+ {:display "bar" :visualization-settings {}}))+ (is (= 2 (count @checked))+ "both source queries are permission-checked")+ (is (= (set (map #(t2/select-one-fn :dataset_query :model/ExplorationQuery :id %) query-ids))+ (set @checked))+ "and they are the two sources' own queries, not the first one twice"))))))++(deftest composite-collapses-duplicate-exploration-query-ids-test+ (testing "A repeated exploration_query_id is collapsed: it passes the caller's de-duped ownership check, and+ left alone would duplicate every row into the composite and insert a duplicate pairing row"+ (mt/with-temp [:model/User u {:email "[email protected]"}+ :model/Card metric (valid-metric-card (:id u))]+ (let [{:keys [document-id query-ids]} (two-ready-queries! u metric)+ qid (first query-ids)+ doc (t2/select-one :model/Document :id document-id)+ src-sr (t2/select-one-fn :stored_result_id :model/ExplorationQueryResult+ :exploration_query_id qid)+ result (combine-with-perms-stubbed!+ [qid qid] document-id (:collection_id doc) u+ {:display "bar" :visualization-settings {}})]+ (is (= src-sr (:stored-result-id result))+ "collapses to the single-query path, reusing the source snapshot rather than combining it with itself")+ (is (= [src-sr] (mapv :stored_result_id+ (t2/select :model/StoredResultUse :card_id (:card-id result))))+ "exactly one pairing row, not one per repeat")))))diff --git a/test/metabase/explorations/composite_test.clj b/test/metabase/explorations/composite_test.cljnew file mode 100644index 00000000000..618ba3ad964--- /dev/null+++ b/test/metabase/explorations/composite_test.clj@@ -0,0 +1,142 @@+(ns metabase.explorations.composite-test+ "Unit tests for the composite-snapshot combine logic — pure functions, no DB."+ (:require+ [clojure.test :refer :all]+ [metabase.explorations.composite :as composite]))++;;; eq-result constructors — match what+;;; `metabase.explorations.models.exploration-query-result/load-eq-results`+;;; produces.++(defn- eq-result+ "Build an `{:eq … :qp-result …}` eq-result. `cols` and `rows` go into+ `qp-result.data`; everything else is shaped just enough to look like a+ cached snapshot. `segment-name` becomes the EQ's hydrated `:segment_name`,+ the discriminator value combine appends."+ [segment-name cols rows]+ {:eq {:segment_name segment-name}+ :qp-result {:status :completed+ :row_count (count rows)+ :data {:cols cols :rows rows}}})++(deftest ^:parallel combine-single-query-passes-through+ (testing "N=1 returns the lone qp-result unchanged — no discriminator column"+ (let [t (eq-result "Solo" [{:name "x"} {:name "y"}] [["a" 1] ["b" 2]])+ result (composite/combine [t] {})]+ (is (= (:qp-result t) result))+ (is (= [{:name "x"} {:name "y"}]+ (get-in result [:data :cols])))+ (is (= [["a" 1] ["b" 2]]+ (get-in result [:data :rows]))))))++(deftest ^:parallel combine-heat-map-appends-Segment-column+ (testing "When `:table.pivot` is truthy the combine appends a `Segment` column whose value is the source EQ's `:segment_name`"+ (let [t1 (eq-result "All" [{:name "dim"} {:name "value"}] [["A" 1] ["B" 2]])+ t2 (eq-result "Enterprise" [{:name "dim"} {:name "value"}] [["A" 3] ["B" 4]])+ t3 (eq-result "SMB" [{:name "dim"} {:name "value"}] [["A" 5] ["B" 6]])+ result (composite/combine [t1 t2 t3] {:table.pivot true})]+ (testing "appends the Segment col with :source :breakout (parity with FE getHeatMapSeries)"+ (is (= [{:name "dim"}+ {:name "value"}+ {:name "Segment"+ :display_name "Segment"+ :base_type :type/Text+ :effective_type :type/Text+ :field_ref [:field "Segment" {:base-type :type/Text}]+ :source :breakout}]+ (get-in result [:data :cols]))))+ (testing "unions all rows, appending the EQ segment_name as the Segment value"+ (is (= [["A" 1 "All"]+ ["B" 2 "All"]+ ["A" 3 "Enterprise"]+ ["B" 4 "Enterprise"]+ ["A" 5 "SMB"]+ ["B" 6 "SMB"]]+ (get-in result [:data :rows]))))+ (testing "refreshes :row_count for the combined result"+ (is (= 6 (:row_count result)))))))++(deftest ^:parallel combine-multi-series-cartesian-appends-Series-column+ (testing "When `:table.pivot` is falsy/missing the combine appends a `Series` column for multi-series cartesian rendering"+ (let [t1 (eq-result "US" [{:name "ts"} {:name "count"}] [["2026-01" 10] ["2026-02" 20]])+ t2 (eq-result "EU" [{:name "ts"} {:name "count"}] [["2026-01" 30] ["2026-02" 40]])+ result (composite/combine [t1 t2] {:graph.split_panels true})]+ (is (= [{:name "ts"}+ {:name "count"}+ {:name "Series"+ :display_name "Series"+ :base_type :type/Text+ :effective_type :type/Text+ :field_ref [:field "Series" {:base-type :type/Text}]+ :source :breakout}]+ (get-in result [:data :cols])))+ (is (= [["2026-01" 10 "US"]+ ["2026-02" 20 "US"]+ ["2026-01" 30 "EU"]+ ["2026-02" 40 "EU"]]+ (get-in result [:data :rows])))+ (is (= 4 (:row_count result))))))++(deftest ^:parallel combine-handles-nil-segment-name+ (testing "An EQ with a nil `:segment_name` falls back to `(All)` so combining never throws"+ (let [t1 {:eq {:segment_name nil}+ :qp-result {:status :completed+ :row_count 1+ :data {:cols [{:name "x"} {:name "y"}]+ :rows [["a" 1]]}}}+ t2 (eq-result "Other" [{:name "x"} {:name "y"}] [["a" 2]])+ result (composite/combine [t1 t2] {})]+ (is (= [["a" 1 "(All)"] ["a" 2 "Other"]]+ (get-in result [:data :rows]))))))++(deftest ^:parallel combine-preserves-first-qp-result-scaffolding+ (testing "Non-`:data` fields (e.g. `:status`) come from the first eq-result's qp-result"+ (let [t1 (-> (eq-result "First" [{:name "x"}] [[1]])+ (assoc-in [:qp-result :status] :completed)+ (assoc-in [:qp-result :json_query] {:scaffolding :ok}))+ t2 (eq-result "Second" [{:name "x"}] [[2]])+ result (composite/combine [t1 t2] {})]+ (is (= :completed (:status result)))+ (is (= {:scaffolding :ok} (:json_query result))))))++(deftest ^:parallel combine-gives-distinct-discriminators-to-unlabeled-queries+ (testing "Two EQs with no `:segment_name` must not collapse into one series"+ (let [t1 {:eq {:segment_name nil}+ :qp-result {:status :completed :row_count 1+ :data {:cols [{:name "x"} {:name "y"}] :rows [["a" 1]]}}}+ t2 {:eq {:segment_name nil}+ :qp-result {:status :completed :row_count 1+ :data {:cols [{:name "x"} {:name "y"}] :rows [["a" 2]]}}}+ rows (get-in (composite/combine [t1 t2] {}) [:data :rows])+ labels (map peek rows)]+ (is (= 2 (count (distinct labels)))+ "each source query gets its own discriminator value"))))++(deftest ^:parallel combine-falls-back-to-query-name-before-all+ (testing "An EQ with no `:segment_name` but a `:name` uses the name as its discriminator"+ (let [t1 {:eq {:segment_name nil :name "Orders over time"}+ :qp-result {:status :completed :row_count 1+ :data {:cols [{:name "x"} {:name "y"}] :rows [["a" 1]]}}}+ t2 (eq-result "Enterprise" [{:name "x"} {:name "y"}] [["a" 2]])]+ (is (= [["a" 1 "Orders over time"] ["a" 2 "Enterprise"]]+ (get-in (composite/combine [t1 t2] {}) [:data :rows]))))))++(deftest ^:parallel combine-disambiguates-duplicate-labels+ (testing "Two EQs sharing a `:segment_name` still get distinct discriminator values"+ (let [t1 (eq-result "SMB" [{:name "x"} {:name "y"}] [["a" 1]])+ t2 (eq-result "SMB" [{:name "x"} {:name "y"}] [["a" 2]])+ labels (map peek (get-in (composite/combine [t1 t2] {}) [:data :rows]))]+ (is (= 2 (count (distinct labels)))))))++(deftest ^:parallel discriminator-col-carries-type-information+ (testing "The synthetic discriminator col has the type keys every other col carries, so the FE can format it and resolve it by column key"+ (let [t1 (eq-result "US" [{:name "ts"} {:name "count"}] [["2026-01" 10]])+ t2 (eq-result "EU" [{:name "ts"} {:name "count"}] [["2026-01" 30]])+ col (peek (get-in (composite/combine [t1 t2] {}) [:data :cols]))]+ (is (= {:name "Series"+ :display_name "Series"+ :base_type :type/Text+ :effective_type :type/Text+ :field_ref [:field "Series" {:base-type :type/Text}]+ :source :breakout}+ col)))))diff --git a/test/metabase/explorations/derived_perms_test.clj b/test/metabase/explorations/derived_perms_test.cljindex 18dba9f7439..f36aa1b67b5 100644--- a/test/metabase/explorations/derived_perms_test.clj+++ b/test/metabase/explorations/derived_perms_test.clj@@ -5,6 +5,7 @@the batching that must not merge snapshots requiring different permissions."(:require[clojure.test :refer :all]+ [metabase.documents.core :as documents][metabase.explorations.derived-perms :as derived-perms][metabase.lib.core :as lib][metabase.lib.metadata :as lib.metadata]@@ -299,3 +300,149 @@large (measure 25)](is (< large (* 2 small))(format "resolution must stay cheap (2 charts: %d queries, 25 charts: %d)" small large)))))++;;; --------------------------------- Summary-document content gate ---------------------------------++(defn- doc-content-visible? [document user-kw]+ (request/with-current-user (mt/user->id user-kw)+ (derived-perms/doc-content-visible-to-current-user? document)))++(deftest doc-content-gate-does-not-fail-open-on-a-partial-select-test+ (testing "a Summary document whose exploration the viewer may not see"+ (let [thread (thread-with-snapshots! [{:creator-id (mt/user->id :lucky) :table :venues :token nil}])+ expl (t2/select-one-fn :exploration_id :model/ExplorationThread :id thread)]+ (mt/with-temp [:model/Document {doc-id :id} {:exploration_id expl :creator_id (mt/user->id :lucky)}]+ (testing "is denied when the instance carries :exploration_id"+ (is (false? (boolean (doc-content-visible? (t2/select-one :model/Document :id doc-id) :rasta)))))+ (testing "is denied on a partial select too — the shape `collection-children-query` produces, which omits :exploration_id"+ (is (false? (boolean (doc-content-visible? (t2/select-one [:model/Document :id :name] :id doc-id) :rasta)))))+ (testing "is denied for an instance carrying neither :exploration_id nor :id — nothing left to adjudicate on"+ (is (false? (boolean (doc-content-visible? {:name "Summary"} :rasta)))))))))++(deftest doc-content-gate-leaves-ordinary-documents-alone-test+ (testing "a document with no owning exploration is visible, on a full or partial select"+ (mt/with-temp [:model/Document {doc-id :id} {:creator_id (mt/user->id :lucky)}]+ (is (true? (boolean (doc-content-visible? (t2/select-one :model/Document :id doc-id) :rasta))))+ (is (true? (boolean (doc-content-visible? (t2/select-one [:model/Document :id :name] :id doc-id) :rasta)))))))++;;; --------------------------- Cards scoped to a gated Summary document ---------------------------++(defn- card-readable? [card-id user-kw]+ (request/with-current-user (mt/user->id user-kw)+ (boolean (mi/can-read? (t2/select-one :model/Card :id card-id)))))++(deftest card-scoped-to-a-gated-document-is-not-readable-test+ (testing "a Card scoped to an exploration Summary document"+ (let [thread (thread-with-snapshots! [{:creator-id (mt/user->id :lucky) :table :venues :token nil}])+ expl (t2/select-one-fn :exploration_id :model/ExplorationThread :id thread)]+ (mt/with-temp [:model/Collection {coll-id :id} {}+ :model/Document {doc-id :id} {:exploration_id expl+ :collection_id coll-id+ :creator_id (mt/user->id :lucky)}+ ;; The ephemeral Summary card: its name and dataset_query are copied from the+ ;; ExplorationQuery, which embeds dimension values discovered under the+ ;; creator's lens.+ :model/Card {card-id :id} {:collection_id coll-id+ :document_id doc-id+ :name "Orders for Customer = ACME Corp over time"}+ ;; A sibling card in the same collection, owned by no document.+ :model/Card {plain-id :id} {:collection_id coll-id :name "Plain card"}]+ ;; Collection read must PASS, so that anything denied below is denied by the content gate+ ;; and not merely by collection permissions.+ (perms/grant-collection-read-permissions! (perms-group/all-users) coll-id)+ (testing "sanity: the owning Summary document is itself gated for this viewer"+ (is (false? (boolean (request/with-current-user (mt/user->id :rasta)+ (mi/can-read? (t2/select-one :model/Document :id doc-id)))))))+ (testing "is not readable by a viewer whose data-access lens is incompatible, even though they can read the collection"+ (is (false? (card-readable? card-id :rasta))))+ (testing "is still readable by a superuser, matching the gate's standing exemption"+ (is (true? (card-readable? card-id :crowberto))))+ (testing "leaves cards that belong to no document alone"+ (is (true? (card-readable? plain-id :rasta))))))))++(deftest card-scoped-to-an-ordinary-document-is-unaffected-test+ (testing "a Card scoped to a Document with no owning exploration is readable on collection perms alone"+ (mt/with-temp [:model/Collection {coll-id :id} {}+ :model/Document {doc-id :id} {:collection_id coll-id+ :creator_id (mt/user->id :lucky)}+ :model/Card {card-id :id} {:collection_id coll-id :document_id doc-id}]+ (perms/grant-collection-read-permissions! (perms-group/all-users) coll-id)+ (is (true? (card-readable? card-id :rasta))))))++;;; ------------------------- comment context on a gated exploration -------------------------++(defn- page-id-for-thread [thread-id]+ (t2/select-one-fn :id :model/ExplorationPage+ {:select [:p.id]+ :from [[:exploration_page :p]]+ :join [[:exploration_block :b] [:= :b.id :p.exploration_block_id]]+ :where [:= :b.exploration_thread_id thread-id]}))++(defn- comment-contexts [exploration-id user-kw]+ (->> (mt/user-http-request user-kw :get 200 "comment/"+ :target_type "exploration"+ :target_id exploration-id)+ :comments+ (mapv :context)))++(deftest exploration-comment-context-is-gated-test+ (testing "a comment anchored to a chart point of an exploration the viewer is gated out of"+ (let [thread (thread-with-snapshots! [{:creator-id (mt/user->id :lucky) :table :venues :token nil}])+ expl-id (t2/select-one-fn :exploration_id :model/ExplorationThread :id thread)+ page-id (page-id-for-thread thread)]+ (mt/with-temp [:model/Collection {coll-id :id} {}]+ ;; Put the exploration somewhere the viewer can read, so anything withheld below is withheld+ ;; by the data-access gate rather than by collection permissions.+ (t2/update! :model/Exploration expl-id {:collection_id coll-id})+ (perms/grant-collection-read-permissions! (perms-group/all-users) coll-id)+ (mt/user-http-request :lucky :post 200 "comment/"+ {:target_type "exploration"+ :target_id expl-id+ :child_target_id (str page-id)+ :content {:type "doc" :content []}+ :context {:highlighted {:columnName "CATEGORY"+ :dimensions [{:columnName "CATEGORY"+ :value "ACME Corp"}]}+ :highlight_label "ACME Corp"}})+ (testing "keeps its context for a superuser, who is exempt from the gate"+ (is (=? [{:highlighted {:columnName "CATEGORY"}+ :highlight_label "ACME Corp"}]+ (comment-contexts expl-id :crowberto))))+ (testing "is stripped of its context for a viewer whose data-access lens is incompatible —+ the comment itself remains readable, only the warehouse values it carries are withheld"+ (let [contexts (comment-contexts expl-id :rasta)]+ (is (= 1 (count contexts)) "the comment is still listed")+ (is (= [nil] contexts) "but carries no context")))))))++(deftest content-gate-verdict-is-memoized-within-a-scope-test+ (testing "every Card in a Summary document shares one document, and therefore one verdict. Without+ memoization each card re-runs the whole rollup — ~20 app-DB queries apiece — so a+ document's cards cost N times what one costs. Bulk read paths scope the cache+ themselves; see the callers of `with-content-gate-cache`."+ (let [thread (thread-with-snapshots! (repeat 5 {:creator-id (mt/user->id :lucky)+ :table :venues :token {}}))+ expl-id (t2/select-one-fn :exploration_id :model/ExplorationThread :id thread)]+ (mt/with-temp [:model/Collection {coll-id :id} {}+ :model/Document {doc-id :id} {:exploration_id expl-id+ :collection_id coll-id+ :creator_id (mt/user->id :lucky)}]+ (perms/grant-collection-read-permissions! (perms-group/all-users) coll-id)+ (let [card-ids (vec (for [_ (range 10)]+ (t2/insert-returning-pk! :model/Card+ {:name "c" :creator_id (mt/user->id :lucky)+ :database_id (mt/id)+ :dataset_query (count-query :venues)+ :display "table" :visualization_settings {}+ :collection_id coll-id :document_id doc-id})))]+ (request/with-current-user (mt/user->id :rasta)+ (let [cards (t2/select :model/Card :id [:in card-ids])+ measure (fn [instances]+ (documents/with-content-gate-cache+ (t2/with-call-count [call-count]+ (doseq [card instances] (mi/can-read? card))+ (call-count))))+ one (measure [(first cards)])+ ten (measure cards)]+ (is (< ten (* 2 one))+ (format "one verdict should serve every card (1 card: %d queries, 10 cards: %d)"+ one ten)))))))))diff --git a/test/metabase/explorations/models/exploration_test.clj b/test/metabase/explorations/models/exploration_test.cljindex 0828f88411f..287b54b77b7 100644--- a/test/metabase/explorations/models/exploration_test.clj+++ b/test/metabase/explorations/models/exploration_test.clj@@ -13,8 +13,11 @@[metabase.search.spec :as search.spec][metabase.search.test-util :as search.tu][metabase.test :as mt]+ [metabase.test.fixtures :as fixtures][toucan2.core :as t2]))+(use-fixtures :once (fixtures/initialize :db :test-users))+(defn- venues-count-query"A `:metric` card's `:dataset_query`: count over the venues table, built with Lib."[]diff --git a/test/metabase/explorations/task/collect_orphaned_results_test.clj b/test/metabase/explorations/task/collect_orphaned_results_test.cljindex f6a19720fcf..561318550ba 100644--- a/test/metabase/explorations/task/collect_orphaned_results_test.clj+++ b/test/metabase/explorations/task/collect_orphaned_results_test.clj@@ -2,6 +2,7 @@(:require[clojure.test :refer :all][java-time.api :as t]+ [metabase.documents.prose-mirror :as prose-mirror][metabase.explorations.task.collect-orphaned-results :as collect][metabase.lib.core :as lib][metabase.lib.metadata :as lib.metadata]@@ -118,3 +119,63 @@(collect/collect-orphaned-results!)(is (false? (t2/exists? :model/StoredResult :id orphan)))(is (zero? (t2/count :model/StoredResultUse :stored_result_id orphan))))))++(defn- summary-embed-card!+ "The ephemeral `report_card` a Summary `cardEmbed` renders through, scoped to an exploration's+ Summary `document`. Returns its id."+ [exploration-id]+ (let [creator (mt/user->id :lucky)+ doc (t2/insert-returning-pk! :model/Document+ {:name "Summary"+ :document {:type "doc" :content []}+ :content_type prose-mirror/prose-mirror-content-type+ :creator_id creator+ :exploration_id exploration-id})]+ (t2/insert-returning-pk! :model/Card+ {:name "embed" :type :question :creator_id creator+ :database_id (mt/id) :dataset_query (venues-count-query)+ :display "table" :visualization_settings {}+ :document_id doc})))++(deftest keeps-composite-blobs-a-summary-card-renders-from-test+ (testing "a composite blob is built by combining source snapshots and has no+ `exploration_query_result` of its own — a Summary `cardEmbed`'s Card is its only+ referent. That reference is durable (unlike an `exploration_id` use row, which+ outlives a restart), so it has to keep the blob alive."+ (let [{:keys [exploration-id]} (exploration-with-query!)+ card (summary-embed-card! exploration-id)+ composite (blob!)]+ (t2/insert! :model/StoredResultUse+ {:stored_result_id composite :card_id card})+ (collect/collect-orphaned-results!)+ (is (true? (t2/exists? :model/StoredResult :id composite))))))++(deftest keeps-single-query-embed-blobs-past-a-restart-test+ (testing "a single-query embed reuses the source snapshot rather than copying it, so after a+ restart drops the `exploration_query_result` the Card use row is all that is left+ standing between the Summary embed and a sweep."+ (let [{:keys [exploration-id query-id]} (exploration-with-query!)+ card (summary-embed-card! exploration-id)+ shared (blob!)]+ (t2/insert! :model/ExplorationQueryResult+ {:exploration_query_id query-id :stored_result_id shared})+ (t2/insert! :model/StoredResultUse+ {:stored_result_id shared :card_id card})+ (t2/delete! :model/ExplorationQuery :id query-id)+ (collect/collect-orphaned-results!)+ (is (true? (t2/exists? :model/StoredResult :id shared))))))++(deftest collects-composite-blobs-once-the-summary-card-is-gone-test+ (testing "deleting the embed's Card cascades its use row away, and with the last referent gone+ the blob becomes collectable — the reference keeps the blob alive, it does not pin it+ forever"+ (let [{:keys [exploration-id]} (exploration-with-query!)+ card (summary-embed-card! exploration-id)+ composite (blob!)]+ (t2/insert! :model/StoredResultUse+ {:stored_result_id composite :card_id card})+ (t2/delete! :model/Card :id card)+ (is (zero? (t2/count :model/StoredResultUse :stored_result_id composite))+ "sanity: the card_id FK cascade takes the use row with the Card")+ (collect/collect-orphaned-results!)+ (is (false? (t2/exists? :model/StoredResult :id composite))))))diff --git a/test/metabase/metabot/tools/resources_test.clj b/test/metabase/metabot/tools/resources_test.cljindex f144c5e782f..8e9e60325e6 100644--- a/test/metabase/metabot/tools/resources_test.clj+++ b/test/metabase/metabot/tools/resources_test.clj@@ -1288,3 +1288,18 @@(is (some? a-root-idx))(is (some? a-child-idx))(is (= (inc a-root-idx) a-child-idx) "child should immediately follow its parent"))))))))++(deftest list-collection-items-excludes-exploration-summary-documents-test+ (testing "metabase://collection/{id}/items hides exploration Summary documents"+ (mt/with-current-user (mt/user->id :crowberto)+ (mt/with-temp [:model/Collection {coll-id :id} {:name "Mixed Coll" :location "/"}+ :model/Document _ {:name "VISIBLE-DOC" :collection_id coll-id}+ :model/Exploration {expl-id :id} {:name "An exploration"}+ :model/Document _ {:name "SUMMARY-DOC"+ :collection_id coll-id+ :exploration_id expl-id}]+ (let [{:keys [output]} (read-resource/read-resource+ {:uris [(str "metabase://collection/" coll-id "/items")]})]+ (is (str/includes? output "VISIBLE-DOC"))+ (is (not (str/includes? output "SUMMARY-DOC"))+ "a Summary document is reachable only through its exploration, so it must not be listed"))))))diff --git a/test/metabase/metabot/tools/save_entity_test.clj b/test/metabase/metabot/tools/save_entity_test.cljindex 079ba019f9a..3f39610e95f 100644--- a/test/metabase/metabot/tools/save_entity_test.clj+++ b/test/metabase/metabot/tools/save_entity_test.clj@@ -169,7 +169,7 @@(defn- card-embed [card-id]{:type "resizeNode"- :content [{:type "cardEmbed" :attrs {:id card-id}}]})+ :content [{:type "cardEmbed" :attrs {:id card-id :_id string?}}]})(deftest save-to-document-test(mt/with-current-user (mt/user->id :crowberto)@@ -185,8 +185,8 @@(is (= (:id coll) (:collection_id card)))(is (= "Venues by price" (:name card))))(testing "omitting position appends a card embed at the end of the document"- (is (= (conj (:content document-ast) (card-embed (:id card)))- (get-in (t2/select-one :model/Document :id (:id doc)) [:document :content]))))+ (is (=? (conj (:content document-ast) (card-embed (:id card)))+ (get-in (t2/select-one :model/Document :id (:id doc)) [:document :content]))))(testing "the destination points at the document"(is (= {:type "document" :id (:id doc)}(get-in result [:data-parts 0 :data :destination])))))))))@@ -198,10 +198,10 @@(let [result (save! {:target_type "document" :document_id (:id doc) :position 1})card-id (get-in result [:structured-output :card-id])](testing "an explicit position inserts before the block at that index"- (is (= [(first (:content document-ast))- (card-embed card-id)- (second (:content document-ast))]- (get-in (t2/select-one :model/Document :id (:id doc)) [:document :content])))))))))+ (is (=? [(first (:content document-ast))+ (card-embed card-id)+ (second (:content document-ast))]+ (get-in (t2/select-one :model/Document :id (:id doc)) [:document :content])))))))))(deftest save-to-document-requires-id-test(mt/with-current-user (mt/user->id :crowberto)diff --git a/test/metabase/queries/models/card_test.clj b/test/metabase/queries/models/card_test.cljindex 6b94f19e605..17ef415dad7 100644--- a/test/metabase/queries/models/card_test.clj+++ b/test/metabase/queries/models/card_test.clj@@ -1745,3 +1745,30 @@(is (= {:metabot_conversation_id convo-id :metabot_chart_id "chart-1"}(t2/select-one [:model/Card :metabot_conversation_id :metabot_chart_id]:id card-id))))))++(deftest serdes-extract-query-excludes-exploration-summary-cards-test+ (testing "serdes never extracts a Card scoped to an exploration Summary document"+ (mt/with-temp [:model/Collection {coll-id :id} {}+ :model/User {user-id :id} {:email "[email protected]"}+ :model/Exploration {expl-id :id} {:name "Explo" :creator_id user-id}+ :model/Document {summary-id :id} {:name "Summary"+ :creator_id user-id+ :collection_id coll-id+ :exploration_id expl-id}+ :model/Document {plain-doc :id} {:name "Plain doc" :creator_id user-id+ :collection_id coll-id}+ :model/Card {plain-card :id} {:collection_id coll-id}+ :model/Card {doc-card :id} {:collection_id coll-id :document_id plain-doc}+ :model/Card {summary-card :id} {:collection_id coll-id :document_id summary-id+ :name "Orders for Customer = ACME Corp over time"}]+ (let [eid #(t2/select-one-fn :entity_id :model/Card :id %)+ extracted (into #{}+ (map :entity_id)+ (serdes/extract-all "Card" {:where [:in :id [plain-card doc-card summary-card]]}))]+ (is (contains? extracted (eid plain-card))+ "an ordinary card is still exported")+ (is (contains? extracted (eid doc-card))+ "a card belonging to an ordinary document still travels with that document")+ (is (not (contains? extracted (eid summary-card)))+ "a card belonging to an exploration Summary is never exported — its name and dataset_query+ carry values discovered under the creator's lens, and its parent document is excluded")))))diff --git a/test/metabase/queries/models/stored_result_use_test.clj b/test/metabase/queries/models/stored_result_use_test.cljindex f824803a2cd..d3cc61eb8a9 100644--- a/test/metabase/queries/models/stored_result_use_test.clj+++ b/test/metabase/queries/models/stored_result_use_test.clj@@ -3,6 +3,8 @@[clojure.test :refer :all][metabase.lib.core :as lib][metabase.lib.metadata :as lib.metadata]+ [metabase.queries.core :as queries]+ [metabase.request.core :as request][metabase.test :as mt][toucan2.core :as t2]))@@ -13,16 +15,133 @@:database_id (mt/id):dataset_query (lib/query mp (lib.metadata/table mp (mt/id :venues)))}))))-(deftest exploration-reference-required-test- (testing "stored_result_use requires :exploration_id"- (mt/with-temp [:model/User u {}+(deftest exactly-one-reference-required-test+ (testing "stored_result_use requires exactly one of :card_id / :exploration_id"+ (mt/with-temp [:model/User u {}+ :model/Collection coll {}+ :model/Card card {:collection_id (:id coll)}:model/Exploration expl {:name "sru-test" :creator_id (:id u)}](let [sr-id (stored-result!)]- (testing "exploration_id succeeds"+ (testing "card_id only succeeds"(let [id (first (t2/insert-returning-pks! :model/StoredResultUse- {:stored_result_id sr-id :exploration_id (:id expl)}))]- (is (=? {:exploration_id (:id expl)}+ {:stored_result_id sr-id :card_id (:id card)}))]+ (is (=? {:card_id (:id card) :exploration_id nil}(t2/select-one :model/StoredResultUse :id id)))))- (testing "missing exploration_id is rejected"+ (testing "neither set is rejected"+ (is (thrown? Exception+ (t2/insert! :model/StoredResultUse {:stored_result_id sr-id}))))+ (testing "both set is rejected"(is (thrown? Exception- (t2/insert! :model/StoredResultUse {:stored_result_id sr-id}))))))))+ (t2/insert! :model/StoredResultUse+ {:stored_result_id sr-id+ :card_id (:id card)+ :exploration_id (:id expl)}))))))))++(deftest exploration-reference-test+ (testing "exploration_id only succeeds"+ (mt/with-temp [:model/User u {}+ :model/Exploration expl {:name "sru-test" :creator_id (:id u)}]+ (let [sr-id (stored-result!)+ id (first (t2/insert-returning-pks! :model/StoredResultUse+ {:stored_result_id sr-id :exploration_id (:id expl)}))]+ (is (=? {:card_id nil :exploration_id (:id expl)}+ (t2/select-one :model/StoredResultUse :id id)))))))++(deftest carry-pairings-for-document-test+ (testing "carry-pairings-for-document! copies a pairing only when the snapshot is already reachable through the document"+ (let [mp (mt/metadata-provider)+ venues-query (lib/query mp (lib.metadata/table mp (mt/id :venues)))]+ (mt/with-temp [:model/Collection coll {}+ :model/Document doc {:name "Summary"+ :document {:type "doc" :content []}+ :content_type "application/json+vnd.prose-mirror"+ :collection_id (:id coll)}+ :model/Document other-doc {:name "Other"+ :document {:type "doc" :content []}+ :content_type "application/json+vnd.prose-mirror"+ :collection_id (:id coll)}+ :model/Card owned {:name "owned"+ :dataset_query venues-query+ :display :table+ :document_id (:id doc)+ :collection_id (:id coll)}+ :model/Card new-card {:name "replacement"+ :dataset_query venues-query+ :display :table+ :document_id (:id doc)+ :collection_id (:id coll)}+ :model/Card hostile-card {:name "hostile"+ :dataset_query venues-query+ :display :table+ :document_id (:id other-doc)+ :collection_id (:id coll)}]+ (let [sr-id (stored-result!)]+ (t2/insert! :model/StoredResultUse {:stored_result_id sr-id :card_id (:id owned)})+ (testing "carries when the snapshot is already paired with a card in this document"+ (queries/carry-pairings-for-document! (:id doc) [[(:id new-card) sr-id]])+ (is (some? (t2/select-one :model/StoredResultUse+ :stored_result_id sr-id+ :card_id (:id new-card)))+ "new card inherits the (document, snapshot) reachability"))+ (testing "refuses when the snapshot is not reachable through the target document"+ (let [before (t2/count :model/StoredResultUse :card_id (:id hostile-card))]+ (queries/carry-pairings-for-document! (:id other-doc) [[(:id hostile-card) sr-id]])+ (is (= before (t2/count :model/StoredResultUse :card_id (:id hostile-card)))+ "hostile document cannot widen reachability to a foreign snapshot"))))))))++;;; ------------------------------ the cached-read gate over a Card ------------------------------++(defn- venues-count-query+ "A count over venues. Built with Lib rather than `mt/mbql-query`, which is deprecated for new+ tests in favour of generating MBQL through Lib."+ []+ (let [mp (mt/metadata-provider)]+ (lib/->legacy-MBQL (-> (lib/query mp (lib.metadata/table mp (mt/id :venues)))+ (lib/aggregate (lib/count))))))++(defn- snapshot-with-token!+ "A StoredResult over venues carrying `token` as its `data_access_token`."+ [token]+ (let [q (venues-count-query)]+ (first (t2/insert-returning-pks! :model/StoredResult+ {:result_data (byte-array [1 2 3])+ :creator_id (mt/user->id :rasta)+ :database_id (mt/id)+ :dataset_query q+ :row_count 1+ :data_access_token token}))))++(defn- gate-verdict! [card-id user-kw]+ (request/with-current-user (mt/user->id user-kw)+ (try+ (queries/assert-can-view-card-snapshots! card-id)+ :allowed+ (catch clojure.lang.ExceptionInfo e+ [:denied (:reason (ex-data e))]))))++(deftest assert-can-view-card-snapshots-gates-every-source-test+ (mt/with-temp [:model/Collection coll {}+ :model/Card card {:collection_id (:id coll)+ :dataset_query (venues-count-query)}]+ (let [viewable (snapshot-with-token! {})+ unviewable (snapshot-with-token! nil)]+ (t2/insert! :model/StoredResultUse {:stored_result_id viewable :card_id (:id card)})+ (testing "a card whose only snapshot is viewable is served"+ (is (= :allowed (gate-verdict! (:id card) :rasta))))+ (t2/insert! :model/StoredResultUse {:stored_result_id unviewable :card_id (:id card)})+ (testing "adding a source the viewer may not see denies the whole card — a composite blob draws its+ rows from every paired snapshot, not just the one named in the request"+ (is (= [:denied :incompatible-context] (gate-verdict! (:id card) :rasta))))+ (testing "the snapshot's own creator is gated too — creating it is not a permanent pass"+ (is (= (mt/user->id :rasta)+ (t2/select-one-fn :creator_id :model/StoredResult :id unviewable)))+ (is (= [:denied :incompatible-context] (gate-verdict! (:id card) :rasta))))+ (testing "superusers pass, by the standing product exemption"+ (is (= :allowed (gate-verdict! (:id card) :crowberto)))))))++(deftest assert-can-view-card-snapshots-404s-when-nothing-is-paired-test+ (mt/with-temp [:model/Collection coll {}+ :model/Card card {:collection_id (:id coll)+ :dataset_query (venues-count-query)}]+ (is (= [:denied nil] (gate-verdict! (:id card) :rasta))+ "a card with no paired snapshots has no cached result to serve")))diff --git a/test/metabase/queries_rest/api/card_test.clj b/test/metabase/queries_rest/api/card_test.cljindex c540dd9aa48..f1738c26e49 100644--- a/test/metabase/queries_rest/api/card_test.clj+++ b/test/metabase/queries_rest/api/card_test.clj@@ -36,6 +36,7 @@[metabase.queries.models.card.metadata :as card.metadata][metabase.query-processor.card :as qp.card][metabase.query-processor.compile :as qp.compile]+ [metabase.query-processor.core :as qp][metabase.query-processor.middleware.constraints :as qp.constraints][metabase.query-processor.pivot.test-util :as api.pivots][metabase.revisions.models.revision :as revision]@@ -201,6 +202,88 @@:target [:variable [:template-tag :category]]:value 2}]})))))))+(defn- venues-count-query+ "A count over venues. Built with Lib rather than `mt/mbql-query`, which is deprecated for new+ tests in favour of generating MBQL through Lib."+ []+ (let [mp (mt/metadata-provider)]+ (lib/->legacy-MBQL (-> (lib/query mp (lib.metadata/table mp (mt/id :venues)))+ (lib/aggregate (lib/count))))))++(deftest ^:parallel card-query-cached-stored-result-pairing-test+ (testing "POST /api/card/:card-id/query with `stored_result_id`"+ (let [result-bytes (qp/do-with-serialization+ (fn [in result-fn]+ (in {:data {:cols [{:name "count"}] :rows [[7]]} :row_count 1 :status :completed})+ (result-fn)))+ count-query (venues-count-query)]+ (mt/with-temp [:model/Card card {:dataset_query count-query}+ :model/Card other-card {:dataset_query count-query}+ :model/StoredResult sr {:result_data result-bytes+ :creator_id (mt/user->id :crowberto)+ :database_id (mt/id)+ :dataset_query count-query+ :data_access_token {}}+ :model/StoredResultUse _ {:stored_result_id (:id sr) :card_id (:id card)}]+ (testing "serves the cached snapshot when the (card, stored_result) pairing exists in stored_result_use"+ (is (=? {:status "completed"+ :row_count 1+ :data {:rows [[7]]}}+ (mt/user-http-request :rasta :post 200 (format "card/%d/query" (:id card))+ {:stored_result_id (:id sr)}))))+ (testing "404s when the stored result is not paired with the read-checked card — a readable card must+ not serve as a skeleton key for arbitrary snapshot ids"+ (is (= "Not found."+ (mt/user-http-request :rasta :post 404 (format "card/%d/query" (:id other-card))+ {:stored_result_id (:id sr)}))))+ (testing "404s for a nonexistent stored result id"+ (is (= "Not found."+ (mt/user-http-request :rasta :post 404 (format "card/%d/query" (:id card))+ {:stored_result_id Integer/MAX_VALUE}))))))))++(deftest ^:parallel card-query-cached-stored-result-gates-the-creator-too-test+ (testing "POST /api/card/:card-id/query applies the cached-read gate to the snapshot's own creator —+ having created a snapshot is not a permanent pass to it, since the creator's own permissions+ may have narrowed since it was taken"+ (let [result-bytes (qp/do-with-serialization+ (fn [in result-fn]+ (in {:data {:cols [{:name "count"}] :rows [[7]]} :row_count 1 :status :completed})+ (result-fn)))+ count-query (venues-count-query)]+ (mt/with-temp [:model/Card card {:dataset_query count-query}+ ;; A nil token is what the gate treats as "lens unknowable" and denies.+ :model/StoredResult sr {:result_data result-bytes+ :creator_id (mt/user->id :rasta)+ :database_id (mt/id)+ :dataset_query count-query+ :data_access_token nil}+ :model/StoredResultUse _ {:stored_result_id (:id sr) :card_id (:id card)}]+ (is (mt/user-http-request :rasta :post 403 (format "card/%d/query" (:id card))+ {:stored_result_id (:id sr)})+ "the creator is gated like any other viewer")))))++(deftest ^:parallel card-query-cached-stored-result-gates-every-paired-snapshot-test+ (testing "POST /api/card/:card-id/query gates every snapshot the card renders from, not just the requested one —+ a composite blob draws its rows from all of them, while describing itself with only the first source's+ query and lens"+ (let [result-bytes (qp/do-with-serialization+ (fn [in result-fn]+ (in {:data {:cols [{:name "count"}] :rows [[7]]} :row_count 1 :status :completed})+ (result-fn)))+ count-query (venues-count-query)+ snapshot {:result_data result-bytes+ :creator_id (mt/user->id :crowberto)+ :database_id (mt/id)+ :dataset_query count-query+ :data_access_token {}}]+ (mt/with-temp [:model/Card card {:dataset_query count-query}+ :model/StoredResult composite snapshot+ :model/StoredResult source (assoc snapshot :data_access_token nil)+ :model/StoredResultUse _ {:stored_result_id (:id composite) :card_id (:id card)}+ :model/StoredResultUse _ {:stored_result_id (:id source) :card_id (:id card)}]+ (is (mt/user-http-request :rasta :post 403 (format "card/%d/query" (:id card))+ {:stored_result_id (:id composite)})+ "denied because one of the card's source snapshots is not viewable, even though the requested row is")))))(deftest dashboard-and-collection-context-metric-query-uses-default-dimension-test(testing "POST card query endpoints use collection-specific metric dimension fallbacks (UXW-4769, UXW-4771, UXW-4958)"(mt/dataset test-data@@ -583,7 +666,6 @@:model/Card scalar-2 (merge (mt/card-with-source-metadata-for-query(mt/mbql-query venues {:aggregation [[:count]]})){:name "A Scalar 2" :display :scalar})-:model/Card native (merge (mt/card-with-source-metadata-for-query (mt/native-query {:query "select sum(price) from venues;"})){:name "A Native query":display :scalar@@ -592,7 +674,6 @@:model/Card metric-2 (merge (mt/card-with-source-metadata-for-query(mt/mbql-query venues {:aggregation [[:sum $venues.price]]})){:name "Another Metric" :type :metric :display :scalar})-;; compatible but user doesn't have access so should not be readble:model/Card _ (simple-mbql-chart-query {:name "A Line with no access" :display :line});; incomptabile cards@@ -740,7 +821,6 @@:model/Card scalar-2 (merge (mt/card-with-source-metadata-for-query(mt/mbql-query venues {:aggregation [[:count]]})){:name "A Scalar 2" :display :scalar})-:model/Card scalar-2-cols (merge (mt/card-with-source-metadata-for-query(mt/mbql-query venues {:aggregation [[:count][:sum $venues.price]]}))@@ -4965,7 +5045,6 @@:model "root":strategy "ttl":config {:multiplier 99999, :min_duration_ms 1}}-:model/Cardmodel{:type :modeldiff --git a/test/metabase/search/appdb/index_test.clj b/test/metabase/search/appdb/index_test.cljindex db6b99cd207..71f58ddefed 100644--- a/test/metabase/search/appdb/index_test.clj+++ b/test/metabase/search/appdb/index_test.clj@@ -542,6 +542,7 @@"metabase_database" #{"action" "measure" "metabase_table" "model_index_value" "report_card" "segment"}"metabase_table" #{"action" "measure" "model_index_value" "report_card" "segment"}"document" #{"action" "model_index_value" "report_card"}+ "exploration" #{"action" "document" "model_index_value" "report_card"}"report_card" #{"action" "model_index_value"}"report_dashboard" #{"action" "model_index_value" "report_card"}})diff --git a/test/metabase/search/filter_test.clj b/test/metabase/search/filter_test.cljindex a497a47f3fa..5e803dd5bf6 100644--- a/test/metabase/search/filter_test.clj+++ b/test/metabase/search/filter_test.clj@@ -108,14 +108,16 @@:where[:and[:= 1 2]- [:or [:= nil :search_index.dashboard_id] nil]]}+ [:or [:= nil :search_index.dashboard_id] nil]+ [:= nil :search_index.exploration_id]]}(search.filter/with-filters {:models []} {:select [:some :stuff], :from :somewhere})))(is (= {:select [:some :stuff],:from :somewhere,:where[:and[:in :search_index.model ["a"]]- [:or [:= nil :search_index.dashboard_id] nil]]}+ [:or [:= nil :search_index.dashboard_id] nil]+ [:= nil :search_index.exploration_id]]}(search.filter/with-filters {:models ["a"]} {:select [:some :stuff], :from :somewhere}))))(testing "We can insert appropriate constraints for all the filters"(is (= {:select [:some :stuff],@@ -131,6 +133,7 @@[:or[:= nil :search_index.dashboard_id][:not= [:inline 0] [:coalesce :search_index.dashboardcard_count [:inline 0]]]]+ [:= nil :search_index.exploration_id][:in:search_index.model#{"dashboard"diff --git a/test/metabase/sql_tools/core_test.clj b/test/metabase/sql_tools/core_test.cljindex e09473f9452..5f168d5090a 100644--- a/test/metabase/sql_tools/core_test.clj+++ b/test/metabase/sql_tools/core_test.clj@@ -68,8 +68,10 @@(sql-tools.tu/test-parser-backends(mt/test-driver :h2(let [catalog-fetches (atom 0)- all-tables lib.metadata/tables]- (with-redefs [lib.metadata/tables (fn [mp] (swap! catalog-fetches inc) (all-tables mp))]+ ;; capture via `original-fn`: once the var is proxied, a bare symbol ref resolves to the+ ;; proxy and delegating to it would recurse forever.+ all-tables (mt/original-fn #'lib.metadata/tables)]+ (mt/with-dynamic-fn-redefs [lib.metadata/tables (fn [mp] (swap! catalog-fetches inc) (all-tables mp))](testing "the referenced table still resolves";; H2 stores table names upper-cased while the query spells them lower-case, so this also covers the;; case-folding that makes an exact name match unusable (the same mismatch Snowflake has).