Skip to content

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

Refactor NativeQueryEditor to be more composable (#75014)

Romeo Van Snickeb6901f096bd
diff --git a/frontend/src/metabase/query_builder/components/NativeQueryEditor/NativeQueryEditor.composition.unit.spec.tsx b/frontend/src/metabase/query_builder/components/NativeQueryEditor/NativeQueryEditor.composition.unit.spec.tsx
new file mode 100644
index 00000000000..08282ca6fa5
--- /dev/null
+++ b/frontend/src/metabase/query_builder/components/NativeQueryEditor/NativeQueryEditor.composition.unit.spec.tsx
@@ -0,0 +1,32 @@
+import { render } from "@testing-library/react";
+
+import { NativeQueryEditor } from "./NativeQueryEditor";
+
+describe("NativeQueryEditor composition API", () => {
+ it("exposes the composable parts as static members", () => {
+ expect(NativeQueryEditor.TopBar).toBeDefined();
+ expect(NativeQueryEditor.Sidebar).toBeDefined();
+ expect(NativeQueryEditor.ParametersList).toBeDefined();
+ expect(NativeQueryEditor.VisibilityToggler).toBeDefined();
+ expect(NativeQueryEditor.RunButton).toBeDefined();
+ });
+
+ it.each([
+ ["TopBar", NativeQueryEditor.TopBar],
+ ["Sidebar", NativeQueryEditor.Sidebar],
+ ["ParametersList", NativeQueryEditor.ParametersList],
+ ["VisibilityToggler", NativeQueryEditor.VisibilityToggler],
+ ["RunButton", NativeQueryEditor.RunButton],
+ ])("throws when %s is rendered outside the editor", (_name, Part) => {
+ // Suppress React's error boundary logging for the expected throw.
+ const consoleError = jest
+ .spyOn(console, "error")
+ .mockImplementation(() => {});
+
+ expect(() => render(<Part />)).toThrow(
+ /must be rendered inside <NativeQueryEditor>/,
+ );
+
+ consoleError.mockRestore();
+ });
+});
diff --git a/frontend/src/metabase/query_builder/components/NativeQueryEditor/NativeQueryEditor.tsx b/frontend/src/metabase/query_builder/components/NativeQueryEditor/NativeQueryEditor.tsx
index 1494abe2af0..10bf94949bb 100644
--- a/frontend/src/metabase/query_builder/components/NativeQueryEditor/NativeQueryEditor.tsx
+++ b/frontend/src/metabase/query_builder/components/NativeQueryEditor/NativeQueryEditor.tsx
@@ -1,444 +1,101 @@
-import { useElementSize } from "@mantine/hooks";
-import cx from "classnames";
-import {
- type ReactNode,
- forwardRef,
- useCallback,
- useEffect,
- useRef,
- useState,
-} from "react";
-import { useMount } from "react-use";
-import { t } from "ttag";
+import { Fragment, type ReactNode, forwardRef } from "react";
-import { useListCollectionsQuery, useListSnippetsQuery } from "metabase/api";
-import { getMetabotVisible } from "metabase/metabot/state";
-import { PLUGIN_REMOTE_SYNC } from "metabase/plugins";
-import { SnippetFormModal } from "metabase/query_builder/components/template_tags/SnippetFormModal";
-import { useNotebookScreenSize } from "metabase/query_builder/hooks/use-notebook-screen-size";
-import {
- CodeMirrorEditor,
- type CodeMirrorEditorProps,
- type CodeMirrorEditorRef,
-} from "metabase/querying/components/CodeMirrorEditor";
-import type { QueryModalType } from "metabase/querying/constants";
-import type {
- SelectionRange,
- SidebarFeatures,
-} from "metabase/querying/editor/types";
-import { useSelector } from "metabase/redux";
-import { Button, Flex, Icon, Stack, Tooltip } from "metabase/ui";
-import * as Lib from "metabase-lib";
-import type Question from "metabase-lib/v1/Question";
-import type Database from "metabase-lib/v1/metadata/Database";
-import type NativeQuery from "metabase-lib/v1/queries/NativeQuery";
-import type {
- CardId,
- DatabaseId,
- DatasetQuery,
- NativeQuerySnippet,
- ParameterId,
-} from "metabase-types/api";
+import type { SidebarFeatures } from "metabase/querying/editor/types";
-import S from "./NativeQueryEditor.module.css";
-import { NativeQueryEditorRunButton } from "./NativeQueryEditorRunButton/NativeQueryEditorRunButton";
-import { NativeQueryEditorTopBar } from "./NativeQueryEditorTopBar/NativeQueryEditorTopBar";
-import { ResizableArea } from "./ResizableArea";
-import { RightClickPopover } from "./RightClickPopover";
import {
- MIN_EDITOR_HEIGHT_AFTER_DRAGGING,
- RESIZE_CONSTRAINT_OFFSET,
- THRESHOLD_FOR_AUTO_CLOSE,
-} from "./constants";
-import {
- canFormatForEngine,
- formatQuery,
- getInitialEditorHeight,
-} from "./utils";
-
-type NativeQueryEditorProps = Omit<CodeMirrorEditorProps, "query"> & {
- availableHeight?: number;
- canChangeDatabase?: boolean;
- cancelQuery?: () => void;
- className?: string;
- closeSnippetModal?: () => void;
- databaseIsDisabled?: (database: Database) => boolean;
- databaseDisabledTooltip?: (database: Database) => string | undefined;
- editorContext?: "question" | "action";
+ type NativeQueryEditorCoreProps,
+ NativeQueryEditorRoot,
+} from "./NativeQueryEditorRoot";
+import { ParametersList } from "./slots/ParametersList";
+import { RunButton } from "./slots/RunButton";
+import { Sidebar } from "./slots/Sidebar";
+import { TopBar } from "./slots/TopBar";
+import { VisibilityToggler } from "./slots/VisibilityToggler";
+
+type NativeQueryEditorProps = NativeQueryEditorCoreProps & {
+ children?: ReactNode;
extraButton?: ReactNode;
- handleResize?: () => void;
hasEditingSidebar?: boolean;
hasParametersList?: boolean;
hasRunButton?: boolean;
hasTopBar?: boolean;
- highlightedLineNumbers?: number[];
- insertSnippet?: (snippet: NativeQuerySnippet) => void;
- isInitiallyOpen?: boolean;
- isNativeEditorOpen: boolean;
- isResultDirty?: boolean;
- isRunnable?: boolean;
- isRunning?: boolean;
- isShowingDataReference?: boolean;
- isShowingSnippetSidebar?: boolean;
- isShowingTemplateTagsEditor?: boolean;
- modalSnippet?:
- | NativeQuerySnippet
- | Partial<Omit<NativeQuerySnippet, "id">>
- | null;
- nativeEditorSelectedText?: string | null;
- onAcceptProposed?: (query: DatasetQuery) => void;
- onBlur?: () => void;
- onOpenModal?: (modalType: QueryModalType) => void;
- onRejectProposed?: () => void;
- onSetDatabaseId?: (id: DatabaseId) => void;
- openDataReferenceAtQuestion?: (id: CardId) => void;
- openSnippetModalWithSelectedText?: () => void;
- placeholder?: string;
- proposedQuestion?: Question | undefined;
- query: NativeQuery;
- question: Question;
- readOnly?: boolean;
- resizable?: boolean;
- runQuery?: () => void;
- setDatasetQuery: (query: NativeQuery) => void;
- setIsNativeEditorOpen?: (
- isOpen: boolean,
- shouldOpenDataReference?: boolean,
- ) => void;
- setNativeEditorSelectedRange?: (range: SelectionRange[]) => void;
- setParameterValue?: (parameterId: ParameterId, value: string) => void;
sidebarFeatures?: SidebarFeatures;
- toggleDataReference?: () => void;
- toggleSnippetSidebar?: () => void;
- toggleTemplateTagsEditor?: () => void;
topBarInnerContent?: ReactNode;
};
-export const NativeQueryEditor = forwardRef<
+/**
+ * Native (SQL) query editor.
+ *
+ * Prefer the composition API, assembling only the parts you need:
+ *
+ * <NativeQueryEditor question={question} query={query} setDatasetQuery={...}>
+ * <NativeQueryEditor.TopBar>
+ * <NativeQueryEditor.ParametersList />
+ * <NativeQueryEditor.Sidebar features={...} />
+ * <NativeQueryEditor.VisibilityToggler />
+ * </NativeQueryEditor.TopBar>
+ * <NativeQueryEditor.RunButton />
+ * </NativeQueryEditor>
+ *
+ * The legacy boolean-flag API (`hasTopBar`, `hasEditingSidebar`,
+ * `hasParametersList`, `hasRunButton`, `sidebarFeatures`, `extraButton`,
+ * `topBarInnerContent`) is still supported as a thin shim over the composition
+ * internals and will be removed once all consumers have migrated. When
+ * `children` are provided they take precedence and the legacy flags are ignored.
+ */
+const NativeQueryEditorBase = forwardRef<
HTMLDivElement,
NativeQueryEditorProps
->(function NativeQueryEditorInner(props, ref) {
+>(function NativeQueryEditor(props, ref) {
const {
- availableHeight = Infinity,
+ children,
extraButton,
- canChangeDatabase = true,
- cancelQuery,
- className,
- closeSnippetModal,
- databaseIsDisabled,
- databaseDisabledTooltip,
- editorContext,
- extensions,
- handleResize: handleResizeFromProps,
hasEditingSidebar = true,
hasParametersList,
hasRunButton = hasEditingSidebar,
hasTopBar = true,
- highlightedLineNumbers,
- insertSnippet,
- isNativeEditorOpen,
- isInitiallyOpen,
- isResultDirty = false,
- isRunnable = false,
- isRunning = false,
- isShowingDataReference = false,
- isShowingSnippetSidebar = false,
- isShowingTemplateTagsEditor = false,
- modalSnippet,
- nativeEditorSelectedText,
- onAcceptProposed,
- onBlur,
- onOpenModal,
- onRejectProposed,
- onSetDatabaseId,
- openDataReferenceAtQuestion,
- openSnippetModalWithSelectedText,
- placeholder,
- proposedQuestion,
- query,
- question,
- readOnly,
- resizable = true,
- runQuery,
- setDatasetQuery,
- setIsNativeEditorOpen,
- setNativeEditorSelectedRange,
- setParameterValue,
- sidebarFeatures = {
- dataReference: true,
- variables: true,
- snippets: true,
- promptInput: true,
- formatQuery: true,
- },
- toggleDataReference,
- toggleSnippetSidebar,
- toggleTemplateTagsEditor,
+ sidebarFeatures,
topBarInnerContent,
+ ...coreProps
} = props;
- const isRemoteSyncReadOnly = useSelector(
- PLUGIN_REMOTE_SYNC.getIsRemoteSyncReadOnly,
- );
- const { data: snippets = [] } = useListSnippetsQuery();
- const { data: snippetCollections = [] } = useListCollectionsQuery({
- namespace: "snippets",
- });
-
- const editorRef = useRef<CodeMirrorEditorRef>(null);
- const { ref: topBarRef, height: topBarHeight } = useElementSize();
-
- const canSaveSnippets =
- !isRemoteSyncReadOnly &&
- snippetCollections.some((collection) => collection.can_write);
-
- const canToggleEditor = typeof setIsNativeEditorOpen === "function";
- const shouldShowEditor = isNativeEditorOpen || !canToggleEditor;
- const [isSelectedTextPopoverOpen, setSelectedTextPopoverOpen] =
- useState(false);
-
- // do not show reference sidebar on small screens automatically
- const screenSize = useNotebookScreenSize();
- const isMetabotSidebarOpen = useSelector((state) =>
- getMetabotVisible(state, "omnibot"),
- );
- const shouldOpenDataReference =
- screenSize !== "small" && !isMetabotSidebarOpen;
-
- useMount(() => {
- setIsNativeEditorOpen?.(
- typeof isInitiallyOpen !== "undefined"
- ? isInitiallyOpen
- : question?.isSaved(),
- shouldOpenDataReference,
+ if (children != null) {
+ return (
+ <NativeQueryEditorRoot {...coreProps} ref={ref}>
+ {children}
+ </NativeQueryEditorRoot>
);
- });
-
- useEffect(() => {
- // Close selected text popover if text is deselected
- if (isSelectedTextPopoverOpen && !nativeEditorSelectedText) {
- setSelectedTextPopoverOpen(false);
- }
- }, [nativeEditorSelectedText, isSelectedTextPopoverOpen]);
-
- const handleChange = useCallback(
- (queryText: string) => {
- if (query.queryText() !== queryText) {
- const updatedQuery = query.setQueryText(queryText);
- setDatasetQuery(updatedQuery);
- }
- },
- [query, setDatasetQuery],
- );
-
- const handleSnippetUpdate = useCallback(
- (newSnippet: NativeQuerySnippet, oldSnippet: NativeQuerySnippet) => {
- // get the query instance with the latest Metadata that has the updated snippet
- const updatedQuery = query.updateSnippet(oldSnippet, newSnippet);
- setDatasetQuery(updatedQuery);
- },
- [query, setDatasetQuery],
- );
-
- const handleRightClickSelection = useCallback(() => {
- setSelectedTextPopoverOpen(true);
- }, []);
-
- const focusEditor = useCallback(() => {
- if (readOnly) {
- return;
- }
- editorRef.current?.focus();
- }, [readOnly]);
-
- const toggleEditor = useCallback(() => {
- setIsNativeEditorOpen?.(!isNativeEditorOpen, shouldOpenDataReference);
- }, [setIsNativeEditorOpen, shouldOpenDataReference, isNativeEditorOpen]);
-
- const handleFormatQuery = useCallback(async () => {
- const query = question.query();
- const engine = Lib.engine(query);
- const queryText = Lib.rawNativeQuery(query);
- const canFormatQuery = engine != null && canFormatForEngine(engine);
- if (!canFormatQuery) {
- return undefined;
- }
-
- if (!engine || !canFormatForEngine(engine)) {
- // no engine found, do nothing
- return;
- }
-
- const formattedQuery = await formatQuery(queryText, engine);
- handleChange(formattedQuery);
- focusEditor();
- }, [question, focusEditor, handleChange]);
-
- const handleResize = useCallback(
- (height: number) => {
- handleResizeFromProps?.();
-
- // If the height is lower than the threshold for auto-closing,
- // close the editor
- if (height <= THRESHOLD_FOR_AUTO_CLOSE) {
- setIsNativeEditorOpen?.(false);
- return;
- }
- },
- [handleResizeFromProps, setIsNativeEditorOpen],
- );
+ }
+
+ const legacyChildren: ReactNode[] = [];
+ if (hasTopBar) {
+ legacyChildren.push(
+ <TopBar key="top-bar">
+ {hasParametersList !== false && <ParametersList />}
+ {topBarInnerContent}
+ {hasEditingSidebar && <Sidebar features={sidebarFeatures} />}
+ <VisibilityToggler />
+ </TopBar>,
+ );
+ }
+ if (extraButton != null) {
+ legacyChildren.push(<Fragment key="extra-button">{extraButton}</Fragment>);
+ }
+ if (hasRunButton) {
+ legacyChildren.push(<RunButton key="run-button" />);
+ }
return (
- <div
- className={cx(S.queryEditor, className, { [S.readOnlyEditor]: readOnly })}
- data-testid="native-query-editor-container"
- ref={ref}
- >
- {hasTopBar && (
- <NativeQueryEditorTopBar
- ref={topBarRef}
- hasEditingSidebar={hasEditingSidebar}
- question={question}
- query={query}
- focus={focusEditor}
- canChangeDatabase={canChangeDatabase}
- sidebarFeatures={sidebarFeatures}
- isRunnable={isRunnable}
- isRunning={isRunning}
- hasParametersList={hasParametersList}
- isResultDirty={isResultDirty}
- isShowingDataReference={isShowingDataReference}
- onOpenModal={onOpenModal}
- isShowingTemplateTagsEditor={isShowingTemplateTagsEditor}
- setIsNativeEditorOpen={setIsNativeEditorOpen}
- snippets={snippets}
- editorContext={editorContext}
- onSetDatabaseId={onSetDatabaseId}
- isShowingSnippetSidebar={isShowingSnippetSidebar}
- isNativeEditorOpen={isNativeEditorOpen}
- toggleEditor={toggleEditor}
- toggleDataReference={toggleDataReference}
- toggleSnippetSidebar={toggleSnippetSidebar}
- toggleTemplateTagsEditor={toggleTemplateTagsEditor}
- setParameterValue={setParameterValue}
- setDatasetQuery={setDatasetQuery}
- onFormatQuery={handleFormatQuery}
- databaseIsDisabled={databaseIsDisabled}
- databaseDisabledTooltip={databaseDisabledTooltip}
- readOnly={readOnly}
- >
- {topBarInnerContent}
- </NativeQueryEditorTopBar>
- )}
- <div className={S.editorWrapper}>
- {shouldShowEditor && (
- <ResizableArea
- resizable={resizable}
- minHeight={MIN_EDITOR_HEIGHT_AFTER_DRAGGING}
- maxHeight={
- availableHeight - topBarHeight - RESIZE_CONSTRAINT_OFFSET
- }
- onResize={handleResize}
- initialHeight={getInitialEditorHeight({ query, availableHeight })}
- className={S.resizableArea}
- >
- <Flex w="100%" flex="1" className={S.resizableBoxContent}>
- <CodeMirrorEditor
- ref={editorRef}
- query={question.query()}
- proposedQuery={proposedQuestion?.query()}
- readOnly={readOnly}
- placeholder={placeholder}
- highlightedLineNumbers={highlightedLineNumbers}
- extensions={extensions}
- onBlur={onBlur}
- onChange={handleChange}
- onRunQuery={runQuery}
- onSelectionChange={setNativeEditorSelectedRange}
- onCursorMoveOverCardTag={openDataReferenceAtQuestion}
- onRightClickSelection={handleRightClickSelection}
- onFormatQuery={handleFormatQuery}
- />
-
- <Stack
- display={readOnly ? "none" : undefined}
- gap="md"
- justify="flex-end"
- p="md"
- >
- {proposedQuestion && onRejectProposed && onAcceptProposed && (
- <>
- <Tooltip label={t`Accept proposed changes`} position="top">
- <Button
- data-testid="accept-proposed-changes-button"
- variant="filled"
- bg="success"
- px="0"
- w="2.5rem"
- onClick={() => {
- const proposedQuery =
- proposedQuestion.legacyNativeQuery();
- if (proposedQuery) {
- handleChange(proposedQuery.queryText());
- onAcceptProposed(proposedQuery.datasetQuery());
- }
- }}
- >
- <Icon name="check" />
- </Button>
- </Tooltip>
- <Tooltip label={t`Reject proposed changes`} position="top">
- <Button
- data-testid="reject-proposed-changes-button"
- w="2.5rem"
- px="0"
- variant="filled"
- bg="danger"
- onClick={onRejectProposed}
- >
- <Icon name="close" />
- </Button>
- </Tooltip>
- </>
- )}
- <Flex gap="sm">
- {extraButton}
- {hasRunButton && !readOnly && (
- <NativeQueryEditorRunButton
- cancelQuery={cancelQuery}
- isResultDirty={isResultDirty}
- isRunnable={isRunnable}
- isRunning={isRunning}
- nativeEditorSelectedText={nativeEditorSelectedText}
- runQuery={runQuery}
- questionErrors={Lib.validateTemplateTags(
- question.query(),
- )}
- />
- )}
- </Flex>
- </Stack>
- </Flex>
- </ResizableArea>
- )}
- </div>
-
- <RightClickPopover
- isOpen={isSelectedTextPopoverOpen}
- openSnippetModalWithSelectedText={openSnippetModalWithSelectedText}
- runQuery={runQuery}
- target={() => editorRef.current?.getSelectionTarget()}
- canSaveSnippets={canSaveSnippets}
- />
-
- {modalSnippet && insertSnippet && closeSnippetModal && (
- <SnippetFormModal
- snippet={modalSnippet}
- onCreate={insertSnippet}
- onUpdate={handleSnippetUpdate}
- onClose={closeSnippetModal}
- />
- )}
- </div>
+ <NativeQueryEditorRoot {...coreProps} ref={ref}>
+ {legacyChildren}
+ </NativeQueryEditorRoot>
);
});
+
+export const NativeQueryEditor = Object.assign(NativeQueryEditorBase, {
+ TopBar,
+ Sidebar,
+ ParametersList,
+ VisibilityToggler,
+ RunButton,
+});
diff --git a/frontend/src/metabase/query_builder/components/NativeQueryEditor/NativeQueryEditorRoot.tsx b/frontend/src/metabase/query_builder/components/NativeQueryEditor/NativeQueryEditorRoot.tsx
new file mode 100644
index 00000000000..23fd9fa658a
--- /dev/null
+++ b/frontend/src/metabase/query_builder/components/NativeQueryEditor/NativeQueryEditorRoot.tsx
@@ -0,0 +1,447 @@
+import { useElementSize } from "@mantine/hooks";
+import cx from "classnames";
+import {
+ Children,
+ type ReactNode,
+ cloneElement,
+ forwardRef,
+ isValidElement,
+ useCallback,
+ useEffect,
+ useRef,
+ useState,
+} from "react";
+import { useMount } from "react-use";
+import { t } from "ttag";
+
+import { useListCollectionsQuery, useListSnippetsQuery } from "metabase/api";
+import { getMetabotVisible } from "metabase/metabot/state";
+import { PLUGIN_REMOTE_SYNC } from "metabase/plugins";
+import { SnippetFormModal } from "metabase/query_builder/components/template_tags/SnippetFormModal";
+import { useNotebookScreenSize } from "metabase/query_builder/hooks/use-notebook-screen-size";
+import {
+ CodeMirrorEditor,
+ type CodeMirrorEditorProps,
+ type CodeMirrorEditorRef,
+} from "metabase/querying/components/CodeMirrorEditor";
+import type { QueryModalType } from "metabase/querying/constants";
+import type { SelectionRange } from "metabase/querying/editor/types";
+import { useSelector } from "metabase/redux";
+import { Button, Flex, Icon, Stack, Tooltip } from "metabase/ui";
+import * as Lib from "metabase-lib";
+import type Question from "metabase-lib/v1/Question";
+import type Database from "metabase-lib/v1/metadata/Database";
+import type NativeQuery from "metabase-lib/v1/queries/NativeQuery";
+import type {
+ CardId,
+ DatabaseId,
+ DatasetQuery,
+ NativeQuerySnippet,
+ ParameterId,
+} from "metabase-types/api";
+
+import S from "./NativeQueryEditor.module.css";
+import { ResizableArea } from "./ResizableArea";
+import { RightClickPopover } from "./RightClickPopover";
+import {
+ MIN_EDITOR_HEIGHT_AFTER_DRAGGING,
+ RESIZE_CONSTRAINT_OFFSET,
+ THRESHOLD_FOR_AUTO_CLOSE,
+} from "./constants";
+import {
+ NativeQueryEditorContextProvider,
+ type NativeQueryEditorContextValue,
+} from "./context/NativeQueryEditorContext";
+import { TopBar } from "./slots/TopBar";
+import {
+ canFormatForEngine,
+ formatQuery,
+ getInitialEditorHeight,
+} from "./utils";
+
+/**
+ * Props shared by the composable {@link NativeQueryEditorRoot} and the
+ * backward-compatible {@link NativeQueryEditor} shim — everything except the
+ * legacy layout flags (`hasTopBar`, `hasEditingSidebar`, `hasParametersList`,
+ * `hasRunButton`, `sidebarFeatures`, `extraButton`, `topBarInnerContent`).
+ */
+export type NativeQueryEditorCoreProps = Omit<
+ CodeMirrorEditorProps,
+ "query"
+> & {
+ availableHeight?: number;
+ canChangeDatabase?: boolean;
+ cancelQuery?: () => void;
+ className?: string;
+ closeSnippetModal?: () => void;
+ databaseIsDisabled?: (database: Database) => boolean;
+ databaseDisabledTooltip?: (database: Database) => string | undefined;
+ editorContext?: "question" | "action";
+ handleResize?: () => void;
+ highlightedLineNumbers?: number[];
+ insertSnippet?: (snippet: NativeQuerySnippet) => void;
+ isInitiallyOpen?: boolean;
+ isNativeEditorOpen: boolean;
+ isResultDirty?: boolean;
+ isRunnable?: boolean;
+ isRunning?: boolean;
+ isShowingDataReference?: boolean;
+ isShowingSnippetSidebar?: boolean;
+ isShowingTemplateTagsEditor?: boolean;
+ modalSnippet?:
+ | NativeQuerySnippet
+ | Partial<Omit<NativeQuerySnippet, "id">>
+ | null;
+ nativeEditorSelectedText?: string | null;
+ onAcceptProposed?: (query: DatasetQuery) => void;
+ onBlur?: () => void;
+ onOpenModal?: (modalType: QueryModalType) => void;
+ onRejectProposed?: () => void;
+ onSetDatabaseId?: (id: DatabaseId) => void;
+ openDataReferenceAtQuestion?: (id: CardId) => void;
+ openSnippetModalWithSelectedText?: () => void;
+ placeholder?: string;
+ proposedQuestion?: Question | undefined;
+ query: NativeQuery;
+ question: Question;
+ readOnly?: boolean;
+ resizable?: boolean;
+ runQuery?: () => void;
+ setDatasetQuery: (query: NativeQuery) => void;
+ setIsNativeEditorOpen?: (
+ isOpen: boolean,
+ shouldOpenDataReference?: boolean,
+ ) => void;
+ setNativeEditorSelectedRange?: (range: SelectionRange[]) => void;
+ setParameterValue?: (parameterId: ParameterId, value: string) => void;
+ toggleDataReference?: () => void;
+ toggleSnippetSidebar?: () => void;
+ toggleTemplateTagsEditor?: () => void;
+};
+
+type NativeQueryEditorRootProps = NativeQueryEditorCoreProps & {
+ children?: ReactNode;
+};
+
+export const NativeQueryEditorRoot = forwardRef<
+ HTMLDivElement,
+ NativeQueryEditorRootProps
+>(function NativeQueryEditorRootInner(props, ref) {
+ const {
+ children,
+ availableHeight = Infinity,
+ canChangeDatabase = true,
+ cancelQuery,
+ className,
+ closeSnippetModal,
+ databaseIsDisabled,
+ databaseDisabledTooltip,
+ editorContext = "question",
+ extensions,
+ handleResize: handleResizeFromProps,
+ highlightedLineNumbers,
+ insertSnippet,
+ isNativeEditorOpen,
+ isInitiallyOpen,
+ isResultDirty = false,
+ isRunnable = false,
+ isRunning = false,
+ isShowingDataReference = false,
+ isShowingSnippetSidebar = false,
+ isShowingTemplateTagsEditor = false,
+ modalSnippet,
+ nativeEditorSelectedText,
+ onAcceptProposed,
+ onBlur,
+ onOpenModal,
+ onRejectProposed,
+ onSetDatabaseId,
+ openDataReferenceAtQuestion,
+ openSnippetModalWithSelectedText,
+ placeholder,
+ proposedQuestion,
+ query,
+ question,
+ readOnly,
+ resizable = true,
+ runQuery,
+ setDatasetQuery,
+ setIsNativeEditorOpen,
+ setNativeEditorSelectedRange,
+ setParameterValue,
+ toggleDataReference,
+ toggleSnippetSidebar,
+ toggleTemplateTagsEditor,
+ } = props;
+
+ const isRemoteSyncReadOnly = useSelector(
+ PLUGIN_REMOTE_SYNC.getIsRemoteSyncReadOnly,
+ );
+ const { data: snippets = [] } = useListSnippetsQuery();
+ const { data: snippetCollections = [] } = useListCollectionsQuery({
+ namespace: "snippets",
+ });
+
+ const editorRef = useRef<CodeMirrorEditorRef>(null);
+ const { ref: topBarRef, height: topBarHeight } = useElementSize();
+
+ const canSaveSnippets =
+ !isRemoteSyncReadOnly &&
+ snippetCollections.some((collection) => collection.can_write);
+
+ const canToggleEditor = typeof setIsNativeEditorOpen === "function";
+ const shouldShowEditor = isNativeEditorOpen || !canToggleEditor;
+
+ const [isSelectedTextPopoverOpen, setSelectedTextPopoverOpen] =
+ useState(false);
+
+ // do not show reference sidebar on small screens automatically
+ const screenSize = useNotebookScreenSize();
+ const isMetabotSidebarOpen = useSelector((state) =>
+ getMetabotVisible(state, "omnibot"),
+ );
+ const shouldOpenDataReference =
+ screenSize !== "small" && !isMetabotSidebarOpen;
+
+ useMount(() => {
+ setIsNativeEditorOpen?.(
+ typeof isInitiallyOpen !== "undefined"
+ ? isInitiallyOpen
+ : question?.isSaved(),
+ shouldOpenDataReference,
+ );
+ });
+
+ useEffect(() => {
+ // Close selected text popover if text is deselected
+ if (isSelectedTextPopoverOpen && !nativeEditorSelectedText) {
+ setSelectedTextPopoverOpen(false);
+ }
+ }, [nativeEditorSelectedText, isSelectedTextPopoverOpen]);
+
+ const handleChange = useCallback(
+ (queryText: string) => {
+ if (query.queryText() !== queryText) {
+ const updatedQuery = query.setQueryText(queryText);
+ setDatasetQuery(updatedQuery);
+ }
+ },
+ [query, setDatasetQuery],
+ );
+
+ const handleSnippetUpdate = useCallback(
+ (newSnippet: NativeQuerySnippet, oldSnippet: NativeQuerySnippet) => {
+ // get the query instance with the latest Metadata that has the updated snippet
+ const updatedQuery = query.updateSnippet(oldSnippet, newSnippet);
+ setDatasetQuery(updatedQuery);
+ },
+ [query, setDatasetQuery],
+ );
+
+ const handleRightClickSelection = useCallback(() => {
+ setSelectedTextPopoverOpen(true);
+ }, []);
+
+ const focusEditor = useCallback(() => {
+ if (readOnly) {
+ return;
+ }
+ editorRef.current?.focus();
+ }, [readOnly]);
+
+ const toggleEditor = useCallback(() => {
+ setIsNativeEditorOpen?.(!isNativeEditorOpen, shouldOpenDataReference);
+ }, [setIsNativeEditorOpen, shouldOpenDataReference, isNativeEditorOpen]);
+
+ const handleFormatQuery = useCallback(async () => {
+ const query = question.query();
+ const engine = Lib.engine(query);
+ const queryText = Lib.rawNativeQuery(query);
+ const canFormatQuery = engine != null && canFormatForEngine(engine);
+ if (!canFormatQuery) {
+ return undefined;
+ }
+
+ if (!engine || !canFormatForEngine(engine)) {
+ // no engine found, do nothing
+ return;
+ }
+
+ const formattedQuery = await formatQuery(queryText, engine);
+ handleChange(formattedQuery);
+ focusEditor();
+ }, [question, focusEditor, handleChange]);
+
+ const handleResize = useCallback(
+ (height: number) => {
+ handleResizeFromProps?.();
+
+ // If the height is lower than the threshold for auto-closing,
+ // close the editor
+ if (height <= THRESHOLD_FOR_AUTO_CLOSE) {
+ setIsNativeEditorOpen?.(false);
+ return;
+ }
+ },
+ [handleResizeFromProps, setIsNativeEditorOpen],
+ );
+
+ const contextValue: NativeQueryEditorContextValue = {
+ question,
+ query,
+ setDatasetQuery,
+ focusEditor,
+ onFormatQuery: handleFormatQuery,
+ readOnly,
+ isNativeEditorOpen,
+ setIsNativeEditorOpen,
+ toggleEditor,
+ canChangeDatabase,
+ editorContext,
+ databaseIsDisabled,
+ databaseDisabledTooltip,
+ onSetDatabaseId,
+ setParameterValue,
+ isRunnable,
+ isRunning,
+ isResultDirty,
+ runQuery,
+ cancelQuery,
+ nativeEditorSelectedText,
+ snippets,
+ snippetCollections,
+ isShowingDataReference,
+ isShowingSnippetSidebar,
+ isShowingTemplateTagsEditor,
+ toggleDataReference,
+ toggleSnippetSidebar,
+ toggleTemplateTagsEditor,
+ onOpenModal,
+ };
+
+ // Separate the top bar (rendered in the header) from the body slots (run
+ // button, extra buttons, custom content rendered over the editor surface).
+ let topBar: ReactNode = null;
+ const bodySlots: ReactNode[] = [];
+ Children.forEach(children, (child) => {
+ if (isValidElement(child) && child.type === TopBar) {
+ topBar = cloneElement(child, { ref: topBarRef });
+ } else {
+ bodySlots.push(child);
+ }
+ });
+
+ return (
+ <NativeQueryEditorContextProvider value={contextValue}>
+ <div
+ className={cx(S.queryEditor, className, {
+ [S.readOnlyEditor]: readOnly,
+ })}
+ data-testid="native-query-editor-container"
+ ref={ref}
+ >
+ {topBar}
+ <div className={S.editorWrapper}>
+ {shouldShowEditor && (
+ <ResizableArea
+ resizable={resizable}
+ minHeight={MIN_EDITOR_HEIGHT_AFTER_DRAGGING}
+ maxHeight={
+ availableHeight - topBarHeight - RESIZE_CONSTRAINT_OFFSET
+ }
+ onResize={handleResize}
+ initialHeight={getInitialEditorHeight({ query, availableHeight })}
+ className={S.resizableArea}
+ >
+ <Flex w="100%" flex="1" className={S.resizableBoxContent}>
+ <CodeMirrorEditor
+ ref={editorRef}
+ query={question.query()}
+ proposedQuery={proposedQuestion?.query()}
+ readOnly={readOnly}
+ placeholder={placeholder}
+ highlightedLineNumbers={highlightedLineNumbers}
+ extensions={extensions}
+ onBlur={onBlur}
+ onChange={handleChange}
+ onRunQuery={runQuery}
+ onSelectionChange={setNativeEditorSelectedRange}
+ onCursorMoveOverCardTag={openDataReferenceAtQuestion}
+ onRightClickSelection={handleRightClickSelection}
+ onFormatQuery={handleFormatQuery}
+ />
+
+ <Stack
+ display={readOnly ? "none" : undefined}
+ gap="md"
+ justify="flex-end"
+ p="md"
+ >
+ {proposedQuestion && onRejectProposed && onAcceptProposed && (
+ <>
+ <Tooltip
+ label={t`Accept proposed changes`}
+ position="top"
+ >
+ <Button
+ data-testid="accept-proposed-changes-button"
+ variant="filled"
+ bg="success"
+ px="0"
+ w="2.5rem"
+ onClick={() => {
+ const proposedQuery =
+ proposedQuestion.legacyNativeQuery();
+ if (proposedQuery) {
+ handleChange(proposedQuery.queryText());
+ onAcceptProposed(proposedQuery.datasetQuery());
+ }
+ }}
+ >
+ <Icon name="check" />
+ </Button>
+ </Tooltip>
+ <Tooltip
+ label={t`Reject proposed changes`}
+ position="top"
+ >
+ <Button
+ data-testid="reject-proposed-changes-button"
+ w="2.5rem"
+ px="0"
+ variant="filled"
+ bg="danger"
+ onClick={onRejectProposed}
+ >
+ <Icon name="close" />
+ </Button>
+ </Tooltip>
+ </>
+ )}
+ <Flex gap="sm">{bodySlots}</Flex>
+ </Stack>
+ </Flex>
+ </ResizableArea>
+ )}
+ </div>
+
+ <RightClickPopover
+ isOpen={isSelectedTextPopoverOpen}
+ openSnippetModalWithSelectedText={openSnippetModalWithSelectedText}
+ runQuery={runQuery}
+ target={() => editorRef.current?.getSelectionTarget()}
+ canSaveSnippets={canSaveSnippets}
+ />
+
+ {modalSnippet && insertSnippet && closeSnippetModal && (
+ <SnippetFormModal
+ snippet={modalSnippet}
+ onCreate={insertSnippet}
+ onUpdate={handleSnippetUpdate}
+ onClose={closeSnippetModal}
+ />
+ )}
+ </div>
+ </NativeQueryEditorContextProvider>
+ );
+});
diff --git a/frontend/src/metabase/query_builder/components/NativeQueryEditor/NativeQueryEditorTopBar/NativeQueryEditorTopBar.tsx b/frontend/src/metabase/query_builder/components/NativeQueryEditor/NativeQueryEditorTopBar/NativeQueryEditorTopBar.tsx
deleted file mode 100644
index 2746e026097..00000000000
--- a/frontend/src/metabase/query_builder/components/NativeQueryEditor/NativeQueryEditorTopBar/NativeQueryEditorTopBar.tsx
+++ /dev/null
@@ -1,190 +0,0 @@
-import { type PropsWithChildren, forwardRef } from "react";
-
-import { updateQuestion } from "metabase/query_builder/actions/core";
-import type { QueryModalType } from "metabase/querying/constants";
-import type { SidebarFeatures } from "metabase/querying/editor/types";
-import { useDispatch } from "metabase/redux";
-import { Flex } from "metabase/ui";
-import type Question from "metabase-lib/v1/Question";
-import type Database from "metabase-lib/v1/metadata/Database";
-import type NativeQuery from "metabase-lib/v1/queries/NativeQuery";
-import type {
- Collection,
- DatabaseId,
- NativeQuerySnippet,
- ParameterId,
- TableId,
-} from "metabase-types/api";
-
-import { ResponsiveParametersList } from "../../ResponsiveParametersList";
-import { DataSourceSelectors } from "../DataSourceSelectors/DataSourceSelectors";
-import { NativeQueryEditorActionButtons } from "../NativeQueryEditorActionButtons/NativeQueryEditorActionButtons";
-import { VisibilityToggler } from "../VisibilityToggler/VisibilityToggler";
-
-interface NativeQueryEditorTopBarProps extends PropsWithChildren {
- question: Question;
- query: NativeQuery;
-
- isRunnable: boolean;
- isRunning: boolean;
- isResultDirty: boolean;
- isShowingSnippetSidebar: boolean;
- isShowingDataReference: boolean;
- isShowingTemplateTagsEditor: boolean;
- isNativeEditorOpen: boolean;
- canChangeDatabase: boolean;
- hasParametersList?: boolean;
- hasEditingSidebar: boolean;
- readOnly?: boolean;
-
- snippets?: NativeQuerySnippet[];
- editorContext?: "question" | "action";
- snippetCollections?: Collection[];
- sidebarFeatures: SidebarFeatures;
-
- toggleEditor?: () => void;
- toggleDataReference?: () => void;
- toggleSnippetSidebar?: () => void;
- toggleTemplateTagsEditor?: () => void;
- setIsNativeEditorOpen?: (isOpen: boolean) => void;
- onFormatQuery?: () => void;
- onSetDatabaseId?: (id: DatabaseId) => void;
- onOpenModal?: (modalType: QueryModalType) => void;
- setParameterValue?: (parameterId: ParameterId, value: string) => void;
- focus: () => void;
- setDatasetQuery: (query: NativeQuery) => void;
- databaseIsDisabled?: (database: Database) => boolean;
- databaseDisabledTooltip?: (database: Database) => string | undefined;
-}
-
-export const NativeQueryEditorTopBar = forwardRef<
- HTMLDivElement,
- NativeQueryEditorTopBarProps
->(function NativeQueryEditorTopBarInner(props, ref) {
- const {
- children,
- query,
- question,
- canChangeDatabase,
- isNativeEditorOpen,
- readOnly,
- editorContext = "question",
- setParameterValue,
- sidebarFeatures,
- hasEditingSidebar,
- snippetCollections,
- focus: setFocus,
- snippets,
- isRunnable,
- isRunning,
- isResultDirty,
- isShowingDataReference,
- isShowingTemplateTagsEditor,
- isShowingSnippetSidebar,
- onFormatQuery,
- onOpenModal,
- setIsNativeEditorOpen,
- toggleEditor,
- toggleDataReference,
- toggleSnippetSidebar,
- toggleTemplateTagsEditor,
- onSetDatabaseId,
- hasParametersList = true,
- setDatasetQuery,
- databaseIsDisabled,
- databaseDisabledTooltip,
- } = props;
-
- const dispatch = useDispatch();
-
- const setTableId = (tableId: TableId) => {
- const table = query.metadata().table(tableId);
- if (table && table.name !== query.collection()) {
- setDatasetQuery(query.setCollectionName(table.name));
- }
- };
-
- const setParameterIndex = (
- parameterId: ParameterId,
- parameterIndex: number,
- ) => {
- const newQuery = query.setParameterIndex(parameterId, parameterIndex);
- dispatch(updateQuestion(question.setDatasetQuery(newQuery.datasetQuery())));
- };
-
- // Change the Database we're currently editing a query for.
- const setDatabaseId = (databaseId: DatabaseId) => {
- if (question.databaseId() !== databaseId) {
- setDatasetQuery(query.setDatabaseId(databaseId).setDefaultCollection());
-
- onSetDatabaseId?.(databaseId);
- setFocus();
- }
- };
-
- if (!question) {
- return null;
- }
-
- const parameters = question.parameters();
-
- return (
- <Flex align="flex-start" data-testid="native-query-top-bar" ref={ref}>
- {canChangeDatabase && (
- <DataSourceSelectors
- isNativeEditorOpen={isNativeEditorOpen}
- query={query}
- question={question}
- readOnly={readOnly}
- setDatabaseId={setDatabaseId}
- setTableId={setTableId}
- editorContext={editorContext}
- databaseIsDisabled={databaseIsDisabled}
- databaseDisabledTooltip={databaseDisabledTooltip}
- />
- )}
- {hasParametersList && setParameterValue && (
- <ResponsiveParametersList
- cardId={question.id()}
- dashboardId={question.getDashboardProps().dashboardId}
- parameters={parameters}
- setParameterValue={setParameterValue}
- setParameterIndex={setParameterIndex}
- enableParameterRequiredBehavior
- />
- )}
- <Flex ml="auto" gap="lg" mr="lg" align="center" h="3rem" pl="md">
- {children}
- {isNativeEditorOpen && hasEditingSidebar && !readOnly && (
- <NativeQueryEditorActionButtons
- features={sidebarFeatures}
- onFormatQuery={onFormatQuery}
- question={question}
- snippetCollections={snippetCollections}
- snippets={snippets}
- isRunnable={isRunnable}
- isRunning={isRunning}
- isResultDirty={isResultDirty}
- isShowingDataReference={isShowingDataReference}
- isShowingTemplateTagsEditor={isShowingTemplateTagsEditor}
- isShowingSnippetSidebar={isShowingSnippetSidebar}
- toggleDataReference={toggleDataReference}
- toggleSnippetSidebar={toggleSnippetSidebar}
- toggleTemplateTagsEditor={toggleTemplateTagsEditor}
- onOpenModal={onOpenModal}
- />
- )}
- {query.hasWritePermission() &&
- !question.isArchived() &&
- setIsNativeEditorOpen &&
- toggleEditor && (
- <VisibilityToggler
- isOpen={isNativeEditorOpen}
- readOnly={!!readOnly}
- toggleEditor={toggleEditor}
- />
- )}
- </Flex>
- </Flex>
- );
-});
diff --git a/frontend/src/metabase/query_builder/components/NativeQueryEditor/__mocks__/NativeQueryEditor.jsx b/frontend/src/metabase/query_builder/components/NativeQueryEditor/__mocks__/NativeQueryEditor.jsx
index 35c6f09eb15..200725c1c2d 100644
--- a/frontend/src/metabase/query_builder/components/NativeQueryEditor/__mocks__/NativeQueryEditor.jsx
+++ b/frontend/src/metabase/query_builder/components/NativeQueryEditor/__mocks__/NativeQueryEditor.jsx
@@ -55,3 +55,13 @@ export const NativeQueryEditor = ({
</div>
);
};
+
+// The composition sub-components are rendered as children of the mocked editor,
+// which ignores its children. They only need to be valid components so consumers
+// using the composition API keep working under the mock.
+const Noop = () => null;
+NativeQueryEditor.TopBar = Noop;
+NativeQueryEditor.Sidebar = Noop;
+NativeQueryEditor.ParametersList = Noop;
+NativeQueryEditor.VisibilityToggler = Noop;
+NativeQueryEditor.RunButton = Noop;
diff --git a/frontend/src/metabase/query_builder/components/NativeQueryEditor/context/NativeQueryEditorContext.tsx b/frontend/src/metabase/query_builder/components/NativeQueryEditor/context/NativeQueryEditorContext.tsx
new file mode 100644
index 00000000000..dcac28b56b6
--- /dev/null
+++ b/frontend/src/metabase/query_builder/components/NativeQueryEditor/context/NativeQueryEditorContext.tsx
@@ -0,0 +1,76 @@
+import { createContext, useContext } from "react";
+
+import type { QueryModalType } from "metabase/querying/constants";
+import type Question from "metabase-lib/v1/Question";
+import type Database from "metabase-lib/v1/metadata/Database";
+import type NativeQuery from "metabase-lib/v1/queries/NativeQuery";
+import type {
+ Collection,
+ DatabaseId,
+ NativeQuerySnippet,
+ ParameterId,
+} from "metabase-types/api";
+
+/**
+ * Shared state and handlers provided by the {@link NativeQueryEditor} root to
+ * its composable sub-components (TopBar, Sidebar, ParametersList,
+ * VisibilityToggler, RunButton). Sub-components read what they need from this
+ * context instead of receiving the full set of props from every consumer.
+ */
+export interface NativeQueryEditorContextValue {
+ question: Question;
+ query: NativeQuery;
+ setDatasetQuery: (query: NativeQuery) => void;
+
+ focusEditor: () => void;
+ onFormatQuery: () => void;
+
+ readOnly?: boolean;
+ isNativeEditorOpen: boolean;
+ setIsNativeEditorOpen?: (
+ isOpen: boolean,
+ shouldOpenDataReference?: boolean,
+ ) => void;
+ toggleEditor: () => void;
+
+ canChangeDatabase: boolean;
+ editorContext: "question" | "action";
+ databaseIsDisabled?: (database: Database) => boolean;
+ databaseDisabledTooltip?: (database: Database) => string | undefined;
+ onSetDatabaseId?: (id: DatabaseId) => void;
+ setParameterValue?: (parameterId: ParameterId, value: string) => void;
+
+ isRunnable: boolean;
+ isRunning: boolean;
+ isResultDirty: boolean;
+ runQuery?: () => void;
+ cancelQuery?: () => void;
+ nativeEditorSelectedText?: string | null;
+
+ snippets: NativeQuerySnippet[];
+ snippetCollections: Collection[];
+
+ isShowingDataReference: boolean;
+ isShowingSnippetSidebar: boolean;
+ isShowingTemplateTagsEditor: boolean;
+ toggleDataReference?: () => void;
+ toggleSnippetSidebar?: () => void;
+ toggleTemplateTagsEditor?: () => void;
+ onOpenModal?: (modalType: QueryModalType) => void;
+}
+
+const NativeQueryEditorContext =
+ createContext<NativeQueryEditorContextValue | null>(null);
+
+export const NativeQueryEditorContextProvider =
+ NativeQueryEditorContext.Provider;
+
+export function useNativeQueryEditorContext(): NativeQueryEditorContextValue {
+ const context = useContext(NativeQueryEditorContext);
+ if (!context) {
+ throw new Error(
+ "NativeQueryEditor sub-components must be rendered inside <NativeQueryEditor>",
+ );
+ }
+ return context;
+}
diff --git a/frontend/src/metabase/query_builder/components/NativeQueryEditor/slots/ParametersList.tsx b/frontend/src/metabase/query_builder/components/NativeQueryEditor/slots/ParametersList.tsx
new file mode 100644
index 00000000000..9c14d5bfecd
--- /dev/null
+++ b/frontend/src/metabase/query_builder/components/NativeQueryEditor/slots/ParametersList.tsx
@@ -0,0 +1,38 @@
+import { updateQuestion } from "metabase/query_builder/actions/core";
+import { ResponsiveParametersList } from "metabase/query_builder/components/ResponsiveParametersList";
+import { useDispatch } from "metabase/redux";
+import type { ParameterId } from "metabase-types/api";
+
+import { useNativeQueryEditorContext } from "../context/NativeQueryEditorContext";
+
+/**
+ * The list of native query parameters (template tag values) shown in the top
+ * bar. Renders nothing when the consumer did not provide `setParameterValue`.
+ */
+export function ParametersList() {
+ const { question, query, setParameterValue } = useNativeQueryEditorContext();
+ const dispatch = useDispatch();
+
+ if (!setParameterValue) {
+ return null;
+ }
+
+ const setParameterIndex = (
+ parameterId: ParameterId,
+ parameterIndex: number,
+ ) => {
+ const newQuery = query.setParameterIndex(parameterId, parameterIndex);
+ dispatch(updateQuestion(question.setDatasetQuery(newQuery.datasetQuery())));
+ };
+
+ return (
+ <ResponsiveParametersList
+ cardId={question.id()}
+ dashboardId={question.getDashboardProps().dashboardId}
+ parameters={question.parameters()}
+ setParameterValue={setParameterValue}
+ setParameterIndex={setParameterIndex}
+ enableParameterRequiredBehavior
+ />
+ );
+}
diff --git a/frontend/src/metabase/query_builder/components/NativeQueryEditor/slots/RunButton.tsx b/frontend/src/metabase/query_builder/components/NativeQueryEditor/slots/RunButton.tsx
new file mode 100644
index 00000000000..59aa380ede5
--- /dev/null
+++ b/frontend/src/metabase/query_builder/components/NativeQueryEditor/slots/RunButton.tsx
@@ -0,0 +1,37 @@
+import * as Lib from "metabase-lib";
+
+import { NativeQueryEditorRunButton } from "../NativeQueryEditorRunButton/NativeQueryEditorRunButton";
+import { useNativeQueryEditorContext } from "../context/NativeQueryEditorContext";
+
+/**
+ * The run/cancel button shown over the editor surface. Renders nothing while
+ * the editor is read-only or when no run handler is wired up.
+ */
+export function RunButton() {
+ const {
+ question,
+ readOnly,
+ isRunnable,
+ isRunning,
+ isResultDirty,
+ nativeEditorSelectedText,
+ runQuery,
+ cancelQuery,
+ } = useNativeQueryEditorContext();
+
+ if (readOnly || !runQuery || !cancelQuery) {
+ return null;
+ }
+
+ return (
+ <NativeQueryEditorRunButton
+ cancelQuery={cancelQuery}
+ isResultDirty={isResultDirty}
+ isRunnable={isRunnable}
+ isRunning={isRunning}
+ nativeEditorSelectedText={nativeEditorSelectedText}
+ runQuery={runQuery}
+ questionErrors={Lib.validateTemplateTags(question.query())}
+ />
+ );
+}
diff --git a/frontend/src/metabase/query_builder/components/NativeQueryEditor/slots/Sidebar.tsx b/frontend/src/metabase/query_builder/components/NativeQueryEditor/slots/Sidebar.tsx
new file mode 100644
index 00000000000..a25dc23500c
--- /dev/null
+++ b/frontend/src/metabase/query_builder/components/NativeQueryEditor/slots/Sidebar.tsx
@@ -0,0 +1,66 @@
+import type { SidebarFeatures } from "metabase/querying/editor/types";
+
+import { NativeQueryEditorActionButtons } from "../NativeQueryEditorActionButtons/NativeQueryEditorActionButtons";
+import { useNativeQueryEditorContext } from "../context/NativeQueryEditorContext";
+
+interface SidebarProps {
+ features?: SidebarFeatures;
+}
+
+const DEFAULT_FEATURES: SidebarFeatures = {
+ dataReference: true,
+ variables: true,
+ snippets: true,
+ promptInput: true,
+ formatQuery: true,
+};
+
+/**
+ * The editing-sidebar action buttons (data reference, variables, snippets,
+ * auto-format, preview) shown on the right of the top bar. Renders nothing
+ * while the editor is collapsed or read-only.
+ */
+export function Sidebar({ features = DEFAULT_FEATURES }: SidebarProps) {
+ const {
+ question,
+ snippets,
+ snippetCollections,
+ isNativeEditorOpen,
+ readOnly,
+ isRunnable,
+ isRunning,
+ isResultDirty,
+ isShowingDataReference,
+ isShowingTemplateTagsEditor,
+ isShowingSnippetSidebar,
+ toggleDataReference,
+ toggleSnippetSidebar,
+ toggleTemplateTagsEditor,
+ onOpenModal,
+ onFormatQuery,
+ } = useNativeQueryEditorContext();
+
+ if (!isNativeEditorOpen || readOnly) {
+ return null;
+ }
+
+ return (
+ <NativeQueryEditorActionButtons
+ features={features}
+ onFormatQuery={onFormatQuery}
+ question={question}
+ snippets={snippets}
+ snippetCollections={snippetCollections}
+ isRunnable={isRunnable}
+ isRunning={isRunning}
+ isResultDirty={isResultDirty}
+ isShowingDataReference={isShowingDataReference}
+ isShowingTemplateTagsEditor={isShowingTemplateTagsEditor}
+ isShowingSnippetSidebar={isShowingSnippetSidebar}
+ toggleDataReference={toggleDataReference}
+ toggleSnippetSidebar={toggleSnippetSidebar}
+ toggleTemplateTagsEditor={toggleTemplateTagsEditor}
+ onOpenModal={onOpenModal}
+ />
+ );
+}
diff --git a/frontend/src/metabase/query_builder/components/NativeQueryEditor/slots/TopBar.tsx b/frontend/src/metabase/query_builder/components/NativeQueryEditor/slots/TopBar.tsx
new file mode 100644
index 00000000000..4b7533b9fd6
--- /dev/null
+++ b/frontend/src/metabase/query_builder/components/NativeQueryEditor/slots/TopBar.tsx
@@ -0,0 +1,90 @@
+import {
+ Children,
+ type PropsWithChildren,
+ type ReactNode,
+ forwardRef,
+ isValidElement,
+} from "react";
+
+import { Flex } from "metabase/ui";
+import type { DatabaseId, TableId } from "metabase-types/api";
+
+import { DataSourceSelectors } from "../DataSourceSelectors/DataSourceSelectors";
+import { useNativeQueryEditorContext } from "../context/NativeQueryEditorContext";
+
+import { ParametersList } from "./ParametersList";
+
+/**
+ * The top bar of the native query editor. Renders the data source selector on
+ * the left (from context) and lays out its children, keeping the parameters
+ * list on the left and pushing the remaining actions (sidebar buttons,
+ * visibility toggler, custom content) into the right-aligned cluster.
+ */
+export const TopBar = forwardRef<HTMLDivElement, PropsWithChildren>(
+ function TopBar({ children }, ref) {
+ const {
+ question,
+ query,
+ canChangeDatabase,
+ isNativeEditorOpen,
+ readOnly,
+ editorContext,
+ setDatasetQuery,
+ onSetDatabaseId,
+ focusEditor,
+ databaseIsDisabled,
+ databaseDisabledTooltip,
+ } = useNativeQueryEditorContext();
+
+ if (!question) {
+ return null;
+ }
+
+ const setTableId = (tableId: TableId) => {
+ const table = query.metadata().table(tableId);
+ if (table && table.name !== query.collection()) {
+ setDatasetQuery(query.setCollectionName(table.name));
+ }
+ };
+
+ const setDatabaseId = (databaseId: DatabaseId) => {
+ if (question.databaseId() !== databaseId) {
+ setDatasetQuery(query.setDatabaseId(databaseId).setDefaultCollection());
+ onSetDatabaseId?.(databaseId);
+ focusEditor();
+ }
+ };
+
+ const leftActions: ReactNode[] = [];
+ const rightActions: ReactNode[] = [];
+ Children.forEach(children, (child) => {
+ if (isValidElement(child) && child.type === ParametersList) {
+ leftActions.push(child);
+ } else {
+ rightActions.push(child);
+ }
+ });
+
+ return (
+ <Flex align="flex-start" data-testid="native-query-top-bar" ref={ref}>
+ {canChangeDatabase && (
+ <DataSourceSelectors
+ isNativeEditorOpen={isNativeEditorOpen}
+ query={query}
+ question={question}
+ readOnly={readOnly}
+ setDatabaseId={setDatabaseId}
+ setTableId={setTableId}
+ editorContext={editorContext}
+ databaseIsDisabled={databaseIsDisabled}
+ databaseDisabledTooltip={databaseDisabledTooltip}
+ />
+ )}
+ {leftActions}
+ <Flex ml="auto" gap="lg" mr="lg" align="center" h="3rem" pl="md">
+ {rightActions}
+ </Flex>
+ </Flex>
+ );
+ },
+);
diff --git a/frontend/src/metabase/query_builder/components/NativeQueryEditor/slots/VisibilityToggler.tsx b/frontend/src/metabase/query_builder/components/NativeQueryEditor/slots/VisibilityToggler.tsx
new file mode 100644
index 00000000000..56b35471061
--- /dev/null
+++ b/frontend/src/metabase/query_builder/components/NativeQueryEditor/slots/VisibilityToggler.tsx
@@ -0,0 +1,34 @@
+import { VisibilityToggler as VisibilityTogglerControl } from "../VisibilityToggler/VisibilityToggler";
+import { useNativeQueryEditorContext } from "../context/NativeQueryEditorContext";
+
+/**
+ * The open/close toggle for the editor. Renders nothing unless the query is
+ * writable, the question is not archived, and the consumer wired up the
+ * open/close handlers.
+ */
+export function VisibilityToggler() {
+ const {
+ query,
+ question,
+ isNativeEditorOpen,
+ readOnly,
+ setIsNativeEditorOpen,
+ toggleEditor,
+ } = useNativeQueryEditorContext();
+
+ if (
+ !query.hasWritePermission() ||
+ question.isArchived() ||
+ !setIsNativeEditorOpen
+ ) {
+ return null;
+ }
+
+ return (
+ <VisibilityTogglerControl
+ isOpen={isNativeEditorOpen}
+ readOnly={!!readOnly}
+ toggleEditor={toggleEditor}
+ />
+ );
+}