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
UXW-3779 Metric dropdown after picking one (#73142)
Denis Berezin6ee919507ae3
diff --git a/e2e/test/scenarios/metrics/metrics-explorer.cy.spec.ts b/e2e/test/scenarios/metrics/metrics-explorer.cy.spec.tsindex 63990848810..3665c23d5c5 100644--- a/e2e/test/scenarios/metrics/metrics-explorer.cy.spec.ts+++ b/e2e/test/scenarios/metrics/metrics-explorer.cy.spec.ts@@ -124,7 +124,6 @@ const SNAPSHOT_NAME = "metrics-explorer-snapshot";*/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 endH.MetricsViewer.searchInput().type(`{end}, ${name}`, {waitForAnimations: true,});@@ -138,7 +137,6 @@ 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}`, {@@ -402,7 +400,9 @@ describe("scenarios > metrics > explorer", () => {});cy.log("no results");- H.MetricsViewer.searchInput().type("{end}, xyznonexistent");+ H.MetricsViewer.searchInput().type("{end}xyznonexistent", {+ waitForAnimations: true,+ });H.MetricsViewer.searchResults().should("contain.text","No search results",@@ -452,10 +452,27 @@ describe("scenarios > metrics > explorer", () => {});});+ it("should add multiple metrics one by one using metrics dropdown", () => {+ H.MetricsViewer.goToViewer();++ addMetric("Count of products", false);+ H.MetricsViewer.searchResults().findByText("Count of orders").click();+ H.MetricsViewer.searchResults()+ .findByText("Count of orders over time")+ .click();+ H.MetricsViewer.searchResults().findByText("Orders model metric").click();+ H.MetricsViewer.runButton().click();++ cy.wait("@dataset");+ verifyMetricCount(4);+ });+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");+ H.MetricsViewer.searchInput().type("Count of", {+ waitForAnimations: true,+ });H.MetricsViewer.searchResults().should("contain.text","No search results",@@ -468,7 +485,9 @@ describe("scenarios > metrics > explorer", () => {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");+ H.MetricsViewer.searchInput().type("Test Measure", {+ waitForAnimations: true,+ });H.MetricsViewer.searchResults().should("contain.text","No search results",@@ -740,7 +759,9 @@ describe("scenarios > metrics > explorer", () => {cy.log("Enter formula edit mode and append a new metric");cy.findByTestId("metrics-formula-input").click();- H.MetricsViewer.searchInput().type(", Count of products");+ H.MetricsViewer.searchInput().type("Count of products", {+ waitForAnimations: true,+ });H.MetricsViewer.searchResults().findByText("Count of products").click();cy.wait("@getMetric");@@ -821,15 +842,11 @@ describe("scenarios > metrics > explorer", () => {cy.log("Create expression: Count of orders + Count of products");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");-- cy.findByTestId("run-expression-button").click();+ addMetricMath([+ { metricName: "Count of orders" },+ "+",+ { metricName: "Count of products" },+ ]);cy.wait("@dataset");cy.log(@@ -888,7 +905,9 @@ describe("scenarios > metrics > explorer", () => {cy.findByTestId("metrics-formula-input").click();- H.MetricsViewer.searchInput().type(" + Count of products");+ H.MetricsViewer.searchInput().type(" + Count of products", {+ waitForAnimations: true,+ });H.MetricsViewer.searchResults().findByText("Count of products").click();cy.wait("@getMetric");@@ -1181,10 +1200,10 @@ describe("scenarios > metrics > explorer", () => {"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.+ // One {backspace} deletes the atomic "Test Measure" token, then 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 },@@ -2191,7 +2210,10 @@ describe("scenarios > metrics > explorer", () => {assertMetricMath();cy.log("edit formula and assert again");- H.MetricsViewer.searchInput().type("{end} + 0", { delay: 100 });+ H.MetricsViewer.searchInput().type("{end} + 0", {+ waitForAnimations: true,+ delay: 100,+ });H.MetricsViewer.runButton().click();assertMetricMath();});@@ -2215,7 +2237,9 @@ describe("scenarios > metrics > explorer", () => {cy.log("Sum metric '123' with itself — both selected from dropdown");cy.findByTestId("metrics-formula-input").click();- H.MetricsViewer.searchInput().type(`+ ${NUMERIC_METRIC_NAME}`);+ H.MetricsViewer.searchInput().type(` + ${NUMERIC_METRIC_NAME}`, {+ waitForAnimations: true,+ });H.MetricsViewer.searchResults().findByText(NUMERIC_METRIC_NAME).click();H.MetricsViewer.runButton().click();cy.wait("@dataset");@@ -2225,7 +2249,9 @@ describe("scenarios > metrics > explorer", () => {"Append literal number 123 — typed without selecting from dropdown",);cy.findByTestId("metrics-formula-input").click();- H.MetricsViewer.searchInput().type("+ 123");+ H.MetricsViewer.searchInput().type(" + 123", {+ waitForAnimations: true,+ });H.MetricsViewer.runButton().click();cy.wait("@dataset");H.MetricsViewer.getMetricVisualization().should("exist");diff --git a/frontend/src/metabase/metrics-viewer/components/MetricSearch/MetricSearchInput/useFormulaEditor.ts b/frontend/src/metabase/metrics-viewer/components/MetricSearch/MetricSearchInput/useFormulaEditor.tsindex 63a885cbaeb..329c47352a3 100644--- a/frontend/src/metabase/metrics-viewer/components/MetricSearch/MetricSearchInput/useFormulaEditor.ts+++ b/frontend/src/metabase/metrics-viewer/components/MetricSearch/MetricSearchInput/useFormulaEditor.ts@@ -18,7 +18,6 @@ import {} from "../../../utils/source-ids";import type { MetricSearchDropdownRef } from "../MetricSearchDropdown";import {- ENTITY_SEPARATOR,type MetricNameMap,applyTrackedDefinitions,buildFullTextWithIdentities,@@ -26,6 +25,7 @@ import {findInvalidRanges,getWordAtCursor,parseFullText,+ planMetricInsertion,removeUnmatchedParens,} from "../utils";@@ -177,6 +177,10 @@ export function useFormulaEditor({formulaEntitiesRef.current,metricNamesRef.current,);++ const requestedCaret = pendingCaretPositionRef.current;+ const shouldOpenDropdown = requestedCaret == null;+setTextAtFocus(fullText);setIsFocused(true);setEditText(fullText);@@ -191,10 +195,11 @@ export function useFormulaEditor({const view = editorRef.current?.view;if (view) {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;+ requestedCaret != null+ ? Math.min(Math.max(requestedCaret, 0), docLen)+ : docLen;const identities = identitiesFromEntries(initialIdentities);view.dispatch({selection: EditorSelection.cursor(caretPos),@@ -205,6 +210,10 @@ export function useFormulaEditor({if (coords) {setAnchorRect({ left: coords.left, top: coords.bottom });}+ if (shouldOpenDropdown) {+ setCurrentWord("");+ setIsOpen(true);+ }}}, 0);}, [editorRef, metricNamesRef]);@@ -384,42 +393,31 @@ export function useFormulaEditor({return;}- const textBeforeWord = docText.slice(0, start).trimEnd();- const lastChar = textBeforeWord[textBeforeWord.length - 1];- const NO_COMMA_CHARS = new Set(["+", "-", "*", "/", "(", ","]);- const needsComma =- textBeforeWord.length > 0 && !NO_COMMA_CHARS.has(lastChar);-- let insertText: string;- let replaceFrom: number;- let newCursorPos: number;- if (needsComma) {- insertText = ENTITY_SEPARATOR + metricName;- replaceFrom = textBeforeWord.length;- newCursorPos = replaceFrom + insertText.length;- } else {- insertText = metricName;- replaceFrom = start;- newCursorPos = start + metricName.length;- }+ const {+ insertText,+ replaceFrom,+ replaceTo,+ newCursorPos,+ metricFrom,+ metricTo,+ isAtEndOfFormula,+ } = planMetricInsertion({+ docText,+ wordStart: start,+ wordEnd: end,+ metricName,+ });const sourceId =metric.sourceType === "metric"? createMetricSourceId(metric.id): createMeasureSourceId(metric.id);- // Positions are in post-change document coordinates — metricIdentityField- // processes addMetricIdentity effects after mapping existing ranges through changes.- const metricFrom = needsComma- ? replaceFrom + ENTITY_SEPARATOR.length- : replaceFrom;- const metricTo = metricFrom + metricName.length;-// Dispatch through the view (not setEditText) — the value-prop sync// in @uiw/react-codemirror does a full doc replacement that destroys// all RangeSet-tracked identities.view.dispatch({- changes: { from: replaceFrom, to: end, insert: insertText },+ changes: { from: replaceFrom, to: replaceTo, insert: insertText },selection: EditorSelection.cursor(newCursorPos),effects: addMetricIdentity.of({from: metricFrom,@@ -435,9 +433,20 @@ export function useFormulaEditor({setCurrentWord("");setIsOpen(false);- // Return focus to the editor after dropdown closessetTimeout(() => {- editorRef.current?.view?.focus();+ const view = editorRef.current?.view;+ if (!view) {+ return;+ }+ // Return focus to the editor after the dropdown item click stole it+ view.focus();+ if (isAtEndOfFormula) {+ const coords = view.coordsAtPos(newCursorPos);+ if (coords) {+ setAnchorRect({ left: coords.left, top: coords.bottom });+ }+ setIsOpen(true);+ }}, 0);},[editorRef, metricNamesRef, handleAddMetric],diff --git a/frontend/src/metabase/metrics-viewer/components/MetricSearch/utils.ts b/frontend/src/metabase/metrics-viewer/components/MetricSearch/utils.tsindex cdd57507671..ea3a79b90ec 100644--- a/frontend/src/metabase/metrics-viewer/components/MetricSearch/utils.ts+++ b/frontend/src/metabase/metrics-viewer/components/MetricSearch/utils.ts@@ -17,6 +17,8 @@ import { stampMetricCounts } from "../../utils/expression";export type MetricNameMap = Partial<Record<MetricSourceId, string>>;+export const NO_COMMA_CHARS = new Set(["+", "-", "*", "/", "(", ","]);+/*** Returns an array of human-readable expression strings interleaved with numbers* identifying when metrics are used multiple times in the expression.@@ -71,6 +73,69 @@ export function buildExpressionText(export const ENTITY_SEPARATOR = ", ";+/**+ * Plans how to splice a selected metric name into the current formula text.+ *+ * Determines whether a leading "," separator is required (when the metric is+ * chained after other content). Returns `isAtEndOfFormula` so the caller can+ * decide whether to keep the dropdown open for a chained pick (no trailing+ * separator is inserted — the dropdown is reopened programmatically instead).+ * Trailing whitespace after the word being replaced is still swallowed so+ * the formula doesn't accumulate stale spaces.+ *+ * Returned offsets are in post-change document coordinates, so `metricFrom`+ * and `metricTo` can be passed straight to the metric-identity tracker.+ */+export function planMetricInsertion({+ docText,+ wordStart,+ wordEnd,+ metricName,+}: {+ docText: string;+ wordStart: number;+ wordEnd: number;+ metricName: string;+}): {+ insertText: string;+ replaceFrom: number;+ replaceTo: number;+ newCursorPos: number;+ metricFrom: number;+ metricTo: number;+ needsLeadingComma: boolean;+ isAtEndOfFormula: boolean;+} {+ const textBeforeWord = docText.slice(0, wordStart).trimEnd();+ const lastChar = textBeforeWord[textBeforeWord.length - 1];+ const needsLeadingComma =+ textBeforeWord.length > 0 && !NO_COMMA_CHARS.has(lastChar);++ // The selection lands the metric at the tail of the formula when nothing+ // meaningful follows the word being replaced. Used by the caller to decide+ // whether to reopen the dropdown for a chained pick.+ const isAtEndOfFormula = docText.slice(wordEnd).trim().length === 0;++ const leadingSep = needsLeadingComma ? ENTITY_SEPARATOR : "";+ const insertText = leadingSep + metricName;+ const replaceFrom = needsLeadingComma ? textBeforeWord.length : wordStart;+ const replaceTo = isAtEndOfFormula ? docText.length : wordEnd;+ const newCursorPos = replaceFrom + insertText.length;+ const metricFrom = replaceFrom + leadingSep.length;+ const metricTo = metricFrom + metricName.length;++ return {+ insertText,+ replaceFrom,+ replaceTo,+ newCursorPos,+ metricFrom,+ metricTo,+ needsLeadingComma,+ isAtEndOfFormula,+ };+}+export interface FullTextWithIdentities {text: string;identities: MetricIdentityEntry[];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 3689875295a..ef30bd475d5 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@@ -30,6 +30,7 @@ import {getWordAtCursor,parseFullText,parseFullTextWithPositions,+ planMetricInsertion,} from "./utils";jest.mock("../../utils/definition-builder", () => ({@@ -1777,3 +1778,106 @@ describe("parseFullText with identities", () => {]);});});++// ---------------------------------------------------------------------------+// planMetricInsertion+// ---------------------------------------------------------------------------++describe("planMetricInsertion", () => {+ it("inserts the metric name into an empty formula", () => {+ const plan = planMetricInsertion({+ docText: "",+ wordStart: 0,+ wordEnd: 0,+ metricName: "Revenue",+ });+ expect(plan.insertText).toBe("Revenue");+ expect(plan.replaceFrom).toBe(0);+ expect(plan.replaceTo).toBe(0);+ expect(plan.newCursorPos).toBe("Revenue".length);+ expect(plan.metricFrom).toBe(0);+ expect(plan.metricTo).toBe("Revenue".length);+ expect(plan.needsLeadingComma).toBe(false);+ expect(plan.isAtEndOfFormula).toBe(true);+ });++ it("inserts the metric name when replacing a partial word at the end of the formula", () => {+ // "Rev" → pick "Revenue"+ const plan = planMetricInsertion({+ docText: "Rev",+ wordStart: 0,+ wordEnd: 3,+ metricName: "Revenue",+ });+ expect(plan.insertText).toBe("Revenue");+ expect(plan.replaceFrom).toBe(0);+ expect(plan.replaceTo).toBe(3);+ expect(plan.isAtEndOfFormula).toBe(true);+ });++ it("prepends ', ' when chaining after an existing metric name and lands at end of formula", () => {+ // "Revenue Cos|" cursor after Cos; choosing "Costs" appends the new one+ const docText = "Revenue Cos";+ const plan = planMetricInsertion({+ docText,+ wordStart: 8,+ wordEnd: 11,+ metricName: "Costs",+ });+ expect(plan.insertText).toBe(", Costs");+ // Leading ", " replaces the trailing whitespace after "Revenue"+ expect(plan.replaceFrom).toBe("Revenue".length);+ expect(plan.replaceTo).toBe(docText.length);+ expect(plan.needsLeadingComma).toBe(true);+ expect(plan.isAtEndOfFormula).toBe(true);+ // Metric range starts after the leading ", "+ expect(plan.metricFrom).toBe("Revenue, ".length);+ expect(plan.metricTo).toBe("Revenue, Costs".length);+ });++ it("does not prepend ', ' after operator characters", () => {+ // "Revenue + Cos|" — operator "+" precedes, so no leading comma+ const docText = "Revenue + Cos";+ const plan = planMetricInsertion({+ docText,+ wordStart: 10,+ wordEnd: 13,+ metricName: "Costs",+ });+ expect(plan.needsLeadingComma).toBe(false);+ expect(plan.insertText).toBe("Costs");+ expect(plan.isAtEndOfFormula).toBe(true);+ });++ it("inserts only the metric name when replacement occurs in the middle of the formula", () => {+ // "Rev|enue + Costs" — replacing "Revenue" mid-formula+ const docText = "Revenue + Costs";+ const plan = planMetricInsertion({+ docText,+ wordStart: 0,+ wordEnd: 7,+ metricName: "Profit",+ });+ expect(plan.insertText).toBe("Profit");+ expect(plan.isAtEndOfFormula).toBe(false);+ expect(plan.replaceTo).toBe(7);+ });++ it("treats trailing whitespace as end of formula", () => {+ // "Revenue " — cursor at end, word is empty+ const docText = "Revenue ";+ const plan = planMetricInsertion({+ docText,+ wordStart: docText.length,+ wordEnd: docText.length,+ metricName: "Costs",+ });+ // Leading separator added because prev char is alphanumeric (via trimEnd)+ expect(plan.needsLeadingComma).toBe(true);+ expect(plan.isAtEndOfFormula).toBe(true);+ expect(plan.insertText).toBe(", Costs");+ // Swallows the trailing whitespace+ expect(plan.replaceFrom).toBe("Revenue".length);+ expect(plan.replaceTo).toBe(docText.length);+ });+});