Skip to content

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

Fix metric math formula editor bugs (#72896)

Kevin Kelleherdaf7af45253d
diff --git a/frontend/src/metabase/metrics-viewer/components/MetricSearch/MetricSearchDropdown/MetricSearchDropdown.tsx b/frontend/src/metabase/metrics-viewer/components/MetricSearch/MetricSearchDropdown/MetricSearchDropdown.tsx
index 0f0257a8c56..3baea5ab381 100644
--- a/frontend/src/metabase/metrics-viewer/components/MetricSearch/MetricSearchDropdown/MetricSearchDropdown.tsx
+++ b/frontend/src/metabase/metrics-viewer/components/MetricSearch/MetricSearchDropdown/MetricSearchDropdown.tsx
@@ -1,4 +1,12 @@
-import { useCallback, useEffect, useMemo, useState } from "react";
+import {
+ type Dispatch,
+ type SetStateAction,
+ useCallback,
+ useEffect,
+ useMemo,
+ useState,
+} from "react";
+import { useUnmount } from "react-use";
import { t } from "ttag";
import { useListKeyboardNavigation } from "metabase/common/hooks/use-list-keyboard-navigation";
@@ -9,8 +17,13 @@ import {
useMetricMeasureSearch,
} from "../../../hooks/use-metric-measure-search";
import type { SelectedMetric } from "../../../types/viewer-state";
+import { createSourceId } from "../../../utils/source-ids";
import { MetricSearchResults } from "../MetricSearchResults";
-import { type ExcludeMetric, filterSearchResults } from "../utils";
+import {
+ type ExcludeMetric,
+ type MetricNameMap,
+ filterSearchResults,
+} from "../utils";
import S from "./MetricSearchDropdown.module.css";
@@ -23,6 +36,7 @@ type MetricSearchDropdownProps = {
showSearchInput?: boolean;
externalSearchText?: string;
onHasSelectionChange?: (hasSelection: boolean) => void;
+ setSearchMetricNames?: Dispatch<SetStateAction<MetricNameMap>>;
};
export function MetricSearchDropdown({
@@ -34,6 +48,7 @@ export function MetricSearchDropdown({
showSearchInput = false,
externalSearchText,
onHasSelectionChange,
+ setSearchMetricNames,
}: MetricSearchDropdownProps) {
const [internalSearchText, setInternalSearchText] = useState("");
const searchText = showSearchInput
@@ -53,6 +68,22 @@ export function MetricSearchDropdown({
[results, selectedMetricIds, selectedMeasureIds, excludeMetric],
);
+ useEffect(() => {
+ setSearchMetricNames?.((prev) => ({
+ ...prev,
+ ...Object.fromEntries(
+ filteredResults.map((result) => [
+ createSourceId(result.id, result.model),
+ result.name,
+ ]),
+ ),
+ }));
+ }, [filteredResults, setSearchMetricNames]);
+
+ useUnmount(() => {
+ setSearchMetricNames?.({});
+ });
+
const handleSelectResult = useCallback(
(id: number, model: "metric" | "measure") => {
const result = results?.find((r) => r.id === id && r.model === model);
diff --git a/frontend/src/metabase/metrics-viewer/components/MetricSearch/MetricSearchInput/MetricSearchInput.tsx b/frontend/src/metabase/metrics-viewer/components/MetricSearch/MetricSearchInput/MetricSearchInput.tsx
index 054e46c06c8..01abd60bd78 100644
--- a/frontend/src/metabase/metrics-viewer/components/MetricSearch/MetricSearchInput/MetricSearchInput.tsx
+++ b/frontend/src/metabase/metrics-viewer/components/MetricSearch/MetricSearchInput/MetricSearchInput.tsx
@@ -61,13 +61,19 @@ export function MetricSearchInput({
const containerRef = useRef<HTMLDivElement>(null);
const editorRef = useRef<ReactCodeMirrorRef>(null);
- const { metricNames, metricNamesRef, ...metricHandlers } =
- useMetricNameTracking({
- definitions,
- onAddMetric,
- onRemoveMetric,
- onSwapMetric,
- });
+ const {
+ metricNames,
+ metricNamesRef,
+ handleAddMetric,
+ handleRemoveMetric,
+ handleSwapMetric,
+ setSearchMetricNames,
+ } = useMetricNameTracking({
+ definitions,
+ onAddMetric,
+ onRemoveMetric,
+ onSwapMetric,
+ });
const {
editText,
@@ -99,8 +105,8 @@ export function MetricSearchInput({
selectedMetrics,
definitions,
metricNamesRef,
- handleAddMetric: metricHandlers.handleAddMetric,
- handleRemoveMetric: metricHandlers.handleRemoveMetric,
+ handleAddMetric,
+ handleRemoveMetric,
editorRef,
containerRef,
});
@@ -156,7 +162,7 @@ export function MetricSearchInput({
metric={metric}
colors={metricColors[entryIndex]}
definitionEntry={definition}
- onSwap={metricHandlers.handleSwapMetric}
+ onSwap={handleSwapMetric}
onRemove={(_id, _sourceType) =>
handleRemoveItem(entryIndex)
}
@@ -252,6 +258,7 @@ export function MetricSearchInput({
externalSearchText={currentWord}
onHasSelectionChange={handleDropdownHasSelectionChange}
onClose={() => setIsOpen(false)}
+ setSearchMetricNames={setSearchMetricNames}
/>
)}
</Popover.Dropdown>
diff --git a/frontend/src/metabase/metrics-viewer/components/MetricSearch/MetricSearchInput/useFormulaEditor.ts b/frontend/src/metabase/metrics-viewer/components/MetricSearch/MetricSearchInput/useFormulaEditor.ts
index faae8601956..1a38edee3af 100644
--- a/frontend/src/metabase/metrics-viewer/components/MetricSearch/MetricSearchInput/useFormulaEditor.ts
+++ b/frontend/src/metabase/metrics-viewer/components/MetricSearch/MetricSearchInput/useFormulaEditor.ts
@@ -343,10 +343,12 @@ export function useFormulaEditor({
// Extract the word at the cursor for the dropdown search
const view = editorRef.current?.view;
const cursorPos = view?.state.selection.main.head ?? newText.length;
+ const identities = view ? readMetricIdentities(view) : [];
const { word, start: wordStart } = getWordAtCursor(
newText,
cursorPos,
metricNamesRef.current,
+ identities,
);
// Anchor the dropdown at the word's left edge / line bottom in the viewport
if (view) {
@@ -369,10 +371,12 @@ export function useFormulaEditor({
}
const docText = view.state.doc.toString();
const cursorPos = view.state.selection.main.head;
+ const identities = readMetricIdentities(view);
const { start, end } = getWordAtCursor(
docText,
cursorPos,
metricNamesRef.current,
+ identities,
);
const metricName = metric.name ?? "";
@@ -544,10 +548,12 @@ export function useFormulaEditor({
// Re-extract word at the new cursor position after a click
const cursorPos = view.state.selection.main.head;
const text = view.state.doc.toString();
+ const identities = readMetricIdentities(view);
const { word, start: wordStart } = getWordAtCursor(
text,
cursorPos,
metricNamesRef.current,
+ identities,
);
// Update the anchor position so the dropdown is correctly placed
const coords = view.coordsAtPos(wordStart);
diff --git a/frontend/src/metabase/metrics-viewer/components/MetricSearch/MetricSearchInput/useMetricNameTracking.ts b/frontend/src/metabase/metrics-viewer/components/MetricSearch/MetricSearchInput/useMetricNameTracking.ts
index 18fdd50885e..09aa5fd0ea2 100644
--- a/frontend/src/metabase/metrics-viewer/components/MetricSearch/MetricSearchInput/useMetricNameTracking.ts
+++ b/frontend/src/metabase/metrics-viewer/components/MetricSearch/MetricSearchInput/useMetricNameTracking.ts
@@ -1,4 +1,4 @@
-import type { MutableRefObject } from "react";
+import type { Dispatch, MutableRefObject, SetStateAction } from "react";
import { useCallback, useMemo, useRef, useState } from "react";
import type { MetricDefinition } from "metabase-lib/metric";
@@ -31,6 +31,7 @@ type UseMetricNameTrackingResult = {
oldMetric: SelectedMetric,
newMetric: SelectedMetric,
) => void;
+ setSearchMetricNames: Dispatch<SetStateAction<MetricNameMap>>;
};
export function useMetricNameTracking({
@@ -39,10 +40,12 @@ export function useMetricNameTracking({
onRemoveMetric,
onSwapMetric,
}: UseMetricNameTrackingParams): UseMetricNameTrackingResult {
+ const [searchMetricNames, setSearchMetricNames] = useState<MetricNameMap>({});
const [localMetricNames, setLocalMetricNames] = useState<MetricNameMap>({});
const metricNames: MetricNameMap = useMemo(
() => ({
+ ...searchMetricNames,
...localMetricNames,
...Object.fromEntries(
Object.values(definitions)
@@ -54,7 +57,7 @@ export function useMetricNameTracking({
.filter(([, name]) => name !== null),
),
}),
- [localMetricNames, definitions],
+ [searchMetricNames, localMetricNames, definitions],
);
const metricNamesRef = useRef<MetricNameMap>(metricNames);
@@ -108,5 +111,6 @@ export function useMetricNameTracking({
handleAddMetric,
handleRemoveMetric,
handleSwapMetric,
+ setSearchMetricNames,
};
}
diff --git a/frontend/src/metabase/metrics-viewer/components/MetricSearch/utils.ts b/frontend/src/metabase/metrics-viewer/components/MetricSearch/utils.ts
index f8f96e46269..e6ed55e7c1e 100644
--- a/frontend/src/metabase/metrics-viewer/components/MetricSearch/utils.ts
+++ b/frontend/src/metabase/metrics-viewer/components/MetricSearch/utils.ts
@@ -180,112 +180,109 @@ function isWordChar(ch: string): boolean {
return /\w/.test(ch);
}
+function isWordDelimiter(ch: string): boolean {
+ return EXPRESSION_DELIMITERS.has(ch) || /\s/.test(ch);
+}
+
/**
- * Extracts the "word" (potential metric name) at the given cursor position,
- * using expression delimiters as boundaries.
- *
- * Spaces are NOT delimiters so that multi-word metric names like "Page Views"
- * are returned as a single word. Surrounding whitespace is trimmed.
- *
- * When `metricEntries` is provided, commas are only treated as delimiters
- * when they are real item separators — i.e. the text before the comma forms
- * a complete token (known metric, number, or closing paren). This allows
- * metric names containing commas (e.g. "Revenue, Total") to be typed and
- * searched as a single word.
+ * Extracts the "word" (potential metric name) at the given cursor position
*/
export function getWordAtCursor(
text: string,
cursorPos: number,
metricNames: MetricNameMap,
+ identities: MetricIdentityEntry[],
): { word: string; start: number; end: number } {
- // Build a set of metric names (lowercased) for quick lookup.
- let metricNamesLower: Set<string> | null = null;
- if (metricNames && Object.values(metricNames).length > 0) {
- metricNamesLower = new Set(
- Object.values(metricNames)
- .map((name) => name?.toLowerCase() ?? "")
- .filter((n) => n.length > 0),
- );
- }
-
- /**
- * Decides whether the comma at `pos` is a separator (delimiter) rather
- * than part of a metric name being typed.
- *
- * A comma is a separator when the trimmed text before it ends with:
- * - a known metric name,
- * - a numeric constant, or
- * - a closing parenthesis.
- *
- * Otherwise the comma is likely inside a metric name the user is still
- * typing (e.g. "Revenue," as part of "Revenue, Total").
- */
- const isCommaASeparator = (commaPos: number): boolean => {
- if (!metricNamesLower) {
- return true; // no entries → fall back to always splitting on commas
- }
-
- const before = text.slice(0, commaPos).trimEnd();
- if (before.length === 0) {
- return true;
- }
+ const metricNamesLower = new Set(
+ Object.values(metricNames)
+ .map((name) => name?.toLowerCase() ?? "")
+ .filter((n) => n.length > 0),
+ );
- const lastCh = before[before.length - 1];
- // After a closing paren → separator
- if (lastCh === ")") {
- return true;
- }
- // After a digit → separator (number constant)
- if (/\d/.test(lastCh)) {
- return true;
- }
- // Check if `before` ends with a known metric name
- const beforeLower = before.toLowerCase();
- for (const name of metricNamesLower) {
- const charBeforeName = before[before.length - name.length - 1];
- const isAtTextStart = before.length === name.length;
- const hasDelimiterBefore =
- NON_COMMA_DELIMITERS.has(charBeforeName) ||
- charBeforeName === COMMA ||
- charBeforeName === " ";
- const endsWithMetricName =
- beforeLower.endsWith(name) && (isAtTextStart || hasDelimiterBefore);
- if (endsWithMetricName) {
+ const isMetricNamePrefix = (s: string) => {
+ const sLower = s.toLowerCase();
+ for (const metricName of metricNamesLower) {
+ if (metricName.startsWith(sLower)) {
return true;
}
}
return false;
};
- const isDelimiter = (pos: number): boolean => {
- const ch = text[pos];
- if (NON_COMMA_DELIMITERS.has(ch)) {
- return true;
+ const leftBoundary = identities.reduce(
+ (left, identity) =>
+ identity.to <= cursorPos ? Math.max(left, identity.to) : left,
+ 0,
+ );
+ const rightBoundary = identities.reduce(
+ (right, identity) =>
+ identity.from >= cursorPos ? Math.min(right, identity.from) : right,
+ text.length,
+ );
+ let start = cursorPos;
+ let end = cursorPos;
+ // we can only split on delimiters or whitespace, so first extend start and end until we hit a delimiter or whitespace
+ for (let i = cursorPos - 1; i >= leftBoundary; i--) {
+ if (isWordDelimiter(text[i])) {
+ break;
}
- if (ch === COMMA) {
- return isCommaASeparator(pos);
+ start = i;
+ }
+ for (let i = cursorPos; i < rightBoundary; i++) {
+ if (isWordDelimiter(text[i])) {
+ break;
+ }
+ end = i + 1;
+ }
+ // now we can extend across a delimiter or whitespace if we find a metric name prefix
+ for (let i = start - 1; i >= leftBoundary; i--) {
+ if (isMetricNamePrefix(text.slice(i, end))) {
+ start = i;
+ }
+ }
+ for (let i = end + 1; i <= rightBoundary; i++) {
+ if (isMetricNamePrefix(text.slice(start, i))) {
+ end = i;
+ } else {
+ break;
}
- return false;
- };
-
- let start = cursorPos;
- while (start > 0 && !isDelimiter(start - 1)) {
- start--;
}
- let end = cursorPos;
- while (end < text.length && !isDelimiter(end)) {
- end++;
+ if (start < end) {
+ return {
+ word: text.slice(start, end),
+ start,
+ end,
+ };
}
- const rawWord = text.slice(start, end);
- const trimmedWord = rawWord.trim();
- const leadingSpaces = rawWord.length - rawWord.trimStart().length;
+ // didn't find any prefixes, fallback to simple delimiter approach
+ for (let i = cursorPos - 1; i >= leftBoundary; i--) {
+ if (EXPRESSION_DELIMITERS.has(text[i])) {
+ break;
+ }
+ start = i;
+ }
+ for (let i = cursorPos + 1; i <= rightBoundary; i++) {
+ if (EXPRESSION_DELIMITERS.has(text[i])) {
+ break;
+ }
+ end = i;
+ }
+ const raw = text.slice(start, end);
+ const trimmed = raw.trim();
+ // special case for all whitespace
+ // trimStart and trimEnd would both count the spaces, causing start > end, which causes an error
+ if (trimmed.length === 0) {
+ return { word: "", start: cursorPos, end: cursorPos };
+ }
+ const leading = raw.length - raw.trimStart().length;
+ const trailing = raw.length - raw.trimEnd().length;
return {
- word: trimmedWord,
- start: start + leadingSpaces,
- end: start + leadingSpaces + trimmedWord.length,
+ word: trimmed,
+ start: start + leading,
+ end: end - trailing,
};
}
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.ts
index 6b97c1989f9..d818d0906d8 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
@@ -1152,53 +1152,149 @@ describe("findInvalidRanges — untracked metric detection", () => {
});
});
-describe("getWordAtCursor — comma handling with metric entries", () => {
+describe("getWordAtCursor", () => {
const commaMetricNames: MetricNameMap = { "metric:99": "Revenue, Total" };
- it("without entries, comma is always a delimiter", () => {
+ it("falls back to delimiter-based extraction when no metric names are known", () => {
const text = "Revenue, Total";
- // cursor at end
- const result = getWordAtCursor(text, text.length, {});
+ const result = getWordAtCursor(text, text.length, {}, []);
expect(result.word).toBe("Total");
+ expect(result.start).toBe(9);
+ expect(result.end).toBe(text.length);
});
- it("with entries, comma inside a known metric name is not a delimiter", () => {
+ it("extracts full metric name when it contains a comma", () => {
const text = "Revenue, Total";
- const result = getWordAtCursor(text, text.length, commaMetricNames);
+ const result = getWordAtCursor(text, text.length, commaMetricNames, []);
expect(result.word).toBe("Revenue, Total");
});
- it("with entries, separator comma between two metrics is still a delimiter", () => {
+ it("distinguishes separator comma from name-internal comma", () => {
+ // Two separate metrics "Revenue" and "Orders", separated by comma.
+ // Cursor at end is inside the second name, so we should only get "Orders".
const text = "Revenue, Orders";
- // cursor at end (inside "Orders")
- const result = getWordAtCursor(text, text.length, {
- "metric:1": "Revenue",
- "metric:2": "Orders",
- });
+ const result = getWordAtCursor(
+ text,
+ text.length,
+ { "metric:1": "Revenue", "metric:2": "Orders" },
+ [],
+ );
expect(result.word).toBe("Orders");
});
it("treats comma as part of metric name when typing a partial match", () => {
- // User is typing "Revenue, T" which is a prefix of "Revenue, Total"
- // The comma is NOT a separator because "Revenue" alone is not a known
- // metric in this set — the only known metric is "Revenue, Total".
+ // User is typing "Revenue, T" which is a prefix of "Revenue, Total".
const text = "Revenue, T";
- const result = getWordAtCursor(text, text.length, commaMetricNames);
+ const result = getWordAtCursor(text, text.length, commaMetricNames, []);
expect(result.word).toBe("Revenue, T");
});
- it("math-operator delimiters still work with metric entries", () => {
- const text = "Revenue, Total + 1";
- const result = getWordAtCursor(text, text.length, commaMetricNames);
- expect(result.word).toBe("1");
- });
-
it("returns full metric name when cursor is in the middle", () => {
const text = "Revenue, Total";
// cursor after the comma+space (position 9, inside "Total")
- const result = getWordAtCursor(text, 9, commaMetricNames);
+ const result = getWordAtCursor(text, 9, commaMetricNames, []);
expect(result.word).toBe("Revenue, Total");
});
+
+ it("matches metric-name prefixes case-insensitively", () => {
+ // User is typing "rev" in lower case; the known metric is "Revenue".
+ const text = "rev";
+ const result = getWordAtCursor(
+ text,
+ text.length,
+ { "metric:1": "Revenue" },
+ [],
+ );
+ expect(result.word).toBe("rev");
+ });
+
+ it("stops at an existing identity on the right (comma separator case)", () => {
+ const metricNames: MetricNameMap = {
+ "metric:1": "Metric1",
+ "metric:2": "Metric2",
+ };
+ const text = "Metric1 + Met, Metric2";
+ const cursorPos = 13; // immediately after "Met"
+ const identities: MetricIdentityEntry[] = [
+ { sourceId: "metric:1", from: 0, to: 7, definition: null, slotIndex: 0 },
+ {
+ sourceId: "metric:2",
+ from: 15,
+ to: 23,
+ definition: null,
+ slotIndex: 1,
+ },
+ ];
+ const result = getWordAtCursor(text, cursorPos, metricNames, identities);
+ expect(result.word).toBe("Met");
+ expect(result.start).toBe(10);
+ expect(result.end).toBe(13);
+ });
+
+ it("treats parens as part of metric name when typing a partial match", () => {
+ const metricNames: MetricNameMap = { "metric:1": "Revenue (new)" };
+ const text = "Revenue (new";
+ const result = getWordAtCursor(text, text.length, metricNames, []);
+ expect(result.word).toBe("Revenue (new");
+ expect(result.start).toBe(0);
+ expect(result.end).toBe(text.length);
+ });
+
+ it("fallback: breaks on math operators and trims surrounding whitespace", () => {
+ const text = "Rev + M";
+ const result = getWordAtCursor(text, text.length, {}, []);
+ expect(result.word).toBe("M");
+ expect(result.start).toBe(6);
+ expect(result.end).toBe(text.length);
+ });
+
+ it("fallback: returns an empty word at the cursor when only whitespace follows a delimiter", () => {
+ const text = "Metric, ";
+ const result = getWordAtCursor(text, text.length, {}, []);
+ expect(result.word).toBe("");
+ expect(result.start).toBe(text.length);
+ expect(result.end).toBe(text.length);
+ });
+
+ it("only splits on delimiters or whitespace", () => {
+ // The trailing 't' in "xyznonexistent" is a prefix of "Test Measure", but we
+ // only split on delimiters or whitespace.
+ const metricNames: MetricNameMap = {
+ "metric:1": "Test Measure",
+ "metric:2": "Count of orders",
+ };
+ const text = "Test Measure, xyznonexistent";
+ const identities: MetricIdentityEntry[] = [
+ { sourceId: "metric:1", from: 0, to: 12, definition: null, slotIndex: 0 },
+ ];
+ const result = getWordAtCursor(text, text.length, metricNames, identities);
+ expect(result.word).toBe("xyznonexistent");
+ expect(result.start).toBe(14);
+ expect(result.end).toBe(text.length);
+ });
+
+ it("handles delimiters directly after the cursor", () => {
+ const metricNames: MetricNameMap = {
+ "metric:1": "Metric1",
+ "metric:2": "Metric2",
+ };
+ const text = "Metric1, Met Metric2";
+ const cursorPos = 12; // immediately after "Met"
+ const identities: MetricIdentityEntry[] = [
+ { sourceId: "metric:1", from: 0, to: 7, definition: null, slotIndex: 0 },
+ {
+ sourceId: "metric:2",
+ from: 13,
+ to: 20,
+ definition: null,
+ slotIndex: 1,
+ },
+ ];
+ const result = getWordAtCursor(text, cursorPos, metricNames, identities);
+ expect(result.word).toBe("Met");
+ expect(result.start).toBe(9);
+ expect(result.end).toBe(12);
+ });
});
function sourceId(id: number): MetricSourceId {