Skip to content

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

Add timeline events to dashboards (#80119)

Uladzimir Havenchyk3e848259f897
diff --git a/.clj-kondo/config/modules/config.edn b/.clj-kondo/config/modules/config.edn
index 48f5dd47a30..7e418f9790c 100644
--- a/.clj-kondo/config/modules/config.edn
+++ b/.clj-kondo/config/modules/config.edn
@@ -798,6 +798,7 @@
settings
staleness
sync
+ timeline
util
util.config}
:model-exports #{:model/Dashboard
@@ -2050,7 +2051,9 @@
:model/Card
:model/Dashboard
:model/DashboardCard
- :model/Document}}
+ :model/Document
+ :model/Timeline
+ :model/TimelineEvent}}
pulse
{:team "Gadget"
@@ -2161,6 +2164,7 @@
:model/NativeQuerySnippet
:model/Notification
:model/Revision
+ :model/Timeline
:model/User}}
queries.rest
@@ -2912,8 +2916,7 @@
timeline
{:team "UX West"
- :api #{metabase.timeline.api
- metabase.timeline.core}
+ :api #{metabase.timeline.api metabase.timeline.core metabase.timeline.schema}
:uses #{analytics
api
api-scope
diff --git a/.clj-kondo/ratchets.edn b/.clj-kondo/ratchets.edn
index 29983c5b4a7..96b2f42912e 100644
--- a/.clj-kondo/ratchets.edn
+++ b/.clj-kondo/ratchets.edn
@@ -25,7 +25,7 @@
:discouraged-java-method 4
:duplicate-require 1
:main-without-gen-class 1
- :metabase/discourage-dynamic-vars 323
+ :metabase/discourage-dynamic-vars 324
:metabase/discourage-millis-duration 1
:metabase/modules 23
:metabase/namespace-name 3
diff --git a/docs/exploration-and-organization/events-and-timelines.md b/docs/exploration-and-organization/events-and-timelines.md
index 921ad0824f7..63c54909d33 100644
--- a/docs/exploration-and-organization/events-and-timelines.md
+++ b/docs/exploration-and-organization/events-and-timelines.md
@@ -16,7 +16,9 @@ Events and timelines are a way to capture that chronological knowledge and make
An event is basically a date + a title + a description + an icon. You can add events to Metabase to show important milestones, launches, or anything else, right alongside your data.
-Metabase will only display events on time series charts when viewing an individual question. Metabase won't display events on charts in dashboard cards.
+Metabase displays events on time series charts when viewing an individual question, and on dashboards for questions that were saved with events turned on.
+
+Dashboards shared via a public link, static embed, interactive embedding, or the embedded analytics SDK show the events each question was saved with. Public and statically embedded questions, SDK questions, and dashboard subscriptions don't show events. Public links and static embeds show a question's saved events to anyone viewing the dashboard, even people who can't access the timeline's collection. Only people who can view a timeline can add a question that uses it to a shared dashboard. In interactive embedding and the SDK, people only see events from timelines they have access to.
## Timelines
@@ -26,7 +28,7 @@ Timelines are groups of events associated with a [collection](collections.md).
For example, you may want to have a timeline that contains important email or sales dates, or an outages timeline that tracks downtime. You can move events between timelines, and move timelines from collection to collection.
-Collections can have timelines, and timelines can contain events. In practice what this means is that events you've added to a timeline will show up on time series questions stored in the same collection as that timeline.
+Collections can have timelines, and timelines can contain events. In practice what this means is that events you've added to a timeline will show up by default on new or unsaved time series questions in the same collection as that timeline. A saved question shows only the timelines and events it was saved with.
- If you don't explicitly create a timeline yet, but you do create events, Metabase will automatically create a timeline for you (which acts as the default timeline for the collection).
- You can have multiple timelines for the same collection.
@@ -43,6 +45,8 @@ Once you create an event, the event will show up in charts in the collection, pr
- The date of the event falls within the chart's time range.
- The timeline is visible (more on that [below](#adding-events-when-viewing-a-question)).
+A timeline you create later won't appear on an already-saved question until you turn it on and save the question again.
+
You'll see an icon along the x-axis that plots the event. A vertical line will extend from the event to show when the data plotted on the chart intersects with the event.
![An event on a chart](./images/example-event.png)
@@ -57,11 +61,29 @@ If your question is a time series, you can click on the **Calendar** in the bott
- Add a new event (even if you haven't saved the question yet).
- Edit, move, or archive an event.
+When you save a new question or change a question's event selection and save it, Metabase records which timelines and events are turned on, and shows those same events wherever the question appears, including on dashboards. Toggling events on a saved question counts as a change, so save the question to keep your selection.
+
+## Events on dashboards
+
+A time series chart on a dashboard shows the events its question was saved with. Questions saved with events turned off (or saved before Metabase started recording events) don't show any events on dashboards. Very small cards don't have room for events, so they won't show them even when a timeline is on, and their **three-dot menu** (**...**) leaves out the **Events** item.
+
+To change which events a chart shows while viewing a dashboard, click on the **three-dot menu** (**...**) on the card and select **Events**. Metabase will open the same events sidebar you get on a question, listing every timeline you can view that has an event in the range of that chart, whatever collection the timeline lives in. You can:
+
+- Toggle a timeline or an event on or off for that card.
+- Add a new event, if you have curate access to the dashboard's collection. You can choose a timeline whose collection you can curate. If there are no available timelines, Metabase creates one in the dashboard's collection.
+- Edit, move, or archive an event, if you have curate access to the collection that holds the event's timeline.
+
+To toggle events for every time series chart on the current tab at once, click on the **three-dot menu** (**...**) in the dashboard header and select **Events**. If some cards show an event and others don't, its checkbox shows a dash. Clicking it applies your choice to every card.
+
+These selections only last for your session; if you reload the dashboard or enter edit mode, each chart goes back to the events its question was saved with. To change what everyone sees, open the question, toggle its events, and save it.
+
+Exporting a dashboard to PDF captures the page as you're viewing it, so the PDF includes whatever events are showing at the time, session toggles and all. Results downloaded as .csv or .xlsx contain data only, and the chart images in dashboard subscriptions don't show events.
+
## Viewing events and timelines on a chart from a different collection
If you're viewing a question with a time series chart from a _different_ collection, you can temporarily apply a timeline to the chart by clicking on the **calendar** icon in the bottom right of the question and selecting the timeline and events you want to display.
-These selections are temporary; if you reload the question, Metabase will drop the events from the chart.
+If you save the question, Metabase keeps the timelines and events you turned on and shows them wherever the question appears.
### To hide the timeline and its events on a chart
@@ -70,9 +92,9 @@ To temporarily hide the events from a chart:
1. Click on the **calendar** icon in the bottom right.
2. Uncheck the timeline or event.
-Your selections will reset on reload.
+Your selections reset on reload unless you save the question.
-To permanently hide the timeline and its events, you'll need to [archive the timeline](#archiving-timelines). Alternatively, you could move the question to a different collection.
+To keep events hidden on this question, save the question after unchecking them. To hide a timeline and its events everywhere, [archive the timeline](#archiving-timelines).
## Edit an event
@@ -117,12 +139,13 @@ Event and timeline permissions depend on your [collection permissions](../permis
- **View access**: you can view the collection's events and timelines. You can also temporarily apply timelines and events to time series in other collections.
- **Curate access**. Anyone with curate access to a collection can add events and timelines to that collection.
+- **Saving a question's events**: you need view access to a timeline to turn it on or show one of its hidden events. You can keep existing selections for timelines you can no longer view. If you switch a question to a chart type that displays events, you need view access to every timeline it has turned on.
### Make a timeline and its events available for everyone
If you want the event and timeline to be available to everyone, create the timeline in a collection that the [All Users group](../people-and-groups/managing.md#all-users) has access to, as by default everyone is in the All Users group.
-Note that for questions outside of that collection, you can only temporarily apply those timelines to charts. The timelines won't appear automatically when you reload the chart.
+For questions outside of that collection, save the question after applying a timeline if you want the timeline to remain visible after reload and wherever the question appears.
## Further reading
diff --git a/e2e/support/helpers/api/createTimelineEvent.ts b/e2e/support/helpers/api/createTimelineEvent.ts
index 1270b18c879..b311e497fa9 100644
--- a/e2e/support/helpers/api/createTimelineEvent.ts
+++ b/e2e/support/helpers/api/createTimelineEvent.ts
@@ -3,6 +3,10 @@ import type {
TimelineEvent,
} from "metabase-types/api";
+/** Everything the API takes, with defaults filled in by this helper — a test only has to name the timeline. */
+export type TimelineEventDetails = Partial<CreateTimelineEventRequest> &
+ Pick<CreateTimelineEventRequest, "timeline_id">;
+
export const createTimelineEvent = ({
name = "Event",
icon = "star",
@@ -11,7 +15,7 @@ export const createTimelineEvent = ({
timezone = "UTC",
archived = false,
...params
-}: CreateTimelineEventRequest): Cypress.Chainable<
+}: TimelineEventDetails): Cypress.Chainable<
Cypress.Response<TimelineEvent>
> => {
return cy.request("POST", "/api/timeline-event", {
diff --git a/e2e/support/helpers/api/createTimelineWithEvents.ts b/e2e/support/helpers/api/createTimelineWithEvents.ts
index 75bd64285b0..ec01c23b904 100644
--- a/e2e/support/helpers/api/createTimelineWithEvents.ts
+++ b/e2e/support/helpers/api/createTimelineWithEvents.ts
@@ -1,5 +1,4 @@
import type {
- CreateTimelineEventRequest,
CreateTimelineRequest,
Timeline,
TimelineEvent,
@@ -8,28 +7,30 @@ import type {
import { cypressWaitAll } from "../e2e-misc-helpers";
import { createTimeline } from "./createTimeline";
-import { createTimelineEvent } from "./createTimelineEvent";
+import {
+ type TimelineEventDetails,
+ createTimelineEvent,
+} from "./createTimelineEvent";
export const createTimelineWithEvents = ({
timeline,
events,
}: {
timeline: CreateTimelineRequest;
- events: Omit<CreateTimelineEventRequest, "timeline_id">[];
-}): {
+ events: Omit<TimelineEventDetails, "timeline_id">[];
+}): Cypress.Chainable<{
timeline: Timeline;
events: TimelineEvent[];
-} => {
- // @ts-expect-error - Cypress typings don't account for what happens in then() here
+}> => {
return createTimeline(timeline).then(({ body: timeline }) => {
return cypressWaitAll(
events.map((query) =>
createTimelineEvent({ ...query, timeline_id: timeline.id }),
),
- ).then((events) => {
+ ).then((responses) => {
return {
timeline,
- events,
+ events: responses.map(({ body }) => body),
};
});
});
diff --git a/e2e/support/helpers/api/index.ts b/e2e/support/helpers/api/index.ts
index 714a81d813f..a6df914f948 100644
--- a/e2e/support/helpers/api/index.ts
+++ b/e2e/support/helpers/api/index.ts
@@ -32,6 +32,7 @@ export { createSnippetFolder } from "./createSnippetFolder";
export { createTestNativeQuery, createTestQuery } from "./createTestQuery";
export { createTimeline } from "./createTimeline";
export { createTimelineEvent } from "./createTimelineEvent";
+export type { TimelineEventDetails } from "./createTimelineEvent";
export { createTimelineWithEvents } from "./createTimelineWithEvents";
export { createTransform } from "./createTransform";
export { createTransformJob } from "./createTransformJob";
diff --git a/e2e/support/helpers/e2e-timelines-helpers.js b/e2e/support/helpers/e2e-timelines-helpers.js
new file mode 100644
index 00000000000..b9c0019fe2e
--- /dev/null
+++ b/e2e/support/helpers/e2e-timelines-helpers.js
@@ -0,0 +1,24 @@
+export function timelineEventCard(eventName) {
+ return cy.findByText(eventName).closest("[aria-label='Timeline event card']");
+}
+
+export function timelineEventVisibility(eventName) {
+ return timelineEventCard(eventName).findByRole("checkbox");
+}
+
+export function toggleTimelineEventVisibility(eventName) {
+ return timelineEventVisibility(eventName).click();
+}
+
+export function timelineVisibility(timelineName) {
+ return cy
+ .findByText(timelineName)
+ .closest("[aria-label='Timeline card header']")
+ .findByRole("checkbox");
+}
+
+export function waitForTimelinesAfterCreatingAnEvent(eventName) {
+ return timelineEventCard(eventName)
+ .findByText(/^Bobby Tables added this on/)
+ .should("be.visible");
+}
diff --git a/e2e/support/helpers/index.ts b/e2e/support/helpers/index.ts
index 6ff53d5763b..6c3b5d2f048 100644
--- a/e2e/support/helpers/index.ts
+++ b/e2e/support/helpers/index.ts
@@ -67,6 +67,7 @@ export * from "./e2e-ui-elements-overflow-helpers";
export * from "./e2e-ui-select";
export * from "./e2e-upload-helpers";
export * from "./e2e-users-helpers";
+export * from "./e2e-timelines-helpers";
export * from "./e2e-visual-tests-helpers";
export * from "./e2e-viz-settings-helpers";
export * from "./embedding-sdk-helpers/constants";
diff --git a/e2e/test-component/scenarios/embedding-sdk/timeline-events.cy.spec.tsx b/e2e/test-component/scenarios/embedding-sdk/timeline-events.cy.spec.tsx
new file mode 100644
index 00000000000..351140480fc
--- /dev/null
+++ b/e2e/test-component/scenarios/embedding-sdk/timeline-events.cy.spec.tsx
@@ -0,0 +1,91 @@
+import {
+ EditableDashboard,
+ InteractiveDashboard,
+ InteractiveQuestion,
+ StaticDashboard,
+ StaticQuestion,
+} from "@metabase/embedding-sdk-react";
+
+import { getSdkRoot } from "e2e/support/helpers/e2e-embedding-sdk-helpers";
+import { mountSdkContent } from "e2e/support/helpers/embedding-sdk-component-testing/component-embedding-sdk-helpers";
+import { signInAsAdminAndEnableEmbeddingSdk } from "e2e/support/helpers/embedding-sdk-testing";
+import { mockAuthProviderAndJwtSignIn } from "e2e/support/helpers/embedding-sdk-testing/embedding-sdk-helpers";
+import {
+ createQuestionAndDashboardWithEvents,
+ expectChartWithoutEvents,
+ expectReadOnlyDashboardEvents,
+} from "e2e/test/scenarios/organization/shared/timeline-events";
+
+const { H } = cy;
+
+describe("scenarios > embedding-sdk > timeline events", () => {
+ beforeEach(() => {
+ signInAsAdminAndEnableEmbeddingSdk();
+ createQuestionAndDashboardWithEvents();
+ cy.signOut();
+
+ mockAuthProviderAndJwtSignIn();
+ });
+
+ [
+ { name: "InteractiveQuestion", component: InteractiveQuestion },
+ { name: "StaticQuestion", component: StaticQuestion },
+ ].forEach(({ name, component: QuestionComponent }) => {
+ it(`should not show events on ${name}`, () => {
+ cy.get<number>("@questionId").then((questionId) => {
+ mountSdkContent(<QuestionComponent questionId={questionId} />);
+ });
+
+ getSdkRoot().within(() => expectChartWithoutEvents());
+ });
+ });
+
+ [
+ { name: "InteractiveDashboard", component: InteractiveDashboard },
+ { name: "StaticDashboard", component: StaticDashboard },
+ { name: "EditableDashboard", component: EditableDashboard },
+ ].forEach(({ name, component: DashboardComponent }) => {
+ it(`should show only saved events read-only on ${name}`, () => {
+ cy.get<number>("@dashboardId").then((dashboardId) => {
+ mountSdkContent(
+ <DashboardComponent dashboardId={dashboardId} withDownloads />,
+ );
+ });
+
+ cy.wait("@getTimelines");
+ getSdkRoot().within(() => {
+ expectReadOnlyDashboardEvents();
+
+ cy.log("the dashcard menu does not offer to open the events panel");
+ H.getDashboardCard().realHover();
+ H.getDashboardCard()
+ .findByRole("button", { name: "More options" })
+ .click();
+ });
+ H.menu().should("be.visible").findByText("Events").should("not.exist");
+ });
+ });
+
+ it("should keep saved events read-only while editing a dashboard", () => {
+ cy.get<number>("@dashboardId").then((dashboardId) => {
+ mountSdkContent(<EditableDashboard dashboardId={dashboardId} />);
+ });
+
+ cy.wait("@getTimelines");
+ getSdkRoot().within(() => {
+ cy.findByRole("button", { name: "Edit dashboard" }).click();
+ cy.findByRole("button", { name: "Add questions" }).should("be.visible");
+ H.timelineEventChip("RC1").should("be.visible");
+ H.timelineEventChip("Internal release notes").should("not.exist");
+
+ cy.log("edit mode offers no events panel or Events button");
+ cy.findByTestId("dashboard-events-sidebar").should("not.exist");
+ cy.findByRole("button", { name: "Events", exact: true }).should(
+ "not.exist",
+ );
+ });
+
+ cy.log("editing the dashboard never changes timeline events");
+ cy.get("@mutateTimelineEvents.all").should("have.length", 0);
+ });
+});
diff --git a/e2e/test/scenarios/documents/documents.cy.spec.ts b/e2e/test/scenarios/documents/documents.cy.spec.ts
index 1dde0947335..c0c1e5d0553 100644
--- a/e2e/test/scenarios/documents/documents.cy.spec.ts
+++ b/e2e/test/scenarios/documents/documents.cy.spec.ts
@@ -1,3 +1,4 @@
+import { USER_GROUPS } from "e2e/support/cypress_data";
import {
NO_SQL_PERSONAL_COLLECTION_ID,
ORDERS_BY_YEAR_QUESTION_ID,
@@ -16,10 +17,17 @@ import {
PRODUCTS_AVERAGE_BY_CATEGORY,
PRODUCTS_COUNT_BY_CATEGORY_PIE,
} from "e2e/support/test-visualization-data";
-import type { Document } from "metabase-types/api";
+import type {
+ CollectionId,
+ CollectionPermission,
+ CollectionPermissions,
+ Document,
+} from "metabase-types/api";
const { H } = cy;
+const { ALL_USERS_GROUP, COLLECTION_GROUP, DATA_GROUP } = USER_GROUPS;
+
describe("documents", () => {
beforeEach(() => {
H.restore();
@@ -2008,9 +2016,85 @@ describe("documents", () => {
TIMELINE_EVENT_NAME,
).should("not.exist");
});
+
+ it("should save a document after editing the visualization of an embed whose timeline the user cannot read", () => {
+ H.createCollection({ name: "Private" }).then(
+ ({ body: { id: collectionId } }) => {
+ H.createTimelineWithEvents({
+ timeline: { name: TIMELINE_NAME, collection_id: collectionId },
+ events: [
+ {
+ name: TIMELINE_EVENT_NAME,
+ timestamp: "2026-06-01T00:00:00Z",
+ icon: "star",
+ timezone: "UTC",
+ },
+ ],
+ }).then(({ timeline }) => {
+ cy.updateCollectionGraph(denyCollection(collectionId));
+ H.createQuestion({
+ ...ORDERS_COUNT_BY_CREATED_AT,
+ visualization_settings: {
+ ...ORDERS_COUNT_BY_CREATED_AT.visualization_settings,
+ "timeline.selected_timeline_ids": [timeline.id],
+ },
+ }).then(({ body: { id: questionId } }) => {
+ cy.signInAsNormalUser();
+ H.createDocument({
+ name: "Private timeline document",
+ document: {
+ type: "doc",
+ content: [
+ {
+ type: "resizeNode",
+ attrs: { height: 350, minHeight: 280, _id: "1" },
+ content: [
+ {
+ type: "cardEmbed",
+ attrs: { id: questionId, name: null, _id: "1a" },
+ },
+ ],
+ },
+ { type: "paragraph", attrs: { _id: "2" } },
+ ],
+ },
+ collection_id: null,
+ idAlias: "privateTimelineDocumentId",
+ });
+ });
+ });
+ },
+ );
+
+ H.visitDocument("@privateTimelineDocumentId");
+
+ H.openDocumentCardMenu(TIMESERIES_CARD_3);
+ H.popover()
+ .findByRole("menuitem", { name: /Edit Visualization/ })
+ .click();
+
+ H.getDocumentSidebar().findByRole("button", { name: /Line/i }).click();
+ cy.findByRole("menu", { name: /Line/i }).findByText("Bar").click();
+ H.getDocumentSidebar().findByRole("button", { name: "Done" }).click();
+
+ cy.intercept("PUT", "/api/document/*").as("saveDocument");
+ H.documentSaveButton().click();
+ cy.wait("@saveDocument").its("response.statusCode").should("eq", 200);
+ H.documentSaveButton().should("not.exist");
+ H.assertDocumentCardVizType(TIMESERIES_CARD_3, "Bar");
+ });
});
});
+function denyCollection(id: CollectionId): CollectionPermissions {
+ const denied: Record<CollectionId, CollectionPermission> = { [id]: "none" };
+ return {
+ [ALL_USERS_GROUP]: denied,
+ [COLLECTION_GROUP]: denied,
+ [DATA_GROUP]: denied,
+ };
+}
+
function documentTimelineSidebar() {
return cy.findByTestId("document-timeline-sidebar");
}
diff --git a/e2e/test/scenarios/organization/shared/timeline-events.ts b/e2e/test/scenarios/organization/shared/timeline-events.ts
new file mode 100644
index 00000000000..a670da805b7
--- /dev/null
+++ b/e2e/test/scenarios/organization/shared/timeline-events.ts
@@ -0,0 +1,108 @@
+const { H } = cy;
+import { SAMPLE_DATABASE } from "e2e/support/cypress_sample_database";
+import type { StructuredQuestionDetails } from "e2e/support/helpers";
+
+const { ORDERS, ORDERS_ID } = SAMPLE_DATABASE;
+
+const TIMELINE_API = /^\/api\/timeline/;
+
+export const TIME_SERIES_QUESTION: StructuredQuestionDetails = {
+ name: "Orders by month",
+ display: "line",
+ query: {
+ "source-table": ORDERS_ID,
+ aggregation: [["count"]],
+ breakout: [["field", ORDERS.CREATED_AT, { "temporal-unit": "month" }]],
+ },
+};
+
+export function createQuestionAndDashboardWithEvents() {
+ interceptTimelineRequests();
+ cy.intercept({ method: "GET", pathname: TIMELINE_API }).as("getTimelines");
+ cy.intercept({ method: /POST|PUT|DELETE/, pathname: TIMELINE_API }).as(
+ "mutateTimelineEvents",
+ );
+
+ H.createTimelineWithEvents({
+ timeline: { name: "Releases" },
+ events: [
+ {
+ name: "RC1",
+ description: "The first release candidate is ready.",
+ timestamp: "2027-10-20T00:00:00Z",
+ },
+ {
+ name: "Internal release notes",
+ description: "Excluded release details.",
+ timestamp: "2027-10-20T00:00:00Z",
+ },
+ ],
+ })
+ .then(({ timeline, events: [, excludedEvent] }) => {
+ cy.wrap(timeline.id).as("timelineId");
+ return H.createQuestionAndDashboard({
+ questionDetails: {
+ ...TIME_SERIES_QUESTION,
+ visualization_settings: {
+ "timeline.selected_timeline_ids": [timeline.id],
+ "timeline.excluded_timeline_event_ids": [excludedEvent.id],
+ },
+ enable_embedding: true,
+ },
+ dashboardDetails: {
+ name: "Dashboard with events",
+ enable_embedding: true,
+ },
+ });
+ })
+ .then(({ body: { dashboard_id }, questionId }) => {
+ cy.wrap(questionId).as("questionId");
+ cy.wrap(dashboard_id).as("dashboardId");
+ });
+
+ H.createTimelineWithEvents({
+ timeline: { name: "Operations" },
+ events: [
+ {
+ name: "Internal review",
+ description: "Unrelated timeline details.",
+ timestamp: "2027-10-20T00:00:00Z",
+ },
+ ],
+ });
+}
+
+export function interceptTimelineRequests(requestAlias = "timelineRequests") {
+ cy.intercept({ pathname: TIMELINE_API }).as(requestAlias);
+}
+
+export function expectChartWithoutEvents({
+ requestAlias = "timelineRequests",
+} = {}) {
+ H.echartsContainer().findByText("Created At: Month").should("be.visible");
+ cy.findByTestId("timeline-event-chip").should("not.exist");
+ cy.findByRole("button", { name: "Events" }).should("not.exist");
+ cy.icon("calendar").should("not.exist");
+ cy.get(`@${requestAlias}.all`).should("have.length", 0);
+}
+
+export function expectReadOnlyDashboardEvents() {
+ H.echartsContainer().findByText("Created At: Month").should("be.visible");
+ cy.findAllByTestId("timeline-event-chip").should("have.length", 1);
+ H.timelineEventChip("RC1")
+ .should("be.visible")
+ .and("have.attr", "data-selected", "false")
+ .click();
+ H.timelineEventChip("RC1").should("have.attr", "data-selected", "false");
+ cy.findByTestId("dashboard-events-sidebar").should("not.exist");
+
+ H.timelineEventChip("RC1").realHover();
+ cy.findByTestId("timeline-event-popover")
+ .should("contain", "RC1")
+ .and("contain", "The first release candidate is ready.")
+ .and("not.contain", "See all");
+ cy.findByTestId("timeline-event-popover")
+ .findByRole("button", { name: /edit|create|delete/i })
+ .should("not.exist");
+ cy.get("@mutateTimelineEvents.all").should("have.length", 0);
+}
diff --git a/e2e/test/scenarios/organization/timelines-dashboard.cy.spec.ts b/e2e/test/scenarios/organization/timelines-dashboard.cy.spec.ts
new file mode 100644
index 00000000000..bbef3914cbe
--- /dev/null
+++ b/e2e/test/scenarios/organization/timelines-dashboard.cy.spec.ts
@@ -0,0 +1,993 @@
+const { H } = cy;
+import { USER_GROUPS } from "e2e/support/cypress_data";
+import { SAMPLE_DATABASE } from "e2e/support/cypress_sample_database";
+import { ADMIN_PERSONAL_COLLECTION_ID } from "e2e/support/cypress_sample_instance_data";
+import type {
+ StructuredQuestionDetails,
+ TimelineEventDetails,
+} from "e2e/support/helpers";
+import type {
+ CollectionId,
+ CollectionPermission,
+ CollectionPermissions,
+ CreateTimelineRequest,
+ DashboardCard,
+ DashboardId,
+ TimelineId,
+ VisualizationSettings,
+} from "metabase-types/api";
+import { createMockDashboardCard } from "metabase-types/api/mocks";
+
+const { ALL_USERS_GROUP, COLLECTION_GROUP, DATA_GROUP } = USER_GROUPS;
+
+const { ORDERS, ORDERS_ID } = SAMPLE_DATABASE;
+
+const questionDetails: StructuredQuestionDetails = {
+ name: "Orders by month",
+ display: "line",
+ query: {
+ "source-table": ORDERS_ID,
+ aggregation: [["count"]],
+ breakout: [["field", ORDERS.CREATED_AT, { "temporal-unit": "month" }]],
+ },
+};
+
+describe("scenarios > organization > timelines > dashboard", () => {
+ beforeEach(() => {
+ H.restore();
+ cy.signInAsAdmin();
+ cy.intercept("POST", "/api/timeline-event").as("createEvent");
+ });
+
+ it("should create the first event and timeline", () => {
+ visitDashboardWithTimeSeries();
+ openEventsSidebar();
+
+ eventsSidebar().button("Create event").click();
+ createEvent("RC1", "10/20/2027");
+
+ eventsSidebar().within(() => {
+ H.timelineVisibility("Our analytics events").should("be.checked");
+ H.timelineEventVisibility("RC1").should("be.checked");
+ });
+ H.timelineEventChip("RC1").should("be.visible");
+ cy.get("@createEvent").its("request.body.source").should("eq", "dashboard");
+ });
+
+ it("should not list timelines without events", () => {
+ H.createTimelineWithEvents({
+ timeline: { name: "Releases" },
+ events: [{ name: "RC1", timestamp: "2027-10-20T00:00:00Z" }],
+ });
+ H.createTimeline({ name: "Empty timeline" });
+
+ visitDashboardWithTimeSeries();
+ openEventsSidebar();
+
+ eventsSidebar().within(() => {
+ cy.findByText("Releases").should("be.visible");
+ cy.findByText("Empty timeline").should("not.exist");
+ });
+ });
+
+ it("should show the whole timeline when creating an event on a hidden timeline", () => {
+ H.createTimelineWithEvents({
+ timeline: { name: "Releases" },
+ events: [{ name: "RC1", timestamp: "2027-10-20T00:00:00Z" }],
+ });
+
+ visitDashboardWithTimeSeries();
+ openEventsSidebar();
+
+ eventsSidebar().within(() => {
+ H.timelineEventVisibility("RC1").should("not.be.checked");
+ });
+ H.timelineEventChip("RC1").should("not.exist");
+
+ eventsSidebar().button("Create event").click();
+ createEvent("RC2", "12/15/2027");
+
+ eventsSidebar().within(() => {
+ H.timelineVisibility("Releases").should("be.checked");
+ H.timelineEventVisibility("RC1").should("be.checked");
+ H.timelineEventVisibility("RC2").should("be.checked");
+ });
+ H.timelineEventChip("RC1").should("be.visible");
+ H.timelineEventChip("RC2").should("be.visible");
+ });
+
+ it("should keep event visibility local to each copy of a question and restore saved choices on reload", () => {
+ createReleaseTimeline().then(({ timeline }) => {
+ visitDashboardWithCopies(timeline.id);
+ });
+ H.waitForDashcardsToLoad({ count: 2 });
+ eventChip(0, "RC1").should("be.visible");
+ eventChip(1, "RC1").should("be.visible");
+ cy.intercept("PUT", "/api/card/*", cy.spy().as("questionUpdates"));
+ cy.intercept("PUT", "/api/dashboard/*", cy.spy().as("dashboardUpdates"));
+
+ eventChip(0, "RC1").click();
+ eventsSidebar().should("be.visible");
+ toggleEventVisibility("RC1");
+ eventsSidebar().within(() => {
+ H.timelineEventVisibility("RC1").should("not.be.checked");
+ });
+ eventChip(0, "RC1").should("not.exist");
+ eventChip(1, "RC1").should("be.visible");
+ cy.get("@questionUpdates").should("not.have.been.called");
+ cy.get("@dashboardUpdates").should("not.have.been.called");
+
+ cy.reload();
+ H.waitForDashcardsToLoad({ count: 2 });
+ eventChip(0, "RC1").should("be.visible");
+ eventChip(1, "RC1").should("be.visible");
+ eventsSidebar().should("not.exist");
+ });
+
+ it("should apply mixed dashboard event choices only to eligible cards on the current tab", () => {
+ createReleaseTimeline().then(({ timeline }) => {
+ H.createQuestion({
+ ...questionDetails,
+ name: "Orders table",
+ display: "table",
+ visualization_settings: {
+ "timeline.selected_timeline_ids": [timeline.id],
+ },
+ }).then(({ body: table }) => {
+ visitDashboardWithCopies(timeline.id, {
+ withTabs: true,
+ extraDashcards: [
+ createMockDashboardCard({
+ id: -4,
+ card_id: table.id,
+ dashboard_tab_id: -1,
+ row: 7,
+ size_x: 12,
+ size_y: 6,
+ }),
+ ],
+ });
+ });
+ });
+ H.waitForDashcardsToLoad({ count: 3 });
+ eventChip(0, "RC1").should("be.visible").click();
+ toggleEventVisibility("RC1");
+ eventChip(1, "RC1").should("be.visible");
+ eventChip(0, "RC1").should("not.exist");
+ closeEventsSidebar();
+ openEventsSidebar();
+
+ eventsSidebar().within(() => {
+ H.timelineEventVisibility("RC1").should(
+ "have.prop",
+ "indeterminate",
+ true,
+ );
+ H.toggleTimelineEventVisibility("RC1");
+ H.timelineEventVisibility("RC1")
+ .should("be.checked")
+ .and("have.prop", "indeterminate", false);
+ });
+ eventChip(0, "RC1").should("be.visible");
+ eventChip(1, "RC1").should("be.visible");
+ H.getDashboardCard(2).findByText("Orders table").should("be.visible");
+ H.getDashboardCard(2)
+ .findByTestId("timeline-events-band")
+ .should("not.exist");
+
+ toggleEventVisibility("RC1");
+ eventsSidebar().within(() => {
+ H.timelineEventVisibility("RC1").should("not.be.checked");
+ });
+ eventChip(0, "RC1").should("not.exist");
+ eventChip(1, "RC1").should("not.exist");
+ H.goToTab("History");
+ H.waitForDashcardsToLoad({ count: 1 });
+ eventChip(0, "RC1").should("be.visible");
+ H.goToTab("Overview");
+ H.waitForDashcardsToLoad({ count: 3 });
+ eventChip(0, "RC1").should("not.exist");
+ eventChip(1, "RC1").should("not.exist");
+ });
+
+ it("should not offer events on a card too small to show them", () => {
+ createReleaseTimeline().then(({ timeline }) => {
+ H.createQuestion({
+ ...questionDetails,
+ visualization_settings: {
+ "timeline.selected_timeline_ids": [timeline.id],
+ },
+ }).then(({ body: question }) => {
+ H.createDashboardWithTabs({
+ dashcards: [
+ createMockDashboardCard({
+ id: -1,
+ card_id: question.id,
+ size_x: 12,
+ size_y: 6,
+ }),
+ createMockDashboardCard({
+ id: -2,
+ card_id: question.id,
+ row: 6,
+ size_x: 4,
+ size_y: 3,
+ }),
+ ],
+ }).then((dashboard) => H.visitDashboard(dashboard.id));
+ });
+ });
+ H.waitForDashcardsToLoad({ count: 2 });
+
+ eventChip(0, "RC1").should("be.visible");
+ openDashCardMenu(0);
+ H.menu().findByText("Events").should("be.visible");
+ cy.realPress("Escape");
+ H.menu().should("not.exist");
+
+ H.getDashboardCard(1).findByText("Orders by month").should("be.visible");
+ H.getDashboardCard(1)
+ .findByTestId("timeline-event-chip")
+ .should("not.exist");
+ openDashCardMenu(1);
+ H.menu().should("contain", "Download results").and("not.contain", "Events");
+ });
+
+ it("should update and archive an event from the dashboard in both the panel and chart", () => {
+ cy.intercept("PUT", "/api/timeline-event/*").as("updateEvent");
+ H.createTimelineWithEvents({
+ timeline: { name: "Releases" },
+ events: [
+ { name: "RC1", timestamp: "2027-10-20T00:00:00Z" },
+ { name: "Stable release", timestamp: "2028-01-15T00:00:00Z" },
+ ],
+ }).then(({ timeline }) => {
+ visitDashboardWithTimeSeries({
+ "timeline.selected_timeline_ids": [timeline.id],
+ });
+ });
+ H.timelineEventChip("RC1").should("be.visible").click();
+ eventsSidebar().within(() => {
+ H.timelineEventCard("RC1")
+ .findByRole("button", { name: "Event menu" })
+ .click();
+ });
+ H.menu().findByText("Edit event").click();
+ H.modal().within(() => {
+ cy.findByLabelText("Event name").clear().type("RC2");
+ cy.findByRole("button", { name: "Update" }).click();
+ });
+ cy.wait("@updateEvent");
+ eventsSidebar().should("contain", "RC2").and("not.contain", "RC1");
+ H.timelineEventChip("RC2").should("be.visible");
+ H.timelineEventChip("RC1").should("not.exist");
+
+ eventsSidebar().within(() => {
+ H.timelineEventCard("RC2")
+ .findByRole("button", { name: "Event menu" })
+ .click();
+ });
+ H.menu().findByText("Archive event").click();
+ cy.wait("@updateEvent");
+ eventsSidebar().should("contain", "Releases").and("not.contain", "RC2");
+ H.timelineEventChip("Stable release").should("be.visible");
+ H.timelineEventChip("RC2").should("not.exist");
+ });
+
+ it("should select single and grouped dashboard chips and focus the matching panel entries", () => {
+ H.createTimelineWithEvents({
+ timeline: { name: "Releases" },
+ events: [
+ { name: "Alpha", timestamp: "2027-10-03T00:00:00Z" },
+ { name: "Beta", timestamp: "2027-10-10T00:00:00Z" },
+ { name: "Stable release", timestamp: "2028-01-15T00:00:00Z" },
+ ],
+ }).then(({ timeline }) => visitDashboardWithCopies(timeline.id));
+ H.waitForDashcardsToLoad({ count: 2 });
+
+ eventChip(0, "2 events").should("be.visible").click();
+ eventChip(0, "2 events").should("have.attr", "data-selected", "true");
+ eventChip(1, "2 events").should("have.attr", "data-selected", "false");
+ eventsSidebar()
+ .should("contain", "Alpha")
+ .and("contain", "Beta")
+ .and("not.contain", "Stable release");
+ eventsSidebar()
+ .findByRole("button", { name: /All events/ })
+ .click();
+ eventsSidebar().findByText("Stable release").should("be.visible");
+
+ eventChip(0, "Stable release").click();
+ eventChip(0, "Stable release").should("have.attr", "data-selected", "true");
+ eventChip(0, "2 events").should("have.attr", "data-selected", "false");
+ eventChip(1, "Stable release").should(
+ "have.attr",
+ "data-selected",
+ "false",
+ );
+ eventsSidebar().should("contain", "Stable release").and("contain", "Alpha");
+ eventsSidebar()
+ .findByRole("button", { name: /All events/ })
+ .should("not.exist");
+ });
+
+ it("should clear the targeted events panel and selection when switching tabs or editing and removing a card", () => {
+ createReleaseTimeline().then(({ timeline }) => {
+ visitDashboardWithCopies(timeline.id, { withTabs: true });
+ });
+ H.waitForDashcardsToLoad({ count: 2 });
+ eventChip(0, "RC1").should("be.visible").click();
+ eventsSidebar().should("be.visible");
+ H.goToTab("History");
+ H.waitForDashcardsToLoad({ count: 1 });
+ eventChip(0, "RC1")
+ .should("be.visible")
+ .and("have.attr", "data-selected", "false");
+ eventsSidebar().should("not.exist");
+ H.goToTab("Overview");
+ H.waitForDashcardsToLoad({ count: 2 });
+ eventChip(0, "RC1").should("have.attr", "data-selected", "false").click();
+ eventsSidebar().should("be.visible");
+
+ H.editDashboard();
+ H.dashboardSaveButton().should("be.visible");
+ eventsSidebar().should("not.exist");
+ // hover away from the chart center, where the event popover would cover the card
+ H.getDashboardCard(0)
+ .realHover({ position: "topLeft" })
+ .findByTestId("dashboardcard-actions-panel")
+ .should("be.visible")
+ .icon("close")
+ .click({ force: true });
+ H.saveDashboard();
+ H.waitForDashcardsToLoad({ count: 1 });
+ eventChip(0, "RC1")
+ .should("be.visible")
+ .and("have.attr", "data-selected", "false");
+ eventsSidebar().should("not.exist");
+ eventChip(0, "RC1").click();
+ eventsSidebar().findByText("RC1").should("be.visible");
+ });
+
+ it("should keep chart data visible while restricting timeline details and editing to permitted collections", () => {
+ H.createTimelineWithEvents({
+ timeline: {
+ name: "Private launches",
+ collection_id: ADMIN_PERSONAL_COLLECTION_ID,
+ },
+ events: [{ name: "Secret release", timestamp: "2027-11-20T00:00:00Z" }],
+ }).then(({ timeline }) => cy.wrap(timeline.id).as("privateTimelineId"));
+ createReleaseTimeline().then(({ timeline }) =>
+ cy.wrap(timeline.id).as("timelineId"),
+ );
+ cy.then(function () {
+ H.createQuestionAndDashboard({
+ questionDetails: {
+ ...questionDetails,
+ visualization_settings: {
+ "timeline.selected_timeline_ids": [
+ this.timelineId,
+ this.privateTimelineId,
+ ],
+ },
+ },
+ }).then(({ body: { dashboard_id } }) => {
+ cy.signOut();
+ cy.signIn("readonly");
+ H.visitDashboard(dashboard_id);
+ });
+ });
+ H.getDashboardCard().findByText("Created At: Month").should("be.visible");
+ H.timelineEventChip("RC1").should("be.visible");
+ H.timelineEventChip("Secret release").should("not.exist");
+ openEventsSidebar();
+ eventsSidebar()
+ .should("contain", "Releases")
+ .and("not.contain", "Private launches")
+ .and("not.contain", "Secret release");
+ eventsSidebar()
+ .findByRole("button", { name: "Create event" })
+ .should("not.exist");
+ eventsSidebar()
+ .findByRole("button", { name: "Event menu" })
+ .should("not.exist");
+ toggleEventVisibility("RC1");
+ eventsSidebar().within(() =>
+ H.timelineEventVisibility("RC1").should("not.be.checked"),
+ );
+ H.timelineEventChip("RC1").should("not.exist");
+ toggleEventVisibility("RC1");
+ H.timelineEventChip("RC1").should("be.visible");
+ });
+
+ it("should filter dashboard event chips and panel entries with the chart date range", () => {
+ H.createTimelineWithEvents({
+ timeline: { name: "Releases" },
+ events: [
+ { name: "RC1", timestamp: "2027-10-20T00:00:00Z" },
+ { name: "Stable release", timestamp: "2028-01-15T00:00:00Z" },
+ ],
+ }).then(({ timeline }) =>
+ H.createQuestionAndDashboard({
+ questionDetails: {
+ ...questionDetails,
+ visualization_settings: {
+ "timeline.selected_timeline_ids": [timeline.id],
+ },
+ },
+ dashboardDetails: {
+ parameters: [
+ { id: "date", name: "Date", slug: "date", type: "date/range" },
+ ],
+ },
+ }).then(({ body: { id, dashboard_id }, questionId }) => {
+ H.addOrUpdateDashboardCard({
+ dashboard_id,
+ card_id: questionId,
+ card: {
+ id,
+ parameter_mappings: [
+ {
+ parameter_id: "date",
+ card_id: questionId,
+ target: [
+ "dimension",
+ [
+ "field",
+ ORDERS.CREATED_AT,
+ { "base-type": "type/DateTime" },
+ ],
+ ],
+ },
+ ],
+ },
+ });
+ H.visitDashboard(dashboard_id);
+ }),
+ );
+ H.timelineEventChip("RC1").should("be.visible");
+ H.timelineEventChip("Stable release").should("be.visible");
+ cy.intercept("POST", "/api/dashboard/*/dashcard/*/card/*/query").as(
+ "filteredQuery",
+ );
+ H.filterWidget().click();
+ H.popover().within(() => {
+ cy.findByLabelText("Start date").clear().type("10/01/2027").blur();
+ cy.findByLabelText("End date").clear().type("11/30/2027").blur();
+ cy.findByRole("button", { name: "Add filter" }).click();
+ });
+ cy.wait("@filteredQuery");
+ H.timelineEventChip("RC1").should("be.visible").click();
+ eventsSidebar()
+ .should("contain", "RC1")
+ .and("not.contain", "Stable release");
+ H.timelineEventChip("Stable release").should("not.exist");
+ closeEventsSidebar();
+ H.clearFilterWidget();
+ cy.wait("@filteredQuery");
+ H.timelineEventChip("Stable release").should("be.visible");
+ H.getDashboardCard().findByText("Created At: Month").should("be.visible");
+ });
+
+ it("should show an event only the card's series reaches", () => {
+ visitDashboardWithSeriesReachingTheEvent();
+
+ H.getDashboardCard().findByText("Orders by month").should("be.visible");
+ eventChip(0, "RC1").should("be.visible").click();
+ eventsSidebar().findByText("RC1").should("be.visible");
+ });
+
+ it("should show the replacing question's events after replacing a card", () => {
+ createTimelineQuestion({
+ timeline: { name: "Launches" },
+ events: [{ name: "GA", timestamp: "2027-11-20T00:00:00Z" }],
+ name: "Orders by month, launches",
+ });
+ visitDashboardWithReleaseEvents();
+
+ eventChip(0, "RC1").should("be.visible").click();
+ eventsSidebar().should("be.visible");
+
+ // the replacement runs as a plain card query until the dashboard is saved
+ cy.intercept("POST", "/api/card/*/query").as("replacedCardQuery");
+ H.editDashboard();
+ H.getDashboardCard()
+ .realHover({ position: "topLeft" })
+ .findByLabelText("Replace")
+ .click();
+ H.entityPickerModal().findByText("Orders by month, launches").click();
+ cy.wait("@replacedCardQuery");
+ H.saveDashboard();
+
+ eventChip(0, "GA").should("be.visible");
+ eventChip(0, "RC1").should("not.exist");
+ eventChip(0, "GA").click();
+ eventsSidebar().within(() => {
+ H.timelineVisibility("Launches").should("be.checked");
+ H.timelineVisibility("Releases").should("not.be.checked");
+ });
+ });
+
+ it("should show the events of a metric and of a model", () => {
+ visitDashboardWithMetricAndModel();
+ H.waitForDashcardsToLoad({ count: 2 });
+
+ eventChip(0, "RC1").should("be.visible");
+ eventChip(1, "RC1").should("be.visible").click();
+ eventsSidebar().findByText("RC1").should("be.visible");
+ });
+
+ it("should deep duplicate a dashboard whose question selects an inaccessible timeline", () => {
+ H.createCollection({ name: "Events" }).then(({ body: { id } }) => {
+ H.createTimelineWithEvents({
+ timeline: { name: "Releases", collection_id: id },
+ events: [{ name: "RC1", timestamp: "2027-10-20T00:00:00Z" }],
+ }).then(({ timeline }) => {
+ H.createQuestionAndDashboard({
+ questionDetails: {
+ ...questionDetails,
+ visualization_settings: {
+ "timeline.selected_timeline_ids": [timeline.id],
+ },
+ },
+ }).then(({ body: { dashboard_id } }) => {
+ cy.wrap(dashboard_id).as("dashboardId");
+ cy.intercept("POST", `/api/dashboard/${dashboard_id}/copy`).as(
+ "copyDashboard",
+ );
+ });
+ });
+ cy.updateCollectionGraph(denyCollection(id));
+ });
+
+ cy.signInAsNormalUser();
+ H.visitDashboard("@dashboardId");
+ H.openDashboardMenu();
+ H.popover().findByText("Duplicate").click();
+ H.modal().within(() => {
+ cy.findByLabelText("Only duplicate the dashboard").should(
+ "not.be.checked",
+ );
+ cy.button("Duplicate").click();
+ });
+
+ cy.wait("@copyDashboard").its("response.statusCode").should("eq", 200);
+ H.dashboardCards()
+ .findByText("Orders by month - Duplicate")
+ .should("be.visible");
+ });
+
+ it("should bring a card's events back on the dashboard when its question is reverted", () => {
+ cy.intercept("POST", "/api/revision/revert").as("revertRevision");
+
+ createReleaseTimeline().then(({ timeline }) =>
+ H.createQuestionAndDashboard({
+ questionDetails: {
+ ...questionDetails,
+ visualization_settings: {
+ "timeline.selected_timeline_ids": [timeline.id],
+ },
+ },
+ }).then(({ body: { card_id, dashboard_id } }) => {
+ cy.wrap(card_id).as("questionId");
+ cy.wrap(dashboard_id).as("dashboardId");
+ }),
+ );
+
+ cy.get<DashboardId>("@dashboardId").then(H.visitDashboard);
+ eventChip(0, "RC1").should("be.visible");
+
+ cy.log("hide the event on the question, which the dashboard follows");
+ H.visitQuestion("@questionId");
+ cy.findByTestId("view-footer").icon("calendar").click();
+ H.rightSidebar().within(() => H.toggleTimelineEventVisibility("RC1"));
+ H.saveSavedQuestion();
+
+ cy.get<DashboardId>("@dashboardId").then(H.visitDashboard);
+ eventChip(0, "RC1").should("not.exist");
+
+ cy.log("reverting the question restores what the dashboard shows");
+ H.visitQuestion("@questionId");
+ H.questionInfoButton().click();
+ H.sidesheet().within(() => {
+ cy.findByRole("tab", { name: "History" }).click();
+ cy.findAllByTestId("question-revert-button").first().click();
+ });
+ cy.wait("@revertRevision").its("response.statusCode").should("eq", 200);
+
+ cy.get<DashboardId>("@dashboardId").then(H.visitDashboard);
+ eventChip(0, "RC1").should("be.visible");
+ });
+
+ it("should not let a user revert a public dashboard to a version with a restricted timeline card", () => {
+ cy.request("PUT", "/api/setting/enable-public-sharing", { value: true });
+ H.createCollection({ name: "Restricted" }).then(({ body: { id } }) => {
+ H.createTimelineWithEvents({
+ timeline: { name: "Releases", collection_id: id },
+ events: [
+ { name: "Secret bday party", timestamp: "2027-10-20T00:00:00Z" },
+ ],
+ }).then(({ timeline }) => {
+ H.createQuestionAndDashboard({
+ questionDetails: {
+ ...questionDetails,
+ visualization_settings: {
+ "timeline.selected_timeline_ids": [timeline.id],
+ },
+ },
+ dashboardDetails: { name: "Shared dashboard" },
+ }).then(({ body: { dashboard_id } }) => {
+ H.createPublicDashboardLink(dashboard_id);
+ cy.wrap(dashboard_id).as("dashboardId");
+ cy.request("PUT", `/api/dashboard/${dashboard_id}`, {
+ dashcards: [],
+ });
+ });
+ });
+ cy.updateCollectionGraph(denyCollection(id));
+ });
+
+ cy.signInAsNormalUser();
+ cy.intercept("GET", "/api/revision*").as("revisionHistory");
+ cy.intercept("POST", "/api/revision/revert").as("revertDashboard");
+ H.visitDashboard("@dashboardId");
+ H.openDashboardInfoSidebar().within(() => {
+ cy.findByRole("tab", { name: "History" }).click();
+ cy.wait("@revisionHistory");
+ cy.findAllByTestId("question-revert-button").first().click();
+ });
+
+ cy.wait("@revertDashboard").its("response.statusCode").should("eq", 403);
+ H.undoToast().should(
+ "contain.text",
+ "You don't have permissions to do that.",
+ );
+ cy.get<DashboardId>("@dashboardId").then((id) => {
+ cy.signInAsAdmin();
+ cy.request("GET", `/api/dashboard/${id}`)
+ .its("body.dashcards")
+ .should("have.length", 0);
+ });
+ });
+
+ describe("visualization type", () => {
+ it("should keep the events after the question switches to another time series display", () => {
+ visitQuestionWithReleaseEvents();
+
+ H.openVizTypeSidebar();
+ H.vizTypeSidebar().icon("area").click();
+ H.saveSavedQuestion();
+
+ cy.get<DashboardId>("@dashboardId").then(H.visitDashboard);
+ eventChip(0, "RC1").should("be.visible");
+ openEventsSidebar();
+ eventsSidebar().findByText("Releases").should("be.visible");
+ });
+
+ it("should stop offering events once the question is no longer a time series", () => {
+ visitQuestionWithReleaseEvents();
+
+ H.openVizTypeSidebar();
+ H.vizTypeSidebar().icon("table2").click();
+ H.saveSavedQuestion();
+
+ cy.get<DashboardId>("@dashboardId").then(H.visitDashboard);
+ openEventsSidebar();
+ cy.findByTestId("dashboard-events-empty-state").should("be.visible");
+ });
+
+ it("should not show events on a card visualized another way", () => {
+ visitDashboardWithReleaseEvents();
+ eventChip(0, "RC1").should("be.visible");
+
+ H.editDashboard();
+ H.showDashcardVisualizerModal(0, { isVisualizerCard: false });
+ H.selectVisualization("area");
+ H.saveDashcardVisualizerModal();
+ H.saveDashboard();
+
+ eventChip(0, "RC1").should("not.exist");
+ openEventsSidebar();
+ cy.findByTestId("dashboard-events-empty-state").should("be.visible");
+ });
+ });
+
+ describe("analytics", () => {
+ beforeEach(() => {
+ H.resetSnowplow();
+ H.enableTracking();
+ });
+
+ afterEach(() => {
+ H.expectNoBadSnowplowEvents();
+ });
+
+ it("should track a dashboard showing events once per load", () => {
+ H.createTimelineWithEvents({
+ timeline: { name: "Releases" },
+ events: [{ name: "RC1", timestamp: "2027-10-20T00:00:00Z" }],
+ }).then(({ timeline }) => {
+ visitDashboardWithCopies(timeline.id);
+ });
+ H.waitForDashcardsToLoad({ count: 2 });
+ eventChip(0, "RC1").should("be.visible");
+ eventChip(1, "RC1").should("be.visible");
+ expectEventsShownOnce();
+
+ openEventsSidebar();
+ expectDashboardEvent({
+ event: "dashboard_events_panel_opened",
+ triggered_from: "dashboard_menu",
+ });
+ toggleEventVisibility("RC1");
+ eventChip(0, "RC1").should("not.exist");
+ eventChip(1, "RC1").should("not.exist");
+ expectDashboardEvent({
+ event: "dashboard_events_visibility_changed",
+ triggered_from: "dashboard",
+ event_detail: "hidden",
+ });
+ toggleEventVisibility("RC1");
+ eventChip(0, "RC1").should("be.visible");
+ eventChip(1, "RC1").should("be.visible");
+ expectDashboardEvent({
+ event: "dashboard_events_visibility_changed",
+ triggered_from: "dashboard",
+ event_detail: "shown",
+ });
+ expectEventsShownOnce();
+
+ eventsSidebar().button("Create event").click();
+ createEvent("RC2", "01/15/2028");
+ eventChip(0, "RC2").should("be.visible");
+ eventChip(1, "RC2").should("be.visible");
+ H.expectUnstructuredSnowplowEvent({
+ event: "new_event_created",
+ source: "dashboard",
+ });
+ expectEventsShownOnce();
+
+ cy.reload();
+ H.waitForDashcardsToLoad({ count: 2 });
+ eventChip(0, "RC1").should("be.visible");
+ eventChip(1, "RC1").should("be.visible");
+ cy.get<DashboardId>("@dashboardId").then((dashboardId) => {
+ H.expectUnstructuredSnowplowEvent(
+ { event: "dashboard_events_shown", target_id: dashboardId },
+ 2,
+ );
+ });
+ });
+ });
+});
+
+function visitDashboardWithTimeSeries(
+ visualizationSettings: VisualizationSettings = {},
+) {
+ H.createQuestionAndDashboard({
+ questionDetails: {
+ ...questionDetails,
+ visualization_settings: visualizationSettings,
+ },
+ }).then(({ body: { dashboard_id } }) => {
+ cy.wrap(dashboard_id).as("dashboardId");
+ H.visitDashboard(dashboard_id);
+ });
+ H.getDashboardCard().findByText("Created At: Month").should("be.visible");
+}
+
+function visitDashboardWithMetricAndModel() {
+ return createReleaseTimeline().then(({ timeline }) =>
+ H.createQuestion({
+ ...questionDetails,
+ name: "Orders metric",
+ type: "metric",
+ visualization_settings: {
+ "timeline.selected_timeline_ids": [timeline.id],
+ },
+ }).then(({ body: metric }) =>
+ H.createQuestion({
+ ...questionDetails,
+ name: "Orders model",
+ type: "model",
+ visualization_settings: {
+ "timeline.selected_timeline_ids": [timeline.id],
+ },
+ }).then(({ body: model }) =>
+ // Converting a question to a model forces its display to table, so restore the time-series display.
+ cy
+ .request("PUT", `/api/card/${model.id}`, { display: "line" })
+ .then(({ body: model }) =>
+ H.createDashboardWithTabs({
+ dashcards: [metric, model].map((card, index) =>
+ createMockDashboardCard({
+ id: -(index + 1),
+ card_id: card.id,
+ row: index * 6,
+ size_x: 12,
+ size_y: 6,
+ }),
+ ),
+ }).then((dashboard) => H.visitDashboard(dashboard.id)),
+ ),
+ ),
+ ),
+ );
+}
+
+function createTimelineQuestion({
+ timeline,
+ events,
+ ...questionOverrides
+}: {
+ timeline: CreateTimelineRequest;
+ events: Omit<TimelineEventDetails, "timeline_id">[];
+} & Partial<StructuredQuestionDetails>) {
+ return H.createTimelineWithEvents({ timeline, events }).then(({ timeline }) =>
+ H.createQuestion({
+ ...questionDetails,
+ ...questionOverrides,
+ visualization_settings: {
+ "timeline.selected_timeline_ids": [timeline.id],
+ },
+ }),
+ );
+}
+
+function visitDashboardWithReleaseEvents() {
+ return createReleaseTimeline().then(({ timeline }) =>
+ visitDashboardWithTimeSeries({
+ "timeline.selected_timeline_ids": [timeline.id],
+ }),
+ );
+}
+
+// the question's own range stops before the event; only its series reaches it
+function visitDashboardWithSeriesReachingTheEvent() {
+ return createReleaseTimeline().then(({ timeline }) =>
+ H.createQuestion(questionDetails).then(({ body: series }) =>
+ H.createQuestionAndDashboard({
+ questionDetails: {
+ ...questionDetails,
+ name: "Orders before the release",
+ query: {
+ ...questionDetails.query,
+ filter: ["<", ["field", ORDERS.CREATED_AT, null], "2027-01-01"],
+ },
+ visualization_settings: {
+ "timeline.selected_timeline_ids": [timeline.id],
+ },
+ },
+ cardDetails: { series: [series] },
+ }).then(({ body: { dashboard_id } }) => H.visitDashboard(dashboard_id)),
+ ),
+ );
+}
+
+function visitQuestionWithReleaseEvents() {
+ return createReleaseTimeline().then(({ timeline }) =>
+ H.createQuestionAndDashboard({
+ questionDetails: {
+ ...questionDetails,
+ visualization_settings: {
+ "timeline.selected_timeline_ids": [timeline.id],
+ },
+ },
+ }).then(({ body: { card_id, dashboard_id } }) => {
+ cy.wrap(dashboard_id).as("dashboardId");
+ cy.wrap(card_id).as("questionId");
+ H.visitQuestion("@questionId");
+ }),
+ );
+}
+
+function createReleaseTimeline() {
+ return H.createTimelineWithEvents({
+ timeline: { name: "Releases" },
+ events: [{ name: "RC1", timestamp: "2027-10-20T00:00:00Z" }],
+ });
+}
+
+function visitDashboardWithCopies(
+ timelineId: TimelineId,
+ {
+ withTabs = false,
+ extraDashcards = [],
+ }: { withTabs?: boolean; extraDashcards?: DashboardCard[] } = {},
+) {
+ H.createQuestion({
+ ...questionDetails,
+ visualization_settings: { "timeline.selected_timeline_ids": [timelineId] },
+ }).then(({ body: question }) => {
+ H.createDashboardWithTabs({
+ tabs: withTabs
+ ? [
+ { id: -1, name: "Overview" },
+ { id: -2, name: "History" },
+ ]
+ : [],
+ dashcards: [
+ ...Array.from({ length: withTabs ? 3 : 2 }, (_, index) =>
+ createMockDashboardCard({
+ id: -(index + 1),
+ card_id: question.id,
+ dashboard_tab_id: withTabs ? (index === 2 ? -2 : -1) : null,
+ row: 0,
+ col: index === 1 ? 12 : 0,
+ size_x: 12,
+ size_y: 6,
+ }),
+ ),
+ ...extraDashcards,
+ ],
+ }).then((dashboard) => {
+ cy.wrap(dashboard.id).as("dashboardId");
+ H.visitDashboard(dashboard.id);
+ });
+ });
+}
+
+function denyCollection(id: CollectionId): CollectionPermissions {
+ const none: CollectionPermission = "none";
+ const denied = { [id]: none };
+ return {
+ [ALL_USERS_GROUP]: denied,
+ [COLLECTION_GROUP]: denied,
+ [DATA_GROUP]: denied,
+ };
+}
+
+function eventChip(cardIndex: number, eventName: string) {
+ return H.getDashboardCard(cardIndex).findByRole("button", {
+ name: eventName,
+ });
+}
+
+function openDashCardMenu(cardIndex: number) {
+ H.getDashboardCard(cardIndex).realHover({ position: "topLeft" });
+ H.getDashboardCardMenu(cardIndex).click();
+}
+
+function closeEventsSidebar() {
+ eventsSidebar().findByLabelText("Close").click();
+}
+
+function expectEventsShownOnce() {
+ expectDashboardEvent({ event: "dashboard_events_shown" }, 1);
+}
+
+function expectDashboardEvent(
+ payload: Record<string, unknown>,
+ count?: number,
+) {
+ cy.get<DashboardId>("@dashboardId").then((dashboardId) => {
+ H.expectUnstructuredSnowplowEvent(
+ { ...payload, target_id: dashboardId },
+ count,
+ );
+ });
+}
+
+function toggleEventVisibility(eventName: string) {
+ eventsSidebar().within(() => H.toggleTimelineEventVisibility(eventName));
+}
+
+function openEventsSidebar() {
+ H.openDashboardMenu("Events");
+ eventsSidebar().should("be.visible");
+}
+
+function eventsSidebar() {
+ return cy.findByTestId("dashboard-events-sidebar");
+}
+
+function createEvent(name: string, date: string) {
+ H.modal().within(() => {
+ cy.findByLabelText("Event name").type(name);
+ cy.findByLabelText("Date").clear().type(date);
+ cy.button("Create").click();
+ });
+ cy.wait("@createEvent");
+ H.modal().should("not.exist");
+ H.waitForTimelinesAfterCreatingAnEvent(name);
+}
diff --git a/e2e/test/scenarios/organization/timelines-question-persistence.cy.spec.ts b/e2e/test/scenarios/organization/timelines-question-persistence.cy.spec.ts
new file mode 100644
index 00000000000..7b1c73a0941
--- /dev/null
+++ b/e2e/test/scenarios/organization/timelines-question-persistence.cy.spec.ts
@@ -0,0 +1,460 @@
+const { H } = cy;
+import { SAMPLE_DB_ID } from "e2e/support/cypress_data";
+import { SAMPLE_DATABASE } from "e2e/support/cypress_sample_database";
+import { ADMIN_PERSONAL_COLLECTION_ID } from "e2e/support/cypress_sample_instance_data";
+import type {
+ Card,
+ CardId,
+ CollectionId,
+ TimelineId,
+ VisualizationSettings,
+} from "metabase-types/api";
+import { createMockDashboardCard } from "metabase-types/api/mocks";
+
+const { ORDERS, ORDERS_ID } = SAMPLE_DATABASE;
+
+const EVENTS = [
+ { name: "Swallows return", timestamp: "2027-04-20T00:00:00Z" },
+ { name: "Swifts return", timestamp: "2027-08-20T00:00:00Z" },
+];
+const EVENT_NAMES = EVENTS.map(({ name }) => name);
+
+describe("scenarios > organization > timelines > question persistence", () => {
+ beforeEach(() => {
+ H.restore();
+ cy.signInAsAdmin();
+ });
+
+ it("should save a timeline from another collection and hidden events for dashboards using the question", () => {
+ H.createCollection({ name: "Migration calendar" }).then(
+ ({ body: collection }) =>
+ H.createTimelineWithEvents({
+ timeline: { name: "Migration seasons", collection_id: collection.id },
+ events: EVENTS,
+ }).then(({ timeline, events }) => {
+ cy.wrap(timeline.id).as("timelineId");
+ cy.wrap(events[1].id).as("hiddenEventId");
+ }),
+ );
+ createTimeSeries();
+
+ H.visitQuestion("@questionId");
+ expectEvents([], EVENT_NAMES);
+ openQuestionEvents();
+ H.rightSidebar().within(() => {
+ H.timelineVisibility("Migration seasons").click();
+ H.toggleTimelineEventVisibility("Swifts return");
+ });
+ expectEvents(["Swallows return"], ["Swifts return"]);
+ H.saveSavedQuestion();
+
+ cy.then(function () {
+ cy.request<Card>(`/api/card/${this.questionId}`)
+ .its("body.visualization_settings")
+ .should("deep.include", {
+ "timeline.selected_timeline_ids": [this.timelineId],
+ "timeline.excluded_timeline_event_ids": [this.hiddenEventId],
+ });
+ });
+ cy.reload();
+ expectEvents(["Swallows return"], ["Swifts return"]);
+
+ H.visitDashboard("@dashboardId");
+ expectEvents(["Swallows return"], ["Swifts return"]);
+ });
+
+ it("should save destination collection events with a new question", () => {
+ const collectionName = "Migration questions";
+
+ H.createCollection({ name: collectionName }).then(({ body: { id } }) =>
+ H.createTimelineWithEvents({
+ timeline: { name: "Migration seasons", collection_id: id },
+ events: EVENTS,
+ }).then(({ timeline }) => cy.wrap(timeline.id).as("timelineId")),
+ );
+ cy.intercept(
+ { method: "GET", url: "/api/timeline?include=events", times: 1 },
+ (request) => {
+ request.on("response", (response) => response.setDelay(5000));
+ },
+ ).as("getDelayedTimelines");
+ H.visitQuestionAdhoc({
+ dataset_query: {
+ database: SAMPLE_DB_ID,
+ type: "query",
+ query: {
+ "source-table": ORDERS_ID,
+ aggregation: [["count"]],
+ breakout: [
+ ["field", ORDERS.CREATED_AT, { "temporal-unit": "month" }],
+ ],
+ },
+ },
+ display: "line",
+ });
+ H.saveQuestionToCollection(
+ "Bird sightings by month",
+ { path: ["Our analytics", collectionName] },
+ { wrapId: true },
+ );
+ cy.wait("@getDelayedTimelines");
+ cy.get<CardId>("@questionId").then((id) =>
+ cy.get<TimelineId>("@timelineId").then((timelineId) =>
+ cy
+ .request<Card>(`/api/card/${id}`)
+ .its("body.visualization_settings")
+ .should((settings) => {
+ expect(settings["timeline.selected_timeline_ids"]).to.deep.equal([
+ timelineId,
+ ]);
+ }),
+ ),
+ );
+ cy.get<CardId>("@questionId").then((questionId) =>
+ H.createDashboardWithTabs({
+ dashcards: [
+ createMockDashboardCard({
+ id: -1,
+ card_id: questionId,
+ size_x: 12,
+ size_y: 8,
+ }),
+ ],
+ }).then((dashboard) => H.visitDashboard(dashboard.id)),
+ );
+ H.waitForDashcardsToLoad();
+ expectEvents(EVENT_NAMES);
+
+ cy.reload();
+ H.waitForDashcardsToLoad();
+ expectEvents(EVENT_NAMES);
+ });
+
+ it("should save a new question when collection timelines fail to load", () => {
+ cy.intercept("GET", "/api/timeline?include=events", {
+ statusCode: 500,
+ body: { message: "Timelines are unavailable" },
+ }).as("getFailedTimelines");
+ H.visitQuestionAdhoc({
+ dataset_query: {
+ database: SAMPLE_DB_ID,
+ type: "query",
+ query: {
+ "source-table": ORDERS_ID,
+ aggregation: [["count"]],
+ breakout: [
+ ["field", ORDERS.CREATED_AT, { "temporal-unit": "month" }],
+ ],
+ },
+ },
+ display: "line",
+ });
+ H.saveQuestionToCollection("Orders by month", undefined, { wrapId: true });
+
+ cy.wait("@getFailedTimelines");
+ cy.get<CardId>("@questionId").then((id) =>
+ cy
+ .request<Card>(`/api/card/${id}`)
+ .its("body.visualization_settings")
+ .should("not.have.property", "timeline.selected_timeline_ids"),
+ );
+ });
+
+ it("should keep a question saved into a collection without timelines empty until a timeline is turned on", () => {
+ H.createCollection({ name: "Quiet corner" }).then(({ body: collection }) =>
+ cy.wrap(collection.id).as("collectionId"),
+ );
+ H.visitQuestionAdhoc({
+ dataset_query: {
+ database: SAMPLE_DB_ID,
+ type: "query",
+ query: {
+ "source-table": ORDERS_ID,
+ aggregation: [["count"]],
+ breakout: [
+ ["field", ORDERS.CREATED_AT, { "temporal-unit": "month" }],
+ ],
+ },
+ },
+ display: "line",
+ });
+ H.saveQuestionToCollection(
+ "Orders by month",
+ { path: ["Our analytics", "Quiet corner"] },
+ { wrapId: true },
+ );
+ cy.get<CardId>("@questionId").then((questionId) => {
+ cy.request<Card>(`/api/card/${questionId}`)
+ .its("body.visualization_settings")
+ .should("deep.include", { "timeline.selected_timeline_ids": [] });
+ H.createDashboardWithTabs({
+ dashcards: [
+ createMockDashboardCard({
+ id: -1,
+ card_id: questionId,
+ size_x: 12,
+ size_y: 8,
+ }),
+ ],
+ }).then((dashboard) => cy.wrap(dashboard.id).as("dashboardId"));
+ });
+ cy.get<CollectionId>("@collectionId").then((collection_id) =>
+ H.createTimelineWithEvents({
+ timeline: { name: "Migration seasons", collection_id },
+ events: EVENTS,
+ }),
+ );
+
+ cy.log("a timeline created later stays off the question and its dashboard");
+ cy.intercept("GET", "/api/timeline?include=events").as("getTimelines");
+ H.visitQuestion("@questionId");
+ cy.wait("@getTimelines");
+ expectEvents([], EVENT_NAMES);
+ H.visitDashboard("@dashboardId");
+ H.waitForDashcardsToLoad();
+ expectEvents([], EVENT_NAMES);
+
+ cy.log("turning the timeline on and saving shows it on both");
+ H.visitQuestion("@questionId");
+ openQuestionEvents();
+ H.rightSidebar().within(() =>
+ H.timelineVisibility("Migration seasons").click(),
+ );
+ expectEvents(EVENT_NAMES);
+ H.saveSavedQuestion();
+ cy.reload();
+ expectEvents(EVENT_NAMES);
+ H.visitDashboard("@dashboardId");
+ H.waitForDashcardsToLoad();
+ expectEvents(EVENT_NAMES);
+ });
+
+ it("should keep an explicitly empty selection hidden after saving and reloading the question and dashboard", () => {
+ H.createTimelineWithEvents({
+ timeline: { name: "Migration seasons" },
+ events: EVENTS,
+ }).then(({ timeline }) =>
+ createTimeSeries({ "timeline.selected_timeline_ids": [timeline.id] }),
+ );
+
+ H.visitQuestion("@questionId");
+ expectEvents(EVENT_NAMES);
+ openQuestionEvents();
+ H.rightSidebar().within(() =>
+ H.timelineVisibility("Migration seasons").click(),
+ );
+ expectEvents([], EVENT_NAMES);
+ H.saveSavedQuestion();
+
+ cy.get<CardId>("@questionId").then((id) => {
+ cy.request<Card>(`/api/card/${id}`)
+ .its("body.visualization_settings")
+ .should("have.property", "timeline.selected_timeline_ids")
+ .and("deep.equal", []);
+ });
+ cy.reload();
+ expectEvents([], EVENT_NAMES);
+ openQuestionEvents();
+ H.rightSidebar().within(() =>
+ H.timelineVisibility("Migration seasons").should("not.be.checked"),
+ );
+
+ H.visitDashboard("@dashboardId");
+ expectEvents([], EVENT_NAMES);
+ });
+
+ it("should discard unsaved event choices when reopening a saved question", () => {
+ cy.intercept("PUT", "/api/card/*").as("updateQuestion");
+ H.createTimelineWithEvents({
+ timeline: { name: "Migration seasons" },
+ events: EVENTS,
+ }).then(({ timeline }) =>
+ createTimeSeries({ "timeline.selected_timeline_ids": [timeline.id] }),
+ );
+
+ H.visitQuestion("@questionId");
+ expectEvents(EVENT_NAMES);
+ openQuestionEvents();
+ H.rightSidebar().within(() =>
+ H.timelineVisibility("Migration seasons").click(),
+ );
+ expectEvents([], EVENT_NAMES);
+ cy.findByTestId("qb-header").button("Save").should("be.visible");
+
+ cy.log("reopen the question without saving");
+ H.visitQuestion("@questionId");
+ expectEvents(EVENT_NAMES);
+ cy.get("@updateQuestion.all").should("have.length", 0);
+ });
+
+ it("should save event choices on a question that also uses a timeline the user cannot see", () => {
+ createTimeSeriesWithHiddenTimeline();
+
+ cy.signInAsNormalUser();
+ H.visitQuestion("@questionId");
+ expectEvents(EVENT_NAMES, ["Rare visitor"]);
+
+ openQuestionEvents();
+ H.rightSidebar()
+ .should("contain", "Migration seasons")
+ .and("not.contain", "Private sightings");
+ H.rightSidebar().within(() =>
+ H.toggleTimelineEventVisibility("Swifts return"),
+ );
+ expectEvents(["Swallows return"], ["Swifts return"]);
+ H.saveSavedQuestion();
+
+ cy.log("the timeline the user cannot see stays on the question");
+ cy.get<TimelineId[]>("@timelineIds").then((timelineIds) =>
+ cy.get<CardId>("@questionId").then((id) =>
+ cy
+ .request<Card>(`/api/card/${id}`)
+ .its("body.visualization_settings")
+ .should((settings: VisualizationSettings) =>
+ expect(settings["timeline.selected_timeline_ids"]).to.have.members(
+ timelineIds,
+ ),
+ ),
+ ),
+ );
+ cy.reload();
+ expectEvents(["Swallows return"], ["Swifts return", "Rare visitor"]);
+ });
+
+ it("should save a question as a new one while it uses a timeline the user cannot see", () => {
+ createTimeSeriesWithHiddenTimeline();
+
+ cy.signInAsNormalUser();
+ H.visitQuestion("@questionId");
+ openQuestionEvents();
+ H.rightSidebar().within(() =>
+ H.toggleTimelineEventVisibility("Swifts return"),
+ );
+ expectEvents(["Swallows return"], ["Swifts return"]);
+
+ cy.intercept("POST", "/api/card").as("createQuestion");
+ cy.findByTestId("qb-header").button("Save").click();
+ cy.findByTestId("save-question-modal").within(() => {
+ cy.findByText("Save as new question").click();
+ cy.button("Save").click();
+ });
+ cy.wait("@createQuestion").its("response.statusCode").should("eq", 200);
+
+ cy.log("the new question keeps the timeline the user cannot see");
+ cy.get<TimelineId[]>("@timelineIds").then((timelineIds) =>
+ cy
+ .get("@createQuestion")
+ .its("response.body.visualization_settings")
+ .should((settings: VisualizationSettings) =>
+ expect(settings["timeline.selected_timeline_ids"]).to.have.members(
+ timelineIds,
+ ),
+ ),
+ );
+ expectEvents(["Swallows return"], ["Swifts return", "Rare visitor"]);
+ });
+
+ it("shows no events and does not record collection-default events when saving an unrelated chart change", () => {
+ H.createTimelineWithEvents({
+ timeline: { name: "Migration seasons" },
+ events: EVENTS,
+ });
+ createTimeSeries();
+
+ H.visitQuestion("@questionId");
+ expectTimelineOff("Migration seasons");
+ expectEvents([], EVENT_NAMES);
+ H.openVizSettingsSidebar();
+ H.vizSettingsSidebar().within(() => {
+ cy.findByText("Display").click();
+ cy.findByText("Show values on data points").click();
+ });
+ H.openVizSettingsSidebar();
+ H.saveSavedQuestion();
+
+ cy.get<CardId>("@questionId").then((id) => {
+ cy.request<Card>(`/api/card/${id}`)
+ .its("body.visualization_settings")
+ .should((settings) => {
+ expect(settings).to.include({ "graph.show_values": true });
+ expect(settings).not.to.have.property(
+ "timeline.selected_timeline_ids",
+ );
+ expect(settings).not.to.have.property(
+ "timeline.excluded_timeline_event_ids",
+ );
+ });
+ });
+ cy.reload();
+ expectTimelineOff("Migration seasons");
+ expectEvents([], EVENT_NAMES);
+
+ cy.log("the dashboard only shows events saved on the question");
+ H.visitDashboard("@dashboardId");
+ H.waitForDashcardsToLoad();
+ expectEvents([], EVENT_NAMES);
+ });
+});
+
+function createTimeSeries(visualization_settings: VisualizationSettings = {}) {
+ H.createQuestionAndDashboard({
+ questionDetails: {
+ name: "Bird sightings by month",
+ display: "line",
+ query: {
+ "source-table": ORDERS_ID,
+ aggregation: [["count"]],
+ breakout: [["field", ORDERS.CREATED_AT, { "temporal-unit": "month" }]],
+ },
+ visualization_settings,
+ },
+ cardDetails: { size_x: 12, size_y: 8 },
+ }).then(({ questionId, body: { dashboard_id } }) => {
+ cy.wrap(questionId).as("questionId");
+ cy.wrap(dashboard_id).as("dashboardId");
+ });
+}
+
+function createTimeSeriesWithHiddenTimeline() {
+ return H.createTimelineWithEvents({
+ timeline: { name: "Migration seasons" },
+ events: EVENTS,
+ }).then(({ timeline: visible }) =>
+ H.createTimelineWithEvents({
+ timeline: { name: "Private sightings" },
+ events: [{ name: "Rare visitor", timestamp: "2027-06-20T00:00:00Z" }],
+ }).then(({ timeline: hidden }) => {
+ createTimeSeries({
+ "timeline.selected_timeline_ids": [visible.id, hidden.id],
+ "timeline.excluded_timeline_event_ids": [],
+ });
+ // the question keeps the selection once the timeline moves out of reach
+ cy.request("PUT", `/api/timeline/${hidden.id}`, {
+ collection_id: ADMIN_PERSONAL_COLLECTION_ID,
+ });
+ cy.wrap([visible.id, hidden.id]).as("timelineIds");
+ }),
+ );
+}
+
+function openQuestionEvents() {
+ cy.findByTestId("view-footer").icon("calendar").click();
+ H.rightSidebar().should("be.visible");
+}
+
+function expectTimelineOff(timelineName: string) {
+ openQuestionEvents();
+ H.rightSidebar().within(() =>
+ H.timelineVisibility(timelineName).should("not.be.checked"),
+ );
+}
+
+function expectEvents(visible: string[], hidden: string[] = []) {
+ H.echartsContainer().should("be.visible");
+ visible.forEach((name) => {
+ H.timelineEventChip(name).should("be.visible");
+ });
+ hidden.forEach((name) => {
+ H.timelineEventChip(name).should("not.exist");
+ });
+}
diff --git a/e2e/test/scenarios/organization/timelines-question.cy.spec.js b/e2e/test/scenarios/organization/timelines-question.cy.spec.js
index 6fc6ecd28d0..7b42ec0984b 100644
--- a/e2e/test/scenarios/organization/timelines-question.cy.spec.js
+++ b/e2e/test/scenarios/organization/timelines-question.cy.spec.js
@@ -1,9 +1,10 @@
const { H } = cy;
-import { SAMPLE_DB_ID } from "e2e/support/cypress_data";
+import { SAMPLE_DB_ID, USER_GROUPS } from "e2e/support/cypress_data";
import { SAMPLE_DATABASE } from "e2e/support/cypress_sample_database";
import { ORDERS_BY_YEAR_QUESTION_ID } from "e2e/support/cypress_sample_instance_data";
const { ORDERS, ORDERS_ID } = SAMPLE_DATABASE;
+const { ALL_USERS_GROUP, COLLECTION_GROUP, DATA_GROUP } = USER_GROUPS;
// brand (#509EE3) in getComputedStyle's normalized color format
const HIGHLIGHTED_DOT_FILL = "rgb(80, 158, 227)";
@@ -316,7 +317,7 @@ describe("scenarios > organization > timelines > question", () => {
events: [
{ name: "RC1", timestamp: "2027-10-20T00:00:00Z", icon: "cloud" },
],
- });
+ }).then(({ timeline }) => createQuestionWithTimeline(timeline.id));
H.createTimelineWithEvents({
timeline: {
@@ -328,7 +329,7 @@ describe("scenarios > organization > timelines > question", () => {
],
});
- H.visitQuestion(ORDERS_BY_YEAR_QUESTION_ID);
+ H.visitQuestion("@questionId");
cy.findByTestId("view-footer")
.findByText("Visualization")
@@ -338,12 +339,12 @@ describe("scenarios > organization > timelines > question", () => {
// should hide individual events from chart if hidden in sidebar
cy.icon("calendar").click();
cy.findByTestId("sidebar-content").findByText("Releases").click();
- toggleEventVisibility("RC1");
+ H.toggleTimelineEventVisibility("RC1");
H.timelineEventChip("RC1").should("not.exist");
// should show individual events in chart again
- toggleEventVisibility("RC1");
+ H.toggleTimelineEventVisibility("RC1");
H.timelineEventChip("RC1").should("be.visible");
@@ -352,34 +353,29 @@ describe("scenarios > organization > timelines > question", () => {
cy.findByLabelText("Event name").type("RC2");
cy.findByLabelText("Date").clear().type("10/20/2026");
cy.button("Create").click();
- waitForTimelinesAfterCreatingAnEvent("RC2");
+ H.waitForTimelinesAfterCreatingAnEvent("RC2");
H.undoToast().icon("close").click();
H.timelineEventChip("RC2").should("be.visible");
// should then hide the newly created event
- timelineEventVisibility("RC2").should("be.checked");
- toggleEventVisibility("RC2");
- timelineEventVisibility("RC2").should("not.be.checked");
+ H.timelineEventVisibility("RC2").should("be.checked");
+ H.toggleTimelineEventVisibility("RC2");
+ H.timelineEventVisibility("RC2").should("not.be.checked");
H.timelineEventChip("RC2").should("not.exist");
// its timeline, visible but having one hidden event
// should display its checkbox in an indeterminate state
- cy.findByTestId("sidebar-content")
- .findByText("Releases")
- .closest("[aria-label='Timeline card header']")
- .within(() => {
- cy.findByRole("checkbox").should(
- "have.prop",
- "indeterminate",
- true,
- );
-
- // Hide the timeline then show it again
- cy.findByRole("checkbox").click();
- cy.findByRole("checkbox").click();
- });
+ H.timelineVisibility("Releases").should(
+ "have.prop",
+ "indeterminate",
+ true,
+ );
+
+ // Hide the timeline then show it again
+ H.timelineVisibility("Releases").click();
+ H.timelineVisibility("Releases").click();
// once timeline is visible, all its events should be visible
H.timelineEventChip("RC2").should("be.visible");
@@ -400,16 +396,13 @@ describe("scenarios > organization > timelines > question", () => {
// making a hidden timeline visible
// should make its events automatically visible
- cy.findByTestId("sidebar-content")
- .findByText("Timeline for collection")
- .closest("[aria-label='Timeline card header']")
- .within(() => cy.findByRole("checkbox").click());
+ H.timelineVisibility("Timeline for collection").click();
H.timelineEventChip("TC1").should("be.visible");
// events whose timeline was invisible on page load
// should be hideable once their timelines are visible
- toggleEventVisibility("TC1");
+ H.toggleTimelineEventVisibility("TC1");
H.timelineEventChip("TC1").should("not.exist");
@@ -431,13 +424,13 @@ describe("scenarios > organization > timelines > question", () => {
cy.button("Create").click();
});
- waitForTimelinesAfterCreatingAnEvent("Event at the end of range");
+ H.waitForTimelinesAfterCreatingAnEvent("Event at the end of range");
H.modal().should("not.exist"); // wait for modal to close
cy.log("remove all other events except the new one");
- toggleEventVisibility("RC1").should("not.be.checked");
- toggleEventVisibility("RC2").should("not.be.checked");
+ H.toggleTimelineEventVisibility("RC1").should("not.be.checked");
+ H.toggleTimelineEventVisibility("RC2").should("not.be.checked");
cy.log("the new event should be visible in the chart");
H.timelineEventChip("Event at the end of range").should("be.visible");
@@ -450,9 +443,9 @@ describe("scenarios > organization > timelines > question", () => {
events: [
{ name: "RC1", timestamp: "2027-10-20T00:00:00Z", icon: "star" },
],
- });
+ }).then(({ timeline }) => createQuestionWithTimeline(timeline.id));
- H.visitQuestion(ORDERS_BY_YEAR_QUESTION_ID);
+ H.visitQuestion("@questionId");
H.timelineEventChip("RC1").should("be.visible").realHover();
@@ -586,7 +579,7 @@ describe("scenarios > organization > timelines > question", () => {
H.timelineEventChip("Summer party").should("be.visible");
});
- it("should collapse close events into a count chip and focus the sidebar on the group from 'See all'", () => {
+ it("should collapse close events into a count chip and focus the sidebar on the group from 'See all' or the chip", () => {
H.createTimelineWithEvents({
timeline: { name: "Releases" },
events: [
@@ -635,6 +628,7 @@ describe("scenarios > organization > timelines > question", () => {
cy.findByText("See all").click();
});
+ cy.findByTestId("timeline-event-popover").should("not.exist");
cy.log("'See all' selects the cluster and focuses the sidebar on it");
H.timelineEventChip("4 events").should(
"have.attr",
@@ -642,8 +636,8 @@ describe("scenarios > organization > timelines > question", () => {
"true",
);
cy.findByTestId("sidebar-content").within(() => {
- timelineEventCard("Alpha").should("be.visible");
- timelineEventCard("Delta").should("be.visible");
+ H.timelineEventCard("Alpha").should("be.visible");
+ H.timelineEventCard("Delta").should("be.visible");
});
cy.log("the unrelated timeline is filtered out of the focused list");
@@ -656,55 +650,34 @@ describe("scenarios > organization > timelines > question", () => {
cy.findByTestId("sidebar-content")
.findByText("Other")
.should("be.visible");
- });
-
- it("should focus the sidebar on the group when a grouped chip is clicked directly", () => {
- H.createTimelineWithEvents({
- timeline: { name: "Releases" },
- events: [
- { name: "Alpha", timestamp: "2027-10-03T00:00:00Z" },
- { name: "Beta", timestamp: "2027-10-10T00:00:00Z" },
- ],
- });
- H.createTimelineWithEvents({
- timeline: { name: "Other" },
- events: [{ name: "Outsider", timestamp: "2028-01-15T00:00:00Z" }],
- });
-
- H.visitQuestionAdhoc({
- dataset_query: {
- type: "query",
- query: {
- "source-table": ORDERS_ID,
- aggregation: [["count"]],
- breakout: [
- ["field", ORDERS.CREATED_AT, { "temporal-unit": "month" }],
- ],
- },
- database: SAMPLE_DB_ID,
- },
- display: "line",
- });
- cy.log("clicking a grouped chip focuses the sidebar on its events");
- H.timelineEventChip("2 events").should("be.visible").click();
+ cy.log("clicking the still-selected chip clears the selection");
+ H.timelineEventChip("4 events").click();
+ H.timelineEventChip("4 events").should(
+ "have.attr",
+ "data-selected",
+ "false",
+ );
+ cy.findByTestId("sidebar-content")
+ .findByText("Other")
+ .should("be.visible");
+ cy.log("clicking it again focuses the sidebar on the group");
+ H.timelineEventChip("4 events").click();
+ cy.findByTestId("timeline-sidebar-show-all").should("be.visible");
cy.findByTestId("sidebar-content").within(() => {
- timelineEventCard("Alpha").should("be.visible");
- timelineEventCard("Beta").should("be.visible");
+ H.timelineEventCard("Alpha").should("be.visible");
+ cy.findByText("Other").should("not.exist");
});
- cy.findByTestId("sidebar-content")
- .findByText("Other")
- .should("not.exist");
});
it("should select a single event and open the full sidebar when its chip is clicked", () => {
H.createTimelineWithEvents({
timeline: { name: "Releases" },
events: [{ name: "RC1", timestamp: "2027-01-01T00:00:00Z" }],
- });
+ }).then(({ timeline }) => createQuestionWithTimeline(timeline.id));
- H.visitQuestion(ORDERS_BY_YEAR_QUESTION_ID);
+ H.visitQuestion("@questionId");
H.timelineEventChip("RC1").should("be.visible").click();
@@ -795,6 +768,92 @@ describe("scenarios > organization > timelines > question", () => {
});
});
+ describe("saved selections", () => {
+ beforeEach(() => {
+ cy.signInAsAdmin();
+ cy.intercept("PUT", "/api/card/*").as("updateQuestion");
+ });
+
+ it("should keep changing the display after a selected timeline is deleted", () => {
+ H.createTimelineWithEvents({
+ timeline: { name: "Releases" },
+ events: [{ name: "RC1", timestamp: "2027-10-20T00:00:00Z" }],
+ }).then(({ timeline }) => {
+ H.createQuestion(
+ {
+ name: "Orders by month",
+ display: "table",
+ query: {
+ "source-table": ORDERS_ID,
+ aggregation: [["count"]],
+ breakout: [
+ ["field", ORDERS.CREATED_AT, { "temporal-unit": "month" }],
+ ],
+ },
+ visualization_settings: {
+ "timeline.selected_timeline_ids": [timeline.id],
+ },
+ },
+ { wrapId: true },
+ );
+ cy.request("DELETE", `/api/timeline/${timeline.id}`);
+ });
+
+ H.visitQuestion("@questionId");
+ H.openVizTypeSidebar();
+ H.vizTypeSidebar().findByTestId("Line-button").click();
+ H.echartsContainer().findByText("Created At: Month").should("be.visible");
+ H.saveSavedQuestion();
+
+ cy.get("@updateQuestion").its("response.statusCode").should("eq", 200);
+ cy.findByTestId("qb-header").button("Save").should("not.exist");
+ });
+
+ it("should duplicate a question whose selected timeline the user cannot access", () => {
+ cy.intercept("POST", "/api/card").as("cardCreate");
+ H.createCollection({ name: "Events" }).then(({ body: { id } }) => {
+ H.createTimelineWithEvents({
+ timeline: { name: "Releases", collection_id: id },
+ events: [{ name: "RC1", timestamp: "2027-10-20T00:00:00Z" }],
+ }).then(({ timeline }) => {
+ H.createQuestion(
+ {
+ name: "Orders by month",
+ display: "line",
+ query: {
+ "source-table": ORDERS_ID,
+ aggregation: [["count"]],
+ breakout: [
+ ["field", ORDERS.CREATED_AT, { "temporal-unit": "month" }],
+ ],
+ },
+ visualization_settings: {
+ "timeline.selected_timeline_ids": [timeline.id],
+ },
+ },
+ { wrapId: true },
+ );
+ });
+ cy.updateCollectionGraph({
+ [ALL_USERS_GROUP]: { [id]: "none" },
+ [COLLECTION_GROUP]: { [id]: "none" },
+ [DATA_GROUP]: { [id]: "none" },
+ });
+ });
+
+ cy.signInAsNormalUser();
+ H.visitQuestion("@questionId");
+ H.openQuestionActions();
+ H.popover().findByText("Duplicate").click();
+ H.modal().button("Duplicate").click();
+
+ cy.wait("@cardCreate").its("response.statusCode").should("eq", 200);
+ cy.findByTestId("qb-header-left-side")
+ .findByDisplayValue("Orders by month - Duplicate")
+ .should("be.visible");
+ });
+ });
+
describe("as readonly user", () => {
it("should not allow creating default timelines", () => {
cy.signIn("readonly");
@@ -829,22 +888,61 @@ describe("scenarios > organization > timelines > question", () => {
H.rightSidebar().icon("ellipsis").should("not.exist");
});
});
-});
-function timelineEventCard(eventName) {
- return cy.findByText(eventName).closest("[aria-label='Timeline event card']");
-}
+ describe("analytics", () => {
+ beforeEach(() => {
+ H.resetSnowplow();
+ cy.signInAsAdmin();
+ H.enableTracking();
+ });
-function toggleEventVisibility(eventName) {
- return timelineEventVisibility(eventName).click();
-}
+ afterEach(() => {
+ H.expectNoBadSnowplowEvents();
+ });
-function timelineEventVisibility(eventName) {
- return timelineEventCard(eventName).findByRole("checkbox");
-}
+ it("should track opening the events panel and saving a question with a recorded selection", () => {
+ H.createTimelineWithEvents({
+ timeline: { name: "Releases" },
+ events: [{ name: "RC1", timestamp: "2027-10-20T00:00:00Z" }],
+ }).then(({ timeline }) => createQuestionWithTimeline(timeline.id));
+
+ H.visitQuestion("@questionId");
+ H.timelineEventChip("RC1").should("be.visible");
+
+ cy.icon("calendar").click();
+ H.expectUnstructuredSnowplowEvent({
+ event: "question_events_panel_opened",
+ triggered_from: "footer",
+ });
+
+ H.toggleTimelineEventVisibility("RC1");
+ H.timelineEventChip("RC1").should("not.exist");
+ H.saveSavedQuestion();
+
+ cy.get("@questionId").then((questionId) =>
+ H.expectUnstructuredSnowplowEvent({
+ event: "question_timeline_events_saved",
+ target_id: questionId,
+ }),
+ );
+ });
+ });
+});
-function waitForTimelinesAfterCreatingAnEvent(eventName) {
- return timelineEventCard(eventName)
- .findByText(/^Bobby Tables added this on/)
- .should("be.visible");
+function createQuestionWithTimeline(timelineId) {
+ return H.createQuestion(
+ {
+ name: "Orders by year",
+ display: "line",
+ query: {
+ "source-table": ORDERS_ID,
+ aggregation: [["count"]],
+ breakout: [["field", ORDERS.CREATED_AT, { "temporal-unit": "year" }]],
+ },
+ visualization_settings: {
+ "timeline.selected_timeline_ids": [timelineId],
+ },
+ },
+ { wrapId: true },
+ );
}
diff --git a/e2e/test/scenarios/organization/timelines-sharing.cy.spec.ts b/e2e/test/scenarios/organization/timelines-sharing.cy.spec.ts
new file mode 100644
index 00000000000..c9255a8a0bc
--- /dev/null
+++ b/e2e/test/scenarios/organization/timelines-sharing.cy.spec.ts
@@ -0,0 +1,303 @@
+const { H } = cy;
+
+import { ADMIN_PERSONAL_COLLECTION_ID } from "e2e/support/cypress_sample_instance_data";
+import type { CardId, DashboardId, TimelineId } from "metabase-types/api";
+
+import {
+ TIME_SERIES_QUESTION,
+ createQuestionAndDashboardWithEvents,
+ expectChartWithoutEvents,
+ expectReadOnlyDashboardEvents,
+ interceptTimelineRequests,
+} from "./shared/timeline-events";
+
+describe("scenarios > organization > timelines > public links and embeds", () => {
+ beforeEach(() => {
+ H.restore();
+ cy.signInAsAdmin();
+ createQuestionAndDashboardWithEvents();
+ });
+
+ it("should not show events on a public question", () => {
+ cy.get<CardId>("@questionId").then((id) => H.visitPublicQuestion(id));
+
+ expectChartWithoutEvents();
+ });
+
+ it("should not show events on a static embedded question", () => {
+ cy.get<CardId>("@questionId").then((id) =>
+ H.visitEmbeddedPage({ resource: { question: id }, params: {} }),
+ );
+
+ expectChartWithoutEvents();
+ });
+
+ it("should show only saved events read-only on a public dashboard for anonymous and signed-in viewers, and none once the timeline is archived", () => {
+ cy.get<DashboardId>("@dashboardId").then((id) =>
+ H.visitPublicDashboard(id),
+ );
+
+ expectSharedDashboardEvents();
+
+ cy.log("a signed-in viewer sees the same read-only events");
+ cy.signInAsAdmin();
+ cy.reload();
+
+ expectSharedDashboardEvents();
+
+ cy.log("archiving the timeline removes its events");
+ cy.get<TimelineId>("@timelineId").then((id) =>
+ cy.request("PUT", `/api/timeline/${id}`, { archived: true }),
+ );
+ cy.reload();
+
+ expectChartWithoutEvents();
+ });
+
+ it("should open single and grouped chip details with the keyboard on a public dashboard", () => {
+ cy.get<DashboardId>("@dashboardId").then((id) =>
+ H.visitPublicDashboard(id),
+ );
+
+ H.timelineEventChip("RC1")
+ .should("be.visible")
+ .focus()
+ .should("be.focused");
+
+ cy.log("Enter opens the read-only details");
+ cy.realPress("Enter");
+ cy.findByTestId("timeline-event-popover")
+ .should("contain", "RC1")
+ .and("contain", "The first release candidate is ready.")
+ .and("not.contain", "See all");
+ cy.findByTestId("timeline-event-popover")
+ .findByRole("checkbox")
+ .should("not.exist");
+ cy.findByTestId("dashboard-events-sidebar").should("not.exist");
+
+ cy.log("Escape dismisses the details and returns focus to the chip");
+ cy.realPress("Escape");
+ cy.findByTestId("timeline-event-popover").should("not.exist");
+ H.timelineEventChip("RC1").should("be.focused");
+
+ cy.log("hovering still opens the details");
+ cy.findByTestId("embed-frame-header").realHover();
+ H.timelineEventChip("RC1").realHover();
+ cy.findByTestId("timeline-event-popover").should("contain", "RC1");
+
+ cy.log("a grouped chip lists every event in the group");
+ // park the pointer away from the chip so nothing hovers it after the reload
+ cy.findByTestId("embed-frame-header").realHover();
+ cy.findByTestId("timeline-event-popover").should("not.exist");
+ cy.signInAsAdmin();
+ cy.get<TimelineId>("@timelineId").then((id) =>
+ H.createTimelineEvent({
+ timeline_id: id,
+ name: "RC2",
+ description: "The second release candidate is ready.",
+ timestamp: "2027-10-20T00:00:00Z",
+ }),
+ );
+ cy.reload();
+ H.timelineEventChip("2 events")
+ .should("be.visible")
+ .focus()
+ .should("be.focused");
+ cy.realPress("Enter");
+ cy.findByTestId("timeline-event-popover")
+ .should("contain", "RC1")
+ .and("contain", "RC2")
+ .and("not.contain", "Internal release notes")
+ .and("not.contain", "See all");
+ cy.findByTestId("timeline-event-popover")
+ .findByRole("checkbox")
+ .should("not.exist");
+ cy.findByTestId("dashboard-events-sidebar").should("not.exist");
+ cy.realPress("Escape");
+ cy.findByTestId("timeline-event-popover").should("not.exist");
+ H.timelineEventChip("2 events").should("be.focused");
+ });
+
+ it("should show only saved events read-only on a static embedded dashboard", () => {
+ cy.get<DashboardId>("@dashboardId").then((id) =>
+ H.visitEmbeddedPage({ resource: { dashboard: id }, params: {} }),
+ );
+
+ expectSharedDashboardEvents();
+ });
+
+ it("should show saved events read-only on an interactively embedded dashboard but keep the events panel on the question", () => {
+ // without the token this runs in plain-app mode and asserts the wrong surface
+ H.activateToken("pro-self-hosted");
+ cy.get<DashboardId>("@dashboardId").then((id) =>
+ H.visitFullAppEmbeddingUrl({ url: `/dashboard/${id}`, qs: {} }),
+ );
+
+ expectReadOnlyDashboardEvents();
+ expectDashCardMenuWithoutEvents();
+ H.openDashboardMenu();
+ H.popover()
+ .should("contain", "Enter fullscreen")
+ .and("not.contain", "Events");
+ cy.realPress("Escape");
+
+ H.getDashboardCard().findByText("Orders by month").click();
+
+ H.timelineEventChip("RC1").should("be.visible");
+ cy.findByTestId("view-footer").icon("calendar").click();
+ H.rightSidebar()
+ .should("contain", "Create event")
+ .and("contain", "Releases");
+ });
+
+ it("should not show events of a timeline the viewer cannot read in interactive embedding", () => {
+ H.activateToken("pro-self-hosted");
+ createDashboardWithPrivateTimeline();
+
+ cy.log("the admin who owns the timeline sees it through the same surface");
+ cy.get<DashboardId>("@privateDashboardId").then((id) =>
+ H.visitFullAppEmbeddingUrl({ url: `/dashboard/${id}`, qs: {} }),
+ );
+ H.timelineEventChip("Secret release").should("be.visible");
+
+ cy.signOut();
+ cy.signIn("readonly");
+ cy.get<DashboardId>("@privateDashboardId").then((id) =>
+ H.visitFullAppEmbeddingUrl({ url: `/dashboard/${id}`, qs: {} }),
+ );
+
+ H.echartsContainer().findByText("Created At: Month").should("be.visible");
+ H.timelineEventChip("Secret release").should("not.exist");
+ });
+
+ it("should show events of a timeline the viewer cannot read on a public dashboard", () => {
+ createDashboardWithPrivateTimeline();
+
+ cy.get<DashboardId>("@privateDashboardId").then((id) =>
+ H.visitPublicDashboard(id),
+ );
+ H.timelineEventChip("Secret release").should("be.visible");
+
+ cy.log("and to a signed-in viewer without access to the collection");
+ cy.signIn("readonly");
+ cy.reload();
+ H.timelineEventChip("Secret release").should("be.visible");
+ });
+
+ it("should not show events on a public document", () => {
+ cy.get<CardId>("@questionId").then((id) => {
+ H.createDocument({
+ name: "Document with events",
+ document: {
+ type: "doc",
+ content: [
+ {
+ type: "resizeNode",
+ attrs: { height: 400, minHeight: 280 },
+ content: [
+ { type: "cardEmbed", attrs: { id, name: null, _id: "1" } },
+ ],
+ },
+ ],
+ },
+ idAlias: "documentId",
+ });
+ });
+ H.visitPublicDocument("@documentId");
+
+ expectChartWithoutEvents();
+ });
+
+ it("should not show events in a question embed preview", () => {
+ H.visitQuestion("@questionId");
+ H.timelineEventChip("RC1").should("be.visible");
+
+ interceptTimelineRequests("previewTimelineRequests");
+ cy.intercept("GET", "/api/preview_embed/card/*/query*").as("previewQuery");
+ cy.get<CardId>("@questionId").then((id) => {
+ H.openLegacyStaticEmbeddingModal({
+ resource: "question",
+ resourceId: id,
+ activeTab: "parameters",
+ previewMode: "preview",
+ unpublishBeforeOpen: false,
+ });
+ });
+
+ cy.wait("@previewQuery");
+ H.getIframeBody().within(() => {
+ expectChartWithoutEvents({ requestAlias: "previewTimelineRequests" });
+ });
+ });
+
+ it("should show only saved events read-only in a dashboard embed preview", () => {
+ H.visitDashboard("@dashboardId");
+ H.timelineEventChip("RC1").should("be.visible");
+
+ interceptTimelineRequests("previewTimelineRequests");
+ cy.intercept("GET", "/api/preview_embed/dashboard/*/dashcard/*/card/*").as(
+ "previewQuery",
+ );
+ cy.get<DashboardId>("@dashboardId").then((id) => {
+ H.openLegacyStaticEmbeddingModal({
+ resource: "dashboard",
+ resourceId: id,
+ activeTab: "parameters",
+ previewMode: "preview",
+ unpublishBeforeOpen: false,
+ });
+ });
+
+ cy.wait("@previewQuery");
+ // the preview iframe reloads on interaction, so only assert what is rendered
+ H.getIframeBody().within(() => {
+ H.echartsContainer().findByText("Created At: Month").should("be.visible");
+ cy.findAllByTestId("timeline-event-chip").should("have.length", 1);
+ H.timelineEventChip("RC1").should("be.visible");
+ cy.findByTestId("dashboard-events-sidebar").should("not.exist");
+ cy.findByRole("button", { name: "Events", exact: true }).should(
+ "not.exist",
+ );
+ });
+ cy.get("@previewTimelineRequests.all").should("have.length", 0);
+ });
+});
+
+function expectSharedDashboardEvents() {
+ expectReadOnlyDashboardEvents();
+ expectDashCardMenuWithoutEvents();
+ cy.get("@getTimelines.all").should("have.length", 0);
+}
+
+function expectDashCardMenuWithoutEvents() {
+ H.getDashboardCard().realHover();
+ H.getDashboardCard().findByRole("button", { name: "More options" }).click();
+ H.menu().should("be.visible").findByText("Events").should("not.exist");
+ cy.realPress("Escape");
+}
+
+function createDashboardWithPrivateTimeline() {
+ return H.createTimelineWithEvents({
+ timeline: {
+ name: "Private launches",
+ collection_id: ADMIN_PERSONAL_COLLECTION_ID,
+ },
+ events: [{ name: "Secret release", timestamp: "2027-10-20T00:00:00Z" }],
+ }).then(({ timeline }) =>
+ H.createQuestionAndDashboard({
+ questionDetails: {
+ ...TIME_SERIES_QUESTION,
+ name: "Orders by month, privately",
+ visualization_settings: {
+ "timeline.selected_timeline_ids": [timeline.id],
+ },
+ },
+ dashboardDetails: {
+ name: "Dashboard with a private timeline",
+ enable_embedding: true,
+ },
+ }).then(({ body: { dashboard_id } }) =>
+ cy.wrap(dashboard_id).as("privateDashboardId"),
+ ),
+ );
+}
diff --git a/enterprise/backend/src/metabase_enterprise/serialization/v2/dependency_validation.clj b/enterprise/backend/src/metabase_enterprise/serialization/v2/dependency_validation.clj
index 63a4c6b1bf1..10aec2caed6 100644
--- a/enterprise/backend/src/metabase_enterprise/serialization/v2/dependency_validation.clj
+++ b/enterprise/backend/src/metabase_enterprise/serialization/v2/dependency_validation.clj
@@ -77,21 +77,20 @@
(mapcat #(serialization.db/existing-ids (keyword "model" model) %)))
ids))
-(def ^:private structural-content-models
+(def ^:private optional-content-models
"Content models whose absence from the archive is tolerated on import, so a reference to one is never a completeness
- failure. A selective export routinely omits the Collection tree an entity lives in; the entity then loads at the
- root of the target rather than producing a dangling reference."
- #{"Collection"})
+ failure. Omitted Collections resolve to the target root; [[serdes.models/elidable-content-models]] are dropped."
+ (conj serdes.models/elidable-content-models "Collection"))
(defn- unsatisfied-dependencies
"The `deps` that won't be satisfied in the archive, each tagged with a `:reason` (see the namespace docstring for the
data-model vs content classification). Two subtleties are encoded below: a content reference to a *deleted* entity
is not a failure (export can't emit a portable id for a gone row, so `fk-elide` just drops it), and
- [[structural-content-models]] references are ignored entirely."
+ [[optional-content-models]] references are ignored entirely."
[deps visited analytics-cards]
(let [content-models (set serdes.models/content)
{content-deps true data-deps false} (group-by #(contains? content-models (:model %)) deps)
- content-deps (remove (comp structural-content-models :model) content-deps)
+ content-deps (remove (comp optional-content-models :model) content-deps)
existing-data (m/map-kv-vals existing-ids (u/group-by :model :id data-deps))
existing-content (m/map-kv-vals existing-ids (u/group-by :model :id content-deps))]
(concat
diff --git a/enterprise/backend/src/metabase_enterprise/serialization/v2/load.clj b/enterprise/backend/src/metabase_enterprise/serialization/v2/load.clj
index 6ad42b87aa1..0ff5a078b96 100644
--- a/enterprise/backend/src/metabase_enterprise/serialization/v2/load.clj
+++ b/enterprise/backend/src/metabase_enterprise/serialization/v2/load.clj
@@ -55,10 +55,19 @@
:model model
:error ::no-known-references})))))
+(defn- elidable-missing-dep?
+ "True when `e` reports `dep` itself as missing from both the archive and the destination, and `dep` names a
+ [[serdes.models/elidable-content-models]] entity."
+ [dep e]
+ (let [{:keys [model id]} (last dep)
+ data (ex-data e)]
+ (and (= ::not-found (:error data))
+ (= [model id] [(:model data) (:id data)])
+ (contains? serdes.models/elidable-content-models model))))
+
(defn- load-deps!
- "Given a list of `deps` (hierarchies), [[load-one]] them all.
- If [[load-one]] throws because it can't find that entity in the filesystem, check if it's already loaded in
- our database."
+ "Given a list of `deps` (hierarchies), [[load-one]] them all. A dependency absent from the archive must already exist
+ locally unless it is [[elidable-missing-dep?]]."
[ctx deps]
(if (empty? deps)
ctx
@@ -66,13 +75,8 @@
(try
(load-one! ctx dep)
(catch Exception e
- (cond
- ;; It was missing, but we found it locally, so just return the context.
- (and (= (:error (ex-data e)) ::not-found)
- (serdes/load-find-local dep))
+ (if (elidable-missing-dep? dep e)
ctx
-
- :else
(throw e)))))]
(reduce loader ctx deps))))
diff --git a/enterprise/backend/src/metabase_enterprise/serialization/v2/models.clj b/enterprise/backend/src/metabase_enterprise/serialization/v2/models.clj
index 60c4014f2db..577e7f8185a 100644
--- a/enterprise/backend/src/metabase_enterprise/serialization/v2/models.clj
+++ b/enterprise/backend/src/metabase_enterprise/serialization/v2/models.clj
@@ -34,6 +34,11 @@
"NativeQuerySnippet"
"Timeline"])
+(def elidable-content-models
+ "Content models a reference may name without the target being in the archive or the destination. Such references
+ are dropped on import instead of failing the load."
+ #{"Timeline"})
+
(def exported-models
"The list of all models exported by serialization by default. Used for production code and by tests."
(concat data-model
diff --git a/enterprise/backend/test/metabase_enterprise/serialization/v2/e2e_test.clj b/enterprise/backend/test/metabase_enterprise/serialization/v2/e2e_test.clj
index ee1ab298733..08132efa653 100644
--- a/enterprise/backend/test/metabase_enterprise/serialization/v2/e2e_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/serialization/v2/e2e_test.clj
@@ -1031,6 +1031,138 @@
(str "Expected query to compile but got error: "
(when (map? result) (:error result)))))))))))))))
+(deftest card-timeline-events-preserved-roundtrip-test
+ (testing "questions preserve selected timelines and hidden events after import"
+ (ts/with-random-dump-dir [dump-dir "serdesv2-"]
+ (ts/with-random-dump-dir [timeline-dir "serdesv2-timeline-"]
+ (ts/with-dbs [source-db dest-db]
+ (ts/with-db source-db
+ (mt/with-temp [:model/Collection {collection-id :id} {:name "Bird sightings"}
+ :model/Timeline {timeline-id :id timeline-eid :entity_id}
+ {:name "Migration seasons" :collection_id collection-id}
+ :model/TimelineEvent {event-id :id}
+ {:name "Swallows return" :timeline_id timeline-id :timestamp #t "2027-04-20T00:00:00Z"}
+ :model/TimelineEvent _
+ {:name "Swifts return" :timeline_id timeline-id :timestamp #t "2027-05-01T00:00:00Z"}
+ :model/Card {card-eid :entity_id}
+ {:name "Sightings over time" :collection_id collection-id
+ :visualization_settings {:graph.show_values true
+ :timeline.selected_timeline_ids [timeline-id]
+ :timeline.excluded_timeline_event_ids [event-id]}}]
+ (-> (serdes/with-cache (into [] (extract/extract {:targets [["Collection" collection-id]]})))
+ (storage/store! (storage.files/file-writer dump-dir)))
+ (-> (serdes/with-cache (into [] (extract/extract {:targets [["Timeline" timeline-eid]]})))
+ (storage/store! (storage.files/file-writer timeline-dir)))
+ (ts/with-db dest-db
+ (mt/with-temp [:model/Timeline {decoy-timeline-id :id} {:name "Nesting seasons"}
+ :model/TimelineEvent {decoy-event-id :id}
+ {:name "Sparrows nest" :timeline_id decoy-timeline-id
+ :timestamp #t "2027-04-20T00:00:00Z"}]
+ (is (= timeline-id decoy-timeline-id))
+ (is (= event-id decoy-event-id))
+ (let [archive (ingest/ingest-yaml dump-dir)]
+ (is (serdes/with-cache (serdes.load/load-metabase! archive)))
+ (let [imported-timeline-id (t2/select-one-pk :model/Timeline :entity_id timeline-eid)
+ imported-event-id (t2/select-one-pk :model/TimelineEvent :timeline_id imported-timeline-id
+ :name "Swallows return")
+ expected {:graph.show_values true
+ :timeline.selected_timeline_ids [imported-timeline-id]
+ :timeline.excluded_timeline_event_ids [imported-event-id]}]
+ (is (some? imported-timeline-id))
+ (is (some? imported-event-id))
+ (is (not= timeline-id imported-timeline-id))
+ (is (not= event-id imported-event-id))
+ (is (= expected
+ (t2/select-one-fn :visualization_settings :model/Card :entity_id card-eid)))
+ (testing "importing only the timeline again preserves the existing question's hidden event"
+ (is (serdes/with-cache (serdes.load/load-metabase! (ingest/ingest-yaml timeline-dir))))
+ (is (= imported-event-id
+ (t2/select-one-pk :model/TimelineEvent :timeline_id imported-timeline-id
+ :name "Swallows return")))
+ (is (= expected
+ (t2/select-one-fn :visualization_settings :model/Card :entity_id card-eid)))))))))))))))
+
+(deftest card-timeline-events-empty-selection-roundtrip-test
+ (testing "an empty event selection stays empty and an unrecorded selection stays unrecorded after import"
+ (ts/with-random-dump-dir [dump-dir "serdesv2-"]
+ (ts/with-dbs [source-db dest-db]
+ (ts/with-db source-db
+ (mt/with-temp [:model/Collection {collection-id :id} {:name "Bird sightings"}
+ :model/Card {empty-card-eid :entity_id}
+ {:name "Sightings without events" :collection_id collection-id
+ :visualization_settings {:graph.show_values true
+ :timeline.selected_timeline_ids []
+ :timeline.excluded_timeline_event_ids []}}
+ :model/Card {unrecorded-card-eid :entity_id}
+ {:name "Sightings with default events" :collection_id collection-id
+ :visualization_settings {:graph.show_values true}}]
+ (-> (serdes/with-cache (into [] (extract/extract {:targets [["Collection" collection-id]]})))
+ (storage/store! (storage.files/file-writer dump-dir)))
+ (ts/with-db dest-db
+ (is (serdes/with-cache (serdes.load/load-metabase! (ingest/ingest-yaml dump-dir))))
+ (is (= {:graph.show_values true
+ :timeline.selected_timeline_ids []
+ :timeline.excluded_timeline_event_ids []}
+ (t2/select-one-fn :visualization_settings :model/Card :entity_id empty-card-eid)))
+ (is (= {:graph.show_values true}
+ (t2/select-one-fn :visualization_settings :model/Card :entity_id unrecorded-card-eid))))))))))
+
+(deftest card-timeline-events-missing-timeline-roundtrip-test
+ (testing "a question imports with an empty event selection when its timeline is absent"
+ (ts/with-random-dump-dir [dump-dir "serdesv2-"]
+ (ts/with-dbs [source-db dest-db]
+ (ts/with-db source-db
+ (mt/with-temp [:model/Timeline {timeline-id :id} {:name "Migration seasons"}
+ :model/TimelineEvent {event-id :id}
+ {:name "Swallows return" :timeline_id timeline-id :timestamp #t "2027-04-20T00:00:00Z"}
+ :model/Card {card-eid :entity_id}
+ {:name "Sightings over time"
+ :visualization_settings {:graph.show_values true
+ :timeline.selected_timeline_ids [timeline-id]
+ :timeline.excluded_timeline_event_ids [event-id]}}]
+ (-> (serdes/with-cache (into [] (extract/extract {:targets [["Card" card-eid]]})))
+ (storage/store! (storage.files/file-writer dump-dir)))
+ (ts/with-db dest-db
+ (is (serdes/with-cache (serdes.load/load-metabase! (ingest/ingest-yaml dump-dir))))
+ (is (= {:graph.show_values true
+ :timeline.selected_timeline_ids []
+ :timeline.excluded_timeline_event_ids []}
+ (t2/select-one-fn :visualization_settings :model/Card :entity_id card-eid))))))))))
+
+(deftest card-timeline-events-existing-timeline-roundtrip-test
+ (testing "a question-only archive preserves available timeline choices and ignores a deleted hidden event"
+ (ts/with-random-dump-dir [timeline-dir "serdesv2-timeline-"]
+ (ts/with-random-dump-dir [question-dir "serdesv2-question-"]
+ (ts/with-dbs [source-db dest-db]
+ (ts/with-db source-db
+ (mt/with-temp [:model/Timeline {timeline-id :id timeline-eid :entity_id} {:name "Migration seasons"}
+ :model/TimelineEvent {event-id :id}
+ {:name "Swallows return" :timeline_id timeline-id :timestamp #t "2027-04-20T00:00:00Z"}
+ :model/TimelineEvent {deleted-event-id :id}
+ {:name "Swifts return" :timeline_id timeline-id :timestamp #t "2027-05-01T00:00:00Z"}
+ :model/Card {card-eid :entity_id}
+ {:name "Sightings over time"
+ :visualization_settings {:graph.show_values true
+ :timeline.selected_timeline_ids [timeline-id]
+ :timeline.excluded_timeline_event_ids [event-id
+ deleted-event-id]}}]
+ (-> (serdes/with-cache (into [] (extract/extract {:targets [["Timeline" timeline-eid]]})))
+ (storage/store! (storage.files/file-writer timeline-dir)))
+ (-> (serdes/with-cache (into [] (extract/extract {:targets [["Card" card-eid]]})))
+ (storage/store! (storage.files/file-writer question-dir)))
+ (ts/with-db dest-db
+ (is (serdes/with-cache (serdes.load/load-metabase! (ingest/ingest-yaml timeline-dir))))
+ (let [imported-timeline-id (t2/select-one-pk :model/Timeline :entity_id timeline-eid)
+ imported-event-id (t2/select-one-pk :model/TimelineEvent :timeline_id imported-timeline-id
+ :name "Swallows return")]
+ (is (some? imported-event-id))
+ (t2/delete! :model/TimelineEvent :timeline_id imported-timeline-id :name "Swifts return")
+ (is (serdes/with-cache (serdes.load/load-metabase! (ingest/ingest-yaml question-dir))))
+ (is (= {:graph.show_values true
+ :timeline.selected_timeline_ids [imported-timeline-id]
+ :timeline.excluded_timeline_event_ids [imported-event-id]}
+ (t2/select-one-fn :visualization_settings :model/Card :entity_id card-eid))))))))))))
+
(deftest schema-coercion-test
(ts/with-random-dump-dir [dump-dir "serdesv2-"]
(mt/with-empty-h2-app-db!
diff --git a/enterprise/backend/test/metabase_enterprise/serialization/v2/extract_test.clj b/enterprise/backend/test/metabase_enterprise/serialization/v2/extract_test.clj
index 1472f2cd2b2..fbef6cfcfdd 100644
--- a/enterprise/backend/test/metabase_enterprise/serialization/v2/extract_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/serialization/v2/extract_test.clj
@@ -770,7 +770,7 @@
:collection_id coll-id
:creator_id ann-id}
:model/TimelineEvent
- _
+ {event-eid :entity_id}
{:name "First Event"
:creator_id ann-id
:timestamp #t "2020-04-11T00:00Z"
@@ -793,7 +793,10 @@
:collection_id coll-eid
:creator_id "[email protected]"
:created_at string?
- :events [{:timestamp "2020-04-11T00:00:00Z"
+ :events [{:entity_id event-eid
+ :serdes/meta [{:model "Timeline" :id line-eid}
+ {:model "TimelineEvent" :id event-eid}]
+ :timestamp "2020-04-11T00:00:00Z"
:creator_id "[email protected]"
:created_at string?}]}
ser))
diff --git a/enterprise/backend/test/metabase_enterprise/serialization/v2/load_test.clj b/enterprise/backend/test/metabase_enterprise/serialization/v2/load_test.clj
index 3e3764282e2..2980feeb8cf 100644
--- a/enterprise/backend/test/metabase_enterprise/serialization/v2/load_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/serialization/v2/load_test.clj
@@ -1191,6 +1191,7 @@
user1d (atom nil)
timeline1d (atom nil)
timeline2d (atom nil)
+ event2d (atom nil)
eventsT1 (atom nil)
eventsT2 (atom nil)]
(ts/with-dbs [source-db dest-db]
@@ -1230,6 +1231,7 @@
[:description {:optional true} [:maybe :string]]
[:events [:sequential
[:map
+ [:entity_id :string]
[:timezone :string]
[:time_matters :boolean]
[:name :string]
@@ -1248,12 +1250,16 @@
;; The collection, timeline 1 and event 2 already exist. Event 1, plus timeline 2 and its event 3, are new.
(reset! user1d (ts/create! :model/User :first_name "Tom" :last_name "Scholz" :email "[email protected]"))
(reset! coll1d (ts/create! :model/Collection :name "col1" :entity_id (:entity_id @coll1s)))
- (reset! timeline1d (ts/create! :model/Timeline :name "Some events" :creator_id (:id @user1s)
+ (reset! timeline1d (ts/create! :model/Timeline :name "Some events" :creator_id (:id @user1d)
:entity_id (:entity_id @timeline1s)
:collection_id (:id @coll1d)))
- (ts/create! :model/TimelineEvent :name "Second thing with different name" :timeline_id (:id @timeline1s)
- :timestamp (:timestamp @event2s)
- :creator_id (:id @user1s) :timezone "America/New_York")
+ (reset! event2d (ts/create! :model/TimelineEvent
+ :name "Second thing with different name"
+ :timeline_id (:id @timeline1d)
+ :entity_id (:entity_id @event2s)
+ :timestamp (:timestamp @event2s)
+ :creator_id (:id @user1d)
+ :timezone "America/New_York"))
;; Load the serialized content.
(serdes.load/load-metabase! (ingestion-in-memory @serialized))
;; Fetch the relevant bits
@@ -1266,6 +1272,10 @@
(is (= 1 (count @eventsT2))))
(testing "resulting events match up"
(let [[event1 event2] (sort-by :timestamp @eventsT1)]
+ (is (= (:id @event2d) (:id event2))
+ "the matching event keeps its local ID")
+ (is (= (map :entity_id [@event1s @event2s @event3s])
+ (map :entity_id [event1 event2 (first @eventsT2)])))
(is (= (:timestamp @event1s) (:timestamp event1)))
(is (= (:timestamp @event2s) (:timestamp event2)))
(is (= (:timestamp @event3s)
@@ -1274,6 +1284,37 @@
(:name event2))
"existing event name should be updated")))))))))
+(deftest legacy-timeline-events-without-entity-ids-test
+ (testing "timeline archives created before event entity IDs still import their events"
+ (mt/with-empty-h2-app-db!
+ (ts/with-temp-dpc [:model/User {user-id :id email :email} {}]
+ (let [timeline-eid (u/generate-nano-id)
+ timeline {:serdes/meta [{:model "Timeline" :id timeline-eid}]
+ :entity_id timeline-eid
+ :name "Bird migrations"
+ :icon "star"
+ :creator_id email
+ :created_at "2027-01-01T00:00:00Z"
+ :events [{:serdes/meta [{:model "TimelineEvent" :id nil :label "swallows_return"}]
+ :name "Swallows return"
+ :icon "star"
+ :creator_id email
+ :created_at "2027-01-01T00:00:00Z"
+ :timestamp "2027-04-20T00:00:00Z"
+ :time_matters false
+ :timezone "UTC"}]}]
+ (serdes.load/load-metabase! (ingestion-in-memory [timeline]))
+ (let [timeline-id (t2/select-one-pk :model/Timeline :entity_id timeline-eid)
+ [event] (t2/select :model/TimelineEvent :timeline_id timeline-id)]
+ (is (= 1 (t2/count :model/TimelineEvent :timeline_id timeline-id)))
+ (is (=? {:name "Swallows return"
+ :creator_id user-id
+ :timestamp (t/offset-date-time "2027-04-20T00:00:00Z")
+ :time_matters false
+ :timezone "UTC"
+ :entity_id #(and (string? %) (= 21 (count %)))}
+ event))))))))
+
(deftest users-test
;; Users are serialized as their email address. If a corresponding user is found during deserialization, its ID is
;; used. However, if no such user exists, a new one is created with mostly blank fields.
@@ -1458,6 +1499,44 @@
(is (false? (:is_published @table2d)))
(is (nil? (:collection_id @table2d))))))))))
+(deftest included-timeline-with-missing-collection-fails-import-test
+ (testing "a question cannot import before its included timeline's dependencies, even if the timeline exists locally"
+ (mt/with-empty-h2-app-db!
+ (ts/with-temp-dpc [:model/User {user-id :id email :email} {}
+ :model/Database {db-name :name} {:engine :postgres}
+ :model/Timeline {timeline-eid :entity_id} {:creator_id user-id}]
+ (let [card-eid (u/generate-nano-id)
+ collection-eid (u/generate-nano-id)
+ card-path [{:model "Card" :id card-eid}]
+ timeline-path [{:model "Timeline" :id timeline-eid}]
+ archive (ingestion-in-memory
+ [{:serdes/meta card-path
+ :entity_id card-eid
+ :name "Question with events"
+ :created_at (t/instant)
+ :creator_id email
+ :database_id db-name
+ :dataset_query {:database db-name :type :native :native {:query "SELECT 1"}}
+ :display :line
+ :visualization_settings {:timeline.selected_timeline_ids [timeline-eid]}}
+ {:serdes/meta timeline-path
+ :entity_id timeline-eid
+ :name "Included timeline"
+ :collection_id collection-eid}])
+ ingestion (reify serdes.ingest/Ingestable
+ (ingest-list [_] [card-path timeline-path])
+ (ingest-one [_ path] (serdes.ingest/ingest-one archive path))
+ (ingest-errors [_] []))
+ e (try
+ (serdes.load/load-metabase! ingestion)
+ nil
+ (catch clojure.lang.ExceptionInfo e e))]
+ (is (= {:model "Collection" :id collection-eid :error ::serdes.load/not-found}
+ (select-keys (ex-data e) [:model :id :error])))
+ (is (= {:model "Timeline" :id timeline-eid :name "Included timeline"}
+ (:referrer (ex-data e))))
+ (is (not (t2/exists? :model/Card :entity_id card-eid))))))))
+
(deftest bare-import-test
;; If the dependencies of an entity exist in the receiving database, they don't need to be in the export.
;; This tests that such an import will succeed, and that it still fails when the dependency is not found in
diff --git a/frontend/src/embedding-sdk-bundle/hooks/private/use-sdk-controlled-parameters.unit.spec.ts b/frontend/src/embedding-sdk-bundle/hooks/private/use-sdk-controlled-parameters.unit.spec.ts
index c2eb99144fc..cba4c1f4bf7 100644
--- a/frontend/src/embedding-sdk-bundle/hooks/private/use-sdk-controlled-parameters.unit.spec.ts
+++ b/frontend/src/embedding-sdk-bundle/hooks/private/use-sdk-controlled-parameters.unit.spec.ts
@@ -1,7 +1,14 @@
+import type { ListenerEffectAPI } from "@reduxjs/toolkit";
import { renderHook } from "@testing-library/react";
+import { createMockState } from "__support__/state/state";
import { useSdkDispatch, useSdkSelector } from "embedding-sdk-bundle/store";
import { startSdkListening } from "embedding-sdk-bundle/store/listener-middleware";
+import type {
+ SdkDispatch,
+ SdkStoreState,
+} from "embedding-sdk-bundle/store/types";
+import { createMockSdkState } from "embedding-sdk-bundle/test/mocks/state";
import {
getDashboardComplete,
getParameterValues,
@@ -11,6 +18,7 @@ import type { ParameterValues } from "metabase/embedding-sdk/types/dashboard";
import { setParameterValues } from "metabase/redux/dashboard";
import type { UiParameter } from "metabase-lib/v1/parameters/types";
import type { ParameterValuesMap } from "metabase-types/api";
+import { createMockDashboard } from "metabase-types/api/mocks";
import { useSdkControlledParameters } from "./use-sdk-controlled-parameters";
@@ -22,44 +30,57 @@ jest.mock("embedding-sdk-bundle/store/listener-middleware", () => ({
startSdkListening: jest.fn(),
}));
jest.mock("metabase/dashboard/selectors", () => ({
+ ...jest.requireActual("metabase/dashboard/selectors"),
getDashboardComplete: jest.fn(),
getParameterValues: jest.fn(),
getParameters: jest.fn(),
}));
-// Unjustified type cast. FIXME
-const useSdkDispatchMock = useSdkDispatch as unknown as jest.Mock;
-// Unjustified type cast. FIXME
-const useSdkSelectorMock = useSdkSelector as unknown as jest.Mock;
-// Unjustified type cast. FIXME
-const startSdkListeningMock = startSdkListening as unknown as jest.Mock;
-// Unjustified type cast. FIXME
-const getDashboardCompleteMock = getDashboardComplete as unknown as jest.Mock;
-// Unjustified type cast. FIXME
-const getParameterValuesMock = getParameterValues as unknown as jest.Mock;
-// Unjustified type cast. FIXME
-const getParametersMock = getParameters as unknown as jest.Mock;
-
-// Unjustified type cast. FIXME
-const STATE_PARAM = {
+const useSdkDispatchMock = jest.mocked(useSdkDispatch);
+const useSdkSelectorMock = jest.mocked(useSdkSelector);
+const startSdkListeningMock = jest.mocked(startSdkListening);
+const getDashboardCompleteMock = jest.mocked(getDashboardComplete);
+const getParameterValuesMock = jest.mocked(getParameterValues);
+const getParametersMock = jest.mocked(getParameters);
+
+const STATE_PARAM: UiParameter = {
id: "p1",
slug: "state",
name: "State",
type: "string/=",
target: ["variable", ["template-tag", "state"]],
-} as unknown as UiParameter;
+};
-// Unjustified type cast. FIXME
-const CATEGORY_PARAM = {
+const CATEGORY_PARAM: UiParameter = {
id: "p2",
slug: "category",
name: "Category",
type: "string/=",
target: ["variable", ["template-tag", "category"]],
-} as unknown as UiParameter;
+};
const DEFAULT_DEFINITIONS: UiParameter[] = [STATE_PARAM, CATEGORY_PARAM];
+const sdkStoreState = createMockState({ sdk: createMockSdkState() });
+
+const listenerApi: ListenerEffectAPI<SdkStoreState, SdkDispatch> = {
+ getState: () => sdkStoreState,
+ getOriginalState: () => sdkStoreState,
+ dispatch: jest.fn(),
+ subscribe: jest.fn(),
+ unsubscribe: jest.fn(),
+ condition: jest.fn(),
+ take: jest.fn(),
+ cancelActiveListeners: jest.fn(),
+ cancel: jest.fn(),
+ throwIfCancelled: jest.fn(),
+ signal: new AbortController().signal,
+ delay: jest.fn(),
+ fork: jest.fn(),
+ pause: jest.fn(),
+ extra: undefined,
+};
+
type RenderProps = {
parameters: ParameterValues | null | undefined;
onParametersChange: jest.Mock | undefined;
@@ -102,7 +123,9 @@ const setup = (options: SetupOptions = {}) => {
getParameterValuesMock.mockImplementation(
() => selectorState.appliedParameterValues,
);
- getDashboardCompleteMock.mockReturnValue({ last_used_param_values: {} });
+ getDashboardCompleteMock.mockReturnValue(
+ createMockDashboard({ last_used_param_values: {} }),
+ );
const unsubInitial = jest.fn();
const unsubManual = jest.fn();
@@ -252,7 +275,7 @@ describe("useSdkControlledParameters", () => {
updateSelectors({ appliedParameterValues: pushed });
rerender({ parameters: hostInput, onParametersChange });
- effect({}, { getState: () => ({}) });
+ effect({ type: "test" }, listenerApi);
expect(onParametersChange).not.toHaveBeenCalled();
});
@@ -273,7 +296,7 @@ describe("useSdkControlledParameters", () => {
updateSelectors({ appliedParameterValues: pushed });
rerender({ parameters: { state: "NY" }, onParametersChange });
- effect({}, { getState: () => ({}) });
+ effect({ type: "test" }, listenerApi);
expect(onParametersChange).toHaveBeenCalledTimes(1);
const payload = onParametersChange.mock.calls[0][0];
@@ -299,7 +322,7 @@ describe("useSdkControlledParameters", () => {
updateSelectors({ appliedParameterValues: pushed });
rerender({ parameters: { state: ["NY"] }, onParametersChange });
- effect({}, { getState: () => ({}) });
+ effect({ type: "test" }, listenerApi);
expect(onParametersChange).toHaveBeenCalledTimes(1);
const payload = onParametersChange.mock.calls[0][0];
@@ -327,12 +350,12 @@ describe("useSdkControlledParameters", () => {
// First fire — push applied unchanged, no callback.
updateSelectors({ appliedParameterValues: pushed });
rerender({ parameters: hostInput, onParametersChange });
- effect({}, { getState: () => ({}) });
+ effect({ type: "test" }, listenerApi);
expect(onParametersChange).not.toHaveBeenCalled();
// Second fire — user widget edit (different value, no pending push).
updateSelectors({ appliedParameterValues: { p1: ["CA"] } });
- effect({}, { getState: () => ({}) });
+ effect({ type: "test" }, listenerApi);
expect(onParametersChange).toHaveBeenCalledTimes(1);
expect(onParametersChange.mock.calls[0][0].source).toEqual(
"manual-change",
diff --git a/frontend/src/metabase-types/analytics/timeline.ts b/frontend/src/metabase-types/analytics/timeline.ts
index d54711e3d8f..618dc857dad 100644
--- a/frontend/src/metabase-types/analytics/timeline.ts
+++ b/frontend/src/metabase-types/analytics/timeline.ts
@@ -1,3 +1,5 @@
+import type { TimelineEventSource } from "metabase-types/api";
+
type TimelineEventSchema = {
event: string;
source?: string | null;
@@ -13,7 +15,7 @@ type ValidateEvent<
export type NewEventCreatedEvent = ValidateEvent<{
event: "new_event_created";
- source: "questions" | "collections" | "api";
+ source: TimelineEventSource;
question_id: number | null;
collection_id: number | null;
time_matters: boolean;
diff --git a/frontend/src/metabase-types/api/card.ts b/frontend/src/metabase-types/api/card.ts
index 12b0629f8bf..991b55d7628 100644
--- a/frontend/src/metabase-types/api/card.ts
+++ b/frontend/src/metabase-types/api/card.ts
@@ -566,6 +566,9 @@ export type VisualizationSettings = {
/** Color used for the list entity icon. */
"list.entity_icon_color"?: string;
+ /** Draw timeline events on time series charts. */
+ "timeline_events.enabled"?: boolean;
+
[key: string]: any;
} & EmbedVisualizationSettings;
@@ -627,6 +630,7 @@ export interface CreateCardRequest {
result_metadata?: Field[] | null;
cache_ttl?: number | null;
size?: DashboardCardSize;
+ source_card_id?: CardId;
}
export interface CreateCardFromCsvRequest {
diff --git a/frontend/src/metabase-types/api/dashboard.ts b/frontend/src/metabase-types/api/dashboard.ts
index 46da28800e3..4ed01ee300c 100644
--- a/frontend/src/metabase-types/api/dashboard.ts
+++ b/frontend/src/metabase-types/api/dashboard.ts
@@ -16,6 +16,7 @@ import type {
ParameterValueOrArray,
SingleSeries,
Table,
+ TimelineEvent,
UserId,
UserInfo,
VirtualCardDisplay,
@@ -162,6 +163,7 @@ export type BaseDashboardCard = DashboardCardLayoutAttrs & {
collection_authority_level?: CollectionAuthorityLevel;
entity_id: BaseEntityId;
visualization_settings?: DashCardVisualizationSettings;
+ timeline_events?: TimelineEvent[];
justAdded?: boolean;
created_at: string;
updated_at: string;
diff --git a/frontend/src/metabase-types/api/document.ts b/frontend/src/metabase-types/api/document.ts
index 26625e7e5f8..c8bde95af72 100644
--- a/frontend/src/metabase-types/api/document.ts
+++ b/frontend/src/metabase-types/api/document.ts
@@ -1,6 +1,6 @@
import type { JSONContent } from "@tiptap/core";
-import type { Card } from "./card";
+import type { Card, CardId } from "./card";
import type { Collection, CollectionId } from "./collection";
import type { BaseUser, UserId } from "./user";
@@ -34,14 +34,18 @@ export type Document = {
export type GetDocumentRequest = { id: DocumentId };
+export type DocumentCardToCreate = Card & { source_card_id?: CardId };
+
export type CreateDocumentRequest = Pick<Document, "name"> & {
document: DocumentContent;
collection_id?: CollectionId;
- cards?: Record<number, Card>;
+ cards?: Record<number, DocumentCardToCreate>;
};
export type UpdateDocumentRequest = Pick<Document, "id"> &
- Partial<Omit<Document, "id">>;
+ Partial<Omit<Document, "id" | "cards">> & {
+ cards?: Record<number, DocumentCardToCreate>;
+ };
export type DeleteDocumentRequest = Pick<Document, "id">;
diff --git a/frontend/src/metabase-types/api/timeline.ts b/frontend/src/metabase-types/api/timeline.ts
index 5d6ff7e0869..dc9d91ab71a 100644
--- a/frontend/src/metabase-types/api/timeline.ts
+++ b/frontend/src/metabase-types/api/timeline.ts
@@ -1,4 +1,4 @@
-import type { CardId } from "./card";
+import type { CardId, VisualizationSettings } from "./card";
import type {
Collection,
CollectionId,
@@ -8,7 +8,11 @@ import type { UserInfo } from "./user";
export type TimelineId = number;
export type TimelineEventId = number;
-export type TimelineEventSource = "question" | "collections" | "api";
+export type TimelineEventSource =
+ | "question"
+ | "dashboard"
+ | "collections"
+ | "api";
export type TimelineIcon =
| "info"
@@ -41,7 +45,7 @@ export interface TimelineData {
export interface TimelineEvent extends TimelineEventData {
id: TimelineEventId;
timeline_id: TimelineId;
- creator: UserInfo;
+ creator?: UserInfo;
created_at: string;
}
@@ -59,6 +63,11 @@ export interface TimelineEventData {
question_id?: CardId;
}
+export type TimelineEventsVisibility = Pick<
+ VisualizationSettings,
+ "timeline.selected_timeline_ids" | "timeline.excluded_timeline_event_ids"
+>;
+
export type ListTimelinesRequest = {
include?: "events";
archived?: boolean;
diff --git a/frontend/src/metabase/analytics/event.ts b/frontend/src/metabase/analytics/event.ts
index 3c64f9ecc1d..5c68c5636a0 100644
--- a/frontend/src/metabase/analytics/event.ts
+++ b/frontend/src/metabase/analytics/event.ts
@@ -29,7 +29,7 @@ const VERSIONS: Record<SchemaType, SchemaVersion> = {
serialization: "1-0-1",
settings: "1-0-2",
setup: "1-0-4",
- timeline: "1-0-0",
+ timeline: "1-0-1",
upsell: "1-0-0",
};
diff --git a/frontend/src/metabase/common/components/SaveQuestionForm/types.ts b/frontend/src/metabase/common/components/SaveQuestionForm/types.ts
index 4bd6f4c5021..2fa45ac3d33 100644
--- a/frontend/src/metabase/common/components/SaveQuestionForm/types.ts
+++ b/frontend/src/metabase/common/components/SaveQuestionForm/types.ts
@@ -1,5 +1,6 @@
import type Question from "metabase-lib/v1/Question";
import type {
+ CardId,
CollectionId,
DashboardId,
DashboardTabId,
@@ -12,6 +13,8 @@ export type SaveQuestionProps<C = CollectionId> = {
question: Question,
options?: {
dashboardTabId?: DashboardTabId;
+ sourceCardId?: CardId;
+ sourceQuestion?: Question;
},
) => Promise<Question>;
onSave: (question: Question) => Promise<void>;
@@ -53,12 +56,9 @@ export type UpdateQuestionOptions = {
export type CreateQuestionOptions = {
details: FormValues;
question: Question;
- onCreate: (
- question: Question,
- options?: {
- dashboardTabId?: DashboardTabId | undefined;
- },
- ) => Promise<Question>;
+ sourceCardId?: CardId;
+ sourceQuestion?: Question;
+ onCreate: SaveQuestionProps["onCreate"];
} & Pick<SaveQuestionProps, "targetCollection">;
export type SubmitQuestionOptions = CreateQuestionOptions & {
diff --git a/frontend/src/metabase/common/components/SaveQuestionForm/util.ts b/frontend/src/metabase/common/components/SaveQuestionForm/util.ts
index 5b6754f6706..e1de3c646d2 100644
--- a/frontend/src/metabase/common/components/SaveQuestionForm/util.ts
+++ b/frontend/src/metabase/common/components/SaveQuestionForm/util.ts
@@ -74,7 +74,14 @@ const updateQuestion = async (options: UpdateQuestionOptions) => {
};
export const createQuestion = async (options: CreateQuestionOptions) => {
- const { details, question, onCreate, targetCollection } = options;
+ const {
+ details,
+ question,
+ sourceCardId,
+ sourceQuestion,
+ onCreate,
+ targetCollection,
+ } = options;
if (details.saveType !== "create") {
return;
@@ -104,7 +111,11 @@ export const createQuestion = async (options: CreateQuestionOptions) => {
const isMetric = question.type() === "metric";
try {
- const result = await onCreate(newQuestion, { dashboardTabId });
+ const result = await onCreate(newQuestion, {
+ dashboardTabId,
+ sourceCardId,
+ sourceQuestion,
+ });
if (isMetric) {
trackMetricCreated("success", "main_app", result.id());
@@ -136,9 +147,13 @@ export async function submitQuestion(options: SubmitQuestionOptions) {
onSave,
});
} else {
+ // A question saved as a new one keeps the original's timeline selection, so the
+ // backend treats it as a copy rather than re-checking every selected timeline.
await createQuestion({
question,
details,
+ sourceCardId: originalQuestion?.id(),
+ sourceQuestion: originalQuestion ?? undefined,
onCreate,
targetCollection,
});
diff --git a/frontend/src/metabase/common/utils/timelines.ts b/frontend/src/metabase/common/utils/timelines.ts
index f6fa6ec17ca..7aa454ca8c2 100644
--- a/frontend/src/metabase/common/utils/timelines.ts
+++ b/frontend/src/metabase/common/utils/timelines.ts
@@ -1,9 +1,14 @@
import { t } from "ttag";
import _ from "underscore";
-import { canonicalCollectionId } from "metabase/common/collections/utils";
+import {
+ canonicalCollectionId,
+ canonicalCollectionIdOrEntityId,
+} from "metabase/common/collections/utils";
import type {
Collection,
+ CollectionId,
+ CreateTimelineRequest,
IconName,
Timeline,
TimelineIcon,
@@ -37,7 +42,7 @@ export const getTimelineIcons = (): {
export const getDefaultTimeline = (
collection: Collection,
-): Partial<Timeline> => {
+): CreateTimelineRequest => {
return {
name: getDefaultTimelineName(collection),
collection_id: canonicalCollectionId(collection.id),
@@ -46,6 +51,28 @@ export const getDefaultTimeline = (
};
};
+/**
+ * null, "root" and "tenant" mean the root collection, whose timelines have a
+ * null collection_id. Regular collections can be addressed by numeric or entity id.
+ */
+export const isCollectionTimeline = (
+ timeline: Timeline,
+ collectionId: CollectionId | null | undefined,
+) => {
+ const canonicalId = canonicalCollectionIdOrEntityId(collectionId);
+
+ return canonicalId === null
+ ? timeline.collection_id == null
+ : timeline.collection_id === canonicalId ||
+ timeline.collection?.entity_id === canonicalId;
+};
+
+export const getCollectionTimelines = (
+ timelines: Timeline[],
+ collectionId: CollectionId | null | undefined,
+): Timeline[] =>
+ timelines.filter((timeline) => isCollectionTimeline(timeline, collectionId));
+
export const getDefaultTimelineName = (collection: Collection) => {
return t`${collection.name} events`;
};
diff --git a/frontend/src/metabase/common/utils/timelines.unit.spec.ts b/frontend/src/metabase/common/utils/timelines.unit.spec.ts
new file mode 100644
index 00000000000..74844092284
--- /dev/null
+++ b/frontend/src/metabase/common/utils/timelines.unit.spec.ts
@@ -0,0 +1,55 @@
+import {
+ createMockCollection,
+ createMockTimeline,
+} from "metabase-types/api/mocks";
+import { createMockEntityId } from "metabase-types/api/mocks/entity-id";
+
+import { getCollectionTimelines } from "./timelines";
+
+const COLLECTION_ID = 7;
+const COLLECTION_ENTITY_ID = createMockEntityId();
+
+const releases = createMockTimeline({
+ id: 1,
+ collection_id: COLLECTION_ID,
+ collection: createMockCollection({
+ id: COLLECTION_ID,
+ entity_id: COLLECTION_ENTITY_ID,
+ }),
+});
+const incidents = createMockTimeline({ id: 2, collection_id: 99 });
+const rootTimeline = createMockTimeline({ id: 3, collection_id: null });
+const timelines = [releases, incidents, rootTimeline];
+
+describe("getCollectionTimelines", () => {
+ it("returns the timelines of the given collection", () => {
+ expect(getCollectionTimelines(timelines, COLLECTION_ID)).toEqual([
+ releases,
+ ]);
+ });
+
+ it("returns the timelines addressed by a numeric collection id string", () => {
+ expect(getCollectionTimelines(timelines, String(COLLECTION_ID))).toEqual([
+ releases,
+ ]);
+ });
+
+ it("returns the timelines addressed by collection entity id", () => {
+ expect(getCollectionTimelines(timelines, COLLECTION_ENTITY_ID)).toEqual([
+ releases,
+ ]);
+ });
+
+ it.each([null, undefined, "root", "tenant"] as const)(
+ "returns root timelines for collection %s",
+ (collectionId) => {
+ expect(getCollectionTimelines(timelines, collectionId)).toEqual([
+ rootTimeline,
+ ]);
+ },
+ );
+
+ it("returns nothing for pseudo collections", () => {
+ expect(getCollectionTimelines(timelines, "personal")).toEqual([]);
+ });
+});
diff --git a/frontend/src/metabase/dashboard/actions/index.ts b/frontend/src/metabase/dashboard/actions/index.ts
index d2bc502baae..e2a2fed0e79 100644
--- a/frontend/src/metabase/dashboard/actions/index.ts
+++ b/frontend/src/metabase/dashboard/actions/index.ts
@@ -11,4 +11,5 @@ export * from "./ui";
export * from "./actions";
export * from "./tabs";
export * from "./tabs-thunks";
+export * from "./timeline-events";
export * from "./trash";
diff --git a/frontend/src/metabase/dashboard/actions/timeline-events.ts b/frontend/src/metabase/dashboard/actions/timeline-events.ts
new file mode 100644
index 00000000000..42348f3ccf4
--- /dev/null
+++ b/frontend/src/metabase/dashboard/actions/timeline-events.ts
@@ -0,0 +1,115 @@
+import { createAction } from "@reduxjs/toolkit";
+
+import {
+ type DashboardEventsPanelLocation,
+ type DashboardEventsVisibilityLocation,
+ trackDashboardEventsPanelOpened,
+ trackDashboardEventsShown,
+ trackDashboardEventsVisibilityChanged,
+} from "metabase/dashboard/analytics";
+import { SIDEBAR_NAME } from "metabase/dashboard/constants";
+import { getDashboard } from "metabase/dashboard/selectors";
+import { getDashCardTimelineEventsVisibility } from "metabase/dashboard/timeline-events/selectors";
+import type {
+ Dispatch,
+ EventsSidebarProps,
+ GetState,
+ TimelineEventsSelection,
+} from "metabase/redux/store";
+import { getTransformedTimelines } from "metabase/timelines/panel/selectors";
+import { isSameTimelineEventsVisibility } from "metabase/visualizations/lib/timeline-events-visibility";
+import type {
+ TimelineEventsVisibilityIntent,
+ TimelineEventsVisibilityUpdate,
+} from "metabase/visualizations/types";
+import type { DashCardId, TimelineEventsVisibility } from "metabase-types/api";
+
+import { setSidebar } from "./ui";
+
+export const setDashCardTimelineEventsVisibility = createAction<
+ Record<DashCardId, TimelineEventsVisibility>
+>("metabase/dashboard/SET_DASHCARD_TIMELINE_EVENTS_VISIBILITY");
+
+export const setDashCardTimelineEventsEnabled = createAction<{
+ dashcardId: DashCardId;
+ isEnabled: boolean;
+}>("metabase/dashboard/SET_DASHCARD_TIMELINE_EVENTS_ENABLED");
+
+export const selectTimelineEvents = createAction<TimelineEventsSelection>(
+ "metabase/dashboard/SELECT_TIMELINE_EVENTS",
+);
+
+export const deselectTimelineEvents = createAction(
+ "metabase/dashboard/DESELECT_TIMELINE_EVENTS",
+);
+
+export const markTimelineEventsShown = createAction(
+ "metabase/dashboard/MARK_TIMELINE_EVENTS_SHOWN",
+);
+
+export const trackTimelineEventsShown =
+ () => (dispatch: Dispatch, getState: GetState) => {
+ const state = getState();
+ const dashboardId = getDashboard(state)?.id;
+ if (
+ dashboardId == null ||
+ state.dashboard.timelineEvents.hasTrackedEventsShown
+ ) {
+ return;
+ }
+ dispatch(markTimelineEventsShown());
+ trackDashboardEventsShown(dashboardId);
+ };
+
+export const openEventsSidebar =
+ (props: EventsSidebarProps = {}, location?: DashboardEventsPanelLocation) =>
+ (dispatch: Dispatch, getState: GetState) => {
+ const state = getState();
+ const wasOpen = state.dashboard.sidebar.name === SIDEBAR_NAME.events;
+ dispatch(setSidebar({ name: SIDEBAR_NAME.events, props }));
+ if (location && !wasOpen) {
+ trackDashboardEventsPanelOpened(getDashboard(state)?.id, location);
+ }
+ };
+
+type VisibilityTracking = {
+ location: DashboardEventsVisibilityLocation;
+ intent: TimelineEventsVisibilityIntent;
+};
+
+export const updateDashCardsTimelineEventsVisibility =
+ (
+ dashcardIds: DashCardId[],
+ update: TimelineEventsVisibilityUpdate,
+ { location, intent }: VisibilityTracking,
+ ) =>
+ (dispatch: Dispatch, getState: GetState) => {
+ const state = getState();
+ const timelines = getTransformedTimelines(state);
+
+ const changed = dashcardIds.flatMap(
+ (dashcardId): [DashCardId, TimelineEventsVisibility][] => {
+ const visibility =
+ getDashCardTimelineEventsVisibility(state, dashcardId) ?? {};
+ const nextVisibility = update(visibility, timelines);
+ return isSameTimelineEventsVisibility(visibility, nextVisibility)
+ ? []
+ : [[dashcardId, nextVisibility]];
+ },
+ );
+
+ if (changed.length === 0) {
+ return;
+ }
+
+ dispatch(setDashCardTimelineEventsVisibility(Object.fromEntries(changed)));
+
+ // creating an event is already reported as new_event_created
+ if (intent !== "create") {
+ trackDashboardEventsVisibilityChanged(
+ getDashboard(state)?.id,
+ location,
+ intent === "show" ? "shown" : "hidden",
+ );
+ }
+ };
diff --git a/frontend/src/metabase/dashboard/actions/timeline-events.unit.spec.ts b/frontend/src/metabase/dashboard/actions/timeline-events.unit.spec.ts
new file mode 100644
index 00000000000..065221f6c15
--- /dev/null
+++ b/frontend/src/metabase/dashboard/actions/timeline-events.unit.spec.ts
@@ -0,0 +1,266 @@
+import { getMainStore } from "__support__/entities-store";
+import {
+ createMockApiState,
+ createMockDashboardState,
+ createMockState,
+ createMockStoreDashboard,
+ seedApiQueryCache,
+} from "__support__/state";
+import { getDashCardById } from "metabase/dashboard/selectors";
+import {
+ getDashCardTimelineEventsVisibility,
+ getDashCardVisibleTimelineEventIds,
+} from "metabase/dashboard/timeline-events/selectors";
+import {
+ hideTimelineEvents,
+ showCreatedTimelineEvent,
+ showTimelineEvents,
+ showTimelines,
+} from "metabase/visualizations/lib/timeline-events-visibility";
+import type { SimpleEventSchema } from "metabase-types/analytics";
+import type { VisualizationSettings } from "metabase-types/api";
+import {
+ createMockCard,
+ createMockDashboardCard,
+ createMockTimeline,
+ createMockTimelineEvent,
+} from "metabase-types/api/mocks";
+
+import { updateDashCardsTimelineEventsVisibility } from "./timeline-events";
+
+const { trackSimpleEvent } = jest.requireMock("metabase/analytics");
+
+const DASHBOARD_ID = 1;
+const DASHCARD_ID = 1;
+
+const eventA = createMockTimelineEvent({
+ id: 100,
+ timeline_id: 10,
+ timestamp: "2021-12-25T00:00:00Z",
+});
+const eventB = createMockTimelineEvent({
+ id: 101,
+ timeline_id: 10,
+ timestamp: "2021-12-26T00:00:00Z",
+});
+const timeline = createMockTimeline({ id: 10, events: [eventA, eventB] });
+
+// a timeline the events sidebar can select before the refetch lands
+const unloadedTimelineId = 11;
+
+function setup({
+ savedVisibility,
+ duplicateQuestion = false,
+}: {
+ savedVisibility?: VisualizationSettings;
+ duplicateQuestion?: boolean;
+} = {}) {
+ const card = createMockCard({
+ visualization_settings: { ...savedVisibility },
+ });
+ const dashcards = [
+ createMockDashboardCard({
+ id: DASHCARD_ID,
+ card,
+ visualization_settings: { "card.title": "First placement" },
+ }),
+ ...(duplicateQuestion
+ ? [
+ createMockDashboardCard({
+ id: 2,
+ card,
+ visualization_settings: { "card.title": "Second placement" },
+ }),
+ ]
+ : []),
+ ];
+ return getMainStore(
+ createMockState({
+ dashboard: createMockDashboardState({
+ dashboardId: DASHBOARD_ID,
+ dashboards: {
+ [DASHBOARD_ID]: createMockStoreDashboard({
+ id: DASHBOARD_ID,
+ dashcards: dashcards.map(({ id }) => id),
+ }),
+ },
+ dashcards: Object.fromEntries(
+ dashcards.map((dashcard) => [dashcard.id, dashcard]),
+ ),
+ }),
+ "metabase-api": seedApiQueryCache(createMockApiState(), [
+ {
+ endpointName: "listTimelines",
+ arg: { include: "events" },
+ value: [timeline],
+ },
+ ]),
+ }),
+ );
+}
+
+type Store = ReturnType<typeof setup>;
+
+const getVisibleEventIds = (store: Store) =>
+ getDashCardVisibleTimelineEventIds(store.getState(), DASHCARD_ID);
+
+const getDashCard = (store: Store) =>
+ getDashCardById(store.getState(), DASHCARD_ID);
+
+const getReportedVisibilityChanges = () => {
+ const events: SimpleEventSchema[] = trackSimpleEvent.mock.calls.map(
+ ([event]: [SimpleEventSchema]) => event,
+ );
+ return events
+ .filter(({ event }) => event === "dashboard_events_visibility_changed")
+ .map(({ event_detail }) => event_detail);
+};
+
+describe("dashboard timeline events visibility", () => {
+ beforeEach(() => {
+ trackSimpleEvent.mockClear();
+ });
+
+ it("shows the events the question was saved with", () => {
+ const store = setup({
+ savedVisibility: {
+ "timeline.selected_timeline_ids": [timeline.id],
+ "timeline.excluded_timeline_event_ids": [eventB.id],
+ },
+ });
+
+ expect(getVisibleEventIds(store)).toEqual([eventA.id]);
+ });
+
+ it("lets a viewer show events for their session without touching the question", () => {
+ const store = setup();
+
+ store.dispatch(
+ updateDashCardsTimelineEventsVisibility(
+ [DASHCARD_ID],
+ (visibility, timelines) =>
+ showTimelines(visibility, [timeline.id], timelines),
+ { location: "dashboard", intent: "show" },
+ ),
+ );
+
+ expect(getVisibleEventIds(store)).toEqual([eventA.id, eventB.id]);
+ expect(getDashCard(store).card.visualization_settings).toEqual({});
+ expect(getDashCard(store).isDirty).toBeFalsy();
+ });
+
+ it("changes only the targeted placement of a question and preserves both saved settings", () => {
+ const savedVisibility = {
+ "graph.show_values": true,
+ "timeline.selected_timeline_ids": [timeline.id],
+ "timeline.excluded_timeline_event_ids": [],
+ };
+ const store = setup({ savedVisibility, duplicateQuestion: true });
+ const savedDashcards = store.getState().dashboard.dashcards;
+
+ store.dispatch(
+ updateDashCardsTimelineEventsVisibility(
+ [DASHCARD_ID],
+ (visibility, timelines) =>
+ hideTimelineEvents(visibility, [eventA], timelines),
+ { location: "dashboard", intent: "hide" },
+ ),
+ );
+
+ expect(getVisibleEventIds(store)).toEqual([eventB.id]);
+ expect(getDashCardVisibleTimelineEventIds(store.getState(), 2)).toEqual([
+ eventA.id,
+ eventB.id,
+ ]);
+ expect(store.getState().dashboard.dashcards).toEqual(savedDashcards);
+ });
+
+ it("tracks hiding and showing events for the session", () => {
+ const store = setup({
+ savedVisibility: {
+ "timeline.selected_timeline_ids": [timeline.id],
+ "timeline.excluded_timeline_event_ids": [],
+ },
+ });
+
+ store.dispatch(
+ updateDashCardsTimelineEventsVisibility(
+ [DASHCARD_ID],
+ (visibility, timelines) =>
+ hideTimelineEvents(visibility, [eventA], timelines),
+ { location: "dashcard", intent: "hide" },
+ ),
+ );
+
+ expect(trackSimpleEvent).toHaveBeenLastCalledWith({
+ event: "dashboard_events_visibility_changed",
+ target_id: DASHBOARD_ID,
+ triggered_from: "dashcard",
+ event_detail: "hidden",
+ });
+
+ store.dispatch(
+ updateDashCardsTimelineEventsVisibility(
+ [DASHCARD_ID],
+ (visibility, timelines) =>
+ showTimelineEvents(visibility, [eventA], timelines),
+ { location: "dashboard", intent: "show" },
+ ),
+ );
+
+ expect(trackSimpleEvent).toHaveBeenLastCalledWith({
+ event: "dashboard_events_visibility_changed",
+ target_id: DASHBOARD_ID,
+ triggered_from: "dashboard",
+ event_detail: "shown",
+ });
+ expect(trackSimpleEvent).toHaveBeenCalledTimes(2);
+ });
+
+ it("keeps the session as it is when a toggle is already applied", () => {
+ const store = setup({
+ savedVisibility: {
+ "timeline.selected_timeline_ids": [timeline.id],
+ "timeline.excluded_timeline_event_ids": [],
+ },
+ });
+
+ store.dispatch(
+ updateDashCardsTimelineEventsVisibility(
+ [DASHCARD_ID],
+ (visibility, timelines) =>
+ showTimelines(visibility, [timeline.id], timelines),
+ { location: "dashboard", intent: "show" },
+ ),
+ );
+
+ expect(getVisibleEventIds(store)).toEqual([eventA.id, eventB.id]);
+ expect(getReportedVisibilityChanges()).toEqual([]);
+ });
+
+ it("makes a created event visible for the session", () => {
+ const store = setup();
+ const createdEvent = createMockTimelineEvent({
+ id: 102,
+ timeline_id: unloadedTimelineId,
+ timestamp: "2021-12-27T00:00:00Z",
+ });
+
+ store.dispatch(
+ updateDashCardsTimelineEventsVisibility(
+ [DASHCARD_ID],
+ (visibility, timelines) =>
+ showCreatedTimelineEvent(visibility, createdEvent, timelines),
+ { location: "dashboard", intent: "create" },
+ ),
+ );
+
+ expect(
+ getDashCardTimelineEventsVisibility(store.getState(), DASHCARD_ID),
+ ).toEqual({
+ "timeline.selected_timeline_ids": [unloadedTimelineId],
+ "timeline.excluded_timeline_event_ids": [],
+ });
+ expect(getReportedVisibilityChanges()).toEqual([]);
+ });
+});
diff --git a/frontend/src/metabase/dashboard/actions/ui.ts b/frontend/src/metabase/dashboard/actions/ui.ts
index 712823cc621..eeb37815d7c 100644
--- a/frontend/src/metabase/dashboard/actions/ui.ts
+++ b/frontend/src/metabase/dashboard/actions/ui.ts
@@ -1,7 +1,10 @@
+import { createAction as createTypedAction } from "@reduxjs/toolkit";
+
import { SIDEBAR_NAME } from "metabase/dashboard/constants";
import { createAction, createThunkAction } from "metabase/redux";
import type {
DashboardSidebarName,
+ DashboardSidebarState,
Dispatch,
GetState,
} from "metabase/redux/store";
@@ -12,7 +15,10 @@ import { getSidebar } from "../selectors";
import { closeAutoApplyFiltersToast } from "./parameters";
export const SET_SIDEBAR = "metabase/dashboard/SET_SIDEBAR";
-export const setSidebar = createAction(SET_SIDEBAR);
+export const setSidebar = createTypedAction<{
+ name: DashboardSidebarName;
+ props?: DashboardSidebarState["props"];
+}>(SET_SIDEBAR);
export const CLOSE_SIDEBAR = "metabase/dashboard/CLOSE_SIDEBAR";
export const closeSidebar = createAction(CLOSE_SIDEBAR);
diff --git a/frontend/src/metabase/dashboard/analytics.ts b/frontend/src/metabase/dashboard/analytics.ts
index 01fa1ed122f..c714f1b5b7d 100644
--- a/frontend/src/metabase/dashboard/analytics.ts
+++ b/frontend/src/metabase/dashboard/analytics.ts
@@ -167,3 +167,42 @@ export const trackDashboardBookmarked = () => {
triggered_from: "dashboard_header",
});
};
+
+export const trackDashboardEventsShown = (dashboardId: DashboardId) => {
+ trackSimpleEvent({
+ event: "dashboard_events_shown",
+ target_id: getDashboardId(dashboardId),
+ });
+};
+
+export type DashboardEventsPanelLocation =
+ | "chart"
+ | "dashcard_menu"
+ | "dashboard_menu";
+
+export const trackDashboardEventsPanelOpened = (
+ dashboardId: DashboardId | undefined,
+ location: DashboardEventsPanelLocation,
+) => {
+ trackSimpleEvent({
+ event: "dashboard_events_panel_opened",
+ target_id: getDashboardId(dashboardId),
+ triggered_from: location,
+ });
+};
+
+export type DashboardEventsVisibilityLocation = "dashboard" | "dashcard";
+export type DashboardEventsVisibilityChange = "shown" | "hidden";
+
+export const trackDashboardEventsVisibilityChanged = (
+ dashboardId: DashboardId | undefined,
+ location: DashboardEventsVisibilityLocation,
+ change: DashboardEventsVisibilityChange,
+) => {
+ trackSimpleEvent({
+ event: "dashboard_events_visibility_changed",
+ target_id: getDashboardId(dashboardId),
+ triggered_from: location,
+ event_detail: change,
+ });
+};
diff --git a/frontend/src/metabase/dashboard/components/DashCard/DashCardMenu/DashCardMenu.tsx b/frontend/src/metabase/dashboard/components/DashCard/DashCardMenu/DashCardMenu.tsx
index 56d93d1b7ff..ecd0e166149 100644
--- a/frontend/src/metabase/dashboard/components/DashCard/DashCardMenu/DashCardMenu.tsx
+++ b/frontend/src/metabase/dashboard/components/DashCard/DashCardMenu/DashCardMenu.tsx
@@ -32,6 +32,7 @@ interface DashCardMenuProps {
onEditVisualization?: () => void;
openUnderlyingQuestionItems?: React.ReactNode[];
canEdit?: boolean;
+ withTimelineEvents?: boolean;
}
function isDashCardMenuEmpty(
@@ -56,6 +57,7 @@ export const DashCardMenu = ({
onEditVisualization,
openUnderlyingQuestionItems,
canEdit,
+ withTimelineEvents = false,
}: DashCardMenuProps) => {
const store = useStore();
@@ -122,6 +124,7 @@ export const DashCardMenu = ({
onDownload={() => setMenuView("download")}
onEditVisualization={onEditVisualization}
canEdit={canEdit}
+ withTimelineEvents={withTimelineEvents}
/>
{!!openUnderlyingQuestionItems?.length && (
<Menu.Sub position="right" shadow="sm">
@@ -159,6 +162,7 @@ export const DashCardMenu = ({
type ShouldRenderDashcardMenuProps = {
question: Question | null;
result?: Dataset;
+ withTimelineEvents?: boolean;
} & Pick<DashboardContextReturned, "dashboard" | "dashcardMenu"> &
Pick<DashCardMenuProps, "canEdit" | "openUnderlyingQuestionItems">;
@@ -169,6 +173,7 @@ DashCardMenu.shouldRender = ({
result,
canEdit,
openUnderlyingQuestionItems,
+ withTimelineEvents = false,
}: ShouldRenderDashcardMenuProps) => {
if (!question || !dashboard || dashcardMenu === null) {
return null;
@@ -184,6 +189,7 @@ DashCardMenu.shouldRender = ({
!isInternalQuery &&
((canEdit && canEditQuestion(question)) ||
canDownloadResults(result) ||
- !!openUnderlyingQuestionItems?.length)
+ !!openUnderlyingQuestionItems?.length ||
+ withTimelineEvents)
);
};
diff --git a/frontend/src/metabase/dashboard/components/DashCard/DashCardMenu/DashCardMenuItems.tsx b/frontend/src/metabase/dashboard/components/DashCard/DashCardMenu/DashCardMenuItems.tsx
index 1cdfc289a66..bab7cafb8ec 100644
--- a/frontend/src/metabase/dashboard/components/DashCard/DashCardMenu/DashCardMenuItems.tsx
+++ b/frontend/src/metabase/dashboard/components/DashCard/DashCardMenu/DashCardMenuItems.tsx
@@ -2,7 +2,7 @@ import { useMemo } from "react";
import { t } from "ttag";
import { canDownloadResults } from "metabase/common/utils/dataset";
-import { editQuestion } from "metabase/dashboard/actions";
+import { editQuestion, openEventsSidebar } from "metabase/dashboard/actions";
import { useDashboardContext } from "metabase/dashboard/context";
import { transformSdkQuestion } from "metabase/embedding-sdk/lib/transform-question";
import type {
@@ -17,21 +17,24 @@ import type { DashCardId, Dataset } from "metabase-types/api";
import { canEditQuestion } from "./utils";
type DashCardMenuItemsProps = {
+ dashcardId: DashCardId;
question: Question;
result: Dataset;
isDownloadingData: boolean;
onDownload: () => void;
onEditVisualization?: () => void;
- dashcardId?: DashCardId;
canEdit?: boolean;
+ withTimelineEvents?: boolean;
};
export const DashCardMenuItems = ({
+ dashcardId,
question,
result,
isDownloadingData,
onDownload,
onEditVisualization,
canEdit,
+ withTimelineEvents = false,
}: DashCardMenuItemsProps) => {
const dispatch = useDispatch();
@@ -93,6 +96,16 @@ export const DashCardMenuItems = ({
}
}
+ if (withTimelineEvents) {
+ items.push({
+ key: "MB_TIMELINE_EVENTS",
+ iconName: "calendar",
+ label: t`Events`,
+ onClick: () =>
+ dispatch(openEventsSidebar({ dashcardId }, "dashcard_menu")),
+ });
+ }
+
if (withDownloads && canDownloadResults(result)) {
items.push({
key: "MB_DOWNLOAD_RESULTS",
@@ -130,6 +143,9 @@ export const DashCardMenuItems = ({
result,
withDownloads,
withEditLink,
+ withTimelineEvents,
+ dashcardId,
+ dispatch,
onEditVisualization,
canEdit,
]);
diff --git a/frontend/src/metabase/dashboard/components/DashCard/DashCardVisualization.tsx b/frontend/src/metabase/dashboard/components/DashCard/DashCardVisualization.tsx
index 98e6d61518a..b6dde03f129 100644
--- a/frontend/src/metabase/dashboard/components/DashCard/DashCardVisualization.tsx
+++ b/frontend/src/metabase/dashboard/components/DashCard/DashCardVisualization.tsx
@@ -15,6 +15,11 @@ import {
getDashCardInlineValuePopulatedParameters,
getDashcardData,
} from "metabase/dashboard/selectors";
+import {
+ getIsDashCardTimelineEventsEnabled,
+ useDashCardTimelineEvents,
+ useReportDashCardTimelineEventsEnabled,
+} from "metabase/dashboard/timeline-events";
import {
getVirtualCardType,
isDashcardAccessRestricted,
@@ -490,6 +495,24 @@ export function DashCardVisualization({
bufferSpace: 100,
});
+ const {
+ isEnabled: isTimelineEventsEnabled,
+ timelineEvents,
+ timelineEventsVisibility,
+ selectedTimelineEventIds,
+ onOpenTimelines,
+ onSelectTimelineEvents,
+ onDeselectTimelineEvents,
+ onTimelineEventsShown,
+ } = useDashCardTimelineEvents(dashcard);
+ const isChartTimelineEventsEnabled = useSelector((state) =>
+ getIsDashCardTimelineEventsEnabled(state, dashcard.id),
+ );
+ const handleTimelineEventsEnabledChange =
+ useReportDashCardTimelineEventsEnabled(dashcard.id);
+ const withTimelineEvents =
+ isTimelineEventsEnabled && isChartTimelineEventsEnabled;
+
const actionButtons = useMemo(() => {
const cardId = dashcard.card_id ?? dashcard.card?.id;
const cardResult = cardId ? datasets?.[cardId] : undefined;
@@ -508,6 +531,7 @@ export function DashCardVisualization({
result,
canEdit: !isVisualizerCard,
openUnderlyingQuestionItems,
+ withTimelineEvents,
});
const errorStatus =
@@ -541,6 +565,7 @@ export function DashCardVisualization({
result={result}
dashcard={dashcard}
canEdit={!isVisualizerCard}
+ withTimelineEvents={withTimelineEvents}
onEditVisualization={
isVisualizerCard ? onEditVisualization : undefined
}
@@ -556,6 +581,7 @@ export function DashCardVisualization({
dashcardMenu,
datasets,
isEditing,
+ withTimelineEvents,
inlineParameters,
onChangeCardAndRun,
onEditVisualization,
@@ -642,6 +668,14 @@ export function DashCardVisualization({
renderLoadingView={renderLoadingView}
titleMenuItems={titleMenuItems}
errorMessageOverride={visualizerErrMsg}
+ timelineEvents={timelineEvents}
+ timelineEventsVisibility={timelineEventsVisibility}
+ selectedTimelineEventIds={selectedTimelineEventIds}
+ onOpenTimelines={onOpenTimelines}
+ onSelectTimelineEvents={onSelectTimelineEvents}
+ onDeselectTimelineEvents={onDeselectTimelineEvents}
+ onTimelineEventsShown={onTimelineEventsShown}
+ onTimelineEventsEnabledChange={handleTimelineEventsEnabledChange}
enableEntityNavigation={enableEntityNavigation}
onSameOriginNavigation={onSameOriginNavigation}
autoAdjustSettings
diff --git a/frontend/src/metabase/dashboard/components/DashCard/Dashcard.unit.spec.tsx b/frontend/src/metabase/dashboard/components/DashCard/Dashcard.unit.spec.tsx
index e8e7f452ffd..0c96d5cd4d6 100644
--- a/frontend/src/metabase/dashboard/components/DashCard/Dashcard.unit.spec.tsx
+++ b/frontend/src/metabase/dashboard/components/DashCard/Dashcard.unit.spec.tsx
@@ -2,7 +2,10 @@ import userEvent from "@testing-library/user-event";
import fetchMock from "fetch-mock";
import { setupEnterpriseOnlyPlugin } from "__support__/enterprise";
-import { setupLastDownloadFormatEndpoints } from "__support__/server-mocks";
+import {
+ setupLastDownloadFormatEndpoints,
+ setupTimelinesEndpoints,
+} from "__support__/server-mocks";
import { mockSettings } from "__support__/settings";
import { createMockDashboardState, createMockState } from "__support__/state";
import { createMockEntitiesState } from "__support__/store";
@@ -39,15 +42,19 @@ import {
createMockDatabase,
createMockDataset,
createMockDatasetData,
+ createMockDatetimeColumn,
createMockHeadingDashboardCard,
createMockIFrameDashboardCard,
createMockLinkDashboardCard,
createMockNativeCard,
+ createMockNumericColumn,
createMockParameter,
createMockPlaceholderDashboardCard,
createMockStructuredDatasetQuery,
createMockTable,
createMockTextDashboardCard,
+ createMockTimeline,
+ createMockTimelineEvent,
createMockTokenFeatures,
} from "metabase-types/api/mocks";
@@ -111,9 +118,13 @@ function setup({
isEditing,
withMetadata = false,
dashcardMenu,
+ withTimelineEvents = false,
...props
}: Partial<DashCardProps> &
- Pick<MockDashboardContextProps, "dashcardMenu" | "isEditing"> & {
+ Pick<
+ MockDashboardContextProps,
+ "dashcardMenu" | "isEditing" | "withTimelineEvents"
+ > & {
dashboard?: NonNullable<MockDashboardContextProps["dashboard"]>;
dashcardData?: DashCardDataMap;
withMetadata?: boolean;
@@ -164,6 +175,7 @@ function setup({
isEditing={isEditing}
isEditingParameter={false}
dashcardMenu={dashcardMenu}
+ withTimelineEvents={withTimelineEvents}
reportAutoScrolledToDashcard={jest.fn()}
>
<DashCard
@@ -241,6 +253,198 @@ describe("DashCard", () => {
expect(within(visualizationRoot).getByText("Daniel Boone")).toBeVisible();
});
+ describe("timeline event availability", () => {
+ it.each([
+ { name: "a supported chart", display: "line", eventsVisible: true },
+ { name: "an unsupported chart", display: "table", eventsVisible: false },
+ ] as const)(
+ "shows the appropriate event controls for $name",
+ async ({ display, eventsVisible }) => {
+ const user = userEvent.setup({
+ advanceTimers: jest.advanceTimersByTime,
+ });
+ const event = createMockTimelineEvent({
+ id: 100,
+ timeline_id: 10,
+ timestamp: "2024-02-15T00:00:00Z",
+ });
+ setupTimelinesEndpoints([
+ createMockTimeline({ id: 10, events: [event] }),
+ ]);
+ const card = createMockCard({
+ name: "Bird sightings",
+ display,
+ visualization_settings: { "timeline.selected_timeline_ids": [10] },
+ });
+ const dashcard = createMockDashboardCard({ card });
+ setup({
+ dashcard,
+ withTimelineEvents: true,
+ dashcardData: {
+ [dashcard.id]: {
+ [card.id]: createMockDataset({
+ data: createMockDatasetData({
+ cols: [
+ createMockDatetimeColumn({
+ name: "CREATED_AT",
+ unit: "month",
+ }),
+ createMockNumericColumn({ name: "count" }),
+ ],
+ rows: [
+ ["2024-01-01", 1],
+ ["2024-03-01", 2],
+ ],
+ }),
+ }),
+ },
+ },
+ });
+
+ expect(await screen.findByText("Bird sightings")).toBeVisible();
+ const chart =
+ display === "table"
+ ? await screen.findByRole("grid")
+ : await screen.findByTestId("chart-container");
+ expect(chart).toBeInTheDocument();
+ await user.click(screen.getByRole("button", { name: "More options" }));
+ expect(await screen.findByText("Download results")).toBeInTheDocument();
+ await waitFor(() =>
+ expect({
+ eventMenuItems: screen.queryAllByRole("menuitem", {
+ name: "Events",
+ }).length,
+ eventBands: screen.queryAllByTestId("timeline-events-band").length,
+ }).toEqual({
+ eventMenuItems: eventsVisible ? 1 : 0,
+ eventBands: eventsVisible ? 1 : 0,
+ }),
+ );
+ },
+ );
+
+ const visualizerCard = createMockCard({
+ id: 51,
+ name: "Bird sightings",
+ display: "line",
+ visualization_settings: { "timeline.selected_timeline_ids": [10] },
+ });
+
+ const visualizerDashcard = createMockDashboardCard({
+ id: 52,
+ card_id: visualizerCard.id,
+ card: visualizerCard,
+ visualization_settings: {
+ visualization: {
+ display: "line",
+ columnValuesMapping: {
+ COLUMN_1: [
+ {
+ sourceId: `card:${visualizerCard.id}`,
+ originalName: "CREATED_AT",
+ name: "COLUMN_1",
+ },
+ ],
+ COLUMN_2: [
+ {
+ sourceId: `card:${visualizerCard.id}`,
+ originalName: "count",
+ name: "COLUMN_2",
+ },
+ ],
+ },
+ settings: {
+ "graph.dimensions": ["COLUMN_1"],
+ "graph.metrics": ["COLUMN_2"],
+ },
+ },
+ },
+ });
+
+ const visualizerDashcardData: DashCardDataMap = {
+ [visualizerDashcard.id]: {
+ [visualizerCard.id]: createMockDataset({
+ data: createMockDatasetData({
+ cols: [
+ createMockDatetimeColumn({ name: "CREATED_AT", unit: "month" }),
+ createMockNumericColumn({ name: "count" }),
+ ],
+ rows: [
+ ["2024-01-01", 1],
+ ["2024-03-01", 2],
+ ],
+ }),
+ }),
+ },
+ };
+
+ it.each([
+ {
+ name: "a text card",
+ dashcard: createMockTextDashboardCard({ text: "Just a note" }),
+ dashcardData: {},
+ findRenderedCard: () => screen.findByText("Just a note"),
+ },
+ {
+ name: "a link card",
+ dashcard: createMockLinkDashboardCard({ url: "https://xkcd.com/327" }),
+ dashcardData: {},
+ findRenderedCard: () => screen.findByText("https://xkcd.com/327"),
+ },
+ {
+ name: "an action card",
+ dashcard: createMockActionDashboardCard(),
+ dashcardData: {},
+ findRenderedCard: () =>
+ screen.findByTestId("action-button-full-container"),
+ },
+ {
+ name: "a visualizer card",
+ dashcard: visualizerDashcard,
+ dashcardData: visualizerDashcardData,
+ findRenderedCard: () => screen.findByTestId("chart-container"),
+ },
+ ])(
+ "never shows event controls on $name",
+ async ({ dashcard, dashcardData, findRenderedCard }) => {
+ const user = userEvent.setup({
+ advanceTimers: jest.advanceTimersByTime,
+ });
+ setupTimelinesEndpoints([
+ createMockTimeline({
+ id: 10,
+ events: [
+ createMockTimelineEvent({
+ id: 100,
+ timeline_id: 10,
+ timestamp: "2024-02-15T00:00:00Z",
+ }),
+ ],
+ }),
+ ]);
+
+ setup({ dashcard, dashcardData, withTimelineEvents: true });
+
+ expect(await findRenderedCard()).toBeInTheDocument();
+
+ const menuButton = screen.queryByRole("button", {
+ name: "More options",
+ });
+ if (menuButton) {
+ await user.click(menuButton);
+ await screen.findByRole("menu");
+ }
+
+ expect(
+ screen.queryByRole("menuitem", { name: "Events" }),
+ ).not.toBeInTheDocument();
+ expect(
+ screen.queryByTestId("timeline-events-band"),
+ ).not.toBeInTheDocument();
+ },
+ );
+ });
+
it("should show a text card", () => {
const textCard = createMockTextDashboardCard({ text: "Hello, world!" });
setup({
diff --git a/frontend/src/metabase/dashboard/components/Dashboard/Dashboard.module.css b/frontend/src/metabase/dashboard/components/Dashboard/Dashboard.module.css
index 0d5d306576d..ad33f77a9f0 100644
--- a/frontend/src/metabase/dashboard/components/Dashboard/Dashboard.module.css
+++ b/frontend/src/metabase/dashboard/components/Dashboard/Dashboard.module.css
@@ -6,7 +6,7 @@
background-color: var(--mb-color-bg-dashboard);
}
- &.isEditingOrSharing {
+ &.isHeightConstrained {
flex-basis: 0;
}
}
diff --git a/frontend/src/metabase/dashboard/components/Dashboard/Dashboard.tsx b/frontend/src/metabase/dashboard/components/Dashboard/Dashboard.tsx
index e7a9a845014..9e25a299dba 100644
--- a/frontend/src/metabase/dashboard/components/Dashboard/Dashboard.tsx
+++ b/frontend/src/metabase/dashboard/components/Dashboard/Dashboard.tsx
@@ -3,8 +3,10 @@ import { useMemo } from "react";
import DashboardS from "metabase/css/dashboard.module.css";
import { DashboardHeader } from "metabase/dashboard/components/DashboardHeader";
+import { SIDEBAR_NAME } from "metabase/dashboard/constants";
import { useDashboardContext } from "metabase/dashboard/context";
import { getIsHeaderVisible } from "metabase/dashboard/selectors";
+import { useDashboardTimelines } from "metabase/dashboard/timeline-events";
import { isEmbeddingSdk } from "metabase/embedding-sdk/config";
import EmbedFrameS from "metabase/embedding/theme.module.css";
import { useSelector } from "metabase/redux";
@@ -31,10 +33,19 @@ import { Grid, ParametersList } from "./components";
import { useDashboardChartPaste } from "./use-dashboard-chart-paste";
const DashboardDefaultView = ({ className }: { className?: string }) => {
- const { dashboard, isEditing, isFullscreen, isSharing, selectedTabId } =
- useDashboardContext();
+ const {
+ dashboard,
+ isEditing,
+ isFullscreen,
+ isSharing,
+ selectedTabId,
+ sidebar,
+ } = useDashboardContext();
+
+ const hasDockedSidebar = isSharing || sidebar.name === SIDEBAR_NAME.events;
useDashboardChartPaste();
+ useDashboardTimelines();
const isHeaderVisible = useSelector(getIsHeaderVisible);
@@ -59,7 +70,7 @@ const DashboardDefaultView = ({ className }: { className?: string }) => {
const hasTabs = (dashboard?.tabs?.length ?? 0) > 1;
// Embedding SDK has parent containers that requires dashboard to be full height to avoid double scrollbars.
- const isFullHeight = isEditing || isSharing || isEmbeddingSdk();
+ const isFullHeight = isEditing || hasDockedSidebar || isEmbeddingSdk();
return (
<Flex
@@ -104,14 +115,14 @@ const DashboardDefaultView = ({ className }: { className?: string }) => {
miw={0}
mih={0}
className={cx(S.DashboardBody, {
- [S.isEditingOrSharing]: isEditing || isSharing,
+ [S.isHeightConstrained]: isEditing || hasDockedSidebar,
[S.isEmbeddingSdk]: isEmbeddingSdk(),
})}
>
<Box
className={cx(S.ParametersAndCardsContainer, {
[S.shouldMakeDashboardHeaderStickyAfterScrolling]:
- !isFullscreen && (isEditing || isSharing),
+ !isFullscreen && (isEditing || hasDockedSidebar),
[S.notEmpty]: !isEmpty,
})}
id={DASHBOARD_PDF_EXPORT_ROOT_ID}
diff --git a/frontend/src/metabase/dashboard/components/DashboardEventsSidebar/DashCardEventsSidebar.tsx b/frontend/src/metabase/dashboard/components/DashboardEventsSidebar/DashCardEventsSidebar.tsx
new file mode 100644
index 00000000000..ee89570c341
--- /dev/null
+++ b/frontend/src/metabase/dashboard/components/DashboardEventsSidebar/DashCardEventsSidebar.tsx
@@ -0,0 +1,75 @@
+import { useCallback, useEffect, useMemo } from "react";
+
+import { Sidebar } from "metabase/common/components/Sidebar";
+import { openEventsSidebar } from "metabase/dashboard/actions";
+import { useDashboardContext } from "metabase/dashboard/context";
+import { getDashCardById } from "metabase/dashboard/selectors";
+import {
+ getDashCardSelectedTimelineEventIds,
+ getDashCardTimeseriesXAxis,
+ getDashCardVisibleTimelineEventIds,
+} from "metabase/dashboard/timeline-events";
+import { isDashCardOnTab } from "metabase/dashboard/utils";
+import { useDispatch, useSelector } from "metabase/redux";
+import { getTransformedTimelines } from "metabase/timelines/panel/selectors";
+import type { DashCardId, TimelineEventId } from "metabase-types/api";
+
+import { EventsPanel } from "./EventsPanel";
+
+export function DashCardEventsSidebar({
+ dashcardId,
+ focusedEventIds,
+}: {
+ dashcardId: DashCardId;
+ focusedEventIds?: TimelineEventId[];
+}) {
+ const dispatch = useDispatch();
+ const { selectedTabId, closeSidebar } = useDashboardContext();
+ const dashcard = useSelector((state) => getDashCardById(state, dashcardId));
+ const timelines = useSelector(getTransformedTimelines);
+ const visibleEventIds = useSelector((state) =>
+ getDashCardVisibleTimelineEventIds(state, dashcardId),
+ );
+ const selectedEventIds = useSelector((state) =>
+ getDashCardSelectedTimelineEventIds(state, dashcardId),
+ );
+ const xAxis = useSelector((state) =>
+ getDashCardTimeseriesXAxis(state, dashcardId),
+ );
+
+ const isOnAnotherTab =
+ dashcard == null ||
+ dashcard.isRemoved ||
+ !isDashCardOnTab(dashcard, selectedTabId);
+ useEffect(() => {
+ if (isOnAnotherTab) {
+ closeSidebar();
+ }
+ }, [isOnAnotherTab, closeSidebar]);
+
+ const dashcardIds = useMemo(() => [dashcardId], [dashcardId]);
+ const xAxes = useMemo(() => (xAxis ? [xAxis] : null), [xAxis]);
+
+ const handleShowAllEvents = useCallback(() => {
+ dispatch(openEventsSidebar({ dashcardId }));
+ }, [dispatch, dashcardId]);
+
+ if (!dashcard) {
+ return null;
+ }
+
+ return (
+ <Sidebar data-testid="dashboard-events-sidebar">
+ <EventsPanel
+ dashcardIds={dashcardIds}
+ selectionDashcardId={dashcardId}
+ timelines={timelines}
+ visibleEventIds={visibleEventIds}
+ selectedEventIds={selectedEventIds}
+ focusedEventIds={focusedEventIds}
+ xAxes={xAxes}
+ onShowAllEvents={handleShowAllEvents}
+ />
+ </Sidebar>
+ );
+}
diff --git a/frontend/src/metabase/dashboard/components/DashboardEventsSidebar/DashboardEventsSidebar.tsx b/frontend/src/metabase/dashboard/components/DashboardEventsSidebar/DashboardEventsSidebar.tsx
new file mode 100644
index 00000000000..3d4f6349297
--- /dev/null
+++ b/frontend/src/metabase/dashboard/components/DashboardEventsSidebar/DashboardEventsSidebar.tsx
@@ -0,0 +1,23 @@
+import { useDashboardContext } from "metabase/dashboard/context";
+import { getEventsSidebarProps } from "metabase/dashboard/selectors";
+import { useSelector } from "metabase/redux";
+
+import { DashCardEventsSidebar } from "./DashCardEventsSidebar";
+import { DashboardWideEventsSidebar } from "./DashboardWideEventsSidebar";
+
+export function DashboardEventsSidebar() {
+ const { withTimelineEvents } = useDashboardContext();
+ const sidebarProps = useSelector(getEventsSidebarProps);
+ if (!withTimelineEvents || !sidebarProps) {
+ return null;
+ }
+ const { dashcardId, focusedEventIds } = sidebarProps;
+ return dashcardId != null ? (
+ <DashCardEventsSidebar
+ dashcardId={dashcardId}
+ focusedEventIds={focusedEventIds}
+ />
+ ) : (
+ <DashboardWideEventsSidebar />
+ );
+}
diff --git a/frontend/src/metabase/dashboard/components/DashboardEventsSidebar/DashboardWideEventsSidebar.tsx b/frontend/src/metabase/dashboard/components/DashboardEventsSidebar/DashboardWideEventsSidebar.tsx
new file mode 100644
index 00000000000..b37de834445
--- /dev/null
+++ b/frontend/src/metabase/dashboard/components/DashboardEventsSidebar/DashboardWideEventsSidebar.tsx
@@ -0,0 +1,51 @@
+import { t } from "ttag";
+
+import { Sidebar } from "metabase/common/components/Sidebar";
+import { SidebarContent } from "metabase/common/components/SidebarContent";
+import { useDashboardContext } from "metabase/dashboard/context";
+import {
+ getDashCardSelectedTimelineEventIds,
+ getDashboardTimelineEventsAggregate,
+ getTimelineEventsDashCardIds,
+ getTimelineEventsDashCardXAxes,
+} from "metabase/dashboard/timeline-events";
+import { useSelector } from "metabase/redux";
+import { getTransformedTimelines } from "metabase/timelines/panel/selectors";
+import { Box, Text } from "metabase/ui";
+
+import { EventsPanel } from "./EventsPanel";
+
+export function DashboardWideEventsSidebar() {
+ const { closeSidebar } = useDashboardContext();
+ const timelines = useSelector(getTransformedTimelines);
+ const dashcardIds = useSelector(getTimelineEventsDashCardIds);
+ const xAxes = useSelector(getTimelineEventsDashCardXAxes);
+ const { visibleEventIds, partiallyVisibleEventIds } = useSelector(
+ getDashboardTimelineEventsAggregate,
+ );
+ const selectedEventIds = useSelector(getDashCardSelectedTimelineEventIds);
+
+ return (
+ <Sidebar data-testid="dashboard-events-sidebar">
+ {dashcardIds.length === 0 ? (
+ <SidebarContent title={t`Events`} onClose={closeSidebar}>
+ <Box mx="lg" data-testid="dashboard-events-empty-state">
+ <Text fw="bold">{t`Events can be displayed on time series charts`}</Text>
+ <Text c="text-secondary" mt="xs">
+ {t`Add some time series charts to this dashboard first`}
+ </Text>
+ </Box>
+ </SidebarContent>
+ ) : (
+ <EventsPanel
+ dashcardIds={dashcardIds}
+ timelines={timelines}
+ visibleEventIds={visibleEventIds}
+ partiallyVisibleEventIds={partiallyVisibleEventIds}
+ selectedEventIds={selectedEventIds}
+ xAxes={xAxes}
+ />
+ )}
+ </Sidebar>
+ );
+}
diff --git a/frontend/src/metabase/dashboard/components/DashboardEventsSidebar/EventsPanel.tsx b/frontend/src/metabase/dashboard/components/DashboardEventsSidebar/EventsPanel.tsx
new file mode 100644
index 00000000000..a68ae33f2fc
--- /dev/null
+++ b/frontend/src/metabase/dashboard/components/DashboardEventsSidebar/EventsPanel.tsx
@@ -0,0 +1,99 @@
+import { useCallback } from "react";
+
+import { useListTimelinesQuery } from "metabase/api";
+import {
+ deselectTimelineEvents,
+ selectTimelineEvents,
+ updateDashCardsTimelineEventsVisibility,
+} from "metabase/dashboard/actions";
+import { useDashboardContext } from "metabase/dashboard/context";
+import { useDispatch } from "metabase/redux";
+import {
+ TimelineSidebar,
+ type TimelineSidebarProps,
+} from "metabase/timelines/panel/components/TimelineSidebar";
+import type {
+ TimelineEventsVisibilityIntent,
+ TimelineEventsVisibilityUpdate,
+} from "metabase/visualizations/types";
+import type { DashCardId, TimelineEvent } from "metabase-types/api";
+
+export type EventsPanelProps = Pick<
+ TimelineSidebarProps,
+ | "timelines"
+ | "visibleEventIds"
+ | "partiallyVisibleEventIds"
+ | "selectedEventIds"
+ | "focusedEventIds"
+ | "xAxes"
+ | "onShowAllEvents"
+> & {
+ /** the charts the toggles apply to */
+ dashcardIds: DashCardId[];
+ /** the chart a selected event is highlighted on; absent = every chart */
+ selectionDashcardId?: DashCardId;
+};
+
+export function EventsPanel({
+ dashcardIds,
+ selectionDashcardId,
+ timelines,
+ visibleEventIds,
+ partiallyVisibleEventIds,
+ selectedEventIds,
+ focusedEventIds,
+ xAxes,
+ onShowAllEvents,
+}: EventsPanelProps) {
+ const dispatch = useDispatch();
+ const { dashboard, closeSidebar } = useDashboardContext();
+ const { isLoading, error } = useListTimelinesQuery({ include: "events" });
+
+ const handleUpdateVisibility = useCallback(
+ (
+ update: TimelineEventsVisibilityUpdate,
+ intent: TimelineEventsVisibilityIntent,
+ ) =>
+ dispatch(
+ updateDashCardsTimelineEventsVisibility(dashcardIds, update, {
+ location: selectionDashcardId != null ? "dashcard" : "dashboard",
+ intent,
+ }),
+ ),
+ [dispatch, dashcardIds, selectionDashcardId],
+ );
+ const handleSelectEvents = useCallback(
+ (events: TimelineEvent[]) =>
+ dispatch(
+ selectTimelineEvents({
+ dashcardId: selectionDashcardId,
+ eventIds: events.map((event) => event.id),
+ }),
+ ),
+ [dispatch, selectionDashcardId],
+ );
+ const handleDeselectEvents = useCallback(
+ () => dispatch(deselectTimelineEvents()),
+ [dispatch],
+ );
+
+ return (
+ <TimelineSidebar
+ collectionId={dashboard?.collection_id}
+ timelines={timelines}
+ visibleEventIds={visibleEventIds}
+ partiallyVisibleEventIds={partiallyVisibleEventIds}
+ selectedEventIds={selectedEventIds}
+ focusedEventIds={focusedEventIds}
+ xAxes={xAxes}
+ isLoading={isLoading}
+ error={error}
+ eventSource="dashboard"
+ onUpdateVisibility={handleUpdateVisibility}
+ onSelectEvents={handleSelectEvents}
+ onDeselectEvents={handleDeselectEvents}
+ onShowAllEvents={onShowAllEvents}
+ onClose={closeSidebar}
+ />
+ );
+}
diff --git a/frontend/src/metabase/dashboard/components/DashboardEventsSidebar/index.ts b/frontend/src/metabase/dashboard/components/DashboardEventsSidebar/index.ts
new file mode 100644
index 00000000000..8d4a76c15ac
--- /dev/null
+++ b/frontend/src/metabase/dashboard/components/DashboardEventsSidebar/index.ts
@@ -0,0 +1 @@
+export { DashboardEventsSidebar } from "./DashboardEventsSidebar";
diff --git a/frontend/src/metabase/dashboard/components/DashboardHeader/buttons/DashboardActionMenu.tsx b/frontend/src/metabase/dashboard/components/DashboardHeader/buttons/DashboardActionMenu.tsx
index 1d5dd2c9649..ded15f6fe79 100644
--- a/frontend/src/metabase/dashboard/components/DashboardHeader/buttons/DashboardActionMenu.tsx
+++ b/frontend/src/metabase/dashboard/components/DashboardHeader/buttons/DashboardActionMenu.tsx
@@ -3,10 +3,12 @@ import { c, t } from "ttag";
import { Link, type LinkProps } from "metabase/common/components/Link";
import { ToolbarButton } from "metabase/common/components/ToolbarButton";
+import { openEventsSidebar } from "metabase/dashboard/actions";
import { useDashboardContext } from "metabase/dashboard/context/context";
import { useRefreshDashboard } from "metabase/dashboard/hooks";
import { useRegisterShortcut } from "metabase/palette/hooks/useRegisterShortcut";
import { PLUGIN_CACHING, PLUGIN_MODERATION } from "metabase/plugins";
+import { useDispatch } from "metabase/redux";
import { useLocation } from "metabase/router";
import { Icon, Menu } from "metabase/ui";
import { parseSearchQuery } from "metabase/utils/browser";
@@ -40,8 +42,14 @@ const DashboardActionMenuInner = ({
openSettingsSidebar,
}: DashboardActionMenuProps) => {
const location = useLocation();
- const { dashboard, isFullscreen, onFullscreenChange, onChangeLocation } =
- useDashboardContext();
+ const dispatch = useDispatch();
+ const {
+ dashboard,
+ isFullscreen,
+ onFullscreenChange,
+ onChangeLocation,
+ withTimelineEvents = false,
+ } = useDashboardContext();
const [opened, setOpened] = useState(false);
const [showAutoRefreshOptions, setShowAutoRefreshOptions] = useState(false);
@@ -128,6 +136,18 @@ const DashboardActionMenuInner = ({
onClick={() => setShowAutoRefreshOptions(true)}
/>
+ {/* fullscreen hides every sidebar, so the panel this opens could never appear */}
+ {withTimelineEvents && !isFullscreen && (
+ <Menu.Item
+ leftSection={<Icon name="calendar" />}
+ onClick={() =>
+ dispatch(openEventsSidebar({}, "dashboard_menu"))
+ }
+ >
+ {t`Events`}
+ </Menu.Item>
+ )}
+
{(canEdit || canConfigureCaching) && (
<Menu.Item
leftSection={<Icon name="gear" />}
diff --git a/frontend/src/metabase/dashboard/components/DashboardSidebars.tsx b/frontend/src/metabase/dashboard/components/DashboardSidebars.tsx
index e5a71ccf95b..e67db61502f 100644
--- a/frontend/src/metabase/dashboard/components/DashboardSidebars.tsx
+++ b/frontend/src/metabase/dashboard/components/DashboardSidebars.tsx
@@ -4,6 +4,7 @@ import { useDashboardContext } from "metabase/dashboard/context";
import { ActionSidebar } from "./ActionSidebar";
import { AddCardSidebar } from "./AddCardSidebar";
import { ClickBehaviorSidebar } from "./ClickBehaviorSidebar/ClickBehaviorSidebar";
+import { DashboardEventsSidebar } from "./DashboardEventsSidebar";
import { DashboardInfoSidebar } from "./DashboardInfoSidebar";
import { DashboardSettingsSidebar } from "./DashboardSettingsSidebar";
import DashboardSubscriptionsSidebar from "./DashboardSubscriptionsSidebar";
@@ -32,6 +33,8 @@ export function DashboardSidebars() {
return <DashboardSubscriptionsSidebar />;
case SIDEBAR_NAME.info:
return <DashboardInfoSidebar />;
+ case SIDEBAR_NAME.events:
+ return <DashboardEventsSidebar />;
default:
return null;
}
diff --git a/frontend/src/metabase/dashboard/constants.ts b/frontend/src/metabase/dashboard/constants.ts
index 1b577acc1fc..23595d3de73 100644
--- a/frontend/src/metabase/dashboard/constants.ts
+++ b/frontend/src/metabase/dashboard/constants.ts
@@ -14,6 +14,7 @@ export const SIDEBAR_NAME: Record<DashboardSidebarName, DashboardSidebarName> =
sharing: "sharing",
settings: "settings",
info: "info",
+ events: "events",
};
export const INITIAL_DASHBOARD_STATE: DashboardState = {
@@ -39,6 +40,12 @@ export const INITIAL_DASHBOARD_STATE: DashboardState = {
isNavigatingBackToDashboard: false,
slowCards: {},
sidebar: { props: {} },
+ timelineEvents: {
+ overrides: {},
+ enabledByDashCard: {},
+ selection: null,
+ hasTrackedEventsShown: false,
+ },
missingActionParameters: null,
autoApplyFilters: {
toastId: null,
diff --git a/frontend/src/metabase/dashboard/containers/DashboardApp/DashboardApp.tsx b/frontend/src/metabase/dashboard/containers/DashboardApp/DashboardApp.tsx
index e96b511e0bd..5cfefffad61 100644
--- a/frontend/src/metabase/dashboard/containers/DashboardApp/DashboardApp.tsx
+++ b/frontend/src/metabase/dashboard/containers/DashboardApp/DashboardApp.tsx
@@ -191,6 +191,7 @@ export const DashboardApp = () => {
dispatch(toggleSidebar(SIDEBAR_NAME.addQuestion));
}}
dashboardActions={DASHBOARD_APP_ACTIONS}
+ withTimelineEvents
>
<DashboardAppInner location={location} />
</DashboardContextProvider>
diff --git a/frontend/src/metabase/dashboard/context/context.tsx b/frontend/src/metabase/dashboard/context/context.tsx
index b7a6fb56fab..e59979d06ac 100644
--- a/frontend/src/metabase/dashboard/context/context.tsx
+++ b/frontend/src/metabase/dashboard/context/context.tsx
@@ -14,6 +14,7 @@ import { usePrevious, useUnmount } from "react-use";
import { isEqual, noop } from "underscore";
import { isAbortError } from "metabase/api/client";
+import { isEmbedding } from "metabase/embedding/config";
import { useEmbeddingEntityContext } from "metabase/embedding/context";
import { getTabHiddenParameterSlugs } from "metabase/embedding/lib/tab-parameters";
import { type NavigateFunction, navigate } from "metabase/router";
@@ -89,6 +90,8 @@ export type DashboardContextOwnProps = {
* instead of being filtered out. Used by the SDK for internal navigation.
*/
enableEntityNavigation?: boolean;
+ /** Whether the dashboard offers Events menus and session visibility controls */
+ withTimelineEvents?: boolean;
};
export type DashboardContextOwnResult = {
@@ -163,6 +166,7 @@ const DashboardContextProviderInner = forwardRef(
clickActionMode = undefined,
withFooter = true,
enableEntityNavigation = true, // true in core app, SDK passes it down as false
+ withTimelineEvents = false,
// redux selectors
dashboard,
@@ -200,7 +204,7 @@ const DashboardContextProviderInner = forwardRef(
const previousTabId = usePrevious(selectedTabId);
const previousParameterValues = usePrevious(parameterValues);
- const { token } = useEmbeddingEntityContext();
+ const { uuid, token } = useEmbeddingEntityContext();
const { refreshDashboardCardData } = useRefreshDashboard({
dashboardId,
@@ -450,6 +454,12 @@ const DashboardContextProviderInner = forwardRef(
clickActionMode,
withFooter,
enableEntityNavigation,
+ withTimelineEvents:
+ withTimelineEvents &&
+ !uuid &&
+ !token &&
+ !isGuestEmbed &&
+ !isEmbedding(),
// redux selectors
selectedTabId,
diff --git a/frontend/src/metabase/dashboard/context/context.unit.spec.tsx b/frontend/src/metabase/dashboard/context/context.unit.spec.tsx
new file mode 100644
index 00000000000..a0c4ef482d3
--- /dev/null
+++ b/frontend/src/metabase/dashboard/context/context.unit.spec.tsx
@@ -0,0 +1,116 @@
+import { renderHook } from "@testing-library/react";
+import type { PropsWithChildren } from "react";
+
+import {
+ setupDashboardEndpoints,
+ setupDashboardQueryMetadataEndpoint,
+ setupEmbedDashboardEndpoints,
+ setupPublicDashboardEndpoint,
+} from "__support__/server-mocks";
+import { getTestStoreAndWrapper, waitFor } from "__support__/ui";
+import * as embeddingSdkConfig from "metabase/embedding-sdk/config";
+import { EmbeddingEntityContextProvider } from "metabase/embedding/context";
+import * as iframeUtils from "metabase/utils/iframe";
+import type { EntityToken, EntityUuid } from "metabase-types/api/entity";
+import {
+ createMockDashboard,
+ createMockDashboardQueryMetadata,
+} from "metabase-types/api/mocks";
+
+import { DashboardContextProvider, useDashboardContext } from "./context";
+
+const PUBLIC_UUID = "12345678-1234-1234-1234-123456789abc";
+const EMBED_TOKEN = "header.payload.signature";
+
+interface SetupOptions {
+ uuid?: EntityUuid | null;
+ token?: EntityToken | null;
+ isGuestEmbed?: boolean;
+ isWithinIframe?: boolean;
+ isEmbeddingSdk?: boolean;
+ withTimelineEvents?: boolean;
+}
+
+async function setup({
+ uuid = null,
+ token = null,
+ isGuestEmbed = false,
+ isWithinIframe = false,
+ isEmbeddingSdk = false,
+ withTimelineEvents,
+}: SetupOptions = {}) {
+ jest.spyOn(iframeUtils, "isWithinIframe").mockReturnValue(isWithinIframe);
+ jest
+ .spyOn(embeddingSdkConfig, "isEmbeddingSdk")
+ .mockReturnValue(isEmbeddingSdk);
+
+ const dashboard = createMockDashboard();
+ setupDashboardEndpoints(dashboard);
+ setupDashboardQueryMetadataEndpoint(
+ dashboard,
+ createMockDashboardQueryMetadata(),
+ );
+ if (uuid) {
+ setupPublicDashboardEndpoint(uuid, dashboard);
+ }
+ if (token) {
+ setupEmbedDashboardEndpoints(token, dashboard);
+ }
+
+ const { wrapper: Wrapper } = getTestStoreAndWrapper({ initialRoute: "/" });
+ const utils = renderHook(useDashboardContext, {
+ wrapper: ({ children }: PropsWithChildren) => (
+ <Wrapper>
+ <EmbeddingEntityContextProvider uuid={uuid} token={token}>
+ <DashboardContextProvider
+ dashboardId={uuid ?? dashboard.id}
+ navigateToNewCardFromDashboard={null}
+ isGuestEmbed={isGuestEmbed}
+ withTimelineEvents={withTimelineEvents}
+ >
+ {children}
+ </DashboardContextProvider>
+ </EmbeddingEntityContextProvider>
+ </Wrapper>
+ ),
+ });
+
+ await waitFor(() => {
+ expect(utils.result.current.dashboard?.name).toBe(dashboard.name);
+ });
+
+ return utils;
+}
+
+describe("DashboardContextProvider timeline event controls", () => {
+ afterEach(() => {
+ jest.restoreAllMocks();
+ });
+
+ it("enables controls when requested on a regular dashboard", async () => {
+ const { result } = await setup({ withTimelineEvents: true });
+
+ expect(result.current.withTimelineEvents).toBe(true);
+ });
+
+ it("disables controls by default on a regular dashboard", async () => {
+ const { result } = await setup();
+
+ expect(result.current.withTimelineEvents).toBe(false);
+ });
+
+ it.each<[string, SetupOptions]>([
+ ["public dashboards", { uuid: PUBLIC_UUID }],
+ ["signed embedded dashboards", { token: EMBED_TOKEN }],
+ ["guest embedded dashboards", { isGuestEmbed: true }],
+ ["iframe dashboards", { isWithinIframe: true }],
+ ["SDK dashboards", { isEmbeddingSdk: true }],
+ ])(
+ "disables controls on %s even when requested",
+ async (_surface, options) => {
+ const { result } = await setup({ ...options, withTimelineEvents: true });
+
+ expect(result.current.withTimelineEvents).toBe(false);
+ },
+ );
+});
diff --git a/frontend/src/metabase/dashboard/reducers-typed.ts b/frontend/src/metabase/dashboard/reducers-typed.ts
index 6609d20f0bb..cd1e4604079 100644
--- a/frontend/src/metabase/dashboard/reducers-typed.ts
+++ b/frontend/src/metabase/dashboard/reducers-typed.ts
@@ -1,7 +1,7 @@
import type { UnknownAction } from "@reduxjs/toolkit";
import { createReducer } from "@reduxjs/toolkit";
import { assocIn, dissocIn } from "icepick";
-import { omit } from "underscore";
+import _ from "underscore";
import {
createDashboardPublicLink,
@@ -26,13 +26,11 @@ import {
} from "metabase/redux/query-builder";
import type {
DashboardLinkTargets,
- DashboardSidebarName,
StoreDashboard,
} from "metabase/redux/store/dashboard";
import type { UiParameter } from "metabase-lib/v1/parameters/types";
import type {
Card,
- DashCardId,
Dashboard,
ParameterId,
ParameterValueOrArray,
@@ -47,7 +45,6 @@ import {
RESET_PARAMETERS,
SET_EDITING_DASHBOARD,
SET_PARAMETER_VALUE,
- SET_SIDEBAR,
SHOW_AUTO_APPLY_FILTERS_TOAST,
addCardToDash,
addDashcardIdsToLoadingQueue,
@@ -62,8 +59,16 @@ import {
setDashboardAttributes,
setDocumentTitle,
setShowLoadingCompleteFavicon,
+ setSidebar,
} from "./actions";
-import { INITIAL_DASHBOARD_STATE } from "./constants";
+import {
+ deselectTimelineEvents,
+ markTimelineEventsShown,
+ selectTimelineEvents,
+ setDashCardTimelineEventsEnabled,
+ setDashCardTimelineEventsVisibility,
+} from "./actions/timeline-events";
+import { INITIAL_DASHBOARD_STATE, SIDEBAR_NAME } from "./constants";
import { syncParametersAndEmbeddingParams } from "./utils";
export const dashboardId = createReducer(
@@ -202,25 +207,61 @@ export const sidebar = createReducer(
builder.addCase(SET_EDITING_DASHBOARD, () => DEFAULT_SIDEBAR);
builder.addCase(CLOSE_SIDEBAR, () => DEFAULT_SIDEBAR);
- builder.addCase<
- string,
- {
- type: string;
- payload: {
- name: DashboardSidebarName;
- props?: {
- dashcardId?: DashCardId;
- parameterId?: ParameterId;
- };
- };
- }
- >(SET_SIDEBAR, (_state, { payload: { name, props } }) => ({
+ builder.addCase(setSidebar, (_state, { payload: { name, props } }) => ({
name,
props: props || {},
}));
},
);
+export const timelineEvents = createReducer(
+ INITIAL_DASHBOARD_STATE.timelineEvents,
+ (builder) => {
+ builder.addCase(INITIALIZE, () => INITIAL_DASHBOARD_STATE.timelineEvents);
+ builder.addCase(RESET, () => INITIAL_DASHBOARD_STATE.timelineEvents);
+ builder.addCase(SET_EDITING_DASHBOARD, (state) => ({
+ ...INITIAL_DASHBOARD_STATE.timelineEvents,
+ hasTrackedEventsShown: state.hasTrackedEventsShown,
+ }));
+ builder.addCase(fetchDashboard.fulfilled, (state) => {
+ if (Object.keys(state.overrides).length > 0) {
+ state.overrides = {};
+ }
+ if (Object.keys(state.enabledByDashCard).length > 0) {
+ state.enabledByDashCard = {};
+ }
+ });
+ builder.addCase(CLOSE_SIDEBAR, (state) => {
+ state.selection = null;
+ });
+ builder.addCase(setSidebar, (state, { payload: { name } }) => {
+ if (name !== SIDEBAR_NAME.events) {
+ state.selection = null;
+ }
+ });
+ builder.addCase(setDashCardTimelineEventsVisibility, (state, action) => {
+ state.overrides = { ...state.overrides, ...action.payload };
+ });
+ builder.addCase(
+ setDashCardTimelineEventsEnabled,
+ (state, { payload: { dashcardId, isEnabled } }) => {
+ if (state.enabledByDashCard[dashcardId] !== isEnabled) {
+ state.enabledByDashCard[dashcardId] = isEnabled;
+ }
+ },
+ );
+ builder.addCase(selectTimelineEvents, (state, action) => {
+ state.selection = action.payload;
+ });
+ builder.addCase(deselectTimelineEvents, (state) => {
+ state.selection = null;
+ });
+ builder.addCase(markTimelineEventsShown, (state) => {
+ state.hasTrackedEventsShown = true;
+ });
+ },
+);
+
export const parameterValues = createReducer(
INITIAL_DASHBOARD_STATE.parameterValues,
(builder) => {
@@ -292,7 +333,7 @@ function newDashboard(
...before,
// mimic the StoreDashboard type - this function is only made to update attributes
// rather than deep values like dashcards or tabs
- ...omit(after, "dashcards", "tabs"),
+ ..._.omit(after, "dashcards", "tabs"),
embedding_params: syncParametersAndEmbeddingParams(before, after),
isDirty,
};
diff --git a/frontend/src/metabase/dashboard/reducers.ts b/frontend/src/metabase/dashboard/reducers.ts
index 313f229ad73..17a8f4eb6dc 100644
--- a/frontend/src/metabase/dashboard/reducers.ts
+++ b/frontend/src/metabase/dashboard/reducers.ts
@@ -48,6 +48,7 @@ import {
parameterValues,
sidebar,
slowCards,
+ timelineEvents,
} from "./reducers-typed";
import { calculateDashCardRowAfterUndo } from "./utils";
@@ -274,6 +275,7 @@ const combinedDashboardReducer = combineReducers({
editingDashboard,
loadingControls,
sidebar,
+ timelineEvents,
parameterValues,
dashboards,
loadingDashCards,
diff --git a/frontend/src/metabase/dashboard/reducers.unit.spec.ts b/frontend/src/metabase/dashboard/reducers.unit.spec.ts
index a9ed8701c52..232c476a0c6 100644
--- a/frontend/src/metabase/dashboard/reducers.unit.spec.ts
+++ b/frontend/src/metabase/dashboard/reducers.unit.spec.ts
@@ -11,8 +11,15 @@ import {
SET_EDITING_DASHBOARD,
SET_SIDEBAR,
fetchCardDataAction,
+ fetchDashboard,
+ markTimelineEventsShown,
+ selectTimelineEvents,
+ setDashCardTimelineEventsEnabled,
+ setDashCardTimelineEventsVisibility,
} from "./actions";
+import { SIDEBAR_NAME } from "./constants";
import { dashboardReducers as reducer } from "./reducers";
+import { timelineEvents } from "./reducers-typed";
const TEST_DASHBOARD = createMockDashboard();
@@ -43,6 +50,12 @@ describe("dashboard reducers", () => {
parameterValues: {},
draftParameterValues: {},
sidebar: { props: {} },
+ timelineEvents: {
+ overrides: {},
+ enabledByDashCard: {},
+ selection: null,
+ hasTrackedEventsShown: false,
+ },
slowCards: {},
loadingControls: {
isLoading: false,
@@ -427,4 +440,91 @@ describe("dashboard reducers", () => {
expect(result.dashcardData).toEqual({ 5: { 2: { data: [] } } });
});
});
+
+ describe("timelineEvents selection", () => {
+ const selectedState = () =>
+ reducer(
+ undefined,
+ selectTimelineEvents({ dashcardId: 1, eventIds: [100] }),
+ );
+
+ it("keeps the selected events while the events sidebar is open", () => {
+ const state = reducer(selectedState(), {
+ type: SET_SIDEBAR,
+ payload: { name: SIDEBAR_NAME.events },
+ });
+ expect(state.timelineEvents.selection).toEqual({
+ dashcardId: 1,
+ eventIds: [100],
+ });
+ });
+
+ it("drops the selected events when another sidebar replaces the events one", () => {
+ const state = reducer(selectedState(), {
+ type: SET_SIDEBAR,
+ payload: { name: SIDEBAR_NAME.sharing },
+ });
+ expect(state.timelineEvents.selection).toBeNull();
+ });
+
+ it("drops the selected events when the sidebar closes", () => {
+ const state = reducer(selectedState(), { type: CLOSE_SIDEBAR });
+ expect(state.timelineEvents.selection).toBeNull();
+ });
+
+ const overriddenState = () =>
+ reducer(
+ selectedState(),
+ setDashCardTimelineEventsVisibility({
+ 1: { "timeline.selected_timeline_ids": [10] },
+ }),
+ );
+
+ it("resets when dashboard editing starts", () => {
+ const state = reducer(overriddenState(), {
+ type: SET_EDITING_DASHBOARD,
+ payload: TEST_DASHBOARD,
+ });
+ expect(state.timelineEvents).toEqual({
+ overrides: {},
+ enabledByDashCard: {},
+ selection: null,
+ hasTrackedEventsShown: false,
+ });
+ });
+
+ it("drops the session overrides when the dashboard is refetched", () => {
+ const overridden = reducer(
+ overriddenState(),
+ setDashCardTimelineEventsEnabled({ dashcardId: 1, isEnabled: false }),
+ );
+ const state = timelineEvents(overridden.timelineEvents, {
+ type: fetchDashboard.fulfilled.type,
+ });
+ expect(state.overrides).toEqual({});
+ expect(state.enabledByDashCard).toEqual({});
+ expect(state.selection).toEqual({ dashcardId: 1, eventIds: [100] });
+ });
+ });
+
+ describe("timelineEvents tracking", () => {
+ const trackedState = () => reducer(undefined, markTimelineEventsShown());
+
+ it("remembers that the shown events were tracked", () => {
+ expect(trackedState().timelineEvents.hasTrackedEventsShown).toBe(true);
+ });
+
+ it("keeps the tracking across dashboard editing", () => {
+ const state = reducer(trackedState(), {
+ type: SET_EDITING_DASHBOARD,
+ payload: TEST_DASHBOARD,
+ });
+ expect(state.timelineEvents.hasTrackedEventsShown).toBe(true);
+ });
+
+ it("forgets the tracking when another dashboard is opened", () => {
+ const state = reducer(trackedState(), { type: INITIALIZE });
+ expect(state.timelineEvents.hasTrackedEventsShown).toBe(false);
+ });
+ });
});
diff --git a/frontend/src/metabase/dashboard/selectors.ts b/frontend/src/metabase/dashboard/selectors.ts
index ba82b7564af..888328dbe60 100644
--- a/frontend/src/metabase/dashboard/selectors.ts
+++ b/frontend/src/metabase/dashboard/selectors.ts
@@ -24,6 +24,7 @@ import { getVisibleParameters } from "metabase/parameters/utils/ui";
import type {
ClickBehaviorSidebarState,
EditParameterSidebarState,
+ EventsSidebarState,
State,
StoreDashboard,
StoreDashcard,
@@ -78,6 +79,15 @@ function isClickBehaviorSidebar(
return sidebar.name === SIDEBAR_NAME.clickBehavior;
}
+function isEventsSidebar(sidebar: SidebarState): sidebar is EventsSidebarState {
+ return sidebar.name === SIDEBAR_NAME.events;
+}
+
+export const getEventsSidebarProps = (state: State) => {
+ const { sidebar } = state.dashboard;
+ return isEventsSidebar(sidebar) ? sidebar.props : null;
+};
+
function isEditParameterSidebar(
sidebar: SidebarState,
): sidebar is EditParameterSidebarState {
diff --git a/frontend/src/metabase/dashboard/timeline-events/hooks.ts b/frontend/src/metabase/dashboard/timeline-events/hooks.ts
new file mode 100644
index 00000000000..dc64045e11a
--- /dev/null
+++ b/frontend/src/metabase/dashboard/timeline-events/hooks.ts
@@ -0,0 +1,180 @@
+import { useCallback } from "react";
+
+import { useListTimelinesQuery } from "metabase/api";
+import { useDashboardContext } from "metabase/dashboard/context";
+import {
+ isPublicEmbedding,
+ isStaticEmbedding,
+} from "metabase/embedding/config";
+import { useDispatch, useSelector } from "metabase/redux";
+import { getRecordedTimelineEventsVisibility } from "metabase/visualizations/lib/timeline-events-visibility";
+import type { VisualizationProps } from "metabase/visualizations/types";
+import type {
+ DashCardId,
+ DashboardCard,
+ TimelineEvent,
+ TimelineEventId,
+ TimelineEventsVisibility,
+} from "metabase-types/api";
+
+import {
+ deselectTimelineEvents,
+ openEventsSidebar,
+ selectTimelineEvents,
+ setDashCardTimelineEventsEnabled,
+ trackTimelineEventsShown,
+} from "../actions/timeline-events";
+
+import {
+ getDashCardSelectedTimelineEventIds,
+ getDashCardTimelineEventsVisibility,
+ getDashCardTimeseriesXAxis,
+ getHasSelectedTimelineEvents,
+ getIsDashCardTimelineEventsEnabled,
+} from "./selectors";
+
+// keeps the timelines loaded for the events sidebar; charts load their own
+export const useDashboardTimelines = () => {
+ const { withTimelineEvents } = useDashboardContext();
+ const hasSelectedEvents = useSelector(getHasSelectedTimelineEvents);
+
+ useListTimelinesQuery(
+ { include: "events" },
+ { skip: !withTimelineEvents || !hasSelectedEvents },
+ );
+};
+
+/**
+ * The chart measures whether it is big enough to draw events and reports it here. Dashboard state resets clear that
+ * flag, and a chart that stays mounted would never correct it, so the callback identity tracks the stored value: a
+ * reset changes it, the chart's effect runs again, and the measurement is re-asserted.
+ */
+export const useReportDashCardTimelineEventsEnabled = (
+ dashcardId: DashCardId,
+) => {
+ const dispatch = useDispatch();
+ const reported = useSelector((state) =>
+ getIsDashCardTimelineEventsEnabled(state, dashcardId),
+ );
+
+ return useCallback(
+ (isEnabled: boolean) => {
+ if (isEnabled !== reported) {
+ dispatch(setDashCardTimelineEventsEnabled({ dashcardId, isEnabled }));
+ }
+ },
+ [dispatch, dashcardId, reported],
+ );
+};
+
+type DashCardTimelineEventsProps = Pick<
+ VisualizationProps,
+ | "timelineEvents"
+ | "timelineEventsVisibility"
+ | "selectedTimelineEventIds"
+ | "onOpenTimelines"
+ | "onSelectTimelineEvents"
+ | "onDeselectTimelineEvents"
+ | "onTimelineEventsShown"
+>;
+
+type DashCardTimelineEvents = {
+ isEnabled: boolean;
+} & DashCardTimelineEventsProps;
+
+const NO_TIMELINE_EVENTS: TimelineEventsVisibility = {
+ "timeline.selected_timeline_ids": [],
+};
+
+const EMPTY_EVENTS: TimelineEvent[] = [];
+
+const DISABLED: DashCardTimelineEvents = {
+ isEnabled: false,
+ timelineEvents: EMPTY_EVENTS,
+ timelineEventsVisibility: NO_TIMELINE_EVENTS,
+};
+
+export const useDashCardTimelineEvents = (
+ dashcard: DashboardCard,
+): DashCardTimelineEvents => {
+ const dispatch = useDispatch();
+ const { withTimelineEvents = false, isFullscreen } = useDashboardContext();
+ const dashcardId: DashCardId = dashcard.id;
+ const canDisplayEvents = useSelector(
+ (state) => getDashCardTimeseriesXAxis(state, dashcardId) != null,
+ );
+ const showsEvents = withTimelineEvents && canDisplayEvents;
+ // fullscreen hides every sidebar, so the panel these controls open could never appear; the chips
+ // still render, so the chart is still an impression
+ const isEnabled = showsEvents && !isFullscreen;
+
+ const timelineEventsVisibility = useSelector((state) => {
+ if (!canDisplayEvents) {
+ return NO_TIMELINE_EVENTS;
+ }
+ return withTimelineEvents
+ ? getDashCardTimelineEventsVisibility(state, dashcardId)
+ : getRecordedTimelineEventsVisibility(
+ dashcard.card?.visualization_settings,
+ );
+ });
+ const selectedTimelineEventIds = useSelector((state) =>
+ isEnabled
+ ? getDashCardSelectedTimelineEventIds(state, dashcardId)
+ : undefined,
+ );
+
+ const onOpenTimelines = useCallback(
+ (eventIds?: TimelineEventId[]) =>
+ dispatch(
+ openEventsSidebar({ dashcardId, focusedEventIds: eventIds }, "chart"),
+ ),
+ [dispatch, dashcardId],
+ );
+ const onSelectTimelineEvents = useCallback(
+ (events: TimelineEvent[]) =>
+ dispatch(
+ selectTimelineEvents({
+ dashcardId,
+ eventIds: events.map((event) => event.id),
+ }),
+ ),
+ [dispatch, dashcardId],
+ );
+ const onDeselectTimelineEvents = useCallback(
+ () => dispatch(deselectTimelineEvents()),
+ [dispatch],
+ );
+ const onTimelineEventsShown = useCallback(
+ () => dispatch(trackTimelineEventsShown()),
+ [dispatch],
+ );
+
+ if (!canDisplayEvents) {
+ return DISABLED;
+ }
+
+ const timelineEvents =
+ dashcard.timeline_events ??
+ (isPublicEmbedding() || isStaticEmbedding() ? EMPTY_EVENTS : undefined);
+
+ if (!isEnabled) {
+ return {
+ isEnabled: false,
+ timelineEvents,
+ timelineEventsVisibility,
+ onTimelineEventsShown: showsEvents ? onTimelineEventsShown : undefined,
+ };
+ }
+
+ return {
+ isEnabled,
+ timelineEvents,
+ timelineEventsVisibility,
+ selectedTimelineEventIds,
+ onOpenTimelines,
+ onSelectTimelineEvents,
+ onDeselectTimelineEvents,
+ onTimelineEventsShown,
+ };
+};
diff --git a/frontend/src/metabase/dashboard/timeline-events/hooks.unit.spec.tsx b/frontend/src/metabase/dashboard/timeline-events/hooks.unit.spec.tsx
new file mode 100644
index 00000000000..a184233fb76
--- /dev/null
+++ b/frontend/src/metabase/dashboard/timeline-events/hooks.unit.spec.tsx
@@ -0,0 +1,863 @@
+import { renderHook } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import fetchMock from "fetch-mock";
+import { type PropsWithChildren, useEffect } from "react";
+import { useMount } from "react-use";
+
+import { setupTimelinesEndpoints } from "__support__/server-mocks";
+import { setupCollectionByIdEndpoint } from "__support__/server-mocks/collection";
+import {
+ createMockApiState,
+ createMockDashboardState,
+ createMockState,
+ createMockStoreDashboard,
+ seedApiQueryCache,
+} from "__support__/state";
+import {
+ getTimelineCheckbox,
+ getTimelineEventCheckbox,
+} from "__support__/timelines";
+import {
+ act,
+ getTestStoreAndWrapper,
+ renderWithProviders,
+ screen,
+ waitFor,
+} from "__support__/ui";
+import { ROOT_COLLECTION } from "metabase/common/collections/constants";
+import {
+ SET_EDITING_DASHBOARD,
+ openEventsSidebar,
+ removeCardFromDashboard,
+ selectTimelineEvents,
+ setDashCardTimelineEventsEnabled,
+ setDashCardTimelineEventsVisibility,
+} from "metabase/dashboard/actions";
+import { DashboardEventsSidebar } from "metabase/dashboard/components/DashboardEventsSidebar/DashboardEventsSidebar";
+import { SIDEBAR_NAME } from "metabase/dashboard/constants";
+import { MockDashboardContext } from "metabase/dashboard/context/mock-context";
+import * as embeddingConfig from "metabase/embedding/config";
+import { selectTab } from "metabase/redux/dashboard";
+import { useTimelineEvents } from "metabase/visualizations/hooks/use-timeline-events";
+import { registerVisualizations } from "metabase/visualizations/register";
+import { getComputedSettingsForSeries } from "metabase/viz-core";
+import type {
+ DashCardDataMap,
+ DashCardId,
+ DashboardCard,
+ DashboardTabId,
+ QuestionDashboardCard,
+ Timeline,
+ TimelineEvent,
+ TimelineEventsVisibility,
+ VisualizationSettings,
+} from "metabase-types/api";
+import {
+ createMockCard,
+ createMockCollection,
+ createMockDashboardCard,
+ createMockDataset,
+ createMockDatasetData,
+ createMockDatetimeColumn,
+ createMockNumericColumn,
+ createMockTimeline,
+ createMockTimelineEvent,
+} from "metabase-types/api/mocks";
+
+import {
+ useDashCardTimelineEvents,
+ useDashboardTimelines,
+ useReportDashCardTimelineEventsEnabled,
+} from "./hooks";
+import {
+ getDashCardVisibleTimelineEventIds,
+ getIsDashCardTimelineEventsEnabled,
+} from "./selectors";
+
+registerVisualizations();
+
+const { trackSimpleEvent } = jest.requireMock("metabase/analytics");
+
+const DASHBOARD_ID = 1;
+const DASHCARD_ID = 2;
+
+const EVENT = createMockTimelineEvent({
+ id: 100,
+ name: "Launch",
+ timeline_id: 10,
+ timestamp: "2024-02-15T00:00:00Z",
+});
+const TIMELINE = createMockTimeline({
+ id: 10,
+ name: "Releases",
+ events: [EVENT],
+});
+const SAME_RANGE_EVENT = createMockTimelineEvent({
+ ...EVENT,
+ id: 103,
+ name: "Earlier launch",
+ timestamp: "2024-01-20T00:00:00Z",
+});
+const OUT_OF_RANGE_EVENT = createMockTimelineEvent({
+ ...EVENT,
+ id: 104,
+ name: "Far future launch",
+ timestamp: "2030-01-01T00:00:00Z",
+});
+const EXCLUDED_EVENT = createMockTimelineEvent({
+ ...EVENT,
+ id: 101,
+ name: "Excluded launch",
+});
+const UNRELATED_EVENT = createMockTimelineEvent({
+ ...EVENT,
+ id: 102,
+ timeline_id: 20,
+ name: "Unrelated collection event",
+});
+
+const EVENTS_RECORDED: VisualizationSettings = {
+ "timeline.selected_timeline_ids": [TIMELINE.id],
+ "timeline.excluded_timeline_event_ids": [],
+};
+
+const createDataset = (rows: [string, number][]) =>
+ createMockDataset({
+ data: createMockDatasetData({
+ cols: [
+ createMockDatetimeColumn({ name: "CREATED_AT", unit: "month" }),
+ createMockNumericColumn({ name: "count" }),
+ ],
+ rows,
+ }),
+ });
+
+const DATASET = createDataset([
+ ["2024-01-01", 1],
+ ["2024-03-01", 2],
+]);
+const LATER_DATASET = createDataset([
+ ["2024-05-01", 1],
+ ["2024-07-01", 2],
+]);
+const LATER_EVENT = createMockTimelineEvent({
+ ...EVENT,
+ id: 105,
+ name: "Later launch",
+ timestamp: "2024-06-15T00:00:00Z",
+});
+
+const DashCardChart = ({
+ dashcard,
+ onRender,
+}: {
+ dashcard: DashboardCard;
+ onRender?: (props: ReturnType<typeof useDashCardTimelineEvents>) => void;
+}) => {
+ const props = useDashCardTimelineEvents(dashcard);
+ useMount(() => {
+ props.onTimelineEventsShown?.();
+ onRender?.(props);
+ });
+ return null;
+};
+
+function setup({
+ savedVisibility,
+ withTimelineEvents = true,
+ isFullscreen = false,
+ selectedTabId = null,
+ dashcardTabId = null,
+ withSidebar = false,
+ dashcards,
+ onRender,
+ datasets = {},
+ timelines = [TIMELINE],
+ seedTimelines = true,
+}: {
+ savedVisibility?: VisualizationSettings;
+ withTimelineEvents?: boolean;
+ isFullscreen?: boolean;
+ selectedTabId?: DashboardTabId | null;
+ dashcardTabId?: DashboardTabId | null;
+ withSidebar?: boolean;
+ dashcards?: QuestionDashboardCard[];
+ onRender?: (props: ReturnType<typeof useDashCardTimelineEvents>) => void;
+ datasets?: DashCardDataMap[number];
+ timelines?: Timeline[];
+ seedTimelines?: boolean;
+} = {}) {
+ setupCollectionByIdEndpoint({
+ collections: [
+ createMockCollection({ ...ROOT_COLLECTION, can_write: true }),
+ ],
+ });
+ const card = createMockCard({
+ display: "line",
+ visualization_settings: { ...savedVisibility },
+ });
+ const dashcard = createMockDashboardCard({
+ id: DASHCARD_ID,
+ dashboard_id: DASHBOARD_ID,
+ dashboard_tab_id: dashcardTabId,
+ card,
+ });
+ const allDashcards = dashcards ?? [dashcard];
+
+ return renderWithProviders(
+ <MockDashboardContext
+ dashboardId={DASHBOARD_ID}
+ withTimelineEvents={withTimelineEvents}
+ isFullscreen={isFullscreen}
+ >
+ {/* two charts report, the dashboard is tracked once */}
+ <DashCardChart dashcard={dashcard} onRender={onRender} />
+ <DashCardChart dashcard={dashcard} />
+ {withSidebar && <DashboardEventsSidebar />}
+ </MockDashboardContext>,
+ {
+ storeInitialState: createMockState({
+ dashboard: createMockDashboardState({
+ dashboardId: DASHBOARD_ID,
+ selectedTabId,
+ sidebar: withSidebar
+ ? { name: SIDEBAR_NAME.events, props: {} }
+ : { props: {} },
+ dashboards: {
+ [DASHBOARD_ID]: createMockStoreDashboard({
+ id: DASHBOARD_ID,
+ dashcards: allDashcards.map(({ id }) => id),
+ }),
+ },
+ dashcards: Object.fromEntries(
+ allDashcards.map((dashcard) => [dashcard.id, dashcard]),
+ ),
+ dashcardData: Object.fromEntries(
+ allDashcards.map((dashcard) => [
+ dashcard.id,
+ Object.fromEntries(
+ [dashcard.card, ...(dashcard.series ?? [])].map((card) => [
+ card.id,
+ datasets[card.id] ?? DATASET,
+ ]),
+ ),
+ ]),
+ ),
+ }),
+ ...(seedTimelines && {
+ "metabase-api": seedApiQueryCache(createMockApiState(), [
+ {
+ endpointName: "listTimelines",
+ arg: { include: "events" },
+ value: timelines,
+ },
+ ]),
+ }),
+ }),
+ },
+ );
+}
+
+describe("dashboard timeline events", () => {
+ beforeEach(() => {
+ trackSimpleEvent.mockClear();
+ });
+
+ afterEach(() => {
+ jest.restoreAllMocks();
+ });
+
+ it("tracks a dashboard once when its charts show events", () => {
+ setup({ savedVisibility: EVENTS_RECORDED });
+
+ expect(trackSimpleEvent).toHaveBeenCalledTimes(1);
+ expect(trackSimpleEvent).toHaveBeenCalledWith({
+ event: "dashboard_events_shown",
+ target_id: DASHBOARD_ID,
+ });
+ });
+
+ it("offers no event controls in fullscreen, but still counts the impression", () => {
+ const onRender = jest.fn();
+ setup({ savedVisibility: EVENTS_RECORDED, isFullscreen: true, onRender });
+
+ expect(trackSimpleEvent).toHaveBeenCalledWith({
+ event: "dashboard_events_shown",
+ target_id: DASHBOARD_ID,
+ });
+ const props = onRender.mock.calls[0][0];
+ expect(props.isEnabled).toBe(false);
+ expect(props.onOpenTimelines).toBeUndefined();
+ expect(props.onSelectTimelineEvents).toBeUndefined();
+ expect(props.onDeselectTimelineEvents).toBeUndefined();
+ });
+
+ it("does not track event visibility when dashboard event controls are disabled", () => {
+ setup({ savedVisibility: EVENTS_RECORDED, withTimelineEvents: false });
+
+ expect(trackSimpleEvent).not.toHaveBeenCalled();
+ });
+
+ it("does not track a dashcard whose timeline events are disabled", () => {
+ setup({
+ savedVisibility: {
+ ...EVENTS_RECORDED,
+ "timeline_events.enabled": false,
+ },
+ });
+
+ expect(trackSimpleEvent).not.toHaveBeenCalled();
+ });
+
+ it.each(["chart", "dashcard_menu", "dashboard_menu"] as const)(
+ "tracks opening the events panel from the %s once until it closes",
+ async (location) => {
+ const { store } = setup();
+ trackSimpleEvent.mockClear();
+
+ await act(async () => {
+ store.dispatch(
+ openEventsSidebar({ dashcardId: DASHCARD_ID }, location),
+ );
+ store.dispatch(openEventsSidebar({}, location));
+ });
+
+ expect(trackSimpleEvent).toHaveBeenCalledTimes(1);
+ expect(trackSimpleEvent).toHaveBeenCalledWith({
+ event: "dashboard_events_panel_opened",
+ target_id: DASHBOARD_ID,
+ triggered_from: location,
+ });
+ },
+ );
+
+ it("does not track reopening the panel from within it", async () => {
+ const { store } = setup();
+ trackSimpleEvent.mockClear();
+
+ await act(async () => {
+ store.dispatch(openEventsSidebar({ dashcardId: DASHCARD_ID }));
+ });
+
+ expect(trackSimpleEvent).not.toHaveBeenCalled();
+ });
+
+ it("lists the events of the charts on the selected tab", async () => {
+ setup({
+ savedVisibility: EVENTS_RECORDED,
+ selectedTabId: 5,
+ dashcardTabId: 5,
+ withSidebar: true,
+ });
+
+ expect(await screen.findByText(EVENT.name)).toBeInTheDocument();
+ });
+
+ it("shows the empty state when the charts are on another tab", async () => {
+ setup({
+ savedVisibility: EVENTS_RECORDED,
+ selectedTabId: 5,
+ dashcardTabId: 6,
+ withSidebar: true,
+ });
+
+ expect(
+ await screen.findByTestId("dashboard-events-empty-state"),
+ ).toBeInTheDocument();
+ expect(screen.queryByText(EVENT.name)).not.toBeInTheDocument();
+ });
+
+ it("does not list events that no chart on the dashboard can show", async () => {
+ setup({
+ savedVisibility: EVENTS_RECORDED,
+ timelines: [
+ createMockTimeline({ ...TIMELINE, events: [OUT_OF_RANGE_EVENT] }),
+ ],
+ withSidebar: true,
+ });
+
+ expect(
+ await screen.findByText("Add context to your time series charts"),
+ ).toBeInTheDocument();
+ expect(screen.queryByText(OUT_OF_RANGE_EVENT.name)).not.toBeInTheDocument();
+ });
+
+ it("keeps the events it does not list when a timeline is unchecked", async () => {
+ const { store } = setup({
+ savedVisibility: EVENTS_RECORDED,
+ timelines: [
+ createMockTimeline({ ...TIMELINE, events: [EVENT, SAME_RANGE_EVENT] }),
+ ],
+ withSidebar: true,
+ });
+ await act(async () => {
+ store.dispatch(
+ openEventsSidebar({
+ dashcardId: DASHCARD_ID,
+ focusedEventIds: [EVENT.id],
+ }),
+ );
+ });
+
+ expect(await screen.findByText(EVENT.name)).toBeInTheDocument();
+ expect(screen.queryByText(SAME_RANGE_EVENT.name)).not.toBeInTheDocument();
+
+ await userEvent.click(getTimelineCheckbox(TIMELINE.name));
+
+ expect(
+ getDashCardVisibleTimelineEventIds(store.getState(), DASHCARD_ID),
+ ).toEqual([SAME_RANGE_EVENT.id]);
+ });
+
+ const setupSeriesChart = ({ withSeries }: { withSeries: boolean }) => {
+ const seriesCard = createMockCard({ id: 42, display: "line" });
+ setup({
+ dashcards: [
+ createMockDashboardCard({
+ id: DASHCARD_ID,
+ dashboard_id: DASHBOARD_ID,
+ card: createMockCard({
+ display: "line",
+ visualization_settings: EVENTS_RECORDED,
+ }),
+ series: withSeries ? [seriesCard] : [],
+ }),
+ ],
+ datasets: { [seriesCard.id]: LATER_DATASET },
+ timelines: [createMockTimeline({ ...TIMELINE, events: [LATER_EVENT] })],
+ withSidebar: true,
+ });
+ };
+
+ it("lists an event that only the chart's added series reaches", async () => {
+ setupSeriesChart({ withSeries: true });
+
+ expect(await screen.findByText(LATER_EVENT.name)).toBeInTheDocument();
+ });
+
+ it("does not list that event when the chart has no series", async () => {
+ setupSeriesChart({ withSeries: false });
+
+ expect(
+ await screen.findByText("Add context to your time series charts"),
+ ).toBeInTheDocument();
+ expect(screen.queryByText(LATER_EVENT.name)).not.toBeInTheDocument();
+ });
+
+ it.each(["metric", "model"] as const)(
+ "lists the events of a %s",
+ async (type) => {
+ const dashcards = [
+ createMockDashboardCard({
+ id: DASHCARD_ID,
+ dashboard_id: DASHBOARD_ID,
+ card: createMockCard({
+ type,
+ display: "line",
+ visualization_settings: EVENTS_RECORDED,
+ }),
+ }),
+ ];
+ setup({ dashcards, withSidebar: true });
+
+ expect(await screen.findByText(EVENT.name)).toBeInTheDocument();
+ },
+ );
+
+ it("re-reports a chart too small for events after a dashboard state reset", async () => {
+ // mirrors what the chart does: report its measured state whenever the reporter identity changes
+ const SmallChart = ({ dashcardId }: { dashcardId: DashCardId }) => {
+ const report = useReportDashCardTimelineEventsEnabled(dashcardId);
+ useEffect(() => report(false), [report]);
+ return null;
+ };
+ const { store } = renderWithProviders(
+ <MockDashboardContext dashboardId={DASHBOARD_ID} withTimelineEvents>
+ <SmallChart dashcardId={DASHCARD_ID} />
+ </MockDashboardContext>,
+ { storeInitialState: createMockState() },
+ );
+
+ const isEnabled = () =>
+ getIsDashCardTimelineEventsEnabled(store.getState(), DASHCARD_ID);
+ await waitFor(() => expect(isEnabled()).toBe(false));
+
+ act(() => {
+ store.dispatch({ type: SET_EDITING_DASHBOARD, payload: {} });
+ });
+
+ await waitFor(() => expect(isEnabled()).toBe(false));
+ });
+
+ it("ignores a chart that is too small to show events", async () => {
+ const question = createMockCard({
+ display: "line",
+ visualization_settings: EVENTS_RECORDED,
+ });
+ const dashcards = [
+ createMockDashboardCard({ id: 2, card: question }),
+ createMockDashboardCard({
+ id: 3,
+ card: createMockCard({ ...question, visualization_settings: {} }),
+ }),
+ ];
+ const { store } = setup({ dashcards, withSidebar: true });
+
+ await screen.findByText(EVENT.name);
+ expect(getTimelineEventCheckbox(EVENT.name)).toBePartiallyChecked();
+
+ await act(async () => {
+ store.dispatch(
+ setDashCardTimelineEventsEnabled({ dashcardId: 3, isEnabled: false }),
+ );
+ });
+
+ expect(getTimelineEventCheckbox(EVENT.name)).toBeChecked();
+ });
+
+ it("loads the timelines once however many charts the dashboard has", async () => {
+ setupTimelinesEndpoints([TIMELINE]);
+ const question = createMockCard({
+ display: "line",
+ visualization_settings: EVENTS_RECORDED,
+ });
+ const dashcards = [3, 4, 5].map((id) =>
+ createMockDashboardCard({
+ id,
+ dashboard_id: DASHBOARD_ID,
+ card: question,
+ }),
+ );
+
+ setup({ dashcards, withSidebar: true, seedTimelines: false });
+
+ expect(await screen.findByText(EVENT.name)).toBeInTheDocument();
+ expect(fetchMock.callHistory.calls("path:/api/timeline")).toHaveLength(1);
+ });
+
+ // mounts the prefetch hook itself — `setup` renders charts, which do not call it
+ const setupPrefetch = async (savedVisibility: VisualizationSettings) => {
+ setupTimelinesEndpoints([TIMELINE]);
+ const Prefetcher = () => {
+ useDashboardTimelines();
+ return null;
+ };
+ const card = createMockCard({
+ display: "line",
+ visualization_settings: savedVisibility,
+ });
+ const dashcard = createMockDashboardCard({
+ id: DASHCARD_ID,
+ dashboard_id: DASHBOARD_ID,
+ card,
+ });
+
+ renderWithProviders(
+ <MockDashboardContext dashboardId={DASHBOARD_ID} withTimelineEvents>
+ <Prefetcher />
+ </MockDashboardContext>,
+ {
+ storeInitialState: createMockState({
+ dashboard: createMockDashboardState({
+ dashboardId: DASHBOARD_ID,
+ dashboards: {
+ [DASHBOARD_ID]: createMockStoreDashboard({
+ id: DASHBOARD_ID,
+ dashcards: [DASHCARD_ID],
+ }),
+ },
+ dashcards: { [DASHCARD_ID]: dashcard },
+ dashcardData: { [DASHCARD_ID]: { [card.id]: DATASET } },
+ }),
+ }),
+ },
+ );
+ await waitFor(() => expect(true).toBe(true));
+ return fetchMock.callHistory.calls("path:/api/timeline");
+ };
+
+ it("loads the timelines when a chart selects one", async () => {
+ expect(await setupPrefetch(EVENTS_RECORDED)).toHaveLength(1);
+ });
+
+ it.each([
+ ["recorded no selection", {}],
+ ["recorded an empty selection", { "timeline.selected_timeline_ids": [] }],
+ ])(
+ "does not load the timelines when every chart %s",
+ async (_description, savedVisibility) => {
+ expect(await setupPrefetch(savedVisibility)).toHaveLength(0);
+ },
+ );
+
+ describe.each([
+ ["public dashboards", "isPublicEmbedding"],
+ ["static embedded dashboards", "isStaticEmbedding"],
+ ] as const)("%s", (_surface, configMethod) => {
+ beforeEach(() => {
+ jest.spyOn(embeddingConfig, configMethod).mockReturnValue(true);
+ });
+
+ it("uses the shared payload and saved selection despite broader cached events and session overrides", () => {
+ const { result } = setupReadOnlyDashboard({ timelineEvents: [EVENT] });
+
+ expect(result.current.timelineEvents).toEqual([EVENT]);
+ expect(result.current.dashcardProps.timelineEventsVisibility).toEqual({
+ "timeline.selected_timeline_ids": [TIMELINE.id],
+ "timeline.excluded_timeline_event_ids": [EXCLUDED_EVENT.id],
+ });
+ expect(fetchMock.callHistory.calls("path:/api/timeline")).toHaveLength(0);
+ });
+
+ it.each([undefined, []])(
+ "does not fall back to cached collection events when the payload is %s",
+ (timelineEvents) => {
+ const { result } = setupReadOnlyDashboard({ timelineEvents });
+
+ expect(result.current.timelineEvents).toEqual([]);
+ expect(fetchMock.callHistory.calls("path:/api/timeline")).toHaveLength(
+ 0,
+ );
+ },
+ );
+ });
+
+ it.each([{}, { dashcardId: DASHCARD_ID }])(
+ "does not reopen a collection-backed sidebar from stale state when controls are disabled (%j)",
+ (sidebarProps) => {
+ renderWithProviders(
+ <MockDashboardContext withTimelineEvents={false}>
+ <div data-testid="sidebar-container">
+ <DashboardEventsSidebar />
+ </div>
+ </MockDashboardContext>,
+ {
+ storeInitialState: createMockState({
+ dashboard: createMockDashboardState({
+ sidebar: { name: "events", props: sidebarProps },
+ }),
+ }),
+ },
+ );
+
+ expect(screen.getByTestId("sidebar-container")).toBeEmptyDOMElement();
+ expect(fetchMock.callHistory.calls("path:/api/timeline")).toHaveLength(0);
+ },
+ );
+
+ it("applies mixed dashboard-wide selections only to eligible charts on the current tab", async () => {
+ const question = createMockCard({
+ display: "line",
+ visualization_settings: EVENTS_RECORDED,
+ });
+ const dashcards = [
+ createMockDashboardCard({ id: 2, card: question, dashboard_tab_id: 5 }),
+ createMockDashboardCard({
+ id: 3,
+ card: createMockCard({ ...question, visualization_settings: {} }),
+ dashboard_tab_id: 5,
+ }),
+ createMockDashboardCard({
+ id: 4,
+ card: createMockCard({ ...question, display: "table" }),
+ dashboard_tab_id: 5,
+ }),
+ createMockDashboardCard({
+ id: 5,
+ card: createMockCard({
+ ...question,
+ visualization_settings: {
+ ...EVENTS_RECORDED,
+ "timeline_events.enabled": false,
+ },
+ }),
+ dashboard_tab_id: 5,
+ }),
+ createMockDashboardCard({ id: 6, card: question, dashboard_tab_id: 6 }),
+ ];
+ const { store } = setup({ dashcards, selectedTabId: 5, withSidebar: true });
+
+ await screen.findByText(EVENT.name);
+ expect(getTimelineEventCheckbox(EVENT.name)).toBePartiallyChecked();
+
+ await userEvent.click(getTimelineEventCheckbox(EVENT.name));
+
+ expect(getTimelineEventCheckbox(EVENT.name)).toBeChecked();
+ expect(getDashCardVisibleTimelineEventIds(store.getState(), 2)).toEqual([
+ EVENT.id,
+ ]);
+ expect(getDashCardVisibleTimelineEventIds(store.getState(), 3)).toEqual([
+ EVENT.id,
+ ]);
+
+ await userEvent.click(getTimelineEventCheckbox(EVENT.name));
+
+ expect(getTimelineEventCheckbox(EVENT.name)).not.toBeChecked();
+ expect(getDashCardVisibleTimelineEventIds(store.getState(), 2)).toEqual([]);
+ expect(getDashCardVisibleTimelineEventIds(store.getState(), 3)).toEqual([]);
+ expect(getDashCardVisibleTimelineEventIds(store.getState(), 6)).toEqual([
+ EVENT.id,
+ ]);
+ expect(
+ Object.keys(store.getState().dashboard.timelineEvents.overrides),
+ ).toEqual(["2", "3"]);
+ expect(Object.values(store.getState().dashboard.dashcards)).toEqual(
+ dashcards,
+ );
+ });
+
+ it.each(["removing its chart", "switching tabs"])(
+ "closes a targeted panel after %s while preserving other chart choices",
+ async (change) => {
+ const question = createMockCard({
+ display: "line",
+ visualization_settings: EVENTS_RECORDED,
+ });
+ const dashcards = [
+ createMockDashboardCard({
+ id: DASHCARD_ID,
+ card: question,
+ dashboard_tab_id: 5,
+ }),
+ createMockDashboardCard({ id: 3, card: question, dashboard_tab_id: 5 }),
+ ];
+ const { store } = setup({
+ dashcards,
+ selectedTabId: 5,
+ withSidebar: true,
+ });
+ await act(async () => {
+ store.dispatch(
+ setDashCardTimelineEventsVisibility({
+ 3: { "timeline.selected_timeline_ids": [] },
+ }),
+ );
+ store.dispatch(
+ selectTimelineEvents({
+ dashcardId: DASHCARD_ID,
+ eventIds: [EVENT.id],
+ }),
+ );
+ store.dispatch(openEventsSidebar({ dashcardId: DASHCARD_ID }));
+ });
+ expect(
+ await screen.findByTestId("dashboard-events-sidebar"),
+ ).toBeInTheDocument();
+
+ await act(async () => {
+ if (change === "removing its chart") {
+ await store.dispatch(
+ removeCardFromDashboard({
+ dashcardId: DASHCARD_ID,
+ cardId: question.id,
+ }),
+ );
+ } else {
+ store.dispatch(selectTab({ tabId: 6 }));
+ }
+ });
+
+ await waitFor(() =>
+ expect(
+ screen.queryByTestId("dashboard-events-sidebar"),
+ ).not.toBeInTheDocument(),
+ );
+ expect(store.getState().dashboard.timelineEvents.selection).toBeNull();
+ expect(getDashCardVisibleTimelineEventIds(store.getState(), 3)).toEqual(
+ [],
+ );
+ expect(store.getState().dashboard.timelineEvents.overrides[3]).toEqual({
+ "timeline.selected_timeline_ids": [],
+ });
+ },
+ );
+});
+
+function setupReadOnlyDashboard({
+ timelineEvents,
+}: {
+ timelineEvents?: TimelineEvent[];
+}) {
+ const savedVisibility: TimelineEventsVisibility = {
+ "timeline.selected_timeline_ids": [TIMELINE.id],
+ "timeline.excluded_timeline_event_ids": [EXCLUDED_EVENT.id],
+ };
+ const card = createMockCard({
+ display: "line",
+ visualization_settings: savedVisibility,
+ });
+ const dashcard = createMockDashboardCard({
+ id: DASHCARD_ID,
+ card,
+ timeline_events: timelineEvents,
+ });
+ const series = [{ card, ...DATASET }];
+ const settings = getComputedSettingsForSeries(series);
+ const { wrapper: Wrapper } = getTestStoreAndWrapper({
+ initialRoute: "/",
+ storeInitialState: createMockState({
+ dashboard: createMockDashboardState({
+ dashboardId: DASHBOARD_ID,
+ dashcards: { [DASHCARD_ID]: dashcard },
+ dashcardData: { [DASHCARD_ID]: { [card.id]: DATASET } },
+ timelineEvents: {
+ overrides: {
+ [DASHCARD_ID]: {
+ "timeline.selected_timeline_ids": [
+ TIMELINE.id,
+ UNRELATED_EVENT.timeline_id,
+ ],
+ "timeline.excluded_timeline_event_ids": [],
+ },
+ },
+ enabledByDashCard: {},
+ selection: {
+ dashcardId: DASHCARD_ID,
+ eventIds: [UNRELATED_EVENT.id],
+ },
+ hasTrackedEventsShown: false,
+ },
+ }),
+ "metabase-api": seedApiQueryCache(createMockApiState(), [
+ {
+ endpointName: "listTimelines",
+ arg: { include: "events" },
+ value: [
+ createMockTimeline({
+ ...TIMELINE,
+ events: [EVENT, EXCLUDED_EVENT],
+ }),
+ createMockTimeline({
+ id: UNRELATED_EVENT.timeline_id,
+ events: [UNRELATED_EVENT],
+ }),
+ ],
+ },
+ ]),
+ }),
+ });
+
+ return renderHook(
+ () => {
+ const dashcardProps = useDashCardTimelineEvents(dashcard);
+ return {
+ dashcardProps,
+ ...useTimelineEvents({
+ ...dashcardProps,
+ series,
+ settings,
+ isDashboard: true,
+ }),
+ };
+ },
+ {
+ wrapper: ({ children }: PropsWithChildren) => (
+ <Wrapper>
+ <MockDashboardContext withTimelineEvents={false}>
+ {children}
+ </MockDashboardContext>
+ </Wrapper>
+ ),
+ },
+ );
+}
diff --git a/frontend/src/metabase/dashboard/timeline-events/index.ts b/frontend/src/metabase/dashboard/timeline-events/index.ts
new file mode 100644
index 00000000000..c2943f10f65
--- /dev/null
+++ b/frontend/src/metabase/dashboard/timeline-events/index.ts
@@ -0,0 +1,3 @@
+export * from "./hooks";
+export * from "./selectors";
+export * from "./utils";
diff --git a/frontend/src/metabase/dashboard/timeline-events/selectors.ts b/frontend/src/metabase/dashboard/timeline-events/selectors.ts
new file mode 100644
index 00000000000..e5141daca90
--- /dev/null
+++ b/frontend/src/metabase/dashboard/timeline-events/selectors.ts
@@ -0,0 +1,196 @@
+import { createSelector } from "@reduxjs/toolkit";
+import { shallowEqual } from "react-redux";
+
+import {
+ getCurrentDashcards,
+ getDashCardById,
+ getDashcardData,
+ getDashcardDataMap,
+ getDashcards,
+ getSelectedTabId,
+} from "metabase/dashboard/selectors";
+import { isDashCardOnTab, isDashcardLoading } from "metabase/dashboard/utils";
+import type {
+ DashboardState,
+ DashboardTimelineEventsState,
+ State,
+} from "metabase/redux/store";
+import { getTransformedTimelines } from "metabase/timelines/panel/selectors";
+import {
+ aggregateVisibleEventIds,
+ getRecordedTimelineEventsVisibility,
+ resolveVisibleTimelineEvents,
+} from "metabase/visualizations/lib/timeline-events-visibility";
+import type { TimeseriesXAxis } from "metabase/viz-core";
+import type {
+ DashCardDataMap,
+ DashCardId,
+ DashboardCard,
+ TimelineEventId,
+ TimelineEventsVisibility,
+} from "metabase-types/api";
+
+import {
+ computeDashCardTimeseriesXAxis,
+ shouldDashCardDisplayTimelineEvents,
+} from "./utils";
+
+const NO_EVENT_IDS: TimelineEventId[] = [];
+
+const shallowEqualResult = {
+ memoizeOptions: { resultEqualityCheck: shallowEqual },
+};
+
+const getTimelineEventsOverrides = (state: State) =>
+ state.dashboard.timelineEvents.overrides;
+
+const getTimelineEventsEnabledByDashCard = (state: State) =>
+ state.dashboard.timelineEvents.enabledByDashCard;
+
+export const getIsDashCardTimelineEventsEnabled = (
+ state: State,
+ dashcardId: DashCardId,
+): boolean => getTimelineEventsEnabledByDashCard(state)[dashcardId] !== false;
+
+const resolveDashCardVisibility = (
+ overrides: DashboardTimelineEventsState["overrides"],
+ dashcards: DashboardState["dashcards"],
+ dashcardId: DashCardId,
+): TimelineEventsVisibility | undefined =>
+ overrides[dashcardId] ??
+ getRecordedTimelineEventsVisibility(
+ dashcards[dashcardId]?.card?.visualization_settings,
+ );
+
+export const getDashCardTimelineEventsVisibility = (
+ state: State,
+ dashcardId: DashCardId,
+): TimelineEventsVisibility | undefined =>
+ resolveDashCardVisibility(
+ getTimelineEventsOverrides(state),
+ getDashcards(state),
+ dashcardId,
+ );
+
+// keyed weakly on the dashcard and its data, independent of the rest of the state
+const computeCachedDashCardTimeseriesXAxis = createSelector(
+ [
+ (dashcard: DashboardCard) => dashcard,
+ (
+ _dashcard: DashboardCard,
+ dashcardData: DashCardDataMap[number] | undefined,
+ ) => dashcardData,
+ ],
+ computeDashCardTimeseriesXAxis,
+);
+
+export const getDashCardTimeseriesXAxis = (
+ state: State,
+ dashcardId: DashCardId,
+) => {
+ const dashcard = getDashCardById(state, dashcardId);
+ return dashcard
+ ? computeCachedDashCardTimeseriesXAxis(
+ dashcard,
+ getDashcardData(state, dashcardId),
+ )
+ : null;
+};
+
+export const getDashCardVisibleTimelineEventIds = createSelector(
+ [getTransformedTimelines, getDashCardTimelineEventsVisibility],
+ (timelines, visibility): TimelineEventId[] => {
+ const ids = resolveVisibleTimelineEvents({ timelines, visibility }).map(
+ (event) => event.id,
+ );
+ return ids.length > 0 ? ids : NO_EVENT_IDS;
+ },
+ shallowEqualResult,
+);
+
+export const getDashCardSelectedTimelineEventIds = (
+ state: State,
+ dashcardId?: DashCardId,
+): TimelineEventId[] => {
+ const selection = state.dashboard.timelineEvents.selection;
+ return selection &&
+ (selection.dashcardId == null || selection.dashcardId === dashcardId)
+ ? selection.eventIds
+ : NO_EVENT_IDS;
+};
+
+export const getTimelineEventsDashCardIds = createSelector(
+ [
+ getCurrentDashcards,
+ getSelectedTabId,
+ getDashcardDataMap,
+ getTimelineEventsEnabledByDashCard,
+ ],
+ (dashcards, selectedTabId, dashcardDataMap, enabledByDashCard) =>
+ dashcards
+ .filter((dashcard) => {
+ const dashcardData = dashcardDataMap[dashcard.id];
+ return (
+ isDashCardOnTab(dashcard, selectedTabId) &&
+ shouldDashCardDisplayTimelineEvents(dashcard) &&
+ enabledByDashCard[dashcard.id] !== false &&
+ (isDashcardLoading(dashcard, dashcardData) ||
+ computeCachedDashCardTimeseriesXAxis(dashcard, dashcardData) !=
+ null)
+ );
+ })
+ .map((dashcard) => dashcard.id),
+ shallowEqualResult,
+);
+
+// absent while a chart is still loading, so the panel does not filter events out prematurely
+export const getTimelineEventsDashCardXAxes = createSelector(
+ [getTimelineEventsDashCardIds, getDashcards, getDashcardDataMap],
+ (dashcardIds, dashcards, dashcardDataMap): TimeseriesXAxis[] | null => {
+ const xAxes = dashcardIds.flatMap((dashcardId) => {
+ const dashcard = dashcards[dashcardId];
+ const xAxis = dashcard
+ ? computeCachedDashCardTimeseriesXAxis(
+ dashcard,
+ dashcardDataMap[dashcardId],
+ )
+ : null;
+ return xAxis ? [xAxis] : [];
+ });
+ return xAxes.length === dashcardIds.length ? xAxes : null;
+ },
+ shallowEqualResult,
+);
+
+export const getHasSelectedTimelineEvents = createSelector(
+ [getTimelineEventsDashCardIds, getTimelineEventsOverrides, getDashcards],
+ (dashcardIds, overrides, dashcards) =>
+ dashcardIds.some(
+ (dashcardId) =>
+ (resolveDashCardVisibility(overrides, dashcards, dashcardId)?.[
+ "timeline.selected_timeline_ids"
+ ]?.length ?? 0) > 0,
+ ),
+);
+
+export const getDashboardTimelineEventsAggregate = createSelector(
+ [
+ getTimelineEventsDashCardIds,
+ getTransformedTimelines,
+ getTimelineEventsOverrides,
+ getDashcards,
+ ],
+ (dashcardIds, timelines, overrides, dashcards) =>
+ aggregateVisibleEventIds(
+ dashcardIds.map((dashcardId) =>
+ resolveVisibleTimelineEvents({
+ timelines,
+ visibility: resolveDashCardVisibility(
+ overrides,
+ dashcards,
+ dashcardId,
+ ),
+ }).map((event) => event.id),
+ ),
+ ),
+);
diff --git a/frontend/src/metabase/dashboard/timeline-events/utils.ts b/frontend/src/metabase/dashboard/timeline-events/utils.ts
new file mode 100644
index 00000000000..be2a8c915c7
--- /dev/null
+++ b/frontend/src/metabase/dashboard/timeline-events/utils.ts
@@ -0,0 +1,49 @@
+import { isQuestionDashCard } from "metabase/utils/dashboard";
+import { isTimelineEventsEnabled } from "metabase/visualizations/lib/timeline-events-visibility";
+import {
+ type TimeseriesXAxis,
+ canDisplayTimelineEvents,
+ extendCardWithDashcardSettings,
+ getComputedSettingsForSeries,
+ getTimeseriesXAxis,
+} from "metabase/viz-core";
+import type {
+ DashCardDataMap,
+ DashboardCard,
+ QuestionDashboardCard,
+ RawSeries,
+} from "metabase-types/api";
+import { isVisualizerDashboardCard } from "metabase-types/guards/dashboard";
+
+// "timeline_events.enabled" is a question-only setting, so dashcard settings can't override it
+export const shouldDashCardDisplayTimelineEvents = (
+ dashcard: DashboardCard,
+): dashcard is QuestionDashboardCard =>
+ isQuestionDashCard(dashcard) &&
+ !isVisualizerDashboardCard(dashcard) &&
+ canDisplayTimelineEvents(dashcard.card.display) &&
+ isTimelineEventsEnabled(dashcard.card.visualization_settings);
+
+export const computeDashCardTimeseriesXAxis = (
+ dashcard: DashboardCard,
+ dashcardData: DashCardDataMap[number] | undefined,
+): TimeseriesXAxis | null => {
+ if (!shouldDashCardDisplayTimelineEvents(dashcard)) {
+ return null;
+ }
+ const cards = [
+ extendCardWithDashcardSettings(
+ dashcard.card,
+ dashcard.visualization_settings,
+ ),
+ ...(dashcard.series ?? []),
+ ];
+ const series: RawSeries = cards.flatMap((card) => {
+ const dataset = dashcardData?.[card.id];
+ return dataset?.data ? [{ card, ...dataset }] : [];
+ });
+ if (series.length === 0) {
+ return null;
+ }
+ return getTimeseriesXAxis(series, getComputedSettingsForSeries(series));
+};
diff --git a/frontend/src/metabase/dashboard/utils.ts b/frontend/src/metabase/dashboard/utils.ts
index f51b00c2723..0399ec63124 100644
--- a/frontend/src/metabase/dashboard/utils.ts
+++ b/frontend/src/metabase/dashboard/utils.ts
@@ -213,14 +213,17 @@ export function getAllDashboardCards(dashboard: Dashboard) {
return results;
}
+export const isDashCardOnTab = (
+ dashcard: BaseDashboardCard,
+ tabId: SelectedTabId,
+) => (dashcard.dashboard_tab_id ?? null) === tabId;
+
export function getCurrentTabDashboardCards(
dashboard: Dashboard,
selectedTabId: SelectedTabId,
) {
- return getAllDashboardCards(dashboard).filter(
- ({ dashcard }) =>
- (dashcard.dashboard_tab_id == null && selectedTabId == null) ||
- dashcard.dashboard_tab_id === selectedTabId,
+ return getAllDashboardCards(dashboard).filter(({ dashcard }) =>
+ isDashCardOnTab(dashcard, selectedTabId),
);
}
diff --git a/frontend/src/metabase/documents/components/EmbedTimelineSidebar.tsx b/frontend/src/metabase/documents/components/EmbedTimelineSidebar.tsx
index 164917bc88d..68d834e7ba0 100644
--- a/frontend/src/metabase/documents/components/EmbedTimelineSidebar.tsx
+++ b/frontend/src/metabase/documents/components/EmbedTimelineSidebar.tsx
@@ -4,14 +4,15 @@ import { t } from "ttag";
import { useListTimelinesQuery } from "metabase/api";
import { useDispatch, useSelector } from "metabase/redux";
-import { TimelineSidebar } from "metabase/timelines/questions/components/TimelineSidebar";
+import { TimelineSidebar } from "metabase/timelines/panel/components/TimelineSidebar";
+import { getTransformedTimelines } from "metabase/timelines/panel/selectors";
import { Box, Loader, Stack, Text } from "metabase/ui";
-import { getTimelineEventSettings } from "metabase/viz-core";
-import type {
- CollectionId,
- TimelineEvent,
- TimelineEventId,
-} from "metabase-types/api";
+import {
+ isSameTimelineEventsVisibility,
+ resolveVisibleTimelineEvents,
+} from "metabase/visualizations/lib/timeline-events-visibility";
+import type { TimelineEventsVisibilityUpdate } from "metabase/visualizations/types";
+import type { CollectionId, TimelineEvent } from "metabase-types/api";
import {
clearFocusedTimelineEvents,
@@ -43,21 +44,11 @@ export function EmbedTimelineSidebar({
collectionId,
}: EmbedTimelineSidebarProps) {
const dispatch = useDispatch();
- const selectedTimelineEventIds = useSelector(getSelectedTimelineEventIds);
- const focusedTimelineEventIds = useSelector(getFocusedTimelineEventIds);
-
- const {
- data: timelineData = [],
- isLoading,
- isError,
- } = useListTimelinesQuery({
- include: "events",
- });
+ const selectedEventIds = useSelector(getSelectedTimelineEventIds);
+ const focusedEventIds = useSelector(getFocusedTimelineEventIds);
- const timelines = useMemo(
- () => timelineData.filter((timeline) => (timeline.events?.length ?? 0) > 0),
- [timelineData],
- );
+ const { isLoading, isError } = useListTimelinesQuery({ include: "events" });
+ const timelines = useSelector(getTransformedTimelines);
const { card, draftCard, regularDataset } = useCardData({
id: cardId,
@@ -72,72 +63,37 @@ export function EmbedTimelineSidebar({
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"] ??
- [],
- );
+ const visibility = card?.visualization_settings;
+ const visibleEventIds = useMemo(
+ () =>
+ resolveVisibleTimelineEvents({ timelines, visibility }).map(
+ (event) => event.id,
+ ),
+ [timelines, visibility],
+ );
- return timelines.flatMap((timeline) => {
- if (!selectedTimelineIds.has(timeline.id)) {
- return [];
+ const handleUpdateVisibility = useCallback(
+ (update: TimelineEventsVisibilityUpdate) => {
+ const nextVisibility = update(visibility ?? {}, timelines);
+ if (isSameTimelineEventsVisibility(visibility, nextVisibility)) {
+ 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),
- }),
+ updateVizSettings({ cardId: draftId, settings: nextVisibility }),
);
},
- [dispatch, ensureDraftCard, timelines],
+ [dispatch, ensureDraftCard, visibility, 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));
+ const handleSelectEvents = useCallback(
+ (events: TimelineEvent[]) => {
+ dispatch(selectTimelineEvents(events));
},
[dispatch],
);
- const handleDeselectTimelineEvents = useCallback(() => {
+ const handleDeselectEvents = useCallback(() => {
dispatch(deselectTimelineEvents());
}, [dispatch]);
@@ -145,6 +101,10 @@ export function EmbedTimelineSidebar({
dispatch(clearFocusedTimelineEvents());
}, [dispatch]);
+ const handleClose = useCallback(() => {
+ dispatch(closeSidebar());
+ }, [dispatch]);
+
if (isLoading) {
return (
<Stack gap="xl" p="xl" className={S.loadingContainer}>
@@ -171,13 +131,12 @@ export function EmbedTimelineSidebar({
<TimelineSidebar
collectionId={collectionId}
timelines={timelines}
- visibleTimelineEventIds={visibleTimelineEventIds}
- selectedTimelineEventIds={selectedTimelineEventIds}
- focusedTimelineEventIds={focusedTimelineEventIds}
- onShowTimelineEvents={handleShowTimelineEvents}
- onHideTimelineEvents={handleHideTimelineEvents}
- onSelectTimelineEvents={handleSelectTimelineEvents}
- onDeselectTimelineEvents={handleDeselectTimelineEvents}
+ visibleEventIds={visibleEventIds}
+ selectedEventIds={selectedEventIds}
+ focusedEventIds={focusedEventIds}
+ onUpdateVisibility={handleUpdateVisibility}
+ onSelectEvents={handleSelectEvents}
+ onDeselectEvents={handleDeselectEvents}
onShowAllEvents={handleShowAllEvents}
onClose={handleClose}
/>
diff --git a/frontend/src/metabase/documents/components/EmbedTimelineSidebar.unit.spec.tsx b/frontend/src/metabase/documents/components/EmbedTimelineSidebar.unit.spec.tsx
new file mode 100644
index 00000000000..47371fc9743
--- /dev/null
+++ b/frontend/src/metabase/documents/components/EmbedTimelineSidebar.unit.spec.tsx
@@ -0,0 +1,118 @@
+import userEvent from "@testing-library/user-event";
+
+import {
+ setupCardEndpoints,
+ setupCardQueryEndpoints,
+ setupCollectionByIdEndpoint,
+ setupTimelinesEndpoints,
+} from "__support__/server-mocks";
+import {
+ getTimelineCheckbox,
+ getTimelineEventCheckbox,
+} from "__support__/timelines";
+import { renderWithProviders, screen, waitFor } from "__support__/ui";
+import { ROOT_COLLECTION } from "metabase/common/collections/constants";
+import type { TimelineEventsVisibility } from "metabase-types/api";
+import {
+ createMockCard,
+ createMockCollection,
+ createMockDataset,
+ createMockTimeline,
+ createMockTimelineEvent,
+} from "metabase-types/api/mocks";
+
+import { getDraftCards } from "../selectors";
+
+import { EmbedTimelineSidebar } from "./EmbedTimelineSidebar";
+
+const CARD_ID = 1;
+
+const RC1 = createMockTimelineEvent({
+ id: 11,
+ timeline_id: 10,
+ name: "RC1",
+ timestamp: "2027-06-03T00:00:00Z",
+});
+const RC2 = createMockTimelineEvent({
+ id: 12,
+ timeline_id: 10,
+ name: "RC2",
+ timestamp: "2027-06-15T00:00:00Z",
+});
+const RELEASES = createMockTimeline({
+ id: 10,
+ name: "Releases",
+ collection_id: null,
+ events: [RC1, RC2],
+});
+
+const setup = async (visibility?: TimelineEventsVisibility) => {
+ const card = createMockCard({
+ id: CARD_ID,
+ display: "line",
+ visualization_settings: { ...visibility },
+ });
+ setupCardEndpoints(card);
+ setupCardQueryEndpoints(card, createMockDataset());
+ setupTimelinesEndpoints([RELEASES]);
+ setupCollectionByIdEndpoint({
+ collections: [
+ createMockCollection({ ...ROOT_COLLECTION, can_write: true }),
+ ],
+ });
+
+ const { store } = renderWithProviders(
+ <EmbedTimelineSidebar
+ cardId={CARD_ID}
+ selectedEmbedIndex={0}
+ collectionId={null}
+ />,
+ );
+ await screen.findByText("RC1");
+ return store;
+};
+
+const getDraftCardSettings = (store: Awaited<ReturnType<typeof setup>>) =>
+ Object.values(getDraftCards(store.getState()))[0]?.visualization_settings;
+
+describe("EmbedTimelineSidebar", () => {
+ it("shows the events the card recorded", async () => {
+ await setup({
+ "timeline.selected_timeline_ids": [RELEASES.id],
+ "timeline.excluded_timeline_event_ids": [RC2.id],
+ });
+
+ expect(getTimelineEventCheckbox("RC1")).toBeChecked();
+ expect(getTimelineEventCheckbox("RC2")).not.toBeChecked();
+ });
+
+ it("hiding an event records the selection on a draft card", async () => {
+ const store = await setup({
+ "timeline.selected_timeline_ids": [RELEASES.id],
+ "timeline.excluded_timeline_event_ids": [],
+ });
+
+ await userEvent.click(getTimelineEventCheckbox("RC1"));
+
+ await waitFor(() => {
+ expect(getDraftCardSettings(store)).toEqual({
+ "timeline.selected_timeline_ids": [RELEASES.id],
+ "timeline.excluded_timeline_event_ids": [RC1.id],
+ });
+ });
+ });
+
+ it("turning a timeline on records it for a card that never recorded events", async () => {
+ const store = await setup();
+ expect(getTimelineEventCheckbox("RC1")).not.toBeChecked();
+
+ await userEvent.click(getTimelineCheckbox("Releases"));
+
+ await waitFor(() => {
+ expect(getDraftCardSettings(store)).toEqual({
+ "timeline.selected_timeline_ids": [RELEASES.id],
+ "timeline.excluded_timeline_event_ids": [],
+ });
+ });
+ });
+});
diff --git a/frontend/src/metabase/documents/documents.slice.ts b/frontend/src/metabase/documents/documents.slice.ts
index a9d9fb093d6..495c4630cc4 100644
--- a/frontend/src/metabase/documents/documents.slice.ts
+++ b/frontend/src/metabase/documents/documents.slice.ts
@@ -181,8 +181,12 @@ const documentsSlice = createSlice({
} as Card;
const originalCardId = originalCard?.id;
- if (originalCardId != null && originalCardId > 0) {
- state.draftCardOriginalIds[draftId] = originalCardId;
+ const savedOriginalId =
+ originalCardId != null && originalCardId < 0
+ ? state.draftCardOriginalIds[originalCardId]
+ : originalCardId;
+ if (savedOriginalId != null && savedOriginalId > 0) {
+ state.draftCardOriginalIds[draftId] = savedOriginalId;
}
},
clearDraftCards: (state) => {
diff --git a/frontend/src/metabase/documents/hooks/use-document-editor.ts b/frontend/src/metabase/documents/hooks/use-document-editor.ts
index 6af13663240..db2d126b228 100644
--- a/frontend/src/metabase/documents/hooks/use-document-editor.ts
+++ b/frontend/src/metabase/documents/hooks/use-document-editor.ts
@@ -30,9 +30,10 @@ import type { CardEmbedRef } from "metabase/redux/store/documents";
import { useNavigate } from "metabase/router";
import * as Urls from "metabase/urls";
import type {
- Card,
+ CardId,
CollectionId,
Document,
+ DocumentCardToCreate,
DocumentId,
RegularCollectionId,
} from "metabase-types/api";
@@ -44,7 +45,11 @@ import {
setHasUnsavedChanges,
setSidebarEmbedIndex,
} from "../documents.slice";
-import { getDraftCards, getHasUnsavedChanges } from "../selectors";
+import {
+ getDraftCardOriginalIds,
+ getDraftCards,
+ getHasUnsavedChanges,
+} from "../selectors";
import { useDocumentState } from "./use-document-state";
import { useRegisterDocumentMetabotContext } from "./use-register-document-metabot-context";
@@ -101,6 +106,7 @@ export function useDocumentEditor({
const [sendToast] = useToast();
const draftCards = useSelector(getDraftCards);
+ const draftCardOriginalIds = useSelector(getDraftCardOriginalIds);
const hasUnsavedEditorChanges = useSelector(getHasUnsavedChanges);
const [editorInstance, setEditorInstance] = useState<TiptapEditor | null>(
@@ -310,7 +316,7 @@ export function useDocumentEditor({
}
try {
- const cardsToSave: Record<number, Card> = {};
+ const cardsToSave: Record<number, DocumentCardToCreate> = {};
const processedCardIds = new Set<number>();
editorInstance.state.doc.descendants((node: ProseMirrorNode) => {
@@ -320,7 +326,12 @@ export function useDocumentEditor({
processedCardIds.add(cardId);
if (cardId < 0 && draftCards[cardId]) {
- cardsToSave[cardId] = draftCards[cardId];
+ const originalId: CardId | undefined =
+ draftCardOriginalIds[cardId];
+ cardsToSave[cardId] =
+ originalId != null
+ ? { ...draftCards[cardId], source_card_id: originalId }
+ : draftCards[cardId];
}
}
}
@@ -385,6 +396,7 @@ export function useDocumentEditor({
isSaving,
documentTitle,
draftCards,
+ draftCardOriginalIds,
documentData?.id,
onDocumentCreated,
onDocumentUpdated,
diff --git a/frontend/src/metabase/documents/hooks/use-document-editor.unit.spec.ts b/frontend/src/metabase/documents/hooks/use-document-editor.unit.spec.ts
index a186e9e6990..686b6aedcf8 100644
--- a/frontend/src/metabase/documents/hooks/use-document-editor.unit.spec.ts
+++ b/frontend/src/metabase/documents/hooks/use-document-editor.unit.spec.ts
@@ -1,14 +1,21 @@
import { renderHook } from "@testing-library/react";
+import { Editor, Node } from "@tiptap/core";
+import TiptapDocument from "@tiptap/extension-document";
+import Paragraph from "@tiptap/extension-paragraph";
+import Text from "@tiptap/extension-text";
import fetchMock from "fetch-mock";
import { act, getTestStoreAndWrapper, waitFor } from "__support__/ui";
import { documentApi } from "metabase/api/document";
import type { Document } from "metabase-types/api";
import {
+ createMockCard,
createMockDocument,
createMockDocumentContent,
} from "metabase-types/api/mocks";
+import { createDraftCard } from "../documents.slice";
+
import { useDocumentEditor } from "./use-document-editor";
const DOCUMENT_ID = 1;
@@ -142,4 +149,59 @@ describe("useDocumentEditor", () => {
expect(result.current.isDocumentLoading).toBe(false);
expect(result.current.documentData?.name).toBe("Current");
});
+
+ it("sends the saved card id as source_card_id when a chart is edited twice", async () => {
+ const doc = createMockDocument({ id: DOCUMENT_ID });
+ const put = setupEndpoints(doc);
+
+ const { result, store } = renderEditorHook();
+ await waitForDocument(result);
+
+ const CardEmbed = Node.create({
+ name: "cardEmbed",
+ group: "block",
+ addAttributes: () => ({ id: { default: null } }),
+ renderHTML: () => ["div"],
+ });
+ const editor = new Editor({
+ extensions: [TiptapDocument, Paragraph, Text, CardEmbed],
+ content: {
+ type: "doc",
+ content: [{ type: "cardEmbed", attrs: { id: -2 } }],
+ },
+ });
+
+ act(() => {
+ result.current.setEditorInstance(editor);
+ store.dispatch(
+ createDraftCard({
+ originalCard: createMockCard({ id: 5 }),
+ modifiedData: {},
+ draftId: -1,
+ }),
+ );
+ store.dispatch(
+ createDraftCard({
+ originalCard: createMockCard({ id: -1 }),
+ modifiedData: {},
+ draftId: -2,
+ }),
+ );
+ });
+
+ put.resolve(doc);
+ await act(() => result.current.handleSave());
+ await waitFor(() => {
+ expect(result.current.isSaving).toBe(false);
+ });
+
+ const body = JSON.parse(
+ String(
+ fetchMock.callHistory.lastCall(`path:/api/document/${DOCUMENT_ID}`, {
+ method: "PUT",
+ })?.options.body,
+ ),
+ );
+ expect(body.cards["-2"]).toMatchObject({ source_card_id: 5 });
+ });
});
diff --git a/frontend/src/metabase/explorations/components/ExplorationVisualization/ActionToolbar.tsx b/frontend/src/metabase/explorations/components/ExplorationVisualization/ActionToolbar.tsx
index 9c85b173aa3..1c1a902a331 100644
--- a/frontend/src/metabase/explorations/components/ExplorationVisualization/ActionToolbar.tsx
+++ b/frontend/src/metabase/explorations/components/ExplorationVisualization/ActionToolbar.tsx
@@ -37,7 +37,7 @@ import {
Popover,
Tooltip,
} from "metabase/ui";
-import { getTimelineEventSettings } from "metabase/viz-core";
+import { showTimelines } from "metabase/visualizations/lib/timeline-events-visibility";
import type {
DocumentContent,
ExplorationId,
@@ -178,13 +178,7 @@ export function ActionToolbar({
async (chart: ExplorationChartForDocumentEmbed) => {
const timelineSettings =
selectedTimelineId != null
- ? getTimelineEventSettings(
- availableTimelines,
- (
- availableTimelines.find((t) => t.id === selectedTimelineId)
- ?.events ?? []
- ).map((event) => event.id),
- )
+ ? showTimelines({}, [selectedTimelineId], availableTimelines)
: {};
const { data: document, error } = await appendChartToSummary({
explorationId,
diff --git a/frontend/src/metabase/query_builder/actions/core/core.ts b/frontend/src/metabase/query_builder/actions/core/core.ts
index b9dde1e05dd..88669a8f75d 100644
--- a/frontend/src/metabase/query_builder/actions/core/core.ts
+++ b/frontend/src/metabase/query_builder/actions/core/core.ts
@@ -5,6 +5,7 @@ import {
databaseApi,
invalidateNotificationsApiCache,
revisionApi,
+ timelineApi,
} from "metabase/api";
import { listTag } from "metabase/api/tags";
import { runRtkEndpoint } from "metabase/api/utils/run-rtk-endpoint";
@@ -25,10 +26,20 @@ import {
questionUpdated,
} from "metabase/redux/query-builder";
import type { Dispatch, GetState } from "metabase/redux/store";
+import {
+ LIST_TIMELINES_REQUEST,
+ getTransformedTimelines,
+ selectListTimelines,
+} from "metabase/timelines/panel/selectors";
import * as Urls from "metabase/urls";
import { clone } from "metabase/utils/clone";
import { isNotNull } from "metabase/utils/types";
import {
+ getCollectionTimelinesVisibility,
+ getRecordedTimelineEventsVisibility,
+} from "metabase/visualizations/lib/timeline-events-visibility";
+import {
+ canDisplayTimelineEvents,
getCardAfterVisualizationClick,
getRegisteredDefaultSize,
} from "metabase/viz-core";
@@ -36,9 +47,17 @@ import * as Lib from "metabase-lib";
import Question from "metabase-lib/v1/Question";
import { isAdHocModelOrMetricQuestion } from "metabase-lib/v1/metadata/utils/models";
import NativeQuery from "metabase-lib/v1/queries/NativeQuery";
-import type { Card, DashboardTabId, DatasetQuery } from "metabase-types/api";
+import type {
+ Card,
+ CardId,
+ DashboardTabId,
+ DatasetQuery,
+} from "metabase-types/api";
-import { trackNewQuestionSaved } from "../../analytics";
+import {
+ trackNewQuestionSaved,
+ trackQuestionTimelineEventsSaved,
+} from "../../analytics";
import { updateModelIndexes } from "../../model-indexes/actions";
import {
API_CREATE_QUESTION,
@@ -60,6 +79,7 @@ import {
getSubmittableQuestion,
isBasedOnExistingQuestion,
} from "../../store/selectors";
+import { isLegacyTimelineEventsSource } from "../../utils/timeline-events";
import { runDirtyQuestionQuery, runQuestionQuery } from "../querying";
import { updateUrl } from "../url";
import { zoomInRow } from "../zoom";
@@ -222,7 +242,38 @@ export const setDatasetQuery =
dispatch(updateQuestion(question.setDatasetQuery(datasetQuery)));
};
-type OnCreateOptions = { dashboardTabId?: DashboardTabId | undefined };
+export type OnCreateOptions = {
+ dashboardTabId?: DashboardTabId | undefined;
+ sourceCardId?: CardId | undefined;
+ sourceQuestion?: Question | undefined;
+};
+
+// Record the displayed selection so the saved question shows the same events on a dashboard.
+const needsTimelineEventsRecording = (question: Question) =>
+ getRecordedTimelineEventsVisibility(question.settings()) == null &&
+ canDisplayTimelineEvents(question.display());
+
+const recordCollectionTimelineEvents = async (
+ question: Question,
+ dispatch: Dispatch,
+ getState: GetState,
+) => {
+ await dispatch(
+ timelineApi.endpoints.listTimelines.initiate(LIST_TIMELINES_REQUEST, {
+ forceRefetch: false,
+ subscribe: false,
+ }),
+ );
+ // Record an empty collection too, only a failed request leaves the selection unrecorded.
+ return selectListTimelines(getState()).isSuccess
+ ? question.updateSettings(
+ getCollectionTimelinesVisibility(
+ getTransformedTimelines(getState()),
+ question.collectionId(),
+ ),
+ )
+ : question;
+};
export const apiCreateQuestion = (
question: Question,
@@ -230,6 +281,20 @@ export const apiCreateQuestion = (
) => {
return async (dispatch: Dispatch, getState: GetState) => {
let submittableQuestion = getSubmittableQuestion(getState(), question);
+ if (needsTimelineEventsRecording(submittableQuestion)) {
+ submittableQuestion = isLegacyTimelineEventsSource(
+ options?.sourceQuestion ?? submittableQuestion,
+ )
+ ? submittableQuestion.updateSettings({
+ "timeline.selected_timeline_ids": [],
+ "timeline.excluded_timeline_event_ids": [],
+ })
+ : await recordCollectionTimelineEvents(
+ submittableQuestion,
+ dispatch,
+ getState,
+ );
+ }
// Saving models with list view setting as a question in not allowed for now,
// so we change it back to table.
if (
@@ -254,6 +319,7 @@ export const apiCreateQuestion = (
createdQuestion,
isBasedOnExistingQuestion(getState()),
);
+ trackQuestionTimelineEventsSaved(createdQuestion);
// Saving a card, locks in the current display as though it had been
// selected in the UI.
@@ -301,7 +367,17 @@ export const apiUpdateQuestion = (
rerunQuery = rerunQuery ?? isResultDirty ?? false;
}
- const submittableQuestion = getSubmittableQuestion(getState(), question);
+ let submittableQuestion = getSubmittableQuestion(getState(), question);
+ if (
+ needsTimelineEventsRecording(submittableQuestion) &&
+ !isLegacyTimelineEventsSource(originalQuestion)
+ ) {
+ submittableQuestion = await recordCollectionTimelineEvents(
+ submittableQuestion,
+ dispatch,
+ getState,
+ );
+ }
// When viewing a dataset, its dataset_query is swapped with a clean query using the dataset as a source table
// (it's necessary for datasets to behave like tables opened in simple mode)
@@ -318,6 +394,8 @@ export const apiUpdateQuestion = (
},
);
+ trackQuestionTimelineEventsSaved(updatedQuestion, originalQuestion);
+
// invalidate question notifications
// (some of the old alerts might be removed during update)
dispatch(invalidateNotificationsApiCache());
@@ -386,6 +464,7 @@ async function reduxCreateQuestion(
createQuestionCard({
...question.card(),
dashboard_tab_id: options?.dashboardTabId,
+ source_card_id: options?.sourceCardId,
...(size && { size: { size_x: size.width, size_y: size.height } }),
}),
)) as Card;
diff --git a/frontend/src/metabase/query_builder/actions/timelines.ts b/frontend/src/metabase/query_builder/actions/timelines.ts
index 46b56da1c40..19cab918eb8 100644
--- a/frontend/src/metabase/query_builder/actions/timelines.ts
+++ b/frontend/src/metabase/query_builder/actions/timelines.ts
@@ -1,28 +1,47 @@
import { createAction } from "redux-actions";
import type { Dispatch, GetState } from "metabase/redux/store";
-import type { CollectionId, Timeline } from "metabase-types/api";
+import { getTransformedTimelines } from "metabase/timelines/panel/selectors";
+import { isSameTimelineEventsVisibility } from "metabase/visualizations/lib/timeline-events-visibility";
+import type { TimelineEventsVisibilityUpdate } from "metabase/visualizations/types";
+import type { TimelineEventId } from "metabase-types/api";
+import {
+ type QuestionEventsPanelLocation,
+ trackQuestionEventsPanelOpened,
+} from "../analytics";
import {
DESELECT_TIMELINE_EVENTS,
- HIDE_TIMELINE_EVENTS,
SELECT_TIMELINE_EVENTS,
- SHOW_TIMELINE_EVENTS,
+ onOpenTimelines,
} from "../store/actions";
-import { getFetchedTimelines } from "../store/selectors";
+import { getTimelineEventsVisibility, getUiControls } from "../store/selectors";
+
+import { onUpdateVisualizationSettings } from "./visualization-settings";
export const selectTimelineEvents = createAction(SELECT_TIMELINE_EVENTS);
export const deselectTimelineEvents = createAction(DESELECT_TIMELINE_EVENTS);
-export const hideTimelineEvents = createAction(HIDE_TIMELINE_EVENTS);
-export const showTimelineEvents = createAction(SHOW_TIMELINE_EVENTS);
-export const showTimelinesForCollection =
- (collectionId?: CollectionId | null) =>
+export const openTimelines =
+ (location: QuestionEventsPanelLocation, eventIds?: TimelineEventId[]) =>
+ (dispatch: Dispatch, getState: GetState) => {
+ if (!getUiControls(getState()).isShowingTimelineSidebar) {
+ trackQuestionEventsPanelOpened(location);
+ }
+ dispatch(onOpenTimelines(eventIds));
+ };
+
+export const openTimelinesFromChart = (eventIds?: TimelineEventId[]) =>
+ openTimelines("chart", eventIds);
+
+export const updateTimelineEventsVisibility =
+ (update: TimelineEventsVisibilityUpdate) =>
(dispatch: Dispatch, getState: GetState) => {
- const fetchedTimelines: Timeline[] = getFetchedTimelines(getState());
- const collectionTimelines = collectionId
- ? fetchedTimelines.filter((t) => t.collection_id === collectionId)
- : fetchedTimelines.filter((t) => t.collection_id == null);
+ const state = getState();
+ const visibility = getTimelineEventsVisibility(state);
+ const nextVisibility = update(visibility, getTransformedTimelines(state));
- dispatch(showTimelineEvents(collectionTimelines.flatMap((t) => t.events)));
+ if (!isSameTimelineEventsVisibility(visibility, nextVisibility)) {
+ dispatch(onUpdateVisualizationSettings(nextVisibility));
+ }
};
diff --git a/frontend/src/metabase/query_builder/analytics.ts b/frontend/src/metabase/query_builder/analytics.ts
index 6396c5a8375..2d934fd187f 100644
--- a/frontend/src/metabase/query_builder/analytics.ts
+++ b/frontend/src/metabase/query_builder/analytics.ts
@@ -1,4 +1,8 @@
import { trackSchemaEvent, trackSimpleEvent } from "metabase/analytics";
+import {
+ getRecordedTimelineEventsVisibility,
+ isSameTimelineEventsVisibility,
+} from "metabase/visualizations/lib/timeline-events-visibility";
import type Question from "metabase-lib/v1/Question";
import type { Card, VisualizationDisplay } from "metabase-types/api";
@@ -53,3 +57,35 @@ export const trackCardBookmarkAdded = (card: Card) => {
triggered_from: "qb_action_panel",
});
};
+
+export type QuestionEventsPanelLocation = "footer" | "chart";
+
+export const trackQuestionEventsPanelOpened = (
+ location: QuestionEventsPanelLocation,
+) => {
+ trackSimpleEvent({
+ event: "question_events_panel_opened",
+ triggered_from: location,
+ });
+};
+
+export const trackQuestionTimelineEventsSaved = (
+ question: Question,
+ originalQuestion?: Question,
+) => {
+ const visibility = getRecordedTimelineEventsVisibility(question.settings());
+ const originalVisibility = getRecordedTimelineEventsVisibility(
+ originalQuestion?.settings(),
+ );
+ const isVisibilityChanged =
+ visibility != null &&
+ (originalVisibility == null ||
+ !isSameTimelineEventsVisibility(visibility, originalVisibility));
+
+ if (isVisibilityChanged) {
+ trackSimpleEvent({
+ event: "question_timeline_events_saved",
+ target_id: question.id(),
+ });
+ }
+};
diff --git a/frontend/src/metabase/query_builder/components/QueryModals/QueryModals.tsx b/frontend/src/metabase/query_builder/components/QueryModals/QueryModals.tsx
index a7cddf1b8b4..0afafc311af 100644
--- a/frontend/src/metabase/query_builder/components/QueryModals/QueryModals.tsx
+++ b/frontend/src/metabase/query_builder/components/QueryModals/QueryModals.tsx
@@ -16,15 +16,12 @@ import { MoveCardModal } from "metabase/questions/components/MoveCardModal";
import { useDispatch, useSelector } from "metabase/redux";
import type { QueryBuilderMode, QueryModalType } 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 type Question from "metabase-lib/v1/Question";
import type { Card, DashboardTabId } from "metabase-types/api";
-import { setArchivedQuestion } from "../../actions";
+import { type OnCreateOptions, setArchivedQuestion } from "../../actions";
import { updateUrl } from "../../actions/url";
import {
getQuestionWithoutComposing,
@@ -34,11 +31,8 @@ import { ImpossibleToCreateModelModal } from "../ImpossibleToCreateModelModal";
import { NewDatasetModal } from "../NewDatasetModal";
import { PreviewQueryModal } from "../view/PreviewQueryModal";
-type OnCreateOptions = { dashboardTabId?: DashboardTabId | undefined };
-
interface QueryModalsProps {
modal: QueryModalType;
- modalContext: number;
question: Question;
setQueryBuilderMode: (mode: QueryBuilderMode) => void;
originalQuestion: Question;
@@ -60,7 +54,6 @@ export function QueryModals({
onSave,
onCreate,
modal,
- modalContext,
card,
question,
onCloseModal,
@@ -273,6 +266,10 @@ export function QueryModals({
const object = await onCreate(question, {
dashboardTabId: formValues.dashboard_tab_id,
+ sourceCardId: underlyingQuestion.isSaved()
+ ? underlyingQuestion.id()
+ : undefined,
+ sourceQuestion: underlyingQuestion,
});
return object.card();
@@ -305,50 +302,6 @@ export function QueryModals({
<ImpossibleToCreateModelModal onClose={onCloseModal} />
</Modal>
);
- case MODAL_TYPES.NEW_EVENT:
- return (
- <Modal
- opened
- onClose={onCloseModal}
- size="lg"
- withCloseButton={false}
- padding={0}
- >
- <NewEventModal
- cardId={question.id()}
- collectionId={question.collectionId()}
- onClose={onCloseModal}
- />
- </Modal>
- );
- case MODAL_TYPES.EDIT_EVENT:
- return (
- <Modal
- opened
- onClose={onCloseModal}
- size="lg"
- withCloseButton={false}
- padding={0}
- >
- <EditEventModal eventId={modalContext} onClose={onCloseModal} />
- </Modal>
- );
- case MODAL_TYPES.MOVE_EVENT:
- return (
- <Modal
- opened
- onClose={onCloseModal}
- size="lg"
- withCloseButton={false}
- padding={0}
- >
- <MoveEventModal
- eventId={modalContext}
- collectionId={question.collectionId()}
- onClose={onCloseModal}
- />
- </Modal>
- );
case MODAL_TYPES.PREVIEW_QUERY:
return <PreviewQueryModal onClose={onCloseModal} />;
case MODAL_TYPES.QUESTION_EMBED:
diff --git a/frontend/src/metabase/query_builder/components/view/QuestionTimelineWidget/QuestionTimelineWidget.tsx b/frontend/src/metabase/query_builder/components/view/QuestionTimelineWidget/QuestionTimelineWidget.tsx
index 896b19d7801..ce783e7b12f 100644
--- a/frontend/src/metabase/query_builder/components/view/QuestionTimelineWidget/QuestionTimelineWidget.tsx
+++ b/frontend/src/metabase/query_builder/components/view/QuestionTimelineWidget/QuestionTimelineWidget.tsx
@@ -2,7 +2,8 @@ import { t } from "ttag";
import { useDispatch, useSelector } from "metabase/redux";
-import { onCloseTimelines, onOpenTimelines } from "../../../store/actions";
+import { openTimelines } from "../../../actions/timelines";
+import { onCloseTimelines } from "../../../store/actions";
import { getUiControls } from "../../../store/selectors";
import { ViewFooterButton } from "../ViewFooterButton";
@@ -16,7 +17,7 @@ export const QuestionTimelineWidget = ({
const { isShowingTimelineSidebar } = useSelector(getUiControls);
const dispatch = useDispatch();
- const handleOpenTimelines = () => dispatch(onOpenTimelines());
+ const handleOpenTimelines = () => dispatch(openTimelines("footer"));
const handleCloseTimelines = () => dispatch(onCloseTimelines());
function handleClick(isShowingTimelineSidebar: boolean) {
diff --git a/frontend/src/metabase/query_builder/components/view/QuestionTimelineWidget/QuestionTimelineWidget.unit.spec.tsx b/frontend/src/metabase/query_builder/components/view/QuestionTimelineWidget/QuestionTimelineWidget.unit.spec.tsx
new file mode 100644
index 00000000000..634d00b9751
--- /dev/null
+++ b/frontend/src/metabase/query_builder/components/view/QuestionTimelineWidget/QuestionTimelineWidget.unit.spec.tsx
@@ -0,0 +1,48 @@
+import userEvent from "@testing-library/user-event";
+
+import {
+ createMockQueryBuilderState,
+ createMockQueryBuilderUIControlsState,
+ createMockState,
+} from "__support__/state";
+import { getIcon, renderWithProviders } from "__support__/ui";
+
+import { QuestionTimelineWidget } from "./QuestionTimelineWidget";
+
+const { trackSimpleEvent } = jest.requireMock("metabase/analytics");
+
+const setup = ({ isShowingTimelineSidebar = false } = {}) =>
+ renderWithProviders(<QuestionTimelineWidget />, {
+ storeInitialState: createMockState({
+ qb: createMockQueryBuilderState({
+ uiControls: createMockQueryBuilderUIControlsState({
+ isShowingTimelineSidebar,
+ }),
+ }),
+ }),
+ });
+
+describe("QuestionTimelineWidget", () => {
+ beforeEach(() => {
+ trackSimpleEvent.mockClear();
+ });
+
+ it("tracks opening the events panel", async () => {
+ setup();
+
+ await userEvent.click(getIcon("calendar"));
+
+ expect(trackSimpleEvent).toHaveBeenCalledWith({
+ event: "question_events_panel_opened",
+ triggered_from: "footer",
+ });
+ });
+
+ it("does not track closing the events panel", async () => {
+ setup({ isShowingTimelineSidebar: true });
+
+ await userEvent.click(getIcon("calendar"));
+
+ expect(trackSimpleEvent).not.toHaveBeenCalled();
+ });
+});
diff --git a/frontend/src/metabase/query_builder/components/view/QuestionTimelineWidget/analytics.ts b/frontend/src/metabase/query_builder/components/view/QuestionTimelineWidget/analytics.ts
deleted file mode 100644
index 94cda74b64c..00000000000
--- a/frontend/src/metabase/query_builder/components/view/QuestionTimelineWidget/analytics.ts
+++ /dev/null
@@ -1,7 +0,0 @@
-import { trackSimpleEvent } from "metabase/analytics";
-
-export const trackEventsClicked = () =>
- trackSimpleEvent({
- event: "events_clicked",
- triggered_from: "chart",
- });
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.tsx
index 466f9fdba2b..622107bfadf 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
@@ -14,8 +14,6 @@ import type {
RowValue,
TemplateTag,
TemplateTagId,
- Timeline,
- TimelineEvent,
} from "metabase-types/api";
import { setTemplateTagConfig } from "../../../../actions";
@@ -26,8 +24,6 @@ import { TimelineSidebar } from "../../sidebars/TimelineSidebar";
interface NativeQueryRightSidebarProps {
question: Question;
- timelineEvents: TimelineEvent[];
- timelines: Timeline[];
toggleTemplateTagsEditor: () => void;
toggleDataReference: () => void;
toggleSnippetSidebar: () => void;
@@ -36,11 +32,6 @@ interface NativeQueryRightSidebarProps {
insertSnippet: (snippet: NativeQuerySnippet) => void;
snippetCollectionId: CollectionId | null;
setSnippetCollectionId?: (id: CollectionId | null) => void;
- showTimelineEvents: (timelineEvents: TimelineEvent[]) => void;
- hideTimelineEvents: (timelineEvents: TimelineEvent[]) => void;
- selectTimelineEvents: (timelineEvents: TimelineEvent[]) => void;
- deselectTimelineEvents: () => void;
- onCloseTimelines: () => void;
onSave: (question: Question) => Promise<void>;
isShowingTemplateTagsEditor: boolean;
isShowingDataReference: boolean;
@@ -48,8 +39,6 @@ interface NativeQueryRightSidebarProps {
isShowingTimelineSidebar: boolean;
isShowingQuestionInfoSidebar: boolean;
isShowingQuestionSettingsSidebar: boolean;
- visibleTimelineEventIds: number[];
- selectedTimelineEventIds: number[];
setDatasetQuery: (query: NativeDatasetQuery) => void;
setTemplateTag: (tag: TemplateTag) => void;
setParameterValue: (tagId: TemplateTagId, value: RowValue) => void;
@@ -70,11 +59,6 @@ export const NativeQueryRightSidebar = (
toggleTemplateTagsEditor,
toggleDataReference,
toggleSnippetSidebar,
- showTimelineEvents,
- hideTimelineEvents,
- selectTimelineEvents,
- deselectTimelineEvents,
- onCloseTimelines,
onSave,
isShowingTemplateTagsEditor,
isShowingDataReference,
@@ -119,17 +103,7 @@ export const NativeQueryRightSidebar = (
.with({ isShowingSnippetSidebar: true }, () => (
<SnippetSidebar {...props} onClose={toggleSnippetSidebar} />
))
- .with({ isShowingTimelineSidebar: true }, () => (
- <TimelineSidebar
- {...props}
- collectionId={question.collectionId()}
- onShowTimelineEvents={showTimelineEvents}
- onHideTimelineEvents={hideTimelineEvents}
- onSelectTimelineEvents={selectTimelineEvents}
- onDeselectTimelineEvents={deselectTimelineEvents}
- onClose={onCloseTimelines}
- />
- ))
+ .with({ isShowingTimelineSidebar: true }, () => <TimelineSidebar />)
.with({ isShowingQuestionInfoSidebar: true }, () => (
<QuestionInfoSidebar question={question} onSave={onSave} />
))
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.tsx
index 0da5926a668..45b583ae01d 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
@@ -1,9 +1,6 @@
import { match } from "ts-pattern";
-import type { Dayjs } from "metabase/dayjs";
-import type { QueryModalType } from "metabase/redux/store";
import type Question from "metabase-lib/v1/Question";
-import type { Timeline, TimelineEvent } from "metabase-types/api";
import { QuestionInfoSidebar } from "../../sidebars/QuestionInfoSidebar";
import { QuestionSettingsSidebar } from "../../sidebars/QuestionSettingsSidebar";
@@ -11,45 +8,25 @@ import { SummarizeSidebar } from "../../sidebars/SummarizeSidebar";
import { TimelineSidebar } from "../../sidebars/TimelineSidebar";
interface StructuredQueryRightSidebarProps {
- deselectTimelineEvents: () => void;
- hideTimelineEvents: (timelineEvents: TimelineEvent[]) => void;
isShowingQuestionInfoSidebar: boolean;
isShowingQuestionSettingsSidebar: boolean;
isShowingSummarySidebar: boolean;
isShowingTimelineSidebar: boolean;
onCloseSummary: () => void;
- onCloseTimelines: () => void;
- onOpenModal: (modal: QueryModalType, modalContext?: unknown) => void;
onSave: (question: Question) => Promise<void>;
question: Question;
- selectTimelineEvents: (timelineEvents: TimelineEvent[]) => void;
- selectedTimelineEventIds: number[];
- showTimelineEvents: (timelineEvents: TimelineEvent[]) => void;
- timelines: Timeline[];
updateQuestion: (question: Question, opts?: { run?: boolean }) => void;
- visibleTimelineEventIds: number[];
- xDomain?: [Dayjs, Dayjs];
}
export const StructuredQueryRightSidebar = ({
- deselectTimelineEvents,
- hideTimelineEvents,
isShowingQuestionInfoSidebar,
isShowingQuestionSettingsSidebar,
isShowingSummarySidebar,
isShowingTimelineSidebar,
onCloseSummary,
- onCloseTimelines,
- onOpenModal,
onSave,
question,
- selectTimelineEvents,
- selectedTimelineEventIds,
- showTimelineEvents,
- timelines,
updateQuestion,
- visibleTimelineEventIds,
- xDomain,
}: StructuredQueryRightSidebarProps) => {
return match({
isSaved: question.isSaved(),
@@ -76,21 +53,7 @@ export const StructuredQueryRightSidebar = ({
/>
),
)
- .with({ isShowingTimelineSidebar: true }, () => (
- <TimelineSidebar
- collectionId={question.collectionId()}
- timelines={timelines}
- visibleTimelineEventIds={visibleTimelineEventIds}
- selectedTimelineEventIds={selectedTimelineEventIds}
- xDomain={xDomain}
- onShowTimelineEvents={showTimelineEvents}
- onHideTimelineEvents={hideTimelineEvents}
- onSelectTimelineEvents={selectTimelineEvents}
- onDeselectTimelineEvents={deselectTimelineEvents}
- onOpenModal={onOpenModal}
- onClose={onCloseTimelines}
- />
- ))
+ .with({ isShowingTimelineSidebar: true }, () => <TimelineSidebar />)
.with(
{
isSaved: true,
diff --git a/frontend/src/metabase/query_builder/components/view/View/View/View.tsx b/frontend/src/metabase/query_builder/components/view/View/View/View.tsx
index ce5186036be..ec0203b42da 100644
--- a/frontend/src/metabase/query_builder/components/view/View/View/View.tsx
+++ b/frontend/src/metabase/query_builder/components/view/View/View/View.tsx
@@ -77,7 +77,6 @@ type ViewProps = Omit<
onDismissToast: () => void;
onConfirmToast: () => void;
modal: QueryModalType;
- modalContext: number;
card: Card;
originalQuestion: Question;
reportTimezone: string;
@@ -157,7 +156,6 @@ const ViewInner = forwardRef<HTMLDivElement, ViewInnerProps>(
onSave,
onChangeLocation,
modal,
- modalContext,
card,
onCloseModal,
onOpenModal,
@@ -228,7 +226,6 @@ const ViewInner = forwardRef<HTMLDivElement, ViewInnerProps>(
onSave={onSave}
onCreate={onCreate}
modal={modal}
- modalContext={modalContext}
card={card}
question={question}
onCloseModal={onCloseModal}
@@ -324,7 +321,6 @@ const ViewInner = forwardRef<HTMLDivElement, ViewInnerProps>(
onSave={onSave}
onCreate={onCreate}
modal={modal}
- modalContext={modalContext}
card={card}
question={question}
onCloseModal={onCloseModal}
diff --git a/frontend/src/metabase/query_builder/components/view/View/ViewRightSidebarContainer/ViewRightSidebarContainer.tsx b/frontend/src/metabase/query_builder/components/view/View/ViewRightSidebarContainer/ViewRightSidebarContainer.tsx
index 3e127a0f171..6458f08707e 100644
--- a/frontend/src/metabase/query_builder/components/view/View/ViewRightSidebarContainer/ViewRightSidebarContainer.tsx
+++ b/frontend/src/metabase/query_builder/components/view/View/ViewRightSidebarContainer/ViewRightSidebarContainer.tsx
@@ -10,11 +10,7 @@ type ViewRightSidebarContainerProps = ComponentProps<
> &
Pick<
ComponentProps<typeof StructuredQueryRightSidebar>,
- | "isShowingSummarySidebar"
- | "onCloseSummary"
- | "onOpenModal"
- | "updateQuestion"
- | "xDomain"
+ "isShowingSummarySidebar" | "onCloseSummary" | "updateQuestion"
>;
export const ViewRightSidebarContainer = (
@@ -22,23 +18,13 @@ export const ViewRightSidebarContainer = (
) => {
const {
question,
- deselectTimelineEvents,
- hideTimelineEvents,
isShowingQuestionInfoSidebar,
isShowingQuestionSettingsSidebar,
isShowingSummarySidebar,
isShowingTimelineSidebar,
onCloseSummary,
- onCloseTimelines,
- onOpenModal,
onSave,
- selectTimelineEvents,
- selectedTimelineEventIds,
- showTimelineEvents,
- timelines,
updateQuestion,
- visibleTimelineEventIds,
- xDomain,
} = props;
const { isNative } = Lib.queryDisplayInfo(question.query());
@@ -47,24 +33,14 @@ export const ViewRightSidebarContainer = (
<NativeQueryRightSidebar {...props} />
) : (
<StructuredQueryRightSidebar
- deselectTimelineEvents={deselectTimelineEvents}
- hideTimelineEvents={hideTimelineEvents}
isShowingQuestionInfoSidebar={isShowingQuestionInfoSidebar}
isShowingQuestionSettingsSidebar={isShowingQuestionSettingsSidebar}
isShowingSummarySidebar={isShowingSummarySidebar}
isShowingTimelineSidebar={isShowingTimelineSidebar}
onCloseSummary={onCloseSummary}
- onCloseTimelines={onCloseTimelines}
- onOpenModal={onOpenModal}
onSave={onSave}
question={question}
- selectTimelineEvents={selectTimelineEvents}
- selectedTimelineEventIds={selectedTimelineEventIds}
- showTimelineEvents={showTimelineEvents}
- timelines={timelines}
updateQuestion={updateQuestion}
- visibleTimelineEventIds={visibleTimelineEventIds}
- xDomain={xDomain}
/>
);
};
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.tsx
index f3a9e3585f2..983179f66c5 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,59 +1,76 @@
-import { useCallback } from "react";
+import { useCallback, useMemo } from "react";
+import { useListTimelinesQuery } from "metabase/api";
import { useDispatch, useSelector } from "metabase/redux";
-import {
- TimelineSidebar as SharedTimelineSidebar,
- type TimelineSidebarProps as SharedTimelineSidebarProps,
-} from "metabase/timelines/questions/components/TimelineSidebar";
+import { TimelineSidebar as SharedTimelineSidebar } from "metabase/timelines/panel/components/TimelineSidebar";
+import { getTransformedTimelines } from "metabase/timelines/panel/selectors";
+import type { TimelineEventsVisibilityUpdate } from "metabase/visualizations/types";
+import type { TimelineEvent } from "metabase-types/api";
-import { onOpenTimelines } from "../../../../store/actions";
import {
- getTimeseriesDataInterval,
- getUiControls,
+ deselectTimelineEvents,
+ selectTimelineEvents,
+ updateTimelineEventsVisibility,
+} from "../../../../actions/timelines";
+import { onCloseTimelines, onOpenTimelines } from "../../../../store/actions";
+import {
+ getFocusedTimelineEventIds,
+ getQuestion,
+ getSelectedTimelineEventIds,
+ getTimeseriesXAxis,
+ getVisibleTimelineEventIds,
} from "../../../../store/selectors";
-export type TimelineSidebarProps = Omit<
- SharedTimelineSidebarProps,
- "focusedTimelineEventIds" | "dataInterval" | "onShowAllEvents"
->;
-
-export const TimelineSidebar = ({
- collectionId,
- timelines,
- visibleTimelineEventIds,
- selectedTimelineEventIds,
- xDomain,
- onShowTimelineEvents,
- onHideTimelineEvents,
- onSelectTimelineEvents,
- onDeselectTimelineEvents,
- onOpenModal,
- onClose,
-}: TimelineSidebarProps) => {
+export const TimelineSidebar = () => {
const dispatch = useDispatch();
- const { focusedTimelineEventIds } = useSelector(getUiControls);
- const dataInterval = useSelector(getTimeseriesDataInterval);
+ const collectionId = useSelector((state) =>
+ getQuestion(state)?.collectionId(),
+ );
+ const timelines = useSelector(getTransformedTimelines);
+ const visibleEventIds = useSelector(getVisibleTimelineEventIds);
+ const selectedEventIds = useSelector(getSelectedTimelineEventIds);
+ const focusedEventIds = useSelector(getFocusedTimelineEventIds);
+ const xAxis = useSelector(getTimeseriesXAxis);
+ const xAxes = useMemo(() => (xAxis ? [xAxis] : null), [xAxis]);
+ const { isLoading, error } = useListTimelinesQuery({ include: "events" });
- const handleShowAllEvents = useCallback(() => {
- dispatch(onOpenTimelines());
- }, [dispatch]);
+ const handleUpdateVisibility = useCallback(
+ (update: TimelineEventsVisibilityUpdate) =>
+ dispatch(updateTimelineEventsVisibility(update)),
+ [dispatch],
+ );
+ const handleSelectEvents = useCallback(
+ (events: TimelineEvent[]) => dispatch(selectTimelineEvents(events)),
+ [dispatch],
+ );
+ const handleDeselectEvents = useCallback(
+ () => dispatch(deselectTimelineEvents()),
+ [dispatch],
+ );
+ const handleShowAllEvents = useCallback(
+ () => dispatch(onOpenTimelines()),
+ [dispatch],
+ );
+ const handleClose = useCallback(
+ () => dispatch(onCloseTimelines()),
+ [dispatch],
+ );
return (
<SharedTimelineSidebar
collectionId={collectionId}
timelines={timelines}
- visibleTimelineEventIds={visibleTimelineEventIds}
- selectedTimelineEventIds={selectedTimelineEventIds}
- focusedTimelineEventIds={focusedTimelineEventIds}
- dataInterval={dataInterval}
- xDomain={xDomain}
- onShowTimelineEvents={onShowTimelineEvents}
- onHideTimelineEvents={onHideTimelineEvents}
- onSelectTimelineEvents={onSelectTimelineEvents}
- onDeselectTimelineEvents={onDeselectTimelineEvents}
+ visibleEventIds={visibleEventIds}
+ selectedEventIds={selectedEventIds}
+ focusedEventIds={focusedEventIds}
+ xAxes={xAxes}
+ isLoading={isLoading}
+ error={error}
+ onUpdateVisibility={handleUpdateVisibility}
+ onSelectEvents={handleSelectEvents}
+ onDeselectEvents={handleDeselectEvents}
onShowAllEvents={handleShowAllEvents}
- onOpenModal={onOpenModal}
- onClose={onClose}
+ onClose={handleClose}
/>
);
};
diff --git a/frontend/src/metabase/query_builder/containers/QueryBuilder.duplicate.unit.spec.tsx b/frontend/src/metabase/query_builder/containers/QueryBuilder.duplicate.unit.spec.tsx
new file mode 100644
index 00000000000..4f07fb9fc12
--- /dev/null
+++ b/frontend/src/metabase/query_builder/containers/QueryBuilder.duplicate.unit.spec.tsx
@@ -0,0 +1,72 @@
+import userEvent from "@testing-library/user-event";
+import fetchMock from "fetch-mock";
+
+import { setupListNotificationEndpoints } from "__support__/server-mocks/notification";
+import { screen, waitFor, within } from "__support__/ui";
+import { checkNotNull } from "metabase/utils/types";
+import { registerVisualizations } from "metabase/visualizations/register";
+import type { CreateCardRequest } from "metabase-types/api";
+
+import {
+ TEST_STRUCTURED_CARD,
+ setup,
+ triggerVisualizationQueryChange,
+ waitForSaveToBeEnabled,
+} from "./test-utils";
+
+registerVisualizations();
+
+const setupQuestion = async () => {
+ setupListNotificationEndpoints({ card_id: TEST_STRUCTURED_CARD.id }, []);
+ await setup({ card: TEST_STRUCTURED_CARD });
+};
+
+const getCreatedCard = (): CreateCardRequest => {
+ const body = checkNotNull(
+ fetchMock.callHistory.lastCall("path:/api/card", { method: "POST" })
+ ?.options.body,
+ );
+ return JSON.parse(body.toString());
+};
+
+const duplicateQuestion = async () => {
+ await userEvent.click(screen.getByLabelText("Move, trash, and more…"));
+ await userEvent.click(
+ await screen.findByRole("menuitem", { name: /Duplicate/ }),
+ );
+
+ const modal = await screen.findByRole("dialog", { name: /Duplicate/ });
+ await userEvent.click(
+ within(modal).getByRole("button", { name: "Duplicate" }),
+ );
+ await waitFor(() => expect(modal).not.toBeInTheDocument());
+};
+
+const saveAsNewQuestion = async () => {
+ await waitForSaveToBeEnabled();
+ await userEvent.click(screen.getByText("Save"));
+
+ const modal = await screen.findByTestId("save-question-modal");
+ await userEvent.click(within(modal).getByText("Save as new question"));
+ await userEvent.click(within(modal).getByText("Save"));
+ await waitFor(() => expect(modal).not.toBeInTheDocument());
+};
+
+describe("QueryBuilder > saving a question based on another one", () => {
+ it("marks a duplicate as a copy of the question it came from", async () => {
+ await setupQuestion();
+
+ await duplicateQuestion();
+
+ expect(getCreatedCard().source_card_id).toBe(TEST_STRUCTURED_CARD.id);
+ });
+
+ it("marks an edited question saved as a new one as a copy of the original", async () => {
+ await setupQuestion();
+
+ await triggerVisualizationQueryChange();
+ await saveAsNewQuestion();
+
+ expect(getCreatedCard().source_card_id).toBe(TEST_STRUCTURED_CARD.id);
+ });
+});
diff --git a/frontend/src/metabase/query_builder/containers/QueryBuilder.timeline-events.unit.spec.tsx b/frontend/src/metabase/query_builder/containers/QueryBuilder.timeline-events.unit.spec.tsx
index a5079890e5d..2c16c48f07d 100644
--- a/frontend/src/metabase/query_builder/containers/QueryBuilder.timeline-events.unit.spec.tsx
+++ b/frontend/src/metabase/query_builder/containers/QueryBuilder.timeline-events.unit.spec.tsx
@@ -1,74 +1,652 @@
-import { screen, waitFor } from "__support__/ui";
+import userEvent from "@testing-library/user-event";
+import fetchMock from "fetch-mock";
+
+import {
+ setupCardCreateEndpoint,
+ setupCardEndpoints,
+} from "__support__/server-mocks";
+import { getTimelineEventCheckbox } from "__support__/timelines";
+import { act, waitFor } from "__support__/ui";
+import { getFetchedTimelines } from "metabase/timelines/panel/selectors";
+import { checkNotNull } from "metabase/utils/types";
+import {
+ hideTimelines,
+ showTimelineEvents,
+ showTimelines,
+} from "metabase/visualizations/lib/timeline-events-visibility";
import { registerVisualizations } from "metabase/visualizations/register";
+import type { TimelineEventsVisibilityUpdate } from "metabase/visualizations/types";
+import type {
+ Card,
+ CardId,
+ TimelineEventsVisibility,
+} from "metabase-types/api";
import {
+ createMockCard,
+ createMockCardQueryMetadata,
+ createMockCollection,
createMockTimeline,
createMockTimelineEvent,
+ createMockUnsavedCard,
} from "metabase-types/api/mocks";
+import { apiCreateQuestion, updateQuestion } from "../actions";
import {
- getFetchedTimelines,
+ openTimelines,
+ updateTimelineEventsVisibility,
+} from "../actions/timelines";
+import { onOpenTimelines } from "../store/actions";
+import {
+ getIsDirty,
+ getOriginalQuestion,
+ getQuestion,
+ getSubmittableQuestion,
getVisibleTimelineEventIds,
} from "../store/selectors";
-import { TEST_TIME_SERIES_WITH_DATE_BREAKOUT_CARD, setup } from "./test-utils";
+import {
+ TEST_TIME_SERIES_WITH_DATE_BREAKOUT_CARD,
+ saveQuestion,
+ setup,
+ triggerVisualizationQueryChange,
+} from "./test-utils";
registerVisualizations();
-const EVENT_ID = 99;
+const { trackSimpleEvent } = jest.requireMock("metabase/analytics");
+
+const CARD = createMockCard({
+ ...TEST_TIME_SERIES_WITH_DATE_BREAKOUT_CARD,
+ display: "line",
+ visualization_settings: { "graph.show_values": true },
+});
+
+const RC1 = createMockTimelineEvent({
+ id: 99,
+ timeline_id: 1,
+ name: "RC1",
+ timestamp: "2025-06-01T00:00:00Z",
+});
+const RC2 = createMockTimelineEvent({
+ id: 98,
+ timeline_id: 1,
+ name: "RC2",
+ timestamp: "2025-06-02T00:00:00Z",
+});
-const CARD = TEST_TIME_SERIES_WITH_DATE_BREAKOUT_CARD;
+const EVENTS_OFF: TimelineEventsVisibility = {
+ "timeline.selected_timeline_ids": [],
+ "timeline.excluded_timeline_event_ids": [],
+};
const TIMELINE = createMockTimeline({
id: 1,
- // Match the question's collection so showTimelinesForCollection selects it.
collection_id: CARD.collection_id,
- events: [
- createMockTimelineEvent({
- id: EVENT_ID,
- name: "RC1",
- timestamp: "2025-06-01T00:00:00Z",
- }),
- ],
+ events: [RC1, RC2],
});
-describe("QueryBuilder > timeline events (GHY-3839)", () => {
- it("shows timeline events when the timelines request resolves after the question loads", async () => {
- // Delay /api/timeline so it resolves *after* the question and bookmarks have
- // loaded — i.e. after the effect that calls showTimelinesForCollection has
- // already run once without them. This reproduces the load-order race: if the
- // effect doesn't re-run when the timelines arrive, the event is never added
- // to the visible set and no marker ever renders on the chart.
+type Store = Awaited<ReturnType<typeof setup>>["store"];
+
+const getVisibleEventIds = (store: Store) =>
+ getVisibleTimelineEventIds(store.getState());
+
+const updateVisibility = (
+ store: Store,
+ update: TimelineEventsVisibilityUpdate,
+) =>
+ act(async () => {
+ store.dispatch(updateTimelineEventsVisibility(update));
+ });
+
+const getSavedSettings = () => {
+ const body = checkNotNull(
+ fetchMock.callHistory.lastCall(`path:/api/card/${CARD.id}`, {
+ method: "PUT",
+ })?.options.body,
+ );
+ const card: Card = JSON.parse(body.toString());
+ return card.visualization_settings;
+};
+
+const setupWithTimelines = async (visibility?: TimelineEventsVisibility) => {
+ const { store } = await setup({
+ card: createMockCard({
+ ...CARD,
+ visualization_settings: { ...CARD.visualization_settings, ...visibility },
+ }),
+ timelines: [TIMELINE],
+ });
+ await waitFor(() => {
+ expect(getFetchedTimelines(store.getState())).toHaveLength(1);
+ });
+ return store;
+};
+
+const setupAdHocWithTimelines = async () => {
+ const { store } = await setup({
+ card: createMockUnsavedCard({
+ dataset_query: CARD.dataset_query,
+ display: "line",
+ }),
+ timelines: [createMockTimeline({ ...TIMELINE, collection_id: null })],
+ });
+ await waitFor(() => {
+ expect(getVisibleEventIds(store)).toEqual([RC1.id, RC2.id]);
+ });
+ return store;
+};
+
+const DESTINATION_COLLECTION = createMockCollection({ id: 123 });
+
+const setupNewQuestion = async ({
+ originalCardId,
+ ...options
+}: Pick<Parameters<typeof setup>[0], "timelines" | "timelinesResponse"> & {
+ originalCardId?: CardId;
+}) => {
+ setupCardCreateEndpoint();
+ fetchMock.get(
+ /\/api\/card\/\d+\/query_metadata/,
+ createMockCardQueryMetadata(),
+ );
+ const { store } = await setup({
+ card: createMockUnsavedCard({
+ dataset_query: CARD.dataset_query,
+ display: "line",
+ original_card_id: originalCardId,
+ }),
+ ...options,
+ });
+ return store;
+};
+
+const getCreatedCard = (): Card => {
+ const body = checkNotNull(
+ fetchMock.callHistory.lastCall("path:/api/card", { method: "POST" })
+ ?.options.body,
+ );
+ return JSON.parse(body.toString());
+};
+
+const saveNewQuestion = async (
+ options: Pick<Parameters<typeof setup>[0], "timelines" | "timelinesResponse">,
+) => {
+ const store = await setupNewQuestion(options);
+ const question = checkNotNull(getQuestion(store.getState())).setCollectionId(
+ DESTINATION_COLLECTION.id,
+ );
+ await act(async () => {
+ await store.dispatch(apiCreateQuestion(question));
+ });
+ return getCreatedCard();
+};
+
+describe("QueryBuilder > timeline events", () => {
+ beforeEach(() => {
+ trackSimpleEvent.mockClear();
+ });
+
+ it("shows no events for a saved question that never recorded any", async () => {
+ const store = await setupWithTimelines();
+
+ expect(getVisibleEventIds(store)).toEqual([]);
+ });
+
+ it("shows no events after editing the query of a saved question that never recorded any", async () => {
+ const store = await setupWithTimelines();
+
+ await triggerVisualizationQueryChange();
+
+ await waitFor(() => {
+ expect(getIsDirty(store.getState())).toBe(true);
+ });
+ expect(getVisibleEventIds(store)).toEqual([]);
+ });
+
+ it("saving a copy of a saved question without recorded events keeps them off", async () => {
+ const store = await setupWithTimelines();
+ const question = checkNotNull(getQuestion(store.getState()));
+
+ await act(async () => {
+ await store.dispatch(
+ apiCreateQuestion(question, {
+ sourceCardId: CARD.id,
+ sourceQuestion: getOriginalQuestion(store.getState()),
+ }),
+ );
+ });
+
+ expect(getCreatedCard().visualization_settings).toMatchObject(EVENTS_OFF);
+ });
+
+ it("saving an edited copy of a saved question without recorded events keeps them off", async () => {
+ const store = await setupWithTimelines();
+
+ await triggerVisualizationQueryChange();
+ await waitFor(() => {
+ expect(getIsDirty(store.getState())).toBe(true);
+ });
+ const question = checkNotNull(getQuestion(store.getState()));
+
+ await act(async () => {
+ await store.dispatch(
+ apiCreateQuestion(question, {
+ sourceCardId: CARD.id,
+ sourceQuestion: getOriginalQuestion(store.getState()),
+ }),
+ );
+ });
+
+ expect(getCreatedCard().visualization_settings).toMatchObject(EVENTS_OFF);
+ });
+
+ it("shows root-collection events for an ad-hoc question", async () => {
+ const { store } = await setup({
+ card: createMockUnsavedCard({
+ dataset_query: CARD.dataset_query,
+ display: "line",
+ }),
+ timelines: [
+ createMockTimeline({ ...TIMELINE, collection_id: null }),
+ createMockTimeline({
+ id: 2,
+ collection_id: 123,
+ events: [createMockTimelineEvent({ ...RC1, id: 97, timeline_id: 2 })],
+ }),
+ ],
+ });
+
+ await waitFor(() => {
+ expect(getVisibleEventIds(store)).toEqual([RC1.id, RC2.id]);
+ });
+ expect(
+ checkNotNull(getQuestion(store.getState())).settings(),
+ ).not.toHaveProperty(["timeline.selected_timeline_ids"]);
+ });
+
+ it.each([
+ { source: "model", type: "model" as const, display: "table" as const },
+ {
+ source: "table question",
+ type: "question" as const,
+ display: "table" as const,
+ },
+ ])(
+ "a time-series chart explored from a saved $source shows and records collection events",
+ async ({ type, display }) => {
+ const sourceCard = createMockCard({
+ id: 2,
+ type,
+ display,
+ dataset_query: CARD.dataset_query,
+ });
+ setupCardEndpoints(sourceCard);
+ const store = await setupNewQuestion({
+ originalCardId: sourceCard.id,
+ timelines: [createMockTimeline({ ...TIMELINE, collection_id: null })],
+ });
+
+ await waitFor(() => {
+ expect(getVisibleEventIds(store)).toEqual([RC1.id, RC2.id]);
+ });
+
+ const question = checkNotNull(getQuestion(store.getState()));
+ await act(async () => {
+ await store.dispatch(
+ apiCreateQuestion(question, {
+ sourceCardId: sourceCard.id,
+ sourceQuestion: getOriginalQuestion(store.getState()),
+ }),
+ );
+ });
+
+ expect(getCreatedCard().visualization_settings).toMatchObject({
+ "timeline.selected_timeline_ids": [TIMELINE.id],
+ });
+ },
+ );
+
+ it("waits for collection timelines before saving a new question", async () => {
+ let resolveTimelines: (timelines: (typeof TIMELINE)[]) => void = () => {};
+ const timelinesResponse = new Promise<(typeof TIMELINE)[]>((resolve) => {
+ resolveTimelines = resolve;
+ });
+ const destinationTimeline = createMockTimeline({
+ id: 2,
+ collection_id: DESTINATION_COLLECTION.id,
+ collection: DESTINATION_COLLECTION,
+ events: [createMockTimelineEvent({ ...RC1, id: 97, timeline_id: 2 })],
+ });
+ const store = await setupNewQuestion({
+ timelinesResponse: () => timelinesResponse,
+ });
+ const question = checkNotNull(
+ getQuestion(store.getState()),
+ ).setCollectionId(checkNotNull(DESTINATION_COLLECTION.entity_id));
+
+ const savePromise = store.dispatch(apiCreateQuestion(question));
+
+ await waitFor(() => {
+ expect(fetchMock.callHistory.called("path:/api/timeline")).toBe(true);
+ });
+ const createCallBeforeTimelinesLoaded = fetchMock.callHistory.lastCall(
+ "path:/api/card",
+ { method: "POST" },
+ );
+
+ resolveTimelines([destinationTimeline]);
+ await act(async () => {
+ await savePromise;
+ });
+
+ expect(createCallBeforeTimelinesLoaded).toBeUndefined();
+ expect(getCreatedCard().visualization_settings).toMatchObject({
+ "timeline.selected_timeline_ids": [destinationTimeline.id],
+ });
+ });
+
+ it("a new question saved after another one still records its collection's timelines", async () => {
+ const destinationTimeline = createMockTimeline({
+ id: 2,
+ collection_id: DESTINATION_COLLECTION.id,
+ collection: DESTINATION_COLLECTION,
+ events: [createMockTimelineEvent({ ...RC1, id: 97, timeline_id: 2 })],
+ });
+ const store = await setupNewQuestion({ timelines: [destinationTimeline] });
+ const question = checkNotNull(
+ getQuestion(store.getState()),
+ ).setCollectionId(DESTINATION_COLLECTION.id);
+
+ await act(async () => {
+ await store.dispatch(apiCreateQuestion(question));
+ });
+ await act(async () => {
+ await store.dispatch(apiCreateQuestion(question));
+ });
+
+ expect(getCreatedCard().visualization_settings).toMatchObject({
+ "timeline.selected_timeline_ids": [destinationTimeline.id],
+ });
+ });
+
+ it("records an explicit empty selection when saving into a collection with no timelines", async () => {
+ const created = await saveNewQuestion({ timelines: [TIMELINE] });
+
+ expect(created.visualization_settings).toMatchObject(EVENTS_OFF);
+ expect(created).not.toHaveProperty("source_card_id");
+ });
+
+ it("records no selection when collection timelines fail to load", async () => {
+ const created = await saveNewQuestion({
+ timelinesResponse: () => Promise.reject(new Error("unavailable")),
+ });
+
+ expect(created.visualization_settings).not.toHaveProperty([
+ "timeline.selected_timeline_ids",
+ ]);
+ expect(created.visualization_settings).not.toHaveProperty([
+ "timeline.excluded_timeline_event_ids",
+ ]);
+ });
+
+ it("shows only the events a saved question recorded", async () => {
+ const store = await setupWithTimelines({
+ "timeline.selected_timeline_ids": [TIMELINE.id],
+ "timeline.excluded_timeline_event_ids": [RC1.id],
+ });
+
+ expect(getVisibleEventIds(store)).toEqual([RC2.id]);
+ });
+
+ it("shows nothing for a question saved with events turned off", async () => {
+ const store = await setupWithTimelines(EVENTS_OFF);
+
+ expect(getVisibleEventIds(store)).toEqual([]);
+ });
+
+ it("hiding an event records the selection on the question", async () => {
+ const store = await setupWithTimelines({
+ "timeline.selected_timeline_ids": [TIMELINE.id],
+ });
+ expect(getVisibleEventIds(store)).toEqual([RC1.id, RC2.id]);
+
+ // The footer's Events button only renders for time series results.
+ await act(async () => {
+ store.dispatch(onOpenTimelines());
+ });
+ await userEvent.click(getTimelineEventCheckbox("RC1"));
+
+ await waitFor(() => {
+ expect(getVisibleEventIds(store)).toEqual([RC2.id]);
+ });
+ expect(checkNotNull(getQuestion(store.getState())).settings()).toEqual(
+ expect.objectContaining({
+ "timeline.selected_timeline_ids": [TIMELINE.id],
+ "timeline.excluded_timeline_event_ids": [RC1.id],
+ }),
+ );
+ expect(getIsDirty(store.getState())).toBe(true);
+
+ await saveQuestion();
+
+ expect(await getSavedSettings()).toEqual(
+ expect.objectContaining({
+ "graph.show_values": true,
+ "timeline.selected_timeline_ids": [TIMELINE.id],
+ "timeline.excluded_timeline_event_ids": [RC1.id],
+ }),
+ );
+ });
+
+ it("saving after turning events off records the absence", async () => {
+ const store = await setupWithTimelines({
+ "timeline.selected_timeline_ids": [TIMELINE.id],
+ });
+
+ await updateVisibility(store, (visibility, timelines) =>
+ hideTimelines(visibility, [TIMELINE.id], timelines),
+ );
+ const state = store.getState();
+
+ const question = getSubmittableQuestion(
+ state,
+ checkNotNull(getQuestion(state)),
+ );
+
+ expect(question.settings()).toEqual(
+ expect.objectContaining({
+ "timeline.selected_timeline_ids": [],
+ "timeline.excluded_timeline_event_ids": [],
+ }),
+ );
+ });
+
+ it("opening the events panel from the chart tracks where it was opened from", async () => {
+ const store = await setupWithTimelines();
+
+ await act(async () => {
+ store.dispatch(openTimelines("chart", [RC1.id]));
+ });
+
+ expect(trackSimpleEvent).toHaveBeenCalledWith({
+ event: "question_events_panel_opened",
+ triggered_from: "chart",
+ });
+ });
+
+ it("focusing events while the panel is already open does not track another opening", async () => {
+ const store = await setupWithTimelines();
+ await act(async () => {
+ store.dispatch(openTimelines("footer"));
+ });
+ trackSimpleEvent.mockClear();
+
+ await act(async () => {
+ store.dispatch(openTimelines("chart", [RC1.id]));
+ });
+
+ expect(trackSimpleEvent).not.toHaveBeenCalled();
+ });
+
+ it("saving a question with a recorded selection tracks it", async () => {
+ const store = await setupWithTimelines({
+ "timeline.selected_timeline_ids": [TIMELINE.id],
+ });
+
+ await updateVisibility(store, (visibility, timelines) =>
+ hideTimelines(visibility, [TIMELINE.id], timelines),
+ );
+ await saveQuestion();
+
+ expect(await getSavedSettings()).toEqual(
+ expect.objectContaining(EVENTS_OFF),
+ );
+
+ expect(trackSimpleEvent).toHaveBeenCalledWith({
+ event: "question_timeline_events_saved",
+ target_id: CARD.id,
+ });
+ });
+
+ it("saving other changes preserves recorded events without tracking an event change", async () => {
+ const savedVisibility = {
+ "timeline.selected_timeline_ids": [TIMELINE.id],
+ "timeline.excluded_timeline_event_ids": [RC1.id],
+ };
+ await setupWithTimelines(savedVisibility);
+
+ await triggerVisualizationQueryChange();
+ await saveQuestion();
+
+ expect(await getSavedSettings()).toEqual(
+ expect.objectContaining(savedVisibility),
+ );
+ expect(trackSimpleEvent).not.toHaveBeenCalled();
+ });
+
+ it("saving unrelated changes does not record collection-default events or track an event change", async () => {
+ await setupWithTimelines();
+
+ await triggerVisualizationQueryChange();
+ await saveQuestion();
+
+ const settings = await getSavedSettings();
+ expect(settings).not.toHaveProperty(["timeline.selected_timeline_ids"]);
+ expect(settings).not.toHaveProperty([
+ "timeline.excluded_timeline_event_ids",
+ ]);
+ expect(trackSimpleEvent).not.toHaveBeenCalled();
+ });
+
+ it("turning a saved table into a time-series chart and replacing it keeps the collection events it shows", async () => {
const { store } = await setup({
- card: CARD,
+ card: createMockCard({ ...CARD, display: "table" }),
timelines: [TIMELINE],
- timelinesDelay: 200,
});
- // Guard the race conditions: the timelines must not have loaded yet, so the
- // effect's first run already happened without them. If this fails, bump the
- // delay — otherwise the test wouldn't actually exercise the re-run.
- expect(getFetchedTimelines(store.getState())).toHaveLength(0);
- expect(getVisibleTimelineEventIds(store.getState())).toHaveLength(0);
+ await act(async () => {
+ await store.dispatch(
+ updateQuestion(
+ checkNotNull(getQuestion(store.getState())).setDisplay("line"),
+ ),
+ );
+ });
+ await waitFor(() => {
+ expect(getVisibleEventIds(store)).toEqual([RC1.id, RC2.id]);
+ });
+ await saveQuestion();
- // The timelines request resolves.
+ expect(await getSavedSettings()).toMatchObject({
+ "timeline.selected_timeline_ids": [TIMELINE.id],
+ });
await waitFor(() => {
- expect(getFetchedTimelines(store.getState())).toHaveLength(1);
- });
-
- // Once loaded, the event must become visible on the chart. Without the fix
- // the effect never re-runs and this stays empty — that's the bug. The DOM
- // query forces React to flush the re-render triggered by the late resolve.
- await waitFor(
- () => {
- // Reading the DOM forces testing-library to flush React's pending
- // re-render from the late timelines resolve (queryByTestId, so it
- // doesn't throw if the chart subtree errored out under jsdom).
- screen.queryByTestId("test-container");
- expect(getVisibleTimelineEventIds(store.getState())).toContain(
- EVENT_ID,
- );
- },
- { timeout: 5000 },
+ expect(getVisibleEventIds(store)).toEqual([RC1.id, RC2.id]);
+ });
+ });
+
+ it("re-showing a timeline keeps events outside the chart's range", async () => {
+ const store = await setupWithTimelines(EVENTS_OFF);
+
+ await updateVisibility(store, (visibility, timelines) =>
+ showTimelines(visibility, [TIMELINE.id], timelines),
+ );
+
+ expect(
+ checkNotNull(getQuestion(store.getState())).settings()[
+ "timeline.excluded_timeline_event_ids"
+ ],
+ ).toEqual([]);
+ expect(getVisibleEventIds(store)).toEqual([RC1.id, RC2.id]);
+ });
+
+ it("creating an event on a timeline that is already shown records nothing", async () => {
+ const store = await setupWithTimelines({
+ "timeline.selected_timeline_ids": [TIMELINE.id],
+ });
+
+ await updateVisibility(store, (visibility, timelines) =>
+ showTimelineEvents(visibility, [RC1], timelines),
+ );
+
+ expect(getVisibleEventIds(store)).toEqual([RC1.id, RC2.id]);
+ expect(
+ checkNotNull(getQuestion(store.getState())).settings(),
+ ).toMatchObject({ "timeline.selected_timeline_ids": [TIMELINE.id] });
+ expect(getIsDirty(store.getState())).toBe(false);
+ });
+
+ it("shows an event created on a timeline that has not been fetched yet", async () => {
+ const store = await setupWithTimelines({
+ "timeline.selected_timeline_ids": [TIMELINE.id],
+ });
+ const firstEvent = createMockTimelineEvent({
+ id: 97,
+ timeline_id: 2,
+ timestamp: "2025-06-03T00:00:00Z",
+ });
+
+ await updateVisibility(store, (visibility, timelines) =>
+ showTimelineEvents(visibility, [firstEvent], timelines),
+ );
+
+ expect(checkNotNull(getQuestion(store.getState())).settings()).toEqual(
+ expect.objectContaining({
+ "timeline.selected_timeline_ids": [TIMELINE.id, 2],
+ "timeline.excluded_timeline_event_ids": [],
+ }),
+ );
+ });
+
+ it("creating an event on a timeline an ad-hoc question already shows records nothing", async () => {
+ const store = await setupAdHocWithTimelines();
+
+ await updateVisibility(store, (visibility, timelines) =>
+ showTimelineEvents(visibility, [RC1], timelines),
+ );
+
+ expect(getVisibleEventIds(store)).toEqual([RC1.id, RC2.id]);
+ expect(
+ checkNotNull(getQuestion(store.getState())).settings(),
+ ).not.toHaveProperty(["timeline.selected_timeline_ids"]);
+ });
+
+ it("shows an event created on a timeline that has not been fetched yet for an ad-hoc question", async () => {
+ const store = await setupAdHocWithTimelines();
+ const firstEvent = createMockTimelineEvent({
+ id: 97,
+ timeline_id: 2,
+ timestamp: "2025-06-03T00:00:00Z",
+ });
+
+ await updateVisibility(store, (visibility, timelines) =>
+ showTimelineEvents(visibility, [firstEvent], timelines),
+ );
+
+ expect(checkNotNull(getQuestion(store.getState())).settings()).toEqual(
+ expect.objectContaining({
+ "timeline.selected_timeline_ids": [TIMELINE.id, 2],
+ "timeline.excluded_timeline_event_ids": [],
+ }),
);
});
});
diff --git a/frontend/src/metabase/query_builder/containers/QueryBuilder.tsx b/frontend/src/metabase/query_builder/containers/QueryBuilder.tsx
index a318a88c708..46925d839cb 100644
--- a/frontend/src/metabase/query_builder/containers/QueryBuilder.tsx
+++ b/frontend/src/metabase/query_builder/containers/QueryBuilder.tsx
@@ -52,7 +52,6 @@ import {
closeSnippetModal,
deselectTimelineEvents,
followForeignKey,
- hideTimelineEvents,
initializeQB,
insertSnippet,
loadObjectDetailFKReferences,
@@ -64,6 +63,7 @@ import {
onUpdateVisualizationSettings,
openDataReferenceAtQuestion,
openSnippetModalWithSelectedText,
+ openTimelinesFromChart,
popDataReferenceStack,
pushDataReferenceStack,
queryCompleted,
@@ -88,8 +88,6 @@ import {
setSnippetCollectionId,
setTemplateTag,
setTemplateTagConfig,
- showTimelineEvents,
- showTimelinesForCollection,
softReloadCard,
toggleDataReference,
toggleSnippetSidebar,
@@ -112,12 +110,10 @@ import {
onCloseQuestionSettings,
onCloseSidebars,
onCloseSummary,
- onCloseTimelines,
onOpenChartSettings,
onOpenChartType,
onOpenQuestionInfo,
onOpenQuestionSettings,
- onOpenTimelines,
setParameterValue,
} from "../store/actions";
import { getIsObjectDetail } from "../store/mode-selectors";
@@ -126,7 +122,6 @@ import {
getDataReferenceStack,
getDocumentTitle,
getEmbeddedParameterVisibility,
- getFilteredTimelines,
getFirstQueryResult,
getIsActionListVisible,
getIsAdditionalInfoVisible,
@@ -156,10 +151,8 @@ import {
getShouldShowUnsavedChangesWarning,
getSnippetCollectionId,
getTableForeignKeyReferences,
- getTimeseriesXDomain,
+ getTimelineEventsVisibility,
getUiControls,
- getVisibleTimelineEventIds,
- getVisibleTimelineEvents,
getVisualizationSettings,
getZoomedObjectRowIndex,
isResultsMetadataDirty,
@@ -187,11 +180,8 @@ const mapStateToProps = (state: State) => {
card: getCard(state),
originalCard: getOriginalCard(state),
- timelines: getFilteredTimelines(state),
- timelineEvents: getVisibleTimelineEvents(state),
+ timelineEventsVisibility: getTimelineEventsVisibility(state),
selectedTimelineEventIds: getSelectedTimelineEventIds(state),
- visibleTimelineEventIds: getVisibleTimelineEventIds(state),
- xDomain: getTimeseriesXDomain(state),
result: getFirstQueryResult(state),
results: getQueryResults(state),
@@ -252,13 +242,12 @@ const mapDispatchToProps = {
onCloseQuestionSettings,
onCloseSidebars,
onCloseSummary,
- onCloseTimelines,
editSummary,
onOpenChartSettings,
onOpenChartType,
onOpenQuestionInfo,
onOpenQuestionSettings,
- onOpenTimelines,
+ onOpenTimelines: openTimelinesFromChart,
setIsNativeEditorOpen,
setParameterValue,
setUIControls,
@@ -269,7 +258,6 @@ const mapDispatchToProps = {
closeSnippetModal,
deselectTimelineEvents,
followForeignKey,
- hideTimelineEvents,
initializeQB,
insertSnippet,
loadObjectDetailFKReferences,
@@ -305,8 +293,6 @@ const mapDispatchToProps = {
setSnippetCollectionId,
setTemplateTag,
setTemplateTagConfig,
- showTimelineEvents,
- showTimelinesForCollection,
softReloadCard,
toggleDataReference,
toggleSnippetSidebar,
@@ -331,17 +317,14 @@ function QueryBuilderInner(props: QueryBuilderInnerProps) {
const location = useLocation();
const navigate = useNavigate();
const params = useParams();
- useFavicon({ favicon: props.pageFavicon ?? null });
const navigationType = useNavigationType();
- const { data: fetchedTimelines, isSuccess: areTimelinesLoaded } =
- useListTimelinesQuery({
- include: "events",
- });
- const { data: bookmarks = [], isSuccess: areBookmarksLoaded } =
- useListBookmarksQuery();
+ const { data: bookmarks = [] } = useListBookmarksQuery();
const [createBookmarkMutation] = useCreateBookmarkMutation();
const [deleteBookmarkMutation] = useDeleteBookmarkMutation();
+ useFavicon({ favicon: props.pageFavicon ?? null });
+ useListTimelinesQuery({ include: "events" });
+
const {
question,
originalQuestion,
@@ -354,7 +337,6 @@ function QueryBuilderInner(props: QueryBuilderInnerProps) {
setUIControls,
runOrCancelQuestionOrSelectedQuery,
cancelQuery,
- showTimelinesForCollection,
card,
isAdmin,
isLoadingComplete,
@@ -413,19 +395,14 @@ function QueryBuilderInner(props: QueryBuilderInnerProps) {
const previousLocation = usePrevious(location);
const wasShowingAnySidebar = usePrevious(isAnySidebarOpen);
const wasNativeEditorOpen = usePrevious(isNativeEditorOpen);
- const hasQuestion = question != null;
- const collectionId = question?.collectionId();
const openModal = useCallback(
- (
- modal: QueryBuilderUIControls["modal"],
- modalContext: QueryBuilderUIControls["modalContext"],
- ) => setUIControls({ modal, modalContext }),
+ (modal: QueryBuilderUIControls["modal"]) => setUIControls({ modal }),
[setUIControls],
);
const closeModal = useCallback(
- () => setUIControls({ modal: null, modalContext: null }),
+ () => setUIControls({ modal: null }),
[setUIControls],
);
@@ -496,25 +473,6 @@ function QueryBuilderInner(props: QueryBuilderInnerProps) {
closeNavbar,
]);
- useEffect(() => {
- // Gate on the timelines actually being loaded (not just bookmarks), and
- // re-run when they arrive: showTimelinesForCollection reads the fetched
- // timelines from the store at dispatch time, so running it before the
- // `/api/timeline` request resolves dispatches an empty set and the chart
- // never receives its events. This restores the pre-#73674 `allLoaded`
- // guarantee that was lost when the Timelines.loadList HOC was removed.
- if (areBookmarksLoaded && areTimelinesLoaded && hasQuestion) {
- showTimelinesForCollection(collectionId);
- }
- }, [
- areBookmarksLoaded,
- areTimelinesLoaded,
- hasQuestion,
- collectionId,
- showTimelinesForCollection,
- fetchedTimelines,
- ]);
-
useEffect(() => {
const { isShowingDataReference, isShowingTemplateTagsEditor } = uiControls;
const {
diff --git a/frontend/src/metabase/query_builder/containers/test-utils.tsx b/frontend/src/metabase/query_builder/containers/test-utils.tsx
index 1ce3d37fa01..63ef4f2a1a0 100644
--- a/frontend/src/metabase/query_builder/containers/test-utils.tsx
+++ b/frontend/src/metabase/query_builder/containers/test-utils.tsx
@@ -229,9 +229,7 @@ interface SetupOpts {
dataset?: Dataset;
initialRoute?: string;
timelines?: Timeline[];
- // Delay (ms) for the /api/timeline response, used to control its resolution
- // order relative to the question/bookmarks load.
- timelinesDelay?: number;
+ timelinesResponse?: () => Promise<Timeline[]>;
}
export const setup = async ({
@@ -245,7 +243,7 @@ export const setup = async ({
: `#${serializeCardForUrl(card)}`
}`,
timelines = [],
- timelinesDelay,
+ timelinesResponse,
}: SetupOpts) => {
setupUserMetabotPermissionsEndpoint();
setupDatabasesEndpoints([TEST_DB]);
@@ -254,7 +252,7 @@ export const setup = async ({
setupPropertiesEndpoints(createMockSettings());
setupCollectionsEndpoints({ collections: [] });
setupBookmarksEndpoints([]);
- setupTimelinesEndpoints(timelines, timelinesDelay);
+ setupTimelinesEndpoints(timelinesResponse ?? timelines);
setupCollectionByIdEndpoint({ collections: [TEST_COLLECTION] });
setupFieldValuesEndpoint(
createMockFieldValues({ field_id: Number(ORDERS.QUANTITY) }),
@@ -410,6 +408,17 @@ export const waitForSaveToBeEnabled = async () => {
});
};
+export const saveQuestion = async () => {
+ await waitForSaveToBeEnabled();
+ await userEvent.click(screen.getByText("Save"));
+ await userEvent.click(
+ within(screen.getByTestId("save-question-modal")).getByText("Save"),
+ );
+ await waitFor(() => {
+ expect(screen.queryByTestId("save-question-modal")).not.toBeInTheDocument();
+ });
+};
+
export const waitForNativeQueryEditorReady = async () => {
await waitFor(() => {
expect(screen.getByTestId("mock-native-query-editor")).toBeInTheDocument();
diff --git a/frontend/src/metabase/query_builder/containers/use-create-question.ts b/frontend/src/metabase/query_builder/containers/use-create-question.ts
index 364f5e43f7b..a90a22b7aed 100644
--- a/frontend/src/metabase/query_builder/containers/use-create-question.ts
+++ b/frontend/src/metabase/query_builder/containers/use-create-question.ts
@@ -4,12 +4,11 @@ import type { ScheduleCallback } from "metabase/common/hooks/use-callback-effect
import { useDispatch } from "metabase/redux";
import { setUIControls } from "metabase/redux/query-builder";
import type Question from "metabase-lib/v1/Question";
-import type { DashboardTabId } from "metabase-types/api";
-import { apiCreateQuestion } from "../actions";
+import { type OnCreateOptions, apiCreateQuestion } from "../actions";
import { updateUrl } from "../actions/url";
-export type OnCreateOptions = { dashboardTabId?: DashboardTabId | undefined };
+export type { OnCreateOptions };
interface UseCreateQuestionParams {
scheduleCallback?: ScheduleCallback;
diff --git a/frontend/src/metabase/query_builder/defaults.ts b/frontend/src/metabase/query_builder/defaults.ts
index e3ef2f4f14f..2d1ff2d288c 100644
--- a/frontend/src/metabase/query_builder/defaults.ts
+++ b/frontend/src/metabase/query_builder/defaults.ts
@@ -30,7 +30,6 @@ export const DEFAULT_UI_CONTROLS: QueryBuilderUIControls = {
notebookNativePreviewSidebarWidth: null,
showSidebarTitle: false,
modal: null,
- modalContext: null,
highlightedNativeQueryLineNumbers: [],
isShowingListViewConfiguration: false,
nativeEditorSelectedRange: [],
diff --git a/frontend/src/metabase/query_builder/store/actions.ts b/frontend/src/metabase/query_builder/store/actions.ts
index 99a7288a903..5c12e75cf3a 100644
--- a/frontend/src/metabase/query_builder/store/actions.ts
+++ b/frontend/src/metabase/query_builder/store/actions.ts
@@ -102,7 +102,6 @@ export const API_CREATE_QUESTION = "metabase/qb/API_CREATE_QUESTION";
export const CLEAR_OBJECT_DETAIL_FK_REFERENCES =
"metabase/qb/CLEAR_OBJECT_DETAIL_FK_REFERENCES";
export const DESELECT_TIMELINE_EVENTS = "metabase/qb/DESELECT_TIMELINE_EVENTS";
-export const HIDE_TIMELINE_EVENTS = "metabase/qb/HIDE_TIMELINE_EVENTS";
export const LOAD_OBJECT_DETAIL_FK_REFERENCES =
"metabase/qb/LOAD_OBJECT_DETAIL_FK_REFERENCES";
export const OPEN_DATA_REFERENCE_AT_QUESTION =
@@ -120,7 +119,6 @@ export const SET_NATIVE_EDITOR_SELECTED_RANGE =
"metabase/qb/SET_NATIVE_EDITOR_SELECTED_RANGE";
export const SET_SNIPPET_COLLECTION_ID =
"metabase/qb/SET_SNIPPET_COLLECTION_ID";
-export const SHOW_TIMELINE_EVENTS = "metabase/qb/SHOW_TIMELINE_EVENTS";
export const TOGGLE_DATA_REFERENCE = "metabase/qb/TOGGLE_DATA_REFERENCE";
export const TOGGLE_SNIPPET_SIDEBAR = "metabase/qb/TOGGLE_SNIPPET_SIDEBAR";
export const TOGGLE_TEMPLATE_TAGS_EDITOR =
diff --git a/frontend/src/metabase/query_builder/store/reducer.ts b/frontend/src/metabase/query_builder/store/reducer.ts
index 3bd08dd101e..223743dede4 100644
--- a/frontend/src/metabase/query_builder/store/reducer.ts
+++ b/frontend/src/metabase/query_builder/store/reducer.ts
@@ -1,11 +1,9 @@
import { type Reducer, combineReducers, createReducer } from "@reduxjs/toolkit";
import { assoc, merge } from "icepick";
-import _ from "underscore";
import {
createCardPublicLink,
deleteCardPublicLink,
- timelineEventApi,
updateCardEmbeddingParams,
updateCardEnableEmbedding,
} from "metabase/api";
@@ -62,7 +60,6 @@ import {
CLOSE_SIDEBARS,
CLOSE_TIMELINES,
DESELECT_TIMELINE_EVENTS,
- HIDE_TIMELINE_EVENTS,
LOAD_OBJECT_DETAIL_FK_REFERENCES,
ON_CLOSE_SUMMARY,
OPEN_CHART_SETTINGS,
@@ -91,7 +88,6 @@ import {
SET_SHOW_LOADING_COMPLETE_FAVICON,
SET_SNIPPET_COLLECTION_ID,
SHOW_CHART_SETTINGS,
- SHOW_TIMELINE_EVENTS,
SOFT_RELOAD_CARD,
TOGGLE_DATA_REFERENCE,
TOGGLE_SNIPPET_SIDEBAR,
@@ -578,28 +574,6 @@ const parentEntity = createReducer<QueryBuilderParentEntityState>(
},
);
-const visibleTimelineEventIds = createReducer<number[]>([], (builder) => {
- builder
- .addCase(INITIALIZE_QB, () => [])
- .addCase<string, { type: string; payload: TimelineEvent[] }>(
- SHOW_TIMELINE_EVENTS,
- (state, action) =>
- _.uniq([...state, ...action.payload.map((event) => event.id)]),
- )
- .addCase<string, { type: string; payload: TimelineEvent[] }>(
- HIDE_TIMELINE_EVENTS,
- (state, action) => {
- const eventIdsToHide = action.payload.map((event) => event.id);
- return state.filter((eventId) => !eventIdsToHide.includes(eventId));
- },
- )
- .addCase(RESET_QB, () => [])
- .addMatcher(
- timelineEventApi.endpoints.createTimelineEvent.matchFulfilled,
- (state, action) => [...state, action.payload.id],
- );
-});
-
const selectedTimelineEventIds = createReducer<number[]>([], (builder) => {
builder
.addCase(INITIALIZE_QB, () => [])
@@ -748,7 +722,6 @@ export const queryBuilderReducer: Reducer<QueryBuilderState> = combineReducers({
parameterValues,
currentState,
parentEntity,
- visibleTimelineEventIds,
selectedTimelineEventIds,
card,
});
diff --git a/frontend/src/metabase/query_builder/store/selectors.ts b/frontend/src/metabase/query_builder/store/selectors.ts
index 14057ad48c9..e91f68fe032 100644
--- a/frontend/src/metabase/query_builder/store/selectors.ts
+++ b/frontend/src/metabase/query_builder/store/selectors.ts
@@ -1,14 +1,10 @@
/*eslint no-use-before-define: "error"*/
import { createSelector } from "@reduxjs/toolkit";
-import * as d3 from "d3";
-import { merge, updateIn } from "icepick";
+import { merge } from "icepick";
import { shallowEqual } from "react-redux";
import _ from "underscore";
-import { timelineApi } from "metabase/api";
import { LOAD_COMPLETE_FAVICON } from "metabase/common/hooks/constants";
-import { getSortedTimelines } from "metabase/common/utils/timelines";
-import { dayjs } from "metabase/dayjs";
import { getEmbedOptions } from "metabase/embedding/interactive-embedding";
import {
getShallowTableFieldIds,
@@ -21,20 +17,22 @@ import {
isQuestionRunnable,
} from "metabase/querying/common/utils/question";
import { getSetting } from "metabase/settings";
+import { getTransformedTimelines } from "metabase/timelines/panel/selectors";
+import { filterTimelinesByXAxes } from "metabase/timelines/panel/utils";
import { selectIsWithinIframe } from "metabase/utils/iframe";
-import { parseTimestamp } from "metabase/utils/time-dayjs";
-import { isNotNull } from "metabase/utils/types";
import type { ObjectId } from "metabase/visualizations/components/ObjectDetail/types";
import {
- type TimeSeriesInterval,
- computeTimeseriesDataInterval,
+ getCollectionTimelinesVisibility,
+ getRecordedTimelineEventsVisibility,
+ resolveVisibleTimelineEvents,
+} from "metabase/visualizations/lib/timeline-events-visibility";
+import {
+ getTimeseriesXAxis as computeTimeseriesXAxis,
createRawSeries,
extractRemappings,
getComputedSettingsForSeries,
getVisualizationTransformed,
- getXValues,
isTimeseries,
- minTimeseriesUnit,
} from "metabase/viz-core";
import * as Lib from "metabase-lib";
import type Question from "metabase-lib/v1/Question";
@@ -52,13 +50,12 @@ import type {
DatasetQuery,
Field,
Series,
- Timeline,
- TimelineEvent,
+ TimelineEventsVisibility,
} from "metabase-types/api";
-import { isAbsoluteDateTimeUnit } from "metabase-types/guards/date-time";
import { cleanIndexFlags } from "../model-indexes/actions";
import { getWritableColumnProperties } from "../utils";
+import { isLegacyTimelineEventsSource } from "../utils/timeline-events";
import { getQuestionWithDefaultVisualizationSettings } from "../utils/viz-settings";
import {
@@ -134,10 +131,10 @@ export const getLastRunCard = (state: QueryBuilderStoreState) =>
export const getMetadataDiff = (state: QueryBuilderStoreState) =>
state.qb.metadataDiff;
-export const getVisibleTimelineEventIds = (state: QueryBuilderStoreState) =>
- state.qb.visibleTimelineEventIds;
export const getSelectedTimelineEventIds = (state: QueryBuilderStoreState) =>
state.qb.selectedTimelineEventIds;
+export const getFocusedTimelineEventIds = (state: QueryBuilderStoreState) =>
+ getUiControls(state).focusedTimelineEventIds;
const getRawQueryResults = (state: QueryBuilderStoreState) =>
state.qb.queryResults;
@@ -817,151 +814,47 @@ export const getIsTimeseries = createSelector(
(settings) => settings && isTimeseries(settings),
);
-export const getTimeseriesXValues = createSelector(
- [getIsTimeseries, getTransformedSeries, getVisualizationSettings],
- (isTimeseries, series, settings) =>
- isTimeseries && series && settings
- ? getXValues({ series, settings })
- : null,
-);
-
-export const getTimeseriesDataInterval = createSelector(
- [
- getTransformedSeries,
- getVisualizationSettings,
- getIsTimeseries,
- getTimeseriesXValues,
- ],
- (series, settings, isTimeseries, xValues): TimeSeriesInterval | null => {
- if (!isTimeseries || !xValues) {
- return null;
- }
- const columns = series?.[0]?.data?.cols ?? [];
- const dimensions = settings?.["graph.dimensions"] ?? [];
- const dimensionColumns = dimensions.map((dimension) =>
- columns.find((column) => column != null && column.name === dimension),
- );
- const columnUnits = dimensionColumns
- .map((column) =>
- isAbsoluteDateTimeUnit(column?.unit) ? column.unit : null,
- )
- .filter(isNotNull);
- return (
- computeTimeseriesDataInterval(xValues, minTimeseriesUnit(columnUnits)) ??
- null
- );
- },
+export const getTimeseriesXAxis = createSelector(
+ [getTransformedSeries, getVisualizationSettings],
+ (series, settings) =>
+ series && settings ? computeTimeseriesXAxis(series, settings) : null,
);
-type Numeric = string | number | boolean | object | dayjs.Dayjs;
-type Domain<T extends Numeric = Numeric> = [T, T];
-
-export const getTimeseriesXDomain = createSelector(
- [getIsTimeseries, getTimeseriesXValues],
- (isTimeseries, xValues) => {
- if (isTimeseries && Array.isArray(xValues) && xValues.length > 0) {
- // Unjustified type cast. FIXME
- return d3.extent(xValues as Array<d3.Numeric>) as Domain<dayjs.Dayjs>;
- }
- return null;
- },
+const getFilteredTimelines = createSelector(
+ [getTransformedTimelines, getTimeseriesXAxis],
+ (timelines, xAxis) =>
+ filterTimelinesByXAxes(timelines, xAxis ? [xAxis] : null),
);
-const selectListTimelines = timelineApi.endpoints.listTimelines.select({
- include: "events",
-});
+const NO_TIMELINE_EVENTS_VISIBILITY: TimelineEventsVisibility = {};
-export const getFetchedTimelines = createSelector(
- [selectListTimelines],
- (result): Timeline[] => result.data ?? [],
-);
-
-export const getTransformedTimelines = createSelector(
- [getFetchedTimelines],
- (timelines) => {
- return getSortedTimelines(
- timelines.map((timeline) =>
- updateIn(timeline, ["events"], (events = []) =>
- _.chain(events)
- .map((event) => updateIn(event, ["timestamp"], parseTimestamp))
- .filter((event) => !event.archived)
- .value(),
- ),
+export const getTimelineEventsVisibility = createSelector(
+ [
+ (state: QueryBuilderStoreState) =>
+ getRecordedTimelineEventsVisibility(getQuestion(state)?.settings()),
+ (state: QueryBuilderStoreState) =>
+ isLegacyTimelineEventsSource(
+ getOriginalQuestion(state) ?? getQuestion(state),
),
- );
- },
+ (state: QueryBuilderStoreState) => getQuestion(state)?.collectionId(),
+ getTransformedTimelines,
+ ],
+ (savedVisibility, isLegacySource, collectionId, timelines) =>
+ savedVisibility ??
+ (isLegacySource
+ ? NO_TIMELINE_EVENTS_VISIBILITY
+ : getCollectionTimelinesVisibility(timelines, collectionId)),
);
-function isEventWithinDomain(
- event: TimelineEvent,
- xDomain: Domain<dayjs.Dayjs>,
-) {
- return dayjs(event.timestamp).isBetween(
- xDomain[0],
- xDomain[1],
- undefined,
- "[]",
- );
-}
-
-function getXDomainForTimelines<T extends Numeric>(
- xDomain: Domain<T> | null,
- dataInterval: TimeSeriesInterval | null,
-): Domain<T> | null {
- // When looking at, let's say, count of orders over years, last year value is Jan 1, 2024
- // If we filter timeline events up until Jan 1, 2024, we won't see any events from 2024,
- // so we need to extend xDomain by dataInterval.count * dataInterval.unit to include them
- if (
- xDomain &&
- isAbsoluteDateTimeUnit(dataInterval?.unit) &&
- dayjs.isDayjs(xDomain[0]) &&
- dayjs.isDayjs(xDomain[1])
- ) {
- let maxValue = xDomain[1]
- .clone()
- .add(dataInterval.count, dataInterval.unit);
-
- if (dataInterval.unit !== "hour" && dataInterval.unit !== "minute") {
- maxValue = maxValue.subtract(1, "day");
- }
-
- // Unjustified type cast. FIXME
- return [xDomain[0], maxValue as T];
- }
-
- return xDomain;
-}
-
-export const getFilteredTimelines = createSelector(
- [getTransformedTimelines, getTimeseriesXDomain, getTimeseriesDataInterval],
- (timelines, xDomain, dataInterval) => {
- const timelineXDomain = getXDomainForTimelines(xDomain, dataInterval);
- return timelines
- .map((timeline) =>
- updateIn(timeline, ["events"], (events: TimelineEvent[]) =>
- xDomain
- ? events.filter(
- (event) =>
- timelineXDomain &&
- isEventWithinDomain(event, timelineXDomain),
- )
- : events,
- ),
- )
- .filter((timeline) => (timeline.events ?? []).length > 0);
- },
+export const getVisibleTimelineEvents = createSelector(
+ [getFilteredTimelines, getTimelineEventsVisibility],
+ (timelines, visibility) =>
+ resolveVisibleTimelineEvents({ timelines, visibility }),
);
-export const getVisibleTimelineEvents = createSelector(
- [getFilteredTimelines, getVisibleTimelineEventIds],
- (timelines, visibleTimelineEventIds) =>
- _.chain(timelines)
- .map((timeline) => timeline.events)
- .flatten()
- .compact()
- .filter((event) => visibleTimelineEventIds.includes(event.id))
- .sortBy((event) => event.timestamp)
- .value(),
+export const getVisibleTimelineEventIds = createSelector(
+ [getVisibleTimelineEvents],
+ (events) => events.map((event) => event.id),
);
export function getOffsetForQueryAndPosition(
diff --git a/frontend/src/metabase/query_builder/utils/timeline-events.ts b/frontend/src/metabase/query_builder/utils/timeline-events.ts
new file mode 100644
index 00000000000..f7d4dd09043
--- /dev/null
+++ b/frontend/src/metabase/query_builder/utils/timeline-events.ts
@@ -0,0 +1,12 @@
+import { canDisplayTimelineEvents } from "metabase/viz-core";
+import type Question from "metabase-lib/v1/Question";
+
+// A saved question chart that could have recorded a timeline selection but didn't predates recording
+export const isLegacyTimelineEventsSource = (
+ source: Question | null | undefined,
+) =>
+ Boolean(
+ source?.isSaved() &&
+ source.type() === "question" &&
+ canDisplayTimelineEvents(source.display()),
+ );
diff --git a/frontend/src/metabase/querying/components/QueryVisualization/VisualizationResult.tsx b/frontend/src/metabase/querying/components/QueryVisualization/VisualizationResult.tsx
index 55023e4feeb..99cae33ce09 100644
--- a/frontend/src/metabase/querying/components/QueryVisualization/VisualizationResult.tsx
+++ b/frontend/src/metabase/querying/components/QueryVisualization/VisualizationResult.tsx
@@ -34,7 +34,7 @@ export function VisualizationResult(props: QueryVisualizationProps) {
navigateToNewCardInsideQB,
result,
rawSeries,
- timelineEvents,
+ timelineEventsVisibility,
selectedTimelineEventIds,
onNavigateBack,
className,
@@ -104,7 +104,7 @@ export function VisualizationResult(props: QueryVisualizationProps) {
queryBuilderMode={queryBuilderMode}
showTitle={false}
canToggleSeriesVisibility
- timelineEvents={timelineEvents}
+ timelineEventsVisibility={timelineEventsVisibility}
selectedTimelineEventIds={selectedTimelineEventIds}
getExtraDataForClick={getExtraDataForClick}
onZoomRow={onZoomRow}
diff --git a/frontend/src/metabase/querying/components/QueryVisualization/types.ts b/frontend/src/metabase/querying/components/QueryVisualization/types.ts
index 5da3be0162a..23cda84240a 100644
--- a/frontend/src/metabase/querying/components/QueryVisualization/types.ts
+++ b/frontend/src/metabase/querying/components/QueryVisualization/types.ts
@@ -11,6 +11,7 @@ import type {
Series,
SeriesCard,
TimelineEvent,
+ TimelineEventsVisibility,
VisualizationSettings,
} from "metabase-types/api";
@@ -48,7 +49,7 @@ export type QueryVisualizationProps = VisualizationPassThroughProps & {
scrollToLastColumn?: boolean;
getExtraDataForClick?: () => Record<string, unknown>;
- timelineEvents?: TimelineEvent[];
+ timelineEventsVisibility?: TimelineEventsVisibility;
selectedTimelineEventIds?: number[];
runQuestionQuery?: () => void;
diff --git a/frontend/src/metabase/querying/constants.ts b/frontend/src/metabase/querying/constants.ts
index 2325bd67083..ae377bacb6b 100644
--- a/frontend/src/metabase/querying/constants.ts
+++ b/frontend/src/metabase/querying/constants.ts
@@ -10,9 +10,6 @@ export const MODAL_TYPES = {
SAVE_QUESTION_BEFORE_EMBED: "save-question-before-embed",
TURN_INTO_DATASET: "turn-into-dataset",
CAN_NOT_CREATE_MODEL: "can-not-create-model",
- NEW_EVENT: "new-event",
- EDIT_EVENT: "edit-event",
- MOVE_EVENT: "move-event",
PREVIEW_QUERY: "preview-query",
QUESTION_EMBED: "question-embed",
} as const satisfies Record<string, QueryModalType>;
diff --git a/frontend/src/metabase/redux/cards.ts b/frontend/src/metabase/redux/cards.ts
index 41ec7c02065..d9f8258d1f6 100644
--- a/frontend/src/metabase/redux/cards.ts
+++ b/frontend/src/metabase/redux/cards.ts
@@ -59,9 +59,16 @@ const WRITABLE_CARD_PROPERTIES = [
"size",
] as const;
-const pickWritable = (card: object) =>
+// Accepted by POST /api/card only, so it stays out of the shared list above:
+// it tells the backend the new card is a copy of an existing one.
+const CREATE_ONLY_CARD_PROPERTIES = ["source_card_id"] as const;
+
+const pickWritable = (card: object, extraProperties: readonly string[] = []) =>
// Unjustified type cast. FIXME
- _.pick(card, "id", ...WRITABLE_CARD_PROPERTIES) as Record<string, unknown>;
+ _.pick(card, "id", ...WRITABLE_CARD_PROPERTIES, ...extraProperties) as Record<
+ string,
+ unknown
+ >;
/**
* Creates a card and notifies the retired-entity reducers. Replaces
@@ -73,7 +80,7 @@ export const createQuestionCard =
(request: object) =>
async (dispatch: Dispatch): Promise<Card> => {
const { collection_id, dashboard_id, dashboard_tab_id, ...rest } =
- pickWritable(request);
+ pickWritable(request, CREATE_ONLY_CARD_PROPERTIES);
const destination = dashboard_id
? { dashboard_id, dashboard_tab_id }
diff --git a/frontend/src/metabase/redux/store/dashboard.ts b/frontend/src/metabase/redux/store/dashboard.ts
index 5291ccfcdbe..37e940a4386 100644
--- a/frontend/src/metabase/redux/store/dashboard.ts
+++ b/frontend/src/metabase/redux/store/dashboard.ts
@@ -11,6 +11,8 @@ import type {
ParameterId,
ParameterValueOrArray,
ParameterValuesMap,
+ TimelineEventId,
+ TimelineEventsVisibility,
} from "metabase-types/api";
export type DashboardSidebarName =
@@ -20,7 +22,8 @@ export type DashboardSidebarName =
| "editParameter"
| "settings"
| "sharing"
- | "info";
+ | "info"
+ | "events";
interface BaseSidebarState {
name?: DashboardSidebarName;
@@ -48,10 +51,34 @@ export interface EditParameterSidebarState extends BaseSidebarState {
props: EditParameterSidebarProps;
}
+export type EventsSidebarProps = {
+ dashcardId?: DashCardId;
+ focusedEventIds?: TimelineEventId[];
+};
+
+export interface EventsSidebarState extends BaseSidebarState {
+ name: "events";
+ props: EventsSidebarProps;
+}
+
export type DashboardSidebarState =
| BaseSidebarState
| ClickBehaviorSidebarState
- | EditParameterSidebarState;
+ | EditParameterSidebarState
+ | EventsSidebarState;
+
+export type TimelineEventsSelection = {
+ dashcardId?: DashCardId;
+ eventIds: TimelineEventId[];
+};
+
+export interface DashboardTimelineEventsState {
+ overrides: Record<DashCardId, TimelineEventsVisibility>;
+ /** what each chart reports after size adjustments; absent until it is measured */
+ enabledByDashCard: Record<DashCardId, boolean>;
+ selection: TimelineEventsSelection | null;
+ hasTrackedEventsShown: boolean;
+}
export type StoreDashboardTab = DashboardTab & {
isRemoved?: boolean;
@@ -126,6 +153,8 @@ export interface DashboardState {
sidebar: DashboardSidebarState;
+ timelineEvents: DashboardTimelineEventsState;
+
missingActionParameters: unknown;
autoApplyFilters: {
diff --git a/frontend/src/metabase/redux/store/qb.ts b/frontend/src/metabase/redux/store/qb.ts
index 017746b0373..1966012add3 100644
--- a/frontend/src/metabase/redux/store/qb.ts
+++ b/frontend/src/metabase/redux/store/qb.ts
@@ -6,7 +6,6 @@ import type {
Field,
NativeQuerySnippet,
ParameterValuesMap,
- TimelineEventId,
} from "metabase-types/api";
export type QueryModalType =
@@ -73,7 +72,6 @@ export interface QueryBuilderUIControls {
notebookNativePreviewSidebarWidth: number | null;
showSidebarTitle: boolean;
modal: QueryModalType | null;
- modalContext: TimelineEventId | null;
modalSnippet?:
| NativeQuerySnippet
| Partial<Omit<NativeQuerySnippet, "id">>
@@ -127,6 +125,4 @@ export interface QueryBuilderState {
cardId?: number;
serializedCard: string;
} | null;
-
- visibleTimelineEventIds: TimelineEventId[];
}
diff --git a/frontend/src/metabase/timelines/collections/containers/NewEventWithTimelineModal/NewEventWithTimelineModal.tsx b/frontend/src/metabase/timelines/collections/containers/NewEventWithTimelineModal/NewEventWithTimelineModal.tsx
index af587b41af6..6ff4f18ed63 100644
--- a/frontend/src/metabase/timelines/collections/containers/NewEventWithTimelineModal/NewEventWithTimelineModal.tsx
+++ b/frontend/src/metabase/timelines/collections/containers/NewEventWithTimelineModal/NewEventWithTimelineModal.tsx
@@ -8,12 +8,7 @@ import { getDefaultTimeline } from "metabase/common/utils/timelines";
import { useNavigate } from "metabase/router";
import NewEventModal from "metabase/timelines/common/components/NewEventModal";
import * as Urls from "metabase/urls";
-import type {
- Collection,
- CreateTimelineEventRequest,
- CreateTimelineRequest,
- TimelineEvent,
-} from "metabase-types/api";
+import type { Collection, TimelineEventData } from "metabase-types/api";
import LoadingAndErrorWrapper from "../../components/LoadingAndErrorWrapper";
import type { ModalParams } from "../../types";
@@ -39,21 +34,19 @@ function NewEventWithTimelineModalContainer(
);
const onSubmit = async (
- values: Partial<TimelineEvent>,
+ values: TimelineEventData,
collection?: Collection,
) => {
if (!collection) {
return;
}
const timeline = await createTimeline(
- // Unjustified type cast. FIXME
- getDefaultTimeline(collection) as CreateTimelineRequest,
+ getDefaultTimeline(collection),
).unwrap();
- // Unjustified type cast. FIXME
await createTimelineEvent({
...values,
timeline_id: timeline.id,
- } as CreateTimelineEventRequest).unwrap();
+ }).unwrap();
navigate(Urls.timelinesInCollection(collection));
};
diff --git a/frontend/src/metabase/timelines/questions/components/EventCard/EventCard.module.css b/frontend/src/metabase/timelines/panel/components/EventCard/EventCard.module.css
similarity index 100%
rename from frontend/src/metabase/timelines/questions/components/EventCard/EventCard.module.css
rename to frontend/src/metabase/timelines/panel/components/EventCard/EventCard.module.css
diff --git a/frontend/src/metabase/timelines/questions/components/EventCard/EventCard.tsx b/frontend/src/metabase/timelines/panel/components/EventCard/EventCard.tsx
similarity index 96%
rename from frontend/src/metabase/timelines/questions/components/EventCard/EventCard.tsx
rename to frontend/src/metabase/timelines/panel/components/EventCard/EventCard.tsx
index 42b85ceece7..b95a6e3ff2b 100644
--- a/frontend/src/metabase/timelines/questions/components/EventCard/EventCard.tsx
+++ b/frontend/src/metabase/timelines/panel/components/EventCard/EventCard.tsx
@@ -16,6 +16,7 @@ export interface EventCardProps {
timeline: Timeline;
isSelected?: boolean;
isVisible: boolean;
+ isPartiallyVisible?: boolean;
onEdit?: (event: TimelineEvent) => void;
onMove?: (event: TimelineEvent) => void;
onArchive?: (event: TimelineEvent) => void;
@@ -29,6 +30,7 @@ const EventCardInner = ({
timeline,
isSelected,
isVisible,
+ isPartiallyVisible = false,
onEdit,
onMove,
onArchive,
@@ -72,6 +74,7 @@ const EventCardInner = ({
<Flex flex="0 0 auto" justify="center" align="center" w="2rem" h="2rem">
<Checkbox
checked={isVisible}
+ indeterminate={!isVisible && isPartiallyVisible}
onChange={handleChangeVisibility}
onClick={handleAsideClick}
/>
diff --git a/frontend/src/metabase/timelines/questions/components/EventCard/EventCard.unit.spec.tsx b/frontend/src/metabase/timelines/panel/components/EventCard/EventCard.unit.spec.tsx
similarity index 100%
rename from frontend/src/metabase/timelines/questions/components/EventCard/EventCard.unit.spec.tsx
rename to frontend/src/metabase/timelines/panel/components/EventCard/EventCard.unit.spec.tsx
diff --git a/frontend/src/metabase/timelines/questions/components/EventCard/index.ts b/frontend/src/metabase/timelines/panel/components/EventCard/index.ts
similarity index 100%
rename from frontend/src/metabase/timelines/questions/components/EventCard/index.ts
rename to frontend/src/metabase/timelines/panel/components/EventCard/index.ts
diff --git a/frontend/src/metabase/timelines/questions/components/TimelineCard/TimelineCard.module.css b/frontend/src/metabase/timelines/panel/components/TimelineCard/TimelineCard.module.css
similarity index 100%
rename from frontend/src/metabase/timelines/questions/components/TimelineCard/TimelineCard.module.css
rename to frontend/src/metabase/timelines/panel/components/TimelineCard/TimelineCard.module.css
diff --git a/frontend/src/metabase/timelines/questions/components/TimelineCard/TimelineCard.tsx b/frontend/src/metabase/timelines/panel/components/TimelineCard/TimelineCard.tsx
similarity index 83%
rename from frontend/src/metabase/timelines/questions/components/TimelineCard/TimelineCard.tsx
rename to frontend/src/metabase/timelines/panel/components/TimelineCard/TimelineCard.tsx
index 56433f3afca..085c3f5c402 100644
--- a/frontend/src/metabase/timelines/questions/components/TimelineCard/TimelineCard.tsx
+++ b/frontend/src/metabase/timelines/panel/components/TimelineCard/TimelineCard.tsx
@@ -5,6 +5,7 @@ import _ from "underscore";
import { getTimelineName } from "metabase/common/utils/timelines";
import { Box, Checkbox, Ellipsified, Flex, Icon } from "metabase/ui";
+import { parseTimestamp } from "metabase/utils/time-dayjs";
import type { Timeline, TimelineEvent } from "metabase-types/api";
import { EventCard } from "../EventCard";
@@ -15,6 +16,7 @@ export interface TimelineCardProps {
timeline: Timeline;
isDefault?: boolean;
visibleEventIds: number[];
+ partiallyVisibleEventIds?: number[];
selectedEventIds?: number[];
onEditEvent?: (event: TimelineEvent) => void;
onMoveEvent?: (event: TimelineEvent) => void;
@@ -22,12 +24,15 @@ export interface TimelineCardProps {
onToggleEventSelected?: (event: TimelineEvent, isSelected: boolean) => void;
onShowTimelineEvents: (timelineEvent: TimelineEvent[]) => void;
onHideTimelineEvents: (timelineEvent: TimelineEvent[]) => void;
+ onShowTimeline: (timeline: Timeline) => void;
+ onHideTimeline: (timeline: Timeline) => void;
}
const TimelineCardInner = ({
timeline,
isDefault,
visibleEventIds = [],
+ partiallyVisibleEventIds = [],
selectedEventIds = [],
onEditEvent,
onMoveEvent,
@@ -35,6 +40,8 @@ const TimelineCardInner = ({
onToggleEventSelected,
onShowTimelineEvents,
onHideTimelineEvents,
+ onShowTimeline,
+ onHideTimeline,
}: TimelineCardProps): JSX.Element => {
const events = getEvents(timeline.events);
const isEventSelected = events.some((e) => selectedEventIds.includes(e.id));
@@ -54,6 +61,11 @@ const TimelineCardInner = ({
[events, visibleEventIds],
);
+ const anyEventPartiallyVisible = useMemo(
+ () => events.some((event) => partiallyVisibleEventIds.includes(event.id)),
+ [events, partiallyVisibleEventIds],
+ );
+
const handleHeaderClick = useCallback(() => {
setIsExpanded((isExpanded) => !isExpanded);
}, []);
@@ -64,15 +76,13 @@ const TimelineCardInner = ({
const handleChangeVisibility = useCallback(
(e: ChangeEvent<HTMLInputElement>) => {
- if (timeline.events) {
- if (e.target.checked) {
- onShowTimelineEvents(timeline.events);
- } else {
- onHideTimelineEvents(timeline.events);
- }
+ if (e.target.checked) {
+ onShowTimeline(timeline);
+ } else {
+ onHideTimeline(timeline);
}
},
- [timeline, onShowTimelineEvents, onHideTimelineEvents],
+ [timeline, onShowTimeline, onHideTimeline],
);
useEffect(() => {
@@ -96,7 +106,9 @@ const TimelineCardInner = ({
>
<Checkbox
checked={anyEventVisible}
- indeterminate={anyEventVisible && !allEventsVisible}
+ indeterminate={
+ (anyEventVisible && !allEventsVisible) || anyEventPartiallyVisible
+ }
onClick={handleCheckboxClick}
onChange={handleChangeVisibility}
/>
@@ -129,6 +141,7 @@ const TimelineCardInner = ({
timeline={timeline}
isSelected={selectedEventIds.includes(event.id)}
isVisible={visibleEventIds.includes(event.id)}
+ isPartiallyVisible={partiallyVisibleEventIds.includes(event.id)}
onEdit={onEditEvent}
onMove={onMoveEvent}
onArchive={onArchiveEvent}
@@ -145,7 +158,7 @@ const TimelineCardInner = ({
const getEvents = (events: TimelineEvent[] = []) => {
return _.chain(events)
- .sortBy((e) => e.timestamp)
+ .sortBy((e) => parseTimestamp(e.timestamp))
.reverse()
.value();
};
diff --git a/frontend/src/metabase/timelines/questions/components/TimelineCard/TimelineCard.unit.spec.tsx b/frontend/src/metabase/timelines/panel/components/TimelineCard/TimelineCard.unit.spec.tsx
similarity index 79%
rename from frontend/src/metabase/timelines/questions/components/TimelineCard/TimelineCard.unit.spec.tsx
rename to frontend/src/metabase/timelines/panel/components/TimelineCard/TimelineCard.unit.spec.tsx
index 339ead16dee..56abb48ab7c 100644
--- a/frontend/src/metabase/timelines/questions/components/TimelineCard/TimelineCard.unit.spec.tsx
+++ b/frontend/src/metabase/timelines/panel/components/TimelineCard/TimelineCard.unit.spec.tsx
@@ -84,6 +84,33 @@ describe("TimelineCard", () => {
expect(screen.getByText("RC")).toBeInTheDocument();
});
+ it("should list events newest first when their UTC offsets differ", () => {
+ const props = getProps({
+ timeline: createMockTimeline({
+ events: [
+ createMockTimelineEvent({
+ id: 1,
+ name: "Earlier release",
+ timestamp: "2024-01-01T10:00:00+05:00",
+ }),
+ createMockTimelineEvent({
+ id: 2,
+ name: "Later release",
+ timestamp: "2024-01-01T08:00:00-02:00",
+ }),
+ ],
+ }),
+ isDefault: true,
+ });
+
+ render(<TimelineCard {...props} />);
+
+ const eventCards = screen.getAllByLabelText("Timeline event card");
+ expect(eventCards).toHaveLength(2);
+ expect(eventCards[0]).toHaveTextContent("Later release");
+ expect(eventCards[1]).toHaveTextContent("Earlier release");
+ });
+
it("should toggle visibility of the card", async () => {
const props = getProps({
timeline: createMockTimeline({
@@ -95,7 +122,7 @@ describe("TimelineCard", () => {
render(<TimelineCard {...props} />);
await userEvent.click(screen.getByRole("checkbox"));
- expect(props.onShowTimelineEvents).toHaveBeenCalled();
+ expect(props.onShowTimeline).toHaveBeenCalledWith(props.timeline);
});
});
@@ -106,5 +133,7 @@ const getProps = (opts?: Partial<TimelineCardProps>): TimelineCardProps => ({
onArchiveEvent: jest.fn(),
onShowTimelineEvents: jest.fn(),
onHideTimelineEvents: jest.fn(),
+ onShowTimeline: jest.fn(),
+ onHideTimeline: jest.fn(),
...opts,
});
diff --git a/frontend/src/metabase/timelines/questions/components/TimelineEmptyState/TimelineEmptyState.tsx b/frontend/src/metabase/timelines/panel/components/TimelineEmptyState/TimelineEmptyState.tsx
similarity index 100%
rename from frontend/src/metabase/timelines/questions/components/TimelineEmptyState/TimelineEmptyState.tsx
rename to frontend/src/metabase/timelines/panel/components/TimelineEmptyState/TimelineEmptyState.tsx
diff --git a/frontend/src/metabase/timelines/questions/components/TimelineEmptyState/TimelineEmptyState.unit.spec.tsx b/frontend/src/metabase/timelines/panel/components/TimelineEmptyState/TimelineEmptyState.unit.spec.tsx
similarity index 100%
rename from frontend/src/metabase/timelines/questions/components/TimelineEmptyState/TimelineEmptyState.unit.spec.tsx
rename to frontend/src/metabase/timelines/panel/components/TimelineEmptyState/TimelineEmptyState.unit.spec.tsx
diff --git a/frontend/src/metabase/timelines/questions/components/TimelineEmptyState/index.ts b/frontend/src/metabase/timelines/panel/components/TimelineEmptyState/index.ts
similarity index 100%
rename from frontend/src/metabase/timelines/questions/components/TimelineEmptyState/index.ts
rename to frontend/src/metabase/timelines/panel/components/TimelineEmptyState/index.ts
diff --git a/frontend/src/metabase/timelines/panel/components/TimelineEventModals/TimelineEventModals.tsx b/frontend/src/metabase/timelines/panel/components/TimelineEventModals/TimelineEventModals.tsx
new file mode 100644
index 00000000000..7e3f8365720
--- /dev/null
+++ b/frontend/src/metabase/timelines/panel/components/TimelineEventModals/TimelineEventModals.tsx
@@ -0,0 +1,88 @@
+import { match } from "ts-pattern";
+import { t } from "ttag";
+
+import { skipToken, useGetTimelineEventQuery } from "metabase/api";
+import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";
+import { Modal } from "metabase/ui";
+import type {
+ CollectionId,
+ TimelineEvent,
+ TimelineEventId,
+ TimelineEventSource,
+} from "metabase-types/api";
+
+import EditEventModal from "../../containers/EditEventModal";
+import MoveEventModal from "../../containers/MoveEventModal";
+import NewEventModal from "../../containers/NewEventModal";
+
+export type TimelineEventModalState =
+ | { type: "new" }
+ | { type: "edit"; eventId: TimelineEventId }
+ | { type: "move"; eventId: TimelineEventId };
+
+const getModalLabel = (type: TimelineEventModalState["type"]) =>
+ ({
+ new: t`New event`,
+ edit: t`Edit event`,
+ move: t`Move event`,
+ })[type];
+
+export function TimelineEventModals({
+ modal,
+ collectionId,
+ source,
+ onEventCreated,
+ onClose,
+}: {
+ modal: TimelineEventModalState | null;
+ collectionId: CollectionId | null | undefined;
+ source?: TimelineEventSource;
+ onEventCreated?: (event: TimelineEvent) => void;
+ onClose: () => void;
+}) {
+ // The edit/move containers render nothing until the event arrives, so the
+ // modal shows this query's loading and error states instead of a blank box.
+ const { isLoading, error } = useGetTimelineEventQuery(
+ modal && modal.type !== "new" ? modal.eventId : skipToken,
+ );
+
+ if (!modal) {
+ return null;
+ }
+
+ const content = match(modal)
+ .with({ type: "new" }, () => (
+ <NewEventModal
+ collectionId={collectionId}
+ source={source}
+ onEventCreated={onEventCreated}
+ onClose={onClose}
+ />
+ ))
+ .with({ type: "edit" }, ({ eventId }) => (
+ <EditEventModal eventId={eventId} onClose={onClose} />
+ ))
+ .with({ type: "move" }, ({ eventId }) => (
+ <MoveEventModal
+ eventId={eventId}
+ collectionId={collectionId}
+ onClose={onClose}
+ />
+ ))
+ .exhaustive();
+
+ return (
+ <Modal
+ opened
+ onClose={onClose}
+ size="lg"
+ withCloseButton={false}
+ padding={0}
+ aria-label={getModalLabel(modal.type)}
+ >
+ <LoadingAndErrorWrapper loading={isLoading} error={error}>
+ {content}
+ </LoadingAndErrorWrapper>
+ </Modal>
+ );
+}
diff --git a/frontend/src/metabase/timelines/panel/components/TimelineEventModals/index.ts b/frontend/src/metabase/timelines/panel/components/TimelineEventModals/index.ts
new file mode 100644
index 00000000000..a2b02df7be1
--- /dev/null
+++ b/frontend/src/metabase/timelines/panel/components/TimelineEventModals/index.ts
@@ -0,0 +1,4 @@
+export {
+ type TimelineEventModalState,
+ TimelineEventModals,
+} from "./TimelineEventModals";
diff --git a/frontend/src/metabase/timelines/questions/components/TimelineList/TimelineList.tsx b/frontend/src/metabase/timelines/panel/components/TimelineList/TimelineList.tsx
similarity index 81%
rename from frontend/src/metabase/timelines/questions/components/TimelineList/TimelineList.tsx
rename to frontend/src/metabase/timelines/panel/components/TimelineList/TimelineList.tsx
index 572ece353c0..e6d2e36698d 100644
--- a/frontend/src/metabase/timelines/questions/components/TimelineList/TimelineList.tsx
+++ b/frontend/src/metabase/timelines/panel/components/TimelineList/TimelineList.tsx
@@ -5,6 +5,7 @@ import { TimelineCard } from "../TimelineCard/TimelineCard";
export interface TimelineListProps {
timelines: Timeline[];
visibleEventIds: number[];
+ partiallyVisibleEventIds?: number[];
selectedEventIds?: number[];
onEditEvent?: (event: TimelineEvent) => void;
onMoveEvent?: (event: TimelineEvent) => void;
@@ -12,11 +13,14 @@ export interface TimelineListProps {
onToggleEventSelected?: (event: TimelineEvent, isSelected: boolean) => void;
onShowTimelineEvents: (timelineEvent: TimelineEvent[]) => void;
onHideTimelineEvents: (timelineEvent: TimelineEvent[]) => void;
+ onShowTimeline: (timeline: Timeline) => void;
+ onHideTimeline: (timeline: Timeline) => void;
}
const TimelineList = ({
timelines,
visibleEventIds,
+ partiallyVisibleEventIds,
selectedEventIds = [],
onEditEvent,
onMoveEvent,
@@ -24,6 +28,8 @@ const TimelineList = ({
onToggleEventSelected,
onShowTimelineEvents,
onHideTimelineEvents,
+ onShowTimeline,
+ onHideTimeline,
}: TimelineListProps): JSX.Element => {
return (
<div>
@@ -33,6 +39,7 @@ const TimelineList = ({
timeline={timeline}
isDefault={timelines.length === 1}
visibleEventIds={visibleEventIds}
+ partiallyVisibleEventIds={partiallyVisibleEventIds}
selectedEventIds={selectedEventIds}
onEditEvent={onEditEvent}
onMoveEvent={onMoveEvent}
@@ -40,6 +47,8 @@ const TimelineList = ({
onArchiveEvent={onArchiveEvent}
onShowTimelineEvents={onShowTimelineEvents}
onHideTimelineEvents={onHideTimelineEvents}
+ onShowTimeline={onShowTimeline}
+ onHideTimeline={onHideTimeline}
/>
))}
</div>
diff --git a/frontend/src/metabase/timelines/questions/components/TimelineList/TimelineList.unit.spec.tsx b/frontend/src/metabase/timelines/panel/components/TimelineList/TimelineList.unit.spec.tsx
similarity index 94%
rename from frontend/src/metabase/timelines/questions/components/TimelineList/TimelineList.unit.spec.tsx
rename to frontend/src/metabase/timelines/panel/components/TimelineList/TimelineList.unit.spec.tsx
index 4eb9e929eed..52f95e4d0ad 100644
--- a/frontend/src/metabase/timelines/questions/components/TimelineList/TimelineList.unit.spec.tsx
+++ b/frontend/src/metabase/timelines/panel/components/TimelineList/TimelineList.unit.spec.tsx
@@ -27,6 +27,8 @@ const getProps = (opts?: Partial<TimelineListProps>): TimelineListProps => ({
onArchiveEvent: jest.fn(),
onShowTimelineEvents: jest.fn(),
onHideTimelineEvents: jest.fn(),
+ onShowTimeline: jest.fn(),
+ onHideTimeline: jest.fn(),
...opts,
});
diff --git a/frontend/src/metabase/timelines/questions/components/TimelineList/index.ts b/frontend/src/metabase/timelines/panel/components/TimelineList/index.ts
similarity index 100%
rename from frontend/src/metabase/timelines/questions/components/TimelineList/index.ts
rename to frontend/src/metabase/timelines/panel/components/TimelineList/index.ts
diff --git a/frontend/src/metabase/timelines/questions/components/TimelinePanel/TimelinePanel.tsx b/frontend/src/metabase/timelines/panel/components/TimelinePanel/TimelinePanel.tsx
similarity index 85%
rename from frontend/src/metabase/timelines/questions/components/TimelinePanel/TimelinePanel.tsx
rename to frontend/src/metabase/timelines/panel/components/TimelinePanel/TimelinePanel.tsx
index ce5b9f9d024..eac4b2d733c 100644
--- a/frontend/src/metabase/timelines/questions/components/TimelinePanel/TimelinePanel.tsx
+++ b/frontend/src/metabase/timelines/panel/components/TimelinePanel/TimelinePanel.tsx
@@ -10,6 +10,7 @@ export interface TimelinePanelProps {
timelines: Timeline[];
collection: Collection;
visibleEventIds: number[];
+ partiallyVisibleEventIds?: number[];
selectedEventIds?: number[];
onNewEvent?: () => void;
onEditEvent?: (event: TimelineEvent) => void;
@@ -18,12 +19,15 @@ export interface TimelinePanelProps {
onToggleEventSelected?: (event: TimelineEvent, isSelected: boolean) => void;
onShowTimelineEvents: (timelineEvent: TimelineEvent[]) => void;
onHideTimelineEvents: (timelineEvent: TimelineEvent[]) => void;
+ onShowTimeline: (timeline: Timeline) => void;
+ onHideTimeline: (timeline: Timeline) => void;
}
const TimelinePanel = ({
timelines,
collection,
visibleEventIds,
+ partiallyVisibleEventIds,
selectedEventIds,
onNewEvent,
onEditEvent,
@@ -32,6 +36,8 @@ const TimelinePanel = ({
onToggleEventSelected,
onShowTimelineEvents,
onHideTimelineEvents,
+ onShowTimeline,
+ onHideTimeline,
}: TimelinePanelProps): JSX.Element => {
const isEmpty = timelines.length === 0;
const canWrite = collection.can_write;
@@ -48,6 +54,7 @@ const TimelinePanel = ({
<TimelineList
timelines={timelines}
visibleEventIds={visibleEventIds}
+ partiallyVisibleEventIds={partiallyVisibleEventIds}
selectedEventIds={selectedEventIds}
onEditEvent={onEditEvent}
onMoveEvent={onMoveEvent}
@@ -55,6 +62,8 @@ const TimelinePanel = ({
onArchiveEvent={onArchiveEvent}
onShowTimelineEvents={onShowTimelineEvents}
onHideTimelineEvents={onHideTimelineEvents}
+ onShowTimeline={onShowTimeline}
+ onHideTimeline={onHideTimeline}
/>
) : (
<TimelineEmptyState
diff --git a/frontend/src/metabase/timelines/questions/components/TimelinePanel/TimelinePanel.unit.spec.tsx b/frontend/src/metabase/timelines/panel/components/TimelinePanel/TimelinePanel.unit.spec.tsx
similarity index 97%
rename from frontend/src/metabase/timelines/questions/components/TimelinePanel/TimelinePanel.unit.spec.tsx
rename to frontend/src/metabase/timelines/panel/components/TimelinePanel/TimelinePanel.unit.spec.tsx
index c88899c282a..14c581cbc8b 100644
--- a/frontend/src/metabase/timelines/questions/components/TimelinePanel/TimelinePanel.unit.spec.tsx
+++ b/frontend/src/metabase/timelines/panel/components/TimelinePanel/TimelinePanel.unit.spec.tsx
@@ -71,6 +71,8 @@ const getProps = (opts?: Partial<TimelinePanelProps>): TimelinePanelProps => ({
onArchiveEvent: jest.fn(),
onShowTimelineEvents: jest.fn(),
onHideTimelineEvents: jest.fn(),
+ onShowTimeline: jest.fn(),
+ onHideTimeline: jest.fn(),
...opts,
});
diff --git a/frontend/src/metabase/timelines/questions/components/TimelinePanel/index.ts b/frontend/src/metabase/timelines/panel/components/TimelinePanel/index.ts
similarity index 100%
rename from frontend/src/metabase/timelines/questions/components/TimelinePanel/index.ts
rename to frontend/src/metabase/timelines/panel/components/TimelinePanel/index.ts
diff --git a/frontend/src/metabase/timelines/panel/components/TimelineSidebar/TimelineSidebar.tsx b/frontend/src/metabase/timelines/panel/components/TimelineSidebar/TimelineSidebar.tsx
new file mode 100644
index 00000000000..791c43d697d
--- /dev/null
+++ b/frontend/src/metabase/timelines/panel/components/TimelineSidebar/TimelineSidebar.tsx
@@ -0,0 +1,199 @@
+import { useCallback, useMemo, useState } from "react";
+import { t } from "ttag";
+
+import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";
+import { SidebarContent } from "metabase/common/components/SidebarContent";
+import { Box, Button, Icon } from "metabase/ui";
+import {
+ hideTimelineEvents,
+ showCreatedTimelineEvent,
+ showTimelineEvents,
+} from "metabase/visualizations/lib/timeline-events-visibility";
+import type {
+ TimelineEventsVisibilityIntent,
+ TimelineEventsVisibilityUpdate,
+} from "metabase/visualizations/types";
+import type { TimeseriesXAxis } from "metabase/viz-core";
+import type {
+ CollectionId,
+ Timeline,
+ TimelineEvent,
+ TimelineEventId,
+ TimelineEventSource,
+} from "metabase-types/api";
+
+import TimelinePanel from "../../containers/TimelinePanel";
+import {
+ filterTimelinesByXAxes,
+ getFocusedTimelines,
+ getTimelineSidebarTitle,
+} from "../../utils";
+import {
+ type TimelineEventModalState,
+ TimelineEventModals,
+} from "../TimelineEventModals";
+
+export interface TimelineSidebarProps {
+ collectionId: CollectionId | null | undefined;
+ timelines: Timeline[];
+ visibleEventIds: TimelineEventId[];
+ partiallyVisibleEventIds?: TimelineEventId[];
+ selectedEventIds: TimelineEventId[];
+ focusedEventIds?: TimelineEventId[] | null;
+ /** the axes of the charts this sidebar controls; events outside them are dropped */
+ xAxes?: TimeseriesXAxis[] | null;
+ isLoading?: boolean;
+ error?: unknown;
+ /** where events created from this sidebar are reported as coming from */
+ eventSource?: TimelineEventSource;
+ onUpdateVisibility: (
+ update: TimelineEventsVisibilityUpdate,
+ intent: TimelineEventsVisibilityIntent,
+ ) => void;
+ onSelectEvents: (events: TimelineEvent[]) => void;
+ onDeselectEvents: () => void;
+ onShowAllEvents?: () => void;
+ onClose: () => void;
+}
+
+export const TimelineSidebar = ({
+ collectionId,
+ timelines,
+ visibleEventIds,
+ partiallyVisibleEventIds,
+ selectedEventIds,
+ focusedEventIds = null,
+ xAxes = null,
+ isLoading = false,
+ error,
+ eventSource,
+ onUpdateVisibility,
+ onSelectEvents,
+ onDeselectEvents,
+ onShowAllEvents,
+ onClose,
+}: TimelineSidebarProps) => {
+ const [modal, setModal] = useState<TimelineEventModalState | null>(null);
+ const isFocused = focusedEventIds != null;
+
+ const displayedTimelines = useMemo(
+ () =>
+ getFocusedTimelines(
+ filterTimelinesByXAxes(timelines, xAxes),
+ focusedEventIds,
+ ),
+ [timelines, xAxes, focusedEventIds],
+ );
+
+ const title = getTimelineSidebarTitle({
+ focusedTimelines: displayedTimelines,
+ isFocused,
+ xAxis: xAxes?.length === 1 ? xAxes[0] : null,
+ });
+
+ const handleShowTimelineEvents = useCallback(
+ (events: TimelineEvent[]) =>
+ onUpdateVisibility(
+ (visibility, allTimelines) =>
+ showTimelineEvents(visibility, events, allTimelines),
+ "show",
+ ),
+ [onUpdateVisibility],
+ );
+
+ const handleHideTimelineEvents = useCallback(
+ (events: TimelineEvent[]) =>
+ onUpdateVisibility(
+ (visibility, allTimelines) =>
+ hideTimelineEvents(visibility, events, allTimelines),
+ "hide",
+ ),
+ [onUpdateVisibility],
+ );
+
+ // the header checkbox reflects the events the card lists, so it acts on those
+ const handleShowTimeline = useCallback(
+ (timeline: Timeline) => handleShowTimelineEvents(timeline.events ?? []),
+ [handleShowTimelineEvents],
+ );
+
+ const handleHideTimeline = useCallback(
+ (timeline: Timeline) => handleHideTimelineEvents(timeline.events ?? []),
+ [handleHideTimelineEvents],
+ );
+
+ const handleEventCreated = useCallback(
+ (event: TimelineEvent) =>
+ onUpdateVisibility(
+ (visibility, allTimelines) =>
+ showCreatedTimelineEvent(visibility, event, allTimelines),
+ "create",
+ ),
+ [onUpdateVisibility],
+ );
+
+ const handleToggleEventSelected = useCallback(
+ (event: TimelineEvent, isSelected: boolean) =>
+ isSelected ? onSelectEvents([event]) : onDeselectEvents(),
+ [onSelectEvents, onDeselectEvents],
+ );
+
+ const handleNewEvent = useCallback(() => setModal({ type: "new" }), []);
+ const handleEditEvent = useCallback(
+ (event: TimelineEvent) => setModal({ type: "edit", eventId: event.id }),
+ [],
+ );
+ const handleMoveEvent = useCallback(
+ (event: TimelineEvent) => setModal({ type: "move", eventId: event.id }),
+ [],
+ );
+ const handleCloseModal = useCallback(() => setModal(null), []);
+
+ return (
+ <>
+ <SidebarContent title={title} onClose={onClose}>
+ {isLoading || error != null ? (
+ <LoadingAndErrorWrapper loading={isLoading} error={error} />
+ ) : (
+ <>
+ {isFocused && onShowAllEvents && (
+ <Box mx="xl" mb="sm">
+ <Button
+ p={0}
+ variant="subtle"
+ leftSection={<Icon name="chevronleft" />}
+ onClick={onShowAllEvents}
+ data-testid="timeline-sidebar-show-all"
+ >
+ {t`All events`}
+ </Button>
+ </Box>
+ )}
+ <TimelinePanel
+ timelines={displayedTimelines}
+ collectionId={collectionId}
+ visibleEventIds={visibleEventIds}
+ partiallyVisibleEventIds={partiallyVisibleEventIds}
+ selectedEventIds={selectedEventIds}
+ onNewEvent={handleNewEvent}
+ onEditEvent={handleEditEvent}
+ onMoveEvent={handleMoveEvent}
+ onShowTimelineEvents={handleShowTimelineEvents}
+ onHideTimelineEvents={handleHideTimelineEvents}
+ onShowTimeline={handleShowTimeline}
+ onHideTimeline={handleHideTimeline}
+ onToggleEventSelected={handleToggleEventSelected}
+ />
+ </>
+ )}
+ </SidebarContent>
+ <TimelineEventModals
+ modal={modal}
+ collectionId={collectionId}
+ source={eventSource}
+ onEventCreated={handleEventCreated}
+ onClose={handleCloseModal}
+ />
+ </>
+ );
+};
diff --git a/frontend/src/metabase/timelines/panel/components/TimelineSidebar/TimelineSidebar.unit.spec.tsx b/frontend/src/metabase/timelines/panel/components/TimelineSidebar/TimelineSidebar.unit.spec.tsx
new file mode 100644
index 00000000000..a37161c64bf
--- /dev/null
+++ b/frontend/src/metabase/timelines/panel/components/TimelineSidebar/TimelineSidebar.unit.spec.tsx
@@ -0,0 +1,79 @@
+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 {
+ createMockCollection,
+ createMockTimeline,
+ createMockTimelineEvent,
+} from "metabase-types/api/mocks";
+
+import { TimelineSidebar, type TimelineSidebarProps } from "./TimelineSidebar";
+
+const getProps = (
+ opts?: Partial<TimelineSidebarProps>,
+): TimelineSidebarProps => ({
+ collectionId: "root",
+ timelines: [],
+ visibleEventIds: [],
+ selectedEventIds: [],
+ onUpdateVisibility: jest.fn(),
+ onSelectEvents: jest.fn(),
+ onDeselectEvents: jest.fn(),
+ onClose: jest.fn(),
+ ...opts,
+});
+
+describe("TimelineSidebar", () => {
+ beforeEach(() => {
+ setupCollectionByIdEndpoint({
+ collections: [
+ createMockCollection({ ...ROOT_COLLECTION, can_write: true }),
+ ],
+ });
+ });
+
+ it("opens the new event modal", 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
+ {...getProps({ timelines: [timeline], visibleEventIds: [1] })}
+ />,
+ );
+
+ expect(await screen.findByText("Create event")).toBeInTheDocument();
+ await userEvent.click(screen.getByText("Create event"));
+ expect(await screen.findByRole("dialog")).toBeInTheDocument();
+ });
+
+ it("waits for the timelines instead of offering to create the first event", () => {
+ renderWithProviders(<TimelineSidebar {...getProps({ isLoading: true })} />);
+
+ expect(screen.getByText("Loading...")).toBeInTheDocument();
+ expect(
+ screen.queryByText("Add context to your time series charts"),
+ ).not.toBeInTheDocument();
+ });
+
+ it("reports a failed load instead of claiming there are no events", () => {
+ renderWithProviders(
+ <TimelineSidebar
+ {...getProps({ error: { data: "Timelines are unavailable" } })}
+ />,
+ );
+
+ expect(screen.getByText("Timelines are unavailable")).toBeInTheDocument();
+ expect(
+ screen.queryByText("Add context to your time series charts"),
+ ).not.toBeInTheDocument();
+ });
+});
diff --git a/frontend/src/metabase/timelines/questions/components/TimelineSidebar/index.ts b/frontend/src/metabase/timelines/panel/components/TimelineSidebar/index.ts
similarity index 100%
rename from frontend/src/metabase/timelines/questions/components/TimelineSidebar/index.ts
rename to frontend/src/metabase/timelines/panel/components/TimelineSidebar/index.ts
diff --git a/frontend/src/metabase/timelines/questions/containers/EditEventModal/EditEventModal.tsx b/frontend/src/metabase/timelines/panel/containers/EditEventModal/EditEventModal.tsx
similarity index 100%
rename from frontend/src/metabase/timelines/questions/containers/EditEventModal/EditEventModal.tsx
rename to frontend/src/metabase/timelines/panel/containers/EditEventModal/EditEventModal.tsx
diff --git a/frontend/src/metabase/timelines/questions/containers/EditEventModal/index.ts b/frontend/src/metabase/timelines/panel/containers/EditEventModal/index.ts
similarity index 100%
rename from frontend/src/metabase/timelines/questions/containers/EditEventModal/index.ts
rename to frontend/src/metabase/timelines/panel/containers/EditEventModal/index.ts
diff --git a/frontend/src/metabase/timelines/questions/containers/MoveEventModal/MoveEventModal.tsx b/frontend/src/metabase/timelines/panel/containers/MoveEventModal/MoveEventModal.tsx
similarity index 100%
rename from frontend/src/metabase/timelines/questions/containers/MoveEventModal/MoveEventModal.tsx
rename to frontend/src/metabase/timelines/panel/containers/MoveEventModal/MoveEventModal.tsx
diff --git a/frontend/src/metabase/timelines/questions/containers/MoveEventModal/index.ts b/frontend/src/metabase/timelines/panel/containers/MoveEventModal/index.ts
similarity index 100%
rename from frontend/src/metabase/timelines/questions/containers/MoveEventModal/index.ts
rename to frontend/src/metabase/timelines/panel/containers/MoveEventModal/index.ts
diff --git a/frontend/src/metabase/timelines/questions/containers/NewEventModal/NewEventModal.tsx b/frontend/src/metabase/timelines/panel/containers/NewEventModal/NewEventModal.tsx
similarity index 75%
rename from frontend/src/metabase/timelines/questions/containers/NewEventModal/NewEventModal.tsx
rename to frontend/src/metabase/timelines/panel/containers/NewEventModal/NewEventModal.tsx
index 4948434672b..9255ce01f80 100644
--- a/frontend/src/metabase/timelines/questions/containers/NewEventModal/NewEventModal.tsx
+++ b/frontend/src/metabase/timelines/panel/containers/NewEventModal/NewEventModal.tsx
@@ -14,19 +14,22 @@ import NewEventModal from "metabase/timelines/common/components/NewEventModal";
import type {
Collection,
CollectionId,
- CreateTimelineEventRequest,
- CreateTimelineRequest,
TimelineEvent,
+ TimelineEventData,
+ TimelineEventSource,
} from "metabase-types/api";
interface NewEventModalContainerProps {
- cardId?: number;
collectionId?: CollectionId | null;
+ source?: TimelineEventSource;
+ onEventCreated?: (event: TimelineEvent) => void;
onClose?: () => void;
}
function NewEventModalContainer({
collectionId,
+ source = "question",
+ onEventCreated,
onClose,
}: NewEventModalContainerProps) {
const dispatch = useDispatch();
@@ -38,29 +41,31 @@ function NewEventModalContainer({
});
const onSubmit = async (
- values: Partial<TimelineEvent>,
+ values: TimelineEventData,
collection?: Collection,
) => {
- if (values.timeline_id) {
- // Unjustified type cast. FIXME
- await createTimelineEvent(values as CreateTimelineEventRequest).unwrap();
+ if (values.timeline_id != null) {
+ const event = await createTimelineEvent({
+ ...values,
+ timeline_id: values.timeline_id,
+ }).unwrap();
+ onEventCreated?.(event);
} else if (collection) {
const timeline = await createTimeline(
- // Unjustified type cast. FIXME
- getDefaultTimeline(collection) as CreateTimelineRequest,
+ getDefaultTimeline(collection),
).unwrap();
- // Unjustified type cast. FIXME
- await createTimelineEvent({
+ const event = await createTimelineEvent({
...values,
timeline_id: timeline.id,
- } as CreateTimelineEventRequest).unwrap();
+ }).unwrap();
+ onEventCreated?.(event);
}
dispatch(addUndo({ message: t`Created event` }));
};
return (
<NewEventModal
- source="question"
+ source={source}
timelines={timelines}
collection={collection}
onSubmit={onSubmit}
diff --git a/frontend/src/metabase/timelines/questions/containers/NewEventModal/index.ts b/frontend/src/metabase/timelines/panel/containers/NewEventModal/index.ts
similarity index 100%
rename from frontend/src/metabase/timelines/questions/containers/NewEventModal/index.ts
rename to frontend/src/metabase/timelines/panel/containers/NewEventModal/index.ts
diff --git a/frontend/src/metabase/timelines/questions/containers/TimelinePanel/TimelinePanel.tsx b/frontend/src/metabase/timelines/panel/containers/TimelinePanel/TimelinePanel.tsx
similarity index 100%
rename from frontend/src/metabase/timelines/questions/containers/TimelinePanel/TimelinePanel.tsx
rename to frontend/src/metabase/timelines/panel/containers/TimelinePanel/TimelinePanel.tsx
diff --git a/frontend/src/metabase/timelines/questions/containers/TimelinePanel/index.ts b/frontend/src/metabase/timelines/panel/containers/TimelinePanel/index.ts
similarity index 100%
rename from frontend/src/metabase/timelines/questions/containers/TimelinePanel/index.ts
rename to frontend/src/metabase/timelines/panel/containers/TimelinePanel/index.ts
diff --git a/frontend/src/metabase/timelines/panel/selectors.ts b/frontend/src/metabase/timelines/panel/selectors.ts
new file mode 100644
index 00000000000..a74f7a59964
--- /dev/null
+++ b/frontend/src/metabase/timelines/panel/selectors.ts
@@ -0,0 +1,26 @@
+import { createSelector } from "@reduxjs/toolkit";
+
+import { timelineApi } from "metabase/api";
+import type { ListTimelinesRequest, Timeline } from "metabase-types/api";
+
+import { transformTimelines } from "./utils";
+
+const NO_TIMELINES: Timeline[] = [];
+
+export const LIST_TIMELINES_REQUEST: ListTimelinesRequest = {
+ include: "events",
+};
+
+export const selectListTimelines = timelineApi.endpoints.listTimelines.select(
+ LIST_TIMELINES_REQUEST,
+);
+
+export const getFetchedTimelines = createSelector(
+ [selectListTimelines],
+ (result): Timeline[] => result.data ?? NO_TIMELINES,
+);
+
+export const getTransformedTimelines = createSelector(
+ [getFetchedTimelines],
+ transformTimelines,
+);
diff --git a/frontend/src/metabase/timelines/panel/utils.ts b/frontend/src/metabase/timelines/panel/utils.ts
new file mode 100644
index 00000000000..9044cb1baaf
--- /dev/null
+++ b/frontend/src/metabase/timelines/panel/utils.ts
@@ -0,0 +1,130 @@
+import { updateIn } from "icepick";
+import { t } from "ttag";
+import _ from "underscore";
+
+import { getSortedTimelines } from "metabase/common/utils/timelines";
+import { type Dayjs, dayjs } from "metabase/dayjs";
+import { formatDateTimeWithUnit } from "metabase/value-formatting";
+import {
+ type CartesianChartDateTimeAbsoluteUnit,
+ type DateRange,
+ type TimeseriesXAxis,
+ isTimelineEventInRange,
+} from "metabase/viz-core";
+import type {
+ DateTimeAbsoluteUnit,
+ Timeline,
+ TimelineEvent,
+ TimelineEventId,
+} from "metabase-types/api";
+import { isAbsoluteDateTimeUnit } from "metabase-types/guards/date-time";
+
+export const transformTimelines = (timelines: Timeline[]): Timeline[] =>
+ getSortedTimelines(
+ timelines.map((timeline) =>
+ updateIn(timeline, ["events"], (events: TimelineEvent[] = []) =>
+ _.chain(events)
+ .filter((event) => !event.archived)
+ .value(),
+ ),
+ ),
+ );
+
+const filterTimelineEvents = (
+ timelines: Timeline[],
+ predicate: (event: TimelineEvent) => boolean,
+): Timeline[] =>
+ timelines
+ .map((timeline) => ({
+ ...timeline,
+ events: (timeline.events ?? []).filter(predicate),
+ }))
+ .filter((timeline) => timeline.events.length > 0);
+
+export const getNonEmptyTimelines = (timelines: Timeline[]): Timeline[] =>
+ timelines.filter((timeline) => (timeline.events ?? []).length > 0);
+
+/** keeps the events at least one of the charts can render */
+export const filterTimelinesByXAxes = (
+ timelines: Timeline[],
+ xAxes: TimeseriesXAxis[] | null | undefined,
+): Timeline[] => {
+ const ranges = (xAxes ?? []).flatMap(({ domain, interval }) =>
+ domain ? [{ domain, interval }] : [],
+ );
+ if (ranges.length === 0) {
+ return getNonEmptyTimelines(timelines);
+ }
+ return filterTimelineEvents(timelines, (event) =>
+ ranges.some(({ domain, interval }) =>
+ isTimelineEventInRange(event, domain, interval),
+ ),
+ );
+};
+
+export const getFocusedTimelines = (
+ timelines: Timeline[],
+ focusedTimelineEventIds: TimelineEventId[] | null,
+): Timeline[] => {
+ if (focusedTimelineEventIds == null) {
+ return timelines;
+ }
+ const focusedIds = new Set(focusedTimelineEventIds);
+ return filterTimelineEvents(timelines, (event) => focusedIds.has(event.id));
+};
+
+export const getEventsXDomain = (
+ timelines: Timeline[],
+): DateRange | 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];
+};
+
+export const getTimelineSidebarTitle = ({
+ focusedTimelines,
+ isFocused,
+ xAxis,
+}: {
+ focusedTimelines: Timeline[];
+ isFocused: boolean;
+ xAxis: TimeseriesXAxis | null | undefined;
+}) =>
+ isFocused
+ ? formatTitle(getEventsXDomain(focusedTimelines), xAxis?.interval?.unit)
+ : formatTitle(xAxis?.domain ?? undefined);
+
+const isPeriodUnit = (unit: DateTimeAbsoluteUnit) =>
+ unit === "week" || unit === "month" || unit === "quarter" || unit === "year";
+
+export const formatTitle = (
+ xDomain?: DateRange,
+ unit?: CartesianChartDateTimeAbsoluteUnit,
+) => {
+ if (!xDomain) {
+ return t`Events`;
+ }
+ const bucketUnit = isAbsoluteDateTimeUnit(unit) ? unit : undefined;
+ const startLabel = formatDate(xDomain[0], bucketUnit);
+ const endLabel = formatDate(xDomain[1], bucketUnit);
+ if (startLabel !== endLabel) {
+ return t`Events between ${startLabel} and ${endLabel}`;
+ }
+
+ return bucketUnit && isPeriodUnit(bucketUnit)
+ ? t`Events in ${startLabel}`
+ : t`Events on ${startLabel}`;
+};
+
+const formatDate = (date: Dayjs, unit?: DateTimeAbsoluteUnit) =>
+ unit == null
+ ? date.format("ll")
+ : formatDateTimeWithUnit(date.startOf(unit), unit);
diff --git a/frontend/src/metabase/timelines/panel/utils.unit.spec.ts b/frontend/src/metabase/timelines/panel/utils.unit.spec.ts
new file mode 100644
index 00000000000..b852fb0f24e
--- /dev/null
+++ b/frontend/src/metabase/timelines/panel/utils.unit.spec.ts
@@ -0,0 +1,260 @@
+import { dayjs } from "metabase/dayjs";
+import type { TimeseriesXAxis } from "metabase/viz-core";
+import {
+ createMockTimeline,
+ createMockTimelineEvent,
+} from "metabase-types/api/mocks";
+
+import {
+ filterTimelinesByXAxes,
+ formatTitle,
+ getEventsXDomain,
+ getFocusedTimelines,
+ getNonEmptyTimelines,
+ transformTimelines,
+} from "./utils";
+
+const releases = createMockTimeline({
+ id: 1,
+ name: "Releases",
+ events: [
+ createMockTimelineEvent({ id: 1, name: "RC1" }),
+ createMockTimelineEvent({ id: 2, name: "RC2" }),
+ ],
+});
+
+const marketing = createMockTimeline({
+ id: 2,
+ name: "Marketing",
+ events: [createMockTimelineEvent({ id: 3, name: "Launch" })],
+});
+
+describe("getFocusedTimelines", () => {
+ it("returns all timelines unchanged when there is no focus", () => {
+ expect(getFocusedTimelines([releases, marketing], null)).toEqual([
+ releases,
+ marketing,
+ ]);
+ });
+
+ it("keeps only the focused events within each timeline", () => {
+ const result = getFocusedTimelines([releases, marketing], [2]);
+ expect(result).toHaveLength(1);
+ expect(result[0].name).toBe("Releases");
+ expect(result[0].events?.map((event) => event.id)).toEqual([2]);
+ });
+
+ it("drops timelines that have no focused events", () => {
+ const result = getFocusedTimelines([releases, marketing], [3]);
+ expect(result.map((timeline) => timeline.name)).toEqual(["Marketing"]);
+ });
+
+ it("can focus events across multiple timelines", () => {
+ const result = getFocusedTimelines([releases, marketing], [1, 3]);
+ expect(result.map((timeline) => timeline.name)).toEqual([
+ "Releases",
+ "Marketing",
+ ]);
+ expect(result[0].events?.map((event) => event.id)).toEqual([1]);
+ expect(result[1].events?.map((event) => event.id)).toEqual([3]);
+ });
+});
+
+describe("getNonEmptyTimelines", () => {
+ it("drops timelines without events", () => {
+ const empty = createMockTimeline({ id: 3, name: "Empty", events: [] });
+ expect(getNonEmptyTimelines([releases, empty, marketing])).toEqual([
+ releases,
+ marketing,
+ ]);
+ });
+});
+
+describe("getEventsXDomain", () => {
+ it("returns undefined when there are no events", () => {
+ expect(
+ getEventsXDomain([createMockTimeline({ events: [] })]),
+ ).toBeUndefined();
+ });
+
+ it("returns the min and max event timestamps across timelines", () => {
+ const timelines = [
+ createMockTimeline({
+ events: [
+ createMockTimelineEvent({ timestamp: "2027-06-15T00:00:00Z" }),
+ createMockTimelineEvent({ timestamp: "2027-06-03T00:00:00Z" }),
+ ],
+ }),
+ createMockTimeline({
+ events: [
+ createMockTimelineEvent({ timestamp: "2027-06-27T00:00:00Z" }),
+ ],
+ }),
+ ];
+
+ const domain = getEventsXDomain(timelines);
+ expect(domain?.[0].toISOString()).toBe("2027-06-03T00:00:00.000Z");
+ expect(domain?.[1].toISOString()).toBe("2027-06-27T00:00:00.000Z");
+ expect(domain?.[0].utcOffset()).toBe(0);
+ });
+});
+
+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");
+
+ it("returns a generic title without a domain", () => {
+ expect(formatTitle()).toBe("Events");
+ });
+
+ it("snaps same-week dates to one week bucket (Jun 7 and Jun 10 are both the week of Jun 6)", () => {
+ const june7 = dayjs.utc("2027-06-07T00:00:00Z");
+ const june10 = dayjs.utc("2027-06-10T00:00:00Z");
+ expect(formatTitle([june7, june10], "week")).toBe("Events in June 6, 2027");
+ });
+
+ it("buckets a single month group to the chart granularity", () => {
+ expect(formatTitle([june3, june27], "month")).toBe("Events in June 2027");
+ });
+
+ it("buckets a single year group to the chart granularity", () => {
+ expect(formatTitle([june3, june27], "year")).toBe("Events in 2027");
+ });
+
+ it("uses 'on' for a single day", () => {
+ expect(formatTitle([june3, june3], "day")).toBe("Events on June 3, 2027");
+ });
+
+ it("shows a bucket range when the group spans multiple buckets", () => {
+ expect(formatTitle([june27, july5], "month")).toBe(
+ "Events between June 2027 and July 2027",
+ );
+ });
+
+ it("falls back to specific dates without a unit", () => {
+ expect(formatTitle([june3, june27])).toBe(
+ "Events between Jun 3, 2027 and Jun 27, 2027",
+ );
+ });
+});
+
+describe("transformTimelines", () => {
+ it("drops archived events", () => {
+ const [timeline] = transformTimelines([
+ createMockTimeline({
+ events: [
+ createMockTimelineEvent({ id: 1 }),
+ createMockTimelineEvent({ id: 2, archived: true }),
+ ],
+ }),
+ ]);
+
+ expect(timeline.events?.map((event) => event.id)).toEqual([1]);
+ });
+
+ it("keeps event timestamps as the strings the API returned", () => {
+ const [timeline] = transformTimelines([
+ createMockTimeline({
+ events: [
+ createMockTimelineEvent({ timestamp: "2024-03-01T00:45:00-08:00" }),
+ ],
+ }),
+ ]);
+
+ expect(timeline.events?.[0].timestamp).toBe("2024-03-01T00:45:00-08:00");
+ });
+});
+
+describe("filterTimelinesByXAxes", () => {
+ const timelines = transformTimelines([
+ createMockTimeline({
+ id: 1,
+ events: [
+ createMockTimelineEvent({ id: 1, timestamp: "2024-01-15T00:00:00Z" }),
+ createMockTimelineEvent({ id: 2, timestamp: "2024-03-20T00:00:00Z" }),
+ createMockTimelineEvent({ id: 3, timestamp: "2024-06-01T00:00:00Z" }),
+ createMockTimelineEvent({ id: 5, timestamp: "2024-04-10T00:00:00Z" }),
+ ],
+ }),
+ createMockTimeline({
+ id: 2,
+ events: [
+ createMockTimelineEvent({ id: 4, timestamp: "2020-01-01T00:00:00Z" }),
+ ],
+ }),
+ ]);
+ const domain: [dayjs.Dayjs, dayjs.Dayjs] = [
+ dayjs("2024-01-01T00:00:00Z"),
+ dayjs("2024-03-01T00:00:00Z"),
+ ];
+
+ const filterIds = (xAxes: TimeseriesXAxis[] | null) =>
+ filterTimelinesByXAxes(timelines, xAxes).flatMap((timeline) =>
+ (timeline.events ?? []).map((event) => event.id),
+ );
+
+ it("keeps events up to the end of the last period and drops empty timelines", () => {
+ expect(
+ filterIds([{ domain, interval: { count: 1, unit: "month" } }]),
+ ).toEqual([1, 2]);
+ });
+
+ it("keeps events in the rest of a multi-unit final bucket", () => {
+ // the last bucket starts 2024-03-01 and spans two months, so an April event belongs to it
+ expect(
+ filterIds([{ domain, interval: { count: 2, unit: "month" } }]),
+ ).toEqual([1, 2, 5]);
+ });
+
+ it("extends by whole intervals for sub-day units", () => {
+ expect(
+ filterIds([{ domain, interval: { count: 6, unit: "hour" } }]),
+ ).toEqual([1]);
+ });
+
+ it("keeps an event later in the last day, like the chart does", () => {
+ const [timeline] = transformTimelines([
+ createMockTimeline({
+ id: 1,
+ events: [
+ createMockTimelineEvent({ id: 1, timestamp: "2024-03-01T00:45:00Z" }),
+ createMockTimelineEvent({ id: 2, timestamp: "2024-03-02T00:45:00Z" }),
+ ],
+ }),
+ ]);
+ const [filtered] = filterTimelinesByXAxes(
+ [timeline],
+ [
+ {
+ domain: [
+ dayjs("2024-01-01T00:30:00Z"),
+ dayjs("2024-03-01T00:30:00Z"),
+ ],
+ interval: { count: 1, unit: "day" },
+ },
+ ],
+ );
+ expect(filtered.events?.map((event) => event.id)).toEqual([1]);
+ });
+
+ it("keeps an event that falls in any one of the chart ranges", () => {
+ expect(
+ filterIds([
+ { domain, interval: { count: 1, unit: "month" } },
+ {
+ domain: [
+ dayjs("2019-12-01T00:00:00Z"),
+ dayjs("2020-02-01T00:00:00Z"),
+ ],
+ interval: { count: 1, unit: "month" },
+ },
+ ]),
+ ).toEqual([1, 2, 4]);
+ });
+
+ it("returns non-empty timelines untouched without an axis", () => {
+ const filtered = filterTimelinesByXAxes(timelines, null);
+ expect(filtered.map((timeline) => timeline.id)).toEqual([1, 2]);
+ });
+});
diff --git a/frontend/src/metabase/timelines/questions/components/TimelineSidebar/TimelineSidebar.tsx b/frontend/src/metabase/timelines/questions/components/TimelineSidebar/TimelineSidebar.tsx
deleted file mode 100644
index b5fbc30705c..00000000000
--- a/frontend/src/metabase/timelines/questions/components/TimelineSidebar/TimelineSidebar.tsx
+++ /dev/null
@@ -1,271 +0,0 @@
-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 } from "metabase/querying/constants";
-import type { QueryModalType } from "metabase/redux/store";
-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/viz-core";
-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="xl" mb="md">
- <Button
- variant="transparent"
- size="compact-md"
- 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/timelines/questions/components/TimelineSidebar/TimelineSidebar.unit.spec.tsx b/frontend/src/metabase/timelines/questions/components/TimelineSidebar/TimelineSidebar.unit.spec.tsx
deleted file mode 100644
index cb6242ad18b..00000000000
--- a/frontend/src/metabase/timelines/questions/components/TimelineSidebar/TimelineSidebar.unit.spec.tsx
+++ /dev/null
@@ -1,169 +0,0 @@
-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,
-} from "./TimelineSidebar";
-
-const releases = createMockTimeline({
- id: 1,
- name: "Releases",
- events: [
- createMockTimelineEvent({ id: 1, name: "RC1" }),
- createMockTimelineEvent({ id: 2, name: "RC2" }),
- ],
-});
-
-const marketing = createMockTimeline({
- id: 2,
- name: "Marketing",
- events: [createMockTimelineEvent({ id: 3, name: "Launch" })],
-});
-
-describe("getFocusedTimelines", () => {
- it("returns all timelines unchanged when there is no focus", () => {
- expect(getFocusedTimelines([releases, marketing], null)).toEqual([
- releases,
- marketing,
- ]);
- });
-
- it("keeps only the focused events within each timeline", () => {
- const result = getFocusedTimelines([releases, marketing], [2]);
- expect(result).toHaveLength(1);
- expect(result[0].name).toBe("Releases");
- expect(result[0].events?.map((event) => event.id)).toEqual([2]);
- });
-
- it("drops timelines that have no focused events", () => {
- const result = getFocusedTimelines([releases, marketing], [3]);
- expect(result.map((timeline) => timeline.name)).toEqual(["Marketing"]);
- });
-
- it("can focus events across multiple timelines", () => {
- const result = getFocusedTimelines([releases, marketing], [1, 3]);
- expect(result.map((timeline) => timeline.name)).toEqual([
- "Releases",
- "Marketing",
- ]);
- expect(result[0].events?.map((event) => event.id)).toEqual([1]);
- expect(result[1].events?.map((event) => event.id)).toEqual([3]);
- });
-});
-
-describe("getEventsXDomain", () => {
- it("returns undefined when there are no events", () => {
- expect(
- getEventsXDomain([createMockTimeline({ events: [] })]),
- ).toBeUndefined();
- });
-
- it("returns the min and max event timestamps across timelines", () => {
- const timelines = [
- createMockTimeline({
- events: [
- createMockTimelineEvent({ timestamp: "2027-06-15T00:00:00Z" }),
- createMockTimelineEvent({ timestamp: "2027-06-03T00:00:00Z" }),
- ],
- }),
- createMockTimeline({
- events: [
- createMockTimelineEvent({ timestamp: "2027-06-27T00:00:00Z" }),
- ],
- }),
- ];
-
- const domain = getEventsXDomain(timelines);
- expect(domain?.[0].toISOString()).toBe("2027-06-03T00:00:00.000Z");
- expect(domain?.[1].toISOString()).toBe("2027-06-27T00:00:00.000Z");
- expect(domain?.[0].utcOffset()).toBe(0);
- });
-});
-
-describe("formatTitle", () => {
- 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");
- });
-
- it("snaps same-week dates to one week bucket (Jun 7 and Jun 10 are both the week of Jun 6)", () => {
- const june7 = dayjs.utc("2027-06-07T00:00:00Z");
- const june10 = dayjs.utc("2027-06-10T00:00:00Z");
- expect(formatTitle([june7, june10], "week")).toBe("Events in June 6, 2027");
- });
-
- it("buckets a single month group to the chart granularity", () => {
- expect(formatTitle([june3, june27], "month")).toBe("Events in June 2027");
- });
-
- it("buckets a single year group to the chart granularity", () => {
- expect(formatTitle([june3, june27], "year")).toBe("Events in 2027");
- });
-
- it("uses 'on' for a single day", () => {
- expect(formatTitle([june3, june3], "day")).toBe("Events on June 3, 2027");
- });
-
- it("shows a bucket range when the group spans multiple buckets", () => {
- expect(formatTitle([june27, july5], "month")).toBe(
- "Events between June 2027 and July 2027",
- );
- });
-
- it("falls back to specific dates without a unit", () => {
- expect(formatTitle([june3, june27])).toBe(
- "Events between Jun 3, 2027 and Jun 27, 2027",
- );
- });
-});
-
-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/visualizations/components/Visualization/Visualization.tsx b/frontend/src/metabase/visualizations/components/Visualization/Visualization.tsx
index 1b46d779ec5..6893a0b00a7 100644
--- a/frontend/src/metabase/visualizations/components/Visualization/Visualization.tsx
+++ b/frontend/src/metabase/visualizations/components/Visualization/Visualization.tsx
@@ -71,6 +71,7 @@ import type {
SeriesCard,
SingleSeries,
TimelineEvent,
+ TimelineEventsVisibility,
VirtualCard,
VisualizationSettings,
} from "metabase-types/api";
@@ -165,6 +166,9 @@ type VisualizationOwnProps = {
hideLegend?: boolean;
style?: CSSProperties;
timelineEvents?: TimelineEvent[];
+ timelineEventsVisibility?: TimelineEventsVisibility;
+ onTimelineEventsShown?: () => void;
+ onTimelineEventsEnabledChange?: (isEnabled: boolean) => void;
tc?: ContentTranslationFunction;
zoomedRowIndex?: number;
onZoomRow?: (rowIndex: number) => void;
@@ -689,12 +693,15 @@ class Visualization extends PureComponent<
style,
tableHeaderHeight,
timelineEvents,
+ timelineEventsVisibility,
totalNumGridCols,
onDeselectTimelineEvents,
onOpenChartSettings,
onOpenTimelines,
onSelectTimelineEvents,
onSeeAllEvents,
+ onTimelineEventsShown,
+ onTimelineEventsEnabledChange,
onTogglePreviewing,
onUpdateVisualizationSettings = () => {},
onUpdateWarnings,
@@ -964,6 +971,11 @@ class Visualization extends PureComponent<
showTitle={!!showTitle}
tableHeaderHeight={tableHeaderHeight}
timelineEvents={timelineEvents}
+ timelineEventsVisibility={timelineEventsVisibility}
+ onTimelineEventsShown={onTimelineEventsShown}
+ onTimelineEventsEnabledChange={
+ onTimelineEventsEnabledChange
+ }
totalNumGridCols={totalNumGridCols}
visualizationIsClickable={this.visualizationIsClickable}
width={width}
diff --git a/frontend/src/metabase/visualizations/hooks/use-timeline-events.ts b/frontend/src/metabase/visualizations/hooks/use-timeline-events.ts
index 780b7bfcf06..a7427dae30a 100644
--- a/frontend/src/metabase/visualizations/hooks/use-timeline-events.ts
+++ b/frontend/src/metabase/visualizations/hooks/use-timeline-events.ts
@@ -1,13 +1,39 @@
-import { useMemo } from "react";
+import { useEffect, useMemo } from "react";
import { skipToken, useListTimelinesQuery } from "metabase/api";
-import type { VisualizationProps } from "metabase/visualizations/types";
-import type { TimelineEvent } from "metabase-types/api";
+import { isEmbeddingSdk } from "metabase/embedding-sdk/config";
+import {
+ isPublicEmbedding,
+ isStaticEmbedding,
+} from "metabase/embedding/config";
+import {
+ getRecordedTimelineEventsVisibility,
+ isTimelineEventsEnabled,
+ resolveVisibleTimelineEvents,
+} from "metabase/visualizations/lib/timeline-events-visibility";
+import {
+ type ComputedVisualizationSettings,
+ getTimeseriesXAxis,
+ isTimelineEventInRange,
+} from "metabase/viz-core";
+import type {
+ Series,
+ Timeline,
+ TimelineEvent,
+ TimelineEventsVisibility,
+} from "metabase-types/api";
-type UseTimelineEventsProps = Pick<
- VisualizationProps,
- "timelineEvents" | "settings"
->;
+interface UseTimelineEventsProps {
+ series: Series;
+ settings: ComputedVisualizationSettings;
+ timelineEvents?: TimelineEvent[];
+ timelineEventsVisibility?: TimelineEventsVisibility;
+ onTimelineEventsShown?: () => void;
+ onTimelineEventsEnabledChange?: (isEnabled: boolean) => void;
+ isDashboard?: boolean;
+ width?: number;
+ height?: number;
+}
interface UseTimelineEventsResult {
timelineEvents: TimelineEvent[];
@@ -15,60 +41,79 @@ interface UseTimelineEventsResult {
isError: boolean;
}
-// stable reference to avoid triggering re-renders
+// stable references to avoid triggering re-renders
const EMPTY_EVENTS: TimelineEvent[] = [];
+const NO_TIMELINES: Timeline[] = [];
+
+const canLoadTimelineEvents = (isDashboard: boolean) =>
+ !isPublicEmbedding() &&
+ !isStaticEmbedding() &&
+ (!isEmbeddingSdk() || isDashboard);
export function useTimelineEvents({
- timelineEvents: timelineEventsProp,
+ timelineEvents: explicitEvents,
+ timelineEventsVisibility,
settings,
+ series,
+ onTimelineEventsShown,
+ onTimelineEventsEnabledChange,
+ isDashboard = false,
+ width = 0,
+ height = 0,
}: UseTimelineEventsProps): UseTimelineEventsResult {
- const selectedTimelineIds = settings["timeline.selected_timeline_ids"];
- const excludedTimelineEventIds =
- settings["timeline.excluded_timeline_event_ids"];
+ const isEnabled = isTimelineEventsEnabled(settings);
+ const visibility = isEnabled
+ ? (timelineEventsVisibility ??
+ getRecordedTimelineEventsVisibility(settings))
+ : undefined;
+ const hasSelection =
+ (visibility?.["timeline.selected_timeline_ids"]?.length ?? 0) > 0;
const shouldFetch =
- !timelineEventsProp &&
- selectedTimelineIds != null &&
- selectedTimelineIds.length > 0;
+ isEnabled &&
+ !explicitEvents &&
+ hasSelection &&
+ canLoadTimelineEvents(isDashboard);
const {
- data: timelines = [],
+ data: timelines = NO_TIMELINES,
isLoading,
isError,
- } = useListTimelinesQuery(
- shouldFetch
- ? {
- include: "events",
- }
- : skipToken,
- );
+ } = useListTimelinesQuery(shouldFetch ? { include: "events" } : skipToken);
const timelineEvents = useMemo(() => {
- if (timelineEventsProp) {
- return timelineEventsProp;
+ if (!isEnabled) {
+ return EMPTY_EVENTS;
}
-
- if (!selectedTimelineIds || selectedTimelineIds.length === 0) {
+ const candidates =
+ explicitEvents ?? resolveVisibleTimelineEvents({ timelines, visibility });
+ if (candidates.length === 0) {
return EMPTY_EVENTS;
}
+ const xAxis = getTimeseriesXAxis(series, settings);
+ const domain = xAxis?.domain;
+ if (xAxis == null || domain == null) {
+ return EMPTY_EVENTS;
+ }
+ const events = candidates.filter((event) =>
+ isTimelineEventInRange(event, domain, xAxis.interval),
+ );
+ return events.length > 0 ? events : EMPTY_EVENTS;
+ }, [isEnabled, explicitEvents, timelines, visibility, series, settings]);
- const selectedSet = new Set(selectedTimelineIds);
- const excludedSet = new Set(excludedTimelineEventIds ?? []);
+ useEffect(() => {
+ if (timelineEvents.length > 0) {
+ onTimelineEventsShown?.();
+ }
+ }, [timelineEvents, onTimelineEventsShown]);
- return timelines.flatMap((timeline) => {
- if (!selectedSet.has(timeline.id)) {
- return [];
- }
- return (timeline.events ?? []).filter(
- (event) => !excludedSet.has(event.id),
- );
- });
- }, [
- timelineEventsProp,
- timelines,
- selectedTimelineIds,
- excludedTimelineEventIds,
- ]);
+ // getDashboardAdjustedSettings turns events off for small cards and while unmeasured (0x0)
+ const isMeasured = width > 0 && height > 0;
+ useEffect(() => {
+ if (isMeasured) {
+ onTimelineEventsEnabledChange?.(isEnabled);
+ }
+ }, [isMeasured, isEnabled, onTimelineEventsEnabledChange]);
return { timelineEvents, isLoading, isError };
}
diff --git a/frontend/src/metabase/visualizations/hooks/use-timeline-events.unit.spec.ts b/frontend/src/metabase/visualizations/hooks/use-timeline-events.unit.spec.ts
new file mode 100644
index 00000000000..0bcd02af825
--- /dev/null
+++ b/frontend/src/metabase/visualizations/hooks/use-timeline-events.unit.spec.ts
@@ -0,0 +1,429 @@
+import { renderHook } from "@testing-library/react";
+import fetchMock from "fetch-mock";
+
+import { setupTimelinesEndpoints } from "__support__/server-mocks";
+import { act, getTestStoreAndWrapper, waitFor } from "__support__/ui";
+import { timelineApi } from "metabase/api";
+import { mockIsEmbeddingSdk } from "metabase/embedding-sdk/mocks/config-mock";
+import * as embeddingConfig from "metabase/embedding/config";
+import { registerVisualizations } from "metabase/visualizations/register";
+import type { VisualizationProps } from "metabase/visualizations/types";
+import { getComputedSettingsForSeries } from "metabase/viz-core";
+import type {
+ RawSeries,
+ Timeline,
+ TimelineEvent,
+ TimelineEventsVisibility,
+ VisualizationSettings,
+} from "metabase-types/api";
+import {
+ createMockCard,
+ createMockDataset,
+ createMockDatasetData,
+ createMockDatetimeColumn,
+ createMockNumericColumn,
+ createMockTimeline,
+ createMockTimelineEvent,
+} from "metabase-types/api/mocks";
+
+import { useTimelineEvents } from "./use-timeline-events";
+
+registerVisualizations();
+
+const SHOWN_EVENT = createMockTimelineEvent({
+ id: 1,
+ timeline_id: 10,
+ timestamp: "2024-02-15T00:00:00Z",
+});
+const HIDDEN_EVENT = createMockTimelineEvent({
+ id: 2,
+ timeline_id: 10,
+ timestamp: "2024-02-20T00:00:00Z",
+});
+const OUT_OF_RANGE_EVENT = createMockTimelineEvent({
+ id: 3,
+ timeline_id: 10,
+ timestamp: "2030-02-15T00:00:00Z",
+});
+const ARCHIVED_EVENT = createMockTimelineEvent({
+ id: 4,
+ timeline_id: 10,
+ timestamp: "2024-02-16T00:00:00Z",
+ archived: true,
+});
+const TIMELINE = createMockTimeline({
+ id: 10,
+ events: [SHOWN_EVENT, HIDDEN_EVENT, OUT_OF_RANGE_EVENT, ARCHIVED_EVENT],
+});
+
+const SAVED_VISIBILITY: TimelineEventsVisibility = {
+ "timeline.selected_timeline_ids": [TIMELINE.id],
+ "timeline.excluded_timeline_event_ids": [HIDDEN_EVENT.id],
+};
+
+const DATASET = createMockDataset({
+ data: createMockDatasetData({
+ cols: [
+ createMockDatetimeColumn({ name: "CREATED_AT", unit: "month" }),
+ createMockNumericColumn({ name: "count" }),
+ ],
+ rows: [
+ ["2024-01-01", 1],
+ ["2024-03-01", 2],
+ ],
+ }),
+});
+
+const getSeries = (
+ visualization_settings: VisualizationSettings,
+): RawSeries => [
+ {
+ card: createMockCard({ display: "line", visualization_settings }),
+ ...DATASET,
+ },
+];
+
+const setup = ({
+ savedSettings = SAVED_VISIBILITY,
+ timelineEvents,
+ timelineEventsVisibility,
+ timelines = [TIMELINE],
+ series = getSeries(savedSettings),
+ settings = getComputedSettingsForSeries(series),
+ onTimelineEventsShown,
+ onTimelineEventsEnabledChange,
+ isDashboard = false,
+ width,
+ height,
+ providers = getTestStoreAndWrapper({ initialRoute: "/" }),
+}: {
+ savedSettings?: VisualizationSettings;
+ timelineEvents?: TimelineEvent[];
+ timelineEventsVisibility?: TimelineEventsVisibility;
+ timelines?: Timeline[];
+ series?: RawSeries;
+ settings?: VisualizationProps["settings"];
+ onTimelineEventsShown?: VisualizationProps["onTimelineEventsShown"];
+ onTimelineEventsEnabledChange?: VisualizationProps["onTimelineEventsEnabledChange"];
+ isDashboard?: boolean;
+ width?: number;
+ height?: number;
+ providers?: ReturnType<typeof getTestStoreAndWrapper>;
+} = {}) => {
+ setupTimelinesEndpoints(timelines);
+ const mount = () =>
+ renderHook(
+ (props: Pick<VisualizationProps, "series" | "settings">) =>
+ useTimelineEvents({
+ timelineEvents,
+ timelineEventsVisibility,
+ onTimelineEventsShown,
+ onTimelineEventsEnabledChange,
+ isDashboard,
+ width,
+ height,
+ ...props,
+ }),
+ { initialProps: { series, settings }, wrapper: providers.wrapper },
+ );
+ return { ...mount(), mount, store: providers.store };
+};
+
+const getTimelineRequests = () =>
+ fetchMock.callHistory.calls("path:/api/timeline");
+
+describe("useTimelineEvents", () => {
+ afterEach(() => {
+ jest.restoreAllMocks();
+ });
+
+ it("loads the events a question was saved with", async () => {
+ const { result } = setup();
+
+ await waitFor(() => {
+ expect(result.current.timelineEvents).toEqual([SHOWN_EVENT]);
+ });
+ expect(getTimelineRequests()).toHaveLength(1);
+ });
+
+ it("drops events outside the chart's range and archived events", async () => {
+ const { result } = setup({
+ savedSettings: { "timeline.selected_timeline_ids": [TIMELINE.id] },
+ });
+
+ await waitFor(() => {
+ expect(result.current.timelineEvents).toEqual([
+ SHOWN_EVENT,
+ HIDDEN_EVENT,
+ ]);
+ });
+ });
+
+ it("uses the events it is given instead of loading them", () => {
+ const { result } = setup({
+ timelineEvents: [OUT_OF_RANGE_EVENT, SHOWN_EVENT],
+ });
+
+ expect(result.current.timelineEvents).toEqual([SHOWN_EVENT]);
+ expect(getTimelineRequests()).toHaveLength(0);
+ });
+
+ it("uses an explicitly empty event list instead of saved or supplied visibility", async () => {
+ const onTimelineEventsShown = jest.fn();
+ const { result } = setup({
+ timelineEvents: [],
+ timelineEventsVisibility: SAVED_VISIBILITY,
+ onTimelineEventsShown,
+ });
+
+ await act(async () => {
+ await fetchMock.callHistory.flush();
+ });
+
+ expect(result.current.timelineEvents).toEqual([]);
+ expect(getTimelineRequests()).toHaveLength(0);
+ expect(onTimelineEventsShown).not.toHaveBeenCalled();
+ });
+
+ it("shows new events from selected timelines after refresh while keeping new timelines hidden", async () => {
+ const { result, store } = setup();
+
+ await waitFor(() => {
+ expect(result.current.timelineEvents).toEqual([SHOWN_EVENT]);
+ });
+
+ const newEvent = createMockTimelineEvent({
+ id: 5,
+ timeline_id: TIMELINE.id,
+ timestamp: "2024-03-10T00:00:00Z",
+ });
+ const newTimeline = createMockTimeline({
+ id: 20,
+ events: [
+ createMockTimelineEvent({
+ id: 6,
+ timeline_id: 20,
+ timestamp: "2024-02-25T00:00:00Z",
+ }),
+ ],
+ });
+ fetchMock.removeRoutes();
+ setupTimelinesEndpoints([
+ { ...TIMELINE, events: [...(TIMELINE.events ?? []), newEvent] },
+ newTimeline,
+ ]);
+
+ await act(async () => {
+ await store.dispatch(
+ timelineApi.endpoints.listTimelines.initiate(
+ { include: "events" },
+ { forceRefetch: true, subscribe: false },
+ ),
+ );
+ });
+
+ await waitFor(() => {
+ expect(result.current.timelineEvents).toEqual([SHOWN_EVENT, newEvent]);
+ });
+ expect(getTimelineRequests()).toHaveLength(2);
+ });
+
+ it("prefers the visibility it is given over the card settings", async () => {
+ const { result } = setup({
+ savedSettings: { "timeline.selected_timeline_ids": [] },
+ timelineEventsVisibility: SAVED_VISIBILITY,
+ });
+
+ await waitFor(() => {
+ expect(result.current.timelineEvents).toEqual([SHOWN_EVENT]);
+ });
+ });
+
+ it("loads nothing when the question never recorded events", () => {
+ const { result } = setup({ savedSettings: {} });
+
+ expect(result.current.timelineEvents).toEqual([]);
+ expect(getTimelineRequests()).toHaveLength(0);
+ });
+
+ it("loads nothing when events are turned off", () => {
+ const { result } = setup({
+ savedSettings: { ...SAVED_VISIBILITY, "timeline_events.enabled": false },
+ });
+
+ expect(result.current.timelineEvents).toEqual([]);
+ expect(getTimelineRequests()).toHaveLength(0);
+ });
+
+ it("loads nothing when the host selects no timelines", () => {
+ const { result } = setup({
+ timelineEventsVisibility: { "timeline.selected_timeline_ids": [] },
+ });
+
+ expect(result.current.timelineEvents).toEqual([]);
+ expect(getTimelineRequests()).toHaveLength(0);
+ });
+
+ it("shows nothing when the chart has no data", () => {
+ const { result } = setup({
+ series: [
+ {
+ card: createMockCard({
+ display: "line",
+ visualization_settings: SAVED_VISIBILITY,
+ }),
+ ...createMockDataset({
+ data: createMockDatasetData({ cols: DATASET.data.cols, rows: [] }),
+ }),
+ },
+ ],
+ });
+
+ expect(result.current.timelineEvents).toEqual([]);
+ });
+
+ it("reports when events are shown", async () => {
+ const onTimelineEventsShown = jest.fn();
+ setup({ onTimelineEventsShown });
+
+ await waitFor(() => {
+ expect(onTimelineEventsShown).toHaveBeenCalled();
+ });
+ });
+
+ it("does not report when no events are shown", () => {
+ const onTimelineEventsShown = jest.fn();
+ setup({ savedSettings: {}, onTimelineEventsShown });
+
+ expect(onTimelineEventsShown).not.toHaveBeenCalled();
+ });
+
+ it("reports once when rerendered with the same inputs", async () => {
+ const onTimelineEventsShown = jest.fn();
+ const series = getSeries(SAVED_VISIBILITY);
+ const settings = getComputedSettingsForSeries(series);
+ const { result, rerender } = setup({
+ series,
+ settings,
+ onTimelineEventsShown,
+ });
+
+ await waitFor(() => {
+ expect(result.current.timelineEvents).toEqual([SHOWN_EVENT]);
+ });
+
+ rerender({ series, settings });
+
+ expect(onTimelineEventsShown).toHaveBeenCalledTimes(1);
+ });
+
+ it("reports whether a measured chart has events enabled as its settings change", () => {
+ const onTimelineEventsEnabledChange = jest.fn();
+ const series = getSeries(SAVED_VISIBILITY);
+ const settings = getComputedSettingsForSeries(series);
+ const { rerender } = setup({
+ series,
+ settings: { ...settings, "timeline_events.enabled": false },
+ width: 400,
+ height: 300,
+ onTimelineEventsEnabledChange,
+ });
+
+ expect(onTimelineEventsEnabledChange).toHaveBeenCalledWith(false);
+
+ rerender({ series, settings });
+
+ expect(onTimelineEventsEnabledChange).toHaveBeenLastCalledWith(true);
+ });
+
+ it("drops the events when the settings turn the chart into a non-timeseries one", async () => {
+ const series = getSeries(SAVED_VISIBILITY);
+ const { result, rerender } = setup({ series });
+
+ await waitFor(() => {
+ expect(result.current.timelineEvents).toEqual([SHOWN_EVENT]);
+ });
+
+ rerender({
+ series,
+ settings: {
+ ...getComputedSettingsForSeries(series),
+ "graph.x_axis.scale": "ordinal",
+ },
+ });
+
+ expect(result.current.timelineEvents).toEqual([]);
+ });
+
+ describe.each([
+ [
+ "public links",
+ () =>
+ jest.spyOn(embeddingConfig, "isPublicEmbedding").mockReturnValue(true),
+ ],
+ [
+ "static embeds",
+ () =>
+ jest.spyOn(embeddingConfig, "isStaticEmbedding").mockReturnValue(true),
+ ],
+ ["the embedding SDK", () => mockIsEmbeddingSdk()],
+ ])("on %s", (_surface, mockSurface) => {
+ it.each([
+ ["saved selections", {}],
+ ["explicit visibility", { timelineEventsVisibility: SAVED_VISIBILITY }],
+ ])(
+ "does not show, request, or report events from %s on a standalone question",
+ async (_input, props) => {
+ await mockSurface();
+ const onTimelineEventsShown = jest.fn();
+ const { result } = setup({ ...props, onTimelineEventsShown });
+
+ await act(async () => {
+ await fetchMock.callHistory.flush();
+ });
+
+ expect(result.current.timelineEvents).toEqual([]);
+ expect(getTimelineRequests()).toHaveLength(0);
+ expect(onTimelineEventsShown).not.toHaveBeenCalled();
+ },
+ );
+
+ it("shows the events the dashboard payload carries, without requesting any", async () => {
+ await mockSurface();
+ const { result } = setup({
+ timelineEvents: [SHOWN_EVENT],
+ isDashboard: true,
+ });
+
+ await act(async () => {
+ await fetchMock.callHistory.flush();
+ });
+
+ expect(result.current.timelineEvents).toEqual([SHOWN_EVENT]);
+ expect(getTimelineRequests()).toHaveLength(0);
+ });
+ });
+
+ it("only shows saved events on an authenticated SDK dashboard", async () => {
+ await mockIsEmbeddingSdk();
+ const unrelatedTimeline = createMockTimeline({
+ id: 20,
+ events: [
+ createMockTimelineEvent({
+ id: 5,
+ timeline_id: 20,
+ timestamp: SHOWN_EVENT.timestamp,
+ }),
+ ],
+ });
+ const { result } = setup({
+ isDashboard: true,
+ timelines: [TIMELINE, unrelatedTimeline],
+ });
+
+ await waitFor(() => {
+ expect(result.current.timelineEvents).toEqual([SHOWN_EVENT]);
+ });
+ expect(getTimelineRequests()).toHaveLength(1);
+ });
+});
diff --git a/frontend/src/metabase/visualizations/lib/timeline-events-visibility.ts b/frontend/src/metabase/visualizations/lib/timeline-events-visibility.ts
new file mode 100644
index 00000000000..3df1b58c756
--- /dev/null
+++ b/frontend/src/metabase/visualizations/lib/timeline-events-visibility.ts
@@ -0,0 +1,226 @@
+import _ from "underscore";
+
+import { getCollectionTimelines } from "metabase/common/utils/timelines";
+import { dayjs } from "metabase/dayjs";
+import type { AggregatedEventsVisibility } from "metabase/visualizations/types";
+import type {
+ CollectionId,
+ Timeline,
+ TimelineEvent,
+ TimelineEventId,
+ TimelineEventsVisibility,
+ TimelineId,
+ VisualizationSettings,
+} from "metabase-types/api";
+
+interface ResolveOptions {
+ timelines: Timeline[];
+ visibility?: TimelineEventsVisibility;
+}
+
+interface VisibilitySets {
+ shownTimelineIds: Set<TimelineId>;
+ hiddenEventIds: Set<TimelineEventId>;
+}
+
+const toSets = (
+ visibility: TimelineEventsVisibility | undefined,
+): VisibilitySets => ({
+ shownTimelineIds: new Set(visibility?.["timeline.selected_timeline_ids"]),
+ hiddenEventIds: new Set(visibility?.["timeline.excluded_timeline_event_ids"]),
+});
+
+const sortedIds = <T extends number>(ids: Iterable<T>): T[] =>
+ [...ids].sort((a, b) => a - b);
+
+const fromSets = ({
+ shownTimelineIds,
+ hiddenEventIds,
+}: VisibilitySets): TimelineEventsVisibility => ({
+ "timeline.selected_timeline_ids": sortedIds(shownTimelineIds),
+ "timeline.excluded_timeline_event_ids": sortedIds(hiddenEventIds),
+});
+
+export const isSameTimelineEventsVisibility = (
+ a: TimelineEventsVisibility | undefined,
+ b: TimelineEventsVisibility | undefined,
+) => _.isEqual(fromSets(toSets(a)), fromSets(toSets(b)));
+
+export const isTimelineEventsEnabled = (
+ settings: VisualizationSettings | undefined,
+) => settings?.["timeline_events.enabled"] !== false;
+
+export const getRecordedTimelineEventsVisibility = (
+ settings: VisualizationSettings | undefined,
+): TimelineEventsVisibility | undefined =>
+ settings?.["timeline.selected_timeline_ids"] != null ? settings : undefined;
+
+const getActiveEvents = (timeline: Timeline) =>
+ (timeline.events ?? []).filter((event) => !event.archived);
+
+const sortByTimestamp = (events: TimelineEvent[]) =>
+ _.sortBy(events, (event) => dayjs(event.timestamp).valueOf());
+
+export const resolveVisibleTimelineEvents = ({
+ timelines,
+ visibility,
+}: ResolveOptions): TimelineEvent[] => {
+ const sets = toSets(visibility);
+ return sortByTimestamp(
+ timelines
+ .filter((timeline) => sets.shownTimelineIds.has(timeline.id))
+ .flatMap(getActiveEvents)
+ .filter((event) => !sets.hiddenEventIds.has(event.id)),
+ );
+};
+
+const setTimelineVisible = (
+ timeline: Timeline,
+ isVisible: boolean,
+ sets: VisibilitySets,
+) => {
+ if (isVisible) {
+ sets.shownTimelineIds.add(timeline.id);
+ } else {
+ sets.shownTimelineIds.delete(timeline.id);
+ }
+ timeline.events?.forEach((event) => sets.hiddenEventIds.delete(event.id));
+};
+
+const setTimelinesVisible = (
+ visibility: TimelineEventsVisibility,
+ timelineIds: TimelineId[],
+ isVisible: boolean,
+ timelines: Timeline[],
+): TimelineEventsVisibility => {
+ const sets = toSets(visibility);
+ const ids = new Set(timelineIds);
+ timelines
+ .filter((timeline) => ids.has(timeline.id))
+ .forEach((timeline) => setTimelineVisible(timeline, isVisible, sets));
+ return fromSets(sets);
+};
+
+export const showTimelines = (
+ visibility: TimelineEventsVisibility,
+ timelineIds: TimelineId[],
+ timelines: Timeline[],
+) => setTimelinesVisible(visibility, timelineIds, true, timelines);
+
+export const hideTimelines = (
+ visibility: TimelineEventsVisibility,
+ timelineIds: TimelineId[],
+ timelines: Timeline[],
+) => setTimelinesVisible(visibility, timelineIds, false, timelines);
+
+export const getCollectionTimelinesVisibility = (
+ timelines: Timeline[],
+ collectionId: CollectionId | null | undefined,
+) =>
+ showTimelines(
+ {},
+ getCollectionTimelines(timelines, collectionId).map(({ id }) => id),
+ timelines,
+ );
+
+const groupEventsByTimelineId = (
+ events: TimelineEvent[],
+): Map<TimelineId, TimelineEvent[]> => {
+ const groups = new Map<TimelineId, TimelineEvent[]>();
+ events.forEach((event) => {
+ const group = groups.get(event.timeline_id);
+ if (group) {
+ group.push(event);
+ } else {
+ groups.set(event.timeline_id, [event]);
+ }
+ });
+ return groups;
+};
+
+const indexTimelinesById = (timelines: Timeline[]) =>
+ new Map(timelines.map((timeline) => [timeline.id, timeline]));
+
+export const showTimelineEvents = (
+ visibility: TimelineEventsVisibility,
+ events: TimelineEvent[],
+ timelines: Timeline[],
+): TimelineEventsVisibility => {
+ const sets = toSets(visibility);
+ const timelinesById = indexTimelinesById(timelines);
+ groupEventsByTimelineId(events).forEach((shownEvents, timelineId) => {
+ const shownEventIds = new Set(shownEvents.map((event) => event.id));
+ if (!sets.shownTimelineIds.has(timelineId)) {
+ const timeline = timelinesById.get(timelineId);
+ if (timeline) {
+ setTimelineVisible(timeline, true, sets);
+ getActiveEvents(timeline)
+ .filter((event) => !shownEventIds.has(event.id))
+ .forEach((event) => sets.hiddenEventIds.add(event.id));
+ } else {
+ sets.shownTimelineIds.add(timelineId);
+ }
+ }
+ shownEventIds.forEach((eventId) => sets.hiddenEventIds.delete(eventId));
+ });
+ return fromSets(sets);
+};
+
+export const showCreatedTimelineEvent = (
+ visibility: TimelineEventsVisibility,
+ event: TimelineEvent,
+ timelines: Timeline[],
+): TimelineEventsVisibility => {
+ const isTimelineShown = visibility[
+ "timeline.selected_timeline_ids"
+ ]?.includes(event.timeline_id);
+ return showTimelineEvents(
+ isTimelineShown
+ ? visibility
+ : showTimelines(visibility, [event.timeline_id], timelines),
+ [event],
+ timelines,
+ );
+};
+
+export const hideTimelineEvents = (
+ visibility: TimelineEventsVisibility,
+ events: TimelineEvent[],
+ timelines: Timeline[],
+): TimelineEventsVisibility => {
+ const sets = toSets(visibility);
+ const timelinesById = indexTimelinesById(timelines);
+ groupEventsByTimelineId(events).forEach((hiddenEvents, timelineId) => {
+ if (!sets.shownTimelineIds.has(timelineId)) {
+ return;
+ }
+ hiddenEvents.forEach((event) => sets.hiddenEventIds.add(event.id));
+ const timeline = timelinesById.get(timelineId);
+ const isEveryEventHidden =
+ timeline !== undefined &&
+ getActiveEvents(timeline).every((event) =>
+ sets.hiddenEventIds.has(event.id),
+ );
+ if (isEveryEventHidden) {
+ setTimelineVisible(timeline, false, sets);
+ }
+ });
+ return fromSets(sets);
+};
+
+export const aggregateVisibleEventIds = (
+ visibleEventIdsPerChart: TimelineEventId[][],
+): AggregatedEventsVisibility => {
+ const [firstChartEventIds = [], ...otherCharts] = visibleEventIdsPerChart;
+ const otherChartSets = otherCharts.map((eventIds) => new Set(eventIds));
+ const visibleEventIds = [...new Set(firstChartEventIds)].filter((eventId) =>
+ otherChartSets.every((eventIdSet) => eventIdSet.has(eventId)),
+ );
+ const visibleSet = new Set(visibleEventIds);
+ return {
+ visibleEventIds,
+ partiallyVisibleEventIds: [
+ ...new Set(visibleEventIdsPerChart.flat()),
+ ].filter((eventId) => !visibleSet.has(eventId)),
+ };
+};
diff --git a/frontend/src/metabase/visualizations/lib/timeline-events-visibility.unit.spec.ts b/frontend/src/metabase/visualizations/lib/timeline-events-visibility.unit.spec.ts
new file mode 100644
index 00000000000..a41405f6d05
--- /dev/null
+++ b/frontend/src/metabase/visualizations/lib/timeline-events-visibility.unit.spec.ts
@@ -0,0 +1,359 @@
+import type {
+ TimelineEventsVisibility,
+ VisualizationSettings,
+} from "metabase-types/api";
+import {
+ createMockTimeline,
+ createMockTimelineEvent,
+} from "metabase-types/api/mocks";
+
+import {
+ aggregateVisibleEventIds,
+ getRecordedTimelineEventsVisibility,
+ hideTimelineEvents,
+ hideTimelines,
+ isSameTimelineEventsVisibility,
+ resolveVisibleTimelineEvents,
+ showCreatedTimelineEvent,
+ showTimelineEvents,
+ showTimelines,
+} from "./timeline-events-visibility";
+
+const SELECTED = "timeline.selected_timeline_ids";
+const EXCLUDED = "timeline.excluded_timeline_event_ids";
+
+const COLLECTION_ID = 7;
+
+const rc1 = createMockTimelineEvent({
+ id: 11,
+ timeline_id: 1,
+ name: "RC1",
+ timestamp: "2027-06-03T00:00:00Z",
+});
+const rc2 = createMockTimelineEvent({
+ id: 12,
+ timeline_id: 1,
+ name: "RC2",
+ timestamp: "2027-06-15T00:00:00Z",
+});
+const archivedRelease = createMockTimelineEvent({
+ id: 13,
+ timeline_id: 1,
+ name: "Archived",
+ archived: true,
+ timestamp: "2027-06-01T00:00:00Z",
+});
+const launch = createMockTimelineEvent({
+ id: 21,
+ timeline_id: 2,
+ name: "Launch",
+ timestamp: "2027-06-10T00:00:00Z",
+});
+const outage = createMockTimelineEvent({
+ id: 31,
+ timeline_id: 3,
+ name: "Outage",
+ timestamp: "2027-06-20T00:00:00Z",
+});
+
+const releases = createMockTimeline({
+ id: 1,
+ name: "Releases",
+ collection_id: COLLECTION_ID,
+ events: [rc1, rc2, archivedRelease],
+});
+const marketing = createMockTimeline({
+ id: 2,
+ name: "Marketing",
+ collection_id: COLLECTION_ID,
+ events: [launch],
+});
+const incidents = createMockTimeline({
+ id: 3,
+ name: "Incidents",
+ collection_id: 99,
+ events: [outage],
+});
+
+// An event created on a brand-new timeline arrives before the timeline
+// list is refetched.
+const unfetchedEvent = createMockTimelineEvent({
+ id: 41,
+ timeline_id: 4,
+ name: "First event",
+ timestamp: "2027-06-25T00:00:00Z",
+});
+
+const timelines = [releases, marketing, incidents];
+const context = timelines;
+
+const visibleNames = (visibility?: TimelineEventsVisibility) =>
+ resolveVisibleTimelineEvents({ timelines, visibility }).map(
+ (event) => event.name,
+ );
+
+describe("resolveVisibleTimelineEvents", () => {
+ it("shows nothing until a timeline is explicitly shown", () => {
+ expect(visibleNames()).toEqual([]);
+ });
+
+ it("shows the non-archived events of shown timelines, sorted by date", () => {
+ expect(visibleNames({ [SELECTED]: [releases.id, marketing.id] })).toEqual([
+ "RC1",
+ "Launch",
+ "RC2",
+ ]);
+ });
+
+ it("hides single events of shown timelines", () => {
+ expect(
+ visibleNames({
+ [SELECTED]: [releases.id, incidents.id],
+ [EXCLUDED]: [rc2.id],
+ }),
+ ).toEqual(["RC1", "Outage"]);
+ });
+
+ it("ignores ids that no longer exist", () => {
+ expect(
+ visibleNames({
+ [SELECTED]: [releases.id, 999],
+ [EXCLUDED]: [999],
+ }),
+ ).toEqual(["RC1", "RC2"]);
+ });
+});
+
+describe("getRecordedTimelineEventsVisibility", () => {
+ it("reads a recorded selection out of the card settings", () => {
+ const settings = {
+ "graph.dimensions": ["CREATED_AT"],
+ [SELECTED]: [releases.id],
+ [EXCLUDED]: [rc2.id],
+ };
+ expect(getRecordedTimelineEventsVisibility(settings)).toBe(settings);
+ });
+
+ it("treats an empty selection as recorded", () => {
+ const settings = { [SELECTED]: [] };
+ expect(getRecordedTimelineEventsVisibility(settings)).toBe(settings);
+ });
+
+ it("is undefined when nothing was ever recorded", () => {
+ expect(getRecordedTimelineEventsVisibility(undefined)).toBeUndefined();
+ expect(getRecordedTimelineEventsVisibility({})).toBeUndefined();
+ expect(
+ getRecordedTimelineEventsVisibility({ [EXCLUDED]: [] }),
+ ).toBeUndefined();
+ });
+});
+
+describe("showing and hiding timelines", () => {
+ it("hiding a timeline leaves nothing behind", () => {
+ const shown = showTimelines({}, [releases.id], context);
+
+ expect(hideTimelines(shown, [releases.id], context)).toEqual({
+ [SELECTED]: [],
+ [EXCLUDED]: [],
+ });
+ });
+
+ it("showing a timeline brings back its individually hidden events", () => {
+ const visibility = hideTimelineEvents(
+ { [SELECTED]: [releases.id] },
+ [rc1],
+ context,
+ );
+ expect(visibleNames(visibility)).toEqual(["RC2"]);
+
+ expect(
+ visibleNames(showTimelines(visibility, [releases.id], context)),
+ ).toEqual(["RC1", "RC2"]);
+ });
+});
+
+describe("showing and hiding single events", () => {
+ it("hides one event and keeps the rest of its timeline", () => {
+ const visibility = hideTimelineEvents(
+ { [SELECTED]: [releases.id, marketing.id] },
+ [rc1],
+ context,
+ );
+ expect(visibleNames(visibility)).toEqual(["Launch", "RC2"]);
+ });
+
+ it("keeps events added later hidden once every event of a timeline was hidden", () => {
+ const visibility = hideTimelineEvents(
+ { [SELECTED]: [releases.id, marketing.id] },
+ [rc1, rc2],
+ context,
+ );
+
+ const rc3 = createMockTimelineEvent({
+ id: 14,
+ timeline_id: 1,
+ name: "RC3",
+ });
+ const withNewRelease = [
+ createMockTimeline({ ...releases, events: [rc1, rc2, rc3] }),
+ marketing,
+ ];
+ expect(
+ resolveVisibleTimelineEvents({
+ timelines: withNewRelease,
+ visibility,
+ }).map((event) => event.name),
+ ).toEqual(["Launch"]);
+ });
+
+ it("shows only the requested event of a timeline that isn't shown", () => {
+ const visibility = showTimelineEvents({}, [rc1], context);
+ expect(visibleNames(visibility)).toEqual(["RC1"]);
+ });
+
+ it("does not affect other timelines", () => {
+ const visibility = hideTimelineEvents(
+ { [SELECTED]: [releases.id] },
+ [rc1],
+ context,
+ );
+ expect(visibleNames(visibility)).toEqual(["RC2"]);
+ expect(
+ visibleNames(showTimelineEvents(visibility, [rc1], context)),
+ ).toEqual(["RC1", "RC2"]);
+ });
+});
+
+describe("aggregateVisibleEventIds", () => {
+ it("splits events into visible on every chart and visible on some charts", () => {
+ expect(
+ aggregateVisibleEventIds([
+ [rc1.id, rc2.id],
+ [rc2.id, launch.id],
+ [rc2.id],
+ ]),
+ ).toEqual({
+ visibleEventIds: [rc2.id],
+ partiallyVisibleEventIds: [rc1.id, launch.id],
+ });
+ });
+
+ it("treats every event as partially visible when one chart shows none", () => {
+ expect(aggregateVisibleEventIds([[rc1.id, rc2.id], []])).toEqual({
+ visibleEventIds: [],
+ partiallyVisibleEventIds: [rc1.id, rc2.id],
+ });
+ });
+});
+
+describe("toggling a timeline the caller only partly knows about", () => {
+ // Sidebars hold timelines whose events were narrowed to a chart's x-axis, so
+ // toggling takes an id and resolves every event from the full list.
+ it("does not exclude the events outside the range when showing", () => {
+ expect(showTimelines({}, [releases.id], context)).toEqual({
+ [SELECTED]: [releases.id],
+ [EXCLUDED]: [],
+ });
+ });
+
+ it("ignores an id that is not in the list", () => {
+ expect(showTimelines({}, [999], context)).toEqual({
+ [SELECTED]: [],
+ [EXCLUDED]: [],
+ });
+ });
+});
+
+describe("showing an event of a timeline that is not loaded yet", () => {
+ it("shows the timeline the event belongs to", () => {
+ expect(showTimelineEvents({}, [unfetchedEvent], context)).toEqual({
+ [SELECTED]: [4],
+ [EXCLUDED]: [],
+ });
+ });
+
+ it("keeps the events already shown", () => {
+ const visibility = showTimelineEvents({}, [rc1], context);
+ expect(showTimelineEvents(visibility, [unfetchedEvent], context)).toEqual({
+ [SELECTED]: [1, 4],
+ [EXCLUDED]: [rc2.id],
+ });
+ });
+
+ it("hiding it records the event without collapsing the timeline", () => {
+ const visibility = showTimelineEvents({}, [unfetchedEvent], context);
+ expect(hideTimelineEvents(visibility, [unfetchedEvent], context)).toEqual({
+ [SELECTED]: [4],
+ [EXCLUDED]: [unfetchedEvent.id],
+ });
+ });
+});
+
+describe("showing a created event", () => {
+ const rc3 = createMockTimelineEvent({
+ id: 14,
+ timeline_id: 1,
+ name: "RC3",
+ timestamp: "2027-06-20T00:00:00Z",
+ });
+
+ it("shows the whole timeline when it was hidden", () => {
+ expect(showCreatedTimelineEvent({}, rc3, context)).toEqual({
+ [SELECTED]: [1],
+ [EXCLUDED]: [],
+ });
+ });
+
+ it("keeps the hidden events of a shown timeline hidden", () => {
+ const visibility = hideTimelineEvents(
+ showTimelines({}, [1], context),
+ [rc1],
+ context,
+ );
+ expect(showCreatedTimelineEvent(visibility, rc3, context)).toEqual({
+ [SELECTED]: [1],
+ [EXCLUDED]: [rc1.id],
+ });
+ });
+
+ it("shows the timeline when it is not loaded yet", () => {
+ expect(showCreatedTimelineEvent({}, unfetchedEvent, context)).toEqual({
+ [SELECTED]: [4],
+ [EXCLUDED]: [],
+ });
+ });
+});
+
+describe("isSameTimelineEventsVisibility", () => {
+ it("ignores id order and unrelated settings", () => {
+ const settings: VisualizationSettings = {
+ "graph.dimensions": ["CREATED_AT"],
+ [SELECTED]: [2, 1],
+ [EXCLUDED]: [rc2.id, rc1.id],
+ };
+ expect(
+ isSameTimelineEventsVisibility(settings, {
+ [SELECTED]: [1, 2],
+ [EXCLUDED]: [rc1.id, rc2.id],
+ }),
+ ).toBe(true);
+ });
+
+ it("treats nothing recorded like an empty selection", () => {
+ expect(
+ isSameTimelineEventsVisibility(undefined, {
+ [SELECTED]: [],
+ [EXCLUDED]: [],
+ }),
+ ).toBe(true);
+ });
+
+ it("tells different selections apart", () => {
+ expect(
+ isSameTimelineEventsVisibility(
+ { [SELECTED]: [1], [EXCLUDED]: [] },
+ { [SELECTED]: [1], [EXCLUDED]: [rc1.id] },
+ ),
+ ).toBe(false);
+ });
+});
diff --git a/frontend/src/metabase/visualizations/types/index.ts b/frontend/src/metabase/visualizations/types/index.ts
index 719b637b8be..cdeaec4fa55 100644
--- a/frontend/src/metabase/visualizations/types/index.ts
+++ b/frontend/src/metabase/visualizations/types/index.ts
@@ -1,2 +1,3 @@
export * from "./click-actions";
+export * from "./timeline-events";
export * from "./visualization";
diff --git a/frontend/src/metabase/visualizations/types/timeline-events.ts b/frontend/src/metabase/visualizations/types/timeline-events.ts
new file mode 100644
index 00000000000..e31c527be98
--- /dev/null
+++ b/frontend/src/metabase/visualizations/types/timeline-events.ts
@@ -0,0 +1,18 @@
+import type {
+ Timeline,
+ TimelineEventId,
+ TimelineEventsVisibility,
+} from "metabase-types/api";
+
+export type TimelineEventsVisibilityUpdate = (
+ visibility: TimelineEventsVisibility,
+ timelines: Timeline[],
+) => TimelineEventsVisibility;
+
+/** the gesture behind a visibility update, for surfaces that report it */
+export type TimelineEventsVisibilityIntent = "show" | "hide" | "create";
+
+export interface AggregatedEventsVisibility {
+ visibleEventIds: TimelineEventId[];
+ partiallyVisibleEventIds: TimelineEventId[];
+}
diff --git a/frontend/src/metabase/visualizations/types/visualization.ts b/frontend/src/metabase/visualizations/types/visualization.ts
index 21fcc572ee7..710c9cec401 100644
--- a/frontend/src/metabase/visualizations/types/visualization.ts
+++ b/frontend/src/metabase/visualizations/types/visualization.ts
@@ -24,6 +24,7 @@ import type {
SeriesCard,
TimelineEvent,
TimelineEventId,
+ TimelineEventsVisibility,
VisualizationSettings,
} from "metabase-types/api";
@@ -86,6 +87,7 @@ export interface VisualizationProps {
clicked?: ClickObject | null;
className?: string;
timelineEvents?: TimelineEvent[];
+ timelineEventsVisibility?: TimelineEventsVisibility;
selectedTimelineEventIds?: TimelineEventId[];
queryBuilderMode?: QueryBuilderMode;
@@ -119,6 +121,8 @@ export interface VisualizationProps {
onDeselectTimelineEvents?: () => void;
onOpenTimelines?: (eventIds?: number[]) => void;
onSeeAllEvents?: (timelineEvents: TimelineEvent[]) => void;
+ onTimelineEventsShown?: () => void;
+ onTimelineEventsEnabledChange?: (isEnabled: boolean) => void;
canToggleSeriesVisibility?: boolean;
onUpdateWarnings?: any;
diff --git a/frontend/src/metabase/visualizations/visualizations/CartesianChart/CartesianChart.tsx b/frontend/src/metabase/visualizations/visualizations/CartesianChart/CartesianChart.tsx
index 2656b398b0a..62a10d84eb0 100644
--- a/frontend/src/metabase/visualizations/visualizations/CartesianChart/CartesianChart.tsx
+++ b/frontend/src/metabase/visualizations/visualizations/CartesianChart/CartesianChart.tsx
@@ -38,8 +38,6 @@ 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
@@ -89,6 +87,8 @@ function CartesianChartInner(props: VisualizationProps) {
[originalSettings, outerHeight, outerWidth, autoAdjustSettings],
);
+ const { timelineEvents } = useTimelineEvents({ ...props, settings });
+
const [hoveredTimelineEventGroup, setHoveredTimelineEventGroup] =
useState<TimelineEventGroup | null>(null);
diff --git a/frontend/src/metabase/visualizations/visualizations/CartesianChart/TimelineEventsBand/TimelineEventChip.tsx b/frontend/src/metabase/visualizations/visualizations/CartesianChart/TimelineEventsBand/TimelineEventChip.tsx
index 255b961a143..b54fcd17752 100644
--- a/frontend/src/metabase/visualizations/visualizations/CartesianChart/TimelineEventsBand/TimelineEventChip.tsx
+++ b/frontend/src/metabase/visualizations/visualizations/CartesianChart/TimelineEventsBand/TimelineEventChip.tsx
@@ -1,8 +1,16 @@
import cx from "classnames";
-import { useState } from "react";
+import {
+ type FocusEvent,
+ type KeyboardEvent,
+ type MouseEvent,
+ useEffect,
+ useRef,
+ useState,
+} from "react";
import { t } from "ttag";
-import { Box, HoverCard, Icon, Text, UnstyledButton } from "metabase/ui";
+import { TimelineEventInfo } from "metabase/common/components/TimelineEventInfo";
+import { Box, Icon, Popover, Text, UnstyledButton } from "metabase/ui";
import {
TIMELINE_EVENTS_BAND,
type TimelineEventGroup,
@@ -22,6 +30,7 @@ const POPOVER_OFFSET =
AXIS_CLEARANCE;
export const POPOVER_CLOSE_DELAY_MS = 150;
+const POPOVER_OPEN_DELAY_MS = 50;
interface TimelineEventChipProps {
group: TimelineEventGroup;
@@ -32,7 +41,7 @@ interface TimelineEventChipProps {
zIndex?: number;
className?: string;
onFocus?: () => void;
- onBlur?: () => void;
+ onBlur?: (event: FocusEvent<HTMLButtonElement>) => void;
onGroupHover?: (group: TimelineEventGroup | null) => void;
onOpenTimelines?: (eventIds?: number[]) => void;
onSelectTimelineEvents?: (events: TimelineEvent[]) => void;
@@ -58,17 +67,32 @@ export const TimelineEventChip = ({
}: TimelineEventChipProps) => {
const { events } = group;
- // Remounting the hover card via a fresh key is how an action taken from the
- // popover (e.g. "See all", which opens a sidebar) dismisses it: a hover-only
- // card would otherwise linger under the cursor after the chart re-lays-out,
- // and controlling `opened` fights Mantine's own hover handling. A remounted
- // card starts closed and only re-opens on a new hover.
- const [popoverKey, setPopoverKey] = useState(0);
- const dismissPopover = () => setPopoverKey((key) => key + 1);
+ const [opened, setOpened] = useState(false);
+ // a keyboard-opened popover traps focus so its contents are reachable; a
+ // hover-opened one must not steal focus from wherever the user is typing
+ const [openedByKeyboard, setOpenedByKeyboard] = useState(false);
+ const openedRef = useRef(opened);
+ openedRef.current = opened;
+ const hoverTimeoutRef = useRef<number>();
+ const dropdownRef = useRef<HTMLDivElement>(null);
+
+ const cancelPendingHover = () => {
+ window.clearTimeout(hoverTimeoutRef.current);
+ };
+
+ const dismissPopover = () => {
+ cancelPendingHover();
+ setOpened(false);
+ };
+
+ useEffect(() => cancelPendingHover, []);
const isSingleEvent = events.length === 1;
const hasMoreThanMax = events.length > MAX_VISIBLE_EVENTS;
- const visibleEvents = hasMoreThanMax
+ const canSelect = onSelectTimelineEvents != null;
+ const showDetails = !canSelect && onSeeAllEvents == null;
+ const showSeeAll = hasMoreThanMax && (canSelect || onSeeAllEvents != null);
+ const visibleEvents = showSeeAll
? events.slice(0, MAX_VISIBLE_EVENTS)
: events;
@@ -79,12 +103,52 @@ export const TimelineEventChip = ({
selectedEventIds.includes(event.id),
);
- const canSelect = onSelectTimelineEvents != null;
const handleSelect = () => {
onOpenTimelines?.(isSingleEvent ? undefined : events.map((e) => e.id));
onSelectTimelineEvents?.(events);
};
+ // a popover that is already open by keyboard keeps its focus handling, so a
+ // passing pointer cannot strand the focus inside it
+ const openFromPointer = () => {
+ if (!openedRef.current) {
+ setOpenedByKeyboard(false);
+ }
+ setOpened(true);
+ };
+
+ const handleMouseEnter = () => {
+ cancelPendingHover();
+ onGroupHover?.(group);
+ hoverTimeoutRef.current = window.setTimeout(
+ openFromPointer,
+ POPOVER_OPEN_DELAY_MS,
+ );
+ };
+
+ const handleMouseLeave = () => {
+ cancelPendingHover();
+ onGroupHover?.(null);
+ hoverTimeoutRef.current = window.setTimeout(
+ () => setOpened(false),
+ POPOVER_CLOSE_DELAY_MS,
+ );
+ };
+
+ const handleKeyDown = (event: KeyboardEvent) => {
+ if (event.key === "Escape" && opened) {
+ event.stopPropagation();
+ dismissPopover();
+ }
+ };
+
+ const handleBlur = (event: FocusEvent<HTMLButtonElement>) => {
+ if (!dropdownRef.current?.contains(event.relatedTarget)) {
+ dismissPopover();
+ }
+ onBlur?.(event);
+ };
+
const handleChipClick = () => {
if (areAllEventsSelected) {
onDeselectTimelineEvents?.();
@@ -97,7 +161,6 @@ export const TimelineEventChip = ({
// "See all" hands the whole cluster to `onSeeAllEvents` when provided (its
// host renders the full list); otherwise it falls back to the select/open
// behavior used by the query builder's timeline sidebar.
- const showSeeAll = hasMoreThanMax && (canSelect || onSeeAllEvents != null);
const handleSeeAll = () => {
dismissPopover();
if (onSeeAllEvents) {
@@ -107,17 +170,38 @@ export const TimelineEventChip = ({
}
};
+ const chipLabel = isSingleEvent ? events[0].name : t`${events.length} events`;
+
+ // without a select action, activating the chip shows the details that would
+ // otherwise only be reachable by hovering; a keyboard activation arrives as
+ // a click with no detail count and may also close them
+ const handleClick = (event: MouseEvent) => {
+ cancelPendingHover();
+ if (canSelect) {
+ handleChipClick();
+ } else if (event.detail === 0) {
+ setOpenedByKeyboard(true);
+ setOpened((isOpened) => !isOpened);
+ } else {
+ openFromPointer();
+ }
+ };
+
return (
- <HoverCard
- key={popoverKey}
+ <Popover
+ opened={opened}
+ onChange={setOpened}
+ onDismiss={() => setOpenedByKeyboard(false)}
position="top"
offset={POPOVER_OFFSET}
- openDelay={50}
- closeDelay={POPOVER_CLOSE_DELAY_MS}
shadow="sm"
+ withRoles={!canSelect}
+ trapFocus={openedByKeyboard}
+ returnFocus={openedByKeyboard}
+ closeOnEscape
classNames={{ dropdown: S.bridgeDropdown }}
>
- <HoverCard.Target>
+ <Popover.Target>
<UnstyledButton
className={cx(
S.chip,
@@ -136,14 +220,13 @@ export const TimelineEventChip = ({
data-hidden={hidden}
aria-hidden={hidden}
tabIndex={hidden ? -1 : undefined}
- aria-label={
- isSingleEvent ? events[0].name : t`${events.length} events`
- }
- onClick={canSelect ? handleChipClick : undefined}
- onMouseEnter={() => onGroupHover?.(group)}
- onMouseLeave={() => onGroupHover?.(null)}
+ aria-label={chipLabel}
+ onClick={handleClick}
+ onMouseEnter={handleMouseEnter}
+ onMouseLeave={handleMouseLeave}
+ onKeyDown={handleKeyDown}
onFocus={onFocus}
- onBlur={onBlur}
+ onBlur={handleBlur}
>
{isSingleEvent ? (
<Icon name={getTimelineEventGroupIconName(group)} size={12} />
@@ -153,17 +236,42 @@ export const TimelineEventChip = ({
</Text>
)}
</UnstyledButton>
- </HoverCard.Target>
- <HoverCard.Dropdown p={0} bdrs="0.75rem">
+ </Popover.Target>
+ <Popover.Dropdown
+ ref={dropdownRef}
+ p={0}
+ bdrs="0.75rem"
+ onMouseEnter={cancelPendingHover}
+ onMouseLeave={handleMouseLeave}
+ >
<div data-testid="timeline-event-popover">
{isSingleEvent ? (
- <Box miw="8rem" maw="16rem" p="0.75rem">
- <TimelineEventRow event={events[0]} showIcon={false} />
+ <Box
+ miw="8rem"
+ maw="16rem"
+ mah="20rem"
+ p="md"
+ tabIndex={0}
+ style={{ overflowY: "auto" }}
+ >
+ {showDetails ? (
+ <TimelineEventInfo event={events[0]} />
+ ) : (
+ <TimelineEventRow event={events[0]} showIcon={false} />
+ )}
</Box>
) : (
<>
- <Box w="16rem">
- <TimelineEventsList events={visibleEvents} />
+ <Box
+ w="16rem"
+ mah="20rem"
+ tabIndex={0}
+ style={{ overflowY: "auto" }}
+ >
+ <TimelineEventsList
+ events={visibleEvents}
+ showDetails={showDetails}
+ />
</Box>
{showSeeAll && (
<UnstyledButton
@@ -176,7 +284,7 @@ export const TimelineEventChip = ({
</>
)}
</div>
- </HoverCard.Dropdown>
- </HoverCard>
+ </Popover.Dropdown>
+ </Popover>
);
};
diff --git a/frontend/src/metabase/visualizations/visualizations/CartesianChart/TimelineEventsBand/TimelineEventChip.unit.spec.tsx b/frontend/src/metabase/visualizations/visualizations/CartesianChart/TimelineEventsBand/TimelineEventChip.unit.spec.tsx
index baae8f33694..7ffbd1c806e 100644
--- a/frontend/src/metabase/visualizations/visualizations/CartesianChart/TimelineEventsBand/TimelineEventChip.unit.spec.tsx
+++ b/frontend/src/metabase/visualizations/visualizations/CartesianChart/TimelineEventsBand/TimelineEventChip.unit.spec.tsx
@@ -1,6 +1,7 @@
import userEvent from "@testing-library/user-event";
-import { renderWithProviders, screen, waitFor } from "__support__/ui";
+import { act, renderWithProviders, screen, waitFor } from "__support__/ui";
+import { delay } from "metabase/utils/promise";
import type { TimelineEventGroup } from "metabase/viz-core";
import type { TimelineEvent, TimelineEventId } from "metabase-types/api";
import { createMockTimelineEvent } from "metabase-types/api/mocks";
@@ -159,6 +160,9 @@ describe("TimelineEventChip", () => {
expect(onSelectTimelineEvents).toHaveBeenCalledWith(
singleGroup.group.events,
);
+ expect(
+ screen.queryByTestId("timeline-event-popover"),
+ ).not.toBeInTheDocument();
});
it("deselects the events when a fully selected chip is clicked", async () => {
@@ -211,20 +215,64 @@ describe("TimelineEventChip", () => {
expect(onSelectTimelineEvents).toHaveBeenCalledWith(manyGroup.group.events);
});
- it("hides 'See all' and does not select in degraded contexts", async () => {
- setup({ eventsGroup: manyGroup, withCallbacks: false });
+ it("shows every event in a read-only cluster without opening a sidebar or selecting events", async () => {
+ const {
+ onOpenTimelines,
+ onSelectTimelineEvents,
+ onDeselectTimelineEvents,
+ } = setup({ eventsGroup: manyGroup, withCallbacks: false });
await userEvent.click(screen.getByTestId("timeline-event-chip"));
await userEvent.hover(screen.getByTestId("timeline-event-chip"));
expect(await screen.findByText("Many 1")).toBeInTheDocument();
+ expect(screen.getByText("Many 4")).toBeInTheDocument();
expect(screen.queryByText("See all")).not.toBeInTheDocument();
+ expect(onOpenTimelines).not.toHaveBeenCalled();
+ expect(onSelectTimelineEvents).not.toHaveBeenCalled();
+ expect(onDeselectTimelineEvents).not.toHaveBeenCalled();
+ expect(screen.getByTestId("timeline-event-chip")).toHaveAttribute(
+ "data-selected",
+ "false",
+ );
});
- it("shows 'See all' handing the cluster to onSeeAllEvents without making the chip clickable", async () => {
+ it.each([singleGroup, manyGroup])(
+ "shows read-only event descriptions without requiring creator metadata ($group.events.length events)",
+ async (eventsGroup) => {
+ setup({
+ withCallbacks: false,
+ eventsGroup: {
+ ...eventsGroup,
+ group: {
+ ...eventsGroup.group,
+ events: eventsGroup.group.events.map((event) => ({
+ ...event,
+ creator: undefined,
+ description: `${event.name} description`,
+ })),
+ },
+ },
+ });
+
+ await userEvent.hover(screen.getByTestId("timeline-event-chip"));
+
+ for (const event of eventsGroup.group.events) {
+ expect(
+ await screen.findByText(`${event.name} description`),
+ ).toBeInTheDocument();
+ }
+ expect(screen.queryByRole("checkbox")).not.toBeInTheDocument();
+ expect(
+ screen.queryByRole("button", { name: /edit|delete|new event/i }),
+ ).not.toBeInTheDocument();
+ },
+ );
+
+ it("shows 'See all' handing the cluster to onSeeAllEvents while a chip click only opens the details", async () => {
const onSeeAllEvents = jest.fn();
// No select/open callbacks — the Explorations wiring, where only
- // "See all" should act (a bare chip click must do nothing).
+ // "See all" acts on the events.
const { onSelectTimelineEvents } = setup({
eventsGroup: manyGroup,
withCallbacks: false,
@@ -232,11 +280,13 @@ describe("TimelineEventChip", () => {
});
await userEvent.click(screen.getByTestId("timeline-event-chip"));
+ expect(
+ await screen.findByTestId("timeline-event-popover"),
+ ).toBeInTheDocument();
expect(onSelectTimelineEvents).not.toHaveBeenCalled();
expect(onSeeAllEvents).not.toHaveBeenCalled();
- await userEvent.hover(screen.getByTestId("timeline-event-chip"));
- await userEvent.click(await screen.findByText("See all"));
+ await userEvent.click(screen.getByText("See all"));
expect(onSeeAllEvents).toHaveBeenCalledWith(manyGroup.group.events);
});
@@ -258,6 +308,133 @@ describe("TimelineEventChip", () => {
});
});
+ it("opens and closes the read-only details from the keyboard", async () => {
+ setup({
+ withCallbacks: false,
+ eventsGroup: {
+ ...singleGroup,
+ group: {
+ ...singleGroup.group,
+ events: [
+ createMockTimelineEvent({
+ id: 1,
+ name: "Release v1",
+ description: "The first release candidate is ready.",
+ }),
+ ],
+ },
+ },
+ });
+
+ const chip = screen.getByTestId("timeline-event-chip");
+ expect(chip).toHaveAttribute("aria-expanded", "false");
+
+ await userEvent.tab();
+ expect(chip).toHaveFocus();
+
+ await userEvent.keyboard("{Enter}");
+
+ expect(await screen.findByText("Release v1")).toBeInTheDocument();
+ expect(
+ screen.getByText("The first release candidate is ready."),
+ ).toBeInTheDocument();
+ expect(chip).toHaveAttribute("aria-expanded", "true");
+
+ await userEvent.keyboard("{Escape}");
+
+ await waitFor(() => {
+ expect(
+ screen.queryByTestId("timeline-event-popover"),
+ ).not.toBeInTheDocument();
+ });
+ expect(chip).toHaveAttribute("aria-expanded", "false");
+ await waitFor(() => expect(chip).toHaveFocus());
+ });
+
+ it("returns focus to the chip when the pointer closes keyboard-opened details", async () => {
+ setup({ withCallbacks: false });
+ const chip = screen.getByTestId("timeline-event-chip");
+
+ await userEvent.tab();
+ await userEvent.keyboard("{Enter}");
+ await waitFor(() => expect(chip).not.toHaveFocus());
+
+ await userEvent.hover(chip);
+ // the hover-open delay must elapse for the pointer to take over the popover
+ await act(() => delay(100));
+ await userEvent.unhover(chip);
+
+ await waitFor(() => {
+ expect(
+ screen.queryByTestId("timeline-event-popover"),
+ ).not.toBeInTheDocument();
+ });
+ await waitFor(() => expect(chip).toHaveFocus());
+ });
+
+ it("leaves focus where the user clicked when keyboard-opened details are dismissed", async () => {
+ setup({ withCallbacks: false });
+ const chip = screen.getByTestId("timeline-event-chip");
+
+ await userEvent.tab();
+ await userEvent.keyboard("{Enter}");
+ await waitFor(() => expect(chip).not.toHaveFocus());
+
+ await userEvent.click(document.body);
+
+ await waitFor(() => {
+ expect(
+ screen.queryByTestId("timeline-event-popover"),
+ ).not.toBeInTheDocument();
+ });
+ await act(() => delay(50));
+ expect(chip).not.toHaveFocus();
+ });
+
+ it("closes hover-opened details when focus leaves the chip", async () => {
+ setup({ withCallbacks: false });
+
+ await userEvent.tab();
+ await userEvent.hover(screen.getByTestId("timeline-event-chip"));
+ expect(
+ await screen.findByTestId("timeline-event-popover"),
+ ).toBeInTheDocument();
+
+ await userEvent.tab({ shift: true });
+
+ await waitFor(() => {
+ expect(
+ screen.queryByTestId("timeline-event-popover"),
+ ).not.toBeInTheDocument();
+ });
+ });
+
+ it("puts 'See all' within keyboard reach of a keyboard-opened cluster", async () => {
+ const onSeeAllEvents = jest.fn();
+ setup({ eventsGroup: manyGroup, withCallbacks: false, onSeeAllEvents });
+
+ await userEvent.tab();
+ await userEvent.keyboard("{Enter}");
+ expect(await screen.findByText("See all")).toBeInTheDocument();
+
+ await waitFor(() => {
+ expect(screen.getByTestId("timeline-event-chip")).not.toHaveFocus();
+ });
+ await userEvent.tab();
+ expect(screen.getByText("See all")).toHaveFocus();
+
+ await userEvent.keyboard("{Enter}");
+ expect(onSeeAllEvents).toHaveBeenCalledWith(manyGroup.group.events);
+ });
+
+ it("does not announce a dialog on a chip whose activation selects events", () => {
+ setup();
+
+ expect(screen.getByTestId("timeline-event-chip")).not.toHaveAttribute(
+ "aria-haspopup",
+ );
+ });
+
it("marks the chip as hidden when hidden", () => {
setup({ eventsGroup: singleGroup, hidden: true });
expect(screen.getByTestId("timeline-event-chip")).toHaveAttribute(
diff --git a/frontend/src/metabase/visualizations/visualizations/CartesianChart/TimelineEventsBand/TimelineEventStack.tsx b/frontend/src/metabase/visualizations/visualizations/CartesianChart/TimelineEventsBand/TimelineEventStack.tsx
index 3486cbc6d71..71d888da8d2 100644
--- a/frontend/src/metabase/visualizations/visualizations/CartesianChart/TimelineEventsBand/TimelineEventStack.tsx
+++ b/frontend/src/metabase/visualizations/visualizations/CartesianChart/TimelineEventsBand/TimelineEventStack.tsx
@@ -1,4 +1,4 @@
-import { useCallback, useEffect, useRef } from "react";
+import { type FocusEvent, useCallback, useEffect, useRef } from "react";
import {
TIMELINE_BAND_HEIGHT,
@@ -91,6 +91,15 @@ export const TimelineEventStack = ({
onExpandedChange(true);
};
+ const handleMemberBlur = (event: FocusEvent<HTMLButtonElement>) => {
+ const isInsideDropdown =
+ event.relatedTarget instanceof Element &&
+ event.relatedTarget.closest(`.${S.bridgeDropdown}`) != null;
+ if (!isInsideDropdown) {
+ scheduleCollapse();
+ }
+ };
+
// React's mouse-leave tracking is unreliable across the members' portaled
// popovers (moving chip → popover → chart never reports leaving the stack),
// so while expanded the pointer is tracked at the document level instead:
@@ -188,7 +197,7 @@ export const TimelineEventStack = ({
hidden={hidden}
selectedEventIds={selectedEventIds}
onFocus={handleMemberFocus}
- onBlur={scheduleCollapse}
+ onBlur={handleMemberBlur}
onGroupHover={onGroupHover}
onOpenTimelines={onOpenTimelines}
onSelectTimelineEvents={onSelectTimelineEvents}
diff --git a/frontend/src/metabase/visualizations/visualizations/CartesianChart/TimelineEventsBand/TimelineEventsBand.module.css b/frontend/src/metabase/visualizations/visualizations/CartesianChart/TimelineEventsBand/TimelineEventsBand.module.css
index 24771b86624..adf7a24a583 100644
--- a/frontend/src/metabase/visualizations/visualizations/CartesianChart/TimelineEventsBand/TimelineEventsBand.module.css
+++ b/frontend/src/metabase/visualizations/visualizations/CartesianChart/TimelineEventsBand/TimelineEventsBand.module.css
@@ -33,8 +33,8 @@
/*
* The bridge extends past the dropdown, so keep overflow visible — otherwise the
* default `overflow: auto` treats the bridge as content and adds a scrollbar.
- * The doubled selector wins over the default dropdown styles. The content always
- * fits (at most three rows plus "See all"), so no scrolling is needed.
+ * The doubled selector wins over the default dropdown styles. Long event lists
+ * scroll inside the dropdown instead.
*/
.bridgeDropdown.bridgeDropdown {
overflow: visible;
diff --git a/frontend/src/metabase/visualizations/visualizations/CartesianChart/TimelineEventsBand/TimelineEventsBand.stories.tsx b/frontend/src/metabase/visualizations/visualizations/CartesianChart/TimelineEventsBand/TimelineEventsBand.stories.tsx
index 0d0f6217dac..88f03791b39 100644
--- a/frontend/src/metabase/visualizations/visualizations/CartesianChart/TimelineEventsBand/TimelineEventsBand.stories.tsx
+++ b/frontend/src/metabase/visualizations/visualizations/CartesianChart/TimelineEventsBand/TimelineEventsBand.stories.tsx
@@ -92,6 +92,7 @@ const Template = () => (
width={800}
timelineEvents={TIMELINE_EVENTS}
selectedTimelineEventIds={[5]}
+ onSelectTimelineEvents={() => {}}
/>
</Box>
</VisualizationWrapper>
diff --git a/frontend/src/metabase/visualizations/visualizations/CartesianChart/TimelineEventsBand/TimelineEventsList.tsx b/frontend/src/metabase/visualizations/visualizations/CartesianChart/TimelineEventsBand/TimelineEventsList.tsx
index 74314da42ea..21f30259691 100644
--- a/frontend/src/metabase/visualizations/visualizations/CartesianChart/TimelineEventsBand/TimelineEventsList.tsx
+++ b/frontend/src/metabase/visualizations/visualizations/CartesianChart/TimelineEventsBand/TimelineEventsList.tsx
@@ -1,4 +1,5 @@
import { DateTime } from "metabase/common/components/DateTime";
+import { TimelineEventInfo } from "metabase/common/components/TimelineEventInfo";
import { Box, Flex, Icon, Stack, Text } from "metabase/ui";
import type { TimelineEvent } from "metabase-types/api";
@@ -39,13 +40,21 @@ export const TimelineEventRow = ({
interface TimelineEventsListProps {
events: TimelineEvent[];
+ showDetails?: boolean;
}
-export const TimelineEventsList = ({ events }: TimelineEventsListProps) => (
+export const TimelineEventsList = ({
+ events,
+ showDetails = false,
+}: TimelineEventsListProps) => (
<Stack gap={0} data-testid="timeline-events-list">
{events.map((event) => (
<Box key={event.id} className={S.listItemWrapper}>
- <TimelineEventRow event={event} />
+ {showDetails ? (
+ <TimelineEventInfo event={event} />
+ ) : (
+ <TimelineEventRow event={event} />
+ )}
</Box>
))}
</Stack>
diff --git a/frontend/src/metabase/viz-core/echarts/cartesian/timeline-events/model.ts b/frontend/src/metabase/viz-core/echarts/cartesian/timeline-events/model.ts
index 44abc5c1db7..c333bf5ed1c 100644
--- a/frontend/src/metabase/viz-core/echarts/cartesian/timeline-events/model.ts
+++ b/frontend/src/metabase/viz-core/echarts/cartesian/timeline-events/model.ts
@@ -2,6 +2,7 @@ import type { SupportedUnit } from "types/dayjs";
import _ from "underscore";
import { type OpUnitType, dayjs } from "metabase/dayjs";
+import { parseTimestamp } from "metabase/utils/time-dayjs";
import type { TimelineEvent } from "metabase-types/api";
import { CHART_STYLE } from "../constants/style";
@@ -93,17 +94,30 @@ export const buildTimelineEventClusters = (
return clusters;
};
+export const isTimelineEventInRange = (
+ event: TimelineEvent,
+ [min, max]: DateRange,
+ interval: TimeSeriesInterval | null,
+) => {
+ const unit: SupportedUnit | undefined = interval?.unit;
+ // `max` is the start of the final bucket, so a multi-unit interval — a two-month bucket, say — runs past it;
+ // comparing at unit granularity alone would drop an event in the rest of that bucket
+ const end =
+ unit && interval
+ ? // SupportedUnit is the dayjs unit set this axis uses, so it is always a valid OpUnitType here
+ max.add(interval.count - 1, unit as OpUnitType)
+ : max;
+ return parseTimestamp(event.timestamp).isBetween(min, end, unit, "[]");
+};
+
const getTimelineEventsInsideRange = (
timelineEvents: TimelineEvent[],
range: DateRange,
- unit: SupportedUnit,
-) => {
- const [min, max] = range;
-
- return timelineEvents.filter((event) => {
- return dayjs(event.timestamp).isBetween(min, max, unit, "[]");
- });
-};
+ interval: TimeSeriesInterval,
+) =>
+ timelineEvents.filter((event) =>
+ isTimelineEventInRange(event, range, interval),
+ );
export const getTimelineEventsModel = (
chartModel: BaseCartesianChartModel,
@@ -122,7 +136,7 @@ export const getTimelineEventsModel = (
const visibleTimelineEvents = getTimelineEventsInsideRange(
timelineEvents,
dimensionRange,
- chartModel.xAxisModel.interval.unit,
+ chartModel.xAxisModel.interval,
);
const hasTimelineEvents = visibleTimelineEvents.length !== 0;
diff --git a/frontend/src/metabase/viz-core/index.ts b/frontend/src/metabase/viz-core/index.ts
index 452a5afe990..cf515f04977 100644
--- a/frontend/src/metabase/viz-core/index.ts
+++ b/frontend/src/metabase/viz-core/index.ts
@@ -56,6 +56,7 @@ export type {
CartesianChartModel,
ChartDataset,
DataKey,
+ DateRange,
Datum,
DimensionModel,
LegendItem,
@@ -77,7 +78,10 @@ export {
export { TREND_LINE_DASH } from "./echarts/cartesian/option/trend-line";
export { getScatterPlotModel } from "./echarts/cartesian/scatter/model";
export { getScatterPlotOption } from "./echarts/cartesian/scatter/option";
-export { getTimelineEventsModel } from "./echarts/cartesian/timeline-events/model";
+export {
+ getTimelineEventsModel,
+ isTimelineEventInRange,
+} from "./echarts/cartesian/timeline-events/model";
export { EMPTY_TIMELINE_SELECTION_SERIES } from "./echarts/cartesian/timeline-events/option";
export type {
TimelineEventCluster,
@@ -269,6 +273,7 @@ export { computeMinimalBoundsCoordinates } from "./lib/mapping";
export { computeChange, computeNumericDataInterval } from "./lib/numeric";
export { getCanonicalRowKey } from "./lib/region-codes";
export {
+ canDisplayTimelineEvents,
canSavePng,
getIconForVisualizationType,
getMaxDimensionsSupported,
@@ -340,10 +345,7 @@ export {
export { nestedSettings } from "./lib/settings/nested";
export { keyForSingleSeries } from "./lib/settings/series";
export { getStackOffset } from "./lib/settings/stacking";
-export {
- getTimelineEventSettings,
- TIMELINE_EVENTS_SETTINGS,
-} from "./lib/settings/timelineEvents";
+export { TIMELINE_EVENTS_SETTINGS } from "./lib/settings/timelineEvents";
export {
extendCardWithDashcardSettings,
mergeSettings,
@@ -387,6 +389,7 @@ export {
} from "./lib/table_format";
export { truncateText } from "./lib/text";
export { dimensionIsTimeseries } from "./lib/timeseries";
+export { getTimeseriesXAxis } from "./lib/timeseries-x-axis";
export { formatValueForTooltipWithoutScaling } from "./lib/tooltip";
export {
computePreviousPeriodChange,
@@ -496,6 +499,7 @@ export type {
RenderingContext,
StaticVisualizationProps,
} from "./types/rendering";
+export type { TimeseriesXAxis } from "./types/timeseries";
export type {
AggregationFunction,
ChartSettingColorRangeProps,
diff --git a/frontend/src/metabase/viz-core/lib/registry.ts b/frontend/src/metabase/viz-core/lib/registry.ts
index eca004d6f8e..07054bbbed4 100644
--- a/frontend/src/metabase/viz-core/lib/registry.ts
+++ b/frontend/src/metabase/viz-core/lib/registry.ts
@@ -314,6 +314,15 @@ export function getVisualizationTransformed(
return { series, visualization };
}
+export function canDisplayTimelineEvents(
+ display: VisualizationDisplay | null | undefined,
+) {
+ return (
+ display != null &&
+ "timeline_events.enabled" in (visualizations.get(display)?.settings ?? {})
+ );
+}
+
export function isCartesianChart(display: VisualizationDisplay) {
const visualization = visualizations.get(display);
const settingNames = Object.keys(visualization?.settings ?? {});
diff --git a/frontend/src/metabase/viz-core/lib/settings/timelineEvents.ts b/frontend/src/metabase/viz-core/lib/settings/timelineEvents.ts
index 1365cf4f3c4..edd750a64b6 100644
--- a/frontend/src/metabase/viz-core/lib/settings/timelineEvents.ts
+++ b/frontend/src/metabase/viz-core/lib/settings/timelineEvents.ts
@@ -1,64 +1,19 @@
-import type { Timeline, TimelineEventId, TimelineId } from "metabase-types/api";
-
import type { VisualizationSettingsDefinitions } from "../../types";
+// dashboard: false keeps these on the question; dashcards never persist them
export const TIMELINE_EVENTS_SETTINGS: VisualizationSettingsDefinitions = {
+ "timeline_events.enabled": {
+ getDefault: () => true,
+ dashboard: false,
+ },
"timeline.selected_timeline_ids": {
hidden: true,
+ dashboard: false,
getDefault: () => [],
},
"timeline.excluded_timeline_event_ids": {
hidden: true,
+ dashboard: false,
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/viz-core/lib/settings/timelineEvents.unit.spec.ts b/frontend/src/metabase/viz-core/lib/settings/timelineEvents.unit.spec.ts
deleted file mode 100644
index aab251b3117..00000000000
--- a/frontend/src/metabase/viz-core/lib/settings/timelineEvents.unit.spec.ts
+++ /dev/null
@@ -1,113 +0,0 @@
-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/viz-core/lib/timeseries-x-axis.ts b/frontend/src/metabase/viz-core/lib/timeseries-x-axis.ts
new file mode 100644
index 00000000000..fed51d1536e
--- /dev/null
+++ b/frontend/src/metabase/viz-core/lib/timeseries-x-axis.ts
@@ -0,0 +1,39 @@
+import * as d3 from "d3";
+
+import { dayjs } from "metabase/dayjs";
+import { isNotNull } from "metabase/utils/types";
+import type { Series } from "metabase-types/api";
+import { isAbsoluteDateTimeUnit } from "metabase-types/guards/date-time";
+
+import {
+ computeTimeseriesDataInterval,
+ minTimeseriesUnit,
+} from "../echarts/cartesian/utils/timeseries";
+import type { ComputedVisualizationSettings } from "../types/computed-settings";
+import type { TimeseriesXAxis } from "../types/timeseries";
+
+import { getXValues, isTimeseries } from "./renderer_utils";
+
+export const getTimeseriesXAxis = (
+ series: Series,
+ settings: ComputedVisualizationSettings,
+): TimeseriesXAxis | null => {
+ if (!isTimeseries(settings)) {
+ return null;
+ }
+ const xValues = getXValues({ series, settings });
+ const [min, max] = d3.extent(xValues.filter(dayjs.isDayjs));
+ const columns = series[0]?.data?.cols ?? [];
+ const columnUnits = (settings["graph.dimensions"] ?? [])
+ .map((dimension) => columns.find((column) => column?.name === dimension))
+ .map((column) =>
+ isAbsoluteDateTimeUnit(column?.unit) ? column.unit : null,
+ )
+ .filter(isNotNull);
+ return {
+ domain: min && max ? [min, max] : null,
+ interval:
+ computeTimeseriesDataInterval(xValues, minTimeseriesUnit(columnUnits)) ??
+ null,
+ };
+};
diff --git a/frontend/src/metabase/viz-core/lib/timeseries-x-axis.unit.spec.ts b/frontend/src/metabase/viz-core/lib/timeseries-x-axis.unit.spec.ts
new file mode 100644
index 00000000000..ba654354bca
--- /dev/null
+++ b/frontend/src/metabase/viz-core/lib/timeseries-x-axis.unit.spec.ts
@@ -0,0 +1,62 @@
+import type { DatetimeUnit, Series } from "metabase-types/api";
+import {
+ createMockDatetimeColumn,
+ createMockNumericColumn,
+ createMockSingleSeries,
+} from "metabase-types/api/mocks";
+
+import type { ComputedVisualizationSettings } from "../types/computed-settings";
+
+import { getTimeseriesXAxis } from "./timeseries-x-axis";
+
+const createSeries = (
+ dates: string[],
+ unit: DatetimeUnit = "month",
+): Series => [
+ createMockSingleSeries(
+ {},
+ {
+ data: {
+ cols: [
+ createMockDatetimeColumn({ name: "CREATED_AT", unit }),
+ createMockNumericColumn({ name: "count" }),
+ ],
+ rows: dates.map((date, index) => [date, index]),
+ },
+ },
+ ),
+];
+
+const TIMESERIES_SETTINGS: ComputedVisualizationSettings = {
+ "graph.x_axis.scale": "timeseries",
+ "graph.dimensions": ["CREATED_AT"],
+ "graph.metrics": ["count"],
+};
+
+const ORDINAL_SETTINGS: ComputedVisualizationSettings = {
+ ...TIMESERIES_SETTINGS,
+ "graph.x_axis.scale": "ordinal",
+};
+
+const DATES = ["2024-03-01", "2024-01-01", "2024-02-01"];
+
+describe("getTimeseriesXAxis", () => {
+ it("returns the domain and the data interval of a timeseries chart", () => {
+ const xAxis = getTimeseriesXAxis(createSeries(DATES), TIMESERIES_SETTINGS);
+ expect(xAxis?.domain?.[0].format("YYYY-MM-DD")).toBe("2024-01-01");
+ expect(xAxis?.domain?.[1].format("YYYY-MM-DD")).toBe("2024-03-01");
+ expect(xAxis?.interval).toMatchObject({ count: 1, unit: "month" });
+ });
+
+ it("returns a null domain without rows", () => {
+ expect(
+ getTimeseriesXAxis(createSeries([]), TIMESERIES_SETTINGS)?.domain,
+ ).toBeNull();
+ });
+
+ it("returns null when the x axis is not a timeseries", () => {
+ expect(
+ getTimeseriesXAxis(createSeries(DATES), ORDINAL_SETTINGS),
+ ).toBeNull();
+ });
+});
diff --git a/frontend/src/metabase/viz-core/shared/settings-adjustments.ts b/frontend/src/metabase/viz-core/shared/settings-adjustments.ts
index 590f76d1d6a..ca08863489f 100644
--- a/frontend/src/metabase/viz-core/shared/settings-adjustments.ts
+++ b/frontend/src/metabase/viz-core/shared/settings-adjustments.ts
@@ -4,6 +4,8 @@ const HIDE_Y_AXIS_LABEL_WIDTH_THRESHOLD = 360;
const HIDE_X_AXIS_LABEL_HEIGHT_THRESHOLD = 200;
const HIDE_Y_AXIS_HEIGHT_THRESHOLD = 150;
const INTERPOLATE_LINE_THRESHOLD = 150;
+const HIDE_TIMELINE_EVENTS_HEIGHT_THRESHOLD = 200;
+const HIDE_TIMELINE_EVENTS_WIDTH_THRESHOLD = 240;
type getAdjustedSettingsProps = {
settings: ComputedVisualizationSettings;
@@ -37,5 +39,12 @@ export const getDashboardAdjustedSettings = ({
adjusted["graph.y_axis.axis_enabled"] = false;
}
+ if (
+ height <= HIDE_TIMELINE_EVENTS_HEIGHT_THRESHOLD ||
+ width <= HIDE_TIMELINE_EVENTS_WIDTH_THRESHOLD
+ ) {
+ adjusted["timeline_events.enabled"] = false;
+ }
+
return adjusted;
};
diff --git a/frontend/src/metabase/viz-core/types/definition.ts b/frontend/src/metabase/viz-core/types/definition.ts
index 71936549f30..81819293c5f 100644
--- a/frontend/src/metabase/viz-core/types/definition.ts
+++ b/frontend/src/metabase/viz-core/types/definition.ts
@@ -349,6 +349,7 @@ export type VisualizationSettingsDefinitions = {
>;
time_enabled?: DatasetColumnSettingDefinition<Value, Props>;
time_style?: DatasetColumnSettingDefinition<Value, Props>;
+ "timeline_events.enabled"?: SeriesSettingDefinition<Value, Props>;
title?: SingleSeriesSettingDefinition<Value, Props>;
"treemap._groups_widget"?: SeriesSettingDefinition<
Value,
diff --git a/frontend/src/metabase/viz-core/types/timeseries.ts b/frontend/src/metabase/viz-core/types/timeseries.ts
new file mode 100644
index 00000000000..648eec86259
--- /dev/null
+++ b/frontend/src/metabase/viz-core/types/timeseries.ts
@@ -0,0 +1,9 @@
+import type {
+ DateRange,
+ TimeSeriesInterval,
+} from "../echarts/cartesian/model/types";
+
+export interface TimeseriesXAxis {
+ domain: DateRange | null;
+ interval: TimeSeriesInterval | null;
+}
diff --git a/frontend/test/__support__/server-mocks/embed.ts b/frontend/test/__support__/server-mocks/embed.ts
index 3c3a90c32fe..6902d44f426 100644
--- a/frontend/test/__support__/server-mocks/embed.ts
+++ b/frontend/test/__support__/server-mocks/embed.ts
@@ -1,7 +1,7 @@
import fetchMock from "fetch-mock";
import type { Card, Dashboard, DashboardCard } from "metabase-types/api";
-import type { EntityToken } from "metabase-types/api/entity";
+import type { EntityToken, EntityUuid } from "metabase-types/api/entity";
import { createMockDataset } from "metabase-types/api/mocks";
export function setupEmbedDashboardEndpoints(
@@ -21,6 +21,13 @@ export function setupEmbedDashboardEndpoints(
}
}
+export function setupPublicDashboardEndpoint(
+ uuid: EntityUuid,
+ dashboard: Dashboard,
+) {
+ fetchMock.get(`path:/api/public/dashboard/${uuid}`, dashboard);
+}
+
export function setupEmbeddableEntitiesEndpoints({
dashboards = [],
cards = [],
diff --git a/frontend/test/__support__/server-mocks/timeline.ts b/frontend/test/__support__/server-mocks/timeline.ts
index 6721eeada8d..ab69132f914 100644
--- a/frontend/test/__support__/server-mocks/timeline.ts
+++ b/frontend/test/__support__/server-mocks/timeline.ts
@@ -2,10 +2,8 @@ import fetchMock from "fetch-mock";
import type { Timeline } from "metabase-types/api";
-export function setupTimelinesEndpoints(timelines: Timeline[], delay?: number) {
- fetchMock.get(
- "path:/api/timeline",
- timelines,
- delay != null ? { delay } : undefined,
- );
+type TimelineResponse = Timeline[] | (() => Promise<Timeline[]>);
+
+export function setupTimelinesEndpoints(response: TimelineResponse) {
+ fetchMock.get("path:/api/timeline", response);
}
diff --git a/frontend/test/__support__/state/dashboard.ts b/frontend/test/__support__/state/dashboard.ts
index bf08ccf0048..1889c204262 100644
--- a/frontend/test/__support__/state/dashboard.ts
+++ b/frontend/test/__support__/state/dashboard.ts
@@ -27,6 +27,12 @@ export const createMockDashboardState = (
sidebar: {
props: {},
},
+ timelineEvents: {
+ overrides: {},
+ enabledByDashCard: {},
+ selection: null,
+ hasTrackedEventsShown: false,
+ },
selectedTabId: null,
missingActionParameters: null,
autoApplyFilters: {
diff --git a/frontend/test/__support__/state/qb.ts b/frontend/test/__support__/state/qb.ts
index c72ca4f0821..daf693dfb55 100644
--- a/frontend/test/__support__/state/qb.ts
+++ b/frontend/test/__support__/state/qb.ts
@@ -31,7 +31,6 @@ export const createMockQueryBuilderUIControlsState = (
notebookNativePreviewSidebarWidth: null,
showSidebarTitle: false,
modal: null,
- modalContext: null,
dataReferenceStack: null,
highlightedNativeQueryLineNumbers: [],
isShowingListViewConfiguration: false,
@@ -78,7 +77,6 @@ export const createMockQueryBuilderState = (
selectedTimelineEventIds: [],
metadataDiff: {},
- visibleTimelineEventIds: [],
currentState: null,
diff --git a/frontend/test/__support__/timelines.ts b/frontend/test/__support__/timelines.ts
new file mode 100644
index 00000000000..09233c71635
--- /dev/null
+++ b/frontend/test/__support__/timelines.ts
@@ -0,0 +1,20 @@
+import { screen, within } from "@testing-library/react";
+
+import { checkNotNull } from "metabase/utils/types";
+
+const getCardByLabel = (label: string, text: string) =>
+ checkNotNull(
+ screen
+ .getAllByLabelText(label)
+ .find((card) => within(card).queryByText(text) != null),
+ );
+
+export const getTimelineEventCheckbox = (eventName: string) =>
+ within(getCardByLabel("Timeline event card", eventName)).getByRole(
+ "checkbox",
+ );
+
+export const getTimelineCheckbox = (timelineName: string) =>
+ within(getCardByLabel("Timeline card header", timelineName)).getByRole(
+ "checkbox",
+ );
diff --git a/resources/migrations/065/20260909_timeline_event_entity_id.yaml b/resources/migrations/065/20260909_timeline_event_entity_id.yaml
new file mode 100644
index 00000000000..69752636874
--- /dev/null
+++ b/resources/migrations/065/20260909_timeline_event_entity_id.yaml
@@ -0,0 +1,65 @@
+## Timeline events get an entity_id so serialization and remote sync can key them on a stable, portable
+## identifier instead of a per-instance row id. The shape mirrors 20260723_backfill_entity_ids: add the column
+## nullable, backfill it, then add NOT NULL and UNIQUE. All three dialect variants of the backfill live in one
+## changeset so every database executes (and records) it — a changeset whose only change is dbms-filtered away
+## never reaches the changelog, which breaks consolidation.
+
+databaseChangeLog:
+ - changeSet:
+ id: v65.h1c4r5
+ author: havenchyk
+ comment: Add a portable entity ID to timeline events
+ changes:
+ - addColumn:
+ tableName: timeline_event
+ columns:
+ - column:
+ name: entity_id
+ type: char(21)
+ remarks: NanoID used to identify the event across instances
+ constraints:
+ nullable: true
+ rollback:
+ - dropColumn:
+ tableName: timeline_event
+ columnName: entity_id
+
+ - changeSet:
+ id: v65.zvhbd7
+ author: havenchyk
+ comment: Backfill entity IDs for existing timeline events
+ changes:
+ - sql:
+ dbms: postgresql
+ sql: UPDATE timeline_event SET entity_id = substr(replace(gen_random_uuid()::text, '-', ''), 1, 21) WHERE entity_id IS NULL;
+ - sql:
+ dbms: mysql,mariadb
+ sql: UPDATE timeline_event SET entity_id = substr(replace(uuid(), '-', ''), 1, 21) WHERE entity_id IS NULL;
+ - sql:
+ dbms: h2
+ sql: UPDATE timeline_event SET entity_id = substr(replace(cast(random_uuid() as varchar), '-', ''), 1, 21) WHERE entity_id IS NULL;
+ rollback: []
+
+ - changeSet:
+ id: v65.0npr54
+ author: havenchyk
+ comment: Require an entity ID on timeline events
+ changes:
+ - addNotNullConstraint:
+ tableName: timeline_event
+ columnName: entity_id
+ columnDataType: char(21)
+
+ - changeSet:
+ id: v65.lpm4z3
+ author: havenchyk
+ comment: entity_id is unique on timeline events
+ changes:
+ - addUniqueConstraint:
+ tableName: timeline_event
+ columnNames: entity_id
+ constraintName: uq_timeline_event_entity_id
+ rollback:
+ - dropUniqueConstraint:
+ tableName: timeline_event
+ constraintName: uq_timeline_event_entity_id
diff --git a/snowplow/iglu-client-embedded/schemas/com.metabase/timeline/jsonschema/1-0-1 b/snowplow/iglu-client-embedded/schemas/com.metabase/timeline/jsonschema/1-0-1
new file mode 100644
index 00000000000..19ddcf6237a
--- /dev/null
+++ b/snowplow/iglu-client-embedded/schemas/com.metabase/timeline/jsonschema/1-0-1
@@ -0,0 +1,64 @@
+{
+ "$schema": "http://iglucentral.com/schemas/com.snowplowanalytics.self-desc/schema/jsonschema/1-0-0#",
+ "description": "Event timelines",
+ "self": {
+ "vendor": "com.metabase",
+ "name": "timeline",
+ "format": "jsonschema",
+ "version": "1-0-1"
+ },
+ "type": "object",
+ "properties": {
+ "event": {
+ "description": "Event name",
+ "type": "string",
+ "enum": [
+ "new_event_created"
+ ],
+ "maxLength": 1024
+ },
+ "source": {
+ "description": "String identifying the product location where the event happened",
+ "type": [
+ "string",
+ "null"
+ ],
+ "enum": [
+ "question",
+ "dashboard",
+ "collections",
+ "api"
+ ],
+ "maxLength": 1024
+ },
+ "question_id": {
+ "description": "Unique identifier for question, only applicable if created from a question",
+ "type": [
+ "integer",
+ "null"
+ ],
+ "minimum": 0,
+ "maximum": 2147483647
+ },
+ "collection_id": {
+ "description": "Unique identifier for collection, only applicable if created from a collection",
+ "type": [
+ "integer",
+ "null"
+ ],
+ "minimum": 0,
+ "maximum": 2147483647
+ },
+ "time_matters": {
+ "description": "Whether the user has added time resolution to the event",
+ "type": [
+ "boolean",
+ "null"
+ ]
+ }
+ },
+ "required": [
+ "event"
+ ],
+ "additionalProperties": true
+}
diff --git a/src/metabase/agent_api/api.clj b/src/metabase/agent_api/api.clj
index 40ed93817cf..85eb14499b9 100644
--- a/src/metabase/agent_api/api.clj
+++ b/src/metabase/agent_api/api.clj
@@ -1348,6 +1348,8 @@
collide with that tab's cards; a move only reflows cards sharing the moved card's tab."
[dashboard-id mutations]
(let [current (agent-api.db/dashcards dashboard-id)
+ ;; the dashboard row is the same for every mutation in the batch
+ dashboard (agent-api.db/dashboard dashboard-id)
;; one fetch serves the default tab, per-mutation tab_id validation, and collision grouping
tab-ids (agent-api.db/dashboard-tab-ids dashboard-id)
;; new dashcards land on the first tab, alongside any nil-tab dashcards, which the
@@ -1374,6 +1376,10 @@
(case action
"add"
(let [card (api/read-check :model/Card card_id)
+ ;; A card placed on a shared dashboard exposes its selected timeline events, so the
+ ;; same read check the REST writer applies runs here too.
+ _ (queries/check-newly-exposed-dashcards-timeline-permissions!
+ dashboard current [{:card_id card_id}])
;; A card internal to a different dashboard (a dashboard question) can't be added
;; here — mirrors the REST dashcard-creation gate.
_ (api/check (or (nil? (:dashboard_id card))
diff --git a/src/metabase/analytics/snowplow.clj b/src/metabase/analytics/snowplow.clj
index 5db9801e0f3..b93274e5d8b 100644
--- a/src/metabase/analytics/snowplow.clj
+++ b/src/metabase/analytics/snowplow.clj
@@ -45,7 +45,7 @@
:snowplow/metabot "1-0-1"
:snowplow/search "1-0-1"
:snowplow/model "1-0-0"
- :snowplow/timeline "1-0-0"
+ :snowplow/timeline "1-0-1"
:snowplow/task "1-0-0"
:snowplow/upsell "1-0-0"
:snowplow/action "1-0-0"
diff --git a/src/metabase/dashboards/schema.clj b/src/metabase/dashboards/schema.clj
index 26addd126a9..747a5af4780 100644
--- a/src/metabase/dashboards/schema.clj
+++ b/src/metabase/dashboards/schema.clj
@@ -7,6 +7,7 @@
[metabase.lib.schema.parameter :as lib.schema.parameter]
[metabase.parameters.schema :as parameters.schema]
[metabase.queries.schema :as queries.schema]
+ [metabase.timeline.schema]
[metabase.util.malli.registry :as mr]
[metabase.util.malli.schema :as ms]))
@@ -101,6 +102,8 @@
[:collection_authority_level {:optional true} [:maybe [:or :keyword :string]]]
[:card {:optional true} [:maybe [:ref ::queries.schema/card]]]
[:series {:optional true} [:maybe [:sequential [:ref ::queries.schema/card]]]]
+ ;; hydrated onto public and embedded dashcards only
+ [:timeline_events {:optional true} [:maybe [:sequential [:ref :metabase.timeline.schema/timeline-event]]]]
[:action {:optional true} [:maybe [:merge
:metabase.actions.schema/action
[:map {:closed true}
diff --git a/src/metabase/dashboards/write.clj b/src/metabase/dashboards/write.clj
index 029ace96757..d1f345ca8e4 100644
--- a/src/metabase/dashboards/write.clj
+++ b/src/metabase/dashboards/write.clj
@@ -220,6 +220,10 @@
(defn- do-update-dashcards!
[dashboard current-cards new-cards]
(let [{:keys [to-create to-update to-delete]} (u/row-diff current-cards new-cards)]
+ ;; Grandfather against the dashboard as it was before this update, as REST does: a card that already showed
+ ;; its events keeps them even if its tab is deleted and it is re-added elsewhere in the same request.
+ (queries/check-newly-exposed-dashcards-timeline-permissions!
+ dashboard (:dashcards dashboard) (concat to-create to-update))
(dashboard/archive-or-unarchive-internal-dashboard-questions! (:id dashboard) new-cards)
;; Check both created and updated dashcards: a "Replace" keeps the dashcard id and only swaps
;; card_id, so it lands in `to-update`, not `to-create` (UXW-4731). Card ids the dashboard already
@@ -473,18 +477,19 @@
{:keys [copy discard reference]} (cond-> (cards-to-copy deep-copy? (:dashcards old-dashboard))
dashboards-only? reference-metrics)]
{:copied (into {} (for [[id to-copy] copy]
- [id (queries/create-card!
- (cond-> to-copy
- true (assoc :collection_id dest-coll-id)
- same-collection? (update :name #(str % " - " (tru "Duplicate")))
- (or (:dashboard_id to-copy)
- dashboards-only?) (-> (assoc :dashboard_id (u/the-id new-dashboard))
- (dissoc :collection_position)))
- @api/*current-user*
- ;; creating cards from a transaction. wait until tx complete to signal event
- true
- ;; do not autoplace these cards. we will create the dashboard cards ourselves.
- false)]))
+ [id (queries/with-copy-source-card to-copy
+ (queries/create-card!
+ (cond-> to-copy
+ true (assoc :collection_id dest-coll-id)
+ same-collection? (update :name #(str % " - " (tru "Duplicate")))
+ (or (:dashboard_id to-copy)
+ dashboards-only?) (-> (assoc :dashboard_id (u/the-id new-dashboard))
+ (dissoc :collection_position)))
+ @api/*current-user*
+ ;; creating cards from a transaction. wait until tx complete to signal event
+ true
+ ;; do not autoplace these cards. we will create the dashboard cards ourselves.
+ false))]))
:discarded discard
:referenced reference}))
diff --git a/src/metabase/dashboards_rest/api.clj b/src/metabase/dashboards_rest/api.clj
index 753e7ea6af2..efba04b1f74 100644
--- a/src/metabase/dashboards_rest/api.clj
+++ b/src/metabase/dashboards_rest/api.clj
@@ -478,18 +478,19 @@
{:keys [copy discard reference]} (cond-> (cards-to-copy deep-copy? (:dashcards old-dashboard))
dashboards-only? reference-metrics)]
{:copied (into {} (for [[id to-copy] copy]
- [id (queries/create-card!
- (cond-> to-copy
- true (assoc :collection_id dest-coll-id)
- same-collection? (update :name #(str % " - " (tru "Duplicate")))
- (or (:dashboard_id to-copy)
- dashboards-only?) (-> (assoc :dashboard_id (u/the-id new-dashboard))
- (dissoc :collection_position)))
- @api/*current-user*
- ;; creating cards from a transaction. wait until tx complete to signal event
- true
- ;; do not autoplace these cards. we will create the dashboard cards ourselves.
- false)]))
+ [id (queries/with-copy-source-card to-copy
+ (queries/create-card!
+ (cond-> to-copy
+ true (assoc :collection_id dest-coll-id)
+ same-collection? (update :name #(str % " - " (tru "Duplicate")))
+ (or (:dashboard_id to-copy)
+ dashboards-only?) (-> (assoc :dashboard_id (u/the-id new-dashboard))
+ (dissoc :collection_position)))
+ @api/*current-user*
+ ;; creating cards from a transaction. wait until tx complete to signal event
+ true
+ ;; do not autoplace these cards. we will create the dashboard cards ourselves.
+ false))]))
:discarded discard
:referenced reference}))
@@ -860,6 +861,8 @@
(defn- do-update-dashcards!
[dashboard current-cards new-cards]
(let [{:keys [to-create to-update to-delete]} (u/row-diff current-cards new-cards)]
+ (queries/check-newly-exposed-dashcards-timeline-permissions!
+ dashboard (:dashcards dashboard) (concat to-create to-update))
(dashboard/archive-or-unarchive-internal-dashboard-questions! (:id dashboard) new-cards)
;; Check both created and updated dashcards: a "Replace" keeps the dashcard id and only swaps
;; card_id, so it lands in `to-update`, not `to-create` (UXW-4731). Card ids the dashboard already
diff --git a/src/metabase/documents/models/document.clj b/src/metabase/documents/models/document.clj
index e0267f9a9d5..201eaace134 100644
--- a/src/metabase/documents/models/document.clj
+++ b/src/metabase/documents/models/document.clj
@@ -162,7 +162,8 @@
(def CardCreateSchema
"Schema for a card created inline with a document (the `cards` map on create/update). The
- card fields are declared locally: the model layer doesn't depend on the REST card schema."
+ card fields are declared locally: the model layer doesn't depend on the REST card schema. `source_card_id`, if
+ given, must be a Card the user can read; the new card inherits its timeline selection for permission purposes."
[:map {:closed true}
[:name ms/NonBlankString]
[:dataset_query ::lib-be.schema/maybe-legacy-query]
@@ -173,7 +174,8 @@
[:display ms/NonBlankString]
[:visualization_settings ms/VisualizationSettings]
[:result_metadata {:optional true} [:maybe ::queries.schema/card.result-metadata]]
- [:cache_ttl {:optional true} [:maybe ms/PositiveInt]]])
+ [:cache_ttl {:optional true} [:maybe ms/PositiveInt]]
+ [:source_card_id {:optional true} [:maybe ms/PositiveInt]]])
(defn- create-card!
"The single choke point every document card-creation path (create, update, copy) funnels through. Runs the same
@@ -199,9 +201,10 @@
user is not authoring anything -- they may be able to view (and run) the source card without having permission to
write such a query themselves, e.g. a native card when they lack native query editing perms (UXW-5037). Running the
clone is still gated by the usual runtime permission checks, the same ones that gate running the source card."
- [card creator]
- (api/create-check :model/Card {:collection_id (:collection_id card)})
- (card/create-card! (assoc card :type :question :dashboard_id nil) creator))
+ [source-card creator]
+ (api/create-check :model/Card {:collection_id (:collection_id source-card)})
+ (card/with-copy-source-card source-card
+ (card/create-card! (assoc source-card :type :question :dashboard_id nil) creator)))
(mu/defn update-cards-in-ast :- [:map [:document :any]
[:content_type :string]]
@@ -238,14 +241,16 @@
(when (seq cards-to-create)
(reduce-kv
(fn [result-map original-key card-data]
- (let [;; Merge document info into card data
+ (let [source-card-id (:source_card_id card-data)
+ ;; Merge document info into card data
;; Cards inherit document's collection_id if not explicitly specified
merged-card-data (-> card-data
+ (dissoc :source_card_id)
(assoc :document_id document-id)
(cond-> (nil? (:collection_id card-data))
(assoc :collection_id document-collection-id)))
- ;; Create the card using the queries core function
- new-card (create-card! merged-card-data creator)]
+ new-card (card/with-copy-source-card (some->> source-card-id (api/read-check :model/Card))
+ (create-card! merged-card-data creator))]
(assoc result-map original-key (:id new-card))))
{}
cards-to-create)))
diff --git a/src/metabase/mcp/v2/tools/duplicate.clj b/src/metabase/mcp/v2/tools/duplicate.clj
index fd34db477bb..86fe7eadbb7 100644
--- a/src/metabase/mcp/v2/tools/duplicate.clj
+++ b/src/metabase/mcp/v2/tools/duplicate.clj
@@ -75,7 +75,10 @@
(assoc :name new-name :collection_id collection-id)
(dissoc :dashboard_id :collection_position))]
(api/create-check :model/Card {:collection_id collection-id})
- (queries/create-card! new-card @api/*current-user*)))
+ ;; Copy semantics for timelines too: an inherited selection the caller cannot read is preserved, as in
+ ;; `POST /api/card/:id/copy`, while any change to it is still checked.
+ (queries/with-copy-source-card card
+ (queries/create-card! new-card @api/*current-user*))))
(defn- fetch-dashboard
[id-or-eid]
diff --git a/src/metabase/models/db.clj b/src/metabase/models/db.clj
index 2dcabe0781c..b88e61278c4 100644
--- a/src/metabase/models/db.clj
+++ b/src/metabase/models/db.clj
@@ -358,6 +358,11 @@
[segment-id :- ::lib.schema.id/segment]
(t2/select-one [:model/Segment :id :entity_id :table_id] :id segment-id))
+(mu/defn timeline-ids-of-events
+ "The distinct Timeline ids of the TimelineEvents with `event-ids`."
+ [event-ids :- [:sequential ms/PositiveInt]]
+ (t2/select-fn-set :timeline_id [:model/TimelineEvent :timeline_id] :id [:in event-ids]))
+
(mu/defn entity-by-own-pk
"The `model` row identified by `id`, using whatever column is that model's own primary key."
[model :- [:or :keyword symbol?]
diff --git a/src/metabase/models/serialization.clj b/src/metabase/models/serialization.clj
index c429f124d0d..8d656102bdd 100644
--- a/src/metabase/models/serialization.clj
+++ b/src/metabase/models/serialization.clj
@@ -865,7 +865,7 @@
(resolve/export-fk (export-resolver) id model))
(defmacro ^:private fk-elide
- "If a call to `*export-fk*` inside of this fails, do not export the whole data structure"
+ "Returns nil when an FK target no longer exists; rethrows other failures."
[& body]
`(try
~@body
@@ -1704,6 +1704,20 @@
:else cols)]
[k updated-cols]))))))
+(defn- timeline-setting-ids
+ "The ids stored under a `:timeline.*` visualization setting. Settings saved before these keys were validated can
+ hold anything, so a non-sequential value counts as no ids rather than throwing mid-export."
+ [ids]
+ (when (sequential? ids) ids))
+
+(defn- export-fks [ids model]
+ (u/keepv #(when (pos-int? %) (fk-elide (*export-fk* % model))) (timeline-setting-ids ids)))
+
+(defn- export-timeline-events [settings]
+ (-> settings
+ (m/update-existing :timeline.selected_timeline_ids export-fks :model/Timeline)
+ (m/update-existing :timeline.excluded_timeline_event_ids export-fks :model/TimelineEvent)))
+
(defn export-visualization-settings
"Given the `:visualization_settings` map, convert all its field-ids to portable `[db schema table field]` form."
[settings]
@@ -1714,6 +1728,7 @@
export-viz-click-behavior
export-visualizer-settings
export-pivot-table
+ export-timeline-events
(update :column_settings export-column-settings))))
(defn- import-viz-link-card
@@ -1794,6 +1809,18 @@
(binding [resolve/*import-resolver* resolve.default/lenient-import-resolver]
(import-visualizer-settings settings)))
+(defn- timeline-event-ref? [event-ref]
+ (and (vector? event-ref) (= 2 (count event-ref)) (every? entity-id? event-ref)))
+
+(defn- import-fks [refs ref? model]
+ (u/keepv #(when (ref? %) (fk-elide (*import-fk* % model))) (timeline-setting-ids refs)))
+
+(defn- import-timeline-events [settings]
+ (-> settings
+ ;; Keep explicit empty selections: removing the key would restore collection defaults.
+ (m/update-existing :timeline.selected_timeline_ids import-fks entity-id? :model/Timeline)
+ (m/update-existing :timeline.excluded_timeline_event_ids import-fks timeline-event-ref? :model/TimelineEvent)))
+
(defn import-visualization-settings
"Given an EDN value as exported by [[export-visualization-settings]], convert its portable `[db schema table field]`
references into Field IDs."
@@ -1805,6 +1832,7 @@
import-viz-click-behavior
import-visualizer-settings
import-pivot-table
+ import-timeline-events
(update :column_settings import-column-settings))))
(defn- viz-link-card-deps
@@ -1830,6 +1858,18 @@
;; that to actually attach to a filter to check what it looks like.
nil)))
+(defn- timeline-events-deps
+ [allow-int-ids? settings]
+ (let [selected-ids (timeline-setting-ids (:timeline.selected_timeline_ids settings))
+ excluded-ids (timeline-setting-ids (:timeline.excluded_timeline_event_ids settings))
+ timeline-ids (concat
+ (filter #(or (raw-ref-id? allow-int-ids? %) (entity-id? %)) selected-ids)
+ (if allow-int-ids?
+ (mapcat models.db/timeline-ids-of-events
+ (partition-all query-batch-size (filter pos-int? excluded-ids)))
+ (map first (filter timeline-event-ref? excluded-ids))))]
+ (into #{} (map (fn [id] [{:model "Timeline" :id id}])) timeline-ids)))
+
(defn visualization-settings-deps
"Given the :visualization_settings (possibly nil) for an entity, return any embedded serdes-deps as a set.
Always returns an empty set even if the input is nil. For `allow-int-ids?` see [[mbql-deps]]."
@@ -1846,7 +1886,8 @@
click-behavior-deps (viz-click-behavior-deps viz)]
(->> (concat column-settings-keys-deps
column-settings-vals-deps
- [(mbql-deps allow-int-ids? viz) link-card-deps click-behavior-deps])
+ [(mbql-deps allow-int-ids? viz) link-card-deps click-behavior-deps
+ (timeline-events-deps allow-int-ids? viz)])
(filter some?)
(reduce set/union #{}))))
diff --git a/src/metabase/models/serialization/resolve/default.clj b/src/metabase/models/serialization/resolve/default.clj
index 8fe50636c1c..5738ac4ba75 100644
--- a/src/metabase/models/serialization/resolve/default.clj
+++ b/src/metabase/models/serialization/resolve/default.clj
@@ -72,7 +72,8 @@
(if entity
(get entity (first (t2/primary-keys model)))
(throw (ex-info "Could not find foreign key target - bad serdes dependencies or other serialization error"
- {:entity_id eid :model (name model)}))))))
+ {:entity_id eid :model (name model)
+ :metabase.models.serialization/type :target-not-found}))))))
(defn import-fk-keyed
"Given a portable identifying field value, return the numeric :id."
diff --git a/src/metabase/public_sharing_rest/api.clj b/src/metabase/public_sharing_rest/api.clj
index f2938a868b9..0edefe023ce 100644
--- a/src/metabase/public_sharing_rest/api.clj
+++ b/src/metabase/public_sharing_rest/api.clj
@@ -303,6 +303,42 @@
(m/remove-keys hidden-parameter-ids fields)))
(select-keys action-public-keys))))
+(defn- public-dashcard-timeline-ids
+ [{:keys [card] :as dashcard}]
+ (when (and (pos-int? (:id card))
+ (false? (:archived card))
+ (not (queries/dashcard-hides-card-events? dashcard)))
+ (not-empty (queries/card-exposed-timeline-ids card))))
+
+(defn- public-timeline-events
+ [timeline-ids]
+ ;; A public dashboard authorizes its saved event selection without granting collection access.
+ (when (seq timeline-ids)
+ (when-let [active-ids (not-empty (public-sharing-rest.db/active-timeline-ids timeline-ids))]
+ (public-sharing-rest.db/active-timeline-events active-ids))))
+
+(defn- public-dashcard-timeline-events
+ [{{settings :visualization_settings} :card, :as dashcard} events]
+ (let [timeline-ids (public-dashcard-timeline-ids dashcard)
+ excluded-ids (:timeline.excluded_timeline_event_ids settings)
+ excluded-ids (if (sequential? excluded-ids) (set excluded-ids) #{})]
+ (filterv #(and (contains? timeline-ids (:timeline_id %))
+ (not (contains? excluded-ids (:id %))))
+ events)))
+
+(defn- public-dashcards
+ [dashcards]
+ (let [events (public-timeline-events (into #{} (mapcat public-dashcard-timeline-ids) dashcards))]
+ (for [dashcard dashcards]
+ (-> (select-keys dashcard [:id :card :card_id :dashboard_id :series :col :row :size_x :dashboard_tab_id
+ :size_y :parameter_mappings :visualization_settings :action :inline_parameters])
+ (assoc :timeline_events (public-dashcard-timeline-events dashcard events))
+ (update :card remove-card-non-public-columns)
+ (update :series (fn [series]
+ (for [series series]
+ (remove-card-non-public-columns series))))
+ (m/update-existing :action public-action)))))
+
(mu/defn public-dashboard :- ::dashboards.schema/dashboard
"Return the public Dashboard with the given `dashboard-id`, removing all columns that should not be visible to
the general public. Throws a 404 if the Dashboard doesn't exist. With `:enable-embedding? true`, additionally
@@ -316,15 +352,7 @@
keep-param-fields-for-parameters
params/remove-param-fields-non-public-columns
api.dashboard/add-query-average-durations
- (update :dashcards (fn [dashcards]
- (for [dashcard dashcards]
- (-> (select-keys dashcard [:id :card :card_id :dashboard_id :series :col :row :size_x :dashboard_tab_id
- :size_y :parameter_mappings :visualization_settings :action :inline_parameters])
- (update :card remove-card-non-public-columns)
- (update :series (fn [series]
- (for [series series]
- (remove-card-non-public-columns series))))
- (m/update-existing :action public-action))))))))
+ (update :dashcards public-dashcards))))
(defn- dashboard-with-uuid [uuid] (public-dashboard (public-sharing/public-uuid->id :model/Dashboard uuid)))
diff --git a/src/metabase/public_sharing_rest/db.clj b/src/metabase/public_sharing_rest/db.clj
index 72266d04869..b9afa1a15d0 100644
--- a/src/metabase/public_sharing_rest/db.clj
+++ b/src/metabase/public_sharing_rest/db.clj
@@ -68,3 +68,20 @@
"The id, content, and content type of the Document with `document-id`, or nil."
[document-id :- [:maybe ms/PositiveInt]]
(t2/select-one [:model/Document :id :document :content_type] :id document-id))
+
+;;; ----------------------------------------------------- Timelines ----------------------------------------------------
+
+(mu/defn active-timeline-ids
+ "The ids of the non-archived Timelines among `timeline-ids`."
+ [timeline-ids :- [:set ms/PositiveInt]]
+ (t2/select-pks-set :model/Timeline :id [:in timeline-ids] :archived false))
+
+(mu/defn active-timeline-events
+ "The non-archived TimelineEvents of the Timelines with `timeline-ids`, restricted to the columns safe to expose
+ publicly, in timestamp order."
+ [timeline-ids :- [:set ms/PositiveInt]]
+ (t2/select [:model/TimelineEvent :id :timeline_id :name :description :icon :timestamp :timezone :time_matters
+ :archived :created_at]
+ :timeline_id [:in timeline-ids]
+ :archived false
+ {:order-by [[:timestamp :asc] [:id :asc]]}))
diff --git a/src/metabase/queries/card_write_checks.clj b/src/metabase/queries/card_write_checks.clj
index f04f249886b..980f264e63c 100644
--- a/src/metabase/queries/card_write_checks.clj
+++ b/src/metabase/queries/card_write_checks.clj
@@ -9,6 +9,7 @@
[metabase.lib-be.schema :as lib-be.schema]
[metabase.lib.core :as lib]
[metabase.queries.db :as queries.db]
+ [metabase.queries.models.card :as card]
[metabase.queries.schema :as queries.schema]
[metabase.query-permissions.core :as query-perms]
[metabase.util.i18n :refer [tru]]
@@ -85,7 +86,10 @@
[card-before-update :- ::queries.schema/card
card-updates :- ::queries.schema/card]
(when (api/column-will-change? (:dashboard_id card-before-update) (get card-updates :dashboard_id ::api/not-provided))
- (check-allowed-to-remove-from-existing-dashboards card-before-update))
+ (check-allowed-to-remove-from-existing-dashboards card-before-update)
+ (when-let [dashboard-id (:dashboard_id card-updates)]
+ (card/check-shared-dashboard-timeline-permissions! (queries.db/dashboard dashboard-id)
+ [(merge card-before-update card-updates)])))
(collection/check-allowed-to-change-collection card-before-update card-updates))
(mu/defn- check-update-result-metadata-data-perms
diff --git a/src/metabase/queries/core.clj b/src/metabase/queries/core.clj
index a8197ed3221..3b07446c5bc 100644
--- a/src/metabase/queries/core.clj
+++ b/src/metabase/queries/core.clj
@@ -36,7 +36,13 @@
cards-queries-info
move-actions-of-models!]
[metabase.queries.models.card
- create-card!]
+ check-shared-dashboard-timeline-permissions!
+ check-newly-exposed-dashcards-timeline-permissions!
+ check-shared-dashboard-timeline-permissions-for-card-ids!
+ create-card!
+ card-exposed-timeline-ids
+ dashcard-hides-card-events?
+ with-copy-source-card]
[metabase.queries.card-write-checks
actual-collection-id
check-allowed-to-create-card!
@@ -55,6 +61,7 @@
model?
sole-dashboard-id
starting-card-schema-version
+ timeline-events-supported-display?
update-card!
visible-metric-cards-where-clause]
[metabase.queries.models.card.metadata
diff --git a/src/metabase/queries/db.clj b/src/metabase/queries/db.clj
index 53bf1d36909..0e9acc5eeef 100644
--- a/src/metabase/queries/db.clj
+++ b/src/metabase/queries/db.clj
@@ -63,6 +63,11 @@
[card-ids :- [:maybe [:or [:set [:maybe ::lib.schema.id/card]] [:sequential [:maybe ::lib.schema.id/card]]]]]
(t2/select :model/Card :id [:in card-ids]))
+(mu/defn timelines
+ "The Timelines with `timeline-ids`; ids of deleted Timelines are skipped."
+ [timeline-ids :- [:set ms/PositiveInt]]
+ (t2/select :model/Timeline :id [:in timeline-ids]))
+
(mu/defn card-query-info
"The query-related fields of the Card with `card-id`.
diff --git a/src/metabase/queries/models/card.clj b/src/metabase/queries/models/card.clj
index 8cdb2f357b1..42686acba1c 100644
--- a/src/metabase/queries/models/card.clj
+++ b/src/metabase/queries/models/card.clj
@@ -25,6 +25,7 @@
[metabase.lib.schema.id :as lib.schema.id]
[metabase.lib.schema.metadata :as lib.schema.metadata]
[metabase.metrics.core :as metrics]
+ [metabase.models.db :as models.db]
[metabase.models.interface :as mi]
[metabase.models.serialization :as serdes]
[metabase.parameters.core :as parameters]
@@ -861,6 +862,125 @@
(cond->> (lib/normalize ::queries.schema/card card)
(mu.fn/instrument-ns? *ns*) (mu.fn/validate-output {:fn-name `normalize-card} [:maybe ::queries.schema/card])))
+(defn timeline-events-supported-display?
+ "Whether `display`, a keyword or string, supports timeline events."
+ [display]
+ ;; Keep this aligned with the frontend's canDisplayTimelineEvents registry check.
+ (contains? #{:line :bar :area :combo :scatter :waterfall} (keyword display)))
+
+(defn- events-enabled? [visibility]
+ (not (false? (:timeline_events.enabled visibility))))
+
+(defn- setting-ids
+ "The ids stored under `k` in `visibility`. Settings saved before these keys were validated can hold anything, so a
+ malformed value counts as no ids rather than throwing — otherwise the card could never be repaired."
+ [visibility k]
+ (let [ids (get visibility k)]
+ (if (sequential? ids) (into #{} (filter pos-int?) ids) #{})))
+
+(defn- selected-timeline-ids [visibility]
+ (setting-ids visibility :timeline.selected_timeline_ids))
+
+(defn- excluded-event-ids [visibility]
+ (setting-ids visibility :timeline.excluded_timeline_event_ids))
+
+(defn- newly-revealed-timeline-ids
+ [visibility previous-visibility reveals-all?]
+ (let [selected-ids (selected-timeline-ids visibility)]
+ (if reveals-all?
+ selected-ids
+ (let [added-ids (set/difference selected-ids (selected-timeline-ids previous-visibility))
+ hidden-ids (excluded-event-ids visibility)
+ unhidden-ids (into [] (remove hidden-ids) (excluded-event-ids previous-visibility))]
+ (into added-ids
+ (filter selected-ids)
+ (models.db/timeline-ids-of-events unhidden-ids))))))
+
+(defn- check-id-setting!
+ [visibility k message]
+ (when-some [ids (get visibility k)]
+ (api/check-400 (and (sequential? ids) (every? pos-int? ids)) message)))
+
+(defn- check-timeline-visibility-permissions!
+ [card previous-card]
+ ;; No bound user means an internal write (serdes import, migrations, tasks) rather than a request.
+ (when api/*current-user-id*
+ (let [visibility-keys [:timeline.selected_timeline_ids :timeline.excluded_timeline_event_ids
+ :timeline_events.enabled]
+ visibility (select-keys (:visualization_settings card) visibility-keys)
+ previous-visibility (select-keys (:visualization_settings previous-card) visibility-keys)
+ draws-events? (fn [visibility display]
+ (and (events-enabled? visibility) (timeline-events-supported-display? display)))
+ reveals-all? (and (draws-events? visibility (:display card))
+ (not (draws-events? previous-visibility (:display previous-card))))]
+ (when (or reveals-all? (not= visibility previous-visibility))
+ (check-id-setting! visibility :timeline.excluded_timeline_event_ids
+ (tru "Excluded timeline event IDs must be a sequence of positive integers."))
+ (when (check-id-setting! visibility :timeline.selected_timeline_ids
+ (tru "Selected timeline IDs must be a sequence of positive integers."))
+ ;; Timelines the card already showed stay visible whatever the user saves, so only the difference is
+ ;; checked. Deleted timelines are skipped when rendering, so a stale id must not block saving the card.
+ (doseq [timeline (queries.db/timelines
+ (newly-revealed-timeline-ids visibility previous-visibility reveals-all?))]
+ (api/read-check timeline)))))))
+
+(defn card-exposed-timeline-ids
+ "The ids of the timelines whose events `card` shows on a dashboard."
+ [{:keys [display] settings :visualization_settings}]
+ ;; Archived cards count too: archiving is undone by a plain `archived: false`, which runs no timeline check.
+ (when (and (timeline-events-supported-display? display)
+ (events-enabled? settings))
+ (selected-timeline-ids settings)))
+
+(defn dashcard-hides-card-events?
+ "Whether `dashcard` never shows its card's timeline events, whatever the card selects: a visualizer dashcard renders
+ its own visualization, an action dashcard renders a button, and a virtual dashcard has no card of its own."
+ [dashcard]
+ (let [settings (:visualization_settings dashcard)]
+ (or (contains? settings :visualization)
+ (some? (:action_id dashcard))
+ (some? (:virtual_card settings)))))
+
+(defn check-shared-dashboard-timeline-permissions!
+ "Placing `cards` on `dashboard` shows their selected timeline events to anyone who opens it when the dashboard is
+ publicly shared or embedded, so the current user needs read access to those timelines."
+ [dashboard cards]
+ (when (and api/*current-user-id*
+ (or (:public_uuid dashboard) (:enable_embedding dashboard)))
+ (let [timeline-ids (into #{} (mapcat card-exposed-timeline-ids) cards)]
+ (doseq [timeline (queries.db/timelines timeline-ids)]
+ (api/read-check timeline)))))
+
+(defn check-shared-dashboard-timeline-permissions-for-card-ids!
+ "[[check-shared-dashboard-timeline-permissions!]] for the saved Cards with `card-ids`."
+ [dashboard card-ids]
+ (when (seq card-ids)
+ (check-shared-dashboard-timeline-permissions! dashboard (queries.db/cards (set card-ids)))))
+
+(defn check-newly-exposed-dashcards-timeline-permissions!
+ "[[check-shared-dashboard-timeline-permissions!]] for the cards `new-dashcards` newly expose on `dashboard`. A card
+ is grandfathered only when `existing-dashcards` already shows its events, so turning a dashcard that hides them
+ into one that shows them is checked like any other placement."
+ [dashboard existing-dashcards new-dashcards]
+ (let [exposed-card-ids (comp (remove dashcard-hides-card-events?) (keep :card_id))
+ existing-card-ids (into #{} exposed-card-ids existing-dashcards)
+ new-card-ids (into #{} (comp exposed-card-ids (remove existing-card-ids)) new-dashcards)]
+ (check-shared-dashboard-timeline-permissions-for-card-ids! dashboard new-card-ids)))
+
+;; before-insert can't take arguments, so the copy source is passed through a binding
+#_{:clj-kondo/ignore [:metabase/discourage-dynamic-vars]}
+(def ^:dynamic *copy-source-card*
+ "The Card a new Card is being copied from, if any. Its timeline visibility settings count as the previous state, so
+ copying a Card does not require read access to the timelines it already selects."
+ nil)
+
+(defmacro with-copy-source-card
+ "Runs `body`, treating a Card inserted within it as a copy of `source-card`: an inherited timeline selection does
+ not require read access to those timelines. `source-card` must be a Card the current user has already passed a
+ read check on, and `body` should perform only the single copy insert."
+ [source-card & body]
+ `(binding [*copy-source-card* ~source-card] ~@body))
+
(defn- library-content-type
"The content type a Library collection checks `card` against, counting a question as a dashboard question when `dashboard-pending?`."
[card dashboard-pending?]
@@ -871,6 +991,7 @@
(t2/define-before-insert :model/Card
[card]
+ (check-timeline-visibility-permissions! card *copy-source-card*)
(u/prog1
(-> card
(assoc :metabase_version config/mb-version-string
@@ -949,6 +1070,8 @@
;; normalization preserving the instance's original.
original (t2/original card)
card (normalize-card card)]
+ (when (or (contains? changes :visualization_settings) (contains? changes :display))
+ (check-timeline-visibility-permissions! card original))
(check-allowed-content card changes)
(-> card
(dissoc :verified-result-metadata?)
@@ -1089,6 +1212,9 @@
;; you can't specify the dashboard_tab_id and not a dashboard_id
(api/check-400 (not (and (:dashboard_tab_id input-card-data)
(not (:dashboard_id input-card-data)))))
+ ;; Gated here, not in `check-allowed-to-create-card!`: the copy endpoints skip that stack but still autoplace.
+ (when-let [dashboard-id (and autoplace-dashboard-questions? (:dashboard_id input-card-data))]
+ (check-shared-dashboard-timeline-permissions! (queries.db/dashboard dashboard-id) [input-card-data]))
(let [data-keys [:dataset_query :description :display :name :visualization_settings
:parameters :parameter_mappings :collection_id :collection_position
:cache_ttl :type :dashboard_id :document_id]
diff --git a/src/metabase/queries_rest/api/card.clj b/src/metabase/queries_rest/api/card.clj
index 23722eba4c9..5cd342756ee 100644
--- a/src/metabase/queries_rest/api/card.clj
+++ b/src/metabase/queries_rest/api/card.clj
@@ -460,7 +460,8 @@
[:dashboard_tab_id {:optional true} [:maybe ms/PositiveInt]]
[:size {:optional true} [:maybe [:map {:closed true}
[:size_x ms/PositiveInt]
- [:size_y ms/PositiveInt]]]]])
+ [:size_y ms/PositiveInt]]]]
+ [:source_card_id {:optional true} [:maybe ms/PositiveInt]]])
(defn- check-parameter-permissions
[parameters query]
@@ -477,14 +478,16 @@
;;
#_{:clj-kondo/ignore [:metabase/validate-defendpoint-has-response-schema]}
(api.macros/defendpoint :post "/"
- "Create a new `Card`. Card `type` can be `question`, `metric`, or `model`."
+ "Create a new `Card`. Card `type` can be `question`, `metric`, or `model`. `source_card_id`, if given, must be a
+ Card the current user can read; the new Card is then treated as a copy of it for timeline-permission purposes."
[_route-params
_query-params
- {card-type :type, collection-id :collection_id, :as card} :- CardCreateSchema]
- (let [card (cond-> card
- (some? collection-id)
- (update :collection_id #(eid-translation/->id-or-404 :collection %)))
- query (:dataset_query card)]
+ {card-type :type, collection-id :collection_id, source-card-id :source_card_id, :as card} :- CardCreateSchema]
+ (let [source-card (some->> source-card-id (api/read-check :model/Card))
+ card (cond-> (dissoc card :source_card_id)
+ (some? collection-id)
+ (update :collection_id #(eid-translation/->id-or-404 :collection %)))
+ query (:dataset_query card)]
;; Parameter permissions run BEFORE the create stack: the parameter-specific 403 names neither
;; the table nor its ids, while the generic run-permissions error carries the query (and its
;; :source-table) in ex-data. Reversing these leaks that through the parameter path.
@@ -492,7 +495,8 @@
;; The full create stack (can-be-saved, run-permissions, collection create-check, cycle
;; detection) lives in `queries` so MCP's question_write runs the identical checks.
(queries/check-allowed-to-create-card! card card-type)
- (let [created-card (queries/create-card! card @api/*current-user*)]
+ (let [created-card (queries/with-copy-source-card source-card
+ (queries/create-card! card @api/*current-user*))]
(when (and (some? (:result_metadata card))
(= (name (:type created-card)) "question"))
(events/publish-event! :event/card-create-with-result-metadata
@@ -514,7 +518,8 @@
new-name (trs "Copy of {0}" (:name orig-card))
new-card (assoc orig-card :name new-name)]
(api/create-check :model/Card new-card)
- (-> (queries/create-card! new-card @api/*current-user*)
+ (-> (queries/with-copy-source-card orig-card
+ (queries/create-card! new-card @api/*current-user*))
hydrate-card-details
(assoc :last-edit-info (revisions/edit-information-for-user @api/*current-user*)))))
diff --git a/src/metabase/revisions/impl/dashboard.clj b/src/metabase/revisions/impl/dashboard.clj
index 71f6615be0e..d12750c4e8f 100644
--- a/src/metabase/revisions/impl/dashboard.clj
+++ b/src/metabase/revisions/impl/dashboard.clj
@@ -46,6 +46,13 @@
(assoc :series (mapv :id (:series dashboard-card)))))))
(assoc :tabs (map #(apply dissoc % excluded-columns-for-dashboard-tab-revision) tabs)))))
+(defn- check-reverted-dashcards-timeline-permissions!
+ "Reverting can put a card back on a publicly shared or embedded dashboard, exposing its selected timeline events, so
+ the current user needs read access to those timelines."
+ [dashboard-id current-cards reverted-cards]
+ (queries/check-newly-exposed-dashcards-timeline-permissions!
+ (revisions.db/entity :model/Dashboard dashboard-id) current-cards reverted-cards))
+
(defn- revert-dashcards
[dashboard-id serialized-cards]
(let [current-cards (->> (t2/hydrate (revisions.db/dashcards dashboard-id) :series)
@@ -55,6 +62,7 @@
(assoc :series (mapv :id (:series dashcard)))))))
id->current-card (zipmap (map :id current-cards) current-cards)
{:keys [to-create to-update to-delete]} (u/row-diff current-cards serialized-cards)]
+ (check-reverted-dashcards-timeline-permissions! dashboard-id current-cards (concat to-create to-update))
(when (seq to-delete)
(dashboard-card/delete-dashboard-cards! (map :id to-delete)))
(when (seq to-create)
diff --git a/src/metabase/timeline/models/timeline.clj b/src/metabase/timeline/models/timeline.clj
index e97ccf8471c..d8622db80d2 100644
--- a/src/metabase/timeline/models/timeline.clj
+++ b/src/metabase/timeline/models/timeline.clj
@@ -47,7 +47,8 @@
;;;; serialization
(defmethod serdes/deserialization-dependencies "Timeline" [{:keys [collection_id]}]
- [[{:model "Collection" :id collection_id}]])
+ (when collection_id
+ [[{:model "Collection" :id collection_id}]]))
(defmethod serdes/serialization-dependencies "Timeline" [_model-name {:keys [collection_id]}]
;; A Timeline only references its containing Collection, which a selective export may legitimately omit.
diff --git a/src/metabase/timeline/models/timeline_event.clj b/src/metabase/timeline/models/timeline_event.clj
index 01e70c45390..03a52c95127 100644
--- a/src/metabase/timeline/models/timeline_event.clj
+++ b/src/metabase/timeline/models/timeline_event.clj
@@ -12,6 +12,7 @@
(doto :model/TimelineEvent
(derive :metabase/model)
(derive :hook/timestamped?)
+ (derive :hook/entity-id)
(derive ::mi/read-policy.full-perms-for-perms-set)
(derive ::mi/write-policy.full-perms-for-perms-set))
@@ -29,8 +30,9 @@
(def Source
"Timeline Event Source Schema. For Snowplow Events, where the Event is created from is important.
- Events are added from one of three sources: `collections`, `questions` (cards in backend code), or directly with an API call. An API call is indicated by having no source key in the `timeline-event` request."
- [:enum "collections" "question"])
+ Events are added from one of four sources: `collections`, `question` (cards in backend code), `dashboard`, or directly
+ with an API call. An API call is indicated by having no source key in the `timeline-event` request."
+ [:enum "collections" "question" "dashboard"])
;;;; transforms
@@ -99,9 +101,12 @@
;;;; serialization
-;; nested in Timeline
+(defmethod serdes/generate-path "TimelineEvent" [_ event]
+ [(serdes/infer-self-path "Timeline" (timeline.db/timeline (:timeline_id event)))
+ (serdes/infer-self-path "TimelineEvent" event)])
+
(defmethod serdes/make-spec "TimelineEvent" [_model-name _opts]
- {:copy [:archived :description :icon :name :time_matters :timezone]
+ {:copy [:archived :description :entity_id :icon :name :time_matters :timezone]
:skip []
:transform {:created_at (serdes/date)
:creator_id (serdes/fk :model/User)
diff --git a/src/metabase/timeline/schema.clj b/src/metabase/timeline/schema.clj
index cbfa1881e97..1417317c5c3 100644
--- a/src/metabase/timeline/schema.clj
+++ b/src/metabase/timeline/schema.clj
@@ -46,4 +46,5 @@
[:archived {:optional true} [:maybe :boolean]]
[:creator_id {:optional true} [:maybe ::lib.schema.id/user]]
[:created_at {:optional true} [:maybe ms/TemporalInstant]]
- [:updated_at {:optional true} [:maybe ms/TemporalInstant]]])
+ [:updated_at {:optional true} [:maybe ms/TemporalInstant]]
+ [:entity_id {:optional true} [:maybe :string]]])
diff --git a/test/metabase/agent_api/api_test.clj b/test/metabase/agent_api/api_test.clj
index 99c5d59f4a9..7f4f68f1fa4 100644
--- a/test/metabase/agent_api/api_test.clj
+++ b/test/metabase/agent_api/api_test.clj
@@ -1454,6 +1454,27 @@
(is (nat-int? (:row (first dashcards))))
(is (nat-int? (:col (first dashcards)))))))))
+(deftest update-dashboard-dashcards-add-restricted-timeline-card-test
+ (testing "Adding a card to a shared dashboard needs read access to the timelines it shows"
+ (mt/with-temporary-setting-values [enable-public-sharing true]
+ (mt/with-temp [:model/Collection restricted {}
+ :model/Timeline timeline {:collection_id (:id restricted)}
+ :model/Dashboard {dash-id :id} {:public_uuid (str (random-uuid))}
+ :model/Card {card-id :id} {:name "Orders over time"
+ :dataset_query (orders-count-query)
+ :display :line
+ :visualization_settings
+ {:timeline.selected_timeline_ids [(:id timeline)]}}]
+ (perms/revoke-collection-permissions! (perms-group/all-users) restricted)
+ (is (= "You don't have permissions to do that."
+ (:cause (mt/user-http-request :rasta :put 403 (str "agent/v1/dashboard/" dash-id)
+ {:dashcards [{:action "add" :card_id card-id}]}))))
+ (is (empty? (t2/select :model/DashboardCard :dashboard_id dash-id)))
+ (testing "a user who can read the timeline can add it"
+ (mt/user-http-request :crowberto :put 200 (str "agent/v1/dashboard/" dash-id)
+ {:dashcards [{:action "add" :card_id card-id}]})
+ (is (= [card-id] (map :card_id (t2/select :model/DashboardCard :dashboard_id dash-id)))))))))
+
(deftest update-dashboard-dashcards-multi-add-test
(testing "Add multiple cards in one call - each one autoplaced w/o overlap"
(mt/with-temp [:model/Dashboard {dash-id :id} {:name "Phase B Multi-add"}
diff --git a/test/metabase/api/timeline_event_test.clj b/test/metabase/api/timeline_event_test.clj
index fc4afa3940b..e2f2b89725f 100644
--- a/test/metabase/api/timeline_event_test.clj
+++ b/test/metabase/api/timeline_event_test.clj
@@ -31,9 +31,9 @@
:time_matters false
:timeline_id (u/the-id timeline)}]
(testing "check that we get the timeline-event with `id`"
- (is (= "Very Important Event"
- (->> (mt/user-http-request :rasta :get 200 (str "timeline-event/" (u/the-id event)))
- :name)))))))
+ (is (= {:name "Very Important Event" :entity_id (:entity_id event)}
+ (select-keys (mt/user-http-request :rasta :get 200 (str "timeline-event/" (u/the-id event)))
+ [:name :entity_id])))))))
(deftest create-timeline-event-test
(testing "POST /api/timeline-event"
@@ -41,12 +41,15 @@
:model/Timeline timeline {:name "Important Events"
:collection_id (u/the-id collection)}]
(testing "create a timeline event"
- ;; make an API call to create a timeline
- (mt/user-http-request :rasta :post 200 "timeline-event" {:name "Rasta Migrates to Florida for the Winter"
- :timestamp (java.time.OffsetDateTime/now)
- :timezone "US/Pacific"
- :time_matters false
- :timeline_id (u/the-id timeline)}))
+ (let [event (mt/user-http-request :rasta :post 200 "timeline-event"
+ {:name "Rasta Migrates to Florida for the Winter"
+ :timestamp (java.time.OffsetDateTime/now)
+ :timezone "US/Pacific"
+ :time_matters false
+ :timeline_id (u/the-id timeline)})]
+ (is (=? {:entity_id #(and (string? %) (= 21 (count %)))} event))
+ (is (= (:entity_id event)
+ (t2/select-one-fn :entity_id :model/TimelineEvent :id (:id event))))))
;; check the Timeline to see if the event is there
(is (= "Rasta Migrates to Florida for the Winter"
(-> (t2/select-one :model/TimelineEvent :timeline_id (u/the-id timeline)) :name))))))
@@ -103,6 +106,17 @@
(is (some #(nil? (hawk.approx/=?-diff* {:data {"event" "new_event_created"}} %))
(snowplow-test/pop-event-data-and-user-id!)))))))
+(deftest create-timeline-event-tracks-dashboard-source-test
+ (testing "POST /api/timeline-event reports a dashboard as the source of a new event"
+ (snowplow-test/with-fake-snowplow-collector
+ (mt/with-temp [:model/Collection {coll-id :id} {}
+ :model/Timeline {tl-id :id} {:collection_id coll-id}]
+ (mt/user-http-request :crowberto :post 200 "timeline-event"
+ {:name "RC1" :timestamp "2027-10-20" :timezone "UTC"
+ :time_matters false :timeline_id tl-id :source "dashboard"})
+ (is (some #(nil? (hawk.approx/=?-diff* {:data {"event" "new_event_created" "source" "dashboard"}} %))
+ (snowplow-test/pop-event-data-and-user-id!)))))))
+
(deftest delete-timeline-event-test
(testing "DELETE /api/timeline-event/:id"
(mt/with-temp [:model/Collection {collection-id :id} {:name "Example Data"}
diff --git a/test/metabase/app_db/schema_migrations_test.clj b/test/metabase/app_db/schema_migrations_test.clj
index 13c1508dd4b..a8261b402c6 100644
--- a/test/metabase/app_db/schema_migrations_test.clj
+++ b/test/metabase/app_db/schema_migrations_test.clj
@@ -3650,6 +3650,86 @@
(is (= #{implicit-id} (t2/select-pks-set :action)))
(is (= #{other-button} (t2/select-pks-set :report_dashboardcard :id [:in [http-button other-button]])))))))
+(deftest timeline-event-entity-ids-test
+ (testing "v65.h1c4r5 thru v65.lpm4z3: existing timeline events get distinct portable IDs, other data unchanged"
+ (impl/test-migrations ["v65.h1c4r5" "v65.lpm4z3"] [migrate!]
+ (let [user-id (t2/insert-returning-pk! :core_user {:email "[email protected]"
+ :password "password"
+ :date_joined :%now
+ :entity_id (u/generate-nano-id)})
+ timeline-id (t2/insert-returning-pk! :timeline {:name "Migration seasons"
+ :icon "star"
+ :creator_id user-id
+ :created_at :%now
+ :updated_at :%now
+ :entity_id (u/generate-nano-id)})
+ event {:name "Swallows return"
+ :archived false
+ :icon "star"
+ :timeline_id timeline-id
+ :creator_id user-id
+ :created_at :%now
+ :updated_at :%now
+ :timestamp #t "2027-04-20T00:00:00Z"
+ :time_matters false
+ :timezone "UTC"}
+ _ (t2/insert! :timeline_event [event (assoc event :archived true)])
+ before (t2/select :timeline_event {:order-by [:id]})]
+ (migrate!)
+ (let [after (t2/select :timeline_event {:order-by [:id]})
+ entity-ids (map :entity_id after)]
+ (is (= before (mapv #(dissoc % :entity_id) after)))
+ (is (= 2 (count (set entity-ids))))
+ (is (every? #(and (string? %) (re-matches #"[A-Za-z0-9_-]{21}" %)) entity-ids))
+ (is (thrown? Exception (t2/insert! :timeline_event event))
+ "new events must carry an entity ID")
+ (is (thrown? Exception (t2/insert! :timeline_event (assoc event :entity_id (first entity-ids))))
+ "two events must not share an entity ID"))))))
+
+(deftest timeline-event-entity-ids-rollback-test
+ (testing "v65.h1c4r5 thru v65.lpm4z3: rolling back leaves timeline events readable and writable by older code"
+ (impl/test-migrations ["v65.h1c4r5" "v65.lpm4z3"] [migrate!]
+ (let [user-id (t2/insert-returning-pk! :core_user {:email "[email protected]"
+ :password "password"
+ :date_joined :%now
+ :entity_id (u/generate-nano-id)})
+ timeline-id (t2/insert-returning-pk! :timeline {:name "Rollback seasons"
+ :icon "star"
+ :creator_id user-id
+ :created_at :%now
+ :updated_at :%now
+ :entity_id (u/generate-nano-id)})
+ event {:name "Swallows return"
+ :archived false
+ :icon "star"
+ :timeline_id timeline-id
+ :creator_id user-id
+ :created_at :%now
+ :updated_at :%now
+ :timestamp #t "2027-04-20T00:00:00Z"
+ :time_matters false
+ :timezone "UTC"}
+ _ (t2/insert! :timeline_event [event (assoc event
+ :name "Swifts leave"
+ :archived true
+ :timestamp #t "2027-08-15T00:00:00Z")])
+ portable-data (fn []
+ (map #(select-keys % [:name :timestamp :timeline_id :archived])
+ (t2/select :timeline_event {:order-by [:id]})))
+ before (portable-data)]
+ (migrate!)
+ (migrate! :down 64)
+ (testing "events written before the upgrade are still there, unchanged"
+ (is (= before (portable-data))))
+ (testing "and an event can be written without an entity ID again"
+ (is (some? (t2/insert-returning-pk! :timeline_event (assoc event :name "Storks nest")))))
+ (migrate!)
+ (testing "migrating forward again gives every event a distinct portable ID"
+ (let [entity-ids (map :entity_id (t2/select :timeline_event {:order-by [:id]}))]
+ (is (= 3 (count entity-ids)))
+ (is (= 3 (count (set entity-ids))))
+ (is (every? #(and (string? %) (re-matches #"[A-Za-z0-9_-]{21}" %)) entity-ids))))))))
+
(deftest add-library-dashboards-section-test
(testing "v65.2026-10-06T16:00:00 through v65.2026-10-06T16:00:02: an existing Library gets a Dashboards section with its permissions"
(impl/test-migrations ["v65.2026-10-06T16:00:00" "v65.2026-10-06T16:00:02"] [migrate!]
diff --git a/test/metabase/channel/render/body_test.clj b/test/metabase/channel/render/body_test.clj
index f96d66ca644..7ded045fdc8 100644
--- a/test/metabase/channel/render/body_test.clj
+++ b/test/metabase/channel/render/body_test.clj
@@ -877,6 +877,34 @@
(is (=? [tl-a tl-b] (:timeline_events (#'body/add-dashcard-timeline-events {:card card})))))
(is (= 2 (count (:timeline_events (first cards-with-data)))))))))))
+(deftest subscription-render-omits-timeline-events-test
+ (testing "A chart saved with timeline events renders in a subscription, without showing any of the events"
+ (mt/dataset test-data
+ (mt/with-current-user (mt/user->id :crowberto)
+ (let [event-name "Kilroy Was Here"]
+ (mt/with-temp [:model/Collection {collection-id :id} {:name "Timeline Collection"}
+ :model/Timeline {timeline-id :id} {:name "Releases"
+ :collection_id collection-id}
+ :model/TimelineEvent _ {:timeline_id timeline-id
+ :name event-name
+ :timestamp #t "2019-05-15T00:00:00Z"}
+ :model/Card {card-id :id}
+ {:display :line
+ :collection_id collection-id
+ :dataset_query (mt/mbql-query orders
+ {:aggregation [[:count]]
+ :breakout [!month.created_at]})
+ :visualization_settings {:timeline.selected_timeline_ids [timeline-id]}}
+ :model/Dashboard {dash-id :id} {:collection_id collection-id}
+ :model/DashboardCard {dashcard-id :id} {:dashboard_id dash-id
+ :card_id card-id}]
+ (let [doc (render.tu/render-dashcard-as-hickory! dashcard-id)]
+ (testing "the line chart itself renders"
+ (is (seq (hik.s/select (hik.s/tag :path) doc))))
+ (testing "the saved event is nowhere in the rendered chart"
+ (is (empty? (hik.s/select (hik.s/find-in-text (re-pattern event-name)) doc)))
+ (is (not (str/includes? (pr-str doc) event-name)))))))))))
+
(deftest unknown-column-settings-test
(testing "Unknown `:column_settings` keys don't break static-viz rendering with a Null Pointer Exception (#27941)."
(mt/dataset test-data
diff --git a/test/metabase/dashboards_rest/api_test.clj b/test/metabase/dashboards_rest/api_test.clj
index f962236cc52..11755098aaf 100644
--- a/test/metabase/dashboards_rest/api_test.clj
+++ b/test/metabase/dashboards_rest/api_test.clj
@@ -1269,6 +1269,244 @@
(is (not= (:entity_id dashboard) (:entity_id response))
"The copy should have a new entity ID generated")))))))
+(deftest copy-dashboard-keeps-inaccessible-timeline-selection-test
+ (testing "POST /api/dashboard/:id/copy deep copies a card whose selected timeline the user cannot read"
+ (mt/with-model-cleanup [:model/Dashboard :model/Card]
+ (mt/with-temp [:model/Collection collection {}
+ :model/Timeline timeline {:collection_id (:id collection)}
+ :model/Card card {:dataset_query (mt/mbql-query venues)
+ :visualization_settings {:timeline.selected_timeline_ids [(:id timeline)]}}
+ :model/Dashboard dashboard {}
+ :model/DashboardCard _ {:dashboard_id (:id dashboard) :card_id (:id card)}]
+ (perms/revoke-collection-permissions! (perms-group/all-users) collection)
+ (let [response (mt/user-http-request :rasta :post 200 (format "dashboard/%d/copy" (:id dashboard))
+ {:is_deep_copy true})
+ copied-card-id (t2/select-one-fn :card_id :model/DashboardCard :dashboard_id (:id response))]
+ (is (not= (:id card) copied-card-id))
+ (is (= [(:id timeline)]
+ (get-in (t2/select-one :model/Card copied-card-id)
+ [:visualization_settings :timeline.selected_timeline_ids]))))))))
+
+(deftest add-card-with-restricted-timeline-to-shared-dashboard-test
+ (testing "PUT /api/dashboard/:id adding a card whose selected timeline the user cannot read"
+ (mt/with-temporary-setting-values [enable-public-sharing true]
+ (mt/with-temp [:model/Collection restricted {}
+ :model/Timeline timeline {:collection_id (:id restricted)}
+ :model/Card {card-id :id} {:display :line
+ :visualization_settings {:timeline.selected_timeline_ids [(:id timeline)]}}
+ :model/Dashboard {public-id :id} {:public_uuid (str (random-uuid))}
+ :model/Dashboard {embedded-id :id} {:enable_embedding true}
+ :model/Dashboard {private-id :id} {}]
+ (perms/revoke-collection-permissions! (perms-group/all-users) restricted)
+ (with-dashboards-in-writeable-collection! [public-id embedded-id private-id]
+ (api.card-test/with-cards-in-readable-collection! [card-id]
+ (let [dashcards [{:id -1 :card_id card-id :row 0 :col 0 :size_x 4 :size_y 4}]]
+ (testing "is rejected on a public dashboard"
+ (is (= "You don't have permissions to do that."
+ (mt/user-http-request :rasta :put 403 (format "dashboard/%d" public-id)
+ {:dashcards dashcards :tabs []})))
+ (is (empty? (t2/select :model/DashboardCard :dashboard_id public-id))))
+ (testing "is rejected on an embedded dashboard"
+ (is (= "You don't have permissions to do that."
+ (mt/user-http-request :rasta :put 403 (format "dashboard/%d" embedded-id)
+ {:dashcards dashcards :tabs []}))))
+ (testing "is allowed on a dashboard that is not shared"
+ (is (= [card-id]
+ (map :card_id (:dashcards (mt/user-http-request :rasta :put 200 (format "dashboard/%d" private-id)
+ {:dashcards dashcards :tabs []}))))))
+ (testing "is allowed for a user who can read the timeline"
+ (is (= [card-id]
+ (map :card_id (:dashcards (mt/user-http-request :crowberto :put 200 (format "dashboard/%d" public-id)
+ {:dashcards dashcards :tabs []}))))))
+ (testing "a card already on the dashboard can still be saved"
+ (let [[dashcard] (t2/select :model/DashboardCard :dashboard_id public-id)]
+ (is (= [card-id]
+ (map :card_id (:dashcards (mt/user-http-request :rasta :put 200 (format "dashboard/%d" public-id)
+ {:dashcards [(assoc dashcard :row 1)] :tabs []}))))))))))))))
+
+(deftest add-series-with-restricted-timeline-to-shared-dashboard-test
+ (testing "PUT /api/dashboard/:id allows a series whose card selects an unreadable timeline, since a dashcard only shows its own card's events"
+ (mt/with-temporary-setting-values [enable-public-sharing true]
+ (mt/with-temp [:model/Collection restricted {}
+ :model/Timeline timeline {:collection_id (:id restricted)}
+ :model/Card {series-id :id} {:display :line
+ :visualization_settings {:timeline.selected_timeline_ids [(:id timeline)]}}
+ :model/Card {card-id :id} {:display :line}
+ :model/Dashboard {public-id :id} {:public_uuid (str (random-uuid))}]
+ (perms/revoke-collection-permissions! (perms-group/all-users) restricted)
+ (with-dashboards-in-writeable-collection! [public-id]
+ (api.card-test/with-cards-in-readable-collection! [card-id series-id]
+ (is (= [card-id]
+ (map :card_id (:dashcards (mt/user-http-request :rasta :put 200 (format "dashboard/%d" public-id)
+ {:dashcards [{:id -1 :card_id card-id
+ :row 0 :col 0 :size_x 4 :size_y 4
+ :series [{:id series-id}]}]
+ :tabs []})))))
+ (is (= [series-id]
+ (map :card_id (t2/select :model/DashboardCardSeries
+ :dashboardcard_id (t2/select-one-pk :model/DashboardCard
+ :dashboard_id public-id)))))))))))
+
+(deftest add-card-showing-no-events-to-shared-dashboard-test
+ (testing "PUT /api/dashboard/:id allows a card that never draws its selected timeline, whatever it names"
+ (mt/with-temporary-setting-values [enable-public-sharing true]
+ (mt/with-temp [:model/Collection restricted {}
+ :model/Timeline timeline {:collection_id (:id restricted)}
+ :model/Card {table-card-id :id} {:display :table
+ :visualization_settings {:timeline.selected_timeline_ids [(:id timeline)]}}
+ :model/Card {disabled-card-id :id} {:display :line
+ :visualization_settings {:timeline.selected_timeline_ids [(:id timeline)]
+ :timeline_events.enabled false}}
+ :model/Dashboard {public-id :id} {:public_uuid (str (random-uuid))}]
+ (perms/revoke-collection-permissions! (perms-group/all-users) restricted)
+ (with-dashboards-in-writeable-collection! [public-id]
+ (api.card-test/with-cards-in-readable-collection! [table-card-id disabled-card-id]
+ (doseq [[description card-id] [["a display that cannot draw events" table-card-id]
+ ["events turned off" disabled-card-id]]]
+ (testing description
+ (is (= [card-id]
+ (map :card_id (:dashcards (mt/user-http-request :rasta :put 200 (format "dashboard/%d" public-id)
+ {:dashcards [{:id -1 :card_id card-id
+ :row 0 :col 0 :size_x 4 :size_y 4}]
+ :tabs []})))))))))))))
+
+(deftest convert-action-dashcard-to-plain-on-shared-dashboard-test
+ (testing "PUT /api/dashboard/:id rejects clearing action_id, which turns a dashcard that hid its card's events into one that shows them"
+ (mt/with-actions-test-data-and-actions-enabled
+ (mt/with-temporary-setting-values [enable-public-sharing true]
+ (mt/with-actions [{:keys [action-id model-id]} {}]
+ (mt/with-temp [:model/Collection restricted {}
+ :model/Timeline timeline {:collection_id (:id restricted)}
+ :model/Dashboard {public-id :id} {:public_uuid (str (random-uuid))}
+ :model/DashboardCard {dashcard-id :id} {:dashboard_id public-id
+ :action_id action-id
+ :card_id model-id
+ :row 0 :col 0 :size_x 4 :size_y 4}]
+ (t2/update! :model/Card model-id {:display :line
+ :visualization_settings {:timeline.selected_timeline_ids [(:id timeline)]}})
+ (perms/revoke-collection-permissions! (perms-group/all-users) restricted)
+ (with-dashboards-in-writeable-collection! [public-id]
+ (api.card-test/with-cards-in-readable-collection! [model-id]
+ (is (= "You don't have permissions to do that."
+ (mt/user-http-request :rasta :put 403 (format "dashboard/%d" public-id)
+ {:dashcards [{:id dashcard-id :card_id model-id :action_id nil
+ :row 0 :col 0 :size_x 4 :size_y 4}]
+ :tabs []})))
+ (is (= [action-id]
+ (map :action_id (t2/select :model/DashboardCard :dashboard_id public-id))))))))))))
+
+(deftest move-card-between-tabs-on-shared-dashboard-test
+ (testing "PUT /api/dashboard/:id deleting a tab and re-adding its card on another tab exposes nothing new"
+ (mt/with-temporary-setting-values [enable-public-sharing true]
+ (mt/with-temp [:model/Collection restricted {}
+ :model/Timeline timeline {:collection_id (:id restricted)}
+ :model/Card {card-id :id} {:display :line
+ :visualization_settings {:timeline.selected_timeline_ids [(:id timeline)]}}
+ :model/Dashboard {public-id :id} {:public_uuid (str (random-uuid))}
+ :model/DashboardTab {tab-a-id :id} {:dashboard_id public-id :name "A" :position 0}
+ :model/DashboardTab tab-b {:dashboard_id public-id :name "B" :position 1}
+ :model/DashboardCard _ {:dashboard_id public-id :dashboard_tab_id tab-a-id
+ :card_id card-id :row 0 :col 0 :size_x 4 :size_y 4}]
+ (perms/revoke-collection-permissions! (perms-group/all-users) restricted)
+ (with-dashboards-in-writeable-collection! [public-id]
+ (api.card-test/with-cards-in-readable-collection! [card-id]
+ (mt/user-http-request :rasta :put 200 (format "dashboard/%d" public-id)
+ {:tabs [tab-b]
+ :dashcards [{:id -1 :card_id card-id :dashboard_tab_id (:id tab-b)
+ :row 0 :col 0 :size_x 4 :size_y 4}]})
+ (is (= [(:id tab-b)]
+ (map :dashboard_tab_id (t2/select :model/DashboardCard :dashboard_id public-id))))))))))
+
+(deftest convert-hidden-dashcard-to-plain-on-shared-dashboard-test
+ (testing "PUT /api/dashboard/:id rejects turning a dashcard that hides its card's events into one that shows them"
+ (mt/with-temporary-setting-values [enable-public-sharing true]
+ (mt/with-temp [:model/Collection restricted {}
+ :model/Timeline timeline {:collection_id (:id restricted)}
+ :model/Card {card-id :id} {:display :line
+ :visualization_settings {:timeline.selected_timeline_ids [(:id timeline)]}}
+ :model/Dashboard {public-id :id} {:public_uuid (str (random-uuid))}]
+ (perms/revoke-collection-permissions! (perms-group/all-users) restricted)
+ (with-dashboards-in-writeable-collection! [public-id]
+ (api.card-test/with-cards-in-readable-collection! [card-id]
+ (doseq [[description hidden-settings]
+ [["a visualizer dashcard" {:visualization {:display "line" :columnValuesMapping {} :settings {}}}]
+ ["a virtual dashcard" {:virtual_card {:display "text"}}]]]
+ (testing description
+ (mt/with-temp [:model/DashboardCard {dashcard-id :id} {:dashboard_id public-id
+ :card_id card-id
+ :visualization_settings hidden-settings
+ :row 0 :col 0 :size_x 4 :size_y 4}]
+ (is (= "You don't have permissions to do that."
+ (mt/user-http-request :rasta :put 403 (format "dashboard/%d" public-id)
+ {:dashcards [{:id dashcard-id :card_id card-id
+ :row 0 :col 0 :size_x 4 :size_y 4
+ :visualization_settings {}}]
+ :tabs []})))
+ (is (= [hidden-settings]
+ (map :visualization_settings
+ (t2/select :model/DashboardCard :dashboard_id public-id)))))))))))))
+
+(deftest point-dashcard-at-archived-restricted-timeline-card-test
+ (testing "PUT /api/dashboard/:id cannot point a dashcard at an archived card whose selected timeline the user cannot read"
+ (mt/with-temporary-setting-values [enable-public-sharing true]
+ (mt/with-temp [:model/Collection restricted {}
+ :model/Timeline timeline {:collection_id (:id restricted)}
+ :model/Card {archived-id :id} {:display :line
+ :archived true
+ :visualization_settings {:timeline.selected_timeline_ids [(:id timeline)]}}
+ :model/Card {placed-id :id} {}
+ :model/Dashboard {public-id :id} {:public_uuid (str (random-uuid))}
+ :model/DashboardCard {dashcard-id :id} {:dashboard_id public-id :card_id placed-id
+ :row 0 :col 0 :size_x 4 :size_y 4}]
+ (perms/revoke-collection-permissions! (perms-group/all-users) restricted)
+ (with-dashboards-in-writeable-collection! [public-id]
+ (api.card-test/with-cards-in-writeable-collection! [archived-id placed-id]
+ (is (= "You don't have permissions to do that."
+ (mt/user-http-request :rasta :put 403 (format "dashboard/%d" public-id)
+ {:dashcards [{:id dashcard-id :card_id archived-id
+ :row 0 :col 0 :size_x 4 :size_y 4}]
+ :tabs []})))
+ (testing "so unarchiving the card cannot put its events on the shared dashboard"
+ (mt/user-http-request :rasta :put 200 (str "card/" archived-id) {:archived false})
+ (is (= [placed-id]
+ (map :card_id (t2/select :model/DashboardCard :dashboard_id public-id)))))))))))
+
+(deftest add-visualizer-dashcard-with-restricted-timeline-to-shared-dashboard-test
+ (testing "PUT /api/dashboard/:id allows a visualizer dashcard whose card selects an unreadable timeline, since a shared dashboard never shows its events"
+ (mt/with-temporary-setting-values [enable-public-sharing true]
+ (mt/with-temp [:model/Collection restricted {}
+ :model/Timeline timeline {:collection_id (:id restricted)}
+ :model/Card {card-id :id} {:display :line
+ :visualization_settings {:timeline.selected_timeline_ids [(:id timeline)]}}
+ :model/Dashboard {public-id :id} {:public_uuid (str (random-uuid))}]
+ (perms/revoke-collection-permissions! (perms-group/all-users) restricted)
+ (with-dashboards-in-writeable-collection! [public-id]
+ (api.card-test/with-cards-in-readable-collection! [card-id]
+ (let [visualizer {:visualization {:display "line" :columnValuesMapping {} :settings {}}}]
+ (is (= [card-id]
+ (map :card_id (:dashcards (mt/user-http-request :rasta :put 200 (format "dashboard/%d" public-id)
+ {:dashcards [{:id -1 :card_id card-id
+ :row 0 :col 0 :size_x 4 :size_y 4
+ :visualization_settings visualizer}]
+ :tabs []})))))
+ (is (= [visualizer]
+ (map :visualization_settings (t2/select :model/DashboardCard :dashboard_id public-id))))
+ (testing "but turning it back into a plain dashcard would show them, so it is rejected"
+ (let [[dashcard] (t2/select :model/DashboardCard :dashboard_id public-id)]
+ (is (= "You don't have permissions to do that."
+ (mt/user-http-request :rasta :put 403 (format "dashboard/%d" public-id)
+ {:dashcards [(assoc dashcard :visualization_settings {})]
+ :tabs []})))
+ (testing "nor can a second plain dashcard be added for the same card"
+ (is (= "You don't have permissions to do that."
+ (mt/user-http-request :rasta :put 403 (format "dashboard/%d" public-id)
+ {:dashcards [dashcard {:id -1 :card_id card-id
+ :row 4 :col 0 :size_x 4 :size_y 4}]
+ :tabs []}))))
+ (is (= [visualizer]
+ (map :visualization_settings
+ (t2/select :model/DashboardCard :dashboard_id public-id)))))))))))))
+
(deftest copy-dashboard-with-dashboard-questions
(testing "`is_deep_copy=true` works for dashboards regardless of whether they have dashboard questions"
(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.clj
index 4ee52d9f051..ca22899ef42 100644
--- a/test/metabase/documents/api/document_test.clj
+++ b/test/metabase/documents/api/document_test.clj
@@ -323,6 +323,52 @@
(testing "no Card carrying that target may exist afterwards"
(is (empty? (t2/select :model/Card :collection_id coll-id))))))))))))
+(deftest document-draft-card-inherits-source-card-timeline-visibility-test
+ (testing "a draft card forked from a saved card inherits the source card's timeline selection"
+ (mt/with-model-cleanup [:model/Document :model/Card]
+ (mt/with-non-admin-groups-no-root-collection-perms
+ (mt/with-temp [:model/Collection {coll-id :id} {}
+ :model/Collection {restricted-id :id} {}
+ :model/Timeline private-timeline {:collection_id restricted-id}
+ :model/Timeline private-timeline-2 {:collection_id restricted-id}
+ :model/Card source {:collection_id coll-id
+ :display :line
+ :dataset_query (mt/mbql-query venues)
+ :visualization_settings {:timeline.selected_timeline_ids
+ [(:id private-timeline)]}}
+ :model/Card unreadable-source {:collection_id restricted-id
+ :display :line
+ :dataset_query (mt/mbql-query venues)
+ :visualization_settings {:timeline.selected_timeline_ids
+ [(:id private-timeline)]}}]
+ (perms/grant-collection-readwrite-permissions! (perms/all-users-group) coll-id)
+ (let [draft (-> source
+ (select-keys [:dataset_query :visualization_settings])
+ (assoc :name "Draft" :display "bar"))
+ save-doc! (fn [status card]
+ (mt/user-http-request :rasta :post status "document/"
+ {:name "d"
+ :collection_id coll-id
+ :document {:type "doc" :content []}
+ :cards {"-1" card}}))]
+ (testing "with the source card id the draft saves with the inherited timeline selection"
+ (let [doc-id (:id (save-doc! 200 (assoc draft :source_card_id (:id source))))]
+ (is (=? {:display :bar
+ :visualization_settings {:timeline.selected_timeline_ids [(:id private-timeline)]}}
+ (t2/select-one :model/Card :document_id doc-id)))))
+ (t2/delete! :model/Card :name "Draft")
+ (testing "without the source card id the unreadable timeline is refused"
+ (save-doc! 403 draft))
+ (testing "a newly added unreadable timeline is still refused"
+ (save-doc! 403 (-> draft
+ (assoc :source_card_id (:id source))
+ (assoc-in [:visualization_settings :timeline.selected_timeline_ids]
+ [(:id private-timeline) (:id private-timeline-2)]))))
+ (testing "a source card the user cannot read is refused"
+ (save-doc! 403 (assoc draft :source_card_id (:id unreadable-source))))
+ (testing "no draft card exists after the refused saves"
+ (is (empty? (t2/select :model/Card :name "Draft"))))))))))
+
(deftest copy-document-archived-document-test
(testing "POST /api/document/:id/copy - archived source document returns 404"
(mt/with-temp [:model/Document {doc-id :id} {:name "Archived Document"
@@ -2723,6 +2769,34 @@
(testing "the document-owned card is copied"
(is (t2/exists? :model/Card :document_id (:id result)))))))))))
+(deftest copy-document-with-inaccessible-timeline-selection-test
+ (testing "POST /api/document/:id/copy keeps a timeline selection the copier cannot read (mirrors card copy behavior)"
+ (mt/with-non-admin-groups-no-root-collection-perms
+ (mt/with-model-cleanup [:model/Document :model/Card]
+ (mt/with-temp [:model/Collection {coll-id :id} {}
+ :model/Collection {timeline-coll-id :id} {}
+ :model/Timeline {timeline-id :id} {:collection_id timeline-coll-id}
+ :model/Document {doc-id :id} {:name "Doc with timeline card"
+ :collection_id coll-id
+ :document (documents.test-util/text->prose-mirror-ast "placeholder")}
+ :model/Card {card-id :id} {:name "Doc-owned Card"
+ :collection_id coll-id
+ :document_id doc-id
+ :dataset_query (mt/mbql-query venues)
+ :visualization_settings {:timeline.selected_timeline_ids [timeline-id]}}]
+ (t2/update! :model/Document doc-id {:document (card-embed-ast card-id)})
+ (perms/grant-collection-readwrite-permissions! (perms/all-users-group) coll-id)
+ (perms/revoke-collection-permissions! (perms/all-users-group) timeline-coll-id)
+ (let [result (mt/user-http-request :rasta :post 200 (format "document/%d/copy" doc-id)
+ {:collection_id coll-id})
+ cloned-card (t2/select-one :model/Card :document_id (:id result))]
+ (testing "the document-owned card is cloned"
+ (is (some? cloned-card))
+ (is (not= card-id (:id cloned-card))))
+ (testing "the inherited timeline selection is preserved without a fresh read check"
+ (is (= [timeline-id]
+ (get-in cloned-card [:visualization_settings :timeline.selected_timeline_ids]))))))))))
+
(deftest post-document-draft-native-card-still-requires-native-perms-test
(testing "POST /api/document/ - client-supplied draft native cards still require native query perms"
(mt/with-non-admin-groups-no-root-collection-perms
diff --git a/test/metabase/mcp/v2/tools/dashboard_test.clj b/test/metabase/mcp/v2/tools/dashboard_test.clj
index 379324bedb4..93bd821d7ac 100644
--- a/test/metabase/mcp/v2/tools/dashboard_test.clj
+++ b/test/metabase/mcp/v2/tools/dashboard_test.clj
@@ -103,6 +103,43 @@
(testing "the dashcard got a real id, not the temp one"
(is (pos-int? (get-in result [:dashcards 0 :id])))))))))
+(deftest add-card-with-restricted-timeline-to-shared-dashboard-test
+ (testing "adding a card to a shared dashboard needs read access to the timelines it shows, as in the REST writer"
+ (mt/with-temporary-setting-values [enable-public-sharing true]
+ (mt/with-temp [:model/Collection restricted {}
+ :model/Timeline timeline {:collection_id (:id restricted)}
+ :model/Card card {:display :line
+ :visualization_settings {:timeline.selected_timeline_ids [(:id timeline)]}}
+ :model/Dashboard dashboard {:public_uuid (str (random-uuid))}]
+ (perms/revoke-collection-permissions! (perms-group/all-users) restricted)
+ (is (re-find #"You don't have permissions to do that"
+ (tool-error (call-tool! :rasta nil "dashboard_write"
+ (wire {:method "update" :id (:id dashboard)
+ :ops [{:op "add_card" :id -1 :card_id (:id card)}]})))))
+ (is (empty? (t2/select :model/DashboardCard :dashboard_id (:id dashboard))))))))
+
+(deftest move-card-between-tabs-on-shared-dashboard-test
+ (testing "deleting a tab and re-adding its card on another tab in one update exposes nothing new, as in REST"
+ (mt/with-temporary-setting-values [enable-public-sharing true]
+ (mt/with-temp [:model/Collection restricted {}
+ :model/Timeline timeline {:collection_id (:id restricted)}
+ :model/Card card {:display :line
+ :visualization_settings {:timeline.selected_timeline_ids [(:id timeline)]}}
+ :model/Dashboard dashboard {:public_uuid (str (random-uuid))}
+ :model/DashboardTab tab-a {:dashboard_id (:id dashboard) :name "A" :position 0}
+ :model/DashboardTab tab-b {:dashboard_id (:id dashboard) :name "B" :position 1}
+ :model/DashboardCard _ {:dashboard_id (:id dashboard) :dashboard_tab_id (:id tab-a)
+ :card_id (:id card) :row 0 :col 0 :size_x 4 :size_y 4}]
+ (perms/revoke-collection-permissions! (perms-group/all-users) restricted)
+ (mt/with-current-user (mt/user->id :rasta)
+ (dashboards.write/update-dashboard!
+ (:id dashboard)
+ {:tabs [tab-b]
+ :dashcards [{:id -1 :card_id (:id card) :dashboard_tab_id (:id tab-b)
+ :row 0 :col 0 :size_x 4 :size_y 4}]}))
+ (is (= [(:id tab-b)]
+ (map :dashboard_tab_id (t2/select :model/DashboardCard :dashboard_id (:id dashboard)))))))))
+
(deftest create-with-a-bad-op-writes-nothing-test
(testing "GHY-4147: a create whose ops fail leaves no dashboard behind — otherwise the agent sees
an error, retries, and ends up with a pile of empty dashboards"
diff --git a/test/metabase/mcp/v2/tools/duplicate_test.clj b/test/metabase/mcp/v2/tools/duplicate_test.clj
index efba172ab68..bee7ef2a16d 100644
--- a/test/metabase/mcp/v2/tools/duplicate_test.clj
+++ b/test/metabase/mcp/v2/tools/duplicate_test.clj
@@ -78,6 +78,23 @@
(is (= (:dataset_query (t2/select-one :model/Card :id card-id))
(:dataset_query copy))))))))
+(deftest duplicate-question-keeps-inaccessible-timeline-selection-test
+ (testing "a copy inherits a timeline selection the caller cannot read, like POST /api/card/:id/copy"
+ (mt/with-model-cleanup [:model/Card]
+ (mt/with-temp [:model/Collection {restricted-id :id} {}
+ :model/Timeline {timeline-id :id} {:collection_id restricted-id}
+ :model/Card {card-id :id} {:name "Orders over time"
+ :type :question
+ :display :line
+ :dataset_query (venues-query)
+ :visualization_settings
+ {:timeline.selected_timeline_ids [timeline-id]}}]
+ (perms/revoke-collection-permissions! (perms/all-users-group) restricted-id)
+ (let [result (tool-result (call-tool! :rasta {:type "question" :id card-id}))
+ copy (t2/select-one :model/Card :id (:id result))]
+ (is (= [timeline-id]
+ (get-in copy [:visualization_settings :timeline.selected_timeline_ids]))))))))
+
(deftest duplicate-question-default-name-is-localized-test
(testing "GHY-4544: the default copy name is translated into the user's locale, like the REST copy endpoints"
(mt/with-model-cleanup [:model/Card]
@@ -294,6 +311,33 @@
(is (=? {:name "Revenue" :collection_id dest-coll}
(t2/select-one :model/Card :id (first new-cards))))))))))
+(deftest duplicate-dashboard-deep-keeps-inaccessible-timeline-selection-test
+ (testing "a deep copy keeps a card's timeline selection the caller cannot read, like the REST deep copy"
+ (mt/with-model-cleanup [:model/Dashboard :model/Card]
+ (mt/with-temp [:model/Collection {source-coll :id} {}
+ :model/Collection {dest-coll :id} {}
+ :model/Collection {restricted :id} {}
+ :model/Timeline {timeline-id :id} {:collection_id restricted}
+ :model/Card {card-id :id} {:name "Orders over time"
+ :type :question
+ :display :line
+ :collection_id source-coll
+ :dataset_query (venues-query)
+ :visualization_settings
+ {:timeline.selected_timeline_ids [timeline-id]}}
+ :model/Dashboard {dash-id :id} {:name "Sales" :collection_id source-coll}
+ :model/DashboardCard _ {:dashboard_id dash-id :card_id card-id}]
+ (perms/revoke-collection-permissions! (perms/all-users-group) restricted)
+ (let [result (tool-result (call-tool! :rasta {:type "dashboard"
+ :id dash-id
+ :collection_id dest-coll
+ :is_deep_copy true}))
+ new-cards (map :card_id (copied-dashcards (:id result)))]
+ (is (= 1 (count new-cards)))
+ (is (= [timeline-id]
+ (get-in (t2/select-one :model/Card :id (first new-cards))
+ [:visualization_settings :timeline.selected_timeline_ids]))))))))
+
(deftest duplicate-dashboard-deep-uncopied-test
(testing "GHY-4151: a deep copy reports cards it left behind as `uncopied`, and an unreadable one
is reported by id alone — the tool must not hand the agent the name or query of a card
diff --git a/test/metabase/models/serialization_test.clj b/test/metabase/models/serialization_test.clj
index 368da79031f..5deb536b282 100644
--- a/test/metabase/models/serialization_test.clj
+++ b/test/metabase/models/serialization_test.clj
@@ -262,6 +262,52 @@
:id "[\"dimension\",[\"field\",54,{\"source-field\":53}]]"
:dimension ["dimension" [:field 54 {:source-field 53}]]}}}}}}})))))
+(deftest ^:parallel import-old-timeline-events-settings-test
+ (testing "source-instance numeric IDs cannot select unrelated destination timelines or hide their events"
+ (let [settings {:graph.show_values true
+ :timeline.selected_timeline_ids [7]
+ :timeline.excluded_timeline_event_ids [42]}]
+ (is (= {:graph.show_values true
+ :timeline.selected_timeline_ids []
+ :timeline.excluded_timeline_event_ids []}
+ (select-keys (serdes/import-visualization-settings settings) (keys settings)))))))
+
+(deftest ^:parallel export-malformed-timeline-events-settings-test
+ (testing "values that are not numeric IDs are dropped on export instead of failing it"
+ (let [settings {:timeline.selected_timeline_ids [1 "abc" nil]
+ :timeline.excluded_timeline_event_ids [2 -1 "xyz"]}]
+ (binding [serdes/*export-fk* (fn [id model] (format "%s___%d" (name model) id))]
+ (is (= {:timeline.selected_timeline_ids ["Timeline___1"]
+ :timeline.excluded_timeline_event_ids ["TimelineEvent___2"]}
+ (select-keys (serdes/export-visualization-settings settings) (keys settings)))))
+ (is (= #{[{:model "Timeline" :id 1}]}
+ (serdes/visualization-settings-deps true (update settings :timeline.excluded_timeline_event_ids
+ (partial remove pos-int?))))))))
+
+(deftest ^:parallel scalar-timeline-events-settings-test
+ (testing "a setting holding a scalar instead of a list counts as no ids rather than failing export or deps"
+ (let [settings {:timeline.selected_timeline_ids 7
+ :timeline.excluded_timeline_event_ids true}]
+ (binding [serdes/*export-fk* (fn [id model] (format "%s___%d" (name model) id))]
+ (is (= {:timeline.selected_timeline_ids []
+ :timeline.excluded_timeline_event_ids []}
+ (select-keys (serdes/export-visualization-settings settings) (keys settings)))))
+ (is (= #{} (serdes/visualization-settings-deps true settings)))
+ (is (= {:timeline.selected_timeline_ids []
+ :timeline.excluded_timeline_event_ids []}
+ (select-keys (serdes/import-visualization-settings settings) (keys settings)))))))
+
+(deftest ^:parallel excluded-timeline-events-deps-without-selection-test
+ (testing "excluded events pull in their Timeline even when the card selects no timelines, so the Timeline loads
+ first and the exclusions survive the import instead of un-hiding the events"
+ (let [eid (fn [c] (apply str (repeat 21 c)))]
+ (is (= #{[{:model "Timeline" :id (eid \a)}]
+ [{:model "Timeline" :id (eid \c)}]}
+ (serdes/visualization-settings-deps
+ false
+ {:timeline.excluded_timeline_event_ids [[(eid \a) (eid \b)]
+ [(eid \c) (eid \d)]]}))))))
+
(deftest ^:parallel import-viz-settings-test
(binding [serdes/*import-field-fk* (constantly 3)]
(is (= {:column_settings
diff --git a/test/metabase/public_sharing_rest/api_test.clj b/test/metabase/public_sharing_rest/api_test.clj
index fdbbd5aeeee..cb839be19e4 100644
--- a/test/metabase/public_sharing_rest/api_test.clj
+++ b/test/metabase/public_sharing_rest/api_test.clj
@@ -2,6 +2,7 @@
"Tests for `api/public/` (public links) endpoints."
{:clj-kondo/config '{:linters {:deprecated-var {:exclude {metabase.test.data/mbql-query {:namespaces [metabase.public-sharing-rest.api-test]}}}}}}
(:require
+ [buddy.sign.jwt :as jwt]
[clojure.data.csv :as csv]
[clojure.set :as set]
[clojure.string :as str]
@@ -33,6 +34,7 @@
[metabase.util :as u]
[metabase.util.encryption :as encryption]
[metabase.util.json :as json]
+ [metabase.util.random :as u.random]
[metabase.warehouse-schema.models.field-values :as field-values]
[throttle.core :as throttle]
[toucan2.core :as t2])
@@ -2512,3 +2514,213 @@
(let [response (client/client :get 200 "public/oembed?url=path/to/url&format=json")]
(is (= "1.0" (:version response)))
(is (= "rich" (:type response)))))))
+
+(defn- public-dashboard-properties []
+ {:public_uuid (str (random-uuid))
+ :made_public_by_id (mt/user->id :crowberto)
+ :enable_embedding true
+ :parameters []})
+
+(defn- dashboard-events [dashboard]
+ (into {} (map (juxt :id :timeline_events)) (:dashcards dashboard)))
+
+(defn- dashboard-event-ids [dashboard]
+ (update-vals (dashboard-events dashboard) #(mapv :id %)))
+
+(defn- public-dashboard [dashboard]
+ (mt/client :get 200 (str "public/dashboard/" (:public_uuid dashboard))))
+
+(deftest public-and-signed-dashboard-timeline-selections-test
+ (let [secret (u.random/secure-hex 32)]
+ (mt/with-temporary-setting-values [enable-public-sharing true
+ enable-embedding-static true
+ embedding-secret-key secret]
+ (mt/with-temp [:model/Collection collection {}
+ :model/Timeline first-timeline {:collection_id (:id collection)}
+ :model/Timeline second-timeline {:collection_id (:id collection)}
+ :model/Timeline unrelated {:collection_id (:id collection)}
+ :model/Timeline archived {:collection_id (:id collection) :archived true}
+ :model/Timeline missing {}
+ :model/TimelineEvent first-event {:timeline_id (:id first-timeline)}
+ :model/TimelineEvent excluded {:timeline_id (:id first-timeline)}
+ :model/TimelineEvent _archived {:timeline_id (:id first-timeline) :archived true}
+ :model/TimelineEvent second-event {:timeline_id (:id second-timeline)}
+ :model/TimelineEvent _unrelated {:timeline_id (:id unrelated)}
+ :model/TimelineEvent _on-archived {:timeline_id (:id archived)}
+ :model/Dashboard dashboard (public-dashboard-properties)
+ :model/Card first-card
+ {:display "line"
+ :collection_id (:id collection)
+ :visualization_settings {:timeline.selected_timeline_ids [(:id first-timeline)
+ (:id archived) (:id missing)]
+ :timeline.excluded_timeline_event_ids [(:id excluded)]}}
+ :model/Card second-card
+ {:display "line"
+ :visualization_settings {:timeline.selected_timeline_ids [(:id second-timeline)]}}
+ :model/Card unselected-card {:display "line" :collection_id (:id collection)}
+ :model/Card empty-card
+ {:display "line"
+ :visualization_settings {:timeline.selected_timeline_ids []}}
+ :model/DashboardCard first-dashcard {:dashboard_id (:id dashboard) :card_id (:id first-card)}
+ :model/DashboardCard second-dashcard {:dashboard_id (:id dashboard) :card_id (:id second-card)}
+ :model/DashboardCard unselected-dashcard {:dashboard_id (:id dashboard)
+ :card_id (:id unselected-card)}
+ :model/DashboardCard empty-dashcard {:dashboard_id (:id dashboard) :card_id (:id empty-card)}]
+ (t2/delete! :model/Timeline (:id missing))
+ (perms/revoke-collection-permissions! (perms-group/all-users) collection)
+ (let [token (jwt/sign {:resource {:dashboard (:id dashboard)} :params {}} secret)
+ expected {(:id first-dashcard) [(:id first-event)]
+ (:id second-dashcard) [(:id second-event)]
+ (:id unselected-dashcard) []
+ (:id empty-dashcard) []}]
+ (doseq [path [(str "public/dashboard/" (:public_uuid dashboard)) (str "embed/dashboard/" token)]]
+ (testing path
+ (let [response (mt/client :get 200 path)]
+ (is (= expected (dashboard-event-ids response)))
+ (testing "only rendering fields are public"
+ (doseq [event (mapcat val (dashboard-events response))]
+ (is (= #{:id :timeline_id :name :description :icon :timestamp :timezone
+ :time_matters :archived :created_at}
+ (set (keys event)))))))))
+ (testing "a signed-in viewer without collection access sees the same public selection"
+ (is (= expected
+ (dashboard-event-ids
+ (mt/user-http-request :rasta :get 200 (str "public/dashboard/" (:public_uuid dashboard))))))))))))
+
+(deftest public-and-signed-dashboard-timeline-display-changes-test
+ (let [secret (u.random/secure-hex 32)]
+ (mt/with-temporary-setting-values [enable-public-sharing true
+ enable-embedding-static true
+ embedding-secret-key secret]
+ (mt/with-temp [:model/Timeline timeline {}
+ :model/TimelineEvent event {:timeline_id (:id timeline)}
+ :model/Card card {:display "line"
+ :visualization_settings {:timeline.selected_timeline_ids [(:id timeline)]}}
+ :model/Dashboard dashboard (public-dashboard-properties)
+ :model/DashboardCard dashcard {:dashboard_id (:id dashboard) :card_id (:id card)}]
+ (let [token (jwt/sign {:resource {:dashboard (:id dashboard)} :params {}} secret)
+ paths [(str "public/dashboard/" (:public_uuid dashboard)) (str "embed/dashboard/" token)]]
+ (doseq [[display visible?] [["line" true] ["table" false] ["pie" false] ["row" false]
+ ["bar" true] ["area" true] ["combo" true] ["scatter" true] ["waterfall" true]]]
+ (testing (str "saving the question as " display)
+ (let [updated-card (mt/user-http-request :crowberto :put 200 (str "card/" (:id card)) {:display display})]
+ (is (= (:visualization_settings card) (:visualization_settings updated-card))
+ "Changing display preserves the saved timeline selection"))
+ (doseq [path paths]
+ (testing path
+ (is (= {(:id dashcard) (if visible? [(:id event)] [])}
+ (dashboard-event-ids (mt/client :get 200 path)))))))))))))
+
+(deftest public-and-signed-dashboard-timeline-display-permissions-test
+ (let [secret (u.random/secure-hex 32)]
+ (mt/with-temporary-setting-values [enable-public-sharing true
+ enable-embedding-static true
+ embedding-secret-key secret]
+ (mt/with-temp [:model/Collection collection {}
+ :model/Timeline timeline {:collection_id (:id collection)}
+ :model/TimelineEvent event {:timeline_id (:id timeline)}
+ :model/Card card {:display "line"
+ :visualization_settings {:timeline.selected_timeline_ids [(:id timeline)]}}
+ :model/Dashboard dashboard (public-dashboard-properties)
+ :model/DashboardCard dashcard {:dashboard_id (:id dashboard) :card_id (:id card)}]
+ (perms/revoke-collection-permissions! (perms-group/all-users) collection)
+ (let [card-path (str "card/" (:id card))
+ token (jwt/sign {:resource {:dashboard (:id dashboard)} :params {}} secret)
+ paths [(str "public/dashboard/" (:public_uuid dashboard)) (str "embed/dashboard/" token)]]
+ (testing "display changes that don't reveal events don't need timeline access"
+ (mt/user-http-request :rasta :put 200 card-path {:display "bar"})
+ (mt/user-http-request :rasta :put 200 card-path {:display "table"}))
+ (testing "changing display cannot reveal an inaccessible timeline"
+ (mt/user-http-request :rasta :put 403 card-path {:display "line"})
+ (is (= :table (t2/select-one-fn :display :model/Card (:id card))))
+ (is (= (:visualization_settings card)
+ (t2/select-one-fn :visualization_settings :model/Card (:id card))))
+ (doseq [path paths]
+ (is (= {(:id dashcard) []} (dashboard-event-ids (mt/client :get 200 path))))))
+ (testing "timeline readers can restore a supported display"
+ (perms/grant-collection-read-permissions! (perms-group/all-users) collection)
+ (mt/user-http-request :rasta :put 200 card-path {:display "line"})
+ (doseq [path paths]
+ (is (= {(:id dashcard) [(:id event)]} (dashboard-event-ids (mt/client :get 200 path)))))))))))
+
+(deftest public-dashboard-ineligible-dashcards-test
+ (mt/with-temporary-setting-values [enable-public-sharing true]
+ (mt/with-temp [:model/Timeline timeline {}
+ :model/TimelineEvent _event {:timeline_id (:id timeline)}
+ :model/Dashboard dashboard (public-dashboard-properties)]
+ (doseq [[description card-properties dashcard-settings]
+ [["disabled events" {:visualization_settings {:timeline_events.enabled false}} {}]
+ ["archived dashboard question" {:dashboard_id (:id dashboard)
+ :archived true :archived_directly false} {}]
+ ["virtual card with a backing question" {} {:virtual_card {:display "text"}}]
+ ["visualizer with a backing question" {} {:visualization {}}]]]
+ (testing description
+ (mt/with-temp [:model/Card card
+ (-> (merge {:display "line"} card-properties)
+ (update :visualization_settings assoc :timeline.selected_timeline_ids [(:id timeline)]))
+ :model/DashboardCard dashcard {:dashboard_id (:id dashboard)
+ :card_id (:id card)
+ :visualization_settings dashcard-settings}]
+ (is (= {(:id dashcard) []} (dashboard-event-ids (public-dashboard dashboard))))))))))
+
+(deftest public-dashboard-action-dashcard-events-test
+ (mt/with-actions-test-data-and-actions-enabled
+ (mt/with-temporary-setting-values [enable-public-sharing true]
+ (mt/with-actions [{:keys [action-id model-id]} {}]
+ (mt/with-temp [:model/Timeline timeline {}
+ :model/TimelineEvent _event {:timeline_id (:id timeline)}
+ :model/Dashboard dashboard (public-dashboard-properties)
+ :model/DashboardCard dashcard {:dashboard_id (:id dashboard)
+ :action_id action-id
+ :card_id model-id}]
+ (t2/update! :model/Card model-id
+ {:visualization_settings {:timeline.selected_timeline_ids [(:id timeline)]}})
+ (is (= {(:id dashcard) []} (dashboard-event-ids (public-dashboard dashboard)))))))))
+
+(deftest public-dashboard-series-card-events-test
+ (testing "a dashcard shows the events its own card selects, not the ones its series select"
+ (mt/with-temporary-setting-values [enable-public-sharing true]
+ (mt/with-temp [:model/Timeline card-timeline {}
+ :model/TimelineEvent card-event {:timeline_id (:id card-timeline)}
+ :model/Timeline series-timeline {}
+ :model/TimelineEvent _series-event {:timeline_id (:id series-timeline)}
+ :model/Dashboard dashboard (public-dashboard-properties)
+ :model/Card card {:display "line"
+ :visualization_settings {:timeline.selected_timeline_ids [(:id card-timeline)]}}
+ :model/Card series-card {:display "line"
+ :visualization_settings {:timeline.selected_timeline_ids [(:id series-timeline)]}}
+ :model/DashboardCard dashcard {:dashboard_id (:id dashboard) :card_id (:id card)}
+ :model/DashboardCardSeries _ {:dashboardcard_id (:id dashcard)
+ :card_id (:id series-card)
+ :position 0}]
+ (is (= {(:id dashcard) [(:id card-event)]}
+ (dashboard-event-ids (public-dashboard dashboard))))))))
+
+(deftest public-dashboard-cardless-dashcard-events-test
+ (mt/with-temporary-setting-values [enable-public-sharing true]
+ (mt/with-temp [:model/Dashboard dashboard (public-dashboard-properties)
+ :model/DashboardCard dashcard {:dashboard_id (:id dashboard) :card_id nil}]
+ (is (= {(:id dashcard) []} (dashboard-event-ids (public-dashboard dashboard)))))))
+
+(deftest public-dashboard-does-not-authorize-timeline-apis-test
+ (mt/with-temporary-setting-values [enable-public-sharing true]
+ (mt/with-temp [:model/Timeline timeline {}
+ :model/TimelineEvent event {:timeline_id (:id timeline)}
+ :model/Dashboard dashboard (public-dashboard-properties)
+ :model/Card card {:display "line"
+ :visualization_settings {:timeline.selected_timeline_ids [(:id timeline)]}}
+ :model/DashboardCard dashcard {:dashboard_id (:id dashboard) :card_id (:id card)}]
+ (is (= {(:id dashcard) [(:id event)]} (dashboard-event-ids (public-dashboard dashboard))))
+ (doseq [[method path body]
+ [[:get "timeline" nil]
+ [:get (str "timeline/" (:id timeline)) nil]
+ [:get (str "timeline-event/" (:id event)) nil]
+ [:post "timeline-event" {:timeline_id (:id timeline) :name "Unauthorized event"
+ :timestamp "2026-09-09" :timezone "UTC"}]
+ [:put (str "timeline-event/" (:id event)) {:name "Unauthorized edit"}]
+ [:delete (str "timeline-event/" (:id event)) nil]]]
+ (testing (str method " " path)
+ (is (= 401 (:status (if body
+ (mt/client-full-response method 401 path body)
+ (mt/client-full-response method 401 path)))))))
+ (is (= (:name event) (t2/select-one-fn :name :model/TimelineEvent (:id event)))))))
diff --git a/test/metabase/queries/models/card_test.clj b/test/metabase/queries/models/card_test.clj
index 93ad5ac18b1..ec2504ed0b0 100644
--- a/test/metabase/queries/models/card_test.clj
+++ b/test/metabase/queries/models/card_test.clj
@@ -14,6 +14,8 @@
[metabase.lib.test-util.notebook-helpers :as notebook-helpers]
[metabase.models.interface :as mi]
[metabase.models.serialization :as serdes]
+ [metabase.permissions.models.permissions :as perms]
+ [metabase.permissions.models.permissions-group :as perms-group]
[metabase.queries.card-schema :as card-schema]
[metabase.queries.db :as queries.db]
[metabase.queries.models.card :as card]
@@ -756,6 +758,15 @@
(is (= {["NativeQuerySnippet" (:id snippet)] {"Card" (:id card)}}
(serdes/descendants "Card" (:id card) {}))))))
+(deftest ^:parallel excluded-only-timeline-events-deps-test
+ (testing "a card that only excludes events still depends on their Timeline, so it imports in the right order"
+ (mt/with-temp [:model/Timeline {timeline-id :id} {}
+ :model/TimelineEvent {event-id :id} {:timeline_id timeline-id}]
+ (is (= #{[{:model "Timeline" :id timeline-id}]}
+ (serdes/visualization-settings-deps
+ true
+ {:timeline.excluded_timeline_event_ids [event-id]}))))))
+
(deftest ^:parallel descendants-test-4
(testing "cards which have parameter's source is another card"
(mt/with-temp [:model/Card card1 {:name "base card"}
@@ -2037,3 +2048,195 @@
(t2/update! :model/Card card-id {:dataset_query (mt/mbql-query categories {:aggregation [[:count]]})})
(is (= #{(mt/id :categories)}
(into #{} (map :table-id) (t2/select-one-fn :dimension_mappings :model/Card :id card-id)))))))
+
+(deftest new-card-timeline-selection-permissions-test
+ (mt/with-temp [:model/Collection collection {}
+ :model/Timeline timeline {:collection_id (:id collection)}]
+ (perms/revoke-collection-permissions! (perms-group/all-users) collection)
+ (mt/with-test-user :rasta
+ (is (thrown-with-msg?
+ clojure.lang.ExceptionInfo #"You don't have permissions"
+ (mt/with-temp [:model/Card _ {:visualization_settings {:timeline.selected_timeline_ids [(:id timeline)]}}]
+ nil))))
+ (perms/grant-collection-read-permissions! (perms-group/all-users) collection)
+ (mt/with-test-user :rasta
+ (mt/with-temp [:model/Card card {:visualization_settings {:timeline.selected_timeline_ids [(:id timeline)]}}]
+ (is (= [(:id timeline)] (get-in card [:visualization_settings :timeline.selected_timeline_ids])))))))
+
+(deftest with-copy-source-card-timeline-selection-permissions-test
+ (mt/with-temp [:model/Collection collection {}
+ :model/Timeline timeline-a {:collection_id (:id collection)}
+ :model/Timeline timeline-b {:collection_id (:id collection)}]
+ (perms/revoke-collection-permissions! (perms-group/all-users) collection)
+ ;; source cards are created outside `with-test-user` so their own insert isn't permission-checked
+ (testing "a copy inheriting the exact source selection does not need a fresh read check"
+ (mt/with-temp [:model/Card source {:visualization_settings {:timeline.selected_timeline_ids [(:id timeline-a)]}}]
+ (mt/with-test-user :rasta
+ (card/with-copy-source-card source
+ (mt/with-temp [:model/Card copy {:visualization_settings {:timeline.selected_timeline_ids [(:id timeline-a)]}}]
+ (is (= [(:id timeline-a)] (get-in copy [:visualization_settings :timeline.selected_timeline_ids]))))))))
+ (testing "a copy whose selection differs from the source is still permission-checked"
+ (mt/with-temp [:model/Card source {:visualization_settings {:timeline.selected_timeline_ids [(:id timeline-a)]}}]
+ (mt/with-test-user :rasta
+ (card/with-copy-source-card source
+ (is (thrown-with-msg?
+ clojure.lang.ExceptionInfo #"You don't have permissions"
+ (mt/with-temp [:model/Card _ {:visualization_settings
+ {:timeline.selected_timeline_ids [(:id timeline-a) (:id timeline-b)]}}]
+ nil)))))))))
+
+(deftest card-timeline-visibility-update-permissions-test
+ (mt/with-temp [:model/Collection collection {}
+ :model/Timeline timeline {:collection_id (:id collection)}
+ :model/TimelineEvent excluded {:timeline_id (:id timeline)}]
+ (perms/revoke-collection-permissions! (perms-group/all-users) collection)
+ (doseq [[description before after]
+ [["revealing an excluded event"
+ {:timeline.selected_timeline_ids [(:id timeline)]
+ :timeline.excluded_timeline_event_ids [(:id excluded)]}
+ {:timeline.selected_timeline_ids [(:id timeline)]
+ :timeline.excluded_timeline_event_ids []}]
+ ["re-enabling an inaccessible timeline"
+ {:timeline.selected_timeline_ids [(:id timeline)] :timeline_events.enabled false}
+ {:timeline.selected_timeline_ids [(:id timeline)] :timeline_events.enabled true}]]]
+ (testing description
+ (mt/with-temp [:model/Card card {:display :line :visualization_settings before}]
+ (mt/with-test-user :rasta
+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"You don't have permissions"
+ (t2/update! :model/Card (:id card) {:visualization_settings after}))))
+ (is (= before (t2/select-one-fn :visualization_settings :model/Card (:id card)))))))))
+
+(deftest card-timeline-visibility-on-a-display-without-events-test
+ (testing "a display that cannot draw events shows nothing, so its visibility settings need no timeline access"
+ (mt/with-temp [:model/Collection collection {}
+ :model/Timeline timeline {:collection_id (:id collection)}
+ :model/Card card {:display :table
+ :visualization_settings {:timeline.selected_timeline_ids [(:id timeline)]
+ :timeline_events.enabled false}}]
+ (perms/revoke-collection-permissions! (perms-group/all-users) collection)
+ (mt/with-test-user :rasta
+ (let [settings {:timeline.selected_timeline_ids [(:id timeline)] :timeline_events.enabled true}]
+ (t2/update! :model/Card (:id card) {:visualization_settings settings})
+ (is (= settings (t2/select-one-fn :visualization_settings :model/Card (:id card)))))
+ (testing "switching to a display that draws them is still checked"
+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"You don't have permissions"
+ (t2/update! :model/Card (:id card) {:display :line}))))))))
+
+(deftest partially-readable-card-timeline-selection-test
+ (testing "on a card that also selects a timeline the user cannot read"
+ (mt/with-temp [:model/Collection restricted {}
+ :model/Timeline private-timeline {:collection_id (:id restricted)}
+ :model/TimelineEvent private-event {:timeline_id (:id private-timeline)}
+ :model/Timeline readable-timeline {}
+ :model/TimelineEvent readable-event {:timeline_id (:id readable-timeline)}
+ :model/Card card {:display :line
+ :visualization_settings
+ {:timeline.selected_timeline_ids [(:id readable-timeline) (:id private-timeline)]
+ :timeline.excluded_timeline_event_ids []}}]
+ (perms/revoke-collection-permissions! (perms-group/all-users) restricted)
+ (let [settings (fn [& {:as overrides}]
+ (merge {:timeline.selected_timeline_ids [(:id readable-timeline) (:id private-timeline)]
+ :timeline.excluded_timeline_event_ids []}
+ overrides))
+ ;; no bound user, so this restores the starting point without a permission check
+ restore! #(t2/update! :model/Card (:id card) {:visualization_settings (settings)})
+ update-settings! (fn [settings]
+ (mt/with-test-user :rasta
+ (t2/update! :model/Card (:id card) {:visualization_settings settings}))
+ (t2/select-one-fn :visualization_settings :model/Card (:id card)))]
+ (testing "an event of the readable timeline can be hidden and shown again"
+ (restore!)
+ (let [hidden (settings :timeline.excluded_timeline_event_ids [(:id readable-event)])]
+ (is (= hidden (update-settings! hidden)))
+ (is (= (settings) (update-settings! (settings))))))
+ (testing "an event of the unreadable timeline can be hidden but not shown again"
+ (restore!)
+ (let [hidden (settings :timeline.excluded_timeline_event_ids [(:id private-event)])]
+ (is (= hidden (update-settings! hidden)))
+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"You don't have permissions"
+ (update-settings! (settings))))
+ (is (= hidden (t2/select-one-fn :visualization_settings :model/Card (:id card))))))
+ (testing "the readable timeline can be deselected and selected again"
+ (restore!)
+ (let [deselected (settings :timeline.selected_timeline_ids [(:id private-timeline)])]
+ (is (= deselected (update-settings! deselected)))
+ (is (= (settings) (update-settings! (settings))))))
+ (testing "another unreadable timeline cannot be selected"
+ (restore!)
+ (mt/with-temp [:model/Timeline other-private {:collection_id (:id restricted)}]
+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"You don't have permissions"
+ (update-settings!
+ (settings :timeline.selected_timeline_ids
+ [(:id readable-timeline) (:id private-timeline) (:id other-private)]))))))))))
+
+(deftest unchanged-or-cleared-card-timeline-selection-test
+ (mt/with-temp [:model/Collection collection {}
+ :model/Timeline timeline {:collection_id (:id collection)}
+ :model/Card card {:visualization_settings {:timeline.selected_timeline_ids [(:id timeline)]}}]
+ (perms/revoke-collection-permissions! (perms-group/all-users) collection)
+ (mt/with-test-user :rasta
+ (testing "unrelated visualization edits preserve inaccessible saved selections"
+ (let [settings (assoc (:visualization_settings card) :graph.show_values true)]
+ (t2/update! :model/Card (:id card) {:visualization_settings settings})
+ (is (= settings (t2/select-one-fn :visualization_settings :model/Card (:id card)))))
+ (testing "an explicit empty selection can hide all events"
+ (t2/update! :model/Card (:id card) {:visualization_settings {:timeline.selected_timeline_ids []}})
+ (is (= [] (get-in (t2/select-one :model/Card (:id card))
+ [:visualization_settings :timeline.selected_timeline_ids]))))))))
+
+(deftest card-timeline-selection-validation-test
+ (mt/with-temp [:model/Card card {}]
+ (mt/with-test-user :rasta
+ (doseq [invalid-ids [false 1 "1" [0] [-1] ["1"] [nil]]]
+ (testing (pr-str invalid-ids)
+ (let [settings {:timeline.selected_timeline_ids invalid-ids}]
+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"Selected timeline IDs must be"
+ (t2/update! :model/Card (:id card) {:visualization_settings settings}))))
+ (let [settings {:timeline.excluded_timeline_event_ids invalid-ids}]
+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"Excluded timeline event IDs must be"
+ (t2/update! :model/Card (:id card) {:visualization_settings settings})))))))))
+
+(deftest card-timeline-malformed-saved-selection-test
+ (testing "a malformed selection saved before it was validated can still be repaired"
+ (mt/with-temp [:model/Timeline timeline {}
+ :model/Card card {:display :line
+ :visualization_settings {:timeline.selected_timeline_ids 7}}]
+ (doseq [repaired [[(:id timeline)] []]]
+ ;; no bound user, so each case starts from the malformed value again
+ (t2/update! :model/Card (:id card) {:visualization_settings {:timeline.selected_timeline_ids 7}})
+ (mt/with-test-user :rasta
+ (t2/update! :model/Card (:id card) {:visualization_settings {:timeline.selected_timeline_ids repaired}}))
+ (is (= repaired
+ (get-in (t2/select-one :model/Card (:id card))
+ [:visualization_settings :timeline.selected_timeline_ids])))))))
+
+(deftest card-timeline-malformed-saved-exclusions-test
+ (testing "a malformed excluded-event list saved before it was validated does not block later edits"
+ (mt/with-temp [:model/Timeline timeline {}
+ :model/Card card {:display :line
+ :visualization_settings {:timeline.selected_timeline_ids [(:id timeline)]
+ :timeline.excluded_timeline_event_ids 5}}]
+ (mt/with-test-user :rasta
+ (t2/update! :model/Card (:id card)
+ {:visualization_settings {:timeline.selected_timeline_ids [(:id timeline)]
+ :timeline.excluded_timeline_event_ids []}})
+ (is (= [] (get-in (t2/select-one :model/Card (:id card))
+ [:visualization_settings :timeline.excluded_timeline_event_ids])))))))
+
+(deftest card-timeline-selection-deleted-timeline-test
+ (testing "a selection pointing at a deleted timeline still saves, so the card is not stuck"
+ (mt/with-temp [:model/Timeline timeline {}
+ :model/Card card {:visualization_settings {:timeline.selected_timeline_ids [(:id timeline)]}}]
+ (t2/delete! :model/Timeline (:id timeline))
+ (mt/with-test-user :rasta
+ (t2/update! :model/Card (:id card) {:display :line})
+ (is (= :line (t2/select-one-fn :display :model/Card (:id card))))))))
+
+(deftest card-timeline-selection-without-user-context-test
+ (mt/with-temp [:model/Timeline timeline {}]
+ (t2/delete! :model/Timeline (:id timeline))
+ (mt/with-current-user nil
+ (mt/with-temp [:model/Card card {:visualization_settings {:timeline.selected_timeline_ids [(:id timeline)]}}]
+ (t2/update! :model/Card (:id card) {:visualization_settings {:timeline.selected_timeline_ids []}})
+ (is (= [] (get-in (t2/select-one :model/Card (:id card))
+ [:visualization_settings :timeline.selected_timeline_ids])))))))
diff --git a/test/metabase/queries_rest/api/card_test.clj b/test/metabase/queries_rest/api/card_test.clj
index e3edcf7d1dd..6e2d8e00295 100644
--- a/test/metabase/queries_rest/api/card_test.clj
+++ b/test/metabase/queries_rest/api/card_test.clj
@@ -3036,6 +3036,179 @@
(mt/user-http-request :rasta :put 403 (str "card/" (u/the-id card))
{:name "Number of Blueberries Consumed Per Month"})))))))
+(deftest update-card-timeline-selection-permissions-test
+ (testing "PUT /api/card/:id requires read perms for the timelines selected in visualization settings"
+ (mt/with-temp [:model/Collection collection {}
+ :model/Timeline timeline {:collection_id (:id collection)}
+ :model/Card card {}]
+ (perms/revoke-collection-permissions! (perms-group/all-users) collection)
+ (is (= "You don't have permissions to do that."
+ (mt/user-http-request :rasta :put 403 (str "card/" (:id card))
+ {:visualization_settings {:timeline.selected_timeline_ids [(:id timeline)]}})))
+ (is (not (contains? (t2/select-one-fn :visualization_settings :model/Card (:id card))
+ :timeline.selected_timeline_ids))))))
+
+(deftest card-timeline-moved-to-private-collection-test
+ (testing "PUT /api/card/:id after one of the card's timelines moved into a collection the editor cannot read"
+ (mt/with-temp [:model/Collection restricted {}
+ :model/Timeline moved {}
+ :model/Timeline readable {}
+ :model/TimelineEvent readable-event {:timeline_id (:id readable)}
+ :model/Card card {:display :line
+ :dataset_query (mt/mbql-query venues)
+ :visualization_settings {:timeline.selected_timeline_ids [(:id readable) (:id moved)]
+ :timeline.excluded_timeline_event_ids []}}]
+ (perms/revoke-collection-permissions! (perms-group/all-users) restricted)
+ (t2/update! :model/Timeline (:id moved) {:collection_id (:id restricted)})
+ (testing "an event of the timeline the editor can still read can be hidden"
+ (let [settings {:timeline.selected_timeline_ids [(:id readable) (:id moved)]
+ :timeline.excluded_timeline_event_ids [(:id readable-event)]}]
+ (is (= [(:id readable-event)]
+ (get-in (mt/user-http-request :rasta :put 200 (str "card/" (:id card))
+ {:visualization_settings settings})
+ [:visualization_settings :timeline.excluded_timeline_event_ids]))))))))
+
+(deftest copy-card-keeps-inaccessible-timeline-selection-test
+ (testing "POST /api/card/:id/copy keeps a timeline selection the user cannot read"
+ (mt/with-temp [:model/Collection collection {}
+ :model/Timeline timeline {:collection_id (:id collection)}
+ :model/Card card {:dataset_query (mt/mbql-query venues)
+ :visualization_settings {:timeline.selected_timeline_ids [(:id timeline)]}}]
+ (perms/revoke-collection-permissions! (perms-group/all-users) collection)
+ (mt/with-model-cleanup [:model/Card]
+ (is (= [(:id timeline)]
+ (get-in (mt/user-http-request :rasta :post 200 (format "card/%d/copy" (:id card)))
+ [:visualization_settings :timeline.selected_timeline_ids])))))))
+
+(deftest create-card-with-source-card-id-preserves-timeline-selection-test
+ (testing "POST /api/card with source_card_id treats the new card as a copy for timeline permission purposes"
+ (mt/with-temp [:model/Collection collection {}
+ :model/Timeline timeline {:collection_id (:id collection)}
+ :model/Timeline timeline-2 {:collection_id (:id collection)}
+ :model/TimelineEvent hidden-event {:timeline_id (:id timeline)}
+ :model/TimelineEvent other-event {:timeline_id (:id timeline)}
+ :model/Card source-card {:dataset_query (mt/mbql-query venues)
+ :display :line
+ :visualization_settings {:timeline.selected_timeline_ids [(:id timeline)]
+ :timeline.excluded_timeline_event_ids [(:id hidden-event)]}}]
+ (perms/revoke-collection-permissions! (perms-group/all-users) collection)
+ (mt/with-model-cleanup [:model/Card]
+ (testing "an identical selection is preserved without a fresh read check"
+ (let [card (mt/user-http-request :rasta :post 200 "card"
+ (assoc (card-with-name-and-query)
+ :source_card_id (:id source-card)
+ :visualization_settings (:visualization_settings source-card)))]
+ (is (= [(:id timeline)]
+ (get-in card [:visualization_settings :timeline.selected_timeline_ids])))))
+ (testing "a selection that differs from the source card is still permission-checked"
+ (is (= "You don't have permissions to do that."
+ (mt/user-http-request :rasta :post 403 "card"
+ (assoc (card-with-name-and-query)
+ :source_card_id (:id source-card)
+ :visualization_settings {:timeline.selected_timeline_ids
+ [(:id timeline) (:id timeline-2)]})))))
+ (testing "un-hiding an event of the inaccessible timeline is still permission-checked"
+ (is (= "You don't have permissions to do that."
+ (mt/user-http-request :rasta :post 403 "card"
+ (assoc (card-with-name-and-query)
+ :display "line"
+ :source_card_id (:id source-card)
+ :visualization_settings
+ (assoc (:visualization_settings source-card)
+ :timeline.excluded_timeline_event_ids []))))))
+ (testing "hiding one more event keeps the inherited selection"
+ (is (= [(:id hidden-event) (:id other-event)]
+ (get-in (mt/user-http-request :rasta :post 200 "card"
+ (assoc (card-with-name-and-query)
+ :display "line"
+ :source_card_id (:id source-card)
+ :visualization_settings
+ (assoc (:visualization_settings source-card)
+ :timeline.excluded_timeline_event_ids
+ [(:id hidden-event) (:id other-event)])))
+ [:visualization_settings :timeline.excluded_timeline_event_ids]))))
+ (testing "source_card_id must itself be readable"
+ (mt/with-temp [:model/Collection unreadable-collection {}
+ :model/Card unreadable-card {:collection_id (:id unreadable-collection)}]
+ (perms/revoke-collection-permissions! (perms-group/all-users) unreadable-collection)
+ (is (= "You don't have permissions to do that."
+ (mt/user-http-request :rasta :post 403 "card"
+ (assoc (card-with-name-and-query)
+ :source_card_id (:id unreadable-card)))))))))))
+
+(deftest card-with-restricted-timeline-on-public-dashboard-test
+ (mt/with-temporary-setting-values [enable-public-sharing true]
+ (mt/with-temp [:model/Collection restricted {}
+ :model/Timeline timeline {:collection_id (:id restricted)}
+ :model/Card source-card {:dataset_query (mt/mbql-query venues)
+ :display :line
+ :visualization_settings {:timeline.selected_timeline_ids [(:id timeline)]}}
+ :model/Dashboard dashboard {:public_uuid (str (random-uuid))}]
+ (perms/revoke-collection-permissions! (perms-group/all-users) restricted)
+ (mt/with-model-cleanup [:model/Card]
+ (testing "POST /api/card cannot copy the card into a public dashboard"
+ (is (= "You don't have permissions to do that."
+ (mt/user-http-request :rasta :post 403 "card"
+ (assoc (card-with-name-and-query)
+ :display "line"
+ :source_card_id (:id source-card)
+ :dashboard_id (:id dashboard)
+ :visualization_settings (:visualization_settings source-card))))))
+ (testing "PUT /api/card/:id cannot move the card into a public dashboard"
+ (is (= "You don't have permissions to do that."
+ (mt/user-http-request :rasta :put 403 (str "card/" (:id source-card))
+ {:dashboard_id (:id dashboard)})))
+ (is (nil? (t2/select-one-fn :dashboard_id :model/Card (:id source-card)))))
+ (testing "a user who can read the timeline can move the card into the public dashboard"
+ (is (= (:id dashboard)
+ (:dashboard_id (mt/user-http-request :crowberto :put 200 (str "card/" (:id source-card))
+ {:dashboard_id (:id dashboard)})))))))))
+
+(deftest archived-card-with-restricted-timeline-on-public-dashboard-test
+ (testing "PUT /api/card/:id moving an archived card onto a public dashboard unarchives and autoplaces it, so it still needs timeline read access"
+ (mt/with-temporary-setting-values [enable-public-sharing true]
+ (mt/with-temp [:model/Collection restricted {}
+ :model/Timeline timeline {:collection_id (:id restricted)}
+ :model/Card {card-id :id} {:dataset_query (mt/mbql-query venues)
+ :display :line
+ :archived true
+ :visualization_settings {:timeline.selected_timeline_ids [(:id timeline)]}}
+ :model/Dashboard {dash-id :id} {:public_uuid (str (random-uuid))}]
+ (perms/revoke-collection-permissions! (perms-group/all-users) restricted)
+ (is (= "You don't have permissions to do that."
+ (mt/user-http-request :rasta :put 403 (str "card/" card-id) {:dashboard_id dash-id})))
+ (is (=? {:archived true, :dashboard_id nil}
+ (t2/select-one :model/Card card-id)))
+ (is (empty? (t2/select :model/DashboardCard :dashboard_id dash-id)))
+ (testing "a user who can read the timeline can still move it"
+ (is (=? {:archived false, :dashboard_id dash-id}
+ (mt/user-http-request :crowberto :put 200 (str "card/" card-id) {:dashboard_id dash-id})))
+ (is (= [card-id] (map :card_id (t2/select :model/DashboardCard :dashboard_id dash-id)))))))))
+
+(deftest copy-card-onto-public-dashboard-timeline-permissions-test
+ (testing "POST /api/card/:id/copy autoplaces the copy on the source's dashboard, so it needs timeline read access"
+ (mt/with-temporary-setting-values [enable-public-sharing true]
+ (mt/with-temp [:model/Collection restricted {}
+ :model/Timeline timeline {:collection_id (:id restricted)}
+ :model/Dashboard {dash-id :id} {:public_uuid (str (random-uuid))}
+ :model/Card {card-id :id} {:dataset_query (mt/mbql-query venues)
+ :display :line
+ :dashboard_id dash-id
+ :visualization_settings {:timeline.selected_timeline_ids [(:id timeline)]}}
+ ;; the source is shown by a visualizer dashcard, which never emits its card's events
+ :model/DashboardCard _ {:dashboard_id dash-id
+ :card_id card-id
+ :visualization_settings {:visualization {}}}]
+ (perms/revoke-collection-permissions! (perms-group/all-users) restricted)
+ (mt/with-model-cleanup [:model/Card]
+ (is (= "You don't have permissions to do that."
+ (mt/user-http-request :rasta :post 403 (format "card/%d/copy" card-id))))
+ (is (= [card-id] (map :card_id (t2/select :model/DashboardCard :dashboard_id dash-id))))
+ (testing "a user who can read the timeline can copy it"
+ (let [copy-id (:id (mt/user-http-request :crowberto :post 200 (format "card/%d/copy" card-id)))]
+ (is (= #{card-id copy-id}
+ (set (map :card_id (t2/select :model/DashboardCard :dashboard_id dash-id))))))))))))
+
(deftest change-collection-permissions-test
(testing "PUT /api/card/:id"
(testing "\nChange the `collection_id` of a Card"
diff --git a/test/metabase/revisions/api_test.clj b/test/metabase/revisions/api_test.clj
index 223fad2446e..fa079d9bd63 100644
--- a/test/metabase/revisions/api_test.clj
+++ b/test/metabase/revisions/api_test.clj
@@ -8,6 +8,7 @@
[metabase.lib.core :as lib]
[metabase.lib.metadata :as lib.metadata]
[metabase.permissions.models.data-permissions :as data-perms]
+ [metabase.permissions.models.permissions :as perms]
[metabase.permissions.models.permissions-group :as perms-group]
[metabase.revisions.models.revision :as revision]
[metabase.test :as mt]
@@ -1024,6 +1025,30 @@
(mt/user-http-request :rasta :post "revision/revert"
{:entity :card :id (:id card) :revision_id prev-rev-id}))))))))
+(deftest revert-card-with-restricted-timeline-test
+ (testing "POST /api/revision/revert restoring a card's selected timeline needs read perms for that timeline"
+ (mt/with-temp [:model/Collection restricted {}
+ :model/Timeline timeline {:collection_id (:id restricted)}
+ :model/Card {card-id :id} {:display :line
+ :visualization_settings
+ {:timeline.selected_timeline_ids [(:id timeline)]}}]
+ (perms/revoke-collection-permissions! (perms-group/all-users) restricted)
+ (create-card-revision! card-id true :crowberto)
+ (mt/user-http-request :crowberto :put 200 (str "card/" card-id) {:visualization_settings {}})
+ (let [selected-timeline-ids #(t2/select-one-fn (comp :timeline.selected_timeline_ids :visualization_settings)
+ :model/Card :id card-id)
+ revision-id (t2/select-one-pk :model/Revision :model "Card" :model_id card-id
+ {:order-by [[:id :asc]]})
+ revert-req {:entity :card :id card-id :revision_id revision-id}]
+ (is (nil? (selected-timeline-ids)))
+ (testing "is rejected for a user who can edit the card but cannot read the timeline"
+ (is (= "You don't have permissions to do that."
+ (mt/user-http-request :rasta :post 403 "revision/revert" revert-req)))
+ (is (nil? (selected-timeline-ids))))
+ (testing "is allowed for a user who can read the timeline"
+ (mt/user-http-request :crowberto :post 200 "revision/revert" revert-req)
+ (is (= [(:id timeline)] (selected-timeline-ids))))))))
+
(deftest revert-model-restores-metadata-and-viz-settings-test
(testing "Reverting a model restores result_metadata and visualization_settings together (#45926)"
(mt/with-temp [:model/Card {card-id :id} (assoc (mt/card-with-metadata
@@ -1086,3 +1111,59 @@
{:entity :card :id card-id :revision_id first-rev-id})
(is (=? [{:target [:dimension [:template-tag "RATING"]]}]
(t2/select-one-fn :parameter_mappings :model/DashboardCard :id dc-id))))))))
+
+(deftest revert-dashboard-to-a-dashcard-that-shows-events-test
+ (testing "POST /api/revision/revert rejects restoring a plain dashcard over one that hid its card's events"
+ (mt/with-temporary-setting-values [enable-public-sharing true]
+ (mt/with-temp [:model/Collection restricted {}
+ :model/Timeline timeline {:collection_id (:id restricted)}
+ :model/Card {card-id :id} {:display :line
+ :visualization_settings {:timeline.selected_timeline_ids [(:id timeline)]}}
+ :model/Dashboard {public-id :id} {:public_uuid (str (random-uuid))}
+ :model/DashboardCard {dashcard-id :id} {:dashboard_id public-id :card_id card-id}]
+ (perms/revoke-collection-permissions! (perms-group/all-users) restricted)
+ (create-dashboard-revision! public-id true :crowberto)
+ ;; the card stays on the dashboard, but as a visualizer dashcard its events are no longer shown
+ (t2/update! :model/DashboardCard dashcard-id
+ {:visualization_settings {:visualization {:display "line" :columnValuesMapping {} :settings {}}}})
+ (create-dashboard-revision! public-id false :crowberto)
+ (let [[_ {revision-id :id}] (revision/revisions :model/Dashboard public-id)]
+ (is (= "You don't have permissions to do that."
+ (mt/user-http-request :rasta :post 403 "revision/revert"
+ {:entity "dashboard" :id public-id :revision_id revision-id})))
+ (is (= [{:visualization {:display "line" :columnValuesMapping {} :settings {}}}]
+ (map :visualization_settings (t2/select :model/DashboardCard :dashboard_id public-id))))
+ (testing "a user who can read the timeline can restore it"
+ (mt/user-http-request :crowberto :post 200 "revision/revert"
+ {:entity "dashboard" :id public-id :revision_id revision-id})
+ (is (= [{}] (map :visualization_settings (t2/select :model/DashboardCard :dashboard_id public-id))))))))))
+
+(deftest revert-dashboard-with-restricted-timeline-card-test
+ (testing "POST /api/revision/revert re-adding a card whose selected timeline the user cannot read"
+ (mt/with-temporary-setting-values [enable-public-sharing true]
+ (mt/with-temp [:model/Collection restricted {}
+ :model/Timeline timeline {:collection_id (:id restricted)}
+ :model/Card {card-id :id} {:display :line
+ :visualization_settings {:timeline.selected_timeline_ids [(:id timeline)]}}
+ :model/Dashboard {public-id :id} {:public_uuid (str (random-uuid))}
+ :model/Dashboard {private-id :id} {}
+ :model/DashboardCard {public-dashcard-id :id} {:dashboard_id public-id :card_id card-id}
+ :model/DashboardCard {private-dashcard-id :id} {:dashboard_id private-id :card_id card-id}]
+ (perms/revoke-collection-permissions! (perms-group/all-users) restricted)
+ (doseq [[dashboard-id dashcard-id] [[public-id public-dashcard-id] [private-id private-dashcard-id]]]
+ (create-dashboard-revision! dashboard-id true :crowberto)
+ (t2/delete! :model/DashboardCard :id dashcard-id)
+ (create-dashboard-revision! dashboard-id false :crowberto))
+ (let [revert-req (fn [dashboard-id]
+ (let [[_ {revision-id :id}] (revision/revisions :model/Dashboard dashboard-id)]
+ {:entity "dashboard" :id dashboard-id :revision_id revision-id}))]
+ (testing "is rejected on a public dashboard, leaving the card off it"
+ (is (= "You don't have permissions to do that."
+ (mt/user-http-request :rasta :post 403 "revision/revert" (revert-req public-id))))
+ (is (empty? (t2/select :model/DashboardCard :dashboard_id public-id))))
+ (testing "is allowed on a dashboard that is not shared"
+ (mt/user-http-request :rasta :post 200 "revision/revert" (revert-req private-id))
+ (is (= [card-id] (map :card_id (t2/select :model/DashboardCard :dashboard_id private-id)))))
+ (testing "is allowed for a user who can read the timeline"
+ (mt/user-http-request :crowberto :post 200 "revision/revert" (revert-req public-id))
+ (is (= [card-id] (map :card_id (t2/select :model/DashboardCard :dashboard_id public-id))))))))))
diff --git a/test_resources/serialization_baseline/collections/main/minimal/populated_timeline.yaml b/test_resources/serialization_baseline/collections/main/minimal/populated_timeline.yaml
index e98bc3ef578..04a5f833677 100644
--- a/test_resources/serialization_baseline/collections/main/minimal/populated_timeline.yaml
+++ b/test_resources/serialization_baseline/collections/main/minimal/populated_timeline.yaml
@@ -5,6 +5,7 @@ entity_id: jqbQYdaqb_vXFlZnjvshP
events:
- created_at: '2024-08-28T14:31:56.942571Z'
creator_id: [email protected]
+ entity_id: UlA1lYjo2tSI6497Ovj_4
icon: star
name: First Event
time_matters: true