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
Set max height to native editor and some other refactors (#67896)
Romeo Van Snick7451ffcd9373
diff --git a/e2e/test/scenarios/dashboard/dashboard-back-navigation.cy.spec.js b/e2e/test/scenarios/dashboard/dashboard-back-navigation.cy.spec.jsindex 625ed372215..409ddb74fc3 100644--- a/e2e/test/scenarios/dashboard/dashboard-back-navigation.cy.spec.js+++ b/e2e/test/scenarios/dashboard/dashboard-back-navigation.cy.spec.js@@ -75,7 +75,7 @@ describe("scenarios > dashboard > dashboard back navigation", () => {cy.findByTestId("native-query-top-bar").findByText("This question is written in SQL.").should("be.visible");- H.NativeEditor.get().should("not.be.visible");+ H.NativeEditor.get().should("not.exist");});it("should display a back to the dashboard button in table x-ray dashboards", () => {diff --git a/e2e/test/scenarios/native-filters/native-filters-reproductions.cy.spec.js b/e2e/test/scenarios/native-filters/native-filters-reproductions.cy.spec.jsindex 05c1ac91655..ac6277f33af 100644--- a/e2e/test/scenarios/native-filters/native-filters-reproductions.cy.spec.js+++ b/e2e/test/scenarios/native-filters/native-filters-reproductions.cy.spec.js@@ -435,7 +435,7 @@ describe("issue 14302", () => {expect(xhr.response.body.error).not.to.exist;});- H.NativeEditor.get().should("not.be.visible");+ H.NativeEditor.get().should("not.exist");cy.get("[data-testid=cell-data]").should("contain", "51");// eslint-disable-next-line no-unscoped-text-selectors -- deprecated usagecy.findByText("Showing 1 row");diff --git a/e2e/test/scenarios/native/native-reproductions.cy.spec.ts b/e2e/test/scenarios/native/native-reproductions.cy.spec.tsindex 41eb8269e30..8c3aed5b8f3 100644--- a/e2e/test/scenarios/native/native-reproductions.cy.spec.ts+++ b/e2e/test/scenarios/native/native-reproductions.cy.spec.ts@@ -682,8 +682,7 @@ describe("issue 59110", () => {H.NativeEditor.get().then((editor) => {const { height } = editor[0].getBoundingClientRect();- const SLOPPY_CLICK_THRESHOLD = 30;- const diff = height - SLOPPY_CLICK_THRESHOLD;+ const diff = height + 20;cy.log("drag the border to hide the editor");@@ -698,12 +697,11 @@ describe("issue 59110", () => {.trigger("mousemove", {clientX: coordsDrag.x,clientY: coordsDrag.y - diff,- })- .trigger("mouseup");+ });});});- H.NativeEditor.get().should("not.be.visible");+ H.NativeEditor.get().should("not.exist");cy.findByTestId("visibility-toggler").findByText(/open editor/i).should("be.visible")@@ -762,7 +760,9 @@ describe("issue 60719", () => {describe("issue 59356", () => {function typeRunShortcut() {- cy.get("body").type("{ctrl+enter}{cmd+enter}");+ const isMac = Cypress.platform === "darwin";+ const metaKey = isMac ? "Meta" : "Control";+ cy.realPress([metaKey, "Enter"]);}function getLoader() {@@ -974,3 +974,43 @@ describe("issue 51717", () => {cy.get("@infoSidebar").should("contain", "You created this");});});++describe("issue 59075", () => {+ const WINDOW_HEIGHT = 1000;+ const BUTTON_INDEX = 0;++ beforeEach(() => {+ H.restore();+ cy.signInAsNormalUser();++ H.startNewNativeQuestion();+ cy.viewport(1024, WINDOW_HEIGHT);+ });++ it("should not be possible to resize the native query editor too far (metabase#59075)", () => {+ cy.findByTestId("drag-handle").then((handle) => {+ const coordsDrag = handle[0].getBoundingClientRect();++ cy.wrap(handle)+ .trigger("mousedown", {+ button: BUTTON_INDEX,+ clientX: coordsDrag.x,+ clientY: coordsDrag.y,+ force: true,+ })+ // Drag to the bottom of the screen+ .trigger("mousemove", {+ button: BUTTON_INDEX,+ clientX: coordsDrag.x,+ clientY: WINDOW_HEIGHT + 10,+ force: true,+ })+ .trigger("mouseup");+ });++ H.NativeEditor.get().then((editor) => {+ const { bottom } = editor.get()[0].getBoundingClientRect();+ cy.wrap(bottom).should("be.lessThan", WINDOW_HEIGHT - 50);+ });+ });+});diff --git a/e2e/test/scenarios/visualizations-charts/bar_chart.cy.spec.js b/e2e/test/scenarios/visualizations-charts/bar_chart.cy.spec.jsindex 201f0e89ea8..d0a7dc29e92 100644--- a/e2e/test/scenarios/visualizations-charts/bar_chart.cy.spec.js+++ b/e2e/test/scenarios/visualizations-charts/bar_chart.cy.spec.js@@ -1120,6 +1120,9 @@ describe("scenarios > visualizations > bar chart", () => {},});+ // Open the data reference sidebar to squish the data further+ cy.findByLabelText("Learn about your data").click();+cy.wait("@dataset");H.echartsContainer().should("be.visible");diff --git a/frontend/src/metabase-lib/v1/queries/NativeQuery.ts b/frontend/src/metabase-lib/v1/queries/NativeQuery.tsindex befbcbe20c9..54f62a0be7f 100644--- a/frontend/src/metabase-lib/v1/queries/NativeQuery.ts+++ b/frontend/src/metabase-lib/v1/queries/NativeQuery.ts@@ -22,6 +22,7 @@ import type {import { TemplateTagDimension } from "../Dimension";import DimensionOptions from "../DimensionOptions";+import Metadata from "../metadata/Metadata";import { getNativeQueryTable } from "./utils/native-query-table";@@ -355,17 +356,24 @@ export default class NativeQuery {oldSnippet: NativeQuerySnippet,newSnippet: NativeQuerySnippet,) {+ // We need to update the metadata first to make sure the new snippet+ // is correctly extracted from the query+ let newQuery = new NativeQuery(this.question(), this.datasetQuery());++ const metadata = new Metadata(this.metadata());+ delete metadata.snippets[oldSnippet.id];+ metadata.snippets[newSnippet.id] = newSnippet;+ newQuery.question()._metadata = metadata;+// if the snippet name has changed, we need to update it in the query- const newQuery =+ newQuery =newSnippet.name !== oldSnippet.name- ? this.updateSnippetNames([newSnippet])- : this;+ ? newQuery.updateSnippetNames([newSnippet])+ : newQuery;// if the query has changed, it was already parsed; otherwise do the parsing// to expand snippet tags into the query tags- return newQuery === this- ? newQuery.setQueryText(newQuery.queryText())- : newQuery;+ return newQuery.setQueryText(newQuery.queryText());}updateSnippetNames(snippets: NativeQuerySnippet[]): NativeQuery {diff --git a/frontend/src/metabase/actions/containers/ActionCreator/ActionContext/QueryActionContextProvider/QueryActionEditor.tsx b/frontend/src/metabase/actions/containers/ActionCreator/ActionContext/QueryActionContextProvider/QueryActionEditor.tsxindex 258115fd679..22b1b0b30b8 100644--- a/frontend/src/metabase/actions/containers/ActionCreator/ActionContext/QueryActionContextProvider/QueryActionEditor.tsx+++ b/frontend/src/metabase/actions/containers/ActionCreator/ActionContext/QueryActionContextProvider/QueryActionEditor.tsx@@ -1,4 +1,4 @@-import NativeQueryEditor from "metabase/query_builder/components/NativeQueryEditor";+import { NativeQueryEditor } from "metabase/query_builder/components/NativeQueryEditor";import type Question from "metabase-lib/v1/Question";import type NativeQuery from "metabase-lib/v1/queries/NativeQuery";@@ -17,9 +17,7 @@ function QueryActionEditor({<NativeQueryEditorquery={query}question={question}- viewHeight="full"setDatasetQuery={onChangeQuestionQuery}- enableRun={true}hasEditingSidebar={false}isNativeEditorOpenhasParametersList={false}diff --git a/frontend/src/metabase/query_builder/actions/native.ts b/frontend/src/metabase/query_builder/actions/native.tsindex 3bdb3c88629..d74eea81cab 100644--- a/frontend/src/metabase/query_builder/actions/native.ts+++ b/frontend/src/metabase/query_builder/actions/native.ts@@ -23,7 +23,7 @@ import {} from "../selectors";import { updateQuestion } from "./core/updateQuestion";-import { SET_UI_CONTROLS } from "./ui";+import { setUIControls } from "./ui";export const TOGGLE_DATA_REFERENCE = "metabase/qb/TOGGLE_DATA_REFERENCE";export const toggleDataReference = createAction(TOGGLE_DATA_REFERENCE);@@ -91,10 +91,24 @@ export const setIsShowingSnippetSidebar = (isShowingSnippetSidebar,});-export const setIsNativeEditorOpen = (isNativeEditorOpen: boolean) => ({- type: SET_UI_CONTROLS,- payload: { isNativeEditorOpen, isShowingDataReference: isNativeEditorOpen },-});+export const SET_IS_NATIVE_EDITOR_OPEN =+ "metabase/qb/SET_IS_NATIVE_EDITOR_OPEN";+export const setIsNativeEditorOpen = createThunkAction(+ SET_IS_NATIVE_EDITOR_OPEN,+ (isNativeEditorOpen: boolean, toggleDataReference?: boolean) =>+ (dispatch) => {+ if (toggleDataReference) {+ dispatch(+ setUIControls({+ isNativeEditorOpen,+ isShowingDataReference: isNativeEditorOpen,+ }),+ );+ } else {+ dispatch(setUIControls({ isNativeEditorOpen }));+ }+ },+);export const SET_NATIVE_EDITOR_SELECTED_RANGE ="metabase/qb/SET_NATIVE_EDITOR_SELECTED_RANGE";diff --git a/frontend/src/metabase/query_builder/components/DatasetEditor/DatasetEditorInner.tsx b/frontend/src/metabase/query_builder/components/DatasetEditor/DatasetEditorInner.tsxindex ad9cf919491..89f443c43fb 100644--- a/frontend/src/metabase/query_builder/components/DatasetEditor/DatasetEditorInner.tsx+++ b/frontend/src/metabase/query_builder/components/DatasetEditor/DatasetEditorInner.tsx@@ -31,7 +31,7 @@ import {setUIControls,updateQuestion as updateQuestionAction,} from "metabase/query_builder/actions";-import { calcInitialEditorHeight } from "metabase/query_builder/components/NativeQueryEditor/utils";+import { getInitialEditorHeight } from "metabase/query_builder/components/NativeQueryEditor/utils";import QueryVisualization from "metabase/query_builder/components/QueryVisualization";import DataReference from "metabase/query_builder/components/dataref/DataReference";import { SnippetSidebar } from "metabase/query_builder/components/template_tags/SnippetSidebar/SnippetSidebar";@@ -371,9 +371,9 @@ const _DatasetEditorInner = (props: DatasetEditorInnerProps) => {if (!isNative) {return INITIAL_NOTEBOOK_EDITOR_HEIGHT;}- return calcInitialEditorHeight({+ return getInitialEditorHeight({query: question.legacyNativeQuery(),- viewHeight: height ?? "full",+ availableHeight: height ?? "full",});}, [question, height]);diff --git a/frontend/src/metabase/query_builder/components/DatasetEditor/DatasetQueryEditor.jsx b/frontend/src/metabase/query_builder/components/DatasetEditor/DatasetQueryEditor.jsxindex bd870dee639..25178e89f5b 100644--- a/frontend/src/metabase/query_builder/components/DatasetEditor/DatasetQueryEditor.jsx+++ b/frontend/src/metabase/query_builder/components/DatasetEditor/DatasetQueryEditor.jsx@@ -3,7 +3,7 @@ import PropTypes from "prop-types";import { memo, useMemo, useState } from "react";import { isReducedMotionPreferred } from "metabase/lib/dom";-import NativeQueryEditor from "metabase/query_builder/components/NativeQueryEditor";+import { NativeQueryEditor } from "metabase/query_builder/components/NativeQueryEditor";import { Box } from "metabase/ui";import * as Lib from "metabase-lib";diff --git a/frontend/src/metabase/query_builder/components/NativeQueryEditor/NativeQueryEditor.module.css b/frontend/src/metabase/query_builder/components/NativeQueryEditor/NativeQueryEditor.module.cssindex 88ca97f0bfb..3b24129a18a 100644--- a/frontend/src/metabase/query_builder/components/NativeQueryEditor/NativeQueryEditor.module.css+++ b/frontend/src/metabase/query_builder/components/NativeQueryEditor/NativeQueryEditor.module.css@@ -3,48 +3,15 @@background-color: var(--mb-color-background-secondary);}-.dragHandleContainer {- display: flex;- justify-content: center;- align-items: center;- width: 100%;- height: 8px;- position: absolute;- bottom: -4px;- cursor: row-resize;-}--.dragHandle {- width: 100px;- height: 5px;- background-color: var(--mb-color-border);- border-radius: 4px;-}-.editorWrapper {width: 100%;}-.resizableBox {- display: none;+.resizableArea {+ display: flex;border-top: 1px solid var(--mb-color-border);- max-height: 0;-- &.open {- display: flex;- /* A large value for animation */- max-height: 1000px;- flex-direction: column;- }-- &.collapsing {- transition: max-height 0.3s ease-out;- display: flex;- }-}--.resizableBoxContent {overflow: hidden;+ flex-direction: column;}.actionButtons {diff --git a/frontend/src/metabase/query_builder/components/NativeQueryEditor/NativeQueryEditor.tsx b/frontend/src/metabase/query_builder/components/NativeQueryEditor/NativeQueryEditor.tsxindex 3d248b1957f..a8e1309aab1 100644--- a/frontend/src/metabase/query_builder/components/NativeQueryEditor/NativeQueryEditor.tsx+++ b/frontend/src/metabase/query_builder/components/NativeQueryEditor/NativeQueryEditor.tsx@@ -1,26 +1,17 @@+import { useElementSize } from "@mantine/hooks";import cx from "classnames";import {- Component,- type ForwardedRef,type ReactNode,- createRef,forwardRef,useCallback,+ useEffect,+ useRef,+ useState,} from "react";-import { ResizableBox, type ResizableBoxProps } from "react-resizable";+import { useMount } from "react-use";import { t } from "ttag";-import _ from "underscore";-import ExplicitSize from "metabase/common/components/ExplicitSize";-import { Databases } from "metabase/entities/databases";-import { SnippetCollections } from "metabase/entities/snippet-collections";-import { Snippets } from "metabase/entities/snippets";-import { useDispatch } from "metabase/lib/redux";-import {- runOrCancelQuestionOrSelectedQuery,- setIsNativeEditorOpen,- setUIControls,-} from "metabase/query_builder/actions";+import { useListCollectionsQuery, useListSnippetsQuery } from "metabase/api";import { SnippetFormModal } from "metabase/query_builder/components/template_tags/SnippetFormModal";import type { QueryModalType } from "metabase/query_builder/constants";import { useNotebookScreenSize } from "metabase/query_builder/hooks/use-notebook-screen-size";@@ -31,7 +22,6 @@ import type Database from "metabase-lib/v1/metadata/Database";import type NativeQuery from "metabase-lib/v1/queries/NativeQuery";import type {CardId,- Collection,DatabaseId,DatasetQuery,NativeQuerySnippet,@@ -46,180 +36,218 @@ import {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 type { SelectionRange, SidebarFeatures } from "./types";import {- calcInitialEditorHeight,canFormatForEngine,formatQuery,+ getInitialEditorHeight,} from "./utils";-type OwnProps = {- question: Question;- query: NativeQuery;-- proposedQuestion?: Question | undefined;- onRejectProposed?: () => void;- onAcceptProposed?: (query: DatasetQuery) => void;-- nativeEditorSelectedText?: string;- modalSnippet?: NativeQuerySnippet;- viewHeight: number;- placeholder?: string;- highlightedLineNumbers?: number[];-- isInitiallyOpen?: boolean;- isNativeEditorOpen: boolean;- isRunnable: boolean;- isRunning: boolean;- isResultDirty: boolean;-- isShowingDataReference: boolean;- isShowingTemplateTagsEditor: boolean;- isShowingSnippetSidebar: boolean;-- readOnly?: boolean;+type NativeQueryEditorProps = Omit<CodeMirrorEditorProps, "query"> & {+ availableHeight?: number;canChangeDatabase?: boolean;- hasTopBar?: boolean;- hasParametersList?: boolean;+ cancelQuery?: () => void;+ className?: string;+ closeSnippetModal?: () => void;+ databaseIsDisabled?: (database: Database) => boolean;+ editorContext?: "question" | "action";+ extraButton?: ReactNode;+ handleResize?: () => void;hasEditingSidebar?: boolean;+ hasParametersList?: boolean;hasRunButton?: boolean;- sidebarFeatures?: SidebarFeatures;- resizable?: boolean;- resizableBoxProps?: Partial<Omit<ResizableBoxProps, "axis">>;-- editorContext?: "question";-- runQuery: () => void;- toggleEditor?: () => void;- handleResize?: () => void;- setDatasetQuery: (query: NativeQuery) => Promise<Question>;- runQuestionQuery: (opts?: {- overrideWithQuestion?: Question;- shouldUpdateUrl?: boolean;- }) => void;- setNativeEditorSelectedRange?: (range: SelectionRange[]) => void;+ 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;- insertSnippet?: (snippet: NativeQuerySnippet) => void;- setIsNativeEditorOpen?: (isOpen: boolean) => 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;- onOpenModal?: (modalType: QueryModalType) => void;- toggleDataReference: () => void;- toggleTemplateTagsEditor: () => void;+ sidebarFeatures?: SidebarFeatures;+ toggleDataReference?: () => void;toggleSnippetSidebar?: () => void;- cancelQuery?: () => void;- closeSnippetModal?: () => void;- onSetDatabaseId?: (id: DatabaseId) => void;- databaseIsDisabled?: (database: Database) => boolean;+ toggleTemplateTagsEditor?: () => void;topBarInnerContent?: ReactNode;- extraButton?: ReactNode;- onBlur?: () => void;};-interface ExplicitSizeProps {- width: number;- height: number;-}--interface EntityLoaderProps {- snippets?: NativeQuerySnippet[];- snippetCollections?: Collection[];-}--type Props = OwnProps &- ExplicitSizeProps &- EntityLoaderProps &- Omit<CodeMirrorEditorProps, "query"> & {- forwardedRef?: ForwardedRef<HTMLDivElement>;- };--interface NativeQueryEditorState {- initialHeight: number;- isSelectedTextPopoverOpen: boolean;- isCollapsing: boolean;-}--class NativeQueryEditor extends Component<Props, NativeQueryEditorState> {- resizeBox = createRef<HTMLDivElement & ResizableBox>();- editor = createRef<CodeMirrorEditorRef>();-- constructor(props: Props) {- super(props);-- const { query, viewHeight } = props;- this.state = {- initialHeight: calcInitialEditorHeight({ query, viewHeight }),- isSelectedTextPopoverOpen: false,- isCollapsing: false,- };- }+export const NativeQueryEditor = forwardRef<+ HTMLDivElement,+ NativeQueryEditorProps+>(function NativeQueryEditorInner(props, ref) {+ const {+ availableHeight = Infinity,+ extraButton,+ canChangeDatabase = true,+ cancelQuery,+ className,+ closeSnippetModal,+ databaseIsDisabled,+ 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,+ topBarInnerContent,+ } = props;++ const { data: snippets = [] } = useListSnippetsQuery();+ const { data: snippetCollections = [] } = useListCollectionsQuery({+ namespace: "snippets",+ });++ const editorRef = useRef<CodeMirrorEditorRef>(null);+ const { ref: topBarRef, height: topBarHeight } = useElementSize();++ const canSaveSnippets = snippetCollections.some(+ (collection) => collection.can_write,+ );- UNSAFE_componentWillMount() {- const { question, setIsNativeEditorOpen, isInitiallyOpen } = this.props;+ const canToggleEditor = typeof setIsNativeEditorOpen === "function";+ const shouldShowEditor = isNativeEditorOpen || !canToggleEditor;- if (typeof isInitiallyOpen !== "undefined") {- setIsNativeEditorOpen?.(isInitiallyOpen);- return;- }+ const [isSelectedTextPopoverOpen, setSelectedTextPopoverOpen] =+ useState(false);- setIsNativeEditorOpen?.(!question || !question.isSaved());- }-- componentDidUpdate(prevProps: Props) {- if (- this.state.isSelectedTextPopoverOpen &&- !this.props.nativeEditorSelectedText &&- prevProps.nativeEditorSelectedText- ) {- // close selected text popover if text is deselected- this.setState({ isSelectedTextPopoverOpen: false });- }+ // do not show reference sidebar on small screens automatically+ const screenSize = useNotebookScreenSize();+ const shouldOpenDataReference = screenSize !== "small";++ useMount(() => {+ setIsNativeEditorOpen?.(+ typeof isInitiallyOpen !== "undefined"+ ? isInitiallyOpen+ : question?.isSaved(),+ shouldOpenDataReference,+ );+ });- if (this.props.isNativeEditorOpen && !prevProps.isNativeEditorOpen) {- const { query, viewHeight } = this.props;- const newHeight = calcInitialEditorHeight({ query, viewHeight });- this.setState({ initialHeight: newHeight });+ 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],+ );- onChange = (queryText: string) => {- const { query, setDatasetQuery } = this.props;- if (query.queryText() !== queryText) {- const updatedQuery = query.setQueryText(queryText);+ 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],+ );- focus = () => {- if (this.props.readOnly) {+ const handleRightClickSelection = useCallback(() => {+ setSelectedTextPopoverOpen(true);+ }, []);++ const focusEditor = useCallback(() => {+ if (readOnly) {return;}- this.editor.current?.focus();- };-- handleRightClickSelection = () => {- this.setState({ isSelectedTextPopoverOpen: true });- };+ editorRef.current?.focus();+ }, [readOnly]);- handleTransitionEnd = () => {- if (this.state.isCollapsing) {- this.setState({- isCollapsing: false,- initialHeight: MIN_EDITOR_HEIGHT_AFTER_DRAGGING,- });- }- };+ const toggleEditor = useCallback(() => {+ setIsNativeEditorOpen?.(!isNativeEditorOpen, shouldOpenDataReference);+ }, [setIsNativeEditorOpen, shouldOpenDataReference, isNativeEditorOpen]);- handleFormatQuery = async () => {- const { question } = this.props;+ 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@@ -227,275 +255,164 @@ class NativeQueryEditor extends Component<Props, NativeQueryEditorState> {}const formattedQuery = await formatQuery(queryText, engine);- this.onChange(formattedQuery);- this.focus();- };-- render() {- const {- canChangeDatabase = true,- resizable = true,- sidebarFeatures = {- dataReference: true,- variables: true,- snippets: true,- promptInput: true,- formatQuery: true,- },- hasTopBar = true,- hasEditingSidebar = true,- hasRunButton = hasEditingSidebar,- resizableBoxProps = {},- snippetCollections = [],- question,- proposedQuestion,- onRejectProposed,- onAcceptProposed,- query,- readOnly,- isNativeEditorOpen,- openSnippetModalWithSelectedText,- openDataReferenceAtQuestion,- setDatasetQuery,- setNativeEditorSelectedRange,- forwardedRef,- runQuery,- highlightedLineNumbers,- placeholder,- extensions,- extraButton,- onBlur,- } = this.props;-- const dragHandle = resizable ? (- <div className={S.dragHandleContainer} data-testid="drag-handle">- <div className={S.dragHandle} />- </div>- ) : null;-- const canSaveSnippets = snippetCollections.some(- (collection) => collection.can_write,- );-- const engine = Lib.engine(question.query());- const canFormatQuery = engine != null && canFormatForEngine(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],+ );- return (- <div- className={S.queryEditor}- data-testid="native-query-editor-container"- ref={forwardedRef}- >- {hasTopBar && (- <NativeQueryEditorTopBar- hasEditingSidebar={hasEditingSidebar}- question={question}- query={query}- focus={this.focus}- canChangeDatabase={canChangeDatabase}- sidebarFeatures={sidebarFeatures}- isRunnable={this.props.isRunnable}- isRunning={this.props.isRunning}- hasParametersList={this.props.hasParametersList}- isResultDirty={this.props.isResultDirty}- isShowingDataReference={this.props.isShowingDataReference}- onOpenModal={this.props.onOpenModal}- isShowingTemplateTagsEditor={this.props.isShowingTemplateTagsEditor}- setIsNativeEditorOpen={this.props.setIsNativeEditorOpen}- snippets={this.props.snippets}- editorContext={this.props.editorContext}- onSetDatabaseId={this.props.onSetDatabaseId}- isShowingSnippetSidebar={this.props.isShowingSnippetSidebar}- isNativeEditorOpen={this.props.isNativeEditorOpen}- toggleEditor={this.props.toggleEditor}- toggleDataReference={this.props.toggleDataReference}- toggleSnippetSidebar={this.props.toggleSnippetSidebar}- setParameterValue={this.props.setParameterValue}- setDatasetQuery={this.props.setDatasetQuery}- onFormatQuery={canFormatQuery ? this.handleFormatQuery : undefined}- databaseIsDisabled={this.props.databaseIsDisabled}- readOnly={readOnly}- >- {this.props.topBarInnerContent}- </NativeQueryEditorTopBar>- )}- <div- className={S.editorWrapper}- onTransitionEnd={this.handleTransitionEnd}+ return (+ <div+ className={cx(S.queryEditor, className)}+ 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}+ setParameterValue={setParameterValue}+ setDatasetQuery={setDatasetQuery}+ onFormatQuery={handleFormatQuery}+ databaseIsDisabled={databaseIsDisabled}+ readOnly={readOnly}>- <ResizableBox- ref={this.resizeBox}- height={this.state.initialHeight}- className={cx(- S.resizableBox,- isNativeEditorOpen && S.open,- this.state.isCollapsing && S.collapsing,- )}- minConstraints={[Infinity, MIN_EDITOR_HEIGHT_AFTER_DRAGGING]}- axis="y"- handle={dragHandle}- resizeHandles={["s"]}- {...resizableBoxProps}- onResizeStop={(e, data) => {- this.props.handleResize?.();- if (typeof resizableBoxProps?.onResizeStop === "function") {- resizableBoxProps.onResizeStop(e, data);- }- const size = data.size;-- if (size.height < THRESHOLD_FOR_AUTO_CLOSE) {- // Start animation to collapse- this.setState({ isCollapsing: true });- this.props.setIsNativeEditorOpen?.(false);- }- }}+ {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={this.editor}- query={question.query()}- proposedQuery={proposedQuestion?.query()}- readOnly={readOnly}- placeholder={placeholder}- highlightedLineNumbers={highlightedLineNumbers}- extensions={extensions}- onChange={this.onChange}- onRunQuery={runQuery}- onSelectionChange={setNativeEditorSelectedRange}- onCursorMoveOverCardTag={openDataReferenceAtQuestion}- onRightClickSelection={this.handleRightClickSelection}- onFormatQuery={- canFormatQuery ? this.handleFormatQuery : undefined- }- onBlur={onBlur}- />+ <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 m="1rem" gap="md" mt="auto">- {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) {- this.onChange(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>- </>+ <Stack m="1rem" gap="md" mt="auto">+ {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 gap="sm">- {extraButton}- {hasRunButton && !readOnly && (- <NativeQueryEditorRunButton- cancelQuery={this.props.cancelQuery}- isResultDirty={this.props.isResultDirty}- isRunnable={this.props.isRunnable}- isRunning={this.props.isRunning}- nativeEditorSelectedText={- this.props.nativeEditorSelectedText- }- runQuery={this.props.runQuery}- questionErrors={Lib.validateTemplateTags(- question.query(),- )}- />- )}- </Flex>- </Stack>- </Flex>- </ResizableBox>- </div>-- <RightClickPopover- isOpen={this.state.isSelectedTextPopoverOpen}- openSnippetModalWithSelectedText={openSnippetModalWithSelectedText}- runQuery={runQuery}- target={() => this.editor.current?.getSelectionTarget()}- canSaveSnippets={canSaveSnippets}- />-- {this.props.modalSnippet &&- this.props.insertSnippet &&- this.props.closeSnippetModal && (- <SnippetFormModal- snippet={this.props.modalSnippet}- onCreate={this.props.insertSnippet}- onUpdate={(newSnippet, oldSnippet) => {- // get the query instance with the latest Metadata that has the updated snippet- const newQuery = this.props.query.updateSnippet(- oldSnippet,- newSnippet,- );- setDatasetQuery(newQuery);- }}- onClose={this.props.closeSnippetModal}- />- )}+ </Flex>+ </Stack>+ </ResizableArea>+ )}</div>- );- }-}--const NativeQueryEditorWrapper = forwardRef<- HTMLDivElement,- Omit<Props, "runQuery" | "toggleEditor">->(function NativeQueryEditorWrapper(props, ref) {- const screenSize = useNotebookScreenSize();- const dispatch = useDispatch();- const { isNativeEditorOpen } = props;-- const runQuery = useCallback(() => {- dispatch(runOrCancelQuestionOrSelectedQuery());- }, [dispatch]);- /**- * do not show reference sidebar on small screens automatically- */- const toggleEditor = useCallback(() => {- if (screenSize === "small") {- dispatch(setUIControls({ isNativeEditorOpen: !isNativeEditorOpen }));- } else {- dispatch(setIsNativeEditorOpen(!isNativeEditorOpen));- }- }, [dispatch, isNativeEditorOpen, screenSize]);-- return (- <NativeQueryEditor- runQuery={runQuery}- toggleEditor={toggleEditor}- {...props}- forwardedRef={ref}- />+ <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>);});--// eslint-disable-next-line import/no-default-export -- deprecated usage-export default _.compose(- Databases.loadList({ loadingAndErrorWrapper: false }),- Snippets.loadList({ loadingAndErrorWrapper: false }),- SnippetCollections.loadList({ loadingAndErrorWrapper: false }),- ExplicitSize(),-)(NativeQueryEditorWrapper);diff --git a/frontend/src/metabase/query_builder/components/NativeQueryEditor/NativeQueryEditorRunButton/NativeQueryEditorRunButton.tsx b/frontend/src/metabase/query_builder/components/NativeQueryEditor/NativeQueryEditorRunButton/NativeQueryEditorRunButton.tsxindex 6da2640a3f2..ecb5ea7af68 100644--- a/frontend/src/metabase/query_builder/components/NativeQueryEditor/NativeQueryEditorRunButton/NativeQueryEditorRunButton.tsx+++ b/frontend/src/metabase/query_builder/components/NativeQueryEditor/NativeQueryEditorRunButton/NativeQueryEditorRunButton.tsx@@ -11,7 +11,7 @@ interface NativeQueryEditorRunButtonProps {isResultDirty: boolean;isRunnable: boolean;isRunning: boolean;- nativeEditorSelectedText?: string;+ nativeEditorSelectedText?: string | null;questionErrors?: Lib.ValidationError[] | null;runQuery?: () => void;}diff --git a/frontend/src/metabase/query_builder/components/NativeQueryEditor/NativeQueryEditorTopBar/NativeQueryEditorTopBar.tsx b/frontend/src/metabase/query_builder/components/NativeQueryEditor/NativeQueryEditorTopBar/NativeQueryEditorTopBar.tsxindex 7d93290f403..be3995073b2 100644--- a/frontend/src/metabase/query_builder/components/NativeQueryEditor/NativeQueryEditorTopBar/NativeQueryEditorTopBar.tsx+++ b/frontend/src/metabase/query_builder/components/NativeQueryEditor/NativeQueryEditorTopBar/NativeQueryEditorTopBar.tsx@@ -1,4 +1,4 @@-import type { PropsWithChildren } from "react";+import { type PropsWithChildren, forwardRef } from "react";import { useDispatch } from "metabase/lib/redux";import { updateQuestion } from "metabase/query_builder/actions/core";@@ -38,7 +38,7 @@ interface NativeQueryEditorTopBarProps extends PropsWithChildren {readOnly?: boolean;snippets?: NativeQuerySnippet[];- editorContext?: "question";+ editorContext?: "question" | "action";snippetCollections?: Collection[];sidebarFeatures: SidebarFeatures;@@ -51,11 +51,14 @@ interface NativeQueryEditorTopBarProps extends PropsWithChildren {onOpenModal?: (modalType: QueryModalType) => void;setParameterValue?: (parameterId: ParameterId, value: string) => void;focus: () => void;- setDatasetQuery: (query: NativeQuery) => Promise<Question>;+ setDatasetQuery: (query: NativeQuery) => void;databaseIsDisabled?: (database: Database) => boolean;}-const NativeQueryEditorTopBar = (props: NativeQueryEditorTopBarProps) => {+const NativeQueryEditorTopBar = forwardRef<+ HTMLDivElement,+ NativeQueryEditorTopBarProps+>(function NativeQueryEditorTopBarInner(props, ref) {const {children,query,@@ -122,7 +125,7 @@ const NativeQueryEditorTopBar = (props: NativeQueryEditorTopBarProps) => {const parameters = question.parameters();return (- <Flex align="flex-start" data-testid="native-query-top-bar">+ <Flex align="flex-start" data-testid="native-query-top-bar" ref={ref}>{canChangeDatabase && (<DataSourceSelectorsisNativeEditorOpen={isNativeEditorOpen}@@ -178,6 +181,6 @@ const NativeQueryEditorTopBar = (props: NativeQueryEditorTopBarProps) => {</Flex></Flex>);-};+});export { NativeQueryEditorTopBar };diff --git a/frontend/src/metabase/query_builder/components/NativeQueryEditor/ResizableArea/ResizableArea.module.css b/frontend/src/metabase/query_builder/components/NativeQueryEditor/ResizableArea/ResizableArea.module.cssnew file mode 100644index 00000000000..8c51672d38b--- /dev/null+++ b/frontend/src/metabase/query_builder/components/NativeQueryEditor/ResizableArea/ResizableArea.module.css@@ -0,0 +1,17 @@+.dragHandleContainer {+ display: flex;+ justify-content: center;+ align-items: center;+ width: 100%;+ height: 8px;+ position: absolute;+ bottom: -4px;+ cursor: row-resize;+}++.dragHandle {+ width: 100px;+ height: 5px;+ background-color: var(--mb-color-border);+ border-radius: 4px;+}diff --git a/frontend/src/metabase/query_builder/components/NativeQueryEditor/ResizableArea/ResizableArea.tsx b/frontend/src/metabase/query_builder/components/NativeQueryEditor/ResizableArea/ResizableArea.tsxnew file mode 100644index 00000000000..5c0386c0ab3--- /dev/null+++ b/frontend/src/metabase/query_builder/components/NativeQueryEditor/ResizableArea/ResizableArea.tsx@@ -0,0 +1,89 @@+import { type ReactNode, useCallback, useEffect, useState } from "react";+import { Resizable } from "react-resizable";++import { Flex } from "metabase/ui";++import S from "./ResizableArea.module.css";++// ResizableArea is a wrapper around Resizable that+// automatically resizes the editor when the max height changes+export function ResizableArea(props: {+ children: ReactNode;+ resizable: boolean;+ initialHeight: number;+ minHeight?: number;+ maxHeight: number;+ onResize?: (height: number) => void;+ className?: string;+}) {+ const {+ children,+ resizable,+ initialHeight,+ minHeight = 0,+ maxHeight: maxHeightFromProps,+ onResize,+ className,+ } = props;++ const maxHeight =+ maxHeightFromProps != null && maxHeightFromProps <= 0+ ? Infinity+ : maxHeightFromProps;+ const [height, setHeight] = useState(initialHeight);++ const resize = useCallback(+ (height: number) => {+ onResize?.(height);+ setHeight(height);+ },+ [onResize],+ );++ const handleResize = useCallback(+ (_event: unknown, data: { size: { height: number } }) => {+ const { height } = data.size;+ resize(height);+ },+ [resize],+ );++ useEffect(() => {+ // If the height is higher than the max height,+ // resize to the max height+ if (maxHeight == null) {+ return;+ }+ if (height >= maxHeight) {+ resize(Math.max(minHeight, maxHeight));+ }+ }, [height, minHeight, maxHeight, resize]);++ // reset height to initialHeight if it started of as Infinity+ if (height === Infinity && initialHeight !== Infinity) {+ setHeight(initialHeight);+ }++ const dragHandle = resizable ? (+ <div className={S.dragHandleContainer} data-testid="drag-handle">+ <div className={S.dragHandle} />+ </div>+ ) : null;++ return (+ <Resizable+ height={height}+ minConstraints={[Infinity, minHeight]}+ maxConstraints={[Infinity, maxHeight]}+ axis="y"+ handle={dragHandle}+ resizeHandles={["s"]}+ onResize={handleResize}+ onResizeStop={handleResize}+ >+ <Flex w="100%" flex="1" h={height} className={className}>+ {children}+ </Flex>+ </Resizable>+ );+}diff --git a/frontend/src/metabase/query_builder/components/NativeQueryEditor/ResizableArea/index.ts b/frontend/src/metabase/query_builder/components/NativeQueryEditor/ResizableArea/index.tsnew file mode 100644index 00000000000..f41a642e010--- /dev/null+++ b/frontend/src/metabase/query_builder/components/NativeQueryEditor/ResizableArea/index.ts@@ -0,0 +1 @@+export * from "./ResizableArea";diff --git a/frontend/src/metabase/query_builder/components/NativeQueryEditor/RightClickPopover/RightClickPopover.tsx b/frontend/src/metabase/query_builder/components/NativeQueryEditor/RightClickPopover/RightClickPopover.tsxindex b239b392052..e82e4456e8d 100644--- a/frontend/src/metabase/query_builder/components/NativeQueryEditor/RightClickPopover/RightClickPopover.tsx+++ b/frontend/src/metabase/query_builder/components/NativeQueryEditor/RightClickPopover/RightClickPopover.tsx@@ -9,7 +9,7 @@ interface RightClickPopoverProps {isOpen: boolean;canSaveSnippets: boolean;target: () => Element | null | undefined;- runQuery: () => void;+ runQuery?: () => void;openSnippetModalWithSelectedText?: () => void;}@@ -22,10 +22,12 @@ export const RightClickPopover = ({}: RightClickPopoverProps) => (<Popover isOpen={isOpen} target={target}><Flex direction="column">- <a className={RightClickPopoverS.Anchor} onClick={runQuery}>- <Icon mr="sm" name="play" size={16} />- <h4>{t`Run selection`}</h4>- </a>+ {runQuery && (+ <a className={RightClickPopoverS.Anchor} onClick={runQuery}>+ <Icon mr="sm" name="play" size={16} />+ <h4>{t`Run selection`}</h4>+ </a>+ )}{canSaveSnippets && openSnippetModalWithSelectedText && (<aclassName={RightClickPopoverS.Anchor}diff --git a/frontend/src/metabase/query_builder/components/NativeQueryEditor/__mocks__/NativeQueryEditor.jsx b/frontend/src/metabase/query_builder/components/NativeQueryEditor/__mocks__/NativeQueryEditor.jsxindex 7cdd380769b..975622918a6 100644--- a/frontend/src/metabase/query_builder/components/NativeQueryEditor/__mocks__/NativeQueryEditor.jsx+++ b/frontend/src/metabase/query_builder/components/NativeQueryEditor/__mocks__/NativeQueryEditor.jsx@@ -3,7 +3,7 @@ import CS from "metabase/css/core/index.css";import DataSourceSelectors from "metabase/query_builder/components/NativeQueryEditor/DataSourceSelectors";import { SyncedParametersList } from "metabase/query_builder/components/SyncedParametersList";-const MockNativeQueryEditor = ({+export const NativeQueryEditor = ({canChangeDatabase = true,editorContext = "question",isNativeEditorOpen,@@ -55,5 +55,3 @@ const MockNativeQueryEditor = ({</div>);};--export default MockNativeQueryEditor;diff --git a/frontend/src/metabase/query_builder/components/NativeQueryEditor/__mocks__/index.ts b/frontend/src/metabase/query_builder/components/NativeQueryEditor/__mocks__/index.tsindex bf0be8903ec..7fb6204039c 100644--- a/frontend/src/metabase/query_builder/components/NativeQueryEditor/__mocks__/index.ts+++ b/frontend/src/metabase/query_builder/components/NativeQueryEditor/__mocks__/index.ts@@ -1,2 +1 @@-// eslint-disable-next-line import/no-default-export-export { default } from "./NativeQueryEditor";+export * from "./NativeQueryEditor";diff --git a/frontend/src/metabase/query_builder/components/NativeQueryEditor/constants.ts b/frontend/src/metabase/query_builder/components/NativeQueryEditor/constants.tsindex fb389fb0ecc..c7b945ab489 100644--- a/frontend/src/metabase/query_builder/components/NativeQueryEditor/constants.ts+++ b/frontend/src/metabase/query_builder/components/NativeQueryEditor/constants.ts@@ -1,4 +1,5 @@export const SCROLL_MARGIN = 8;export const MIN_HEIGHT_LINES = 15;-export const MIN_EDITOR_HEIGHT_AFTER_DRAGGING = 0;+export const MIN_EDITOR_HEIGHT_AFTER_DRAGGING = 40;+export const RESIZE_CONSTRAINT_OFFSET = 80;export const THRESHOLD_FOR_AUTO_CLOSE = 50;diff --git a/frontend/src/metabase/query_builder/components/NativeQueryEditor/index.ts b/frontend/src/metabase/query_builder/components/NativeQueryEditor/index.tsindex 5f1c2c2a7b9..6287790cacf 100644--- a/frontend/src/metabase/query_builder/components/NativeQueryEditor/index.ts+++ b/frontend/src/metabase/query_builder/components/NativeQueryEditor/index.ts@@ -1,3 +1,2 @@-// eslint-disable-next-line import/no-default-export -- deprecated usage-export { default } from "./NativeQueryEditor";+export * from "./NativeQueryEditor";export { type SelectionRange } from "./types";diff --git a/frontend/src/metabase/query_builder/components/NativeQueryEditor/utils.ts b/frontend/src/metabase/query_builder/components/NativeQueryEditor/utils.tsindex 6b7a84e2ce3..2ecd6f1d004 100644--- a/frontend/src/metabase/query_builder/components/NativeQueryEditor/utils.ts+++ b/frontend/src/metabase/query_builder/components/NativeQueryEditor/utils.ts@@ -25,37 +25,37 @@ const FULL_HEIGHT = 400;// - On load, long queries will be capped at this length// - When loading an empty query, this is the height// - When the editor grows during typing this is the max height-export function getMaxAutoSizeLines(viewHeight: number) {- const pixelHeight = viewHeight * FRACTION_OF_TOTAL_VIEW_HEIGHT;+export function getMaxAutoSizeLines(availableHeight: number) {+ const pixelHeight = availableHeight * FRACTION_OF_TOTAL_VIEW_HEIGHT;return Math.ceil(getLinesForHeight(pixelHeight));}type GetVisibleLinesCountParams = {query?: NativeQuery;- viewHeight: number | "full";+ availableHeight?: number | "full";};function getVisibleLinesCount({query,- viewHeight,+ availableHeight,}: {query?: NativeQuery;- viewHeight: number;+ availableHeight: number;}) {- const maxAutoSizeLines = getMaxAutoSizeLines(viewHeight);+ const maxAutoSizeLines = getMaxAutoSizeLines(availableHeight);const queryLineCount = query?.lineCount() || maxAutoSizeLines;return Math.max(Math.min(queryLineCount, maxAutoSizeLines), MIN_HEIGHT_LINES);}-export function calcInitialEditorHeight({+export function getInitialEditorHeight({query,- viewHeight,+ availableHeight = 0,}: GetVisibleLinesCountParams) {- if (viewHeight === "full") {+ if (availableHeight === "full") {// override for action editorreturn FULL_HEIGHT;}- const lines = getVisibleLinesCount({ query, viewHeight });+ const lines = getVisibleLinesCount({ query, availableHeight });return getEditorLineHeight(lines);}diff --git a/frontend/src/metabase/query_builder/components/view/View/View/View.jsx b/frontend/src/metabase/query_builder/components/view/View/View/View.jsxindex 264b798d033..c596f61dc1a 100644--- a/frontend/src/metabase/query_builder/components/view/View/View/View.jsx+++ b/frontend/src/metabase/query_builder/components/view/View/View/View.jsx@@ -17,6 +17,7 @@ import { Questions } from "metabase/entities/questions";import { connect } from "metabase/lib/redux";import {rememberLastUsedDatabase,+ runOrCancelQuestionOrSelectedQuery,setArchivedQuestion,} from "metabase/query_builder/actions";import { SIDEBAR_SIZES } from "metabase/query_builder/constants";@@ -291,6 +292,9 @@ const mapDispatchToProps = (dispatch) => ({const deleteAction = Questions.actions.delete({ id });dispatch(deletePermanently(deleteAction));},+ runQuery: () => {+ dispatch(runOrCancelQuestionOrSelectedQuery());+ },});export const View = _.compose(diff --git a/frontend/src/metabase/query_builder/components/view/View/ViewMainContainer/ViewMainContainer.tsx b/frontend/src/metabase/query_builder/components/view/View/ViewMainContainer/ViewMainContainer.tsxindex d8022af075c..a136fdbed05 100644--- a/frontend/src/metabase/query_builder/components/view/View/ViewMainContainer/ViewMainContainer.tsx+++ b/frontend/src/metabase/query_builder/components/view/View/ViewMainContainer/ViewMainContainer.tsx@@ -1,3 +1,4 @@+import { useElementSize } from "@mantine/hooks";import cx from "classnames";import type { ResizableBoxProps } from "react-resizable";@@ -36,7 +37,6 @@ interface ViewMainContainerProps {nativeEditorSelectedText?: string;modalSnippet?: NativeQuerySnippet;- viewHeight: number;highlightedLineNumbers?: number[];isInitiallyOpen?: boolean;@@ -106,6 +106,9 @@ export const ViewMainContainer = (props: ViewMainContainerProps) => {updateQuestion,} = props;+ const { ref: mainRef, height: mainHeight } = useElementSize();+ const { ref: footerRef, height: footerHeight } = useElementSize();+if (queryBuilderMode === "notebook") {// we need to render main only in view modereturn;@@ -115,6 +118,8 @@ export const ViewMainContainer = (props: ViewMainContainerProps) => {const { isNative } = Lib.queryDisplayInfo(question.query());const isSidebarOpen = showLeftSidebar || showRightSidebar;+ const availableHeight = mainHeight ? mainHeight - footerHeight : undefined;+return (<Boxcomponent="main"@@ -122,9 +127,10 @@ export const ViewMainContainer = (props: ViewMainContainerProps) => {[ViewMainContainerS.isSidebarOpen]: isSidebarOpen,})}data-testid="query-builder-main"+ ref={mainRef}>{isNative ? (- <ViewNativeQueryEditor {...props} />+ <ViewNativeQueryEditor {...props} availableHeight={availableHeight} />) : (<SyncedParametersListclassName={ViewMainContainerS.StyledSyncedParametersList}@@ -148,8 +154,10 @@ export const ViewMainContainer = (props: ViewMainContainerProps) => {onUpdateQuestion={updateQuestion}/></DebouncedFrame>- <TimeseriesChrome question={question} updateQuestion={updateQuestion} />- <ViewFooter className={CS.flexNoShrink} />+ <Box ref={footerRef}>+ <TimeseriesChrome question={question} updateQuestion={updateQuestion} />+ <ViewFooter className={CS.flexNoShrink} />+ </Box></Box>);};diff --git a/frontend/src/metabase/query_builder/components/view/View/ViewNativeQueryEditor/ViewNativeQueryEditor.tsx b/frontend/src/metabase/query_builder/components/view/View/ViewNativeQueryEditor/ViewNativeQueryEditor.tsxindex bf1236d0b87..ef84c06cb83 100644--- a/frontend/src/metabase/query_builder/components/view/View/ViewNativeQueryEditor/ViewNativeQueryEditor.tsx+++ b/frontend/src/metabase/query_builder/components/view/View/ViewNativeQueryEditor/ViewNativeQueryEditor.tsx@@ -2,7 +2,7 @@ import type { ResizableBoxProps } from "react-resizable";import { useSelector } from "metabase/lib/redux";import { PLUGIN_METABOT } from "metabase/plugins";-import NativeQueryEditor from "metabase/query_builder/components/NativeQueryEditor";+import { NativeQueryEditor } from "metabase/query_builder/components/NativeQueryEditor";import type {SelectionRange,SidebarFeatures,@@ -32,7 +32,6 @@ interface ViewNativeQueryEditorProps {nativeEditorSelectedText?: string;modalSnippet?: NativeQuerySnippet;- viewHeight: number;highlightedLineNumbers?: number[];isInitiallyOpen?: boolean;@@ -77,10 +76,11 @@ interface ViewNativeQueryEditorProps {cancelQuery?: () => void;closeSnippetModal: () => void;onSetDatabaseId?: (id: DatabaseId) => void;+ availableHeight?: number;}export const ViewNativeQueryEditor = (props: ViewNativeQueryEditorProps) => {- const { question, height, isNativeEditorOpen, card, onSetDatabaseId } = props;+ const { question, isNativeEditorOpen, onSetDatabaseId } = props;const legacyNativeQuery = question.legacyNativeQuery();const highlightedLineNumbers = useSelector(@@ -97,7 +97,7 @@ export const ViewNativeQueryEditor = (props: ViewNativeQueryEditorProps) => {// This check makes it hide the editor in this particular case// More details: https://github.com/metabase/metabase/pull/20161const { isEditable } = Lib.queryDisplayInfo(question.query());- if (question.type() === "model" && !isEditable) {+ if ((question.type() === "model" && !isEditable) || !legacyNativeQuery) {return null;}@@ -106,10 +106,8 @@ export const ViewNativeQueryEditor = (props: ViewNativeQueryEditorProps) => {<NativeQueryEditor{...props}query={legacyNativeQuery}- viewHeight={height}highlightedLineNumbers={highlightedLineNumbers}isInitiallyOpen={isNativeEditorOpen}- datasetQuery={card && card.dataset_query}onSetDatabaseId={onSetDatabaseId}extensions={inlineSQLPrompt?.extensions}proposedQuestion={inlineSQLPrompt?.proposedQuestion}diff --git a/frontend/src/metabase/querying/editor/components/QueryEditor/QueryEditor.tsx b/frontend/src/metabase/querying/editor/components/QueryEditor/QueryEditor.tsxindex 1b3138262e1..8c2d3405523 100644--- a/frontend/src/metabase/querying/editor/components/QueryEditor/QueryEditor.tsx+++ b/frontend/src/metabase/querying/editor/components/QueryEditor/QueryEditor.tsx@@ -1,3 +1,4 @@+import { useElementSize } from "@mantine/hooks";import type { ReactNode } from "react";import { t } from "ttag";@@ -80,6 +81,8 @@ export function QueryEditor({onChangeUiState,});+ const { ref, height: availableHeight } = useElementSize();+if (isLoading || error != null) {return (<Center h={height}>@@ -90,9 +93,10 @@ export function QueryEditor({return (<>- <Flex flex={1} h={height} mih={0}>+ <Flex flex={1} h={height} mih={0} ref={ref}><Flex flex="2 1 0" miw={0} direction="column" pos="relative"><QueryEditorBody+ availableHeight={availableHeight}question={question}proposedQuestion={proposedQuestion}modalSnippet={uiState.modalSnippet}diff --git a/frontend/src/metabase/querying/editor/components/QueryEditor/QueryEditorBody/QueryEditorBody.module.css b/frontend/src/metabase/querying/editor/components/QueryEditor/QueryEditorBody/QueryEditorBody.module.cssindex 67dadfc8b09..ba0d4032121 100644--- a/frontend/src/metabase/querying/editor/components/QueryEditor/QueryEditorBody/QueryEditorBody.module.css+++ b/frontend/src/metabase/querying/editor/components/QueryEditor/QueryEditorBody/QueryEditorBody.module.css@@ -3,8 +3,6 @@border-bottom: 1px solid var(--mb-color-border);}-.nativeResizableBox {- display: flex;- border-top: 1px solid var(--mb-color-border);+.nativeQueryEditor {border-bottom: 1px solid var(--mb-color-border);}diff --git a/frontend/src/metabase/querying/editor/components/QueryEditor/QueryEditorBody/QueryEditorBody.tsx b/frontend/src/metabase/querying/editor/components/QueryEditor/QueryEditorBody/QueryEditorBody.tsxindex 797ca252874..b1024347504 100644--- a/frontend/src/metabase/querying/editor/components/QueryEditor/QueryEditorBody/QueryEditorBody.tsx+++ b/frontend/src/metabase/querying/editor/components/QueryEditor/QueryEditorBody/QueryEditorBody.tsx@@ -1,11 +1,12 @@import { type ReactNode, useMemo, useState } from "react";-import { ResizableBox, type ResizableBoxProps } from "react-resizable";+import { ResizableBox } from "react-resizable";import { useWindowSize } from "react-use";import type { CollectionPickerItem } from "metabase/common/components/Pickers/CollectionPicker";import type { DataPickerItem } from "metabase/common/components/Pickers/DataPicker";import { useSetting } from "metabase/common/hooks";-import NativeQueryEditor, {+import {+ NativeQueryEditor,type SelectionRange,} from "metabase/query_builder/components/NativeQueryEditor";import type { QueryModalType } from "metabase/query_builder/constants";@@ -37,6 +38,7 @@ const NATIVE_EDITOR_SIDEBAR_FEATURES = {};type QueryEditorBodyProps = {+ extraButton?: ReactNode;question: Question;proposedQuestion: Question | undefined;modalSnippet?:@@ -56,6 +58,7 @@ type QueryEditorBodyProps = {item: DataPickerItem | CollectionPickerItem | RecentCollectionItem,) => boolean;shouldShowLibrary?: boolean;+ onBlur?: () => void;onChange: (newQuestion: Question) => void;onRunQuery: () => Promise<void>;onToggleDataReference: () => void;@@ -67,12 +70,12 @@ type QueryEditorBodyProps = {onOpenModal: (type: QueryModalType) => void;onAcceptProposed?: () => void;onRejectProposed?: () => void;- onBlur?: () => void;topBarInnerContent?: ReactNode;- extraButton?: ReactNode;+ availableHeight?: number;};export function QueryEditorBody({+ extraButton,question,proposedQuestion,modalSnippet,@@ -87,6 +90,7 @@ export function QueryEditorBody({shouldDisableDatabase,shouldDisableItem,shouldShowLibrary,+ onBlur,onChange,onRunQuery,onToggleDataReference,@@ -98,9 +102,8 @@ export function QueryEditorBody({onOpenModal,onAcceptProposed,onRejectProposed,- onBlur,topBarInnerContent,- extraButton,+ availableHeight,}: QueryEditorBodyProps) {const [isResizing, setIsResizing] = useState(false);const reportTimezone = useSetting("report-timezone-long");@@ -111,18 +114,6 @@ export function QueryEditorBody({[shouldDisableItem, shouldDisableDatabase, shouldShowLibrary],);- const resizableBoxProps: Partial<ResizableBoxProps> = useMemo(- () => ({- className: S.nativeResizableBox,- height: editorHeight,- resizeHandles: ["s"],- style: isResizing ? undefined : { transition: "height 0.25s" },- onResizeStart: () => setIsResizing(true),- onResizeStop: () => setIsResizing(false),- }),- [isResizing, editorHeight],- );-const setQuestion = (newQuestion: Question) => {onChange(newQuestion);return Promise.resolve();@@ -132,44 +123,54 @@ export function QueryEditorBody({onChange(newNativeQuery.question());};- return isNative ? (- <NativeQueryEditor- question={question}- proposedQuestion={proposedQuestion}- query={question.legacyNativeQuery()}- resizableBoxProps={resizableBoxProps}- placeholder="SELECT * FROM TABLE_NAME"- hasTopBar- hasRunButton={!readOnly}- isInitiallyOpen- isNativeEditorOpen- readOnly={readOnly}- hasParametersList={false}- isRunnable={isRunnable}- isRunning={isRunning}- isResultDirty={isResultDirty}- isShowingDataReference={isShowingDataReference}- isShowingSnippetSidebar={isShowingSnippetSidebar}- runQuery={onRunQuery}- cancelQuery={onCancelQuery}- databaseIsDisabled={shouldDisableDatabase}- setDatasetQuery={handleNativeQueryChange}- sidebarFeatures={NATIVE_EDITOR_SIDEBAR_FEATURES}- toggleDataReference={onToggleDataReference}- toggleSnippetSidebar={onToggleSnippetSidebar}- modalSnippet={modalSnippet}- insertSnippet={onInsertSnippet}- closeSnippetModal={() => onChangeModalSnippet(null)}- setNativeEditorSelectedRange={onChangeNativeEditorSelection}- nativeEditorSelectedText={nativeEditorSelectedText}- onOpenModal={onOpenModal}- onAcceptProposed={onAcceptProposed}- onRejectProposed={onRejectProposed}- onBlur={onBlur}- topBarInnerContent={topBarInnerContent}- extraButton={extraButton}- />- ) : (+ if (isNative) {+ const query = question.legacyNativeQuery();+ if (!query) {+ return null;+ }++ return (+ <NativeQueryEditor+ className={S.nativeQueryEditor}+ availableHeight={availableHeight}+ question={question}+ proposedQuestion={proposedQuestion}+ query={query}+ placeholder="SELECT * FROM TABLE_NAME"+ hasTopBar+ hasRunButton={!readOnly}+ isInitiallyOpen+ isNativeEditorOpen+ readOnly={readOnly}+ hasParametersList={false}+ isRunnable={isRunnable}+ isRunning={isRunning}+ isResultDirty={isResultDirty}+ isShowingDataReference={isShowingDataReference}+ isShowingSnippetSidebar={isShowingSnippetSidebar}+ runQuery={onRunQuery}+ cancelQuery={onCancelQuery}+ databaseIsDisabled={shouldDisableDatabase}+ setDatasetQuery={handleNativeQueryChange}+ sidebarFeatures={NATIVE_EDITOR_SIDEBAR_FEATURES}+ toggleDataReference={onToggleDataReference}+ toggleSnippetSidebar={onToggleSnippetSidebar}+ modalSnippet={modalSnippet}+ insertSnippet={onInsertSnippet}+ closeSnippetModal={() => onChangeModalSnippet(null)}+ setNativeEditorSelectedRange={onChangeNativeEditorSelection}+ nativeEditorSelectedText={nativeEditorSelectedText}+ onBlur={onBlur}+ onOpenModal={onOpenModal}+ onAcceptProposed={onAcceptProposed}+ onRejectProposed={onRejectProposed}+ topBarInnerContent={topBarInnerContent}+ extraButton={extraButton}+ />+ );+ }++ return (<ResizableBoxaxis="y"className={S.queryResizableBox}diff --git a/frontend/src/metabase/rich_text_editing/tiptap/extensions/shared/NativeQueryModal.tsx b/frontend/src/metabase/rich_text_editing/tiptap/extensions/shared/NativeQueryModal.tsxindex 16aba19d654..39eefbd80a8 100644--- a/frontend/src/metabase/rich_text_editing/tiptap/extensions/shared/NativeQueryModal.tsx+++ b/frontend/src/metabase/rich_text_editing/tiptap/extensions/shared/NativeQueryModal.tsx@@ -1,3 +1,4 @@+import { useElementSize } from "@mantine/hooks";import { useCallback, useEffect, useMemo, useState } from "react";import { c, t } from "ttag";@@ -11,7 +12,7 @@ import {} from "metabase/documents/documents.slice";import { isMac } from "metabase/lib/browser";import { useDispatch, useSelector } from "metabase/lib/redux";-import NativeQueryEditor from "metabase/query_builder/components/NativeQueryEditor";+import { NativeQueryEditor } from "metabase/query_builder/components/NativeQueryEditor";import DataReference from "metabase/query_builder/components/dataref/DataReference";import { createRawSeries } from "metabase/query_builder/utils";import { getMetadata } from "metabase/selectors/metadata";@@ -38,10 +39,6 @@ interface NativeQueryModalProps {initialDataset?: Dataset;}-const EDITOR_HEIGHT_RATIO = 0.4;-const EDITOR_MIN_HEIGHT = 200;-const EDITOR_HEIGHT_OFFSET = 80;-const MODAL_SIDEBAR_FEATURES = {dataReference: true,variables: false,@@ -139,6 +136,8 @@ export const NativeQueryModal = ({typeof triggerQuery> | null>(null);+ const { ref: mainRef, height: totalHeight } = useElementSize();+const isQueryRunning = isLoading || isFetching;const datasetToUse =@@ -302,6 +301,11 @@ export const NativeQueryModal = ({);}+ const nativeQuery =+ modifiedQuestion?.legacyNativeQuery() ??+ question?.legacyNativeQuery() ??+ null;+return (<Modalopened={isOpen}@@ -322,24 +326,20 @@ export const NativeQueryModal = ({mih={0}miw={0}className={S.mainContent}+ ref={mainRef}><Box pos="relative" className={S.editorContainer}>- {(modifiedQuestion?.legacyNativeQuery() ||- question?.legacyNativeQuery()) && (+ {nativeQuery && (<NativeQueryEditorquestion={modifiedQuestion}- query={- modifiedQuestion?.legacyNativeQuery() ??- question?.legacyNativeQuery() ??- {}- }+ query={nativeQuery}isNativeEditorOpenisInitiallyOpenhasTopBarhasEditingSidebarhasParametersList={false}sidebarFeatures={MODAL_SIDEBAR_FEATURES}- viewHeight={400}+ availableHeight={totalHeight}isRunnableisRunning={isQueryRunning}isResultDirty={false}@@ -347,7 +347,6 @@ export const NativeQueryModal = ({isShowingTemplateTagsEditor={isShowingTemplateTagsEditor}isShowingSnippetSidebar={false}setDatasetQuery={setDatasetQuery}- runQuestionQuery={handleRunQuery}runQuery={handleRunQuery}cancelQuery={handleCancelQuery}toggleTemplateTagsEditor={() =>@@ -379,21 +378,6 @@ export const NativeQueryModal = ({setModifiedQuestion(newQuestion);}}resizable- resizableBoxProps={{- height: Math.max(- EDITOR_MIN_HEIGHT,- Math.floor(- window.innerHeight * EDITOR_HEIGHT_RATIO -- EDITOR_HEIGHT_OFFSET,- ),- ),- style: {- border: "none",- width: "100%",- minWidth: 0,- overflow: "hidden",- },- }}/>)}</Box>