Skip to content

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

[BOT-1685] Fix UX of Metabot inline SQL search (#75772)

Tyler Plude70da91060268
diff --git a/frontend/src/metabase/metabot/components/MetabotPromptInput/MetabotPromptInput.tsx b/frontend/src/metabase/metabot/components/MetabotPromptInput/MetabotPromptInput.tsx
index 2b696f08b0c..9b9597c0947 100644
--- a/frontend/src/metabase/metabot/components/MetabotPromptInput/MetabotPromptInput.tsx
+++ b/frontend/src/metabase/metabot/components/MetabotPromptInput/MetabotPromptInput.tsx
@@ -65,6 +65,14 @@ export const MetabotPromptInput = forwardRef<
const siteUrl = useSelector((state) => getSetting(state, "site-url"));
const serializedRef = useRef(value);
+ // editorProps closures are baked into the editor at creation and are not
+ // refreshed by tiptap when useEditor has a dependency array, so they must
+ // read the latest handlers through refs.
+ const onSubmitRef = useRef(onSubmit);
+ onSubmitRef.current = onSubmit;
+ const onStopRef = useRef(onStop);
+ onStopRef.current = onStop;
+
const extensions = [
Document,
Paragraph,
@@ -87,89 +95,105 @@ export const MetabotPromptInput = forwardRef<
}),
];
- const editor = useEditor({
- extensions,
- content: parseMetabotMessageToTiptapDoc(value),
- autofocus: autoFocus,
- injectNonce: getCspNonce(),
- onUpdate: ({ editor }) => {
- const jsonContent = editor.getJSON();
- serializedRef.current = serializeTiptapToMetabotMessage(jsonContent);
- onChange(serializedRef.current);
- },
- editorProps: {
- handleDOMEvents: {
- copy: (view: EditorView, e: ClipboardEvent) => {
- e.preventDefault();
- const { from, to } = view.state.selection;
- const slice = view.state.doc.slice(from, to);
- const doc = view.state.schema.topNodeType.create(
- null,
- slice.content,
- );
- const serialized = serializeTiptapToMetabotMessage(doc.toJSON());
- e.clipboardData?.setData("text/plain", serialized);
- return true;
- },
- cut: (view: EditorView, e: ClipboardEvent) => {
- e.preventDefault();
- const { from, to } = view.state.selection;
- const slice = view.state.doc.slice(from, to);
- const doc = view.state.schema.topNodeType.create(
- null,
- slice.content,
- );
- const serialized = serializeTiptapToMetabotMessage(doc.toJSON());
- e.clipboardData?.setData("text/plain", serialized);
-
- // Delete the selected text and position cursor at cut location
- const tr = view.state.tr.deleteRange(from, to);
- tr.setSelection(TextSelection.create(tr.doc, from));
- view.dispatch(tr);
-
- return true;
- },
+ const editor = useEditor(
+ {
+ extensions,
+ content: parseMetabotMessageToTiptapDoc(value),
+ autofocus: autoFocus,
+ injectNonce: getCspNonce(),
+ onUpdate: ({ editor }) => {
+ const jsonContent = editor.getJSON();
+ serializedRef.current = serializeTiptapToMetabotMessage(jsonContent);
+ onChange(serializedRef.current);
},
- handleKeyDown: (view, event) => {
- if (event.key === "Escape" || event.key === "Enter") {
- // Defer enter handling to mention UI if open
- const mentionState = MetabotMentionPluginKey.getState(view.state);
- if (mentionState?.active) {
- return false; // Let the suggestion system handle it
- }
- }
-
- if (event.key === "Enter") {
- // Check for any modifier keys (shift, ctrl, meta, alt)
- const isModifiedKeyPress =
- event.shiftKey || event.ctrlKey || event.metaKey || event.altKey;
+ editorProps: {
+ handleDOMEvents: {
+ copy: (view: EditorView, e: ClipboardEvent) => {
+ e.preventDefault();
+ const { from, to } = view.state.selection;
+ const slice = view.state.doc.slice(from, to);
+ const doc = view.state.schema.topNodeType.create(
+ null,
+ slice.content,
+ );
+ const serialized = serializeTiptapToMetabotMessage(doc.toJSON());
+ e.clipboardData?.setData("text/plain", serialized);
+ return true;
+ },
+ cut: (view: EditorView, e: ClipboardEvent) => {
+ e.preventDefault();
+ const { from, to } = view.state.selection;
+ const slice = view.state.doc.slice(from, to);
+ const doc = view.state.schema.topNodeType.create(
+ null,
+ slice.content,
+ );
+ const serialized = serializeTiptapToMetabotMessage(doc.toJSON());
+ e.clipboardData?.setData("text/plain", serialized);
+
+ // Delete the selected text and position cursor at cut location
+ const tr = view.state.tr.deleteRange(from, to);
+ tr.setSelection(TextSelection.create(tr.doc, from));
+ view.dispatch(tr);
- if (!isModifiedKeyPress && onSubmit) {
- event.preventDefault();
- onSubmit();
return true;
+ },
+ },
+ handleKeyDown: (view, event) => {
+ if (event.key === "Escape" || event.key === "Enter") {
+ // Defer enter handling to mention UI if open
+ const mentionState = MetabotMentionPluginKey.getState(view.state);
+ if (mentionState?.active) {
+ return false; // Let the suggestion system handle it
+ }
}
- }
- if (event.key === "Escape") {
- const mentionState = MetabotMentionPluginKey.getState(view.state);
- if (mentionState?.active) {
- return false;
+ if (event.key === "Enter") {
+ // Check for any modifier keys (shift, ctrl, meta, alt)
+ const isModifiedKeyPress =
+ event.shiftKey ||
+ event.ctrlKey ||
+ event.metaKey ||
+ event.altKey;
+
+ if (!isModifiedKeyPress && onSubmitRef.current) {
+ event.preventDefault();
+ onSubmitRef.current();
+ return true;
+ }
}
- event.preventDefault();
- onStop();
- return true;
- }
+ if (event.key === "Escape") {
+ const mentionState = MetabotMentionPluginKey.getState(view.state);
+ if (mentionState?.active) {
+ return false;
+ }
- return false;
- },
- clipboardTextSerializer: (content) => {
- return serializeTiptapToMetabotMessage(content.toJSON());
+ event.preventDefault();
+ onStopRef.current();
+ return true;
+ }
+
+ return false;
+ },
+ clipboardTextSerializer: (content) => {
+ return serializeTiptapToMetabotMessage(content.toJSON());
+ },
+ clipboardTextParser: parseClipboardTextAsParagraphs,
},
- clipboardTextParser: parseClipboardTextAsParagraphs,
},
- });
+ // Extension config (including the suggestion closure over onlyDatabaseId)
+ // is captured by plugins at editor creation and cannot be updated via
+ // setOptions, so the editor must be recreated when it changes.
+ // suggestionModels is keyed by content because some consumers pass a
+ // fresh array on every render.
+ [
+ suggestionConfig.onlyDatabaseId,
+ suggestionConfig.suggestionModels.join(","),
+ placeholder,
+ siteUrl,
+ ],
+ );
useImperativeHandle(ref, () => {
if (!editor) {
diff --git a/frontend/src/metabase/metabot/components/MetabotPromptInput/MetabotPromptInput.unit.spec.tsx b/frontend/src/metabase/metabot/components/MetabotPromptInput/MetabotPromptInput.unit.spec.tsx
index d8c1ba0ea89..58a8711d0b2 100644
--- a/frontend/src/metabase/metabot/components/MetabotPromptInput/MetabotPromptInput.unit.spec.tsx
+++ b/frontend/src/metabase/metabot/components/MetabotPromptInput/MetabotPromptInput.unit.spec.tsx
@@ -1,11 +1,13 @@
import { screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import type { EditorState } from "@tiptap/pm/state";
+import fetchMock from "fetch-mock";
import { createRef } from "react";
import {
setupCollectionByIdEndpoint,
setupDatabasesEndpoints,
+ setupSearchEndpoints,
} from "__support__/server-mocks";
import { mockSettings } from "__support__/settings";
import { renderWithProviders } from "__support__/ui";
@@ -39,6 +41,7 @@ const setup = (props = {}) => {
setupCollectionByIdEndpoint({
collections: [rootCollection],
});
+ setupSearchEndpoints([]);
return renderWithProviders(
<MetabotPromptInput {...defaultProps} {...props} autoFocus />,
@@ -106,4 +109,36 @@ describe("MetabotPromptInput", () => {
expect(screen.queryByTestId("mini-picker")).not.toBeInTheDocument();
});
});
+
+ it("should scope mention search to the currently selected database after a database change", async () => {
+ const suggestionModels: SuggestionModel[] = ["table"];
+
+ const typeMentionQueryAndGetSearchDbId = async () => {
+ await userEvent.type(getEditor(), "@ord");
+ await waitFor(() => {
+ expect(fetchMock.callHistory.lastCall("path:/api/search")).toBeTruthy();
+ });
+ const lastCall = fetchMock.callHistory.lastCall("path:/api/search");
+ return new URL(lastCall!.url).searchParams.get("table_db_id");
+ };
+
+ const { rerender } = setup({
+ suggestionConfig: { suggestionModels, onlyDatabaseId: 1 },
+ });
+
+ expect(await typeMentionQueryAndGetSearchDbId()).toBe("1");
+
+ await userEvent.keyboard("{Escape}");
+ fetchMock.clearHistory();
+
+ rerender(
+ <MetabotPromptInput
+ {...defaultProps}
+ suggestionConfig={{ suggestionModels, onlyDatabaseId: 2 }}
+ autoFocus
+ />,
+ );
+
+ expect(await typeMentionQueryAndGetSearchDbId()).toBe("2");
+ });
});
diff --git a/frontend/src/metabase/rich_text_editing/tiptap/extensions/MetabotMention/MetabotSuggestionNew.tsx b/frontend/src/metabase/rich_text_editing/tiptap/extensions/MetabotMention/MetabotSuggestionNew.tsx
index e2634546773..bbc7169b0c2 100644
--- a/frontend/src/metabase/rich_text_editing/tiptap/extensions/MetabotMention/MetabotSuggestionNew.tsx
+++ b/frontend/src/metabase/rich_text_editing/tiptap/extensions/MetabotMention/MetabotSuggestionNew.tsx
@@ -129,6 +129,14 @@ const MetabotMentionSuggestionComponent = forwardRef<
[editor.view.dom, menuDropdownDom],
);
+ const searchParams = useMemo(
+ () =>
+ onlyDatabaseId !== undefined
+ ? { table_db_id: onlyDatabaseId }
+ : undefined,
+ [onlyDatabaseId],
+ );
+
return (
<>
<MiniPicker
@@ -140,6 +148,7 @@ const MetabotMentionSuggestionComponent = forwardRef<
onChange={onSelectEntity}
onClose={onClose}
shouldHide={shouldHide}
+ searchParams={searchParams}
onBrowseAll={() => {
setIsBrowsing(true);
}}
@@ -182,13 +191,7 @@ const MetabotMentionSuggestionComponent = forwardRef<
setIsBrowsing(false);
}}
isDisabledItem={shouldDisableItemNotInDb(onlyDatabaseId)}
- searchParams={
- onlyDatabaseId !== undefined
- ? {
- table_db_id: onlyDatabaseId,
- }
- : undefined
- }
+ searchParams={searchParams}
searchQuery={query}
/>
)}
diff --git a/frontend/src/metabase/rich_text_editing/tiptap/extensions/MetabotMention/MetabotSuggestionNew.unit.spec.tsx b/frontend/src/metabase/rich_text_editing/tiptap/extensions/MetabotMention/MetabotSuggestionNew.unit.spec.tsx
index b89e32e4205..a8fd18ff11b 100644
--- a/frontend/src/metabase/rich_text_editing/tiptap/extensions/MetabotMention/MetabotSuggestionNew.unit.spec.tsx
+++ b/frontend/src/metabase/rich_text_editing/tiptap/extensions/MetabotMention/MetabotSuggestionNew.unit.spec.tsx
@@ -23,7 +23,10 @@ jest.mock("metabase/common/components/Pickers", () => {
};
return (
- <div data-testid="mini-picker">
+ <div
+ data-testid="mini-picker"
+ data-search-params={JSON.stringify(props.searchParams)}
+ >
<button onClick={() => props.onChange(miniItem)}>mini-select</button>
<button onClick={() => props.onBrowseAll?.()}>browse-all</button>
{props.children}
@@ -134,6 +137,23 @@ describe("MetabotMentionSuggestionNew", () => {
).toBeInTheDocument();
});
+ it("scopes mini picker search to the selected database", () => {
+ setup({ onlyDatabaseId: 5 });
+
+ expect(screen.getByTestId("mini-picker")).toHaveAttribute(
+ "data-search-params",
+ JSON.stringify({ table_db_id: 5 }),
+ );
+ });
+
+ it("does not scope mini picker search when no database is selected", () => {
+ setup();
+
+ expect(screen.getByTestId("mini-picker")).not.toHaveAttribute(
+ "data-search-params",
+ );
+ });
+
it("pressing Escape closes suggestion when focus is on field", () => {
const { onClose, ref } = setup();
let handled: boolean | undefined;