Skip to content

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

Place SQL review controls under proposals with shortcut hints (#83922)

Andrei Simionescu2ef32e05bc0e
diff --git a/enterprise/frontend/src/metabase-enterprise/transforms-python/components/PythonTransformEditor/PythonEditorBody/PythonEditorBody.tsx b/enterprise/frontend/src/metabase-enterprise/transforms-python/components/PythonTransformEditor/PythonEditorBody/PythonEditorBody.tsx
index fbb7745edf4..d46c8387fa0 100644
--- a/enterprise/frontend/src/metabase-enterprise/transforms-python/components/PythonTransformEditor/PythonEditorBody/PythonEditorBody.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/transforms-python/components/PythonTransformEditor/PythonEditorBody/PythonEditorBody.tsx
@@ -6,7 +6,7 @@ import { t } from "ttag";
import { clickableTokens } from "metabase/common/components/CodeMirror";
import { RunButtonWithTooltip } from "metabase/querying/components/QueryVisualization/RunButtonWithTooltip";
import { useNavigate } from "metabase/router";
-import { Button, Flex, Icon, Stack, Tooltip } from "metabase/ui";
+import { Flex, Stack } from "metabase/ui";
import * as Urls from "metabase/urls";
import { SHARED_LIB_IMPORT_PATH } from "../../../constants";
@@ -29,8 +29,6 @@ export type PythonEditorBodyProps = {
isDirty?: boolean;
tables?: Record<string, number>;
withDebugger?: boolean;
- onAcceptProposed?: () => void;
- onRejectProposed?: () => void;
};
const EDITOR_HEIGHT = 400;
@@ -50,8 +48,6 @@ export function PythonEditorBody({
isRunning,
isDirty,
withDebugger,
- onAcceptProposed,
- onRejectProposed,
}: PythonEditorBodyProps) {
const [isResizing, setIsResizing] = useState(false);
const showResizeHandle = isEditMode && withDebugger;
@@ -98,28 +94,6 @@ export function PythonEditorBody({
{isEditMode && (
<Stack m="1rem" gap="lg" mt="auto">
- {proposedSource && onRejectProposed && onAcceptProposed && (
- <>
- <Tooltip label={t`Accept proposed changes`} position="left">
- <Button
- data-testid="accept-proposed-changes-button"
- variant="light"
- color="positive"
- onClick={onAcceptProposed}
- leftSection={<Icon name="check" />}
- />
- </Tooltip>
- <Tooltip label={t`Reject proposed changes`} position="left">
- <Button
- data-testid="reject-proposed-changes-button"
- variant="light"
- color="negative"
- onClick={onRejectProposed}
- leftSection={<Icon name="close" />}
- />
- </Tooltip>
- </>
- )}
{!hideRunButton && (
<RunButtonWithTooltip
disabled={!isRunnable}
diff --git a/enterprise/frontend/src/metabase-enterprise/transforms-python/components/PythonTransformEditor/PythonEditorBody/PythonEditorBody.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/transforms-python/components/PythonTransformEditor/PythonEditorBody/PythonEditorBody.unit.spec.tsx
index 42216b35ff4..34bb3a0afdb 100644
--- a/enterprise/frontend/src/metabase-enterprise/transforms-python/components/PythonTransformEditor/PythonEditorBody/PythonEditorBody.unit.spec.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/transforms-python/components/PythonTransformEditor/PythonEditorBody/PythonEditorBody.unit.spec.tsx
@@ -6,31 +6,24 @@ import { PythonEditorBody } from "./PythonEditorBody";
type SetupOpts = {
source?: string;
- proposedSource?: string;
isEditMode?: boolean;
isRunnable?: boolean;
isRunning?: boolean;
isDirty?: boolean;
withDebugger?: boolean;
- onAcceptProposed?: () => void;
- onRejectProposed?: () => void;
};
function setup({
source = "# test script",
- proposedSource,
isEditMode = true,
isRunnable = true,
isRunning = false,
isDirty = false,
withDebugger = true,
- onAcceptProposed,
- onRejectProposed,
}: SetupOpts = {}) {
renderWithProviders(
<PythonEditorBody
source={source}
- proposedSource={proposedSource}
isEditMode={isEditMode}
isRunnable={isRunnable}
isRunning={isRunning}
@@ -39,8 +32,6 @@ function setup({
onChange={jest.fn()}
onRun={jest.fn()}
onCancel={jest.fn()}
- onAcceptProposed={onAcceptProposed}
- onRejectProposed={onRejectProposed}
/>,
);
}
@@ -52,22 +43,6 @@ describe("PythonEditorBody", () => {
expect(screen.queryByTestId("run-button")).not.toBeInTheDocument();
});
- it("should not render proposed changes buttons when not in edit mode", () => {
- setup({
- isEditMode: false,
- proposedSource: "# proposed",
- onAcceptProposed: jest.fn(),
- onRejectProposed: jest.fn(),
- });
-
- expect(
- screen.queryByTestId("accept-proposed-changes-button"),
- ).not.toBeInTheDocument();
- expect(
- screen.queryByTestId("reject-proposed-changes-button"),
- ).not.toBeInTheDocument();
- });
-
it("should render the python editor", () => {
setup({ isEditMode: false });
expect(screen.getByTestId("python-editor")).toBeInTheDocument();
@@ -80,33 +55,6 @@ describe("PythonEditorBody", () => {
expect(screen.getByTestId("run-button")).toBeInTheDocument();
});
- it("should render proposed changes buttons when proposedSource and callbacks are provided", () => {
- setup({
- isEditMode: true,
- proposedSource: "# proposed changes",
- onAcceptProposed: jest.fn(),
- onRejectProposed: jest.fn(),
- });
-
- expect(
- screen.getByTestId("accept-proposed-changes-button"),
- ).toBeInTheDocument();
- expect(
- screen.getByTestId("reject-proposed-changes-button"),
- ).toBeInTheDocument();
- });
-
- it("should not render proposed changes buttons when proposedSource is not provided", () => {
- setup({ isEditMode: true });
-
- expect(
- screen.queryByTestId("accept-proposed-changes-button"),
- ).not.toBeInTheDocument();
- expect(
- screen.queryByTestId("reject-proposed-changes-button"),
- ).not.toBeInTheDocument();
- });
-
it("should render the python editor", () => {
setup({ isEditMode: true });
expect(screen.getByTestId("python-editor")).toBeInTheDocument();
diff --git a/frontend/src/metabase/querying/components/CodeMirrorEditor/CodeMirrorEditor.tsx b/frontend/src/metabase/querying/components/CodeMirrorEditor/CodeMirrorEditor.tsx
index 86c836ed757..7c33930cdd9 100644
--- a/frontend/src/metabase/querying/components/CodeMirrorEditor/CodeMirrorEditor.tsx
+++ b/frontend/src/metabase/querying/components/CodeMirrorEditor/CodeMirrorEditor.tsx
@@ -21,7 +21,9 @@ import type { CardId } from "metabase-types/api";
import type { SelectionRange } from "../../editor/types";
import S from "./CodeMirrorEditor.module.css";
+import { DiffControls } from "./DiffControls";
import { useExtensions } from "./extensions";
+import { useDiffControls } from "./use-diff-controls";
import {
getPlaceholderText,
getSelectedRanges,
@@ -43,6 +45,8 @@ export type CodeMirrorEditorProps = {
onRightClickSelection?: () => void;
onSelectionChange?: (range: SelectionRange[]) => void;
onBlur?: () => void;
+ onAcceptProposed?: () => void;
+ onRejectProposed?: () => void;
};
export interface CodeMirrorEditorRef {
@@ -69,10 +73,23 @@ export const CodeMirrorEditor = forwardRef<
onCursorMoveOverCardTag,
onFormatQuery,
onBlur,
+ onAcceptProposed,
+ onRejectProposed,
},
ref,
) {
const editorRef = useRef<CodeMirrorRef>(null);
+ const hasDiffControls =
+ !!proposedQuery && !readOnly && !!onAcceptProposed && !!onRejectProposed;
+ const {
+ extensions: diffControlsExtensions,
+ portalTarget,
+ shortcuts,
+ } = useDiffControls({
+ isEnabled: hasDiffControls,
+ onAcceptProposed,
+ onRejectProposed,
+ });
const placeholder =
placeholderProp ??
getPlaceholderText(Lib.engine(query), hasSqlGenerationAccess);
@@ -83,11 +100,12 @@ export const CodeMirrorEditor = forwardRef<
});
const extensions = useMemo(() => {
- if (customExtensions?.length) {
- return [...baseExtensions, ...customExtensions];
- }
- return baseExtensions;
- }, [baseExtensions, customExtensions]);
+ return [
+ ...baseExtensions,
+ ...diffControlsExtensions,
+ ...(customExtensions ?? []),
+ ];
+ }, [baseExtensions, customExtensions, diffControlsExtensions]);
useImperativeHandle(ref, () => {
return {
@@ -156,23 +174,33 @@ export const CodeMirrorEditor = forwardRef<
}, [proposedQuery, query]);
return (
- <CodeMirror
- ref={editorRef}
- data-testid="native-query-editor"
- className={S.editor}
- editable={!readOnly}
- extensions={extensions}
- value={value}
- readOnly={readOnly}
- onChange={onChange}
- height="100%"
- onUpdate={handleUpdate}
- autoFocus
- autoCorrect="off"
- placeholder={placeholder}
- highlightRanges={highlightedRanges}
- onFormat={onFormatQuery}
- onBlur={onBlur}
- />
+ <>
+ <CodeMirror
+ ref={editorRef}
+ data-testid="native-query-editor"
+ className={S.editor}
+ editable={!readOnly}
+ extensions={extensions}
+ value={value}
+ readOnly={readOnly}
+ onChange={onChange}
+ height="100%"
+ onUpdate={handleUpdate}
+ autoFocus
+ autoCorrect="off"
+ placeholder={placeholder}
+ highlightRanges={highlightedRanges}
+ onFormat={onFormatQuery}
+ onBlur={onBlur}
+ />
+ {hasDiffControls && (
+ <DiffControls
+ portalTarget={portalTarget}
+ shortcuts={shortcuts}
+ onAcceptProposed={onAcceptProposed}
+ onRejectProposed={onRejectProposed}
+ />
+ )}
+ </>
);
});
diff --git a/frontend/src/metabase/querying/components/CodeMirrorEditor/CodeMirrorEditor.unit.spec.tsx b/frontend/src/metabase/querying/components/CodeMirrorEditor/CodeMirrorEditor.unit.spec.tsx
index f9c8bacef8f..fae25b72a25 100644
--- a/frontend/src/metabase/querying/components/CodeMirrorEditor/CodeMirrorEditor.unit.spec.tsx
+++ b/frontend/src/metabase/querying/components/CodeMirrorEditor/CodeMirrorEditor.unit.spec.tsx
@@ -1,27 +1,50 @@
+jest.unmock("@uiw/react-codemirror");
+
+import userEvent from "@testing-library/user-event";
import fetchMock from "fetch-mock";
import { createMockMetadata } from "__support__/metadata";
-import { renderWithProviders, screen } from "__support__/ui";
+import {
+ fireEvent,
+ renderWithProviders,
+ screen,
+ waitFor,
+ within,
+} from "__support__/ui";
+import * as Browser from "metabase/utils/browser";
import * as Lib from "metabase-lib";
import { createMetadataProvider } from "metabase-lib/test-helpers";
import type { NativeQuerySnippet } from "metabase-types/api";
import { createSampleDatabase } from "metabase-types/api/mocks/presets";
-import { CodeMirrorEditor } from "./CodeMirrorEditor";
+import {
+ CodeMirrorEditor,
+ type CodeMirrorEditorProps,
+} from "./CodeMirrorEditor";
+import { getDiffControls } from "./test-utils";
+
+const ORIGINAL =
+ "SELECT *\nFROM orders\nWHERE id = 1\nGROUP BY id\nORDER BY id\nLIMIT 10";
+const PROPOSED = ORIGINAL.replace("WHERE id = 1", "WHERE id = 2");
function setup({
text = "",
readOnly = false,
snippets = [],
+ proposedText,
}: {
text?: string;
readOnly?: boolean;
snippets?: NativeQuerySnippet[];
+ proposedText?: string;
} = {}) {
const onChange = jest.fn();
const onCursorMoveOverCardTag = jest.fn();
const onRightClickSelection = jest.fn();
const onSelectionChange = jest.fn();
+ const onAcceptProposed = jest.fn();
+ const onRejectProposed = jest.fn();
+ const onRunQuery = jest.fn();
fetchMock.get("path:/api/native-query-snippet", {
body: snippets,
@@ -38,30 +61,213 @@ function setup({
const query = Lib.createTestNativeQuery(provider, { query: text });
- renderWithProviders(
- <CodeMirrorEditor
- query={query}
- onChange={onChange}
- readOnly={readOnly}
- onCursorMoveOverCardTag={onCursorMoveOverCardTag}
- onRightClickSelection={onRightClickSelection}
- onSelectionChange={onSelectionChange}
- />,
+ const props: CodeMirrorEditorProps = {
+ query,
+ proposedQuery:
+ proposedText !== undefined
+ ? Lib.createTestNativeQuery(provider, { query: proposedText })
+ : undefined,
+ onAcceptProposed,
+ onRejectProposed,
+ onRunQuery,
+ onChange,
+ readOnly,
+ onCursorMoveOverCardTag,
+ onRightClickSelection,
+ onSelectionChange,
+ };
+ const { rerender, container } = renderWithProviders(
+ <CodeMirrorEditor {...props} />,
);
return {
+ container,
onChange,
onCursorMoveOverCardTag,
onRightClickSelection,
onSelectionChange,
+ onAcceptProposed,
+ onRejectProposed,
+ onRunQuery,
+ createQuery: (text: string) =>
+ Lib.createTestNativeQuery(provider, { query: text }),
+ rerender: (overrides: Partial<CodeMirrorEditorProps>) =>
+ rerender(<CodeMirrorEditor {...props} {...overrides} />),
};
}
describe("CodemirrorEditor", () => {
+ afterEach(() => {
+ jest.restoreAllMocks();
+ });
+
+ it.each([
+ ["an earlier line", "FROM orders", "FROM people"],
+ ["the same line", "WHERE id = 1", "WHERE id = 3"],
+ ["a later line", "ORDER BY id", "ORDER BY total"],
+ ])(
+ "keeps the buttons under a second proposal on %s",
+ async (_name, before, after) => {
+ const { createQuery, rerender } = setup({ text: ORIGINAL });
+ rerender({ proposedQuery: createQuery(PROPOSED) });
+ expect(getDiffControls().previousLine).toHaveTextContent("WHERE id = 2");
+
+ rerender({ proposedQuery: createQuery(ORIGINAL.replace(before, after)) });
+
+ await waitFor(() =>
+ expect(screen.getByRole("textbox")).toHaveTextContent(after),
+ );
+ expect(getDiffControls().previousLine).toHaveTextContent(after);
+ },
+ );
+
+ it("keeps the buttons after undoing a proposal", async () => {
+ const { createQuery, rerender } = setup({ text: ORIGINAL });
+ rerender({ proposedQuery: createQuery(PROPOSED) });
+ expect(getDiffControls().previousLine).toHaveTextContent("WHERE id = 2");
+
+ fireEvent.keyDown(screen.getByRole("textbox"), {
+ key: "z",
+ code: "KeyZ",
+ ctrlKey: true,
+ });
+
+ await waitFor(() =>
+ expect(screen.getByRole("textbox")).toHaveTextContent("WHERE id = 1"),
+ );
+ expect(getDiffControls().previousLine).toHaveTextContent("LIMIT 10");
+ });
+
+ it("keeps the editor configuration and styles stable when callbacks change", () => {
+ const { rerender, onRejectProposed } = setup({
+ text: ORIGINAL,
+ proposedText: PROPOSED,
+ });
+ const styleRuleCount = () =>
+ Array.from(document.styleSheets).reduce(
+ (count, sheet) => count + sheet.cssRules.length,
+ 0,
+ );
+ const before = styleRuleCount();
+ const reject = jest.fn();
+
+ rerender({ onRejectProposed: reject });
+
+ expect(styleRuleCount()).toBe(before);
+ expect(getDiffControls().previousLine).toHaveTextContent("WHERE id = 2");
+ fireEvent.keyDown(screen.getByRole("textbox"), {
+ key: "x",
+ altKey: true,
+ ctrlKey: true,
+ });
+ expect(reject).toHaveBeenCalledTimes(1);
+ expect(onRejectProposed).not.toHaveBeenCalled();
+ });
+
+ it("renders working review buttons when the changed chunk is outside the viewport", async () => {
+ const { container, onAcceptProposed } = setup({
+ text: "SELECT 1",
+ proposedText: Array.from(
+ { length: 3000 },
+ (_, line) => `SELECT ${line}`,
+ ).join("\n"),
+ });
+ await screen.findByRole("button", { name: /Accept/ });
+ const { row, parent } = getDiffControls(container);
+ expect(parent).toHaveClass("cm-editor");
+ expect(screen.getByRole("textbox")).not.toHaveTextContent("SELECT 2999");
+ await userEvent.click(within(row).getByRole("button", { name: /Accept/ }));
+ expect(onAcceptProposed).toHaveBeenCalledTimes(1);
+ });
+
it("Should render the natie query's text", () => {
const text = "SELECT 1;";
setup({ text });
expect(screen.getByRole("textbox")).toHaveTextContent(text);
});
+
+ it.each([
+ ["Accept", "onAcceptProposed"],
+ ["Reject", "onRejectProposed"],
+ ] as const)("resolves the proposal with %s", async (label, callback) => {
+ const callbacks = setup({ text: "SELECT 1", proposedText: "SELECT 2" });
+
+ await userEvent.click(
+ screen.getByRole("button", { name: new RegExp(label) }),
+ );
+
+ expect(callbacks[callback]).toHaveBeenCalledTimes(1);
+ });
+
+ it.each([
+ {
+ platform: "Linux",
+ isWindows: false,
+ hint: "CtrlAlt",
+ modifiers: { ctrlKey: true, altKey: true },
+ },
+ {
+ platform: "Windows",
+ isWindows: true,
+ hint: "AltShift",
+ modifiers: { altKey: true, shiftKey: true },
+ },
+ ])(
+ "resolves the proposal with the $platform shortcuts",
+ ({ isWindows, hint, modifiers }) => {
+ jest.spyOn(Browser, "isWindows").mockReturnValue(isWindows);
+ const { onAcceptProposed, onRejectProposed, onRunQuery } = setup({
+ text: "SELECT 1",
+ proposedText: "SELECT 2",
+ });
+
+ expect(screen.getByRole("button", { name: /Accept/ })).toHaveTextContent(
+ `Accept${hint}Y`,
+ );
+ expect(screen.getByRole("button", { name: /Reject/ })).toHaveTextContent(
+ `Reject${hint}X`,
+ );
+
+ fireEvent.keyDown(screen.getByRole("textbox"), {
+ key: "y",
+ code: "KeyY",
+ ...modifiers,
+ });
+ expect(onAcceptProposed).toHaveBeenCalledTimes(1);
+
+ fireEvent.keyDown(screen.getByRole("textbox"), {
+ key: "x",
+ code: "KeyX",
+ ...modifiers,
+ });
+ expect(onRejectProposed).toHaveBeenCalledTimes(1);
+ expect(onRunQuery).not.toHaveBeenCalled();
+ },
+ );
+
+ it("runs the query with Ctrl+Enter while reviewing a proposal", () => {
+ const { onRunQuery } = setup({
+ text: "SELECT 1",
+ proposedText: "SELECT 2",
+ });
+
+ fireEvent.keyDown(screen.getByRole("textbox"), {
+ key: "Enter",
+ ctrlKey: true,
+ });
+
+ expect(onRunQuery).toHaveBeenCalledTimes(1);
+ });
+
+ it("keeps read-only proposals read-only", () => {
+ setup({ text: "SELECT 1", proposedText: "SELECT 2", readOnly: true });
+
+ expect(
+ screen.queryByRole("button", { name: /Accept/ }),
+ ).not.toBeInTheDocument();
+ expect(
+ screen.queryByRole("button", { name: /Reject/ }),
+ ).not.toBeInTheDocument();
+ });
});
diff --git a/frontend/src/metabase/querying/components/CodeMirrorEditor/DiffControls.tsx b/frontend/src/metabase/querying/components/CodeMirrorEditor/DiffControls.tsx
new file mode 100644
index 00000000000..c6dcfd58d04
--- /dev/null
+++ b/frontend/src/metabase/querying/components/CodeMirrorEditor/DiffControls.tsx
@@ -0,0 +1,44 @@
+import { createPortal } from "react-dom";
+import { t } from "ttag";
+
+import { Button, Flex, KeyboardShortcut } from "metabase/ui";
+
+import type { DiffControlsShortcuts } from "./use-diff-controls";
+
+type DiffControlsProps = {
+ portalTarget: HTMLElement;
+ shortcuts: DiffControlsShortcuts;
+ onAcceptProposed: () => void;
+ onRejectProposed: () => void;
+};
+
+export function DiffControls({
+ portalTarget,
+ shortcuts,
+ onAcceptProposed,
+ onRejectProposed,
+}: DiffControlsProps) {
+ return createPortal(
+ <Flex gap="xs" py="xxs" px="xs" bg="background_page-secondary">
+ <Button
+ data-testid="accept-proposed-changes-button"
+ variant="default"
+ size="sm"
+ onClick={onAcceptProposed}
+ rightSection={<KeyboardShortcut shortcut={shortcuts.accept.hint} />}
+ >
+ {t`Accept`}
+ </Button>
+ <Button
+ data-testid="reject-proposed-changes-button"
+ variant="default"
+ size="sm"
+ onClick={onRejectProposed}
+ rightSection={<KeyboardShortcut shortcut={shortcuts.reject.hint} />}
+ >
+ {t`Reject`}
+ </Button>
+ </Flex>,
+ portalTarget,
+ );
+}
diff --git a/frontend/src/metabase/querying/components/CodeMirrorEditor/test-utils.ts b/frontend/src/metabase/querying/components/CodeMirrorEditor/test-utils.ts
new file mode 100644
index 00000000000..5eb9c39f6cc
--- /dev/null
+++ b/frontend/src/metabase/querying/components/CodeMirrorEditor/test-utils.ts
@@ -0,0 +1,20 @@
+import { screen, within } from "__support__/ui";
+import { checkNotNull } from "metabase/utils/types";
+
+export function getDiffControls(container = screen.getByRole("textbox")) {
+ const row = checkNotNull(
+ container.querySelector<HTMLDivElement>(".cm-diff-controls"),
+ );
+ expect(
+ within(row).getByRole("button", { name: /Accept/ }),
+ ).toBeInTheDocument();
+ expect(
+ within(row).getByRole("button", { name: /Reject/ }),
+ ).toBeInTheDocument();
+ return {
+ row,
+ previousLine: row.previousElementSibling,
+ nextLine: row.nextElementSibling,
+ parent: row.parentElement,
+ };
+}
diff --git a/frontend/src/metabase/querying/components/CodeMirrorEditor/use-diff-controls.ts b/frontend/src/metabase/querying/components/CodeMirrorEditor/use-diff-controls.ts
new file mode 100644
index 00000000000..2d9b8c62407
--- /dev/null
+++ b/frontend/src/metabase/querying/components/CodeMirrorEditor/use-diff-controls.ts
@@ -0,0 +1,228 @@
+import { getChunks } from "@codemirror/merge";
+import { type EditorState, Prec, StateField } from "@codemirror/state";
+import {
+ Decoration,
+ type DecorationSet,
+ EditorView,
+ ViewPlugin,
+ type ViewUpdate,
+ WidgetType,
+ keymap,
+} from "@codemirror/view";
+import { useMemo } from "react";
+import { useLatest } from "react-use";
+import { once } from "underscore";
+
+import { isMac, isWindows } from "metabase/utils/browser";
+
+const CONTROLS_CLASS_NAME = "cm-diff-controls";
+const FALLBACK_CLASS_NAME = "cm-diff-controls-fallback";
+const getControlsTheme = once(() =>
+ EditorView.baseTheme({
+ [`.${CONTROLS_CLASS_NAME}`]: {
+ position: "sticky",
+ bottom: "0",
+ zIndex: "1",
+ boxSizing: "border-box",
+ },
+ [`.${FALLBACK_CLASS_NAME}`]: {
+ position: "absolute",
+ left: "0",
+ bottom: "0",
+ },
+ }),
+);
+
+function getShortcuts() {
+ let keyModifiers = "Ctrl-Alt";
+ let hintModifiers = "$mod+Alt";
+ if (isWindows()) {
+ keyModifiers = "Alt-Shift";
+ hintModifiers = "Alt+Shift";
+ } else if (isMac()) {
+ keyModifiers = "Meta-Alt";
+ }
+ return {
+ accept: { key: `${keyModifiers}-y`, hint: `${hintModifiers}+y` },
+ reject: { key: `${keyModifiers}-x`, hint: `${hintModifiers}+x` },
+ };
+}
+
+export type DiffControlsShortcuts = ReturnType<typeof getShortcuts>;
+
+class DiffControlsWidget extends WidgetType {
+ constructor(private readonly container: HTMLElement) {
+ super();
+ }
+
+ toDOM() {
+ return this.container;
+ }
+
+ eq(other: DiffControlsWidget) {
+ return this.container === other.container;
+ }
+}
+
+class DiffControlsViewport {
+ constructor(
+ private readonly view: EditorView,
+ private readonly container: HTMLElement,
+ private readonly controlsField: StateField<DecorationSet>,
+ ) {
+ this.measure();
+ }
+
+ update(update: ViewUpdate) {
+ if (
+ update.docChanged ||
+ update.viewportChanged ||
+ update.geometryChanged ||
+ update.transactions.some((transaction) => transaction.reconfigured)
+ ) {
+ this.measure();
+ }
+ }
+
+ measure() {
+ const { container, controlsField } = this;
+ this.view.requestMeasure({
+ key: this,
+ read(view) {
+ const decorations = view.state.field(controlsField, false);
+ if (!decorations) {
+ return null;
+ }
+ return {
+ isMounted: view.contentDOM.contains(container),
+ isBelowViewport: decorations.iter().from >= view.viewport.to,
+ gutterWidth: view.contentDOM.offsetLeft,
+ scrollbarWidth:
+ view.scrollDOM.offsetWidth - view.scrollDOM.clientWidth,
+ };
+ },
+ write(position, view) {
+ if (!position) {
+ return;
+ }
+ if (position.isMounted) {
+ container.classList.remove(FALLBACK_CLASS_NAME);
+ container.style.paddingLeft = "";
+ container.style.right = "";
+ } else if (position.isBelowViewport) {
+ container.classList.add(FALLBACK_CLASS_NAME);
+ container.style.paddingLeft = `${position.gutterWidth}px`;
+ container.style.right = `${position.scrollbarWidth}px`;
+ if (container.parentElement !== view.dom) {
+ view.dom.append(container);
+ }
+ } else {
+ container.remove();
+ }
+ },
+ });
+ }
+
+ destroy() {
+ this.container.remove();
+ }
+}
+
+export function createDiffControlsExtensions({
+ container,
+ shortcuts = getShortcuts(),
+ onAcceptProposed,
+ onRejectProposed,
+}: {
+ container: HTMLElement;
+ shortcuts?: DiffControlsShortcuts;
+ onAcceptProposed: () => void;
+ onRejectProposed: () => void;
+}) {
+ container.className = CONTROLS_CLASS_NAME;
+ const widget = new DiffControlsWidget(container);
+
+ function decorate(state: EditorState) {
+ const chunk = getChunks(state)?.chunks.at(-1);
+ const isDeletion = chunk != null && chunk.fromB === chunk.toB;
+ const position = isDeletion
+ ? chunk.fromB
+ : state.doc.lineAt(chunk?.endB ?? state.doc.length).to;
+
+ return Decoration.set([
+ Decoration.widget({
+ widget,
+ block: true,
+ side: isDeletion ? 0 : 1,
+ }).range(position),
+ ]);
+ }
+
+ const controlsField = StateField.define<DecorationSet>({
+ create: decorate,
+ update(decorations, transaction) {
+ const before = getChunks(transaction.startState)?.chunks;
+ const after = getChunks(transaction.state)?.chunks;
+ return transaction.docChanged || before !== after
+ ? decorate(transaction.state)
+ : decorations;
+ },
+ provide: (field) => EditorView.decorations.from(field),
+ });
+
+ return [
+ getControlsTheme(),
+ controlsField,
+ EditorView.scrollMargins.of(() => ({ bottom: container.offsetHeight })),
+ ViewPlugin.define(
+ (view) => new DiffControlsViewport(view, container, controlsField),
+ ),
+ Prec.highest(
+ keymap.of([
+ {
+ key: shortcuts.accept.key,
+ run: () => {
+ onAcceptProposed();
+ return true;
+ },
+ },
+ {
+ key: shortcuts.reject.key,
+ run: () => {
+ onRejectProposed();
+ return true;
+ },
+ },
+ ]),
+ ),
+ ];
+}
+
+export function useDiffControls({
+ isEnabled,
+ onAcceptProposed,
+ onRejectProposed,
+}: {
+ isEnabled: boolean;
+ onAcceptProposed?: () => void;
+ onRejectProposed?: () => void;
+}) {
+ const portalTarget = useMemo(() => document.createElement("div"), []);
+ const shortcuts = useMemo(getShortcuts, []);
+ const onAcceptRef = useLatest(onAcceptProposed);
+ const onRejectRef = useLatest(onRejectProposed);
+ const extensions = useMemo(
+ () =>
+ isEnabled
+ ? createDiffControlsExtensions({
+ container: portalTarget,
+ shortcuts,
+ onAcceptProposed: () => onAcceptRef.current?.(),
+ onRejectProposed: () => onRejectRef.current?.(),
+ })
+ : [],
+ [isEnabled, portalTarget, shortcuts, onAcceptRef, onRejectRef],
+ );
+
+ return { extensions, portalTarget, shortcuts };
+}
diff --git a/frontend/src/metabase/querying/components/CodeMirrorEditor/use-diff-controls.unit.spec.ts b/frontend/src/metabase/querying/components/CodeMirrorEditor/use-diff-controls.unit.spec.ts
new file mode 100644
index 00000000000..5ed4393effa
--- /dev/null
+++ b/frontend/src/metabase/querying/components/CodeMirrorEditor/use-diff-controls.unit.spec.ts
@@ -0,0 +1,192 @@
+import { unifiedMergeView } from "@codemirror/merge";
+import { EditorView } from "@codemirror/view";
+
+import { createDiffControlsExtensions } from "./use-diff-controls";
+
+const ORIGINAL = "SELECT *\nFROM orders\nWHERE id = 1\nORDER BY id;\n-- end";
+const PROPOSED = "SELECT *\nFROM orders\nWHERE id = 2\nORDER BY id;\n-- end";
+let cleanup: (() => void) | undefined;
+
+function setup({ original = ORIGINAL, proposed = PROPOSED } = {}) {
+ const container = document.createElement("div");
+ document.body.append(container);
+ const controls = document.createElement("div");
+ const mergeExtension = unifiedMergeView({ original, mergeControls: false });
+ const view = new EditorView({
+ parent: container,
+ doc: proposed,
+ extensions: [
+ mergeExtension,
+ ...createDiffControlsExtensions({
+ container: controls,
+ onAcceptProposed: jest.fn(),
+ onRejectProposed: jest.fn(),
+ }),
+ ],
+ });
+
+ cleanup = () => {
+ view.destroy();
+ container.remove();
+ };
+
+ return { view, controls };
+}
+
+describe("diff controls widget", () => {
+ afterEach(() => {
+ cleanup?.();
+ cleanup = undefined;
+ });
+
+ it("gives the controls their own row between the change and following code", () => {
+ const { view, controls } = setup();
+
+ expect(controls.parentElement).toBe(view.contentDOM);
+ expect(controls.previousElementSibling).toHaveTextContent("WHERE id = 2");
+ expect(controls.nextElementSibling).toHaveTextContent("ORDER BY id;");
+ expect(controls.previousElementSibling).toHaveClass("cm-line");
+ expect(controls.nextElementSibling).toHaveClass("cm-line");
+ });
+
+ it("reserves the current review row height when scrolling the cursor into view", () => {
+ const { view, controls } = setup();
+ const height = jest
+ .spyOn(controls, "offsetHeight", "get")
+ .mockReturnValue(40);
+ const margins = () =>
+ view.state.facet(EditorView.scrollMargins).map((margin) => margin(view));
+
+ expect(margins()).toContainEqual({ bottom: 40 });
+
+ height.mockReturnValue(64);
+
+ expect(margins()).toContainEqual({ bottom: 64 });
+ });
+
+ it("places controls after the last of several changes", () => {
+ const { controls } = setup({
+ proposed: PROPOSED.replace("-- end", "-- changed"),
+ });
+
+ expect(controls.previousElementSibling).toHaveTextContent("-- changed");
+ expect(controls.nextElementSibling).toBeNull();
+ });
+
+ it("places controls after deleted lines and before following code", () => {
+ const { controls } = setup({
+ proposed: ORIGINAL.replace("WHERE id = 1\n", ""),
+ });
+
+ expect(controls.previousElementSibling).toHaveClass("cm-deletedChunk");
+ expect(controls.previousElementSibling).toHaveTextContent("WHERE id = 1");
+ expect(controls.nextElementSibling).toHaveTextContent("ORDER BY id;");
+ });
+
+ it.each([
+ ["an identical proposal", ORIGINAL, ORIGINAL],
+ ["a proposal replacing the whole query", "SELECT 1", PROPOSED],
+ ["an empty original query", "", PROPOSED],
+ ])("places controls after %s", (_name, original, proposed) => {
+ const { controls } = setup({ original, proposed });
+
+ expect(controls.previousElementSibling).toHaveTextContent("-- end");
+ expect(controls.nextElementSibling).toBeNull();
+ });
+});
+
+async function withWindowsEditor(
+ test: (
+ view: EditorView,
+ callbacks: {
+ onAcceptProposed: jest.Mock<void, []>;
+ onRejectProposed: jest.Mock<void, []>;
+ },
+ ) => void,
+) {
+ const platform = navigator.platform;
+ Object.defineProperty(navigator, "platform", {
+ value: "Win32",
+ configurable: true,
+ });
+ try {
+ await jest.isolateModulesAsync(async () => {
+ const { EditorView } = await import("@codemirror/view");
+ const { createDiffControlsExtensions } =
+ await import("./use-diff-controls");
+ const callbacks = {
+ onAcceptProposed: jest.fn<void, []>(),
+ onRejectProposed: jest.fn<void, []>(),
+ };
+ const view = new EditorView({
+ parent: document.body,
+ doc: "SELECT 2",
+ extensions: createDiffControlsExtensions({
+ container: document.createElement("div"),
+ ...callbacks,
+ }),
+ });
+ try {
+ test(view, callbacks);
+ } finally {
+ view.destroy();
+ }
+ });
+ } finally {
+ Object.defineProperty(navigator, "platform", { value: platform });
+ }
+}
+
+describe("Windows review shortcuts", () => {
+ it.each([
+ ["y", "onAcceptProposed", "onRejectProposed"],
+ ["x", "onRejectProposed", "onAcceptProposed"],
+ ] as const)(
+ "resolves the proposal with Alt+Shift+%s",
+ async (key, action, otherAction) => {
+ await withWindowsEditor((view, callbacks) => {
+ const event = new KeyboardEvent("keydown", {
+ key: key.toUpperCase(),
+ code: `Key${key.toUpperCase()}`,
+ keyCode: key.toUpperCase().charCodeAt(0),
+ altKey: true,
+ shiftKey: true,
+ bubbles: true,
+ cancelable: true,
+ });
+
+ view.contentDOM.dispatchEvent(event);
+
+ expect(callbacks[action]).toHaveBeenCalledTimes(1);
+ expect(callbacks[otherAction]).not.toHaveBeenCalled();
+ expect(event.defaultPrevented).toBe(true);
+ });
+ },
+ );
+
+ it.each([
+ ["ü", "KeyY", 89],
+ ["ź", "KeyX", 88],
+ ] as const)(
+ "leaves AltGr+%s available for typing",
+ async (key, code, keyCode) => {
+ await withWindowsEditor((view, callbacks) => {
+ const event = new KeyboardEvent("keydown", {
+ key,
+ code,
+ keyCode,
+ altKey: true,
+ ctrlKey: true,
+ bubbles: true,
+ cancelable: true,
+ });
+
+ view.contentDOM.dispatchEvent(event);
+
+ expect(callbacks.onAcceptProposed).not.toHaveBeenCalled();
+ expect(callbacks.onRejectProposed).not.toHaveBeenCalled();
+ expect(event.defaultPrevented).toBe(false);
+ });
+ },
+ );
+});
diff --git a/frontend/src/metabase/querying/components/NativeQueryEditor/NativeQueryEditor.proposal.unit.spec.tsx b/frontend/src/metabase/querying/components/NativeQueryEditor/NativeQueryEditor.proposal.unit.spec.tsx
new file mode 100644
index 00000000000..4085ba03fc7
--- /dev/null
+++ b/frontend/src/metabase/querying/components/NativeQueryEditor/NativeQueryEditor.proposal.unit.spec.tsx
@@ -0,0 +1,116 @@
+jest.unmock("@uiw/react-codemirror");
+
+import userEvent from "@testing-library/user-event";
+import { useState } from "react";
+
+import { createMockMetadata } from "__support__/metadata";
+import {
+ setupCollectionsEndpoints,
+ setupDatabasesEndpoints,
+ setupNativeQuerySnippetEndpoints,
+} from "__support__/server-mocks";
+import { renderWithProviders, screen, waitFor } from "__support__/ui";
+import { getDiffControls } from "metabase/querying/components/CodeMirrorEditor/test-utils";
+import { checkNotNull } from "metabase/utils/types";
+import * as Lib from "metabase-lib";
+import { createMetadataProvider } from "metabase-lib/test-helpers";
+import Question from "metabase-lib/v1/Question";
+import type NativeQuery from "metabase-lib/v1/queries/NativeQuery";
+import { createSampleDatabase } from "metabase-types/api/mocks/presets";
+
+import { NativeQueryEditor } from "./NativeQueryEditor";
+import { formatQuery } from "./utils";
+
+function setup({ text = "SELECT 1", proposedText = "SELECT 2" } = {}) {
+ setupNativeQuerySnippetEndpoints();
+ setupCollectionsEndpoints({ collections: [] });
+ const database = createSampleDatabase();
+ setupDatabasesEndpoints([database]);
+ const metadata = createMockMetadata({ databases: [database] });
+ const provider = createMetadataProvider({
+ databaseId: database.id,
+ metadata,
+ });
+ const initialQuestion = Question.create({ metadata }).setQuery(
+ Lib.createTestNativeQuery(provider, { query: text }),
+ );
+ const proposedQuestion = initialQuestion.setQuery(
+ Lib.withNativeQuery(initialQuestion.query(), proposedText),
+ );
+ const setDatasetQuery = jest.fn<void, [NativeQuery]>();
+ const onAcceptProposed = jest.fn();
+ const onRejectProposed = jest.fn();
+
+ function Editor() {
+ const [question, setQuestion] = useState(initialQuestion);
+ return (
+ <NativeQueryEditor
+ question={question}
+ query={checkNotNull(question.legacyNativeQuery())}
+ proposedQuestion={proposedQuestion}
+ isNativeEditorOpen
+ setDatasetQuery={(query) => {
+ setDatasetQuery(query);
+ setQuestion(question.setDatasetQuery(query.datasetQuery()));
+ }}
+ onAcceptProposed={onAcceptProposed}
+ onRejectProposed={onRejectProposed}
+ >
+ <NativeQueryEditor.TopBar>
+ <NativeQueryEditor.Sidebar />
+ </NativeQueryEditor.TopBar>
+ </NativeQueryEditor>
+ );
+ }
+
+ renderWithProviders(<Editor />);
+
+ return {
+ setDatasetQuery,
+ onAcceptProposed,
+ onRejectProposed,
+ proposedQuestion,
+ };
+}
+
+describe("native query proposals", () => {
+ it("keeps the review buttons under the changed clause after auto-format", async () => {
+ const text =
+ "select id, total from orders where id = 1 order by id limit 10";
+ const formatted = await formatQuery(text, "h2");
+ setup({ text, proposedText: formatted.replace("id = 1", "id = 2") });
+ expect(screen.getByRole("button", { name: /Accept/ })).toBeInTheDocument();
+
+ await userEvent.click(await screen.findByLabelText("Auto-format"));
+
+ await waitFor(() =>
+ expect(getDiffControls().previousLine).toHaveTextContent("id = 2"),
+ );
+ expect(getDiffControls().nextLine).toHaveTextContent("ORDER BY");
+ });
+
+ it("applies the proposed SQL before accepting it", async () => {
+ const { setDatasetQuery, onAcceptProposed, proposedQuestion } = setup();
+
+ await userEvent.click(screen.getByRole("button", { name: /Accept/ }));
+
+ expect(setDatasetQuery).toHaveBeenCalledTimes(1);
+ expect(checkNotNull(setDatasetQuery.mock.calls[0]?.[0]).queryText()).toBe(
+ "SELECT 2",
+ );
+ expect(onAcceptProposed).toHaveBeenCalledWith(
+ proposedQuestion.datasetQuery(),
+ );
+ expect(setDatasetQuery.mock.invocationCallOrder[0]).toBeLessThan(
+ onAcceptProposed.mock.invocationCallOrder[0],
+ );
+ });
+
+ it("rejects the proposed SQL", async () => {
+ const { onRejectProposed } = setup();
+
+ await userEvent.click(screen.getByRole("button", { name: /Reject/ }));
+
+ expect(onRejectProposed).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/frontend/src/metabase/querying/components/NativeQueryEditor/NativeQueryEditorRoot.tsx b/frontend/src/metabase/querying/components/NativeQueryEditor/NativeQueryEditorRoot.tsx
index e1662e22688..d8d03ad302b 100644
--- a/frontend/src/metabase/querying/components/NativeQueryEditor/NativeQueryEditorRoot.tsx
+++ b/frontend/src/metabase/querying/components/NativeQueryEditor/NativeQueryEditorRoot.tsx
@@ -12,7 +12,6 @@ import {
useState,
} from "react";
import { useLatest, useMount } from "react-use";
-import { t } from "ttag";
import { useListCollectionsQuery, useListSnippetsQuery } from "metabase/api";
import { PLUGIN_REMOTE_SYNC } from "metabase/plugins";
@@ -27,7 +26,7 @@ import { useNotebookScreenSize } from "metabase/querying/components/NativeQueryE
import type { SelectionRange } from "metabase/querying/editor/types";
import { useSelector } from "metabase/redux";
import type { QueryModalType } from "metabase/redux/store";
-import { Button, Flex, Icon, Stack, Tooltip } from "metabase/ui";
+import { Flex, Stack } from "metabase/ui";
import * as Lib from "metabase-lib";
import type Question from "metabase-lib/v1/Question";
import type NativeQuery from "metabase-lib/v1/queries/NativeQuery";
@@ -66,7 +65,7 @@ import {
*/
export type NativeQueryEditorCoreProps = Omit<
CodeMirrorEditorProps,
- "query"
+ "query" | "onAcceptProposed"
> & {
availableHeight?: number;
canAutoOpenDataReference?: boolean;
@@ -256,6 +255,15 @@ export const NativeQueryEditorRoot = forwardRef<
onBlur?.();
}, [handleChange, onBlur]);
+ const handleAcceptProposed = useCallback(() => {
+ const proposedQuery = proposedQuestion?.legacyNativeQuery();
+ if (proposedQuery) {
+ handleChange(proposedQuery.queryText());
+ handleChange.flush();
+ onAcceptProposed?.(proposedQuery.datasetQuery());
+ }
+ }, [proposedQuestion, handleChange, onAcceptProposed]);
+
const handleSnippetUpdate = useCallback(
(newSnippet: NativeQuerySnippet, oldSnippet: NativeQuerySnippet) => {
// get the query instance with the latest Metadata that has the updated snippet
@@ -398,6 +406,10 @@ export const NativeQueryEditorRoot = forwardRef<
onCursorMoveOverCardTag={openDataReferenceAtQuestion}
onRightClickSelection={handleRightClickSelection}
onFormatQuery={handleFormatQuery}
+ onAcceptProposed={
+ onAcceptProposed ? handleAcceptProposed : undefined
+ }
+ onRejectProposed={onRejectProposed}
/>
<Stack
@@ -406,42 +418,6 @@ export const NativeQueryEditorRoot = forwardRef<
justify="flex-end"
p="lg"
>
- {proposedQuestion && onRejectProposed && onAcceptProposed && (
- <>
- <Tooltip
- label={t`Accept proposed changes`}
- position="top"
- >
- <Button
- data-testid="accept-proposed-changes-button"
- variant="light"
- color="positive"
- onClick={() => {
- const proposedQuery =
- proposedQuestion.legacyNativeQuery();
- if (proposedQuery) {
- handleChange(proposedQuery.queryText());
- handleChange.flush();
- onAcceptProposed(proposedQuery.datasetQuery());
- }
- }}
- leftSection={<Icon name="check" />}
- />
- </Tooltip>
- <Tooltip
- label={t`Reject proposed changes`}
- position="top"
- >
- <Button
- data-testid="reject-proposed-changes-button"
- variant="light"
- color="negative"
- onClick={onRejectProposed}
- leftSection={<Icon name="close" />}
- />
- </Tooltip>
- </>
- )}
<Flex gap="sm">{bodySlots}</Flex>
</Stack>
</Flex>
diff --git a/frontend/src/metabase/utils/browser.ts b/frontend/src/metabase/utils/browser.ts
index cd6120fbe3d..6018543b3d5 100644
--- a/frontend/src/metabase/utils/browser.ts
+++ b/frontend/src/metabase/utils/browser.ts
@@ -66,6 +66,10 @@ export function isMac() {
return Boolean(platform.match(/^Mac/));
}
+export function isWindows() {
+ return /Win/.test(navigator.platform);
+}
+
export const isTouchDevice = () => {
if (typeof window === "undefined") {
return false;