The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
Detail view (#62011)
Kamil Mielnik7dd4936c5705
diff --git a/e2e/support/helpers/e2e-detail-view-helpers.ts b/e2e/support/helpers/e2e-detail-view-helpers.tsnew file mode 100644index 00000000000..cdaac3e3f39--- /dev/null+++ b/e2e/support/helpers/e2e-detail-view-helpers.ts@@ -0,0 +1,83 @@+import type { CardId, TableId } from "metabase-types/api";++export const DetailView = {+ visitModel,+ visitTable,+ getHeader,+ getDetails,+ getDetailsRow,+ getDetailsRowColumnName,+ getDetailsRowValue,+ getRelationships,+ verifyDetails,+};++interface RowOptions {+ index: number;+ rowsCount: number;+}++function visitModel(modelIdOrSlug: CardId | string, rowId: string | number) {+ cy.intercept("GET", "/api/card/*/query_metadata*").as(+ "modelDetailTableMetadata",+ );+ cy.visit(`/model/${modelIdOrSlug}/detail/${rowId}`);+ cy.wait("@modelDetailTableMetadata");+}++function visitTable(tableId: TableId, rowId: string | number) {+ cy.intercept("GET", "/api/table/*/query_metadata*").as(+ "tableDetailTableMetadata",+ );+ cy.visit(`/table/${tableId}/detail/${rowId}`);+ cy.wait("@tableDetailTableMetadata");+}++function getHeader() {+ return cy.findByTestId("detail-view-header");+}++function getDetails() {+ return cy.findByTestId("object-details");+}++function getDetailsRow({ index, rowsCount }: RowOptions) {+ return getDetails()+ .findAllByTestId("object-details-row")+ .should("have.length", rowsCount)+ .eq(index);+}++function getDetailsRowColumnName({ index, rowsCount }: RowOptions) {+ return getDetailsRow({ index, rowsCount }).findByTestId("column-name");+}++function getDetailsRowValue({ index, rowsCount }: RowOptions) {+ return getDetailsRow({ index, rowsCount }).findByTestId("value");+}++function getRelationships() {+ return cy.findByTestId("relationships");+}++function verifyDetails(rows: [string, string][]) {+ getDetails().within(() => {+ cy.findAllByTestId("object-details-row").should("have.length", rows.length);++ for (let index = 0; index < rows.length; ++index) {+ const [column, value] = rows[index];++ cy.findAllByTestId("object-details-row")+ .should("have.length", rows.length)+ .eq(index)+ .findByTestId("column-name")+ .should("have.text", column);++ cy.findAllByTestId("object-details-row")+ .should("have.length", rows.length)+ .eq(index)+ .findByTestId("value")+ .should("have.text", value);+ }+ });+}diff --git a/e2e/support/helpers/index.ts b/e2e/support/helpers/index.tsindex e9a68da9a72..258c7912336 100644--- a/e2e/support/helpers/index.ts+++ b/e2e/support/helpers/index.ts@@ -13,6 +13,7 @@ export * from "./e2e-dashboard-helpers";export * from "./e2e-dashboard-visualizer-helpers";export * from "./e2e-database-metadata-helpers";export * from "./e2e-datamodel-helpers";+export * from "./e2e-detail-view-helpers";export * from "./e2e-dimension-list-helpers";export * from "./e2e-document-helpers";export * from "./e2e-downloads-helpers";diff --git a/e2e/test/scenarios/actions/actions-in-object-detail-view.cy.spec.js b/e2e/test/scenarios/actions/actions-in-object-detail-view.cy.spec.jsindex 1b967ca465e..c345a5cb65a 100644--- a/e2e/test/scenarios/actions/actions-in-object-detail-view.cy.spec.js+++ b/e2e/test/scenarios/actions/actions-in-object-detail-view.cy.spec.js@@ -1,8 +1,9 @@import dayjs from "dayjs";-const { H } = cy;import { USER_GROUPS, WRITABLE_DB_ID } from "e2e/support/cypress_data";+const { H } = cy;+const WRITABLE_TEST_TABLE = "scoreboard_actions";const FIRST_SCORE_ROW_ID = 11;const SECOND_SCORE_ROW_ID = 12;@@ -127,6 +128,16 @@ describe(assertActionsDropdownExists();});+ cy.log(+ "does not close object detail modal when pressing Esc while action modal is open",+ );+ openUpdateObjectModal();+ cy.wait("@prefetchValues");+ actionExecuteModal().should("be.visible");+ cy.realPress("Escape");+ actionExecuteModal().should("not.exist");+ objectDetailModal().should("be.visible");+cy.log(`As ${name} user: verify update form gets prefilled`);openUpdateObjectModal();actionExecuteModal().within(() => {diff --git a/e2e/test/scenarios/detail-view/detail-view.cy.spec.ts b/e2e/test/scenarios/detail-view/detail-view.cy.spec.tsnew file mode 100644index 00000000000..41914e9a830--- /dev/null+++ b/e2e/test/scenarios/detail-view/detail-view.cy.spec.ts@@ -0,0 +1,392 @@+import { SAMPLE_DB_ID } from "e2e/support/cypress_data";+import { SAMPLE_DATABASE } from "e2e/support/cypress_sample_database";+import {+ FIRST_COLLECTION_ID,+ SECOND_COLLECTION_ID,+} from "e2e/support/cypress_sample_instance_data";++const { H } = cy;+const { DetailView } = H;+const { ORDERS, ORDERS_ID, PEOPLE, PEOPLE_ID, PRODUCTS, PRODUCTS_ID } =+ SAMPLE_DATABASE;++const VERY_LONG_STRING = "VERY_LONG_STRING_".repeat(10);++describe("detail view", () => {+ beforeEach(() => {+ H.restore();+ cy.signInAsAdmin();+ });++ describe("table", () => {+ it("displays object details with breadcrumbs and relationships", () => {+ DetailView.visitTable(PRODUCTS_ID, 1);++ cy.findByRole("heading", {+ name: "Rustic Paper Wallet",+ level: 1,+ }).should("be.visible");+ cy.findByRole("heading", { name: "1", level: 2 }).should("be.visible");+ cy.icon("document").should("be.visible");++ H.appBar().within(() => {+ cy.findByRole("link", { name: /Sample Database/ })+ .should("be.visible")+ .and("have.attr", "href", `/browse/databases/${SAMPLE_DB_ID}`);+ cy.findByRole("link", { name: "Products" })+ .should("be.visible")+ .and(+ "have.attr",+ "href",+ `/question#?db=${SAMPLE_DB_ID}&table=${PRODUCTS_ID}`,+ );+ cy.findByText("Rustic Paper Wallet").should("be.visible");+ });++ DetailView.verifyDetails([+ ["Ean", "1018947080336"],+ ["Category", "Gizmo"],+ ["Vendor", "Swaniawski, Casper and Hilll"],+ ["Price", "29.46"],+ ["Rating", "4.6"],+ ["Created At", "July 19, 2023, 7:44 PM"],+ ]);++ DetailView.getRelationships().within(() => {+ cy.findByText("Rustic Paper Wallet").should("be.visible");+ cy.findByRole("link", { name: "93 Orders" }).should("be.visible");+ cy.findByRole("link", { name: "8 Reviews" })+ .should("be.visible")+ .click();+ });++ H.queryBuilderHeader().findByText("Reviews").should("be.visible");+ H.queryBuilderFiltersPanel().children().should("have.length", 1);+ H.queryBuilderFiltersPanel()+ .findByText("Product ID is 1")+ .should("be.visible");+ cy.findByTestId("question-row-count")+ .should("be.visible")+ .and("have.text", "Showing 8 rows");+ });++ it("shows loading state and 404 error state", () => {+ DetailView.visitTable(PRODUCTS_ID, 9999);++ cy.findByTestId("loading-indicator").should("be.visible");+ cy.findByTestId("loading-indicator").should("not.exist");++ cy.findByRole("heading", { name: "Row not found" }).should("be.visible");++ H.appBar().within(() => {+ cy.findByRole("link", { name: /Sample Database/ }).should("be.visible");+ cy.findByRole("link", { name: "Products" }).should("be.visible");+ cy.findByText("9999").should("be.visible");+ });+ });+ });++ describe("model", () => {+ it("displays object details with breadcrumbs", () => {+ createOrdersJoinProductsModel().then(({ body: card }) => {+ DetailView.visitModel(card.id, 1);+ cy.wrap(card.id).as("modelId");+ });++ cy.findByRole("heading", {+ name: "Awesome Concrete Shoes",+ level: 1,+ }).should("be.visible");+ cy.findByRole("heading", { name: "1", level: 2 }).should("be.visible");+ cy.icon("document").should("be.visible");++ H.appBar().within(() => {+ cy.findByRole("link", { name: /First collection/ })+ .should("be.visible")+ .and(+ "have.attr",+ "href",+ `/collection/${FIRST_COLLECTION_ID}-first-collection`,+ );+ cy.findByRole("link", { name: /Second collection/ })+ .should("be.visible")+ .and(+ "have.attr",+ "href",+ `/collection/${SECOND_COLLECTION_ID}-second-collection`,+ );+ cy.get("@modelId").then((modelId) => {+ cy.findByRole("link", { name: /My model/ })+ .should("be.visible")+ .and("have.attr", "href", `/model/${modelId}-my-model`);+ });+ cy.findByText("Awesome Concrete Shoes").should("be.visible");+ });++ DetailView.verifyDetails([+ ["User ID", "1"],+ ["Product ID", "14"],+ ["Subtotal", "37.65"],+ ["Tax", "2.07"],+ ["Total", "39.72"],+ ["Discount ($)", "empty"],+ ["Created At", "February 11, 2025, 9:40 PM"],+ ["Quantity", "2"],+ ["Order image", "https://example.com/order/1.jpg"],+ ["Product image", "https://example.com/product/14.jpg"],+ ["Products → Category", "Widget"],+ ["Products → Created At", "December 31, 2023, 2:41 PM"],+ ["Products → Ean", "8833419218504"],+ ["Products → Price", "25.1"],+ ["Products → Rating", "4"],+ ["Products → Vendor", "McClure-Lockman"],+ ]);++ DetailView.getRelationships().should("not.exist");+ });++ it("shows 404 error state", () => {+ createOrdersJoinProductsModel().then(({ body: card }) => {+ DetailView.visitModel(card.id, 9999);+ });++ cy.findByTestId("loading-indicator").should("be.visible");+ cy.findByTestId("loading-indicator").should("not.exist");++ cy.findByRole("heading", { name: "Row not found" }).should("be.visible");++ H.appBar().within(() => {+ cy.findByRole("link", { name: /First collection/ }).should(+ "be.visible",+ );+ cy.findByRole("link", { name: /Second collection/ }).should(+ "be.visible",+ );+ cy.findByRole("link", { name: /My model/ }).should("be.visible");+ cy.findByText("9999").should("be.visible");+ });+ });+ });++ describe("value rendering", () => {+ it("respects datamodel remapping and viz settings", () => {+ cy.log("user id - fk remapping");+ H.remapDisplayValueToFK({+ display_value: ORDERS.USER_ID,+ name: "User",+ fk: PEOPLE.NAME,+ });++ cy.log("product id - fk remapping + view as link setting");+ H.remapDisplayValueToFK({+ display_value: ORDERS.PRODUCT_ID,+ name: "Product",+ fk: PRODUCTS.TITLE,+ });+ cy.request("PUT", `/api/field/${ORDERS.PRODUCT_ID}`, {+ settings: {+ view_as: "link",+ link_text: "Product: {{PRODUCT_ID}}",+ link_url: "https://example.com/{{PRODUCT_ID}}",+ },+ });++ cy.log("subtotal - currency_in_header: true");+ cy.request("PUT", `/api/field/${ORDERS.SUBTOTAL}`, {+ semantic_type: "type/Currency",+ });++ cy.log("tax - currency_in_header: false");+ cy.request("PUT", `/api/field/${ORDERS.TAX}`, {+ semantic_type: "type/Currency",+ settings: {+ currency_in_header: false,+ },+ });++ cy.log("total - wrapping very long values");+ cy.request("PUT", `/api/field/${ORDERS.TOTAL}`, {+ settings: {+ prefix: VERY_LONG_STRING,+ },+ });++ cy.log("quantity - custom mapping");+ cy.request("PUT", `/api/field/${ORDERS.QUANTITY}`, {+ settings: {+ has_field_values: "list",+ },+ });+ cy.request("POST", `/api/field/${ORDERS.QUANTITY}/dimension`, {+ name: "Quantity",+ human_readable_field_id: null,+ type: "internal",+ });+ cy.request("GET", `/api/field/${ORDERS.QUANTITY}/values`).then(+ ({ body: response }) => {+ const values = response.values.map(([value]: [number]) => {+ if (value === 2) {+ return [value, "two"];+ }++ return [value, String(value)];+ });++ cy.request("POST", `/api/field/${ORDERS.QUANTITY}/values`, {+ values,+ });+ },+ );++ createOrdersJoinProductsModel().then(({ body: card }) => {+ cy.request("PUT", `/api/card/${card.id}`, {+ result_metadata: card.result_metadata.map((column) => {+ if (+ column.name === "Order image" ||+ column.name === "Product image"+ ) {+ return {+ ...column,+ semantic_type: "type/ImageURL",+ settings: {+ view_as: "image",+ },+ };+ }++ return column;+ }),+ });++ DetailView.visitModel(card.id, 1);+ });++ DetailView.getHeader().within(() => {+ cy.findByRole("img")+ .should("be.visible")+ .and("have.attr", "src", "https://example.com/order/1.jpg");++ cy.findByRole("heading", {+ name: "Awesome Concrete Shoes",+ level: 1,+ }).should("be.visible");++ cy.findByRole("heading", { name: "1", level: 2 }).should("be.visible");+ });++ DetailView.verifyDetails([+ ["User", "Hudson Borer"],+ ["Product", "Product: Awesome Concrete Shoes"],+ ["Subtotal ($)", "37.65"],+ ["Tax", "$2.07"],+ ["Total", `${VERY_LONG_STRING}39.72`],+ ["Discount ($)", "empty"],+ ["Created At", "February 11, 2025, 9:40 PM"],+ ["Quantity", "two"],+ ["Product image", "https://example.com/product/14.jpg"],+ ["Products → Category", "Widget"],+ ["Products → Created At", "December 31, 2023, 2:41 PM"],+ ["Products → Ean", "8833419218504"],+ ["Products → Price", "25.1"],+ ["Products → Rating", "4"],+ ["Products → Vendor", "McClure-Lockman"],+ ]);++ cy.log("user id remapped to user name");+ DetailView.getDetailsRowValue({ index: 0, rowsCount: 15 }).within(() => {+ cy.findByRole("link", { name: "Hudson Borer" })+ .should("be.visible")+ .and("have.attr", "href", `/table/${PEOPLE_ID}/detail/1`);+ });++ cy.log(+ "product id remapped to product title, and custom view_as setting",+ );+ DetailView.getDetailsRowValue({ index: 1, rowsCount: 15 }).within(() => {+ cy.findByRole("link", { name: "Product: Awesome Concrete Shoes" })+ .should("be.visible")+ .and("have.attr", "href", "https://example.com/14")+ .and("have.attr", "target", "_blank")+ .and("have.attr", "rel", "noopener noreferrer");+ });++ cy.log("very long value without whitespace wraps");+ cy.get("main").should(($main) => {+ expect(H.isScrollableHorizontally($main[0])).to.be.false;+ });++ cy.log("image should be rendered in a frame with a link");+ DetailView.getDetailsRowValue({ index: 8, rowsCount: 15 }).within(() => {+ cy.findByRole("img")+ .should("be.visible")+ .and("have.attr", "src", "https://example.com/product/14.jpg");++ cy.findByRole("link")+ .should("be.visible")+ .and("have.text", "https://example.com/product/14.jpg")+ .and("have.attr", "href", "https://example.com/product/14.jpg")+ .and("have.attr", "target", "_blank")+ .and("have.attr", "rel", "noopener noreferrer");+ });+ });+ });++ it("displays emails as links", () => {+ DetailView.visitTable(PEOPLE_ID, 1);++ DetailView.getDetailsRowValue({ index: 1, rowsCount: 11 }).within(() => {+ cy.findByRole("link", { name: "[email protected]" }).should(+ "have.attr",+ "href",+ "mailto:[email protected]",+ );+ });+ });+});++function createOrdersJoinProductsModel() {+ return H.createQuestion({+ type: "model",+ name: "My model",+ query: {+ "source-table": ORDERS_ID,+ joins: [+ {+ fields: [+ ["field", PRODUCTS.CATEGORY, { "join-alias": "Products" }],+ ["field", PRODUCTS.CREATED_AT, { "join-alias": "Products" }],+ ["field", PRODUCTS.EAN, { "join-alias": "Products" }],+ ["field", PRODUCTS.PRICE, { "join-alias": "Products" }],+ ["field", PRODUCTS.RATING, { "join-alias": "Products" }],+ ["field", PRODUCTS.TITLE, { "join-alias": "Products" }],+ ["field", PRODUCTS.VENDOR, { "join-alias": "Products" }],+ ],+ strategy: "left-join",+ alias: "Products",+ condition: [+ "=",+ ["field", ORDERS.PRODUCT_ID, {}],+ ["field", PRODUCTS.ID, {}],+ ],+ "source-table": PRODUCTS_ID,+ },+ ],+ expressions: {+ "Order image": [+ "concat",+ "https://example.com/order/",+ ["field", ORDERS.ID],+ ".jpg",+ ],+ "Product image": [+ "concat",+ "https://example.com/product/",+ ["field", ORDERS.PRODUCT_ID],+ ".jpg",+ ],+ },+ limit: 5,+ },+ collection_id: SECOND_COLLECTION_ID,+ });+}diff --git a/e2e/test/scenarios/models/model-indexes.cy.spec.js b/e2e/test/scenarios/models/model-indexes.cy.spec.jsindex 03a2ddcd474..075836acc71 100644--- a/e2e/test/scenarios/models/model-indexes.cy.spec.js+++ b/e2e/test/scenarios/models/model-indexes.cy.spec.js@@ -136,9 +136,11 @@ describe("scenarios > model indexes", () => {cy.wait("@dataset");cy.findByTestId("object-detail").within(() => {- cy.findByRole("heading", { name: /Product/ });- cy.findByText("Small Marble Shoes");- cy.findByText("Doohickey");+ cy.findByRole("heading", { name: "Small Marble Shoes" }).should(+ "be.visible",+ );+ cy.findAllByText("Small Marble Shoes").should("have.length", 1);+ cy.findByText("Doohickey").should("be.visible");});});@@ -173,7 +175,8 @@ describe("scenarios > model indexes", () => {cy.findByTestId("object-detail").within(() => {cy.findByText(/We're a little lost/i).should("not.exist");- cy.findAllByText("Anais Zieme").should("have.length", 2);+ cy.findByRole("heading", { name: "Anais Zieme" }).should("be.visible");+ cy.findAllByText("Anais Zieme").should("have.length", 1);});});@@ -190,9 +193,11 @@ describe("scenarios > model indexes", () => {cy.wait("@dataset");cy.findByTestId("object-detail").within(() => {- cy.findByRole("heading", { name: /Product/ });- cy.findByText("Small Marble Shoes");- cy.findByText("Doohickey");+ cy.findByRole("heading", { name: "Small Marble Shoes" }).should(+ "be.visible",+ );+ cy.findAllByText("Small Marble Shoes").should("have.length", 1);+ cy.findByText("Doohickey").should("be.visible");});expectCardQueries(1);diff --git a/e2e/test/scenarios/models/reproductions.cy.spec.ts b/e2e/test/scenarios/models/reproductions.cy.spec.tsindex fe53973e85c..863d1221f69 100644--- a/e2e/test/scenarios/models/reproductions.cy.spec.ts+++ b/e2e/test/scenarios/models/reproductions.cy.spec.ts@@ -861,9 +861,9 @@ describe("issue 33844", () => {H.tableInteractive().findByText("ID").should("not.exist");H.openObjectDetail(0);H.modal().within(() => {- cy.findByText("Order").should("be.visible");- cy.findByText("ID").should("be.visible");- cy.findByTestId("object-detail-close-button").click();+ cy.findByText("Quantity").should("be.visible");+ cy.findByRole("heading", { name: "1" }).should("be.visible");+ cy.findByLabelText("Close").click();});cy.log("make the column visible in table views");diff --git a/e2e/test/scenarios/question/nested.cy.spec.js b/e2e/test/scenarios/question/nested.cy.spec.jsindex 5f5e2eefaab..c18e4127dd7 100644--- a/e2e/test/scenarios/question/nested.cy.spec.js+++ b/e2e/test/scenarios/question/nested.cy.spec.js@@ -469,7 +469,7 @@ describe("scenarios > question > nested", () => {"contain","Swaniawski, Casper and Hilll",);- cy.findByTestId("object-detail-close-button").click();+ cy.findByLabelText("Close").click();cy.log("Should be able to save a nested question (metabase#18364)");saveQuestion();diff --git a/e2e/test/scenarios/question/nulls.cy.spec.js b/e2e/test/scenarios/question/nulls.cy.spec.jsindex 7642808f8dd..603cdc19701 100644--- a/e2e/test/scenarios/question/nulls.cy.spec.js+++ b/e2e/test/scenarios/question/nulls.cy.spec.js@@ -30,8 +30,8 @@ describe("scenarios > question > null", () => {cy.log("'No Results since at least v0.34.3");H.openObjectDetail(0);cy.findByRole("dialog").within(() => {- cy.findByText(/Discount/i);- cy.findByText("Empty");+ cy.findByText(/Discount/i).should("be.visible");+ cy.findByText("empty").should("be.visible");});});diff --git a/e2e/test/scenarios/visualizations-tabular/object_detail.cy.spec.js b/e2e/test/scenarios/visualizations-tabular/object_detail.cy.spec.jsindex 616ee8bd75b..bfc563a0764 100644--- a/e2e/test/scenarios/visualizations-tabular/object_detail.cy.spec.js+++ b/e2e/test/scenarios/visualizations-tabular/object_detail.cy.spec.js@@ -66,7 +66,10 @@ describe("scenarios > question > object details", { tags: "@slow" }, () => {drillPK({ id: 1 });cy.findByTestId("object-detail").within(() => {- cy.get("h2").should("contain", "Order").should("contain", 1);+ cy.findByRole("heading", { name: "Awesome Concrete Shoes" }).should(+ "be.visible",+ );+ cy.findByRole("heading", { name: "1" }).should("be.visible");});});@@ -99,9 +102,12 @@ describe("scenarios > question > object details", { tags: "@slow" }, () => {cy.findAllByTestId("detail-shortcut").eq(1).should("be.hidden");H.openObjectDetail(0);cy.findByTestId("object-detail").within(() => {- cy.findByRole("heading").should("contain", "Order").and("contain", 1);+ cy.findByRole("heading", { name: "Awesome Concrete Shoes" }).should(+ "be.visible",+ );+ cy.findByRole("heading", { name: "1" }).should("be.visible");cy.findByText("37.65").should("be.visible");- cy.findByTestId("object-detail-close-button").click();+ cy.findByLabelText("Close").click();});cy.log("Check object details for the second row");@@ -109,7 +115,10 @@ describe("scenarios > question > object details", { tags: "@slow" }, () => {cy.findAllByTestId("detail-shortcut").eq(0).should("be.hidden");H.openObjectDetail(1);cy.findByTestId("object-detail").within(() => {- cy.findByRole("heading").should("contain", "Order").and("contain", 2);+ cy.findByRole("heading", { name: "Mediocre Wooden Bench" }).should(+ "be.visible",+ );+ cy.findByRole("heading", { name: "2" }).should("be.visible");cy.findByText("110.93").should("be.visible");});});@@ -144,10 +153,9 @@ describe("scenarios > question > object details", { tags: "@slow" }, () => {cy.findByRole("gridcell", { name: "3" }).should("be.visible").click();- // we might render the thing before it's actually clickable- cy.get("[data-testid=click-icon]", { timeout: 1000 }).should("be.visible");-- cy.findByRole("dialog").findByTestId("fk-relation-orders").click();+ H.modal().findByRole("link", { name: "77 Orders" }).click();+ cy.log("should close the modal when browsing relationships");+ cy.findByTestId("object-detail").should("not.exist");cy.findByTestId("qb-filters-panel").findByText("Product ID is 3")@@ -158,21 +166,36 @@ describe("scenarios > question > object details", { tags: "@slow" }, () => {H.createQuestion(TEST_QUESTION, { visitQuestion: true });drillPK({ id: FIRST_ORDER_ID });- assertOrderDetailView({ id: FIRST_ORDER_ID });+ assertOrderDetailView({+ id: FIRST_ORDER_ID,+ heading: String(FIRST_ORDER_ID),+ });getPreviousObjectDetailButton().should("have.attr", "disabled", "disabled");getNextObjectDetailButton().click();- assertOrderDetailView({ id: SECOND_ORDER_ID });+ assertOrderDetailView({+ id: SECOND_ORDER_ID,+ heading: String(SECOND_ORDER_ID),+ });getNextObjectDetailButton().click();- assertOrderDetailView({ id: THIRD_ORDER_ID });+ assertOrderDetailView({+ id: THIRD_ORDER_ID,+ heading: String(THIRD_ORDER_ID),+ });getNextObjectDetailButton().should("have.attr", "disabled", "disabled");getPreviousObjectDetailButton().click();- assertOrderDetailView({ id: SECOND_ORDER_ID });+ assertOrderDetailView({+ id: SECOND_ORDER_ID,+ heading: String(SECOND_ORDER_ID),+ });getPreviousObjectDetailButton().click();- assertOrderDetailView({ id: FIRST_ORDER_ID });+ assertOrderDetailView({+ id: FIRST_ORDER_ID,+ heading: String(FIRST_ORDER_ID),+ });});it("calculates a row after both vertical and horizontal scrolling correctly (metabase#51301)", () => {@@ -229,44 +252,39 @@ describe("scenarios > question > object details", { tags: "@slow" }, () => {cy.visit(`/question/${id}/${OUT_OF_RANGE_ID}`);cy.wait("@cardQuery");cy.findByTestId("object-detail").within(() => {- // should appear in header and body of the modal- cy.findAllByText(/Marcelina Kuhn/i).should("have.length", 2);+ cy.findByRole("heading", { name: "Marcelina Kuhn" }).should(+ "be.visible",+ );});});});it("should allow to browse linked entities by FKs (metabase#21757)", () => {- const PRODUCT_ID = 7;- const EXPECTED_LINKED_ORDERS_COUNT = 92;- const EXPECTED_LINKED_REVIEWS_COUNT = 8;H.openProductsTable();drillPK({ id: 5 });cy.findByTestId("object-detail").within(() => {- cy.findByTestId("fk-relation-orders").findByText(97);- cy.findByTestId("fk-relation-reviews").findByText(4);- cy.findByTestId("view-next-object-detail").click();+ cy.findByRole("link", { name: "4 Reviews" }).should("be.visible");+ cy.findByRole("link", { name: "97 Orders" }).should("be.visible");+ cy.findByLabelText("Next row").click();- cy.findByTestId("fk-relation-orders").findByText(88);- cy.findByTestId("fk-relation-reviews").findByText(5);- cy.findByTestId("view-next-object-detail").click();+ cy.findByRole("link", { name: "5 Reviews" }).should("be.visible");+ cy.findByRole("link", { name: "88 Orders" }).should("be.visible");+ cy.findByLabelText("Next row").click();- cy.findByTestId("fk-relation-reviews").findByText(- EXPECTED_LINKED_REVIEWS_COUNT,- );- cy.findByTestId("fk-relation-orders")- .findByText(EXPECTED_LINKED_ORDERS_COUNT)- .click();+ cy.findByRole("link", { name: "8 Reviews" }).should("be.visible");+ cy.findByRole("link", { name: "92 Orders" }).should("be.visible").click();});+ cy.log("should close the modal when browsing relationships");+ cy.findByTestId("object-detail").should("not.exist");cy.wait("@dataset");- cy.findByTestId("qb-filters-panel").findByText(- `Product ID is ${PRODUCT_ID}`,- );- // eslint-disable-next-line no-unscoped-text-selectors -- deprecated usage- cy.findByText(`Showing ${EXPECTED_LINKED_ORDERS_COUNT} rows`);+ cy.findByTestId("qb-filters-panel").findByText("Product ID is 7");+ cy.findByTestId("view-footer")+ .findByText("Showing 92 rows")+ .should("be.visible");});it("should fetch linked entities data only once per entity type when reopening the modal (metabase#32720)", () => {@@ -278,13 +296,13 @@ describe("scenarios > question > object details", { tags: "@slow" }, () => {drillPK({ id: 5 });cy.get("@fetchDataset").should("have.callCount", 3);- cy.findByTestId("object-detail-close-button").click();+ cy.findByLabelText("Close").click();drillPK({ id: 5 });- cy.get("@fetchDataset").should("have.callCount", 5);+ cy.get("@fetchDataset").should("have.callCount", 3);cy.wait(100);- cy.get("@fetchDataset").should("have.callCount", 5);+ cy.get("@fetchDataset").should("have.callCount", 3);});it("should not offer drill-through on the object detail records (metabase#20560)", () => {@@ -422,7 +440,7 @@ describe("scenarios > question > object details", { tags: "@slow" }, () => {.and("eq", "https://metabase.test?rating=5");});- cy.findByTestId("view-next-object-detail").click();+ cy.findByLabelText("Next row").click();cy.findByTestId("object-detail").within(() => {cy.findByText("Link to review 2")@@ -436,8 +454,340 @@ describe("scenarios > question > object details", { tags: "@slow" }, () => {.and("eq", "https://metabase.test?rating=4");});});++ it("should support keyboard navigation and opened row highlighting", () => {+ H.visitQuestionAdhoc({+ display: "table",+ dataset_query: {+ type: "query",+ database: SAMPLE_DB_ID,+ query: { "source-table": PEOPLE_ID },+ },+ });++ getObjectDetailShortcut(0).icon("sidebar_open").should("be.visible");++ getRow(0).should("have.css", "background-color", "rgba(0, 0, 0, 0)");+ H.openObjectDetail(0);+ getRow(0).should("not.have.css", "background-color", "rgba(0, 0, 0, 0)");+ cy.findByTestId("object-detail")+ .findByRole("heading", { name: "Hudson Borer" })+ .should("be.visible");++ cy.log("navigates down");+ getRow(1).should("have.css", "background-color", "rgba(0, 0, 0, 0)");+ cy.realPress("ArrowDown");+ getRow(1).should("not.have.css", "background-color", "rgba(0, 0, 0, 0)");+ cy.findByTestId("object-detail")+ .findByRole("heading", { name: "Domenica Williamson" })+ .should("be.visible");++ cy.log("navigates up");+ getRow(0).should("have.css", "background-color", "rgba(0, 0, 0, 0)");+ cy.realPress("ArrowUp");+ getRow(0).should("not.have.css", "background-color", "rgba(0, 0, 0, 0)");+ cy.findByTestId("object-detail")+ .findByRole("heading", { name: "Hudson Borer" })+ .should("be.visible");++ cy.log("does not navigate outside of bounds");+ cy.realPress("ArrowUp");+ getRow(0).should("not.have.css", "background-color", "rgba(0, 0, 0, 0)");+ cy.findByTestId("object-detail")+ .findByRole("heading", { name: "Hudson Borer" })+ .should("be.visible");+ });++ it("should support toggling the sidebar", () => {+ H.visitQuestionAdhoc({+ display: "table",+ dataset_query: {+ type: "query",+ database: SAMPLE_DB_ID,+ query: { "source-table": PEOPLE_ID },+ },+ });++ getObjectDetailShortcut(0).icon("sidebar_open").should("be.visible");+ H.openObjectDetail(0);++ // realHover does not work behind the modal overlay, so we're working around it with realMouseMove+ getRow(0).then(($row) => {+ const rect = $row[0].getBoundingClientRect();+ const detailShortcutWidth = 24;+ const detailShortcutOffset = 10;+ const x = detailShortcutOffset + detailShortcutWidth / 2;+ const y = rect.height / 2;++ getRow(0).realMouseMove(x, y, { scrollBehavior: false });+ getRow(0)+ .findByTestId("detail-shortcut")+ .icon("sidebar_closed")+ .should("be.visible");+ H.tooltip().should("be.visible").and("contain.text", "Hide details");++ getRow(0).realClick({ x, y, scrollBehavior: false });+ getRow(0)+ .findByTestId("detail-shortcut")+ .icon("sidebar_open")+ .should("be.visible");+ H.tooltip().should("be.visible").and("contain.text", "View details");+ });+ });++ it("should respect viz settings column order and visibility", () => {+ H.visitQuestionAdhoc({+ display: "table",+ dataset_query: {+ type: "query",+ database: SAMPLE_DB_ID,+ query: { "source-table": PEOPLE_ID },+ },+ });++ H.openVizSettingsSidebar();+ cy.findByTestId("sidebar-left").within(() => {+ cy.findByTestId("Address-hide-button").click();++ cy.findAllByRole("listitem")+ .eq("7")+ .as("stateItem")+ .should("have.text", "State");+ H.moveDnDKitElement(cy.get("@stateItem"), { vertical: -300 });+ });++ H.openObjectDetail(0);++ cy.findByTestId("object-detail").within(() => {+ cy.log("hidden columns are not shown");+ cy.findByText("Address").should("not.exist");++ cy.log("viz settings columns order is respected");+ cy.findAllByText(/State|Email/).then(($elements) => {+ const texts = $elements+ .map((_index, element) => element.textContent)+ .get();++ expect(texts.indexOf("State")).to.be.lessThan(texts.indexOf("Email"));+ });+ });+ });++ describe("detail page links - questions", () => {+ it("no primary keys", () => {+ H.visitQuestionAdhoc({+ display: "table",+ dataset_query: {+ type: "query",+ database: SAMPLE_DB_ID,+ query: {+ "source-table": PEOPLE_ID,+ fields: [+ ["field", PEOPLE.ADDRESS],+ ["field", PEOPLE.EMAIL],+ ["field", PEOPLE.NAME],+ ],+ limit: 5,+ },+ },+ });++ H.openObjectDetail(0);+ cy.findByTestId("object-detail").within(() => {+ cy.findByLabelText("Copy link to this record").should("not.exist");+ cy.findByLabelText("Open in full page").should("not.exist");+ });+ });++ it("1 primary key", () => {+ H.grantClipboardPermissions();+ H.visitQuestionAdhoc({+ display: "table",+ dataset_query: {+ type: "query",+ database: SAMPLE_DB_ID,+ query: {+ "source-table": PEOPLE_ID,+ fields: [+ ["field", PEOPLE.ID],+ ["field", PEOPLE.ADDRESS],+ ["field", PEOPLE.EMAIL],+ ["field", PEOPLE.NAME],+ ],+ limit: 5,+ },+ },+ });++ H.openObjectDetail(0);+ cy.findByTestId("object-detail").within(() => {+ const expectedUrl = `http://localhost:4000/table/${PEOPLE_ID}/detail/1`;++ cy.findByLabelText("Copy link to this record").click();+ cy.window()+ .then((window) => window.navigator.clipboard.readText())+ .should("equal", expectedUrl);++ cy.findByLabelText("Open in full page").click();+ cy.location("href").should("eq", expectedUrl);+ cy.findByRole("heading", { name: "Hudson Borer" }).should("be.visible");+ });+ });++ it("2 primary keys", () => {+ H.visitQuestionAdhoc({+ display: "table",+ dataset_query: {+ type: "query",+ database: SAMPLE_DB_ID,+ query: {+ "source-table": PEOPLE_ID,+ fields: [+ ["field", PEOPLE.ID],+ ["field", PEOPLE.ADDRESS],+ ["field", PEOPLE.EMAIL],+ ["field", PEOPLE.NAME],+ ], //["field", ORDERS.ID],+ joins: [+ {+ "source-table": ORDERS_ID,+ fields: [["field", ORDERS.ID]],+ strategy: "left-join",+ alias: "Orders",+ condition: [+ "=",+ ["field", PEOPLE.ID],+ ["field", ORDERS.USER_ID],+ ],+ },+ ],+ limit: 5,+ },+ },+ });++ H.openObjectDetail(0);+ cy.findByTestId("object-detail").within(() => {+ cy.findByLabelText("Copy link to this record").should("not.exist");+ cy.findByLabelText("Open in full page").should("not.exist");+ });+ });+ });++ describe("detail page links - models", () => {+ it("no primary keys", () => {+ H.createQuestion(+ {+ type: "model",+ query: {+ "source-table": PEOPLE_ID,+ fields: [+ ["field", PEOPLE.ADDRESS],+ ["field", PEOPLE.EMAIL],+ ["field", PEOPLE.NAME],+ ],+ limit: 5,+ },+ },+ { visitQuestion: true },+ );++ H.openObjectDetail(0);+ cy.findByTestId("object-detail").within(() => {+ cy.findByLabelText("Copy link to this record").should("not.exist");+ cy.findByLabelText("Open in full page").should("not.exist");+ });+ });++ it("1 primary key", () => {+ H.grantClipboardPermissions();+ H.createQuestion({+ type: "model",+ name: "model",+ query: {+ "source-table": PEOPLE_ID,+ fields: [+ ["field", PEOPLE.ID],+ ["field", PEOPLE.ADDRESS],+ ["field", PEOPLE.EMAIL],+ ["field", PEOPLE.NAME],+ ],+ limit: 5,+ },+ }).then(({ body: card }) => {+ const slug = [card.id, card.name].join("-");++ H.visitModel(card.id);+ H.openObjectDetail(0);++ cy.findByTestId("object-detail").within(() => {+ const expectedUrl = `http://localhost:4000/model/${slug}/detail/1`;++ cy.findByLabelText("Copy link to this record").click();+ cy.window()+ .then((window) => window.navigator.clipboard.readText())+ .should("equal", expectedUrl);++ cy.findByLabelText("Open in full page").click();+ cy.location("href").should("eq", expectedUrl);+ cy.findByRole("heading", { name: "Hudson Borer" }).should(+ "be.visible",+ );+ });+ });+ });++ it("2 primary keys", () => {+ H.createQuestion(+ {+ type: "model",+ query: {+ "source-table": PEOPLE_ID,+ fields: [+ ["field", PEOPLE.ID],+ ["field", PEOPLE.ADDRESS],+ ["field", PEOPLE.EMAIL],+ ["field", PEOPLE.NAME],+ ],+ joins: [+ {+ "source-table": ORDERS_ID,+ fields: [["field", ORDERS.ID]],+ strategy: "left-join",+ alias: "Orders",+ condition: [+ "=",+ ["field", PEOPLE.ID],+ ["field", ORDERS.USER_ID],+ ],+ },+ ],+ limit: 5,+ },+ },+ { visitQuestion: true },+ );++ H.openObjectDetail(0);+ cy.findByTestId("object-detail").within(() => {+ cy.findByLabelText("Copy link to this record").should("not.exist");+ cy.findByLabelText("Open in full page").should("not.exist");+ });+ });+ });});+function getObjectDetailShortcut(rowIndex) {+ return getRow(rowIndex)+ .realHover({ scrollBehavior: false })+ .findByTestId("detail-shortcut")+ .should("be.visible");+}++function getRow(rowIndex) {+ return cy.get(`[data-index=${rowIndex}]`);+}+function drillPK({ id }) {cy.get(".test-Table-ID").contains(id).first().click();}@@ -447,8 +797,14 @@ function drillFK({ id }) {H.popover().findByText("View details").click();}-function assertDetailView({ id, entityName, byFK = false }) {- cy.get("h2").should("contain", entityName).should("contain", id);+function assertDetailView({ id, heading, subtitle, byFK = false }) {+ if (heading) {+ cy.findByRole("heading", { name: heading }).should("be.visible");+ }++ if (subtitle) {+ cy.findByRole("heading", { name: subtitle }).should("be.visible");+ }const pattern = byFK? new RegExp("/question#*")@@ -457,20 +813,20 @@ function assertDetailView({ id, entityName, byFK = false }) {cy.url().should("match", pattern);}-function assertOrderDetailView({ id }) {- assertDetailView({ id, entityName: "Order" });+function assertOrderDetailView({ id, heading, subtitle }) {+ assertDetailView({ id, heading, subtitle });}-function assertUserDetailView({ id, name }) {- assertDetailView({ id, entityName: name, byFK: true });+function assertUserDetailView({ id, heading, subtitle }) {+ assertDetailView({ id, heading, subtitle, byFK: true });}function getPreviousObjectDetailButton() {- return cy.findByTestId("view-previous-object-detail");+ return cy.findByLabelText("Previous row");}function getNextObjectDetailButton() {- return cy.findByTestId("view-next-object-detail");+ return cy.findByLabelText("Next row");}function changeSorting(columnName, direction) {@@ -504,9 +860,9 @@ function changeSorting(columnName, direction) {H.openObjectDetail(0);cy.findByRole("dialog").within(() => {- cy.findAllByText("Duck").should("have.length", 2);- cy.icon("chevrondown").click();- cy.findAllByText("Horse").should("have.length", 2);+ cy.findByRole("heading", { name: "Duck" }).should("be.visible");+ cy.findByLabelText("Next row").click();+ cy.findByRole("heading", { name: "Horse" }).should("be.visible");});});@@ -521,13 +877,13 @@ function changeSorting(columnName, direction) {H.openObjectDetail(5);cy.findByRole("dialog").within(() => {- cy.findAllByText("Rabbit").should("have.length", 2);+ cy.findByRole("heading", { name: "Rabbit" }).should("be.visible");});cy.get("body").type("{downarrow}");cy.findByRole("dialog").within(() => {- cy.findAllByText("Rabbit").should("have.length", 2);+ cy.findByRole("heading", { name: "Rabbit" }).should("be.visible");cy.findByText("Empty").should("not.exist");});});@@ -555,9 +911,9 @@ function changeSorting(columnName, direction) {H.openObjectDetail(0);cy.findByRole("dialog").within(() => {- cy.findAllByText("Duck").should("have.length", 2);- cy.icon("chevrondown").click();- cy.findAllByText("Horse").should("have.length", 2);+ cy.findByRole("heading", { name: "Duck" }).should("be.visible");+ cy.findByLabelText("Next row").click();+ cy.findByRole("heading", { name: "Horse" }).should("be.visible");});});},diff --git a/e2e/test/scenarios/visualizations-tabular/table.cy.spec.js b/e2e/test/scenarios/visualizations-tabular/table.cy.spec.jsindex 2ab3bb93a8d..609042a3b06 100644--- a/e2e/test/scenarios/visualizations-tabular/table.cy.spec.js+++ b/e2e/test/scenarios/visualizations-tabular/table.cy.spec.js@@ -155,7 +155,7 @@ describe("scenarios > visualizations > table", () => {H.openObjectDetail(5);// Ensure click on row index opens the object detail- H.modal().findByText("Order");+ H.modal().findByText("6").should("be.visible");// Close object detail modalcy.realType("{esc}");diff --git a/frontend/src/metabase-lib/metadata.ts b/frontend/src/metabase-lib/metadata.tsindex c8dc0c481b3..e2eb891fab1 100644--- a/frontend/src/metabase-lib/metadata.ts+++ b/frontend/src/metabase-lib/metadata.ts@@ -1,6 +1,7 @@import * as ML from "cljs/metabase.lib.js";import * as ML_MetadataCalculation from "cljs/metabase.lib.metadata.calculation";import type {+ Field as ApiField,CardId,CardType,DatabaseId,@@ -194,7 +195,7 @@ export function returnedColumns(export function fromLegacyColumn(query: Query,stageIndex: number,- columnOrField: DatasetColumn | Field,+ columnOrField: DatasetColumn | Field | ApiField,): ColumnMetadata {return ML.legacy_column__GT_metadata(query, stageIndex, columnOrField);}diff --git a/frontend/src/metabase-lib/v1/types/utils/isa.js b/frontend/src/metabase-lib/v1/types/utils/isa.jsindex 6190f3c74f2..3396558bb1f 100644--- a/frontend/src/metabase-lib/v1/types/utils/isa.js+++ b/frontend/src/metabase-lib/v1/types/utils/isa.js@@ -120,6 +120,7 @@ export const isFK = (field) => field && isTypeFK(field.semantic_type);export const isPK = (field) => field && isTypePK(field.semantic_type);export const isEntityName = (field) =>field && isa(field.semantic_type, TYPE.Name);+export const isTitle = (field) => field && isa(field.semantic_type, TYPE.Title);export const isAddress = (field) =>field && isa(field.semantic_type, TYPE.Address);diff --git a/frontend/src/metabase-types/api/table.ts b/frontend/src/metabase-types/api/table.tsindex 6640364852c..e55722580d6 100644--- a/frontend/src/metabase-types/api/table.ts+++ b/frontend/src/metabase-types/api/table.ts@@ -26,6 +26,7 @@ export type Table = {name: string;display_name: string;description: string | null;+ entity_type?: string | null;db_id: DatabaseId;db?: Database;diff --git a/frontend/src/metabase-types/store/app.ts b/frontend/src/metabase-types/store/app.tsindex b57bcf13114..6586d23f76e 100644--- a/frontend/src/metabase-types/store/app.ts+++ b/frontend/src/metabase-types/store/app.ts@@ -1,4 +1,5 @@import type { ChecklistItemValue } from "metabase/home/components/Onboarding/types";+import type { Table } from "metabase-types/api";import type { CollectionId } from "metabase-types/api/collection";export interface AppErrorDescriptor {@@ -29,7 +30,14 @@ export type TempStorageKey = keyof TempStorage;export type TempStorageValue<Key extends TempStorageKey = TempStorageKey> =TempStorage[Key];+export interface DetailViewState {+ rowName: string;+ table: Table;+ collectionId: CollectionId | null;+}+export interface AppState {+ detailView: DetailViewState | null;errorPage: AppErrorDescriptor | null;isNavbarOpen: boolean;isDndAvailable: boolean;diff --git a/frontend/src/metabase-types/store/mocks/app.ts b/frontend/src/metabase-types/store/mocks/app.tsindex 9ecb033639b..bfb8be6e054 100644--- a/frontend/src/metabase-types/store/mocks/app.ts+++ b/frontend/src/metabase-types/store/mocks/app.ts@@ -1,6 +1,7 @@import type { AppState } from "metabase-types/store";export const createMockAppState = (opts?: Partial<AppState>): AppState => ({+ detailView: null,isNavbarOpen: true,errorPage: null,isDndAvailable: false,diff --git a/frontend/src/metabase/api/table.ts b/frontend/src/metabase/api/table.tsindex 9c163cef00e..059e98dde43 100644--- a/frontend/src/metabase/api/table.ts+++ b/frontend/src/metabase/api/table.ts@@ -1,5 +1,5 @@import type {- Field,+ ForeignKey,GetTableQueryMetadataRequest,GetTableRequest,Table,@@ -45,7 +45,7 @@ export const tableApi = Api.injectEndpoints({}),providesTags: (table) => (table ? provideTableTags(table) : []),}),- listTableForeignKeys: builder.query<Field[], TableId>({+ listTableForeignKeys: builder.query<ForeignKey[], TableId>({query: (id) => ({method: "GET",url: `/api/table/${id}/fks`,@@ -128,6 +128,7 @@ export const {useListTablesQuery,useGetTableQuery,useGetTableQueryMetadataQuery,+ useListTableForeignKeysQuery,useLazyListTableForeignKeysQuery,useUpdateTableMutation,useUpdateTableListMutation,diff --git a/frontend/src/metabase/data-grid/components/DataGrid/DataGrid.module.css b/frontend/src/metabase/data-grid/components/DataGrid/DataGrid.module.cssindex db6ffe26563..6718e375c7e 100644--- a/frontend/src/metabase/data-grid/components/DataGrid/DataGrid.module.css+++ b/frontend/src/metabase/data-grid/components/DataGrid/DataGrid.module.css@@ -40,6 +40,14 @@.row {display: flex;width: 100%;++ &.active {+ background-color: color-mix(+ in srgb,+ var(--mb-color-brand),+ transparent 90%+ );+ }}.headerCell {diff --git a/frontend/src/metabase/data-grid/components/DataGrid/DataGrid.stories.tsx b/frontend/src/metabase/data-grid/components/DataGrid/DataGrid.stories.tsxindex 4c3c45533b7..4ca0f5f4b7a 100644--- a/frontend/src/metabase/data-grid/components/DataGrid/DataGrid.stories.tsx+++ b/frontend/src/metabase/data-grid/components/DataGrid/DataGrid.stories.tsx@@ -246,6 +246,7 @@ export const CombinedFeatures: Story = () => {const rowId: RowIdColumnOptions = useMemo(() => ({variant: "indexExpand",+ expandedIndex: undefined,getBackgroundColor: (rowIndex: number) =>rowIndex % 2 === 0 ? "#f0f0f0" : "transparent",}),diff --git a/frontend/src/metabase/data-grid/components/DataGrid/DataGrid.tsx b/frontend/src/metabase/data-grid/components/DataGrid/DataGrid.tsxindex 7a11fc786d5..c1ad6c65250 100644--- a/frontend/src/metabase/data-grid/components/DataGrid/DataGrid.tsx+++ b/frontend/src/metabase/data-grid/components/DataGrid/DataGrid.tsx@@ -54,6 +54,7 @@ export interface DataGridProps<TData>showRowsCount?: boolean;isColumnReorderingDisabled?: boolean;theme?: DataGridTheme;+ zoomedRowIndex?: number;}export const DataGrid = function DataGrid<TData>({@@ -72,6 +73,7 @@ export const DataGrid = function DataGrid<TData>({getTotalHeight,getVisibleRows,isColumnReorderingDisabled,+ zoomedRowIndex,onBodyCellClick,onHeaderCellClick,onAddColumnClick,@@ -281,6 +283,7 @@ export const DataGrid = function DataGrid<TData>({const dataIndex =virtualRow != null ? virtualRow.index : row.index;+ const active = zoomedRowIndex === dataIndex;return (<div@@ -291,7 +294,9 @@ export const DataGrid = function DataGrid<TData>({data-index={dataIndex}data-allow-page-break-after="true"data-row-selected={row.getIsSelected()}- className={cx(S.row, classNames?.row)}+ className={cx(S.row, classNames?.row, {+ [S.active]: active,+ })}style={{...virtualRowStyles,...styles?.row,@@ -321,7 +326,9 @@ export const DataGrid = function DataGrid<TData>({position: "sticky",left: `${virtualColumn.start}px`,zIndex: PINNED_COLUMN_Z_INDEX,- backgroundColor: stickyElementsBackgroundColor,+ backgroundColor: active+ ? undefined+ : stickyElementsBackgroundColor,...styles?.bodyCell,}: {diff --git a/frontend/src/metabase/data-grid/components/DataGrid/DataGrid.unit.spec.tsx b/frontend/src/metabase/data-grid/components/DataGrid/DataGrid.unit.spec.tsxindex cd8fbade681..e6aec192188 100644--- a/frontend/src/metabase/data-grid/components/DataGrid/DataGrid.unit.spec.tsx+++ b/frontend/src/metabase/data-grid/components/DataGrid/DataGrid.unit.spec.tsx@@ -116,11 +116,12 @@ const TestDataGrid = ({[sortableColumns, wrapableColumns],);- const rowId: RowIdColumnOptions | undefined = useMemo(+ const rowId = useMemo<RowIdColumnOptions | undefined>(() =>enableRowId? {variant: "indexExpand",+ expandedIndex: undefined,}: undefined,[enableRowId],diff --git a/frontend/src/metabase/data-grid/components/RowIdCell/RowIdCell.tsx b/frontend/src/metabase/data-grid/components/RowIdCell/RowIdCell.tsxindex 68f538fff3f..6673d7940d0 100644--- a/frontend/src/metabase/data-grid/components/RowIdCell/RowIdCell.tsx+++ b/frontend/src/metabase/data-grid/components/RowIdCell/RowIdCell.tsx@@ -13,17 +13,22 @@ export interface RowIdCellProps {value?: React.ReactNode;backgroundColor?: string;canExpand?: boolean;+ expanded?: boolean;}export const RowIdCell = memo(function RowIdCell({value,backgroundColor,canExpand = true,+ expanded,}: RowIdCellProps) {const hasValue = value != null;return (- <Tooltip label={t`View details`} disabled={!canExpand}>+ <Tooltip+ label={expanded ? t`Hide details` : t`View details`}+ disabled={!canExpand}+ ><span><BaseCelldata-testid="row-id-cell"@@ -45,7 +50,9 @@ export const RowIdCell = memo(function RowIdCell({h={24}className={cx(DataGridS.rowHoverVisible, S.expandButton)}size="compact-md"- leftSection={<Icon name="expand" size={14} />}+ leftSection={+ <Icon name={expanded ? "sidebar_closed" : "sidebar_open"} />+ }/>)}</BaseCell>diff --git a/frontend/src/metabase/data-grid/types.ts b/frontend/src/metabase/data-grid/types.tsindex e8568ad45e9..70b1f67f091 100644--- a/frontend/src/metabase/data-grid/types.ts+++ b/frontend/src/metabase/data-grid/types.ts@@ -115,6 +115,9 @@ export interface ColumnOptions<TRow extends RowData, TValue = unknown> {* Configuration for the row ID column*/export interface RowIdColumnOptions {+ /** Index in rows array of corresponding expanded row, if any (i.e. DetailViewSidesheet) */+ expandedIndex: number | undefined;+/** Display style of the row ID column */variant: RowIdVariant;diff --git a/frontend/src/metabase/data-grid/utils/columns/row-id-column.tsx b/frontend/src/metabase/data-grid/utils/columns/row-id-column.tsxindex 9c18c808b53..04a4916d56b 100644--- a/frontend/src/metabase/data-grid/utils/columns/row-id-column.tsx+++ b/frontend/src/metabase/data-grid/utils/columns/row-id-column.tsx@@ -12,6 +12,7 @@ export const getRowIdColumnSize = (variant: RowIdVariant) =>variant === "expandButton" ? 40 : 46;export const getRowIdColumn = <TRow, TValue>({+ expandedIndex,variant,getBackgroundColor,}: RowIdColumnOptions): ColumnDef<TRow, TValue> => {@@ -35,6 +36,7 @@ export const getRowIdColumn = <TRow, TValue>({return (<RowIdCellcanExpand={canExpand}+ expanded={row.index === expandedIndex}value={value}backgroundColor={getBackgroundColor?.(row.index)}/>diff --git a/frontend/src/metabase/detail-view/components/DetailViewPage/DetailViewPage.module.css b/frontend/src/metabase/detail-view/components/DetailViewPage/DetailViewPage.module.cssnew file mode 100644index 00000000000..d2291302e8f--- /dev/null+++ b/frontend/src/metabase/detail-view/components/DetailViewPage/DetailViewPage.module.css@@ -0,0 +1,11 @@+.header {+ border-bottom: 1px solid var(--mb-color-border);+}++.footer {+ border-top: 1px solid var(--mb-color-border);+}++.scrollable {+ overflow: auto;+}diff --git a/frontend/src/metabase/detail-view/components/DetailViewPage/DetailViewPage.tsx b/frontend/src/metabase/detail-view/components/DetailViewPage/DetailViewPage.tsxnew file mode 100644index 00000000000..ba921b206a6--- /dev/null+++ b/frontend/src/metabase/detail-view/components/DetailViewPage/DetailViewPage.tsx@@ -0,0 +1,129 @@+import { useViewportSize } from "@mantine/hooks";+import { useMemo } from "react";++import {+ DetailsGroup,+ Header,+ Relationships,+} from "metabase/detail-view/components";+import { DETAIL_VIEW_PADDING_LEFT } from "metabase/detail-view/constants";+import {+ getEntityIcon,+ getHeaderColumns,+ getRowName,+} from "metabase/detail-view/utils";+import { NAV_SIDEBAR_WIDTH } from "metabase/nav/constants";+import { Box, Group, Stack, rem } from "metabase/ui";+import type {+ DatasetColumn,+ ForeignKey,+ RowValues,+ Table,+} from "metabase-types/api";++import S from "./DetailViewPage.module.css";++interface Props {+ columns: DatasetColumn[];+ isNavBarOpen: boolean;+ row: RowValues;+ rowId: string | number;+ table: Table;+ tableForeignKeys?: ForeignKey[];+}++const BREAKPOINT_MEDIUM = 1024;+const BREAKPOINT_SMALL = 640;++export function DetailViewPage({+ columns,+ isNavBarOpen,+ row,+ rowId,+ table,+ tableForeignKeys,+}: Props) {+ const headerColumns = useMemo(() => getHeaderColumns(columns), [columns]);+ const rowName = getRowName(columns, row) || rowId;+ const icon = getEntityIcon(table.entity_type);+ const viewport = useViewportSize();+ const navBarWidth = isNavBarOpen ? parseInt(NAV_SIDEBAR_WIDTH, 10) : 0;+ const width = viewport.width - navBarWidth;+ const isMediumBreakpoint = width <= BREAKPOINT_MEDIUM;+ const isSmallBreakpoint = width <= BREAKPOINT_SMALL;+ const paddingLeft = isSmallBreakpoint ? 32 : DETAIL_VIEW_PADDING_LEFT;++ return (+ <Stack+ bg="var(--mb-color-background-light)"+ data-testid="object-detail"+ gap={0}+ mih="100%"+ >+ {headerColumns.length > 0 && (+ <Box+ bg="bg-white"+ className={S.header}+ pl={rem(paddingLeft)}+ pr="xl"+ py={rem(64)}+ >+ <Box+ // intentionally misalign the header to create an "optical alignment effect" (due to rounded avatar)+ ml={rem(-8)}+ >+ <Header columns={columns} icon={icon} row={row} />+ </Box>+ </Box>+ )}++ <Group+ align="stretch"+ flex="1"+ gap={0}+ key={rowId}+ mih={0}+ wrap={isMediumBreakpoint ? "wrap" : "nowrap"}+ >+ <Group+ align="flex-start"+ bg="bg-white"+ flex="1"+ p="xl"+ pl={rem(paddingLeft)}+ w={isMediumBreakpoint ? "100%" : undefined}+ >+ <Stack gap={rem(64)} h="100%" maw={rem(900)} w="100%">+ {columns.length - headerColumns.length > 0 && (+ <DetailsGroup+ columns={columns}+ responsive={isSmallBreakpoint}+ row={row}+ table={table}+ />+ )}+ </Stack>+ </Group>++ {tableForeignKeys && tableForeignKeys.length > 0 && (+ <Box+ flex={isMediumBreakpoint ? undefined : "0 0 auto"}+ pl={rem(isMediumBreakpoint ? paddingLeft : 40)}+ pr={rem(40)}+ py="xl"+ w={isMediumBreakpoint ? "100%" : rem(440)}+ >+ <Relationships+ columns={columns}+ row={row}+ rowId={rowId}+ rowName={rowName}+ table={table}+ tableForeignKeys={tableForeignKeys}+ />+ </Box>+ )}+ </Group>+ </Stack>+ );+}diff --git a/frontend/src/metabase/detail-view/components/DetailViewPage/index.ts b/frontend/src/metabase/detail-view/components/DetailViewPage/index.tsnew file mode 100644index 00000000000..823bc89a0d9--- /dev/null+++ b/frontend/src/metabase/detail-view/components/DetailViewPage/index.ts@@ -0,0 +1 @@+export * from "./DetailViewPage";diff --git a/frontend/src/metabase/detail-view/components/DetailViewSidesheet/DetailViewSidesheet.tsx b/frontend/src/metabase/detail-view/components/DetailViewSidesheet/DetailViewSidesheet.tsxnew file mode 100644index 00000000000..34134571819--- /dev/null+++ b/frontend/src/metabase/detail-view/components/DetailViewSidesheet/DetailViewSidesheet.tsx@@ -0,0 +1,409 @@+import { useWindowEvent } from "@mantine/hooks";+import { useCallback, useEffect, useMemo, useState } from "react";+import { Link } from "react-router";+import { t } from "ttag";++import { ActionExecuteModal } from "metabase/actions/containers/ActionExecuteModal";+import {+ skipToken,+ useGetAdhocQueryQuery,+ useListActionsQuery,+ useListDatabasesQuery,+} from "metabase/api";+import EntityMenu from "metabase/common/components/EntityMenu";+import { NotFound } from "metabase/common/components/ErrorPages";+import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";+import Modal from "metabase/common/components/Modal";+import {+ DetailsGroup,+ Header,+ Relationships,+} from "metabase/detail-view/components";+import {+ getEntityIcon,+ getHeaderColumns,+ getRowName,+} from "metabase/detail-view/utils";+import type { OptionsType } from "metabase/lib/formatting/types";+import { useDispatch } from "metabase/lib/redux";+import { runQuestionQuery } from "metabase/query_builder/actions";+import { ActionsApi } from "metabase/services";+import {+ Box,+ Button,+ Divider,+ Group,+ Icon,+ Stack,+ Tooltip,+ rem,+} from "metabase/ui";+import { DeleteObjectModal } from "metabase/visualizations/components/ObjectDetail/DeleteObjectModal";+import * as Lib from "metabase-lib";+import type {+ DatasetColumn,+ ForeignKey,+ RowValues,+ Table,+ TableColumnOrderSetting,+ WritebackActionId,+} from "metabase-types/api";++import { Sidesheet } from "./Sidesheet";+import { extractData, getActionItems, getModelId } from "./utils";++interface Props {+ columnSettings: TableColumnOrderSetting[] | undefined;+ columns: DatasetColumn[];+ columnsSettings: (OptionsType | undefined)[];+ query: Lib.Query | undefined;+ row: RowValues | undefined;+ rowId: string | number;+ showImplicitActions: boolean;+ showNav: boolean;+ table: Table | undefined;+ tableForeignKeys?: ForeignKey[];+ url: string | undefined;+ onClose: () => void;+ onNextClick: (() => void) | undefined;+ onPreviousClick: (() => void) | undefined;+}++export function DetailViewSidesheet({+ columns: columnsFromProp,+ columnSettings,+ columnsSettings,+ query,+ row: rowFromProps,+ rowId,+ showImplicitActions,+ showNav,+ table,+ tableForeignKeys,+ url,+ onClose,+ onNextClick,+ onPreviousClick,+}: Props) {+ const {+ data: dataset,+ error,+ isLoading,+ } = useGetAdhocQueryQuery(+ query != null && rowFromProps == null+ ? Lib.toLegacyQuery(query)+ : skipToken,+ );+ const { columns, row } = useMemo(+ () => extractData(dataset, columnsFromProp, columnSettings, rowFromProps),+ [dataset, columnsFromProp, columnSettings, rowFromProps],+ );++ const dispatch = useDispatch();+ const [linkCopied, setLinkCopied] = useState(false);+ const headerColumns = useMemo(() => getHeaderColumns(columns), [columns]);+ const rowName = useMemo(() => {+ return getRowName(columns, row) || rowId;+ }, [columns, row, rowId]);+ const icon = getEntityIcon(table?.entity_type);+ const modelId = getModelId(table);+ const isNavEnabled = rowFromProps != null && showNav;++ const [actionId, setActionId] = useState<WritebackActionId>();+ const [deleteActionId, setDeleteActionId] = useState<WritebackActionId>();+ const isActionExecuteModalOpen = typeof actionId === "number";+ const isDeleteModalOpen = typeof deleteActionId === "number";+ const isModalOpen = isActionExecuteModalOpen || isDeleteModalOpen;+ const initialValues = useMemo(() => ({ id: rowId ?? null }), [rowId]);++ const { data: actions } = useListActionsQuery(+ showImplicitActions && modelId != null+ ? { "model-id": modelId }+ : skipToken,+ );++ const { data: databases } = useListDatabasesQuery(+ showImplicitActions ? {} : skipToken,+ );++ const actionItems = getActionItems({+ actions: actions ?? [],+ databases: databases?.data ?? [],+ onDelete: (action) => setDeleteActionId(action.id),+ onUpdate: (action) => setActionId(action.id),+ });++ const handleClose = () => {+ // prevent Esc key from closing both modal and the sidesheet+ if (!isModalOpen) {+ onClose();+ }+ };++ const handleExecuteModalClose = () => {+ setActionId(undefined);+ };++ const handleDeleteModalClose = () => {+ setDeleteActionId(undefined);+ };++ const fetchInitialValues = useCallback(async () => {+ if (typeof actionId !== "number") {+ return {};+ }++ return ActionsApi.prefetchValues({+ id: actionId,+ parameters: JSON.stringify({ id: String(rowId) }),+ });+ }, [actionId, rowId]);++ const handleActionSuccess = useCallback(() => {+ dispatch(runQuestionQuery());+ }, [dispatch]);++ const handleDeleteSuccess = useCallback(() => {+ handleActionSuccess();+ onClose();+ }, [onClose, handleActionSuccess]);++ const handleCopyLink = useCallback(() => {+ if (!url) {+ return;+ }++ navigator.clipboard.writeText(`${window.location.origin}${url}`);+ setLinkCopied(true);+ }, [url]);++ useEffect(() => {+ if (linkCopied) {+ const timeout = setTimeout(() => setLinkCopied(false), 2000);+ return () => clearTimeout(timeout);+ }+ }, [linkCopied]);++ useWindowEvent(+ "keydown",+ (event) => {+ const activeElement = document.activeElement;+ const isInputFocused =+ activeElement instanceof HTMLElement &&+ (["INPUT", "TEXTAREA", "SELECT"].includes(activeElement.tagName) ||+ activeElement.isContentEditable);++ if (isNavEnabled && !isInputFocused && !isModalOpen) {+ if (event.key === "ArrowUp" && onPreviousClick) {+ event.stopPropagation();+ onPreviousClick();+ }++ if (event.key === "ArrowDown" && onNextClick) {+ event.stopPropagation();+ onNextClick();+ }+ }+ },+ {+ // otherwise modals get closed ealier and isModalOpen evaluates to false in the handler+ capture: true,+ },+ );++ if (error || isLoading) {+ return (+ <Sidesheet data-testid="object-detail" onClose={handleClose}>+ <LoadingAndErrorWrapper error={error} loading={isLoading} />;+ </Sidesheet>+ );+ }++ if (row == null) {+ return (+ <Sidesheet data-testid="object-detail" onClose={handleClose}>+ <Group align="center" justify="center">+ <NotFound message={t`We couldn't find that record`} />+ </Group>+ </Sidesheet>+ );+ }++ return (+ <>+ <Sidesheet+ actions={+ <>+ {isNavEnabled && (+ <>+ <Tooltip disabled={!onPreviousClick} label={t`Previous row`}>+ <Button+ aria-label={t`Previous row`}+ c="text-dark"+ disabled={!onPreviousClick}+ h={20}+ leftSection={<Icon name="chevronup" />}+ p={0}+ variant="subtle"+ style={{+ opacity: onPreviousClick ? undefined : 0.5,+ }}+ w={20}+ onClick={onPreviousClick}+ />+ </Tooltip>++ <Tooltip disabled={!onNextClick} label={t`Next row`}>+ <Button+ aria-label={t`Next row`}+ c="text-dark"+ disabled={!onNextClick}+ h={20}+ leftSection={<Icon name="chevrondown" />}+ p={0}+ variant="subtle"+ style={{+ opacity: onNextClick ? undefined : 0.5,+ }}+ w={20}+ onClick={onNextClick}+ />+ </Tooltip>++ <Divider orientation="vertical" />+ </>+ )}++ {actionItems.length > 0 && (+ <EntityMenu+ items={actionItems}+ renderTrigger={({ onClick }: { onClick: () => void }) => (+ <Tooltip label={t`Actions`}>+ <Button+ aria-label={t`Actions`}+ c="text-dark"+ data-testid="actions-menu"+ h={20}+ leftSection={<Icon name="ellipsis" />}+ p={0}+ variant="subtle"+ w={20}+ onClick={onClick}+ />+ </Tooltip>+ )}+ />+ )}++ {url && (+ <>+ <Tooltip+ label={linkCopied ? t`Copied!` : t`Copy link to this record`}+ >+ <Button+ aria-label={+ linkCopied ? t`Copied!` : t`Copy link to this record`+ }+ c="text-dark"+ h={20}+ leftSection={<Icon name="link" />}+ p={0}+ variant="subtle"+ w={20}+ onClick={handleCopyLink}+ />+ </Tooltip>++ <Tooltip label={t`Open in full page`}>+ <Box>+ <Button+ aria-label={t`Open in full page`}+ c="text-dark"+ component={Link}+ h={20}+ leftSection={<Icon name="expand" />}+ p={0}+ to={url}+ variant="subtle"+ w={20}+ />+ </Box>+ </Tooltip>+ </>+ )}+ </>+ }+ data-testid="object-detail"+ onClose={handleClose}+ >+ <Stack gap={0} mih="100%">+ {headerColumns.length > 0 && (+ <Box pb="md" pt="xs" px={rem(56)}>+ <Box+ // intentionally misalign the header to create an "optical alignment effect" (due to rounded avatar)+ ml={rem(-8)}+ >+ <Header columns={columns} icon={icon} row={row} />+ </Box>+ </Box>+ )}++ <Group pb={rem(48)} pt="xl" px={rem(56)}>+ <Stack gap={rem(64)} h="100%" maw={rem(900)} w="100%">+ {columns.length - headerColumns.length > 0 && (+ <DetailsGroup+ columns={columns}+ columnsSettings={columnsSettings}+ row={row}+ table={table}+ />+ )}+ </Stack>+ </Group>++ {table && tableForeignKeys && tableForeignKeys.length > 0 && (+ <Box+ flex="1"+ bg="var(--mb-color-background-light)"+ px={rem(56)}+ py={rem(48)}+ >+ <Relationships+ columns={columns}+ row={row}+ rowId={rowId}+ rowName={rowName}+ table={table}+ tableForeignKeys={tableForeignKeys}+ onClick={onClose}+ />+ </Box>+ )}+ </Stack>+ </Sidesheet>++ <Modal+ isOpen={isActionExecuteModalOpen}+ onClose={handleExecuteModalClose}+ >+ <ActionExecuteModal+ actionId={actionId}+ initialValues={initialValues}+ fetchInitialValues={fetchInitialValues}+ shouldPrefetch+ onClose={handleExecuteModalClose}+ onSuccess={handleActionSuccess}+ />+ </Modal>++ <Modal isOpen={isDeleteModalOpen} onClose={handleDeleteModalClose}>+ <DeleteObjectModal+ actionId={deleteActionId}+ objectId={rowId}+ onClose={handleDeleteModalClose}+ onSuccess={handleDeleteSuccess}+ />+ </Modal>+ </>+ );+}diff --git a/frontend/src/metabase/detail-view/components/DetailViewSidesheet/Sidesheet/Sidesheet.module.css b/frontend/src/metabase/detail-view/components/DetailViewSidesheet/Sidesheet/Sidesheet.module.cssnew file mode 100644index 00000000000..e2af7ef1b47--- /dev/null+++ b/frontend/src/metabase/detail-view/components/DetailViewSidesheet/Sidesheet/Sidesheet.module.css@@ -0,0 +1,26 @@+.body {+ display: flex;+ flex-direction: column;+ flex: 1 1 auto;+ overflow: hidden;+}++.content {+ &:not([data-css-specificity-hack="🤷♀️"]) {+ position: fixed;+ height: 100dvh;+ max-height: 100dvh;+ inset-inline-end: 0;+ border-radius: 0;+ display: flex;+ flex: 1;+ flex-direction: column;+ box-shadow:+ -2px 0 4px -2px rgba(16, 24, 40, 0.06),+ -4px 0 8px -2px rgba(16, 24, 40, 0.1);+ }+}++.scrollable {+ overflow: auto;+}diff --git a/frontend/src/metabase/detail-view/components/DetailViewSidesheet/Sidesheet/Sidesheet.tsx b/frontend/src/metabase/detail-view/components/DetailViewSidesheet/Sidesheet/Sidesheet.tsxnew file mode 100644index 00000000000..f3da5d56d2d--- /dev/null+++ b/frontend/src/metabase/detail-view/components/DetailViewSidesheet/Sidesheet/Sidesheet.tsx@@ -0,0 +1,65 @@+import cx from "classnames";+import type { ReactNode } from "react";+import { t } from "ttag";++import Animation from "metabase/css/core/animation.module.css";+import { Button, Group, Icon, Modal, Stack, Tooltip, rem } from "metabase/ui";++import S from "./Sidesheet.module.css";++interface Props {+ actions?: ReactNode;+ children: ReactNode;+ "data-testid"?: string;+ onClose: () => void;+}++export function Sidesheet({+ actions,+ "data-testid": dataTestId,+ children,+ onClose,+}: Props) {+ return (+ <Modal.Root+ data-testid={dataTestId}+ h="100dvh"+ opened+ variant="sidesheet"+ onClose={onClose}+ >+ <Modal.Content+ classNames={{+ content: cx(S.content, Animation.slideLeft),+ }}+ data-testid="sidesheet"+ px="none"+ transitionProps={{ duration: 0 }}+ w={rem(720)}+ >+ <Modal.Body className={S.body} p={0} pt="lg">+ <Group gap="lg" justify="flex-end" px="xl">+ {actions}++ <Tooltip label={t`Close`}>+ <Button+ aria-label={t`Close`}+ c="text-dark"+ h={20}+ leftSection={<Icon name="close" />}+ p={0}+ variant="subtle"+ w={20}+ onClick={onClose}+ />+ </Tooltip>+ </Group>++ <Stack className={S.scrollable} gap={0} h="100%">+ {children}+ </Stack>+ </Modal.Body>+ </Modal.Content>+ </Modal.Root>+ );+}diff --git a/frontend/src/metabase/detail-view/components/DetailViewSidesheet/Sidesheet/index.ts b/frontend/src/metabase/detail-view/components/DetailViewSidesheet/Sidesheet/index.tsnew file mode 100644index 00000000000..9c1246626ee--- /dev/null+++ b/frontend/src/metabase/detail-view/components/DetailViewSidesheet/Sidesheet/index.ts@@ -0,0 +1 @@+export * from "./Sidesheet";diff --git a/frontend/src/metabase/detail-view/components/DetailViewSidesheet/index.ts b/frontend/src/metabase/detail-view/components/DetailViewSidesheet/index.tsnew file mode 100644index 00000000000..91a34ca18fc--- /dev/null+++ b/frontend/src/metabase/detail-view/components/DetailViewSidesheet/index.ts@@ -0,0 +1 @@+export * from "./DetailViewSidesheet";diff --git a/frontend/src/metabase/detail-view/components/DetailViewSidesheet/utils.ts b/frontend/src/metabase/detail-view/components/DetailViewSidesheet/utils.tsnew file mode 100644index 00000000000..7123e293749--- /dev/null+++ b/frontend/src/metabase/detail-view/components/DetailViewSidesheet/utils.ts@@ -0,0 +1,92 @@+import { t } from "ttag";++import {+ isImplicitDeleteAction,+ isImplicitUpdateAction,+} from "metabase/actions/utils";+import { hasActionsEnabled } from "metabase/admin/databases/utils";+import { extractRemappedColumns } from "metabase/visualizations";+import { getQuestionIdFromVirtualTableId } from "metabase-lib/v1/metadata/utils/saved-questions";+import { findColumnIndexesForColumnSettings } from "metabase-lib/v1/queries/utils/dataset";+import type {+ Database,+ Dataset,+ DatasetColumn,+ RowValues,+ Table,+ TableColumnOrderSetting,+ WritebackAction,+} from "metabase-types/api";++export const getActionItems = ({+ actions,+ databases,+ onDelete,+ onUpdate,+}: {+ actions: WritebackAction[];+ databases: Database[];+ onDelete: (action: WritebackAction) => void;+ onUpdate: (action: WritebackAction) => void;+}) => {+ const actionItems = [];+ const privateActions = actions.filter((action) => !action.public_uuid);+ const deleteAction = privateActions.find(isValidImplicitDeleteAction);+ const updateAction = privateActions.find(isValidImplicitUpdateAction);++ if (updateAction && canRunAction(updateAction, databases)) {+ const action = () => onUpdate(updateAction);+ actionItems.push({ title: t`Update`, icon: "pencil", action });+ }++ if (deleteAction && canRunAction(deleteAction, databases)) {+ const action = () => onDelete(deleteAction);+ actionItems.push({ title: t`Delete`, icon: "trash", action });+ }++ return actionItems;+};++export const isValidImplicitDeleteAction = (action: WritebackAction): boolean =>+ isImplicitDeleteAction(action) && !action.archived;++export const isValidImplicitUpdateAction = (action: WritebackAction): boolean =>+ isImplicitUpdateAction(action) && !action.archived;++export const canRunAction = (+ action: WritebackAction,+ databases: Database[],+) => {+ const database = databases.find(({ id }) => id === action.database_id);+ return database != null && hasActionsEnabled(database);+};++export function extractData(+ dataset: Dataset | undefined,+ columnsFromProp: DatasetColumn[],+ columnSettings: TableColumnOrderSetting[] | undefined,+ rowFromProps: RowValues | undefined,+) {+ const data = dataset ? extractRemappedColumns(dataset.data) : undefined;+ const unsortedColumns = data?.cols ?? columnsFromProp;+ const columnIndexes = columnSettings+ ? findColumnIndexesForColumnSettings(+ unsortedColumns,+ columnSettings.filter(({ enabled }) => enabled),+ ).filter((columnIndex: number) => columnIndex >= 0)+ : unsortedColumns.map((_value, index) => index);+ const columns = columnIndexes.map((index) => unsortedColumns[index]);+ const rowFromQuery = (data?.rows ?? [])[0];+ const unsortedRow = rowFromProps ?? rowFromQuery;+ const row = unsortedRow+ ? columnIndexes.map((index) => unsortedRow[index])+ : undefined;++ return { columns, row };+}++export function getModelId(table: Table | undefined) {+ return table?.type === "model"+ ? getQuestionIdFromVirtualTableId(table.id)+ : undefined;+}diff --git a/frontend/src/metabase/detail-view/components/DetailsGroup/DetailsGroup.module.css b/frontend/src/metabase/detail-view/components/DetailsGroup/DetailsGroup.module.cssnew file mode 100644index 00000000000..503bd1eb073--- /dev/null+++ b/frontend/src/metabase/detail-view/components/DetailsGroup/DetailsGroup.module.css@@ -0,0 +1,4 @@+.name {+ overflow-wrap: break-word;+ word-break: break-word;+}diff --git a/frontend/src/metabase/detail-view/components/DetailsGroup/DetailsGroup.tsx b/frontend/src/metabase/detail-view/components/DetailsGroup/DetailsGroup.tsxnew file mode 100644index 00000000000..c41a75ec9b3--- /dev/null+++ b/frontend/src/metabase/detail-view/components/DetailsGroup/DetailsGroup.tsx@@ -0,0 +1,75 @@+import { useMemo } from "react";++import {+ getBodyColumns,+ getColumnTitle,+ getRowValue,+ renderValue,+} from "metabase/detail-view/utils";+import { useTranslateContent } from "metabase/i18n/hooks";+import type { OptionsType } from "metabase/lib/formatting/types";+import { Flex, Group, Stack, Text, rem } from "metabase/ui";+import type { DatasetColumn, RowValues, Table } from "metabase-types/api";++import S from "./DetailsGroup.module.css";+import { Value } from "./Value";++interface Props {+ columns: DatasetColumn[];+ columnsSettings?: (OptionsType | undefined)[];+ responsive?: boolean;+ row: RowValues;+ table: Table | undefined;+}++export const DetailsGroup = ({+ columns,+ columnsSettings,+ responsive,+ row,+ table,+}: Props) => {+ const tc = useTranslateContent();+ const bodyColumns = useMemo(() => getBodyColumns(columns), [columns]);+ const columnIndexMap = useMemo(+ () => new Map(columns.map((column, index) => [column, index])),+ [columns],+ );++ return (+ <Stack data-testid="object-details" gap="lg">+ {bodyColumns.map((column, index) => {+ const field = table?.fields?.find((field) => field.id === column.id);+ const value = getRowValue(columns, column, row);+ const realIndex = columnIndexMap.get(column) ?? -1;+ const columnSettings = columnsSettings?.[realIndex] ?? {};++ return (+ <Group+ align="flex-start"+ data-testid="object-details-row"+ gap="xl"+ key={index}+ wrap="nowrap"+ >+ <Text+ c="text-secondary"+ className={S.name}+ data-testid="column-name"+ flex={responsive ? "0 1 50%" : "0 0 auto"}+ w={responsive ? undefined : rem(224)}+ >+ {getColumnTitle(column, columnSettings)}+ </Text>++ <Flex data-testid="value" flex={responsive ? "0 1 50%" : "1"}>+ <Value column={column} field={field} value={value}>+ {renderValue(tc, value, column, columnSettings)}+ </Value>+ </Flex>+ </Group>+ );+ })}+ </Stack>+ );+};diff --git a/frontend/src/metabase/detail-view/components/DetailsGroup/Value/Value.module.css b/frontend/src/metabase/detail-view/components/DetailsGroup/Value/Value.module.cssnew file mode 100644index 00000000000..340aa15da79--- /dev/null+++ b/frontend/src/metabase/detail-view/components/DetailsGroup/Value/Value.module.css@@ -0,0 +1,34 @@+.value {+ overflow-wrap: break-word;+ word-break: break-word;++ a {+ color: var(--mb-color-text-primary);+ text-decoration: underline solid var(--mb-base-color-gray-40) 1px;++ &:hover {+ color: var(--mb-color-brand);+ }+ }+}++.fk {+ border-radius: 12px;+ border: 1px solid var(--mb-color-border);++ &:hover {+ color: var(--mb-color-brand) !important;+ }+}++.imageFrame {+ border: 1px solid var(--mb-color-border);+ border-radius: 8px;+ overflow: hidden;+ box-shadow: 0 1px 3px 0 hsla(220, 43%, 11%, 0.1);+}++.maxHeight {+ max-height: 560px;+ overflow: auto;+}diff --git a/frontend/src/metabase/detail-view/components/DetailsGroup/Value/Value.tsx b/frontend/src/metabase/detail-view/components/DetailsGroup/Value/Value.tsxnew file mode 100644index 00000000000..b68557c0888--- /dev/null+++ b/frontend/src/metabase/detail-view/components/DetailsGroup/Value/Value.tsx@@ -0,0 +1,85 @@+import cx from "classnames";+import type { ReactNode } from "react";+import { Link } from "react-router";+import { t } from "ttag";++import { Box, Image, Stack, Text, rem } from "metabase/ui";+import { isFK } from "metabase-lib/v1/types/utils/isa";+import type { DatasetColumn, Field, RowValue } from "metabase-types/api";++import S from "./Value.module.css";++interface Props {+ children: ReactNode;+ column: DatasetColumn;+ field: Field | undefined;+ value: RowValue | undefined;+}++const FRAME_SIZE = 240;+const IMAGE_SIZE = FRAME_SIZE - 2 * 16;++export const Value = ({ children, column, field, value }: Props) => {+ const isEmptyValue = value == null || value === "";+ const newTableId = field?.target?.table_id;+ const isValidLink = Boolean(+ column.settings?.view_as === "link" &&+ column.settings.link_text &&+ column.settings.link_url,+ );++ if (isEmptyValue) {+ return <Text c="text-light">{t`empty`}</Text>;+ }++ if (isFK(column) && newTableId != null && !isValidLink) {+ return (+ <Text+ bg="var(--mb-color-bg-light)"+ c="text-primary"+ className={S.fk}+ component={Link}+ fw="bold"+ my={rem(-1)}+ px="sm"+ to={`/table/${newTableId}/detail/${value}`}+ >+ {children}+ </Text>+ );+ }++ if (column.settings?.view_as === "image") {+ return (+ <Stack className={S.value} gap="sm" align="flex-start">+ <Box+ bg="var(--mb-color-background-light)"+ className={S.imageFrame}+ mah={FRAME_SIZE}+ maw={FRAME_SIZE}+ p="md"+ >+ <Image mah={IMAGE_SIZE} src={value} maw={IMAGE_SIZE} />+ </Box>++ <Text+ c="text-primary"+ className={S.maxHeight}+ component="a"+ fw="bold"+ href={String(value)}+ rel="noopener noreferrer"+ target="_blank"+ >+ {String(value)}+ </Text>+ </Stack>+ );+ }++ return (+ <Text c="text-primary" className={cx(S.value, S.maxHeight)} fw="bold">+ {children}+ </Text>+ );+};diff --git a/frontend/src/metabase/detail-view/components/DetailsGroup/Value/index.ts b/frontend/src/metabase/detail-view/components/DetailsGroup/Value/index.tsnew file mode 100644index 00000000000..16c8a1a73f6--- /dev/null+++ b/frontend/src/metabase/detail-view/components/DetailsGroup/Value/index.ts@@ -0,0 +1 @@+export * from "./Value";diff --git a/frontend/src/metabase/detail-view/components/DetailsGroup/index.ts b/frontend/src/metabase/detail-view/components/DetailsGroup/index.tsnew file mode 100644index 00000000000..3ffbdcba787--- /dev/null+++ b/frontend/src/metabase/detail-view/components/DetailsGroup/index.ts@@ -0,0 +1 @@+export * from "./DetailsGroup";diff --git a/frontend/src/metabase/detail-view/components/Header/Header.module.css b/frontend/src/metabase/detail-view/components/Header/Header.module.cssnew file mode 100644index 00000000000..95753d108e7--- /dev/null+++ b/frontend/src/metabase/detail-view/components/Header/Header.module.css@@ -0,0 +1,11 @@+.avatarFrame {+ background-color: var(--mb-color-bg-light);+ border: 1px solid var(--mb-color-border);+ border-radius: 50%;+ overflow: hidden;+}++.text {+ overflow-wrap: break-word;+ word-break: break-word;+}diff --git a/frontend/src/metabase/detail-view/components/Header/Header.tsx b/frontend/src/metabase/detail-view/components/Header/Header.tsxnew file mode 100644index 00000000000..0e7afda7715--- /dev/null+++ b/frontend/src/metabase/detail-view/components/Header/Header.tsx@@ -0,0 +1,100 @@+import { useMemo } from "react";++import {+ getAvatarColumn,+ getRowValue,+ getSubtitleColumn,+ getTitleColumn,+ renderValue,+} from "metabase/detail-view/utils";+import { useTranslateContent } from "metabase/i18n/hooks";+import {+ Box,+ Group,+ Icon,+ type IconName,+ Image,+ Stack,+ Text,+ rem,+} from "metabase/ui";+import type { DatasetColumn, RowValues } from "metabase-types/api";++import S from "./Header.module.css";++interface Props {+ columns: DatasetColumn[];+ icon?: IconName;+ row: RowValues;+}++const IMAGE_SIZE = 80;++export const Header = ({ columns, icon, row }: Props) => {+ const tc = useTranslateContent();+ const titleColumn = useMemo(() => getTitleColumn(columns), [columns]);+ const subtitleColumn = useMemo(() => getSubtitleColumn(columns), [columns]);+ const avatarColumn = useMemo(() => getAvatarColumn(columns), [columns]);+ const title = useMemo(+ () => getRowValue(columns, titleColumn, row),+ [columns, titleColumn, row],+ );+ const subtitle = useMemo(+ () => getRowValue(columns, subtitleColumn, row),+ [columns, subtitleColumn, row],+ );+ const avatar = useMemo(+ () => getRowValue(columns, avatarColumn, row),+ [columns, avatarColumn, row],+ );++ if (!title && !subtitle && !avatar && !icon) {+ return null;+ }++ return (+ <Group data-testid="detail-view-header" gap="xl" wrap="nowrap">+ {(avatar || icon) && (+ <Box className={S.avatarFrame} flex="0 0 auto">+ {avatar && (+ <Image h={IMAGE_SIZE} src={String(avatar)} w={IMAGE_SIZE} />+ )}++ {!avatar && icon && (+ <Group h={IMAGE_SIZE} justify="center" w={IMAGE_SIZE}>+ <Icon c="brand" name={icon} size={24} />+ </Group>+ )}+ </Box>+ )}++ <Stack gap="sm">+ {titleColumn && title && (+ <Text+ c="text-primary"+ className={S.text}+ component="h1"+ fw="bold"+ fz={rem(32)}+ lh={1}+ >+ {renderValue(tc, title, titleColumn)}+ </Text>+ )}++ {subtitleColumn && subtitle && (+ <Text+ c="text-secondary"+ className={S.text}+ component="h2"+ fw="bold"+ fz={rem(14)}+ lh={1}+ >+ {renderValue(tc, subtitle, subtitleColumn)}+ </Text>+ )}+ </Stack>+ </Group>+ );+};diff --git a/frontend/src/metabase/detail-view/components/Header/Header.unit.spec.tsx b/frontend/src/metabase/detail-view/components/Header/Header.unit.spec.tsxnew file mode 100644index 00000000000..4c93ab86b84--- /dev/null+++ b/frontend/src/metabase/detail-view/components/Header/Header.unit.spec.tsx@@ -0,0 +1,172 @@+import { screen } from "@testing-library/react";++import { getIcon, queryIcon, renderWithProviders } from "__support__/ui";+import type { IconName } from "metabase/ui";+import registerVisualizations from "metabase/visualizations/register";+import type { DatasetColumn, RowValues } from "metabase-types/api";+import { createMockColumn } from "metabase-types/api/mocks/dataset";++import { Header } from "./Header";++registerVisualizations();++const AVATAR_COLUMN = createMockColumn({+ name: "avatar",+ base_type: "type/Text",+ semantic_type: "type/AvatarURL",+});++const TITLE_COLUMN = createMockColumn({+ name: "title",+ base_type: "type/Text",+ semantic_type: "type/Title",+});++const PK_COLUMN = createMockColumn({+ name: "id",+ base_type: "type/Integer",+ semantic_type: "type/PK",+});++interface SetupOpts {+ columns?: DatasetColumn[];+ icon?: IconName;+ row?: RowValues;+}++function setup({ columns = [], icon, row = [] }: SetupOpts = {}) {+ renderWithProviders(<Header columns={columns} icon={icon} row={row} />);+}++describe("Header", () => {+ describe("avatar section", () => {+ it("should render avatar when avatar column exists and has value", () => {+ setup({+ columns: [AVATAR_COLUMN, TITLE_COLUMN],+ row: ["https://example.com/avatar.jpg", "Test Title"],+ });++ const avatar = screen.getByRole("img");+ expect(avatar).toBeInTheDocument();+ expect(avatar).toHaveAttribute("src", "https://example.com/avatar.jpg");+ });++ it("should render icon when no avatar but icon prop is provided", () => {+ setup({ columns: [TITLE_COLUMN], icon: "person" });++ expect(getIcon("person")).toBeInTheDocument();+ });++ it("should not render avatar section when neither avatar nor icon is provided", () => {+ setup({ columns: [TITLE_COLUMN] });++ expect(screen.queryByRole("img")).not.toBeInTheDocument();+ });++ it("should prioritize avatar over icon when both are available", () => {+ setup({+ columns: [AVATAR_COLUMN, TITLE_COLUMN],+ row: ["https://example.com/avatar.jpg", "Test Title"],+ icon: "person",+ });++ expect(screen.getByRole("img")).toBeInTheDocument();+ expect(queryIcon("person")).not.toBeInTheDocument();+ });+ });++ describe("title section", () => {+ it("should render title when title column exists and has value", () => {+ setup({ columns: [TITLE_COLUMN], row: ["Test Title"] });++ const title = screen.getByRole("heading", { level: 1 });+ expect(title).toBeInTheDocument();+ expect(title).toHaveTextContent("Test Title");+ });++ it("should not render title when title column is undefined", () => {+ setup({ columns: [PK_COLUMN] });++ expect(+ screen.queryByRole("heading", { level: 1 }),+ ).not.toBeInTheDocument();+ });++ it("should not render title when title value is undefined", () => {+ setup({ columns: [TITLE_COLUMN], row: [null] });++ expect(+ screen.queryByRole("heading", { level: 1 }),+ ).not.toBeInTheDocument();+ });+ });++ describe("subtitle section", () => {+ it("should render subtitle when subtitle column exists and has value", () => {+ setup({+ columns: [TITLE_COLUMN, PK_COLUMN],+ row: ["Test Title", 123],+ });++ const subtitle = screen.getByRole("heading", { level: 2 });+ expect(subtitle).toBeInTheDocument();+ expect(subtitle).toHaveTextContent("123");+ });++ it("should not render subtitle when subtitle column does not exist", () => {+ setup({ columns: [TITLE_COLUMN] });++ expect(+ screen.queryByRole("heading", { level: 2 }),+ ).not.toBeInTheDocument();+ });++ it("should not render subtitle when subtitle value does not exist", () => {+ setup({+ columns: [TITLE_COLUMN, PK_COLUMN],+ row: ["Test Title", null],+ });++ expect(+ screen.queryByRole("heading", { level: 2 }),+ ).not.toBeInTheDocument();+ });+ });++ describe("edge cases", () => {+ it("should handle empty columns array", () => {+ setup({ columns: [] });++ expect(+ screen.queryByTestId("detail-view-header"),+ ).not.toBeInTheDocument();+ });++ it("should handle empty row array", () => {+ setup({ columns: [TITLE_COLUMN], row: [] });++ expect(screen.queryByRole("img")).not.toBeInTheDocument();+ expect(+ screen.queryByRole("heading", { level: 1 }),+ ).not.toBeInTheDocument();+ expect(+ screen.queryByRole("heading", { level: 2 }),+ ).not.toBeInTheDocument();+ });++ it("should handle null/undefined values gracefully", () => {+ setup({+ columns: [TITLE_COLUMN, PK_COLUMN, AVATAR_COLUMN],+ row: [null, null, null],+ });++ expect(screen.queryByRole("img")).not.toBeInTheDocument();+ expect(+ screen.queryByRole("heading", { level: 1 }),+ ).not.toBeInTheDocument();+ expect(+ screen.queryByRole("heading", { level: 2 }),+ ).not.toBeInTheDocument();+ });+ });+});diff --git a/frontend/src/metabase/detail-view/components/Header/index.ts b/frontend/src/metabase/detail-view/components/Header/index.tsnew file mode 100644index 00000000000..9e08a64dbfb--- /dev/null+++ b/frontend/src/metabase/detail-view/components/Header/index.ts@@ -0,0 +1 @@+export * from "./Header";diff --git a/frontend/src/metabase/detail-view/components/Header/utils.ts b/frontend/src/metabase/detail-view/components/Header/utils.tsnew file mode 100644index 00000000000..ec308901f5c--- /dev/null+++ b/frontend/src/metabase/detail-view/components/Header/utils.ts@@ -0,0 +1,19 @@+import type { Table } from "metabase-types/api";++export const getEntityIcon = (entityType?: Table["entity_type"]) => {+ switch (entityType) {+ case "entity/UserTable":+ return "person";+ case "entity/CompanyTable":+ return "globe";+ case "entity/TransactionTable":+ return "index";+ case "entity/SubscriptionTable":+ return "sync";+ case "entity/ProductTable":+ case "entity/EventTable":+ case "entity/GenericTable":+ default:+ return "document";+ }+};diff --git a/frontend/src/metabase/detail-view/components/Nav/Breadcrumb/Breadcrumb.module.css b/frontend/src/metabase/detail-view/components/Nav/Breadcrumb/Breadcrumb.module.cssnew file mode 100644index 00000000000..9e69e83e7ba--- /dev/null+++ b/frontend/src/metabase/detail-view/components/Nav/Breadcrumb/Breadcrumb.module.css@@ -0,0 +1,9 @@+.breadcrumb {+ overflow: hidden;+}++.link {+ &:hover {+ color: var(--mb-color-brand) !important;+ }+}diff --git a/frontend/src/metabase/detail-view/components/Nav/Breadcrumb/Breadcrumb.tsx b/frontend/src/metabase/detail-view/components/Nav/Breadcrumb/Breadcrumb.tsxnew file mode 100644index 00000000000..f927ef001ee--- /dev/null+++ b/frontend/src/metabase/detail-view/components/Nav/Breadcrumb/Breadcrumb.tsx@@ -0,0 +1,57 @@+import cx from "classnames";+import type { ReactNode } from "react";+import { Link } from "react-router";++import { Ellipsified } from "metabase/common/components/Ellipsified";+import {+ Box,+ type BoxProps,+ Group,+ Icon,+ type IconName,+ rem,+} from "metabase/ui";++import S from "./Breadcrumb.module.css";++interface Props extends BoxProps {+ children?: ReactNode;+ icon?: IconName;+ href?: string;+}++export const Breadcrumb = ({+ children,+ className,+ href,+ icon,+ ...props+}: Props) => {+ if (href) {+ return (+ <Box+ c="text-secondary"+ className={cx(S.breadcrumb, S.link, className)}+ component={Link}+ to={href}+ {...props}+ >+ <Group align="center" gap={rem(10)} wrap="nowrap">+ {icon && <Icon flex="0 0 auto" name={icon} />}++ <Ellipsified tooltip={children}>{children}</Ellipsified>+ </Group>+ </Box>+ );+ }++ return (+ <Box c="text-secondary" className={cx(S.breadcrumb, className)} {...props}>+ <Group align="center" gap={rem(10)} wrap="nowrap">+ {icon && <Icon flex="0 0 auto" name={icon} />}++ <Ellipsified tooltip={children}>{children}</Ellipsified>+ </Group>+ </Box>+ );+};diff --git a/frontend/src/metabase/detail-view/components/Nav/Breadcrumb/index.ts b/frontend/src/metabase/detail-view/components/Nav/Breadcrumb/index.tsnew file mode 100644index 00000000000..3bc34d185a9--- /dev/null+++ b/frontend/src/metabase/detail-view/components/Nav/Breadcrumb/index.ts@@ -0,0 +1 @@+export * from "./Breadcrumb";diff --git a/frontend/src/metabase/detail-view/components/Nav/CollectionBreadcrumb.tsx b/frontend/src/metabase/detail-view/components/Nav/CollectionBreadcrumb.tsxnew file mode 100644index 00000000000..acae4720305--- /dev/null+++ b/frontend/src/metabase/detail-view/components/Nav/CollectionBreadcrumb.tsx@@ -0,0 +1,28 @@+import { useGetCollectionQuery } from "metabase/api";+import * as Urls from "metabase/lib/urls";+import type { CollectionId } from "metabase-types/api";++import { Breadcrumb } from "./Breadcrumb";+import { Separator } from "./Separator";++interface Props {+ collectionId: CollectionId;+}++export const CollectionBreadcrumb = ({ collectionId }: Props) => {+ const { data: collection } = useGetCollectionQuery({ id: collectionId });++ if (!collection) {+ return null;+ }++ return (+ <>+ <Breadcrumb href={Urls.collection(collection)} icon="folder">+ {collection.name}+ </Breadcrumb>++ <Separator />+ </>+ );+};diff --git a/frontend/src/metabase/detail-view/components/Nav/ModelNav.tsx b/frontend/src/metabase/detail-view/components/Nav/ModelNav.tsxnew file mode 100644index 00000000000..3e80d6245a8--- /dev/null+++ b/frontend/src/metabase/detail-view/components/Nav/ModelNav.tsx@@ -0,0 +1,70 @@+import { type ReactNode, useMemo } from "react";++import {+ skipToken,+ useGetCardQuery,+ useGetCollectionQuery,+} from "metabase/api";+import * as Urls from "metabase/lib/urls";+import { Group, type GroupProps } from "metabase/ui";+import { getQuestionIdFromVirtualTableId } from "metabase-lib/v1/metadata/utils/saved-questions";+import type { Table } from "metabase-types/api";++import { Breadcrumb } from "./Breadcrumb";+import { CollectionBreadcrumb } from "./CollectionBreadcrumb";+import { Separator } from "./Separator";+import { getCollectionList } from "./utils";++interface Props extends GroupProps {+ rowName: ReactNode;+ table: Table;+}++export const ModelNav = ({ rowName, table, ...props }: Props) => {+ const modelId = getQuestionIdFromVirtualTableId(table.id);++ const { data: card } = useGetCardQuery(+ modelId == null ? skipToken : { id: modelId },+ );++ const { data: collection } = useGetCollectionQuery(+ card?.collection_id ? { id: card.collection_id } : skipToken,+ );++ const collections = useMemo(() => {+ return getCollectionList(collection);+ }, [collection]);++ return (+ <Group align="center" gap="sm" miw={0} wrap="nowrap" {...props}>+ {collections.map((collection) => (+ <CollectionBreadcrumb+ collectionId={collection.id}+ key={collection.id}+ />+ ))}++ {collection && (+ <>+ <Breadcrumb href={Urls.collection(collection)} icon="folder">+ {collection.name}+ </Breadcrumb>++ <Separator />+ </>+ )}++ {card && (+ <>+ <Breadcrumb href={Urls.question(card)} icon="model">+ {card.name}+ </Breadcrumb>++ <Separator />+ </>+ )}++ {rowName && <Breadcrumb>{rowName}</Breadcrumb>}+ </Group>+ );+};diff --git a/frontend/src/metabase/detail-view/components/Nav/Nav.tsx b/frontend/src/metabase/detail-view/components/Nav/Nav.tsxnew file mode 100644index 00000000000..07c3681d9a7--- /dev/null+++ b/frontend/src/metabase/detail-view/components/Nav/Nav.tsx@@ -0,0 +1,22 @@+import type { ReactNode } from "react";++import type { GroupProps } from "metabase/ui";+import type { Table } from "metabase-types/api";++import { ModelNav } from "./ModelNav";+import { TableNav } from "./TableNav";++interface Props extends GroupProps {+ rowName: ReactNode;+ table: Table;+}++export const Nav = (props: Props) => {+ const { table } = props;++ if (table.type === "model") {+ return <ModelNav {...props} />;+ }++ return <TableNav {...props} />;+};diff --git a/frontend/src/metabase/detail-view/components/Nav/Separator.tsx b/frontend/src/metabase/detail-view/components/Nav/Separator.tsxnew file mode 100644index 00000000000..838fdab81a5--- /dev/null+++ b/frontend/src/metabase/detail-view/components/Nav/Separator.tsx@@ -0,0 +1,7 @@+import { Text } from "metabase/ui";++export const Separator = () => (+ <Text c="text-secondary" flex="0 0 auto" fw="bold">+ /+ </Text>+);diff --git a/frontend/src/metabase/detail-view/components/Nav/TableNav.tsx b/frontend/src/metabase/detail-view/components/Nav/TableNav.tsxnew file mode 100644index 00000000000..ab487983ebb--- /dev/null+++ b/frontend/src/metabase/detail-view/components/Nav/TableNav.tsx@@ -0,0 +1,59 @@+import type { ReactNode } from "react";++import { skipToken, useListDatabaseSchemasQuery } from "metabase/api";+import * as Urls from "metabase/lib/urls";+import { Group, type GroupProps } from "metabase/ui";+import type { Table } from "metabase-types/api";++import { Breadcrumb } from "./Breadcrumb";+import { Separator } from "./Separator";++interface Props extends GroupProps {+ rowName: ReactNode;+ table: Table;+}++export const TableNav = ({ rowName, table, ...props }: Props) => {+ const { data: schemas, isLoading: isLoadingSchemas } =+ useListDatabaseSchemasQuery(+ table && table.db_id && table.schema ? { id: table.db_id } : skipToken,+ );++ if (!table || !table.db || isLoadingSchemas) {+ return null;+ }++ return (+ <Group align="center" gap="sm" miw={0} wrap="nowrap" {...props}>+ <Breadcrumb href={`/browse/databases/${table.db_id}`} icon="database">+ {table.db.name}+ </Breadcrumb>++ {schemas && schemas.length > 1 && table.schema && (+ <>+ <Separator />++ <Breadcrumb+ href={`/browse/databases/${table.db_id}/schema/${table.schema}`}+ >+ {table.schema}+ </Breadcrumb>+ </>+ )}++ <Separator />++ <Breadcrumb href={Urls.tableRowsQuery(table.db_id, table.id)}>+ {table.display_name}+ </Breadcrumb>++ {rowName && (+ <>+ <Separator />++ <Breadcrumb>{rowName}</Breadcrumb>+ </>+ )}+ </Group>+ );+};diff --git a/frontend/src/metabase/detail-view/components/Nav/index.ts b/frontend/src/metabase/detail-view/components/Nav/index.tsnew file mode 100644index 00000000000..48956118c93--- /dev/null+++ b/frontend/src/metabase/detail-view/components/Nav/index.ts@@ -0,0 +1 @@+export * from "./Nav";diff --git a/frontend/src/metabase/detail-view/components/Nav/utils.ts b/frontend/src/metabase/detail-view/components/Nav/utils.tsnew file mode 100644index 00000000000..24badd71791--- /dev/null+++ b/frontend/src/metabase/detail-view/components/Nav/utils.ts@@ -0,0 +1,9 @@+import { isRootCollection } from "metabase/collections/utils";+import type { Collection } from "metabase-types/api";++export const getCollectionList = (collection: Collection | undefined) => {+ const ancestors = collection?.effective_ancestors || [];+ const hasRoot = ancestors[0] && isRootCollection(ancestors[0]);+ const [_root, ...crumbsWithoutRoot] = ancestors;+ return hasRoot ? crumbsWithoutRoot : ancestors;+};diff --git a/frontend/src/metabase/detail-view/components/Relationships/Relationship/Relationship.module.css b/frontend/src/metabase/detail-view/components/Relationships/Relationship/Relationship.module.cssnew file mode 100644index 00000000000..79701f4d2de--- /dev/null+++ b/frontend/src/metabase/detail-view/components/Relationships/Relationship/Relationship.module.css@@ -0,0 +1,9 @@+.clickable {+ color: var(--mb-color-text-dark) !important;++ &:hover {+ .text {+ color: var(--mb-color-brand) !important;+ }+ }+}diff --git a/frontend/src/metabase/detail-view/components/Relationships/Relationship/Relationship.tsx b/frontend/src/metabase/detail-view/components/Relationships/Relationship/Relationship.tsxnew file mode 100644index 00000000000..a1100977238--- /dev/null+++ b/frontend/src/metabase/detail-view/components/Relationships/Relationship/Relationship.tsx@@ -0,0 +1,97 @@+import cx from "classnames";+import { inflect } from "inflection";+import { useMemo } from "react";+import { Link } from "react-router";+import { t } from "ttag";++import { skipToken, useGetAdhocQueryQuery } from "metabase/api";+import { Loader, Stack, Text, rem } from "metabase/ui";+import { isNumeric, isPK } from "metabase-lib/v1/types/utils/isa";+import type { ForeignKey, Table } from "metabase-types/api";++import S from "./Relationship.module.css";++interface Props {+ fk: ForeignKey;+ href: string | undefined;+ rowId: string | number;+ table: Table;+ onClick?: () => void;+}++export const Relationship = ({ fk, href, rowId, table, onClick }: Props) => {+ const pk = (table.fields ?? []).find(isPK);+ const fkOriginId =+ fk.origin && typeof fk.origin.id == "number" ? fk.origin.id : undefined;++ const {+ data: dataset,+ error,+ isFetching,+ } = useGetAdhocQueryQuery(+ fk.origin != null && fkOriginId != null+ ? {+ type: "query",+ query: {+ "source-table": fk.origin?.table_id,+ filter: [+ "=",+ ["field", fkOriginId, null],+ isNumeric(pk) && typeof rowId === "string"+ ? parseFloat(rowId)+ : rowId,+ ],+ aggregation: [["count"]],+ },+ database: fk.origin.table?.db_id ?? table.db_id,+ }+ : skipToken,+ );++ const count = useMemo(() => {+ if (!dataset) {+ return undefined;+ }++ return dataset.data.rows[0]?.[0] ?? 0; // rows array can be empty (metabase#62156)+ }, [dataset]);+ const clickable = typeof count === "number" && count > 0;+ const originTableName = fk.origin?.table?.display_name ?? "";+ const relationName =+ typeof count === "number"+ ? inflect(originTableName, count)+ : originTableName;++ return (+ <Stack+ className={cx({+ [S.clickable]: clickable,+ })}+ gap={rem(12)}+ {...(clickable ? { component: Link, to: href, onClick } : undefined)}+ >+ {isFetching && <Loader data-testid="loading-indicator" size="md" />}++ {!isFetching && (+ <Text+ c={count === 0 ? "text-light" : "text-medium"}+ className={S.text}+ fw="bold"+ fz={rem(24)}+ lh={1}+ >+ {error ? t`Unknown` : String(count)}+ </Text>+ )}++ <Text+ c={count === 0 ? "text-light" : "text-medium"}+ className={S.text}+ fw="bold"+ lh={1}+ >+ {relationName}+ </Text>+ </Stack>+ );+};diff --git a/frontend/src/metabase/detail-view/components/Relationships/Relationship/Relationship.unit.spec.tsx b/frontend/src/metabase/detail-view/components/Relationships/Relationship/Relationship.unit.spec.tsxnew file mode 100644index 00000000000..b3d63493b87--- /dev/null+++ b/frontend/src/metabase/detail-view/components/Relationships/Relationship/Relationship.unit.spec.tsx@@ -0,0 +1,161 @@+import { screen } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import fetchMock from "fetch-mock";+import { Route } from "react-router";++import { setupCardDataset } from "__support__/server-mocks";+import { renderWithProviders, waitForLoaderToBeRemoved } from "__support__/ui";+import type { Table } from "metabase-types/api";+import { createMockForeignKey } from "metabase-types/api/mocks";+import {+ type MockDatasetOpts,+ createMockColumn,+} from "metabase-types/api/mocks/dataset";+import {+ ORDERS,+ PRODUCTS,+ createOrdersProductIdField,+ createOrdersTable,+} from "metabase-types/api/mocks/presets";++import { Relationship } from "./Relationship";++const ORDERS_TABLE = createOrdersTable();++const COUNT_COLUMN = createMockColumn({+ id: 1,+ display_name: "Count",+ name: "count",+ base_type: "type/Integer",+});++const FK = createMockForeignKey({+ origin: createOrdersProductIdField({+ table: ORDERS_TABLE,+ }),+ origin_id: ORDERS.PRODUCT_ID,+ destination_id: PRODUCTS.ID,+});++const DATASET: MockDatasetOpts = {+ data: {+ rows: [[5]],+ cols: [COUNT_COLUMN],+ },+};++const ROW_ID = 123;++interface SetupOpts {+ dataset?: MockDatasetOpts;+ table?: Table;+}++function setup({ dataset = DATASET, table = ORDERS_TABLE }: SetupOpts = {}) {+ const onClick = jest.fn();++ const TestComponent = () => (+ <Relationship+ fk={FK}+ href="/test"+ rowId={ROW_ID}+ table={table}+ onClick={onClick}+ />+ );++ setupCardDataset(dataset);++ renderWithProviders(<Route path="/" component={TestComponent} />, {+ withRouter: true,+ });++ return { onClick };+}++describe("Relationship", () => {+ it("should render loading state initially", async () => {+ setup();++ expect(screen.getByTestId("loading-indicator")).toBeInTheDocument();+ await waitForLoaderToBeRemoved();+ expect(screen.queryByTestId("loading-indicator")).not.toBeInTheDocument();+ });++ it("should render clickable count and relationship name when data is loaded", async () => {+ const { onClick } = setup();+ await waitForLoaderToBeRemoved();++ expect(screen.getByText("5")).toBeInTheDocument();+ expect(screen.getByText("Orders")).toBeInTheDocument();+ expect(screen.getByRole("link")).toBeInTheDocument();+ await userEvent.click(screen.getByText("5"));+ expect(onClick).toHaveBeenCalled();+ });++ it("should render non-clickable zero count when no related records", async () => {+ const { onClick } = setup({+ dataset: {+ data: {+ rows: [[0]],+ cols: [COUNT_COLUMN],+ },+ },+ });+ await waitForLoaderToBeRemoved();++ expect(screen.getByText("0")).toBeInTheDocument();+ expect(screen.queryByRole("link")).not.toBeInTheDocument();+ await userEvent.click(screen.getByText("0"));+ expect(onClick).not.toHaveBeenCalled();+ });++ it("should handle empty rows array gracefully", async () => {+ const { onClick } = setup({+ dataset: {+ data: {+ rows: [],+ cols: [COUNT_COLUMN],+ },+ },+ });+ await waitForLoaderToBeRemoved();++ expect(screen.getByText("0")).toBeInTheDocument();+ expect(screen.queryByRole("link")).not.toBeInTheDocument();+ await userEvent.click(screen.getByText("0"));+ expect(onClick).not.toHaveBeenCalled();+ });++ it("should handle errors gracefully", async () => {+ const { onClick } = setup();++ fetchMock.modifyRoute("dataset-post", {+ response: { status: 500 },+ });++ await waitForLoaderToBeRemoved();++ expect(screen.getByText("Unknown")).toBeInTheDocument();+ expect(screen.getByText("Orders")).toBeInTheDocument();+ expect(screen.queryByRole("link")).not.toBeInTheDocument();+ await userEvent.click(screen.getByText("Unknown"));+ expect(onClick).not.toHaveBeenCalled();+ });++ it("should render singular relationship names correctly", async () => {+ setup({+ dataset: {+ data: {+ rows: [[1]],+ cols: [COUNT_COLUMN],+ },+ },+ });+ await waitForLoaderToBeRemoved();++ expect(screen.getByText("1")).toBeInTheDocument();+ expect(screen.getByText("Order")).toBeInTheDocument();+ expect(screen.queryByText("Orders")).not.toBeInTheDocument();+ });+});diff --git a/frontend/src/metabase/detail-view/components/Relationships/Relationship/index.ts b/frontend/src/metabase/detail-view/components/Relationships/Relationship/index.tsnew file mode 100644index 00000000000..40597a33dcb--- /dev/null+++ b/frontend/src/metabase/detail-view/components/Relationships/Relationship/index.ts@@ -0,0 +1 @@+export * from "./Relationship";diff --git a/frontend/src/metabase/detail-view/components/Relationships/Relationships.tsx b/frontend/src/metabase/detail-view/components/Relationships/Relationships.tsxnew file mode 100644index 00000000000..07536719370--- /dev/null+++ b/frontend/src/metabase/detail-view/components/Relationships/Relationships.tsx@@ -0,0 +1,76 @@+import { type ReactNode, useMemo } from "react";+import { jt, t } from "ttag";++import { type BoxProps, Stack, Text } from "metabase/ui";+import type {+ DatasetColumn,+ ForeignKey,+ RowValues,+ Table,+} from "metabase-types/api";++import { Relationship } from "./Relationship";+import { getUrl } from "./utils";++interface Props {+ columns: DatasetColumn[];+ row: RowValues;+ rowId: string | number;+ rowName: ReactNode;+ table: Table;+ tableForeignKeys: ForeignKey[];+ onClick?: () => void;+}++export function Relationships({+ columns,+ row,+ rowId,+ rowName,+ table,+ tableForeignKeys,+ onClick,+}: Props & BoxProps): JSX.Element | null {+ const sortedForeignTables = useMemo(+ () =>+ tableForeignKeys.toSorted((a, b) => {+ const aDisplayName = a.origin?.table?.display_name ?? "";+ const bDisplayName = b.origin?.table?.display_name ?? "";+ return aDisplayName.localeCompare(bDisplayName);+ }),+ [tableForeignKeys],+ );++ return (+ <Stack data-testid="relationships" gap="md">+ <Text c="text-secondary" fz={17}>+ {jt`${(+ <Text+ c="text-secondary"+ component="span"+ fw="bold"+ fz={17}+ key="row-name"+ >+ {rowName ? rowName : t`This record`}+ </Text>+ )} is connected to:`}+ </Text>++ <Stack gap="md">+ {sortedForeignTables.map((fk) => {+ return (+ <Relationship+ key={`${fk.origin_id}-${fk.destination_id}`}+ fk={fk}+ href={getUrl({ columns, row, table, fk })}+ rowId={rowId}+ table={table}+ onClick={onClick}+ />+ );+ })}+ </Stack>+ </Stack>+ );+}diff --git a/frontend/src/metabase/detail-view/components/Relationships/index.ts b/frontend/src/metabase/detail-view/components/Relationships/index.tsnew file mode 100644index 00000000000..4b59ca2dc22--- /dev/null+++ b/frontend/src/metabase/detail-view/components/Relationships/index.ts@@ -0,0 +1 @@+export * from "./Relationships";diff --git a/frontend/src/metabase/detail-view/components/Relationships/utils.ts b/frontend/src/metabase/detail-view/components/Relationships/utils.tsnew file mode 100644index 00000000000..d5c5fade0d7--- /dev/null+++ b/frontend/src/metabase/detail-view/components/Relationships/utils.ts@@ -0,0 +1,51 @@+import { question } from "metabase/lib/urls";+import { isPK } from "metabase-lib/v1/types/utils/isa";+import type {+ DatasetColumn,+ ForeignKey,+ RowValues,+ Table,+} from "metabase-types/api";++export const getUrl = ({+ columns,+ row,+ table,+ fk,+}: {+ columns: DatasetColumn[];+ fk: ForeignKey;+ row: RowValues;+ table: Table;+}): string | undefined => {+ const pkIndex = columns.findIndex(isPK);++ if (pkIndex === -1) {+ return undefined;+ }++ const objectId = row[pkIndex];++ if (objectId == null) {+ return undefined;+ }++ if (fk.origin?.table_id) {+ const card = {+ type: "question" as const,+ dataset_query: {+ type: "query" as const,+ query: {+ "source-table": fk.origin.table_id,+ filter: ["=", ["field", fk.origin.id, null], objectId],+ },+ database: fk.origin.table?.db_id || table.db_id,+ },+ };++ const questionUrl = question(card, { hash: card as any });+ return questionUrl;+ }++ return undefined;+};diff --git a/frontend/src/metabase/detail-view/components/index.ts b/frontend/src/metabase/detail-view/components/index.tsnew file mode 100644index 00000000000..f95ed3b9451--- /dev/null+++ b/frontend/src/metabase/detail-view/components/index.ts@@ -0,0 +1,6 @@+export * from "./DetailsGroup";+export * from "./DetailViewPage";+export * from "./DetailViewSidesheet";+export * from "./Header";+export * from "./Nav";+export * from "./Relationships";diff --git a/frontend/src/metabase/detail-view/constants.ts b/frontend/src/metabase/detail-view/constants.tsnew file mode 100644index 00000000000..2bbbefa66d0--- /dev/null+++ b/frontend/src/metabase/detail-view/constants.ts@@ -0,0 +1 @@+export const DETAIL_VIEW_PADDING_LEFT = 112;diff --git a/frontend/src/metabase/detail-view/pages/ModelDetailPage/ModelDetailPage.tsx b/frontend/src/metabase/detail-view/pages/ModelDetailPage/ModelDetailPage.tsxnew file mode 100644index 00000000000..2f0c026bfbd--- /dev/null+++ b/frontend/src/metabase/detail-view/pages/ModelDetailPage/ModelDetailPage.tsx@@ -0,0 +1,111 @@+import { useEffect, useMemo } from "react";+import { useUnmount } from "react-use";+import { t } from "ttag";++import { useGetCardQuery, useGetCardQueryMetadataQuery } from "metabase/api";+import { skipToken } from "metabase/api/api";+import { useGetAdhocQueryQuery } from "metabase/api/dataset";+import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper/LoadingAndErrorWrapper";+import { DetailViewPage } from "metabase/detail-view/components";+import {+ filterByPk,+ getRowName,+ getTableQuery,+} from "metabase/detail-view/utils";+import { useDispatch, useSelector } from "metabase/lib/redux";+import * as Urls from "metabase/lib/urls";+import { closeNavbar, setDetailView } from "metabase/redux/app";+import { getIsNavbarOpen } from "metabase/selectors/app";+import { extractRemappedColumns } from "metabase/visualizations";+import * as Lib from "metabase-lib";+import { getQuestionVirtualTableId } from "metabase-lib/v1/metadata/utils/saved-questions";++interface Props {+ params: {+ slug: string;+ rowId: string;+ };+}++export function ModelDetailPage({ params }: Props) {+ const cardId = Urls.extractEntityId(params.slug);+ const rowId = params.rowId;++ const {+ data: card,+ error: cardError,+ isLoading: isCardLoading,+ } = useGetCardQuery(cardId == null ? skipToken : { id: cardId });++ const {+ data: metadata,+ error: metadataError,+ isLoading: isMetadataLoading,+ } = useGetCardQueryMetadataQuery(cardId == null ? skipToken : cardId);++ const table = metadata?.tables?.find(+ (table) => table.id === getQuestionVirtualTableId(cardId),+ );++ const tableQuery = useMemo(() => getTableQuery(table), [table]);+ const objectQuery = useMemo(() => {+ return tableQuery && table+ ? filterByPk(tableQuery, table.fields ?? [], rowId)+ : undefined;+ }, [rowId, table, tableQuery]);++ const {+ data: dataset,+ error: queryError,+ isLoading: isQueryLoading,+ } = useGetAdhocQueryQuery(+ objectQuery ? Lib.toLegacyQuery(objectQuery) : skipToken,+ );++ const error = metadataError ?? queryError ?? cardError;+ const isLoading = isMetadataLoading || isQueryLoading || isCardLoading;++ const data = useMemo(() => {+ return dataset ? extractRemappedColumns(dataset.data) : undefined;+ }, [dataset]);++ const collectionId = card?.collection_id ?? null;+ const columns = useMemo(() => data?.cols ?? [], [data]);+ const row = useMemo(() => (data?.rows ?? [])[0], [data]);+ const rowName = getRowName(columns, row) || rowId;++ const dispatch = useDispatch();+ const isNavBarOpen = useSelector(getIsNavbarOpen);++ useEffect(() => {+ dispatch(closeNavbar());+ }, [dispatch]);++ useEffect(() => {+ if (table) {+ dispatch(setDetailView({ rowName, table, collectionId }));+ }+ }, [dispatch, rowName, table, collectionId]);++ useUnmount(() => {+ dispatch(setDetailView(null));+ });++ if (!table || !dataset || !row || error || isLoading) {+ const rowError = !row && !isLoading ? t`Row not found` : undefined;++ return (+ <LoadingAndErrorWrapper error={error ?? rowError} loading={isLoading} />+ );+ }++ return (+ <DetailViewPage+ columns={columns}+ isNavBarOpen={isNavBarOpen}+ row={row}+ rowId={rowId}+ table={table}+ />+ );+}diff --git a/frontend/src/metabase/detail-view/pages/ModelDetailPage/index.ts b/frontend/src/metabase/detail-view/pages/ModelDetailPage/index.tsnew file mode 100644index 00000000000..6c97c2444c1--- /dev/null+++ b/frontend/src/metabase/detail-view/pages/ModelDetailPage/index.ts@@ -0,0 +1 @@+export * from "./ModelDetailPage";diff --git a/frontend/src/metabase/detail-view/pages/TableDetailPage/TableDetailPage.tsx b/frontend/src/metabase/detail-view/pages/TableDetailPage/TableDetailPage.tsxnew file mode 100644index 00000000000..0872f9af915--- /dev/null+++ b/frontend/src/metabase/detail-view/pages/TableDetailPage/TableDetailPage.tsx@@ -0,0 +1,103 @@+import { useEffect, useMemo } from "react";+import { useUnmount } from "react-use";+import { t } from "ttag";++import { skipToken } from "metabase/api/api";+import { useGetAdhocQueryQuery } from "metabase/api/dataset";+import {+ useGetTableQueryMetadataQuery,+ useListTableForeignKeysQuery,+} from "metabase/api/table";+import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper/LoadingAndErrorWrapper";+import { DetailViewPage } from "metabase/detail-view/components";+import {+ filterByPk,+ getRowName,+ getTableQuery,+} from "metabase/detail-view/utils";+import { useDispatch, useSelector } from "metabase/lib/redux";+import { closeNavbar, setDetailView } from "metabase/redux/app";+import { getIsNavbarOpen } from "metabase/selectors/app";+import { extractRemappedColumns } from "metabase/visualizations";+import * as Lib from "metabase-lib";++interface Props {+ params: {+ tableId: string;+ rowId: string;+ };+}++export function TableDetailPage({ params }: Props) {+ const tableId = parseInt(params.tableId, 10);+ const rowId = params.rowId;++ const {+ data: table,+ error: tableError,+ isLoading: isTableLoading,+ } = useGetTableQueryMetadataQuery({ id: tableId });+ const { data: tableForeignKeys } = useListTableForeignKeysQuery(tableId);++ const tableQuery = useMemo(() => getTableQuery(table), [table]);+ const objectQuery = useMemo(() => {+ return tableQuery && table+ ? filterByPk(tableQuery, table.fields ?? [], rowId)+ : undefined;+ }, [rowId, table, tableQuery]);++ const {+ data: dataset,+ error: queryError,+ isLoading: isQueryLoading,+ } = useGetAdhocQueryQuery(+ objectQuery ? Lib.toLegacyQuery(objectQuery) : skipToken,+ );++ const error = tableError ?? queryError;+ const isLoading = isTableLoading || isQueryLoading;++ const data = useMemo(() => {+ return dataset ? extractRemappedColumns(dataset.data) : undefined;+ }, [dataset]);++ const columns = useMemo(() => data?.cols ?? [], [data]);+ const row = useMemo(() => (data?.rows ?? [])[0], [data]);+ const rowName = getRowName(columns, row) || rowId;++ const dispatch = useDispatch();+ const isNavBarOpen = useSelector(getIsNavbarOpen);++ useEffect(() => {+ dispatch(closeNavbar());+ }, [dispatch]);++ useEffect(() => {+ if (table) {+ dispatch(setDetailView({ rowName, table, collectionId: null }));+ }+ }, [dispatch, rowName, table]);++ useUnmount(() => {+ dispatch(setDetailView(null));+ });++ if (!table || !dataset || !row || error || isLoading) {+ const rowError = !row && !isLoading ? t`Row not found` : undefined;++ return (+ <LoadingAndErrorWrapper error={error ?? rowError} loading={isLoading} />+ );+ }++ return (+ <DetailViewPage+ columns={columns}+ isNavBarOpen={isNavBarOpen}+ row={row}+ rowId={rowId}+ table={table}+ tableForeignKeys={tableForeignKeys}+ />+ );+}diff --git a/frontend/src/metabase/detail-view/pages/TableDetailPage/index.ts b/frontend/src/metabase/detail-view/pages/TableDetailPage/index.tsnew file mode 100644index 00000000000..0f01b779b45--- /dev/null+++ b/frontend/src/metabase/detail-view/pages/TableDetailPage/index.ts@@ -0,0 +1 @@+export * from "./TableDetailPage";diff --git a/frontend/src/metabase/detail-view/utils.ts b/frontend/src/metabase/detail-view/utils.tsnew file mode 100644index 00000000000..1af7b0e6f52--- /dev/null+++ b/frontend/src/metabase/detail-view/utils.ts@@ -0,0 +1,235 @@+import { createMockMetadata } from "__support__/metadata";+import type { ContentTranslationFunction } from "metabase/i18n/types";+import { type OptionsType, formatValue } from "metabase/lib/formatting";+import { getComputedSettings } from "metabase/visualizations/lib/settings";+import {+ getGlobalSettingsForColumn,+ getSettingDefinitionsForColumn,+ getTitleForColumn,+} from "metabase/visualizations/lib/settings/column";+import { getComputedSettingsForSeries } from "metabase/visualizations/lib/settings/visualization";+import * as Lib from "metabase-lib";+import {+ isAvatarURL,+ isEntityName,+ isImageURL,+ isPK,+ isTitle,+} from "metabase-lib/v1/types/utils/isa";+import type { DatasetColumn, Field, RowValue, Table } from "metabase-types/api";+import { createMockCard } from "metabase-types/api/mocks";++export function renderValue(+ tc: ContentTranslationFunction,+ value: RowValue | undefined,+ column: DatasetColumn,+ optionsOverride?: OptionsType,+) {+ const mockSeries = [{ data: { cols: [column] }, card: createMockCard() }];+ const settingDefs = getSettingDefinitionsForColumn(mockSeries, column);+ const inheritedSettings = {+ ...getGlobalSettingsForColumn(),+ ...(column.settings || {}),+ };+ const finalSettings = getComputedSettings(+ settingDefs,+ column,+ inheritedSettings,+ {+ series: mockSeries,+ },+ );++ const NO_VALUE = undefined;++ if (value === undefined) {+ return NO_VALUE;+ }++ if (!column) {+ return String(value) || NO_VALUE;+ }++ const formattedValue = formatValue(tc(value), {+ ...column.settings,+ ...finalSettings,+ ...optionsOverride,+ column,+ type: "cell",+ jsx: true,+ rich: true,+ remap: true,+ clicked: {+ type: "cell",+ value,+ column,+ data: [+ {+ col: column,+ value,+ },+ ],+ },+ });++ return formattedValue != null && formattedValue !== ""+ ? formattedValue+ : NO_VALUE;+}++export function getHeaderColumns(columns: DatasetColumn[]): DatasetColumn[] {+ return [+ getTitleColumn(columns),+ getSubtitleColumn(columns),+ getAvatarColumn(columns),+ ].filter((column): column is DatasetColumn => column != null);+}++export function getTitleColumn(+ columns: DatasetColumn[],+): DatasetColumn | undefined {+ const entityName = columns.find(isEntityName);+ const title = columns.find(isTitle);+ const pk = columns.find(isPK);++ return entityName ?? title ?? pk;+}++export function getSubtitleColumn(+ columns: DatasetColumn[],+): DatasetColumn | undefined {+ const titleColumn = getTitleColumn(columns);+ const pk = columns.find(isPK);++ if (titleColumn) {+ return titleColumn === pk ? undefined : pk;+ }++ return pk;+}++export function getAvatarColumn(+ columns: DatasetColumn[],+): DatasetColumn | undefined {+ const avatar = columns.find(isAvatarURL);+ const image = columns.find(isImageURL);++ return avatar ?? image;+}++export function getBodyColumns(columns: DatasetColumn[]): DatasetColumn[] {+ const headerColumns = getHeaderColumns(columns);+ return columns.filter((column) => !headerColumns.includes(column));+}++export function getRowName(+ columns: DatasetColumn[],+ row: RowValue[] | undefined,+): string | undefined {+ if (!row) {+ return undefined;+ }++ const title = getTitleColumn(columns);+ const rowName = getRowValue(columns, title, row);+ return String(rowName || "");+}++export function getRowValue(+ columns: DatasetColumn[],+ column: DatasetColumn | undefined,+ row: RowValue[] | undefined,+): RowValue | undefined {+ if (!row || !column) {+ return undefined;+ }++ const index = columns.indexOf(column);+ const value = row[index];+ return value;+}++export const getColumnTitle = (+ column: DatasetColumn,+ settings: OptionsType,+) => {+ const series = [{ data: { cols: [column] }, card: createMockCard() }];++ return getTitleForColumn(column, series, {+ ...getComputedSettingsForSeries(series),+ ...settings,+ });+};++export const getEntityIcon = (entityType?: Table["entity_type"]) => {+ switch (entityType) {+ case "entity/UserTable":+ return "person";+ case "entity/CompanyTable":+ return "globe";+ case "entity/TransactionTable":+ return "index";+ case "entity/SubscriptionTable":+ return "sync";+ case "entity/ProductTable":+ case "entity/EventTable":+ case "entity/GenericTable":+ default:+ return "document";+ }+};++export function getTableQuery(table: Table | undefined): Lib.Query | undefined {+ if (!table) {+ return undefined;+ }++ const metadata = createMockMetadata({+ tables: [table],+ });++ const metadataProvider = Lib.metadataProvider(table.db_id, metadata);++ return Lib.fromLegacyQuery(table.db_id, metadataProvider, {+ type: "query",+ database: table.db_id,+ query: {+ "source-table": table.id,+ },+ });+}++export function filterByPk(+ query: Lib.Query,+ columns: (DatasetColumn | Field)[],+ rowId: string | number | undefined,+) {+ if (typeof rowId === "undefined") {+ return undefined;+ }++ const pks = columns.filter(isPK);++ if (pks.length !== 1) {+ return undefined;+ }++ const [pk] = pks;+ const stageIndex = -1;+ const column = Lib.fromLegacyColumn(query, stageIndex, pk);+ const filterClause =+ typeof rowId === "number"+ ? Lib.numberFilterClause({+ operator: "=",+ column,+ values: [rowId],+ })+ : Lib.stringFilterClause({+ operator: "=",+ column,+ values: [rowId],+ options: {},+ });++ return Lib.filter(query, stageIndex, filterClause);+}diff --git a/frontend/src/metabase/lib/formatting.js b/frontend/src/metabase/lib/formatting.jsindex e1109b617bb..517c2b09335 100644--- a/frontend/src/metabase/lib/formatting.js+++ b/frontend/src/metabase/lib/formatting.js@@ -9,5 +9,6 @@ export * from "./formatting/image";export * from "./formatting/numbers";export * from "./formatting/strings";export * from "./formatting/time";+export * from "./formatting/types";export * from "./formatting/url";export * from "./formatting/value";diff --git a/frontend/src/metabase/models/routes.tsx b/frontend/src/metabase/models/routes.tsxindex 93f7f57054c..46f93a66613 100644--- a/frontend/src/metabase/models/routes.tsx+++ b/frontend/src/metabase/models/routes.tsx@@ -1,6 +1,7 @@import { IndexRedirect, Redirect } from "react-router";import ActionCreatorModal from "metabase/actions/containers/ActionCreatorModal/ActionCreatorModal";+import { ModelDetailPage } from "metabase/detail-view/pages/ModelDetailPage/ModelDetailPage";import { ModalRoute } from "metabase/hoc/ModalRoute";import { Route } from "metabase/hoc/Title";import ModelActions from "metabase/models/containers/ModelActions/ModelActions";@@ -28,6 +29,7 @@ export const getRoutes = () => (}}/></Route>+ <Route path=":rowId" component={ModelDetailPage} /><IndexRedirect to="actions" /><Redirect from="usage" to="actions" /><Redirect from="schema" to="actions" />diff --git a/frontend/src/metabase/nav/components/AppBar/AppBar.styled.tsx b/frontend/src/metabase/nav/components/AppBar/AppBar.styled.tsxindex 93fc4e7c168..2afd3f512cc 100644--- a/frontend/src/metabase/nav/components/AppBar/AppBar.styled.tsx+++ b/frontend/src/metabase/nav/components/AppBar/AppBar.styled.tsx@@ -1,9 +1,11 @@// eslint-disable-next-line no-restricted-importsimport styled from "@emotion/styled";-export const AppBarRoot = styled.header`+export const AppBarRoot = styled.header<{ withBorder?: boolean }>`position: relative;z-index: 4;+ border-bottom: ${(props) =>+ props.withBorder ? "1px solid var(--mb-color-border)" : undefined};@media print {display: none;diff --git a/frontend/src/metabase/nav/components/AppBar/AppBar.tsx b/frontend/src/metabase/nav/components/AppBar/AppBar.tsxindex 2b3a7b194e0..e619e461a65 100644--- a/frontend/src/metabase/nav/components/AppBar/AppBar.tsx+++ b/frontend/src/metabase/nav/components/AppBar/AppBar.tsx@@ -3,6 +3,7 @@ import { t } from "ttag";import ErrorBoundary from "metabase/ErrorBoundary";import useIsSmallScreen from "metabase/common/hooks/use-is-small-screen";import type { CollectionId, User } from "metabase-types/api";+import type { DetailViewState } from "metabase-types/store";import { AppBarRoot } from "./AppBar.styled";import AppBarLarge from "./AppBarLarge";@@ -11,6 +12,7 @@ import AppBarSmall from "./AppBarSmall";export interface AppBarProps {currentUser: User;collectionId?: CollectionId;+ detailView: DetailViewState | null;isNavBarOpen?: boolean;isNavBarEnabled?: boolean;isMetabotVisible?: boolean;@@ -34,6 +36,7 @@ const AppBar = (props: AppBarProps): JSX.Element => {data-element-id="app-bar"data-testid="app-bar"aria-label={t`Navigation bar`}+ withBorder={props.detailView != null}><ErrorBoundary>{isSmallScreen ? (diff --git a/frontend/src/metabase/nav/components/AppBar/AppBar.unit.spec.tsx b/frontend/src/metabase/nav/components/AppBar/AppBar.unit.spec.tsxindex 207559a9b61..adee35b6f34 100644--- a/frontend/src/metabase/nav/components/AppBar/AppBar.unit.spec.tsx+++ b/frontend/src/metabase/nav/components/AppBar/AppBar.unit.spec.tsx@@ -163,6 +163,7 @@ describe("AppBar", () => {});const getProps = (opts?: Partial<AppBarProps>): AppBarProps => ({+ detailView: null,currentUser: createMockUser(),onToggleNavbar: jest.fn(),onCloseNavbar: jest.fn(),diff --git a/frontend/src/metabase/nav/components/AppBar/AppBarLarge.tsx b/frontend/src/metabase/nav/components/AppBar/AppBarLarge.tsxindex dfb45d23845..b2ff357913c 100644--- a/frontend/src/metabase/nav/components/AppBar/AppBarLarge.tsx+++ b/frontend/src/metabase/nav/components/AppBar/AppBarLarge.tsx@@ -1,7 +1,10 @@import { t } from "ttag";+import { Nav as DetailViewNav } from "metabase/detail-view/components";+import { DETAIL_VIEW_PADDING_LEFT } from "metabase/detail-view/constants";import { PLUGIN_METABOT } from "metabase/plugins";import type { CollectionId } from "metabase-types/api";+import type { DetailViewState } from "metabase-types/store";import CollectionBreadcrumbs from "../../containers/CollectionBreadcrumbs";import QuestionLineage from "../../containers/QuestionLineage";@@ -21,6 +24,7 @@ import { AppBarToggle } from "./AppBarToggle";export interface AppBarLargeProps {collectionId?: CollectionId;+ detailView: DetailViewState | null;isNavBarOpen?: boolean;isNavBarEnabled?: boolean;isMetabotVisible?: boolean;@@ -36,6 +40,7 @@ export interface AppBarLargeProps {}const AppBarLarge = ({+ detailView,collectionId,isNavBarOpen,isNavBarEnabled,@@ -67,7 +72,13 @@ const AppBarLarge = ({<AppBarInfoContainerisVisible={!isNavBarVisible || isQuestionLineageVisible}>- {isQuestionLineageVisible ? (+ {detailView ? (+ <DetailViewNav+ ml={DETAIL_VIEW_PADDING_LEFT - 125}+ rowName={detailView.rowName}+ table={detailView.table}+ />+ ) : isQuestionLineageVisible ? (<QuestionLineage />) : isCollectionPathVisible ? (<CollectionBreadcrumbs />diff --git a/frontend/src/metabase/nav/components/AppBar/AppBarSmall.tsx b/frontend/src/metabase/nav/components/AppBar/AppBarSmall.tsxindex 4d5951fc9f5..f2ad4f514e7 100644--- a/frontend/src/metabase/nav/components/AppBar/AppBarSmall.tsx+++ b/frontend/src/metabase/nav/components/AppBar/AppBarSmall.tsx@@ -1,8 +1,10 @@import { useCallback, useState } from "react";+import { Nav as DetailViewNav } from "metabase/detail-view/components";import { SearchBar } from "metabase/nav/components/search/SearchBar";import { PLUGIN_METABOT } from "metabase/plugins";import { Flex } from "metabase/ui";+import type { DetailViewState } from "metabase-types/store";import CollectionBreadcrumbs from "../../containers/CollectionBreadcrumbs";import QuestionLineage from "../../containers/QuestionLineage";@@ -22,6 +24,7 @@ import {import { AppBarToggle } from "./AppBarToggle";export interface AppBarSmallProps {+ detailView: DetailViewState | null;isNavBarOpen?: boolean;isNavBarEnabled?: boolean;isLogoVisible?: boolean;@@ -36,6 +39,7 @@ export interface AppBarSmallProps {}const AppBarSmall = ({+ detailView,isNavBarOpen,isNavBarEnabled,isLogoVisible,@@ -109,7 +113,12 @@ const AppBarSmall = ({)}{isSubheaderVisible && (<AppBarSubheader isNavBarOpen={isNavBarVisible}>- {isQuestionLineageVisible ? (+ {detailView ? (+ <DetailViewNav+ rowName={detailView.rowName}+ table={detailView.table}+ />+ ) : isQuestionLineageVisible ? (<QuestionLineage />) : isCollectionPathVisible ? (<CollectionBreadcrumbs />diff --git a/frontend/src/metabase/nav/containers/AppBar/AppBar.tsx b/frontend/src/metabase/nav/containers/AppBar/AppBar.tsxindex 88b943e5fe6..4f71d81122a 100644--- a/frontend/src/metabase/nav/containers/AppBar/AppBar.tsx+++ b/frontend/src/metabase/nav/containers/AppBar/AppBar.tsx@@ -8,6 +8,7 @@ import { PLUGIN_METABOT } from "metabase/plugins";import { closeNavbar, toggleNavbar } from "metabase/redux/app";import type { RouterProps } from "metabase/selectors/app";import {+ getDetailViewState,getIsCollectionPathVisible,getIsLogoVisible,getIsNavBarEnabled,@@ -36,6 +37,7 @@ const mapStateToProps = (state: State, props: RouterProps) => ({isProfileLinkVisible: getIsProfileLinkVisible(state),isCollectionPathVisible: getIsCollectionPathVisible(state, props),isQuestionLineageVisible: getIsQuestionLineageVisible(state, props),+ detailView: getDetailViewState(state),});const mapDispatchToProps = {diff --git a/frontend/src/metabase/query_builder/components/VisualizationResult.jsx b/frontend/src/metabase/query_builder/components/VisualizationResult.jsxindex 9cc2ab2602b..0487ac49d54 100644--- a/frontend/src/metabase/query_builder/components/VisualizationResult.jsx+++ b/frontend/src/metabase/query_builder/components/VisualizationResult.jsx@@ -24,6 +24,7 @@ const ALLOWED_VISUALIZATION_PROPS = ["renderTableHeader","mode","renderEmptyMessage",+ "zoomedRowIndex",];export default class VisualizationResult extends Component {diff --git a/frontend/src/metabase/query_builder/containers/QueryBuilder.tsx b/frontend/src/metabase/query_builder/containers/QueryBuilder.tsxindex 9c320e0c668..e9326f4f000 100644--- a/frontend/src/metabase/query_builder/containers/QueryBuilder.tsx+++ b/frontend/src/metabase/query_builder/containers/QueryBuilder.tsx@@ -84,6 +84,7 @@ import {getVisibleTimelineEventIds,getVisibleTimelineEvents,getVisualizationSettings,+ getZoomedObjectRowIndex,isResultsMetadataDirty,} from "../selectors";import { getIsObjectDetail, getMode } from "../selectors/mode";@@ -184,6 +185,8 @@ const mapStateToProps = (state: State, props: EntityListLoaderMergedProps) => {pageFavicon: getPageFavicon(state),isLoadingComplete: getIsLoadingComplete(state),+ zoomedRowIndex: getZoomedObjectRowIndex(state),+reportTimezone: getSetting(state, "report-timezone-long"),didFirstNonTableChartGenerated: getSetting(state,diff --git a/frontend/src/metabase/query_builder/selectors.js b/frontend/src/metabase/query_builder/selectors.jsindex 45c7d721a52..9132613d7fe 100644--- a/frontend/src/metabase/query_builder/selectors.js+++ b/frontend/src/metabase/query_builder/selectors.js@@ -341,7 +341,7 @@ export const getTableForeignKeys = createSelector(export const getPKColumnIndex = createSelector([getFirstQueryResult, getTableId],(result, tableId) => {- if (!result) {+ if (!result || !result.data) {return;}const { cols } = result.data;@@ -359,7 +359,7 @@ export const getPKColumnIndex = createSelector(export const getPKRowIndexMap = createSelector([getFirstQueryResult, getPKColumnIndex],(result, PKColumnIndex) => {- if (!result || !Number.isSafeInteger(PKColumnIndex)) {+ if (!result || !result.data || !Number.isSafeInteger(PKColumnIndex)) {return {};}const { rows } = result.data;@@ -510,7 +510,7 @@ export const getIsResultDirty = createSelector(export const getZoomedObjectId = (state) => state.qb.zoomedRowObjectId;-const getZoomedObjectRowIndex = createSelector(+export const getZoomedObjectRowIndex = createSelector([getPKRowIndexMap, getZoomedObjectId],(PKRowIndexMap, objectId) => {if (!PKRowIndexMap) {diff --git a/frontend/src/metabase/querying/drills/utils/fk-details-drill.ts b/frontend/src/metabase/querying/drills/utils/fk-details-drill.tsindex 961c438f03d..00083c461fb 100644--- a/frontend/src/metabase/querying/drills/utils/fk-details-drill.ts+++ b/frontend/src/metabase/querying/drills/utils/fk-details-drill.ts@@ -16,7 +16,7 @@ export const fkDetailsDrill: Drill<Lib.FKDetailsDrillThruInfo> = ({section: "details",title: t`View details`,buttonType: "horizontal",- icon: "expand",+ icon: "sidebar_open",default: true,question: () => applyDrill(drill, objectId).setDefaultDisplay(),...(!isManyPks ? { extra: () => ({ objectId }) } : {}),diff --git a/frontend/src/metabase/querying/drills/utils/pk-drill.ts b/frontend/src/metabase/querying/drills/utils/pk-drill.tsindex d040dfafb71..a2ec8f7b7af 100644--- a/frontend/src/metabase/querying/drills/utils/pk-drill.ts+++ b/frontend/src/metabase/querying/drills/utils/pk-drill.ts@@ -16,7 +16,7 @@ export const pkDrill: Drill<Lib.PKDrillThruInfo> = ({section: "details",title: t`View details`,buttonType: "horizontal",- icon: "expand",+ icon: "sidebar_open",default: true,question: () => applyDrill(drill, objectId),},diff --git a/frontend/src/metabase/querying/drills/utils/zoom-drill.ts b/frontend/src/metabase/querying/drills/utils/zoom-drill.tsindex 57d3956ac87..5a339dbe721 100644--- a/frontend/src/metabase/querying/drills/utils/zoom-drill.ts+++ b/frontend/src/metabase/querying/drills/utils/zoom-drill.ts@@ -19,7 +19,7 @@ export const zoomDrill: Drill<Lib.ZoomDrillThruInfo> = ({section: "details",title: t`View details`,buttonType: "horizontal",- icon: "expand",+ icon: "sidebar_open",default: true,...(isDashboard? { question: () => applyDrill(drill, objectId) }diff --git a/frontend/src/metabase/redux/app.ts b/frontend/src/metabase/redux/app.tsindex f7dda8f4786..fb74173d2b2 100644--- a/frontend/src/metabase/redux/app.ts+++ b/frontend/src/metabase/redux/app.ts@@ -12,6 +12,7 @@ import {} from "metabase/lib/dom";import { combineReducers, handleActions } from "metabase/lib/redux";import type {+ DetailViewState,Dispatch,TempStorage,TempStorageKey,@@ -125,6 +126,21 @@ const isErrorDiagnosticsOpen = handleActions(false,);+export const SET_DETAIL_VIEW = "metabase/app/SET_DETAIL_VIEW";++export const setDetailView = createAction<DetailViewState | null>(+ SET_DETAIL_VIEW,+);++const detailView = handleActions(+ {+ [SET_DETAIL_VIEW]: {+ next: (_oldState, { payload: newState }) => newState,+ },+ },+ null,+);+const tempStorageSlice = createSlice({name: "tempStorage",initialState: {} as TempStorage,@@ -145,6 +161,7 @@ export const { setTempSetting } = tempStorageSlice.actions;// eslint-disable-next-line import/no-default-export -- deprecated usageexport default combineReducers({+ detailView,errorPage,isNavbarOpen,isDndAvailable: (initValue: unknown) => {diff --git a/frontend/src/metabase/routes.jsx b/frontend/src/metabase/routes.jsxindex 7308e753743..a9a3f09cb56 100644--- a/frontend/src/metabase/routes.jsx+++ b/frontend/src/metabase/routes.jsx@@ -30,6 +30,7 @@ import { DashboardMoveModalConnected } from "metabase/dashboard/components/Dashbimport { ArchiveDashboardModalConnected } from "metabase/dashboard/containers/ArchiveDashboardModal";import { AutomaticDashboardApp } from "metabase/dashboard/containers/AutomaticDashboardApp";import { DashboardApp } from "metabase/dashboard/containers/DashboardApp/DashboardApp";+import { TableDetailPage } from "metabase/detail-view/pages/TableDetailPage";import { ModalRoute } from "metabase/hoc/ModalRoute";import { Route } from "metabase/hoc/Title";import { HomePage } from "metabase/home/components/HomePage";@@ -317,6 +318,10 @@ export const getRoutes = (store) => {/></Route>+ <Route path="table">+ <Route path=":tableId/detail/:rowId" component={TableDetailPage} />+ </Route>+{/* INDIVIDUAL DASHBOARDS */}<Route path="/auto/dashboard/*" component={AutomaticDashboardApp} />diff --git a/frontend/src/metabase/selectors/app.ts b/frontend/src/metabase/selectors/app.tsindex aa567b8d49c..1c24c31dd4e 100644--- a/frontend/src/metabase/selectors/app.ts+++ b/frontend/src/metabase/selectors/app.ts@@ -78,6 +78,11 @@ export const getIsCollectionPathVisible = createSelector(return false;}+ const isModelDetail = /\/model\/.*\/detail\/.*/.test(path);+ if (isModelDetail) {+ return true;+ }+return (((question != null && question.isSaved()) ||dashboard != null ||@@ -202,6 +207,10 @@ export const getErrorPage = (state: State) => {return state.app.errorPage;};+export const getDetailViewState = (state: State) => {+ return state.app.detailView;+};+export const getErrorMessage = (state: State) => {const errorPage = getErrorPage(state);return errorPage?.data?.message || errorPage?.data;@@ -213,13 +222,23 @@ export const getCollectionId = createSelector(getDashboard,getDashboardId,(state) => PLUGIN_DOCUMENTS.getCurrentDocument(state),+ getDetailViewState,],- (question, dashboard, dashboardId, document) =>- document- ? document.collection_id- : dashboardId- ? dashboard?.collection_id- : question?.collectionId(),+ (question, dashboard, dashboardId, document, detailView) => {+ if (detailView) {+ return detailView.collectionId;+ }++ if (document) {+ return document.collection_id;+ }++ if (dashboardId) {+ return dashboard?.collection_id;+ }++ return question?.collectionId();+ },);export const getIsNavbarOpen: Selector<State, boolean> = createSelector(diff --git a/frontend/src/metabase/visualizations/components/ObjectDetail/ObjectDetail.unit.spec.tsx b/frontend/src/metabase/visualizations/components/ObjectDetail/ObjectDetail.unit.spec.tsxindex c43b5964b99..7fcc6d5e506 100644--- a/frontend/src/metabase/visualizations/components/ObjectDetail/ObjectDetail.unit.spec.tsx+++ b/frontend/src/metabase/visualizations/components/ObjectDetail/ObjectDetail.unit.spec.tsx@@ -11,8 +11,11 @@ import {getBrokenUpTextMatcher,renderWithProviders,screen,+ waitFor,+ waitForLoaderToBeRemoved,} from "__support__/ui";import { checkNotNull } from "metabase/lib/types";+import registerVisualizations from "metabase/visualizations/register";import type { Field } from "metabase-types/api";import { createMockCard, createMockDataset } from "metabase-types/api/mocks";import {@@ -29,6 +32,8 @@ import {import ObjectDetail from "./ObjectDetail";+registerVisualizations();+const PRODUCTS_TABLE = createProductsTable();const ORDERS_TABLE = createOrdersTable();const HIDDEN_ORDERS_TABLE = createOrdersTable({@@ -47,12 +52,14 @@ function setup({ hideOrdersTable = false }: SetupOpts = {}) {setupDatabasesEndpoints([]);setupActionsEndpoints([]);const productsId = checkNotNull(findField(PRODUCTS_TABLE.fields, "ID"));- const ordersProductId = checkNotNull(- findField(ORDERS_TABLE.fields, "PRODUCT_ID"),- );- const reviewsProductId = checkNotNull(- findField(REVIEWS_TABLE.fields, "PRODUCT_ID"),- );+ const ordersProductId = {+ ...checkNotNull(findField(ORDERS_TABLE.fields, "PRODUCT_ID")),+ table: ORDERS_TABLE,+ };+ const reviewsProductId = {+ ...checkNotNull(findField(REVIEWS_TABLE.fields, "PRODUCT_ID")),+ table: REVIEWS_TABLE,+ };setupTableEndpoints(PRODUCTS_TABLE, [{origin: ordersProductId,@@ -151,6 +158,11 @@ describe("ObjectDetail", () => {it("should render foreign key count when no table is hidden", async () => {setup();+ await waitFor(() => {+ expect(screen.getAllByTestId("loading-indicator")).toHaveLength(2);+ });+ await waitForLoaderToBeRemoved();+expect(await screen.findByText(getBrokenUpTextMatcher(@@ -170,6 +182,11 @@ describe("ObjectDetail", () => {it("should render related objects count only for foreign keys referencing non-hidden tables (metabase#32654)", async () => {setup({ hideOrdersTable: true });+ await waitFor(() => {+ expect(screen.getAllByTestId("loading-indicator")).toHaveLength(2);+ });+ await waitForLoaderToBeRemoved();+expect(await screen.findByText(getBrokenUpTextMatcher(diff --git a/frontend/src/metabase/visualizations/components/ObjectDetail/ObjectDetailWrapper.tsx b/frontend/src/metabase/visualizations/components/ObjectDetail/ObjectDetailWrapper.tsxindex 5f1ad9b8c62..eb43e43efc8 100644--- a/frontend/src/metabase/visualizations/components/ObjectDetail/ObjectDetailWrapper.tsx+++ b/frontend/src/metabase/visualizations/components/ObjectDetail/ObjectDetailWrapper.tsx@@ -1,13 +1,17 @@import { useState } from "react";+import { skipToken, useListTableForeignKeysQuery } from "metabase/api";+import { DetailViewSidesheet } from "metabase/detail-view/components";+import { filterByPk } from "metabase/detail-view/utils";import Question from "metabase-lib/v1/Question";+import { getColumnKey } from "metabase-lib/v1/queries/utils/column-key";import { PaginationFooter } from "../PaginationFooter/PaginationFooter";import { ObjectDetailView } from "./ObjectDetailView";import S from "./ObjectDetailWrapper.module.css";-import { RootModal } from "./ObjectDetailWrapper.styled";import type { ObjectDetailProps } from "./types";+import { getApiTable, getRowUrl } from "./utils";export function ObjectDetailWrapper({question,@@ -26,22 +30,58 @@ export function ObjectDetailWrapper({const getFallbackQuestion = () =>card && rest.metadata ? new Question(card, rest.metadata) : undefined;+ const { data: tableForeignKeys } = useListTableForeignKeysQuery(+ shouldShowModal && rest.table ? rest.table.id : skipToken,+ );++ const areImplicitActionsEnabled = Boolean(+ question &&+ question.canWrite() &&+ question.type() === "model" &&+ question.supportsImplicitActions(),+ );+if (shouldShowModal) {- return (- <RootModal- isOpen- onClose={closeObjectDetail}- className="" // need an empty className to override the Modal default width- >- <ObjectDetailView- {...rest}- showHeader- data={data}- question={question ?? getFallbackQuestion()}- closeObjectDetail={closeObjectDetail}+ const {+ canZoom,+ canZoomNextRow,+ canZoomPreviousRow,+ settings,+ table: tableWrapper,+ viewNextObjectDetail,+ viewPreviousObjectDetail,+ zoomedRow,+ zoomedRowID,+ } = rest;+ const table = getApiTable(tableWrapper);+ const columns = data?.cols;++ if (columns != null && zoomedRowID != null && question != null) {+ const columnsSettings = columns.map((column) => {+ return settings?.column_settings?.[getColumnKey(column)];+ });++ return (+ <DetailViewSidesheet+ columnSettings={settings?.["table.columns"]}+ columns={columns}+ columnsSettings={columnsSettings}+ query={filterByPk(question.query(), columns, zoomedRowID)}+ row={zoomedRow}+ rowId={zoomedRowID}+ showImplicitActions={areImplicitActionsEnabled}+ showNav={Boolean(canZoom && (canZoomNextRow || canZoomPreviousRow))}+ table={table}+ tableForeignKeys={tableForeignKeys}+ url={getRowUrl(question, columns, table, zoomedRowID)}+ onClose={closeObjectDetail}+ onNextClick={canZoomNextRow ? viewNextObjectDetail : undefined}+ onPreviousClick={+ canZoomPreviousRow ? viewPreviousObjectDetail : undefined+ }/>- </RootModal>- );+ );+ }}const hasPagination = data?.rows?.length > 1;diff --git a/frontend/src/metabase/visualizations/components/ObjectDetail/ObjectDetailWrapper.unit.spec.tsx b/frontend/src/metabase/visualizations/components/ObjectDetail/ObjectDetailWrapper.unit.spec.tsxindex 8e03dc80006..041e95a4439 100644--- a/frontend/src/metabase/visualizations/components/ObjectDetail/ObjectDetailWrapper.unit.spec.tsx+++ b/frontend/src/metabase/visualizations/components/ObjectDetail/ObjectDetailWrapper.unit.spec.tsx@@ -11,6 +11,7 @@ import { checkNotNull } from "metabase/lib/types";import { getMetadata } from "metabase/selectors/metadata";import { ObjectDetailWrapper } from "metabase/visualizations/components/ObjectDetail/ObjectDetailWrapper";import type { ObjectDetailProps } from "metabase/visualizations/components/ObjectDetail/types";+import registerVisualizations from "metabase/visualizations/register";import { createMockCard } from "metabase-types/api/mocks";import { createProductsTable } from "metabase-types/api/mocks/presets";import {@@ -18,6 +19,8 @@ import {createMockState,} from "metabase-types/store/mocks";+registerVisualizations();+const DATABASE_ID = 1;const MOCK_TABLE = createProductsTable();@@ -115,11 +118,11 @@ describe("Object Detail Wrapper", () => {// first tab should focus on the close button, since there's only// one element to show here.await userEvent.tab();- expect(screen.getByTestId("object-detail-close-button")).toHaveFocus();+ expect(screen.getByLabelText("Close")).toHaveFocus();- // second tab should *keep* focus on the close button, not go+ // second tab should *keep* focus inside the modal, not go// to the bodyawait userEvent.tab();- expect(screen.getByTestId("object-detail-close-button")).toHaveFocus();+ expect(screen.getByLabelText("Copy link to this record")).toHaveFocus();});});diff --git a/frontend/src/metabase/visualizations/components/ObjectDetail/utils.ts b/frontend/src/metabase/visualizations/components/ObjectDetail/utils.tsindex 221ae08040e..0cbabf89644 100644--- a/frontend/src/metabase/visualizations/components/ObjectDetail/utils.ts+++ b/frontend/src/metabase/visualizations/components/ObjectDetail/utils.ts@@ -15,6 +15,7 @@ import {isPK,} from "metabase-lib/v1/types/utils/isa";import type {+ Table as ApiTable,DatasetColumn,DatasetData,TableId,@@ -174,3 +175,41 @@ export const isValidImplicitDeleteAction = (action: WritebackAction): boolean =>export const isValidImplicitUpdateAction = (action: WritebackAction): boolean =>isImplicitUpdateAction(action) && !action.archived;++export function getApiTable(+ table: Table | undefined | null,+): ApiTable | undefined {+ if (!table) {+ return undefined;+ }++ const apiTable: ApiTable = {+ ...table.getPlainObject(),+ fields: table.original_fields,+ } as ApiTable;++ return apiTable;+}++export function getRowUrl(+ question: Question,+ columns: DatasetColumn[],+ table: ApiTable | undefined,+ rowId: string | number,+): string | undefined {+ const pks = columns.filter(isPK);++ if (pks.length !== 1) {+ return undefined;+ }++ if (question.type() === "model") {+ return `/model/${question.slug()}/detail/${rowId}`;+ }++ if (typeof table?.id === "number") {+ return `/table/${table.id}/detail/${rowId}`;+ }++ return undefined;+}diff --git a/frontend/src/metabase/visualizations/components/TableInteractive/TableInteractive.tsx b/frontend/src/metabase/visualizations/components/TableInteractive/TableInteractive.tsxindex fc0a9163d2b..fa22ef71122 100644--- a/frontend/src/metabase/visualizations/components/TableInteractive/TableInteractive.tsx+++ b/frontend/src/metabase/visualizations/components/TableInteractive/TableInteractive.tsx@@ -101,6 +101,7 @@ interface TableProps extends VisualizationProps {scrollToLastColumn?: boolean;theme: MantineTheme;renderEmptyMessage?: boolean;+ zoomedRowIndex?: number;getColumnTitle: (columnIndex: number) => string;getColumnSortDirection: (columnIndex: number) => OrderByDirection | undefined;renderTableHeader: HeaderCellWithColumnInfoProps["renderTableHeader"];@@ -165,6 +166,7 @@ export const TableInteractiveInner = forwardRef(function TableInteractiveInner(getColumnSortDirection: getServerColumnSortDirection,onVisualizationClick,onUpdateVisualizationSettings,+ zoomedRowIndex,}: TableProps,ref: Ref<HTMLDivElement>,) {@@ -611,7 +613,7 @@ export const TableInteractiveInner = forwardRef(function TableInteractiveInner([cols, isDashcardViewTable, onUpdateVisualizationSettings, settings],);- const rowId: RowIdColumnOptions | undefined = useMemo(() => {+ const rowId = useMemo<RowIdColumnOptions | undefined>(() => {const getBackgroundColor = memoize((rowIndex: number) =>settings["table._cell_background_getter"]?.(null, rowIndex),);@@ -641,6 +643,7 @@ export const TableInteractiveInner = forwardRef(function TableInteractiveInner(? {variant: "index",getBackgroundColor,+ expandedIndex: undefined,}: undefined;}@@ -648,6 +651,7 @@ export const TableInteractiveInner = forwardRef(function TableInteractiveInner(return {variant: shouldShowRowIndex ? "indexExpand" : "expandButton",getBackgroundColor,+ expandedIndex: zoomedRowIndex,};}, [cols,@@ -657,6 +661,7 @@ export const TableInteractiveInner = forwardRef(function TableInteractiveInner(settings,isDashboard,isDocument,+ zoomedRowIndex,]);const backgroundColor = useMemo(() => {@@ -806,6 +811,7 @@ export const TableInteractiveInner = forwardRef(function TableInteractiveInner(showRowsCount={isDashboard}isColumnReorderingDisabled={isColumnReorderingDisabled}emptyState={emptyState}+ zoomedRowIndex={zoomedRowIndex}onBodyCellClick={handleBodyCellClick}onAddColumnClick={handleAddColumnButtonClick}onHeaderCellClick={handleHeaderCellClick}diff --git a/frontend/src/metabase/visualizations/components/TableInteractive/hooks/use-object-detail.ts b/frontend/src/metabase/visualizations/components/TableInteractive/hooks/use-object-detail.tsindex e90ad2244b7..d3b52ec741a 100644--- a/frontend/src/metabase/visualizations/components/TableInteractive/hooks/use-object-detail.ts+++ b/frontend/src/metabase/visualizations/components/TableInteractive/hooks/use-object-detail.ts@@ -1,15 +1,24 @@import { useCallback, useMemo } from "react";import { useDispatch, useSelector } from "metabase/lib/redux";-import { zoomInRow } from "metabase/query_builder/actions";-import { getRowIndexToPKMap } from "metabase/query_builder/selectors";+import { resetRowZoom, zoomInRow } from "metabase/query_builder/actions";+import {+ getRowIndexToPKMap,+ getZoomedObjectId,+} from "metabase/query_builder/selectors";import type { ObjectId } from "metabase/visualizations/components/ObjectDetail/types";import type { ColumnDescriptor } from "metabase/visualizations/lib/graph/columns";import { isPK } from "metabase-lib/v1/types/utils/isa";import type { DatasetData } from "metabase-types/api";+import type { State } from "metabase-types/store";++const getZoomedObjectIdSafe = (state: State) => {+ return state.qb ? getZoomedObjectId(state) : undefined;+};export const useObjectDetail = ({ rows, cols }: DatasetData) => {const dispatch = useDispatch();+ const zoomedObjectId = useSelector(getZoomedObjectIdSafe);const rowIndexToPkMap: Record<number, ObjectId> = useSelector((state) =>state.qb != null ? getRowIndexToPKMap(state) : {},);@@ -42,9 +51,13 @@ export const useObjectDetail = ({ rows, cols }: DatasetData) => {objectId = rowIndexToPkMap?.[rowIndex] ?? rowIndex;}- dispatch(zoomInRow({ objectId }));+ if (objectId === zoomedObjectId) {+ dispatch(resetRowZoom());+ } else {+ dispatch(zoomInRow({ objectId }));+ }},- [dispatch, primaryKeyColumn, rowIndexToPkMap, rows],+ [dispatch, primaryKeyColumn, rowIndexToPkMap, rows, zoomedObjectId],);return onOpenObjectDetail;diff --git a/frontend/src/metabase/visualizations/components/Visualization/Visualization.tsx b/frontend/src/metabase/visualizations/components/Visualization/Visualization.tsxindex 94e0580ca48..ab6f2c1d579 100644--- a/frontend/src/metabase/visualizations/components/Visualization/Visualization.tsx+++ b/frontend/src/metabase/visualizations/components/Visualization/Visualization.tsx@@ -1,6 +1,6 @@/* eslint-disable complexity */import cx from "classnames";-import {+import React, {type CSSProperties,type ComponentType,type ErrorInfo,@@ -9,7 +9,6 @@ import {type Ref,forwardRef,} from "react";-import React from "react";import { t } from "ttag";import _ from "underscore";@@ -166,6 +165,7 @@ type VisualizationOwnProps = {tc?: ContentTranslationFunction;uuid?: string;token?: string;+ zoomedRowIndex?: number;onOpenChartSettings?: (data: {initialChartSettings: { section: string };showSidebarTitle?: boolean;@@ -632,6 +632,7 @@ class Visualization extends PureComponent<onUpdateVisualizationSettings = () => {},onUpdateWarnings,titleMenuItems,+ zoomedRowIndex,} = this.props;const { width, height } = this.getNormalizedSizes();@@ -815,7 +816,7 @@ class Visualization extends PureComponent<<divdata-card-key={getCardKey(series[0].card?.id)}className={cx(CS.flex, CS.flexColumn, CS.flexFull)}- style={{ position: "relative" }}+ style={{ position: hasDevWatermark ? "relative" : undefined }}><VisualizationRenderedWrapperonRendered={this.handleVisualizationRendered}@@ -878,6 +879,7 @@ class Visualization extends PureComponent<width={rawWidth}uuid={uuid}token={token}+ zoomedRowIndex={zoomedRowIndex}onActionDismissal={this.hideActions}onChangeCardAndRun={this.props.onChangeCardAndRundiff --git a/frontend/src/metabase/visualizations/types/visualization.ts b/frontend/src/metabase/visualizations/types/visualization.tsindex bd404c260b4..b6456f14d5d 100644--- a/frontend/src/metabase/visualizations/types/visualization.ts+++ b/frontend/src/metabase/visualizations/types/visualization.ts@@ -193,6 +193,7 @@ export type VisualizationPassThroughProps = {isObjectDetail?: boolean;isQueryBuilder?: boolean;queryBuilderMode?: QueryBuilderMode;+ zoomedRowIndex?: number;onDeselectTimelineEvents?: () => void;onOpenTimelines?: () => void;onSelectTimelineEvents?: (timelineEvents: TimelineEvent[]) => void;diff --git a/frontend/test/__support__/metadata.ts b/frontend/test/__support__/metadata.tsindex 265af943a8d..bb9a48cbc17 100644--- a/frontend/test/__support__/metadata.ts+++ b/frontend/test/__support__/metadata.ts@@ -9,7 +9,7 @@ import type { EntitiesStateOpts } from "./store";import { createMockEntitiesState } from "./store";export function createMockMetadata(- entities: EntitiesStateOpts,+ entities: EntitiesStateOpts = {},settings?: Settings,) {const state = createMockState({