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
Provide custom name for Metric Math expression (#72586)
Denis Berezin0a6b688d0981
diff --git a/e2e/test/scenarios/metrics/metrics-explorer.cy.spec.ts b/e2e/test/scenarios/metrics/metrics-explorer.cy.spec.tsindex 4b399449e50..2510a4dc8b9 100644--- a/e2e/test/scenarios/metrics/metrics-explorer.cy.spec.ts+++ b/e2e/test/scenarios/metrics/metrics-explorer.cy.spec.ts@@ -120,25 +120,38 @@ const SNAPSHOT_NAME = "metrics-explorer-snapshot";/*** Add a metric or measure to the explorer via the search panel*/-const addMetric = (name: string) => {+const addMetric = (name: string, runExpression: boolean = true) => {// for some reason `type` clicks in the middle of the input first// so we use `{end}` to make sure we type at the end- H.MetricsViewer.searchInput().type(`{end}, ${name}`);+ H.MetricsViewer.searchInput().type(`{end}, ${name}`, {+ waitForAnimations: true,+ });H.MetricsViewer.searchResults().findByText(name).click();- H.MetricsViewer.runButton().click();+ if (runExpression) {+ H.MetricsViewer.runButton().click();+ }};-const addMetricMath = (expression: ({ metricName: string } | string)[]) => {+const addMetricMath = (+ expression: ({ metricName: string } | string)[],+ runExpression: boolean = true,+) => {H.MetricsViewer.searchInput().type("{end}, ");for (const item of expression) {if (typeof item === "string") {- H.MetricsViewer.searchInput().type(`{end}${item}`);+ H.MetricsViewer.searchInput().type(`{end}${item}`, {+ waitForAnimations: true,+ });} else {- H.MetricsViewer.searchInput().type(`{end}${item.metricName}`);+ H.MetricsViewer.searchInput().type(`{end}${item.metricName}`, {+ waitForAnimations: true,+ });H.MetricsViewer.searchResults().findByText(item.metricName).click();}}- H.MetricsViewer.runButton().click();+ if (runExpression) {+ H.MetricsViewer.runButton().click();+ }};/**@@ -150,7 +163,7 @@ const selectBreakout = (index = 0,binning?: string,) => {- H.MetricsViewer.searchBarPills().contains(cardname).rightclick();+ H.MetricsViewer.searchBarPills().contains(cardname).click();H.popover().findByText("Break out").click();const breakout = H.popover().findAllByText(dimensionName)@@ -180,6 +193,19 @@ const verifyMetricCount = (count: number) => {H.MetricsViewer.searchBarPills().should("have.length", count);};+/**+ * Open the rename flow on an expression pill by clicking it and then the+ * "Rename" menu item that appears in the action menu.+ */+const openExpressionRename = (pillIndex: number) => {+ H.MetricsViewer.searchBarPills()+ .should("have.length.at.least", pillIndex + 1)+ .eq(pillIndex)+ .click();++ H.popover().findByRole("menuitem", { name: "rename icon Rename" }).click();+};+/*** Switch to a specific tab*/@@ -198,26 +224,39 @@ const rgbToHex = (rgb: string): string => {* Get hex color(s) from a search bar pill's color indicator.* Returns an array of hex color strings.*/+const DEFAULT_PLACEHOLDER_COLOR = "#071722";++const readColorsFromIndicator = ($pill: JQuery): string[] => {+ const colors: string[] = [];+ $pill+ .find("[data-testid='color-indicator-container']")+ .children()+ .each((_i, el) => {+ const $el = Cypress.$(el);+ // Multi-dot: backgroundColor is set; single icon: color is set+ const bg = $el.css("background-color");+ const fg = $el.css("color");+ const raw =+ bg && bg !== "rgba(0, 0, 0, 0)" && bg !== "transparent" ? bg : fg;+ colors.push(rgbToHex(raw));+ });+ return colors;+};+const getPillColors = (pillIndex: number): Cypress.Chainable<string[]> => {// eslint-disable-next-line metabase/no-unsafe-element-filteringreturn H.MetricsViewer.searchBarPills().should("have.length.greaterThan", pillIndex).eq(pillIndex)- .findByTestId("color-indicator-container")- .children()- .then(($children) => {- const colors: string[] = [];- $children.each((_i, el) => {- const $el = Cypress.$(el);- // Multi-dot: backgroundColor is set; single icon: color is set- const bg = $el.css("background-color");- const fg = $el.css("color");- const raw =- bg && bg !== "rgba(0, 0, 0, 0)" && bg !== "transparent" ? bg : fg;- colors.push(rgbToHex(raw));- });- return colors;- });+ .should(($pill) => {+ const colors = readColorsFromIndicator($pill);+ expect(colors.length, "pill should have at least one color").to.be.gt(0);+ expect(+ colors.every((c) => c === DEFAULT_PLACEHOLDER_COLOR),+ "pill colors should not all be the default placeholder color",+ ).to.be.false;+ })+ .then(($pill) => readColorsFromIndicator($pill));};/**@@ -305,7 +344,7 @@ describe("scenarios > metrics > explorer", () => {H.MetricsViewer.goToViewer();addMetric("Count of orders");- H.MetricsViewer.searchBarPills().contains("Count of orders").rightclick();+ H.MetricsViewer.searchBarPills().contains("Count of orders").click();H.popover().should("not.contain", "Edit in Data Studio");});@@ -368,7 +407,7 @@ describe("scenarios > metrics > explorer", () => {);});- it("Should not show me metrics that live in collections I do not have permissions to see", () => {+ it("should not show me metrics that live in collections I do not have permissions to see", () => {cy.signIn("nocollection");H.MetricsViewer.goToViewer();H.MetricsViewer.searchInput().type("Count of");@@ -381,7 +420,7 @@ describe("scenarios > metrics > explorer", () => {H.MetricsViewer.searchResults().should("contain.text", "Test Measure");});- it("Should not show me measures that live in tables I do not have permissions to see", () => {+ it("should not show me measures that live in tables I do not have permissions to see", () => {cy.signIn("nodata");H.MetricsViewer.goToViewer();H.MetricsViewer.searchInput().type("Test Measure");@@ -432,7 +471,7 @@ describe("scenarios > metrics > explorer", () => {.children().should("have.length", 5);- H.MetricsViewer.searchBarPills().contains("Count of orders").rightclick();+ H.MetricsViewer.searchBarPills().contains("Count of orders").click();H.popover().findByText("Change breakout").click();H.popover().findByText("Category").click();@@ -440,7 +479,7 @@ describe("scenarios > metrics > explorer", () => {.findByRole("heading", { name: /Category/ }).should("be.visible");- H.MetricsViewer.searchBarPills().contains("Count of orders").rightclick();+ H.MetricsViewer.searchBarPills().contains("Count of orders").click();H.popover().findByText("Remove breakout").click();H.MetricsViewer.breakoutLegend().should("not.exist");});@@ -492,21 +531,16 @@ describe("scenarios > metrics > explorer", () => {"Expand formula editor and create expression with second metric instance",);cy.findByTestId("metrics-formula-input").click();- H.MetricsViewer.searchInput().type(", Count of orders");- H.MetricsViewer.searchResults().findByText("Count of orders").click();- cy.wait("@getMetric");-- H.MetricsViewer.searchInput().type(" + Count of products");-- H.MetricsViewer.searchResults().findByText("Count of products").click();- cy.wait("@getMetric");-- H.MetricsViewer.searchInput().type(", Count of orders");- H.MetricsViewer.searchResults().findByText("Count of orders").click();- cy.wait("@getMetric");-- cy.findByTestId("run-expression-button").click();+ addMetricMath(+ [+ { metricName: "Count of orders" },+ "+",+ { metricName: "Count of products" },+ ],+ false,+ );+ addMetric("Count of orders");cy.wait("@dataset");cy.log("Should have 2 metric pills (expression pill is separate)");@@ -528,7 +562,7 @@ describe("scenarios > metrics > explorer", () => {assertPillColorsInChart(2);cy.log("Apply breakout to first instance of Count of orders");- H.MetricsViewer.searchBarPills().eq(0).rightclick();+ H.MetricsViewer.searchBarPills().eq(0).click();H.popover().findByText("Break out").click();H.popover().findByText("Source").click();cy.wait("@dataset");@@ -572,7 +606,7 @@ describe("scenarios > metrics > explorer", () => {assertLegendColorsMatchPill(0);cy.log("Apply breakout to second instance of Count of orders");- H.MetricsViewer.searchBarPills().eq(2).rightclick();+ H.MetricsViewer.searchBarPills().eq(2).click();H.popover().findByText("Break out").click();H.popover().findByText("Source").click();cy.wait("@dataset");@@ -603,7 +637,7 @@ describe("scenarios > metrics > explorer", () => {});cy.log("Remove breakout from first instance");- H.MetricsViewer.searchBarPills().eq(0).rightclick();+ H.MetricsViewer.searchBarPills().eq(0).click();H.popover().findByText("Remove breakout").click();cy.log(@@ -645,7 +679,7 @@ describe("scenarios > metrics > explorer", () => {H.MetricsViewer.searchBarPills().should("have.length", 2);cy.log("Apply breakout to first instance of Count of orders");- H.MetricsViewer.searchBarPills().eq(0).rightclick();+ H.MetricsViewer.searchBarPills().eq(0).click();H.popover().findByText("Break out").click();H.popover().findByText("Source").click();cy.wait("@dataset");@@ -725,8 +759,17 @@ describe("scenarios > metrics > explorer", () => {{ metricName: "Test Measure" },]);cy.wait("@dataset");- H.MetricsViewer.searchBarPills().eq(1).rightclick();- H.popover({ skipVisibilityCheck: true }).should("not.exist");++ cy.log("Expression pill menu only offers Rename, no breakout options");+ H.MetricsViewer.searchBarPills().eq(1).click();+ H.popover().within(() => {+ cy.findByRole("menuitem", { name: "rename icon Rename" }).should(+ "exist",+ );+ cy.findByText(/Break out/).should("not.exist");+ cy.findByText(/Change breakout/).should("not.exist");+ cy.findByText(/Remove breakout/).should("not.exist");+ });});it("should show an expression dimension pill with per-metric accordion", () => {@@ -873,6 +916,321 @@ describe("scenarios > metrics > explorer", () => {});});+ // ============================================================================+ // Expression Custom Names+ // ============================================================================++ describe("Expression custom names", () => {+ beforeEach(() => {+ interceptDatasetQuery();+ H.MetricsViewer.goToViewer();+ addMetric("Count of orders");+ cy.wait("@dataset");+ });++ it("should allow setting a custom name on an expression pill", () => {+ addMetricMath([+ { metricName: "Count of orders" },+ "+",+ { metricName: "Test Measure" },+ ]);+ cy.wait("@dataset");++ cy.log("Click the expression pill to open name editor");+ H.MetricsViewer.searchBarPills()+ .should("have.length", 2)+ .eq(1)+ .should("contain.text", "Count of orders");+ openExpressionRename(1);++ cy.log("Type a custom name");+ cy.findByTestId("expression-name-input")+ .should("be.focused")+ .clear()+ .type("My Custom Expression{enter}");++ cy.log("Pill should display the custom name");+ H.MetricsViewer.searchBarPills()+ .should("have.length", 2)+ .eq(1)+ .should("contain.text", "My Custom Expression");++ cy.log("Add breakout on the first metric to trigger the legend");+ selectBreakout("Count of orders", "Source");+ cy.wait("@dataset");++ cy.log("Legend should display the custom expression name");+ H.MetricsViewer.breakoutLegend().within(() => {+ cy.findAllByText("My Custom Expression")+ .should("exist")+ .should("have.length", 2);+ cy.findByText(/Test Measure/).should("not.exist");+ });++ cy.log("Chart tooltip should display the custom name");+ H.cartesianChartCircle()+ .should("have.length.at.least", 4)+ .eq(4)+ .trigger("mousemove", { force: true });+ H.echartsTooltip().within(() => {+ cy.findByText("My Custom Expression").should("exist");+ cy.findByText(/Test Measure/).should("not.exist");+ });+ });++ it("should revert to formula text when custom name is cleared", () => {+ addMetricMath([+ { metricName: "Count of orders" },+ "+",+ { metricName: "Test Measure" },+ ]);+ cy.wait("@dataset");++ cy.log("Set a custom name");+ H.MetricsViewer.searchBarPills().should("have.length", 2);+ openExpressionRename(1);+ cy.findByTestId("expression-name-input")+ .clear()+ .type("Temporary Name{enter}");++ H.MetricsViewer.searchBarPills()+ .should("have.length", 2)+ .eq(1)+ .should("contain.text", "Temporary Name");++ cy.log("Clear the custom name");+ H.MetricsViewer.searchBarPills().should("have.length", 2);+ openExpressionRename(1);+ cy.findByTestId("expression-name-input").clear().type("{enter}");++ cy.log(+ "Pill should revert to formula-derived text (contains metric names)",+ );+ H.MetricsViewer.searchBarPills()+ .should("have.length", 2)+ .eq(1)+ .should("not.contain.text", "Temporary Name")+ .should("contain.text", "Count of orders");++ cy.log("Add breakout on the first metric to trigger the legend");+ selectBreakout("Count of orders", "Source");+ cy.wait("@dataset");++ cy.log(+ "Legend should use the formula-derived name, not the old custom name",+ );+ H.MetricsViewer.breakoutLegend().within(() => {+ cy.findByText("Temporary Name").should("not.exist");+ cy.findAllByText("Count of orders + Test Measure")+ .should("exist")+ .should("have.length", 2);+ });++ cy.log(+ "Tooltip should use the formula-derived name, not the old custom name",+ );+ H.cartesianChartCircle()+ .should("have.length.at.least", 4)+ .eq(4)+ .trigger("mousemove", { force: true });+ H.echartsTooltip().within(() => {+ cy.findByText("Temporary Name").should("not.exist");+ cy.findByText("Count of orders + Test Measure").should("exist");+ });+ });++ it("should preserve custom name when re-running with the same expression", () => {+ addMetricMath([+ { metricName: "Count of orders" },+ "+",+ { metricName: "Test Measure" },+ ]);+ cy.wait("@dataset");++ cy.log("Set a custom name on the expression pill");+ H.MetricsViewer.searchBarPills().should("have.length", 2);+ openExpressionRename(1);+ cy.findByTestId("expression-name-input")+ .clear()+ .type("My Stable Name{enter}");++ H.MetricsViewer.searchBarPills()+ .should("have.length", 2)+ .eq(1)+ .should("contain.text", "My Stable Name");++ cy.log("Enter formula mode and re-run the expression");+ addMetric("Count of products");+ cy.wait("@dataset");++ cy.log("Custom name should still be preserved");+ H.MetricsViewer.searchBarPills()+ .should("have.length", 3)+ .eq(1)+ .should("contain.text", "My Stable Name");++ cy.log("Tooltip should display the preserved custom name");+ H.cartesianChartCircle()+ .should("have.length.at.least", 4)+ .eq(4)+ .trigger("mousemove", { force: true });+ H.echartsTooltip().within(() => {+ cy.findByText("My Stable Name").should("exist");+ cy.findByText(/Test Measure/).should("not.exist");+ });+ });++ it("should not change expression pill color when renaming", () => {+ addMetricMath([+ { metricName: "Count of orders" },+ "+",+ { metricName: "Test Measure" },+ ]);+ cy.wait("@dataset");++ cy.log("Capture the expression pill color before renaming");+ const expressionPillIndex = 1;+ getPillColors(expressionPillIndex).then((colorsBefore) => {+ cy.log("Set a custom name on the expression pill");+ H.MetricsViewer.searchBarPills().should("have.length", 2);+ openExpressionRename(1);+ cy.findByTestId("expression-name-input")+ .clear()+ .type("Renamed Expression{enter}", { waitForAnimations: true });++ H.MetricsViewer.searchBarPills()+ .should("have.length", 2)+ .eq(1)+ .should("contain.text", "Renamed Expression");++ cy.log("Verify the pill color has not changed after renaming");+ getPillColors(expressionPillIndex).then((colorsAfter) => {+ expect(colorsAfter).to.deep.equal(colorsBefore);+ });+ });+ });++ it("should preserve custom name when the expression is edited in place but keeps at least one original metric", () => {+ addMetricMath([+ { metricName: "Count of orders" },+ "+",+ { metricName: "Test Measure" },+ ]);+ cy.wait("@dataset");++ cy.log("Set a custom name on the expression pill");+ H.MetricsViewer.searchBarPills().should("have.length", 2);+ openExpressionRename(1);+ cy.findByTestId("expression-name-input")+ .clear()+ .type("Preserved Name{enter}");++ H.MetricsViewer.searchBarPills()+ .should("have.length", 2)+ .eq(1)+ .should("contain.text", "Preserved Name");++ cy.log(+ "Edit in place: delete '+ Test Measure' from the end of the expression " ++ "while keeping the 'Count of orders' token intact, then append a new operand. " ++ "The surviving identity carries the custom name.",+ );+ cy.findByTestId("metrics-formula-input").click();+ // Cursor at end → one {backspace} deletes the atomic "Test Measure"+ // token, the next three delete " + " char-by-char. The first metric+ // token in the expression ("Count of orders") is untouched and its+ // MetricIdentity (with customName) survives.+ H.MetricsViewer.searchInput().type(+ "{end}{backspace}{backspace}{backspace}{backspace} * Count of products",+ { waitForAnimations: true },+ );+ H.MetricsViewer.searchResults().findByText("Count of products").click();+ H.MetricsViewer.runButton().click();+ cy.wait("@dataset");++ cy.log(+ "The expression now reads 'Count of orders * Count of products' " ++ "and keeps the user-assigned name because one identity survived.",+ );+ H.MetricsViewer.searchBarPills()+ .should("have.length", 2)+ .eq(1)+ .should("contain.text", "Preserved Name");+ });++ it("should keep each expression's own name when an earlier expression is removed", () => {+ // Regression: names used to shift up by ordinal position, so deleting+ // the first expression made the second one inherit "First Name".+ // Now names are bound to identities — the surviving expression keeps+ // its own "Second Name".+ cy.log("Build two separately-named expressions");+ cy.findByTestId("metrics-formula-input").click();+ H.MetricsViewer.searchInput().clear();+ addMetricMath([+ { metricName: "Count of orders" },+ "+",+ { metricName: "Test Measure" },+ ]);+ cy.wait("@dataset");++ H.MetricsViewer.searchBarPills().should("have.length", 1);+ openExpressionRename(0);+ cy.findByTestId("expression-name-input")+ .clear()+ .type("First Name{enter}");+ H.MetricsViewer.searchBarPills()+ .eq(0)+ .should("contain.text", "First Name");++ cy.findByTestId("metrics-formula-input").click();+ addMetricMath([+ { metricName: "Count of orders" },+ "+",+ { metricName: "Test Measure" },+ ]);+ cy.wait("@dataset");++ H.MetricsViewer.searchBarPills().should("have.length", 2);+ openExpressionRename(1);+ cy.findByTestId("expression-name-input")+ .clear()+ .type("Second Name{enter}");+ H.MetricsViewer.searchBarPills()+ .eq(0)+ .should("contain.text", "First Name");+ H.MetricsViewer.searchBarPills()+ .eq(1)+ .should("contain.text", "Second Name");++ cy.log(+ "Delete the first expression in place (atomic-range-aware {del} " ++ "sequence). The second expression's identities — and therefore " ++ "its custom name — are preserved by CodeMirror's range tracking.",+ );+ cy.findByTestId("metrics-formula-input").click();+ // text: "Count of orders + Test Measure, Count of orders + Test Measure"+ // cursor at {home} = 0. Seven forward-deletes remove, in order:+ // "Count of orders" (atomic), " ", "+", " ", "Test Measure" (atomic),+ // ",", " ". What remains is exactly the second expression.+ H.MetricsViewer.searchInput().type(+ "{home}{del}{del}{del}{del}{del}{del}{del}",+ { waitForAnimations: true },+ );+ H.MetricsViewer.runButton().click();+ cy.wait("@dataset");++ cy.log(+ "The surviving expression must keep its own 'Second Name' and " ++ "must NOT inherit 'First Name' from the removed expression.",+ );+ H.MetricsViewer.searchBarPills()+ .should("have.length", 1)+ .eq(0)+ .should("contain.text", "Second Name")+ .should("not.contain.text", "First Name");+ });+ });+// ============================================================================// Tabs// ============================================================================@@ -1378,7 +1736,7 @@ describe("scenarios > metrics > explorer", () => {H.MetricsViewer.getAllFilterPills().should("have.length", 0);});- it("Should allow me to apply filters to each metric individually", () => {+ it("should allow me to apply filters to each metric individually", () => {addMetric("Count of products");switchToTab("Category");H.MetricsViewer.changeVizType("line");@@ -1646,6 +2004,7 @@ describe("scenarios > metrics > explorer", () => {addMetric("Count of orders");cy.wait("@dataset");});+it("should apply filters and dimensions to individual metric instances within expressions", () => {selectBreakout("Count of orders", "Category");cy.wait("@dataset");@@ -1741,10 +2100,7 @@ describe("scenarios > metrics > explorer", () => {});cy.log("Add numeric metric '123' as standalone");- cy.findByTestId("metrics-formula-input").click();- H.MetricsViewer.searchInput().type(`, ${NUMERIC_METRIC_NAME}`);- H.MetricsViewer.searchResults().findByText(NUMERIC_METRIC_NAME).click();- H.MetricsViewer.runButton().click();+ addMetric("123");cy.wait("@dataset");cy.log("Sum metric '123' with itself — both selected from dropdown");@@ -1765,10 +2121,7 @@ describe("scenarios > metrics > explorer", () => {H.MetricsViewer.getMetricVisualization().should("exist");cy.log("Append metric '123' as standalone — selected from dropdown");- cy.findByTestId("metrics-formula-input").click();- H.MetricsViewer.searchInput().type(`, ${NUMERIC_METRIC_NAME}`);- H.MetricsViewer.searchResults().findByText(NUMERIC_METRIC_NAME).click();- H.MetricsViewer.runButton().click();+ addMetric("123");cy.wait("@dataset");H.MetricsViewer.getMetricVisualization().should("exist");diff --git a/frontend/src/metabase/common/components/SourceColorIndicator/SourceColorIndicator.tsx b/frontend/src/metabase/common/components/SourceColorIndicator/SourceColorIndicator.tsxindex 4d10584fbe8..8b217a9c497 100644--- a/frontend/src/metabase/common/components/SourceColorIndicator/SourceColorIndicator.tsx+++ b/frontend/src/metabase/common/components/SourceColorIndicator/SourceColorIndicator.tsx@@ -43,13 +43,15 @@ export function SourceColorIndicator({);}return (- <Box- className={S.colorDot}- w={size}- h={size}- style={{- backgroundColor: color,- }}- />+ <Flex align="center" data-testid="color-indicator-container">+ <Box+ className={S.colorDot}+ w={size}+ h={size}+ style={{+ backgroundColor: color,+ }}+ />+ </Flex>);}diff --git a/frontend/src/metabase/metrics-viewer/components/DimensionPillBar/ExpressionDimensionPill.tsx b/frontend/src/metabase/metrics-viewer/components/DimensionPillBar/ExpressionDimensionPill.tsxindex 21a843dcd1c..e28b065c927 100644--- a/frontend/src/metabase/metrics-viewer/components/DimensionPillBar/ExpressionDimensionPill.tsx+++ b/frontend/src/metabase/metrics-viewer/components/DimensionPillBar/ExpressionDimensionPill.tsx@@ -27,7 +27,8 @@ import type {} from "./DimensionPillBar";import S from "./ExpressionDimensionPill.module.css";-const LIST_WIDTH = "20rem";+const SINGLE_METRIC_LIST_WIDTH = "15rem";+const MULTI_METRIC_LIST_WIDTH = "20rem";interface ExpressionDimensionPillProps {item: ExpressionDimensionItem;@@ -115,7 +116,7 @@ export function ExpressionDimensionPill({<Popover.Dropdownpx={0}py="xs"- w={LIST_WIDTH}+ w={isSingleMetric ? SINGLE_METRIC_LIST_WIDTH : MULTI_METRIC_LIST_WIDTH}mah={300}className={S.dropdown}>@@ -175,7 +176,7 @@ function SingleMetricContent({itemIsSelected={itemIsSelected}alwaysExpandedmaxHeight={Infinity}- width={240}+ width={SINGLE_METRIC_LIST_WIDTH}/>);}diff --git a/frontend/src/metabase/metrics-viewer/components/MetricSearch/MetricExpressionPill/MetricExpressionPill.module.css b/frontend/src/metabase/metrics-viewer/components/MetricSearch/MetricExpressionPill/MetricExpressionPill.module.cssindex 9ab785abec9..f65b1dabda0 100644--- a/frontend/src/metabase/metrics-viewer/components/MetricSearch/MetricExpressionPill/MetricExpressionPill.module.css+++ b/frontend/src/metabase/metrics-viewer/components/MetricSearch/MetricExpressionPill/MetricExpressionPill.module.css@@ -2,6 +2,7 @@background-color: var(--mb-color-background-primary);border: 1px solid var(--mb-color-border);border-radius: var(--default-border-radius);+ cursor: pointer;transition: background-color 150ms ease;max-width: 100%;}@@ -13,3 +14,22 @@.expressionText {white-space: pre-wrap;}++.editableName:not([data-css-specificity-hack="🪗"]) {+ padding: 0;+ border: none;+ font-size: inherit;+ font-weight: inherit;+ line-height: 1.375rem !important;+ min-width: 2rem;++ &:hover,+ &:focus-within {+ border-color: transparent;+ }++ textarea {+ white-space: nowrap;+ cursor: text;+ }+}diff --git a/frontend/src/metabase/metrics-viewer/components/MetricSearch/MetricExpressionPill/MetricExpressionPill.tsx b/frontend/src/metabase/metrics-viewer/components/MetricSearch/MetricExpressionPill/MetricExpressionPill.tsxindex 7840fc1c5a9..7f1f020bae0 100644--- a/frontend/src/metabase/metrics-viewer/components/MetricSearch/MetricExpressionPill/MetricExpressionPill.tsx+++ b/frontend/src/metabase/metrics-viewer/components/MetricSearch/MetricExpressionPill/MetricExpressionPill.tsx@@ -1,10 +1,16 @@+import { useCallback, useEffect, useMemo, useRef, useState } from "react";import { t } from "ttag";+import { EditableText } from "metabase/common/components/EditableText";import { SourceColorIndicator } from "metabase/common/components/SourceColorIndicator";-import { Badge, Flex, Pill } from "metabase/ui";+import { Badge, Flex, Icon, Menu, Pill } from "metabase/ui";import type { ExpressionDefinitionEntry } from "../../../types/viewer-state";-import { type MetricNameMap, buildExpressionForPill } from "../utils";+import {+ type MetricNameMap,+ buildExpressionForPill,+ buildExpressionText,+} from "../utils";import S from "./MetricExpressionPill.module.css";@@ -12,62 +18,148 @@ type MetricExpressionPillProps = {expressionEntry: ExpressionDefinitionEntry;metricNames: MetricNameMap;colors?: string[];- onClick: (e: React.MouseEvent) => void;+ onNameChange: (name: string) => void;onRemove: () => void;+ onEdit: () => void;};export function MetricExpressionPill({expressionEntry,metricNames,colors,- onClick,+ onNameChange,onRemove,+ onEdit,}: MetricExpressionPillProps) {- const expression = buildExpressionForPill(- expressionEntry.tokens,- metricNames,+ const [isRenaming, setIsRenaming] = useState(false);+ const [menuOpened, setMenuOpened] = useState(false);+ const editableRef = useRef<HTMLDivElement>(null);++ const expressionText = useMemo(+ () => buildExpressionText(expressionEntry.tokens, metricNames),+ [expressionEntry.tokens, metricNames],+ );++ const expressionForPill = useMemo(+ () => buildExpressionForPill(expressionEntry.tokens, metricNames),+ [expressionEntry.tokens, metricNames],+ );++ useEffect(() => {+ if (isRenaming) {+ const textarea = editableRef.current?.querySelector("textarea");+ if (textarea) {+ textarea.focus();+ const len = textarea.value.length;+ textarea.setSelectionRange(0, len);+ }+ }+ }, [isRenaming]);++ const handleRename = useCallback(() => {+ setMenuOpened(false);+ setIsRenaming(true);+ }, []);++ const handleEdit = useCallback(() => {+ setMenuOpened(false);+ onEdit?.();+ }, [onEdit]);++ const handleBlur = useCallback(() => {+ if (isRenaming) {+ setMenuOpened(false);+ setIsRenaming(false);+ }+ }, [isRenaming]);++ const handleNameChange = useCallback(+ (value: string) => {+ // Empty name → revert to the formula-derived default so chart series+ // and legend labels always have a non-empty display name.+ onNameChange(value || expressionText);+ setMenuOpened(false);+ setIsRenaming(false);+ },+ [onNameChange, expressionText],);+return (- <Pill- className={S.metricExpressionPill}- c="text-primary"- h="2rem"- px="sm"- py="xs"- fw={600}- withRemoveButton- onRemove={onRemove}- removeButtonProps={{- mr: 0,- "aria-label": t`Remove expression`,- }}- onClick={onClick}- data-testid="metrics-viewer-search-pill"+ <Menu+ opened={menuOpened}+ onChange={setMenuOpened}+ position="bottom-start"+ withinPortal+ disabled={isRenaming}>- <Flex align="center" gap="xs">- <SourceColorIndicator colors={colors} />- <Flex align="center" gap={0}>- {expression.map((e, i) => {- if (typeof e === "number") {- return (- <Badge- key={i}- circle- c="text-hover"- style={{ marginInlineStart: "0.2em" }}- >- {e}- </Badge>- );- }- return (- <span key={i} className={S.expressionText}>- {e}- </span>- );- })}- </Flex>- </Flex>- </Pill>+ <Menu.Target>+ <Pill+ className={S.metricExpressionPill}+ c="text-primary"+ h="2rem"+ px="sm"+ py="xs"+ fw={600}+ withRemoveButton+ onRemove={onRemove}+ removeButtonProps={{+ mr: 0,+ ml: 0,+ "aria-label": t`Remove expression`,+ }}+ data-testid="metrics-viewer-search-pill"+ >+ <Flex align="center" gap="xs">+ <SourceColorIndicator colors={colors} />+ {isRenaming ? (+ <EditableText+ ref={editableRef}+ className={S.editableName}+ initialValue={expressionEntry.name}+ placeholder={expressionText}+ isEditing+ isOptional+ onChange={handleNameChange}+ onBlur={handleBlur}+ data-testid="expression-name-input"+ />+ ) : (+ <Flex align="center" gap={0}>+ {expressionEntry.name && expressionEntry.name !== expressionText+ ? expressionEntry.name+ : expressionForPill.map((segment, i) => {+ if (typeof segment === "number") {+ return (+ <Badge+ key={i}+ circle+ c="text-hover"+ style={{ marginInlineStart: "0.2em" }}+ >+ {segment}+ </Badge>+ );+ }+ return (+ <span key={i} className={S.expressionText}>+ {segment}+ </span>+ );+ })}+ <span className={S.expressionText}>{"\u00a0"}</span>+ </Flex>+ )}+ </Flex>+ </Pill>+ </Menu.Target>+ <Menu.Dropdown mt="-0.15rem">+ <Menu.Item leftSection={<Icon name="pencil" />} onClick={handleEdit}>+ {t`Edit`}+ </Menu.Item>+ <Menu.Item leftSection={<Icon name="rename" />} onClick={handleRename}>+ {t`Rename`}+ </Menu.Item>+ </Menu.Dropdown>+ </Menu>);}diff --git a/frontend/src/metabase/metrics-viewer/components/MetricSearch/MetricExpressionPill/MetricExpressionPill.unit.spec.tsx b/frontend/src/metabase/metrics-viewer/components/MetricSearch/MetricExpressionPill/MetricExpressionPill.unit.spec.tsxnew file mode 100644index 00000000000..da5dea937ce--- /dev/null+++ b/frontend/src/metabase/metrics-viewer/components/MetricSearch/MetricExpressionPill/MetricExpressionPill.unit.spec.tsx@@ -0,0 +1,147 @@+import { screen } from "@testing-library/react";+import userEvent from "@testing-library/user-event";++import { renderWithProviders } from "__support__/ui";++import type { ExpressionDefinitionEntry } from "../../../types/viewer-state";+import type { MetricNameMap } from "../utils";++import { MetricExpressionPill } from "./MetricExpressionPill";++function buildEntry(+ overrides: Partial<ExpressionDefinitionEntry> = {},+): ExpressionDefinitionEntry {+ return {+ id: "expression:abc",+ type: "expression",+ name: "A + B",+ tokens: [+ { type: "metric", sourceId: "metric:1", count: 1 },+ { type: "operator", op: "+" },+ { type: "metric", sourceId: "metric:2", count: 1 },+ ],+ ...overrides,+ };+}++function setup({+ expressionEntry = buildEntry(),+ onNameChange = jest.fn(),+ onRemove = jest.fn(),+ onEdit = jest.fn(),+}: {+ expressionEntry?: ExpressionDefinitionEntry;+ onNameChange?: jest.Mock;+ onRemove?: jest.Mock;+ onEdit?: jest.Mock;+} = {}) {+ const metricNames: MetricNameMap = {+ "metric:1": "A",+ "metric:2": "B",+ };+ renderWithProviders(+ <MetricExpressionPill+ expressionEntry={expressionEntry}+ metricNames={metricNames}+ onNameChange={onNameChange}+ onRemove={onRemove}+ onEdit={onEdit}+ />,+ );+ return { onNameChange, onRemove, onEdit };+}++describe("MetricExpressionPill expression rendering", () => {+ it("should display ordinal badges after repeated metrics when no custom name is provided", () => {+ // Expression "A + A + A" — same metric repeated three times.+ // Without a custom name, the pill is rendered from tokens and each+ // duplicated occurrence should be suffixed with an ordinal badge.+ const expressionEntry: ExpressionDefinitionEntry = {+ id: "expression:repeated",+ type: "expression",+ name: "",+ tokens: [+ { type: "metric", sourceId: "metric:1", count: 1 },+ { type: "operator", op: "+" },+ { type: "metric", sourceId: "metric:1", count: 2 },+ { type: "operator", op: "+" },+ { type: "metric", sourceId: "metric:1", count: 3 },+ ],+ };++ setup({ expressionEntry });++ const pill = screen.getByTestId("metrics-viewer-search-pill");+ // The raw expression text is shown — custom-name fallback is not used.+ expect(pill).toHaveTextContent(/A\s*\+\s*A/);+ // The first "A" is unique so far (no badge), but the second and third+ // are non-unique and should carry ordinal badges "2" and "3".+ expect(screen.getByText("2")).toBeInTheDocument();+ expect(screen.getByText("3")).toBeInTheDocument();+ });++ it("should display ordinal badges when the custom name matches the expression text", () => {+ // When the stored `name` equals the auto-generated expression text, the pill+ // should still render the token-based view (with ordinal badges) rather than+ // echoing the plain string — otherwise duplicate metrics would lose their+ // disambiguating numbers.+ const expressionEntry: ExpressionDefinitionEntry = {+ id: "expression:repeated-named",+ type: "expression",+ name: "A + A + A",+ tokens: [+ { type: "metric", sourceId: "metric:1", count: 1 },+ { type: "operator", op: "+" },+ { type: "metric", sourceId: "metric:1", count: 2 },+ { type: "operator", op: "+" },+ { type: "metric", sourceId: "metric:1", count: 3 },+ ],+ };++ setup({ expressionEntry });++ expect(screen.getByText("2")).toBeInTheDocument();+ expect(screen.getByText("3")).toBeInTheDocument();+ });++ it("should not display ordinal badges when all metrics are unique", () => {+ // Default entry — "A + B" with distinct metrics, no custom name behavior.+ setup({ expressionEntry: buildEntry({ name: "" }) });++ expect(screen.queryByText("2")).not.toBeInTheDocument();+ expect(screen.queryByText("3")).not.toBeInTheDocument();+ });+});++describe("MetricExpressionPill action menu", () => {+ it("should open a menu with a Rename item when the pill is clicked", async () => {+ setup();++ await userEvent.click(screen.getByTestId("metrics-viewer-search-pill"));++ expect(await screen.findByText("Edit")).toBeInTheDocument();+ expect(await screen.findByText("Rename")).toBeInTheDocument();+ });++ it("should start the inline rename flow when Rename is clicked", async () => {+ setup();++ await userEvent.click(screen.getByTestId("metrics-viewer-search-pill"));+ await userEvent.click(await screen.findByText("Rename"));++ expect(+ await screen.findByTestId("expression-name-input"),+ ).toBeInTheDocument();+ // The textarea inside EditableText should be focused after Rename.+ expect(await screen.findByRole("textbox")).toHaveFocus();+ });++ it('should call onEdit if "Edit" menu item is clicked', async () => {+ const { onEdit } = setup();++ await userEvent.click(screen.getByTestId("metrics-viewer-search-pill"));+ await userEvent.click(await screen.findByText("Edit"));++ expect(onEdit).toHaveBeenCalledTimes(1);+ });+});diff --git a/frontend/src/metabase/metrics-viewer/components/MetricSearch/MetricPill/MetricPill.tsx b/frontend/src/metabase/metrics-viewer/components/MetricSearch/MetricPill/MetricPill.tsxindex f49b5727b31..cfde8aafd97 100644--- a/frontend/src/metabase/metrics-viewer/components/MetricSearch/MetricPill/MetricPill.tsx+++ b/frontend/src/metabase/metrics-viewer/components/MetricSearch/MetricPill/MetricPill.tsx@@ -19,7 +19,7 @@ import { MetricSearchDropdown } from "../MetricSearchDropdown";import S from "./MetricPill.module.css";-type PillPopoverState = "closed" | "swap" | "context-menu" | "breakout-picker";+type PillPopoverState = "closed" | "menu" | "swap" | "breakout-picker";type MetricPillProps = {metric: SelectedMetric;@@ -102,13 +102,11 @@ export function MetricPill({const handleOpen = useCallback(() => {onOpen?.();- setPopoverState("swap");+ setPopoverState("menu");}, [onOpen]);- const handleContextMenu = useCallback((e: React.MouseEvent) => {- e.preventDefault();- e.stopPropagation();- setPopoverState("context-menu");+ const handleOpenReplace = useCallback(() => {+ setPopoverState("swap");}, []);const handleOpenBreakoutPicker = useCallback(() => {@@ -150,7 +148,6 @@ export function MetricPill({e.stopPropagation();handleOpen();}}- onContextMenu={handleContextMenu}removeButtonProps={{mr: 0,"aria-label": metric.name@@ -176,7 +173,7 @@ export function MetricPill({</Flex></Pill></Popover.Target>- <Popover.Dropdown p={0}>+ <Popover.Dropdown p={0} mt="-0.15rem"><MetricSearchDropdownselectedMetricIds={selectedMetricIds}selectedMeasureIds={selectedMeasureIds}@@ -191,12 +188,10 @@ export function MetricPill({</Popover.Dropdown></Popover><Menu- opened={popoverState === "context-menu"}+ opened={popoverState === "menu"}onChange={(opened) => {if (!opened) {- setPopoverState((prev) =>- prev === "context-menu" ? "closed" : prev,- );+ setPopoverState((prev) => (prev === "menu" ? "closed" : prev));}}}position="bottom-start"@@ -210,7 +205,13 @@ export function MetricPill({className={S.menuTarget}/></Menu.Target>- <Menu.Dropdown>+ <Menu.Dropdown mt="-0.15rem">+ <Menu.Item+ leftSection={<Icon name="sync" />}+ onClick={handleOpenReplace}+ >+ {t`Replace`}+ </Menu.Item>{dimensions.size > 0 && definition && (<>{breakoutDimension && (@@ -267,7 +268,7 @@ export function MetricPill({className={S.menuTarget}/></Popover.Target>- <Popover.Dropdown p={0}>+ <Popover.Dropdown p={0} mt="-0.15rem"><BreakoutDimensionPickerdefinition={definition}currentBreakoutDimension={breakoutDimension}diff --git a/frontend/src/metabase/metrics-viewer/components/MetricSearch/MetricPill/MetricPill.unit.spec.tsx b/frontend/src/metabase/metrics-viewer/components/MetricSearch/MetricPill/MetricPill.unit.spec.tsxindex 755aa2071f1..970fe3481f3 100644--- a/frontend/src/metabase/metrics-viewer/components/MetricSearch/MetricPill/MetricPill.unit.spec.tsx+++ b/frontend/src/metabase/metrics-viewer/components/MetricSearch/MetricPill/MetricPill.unit.spec.tsx@@ -1,5 +1,7 @@-import { fireEvent, screen } from "@testing-library/react";+import { screen } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { setupSearchEndpoints } from "__support__/server-mocks";import { renderWithProviders } from "__support__/ui";import type {@@ -21,6 +23,7 @@ function setup({metric: SelectedMetric;definitionEntry?: MetricsViewerDefinitionEntry;}) {+ setupSearchEndpoints([]);renderWithProviders(<MetricPillmetric={metric}@@ -32,35 +35,39 @@ function setup({);}-function openContextMenu() {+async function openMenu() {const pill = screen.getByTestId("metrics-viewer-search-pill");- fireEvent.contextMenu(pill);+ await userEvent.click(pill);}-describe("MetricPill context menu", () => {- it("should not show bottom menu items for a measure", () => {+describe("MetricPill action menu", () => {+ it("should show only 'Replace' for a measure with no dimensions", async () => {setup({metric: { id: 1, name: "Revenue", sourceType: "measure" },});- openContextMenu();+ await openMenu();+ expect(screen.getByText("Replace")).toBeInTheDocument();expect(screen.queryByRole("separator")).not.toBeInTheDocument();+ expect(screen.queryByText("Break out")).not.toBeInTheDocument();expect(screen.queryByText("Go to metric home page"),).not.toBeInTheDocument();});- it("should show 'Go to metric home page' without separator when no breakout items", () => {+ it("should show 'Replace' + 'Go to metric home page' for a metric without dimensions", async () => {setup({metric: { id: 1, name: "Revenue", sourceType: "metric" },});- openContextMenu();+ await openMenu();- expect(screen.queryByRole("separator")).not.toBeInTheDocument();+ expect(screen.getByText("Replace")).toBeInTheDocument();expect(screen.getByText("Go to metric home page")).toBeInTheDocument();+ // No separator when there are no breakout items between them.+ expect(screen.queryByRole("separator")).not.toBeInTheDocument();});- it("should show separator between breakout items and 'Go to metric home page'", () => {+ it("should show 'Replace', 'Break out', and 'Go to metric home page' with a separator when dimensions exist", async () => {const metadata = createMetricMetadata([REVENUE_METRIC]);const definition = setupDefinition(metadata, REVENUE_METRIC.id);@@ -68,10 +75,24 @@ describe("MetricPill context menu", () => {metric: { id: REVENUE_METRIC.id, name: "Revenue", sourceType: "metric" },definitionEntry: { id: "metric:1", definition },});- openContextMenu();+ await openMenu();- expect(screen.getByRole("separator")).toBeInTheDocument();+ expect(screen.getByText("Replace")).toBeInTheDocument();expect(screen.getByText("Break out")).toBeInTheDocument();expect(screen.getByText("Go to metric home page")).toBeInTheDocument();+ // One separator between breakout items and 'Go to metric home page'.+ expect(screen.getAllByRole("separator")).toHaveLength(1);+ });++ it("should open the MetricSearchDropdown when Replace is clicked", async () => {+ setup({+ metric: { id: 1, name: "Revenue", sourceType: "metric" },+ });+ await openMenu();+ await userEvent.click(screen.getByText("Replace"));++ expect(+ await screen.findByPlaceholderText("Search for metrics..."),+ ).toBeInTheDocument();});});diff --git a/frontend/src/metabase/metrics-viewer/components/MetricSearch/MetricSearchInput/MetricSearchInput.tsx b/frontend/src/metabase/metrics-viewer/components/MetricSearch/MetricSearchInput/MetricSearchInput.tsxindex f02e6fb8763..054e46c06c8 100644--- a/frontend/src/metabase/metrics-viewer/components/MetricSearch/MetricSearchInput/MetricSearchInput.tsx+++ b/frontend/src/metabase/metrics-viewer/components/MetricSearch/MetricSearchInput/MetricSearchInput.tsx@@ -81,6 +81,7 @@ export function MetricSearchInput({pendingFocusRef,handleInputFocus,handleInputBlur,+ handleEditExpression,handleChange,handleSelect,handleRemoveItem,@@ -173,16 +174,21 @@ export function MetricSearchInput({: undefined;return (- <span key={`${entry.id}-${entryIndex}`}>+ <span+ key={`${entry.id}-${entryIndex}`}+ onClick={(e) => e.stopPropagation()}+ ><MetricExpressionPillexpressionEntry={entry}metricNames={metricNames}colors={expressionColors}- onClick={(e: React.MouseEvent) => {- e.stopPropagation();- handleContainerClick(e);+ onNameChange={(newName) => {+ const updated = [...formulaEntities];+ updated[entryIndex] = { ...entry, name: newName };+ onFormulaEntitiesChange(updated);}}onRemove={() => handleRemoveItem(entryIndex)}+ onEdit={() => handleEditExpression(entryIndex)}/></span>);diff --git a/frontend/src/metabase/metrics-viewer/components/MetricSearch/MetricSearchInput/MetricSearchInput.unit.spec.tsx b/frontend/src/metabase/metrics-viewer/components/MetricSearch/MetricSearchInput/MetricSearchInput.unit.spec.tsxindex ed64bf2828a..25cf77c3056 100644--- a/frontend/src/metabase/metrics-viewer/components/MetricSearch/MetricSearchInput/MetricSearchInput.unit.spec.tsx+++ b/frontend/src/metabase/metrics-viewer/components/MetricSearch/MetricSearchInput/MetricSearchInput.unit.spec.tsx@@ -47,20 +47,18 @@ jest.mock("../MetricPill", () => ({jest.mock("../MetricExpressionPill", () => ({MetricExpressionPill: ({expressionEntry,- onClick,onRemove,}: {expressionEntry: { name: string };- metricEntries: unknown[];+ metricNames: unknown;colors?: string[];- onClick: (e: React.MouseEvent) => void;+ onNameChange: (name: string) => void;onRemove: () => void;}) => {return (<divdata-testid="metric-expression-pill"data-expression-text={expressionEntry.name}- onClick={onClick}><span>{expressionEntry.name}</span><button onClick={onRemove}>remove</button>@@ -304,7 +302,10 @@ describe("expanded view (focused text input)", () => {entries: [revenueEntry, costsEntry, expr],});- await user.click(screen.getByTestId("metric-expression-pill"));+ // Click a metric pill (not expression pill) to enter formula editing mode.+ // Expression pill clicks now open the name editor instead.+ const pills = screen.getAllByTestId("metric-pill");+ await user.click(pills[0]);await waitFor(() => {expect(@@ -382,7 +383,9 @@ describe("blur behavior", () => {entries: [revenueEntry, costsEntry, expr],});- await user.click(screen.getByTestId("metric-expression-pill"));+ // Click a metric pill to enter formula editing mode.+ const pills = screen.getAllByTestId("metric-pill");+ await user.click(pills[0]);expect(await screen.findByRole("textbox")).toBeInTheDocument();expect(diff --git a/frontend/src/metabase/metrics-viewer/components/MetricSearch/MetricSearchInput/metricTokenHighlight.ts b/frontend/src/metabase/metrics-viewer/components/MetricSearch/MetricSearchInput/metricTokenHighlight.tsindex a0e93f4ab71..c4a9a77784d 100644--- a/frontend/src/metabase/metrics-viewer/components/MetricSearch/MetricSearchInput/metricTokenHighlight.ts+++ b/frontend/src/metabase/metrics-viewer/components/MetricSearch/MetricSearchInput/metricTokenHighlight.ts@@ -56,6 +56,7 @@ class MetricIdentity extends RangeValue {readonly sourceId: MetricSourceId,readonly definition: MetricDefinition | null,readonly slotIndex: number | undefined,+ readonly customName: string | undefined,) {super();}@@ -64,7 +65,8 @@ class MetricIdentity extends RangeValue {return (this.sourceId === other.sourceId &&this.definition === other.definition &&- this.slotIndex === other.slotIndex+ this.slotIndex === other.slotIndex &&+ this.customName === other.customName);}}@@ -92,11 +94,13 @@ export const metricIdentityField = StateField.define<RangeSet<MetricIdentity>>({for (const effect of tr.effects) {if (effect.is(addMetricIdentity)) {- const { from, to, sourceId, definition, slotIndex } = effect.value;+ const { from, to, sourceId, definition, slotIndex, customName } =+ effect.value;const newRange = new MetricIdentity(sourceId,definition,slotIndex,+ customName,).range(from, to);current = current.update({ add: [newRange] });}@@ -110,10 +114,12 @@ export function identitiesFromEntries(entries: MetricIdentityEntry[],): RangeSet<MetricIdentity> {const ranges = entries.map((entry) =>- new MetricIdentity(entry.sourceId, entry.definition, entry.slotIndex).range(- entry.from,- entry.to,- ),+ new MetricIdentity(+ entry.sourceId,+ entry.definition,+ entry.slotIndex,+ entry.customName,+ ).range(entry.from, entry.to),);return RangeSet.of(ranges, true);}@@ -129,6 +135,7 @@ export function readMetricIdentities(view: EditorView): MetricIdentityEntry[] {to,definition: value.definition,slotIndex: value.slotIndex,+ customName: value.customName,});});return result;diff --git a/frontend/src/metabase/metrics-viewer/components/MetricSearch/MetricSearchInput/useFormulaEditor.ts b/frontend/src/metabase/metrics-viewer/components/MetricSearch/MetricSearchInput/useFormulaEditor.tsindex dd796227780..faae8601956 100644--- a/frontend/src/metabase/metrics-viewer/components/MetricSearch/MetricSearchInput/useFormulaEditor.ts+++ b/frontend/src/metabase/metrics-viewer/components/MetricSearch/MetricSearchInput/useFormulaEditor.ts@@ -66,6 +66,7 @@ export type UseFormulaEditorResult = {pendingFocusRef: MutableRefObject<boolean>;handleInputFocus: () => void;handleInputBlur: () => void;+ handleEditExpression: (entityIndex: number) => void;handleChange: (newText: string) => void;handleSelect: (metric: SelectedMetric) => void;handleRemoveItem: (itemIndex: number) => void;@@ -108,6 +109,10 @@ export function useFormulaEditor({});const pendingFocusRef = useRef(false);+ // When set, overrides the default end-of-doc caret position on focus —+ // used when the user triggers "Edit" from a specific expression pill so the+ // caret lands at the end of that expression instead of the full formula.+ const pendingCaretPositionRef = useRef<number | null>(null);// Refs for reading latest values in callbacks without stale closuresconst editTextRef = useRef(editText);editTextRef.current = editText;@@ -190,14 +195,18 @@ export function useFormulaEditor({setTimeout(() => {const view = editorRef.current?.view;if (view) {- const endPos = view.state.doc.length;+ const docLen = view.state.doc.length;+ const requested = pendingCaretPositionRef.current;+ pendingCaretPositionRef.current = null;+ const caretPos =+ requested != null ? Math.min(Math.max(requested, 0), docLen) : docLen;const identities = identitiesFromEntries(initialIdentities);view.dispatch({- selection: EditorSelection.cursor(endPos),+ selection: EditorSelection.cursor(caretPos),effects: setMetricIdentities.of(identities),annotations: isolateHistory.of("full"),});- const coords = view.coordsAtPos(endPos);+ const coords = view.coordsAtPos(caretPos);if (coords) {setAnchorRect({ left: coords.left, top: coords.bottom });}@@ -205,6 +214,27 @@ export function useFormulaEditor({}, 0);}, [editorRef, metricNamesRef]);+ /**+ * Transition into focused-formula mode and place the caret at the end of+ * the expression at `entityIndex` within the full formula text.+ */+ const handleEditExpression = useCallback(+ (entityIndex: number) => {+ const entities = formulaEntitiesRef.current;+ if (entityIndex < 0 || entityIndex >= entities.length) {+ return;+ }+ const { text } = buildFullTextWithIdentities(+ entities.slice(0, entityIndex + 1),+ metricNamesRef.current,+ );+ pendingCaretPositionRef.current = text.length;+ pendingFocusRef.current = true;+ setIsFocused(true);+ },+ [metricNamesRef],+ );+/** Commits the current text: parses formula entities, removes unreferenced metrics, and collapses. */const commitAndCollapse = useCallback(() => {const newText = editTextRef.current;@@ -590,6 +620,7 @@ export function useFormulaEditor({pendingFocusRef,handleInputFocus,handleInputBlur,+ handleEditExpression,handleChange,handleSelect,handleRemoveItem,diff --git a/frontend/src/metabase/metrics-viewer/components/MetricSearch/utils.ts b/frontend/src/metabase/metrics-viewer/components/MetricSearch/utils.tsindex 57421fa95e1..f8f96e46269 100644--- a/frontend/src/metabase/metrics-viewer/components/MetricSearch/utils.ts+++ b/frontend/src/metabase/metrics-viewer/components/MetricSearch/utils.ts@@ -110,6 +110,10 @@ export function buildFullTextWithIdentities(}if (isExpressionEntry(entity)) {+ const defaultText = buildExpressionText(entity.tokens, metricNames);+ const customName =+ entity.name && entity.name !== defaultText ? entity.name : undefined;+for (let tokenIndex = 0;tokenIndex < entity.tokens.length;@@ -134,6 +138,7 @@ export function buildFullTextWithIdentities(to: offset + fragment.length,definition: token.definition ?? null,slotIndex: slotIndex++,+ customName,});}parts.push(fragment);@@ -1001,6 +1006,7 @@ export type MetricIdentityEntry = {to: number;definition: MetricDefinition | null;slotIndex?: number;+ customName?: string;};export function stripDefinitionProjections(@@ -1032,12 +1038,17 @@ export function applyTrackedDefinitions(): ApplyTrackedDefinitionsResult {const identityByPosition = new Map<string,- { definition: MetricDefinition | null; slotIndex: number | undefined }+ {+ definition: MetricDefinition | null;+ slotIndex: number | undefined;+ customName: string | undefined;+ }>();for (const identity of trackedIdentities) {identityByPosition.set(getPositionKey(identity.from, identity.to), {definition: identity.definition,slotIndex: identity.slotIndex,+ customName: identity.customName,});}@@ -1049,6 +1060,7 @@ export function applyTrackedDefinitions(MetricsViewerFormulaEntity,Map<number, MetricDefinition | undefined>>();+ const exprCustomNamesMap = new Map<MetricsViewerFormulaEntity, string>();const slotMapping = new Map<number, number>();let newSlotCounter = 0;@@ -1084,6 +1096,13 @@ export function applyTrackedDefinitions(? stripDefinitionProjections(tracked.definition): undefined;tokenMap.set(visit.exprTokenIndex, definition);++ // First surviving identity with a custom name wins. If identities+ // from two named expressions merge into one, the earliest (by token+ // order) name is kept — acceptable per the design.+ if (tracked.customName && !exprCustomNamesMap.has(visit.entity)) {+ exprCustomNamesMap.set(visit.entity, tracked.customName);+ }},trackedIdentities,);@@ -1093,18 +1112,30 @@ export function applyTrackedDefinitions(return { ...entity, definition: metricOverrides.get(entity) ?? null };}- const tokenMap = exprTokenOverrides.get(entity);- if (tokenMap && isExpressionEntry(entity)) {- const newTokens = entity.tokens.map((token, index) => {- if (!tokenMap.has(index)) {- return token;- }- return { ...token, definition: tokenMap.get(index) };- });- const hasChanges = newTokens.some(+ if (isExpressionEntry(entity)) {+ const tokenMap = exprTokenOverrides.get(entity);+ const newTokens = tokenMap+ ? entity.tokens.map((token, index) => {+ if (!tokenMap.has(index)) {+ return token;+ }+ return { ...token, definition: tokenMap.get(index) };+ })+ : entity.tokens;+ const tokensChanged = newTokens.some((token, index) => token !== entity.tokens[index],);- return hasChanges ? { ...entity, tokens: newTokens } : entity;+ const inheritedName = exprCustomNamesMap.get(entity);+ const nameChanged =+ inheritedName != null && inheritedName !== entity.name;+ if (!tokensChanged && !nameChanged) {+ return entity;+ }+ return {+ ...entity,+ tokens: newTokens,+ ...(nameChanged ? { name: inheritedName } : {}),+ };}return entity;diff --git a/frontend/src/metabase/metrics-viewer/components/MetricSearch/utils.unit.spec.ts b/frontend/src/metabase/metrics-viewer/components/MetricSearch/utils.unit.spec.tsindex 0b01fd743fa..6b97c1989f9 100644--- a/frontend/src/metabase/metrics-viewer/components/MetricSearch/utils.unit.spec.ts+++ b/frontend/src/metabase/metrics-viewer/components/MetricSearch/utils.unit.spec.ts@@ -1228,8 +1228,16 @@ function identity(to: number,definition: MetricDefinitionEntry["definition"] = null,slotIndex: number = nextSlotIndex++,+ customName?: string,): MetricIdentityEntry {- return { sourceId: metricSourceId, from, to, definition, slotIndex };+ return {+ sourceId: metricSourceId,+ from,+ to,+ definition,+ slotIndex,+ customName,+ };}describe("applyTrackedDefinitions", () => {@@ -1458,6 +1466,113 @@ describe("applyTrackedDefinitions", () => {);expect((entities[1] as MetricDefinitionEntry).definition).toBe(revenueDef);});++ // ─────────────────────────────────────────────────────────────────────────+ // Custom-name propagation through tracked MetricIdentity.customName.+ //+ // Custom expression names ride on the MetricIdentity range value — at+ // edit-session start, buildFullTextWithIdentities stamps the name onto+ // every metric-token identity that belongs to a renamed expression.+ // Here we skip the stamping step and inject `customName` directly into+ // the tracked identities to drive applyTrackedDefinitions in isolation.+ // ─────────────────────────────────────────────────────────────────────────++ it("preserves a custom expression name when every identity survives", () => {+ // "Revenue+Geo Revenue" — expression with two metric tokens.+ const text = "Revenue+Geo Revenue";+ const parsed = parseFullText(text, metricNames, []);+ const tracked = [+ identity(sourceId(1), 0, 7, null, 0, "My sum"),+ identity(sourceId(2), 8, 19, null, 1, "My sum"),+ ];+ const { entities } = applyTrackedDefinitions(+ parsed,+ tracked,+ text,+ metricNames,+ );+ const expr = entities[0] as ExpressionDefinitionEntry;+ expect(isExpressionEntry(expr)).toBe(true);+ expect(expr.name).toBe("My sum");+ });++ it("preserves a custom expression name when at least one identity survives", () => {+ // Same text as above, but only the first token's identity survives+ // (e.g. the user deleted and retyped the second metric).+ const text = "Revenue+Geo Revenue";+ const parsed = parseFullText(text, metricNames, []);+ const tracked = [identity(sourceId(1), 0, 7, null, 0, "My sum")];+ const { entities } = applyTrackedDefinitions(+ parsed,+ tracked,+ text,+ metricNames,+ );+ expect((entities[0] as ExpressionDefinitionEntry).name).toBe("My sum");+ });++ it("drops the custom name when every identity of the old expression is deleted", () => {+ // All tokens retyped from scratch → no tracked identities match.+ const text = "Revenue+Geo Revenue";+ const parsed = parseFullText(text, metricNames, []);+ const { entities } = applyTrackedDefinitions(parsed, [], text, metricNames);+ const expr = entities[0] as ExpressionDefinitionEntry;+ // Default name is the auto-derived expression text.+ expect(expr.name).toBe(buildExpressionText(expr.tokens, metricNames));+ expect(expr.name).not.toBe("My sum");+ });++ it("takes the first non-empty custom name when two named expressions merge", () => {+ // Two previously-separate expressions — "Revenue+5" named "A" and+ // "Geo Revenue+5" named "B" — collapse into one combined expression.+ const text = "Revenue+5+Geo Revenue+5";+ const parsed = parseFullText(text, metricNames, []);+ const tracked = [+ identity(sourceId(1), 0, 7, null, 0, "A"),+ identity(sourceId(2), 10, 21, null, 1, "B"),+ ];+ const { entities } = applyTrackedDefinitions(+ parsed,+ tracked,+ text,+ metricNames,+ );+ // "First wins" — the earliest token by traversal order decides.+ expect((entities[0] as ExpressionDefinitionEntry).name).toBe("A");+ });++ it("does not bleed a custom name across unrelated expression entities", () => {+ // Before edit: [Expr("Revenue+5", "A"), Metric(Geo Revenue), Expr("Revenue+5", "B")]+ // User edited the middle Geo Revenue into a brand-new "Revenue+5".+ // After edit: "Revenue+5, Revenue+5, Revenue+5".+ // - First Revenue at [0,7) survived → customName "A".+ // - Middle Revenue at [11,18) is brand new → no tracked identity.+ // - Third Revenue at [22,29) survived → customName "B".+ // Expected: entities[0].name === "A", entities[1].name === default,+ // entities[2].name === "B".+ const text = "Revenue+5, Revenue+5, Revenue+5";+ const parsed = parseFullText(text, metricNames, []);+ const tracked = [+ identity(sourceId(1), 0, 7, null, 0, "A"),+ identity(sourceId(1), 22, 29, null, 2, "B"),+ ];+ const { entities } = applyTrackedDefinitions(+ parsed,+ tracked,+ text,+ metricNames,+ );+ expect(entities).toHaveLength(3);+ const [first, middle, last] = entities as ExpressionDefinitionEntry[];+ expect(isExpressionEntry(first)).toBe(true);+ expect(isExpressionEntry(middle)).toBe(true);+ expect(isExpressionEntry(last)).toBe(true);+ expect(first.name).toBe("A");+ expect(last.name).toBe("B");+ // The middle one must NOT pick up "B" — the whole point of the fix.+ expect(middle.name).not.toBe("B");+ expect(middle.name).toBe(buildExpressionText(middle.tokens, metricNames));+ });});// ---------------------------------------------------------------------------diff --git a/frontend/src/metabase/metrics-viewer/utils/series.ts b/frontend/src/metabase/metrics-viewer/utils/series.tsindex 1c3edeeb596..8947231ce95 100644--- a/frontend/src/metabase/metrics-viewer/utils/series.ts+++ b/frontend/src/metabase/metrics-viewer/utils/series.ts@@ -149,16 +149,28 @@ export function buildSeries({const seriesKey = isFirstSeries ? result.data.cols[1]?.name : name;+ const vizSettingsOverride: Partial<VisualizationSettings> = nativeBreakout+ ? {}+ : computeColorVizSettings({+ displayType: display,+ seriesKey,+ color,+ });++ if (isFirstSeries && isExpressionEntry(entity) && seriesKey && name) {+ vizSettingsOverride.series_settings = {+ ...vizSettingsOverride.series_settings,+ [seriesKey]: {+ ...vizSettingsOverride.series_settings?.[seriesKey],+ title: name,+ },+ };+ }+const singleSeries: SingleSeries = {card: createSeriesCard(cardId, name, display, {...vizSettings,- ...(nativeBreakout- ? {}- : computeColorVizSettings({- displayType: display,- seriesKey,- color,- })),+ ...vizSettingsOverride,...extraVizSettings,}),data: result.data,@@ -344,7 +356,13 @@ export function computeSourceBreakoutColors(}if (isExpressionEntry(entity)) {- entries.push({ entityIndex, keys: [uniqueName], keyToBreakoutValue: {} });+ // Use entity.id (which encodes the formula text) as the color key so+ // that renaming the expression doesn't change its assigned color.+ entries.push({+ entityIndex,+ keys: [entity.id],+ keyToBreakoutValue: {},+ });}}diff --git a/frontend/src/metabase/ui/components/icons/Icon/icons/index.ts b/frontend/src/metabase/ui/components/icons/Icon/icons/index.tsindex 67f959332ef..b8a6829d4e9 100644--- a/frontend/src/metabase/ui/components/icons/Icon/icons/index.ts+++ b/frontend/src/metabase/ui/components/icons/Icon/icons/index.ts@@ -410,6 +410,8 @@ import refresh_component from "./refresh.svg?component";import refresh_source from "./refresh.svg?source";import refresh_downstream_component from "./refresh_downstream.svg?component";import refresh_downstream_source from "./refresh_downstream.svg?source";+import rename_component from "./rename.svg?component";+import rename_source from "./rename.svg?source";import repository_component from "./repository.svg?component";import repository_source from "./repository.svg?source";import return_component from "./return.svg?component";@@ -1437,6 +1439,10 @@ export const Icons: Record<IconName, { component: React.VFC; source: string }> =component: refresh_downstream_component,source: refresh_downstream_source,},+ rename: {+ component: rename_component,+ source: rename_source,+ },repository: {component: repository_component,source: repository_source,@@ -1951,6 +1957,7 @@ export type IconName =| "reference"| "refresh"| "refresh_downstream"+ | "rename"| "repository"| "rocket"| "ruler"diff --git a/frontend/src/metabase/ui/components/icons/Icon/icons/rename.svg b/frontend/src/metabase/ui/components/icons/Icon/icons/rename.svgnew file mode 100644index 00000000000..8d3fda7453c--- /dev/null+++ b/frontend/src/metabase/ui/components/icons/Icon/icons/rename.svg@@ -0,0 +1,3 @@+<svg width="16" height="16" viewBox="0 0 16 16" fill="currentcolor" xmlns="http://www.w3.org/2000/svg">+<path d="M10 2.25C9.30964 2.25 8.75 2.80964 8.75 3.5V12.5C8.75 13.1904 9.30964 13.75 10 13.75V15.25C9.21077 15.25 8.50151 14.9153 8 14.3828C7.49849 14.9153 6.78923 15.25 6 15.25V13.75C6.69036 13.75 7.25 13.1904 7.25 12.5V3.5C7.25 2.80964 6.69036 2.25 6 2.25V0.75C6.78898 0.75 7.49851 1.08399 8 1.61621C8.50149 1.08399 9.21102 0.75 10 0.75V2.25ZM5.5 5.75H3.5C3.08579 5.75 2.75 6.08579 2.75 6.5V9.5C2.75 9.91421 3.08579 10.25 3.5 10.25H5.5V11.75H3.5C2.25736 11.75 1.25 10.7426 1.25 9.5V6.5C1.25 5.25736 2.25736 4.25 3.5 4.25H5.5V5.75ZM12.5 4.25C13.7426 4.25 14.75 5.25736 14.75 6.5V9.5C14.75 10.7426 13.7426 11.75 12.5 11.75H10.5V10.25H12.5C12.9142 10.25 13.25 9.91421 13.25 9.5V6.5C13.25 6.08579 12.9142 5.75 12.5 5.75H10.5V4.25H12.5Z" />+</svg>