Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
fix(plan): keep the reading position when editing a statement (#21547)
boojack80524fc54601
diff --git a/frontend/src/components/monaco/index.ts b/frontend/src/components/monaco/index.tsindex 3c7f6fd930..684a446b36 100644--- a/frontend/src/components/monaco/index.ts+++ b/frontend/src/components/monaco/index.ts@@ -6,3 +6,4 @@ export * from "./ReadonlyDiffMonaco";export * from "./types";export * from "./utils";export * from "./MonacoViewZone";+export * from "./viewAnchor";diff --git a/frontend/src/components/monaco/viewAnchor.test.ts b/frontend/src/components/monaco/viewAnchor.test.tsnew file mode 100644index 0000000000..f219a54ca5--- /dev/null+++ b/frontend/src/components/monaco/viewAnchor.test.ts@@ -0,0 +1,120 @@+// @vitest-environment node+import { describe, expect, test, vi } from "vitest";+import {+ captureEditorViewAnchor,+ focusEditorAtAnchor,+ lineViewAnchor,+} from "./viewAnchor";++const readerAt = ({+ visibleRanges,+ cursorLine,+}: {+ visibleRanges: { startLineNumber: number; endLineNumber: number }[];+ cursorLine: number;+}) =>+ ({+ getModel: () => ({}),+ getVisibleRanges: () => visibleRanges,+ getSelection: () => ({+ selectionStartLineNumber: cursorLine,+ selectionStartColumn: 1,+ positionLineNumber: cursorLine,+ positionColumn: 4,+ }),+ }) as unknown as Parameters<typeof captureEditorViewAnchor>[0];++const editorWithLines = (lineCount: number) => ({+ focus: vi.fn(),+ getModel: () =>+ ({ getLineCount: () => lineCount }) as unknown as ReturnType<+ Parameters<typeof focusEditorAtAnchor>[0]["getModel"]+ >,+ getTopForLineNumber: (lineNumber: number) => lineNumber * 20,+ revealLineInCenter: vi.fn(),+ setScrollTop: vi.fn(),+ setSelection: vi.fn(),+});++describe("captureEditorViewAnchor", () => {+ test("keeps the top visible line and a cursor the reader can see", () => {+ expect(+ captureEditorViewAnchor(+ readerAt({+ visibleRanges: [+ { startLineNumber: 750, endLineNumber: 766 },+ { startLineNumber: 767, endLineNumber: 780 },+ ],+ cursorLine: 770,+ })+ )+ ).toEqual({+ selection: {+ selectionStartLineNumber: 770,+ selectionStartColumn: 1,+ positionLineNumber: 770,+ positionColumn: 4,+ },+ revealLineNumber: 750,+ revealAt: "top",+ });+ });++ test("moves a cursor scrolled out of view to the top visible line", () => {+ expect(+ captureEditorViewAnchor(+ readerAt({+ visibleRanges: [{ startLineNumber: 757, endLineNumber: 780 }],+ cursorLine: 1,+ })+ )?.selection+ ).toEqual({+ selectionStartLineNumber: 757,+ selectionStartColumn: 1,+ positionLineNumber: 757,+ positionColumn: 1,+ });+ });++ test("returns nothing for an editor without a model", () => {+ expect(+ captureEditorViewAnchor({+ getModel: () => null,+ getVisibleRanges: () => [],+ getSelection: () => null,+ })+ ).toBeUndefined();+ });+});++describe("focusEditorAtAnchor", () => {+ test("scrolls a top anchor's line to the top of the viewport", () => {+ const editor = editorWithLines(800);+ focusEditorAtAnchor(editor, {+ selection: {+ selectionStartLineNumber: 766,+ selectionStartColumn: 1,+ positionLineNumber: 766,+ positionColumn: 8,+ },+ revealLineNumber: 757,+ revealAt: "top",+ });+ expect(editor.setScrollTop).toHaveBeenCalledWith(757 * 20);+ expect(editor.revealLineInCenter).not.toHaveBeenCalled();+ expect(editor.focus).toHaveBeenCalled();+ });++ test("centers a line anchor and clamps it to shortened text", () => {+ const editor = editorWithLines(3);+ focusEditorAtAnchor(editor, lineViewAnchor(99));+ expect(editor.setSelection).toHaveBeenCalledWith({+ selectionStartLineNumber: 3,+ selectionStartColumn: 1,+ positionLineNumber: 3,+ positionColumn: 1,+ });+ expect(editor.revealLineInCenter).toHaveBeenCalledWith(3);+ expect(editor.setScrollTop).not.toHaveBeenCalled();+ });+});diff --git a/frontend/src/components/monaco/viewAnchor.ts b/frontend/src/components/monaco/viewAnchor.tsnew file mode 100644index 0000000000..f612893793--- /dev/null+++ b/frontend/src/components/monaco/viewAnchor.ts@@ -0,0 +1,91 @@+import type * as monaco from "monaco-editor";+import type { IStandaloneCodeEditor } from "./types";++// A place to land in an editor, recorded by line rather than scroll pixels so+// it carries over to an editor showing the same text with different view+// zones, such as the statement editor without its inline threads.+export type EditorViewAnchor = {+ selection: monaco.ISelection;+ revealLineNumber: number;+ revealAt: "top" | "center";+};++const collapsedSelectionAt = (lineNumber: number): monaco.ISelection => ({+ selectionStartLineNumber: lineNumber,+ selectionStartColumn: 1,+ positionLineNumber: lineNumber,+ positionColumn: 1,+});++// Keeps the reader's place: the top visible line stays on top.+export const captureEditorViewAnchor = (+ editor: Pick<+ IStandaloneCodeEditor,+ "getModel" | "getSelection" | "getVisibleRanges"+ >+): EditorViewAnchor | undefined => {+ if (!editor.getModel()) return undefined;+ const visibleRanges = editor.getVisibleRanges();+ const topLineNumber = visibleRanges[0]?.startLineNumber ?? 1;+ const selection = editor.getSelection();+ // A reader who never placed a cursor still has one at the top of the+ // document; only keep a cursor they can see.+ const selectionIsVisible =+ selection !== null &&+ visibleRanges.some(+ (range) =>+ range.startLineNumber <= selection.positionLineNumber &&+ selection.positionLineNumber <= range.endLineNumber+ );+ return {+ selection: selectionIsVisible+ ? {+ selectionStartLineNumber: selection.selectionStartLineNumber,+ selectionStartColumn: selection.selectionStartColumn,+ positionLineNumber: selection.positionLineNumber,+ positionColumn: selection.positionColumn,+ }+ : collapsedSelectionAt(topLineNumber),+ revealLineNumber: topLineNumber,+ revealAt: "top",+ };+};++// Jumps to a line from elsewhere on the page, centered for context.+export const lineViewAnchor = (lineNumber: number): EditorViewAnchor => ({+ selection: collapsedSelectionAt(lineNumber),+ revealLineNumber: lineNumber,+ revealAt: "center",+});++// Lines past the end land on the last line: the anchor may come from text+// that has since been edited shorter.+export const focusEditorAtAnchor = (+ editor: Pick<+ IStandaloneCodeEditor,+ | "focus"+ | "getModel"+ | "getTopForLineNumber"+ | "revealLineInCenter"+ | "setScrollTop"+ | "setSelection"+ >,+ anchor: EditorViewAnchor+) => {+ const lineCount = editor.getModel()?.getLineCount();+ if (!lineCount) return;+ const clampLine = (lineNumber: number) => Math.min(lineNumber, lineCount);+ const { selection } = anchor;+ editor.setSelection({+ ...selection,+ selectionStartLineNumber: clampLine(selection.selectionStartLineNumber),+ positionLineNumber: clampLine(selection.positionLineNumber),+ });+ const revealLineNumber = clampLine(anchor.revealLineNumber);+ if (anchor.revealAt === "top") {+ editor.setScrollTop(editor.getTopForLineNumber(revealLineNumber));+ } else {+ editor.revealLineInCenter(revealLineNumber);+ }+ editor.focus();+};diff --git a/frontend/src/routes/project/issue-detail/components/IssueDetailStatementSection.tsx b/frontend/src/routes/project/issue-detail/components/IssueDetailStatementSection.tsxindex e73a42da0e..8e6ceddae6 100644--- a/frontend/src/routes/project/issue-detail/components/IssueDetailStatementSection.tsx+++ b/frontend/src/routes/project/issue-detail/components/IssueDetailStatementSection.tsx@@ -3,7 +3,14 @@ import { Loader2, Upload } from "lucide-react";import { type ChangeEvent, useEffect, useMemo, useRef, useState } from "react";import { useTranslation } from "react-i18next";import { planServiceClientConnect, sheetServiceClientConnect } from "@/api";-import { MonacoEditor, ReadonlyMonaco } from "@/components/monaco";+import {+ captureEditorViewAnchor,+ type EditorViewAnchor,+ focusEditorAtAnchor,+ type IStandaloneCodeEditor,+ MonacoEditor,+ ReadonlyMonaco,+} from "@/components/monaco";import { ReleaseInfoCard } from "@/components/release/ReleaseInfoCard";import { Alert } from "@/components/ui/alert";import { Button } from "@/components/ui/button";@@ -86,6 +93,10 @@ export function IssueDetailStatementSection({);const [draftStatement, setDraftStatement] = useState("");const inputRef = useRef<HTMLInputElement>(null);+ const readonlyEditorRef = useRef<IStandaloneCodeEditor | undefined>(+ undefined+ );+ const editAnchorRef = useRef<EditorViewAnchor | undefined>(undefined);const editingScope = useMemo(() => `statement:${spec.id}`, [spec.id]);const targetDatabaseName = useMemo(() => {@@ -124,6 +135,10 @@ export function IssueDetailStatementSection({}}, [isEditing, statement]);+ useEffect(() => {+ if (!isEditing) editAnchorRef.current = undefined;+ }, [isEditing]);+useEffect(() => {setEditing(editingScope, isEditing);return () => {@@ -228,6 +243,9 @@ export function IssueDetailStatementSection({hasChanges;const handleBeginEdit = () => {+ editAnchorRef.current =+ readonlyEditorRef.current &&+ captureEditorViewAnchor(readonlyEditorRef.current);setDraftStatement(statement);setIsEditing(true);};@@ -486,12 +504,20 @@ export function IssueDetailStatementSection({content={draftStatement}language={language}onChange={setDraftStatement}+ onReady={(_monaco, editor) => {+ const anchor = editAnchorRef.current;+ editAnchorRef.current = undefined;+ if (anchor) focusEditorAtAnchor(editor, anchor);+ }}/>) : (<ReadonlyMonacoclassName="relative h-auto max-h-[600px] min-h-[120px]"content={statement}language={language}+ onReady={(_monaco, editor) => {+ readonlyEditorRef.current = editor;+ }}/>)}</div>diff --git a/frontend/src/routes/project/plan-detail/components/PlanDetailStatementSection.test.tsx b/frontend/src/routes/project/plan-detail/components/PlanDetailStatementSection.test.tsxindex 63cd9120bc..7f28ebb703 100644--- a/frontend/src/routes/project/plan-detail/components/PlanDetailStatementSection.test.tsx+++ b/frontend/src/routes/project/plan-detail/components/PlanDetailStatementSection.test.tsx@@ -16,17 +16,21 @@ const mocks = vi.hoisted(() => ({| { commentName: string; specId: string; lineNumber: number; nonce: number }| undefined,clearThreadFocus: vi.fn(),- setPosition: vi.fn(),revealLineInCenter: vi.fn(),focus: vi.fn(),scrollIntoView: vi.fn(),+ setSelection: vi.fn(),+ setScrollTop: vi.fn(),}));vi.mock("react-i18next", () => ({initReactI18next: { type: "3rdParty", init: () => {} },useTranslation: () => ({ t: (key: string) => key }),}));-vi.mock("@/components/monaco", () => ({+vi.mock("@/components/monaco", async () => ({+ ...(await vi.importActual<typeof import("@/components/monaco/viewAnchor")>(+ "@/components/monaco/viewAnchor"+ )),MonacoEditor: ({onChange,onReady,@@ -39,10 +43,12 @@ vi.mock("@/components/monaco", () => ({onClick={() =>onReady({}, {getModel: () => ({ getLineCount: () => 3 }),- setPosition: mocks.setPosition,revealLineInCenter: mocks.revealLineInCenter,focus: mocks.focus,getDomNode: () => ({ scrollIntoView: mocks.scrollIntoView }),+ setSelection: mocks.setSelection,+ setScrollTop: mocks.setScrollTop,+ getTopForLineNumber: (lineNumber: number) => lineNumber * 20,})}>@@ -54,8 +60,32 @@ vi.mock("@/components/monaco", () => ({<button onClick={() => onChange("SELECT 2;")}>Make small draft</button></>),- ReadonlyMonaco: ({ content }: { content: string }) => (- <div data-testid="statement">{content.slice(0, 24)}</div>+ ReadonlyMonaco: ({+ content,+ onReady,+ }: {+ content: string;+ onReady?: (monaco: unknown, editor: unknown) => void;+ }) => (+ <>+ <div data-testid="statement">{content.slice(0, 24)}</div>+ <button+ onClick={() =>+ onReady?.({}, {+ getModel: () => ({}),+ getVisibleRanges: () => [{ startLineNumber: 2, endLineNumber: 3 }],+ getSelection: () => ({+ selectionStartLineNumber: 3,+ selectionStartColumn: 2,+ positionLineNumber: 3,+ positionColumn: 5,+ }),+ })+ }+ >+ Readonly editor ready+ </button>+ </>),}));vi.mock("@/stores", () => ({ pushNotification: vi.fn() }));@@ -141,7 +171,7 @@ test("shows the large-sheet warning as soon as the saved sheet changes", async (expect(getByTestId("statement").textContent).toContain("SELECT 2;");});-test("shows a draft-specific warning before saving and removes it below the limit", () => {+const renderEditableSpec = (statement: string) => {const sheetName = `projects/p/sheets/${"c".repeat(64)}`;const spec = create(Plan_SpecSchema, {id: "spec",@@ -150,7 +180,7 @@ test("shows a draft-specific warning before saving and removes it below the limivalue: create(Plan_ChangeDatabaseConfigSchema, { sheet: sheetName }),},});- const content = new TextEncoder().encode("SELECT 1;");+ const content = new TextEncoder().encode(statement);mocks.sheets.set(sheetName,create(SheetSchema, { name: sheetName, content, contentSize: BigInt(content.length) })@@ -163,10 +193,17 @@ test("shows a draft-specific warning before saving and removes it below the limireadonly: false,setEditing: vi.fn(),};+ const view = render(<PlanDetailStatementSection spec={spec} />);+ return {+ ...view,+ rerender: () => view.rerender(<PlanDetailStatementSection spec={spec} />),+ };+};- const { getByText, queryByText } = render(- <PlanDetailStatementSection spec={spec} />- );+const THREE_LINES = "SELECT 1;\nSELECT 2;\nSELECT 3;";++test("shows a draft-specific warning before saving and removes it below the limit", () => {+ const { getByText, queryByText } = renderEditableSpec("SELECT 1;");fireEvent.click(getByText("common.edit"));fireEvent.click(getByText("Make large draft"));expect(getByText("issue.statement-exceeds-preview-limit")).toBeTruthy();@@ -177,31 +214,7 @@ test("shows a draft-specific warning before saving and removes it below the limi});test("reveals an Activity anchor after the edit editor is ready", () => {- const sheetName = `projects/p/sheets/${"c".repeat(64)}`;- const spec = create(Plan_SpecSchema, {- id: "spec",- config: {- case: "changeDatabaseConfig",- value: create(Plan_ChangeDatabaseConfigSchema, { sheet: sheetName }),- },- });- const content = new TextEncoder().encode("SELECT 1;\nSELECT 2;\nSELECT 3;");- mocks.sheets.set(- sheetName,- create(SheetSchema, { name: sheetName, content, contentSize: BigInt(content.length) })- );- mocks.page = {- currentUser: { name: "users/test" },- isCreating: false,- plan: create(PlanSchema, { creator: "users/test", specs: [spec] }),- project: { name: "projects/p" },- readonly: false,- setEditing: vi.fn(),- };-- const { getByText, rerender } = render(- <PlanDetailStatementSection spec={spec} />- );+ const { getByText, rerender } = renderEditableSpec(THREE_LINES);fireEvent.click(getByText("common.edit"));mocks.threadFocus = {commentName: "comments/1",@@ -209,11 +222,16 @@ test("reveals an Activity anchor after the edit editor is ready", () => {lineNumber: 3,nonce: 7,};- rerender(<PlanDetailStatementSection spec={spec} />);+ rerender();expect(mocks.revealLineInCenter).not.toHaveBeenCalled();fireEvent.click(getByText("Editor ready"));- expect(mocks.setPosition).toHaveBeenCalledWith({ lineNumber: 3, column: 1 });+ expect(mocks.setSelection).toHaveBeenCalledWith({+ selectionStartLineNumber: 3,+ selectionStartColumn: 1,+ positionLineNumber: 3,+ positionColumn: 1,+ });expect(mocks.revealLineInCenter).toHaveBeenCalledWith(3);expect(mocks.focus).toHaveBeenCalled();expect(mocks.scrollIntoView).toHaveBeenCalledWith({ block: "nearest" });@@ -225,7 +243,44 @@ test("reveals an Activity anchor after the edit editor is ready", () => {lineNumber: 99,nonce: 8,};- rerender(<PlanDetailStatementSection spec={spec} />);+ rerender();expect(mocks.revealLineInCenter).toHaveBeenLastCalledWith(3);expect(mocks.clearThreadFocus).toHaveBeenCalledWith(8);});++test("keeps the reading position and cursor when entering edit mode", () => {+ const { getByText } = renderEditableSpec(THREE_LINES);+ fireEvent.click(getByText("Readonly editor ready"));+ fireEvent.click(getByText("common.edit"));+ fireEvent.click(getByText("Editor ready"));++ expect(mocks.setSelection).toHaveBeenCalledWith({+ selectionStartLineNumber: 3,+ selectionStartColumn: 2,+ positionLineNumber: 3,+ positionColumn: 5,+ });+ expect(mocks.setScrollTop).toHaveBeenCalledWith(40);+ expect(mocks.revealLineInCenter).not.toHaveBeenCalled();+ expect(mocks.focus).toHaveBeenCalled();+ expect(mocks.scrollIntoView).not.toHaveBeenCalled();+});++test("an Activity anchor wins over the reading position captured by Edit", () => {+ const { getByText, rerender } = renderEditableSpec(THREE_LINES);+ fireEvent.click(getByText("Readonly editor ready"));+ fireEvent.click(getByText("common.edit"));+ mocks.threadFocus = {+ commentName: "comments/1",+ specId: "spec",+ lineNumber: 1,+ nonce: 3,+ };+ rerender();+ fireEvent.click(getByText("Editor ready"));++ expect(mocks.setSelection).toHaveBeenCalledTimes(1);+ expect(mocks.revealLineInCenter).toHaveBeenCalledWith(1);+ expect(mocks.setScrollTop).not.toHaveBeenCalled();+ expect(mocks.clearThreadFocus).toHaveBeenCalledWith(3);+});diff --git a/frontend/src/routes/project/plan-detail/components/PlanDetailStatementSection.tsx b/frontend/src/routes/project/plan-detail/components/PlanDetailStatementSection.tsxindex 66d2b0ecbd..5d6601f610 100644--- a/frontend/src/routes/project/plan-detail/components/PlanDetailStatementSection.tsx+++ b/frontend/src/routes/project/plan-detail/components/PlanDetailStatementSection.tsx@@ -8,7 +8,11 @@ import {sheetServiceClientConnect,} from "@/api";import {+ captureEditorViewAnchor,+ type EditorViewAnchor,+ focusEditorAtAnchor,type IStandaloneCodeEditor,+ lineViewAnchor,MonacoEditor,type MonacoModule,ReadonlyMonaco,@@ -136,6 +140,7 @@ export function PlanDetailStatementSection({monaco: MonacoModule;}>();const [editingEditor, setEditingEditor] = useState<IStandaloneCodeEditor>();+ const editAnchorRef = useRef<EditorViewAnchor | undefined>(undefined);const threadFocus = usePlanDetailStore((state) => state.threadFocus);const clearThreadFocus = usePlanDetailStore((state) => state.clearThreadFocus@@ -144,26 +149,28 @@ export function PlanDetailStatementSection({if (!showsReadonlyEditor) setReadonlyEditor(undefined);}, [showsReadonlyEditor]);useEffect(() => {- if (!isEditing) setEditingEditor(undefined);+ if (isEditing) return;+ setEditingEditor(undefined);+ editAnchorRef.current = undefined;}, [isEditing]);+ // The edit editor lands on a pending Activity anchor, which may arrive+ // before or after it mounts, or else on the place captured by Edit.useEffect(() => {- if (- !isEditing ||- !editingEditor ||- !threadFocus ||- threadFocus.specId !== spec.id ||- !threadFocus.lineNumber- )- return;- const line = Math.min(- threadFocus.lineNumber,- editingEditor.getModel()?.getLineCount() ?? threadFocus.lineNumber- );- editingEditor.setPosition({ lineNumber: line, column: 1 });- editingEditor.revealLineInCenter(line);- editingEditor.focus();- editingEditor.getDomNode()?.scrollIntoView({ block: "nearest" });- clearThreadFocus(threadFocus.nonce);+ if (!isEditing || !editingEditor) return;+ const activityLine =+ threadFocus?.specId === spec.id ? threadFocus.lineNumber : undefined;+ const anchor = activityLine+ ? lineViewAnchor(activityLine)+ : editAnchorRef.current;+ editAnchorRef.current = undefined;+ if (!anchor) return;+ focusEditorAtAnchor(editingEditor, anchor);+ if (activityLine && threadFocus) {+ // Activity lives in another phase section, so the editor may be off+ // screen.+ editingEditor.getDomNode()?.scrollIntoView({ block: "nearest" });+ clearThreadFocus(threadFocus.nonce);+ }}, [clearThreadFocus, editingEditor, isEditing, spec.id, threadFocus]);const editingScope = useMemo(() => `statement:${spec.id}`, [spec.id]);@@ -384,6 +391,12 @@ export function PlanDetailStatementSection({setIsEditing(true);};+ const handleBeginEdit = () => {+ editAnchorRef.current =+ readonlyEditor && captureEditorViewAnchor(readonlyEditor.editor);+ setIsEditing(true);+ };+const handleSchemaEditorInsert = (nextStatement: string) => {if (page.isCreating) {updateLocalStatement(nextStatement);@@ -589,11 +602,7 @@ export function PlanDetailStatementSection({</>)}{!isEditing && canEdit && (- <Button- onClick={() => setIsEditing(true)}- size="xs"- appearance="outline"- >+ <Button onClick={handleBeginEdit} size="xs" appearance="outline"><Pencil className="h-3.5 w-3.5" />{t("common.edit")}</Button>