fix(editor): split query editor into focused components
This commit is contained in:
63 files changed
+11857
-7011
No files matched your search
Vendored
+397
@@ -0,0 +1,397 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import { createApp, h, nextTick, reactive, shallowRef } from "vue";
|
||||
import { createPinia, setActivePinia } from "pinia";
|
||||
import { createI18n } from "vue-i18n";
|
||||
import { EditorSelection } from "@codemirror/state";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { toggleLineComment, undo } from "@codemirror/commands";
|
||||
import { closeCompletion, completionStatus, currentCompletions, selectedCompletionIndex, startCompletion } from "@codemirror/autocomplete";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import QueryEditor from "../QueryEditor.vue";
|
||||
import { useSettingsStore } from "@/stores/settingsStore";
|
||||
import { useConnectionStore } from "@/stores/connectionStore";
|
||||
import { createTableReferenceDropEvent, createTableReferenceHoverEvent, setActiveTableReferencePayload, type QueryEditorTableReferencePayload } from "@/lib/editor/queryEditorTableDrop";
|
||||
import type { QueryEditorProps } from "../queryEditorTypes";
|
||||
import { focusedQueryEditorView, queryEditorInsertContext } from "@/lib/editor/focusedQueryEditorView";
|
||||
|
||||
vi.mock("@/lib/common/clipboard", () => ({
|
||||
copyToClipboard: vi.fn().mockResolvedValue(undefined),
|
||||
readTextFromClipboard: vi.fn().mockResolvedValue("alice\nbob"),
|
||||
}));
|
||||
|
||||
const cleanups: Array<() => void> = [];
|
||||
|
||||
afterEach(() => {
|
||||
for (const cleanup of cleanups.splice(0).reverse()) cleanup();
|
||||
setActiveTableReferencePayload(null);
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
async function mountEditor(overrides: Partial<QueryEditorProps> = {}) {
|
||||
const pinia = createPinia();
|
||||
setActivePinia(pinia);
|
||||
const settingsStore = useSettingsStore();
|
||||
const connectionStore = useConnectionStore();
|
||||
settingsStore.editorSettings.showExecutionTargetPicker = false;
|
||||
settingsStore.editorSettings.executeMode = "current";
|
||||
settingsStore.editorSettings.executeAllOnBlankLine = false;
|
||||
const props = reactive<QueryEditorProps>({ modelValue: "SELECT 1;\nSELECT 2;", tabId: "split-a", databaseType: "mysql", dialect: "mysql", autoFocus: false, ...overrides });
|
||||
const editor = shallowRef<InstanceType<typeof QueryEditor>>();
|
||||
const onExecute = vi.fn();
|
||||
const onExecuteInNewResultTab = vi.fn();
|
||||
const onClickTable = vi.fn();
|
||||
const host = document.createElement("div");
|
||||
document.body.append(host);
|
||||
const app = createApp({
|
||||
render: () =>
|
||||
h(QueryEditor, {
|
||||
...props,
|
||||
ref: editor,
|
||||
onExecute,
|
||||
onExecuteInNewResultTab,
|
||||
onClickTable,
|
||||
"onUpdate:modelValue": (value: string) => {
|
||||
props.modelValue = value;
|
||||
},
|
||||
}),
|
||||
});
|
||||
app.use(pinia);
|
||||
app.use(createI18n({ legacy: false, locale: "en", messages: { en: {} }, missingWarn: false, fallbackWarn: false }));
|
||||
app.mount(host);
|
||||
let mounted = true;
|
||||
const unmount = () => {
|
||||
if (!mounted) return;
|
||||
mounted = false;
|
||||
app.unmount();
|
||||
host.remove();
|
||||
};
|
||||
cleanups.push(unmount);
|
||||
await vi.waitFor(() => expect(host.querySelector(".cm-editor")).not.toBeNull(), { timeout: 5000 });
|
||||
const view = EditorView.findFromDOM(host.querySelector(".cm-editor") as HTMLElement)!;
|
||||
return { editor: editor.value!, props, view, host, settingsStore, connectionStore, onExecute, onExecuteInNewResultTab, onClickTable, unmount };
|
||||
}
|
||||
|
||||
function keydown(target: HTMLElement, key: string) {
|
||||
const event = new KeyboardEvent("keydown", { key, bubbles: true, cancelable: true });
|
||||
target.dispatchEvent(event);
|
||||
return event;
|
||||
}
|
||||
|
||||
describe("QueryEditor component split integration", () => {
|
||||
it("preserves upstream structure-peek focus and insertion context across updates and unmount", async () => {
|
||||
const { view, props, unmount } = await mountEditor({ connectionId: "peek-a", database: "demo", schema: "public" });
|
||||
expect(queryEditorInsertContext(view)).toEqual({ connectionId: "peek-a", database: "demo", schema: "public", databaseType: "mysql" });
|
||||
view.focus();
|
||||
await nextTick();
|
||||
const panel = document.createElement("div");
|
||||
panel.setAttribute("data-structure-peek-panel", "");
|
||||
document.body.append(panel);
|
||||
cleanups.push(() => panel.remove());
|
||||
await vi.waitFor(() => expect(focusedQueryEditorView(panel)).toBe(view));
|
||||
props.connectionId = "peek-b";
|
||||
props.database = "updated";
|
||||
props.schema = "reporting";
|
||||
await nextTick();
|
||||
expect(queryEditorInsertContext(view)).toEqual({ connectionId: "peek-b", database: "updated", schema: "reporting", databaseType: "mysql" });
|
||||
unmount();
|
||||
expect(queryEditorInsertContext(view)).toBeUndefined();
|
||||
expect(focusedQueryEditorView(panel)).toBeNull();
|
||||
});
|
||||
|
||||
it("preserves the public editor API and the direct CodeMirror host", async () => {
|
||||
const { editor, host, view } = await mountEditor();
|
||||
for (const method of [
|
||||
"openSearch",
|
||||
"openReplace",
|
||||
"scrollCursorIntoView",
|
||||
"beginExecutionViewportTracking",
|
||||
"acceptGutterExecutionViewport",
|
||||
"cancelGutterExecutionViewport",
|
||||
"shouldBlockExecutionShortcut",
|
||||
"requestExecute",
|
||||
"requestExecuteInNewResultTab",
|
||||
"requestPreviewChanges",
|
||||
"captureExecutionSnapshot",
|
||||
"pasteClipboardAsSqlInCondition",
|
||||
"focusStatementRange",
|
||||
"focusErrorPosition",
|
||||
"previewStatementRange",
|
||||
"refreshCompletionCache",
|
||||
]) {
|
||||
expect(typeof editor[method as keyof typeof editor], method).toBe("function");
|
||||
}
|
||||
expect(host.querySelector("[data-query-editor-root] > .cm-editor")).toBe(view.dom);
|
||||
expect(host.querySelectorAll(".cm-editor")).toHaveLength(1);
|
||||
expect(editor.openSearch()).toBe(true);
|
||||
await nextTick();
|
||||
expect(host.querySelector(".cm-editor")).toBe(view.dom);
|
||||
});
|
||||
|
||||
it.each(["current", "all"] as const)("keeps selection priority in %s mode and immutable toolbar snapshots", async (executeMode) => {
|
||||
const { editor, props, view, settingsStore, onExecute } = await mountEditor();
|
||||
settingsStore.editorSettings.executeMode = executeMode;
|
||||
view.dispatch({ selection: EditorSelection.range(10, 18) });
|
||||
const snapshot = editor.captureExecutionSnapshot();
|
||||
expect(snapshot).toEqual({ fullSql: props.modelValue, selectedSql: "SELECT 2", cursorPos: 18, selectionFrom: 10, selectionTo: 18 });
|
||||
expect(editor.requestExecute()).toBe(true);
|
||||
expect(onExecute).toHaveBeenLastCalledWith(snapshot);
|
||||
view.dispatch({ selection: { anchor: 0 } });
|
||||
expect(snapshot?.selectedSql).toBe("SELECT 2");
|
||||
expect(editor.captureExecutionSnapshot()).toBeUndefined();
|
||||
});
|
||||
|
||||
it.each(["current", "all"] as const)("keeps %s execution ranges without a manual selection", async (executeMode) => {
|
||||
const { editor, props, view, settingsStore, onExecute } = await mountEditor();
|
||||
settingsStore.editorSettings.executeMode = executeMode;
|
||||
view.dispatch({ selection: { anchor: 12 } });
|
||||
expect(editor.requestExecute({ bypassPicker: true })).toBe(true);
|
||||
const source = onExecute.mock.calls[0][0];
|
||||
expect(source.fullSql).toBe(props.modelValue);
|
||||
expect(source.cursorPos).toBe(12);
|
||||
expect(source.selectedSql).toBe(executeMode === "current" ? "SELECT 2" : props.modelValue);
|
||||
expect(source.selectionFrom).toBe(executeMode === "current" ? 10 : 0);
|
||||
expect(source.selectionTo).toBe(executeMode === "current" ? 18 : props.modelValue.length);
|
||||
});
|
||||
|
||||
it("keeps the new-result-tab shortcut independent of the optional picker", async () => {
|
||||
const { editor, host, settingsStore, onExecute, onExecuteInNewResultTab } = await mountEditor();
|
||||
settingsStore.editorSettings.showExecutionTargetPicker = true;
|
||||
expect(editor.requestExecuteInNewResultTab()).toBe(true);
|
||||
await nextTick();
|
||||
expect(host.querySelector('[role="listbox"]')).toBeNull();
|
||||
expect(onExecute).not.toHaveBeenCalled();
|
||||
expect(onExecuteInNewResultTab).toHaveBeenCalledTimes(1);
|
||||
expect(onExecuteInNewResultTab.mock.calls[0][0].selectedSql).toBe("SELECT 1");
|
||||
});
|
||||
|
||||
it("opens, navigates, cancels and confirms the execution picker without replacing the editor", async () => {
|
||||
const { editor, host, view, props, settingsStore, onExecute } = await mountEditor();
|
||||
settingsStore.editorSettings.showExecutionTargetPicker = true;
|
||||
vi.spyOn(view, "coordsAtPos").mockReturnValue({ left: 10, right: 12, top: 20, bottom: 40 });
|
||||
vi.spyOn(host.querySelector("[data-query-editor-root]")!, "getBoundingClientRect").mockReturnValue(new DOMRect(0, 0, 800, 600));
|
||||
expect(editor.requestExecute()).toBe(true);
|
||||
await nextTick();
|
||||
let picker = host.querySelector<HTMLElement>('[role="listbox"]')!;
|
||||
expect(picker).not.toBeNull();
|
||||
expect(picker.style.left).toBe("400px");
|
||||
expect(onExecute).not.toHaveBeenCalled();
|
||||
keydown(picker, "ArrowDown");
|
||||
await nextTick();
|
||||
expect(picker.querySelectorAll('[role="option"]')[1].getAttribute("aria-selected")).toBe("true");
|
||||
keydown(picker, "Escape");
|
||||
await nextTick();
|
||||
expect(host.querySelector('[role="listbox"]')).toBeNull();
|
||||
expect(onExecute).not.toHaveBeenCalled();
|
||||
expect(view.hasFocus).toBe(true);
|
||||
editor.requestExecute();
|
||||
await nextTick();
|
||||
picker = host.querySelector<HTMLElement>('[role="listbox"]')!;
|
||||
keydown(picker, "ArrowDown");
|
||||
await nextTick();
|
||||
keydown(picker, "Enter");
|
||||
await nextTick();
|
||||
expect(onExecute).toHaveBeenCalledTimes(1);
|
||||
expect(onExecute.mock.calls[0][0].selectedSql).toBe(props.modelValue);
|
||||
expect(host.querySelector('[role="listbox"]')).toBeNull();
|
||||
expect(host.querySelector(".cm-editor")).toBe(view.dom);
|
||||
});
|
||||
|
||||
it.each(["redis", "mongodb", "elasticsearch"] as const)("preserves the non-SQL %s execution path", async (databaseType) => {
|
||||
const { editor, props, host, settingsStore, onExecute } = await mountEditor({ databaseType, modelValue: databaseType === "redis" ? "GET key" : "{}" });
|
||||
settingsStore.editorSettings.showExecutionTargetPicker = true;
|
||||
expect(editor.requestExecute()).toBe(true);
|
||||
await nextTick();
|
||||
expect(onExecute).toHaveBeenCalledWith({ fullSql: props.modelValue, selectedSql: databaseType === "mongodb" ? "" : props.modelValue, cursorPos: 0, selectionFrom: 0, selectionTo: databaseType === "mongodb" ? 0 : props.modelValue.length });
|
||||
expect(host.querySelector('[role="listbox"]')).toBeNull();
|
||||
expect(await editor.pasteClipboardAsSqlInCondition()).toBe(false);
|
||||
});
|
||||
|
||||
it.each([false, true])("preserves the blank-line execution fallback setting (%s)", async (fallback) => {
|
||||
const { editor, view, props, settingsStore, onExecute } = await mountEditor({ modelValue: "SELECT 1;\n\nSELECT 2;" });
|
||||
settingsStore.editorSettings.executeAllOnBlankLine = fallback;
|
||||
view.dispatch({ selection: { anchor: 10 } });
|
||||
expect(editor.requestExecute()).toBe(true);
|
||||
expect(onExecute).toHaveBeenCalledTimes(fallback ? 1 : 0);
|
||||
if (fallback) expect(onExecute.mock.calls[0][0].selectedSql).toBe(props.modelValue);
|
||||
});
|
||||
|
||||
it("reads current read-only props for extracted clipboard actions and keeps undo history", async () => {
|
||||
const { editor, props, view } = await mountEditor({ modelValue: "" });
|
||||
expect(await editor.pasteClipboardAsSqlInCondition()).toBe(true);
|
||||
expect(view.state.doc.toString()).toContain("'alice'");
|
||||
expect(view.state.doc.toString()).toContain("'bob'");
|
||||
expect(undo(view)).toBe(true);
|
||||
expect(view.state.doc.toString()).toBe("");
|
||||
props.readOnly = true;
|
||||
await nextTick();
|
||||
expect(await editor.pasteClipboardAsSqlInCondition()).toBe(false);
|
||||
expect(view.state.doc.toString()).toBe("");
|
||||
});
|
||||
|
||||
it("preserves per-tab undo isolation, external model updates and the editor instance", async () => {
|
||||
const { editor, props, view, host } = await mountEditor({ modelValue: "SELECT 1;" });
|
||||
view.dispatch({ changes: { from: 7, to: 8, insert: "10" }, userEvent: "input" });
|
||||
await nextTick();
|
||||
props.tabId = "split-b";
|
||||
props.modelValue = "SELECT 2;";
|
||||
await nextTick();
|
||||
expect(view.state.doc.toString()).toBe("SELECT 2;");
|
||||
expect(undo(view)).toBe(false);
|
||||
props.tabId = "split-a";
|
||||
props.modelValue = "SELECT 10;";
|
||||
await nextTick();
|
||||
expect(undo(view)).toBe(true);
|
||||
expect(view.state.doc.toString()).toBe("SELECT 1;");
|
||||
props.modelValue = "SELECT 3;";
|
||||
await nextTick();
|
||||
expect(view.state.doc.toString()).toBe("SELECT 3;");
|
||||
expect(editor.captureExecutionSnapshot()).toBeUndefined();
|
||||
expect(host.querySelector(".cm-editor")).toBe(view.dom);
|
||||
});
|
||||
|
||||
it("connects manual completion to the provider without preselecting a candidate", async () => {
|
||||
const { view, settingsStore } = await mountEditor({ modelValue: "SEL", initialSelection: { anchor: 3, head: 3 }, connectionId: "completion-test" });
|
||||
settingsStore.editorSettings.completionTriggerMode = "manual";
|
||||
settingsStore.editorSettings.selectFirstCompletionOnOpen = false;
|
||||
await nextTick();
|
||||
expect(startCompletion(view)).toBe(true);
|
||||
await vi.waitFor(() => expect(completionStatus(view.state)).toBe("active"));
|
||||
expect(currentCompletions(view.state).map((option) => option.label)).toContain("SELECT");
|
||||
expect(selectedCompletionIndex(view.state)).toBeNull();
|
||||
expect(view.state.doc.toString()).toBe("SEL");
|
||||
expect(closeCompletion(view)).toBe(true);
|
||||
});
|
||||
|
||||
it("reconfigures language and wrapping extensions without replacing the view", async () => {
|
||||
const { view, props, host } = await mountEditor({ modelValue: "SELECT 1" });
|
||||
expect(toggleLineComment(view)).toBe(true);
|
||||
expect(view.state.doc.toString()).toBe("-- SELECT 1");
|
||||
props.databaseType = "mongodb";
|
||||
props.modelValue = "db.users.find({})";
|
||||
await nextTick();
|
||||
expect(toggleLineComment(view)).toBe(true);
|
||||
expect(view.state.doc.toString()).toBe("// db.users.find({})");
|
||||
props.forceWordWrap = true;
|
||||
await nextTick();
|
||||
expect(view.contentDOM.classList.contains("cm-lineWrapping")).toBe(true);
|
||||
props.forceWordWrap = false;
|
||||
await nextTick();
|
||||
expect(view.contentDOM.classList.contains("cm-lineWrapping")).toBe(false);
|
||||
expect(host.querySelector(".cm-editor")).toBe(view.dom);
|
||||
});
|
||||
|
||||
it("keeps result-source decorations connected to public navigation methods", async () => {
|
||||
const { view, host, editor } = await mountEditor();
|
||||
editor.previewStatementRange({ from: 10, to: 19 });
|
||||
expect(view.state.selection.main.anchor).toBe(10);
|
||||
expect(host.querySelector(".cm-db-result-source-highlight")?.textContent).toBe("SELECT 2;");
|
||||
editor.previewStatementRange(null);
|
||||
expect(host.querySelector(".cm-db-result-source-highlight")).toBeNull();
|
||||
expect(view.state.doc.toString()).toBe("SELECT 1;\nSELECT 2;");
|
||||
});
|
||||
|
||||
it("isolates extension reconfiguration and disposal between editor instances", async () => {
|
||||
const first = await mountEditor({ modelValue: "SELECT 1;", tabId: "independent-a" });
|
||||
const second = await mountEditor({ modelValue: "SELECT 2;", tabId: "independent-b" });
|
||||
first.props.forceWordWrap = true;
|
||||
await nextTick();
|
||||
expect(first.view.contentDOM.classList.contains("cm-lineWrapping")).toBe(true);
|
||||
expect(second.view.contentDOM.classList.contains("cm-lineWrapping")).toBe(false);
|
||||
first.unmount();
|
||||
second.view.dispatch({ changes: { from: 7, to: 8, insert: "3" } });
|
||||
expect(second.view.state.doc.toString()).toBe("SELECT 3;");
|
||||
expect(second.host.querySelectorAll(".cm-editor")).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("selects the CTE definition and renders its source range before focusing", async () => {
|
||||
const sql = "WITH picked AS (SELECT id FROM users) SELECT id FROM picked";
|
||||
const { view, host, connectionStore, onClickTable } = await mountEditor({ modelValue: sql, connectionId: "navigation-test", database: "demo", databaseType: "postgres", dialect: "postgres" });
|
||||
const originalFocus = view.focus.bind(view);
|
||||
let navigationSnapshot: { selection: string; highlightedSource: string | null | undefined } | undefined;
|
||||
const focus = vi.spyOn(view, "focus").mockImplementation(() => {
|
||||
navigationSnapshot = {
|
||||
selection: view.state.sliceDoc(view.state.selection.main.from, view.state.selection.main.to),
|
||||
highlightedSource: host.querySelector(".cm-db-result-source-highlight")?.textContent,
|
||||
};
|
||||
originalFocus();
|
||||
});
|
||||
vi.spyOn(view, "posAtCoords").mockReturnValue(sql.lastIndexOf("picked") + 2);
|
||||
const lookupTables = vi.spyOn(connectionStore, "lookupLocalCompletionTables");
|
||||
view.contentDOM.dispatchEvent(new MouseEvent("mousedown", { ctrlKey: true, button: 0, bubbles: true, cancelable: true }));
|
||||
await vi.waitFor(() => expect(focus).toHaveBeenCalledOnce());
|
||||
expect(navigationSnapshot).toEqual({ selection: "picked", highlightedSource: "picked AS (SELECT id FROM users)" });
|
||||
expect(view.state.selection.main.from).toBe(sql.indexOf("picked"));
|
||||
expect(onClickTable).not.toHaveBeenCalled();
|
||||
expect(lookupTables).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("emits table navigation from the local cache without consuming Alt-modified gestures", async () => {
|
||||
const sql = "SELECT * FROM users";
|
||||
const { view, connectionStore, onClickTable } = await mountEditor({ modelValue: sql, connectionId: "navigation-test", database: "demo" });
|
||||
vi.spyOn(view, "posAtCoords").mockReturnValue(sql.indexOf("users") + 2);
|
||||
vi.spyOn(connectionStore, "lookupLocalCompletionTables").mockReturnValue([{ name: "users", schema: "demo" }]);
|
||||
view.contentDOM.dispatchEvent(new MouseEvent("mousedown", { ctrlKey: true, altKey: true, button: 0, bubbles: true, cancelable: true }));
|
||||
await nextTick();
|
||||
expect(onClickTable).not.toHaveBeenCalled();
|
||||
view.dispatch({ selection: { anchor: 0 } });
|
||||
view.contentDOM.dispatchEvent(new MouseEvent("mousedown", { ctrlKey: true, button: 0, bubbles: true, cancelable: true }));
|
||||
await vi.waitFor(() => expect(onClickTable).toHaveBeenCalledWith(expect.objectContaining({ name: "users" })));
|
||||
expect(view.state.doc.toString()).toBe(sql);
|
||||
});
|
||||
|
||||
it.each([false, true])("preserves selection drag edits with copy=%s through the real mouse handlers", async (copy) => {
|
||||
const { view, props } = await mountEditor({ modelValue: "abc def ghi" });
|
||||
view.dispatch({ selection: { anchor: 4, head: 7 } });
|
||||
const position = vi.spyOn(view, "posAtCoords").mockReturnValue(5);
|
||||
vi.spyOn(view, "coordsAtPos").mockReturnValue({ left: 50, right: 51, top: 20, bottom: 38 });
|
||||
view.contentDOM.dispatchEvent(new MouseEvent("mousedown", { button: 0, detail: 1, clientX: 10, clientY: 10, ctrlKey: copy, bubbles: true, cancelable: true }));
|
||||
position.mockReturnValue(11);
|
||||
document.dispatchEvent(new MouseEvent("mousemove", { clientX: 30, clientY: 10, ctrlKey: copy, cancelable: true }));
|
||||
expect(document.querySelector(".dbx-editor-selection-drop-cursor")).not.toBeNull();
|
||||
document.dispatchEvent(new MouseEvent("mouseup", { clientX: 30, clientY: 10, ctrlKey: copy, cancelable: true }));
|
||||
await nextTick();
|
||||
expect(view.state.doc.toString()).toBe(copy ? "abc def ghidef" : "abc ghidef");
|
||||
expect(props.modelValue).toBe(view.state.doc.toString());
|
||||
expect(document.querySelector(".dbx-editor-selection-drop-cursor")).toBeNull();
|
||||
});
|
||||
|
||||
it.each(["native", "window"])("connects %s table-reference drops to document updates and caret cleanup", async (source) => {
|
||||
const { view, props, host } = await mountEditor({ modelValue: "SELECT old", databaseType: "postgres", dialect: "postgres" });
|
||||
const root = host.querySelector("[data-query-editor-root]") as HTMLElement;
|
||||
vi.spyOn(root, "getBoundingClientRect").mockReturnValue(new DOMRect(0, 0, 200, 100));
|
||||
const position = vi.spyOn(view, "posAtCoords").mockReturnValue(7);
|
||||
vi.spyOn(view, "coordsAtPos").mockReturnValue({ left: 25, right: 26, top: 30, bottom: 48 });
|
||||
view.dispatch({ selection: { anchor: 7, head: 10 } });
|
||||
const payload: QueryEditorTableReferencePayload = { kind: "dbx-table-reference", connectionId: "drop-test", database: "demo", tableName: "users", referenceType: "column", columnName: "id" };
|
||||
setActiveTableReferencePayload(payload);
|
||||
window.dispatchEvent(createTableReferenceHoverEvent({ clientX: 30, clientY: 40 }));
|
||||
await nextTick();
|
||||
const caret = host.querySelector("[data-query-editor-drop-caret]") as HTMLElement;
|
||||
expect(caret.style.display).not.toBe("none");
|
||||
position.mockReturnValue(null);
|
||||
if (source === "native") view.contentDOM.dispatchEvent(new DragEvent("drop", { clientX: 30, clientY: 40, bubbles: true, cancelable: true }));
|
||||
else window.dispatchEvent(createTableReferenceDropEvent({ payload, clientX: 30, clientY: 40 }));
|
||||
await nextTick();
|
||||
expect(view.state.doc.toString()).toBe("SELECT id");
|
||||
expect(props.modelValue).toBe("SELECT id");
|
||||
expect(caret.style.display).toBe("none");
|
||||
});
|
||||
|
||||
it("keeps readonly table drops inert and removes global drop listeners on unmount", async () => {
|
||||
const { view, host, props, unmount } = await mountEditor({ modelValue: "SELECT old", readOnly: true });
|
||||
const root = host.querySelector("[data-query-editor-root]") as HTMLElement;
|
||||
vi.spyOn(root, "getBoundingClientRect").mockReturnValue(new DOMRect(0, 0, 200, 100));
|
||||
const position = vi.spyOn(view, "posAtCoords").mockReturnValue(10);
|
||||
const payload: QueryEditorTableReferencePayload = { kind: "dbx-table-reference", connectionId: "drop-test", database: "demo", tableName: "users", referenceType: "column", columnName: "id" };
|
||||
window.dispatchEvent(createTableReferenceDropEvent({ payload, clientX: 30, clientY: 40 }));
|
||||
expect(position).not.toHaveBeenCalled();
|
||||
expect(view.state.doc.toString()).toBe("SELECT old");
|
||||
props.readOnly = false;
|
||||
await nextTick();
|
||||
unmount();
|
||||
position.mockClear();
|
||||
window.dispatchEvent(createTableReferenceDropEvent({ payload, clientX: 30, clientY: 40 }));
|
||||
expect(position).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
+21
-11
@@ -2,22 +2,26 @@ import { readFileSync } from "node:fs";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
/**
|
||||
* QueryEditor.vue 的 CTE 接线(hover 溯源、Ctrl+点击跳转、语义模型缓存)都写在
|
||||
* `<script setup>` 内部,无法直接 import,因此沿用仓库既有做法
|
||||
* (queryEditorExtendSelection.spec.ts 对 queryEditorSource 的结构断言)。
|
||||
* CTE 接线(hover 溯源、Ctrl+点击跳转、语义模型缓存)分布在独立模块中。
|
||||
* 此处保留结构断言,模块行为另由 useQueryEditorHover 和
|
||||
* useQueryEditorObjectNavigation 的直接测试覆盖。
|
||||
*
|
||||
* 这里锁定回归成本最高的两类契约:分支先后顺序、关键调用参数。算法本身由
|
||||
* cteNavigation.spec.ts / model.spec.ts / sqlNavigation.spec.ts 覆盖。
|
||||
*/
|
||||
const source = readFileSync(new URL("../QueryEditor.vue", import.meta.url), "utf8");
|
||||
const componentSource = readFileSync(new URL("../QueryEditor.vue", import.meta.url), "utf8");
|
||||
const source = [readFileSync(new URL("../useQueryEditorHover.ts", import.meta.url), "utf8"), readFileSync(new URL("../useQueryEditorObjectNavigation.ts", import.meta.url), "utf8")].join("\n");
|
||||
|
||||
/** 截取模块中的函数体,避免跨函数误匹配。 */
|
||||
const metadataSource = readFileSync(new URL("../useQueryEditorCompletionMetadata.ts", import.meta.url), "utf8");
|
||||
|
||||
/** 截取 `<script setup>` 顶层函数体,避免跨函数误匹配。 */
|
||||
function functionBody(name: string): string {
|
||||
const start = source.indexOf(`function ${name}(`);
|
||||
const functionSource = name === "getEditorSemanticModel" ? metadataSource : source;
|
||||
const start = functionSource.indexOf(`function ${name}(`);
|
||||
expect(start, `QueryEditor.vue 缺少函数 ${name}`).toBeGreaterThanOrEqual(0);
|
||||
const end = source.indexOf("\n}", start);
|
||||
const end = functionSource.indexOf("\n }", start);
|
||||
expect(end, `${name} 函数体未闭合`).toBeGreaterThan(start);
|
||||
return source.slice(start, end);
|
||||
return functionSource.slice(start, end);
|
||||
}
|
||||
|
||||
function positionOf(fragment: string): number {
|
||||
@@ -43,6 +47,12 @@ function expectSourceToContain(fragment: string): void {
|
||||
}
|
||||
|
||||
describe("QueryEditor hover 的语义模型缓存接线", () => {
|
||||
it("连接独立的 hover 和对象导航入口及监听器生命周期", () => {
|
||||
expect(componentSource).toContain("hoverTooltip((currentView, pos) => resolveSqlHoverTooltip(currentView, pos))");
|
||||
expect(componentSource).toContain("mousedown: onEditorMouseDown");
|
||||
expect(componentSource).toContain("objectNavigation.attach();");
|
||||
expect(componentSource).toContain("objectNavigation.dispose();");
|
||||
});
|
||||
it("hover 复用 getEditorSemanticModel,而不是每次重新解析", () => {
|
||||
expect(source).toContain("semanticModel = getEditorSemanticModel(sql, pos, currentView.state);");
|
||||
// 换回逐次解析会让 hover 在每次移动时重复建模型(原实现即为此形态)。
|
||||
@@ -158,7 +168,7 @@ describe("jumpToCteRange 的跳转范围处理", () => {
|
||||
const body = functionBody("jumpToCteRange");
|
||||
|
||||
it("缺少视图或 CodeMirror 模块时直接返回", () => {
|
||||
expect(body).toContain("if (!currentView || !editorViewModule || !setResultSourceRangeEffect) return;");
|
||||
expect(body).toContain("if (!currentView || !codeMirrorRuntime.editorViewModule || !codeMirrorRuntime.setResultSourceRangeEffect) return;");
|
||||
});
|
||||
|
||||
it("把目标与高亮范围都收敛到文档长度内", () => {
|
||||
@@ -172,8 +182,8 @@ describe("jumpToCteRange 的跳转范围处理", () => {
|
||||
it("空目标不动光标,命中时选中目标 token 并高亮整个定义块", () => {
|
||||
expect(body).toContain("if (targetFrom >= targetTo) return;");
|
||||
expect(normalizeCode(body)).toContain(normalizeCode("selection: { anchor: targetFrom, head: targetTo }"));
|
||||
expectSourceToContain("setResultSourceRangeEffect.of({ from: highlightFrom, to: highlightTo })");
|
||||
expectSourceToContain('editorViewModule.EditorView.scrollIntoView(targetFrom, { y: "center" })');
|
||||
expectSourceToContain("codeMirrorRuntime.setResultSourceRangeEffect.of({ from: highlightFrom, to: highlightTo })");
|
||||
expectSourceToContain('codeMirrorRuntime.editorViewModule.EditorView.scrollIntoView(targetFrom, { y: "center" })');
|
||||
expect(body).toContain("currentView.focus();");
|
||||
});
|
||||
});
|
||||
+7
-7
@@ -1,11 +1,11 @@
|
||||
import { readFileSync } from "node:fs";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
const editorSource = readFileSync(new URL("../QueryEditor.vue", import.meta.url), "utf8");
|
||||
const editorSource = readFileSync(new URL("../useQueryEditorCompletionKeys.ts", import.meta.url), "utf8");
|
||||
|
||||
function functionSource(name: string, nextName: string) {
|
||||
function functionSource(name: string) {
|
||||
const start = editorSource.indexOf(`function ${name}(`);
|
||||
const end = editorSource.indexOf(`function ${nextName}(`, start);
|
||||
const end = editorSource.indexOf("\n }", start);
|
||||
expect(start).toBeGreaterThanOrEqual(0);
|
||||
expect(end).toBeGreaterThan(start);
|
||||
return editorSource.slice(start, end);
|
||||
@@ -18,7 +18,7 @@ function functionSource(name: string, nextName: string) {
|
||||
// a composition starts instead of accepting over (or after) it.
|
||||
describe("QueryEditor IME-safe completion acceptance", () => {
|
||||
it("gates the Enter handler on IME composition before any acceptance", () => {
|
||||
const source = functionSource("handleEnter", "clearPendingCompletionEnter");
|
||||
const source = functionSource("handleEnter");
|
||||
const composingGuard = source.indexOf("if (isEditorComposing(view)) return false;");
|
||||
const acceptCall = source.indexOf("codeMirrorAcceptCompletion?.(view)");
|
||||
|
||||
@@ -27,7 +27,7 @@ describe("QueryEditor IME-safe completion acceptance", () => {
|
||||
});
|
||||
|
||||
it("gates the Tab completion-accept handler on IME composition", () => {
|
||||
const source = functionSource("acceptCompletionOrNextSnippetField", "clearPendingCompletionTab");
|
||||
const source = functionSource("acceptCompletionOrNextSnippetField");
|
||||
const composingGuard = source.indexOf("if (isEditorComposing(view)) return false;");
|
||||
const selectionCheck = source.indexOf("view.state.selection.ranges.every");
|
||||
|
||||
@@ -36,7 +36,7 @@ describe("QueryEditor IME-safe completion acceptance", () => {
|
||||
});
|
||||
|
||||
it("drops the pending Tab acceptance retry when an IME composition starts", () => {
|
||||
const source = functionSource("waitForCompletionTab", "wordWrapExtension");
|
||||
const source = functionSource("waitForCompletionTab");
|
||||
const retry = source.indexOf("const retry = () => {");
|
||||
const composingGuard = source.indexOf("if (isEditorComposing(view)) return;", retry);
|
||||
|
||||
@@ -45,7 +45,7 @@ describe("QueryEditor IME-safe completion acceptance", () => {
|
||||
});
|
||||
|
||||
it("passes an IME guard to the Enter acceptance retry helper", () => {
|
||||
const source = functionSource("handleEnter", "clearPendingCompletionEnter");
|
||||
const source = functionSource("handleEnter");
|
||||
expect(source.includes("isComposing: () => isEditorComposing(view)")).toBe(true);
|
||||
});
|
||||
});
|
||||
+5
-4
@@ -1,6 +1,6 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import componentSource from "../QueryEditor.vue?raw";
|
||||
import componentSource from "../useQueryEditorCompletionKeys.ts?raw";
|
||||
import ts from "typescript";
|
||||
import { indentMore } from "@codemirror/commands";
|
||||
import { autocompletion, nextSnippetField, closeCompletion, completionKeymap, completionStatus, hasNextSnippetField, snippet, startCompletion, type CompletionResult } from "@codemirror/autocomplete";
|
||||
@@ -20,10 +20,11 @@ const mountedApps: Array<{ app: App; host: HTMLElement }> = [];
|
||||
|
||||
// Exercise the component's highest-priority Tab handler with real selections,
|
||||
// including typing into each field before advancing to the next one.
|
||||
const componentAst = ts.createSourceFile("QueryEditor.ts", componentSource.match(/^<script setup[^>]*>([\s\S]*?)<\/script>/m)![1], ts.ScriptTarget.Latest, true);
|
||||
const componentAst = ts.createSourceFile("useQueryEditorCompletionKeys.ts", componentSource, ts.ScriptTarget.Latest, true);
|
||||
const tabFunctions = new Set(["handleTab", "tabKeyAcceptsCompletion", "handleTabWithoutAcceptingCompletion", "performNormalTab", "editorIndentUnit", "acceptCompletionOrNextSnippetField"]);
|
||||
const tabSource = componentAst.statements
|
||||
.filter((statement) => ts.isFunctionDeclaration(statement) && statement.name && tabFunctions.has(statement.name.text))
|
||||
.find(ts.isFunctionDeclaration)!
|
||||
.body!.statements.filter((statement) => ts.isFunctionDeclaration(statement) && statement.name && tabFunctions.has(statement.name.text))
|
||||
.map((statement) => statement.getText(componentAst))
|
||||
.join("\n");
|
||||
const handleTab = new Function(
|
||||
@@ -35,7 +36,7 @@ const handleTab = new Function(
|
||||
"shortcutToCodeMirrorKey",
|
||||
"isEditorComposing",
|
||||
"isBatchColumnSelectionCompletionActive",
|
||||
ts.transpileModule(tabSource, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText + "\nreturn handleTab;",
|
||||
ts.transpileModule("const codeMirrorRuntime = { codeMirrorCompletionStatus, codeMirrorNextSnippetField, codeMirrorIndentMore };\n" + tabSource, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText + "\nreturn handleTab;",
|
||||
)(
|
||||
completionStatus,
|
||||
nextSnippetField,
|
||||
|
||||
Vendored
+2
-2
@@ -2,12 +2,12 @@ import { readFileSync } from "node:fs";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
/**
|
||||
* SQL Server 例程批次的语法诊断接线(#9315)写在 `<script setup>` 内部,
|
||||
* SQL Server 例程批次的语法诊断接线(#9315)写在诊断 composable 内部,
|
||||
* 无法直接 import,因此沿用仓库既有做法(QueryEditor.cteNavigationWiring.spec.ts)
|
||||
* 对源码做结构断言。规则本身由 sqlServerRoutineSyntaxDiagnostics.test.ts 覆盖,
|
||||
* 批次/视口裁剪由 sqlSemanticDiagnostics.test.ts 覆盖,这里只锁定接线契约。
|
||||
*/
|
||||
const source = readFileSync(new URL("../QueryEditor.vue", import.meta.url), "utf8");
|
||||
const source = readFileSync(new URL("../useQueryEditorDiagnostics.ts", import.meta.url), "utf8");
|
||||
|
||||
function normalizeCode(text: string): string {
|
||||
return text.replace(/\s+/g, "").replace(/,(?=[)\]}])/g, "");
|
||||
|
||||
+202
@@ -0,0 +1,202 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import { createApp, h, nextTick, reactive } from "vue";
|
||||
import { createI18n } from "vue-i18n";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import QueryEditorContextMenu, { type QueryEditorContextMenuActions, type QueryEditorContextMenuState } from "../QueryEditorContextMenu.vue";
|
||||
import { DEFAULT_SHORTCUT_SETTINGS } from "@/lib/editor/shortcutRegistry";
|
||||
|
||||
const cleanups: Array<() => void> = [];
|
||||
|
||||
afterEach(() => {
|
||||
for (const cleanup of cleanups.splice(0).reverse()) cleanup();
|
||||
});
|
||||
|
||||
function mountMenu() {
|
||||
const state = reactive<QueryEditorContextMenuState>({ readOnly: false, hideExecutionControls: false, databaseType: "mysql", selectedSql: "", executableSql: "", previewContextSql: "", contextObjectTarget: null, shortcuts: { ...DEFAULT_SHORTCUT_SETTINGS }, expandSelectStar: undefined });
|
||||
const actions = {
|
||||
executeFromContextMenu: vi.fn(),
|
||||
executeInNewResultTabFromContextMenu: vi.fn(),
|
||||
requestPreviewChanges: vi.fn(),
|
||||
exportQueryFromContextMenu: vi.fn(),
|
||||
toggleCommentFromContextMenu: vi.fn(),
|
||||
toggleBlockCommentFromContextMenu: vi.fn(),
|
||||
formatCurrentSql: vi.fn(),
|
||||
compressCurrentSql: vi.fn(),
|
||||
copySelectedSqlFromContextMenu: vi.fn(),
|
||||
copySelectedSqlAsRichTextFromContextMenu: vi.fn(),
|
||||
cutSelectedSqlFromContextMenu: vi.fn(),
|
||||
pasteClipboardSqlFromContextMenu: vi.fn(),
|
||||
convertSelectedSqlCase: vi.fn(),
|
||||
convertSelectedNamingStyle: vi.fn(),
|
||||
openDelimitedListDialog: vi.fn(),
|
||||
addNextSelectionOccurrenceFromContextMenu: vi.fn(),
|
||||
selectAllSelectionOccurrencesFromContextMenu: vi.fn(),
|
||||
openFindReplaceFromContextMenu: vi.fn(),
|
||||
deleteEmptyLines: vi.fn(),
|
||||
selectAllSqlFromContextMenu: vi.fn(),
|
||||
emitContextObjectAction: vi.fn(),
|
||||
openCodeSnapshot: vi.fn(),
|
||||
sendSelectionToAi: vi.fn(),
|
||||
} satisfies QueryEditorContextMenuActions;
|
||||
const onClose = vi.fn();
|
||||
let synchronize = () => {};
|
||||
const host = document.createElement("div");
|
||||
document.body.append(host);
|
||||
const app = createApp({
|
||||
render: () =>
|
||||
h(
|
||||
QueryEditorContextMenu,
|
||||
{ getState: () => ({ ...state }), actions, onClose },
|
||||
{
|
||||
default: ({ onContextMenu }: { onContextMenu: (event: MouseEvent) => void }) =>
|
||||
h("div", {
|
||||
"data-editor-host": "",
|
||||
onContextmenu: (event: MouseEvent) => {
|
||||
synchronize();
|
||||
onContextMenu(event);
|
||||
},
|
||||
}),
|
||||
},
|
||||
),
|
||||
});
|
||||
app.use(createI18n({ legacy: false, locale: "en", messages: { en: {} }, missingWarn: false, fallbackWarn: false }));
|
||||
app.mount(host);
|
||||
cleanups.push(() => {
|
||||
app.unmount();
|
||||
host.remove();
|
||||
});
|
||||
const open = async (update = () => {}) => {
|
||||
synchronize = update;
|
||||
host.querySelector("[data-editor-host]")!.dispatchEvent(new MouseEvent("contextmenu", { bubbles: true, cancelable: true, clientX: 20, clientY: 20 }));
|
||||
await nextTick();
|
||||
};
|
||||
return { state, actions, onClose, open, host };
|
||||
}
|
||||
|
||||
function button(label: string) {
|
||||
const found = [...document.querySelectorAll<HTMLButtonElement>("[data-dbx-context-menu] button")].find((candidate) => candidate.textContent?.includes(label));
|
||||
expect(found, label).toBeDefined();
|
||||
return found!;
|
||||
}
|
||||
|
||||
describe("QueryEditor extracted context menu", () => {
|
||||
it("routes the upstream table structure peek action through the extracted menu", async () => {
|
||||
const { state, actions, open } = mountMenu();
|
||||
state.contextObjectTarget = { name: "users", database: "demo", schema: "public", type: "table" };
|
||||
await open();
|
||||
expect(button("contextMenu.peekStructure").disabled).toBe(false);
|
||||
button("contextMenu.peekStructure").click();
|
||||
expect(actions.emitContextObjectAction).toHaveBeenCalledExactlyOnceWith("peek-table-structure");
|
||||
});
|
||||
|
||||
it("reads freshly synchronized state before Vue flushes child props", async () => {
|
||||
const { state, open } = mountMenu();
|
||||
await open();
|
||||
expect(button("editor.contextMenu.executeCurrent").disabled).toBe(true);
|
||||
expect(button("editor.contextMenu.copySelection").disabled).toBe(true);
|
||||
await open(() => {
|
||||
state.selectedSql = "SELECT 1";
|
||||
state.executableSql = "SELECT 1";
|
||||
});
|
||||
expect(button("editor.contextMenu.executeSelection").disabled).toBe(false);
|
||||
expect(button("editor.contextMenu.copySelection").disabled).toBe(false);
|
||||
await open(() => {
|
||||
state.selectedSql = "";
|
||||
state.executableSql = "";
|
||||
});
|
||||
expect(button("editor.contextMenu.executeCurrent").disabled).toBe(true);
|
||||
});
|
||||
|
||||
it("keeps whitespace copyable without treating it as executable SQL", async () => {
|
||||
const { state, open } = mountMenu();
|
||||
await open(() => {
|
||||
state.selectedSql = " \n ";
|
||||
state.executableSql = " \n ";
|
||||
});
|
||||
expect(button("editor.contextMenu.executeCurrent").disabled).toBe(true);
|
||||
expect(button("editor.contextMenu.copySelection").disabled).toBe(false);
|
||||
});
|
||||
|
||||
it("keeps read-only and hidden-execution controls independent", async () => {
|
||||
const { state, open } = mountMenu();
|
||||
await open(() => {
|
||||
state.readOnly = true;
|
||||
state.hideExecutionControls = true;
|
||||
state.selectedSql = "SELECT 1";
|
||||
});
|
||||
expect(document.querySelector("[data-dbx-context-menu]")!.textContent).not.toContain("editor.contextMenu.executeSelection");
|
||||
for (const name of ["cutSelection", "pasteFromClipboard", "commentSelection", "blockCommentSelection", "formatSelectionSql", "compressSelectionSql", "delimitedList", "deleteEmptyLines"]) {
|
||||
expect(button(`editor.contextMenu.${name}`).disabled, name).toBe(true);
|
||||
}
|
||||
expect(button("editor.contextMenu.copySelection").disabled).toBe(false);
|
||||
});
|
||||
|
||||
it.each(["redis", "mongodb"] as const)("preserves unsupported SQL controls for %s", async (databaseType) => {
|
||||
const { state, open } = mountMenu();
|
||||
await open(() => {
|
||||
state.databaseType = databaseType;
|
||||
state.selectedSql = "command";
|
||||
});
|
||||
expect(button("editor.contextMenu.blockCommentSelection").disabled).toBe(true);
|
||||
expect(button("editor.contextMenu.formatSelectionSql").disabled).toBe(databaseType === "redis");
|
||||
});
|
||||
|
||||
it("retains the resolved star expansion after the menu close callback clears it", async () => {
|
||||
const { state, open, onClose } = mountMenu();
|
||||
const expand = vi.fn();
|
||||
onClose.mockImplementation(() => {
|
||||
state.expandSelectStar = undefined;
|
||||
});
|
||||
await open(() => {
|
||||
state.expandSelectStar = expand;
|
||||
});
|
||||
button("editor.contextMenu.expandSelectStar").click();
|
||||
await nextTick();
|
||||
expect(onClose).toHaveBeenCalledTimes(1);
|
||||
expect(expand).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("reads the current preview SQL when invoking the action", async () => {
|
||||
const { state, actions, open } = mountMenu();
|
||||
state.previewContextSql = "UPDATE users SET name = 'before'";
|
||||
await open();
|
||||
state.previewContextSql = "UPDATE users SET name = 'after'";
|
||||
button("editor.previewChanges").click();
|
||||
expect(actions.requestPreviewChanges).toHaveBeenCalledExactlyOnceWith(state.previewContextSql);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["editor.contextMenu.executeCurrent", "executeFromContextMenu"],
|
||||
["settings.shortcutExecuteSqlInNewResultTab", "executeInNewResultTabFromContextMenu"],
|
||||
["editor.contextMenu.screenshotSelection", "openCodeSnapshot"],
|
||||
["editor.contextMenu.delimitedList", "openDelimitedListDialog"],
|
||||
["editor.contextMenu.sendToAi", "sendSelectionToAi"],
|
||||
["editor.contextMenu.findReplace", "openFindReplaceFromContextMenu"],
|
||||
] as const)("forwards %s exactly once", async (label, action) => {
|
||||
const { state, actions, open } = mountMenu();
|
||||
state.selectedSql = "SELECT 1";
|
||||
state.executableSql = "SELECT 1";
|
||||
if (label.endsWith("executeCurrent")) state.selectedSql = "";
|
||||
await open();
|
||||
button(label).click();
|
||||
expect(actions[action]).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["table", "contextMenu.editStructure", "edit-table-structure"],
|
||||
["view", "contextMenu.editView", "edit-view"],
|
||||
["materialized_view", "contextMenu.viewSource", "view-source"],
|
||||
] as const)("keeps object routing for %s targets", async (type, label, action) => {
|
||||
const { state, actions, open } = mountMenu();
|
||||
await open(() => {
|
||||
state.contextObjectTarget = { type, name: "users", schema: "public", database: "db" };
|
||||
});
|
||||
button(label).click();
|
||||
expect(actions.emitContextObjectAction).toHaveBeenCalledExactlyOnceWith(action);
|
||||
await open(() => {
|
||||
state.contextObjectTarget = null;
|
||||
});
|
||||
expect(button("contextMenu.viewData").disabled).toBe(true);
|
||||
});
|
||||
});
|
||||
+56
-46
@@ -8,10 +8,19 @@ import CustomContextMenu, { type ContextMenuItem } from "@/components/ui/CustomC
|
||||
|
||||
const source = readFileSync(path.resolve(process.cwd(), "apps/desktop/src/components/editor/QueryEditor.vue"), "utf8");
|
||||
|
||||
const menuSource = readFileSync(path.resolve(process.cwd(), "apps/desktop/src/components/editor/QueryEditorContextMenu.vue"), "utf8");
|
||||
|
||||
const documentSource = readFileSync(path.resolve(process.cwd(), "apps/desktop/src/components/editor/useQueryEditorDocumentState.ts"), "utf8");
|
||||
const batchSource = readFileSync(path.resolve(process.cwd(), "apps/desktop/src/components/editor/useQueryEditorBatchSelection.ts"), "utf8");
|
||||
|
||||
const completionSource = readFileSync(path.resolve(process.cwd(), "apps/desktop/src/components/editor/useQueryEditorCompletion.ts"), "utf8");
|
||||
const completionKeysSource = readFileSync(path.resolve(process.cwd(), "apps/desktop/src/components/editor/useQueryEditorCompletionKeys.ts"), "utf8");
|
||||
const extensionsSource = readFileSync(path.resolve(process.cwd(), "apps/desktop/src/components/editor/queryEditorSqlExtensions.ts"), "utf8");
|
||||
|
||||
describe("QueryEditor context menu lifecycle", () => {
|
||||
it("keeps heavyweight context derivation out of the per-update path", () => {
|
||||
const updateStart = source.indexOf("EditorView.updateListener.of((update) => {");
|
||||
const updateEnd = source.indexOf("\n fontThemeComp.of(", updateStart);
|
||||
const updateEnd = source.indexOf("initializedRuntime.fontThemeComp.of(", updateStart);
|
||||
const updateSource = source.slice(updateStart, updateEnd);
|
||||
|
||||
expect(updateStart).toBeGreaterThanOrEqual(0);
|
||||
@@ -23,13 +32,13 @@ describe("QueryEditor context menu lifecycle", () => {
|
||||
|
||||
it("does not suppress legitimate external model updates", () => {
|
||||
expect(source).not.toContain("lastEmittedModelValue");
|
||||
expect(source).toContain("if (val !== currentEditorDocText(view.value)) {");
|
||||
expect(documentSource).toContain("if (val !== currentEditorDocText(view.value)) {");
|
||||
});
|
||||
|
||||
it("resynchronizes context state after restoring a tab document", () => {
|
||||
const activateStart = source.indexOf("function activateTabDocument");
|
||||
const activateEnd = source.indexOf("\nwatch([() => props.tabId", activateStart);
|
||||
const activateSource = source.slice(activateStart, activateEnd);
|
||||
const activateStart = documentSource.indexOf("function activateTabDocument");
|
||||
const activateEnd = documentSource.indexOf("\n watch([() => props.tabId", activateStart);
|
||||
const activateSource = documentSource.slice(activateStart, activateEnd);
|
||||
|
||||
expect(activateStart).toBeGreaterThanOrEqual(0);
|
||||
expect(activateEnd).toBeGreaterThan(activateStart);
|
||||
@@ -49,9 +58,9 @@ describe("QueryEditor context menu lifecycle", () => {
|
||||
const syncSource = source.slice(syncStart, syncEnd);
|
||||
const syncIndex = source.indexOf("syncContextMenuStateAtEvent(view, e);");
|
||||
const openIndex = source.indexOf("onContextMenu(e);", syncIndex);
|
||||
const getterStart = source.indexOf("function currentContextMenuItems()");
|
||||
const getterEnd = source.indexOf("\n}", getterStart);
|
||||
const getterSource = source.slice(getterStart, getterEnd);
|
||||
const getterStart = menuSource.indexOf("function currentContextMenuItems()");
|
||||
const getterEnd = menuSource.indexOf("\n}", getterStart);
|
||||
const getterSource = menuSource.slice(getterStart, getterEnd);
|
||||
|
||||
expect(syncStart).toBeGreaterThanOrEqual(0);
|
||||
expect(syncEnd).toBeGreaterThan(syncStart);
|
||||
@@ -64,8 +73,9 @@ describe("QueryEditor context menu lifecycle", () => {
|
||||
expect(getterSource).toContain("return contextMenuItems.value;");
|
||||
expect(getterSource).not.toContain("nextTick");
|
||||
expect(getterSource).not.toContain("setTimeout");
|
||||
expect(source).toContain(':items="currentContextMenuItems"');
|
||||
expect(source).not.toContain('<CustomContextMenu :items="contextMenuItems"');
|
||||
expect(menuSource).toContain(':items="currentContextMenuItems"');
|
||||
expect(source).toContain(':get-state="getContextMenuState"');
|
||||
expect(menuSource).not.toContain('<CustomContextMenu :items="contextMenuItems"');
|
||||
});
|
||||
|
||||
it("uses the target synchronized in the current context-menu event", async () => {
|
||||
@@ -135,67 +145,67 @@ describe("QueryEditor context menu lifecycle", () => {
|
||||
|
||||
describe("QueryEditor batch column selection", () => {
|
||||
it("keeps the confirmation action visible during pinyin filtering and supports keyboard toggling", () => {
|
||||
const bypassFilterStart = source.indexOf("function completionItemsForBypassedFilter");
|
||||
const bypassFilterEnd = source.indexOf("\n}\n\nfunction localCompletionDatabaseNames", bypassFilterStart);
|
||||
const bypassFilterSource = source.slice(bypassFilterStart, bypassFilterEnd);
|
||||
const bypassFilterStart = completionSource.indexOf("function completionItemsForBypassedFilter");
|
||||
const bypassFilterEnd = completionSource.indexOf("\n }\n\n function localCompletionDatabaseNames", bypassFilterStart);
|
||||
const bypassFilterSource = completionSource.slice(bypassFilterStart, bypassFilterEnd);
|
||||
|
||||
expect(bypassFilterStart).toBeGreaterThanOrEqual(0);
|
||||
expect(bypassFilterEnd).toBeGreaterThan(bypassFilterStart);
|
||||
expect(bypassFilterSource).toContain("if (isBatchColumnSelectionAction(item)) return true;");
|
||||
expect(source).toContain('key: "Space"');
|
||||
expect(source).toContain("run: toggleSelectedBatchColumnSelection");
|
||||
expect(source).toContain("codeMirrorSelectedCompletion?.(view.state)");
|
||||
expect(completionKeysSource).toContain("codeMirrorSelectedCompletion?.(view.state)");
|
||||
});
|
||||
|
||||
it("applies checked columns directly through Enter and the completion Tab shortcut", () => {
|
||||
const handleEnterStart = source.indexOf("function handleEnter");
|
||||
const handleEnterEnd = source.indexOf("\n}\n\nfunction clearPendingCompletionEnter", handleEnterStart);
|
||||
const tabStart = source.indexOf("function acceptCompletionOrNextSnippetField");
|
||||
const tabEnd = source.indexOf("\n}\n\nfunction clearPendingCompletionTab", tabStart);
|
||||
const handleEnterStart = completionKeysSource.indexOf("function handleEnter");
|
||||
const handleEnterEnd = completionKeysSource.indexOf("\n }", handleEnterStart);
|
||||
const tabStart = completionKeysSource.indexOf("function acceptCompletionOrNextSnippetField");
|
||||
const tabEnd = completionKeysSource.indexOf("\n }", tabStart);
|
||||
|
||||
expect(source).toContain("function applySelectedBatchColumnSelection");
|
||||
expect(source.slice(handleEnterStart, handleEnterEnd)).toContain("if (isBatchColumnSelectionCompletionActive(codeMirrorCompletionStatus?.(view.state) ?? null) && applySelectedBatchColumnSelection(view)) return true;");
|
||||
expect(source.slice(handleEnterStart, handleEnterEnd)).toContain("if (codeMirrorAcceptCompletion?.(view)) return true;");
|
||||
expect(source.slice(tabStart, tabEnd)).toContain("if (isBatchColumnSelectionCompletionActive(completionStatus) && applySelectedBatchColumnSelection(view)) return true;");
|
||||
expect(source).toContain("defaultKeymap: false");
|
||||
expect(batchSource).toContain("function applySelectedBatchColumnSelection");
|
||||
expect(completionKeysSource.slice(handleEnterStart, handleEnterEnd)).toContain("if (isBatchColumnSelectionCompletionActive(codeMirrorRuntime.codeMirrorCompletionStatus?.(view.state) ?? null) && applySelectedBatchColumnSelection(view)) return true;");
|
||||
expect(completionKeysSource.slice(handleEnterStart, handleEnterEnd)).toContain("if (codeMirrorRuntime.codeMirrorAcceptCompletion?.(view)) return true;");
|
||||
expect(completionKeysSource.slice(tabStart, tabEnd)).toContain("if (isBatchColumnSelectionCompletionActive(completionStatus) && applySelectedBatchColumnSelection(view)) return true;");
|
||||
expect(extensionsSource).toContain("defaultKeymap: false");
|
||||
expect(source).toContain('{ key: "ArrowDown", run: (view) => moveCompletion(view, true) }');
|
||||
expect(source).toContain('{ key: "ArrowUp", run: (view) => moveCompletion(view, false) }');
|
||||
});
|
||||
|
||||
it("marks the insertion action so the completion menu can keep it sticky", () => {
|
||||
expect(source).toContain("dbxBatchColumnSelectionAction: { sessionKey: item.sessionKey, ...(item.batchColumnSelectionToggleAll ? { toggleAll: true as const } : {}) }");
|
||||
expect(source).toContain('optionClass: (completion) => ((completion as QueryCompletionOption).dbxBatchColumnSelectionAction ? "cm-batch-column-selection-action" : "")');
|
||||
expect(completionSource).toContain("dbxBatchColumnSelectionAction: { sessionKey: item.sessionKey, ...(item.batchColumnSelectionToggleAll ? { toggleAll: true as const } : {}) }");
|
||||
expect(extensionsSource).toContain('optionClass: (completion) => ((completion as QueryCompletionOption).dbxBatchColumnSelectionAction ? "cm-batch-column-selection-action" : "")');
|
||||
});
|
||||
|
||||
it("updates the insertion count while a mouse selection is still in progress", () => {
|
||||
const dragUpdateStart = source.indexOf("function updateBatchColumnSelectionAtPoint");
|
||||
const dragUpdateEnd = source.indexOf("\n}\n\nconst BATCH_COLUMN_SELECTION_AUTO_SCROLL_EDGE_PX", dragUpdateStart);
|
||||
const dragUpdateStart = batchSource.indexOf("function updateBatchColumnSelectionAtPoint");
|
||||
const dragUpdateEnd = batchSource.indexOf("\n }\n\n const BATCH_COLUMN_SELECTION_AUTO_SCROLL_EDGE_PX", dragUpdateStart);
|
||||
|
||||
expect(source).toContain("function updateBatchColumnSelectionActionLabel");
|
||||
expect(source.slice(dragUpdateStart, dragUpdateEnd)).toContain("updateBatchColumnSelectionActionLabel(state.view, state.sessionKey);");
|
||||
expect(source).toContain("const batchColumnSelectionTooltipParents = new WeakMap<EditorViewType, HTMLElement>();");
|
||||
expect(source).toContain("batchColumnSelectionTooltipParents.set(view.value, tooltipParent);");
|
||||
expect(source).toContain("const batchColumnSelectionActionMarkers = new WeakMap<HTMLElement, { sessionKey: string; toggleAll: boolean }>();");
|
||||
expect(source).toContain("!markerState || markerState.sessionKey !== sessionKey");
|
||||
expect(source).toContain("renderBatchColumnSelectionActionMarker");
|
||||
expect(batchSource).toContain("function updateBatchColumnSelectionActionLabel");
|
||||
expect(batchSource.slice(dragUpdateStart, dragUpdateEnd)).toContain("updateBatchColumnSelectionActionLabel(state.view, state.sessionKey);");
|
||||
expect(batchSource).toContain("const batchColumnSelectionTooltipParents = new WeakMap<EditorViewType, HTMLElement>();");
|
||||
expect(batchSource).toContain("batchColumnSelectionTooltipParents.set(currentView, tooltipParent);");
|
||||
expect(batchSource).toContain("const batchColumnSelectionActionMarkers = new WeakMap<HTMLElement, { sessionKey: string; toggleAll: boolean }>();");
|
||||
expect(batchSource).toContain("!markerState || markerState.sessionKey !== sessionKey");
|
||||
expect(batchSource).toContain("renderBatchColumnSelectionActionMarker");
|
||||
});
|
||||
|
||||
it("cancels stale scroll restoration before a new drag can begin", () => {
|
||||
const refreshStart = source.indexOf("function scheduleBatchColumnSelectionRefresh");
|
||||
const refreshEnd = source.indexOf("\n}\n\nfunction finishBatchColumnSelectionDrag", refreshStart);
|
||||
const dragStart = source.indexOf("function startBatchColumnSelectionDrag");
|
||||
const dragEnd = source.indexOf("\n}\n\nfunction renderBatchColumnSelectionCheckbox", dragStart);
|
||||
const refreshStart = batchSource.indexOf("function scheduleBatchColumnSelectionRefresh");
|
||||
const refreshEnd = batchSource.indexOf("\n }\n\n function finishBatchColumnSelectionDrag", refreshStart);
|
||||
const dragStart = batchSource.indexOf("function startBatchColumnSelectionDrag");
|
||||
const dragEnd = batchSource.indexOf("\n }\n\n function renderBatchColumnSelectionCheckbox", dragStart);
|
||||
|
||||
expect(source).toContain("let batchColumnSelectionRefreshCleanup: (() => void) | null = null;");
|
||||
expect(source.slice(refreshStart, refreshEnd)).toContain("cancelBatchColumnSelectionRefresh();");
|
||||
expect(source.slice(dragStart, dragEnd)).toContain("cancelBatchColumnSelectionRefresh();");
|
||||
expect(source).toContain("if (restoreStartTimer) window.clearTimeout(restoreStartTimer);");
|
||||
expect(batchSource).toContain("let batchColumnSelectionRefreshCleanup: (() => void) | null = null;");
|
||||
expect(batchSource.slice(refreshStart, refreshEnd)).toContain("cancelBatchColumnSelectionRefresh();");
|
||||
expect(batchSource.slice(dragStart, dragEnd)).toContain("cancelBatchColumnSelectionRefresh();");
|
||||
expect(batchSource).toContain("if (restoreStartTimer) window.clearTimeout(restoreStartTimer);");
|
||||
});
|
||||
|
||||
it("only expands rendering for batch field selection", () => {
|
||||
expect(source).toContain("function setBatchColumnSelectionExpandedRendering");
|
||||
expect(source).toContain("setBatchColumnSelectionExpandedRendering(true);");
|
||||
expect(source).toContain("setBatchColumnSelectionExpandedRendering(false);");
|
||||
expect(source).toContain("maxRenderedOptions: batchColumnSelectionExpandedRendering ? Number.MAX_SAFE_INTEGER : 100,");
|
||||
expect(batchSource).toContain("function setBatchColumnSelectionExpandedRendering");
|
||||
expect(batchSource).toContain("setBatchColumnSelectionExpandedRendering(true);");
|
||||
expect(batchSource).toContain("setBatchColumnSelectionExpandedRendering(false);");
|
||||
expect(extensionsSource).toContain("maxRenderedOptions: batchSelection.expandedRendering ? Number.MAX_SAFE_INTEGER : 100,");
|
||||
});
|
||||
});
|
||||
+131
@@ -0,0 +1,131 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import { ref } from "vue";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { createQueryEditorHoverContent } from "../queryEditorHoverContent";
|
||||
|
||||
const { copy, highlight, createHighlighter, mountLayout, destroyLayout } = vi.hoisted(() => ({ copy: vi.fn(), highlight: vi.fn(), createHighlighter: vi.fn(), mountLayout: vi.fn(), destroyLayout: vi.fn() }));
|
||||
vi.mock("@/lib/common/clipboard", () => ({ copyToClipboard: copy }));
|
||||
vi.mock("@/lib/sql/sqlHighlighter", () => ({ createShikiSqlHighlighter: createHighlighter }));
|
||||
vi.mock("@/lib/editor/sqlHoverLayout", () => ({ constrainSqlHoverLayout: () => ({ mount: mountLayout, destroy: destroyLayout }) }));
|
||||
const cleanups: Array<() => void> = [];
|
||||
|
||||
beforeEach(() => {
|
||||
copy.mockResolvedValue(undefined);
|
||||
highlight.mockImplementation((sql: string) => `<pre>${sql}</pre>`);
|
||||
createHighlighter.mockResolvedValue(highlight);
|
||||
});
|
||||
afterEach(() => {
|
||||
for (const cleanup of cleanups.splice(0).reverse()) cleanup();
|
||||
document.getSelection()?.removeAllRanges();
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
function createHarness() {
|
||||
const isDark = ref(false);
|
||||
const toast = vi.fn();
|
||||
const t = vi.fn((key: string) => key);
|
||||
const content = createQueryEditorHoverContent({ isDark, toast, t: t as Parameters<typeof createQueryEditorHoverContent>[0]["t"] });
|
||||
function render(sql?: string, rows?: string[]) {
|
||||
const tooltip = content.createHoverDom("users", "TABLE", sql, rows);
|
||||
document.body.append(tooltip.dom);
|
||||
tooltip.mount?.();
|
||||
cleanups.push(() => {
|
||||
tooltip.destroy?.();
|
||||
tooltip.dom.remove();
|
||||
});
|
||||
return tooltip;
|
||||
}
|
||||
return { content, isDark, toast, t, render };
|
||||
}
|
||||
|
||||
describe("QueryEditor hover content", () => {
|
||||
it("renders plain metadata safely without creating DDL controls", () => {
|
||||
const { render } = createHarness();
|
||||
const tooltip = render(undefined, ["<img src=x>"]);
|
||||
expect(tooltip.dom.textContent).toContain("<img src=x>");
|
||||
expect(tooltip.dom.querySelector("img")).toBeNull();
|
||||
expect(tooltip.dom.querySelector("button")).toBeNull();
|
||||
expect(mountLayout).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("copies normalized DDL without changing its displayed alignment", async () => {
|
||||
const { render, toast } = createHarness();
|
||||
const sql = "CREATE TABLE users (id INTEGER);";
|
||||
const tooltip = render(sql);
|
||||
const button = tooltip.dom.querySelector<HTMLButtonElement>('button[aria-label="grid.copyDdl"]')!;
|
||||
const pointer = new MouseEvent("pointerdown", { bubbles: true, cancelable: true });
|
||||
button.dispatchEvent(pointer);
|
||||
expect(pointer.defaultPrevented).toBe(true);
|
||||
button.click();
|
||||
await vi.waitFor(() => expect(copy).toHaveBeenCalledWith("CREATE TABLE users (id INTEGER);"));
|
||||
expect(toast).toHaveBeenCalledWith("contextMenu.ddlCopied", 2000);
|
||||
expect(tooltip.dom.textContent).toContain(sql);
|
||||
});
|
||||
|
||||
it("reports copy failures without dismissing the content", async () => {
|
||||
copy.mockRejectedValue(new Error("clipboard unavailable"));
|
||||
const { render, toast, t } = createHarness();
|
||||
const tooltip = render("SELECT 1");
|
||||
tooltip.dom.querySelector<HTMLButtonElement>('button[aria-label="grid.copyDdl"]')!.click();
|
||||
await vi.waitFor(() => expect(toast).toHaveBeenCalledWith("grid.copyFailed", 5000));
|
||||
expect(t).toHaveBeenCalledWith("grid.copyFailed", { message: "clipboard unavailable" });
|
||||
expect(tooltip.dom.isConnected).toBe(true);
|
||||
});
|
||||
|
||||
it("removes its document copy listener and layout controller on destroy", () => {
|
||||
const { render } = createHarness();
|
||||
const tooltip = render("SELECT 1");
|
||||
const sqlContainer = tooltip.dom.querySelector(".whitespace-pre")!;
|
||||
const range = document.createRange();
|
||||
range.selectNodeContents(sqlContainer);
|
||||
document.getSelection()?.addRange(range);
|
||||
const clipboardData = { setData: vi.fn() };
|
||||
const copyEvent = () => {
|
||||
const event = new Event("copy", { cancelable: true });
|
||||
Object.defineProperty(event, "clipboardData", { value: clipboardData });
|
||||
document.dispatchEvent(event);
|
||||
return event;
|
||||
};
|
||||
expect(copyEvent().defaultPrevented).toBe(true);
|
||||
expect(clipboardData.setData).toHaveBeenCalledWith("text/plain", "SELECT 1");
|
||||
tooltip.destroy?.();
|
||||
clipboardData.setData.mockClear();
|
||||
expect(copyEvent().defaultPrevented).toBe(false);
|
||||
expect(clipboardData.setData).not.toHaveBeenCalled();
|
||||
expect(mountLayout).toHaveBeenCalledOnce();
|
||||
expect(destroyLayout).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("uses late-loaded highlighting and reads the current appearance", async () => {
|
||||
const { content, isDark, render } = createHarness();
|
||||
expect(render("SELECT 1").dom.querySelector("pre")).toBeNull();
|
||||
content.initializeHighlighter();
|
||||
await vi.waitFor(() => expect(createHighlighter).toHaveBeenCalled());
|
||||
render("SELECT 2");
|
||||
expect(highlight).toHaveBeenLastCalledWith("SELECT 2", "light");
|
||||
isDark.value = true;
|
||||
render("SELECT 3");
|
||||
expect(highlight).toHaveBeenLastCalledWith("SELECT 3", "dark");
|
||||
});
|
||||
|
||||
it("keeps a plain-text fallback when the highlighter fails", async () => {
|
||||
createHighlighter.mockRejectedValue(new Error("unavailable"));
|
||||
const { content, render } = createHarness();
|
||||
content.initializeHighlighter();
|
||||
await vi.waitFor(() => expect(createHighlighter).toHaveBeenCalled());
|
||||
const tooltip = render("SELECT '<script>'");
|
||||
expect(tooltip.dom.textContent).toContain("SELECT '<script>'");
|
||||
expect(tooltip.dom.querySelector("script")).toBeNull();
|
||||
expect(highlight).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("keeps loaded highlighters local to each editor instance", async () => {
|
||||
const first = createHarness();
|
||||
const second = createHarness();
|
||||
first.content.initializeHighlighter();
|
||||
await vi.waitFor(() => expect(createHighlighter).toHaveBeenCalled());
|
||||
expect(first.render("SELECT 1").dom.querySelector("pre")).not.toBeNull();
|
||||
expect(second.render("SELECT 2").dom.querySelector("pre")).toBeNull();
|
||||
});
|
||||
});
|
||||
+195
@@ -0,0 +1,195 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import { shallowRef } from "vue";
|
||||
import { Compartment, EditorState } from "@codemirror/state";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { snippetCompletion } from "@codemirror/autocomplete";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { useQueryEditorBatchSelection, type QueryCompletionOption } from "../useQueryEditorBatchSelection";
|
||||
import type { SqlCompletionItem } from "@/lib/sql/sqlCompletion";
|
||||
|
||||
const { toast } = vi.hoisted(() => ({ toast: vi.fn() }));
|
||||
vi.mock("vue-i18n", () => ({ useI18n: () => ({ t: (key: string) => key }) }));
|
||||
vi.mock("@/composables/useToast", () => ({ useToast: () => ({ toast }) }));
|
||||
|
||||
type Options = Parameters<typeof useQueryEditorBatchSelection>[0];
|
||||
const cleanups: Array<() => void> = [];
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
vi.spyOn(EditorView.prototype, "focus").mockImplementation(() => {});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
for (const cleanup of cleanups.splice(0).reverse()) cleanup();
|
||||
vi.clearAllTimers();
|
||||
vi.useRealTimers();
|
||||
vi.restoreAllMocks();
|
||||
toast.mockReset();
|
||||
});
|
||||
|
||||
function createHarness(doc = "SELECT FROM users", mode: "select" | "insert" = "select") {
|
||||
const completionComp = new Compartment();
|
||||
const parent = document.createElement("div");
|
||||
document.body.append(parent);
|
||||
const currentView = new EditorView({ parent, state: EditorState.create({ doc, extensions: [completionComp.of([])] }) });
|
||||
const view = shallowRef<EditorView | null>(currentView);
|
||||
const runtime: Options["runtime"] = {
|
||||
completionComp,
|
||||
buildSqlCompletionExtension: vi.fn(() => []),
|
||||
codeMirrorCompletionStatus: vi.fn(() => "active"),
|
||||
codeMirrorStartCompletion: vi.fn(() => true),
|
||||
codeMirrorCurrentCompletions: vi.fn(() => []),
|
||||
codeMirrorSetSelectedCompletion: null,
|
||||
codeMirrorSelectedCompletion: vi.fn(() => null),
|
||||
codeMirrorSnippetCompletion: snippetCompletion,
|
||||
};
|
||||
const accepted = vi.fn();
|
||||
const batch = useQueryEditorBatchSelection({ view, runtime, settingsStore: { editorSettings: { sqlFormatter: { keywordCase: "upper" } } } as Options["settingsStore"], markCompletionAccepted: accepted });
|
||||
const items: SqlCompletionItem[] = ["id", "name", "email"].map((label) => ({ label, apply: label, type: "column", batchSelectionMode: mode }));
|
||||
const from = mode === "select" ? 7 : doc.length;
|
||||
const session = batch.prepareBatchColumnSelectionSession(items, doc, from, from)!;
|
||||
batch.attach(currentView, parent);
|
||||
cleanups.push(() => {
|
||||
batch.dispose();
|
||||
currentView.destroy();
|
||||
parent.remove();
|
||||
});
|
||||
function completion(index: number): QueryCompletionOption {
|
||||
return { label: items[index].label, dbxBatchColumnSelection: batch.batchColumnSelectionMarkerForItem(items[index]) };
|
||||
}
|
||||
function row(index: number) {
|
||||
const element = document.createElement("li");
|
||||
element.setAttribute("role", "option");
|
||||
const checkbox = batch.renderBatchColumnSelectionCheckbox(completion(index), currentView.state, currentView) as HTMLInputElement;
|
||||
const label = document.createElement("span");
|
||||
label.textContent = items[index].label;
|
||||
element.append(checkbox, label);
|
||||
parent.append(element);
|
||||
return { element, checkbox, label };
|
||||
}
|
||||
return { batch, currentView, view, runtime, accepted, items, session, completion, row };
|
||||
}
|
||||
|
||||
describe("QueryEditor batch selection ownership", () => {
|
||||
it("keeps checked fields and cached options across refreshes, pruning removed fields", () => {
|
||||
const { batch, session, items, completion, currentView } = createHarness();
|
||||
batch.toggleAllBatchColumnSelection(currentView, session.key);
|
||||
const option = completion(0);
|
||||
expect(batch.cacheBatchColumnSelectionOption(option.dbxBatchColumnSelection, option)).toBe(option);
|
||||
expect(batch.cacheBatchColumnSelectionOption(option.dbxBatchColumnSelection, completion(0))).toBe(option);
|
||||
const refreshed = batch.prepareBatchColumnSelectionSession(items.slice(0, 2), session.document, session.from, session.to)!;
|
||||
expect(refreshed).toBe(session);
|
||||
expect(refreshed.selectedKeys).toEqual(new Set(refreshed.candidates.map((candidate) => candidate.key)));
|
||||
expect(refreshed.completionOptions.size).toBe(1);
|
||||
});
|
||||
|
||||
it("starts a fresh session when the document changes and ignores old select-all actions", () => {
|
||||
const { batch, session, items, currentView } = createHarness();
|
||||
batch.toggleAllBatchColumnSelection(currentView, session.key);
|
||||
const next = batch.prepareBatchColumnSelectionSession(items, session.document + " ", session.from, session.to)!;
|
||||
batch.toggleAllBatchColumnSelection(currentView, session.key);
|
||||
expect(next.selectedKeys.size).toBe(0);
|
||||
expect(next.completionOptions.size).toBe(0);
|
||||
batch.prepareBatchColumnSelectionSession([], next.document, next.from, next.to);
|
||||
expect(batch.expandedRendering).toBe(false);
|
||||
});
|
||||
|
||||
it("guards label clicks and applies checked fields together, never an individual row", () => {
|
||||
const { batch, session, currentView, row, accepted } = createHarness();
|
||||
const { label } = row(1);
|
||||
vi.spyOn(document, "elementFromPoint").mockReturnValue(label);
|
||||
const mouseDown = new MouseEvent("mousedown", { button: 0, bubbles: true, cancelable: true });
|
||||
label.dispatchEvent(mouseDown);
|
||||
expect(mouseDown.defaultPrevented).toBe(true);
|
||||
expect(session.selectedKeys).toEqual(new Set([session.candidates[1].key]));
|
||||
expect(currentView.state.doc.toString()).toBe(session.document);
|
||||
expect(batch.applySelectedBatchColumnSelection(currentView)).toBe(true);
|
||||
expect(currentView.state.doc.toString()).toBe("SELECT name FROM users");
|
||||
expect(accepted).toHaveBeenCalledOnce();
|
||||
expect(batch.expandedRendering).toBe(false);
|
||||
});
|
||||
|
||||
it("uses the live selected completion and inserts fields in candidate order", () => {
|
||||
const { batch, session, runtime, currentView, completion } = createHarness();
|
||||
runtime.codeMirrorSelectedCompletion = () => completion(2);
|
||||
expect(batch.toggleSelectedBatchColumnSelection(currentView)).toBe(true);
|
||||
runtime.codeMirrorSelectedCompletion = () => completion(0);
|
||||
batch.toggleSelectedBatchColumnSelection(currentView);
|
||||
expect(session.selectedKeys.size).toBe(2);
|
||||
expect(batch.applySelectedBatchColumnSelection(currentView)).toBe(true);
|
||||
expect(currentView.state.doc.toString()).toBe("SELECT id, email FROM users");
|
||||
});
|
||||
|
||||
it("rejects stale documents and pending completion without recording acceptance", () => {
|
||||
const { batch, session, runtime, currentView, accepted } = createHarness();
|
||||
batch.toggleAllBatchColumnSelection(currentView, session.key);
|
||||
runtime.codeMirrorCompletionStatus = () => "pending";
|
||||
expect(batch.applySelectedBatchColumnSelection(currentView)).toBe(false);
|
||||
runtime.codeMirrorCompletionStatus = () => "active";
|
||||
currentView.dispatch({ changes: { from: 0, insert: " " } });
|
||||
expect(batch.applySelectedBatchColumnSelection(currentView)).toBe(false);
|
||||
expect(accepted).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("preserves the empty-selection warning and INSERT snippet application", () => {
|
||||
const { batch, session, currentView, accepted } = createHarness("INSERT INTO users (", "insert");
|
||||
const action = { label: "insert", type: "text" as const, detail: "", boost: 0, batchColumnSelectionAction: true as const, sessionKey: session.key };
|
||||
batch.applyBatchColumnSelection(currentView, action, session.from, session.to);
|
||||
expect(toast).toHaveBeenCalledWith("editor.completion.selectColumnsBeforeInsert", 3000);
|
||||
expect(accepted).not.toHaveBeenCalled();
|
||||
batch.toggleAllBatchColumnSelection(currentView, session.key);
|
||||
batch.applySelectedBatchColumnSelection(currentView);
|
||||
expect(currentView.state.doc.toString()).toMatch(/^INSERT INTO users \(id, name, email\) VALUES \(/);
|
||||
expect(currentView.state.doc.toString()).not.toContain("${");
|
||||
expect(accepted).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("restores selection styles and cancels refresh work when disposed during a drag", () => {
|
||||
const { batch, row, currentView, runtime } = createHarness();
|
||||
const { checkbox } = row(0);
|
||||
document.body.style.userSelect = "text";
|
||||
checkbox.dispatchEvent(new PointerEvent("pointerdown", { button: 0, buttons: 1, isPrimary: true, pointerId: 9, bubbles: true }));
|
||||
expect(document.body.style.userSelect).toBe("none");
|
||||
const remove = vi.spyOn(window, "removeEventListener");
|
||||
batch.dispose();
|
||||
expect(document.body.style.userSelect).toBe("text");
|
||||
expect(remove.mock.calls.map(([event]) => event)).toEqual(expect.arrayContaining(["pointermove", "pointerup", "pointercancel", "blur"]));
|
||||
const dispatch = vi.spyOn(currentView, "dispatch");
|
||||
vi.advanceTimersByTime(2000);
|
||||
expect(dispatch).not.toHaveBeenCalled();
|
||||
expect(runtime.codeMirrorStartCompletion).not.toHaveBeenCalled();
|
||||
expect(batch.applySelectedBatchColumnSelection(currentView)).toBe(false);
|
||||
document.body.style.userSelect = "";
|
||||
});
|
||||
|
||||
it("cancels pending refresh timers and document row guards on disposal", () => {
|
||||
const { batch, session, currentView, runtime, row } = createHarness();
|
||||
const { label } = row(0);
|
||||
batch.toggleAllBatchColumnSelection(currentView, session.key);
|
||||
batch.dispose();
|
||||
vi.advanceTimersByTime(2000);
|
||||
expect(runtime.codeMirrorStartCompletion).not.toHaveBeenCalled();
|
||||
const mouseDown = new MouseEvent("mousedown", { button: 0, bubbles: true, cancelable: true });
|
||||
label.dispatchEvent(mouseDown);
|
||||
expect(mouseDown.defaultPrevented).toBe(false);
|
||||
});
|
||||
|
||||
it("does not reconfigure a replaced editor through an old render timer", () => {
|
||||
const { view, currentView } = createHarness();
|
||||
const dispatch = vi.spyOn(currentView, "dispatch");
|
||||
view.value = null;
|
||||
vi.advanceTimersByTime(1);
|
||||
expect(dispatch).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not consume an INSERT completion before the lazy snippet API is ready", () => {
|
||||
const { batch, session, currentView, accepted, runtime } = createHarness("INSERT INTO users (", "insert");
|
||||
Object.assign(runtime, { codeMirrorSnippetCompletion: undefined });
|
||||
batch.toggleAllBatchColumnSelection(currentView, session.key);
|
||||
batch.applySelectedBatchColumnSelection(currentView);
|
||||
expect(accepted).not.toHaveBeenCalled();
|
||||
expect(currentView.state.doc.toString()).toBe(session.document);
|
||||
expect(batch.expandedRendering).toBe(false);
|
||||
});
|
||||
});
|
||||
+149
@@ -0,0 +1,149 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import { EditorState, Compartment } from "@codemirror/state";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { shallowRef } from "vue";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { createQueryEditorCodeMirrorRuntime } from "../queryEditorCodeMirrorRuntime";
|
||||
import { useQueryEditorCodeMirror } from "../useQueryEditorCodeMirror";
|
||||
|
||||
type Options = Parameters<typeof useQueryEditorCodeMirror>[0];
|
||||
const cleanups: Array<() => void> = [];
|
||||
|
||||
afterEach(() => {
|
||||
for (const cleanup of cleanups.splice(0).reverse()) cleanup();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
function deferred<Value>() {
|
||||
let resolve!: (value: Value) => void;
|
||||
const promise = new Promise<Value>((complete) => {
|
||||
resolve = complete;
|
||||
});
|
||||
return { promise, resolve };
|
||||
}
|
||||
|
||||
function createHarness() {
|
||||
const parent = document.createElement("div");
|
||||
document.body.append(parent);
|
||||
const view = shallowRef<EditorView | null>(null);
|
||||
const runtime = createQueryEditorCodeMirrorRuntime();
|
||||
const editorRef = shallowRef<HTMLElement | null>(parent);
|
||||
const events: string[] = [];
|
||||
const onReady = vi.fn(() => {
|
||||
expect(view.value?.state.doc.toString()).toBe("SELECT 1;");
|
||||
events.push("ready");
|
||||
});
|
||||
const configuration = { parent, state: EditorState.create({ doc: "SELECT 1;" }), onReady };
|
||||
const beforeLoad = vi.fn(() => {
|
||||
events.push("beforeLoad");
|
||||
});
|
||||
const prepare = vi.fn<Options["prepare"]>(async () => {
|
||||
events.push("prepare");
|
||||
return configuration;
|
||||
});
|
||||
const lifecycle = useQueryEditorCodeMirror({ editorRef, view, runtime, beforeLoad, prepare });
|
||||
cleanups.push(() => {
|
||||
lifecycle.dispose();
|
||||
parent.remove();
|
||||
});
|
||||
return { lifecycle, editorRef, view, runtime, beforeLoad, prepare, configuration, onReady, events, parent };
|
||||
}
|
||||
|
||||
describe("QueryEditor lazy CodeMirror runtime", () => {
|
||||
it("keeps unloaded handles empty and publishes initialized handles on the same object", async () => {
|
||||
const runtime = createQueryEditorCodeMirrorRuntime();
|
||||
expect(runtime.editorViewModule).toBeNull();
|
||||
expect(runtime.codeMirrorStartCompletion).toBeNull();
|
||||
expect(runtime.sqlSignatureComp).toBeNull();
|
||||
const modules = await runtime.load();
|
||||
expect(modules.runtime).toBe(runtime);
|
||||
expect(runtime.editorViewModule?.EditorView).toBe(EditorView);
|
||||
expect(runtime.codeMirrorStartCompletion).toBe(modules.startCompletion);
|
||||
expect(runtime.codeMirrorToggleBlockComment).toBe(modules.toggleBlockComment);
|
||||
expect(runtime.sqlSignatureComp).toBeInstanceOf(Compartment);
|
||||
expect(runtime.buildSqlLanguageExtension).toBeNull();
|
||||
});
|
||||
|
||||
it("isolates per-editor compartments and effects while sharing imported functions", async () => {
|
||||
const first = createQueryEditorCodeMirrorRuntime();
|
||||
const second = createQueryEditorCodeMirrorRuntime();
|
||||
await Promise.all([first.load(), second.load()]);
|
||||
expect(first.codeMirrorStartCompletion).toBe(second.codeMirrorStartCompletion);
|
||||
expect(first.completionComp).not.toBe(second.completionComp);
|
||||
expect(first.sqlLanguageComp).not.toBe(second.sqlLanguageComp);
|
||||
expect(first.sqlSignatureComp).not.toBe(second.sqlSignatureComp);
|
||||
expect(first.setSqlDiagnosticsEffect).not.toBe(second.setSqlDiagnosticsEffect);
|
||||
expect(first.statementBoundariesRefreshEffect).not.toBe(second.statementBoundariesRefreshEffect);
|
||||
});
|
||||
});
|
||||
|
||||
describe("QueryEditor initialization lifecycle", () => {
|
||||
it("loads, prepares, creates and notifies in order", async () => {
|
||||
const harness = createHarness();
|
||||
const load = harness.runtime.load;
|
||||
vi.spyOn(harness.runtime, "load").mockImplementation(async () => {
|
||||
harness.events.push("load");
|
||||
return load();
|
||||
});
|
||||
await harness.lifecycle.initialize();
|
||||
expect(harness.events).toEqual(["beforeLoad", "load", "prepare", "ready"]);
|
||||
expect(harness.parent.querySelector(".cm-editor")).toBe(harness.view.value?.dom);
|
||||
const destroy = vi.spyOn(harness.view.value!, "destroy");
|
||||
harness.lifecycle.dispose();
|
||||
expect(destroy).toHaveBeenCalledOnce();
|
||||
expect(harness.parent.querySelector(".cm-editor")).toBeNull();
|
||||
});
|
||||
|
||||
it.each(["missing host", "disposed"])("does not begin initialization when %s", async (reason) => {
|
||||
const harness = createHarness();
|
||||
const load = vi.spyOn(harness.runtime, "load");
|
||||
if (reason === "missing host") harness.editorRef.value = null;
|
||||
else harness.lifecycle.dispose();
|
||||
await harness.lifecycle.initialize();
|
||||
expect(harness.beforeLoad).not.toHaveBeenCalled();
|
||||
expect(load).not.toHaveBeenCalled();
|
||||
expect(harness.prepare).not.toHaveBeenCalled();
|
||||
expect(harness.view.value).toBeNull();
|
||||
});
|
||||
|
||||
it("does not prepare or mount after disposal during lazy loading", async () => {
|
||||
const harness = createHarness();
|
||||
const modules = await harness.runtime.load();
|
||||
const pending = deferred<typeof modules>();
|
||||
vi.spyOn(harness.runtime, "load").mockReturnValue(pending.promise);
|
||||
const initializing = harness.lifecycle.initialize();
|
||||
harness.lifecycle.dispose();
|
||||
pending.resolve(modules);
|
||||
await initializing;
|
||||
expect(harness.prepare).not.toHaveBeenCalled();
|
||||
expect(harness.view.value).toBeNull();
|
||||
expect(harness.onReady).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not create a view after disposal during asynchronous preparation", async () => {
|
||||
const harness = createHarness();
|
||||
const preparing = deferred<void>();
|
||||
const pending = deferred<typeof harness.configuration>();
|
||||
harness.prepare.mockImplementation(() => {
|
||||
preparing.resolve();
|
||||
return pending.promise;
|
||||
});
|
||||
const initializing = harness.lifecycle.initialize();
|
||||
await preparing.promise;
|
||||
harness.lifecycle.dispose();
|
||||
pending.resolve(harness.configuration);
|
||||
await initializing;
|
||||
expect(harness.view.value).toBeNull();
|
||||
expect(harness.onReady).not.toHaveBeenCalled();
|
||||
expect(harness.parent.querySelector(".cm-editor")).toBeNull();
|
||||
});
|
||||
|
||||
it("respects a cancelled configuration", async () => {
|
||||
const harness = createHarness();
|
||||
harness.prepare.mockResolvedValue(undefined);
|
||||
await harness.lifecycle.initialize();
|
||||
expect(harness.view.value).toBeNull();
|
||||
expect(harness.onReady).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
+229
@@ -0,0 +1,229 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import { CompletionContext, insertCompletionText, snippetCompletion } from "@codemirror/autocomplete";
|
||||
import { EditorState } from "@codemirror/state";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { computed, reactive, shallowRef } from "vue";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { useQueryEditorCompletion } from "../useQueryEditorCompletion";
|
||||
import { useQueryEditorCompletionMetadata } from "../useQueryEditorCompletionMetadata";
|
||||
import type { QueryEditorProps } from "../queryEditorTypes";
|
||||
import type { RedisCommandDocumentation } from "@/lib/redis/redisCommandDocs";
|
||||
import type { SqlCompletionTable } from "@/lib/sql/sqlCompletion";
|
||||
|
||||
vi.mock("@/stores/connectionStore", () => ({ COMPLETION_METADATA_CONCURRENCY: 4 }));
|
||||
vi.mock("@/lib/backend/api", () => ({}));
|
||||
|
||||
type Options = Parameters<typeof useQueryEditorCompletion>[0];
|
||||
const cleanups: Array<() => void> = [];
|
||||
const commands: RedisCommandDocumentation[] = [
|
||||
{ name: "GET", arity: 2, keySpecs: [{ beginSearch: { type: "index", index: 1 }, findKeys: { type: "range", lastKey: 0, keyStep: 1, limit: 0 } }] },
|
||||
{ name: "CUSTOM.SERVER.COMMAND", keySpecs: [] },
|
||||
];
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
});
|
||||
afterEach(() => {
|
||||
for (const cleanup of cleanups.splice(0).reverse()) cleanup();
|
||||
vi.clearAllTimers();
|
||||
vi.useRealTimers();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
function createHarness(overrides: Partial<QueryEditorProps> = {}) {
|
||||
const props = reactive<QueryEditorProps>({ modelValue: "SEL", databaseType: "mysql", dialect: "mysql", connectionId: "connection", database: "demo", ...overrides });
|
||||
const parent = document.createElement("div");
|
||||
document.body.append(parent);
|
||||
const currentView = new EditorView({ parent, state: EditorState.create({ doc: props.modelValue, selection: { anchor: props.modelValue.length } }) });
|
||||
const view = shallowRef<EditorView | null>(currentView);
|
||||
const store = {
|
||||
getConfig: vi.fn(() => undefined),
|
||||
lookupLocalCompletionTables: vi.fn((): SqlCompletionTable[] => []),
|
||||
lookupLocalCompletionColumns: vi.fn(() => []),
|
||||
lookupLocalCompletionColumnsByPrefix: vi.fn(() => []),
|
||||
lookupLocalCompletionObjects: vi.fn(() => []),
|
||||
lookupLocalCompletionDatabases: vi.fn(() => []),
|
||||
lookupLocalCompletionSchemas: vi.fn(() => []),
|
||||
lookupLocalCompletionForeignKeys: vi.fn(() => []),
|
||||
listCompletionTables: vi.fn(async (): Promise<SqlCompletionTable[]> => []),
|
||||
listCompletionObjects: vi.fn(async () => []),
|
||||
listCompletionColumns: vi.fn(async () => []),
|
||||
listCompletionSchemas: vi.fn(async () => []),
|
||||
listCompletionDatabases: vi.fn(async () => []),
|
||||
refreshCompletionTables: vi.fn(async () => []),
|
||||
refreshCompletionColumns: vi.fn(async () => []),
|
||||
refreshCompletionSchemas: vi.fn(async () => []),
|
||||
refreshCompletionDatabases: vi.fn(async () => []),
|
||||
listRedisCompletionCommandDocs: vi.fn(async () => commands),
|
||||
listRedisCompletionKeys: vi.fn(async () => ["user:1"]),
|
||||
listMongoCompletionCollections: vi.fn(async () => ["users"]),
|
||||
listMongoCompletionFields: vi.fn(async () => []),
|
||||
listElasticsearchCompletionIndices: vi.fn(async () => ["users"]),
|
||||
listElasticsearchCompletionFields: vi.fn(async () => []),
|
||||
};
|
||||
const connectionStore = store as unknown as Options["connectionStore"];
|
||||
const settings = reactive({ editorSettings: { completionTriggerMode: "positional", snippets: [], sqlFormatter: { keywordCase: "upper", functionCase: "upper" }, autoAliasTables: false, generateSqlQuoteIdentifiers: false } });
|
||||
const metadata = useQueryEditorCompletionMetadata({ props, view, connectionStore, sqlBehaviorDialect: () => props.dialect, remoteLatencyBudgetMs: 40, maxCompletionTables: 100, onDemandMinPrefix: 2, semanticCompletionEnabled: false });
|
||||
const startCompletion = vi.fn(() => true);
|
||||
const runtime: Options["runtime"] = { codeMirrorStartCompletion: startCompletion, codeMirrorInsertCompletionText: insertCompletionText, codeMirrorSnippetCompletion: snippetCompletion, codeMirrorCompletionStatus: () => null, imeCompositionActive: false };
|
||||
const batchSelection = {
|
||||
clearBatchColumnSelectionSession: vi.fn(),
|
||||
prepareBatchColumnSelectionSession: vi.fn(() => null),
|
||||
isBatchColumnSelectionAction: () => false,
|
||||
batchColumnSelectionMarkerForItem: () => undefined,
|
||||
cacheBatchColumnSelectionOption: (_marker: unknown, option: unknown) => option,
|
||||
} as unknown as Options["batchSelection"];
|
||||
const completion = useQueryEditorCompletion({
|
||||
props,
|
||||
view,
|
||||
connectionStore,
|
||||
settingsStore: settings as Options["settingsStore"],
|
||||
sqlDriverProfile: computed(() => undefined),
|
||||
t: ((key: string) => key) as Options["t"],
|
||||
metadata,
|
||||
batchSelection,
|
||||
runtime,
|
||||
isEditorComposing: () => runtime.imeCompositionActive,
|
||||
debounceDelayMs: 30,
|
||||
triggerDeferDelayMs: 25,
|
||||
maxCompletionTables: 100,
|
||||
onDemandTableLimit: 100,
|
||||
semanticCompletionEnabled: false,
|
||||
});
|
||||
cleanups.push(() => {
|
||||
completion.clearDeferredCompletionTrigger();
|
||||
completion.invalidateRequests();
|
||||
currentView.destroy();
|
||||
parent.remove();
|
||||
});
|
||||
const provide = (explicit = true) => completion.provideSqlCompletions(new CompletionContext(currentView.state, currentView.state.selection.main.head, explicit));
|
||||
return { props, currentView, view, store, settings, runtime, completion, provide, startCompletion };
|
||||
}
|
||||
|
||||
describe("QueryEditor completion provider ownership", () => {
|
||||
it("keeps manual completion available while automatic completion is disabled", async () => {
|
||||
const { settings, provide, completion, currentView, startCompletion } = createHarness({ database: undefined });
|
||||
settings.editorSettings.completionTriggerMode = "manual";
|
||||
expect(await provide(false)).toBeNull();
|
||||
completion.activeOrigin = null;
|
||||
const manual = await provide(true);
|
||||
expect(manual?.options.map((option) => option.label)).toContain("SELECT");
|
||||
expect(completion.triggerSqlCompletion(currentView)).toBe(true);
|
||||
expect(startCompletion).toHaveBeenCalledWith(currentView);
|
||||
});
|
||||
|
||||
it("does not request metadata or start completion during IME composition", async () => {
|
||||
const { runtime, provide, completion, currentView, store, startCompletion } = createHarness({ databaseType: "redis" });
|
||||
runtime.imeCompositionActive = true;
|
||||
expect(await provide()).toBeNull();
|
||||
expect(completion.triggerSqlCompletion(currentView)).toBe(false);
|
||||
completion.scheduleSqlCompletionStart(currentView);
|
||||
await vi.advanceTimersByTimeAsync(1);
|
||||
expect(startCompletion).not.toHaveBeenCalled();
|
||||
expect(store.listRedisCompletionCommandDocs).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each(["cursor", "document", "view", "composition", "cancel"])("rejects deferred triggers after a %s change", async (change) => {
|
||||
const { currentView, view, runtime, completion, startCompletion } = createHarness();
|
||||
completion.scheduleDeferredCompletionTrigger(currentView, "L", "");
|
||||
if (change === "cursor") currentView.dispatch({ selection: { anchor: 0 } });
|
||||
if (change === "document") currentView.dispatch({ changes: { from: 0, insert: " " } });
|
||||
if (change === "view") view.value = null;
|
||||
if (change === "composition") runtime.imeCompositionActive = true;
|
||||
if (change === "cancel") completion.clearDeferredCompletionTrigger();
|
||||
await vi.advanceTimersByTimeAsync(50);
|
||||
expect(startCompletion).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("coalesces valid deferred input and reads late runtime initialization", async () => {
|
||||
const { currentView, runtime, completion, startCompletion } = createHarness();
|
||||
runtime.codeMirrorStartCompletion = null;
|
||||
expect(completion.triggerSqlCompletion(currentView)).toBe(false);
|
||||
completion.scheduleDeferredCompletionTrigger(currentView, "E", "");
|
||||
completion.scheduleDeferredCompletionTrigger(currentView, "L", "");
|
||||
runtime.codeMirrorStartCompletion = startCompletion;
|
||||
await vi.advanceTimersByTimeAsync(50);
|
||||
expect(startCompletion).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("consumes completion suppression once and respects expiry", () => {
|
||||
const { completion } = createHarness();
|
||||
completion.suppressAutoStartUntil = Date.now() + 100;
|
||||
expect(completion.consumeSqlCompletionAutoStartSuppression()).toBe(true);
|
||||
expect(completion.consumeSqlCompletionAutoStartSuppression()).toBe(false);
|
||||
completion.suppressAutoStartUntil = Date.now() - 1;
|
||||
expect(completion.consumeSqlCompletionAutoStartSuppression()).toBe(false);
|
||||
});
|
||||
|
||||
it("uses only server-provided Redis commands and never fabricates fallback metadata", async () => {
|
||||
const { store, provide } = createHarness({ databaseType: "redis", database: undefined, modelValue: "" });
|
||||
const result = await provide();
|
||||
expect(result?.options.map((option) => option.label)).toEqual(expect.arrayContaining(["GET", "CUSTOM.SERVER.COMMAND"]));
|
||||
expect(result?.options.map((option) => option.label)).not.toContain("SET");
|
||||
expect(store.listRedisCompletionCommandDocs).toHaveBeenCalledWith("connection", "0");
|
||||
expect(store.listRedisCompletionKeys).not.toHaveBeenCalled();
|
||||
store.listRedisCompletionCommandDocs.mockRejectedValue(new Error("unavailable"));
|
||||
expect(await provide()).toBeNull();
|
||||
});
|
||||
|
||||
it("loads Redis keys only for a key argument with a resolved database", async () => {
|
||||
const { props, store, provide } = createHarness({ databaseType: "redis", database: "", modelValue: "GET " });
|
||||
await provide();
|
||||
expect(store.listRedisCompletionKeys).not.toHaveBeenCalled();
|
||||
props.database = "3";
|
||||
const result = await provide();
|
||||
expect(store.listRedisCompletionKeys).toHaveBeenCalledWith("connection", "3");
|
||||
expect(result?.options.map((option) => option.label)).toContain("user:1");
|
||||
});
|
||||
|
||||
it("rejects stale Mongo collection loads after request invalidation", async () => {
|
||||
const { store, provide, completion } = createHarness({ databaseType: "mongodb", modelValue: "db.us" });
|
||||
let resolve!: (collections: string[]) => void;
|
||||
store.listMongoCompletionCollections.mockReturnValue(
|
||||
new Promise((complete) => {
|
||||
resolve = complete;
|
||||
}),
|
||||
);
|
||||
const pending = provide();
|
||||
expect(store.listMongoCompletionCollections).toHaveBeenCalledWith("connection", "demo");
|
||||
completion.invalidateRequests();
|
||||
resolve(["users"]);
|
||||
expect(await pending).toBeNull();
|
||||
store.listMongoCompletionCollections.mockResolvedValue(["users"]);
|
||||
expect((await provide())?.options.map((option) => option.label)).toContain("users");
|
||||
});
|
||||
|
||||
it.each(["mongodb", "elasticsearch", "easysearch"] as const)("preserves %s completion and tolerates metadata failures", async (databaseType) => {
|
||||
const { store, provide } = createHarness({ databaseType, modelValue: databaseType === "mongodb" ? "db.us" : "GET /us" });
|
||||
expect((await provide())?.options.map((option) => option.label)).toContain("users");
|
||||
store.listMongoCompletionCollections.mockRejectedValue(new Error("offline"));
|
||||
store.listElasticsearchCompletionIndices.mockRejectedValue(new Error("offline"));
|
||||
const fallback = await provide();
|
||||
expect(fallback?.options.some((option) => option.label === "users") ?? false).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects pending SQL metadata after the editor invalidates the request", async () => {
|
||||
const { store, completion, provide } = createHarness({ modelValue: "SELECT * FROM us" });
|
||||
let resolve!: (tables: SqlCompletionTable[]) => void;
|
||||
store.listCompletionTables.mockReturnValue(
|
||||
new Promise((complete) => {
|
||||
resolve = complete;
|
||||
}),
|
||||
);
|
||||
const pending = provide();
|
||||
await vi.advanceTimersByTimeAsync(31);
|
||||
expect(store.listCompletionTables).toHaveBeenCalled();
|
||||
completion.invalidateRequests();
|
||||
resolve([{ name: "users" }]);
|
||||
expect(await pending).toBeNull();
|
||||
});
|
||||
|
||||
it.each(["redis", "mongodb", "mysql"] as const)("does not query %s metadata without a connection", async (databaseType) => {
|
||||
const { store, provide } = createHarness({ databaseType, connectionId: undefined });
|
||||
expect(await provide()).toBeNull();
|
||||
expect(store.listCompletionTables).not.toHaveBeenCalled();
|
||||
expect(store.listMongoCompletionCollections).not.toHaveBeenCalled();
|
||||
expect(store.listRedisCompletionCommandDocs).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
+177
@@ -0,0 +1,177 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import { EditorSelection, EditorState } from "@codemirror/state";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { reactive } from "vue";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { createQueryEditorCodeMirrorRuntime } from "../queryEditorCodeMirrorRuntime";
|
||||
import { useQueryEditorCompletionKeys } from "../useQueryEditorCompletionKeys";
|
||||
import type { QueryEditorProps } from "../queryEditorTypes";
|
||||
|
||||
type Options = Parameters<typeof useQueryEditorCompletionKeys>[0];
|
||||
const cleanups: Array<() => void> = [];
|
||||
|
||||
beforeEach(() => vi.useFakeTimers());
|
||||
afterEach(() => {
|
||||
for (const cleanup of cleanups.splice(0).reverse()) cleanup();
|
||||
vi.clearAllTimers();
|
||||
vi.useRealTimers();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
function createHarness(overrides: Partial<QueryEditorProps> = {}) {
|
||||
const props = reactive<QueryEditorProps>({ modelValue: "abc", databaseType: "postgres", ...overrides });
|
||||
const host = document.createElement("div");
|
||||
document.body.append(host);
|
||||
const view = new EditorView({ parent: host, state: EditorState.create({ doc: props.modelValue, selection: { anchor: props.modelValue.length }, extensions: [EditorState.allowMultipleSelections.of(true)] }) });
|
||||
const runtime = createQueryEditorCodeMirrorRuntime();
|
||||
const status = vi.fn<NonNullable<typeof runtime.codeMirrorCompletionStatus>>(() => null);
|
||||
const accept = vi.fn(() => false);
|
||||
const snippet = vi.fn(() => false);
|
||||
const indent = vi.fn(() => true);
|
||||
const composing = vi.fn(() => false);
|
||||
const batch = vi.fn(() => false);
|
||||
const newline = vi.fn((currentView: EditorView) => {
|
||||
currentView.dispatch(currentView.state.replaceSelection("\n"));
|
||||
return true;
|
||||
});
|
||||
Object.assign(runtime, {
|
||||
codeMirrorCompletionStatus: status,
|
||||
codeMirrorAcceptCompletion: accept,
|
||||
codeMirrorNextSnippetField: snippet,
|
||||
codeMirrorIndentMore: indent,
|
||||
codeMirrorCloseCompletion: vi.fn(() => false),
|
||||
codeMirrorSelectedCompletionIndex: vi.fn(() => null),
|
||||
codeMirrorSelectFirstCompletion: vi.fn(() => false),
|
||||
codeMirrorInsertNewlineKeepIndent: newline,
|
||||
});
|
||||
const settings = reactive({ editorSettings: { sqlFormatter: { useTabs: false, tabWidth: 2 }, shortcuts: { acceptCompletion: "Tab" }, selectFirstCompletionOnOpen: false, sqlServerSpaceConfirmsCompletion: true } });
|
||||
const completion = { suppressAutoStartUntil: 0 };
|
||||
const keys = useQueryEditorCompletionKeys({ props, settingsStore: settings as Options["settingsStore"], runtime, completion, batchSelection: { applySelectedBatchColumnSelection: batch }, isEditorComposing: composing, retryDelayMs: 5, tabMaxWaitMs: 40, enterMaxWaitMs: 20 });
|
||||
cleanups.push(() => {
|
||||
keys.clearPendingCompletionEnter();
|
||||
keys.clearPendingCompletionTab();
|
||||
view.destroy();
|
||||
host.remove();
|
||||
});
|
||||
return { props, view, runtime, status, accept, snippet, indent, composing, batch, newline, settings, completion, keys };
|
||||
}
|
||||
|
||||
describe("QueryEditor completion-key ownership", () => {
|
||||
it.each(["handleTab", "handleEnter", "acceptCompletionOrNextSnippetField"] as const)("leaves %s to an active IME", (method) => {
|
||||
const { keys, view, composing, accept, snippet, indent } = createHarness();
|
||||
composing.mockReturnValue(true);
|
||||
expect(keys[method](view)).toBe(false);
|
||||
expect(accept).not.toHaveBeenCalled();
|
||||
expect(snippet).not.toHaveBeenCalled();
|
||||
expect(indent).not.toHaveBeenCalled();
|
||||
expect(view.state.doc.toString()).toBe("abc");
|
||||
});
|
||||
|
||||
it("preserves ordinary Tab indentation when completion acceptance is remapped", () => {
|
||||
const { keys, view, settings, status, accept } = createHarness();
|
||||
settings.editorSettings.shortcuts.acceptCompletion = "Enter";
|
||||
status.mockReturnValue("active");
|
||||
expect(keys.handleTab(view)).toBe(true);
|
||||
expect(view.state.doc.toString()).toBe("abc ");
|
||||
expect(accept).not.toHaveBeenCalled();
|
||||
settings.editorSettings.sqlFormatter.useTabs = true;
|
||||
expect(keys.editorIndentUnit()).toBe("\t");
|
||||
});
|
||||
|
||||
it("prioritizes a selected snippet field over ordinary indentation", () => {
|
||||
const { keys, view, snippet, indent, accept } = createHarness();
|
||||
view.dispatch({ selection: { anchor: 0, head: 3 } });
|
||||
snippet.mockReturnValueOnce(true);
|
||||
expect(keys.handleTab(view)).toBe(true);
|
||||
expect(indent).not.toHaveBeenCalled();
|
||||
expect(keys.handleTab(view)).toBe(true);
|
||||
expect(indent).toHaveBeenCalledOnce();
|
||||
expect(accept).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each(["handleEnter", "acceptCompletionOrNextSnippetField"] as const)("gives checked-column insertion priority in %s", (method) => {
|
||||
const { keys, view, status, batch, accept } = createHarness();
|
||||
status.mockReturnValue("active");
|
||||
batch.mockReturnValue(true);
|
||||
expect(keys[method](view)).toBe(true);
|
||||
expect(batch).toHaveBeenCalledWith(view);
|
||||
expect(accept).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("accepts a pending Tab only after completion becomes available", async () => {
|
||||
const { keys, view, status, runtime, accept, snippet } = createHarness();
|
||||
status.mockReturnValue("pending");
|
||||
expect(keys.handleTab(view)).toBe(true);
|
||||
expect(accept).not.toHaveBeenCalled();
|
||||
status.mockReturnValue("active");
|
||||
runtime.codeMirrorSelectedCompletionIndex = () => 0;
|
||||
accept.mockReturnValue(true);
|
||||
await vi.advanceTimersByTimeAsync(5);
|
||||
expect(accept).toHaveBeenCalledOnce();
|
||||
expect(snippet).not.toHaveBeenCalled();
|
||||
expect(view.state.doc.toString()).toBe("abc");
|
||||
});
|
||||
|
||||
it("falls back to normal Tab once the pending completion budget expires", async () => {
|
||||
const { keys, view, status, snippet } = createHarness();
|
||||
status.mockReturnValue("pending");
|
||||
keys.handleTab(view);
|
||||
await vi.advanceTimersByTimeAsync(45);
|
||||
expect(snippet).toHaveBeenCalledOnce();
|
||||
expect(view.state.doc.toString()).toBe("abc ");
|
||||
});
|
||||
|
||||
it.each(["document", "secondary-selection", "composition", "cancel"])("invalidates queued Tab after %s changes", async (change) => {
|
||||
const { keys, view, status, composing, accept, snippet } = createHarness();
|
||||
status.mockReturnValue("pending");
|
||||
keys.handleTab(view);
|
||||
if (change === "document") view.dispatch({ changes: { from: 0, insert: "x" } });
|
||||
if (change === "secondary-selection") view.dispatch({ selection: EditorSelection.create([EditorSelection.cursor(0), EditorSelection.cursor(3)], 1) });
|
||||
if (change === "composition") composing.mockReturnValue(true);
|
||||
if (change === "cancel") keys.clearPendingCompletionTab();
|
||||
const document = view.state.doc.toString();
|
||||
await vi.advanceTimersByTimeAsync(50);
|
||||
expect(view.state.doc.toString()).toBe(document);
|
||||
expect(accept).not.toHaveBeenCalled();
|
||||
expect(snippet).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("inserts one newline and suppresses automatic completion after an Enter retry expires", async () => {
|
||||
const { keys, view, status, settings, newline, completion } = createHarness();
|
||||
status.mockReturnValue("active");
|
||||
settings.editorSettings.selectFirstCompletionOnOpen = true;
|
||||
expect(keys.handleEnter(view)).toBe(true);
|
||||
expect(newline).not.toHaveBeenCalled();
|
||||
await vi.advanceTimersByTimeAsync(25);
|
||||
expect(newline).toHaveBeenCalledOnce();
|
||||
expect(view.state.doc.toString()).toBe("abc\n");
|
||||
expect(completion.suppressAutoStartUntil).toBeGreaterThan(Date.now());
|
||||
});
|
||||
|
||||
it("cancels Enter retries without cancelling another editor's pending Tab", async () => {
|
||||
const first = createHarness();
|
||||
const second = createHarness();
|
||||
first.settings.editorSettings.selectFirstCompletionOnOpen = true;
|
||||
first.status.mockReturnValue("active");
|
||||
second.status.mockReturnValue("pending");
|
||||
first.keys.handleEnter(first.view);
|
||||
second.keys.handleTab(second.view);
|
||||
first.keys.clearPendingCompletionEnter();
|
||||
await vi.advanceTimersByTimeAsync(50);
|
||||
expect(first.view.state.doc.toString()).toBe("abc");
|
||||
expect(first.newline).not.toHaveBeenCalled();
|
||||
expect(second.view.state.doc.toString()).toBe("abc ");
|
||||
});
|
||||
|
||||
it.each(["users", "users "])("preserves SQL Server Space acceptance and existing whitespace in %s", (sql) => {
|
||||
const { keys, view, runtime, status, accept } = createHarness({ modelValue: sql, databaseType: "sqlserver" });
|
||||
view.dispatch({ selection: { anchor: 5 } });
|
||||
status.mockReturnValue("active");
|
||||
runtime.codeMirrorSelectedCompletion = () => ({ label: "users", type: "table" });
|
||||
accept.mockReturnValue(true);
|
||||
expect(keys.acceptSqlServerCompletionOnSpace(view)).toBe(true);
|
||||
expect(view.state.doc.toString()).toBe("users ");
|
||||
expect(view.state.selection.main.head).toBe(6);
|
||||
});
|
||||
});
|
||||
+137
@@ -0,0 +1,137 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import { EditorState } from "@codemirror/state";
|
||||
import type { EditorView } from "@codemirror/view";
|
||||
import { reactive, shallowRef } from "vue";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { useQueryEditorCompletionMetadata } from "../useQueryEditorCompletionMetadata";
|
||||
import type { QueryEditorProps } from "../queryEditorTypes";
|
||||
import type { SqlCompletionColumn, SqlCompletionTable } from "@/lib/sql/sqlCompletion";
|
||||
|
||||
vi.mock("@/stores/connectionStore", () => ({ COMPLETION_METADATA_CONCURRENCY: 4 }));
|
||||
vi.mock("@/lib/backend/api", () => ({}));
|
||||
|
||||
type Options = Parameters<typeof useQueryEditorCompletionMetadata>[0];
|
||||
const columns: SqlCompletionColumn[] = [{ name: "id", table: "users", dataType: "int" }];
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
function createHarness(overrides: Partial<QueryEditorProps> = {}) {
|
||||
const props = reactive<QueryEditorProps>({ modelValue: "SELECT id FROM users", databaseType: "postgres", dialect: "postgres", connectionId: "connection", database: "demo", schema: "public", ...overrides });
|
||||
const store = {
|
||||
getConfig: vi.fn(() => undefined),
|
||||
lookupLocalCompletionColumns: vi.fn((): SqlCompletionColumn[] => []),
|
||||
listCompletionColumns: vi.fn(async (): Promise<SqlCompletionColumn[]> => []),
|
||||
lookupLocalCompletionTables: vi.fn((): SqlCompletionTable[] => []),
|
||||
listCompletionTables: vi.fn(async (): Promise<SqlCompletionTable[]> => []),
|
||||
};
|
||||
const metadata = useQueryEditorCompletionMetadata({
|
||||
props,
|
||||
view: shallowRef<EditorView | null>(null),
|
||||
connectionStore: store as unknown as Options["connectionStore"],
|
||||
sqlBehaviorDialect: () => props.dialect,
|
||||
remoteLatencyBudgetMs: 40,
|
||||
maxCompletionTables: 100,
|
||||
onDemandMinPrefix: 2,
|
||||
semanticCompletionEnabled: true,
|
||||
});
|
||||
return { metadata, store, props };
|
||||
}
|
||||
|
||||
describe("QueryEditor completion metadata ownership", () => {
|
||||
it.each(["getEditorSqlCompletionContext", "getEditorSemanticModel"] as const)("keys %s by document, editor state, position and dialect", (method) => {
|
||||
const { metadata, props } = createHarness();
|
||||
const state = EditorState.create({ doc: props.modelValue });
|
||||
const first = metadata[method](props.modelValue, 8, state);
|
||||
expect(first).not.toBeNull();
|
||||
expect(metadata[method](props.modelValue, 8, state)).toBe(first);
|
||||
const moved = metadata[method](props.modelValue, 9, state);
|
||||
expect(moved).not.toBe(first);
|
||||
const selected = state.update({ selection: { anchor: 3 } }).state;
|
||||
expect(selected.doc).toBe(state.doc);
|
||||
expect(metadata[method](props.modelValue, 9, selected)).not.toBe(moved);
|
||||
props.dialect = "mysql";
|
||||
const changedDialect = metadata[method](props.modelValue, 9, selected);
|
||||
expect(metadata[method](props.modelValue, 9, selected)).toBe(changedDialect);
|
||||
props.databaseType = "mysql";
|
||||
expect(metadata[method](props.modelValue, 9, selected)).not.toBe(changedDialect);
|
||||
const edited = state.update({ changes: { from: 0, insert: " " } }).state;
|
||||
expect(metadata[method](edited.doc.toString(), 9, edited)).not.toBe(first);
|
||||
});
|
||||
|
||||
it("prefers local columns and shares successful loads with subsequent callers", async () => {
|
||||
const { metadata, store } = createHarness();
|
||||
store.lookupLocalCompletionColumns.mockReturnValue(columns);
|
||||
expect(await metadata.ensureColumnsForTable({ name: "users" })).toBe(true);
|
||||
expect(metadata.cachedColumnsByTable.get("public.users")).toBe(columns);
|
||||
expect(metadata.loadedColumnsByTable.has("public.users")).toBe(true);
|
||||
expect(metadata.getInsertValueHintTableColumns("users")).toEqual(["id"]);
|
||||
await metadata.ensureColumnsForTable({ name: "users" });
|
||||
expect(store.lookupLocalCompletionColumns).toHaveBeenCalledOnce();
|
||||
expect(store.listCompletionColumns).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("retries empty remote responses rather than marking them as loaded", async () => {
|
||||
const { metadata, store } = createHarness();
|
||||
store.listCompletionColumns.mockResolvedValueOnce([]).mockResolvedValueOnce(columns);
|
||||
await metadata.ensureColumnsForTable({ name: "users" });
|
||||
expect(metadata.cachedColumnsByTable.has("public.users")).toBe(false);
|
||||
expect(metadata.loadedColumnsByTable.size).toBe(0);
|
||||
await metadata.ensureColumnsForTable({ name: "users" });
|
||||
expect(store.listCompletionColumns).toHaveBeenCalledTimes(2);
|
||||
expect(metadata.cachedColumnsByTable.get("public.users")).toBe(columns);
|
||||
});
|
||||
|
||||
it("isolates quoted names and prefix caches by table and schema", () => {
|
||||
const { metadata } = createHarness();
|
||||
const table = { name: "users", schema: "public" };
|
||||
expect(metadata.completionCacheKey({ ...table, nameQuoted: true })).not.toBe(metadata.completionCacheKey(table));
|
||||
metadata.cachedPrefixColumnsByTable.set(metadata.completionPrefixCacheKey(table, undefined, "us"), [
|
||||
{ name: "user_id", table: "users" },
|
||||
{ name: "username", table: "users" },
|
||||
]);
|
||||
expect(metadata.lookupCachedPrefixColumns(table, undefined, " USER_ ")).toEqual([{ name: "user_id", table: "users" }]);
|
||||
expect(metadata.lookupCachedPrefixColumns({ ...table, schema: "archive" }, undefined, "user_")).toBeUndefined();
|
||||
});
|
||||
|
||||
it("returns local tables within the latency budget but still merges scoped remote metadata", async () => {
|
||||
vi.useFakeTimers();
|
||||
const { metadata, store } = createHarness({ catalog: "catalog" });
|
||||
store.lookupLocalCompletionTables.mockReturnValue([{ name: "local", schema: "public" }]);
|
||||
let resolve!: (tables: SqlCompletionTable[]) => void;
|
||||
store.listCompletionTables.mockReturnValue(
|
||||
new Promise((complete) => {
|
||||
resolve = complete;
|
||||
}),
|
||||
);
|
||||
const loading = metadata.listCompletionTablesWithLatencyBudget("connection", "demo", "", 100, "public");
|
||||
await vi.advanceTimersByTimeAsync(40);
|
||||
expect(await loading).toEqual([{ name: "local", schema: "public", database: "demo", catalog: "catalog" }]);
|
||||
resolve([{ name: "remote", schema: "public" }]);
|
||||
await Promise.resolve();
|
||||
expect(metadata.cachedTables).toEqual([{ name: "remote", schema: "public", database: "demo", catalog: "catalog" }]);
|
||||
});
|
||||
|
||||
it("clears shared maps in place and exposes replacement table arrays live", async () => {
|
||||
const { metadata, store } = createHarness();
|
||||
const cachedColumns = metadata.cachedColumnsByTable;
|
||||
store.lookupLocalCompletionColumns.mockReturnValue(columns);
|
||||
await metadata.ensureColumnsForTable({ name: "users" });
|
||||
metadata.cachedTables = [{ name: "users" }];
|
||||
metadata.cachedPrefixColumnsByTable.set("prefix", columns);
|
||||
metadata.cachedForeignKeysByTable.set("table", []);
|
||||
metadata.cachedCompletionObjectsByScope.set("scope", []);
|
||||
expect(metadata.cachedTables).toEqual([{ name: "users" }]);
|
||||
metadata.refreshCompletionCache();
|
||||
expect(metadata.cachedColumnsByTable).toBe(cachedColumns);
|
||||
expect(cachedColumns.size).toBe(0);
|
||||
expect(metadata.cachedPrefixColumnsByTable.size).toBe(0);
|
||||
expect(metadata.cachedForeignKeysByTable.size).toBe(0);
|
||||
expect(metadata.cachedCompletionObjectsByScope.size).toBe(0);
|
||||
expect(metadata.loadedColumnsByTable.size).toBe(0);
|
||||
expect(metadata.cachedTables).toEqual([]);
|
||||
});
|
||||
});
|
||||
+218
@@ -0,0 +1,218 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import { computed, createApp, h, reactive, shallowRef } from "vue";
|
||||
import { EditorState, StateEffect } from "@codemirror/state";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { useQueryEditorDiagnostics } from "../useQueryEditorDiagnostics";
|
||||
import type { SqlSemanticDiagnostic } from "@/lib/sql/semantic/diagnostics";
|
||||
import type { QueryEditorProps } from "../queryEditorTypes";
|
||||
import type { SqlReferenceAnalysis } from "@/types/database";
|
||||
|
||||
const { analyze, buildDiagnostics } = vi.hoisted(() => ({ analyze: vi.fn(), buildDiagnostics: vi.fn() }));
|
||||
vi.mock("@/lib/backend/api", () => ({ analyzeSqlReferences: analyze }));
|
||||
vi.mock("@/lib/sql/semantic/diagnostics", async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import("@/lib/sql/semantic/diagnostics")>()),
|
||||
buildSqlSemanticDiagnostics: buildDiagnostics,
|
||||
}));
|
||||
|
||||
type Options = Parameters<typeof useQueryEditorDiagnostics>[0];
|
||||
const cleanups: Array<() => void> = [];
|
||||
const diagnostic: SqlSemanticDiagnostic = { message: "missing field", severity: "error", span: { start_line: 1, start_column: 8, end_line: 1, end_column: 15 } };
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
analyze.mockResolvedValue({ tables: [], columns: [] });
|
||||
buildDiagnostics.mockReturnValue([diagnostic]);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
for (const cleanup of cleanups.splice(0).reverse()) cleanup();
|
||||
vi.clearAllTimers();
|
||||
vi.useRealTimers();
|
||||
vi.restoreAllMocks();
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
function createHarness(overrides: Partial<QueryEditorProps> = {}) {
|
||||
const props = reactive<QueryEditorProps>({ modelValue: "SELECT missing;", databaseType: "mysql", dialect: "mysql", connectionId: "connection", database: "demo", ...overrides });
|
||||
const parent = document.createElement("div");
|
||||
document.body.append(parent);
|
||||
const currentView = new EditorView({ parent, state: EditorState.create({ doc: props.modelValue }) });
|
||||
const view = shallowRef<EditorView | null>(currentView);
|
||||
const runtime: Options["runtime"] = { editorIsActive: true, executableStatementRangeCache: null, setSqlDiagnosticsEffect: StateEffect.define<SqlSemanticDiagnostic[]>(), diagnosticComp: null, buildSqlDiagnosticExtension: null, codeMirrorCompletionStatus: () => null };
|
||||
const settingsStore = { editorSettings: { sqlSemanticDiagnosticsEnabled: true } } as Options["settingsStore"];
|
||||
let diagnostics!: ReturnType<typeof useQueryEditorDiagnostics>;
|
||||
const host = document.createElement("div");
|
||||
const app = createApp({
|
||||
setup() {
|
||||
diagnostics = useQueryEditorDiagnostics({
|
||||
props,
|
||||
view,
|
||||
runtime,
|
||||
settingsStore,
|
||||
connectionStore: { connectionIdentifierQuote: () => "`" } as Options["connectionStore"],
|
||||
sqlDriverProfile: computed(() => undefined),
|
||||
sqlStatementParameterOptions: () => ({}),
|
||||
sqlBehaviorDialect: () => props.dialect,
|
||||
semanticCompletionEnabled: false,
|
||||
maxCompletionTables: 100,
|
||||
metadata: {
|
||||
cachedTables: [],
|
||||
cachedColumnsByTable: new Map(),
|
||||
loadedColumnsByTable: new Set(),
|
||||
usesOracleSessionCompletionColumns: () => false,
|
||||
findExactSemanticDiagnosticTable: vi.fn().mockResolvedValue(null),
|
||||
completionCacheKey: (table) => table.name,
|
||||
ensureColumnsForTable: vi.fn().mockResolvedValue(false),
|
||||
isMissingTableMetadataError: () => false,
|
||||
},
|
||||
});
|
||||
return () => h("div");
|
||||
},
|
||||
});
|
||||
app.mount(host);
|
||||
let mounted = true;
|
||||
const unmount = () => {
|
||||
if (!mounted) return;
|
||||
mounted = false;
|
||||
app.unmount();
|
||||
};
|
||||
cleanups.push(() => {
|
||||
unmount();
|
||||
currentView.destroy();
|
||||
parent.remove();
|
||||
});
|
||||
return { diagnostics, props, runtime, settingsStore, currentView, unmount };
|
||||
}
|
||||
|
||||
describe("QueryEditor diagnostic scheduling ownership", () => {
|
||||
it("coalesces timers and shares the latest executable statement cache", async () => {
|
||||
const { diagnostics, currentView, runtime } = createHarness();
|
||||
diagnostics.scheduleSemanticDiagnostics(50);
|
||||
diagnostics.scheduleSemanticDiagnostics(100);
|
||||
await vi.advanceTimersByTimeAsync(99);
|
||||
expect(analyze).not.toHaveBeenCalled();
|
||||
await vi.advanceTimersByTimeAsync(1);
|
||||
expect(analyze).toHaveBeenCalledOnce();
|
||||
expect(diagnostics.diagnostics).toEqual([diagnostic]);
|
||||
expect(runtime.executableStatementRangeCache).not.toBeNull();
|
||||
const cache = runtime.executableStatementRangeCache;
|
||||
diagnostics.scheduleSemanticDiagnostics(0);
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
expect(runtime.executableStatementRangeCache).toBe(cache);
|
||||
expect(currentView.state.doc.toString()).toBe("SELECT missing;");
|
||||
});
|
||||
|
||||
it("clears old decorations and pending work when SQL diagnostics are disabled", async () => {
|
||||
const { diagnostics, settingsStore } = createHarness();
|
||||
diagnostics.setSemanticDiagnostics([diagnostic]);
|
||||
diagnostics.scheduleSemanticDiagnostics(10);
|
||||
settingsStore.editorSettings.sqlSemanticDiagnosticsEnabled = false;
|
||||
diagnostics.scheduleSemanticDiagnostics(0);
|
||||
await vi.advanceTimersByTimeAsync(20);
|
||||
expect(diagnostics.diagnostics).toEqual([]);
|
||||
expect(analyze).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not schedule work while the editor is inactive", async () => {
|
||||
const { diagnostics, runtime } = createHarness();
|
||||
runtime.editorIsActive = false;
|
||||
diagnostics.scheduleSemanticDiagnostics(0);
|
||||
await vi.advanceTimersByTimeAsync(2000);
|
||||
expect(analyze).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each([{ connectionId: undefined }, { database: undefined }, { modelValue: " " }, { databaseType: "elasticsearch" as const }])("clears diagnostics without SQL analysis for unsupported context %j", async (overrides) => {
|
||||
const { diagnostics } = createHarness(overrides);
|
||||
diagnostics.setSemanticDiagnostics([diagnostic]);
|
||||
diagnostics.scheduleSemanticDiagnostics(0);
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
expect(diagnostics.diagnostics).toEqual([]);
|
||||
expect(analyze).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects an old analysis after document invalidation", async () => {
|
||||
let resolve!: (analysis: SqlReferenceAnalysis) => void;
|
||||
analyze.mockImplementationOnce(
|
||||
() =>
|
||||
new Promise<SqlReferenceAnalysis>((done) => {
|
||||
resolve = done;
|
||||
}),
|
||||
);
|
||||
const { diagnostics, currentView } = createHarness();
|
||||
diagnostics.scheduleSemanticDiagnostics(0);
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
expect(analyze).toHaveBeenCalledOnce();
|
||||
currentView.dispatch({ changes: { from: 0, to: currentView.state.doc.length, insert: "SELECT 1;" } });
|
||||
diagnostics.invalidateSemanticDiagnosticsForDocumentChange();
|
||||
resolve({ tables: [], columns: [] });
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
expect(buildDiagnostics).not.toHaveBeenCalled();
|
||||
expect(diagnostics.diagnostics).toEqual([]);
|
||||
});
|
||||
|
||||
it("invalidates in-flight analysis on unmount and cancels scheduled work", async () => {
|
||||
let resolve!: (analysis: SqlReferenceAnalysis) => void;
|
||||
analyze.mockImplementationOnce(
|
||||
() =>
|
||||
new Promise<SqlReferenceAnalysis>((done) => {
|
||||
resolve = done;
|
||||
}),
|
||||
);
|
||||
const { diagnostics, unmount, currentView } = createHarness();
|
||||
diagnostics.scheduleSemanticDiagnostics(0);
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
diagnostics.scheduleSemanticDiagnostics(500);
|
||||
unmount();
|
||||
const dispatch = vi.spyOn(currentView, "dispatch");
|
||||
resolve({ tables: [], columns: [] });
|
||||
await vi.advanceTimersByTimeAsync(1000);
|
||||
expect(analyze).toHaveBeenCalledOnce();
|
||||
expect(dispatch).not.toHaveBeenCalled();
|
||||
expect(buildDiagnostics).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ databaseType: "redis" as const, modelValue: "GET" },
|
||||
{ databaseType: "mongodb" as const, modelValue: "db.users.unknownMethod()" },
|
||||
])("preserves native diagnostics with SQL diagnostics disabled for $databaseType", async (overrides) => {
|
||||
const { diagnostics, settingsStore } = createHarness(overrides);
|
||||
settingsStore.editorSettings.sqlSemanticDiagnosticsEnabled = false;
|
||||
diagnostics.scheduleSemanticDiagnostics(0);
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
expect(diagnostics.diagnostics.length).toBeGreaterThan(0);
|
||||
expect(analyze).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("keeps unfinished MongoDB expressions under the cursor free of premature errors", async () => {
|
||||
const { diagnostics } = createHarness({ databaseType: "mongodb", modelValue: "db.users.find({" });
|
||||
diagnostics.scheduleSemanticDiagnostics(0);
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
expect(diagnostics.diagnostics).toEqual([]);
|
||||
expect(analyze).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("keeps completed MongoDB warnings while the cursor is in a later unfinished command", async () => {
|
||||
const sql = "db.a.deleteMany({});\ndb.b.find({";
|
||||
const { diagnostics, currentView } = createHarness({ databaseType: "mongodb", modelValue: sql });
|
||||
currentView.dispatch({ selection: { anchor: sql.length } });
|
||||
diagnostics.scheduleSemanticDiagnostics(0);
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
expect(diagnostics.diagnostics).toHaveLength(1);
|
||||
expect(diagnostics.diagnostics[0].severity).toBe("warning");
|
||||
expect(diagnostics.diagnostics[0].message).toContain("every document in a");
|
||||
expect(analyze).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not dispatch unchanged diagnostics or rewrite editor selection", () => {
|
||||
const { diagnostics, currentView } = createHarness();
|
||||
currentView.dispatch({ selection: { anchor: 3 } });
|
||||
const dispatch = vi.spyOn(currentView, "dispatch");
|
||||
diagnostics.setSemanticDiagnostics([diagnostic]);
|
||||
diagnostics.setSemanticDiagnostics([structuredClone(diagnostic)]);
|
||||
expect(dispatch).toHaveBeenCalledOnce();
|
||||
expect(dispatch.mock.calls[0][0]).not.toHaveProperty("selection");
|
||||
expect(currentView.state.selection.main.head).toBe(3);
|
||||
});
|
||||
});
|
||||
+196
@@ -0,0 +1,196 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import { createApp, h, nextTick, onBeforeUnmount, reactive, ref, shallowRef } from "vue";
|
||||
import { Compartment, EditorSelection, EditorState } from "@codemirror/state";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { history, undo } from "@codemirror/commands";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { useQueryEditorDocumentState } from "../useQueryEditorDocumentState";
|
||||
import type { QueryEditorProps } from "../queryEditorTypes";
|
||||
|
||||
const cleanups: Array<() => void> = [];
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
vi.spyOn(EditorView.prototype, "focus").mockImplementation(() => {});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
for (const cleanup of cleanups.splice(0).reverse()) cleanup();
|
||||
vi.clearAllTimers();
|
||||
vi.useRealTimers();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
function createHarness(overrides: Partial<QueryEditorProps> = {}) {
|
||||
const props = reactive<QueryEditorProps>({ modelValue: "SELECT 1;", tabId: "tab-a", autoFocus: false, ...overrides });
|
||||
const historyResetComp = new Compartment();
|
||||
const parent = document.createElement("div");
|
||||
document.body.append(parent);
|
||||
const currentView = new EditorView({ parent, state: EditorState.create({ doc: props.modelValue, extensions: [historyResetComp.of(history())] }) });
|
||||
const view = shallowRef<EditorView | null>(currentView);
|
||||
const runtime = { historyResetComp, codeMirrorHistory: history, codeMirrorEditorSelection: EditorSelection, editorIsActive: true };
|
||||
const emit = vi.fn();
|
||||
const callbacks = {
|
||||
scheduleSemanticDiagnostics: vi.fn(),
|
||||
clearScheduledPreviewContextRefresh: vi.fn(),
|
||||
syncContextMenuState: vi.fn(),
|
||||
applyEditorAppearance: vi.fn().mockResolvedValue(undefined),
|
||||
applyEditorShortcutKeymaps: vi.fn(),
|
||||
applyEditorIndentExtension: vi.fn(),
|
||||
applyEditorCompletionExtension: vi.fn(),
|
||||
invalidateSemanticDiagnosticsForDocumentChange: vi.fn(),
|
||||
currentEditorDocText: (editor: EditorView) => editor.state.doc.toString(),
|
||||
scheduleDocumentSearchUpdate: vi.fn(),
|
||||
isEditorComposing: vi.fn(() => false),
|
||||
};
|
||||
let state!: ReturnType<typeof useQueryEditorDocumentState>;
|
||||
const app = createApp({
|
||||
setup() {
|
||||
state = useQueryEditorDocumentState({ props, view, runtime, emit, previewContextSql: ref(""), ...callbacks });
|
||||
state.attach();
|
||||
onBeforeUnmount(() => {
|
||||
state.flushBeforeDeactivation();
|
||||
state.dispose();
|
||||
});
|
||||
return () => h("div");
|
||||
},
|
||||
});
|
||||
const host = document.createElement("div");
|
||||
app.mount(host);
|
||||
let mounted = true;
|
||||
const unmount = () => {
|
||||
if (!mounted) return;
|
||||
mounted = false;
|
||||
app.unmount();
|
||||
};
|
||||
cleanups.push(() => {
|
||||
unmount();
|
||||
currentView.destroy();
|
||||
parent.remove();
|
||||
});
|
||||
async function activate(tabId: string, modelValue: string, saved: Partial<QueryEditorProps> = {}) {
|
||||
Object.assign(props, { tabId, modelValue, initialSelection: undefined, initialViewport: undefined }, saved);
|
||||
await nextTick();
|
||||
}
|
||||
async function append(text: string) {
|
||||
currentView.dispatch({ changes: { from: currentView.state.doc.length, insert: text } });
|
||||
props.modelValue = currentView.state.doc.toString();
|
||||
await nextTick();
|
||||
}
|
||||
return { state, props, runtime, emit, callbacks, currentView, activate, append, unmount };
|
||||
}
|
||||
|
||||
describe("QueryEditor document and viewport ownership", () => {
|
||||
it("isolates undo on new tabs and restores each cached tab's own history", async () => {
|
||||
const { currentView, activate, append, callbacks } = createHarness();
|
||||
await append(" -- a");
|
||||
await activate("tab-b", "SELECT 2;");
|
||||
expect(undo(currentView)).toBe(false);
|
||||
await append(" -- b");
|
||||
await activate("tab-a", "SELECT 1; -- a");
|
||||
expect(undo(currentView)).toBe(true);
|
||||
expect(currentView.state.doc.toString()).toBe("SELECT 1;");
|
||||
await activate("tab-b", "SELECT 2; -- b");
|
||||
expect(undo(currentView)).toBe(true);
|
||||
expect(currentView.state.doc.toString()).toBe("SELECT 2;");
|
||||
expect(callbacks.applyEditorAppearance).toHaveBeenCalledTimes(2);
|
||||
expect(callbacks.applyEditorShortcutKeymaps).toHaveBeenCalledTimes(2);
|
||||
expect(callbacks.applyEditorIndentExtension).toHaveBeenCalledTimes(2);
|
||||
expect(callbacks.applyEditorCompletionExtension).toHaveBeenCalledTimes(2);
|
||||
expect(callbacks.scheduleDocumentSearchUpdate).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("bounds cached histories and treats an evicted tab as a fresh document", async () => {
|
||||
const { currentView, activate, append } = createHarness();
|
||||
await append(" -- a");
|
||||
for (let index = 0; index < 17; index++) await activate(`tab-${index}`, `SELECT ${index};`);
|
||||
await activate("tab-a", "SELECT 1; -- a");
|
||||
expect(currentView.state.doc.toString()).toBe("SELECT 1; -- a");
|
||||
expect(undo(currentView)).toBe(false);
|
||||
});
|
||||
|
||||
it("keeps external edits to a cached inactive document undoable", async () => {
|
||||
const { currentView, activate } = createHarness();
|
||||
await activate("tab-b", "SELECT 2;");
|
||||
await activate("tab-a", "SELECT 100;");
|
||||
expect(undo(currentView)).toBe(true);
|
||||
expect(currentView.state.doc.toString()).toBe("SELECT 1;");
|
||||
});
|
||||
|
||||
it("restores saved selection and viewport, without leaking them into a brand-new tab", async () => {
|
||||
const { currentView, activate, callbacks } = createHarness();
|
||||
await activate("tab-b", "SELECT 200;", { initialSelection: { anchor: 7, head: 10 }, initialViewport: { scrollTop: 300, scrollLeft: 40 } });
|
||||
expect(currentView.state.selection.main.anchor).toBe(7);
|
||||
expect(currentView.state.selection.main.head).toBe(10);
|
||||
expect(currentView.scrollDOM.scrollTop).toBe(300);
|
||||
expect(currentView.scrollDOM.scrollLeft).toBe(40);
|
||||
expect(callbacks.syncContextMenuState).toHaveBeenCalledWith(currentView);
|
||||
await activate("tab-c", "SELECT 3;");
|
||||
expect(currentView.state.selection.main.head).toBe(0);
|
||||
expect(currentView.scrollDOM.scrollTop).toBe(0);
|
||||
expect(currentView.scrollDOM.scrollLeft).toBe(0);
|
||||
});
|
||||
|
||||
it("flushes a deferred viewport with its outgoing tab owner and deduplicates emissions", async () => {
|
||||
const { state, currentView, activate, emit } = createHarness();
|
||||
currentView.scrollDOM.scrollTop = 240;
|
||||
state.scheduleEditorViewportEmit();
|
||||
await activate("tab-b", "SELECT 2;");
|
||||
expect(emit.mock.calls.filter(([event]) => event === "viewportChange")).toEqual([["viewportChange", { scrollTop: 240, scrollLeft: 0 }, "tab-a"]]);
|
||||
await vi.advanceTimersByTimeAsync(200);
|
||||
expect(emit.mock.calls.filter(([event]) => event === "viewportChange")).toHaveLength(1);
|
||||
currentView.scrollDOM.scrollTop = 100;
|
||||
state.scheduleEditorViewportEmit();
|
||||
await vi.advanceTimersByTimeAsync(200);
|
||||
expect(emit).toHaveBeenCalledWith("viewportChange", { scrollTop: 100, scrollLeft: 0 }, "tab-b");
|
||||
});
|
||||
|
||||
it("captures state before tab deactivation and never flushes a reset inactive viewport", () => {
|
||||
const { state, currentView, runtime, emit } = createHarness();
|
||||
currentView.scrollDOM.scrollTop = 220;
|
||||
currentView.dispatch({ selection: { anchor: 4 } });
|
||||
window.dispatchEvent(new CustomEvent("dbx:before-tab-switch", { detail: { fromTabId: "another-tab" } }));
|
||||
expect(emit).not.toHaveBeenCalled();
|
||||
window.dispatchEvent(new CustomEvent("dbx:before-tab-switch", { detail: { fromTabId: "tab-a" } }));
|
||||
expect(emit).toHaveBeenCalledWith("viewportChange", { scrollTop: 220, scrollLeft: 0 }, "tab-a");
|
||||
expect(emit).toHaveBeenCalledWith("selectionStateChange", { anchor: 4, head: 4 });
|
||||
emit.mockClear();
|
||||
currentView.scrollDOM.scrollTop = 0;
|
||||
state.flushBeforeDeactivation();
|
||||
runtime.editorIsActive = false;
|
||||
state.flushBeforeDeactivation();
|
||||
expect(emit).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("hydrates saved state after mount and respects IME composition for external content updates", async () => {
|
||||
const { props, currentView, callbacks } = createHarness();
|
||||
props.initialViewport = { scrollTop: 280, scrollLeft: 30 };
|
||||
props.initialSelection = { anchor: 3, head: 3 };
|
||||
await nextTick();
|
||||
expect(currentView.scrollDOM.scrollTop).toBe(280);
|
||||
expect(currentView.state.selection.main.head).toBe(3);
|
||||
callbacks.isEditorComposing.mockReturnValue(true);
|
||||
props.modelValue = "SELECT blocked;";
|
||||
await nextTick();
|
||||
expect(currentView.state.doc.toString()).toBe("SELECT 1;");
|
||||
callbacks.isEditorComposing.mockReturnValue(false);
|
||||
props.modelValue = "SELECT allowed;";
|
||||
await nextTick();
|
||||
expect(currentView.state.doc.toString()).toBe("SELECT allowed;");
|
||||
});
|
||||
|
||||
it("cancels pending viewport work and removes listeners when unmounted", async () => {
|
||||
const { state, currentView, runtime, emit, unmount } = createHarness();
|
||||
currentView.scrollDOM.scrollTop = 500;
|
||||
state.scheduleEditorViewportEmit();
|
||||
state.restoreEditorViewport({ scrollTop: 500, scrollLeft: 0 });
|
||||
await nextTick();
|
||||
runtime.editorIsActive = false;
|
||||
unmount();
|
||||
emit.mockClear();
|
||||
window.dispatchEvent(new CustomEvent("dbx:before-tab-switch", { detail: { fromTabId: "tab-a" } }));
|
||||
await vi.advanceTimersByTimeAsync(2000);
|
||||
expect(emit).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,147 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import { EditorState } from "@codemirror/state";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { reactive, ref, shallowRef } from "vue";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { useQueryEditorHover } from "../useQueryEditorHover";
|
||||
import { useQueryEditorCompletionMetadata } from "../useQueryEditorCompletionMetadata";
|
||||
import type { QueryEditorProps } from "../queryEditorTypes";
|
||||
import type { SqlCompletionColumn, SqlCompletionTable } from "@/lib/sql/sqlCompletion";
|
||||
|
||||
const { loadDdl, getColumns, listIndexes, getTableComment } = vi.hoisted(() => ({ loadDdl: vi.fn(), getColumns: vi.fn(), listIndexes: vi.fn(), getTableComment: vi.fn() }));
|
||||
vi.mock("@/stores/connectionStore", () => ({ COMPLETION_METADATA_CONCURRENCY: 4 }));
|
||||
vi.mock("@/lib/backend/api", () => ({ getColumns, listIndexes, getTableComment }));
|
||||
vi.mock("@/lib/metadata/objectDdlCache", () => ({ loadObjectDdl: loadDdl }));
|
||||
vi.mock("@/lib/metadata/objectMetadataCache", () => ({ loadObjectMetadataFacet: async (_request: unknown, _facet: string, load: () => Promise<unknown>) => ({ value: await load(), cacheStatus: "remote" }) }));
|
||||
type Options = Parameters<typeof useQueryEditorHover>[0];
|
||||
const cleanups: Array<() => void> = [];
|
||||
|
||||
beforeEach(() => {
|
||||
loadDdl.mockResolvedValue({ ddl: 'CREATE TABLE "users" ("id" INTEGER);' });
|
||||
getColumns.mockResolvedValue([{ name: "id", data_type: "INTEGER", is_nullable: false, column_default: null, is_primary_key: true, extra: null }]);
|
||||
listIndexes.mockResolvedValue([]);
|
||||
getTableComment.mockResolvedValue(null);
|
||||
});
|
||||
afterEach(() => {
|
||||
for (const cleanup of cleanups.splice(0).reverse()) cleanup();
|
||||
vi.restoreAllMocks();
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
function createHarness(overrides: Partial<QueryEditorProps> = {}, semanticCompletionEnabled = false) {
|
||||
const props = reactive<QueryEditorProps>({ modelValue: "SELECT * FROM users", connectionId: "connection", database: "demo", schema: "public", databaseType: "postgres", dialect: "postgres", ...overrides });
|
||||
const currentView = new EditorView({ state: EditorState.create({ doc: props.modelValue }) });
|
||||
cleanups.push(() => currentView.destroy());
|
||||
const store = {
|
||||
getConfig: vi.fn(() => undefined),
|
||||
lookupLocalCompletionTables: vi.fn((): SqlCompletionTable[] => []),
|
||||
listCompletionTables: vi.fn<Options["connectionStore"]["listCompletionTables"]>(async () => []),
|
||||
lookupLocalCompletionColumns: vi.fn((): SqlCompletionColumn[] => []),
|
||||
listCompletionColumns: vi.fn(async (): Promise<SqlCompletionColumn[]> => []),
|
||||
};
|
||||
const connectionStore = store as unknown as Options["connectionStore"];
|
||||
const metadata = useQueryEditorCompletionMetadata({ props, view: shallowRef<EditorView | null>(currentView), connectionStore, sqlBehaviorDialect: () => props.dialect, maxCompletionTables: 200, remoteLatencyBudgetMs: 40, onDemandMinPrefix: 2, semanticCompletionEnabled });
|
||||
const settings = reactive({ editorSettings: { tableHoverLookupMode: "fallback", showTableDdlHoverPreview: true, generateSqlQuoteIdentifiers: true, generateSqlIncludeDatabaseName: false, excludeDdlStorage: false, sqlFormatter: {} } });
|
||||
const contextMenuOpen = ref(false);
|
||||
const createHoverDom = vi.fn((_title: string, _detail: string, _sql?: string, _rows?: string[]) => ({ dom: document.createElement("div") }));
|
||||
const hover = useQueryEditorHover({ props, contextMenuOpen, settingsStore: settings as Options["settingsStore"], connectionStore, metadata, createHoverDom, maxCompletionTables: 200, semanticCompletionEnabled });
|
||||
const resolve = (position = props.modelValue.lastIndexOf("users") + 2) => hover.resolveSqlHoverTooltip(currentView, position);
|
||||
return { props, currentView, store, metadata, settings, contextMenuOpen, createHoverDom, resolve };
|
||||
}
|
||||
|
||||
describe("QueryEditor hover resolution", () => {
|
||||
it.each(["connection", "database", "menu"])("does no metadata work without an available %s context", async (missing) => {
|
||||
const harness = createHarness();
|
||||
if (missing === "connection") harness.props.connectionId = undefined;
|
||||
if (missing === "database") harness.props.database = undefined;
|
||||
if (missing === "menu") harness.contextMenuOpen.value = true;
|
||||
expect(await harness.resolve()).toBeNull();
|
||||
expect(harness.store.lookupLocalCompletionTables).not.toHaveBeenCalled();
|
||||
expect(loadDdl).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("prefers local tables and preserves catalog scope for persisted DDL", async () => {
|
||||
const { store, metadata, resolve, createHoverDom } = createHarness({ catalog: "catalog" });
|
||||
store.lookupLocalCompletionTables.mockReturnValue([{ name: "users", schema: "public", database: "demo", catalog: "catalog" }]);
|
||||
const tooltip = await resolve();
|
||||
expect(tooltip).not.toBeNull();
|
||||
tooltip!.create();
|
||||
expect(store.listCompletionTables).not.toHaveBeenCalled();
|
||||
expect(loadDdl).toHaveBeenCalledWith(expect.objectContaining({ connectionId: "connection", database: "demo", schema: "public", tableName: "users", catalog: "catalog" }));
|
||||
expect(metadata.cachedTables).toHaveLength(1);
|
||||
expect(createHoverDom).toHaveBeenCalledWith("users", expect.any(String), expect.stringContaining("create table"), undefined);
|
||||
expect(getColumns).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("falls back from scoped to global metadata only in fallback mode", async () => {
|
||||
const { store, resolve } = createHarness();
|
||||
store.listCompletionTables.mockResolvedValueOnce([]).mockResolvedValueOnce([{ name: "users", schema: "archive" }]);
|
||||
expect(await resolve()).not.toBeNull();
|
||||
expect(store.listCompletionTables.mock.calls.map((call) => [call[4], call[5]])).toEqual([
|
||||
["public", false],
|
||||
[undefined, true],
|
||||
]);
|
||||
expect(loadDdl).toHaveBeenCalledWith(expect.objectContaining({ schema: "archive" }));
|
||||
});
|
||||
|
||||
it("falls back to column metadata when DDL loading fails", async () => {
|
||||
vi.spyOn(console, "warn").mockImplementation(() => {});
|
||||
loadDdl.mockRejectedValue(new Error("DDL unavailable"));
|
||||
listIndexes.mockRejectedValue(new Error("indexes unavailable"));
|
||||
const { store, resolve, createHoverDom } = createHarness();
|
||||
store.lookupLocalCompletionTables.mockReturnValue([{ name: "users", schema: "public" }]);
|
||||
const tooltip = await resolve();
|
||||
tooltip!.create();
|
||||
expect(getColumns).toHaveBeenCalledWith("connection", "demo", "public", "users", undefined);
|
||||
expect(createHoverDom.mock.calls[0][2]).toContain("create table");
|
||||
expect(createHoverDom.mock.calls[0][2]).toContain("id");
|
||||
expect(createHoverDom.mock.calls[0][3]).toBeUndefined();
|
||||
});
|
||||
|
||||
it("shows an explicit structure failure instead of inventing an empty DDL", async () => {
|
||||
vi.spyOn(console, "warn").mockImplementation(() => {});
|
||||
loadDdl.mockRejectedValue(new Error("offline"));
|
||||
getColumns.mockRejectedValue(new Error("offline"));
|
||||
const { store, resolve, createHoverDom } = createHarness();
|
||||
store.lookupLocalCompletionTables.mockReturnValue([{ name: "users", schema: "public" }]);
|
||||
(await resolve())!.create();
|
||||
expect(createHoverDom).toHaveBeenCalledWith("users", expect.any(String), undefined, ["[DBX] Failed to load table structure — check connection"]);
|
||||
});
|
||||
|
||||
it("suppresses a late DDL tooltip when a context menu opens during its request", async () => {
|
||||
let finish!: (result: { ddl: string }) => void;
|
||||
loadDdl.mockReturnValue(
|
||||
new Promise((resolve) => {
|
||||
finish = resolve;
|
||||
}),
|
||||
);
|
||||
const { store, resolve, contextMenuOpen } = createHarness();
|
||||
store.lookupLocalCompletionTables.mockReturnValue([{ name: "users", schema: "public" }]);
|
||||
const pending = resolve();
|
||||
await vi.waitFor(() => expect(loadDdl).toHaveBeenCalled());
|
||||
contextMenuOpen.value = true;
|
||||
finish({ ddl: "CREATE TABLE users (id INTEGER);" });
|
||||
expect(await pending).toBeNull();
|
||||
});
|
||||
|
||||
it("keeps column hover when table DDL preview is disabled", async () => {
|
||||
const { store, settings, resolve, createHoverDom } = createHarness({ modelValue: "SELECT u.name FROM users u" });
|
||||
settings.editorSettings.showTableDdlHoverPreview = false;
|
||||
store.lookupLocalCompletionColumns.mockReturnValue([{ name: "name", table: "users", schema: "public", dataType: "varchar", comment: "Display name" }]);
|
||||
(await resolve(10))!.create();
|
||||
expect(createHoverDom).toHaveBeenCalledWith("name", "varchar", undefined, ["public.users", "Display name"]);
|
||||
expect(loadDdl).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("resolves CTE column origins through the shared cache before physical-table fallback", async () => {
|
||||
const sql = "WITH named_users AS (SELECT name FROM users) SELECT name FROM named_users";
|
||||
const { store, resolve, createHoverDom, metadata } = createHarness({ modelValue: sql }, true);
|
||||
store.lookupLocalCompletionColumns.mockReturnValue([{ name: "name", table: "users", schema: "public", dataType: "varchar" }]);
|
||||
(await resolve(sql.lastIndexOf("SELECT name") + 8))!.create();
|
||||
expect(createHoverDom).toHaveBeenCalledWith("name", "varchar", undefined, ["public.users"]);
|
||||
expect(metadata.cachedColumnsByTable.get("public.users")).toHaveLength(1);
|
||||
expect(store.lookupLocalCompletionTables).not.toHaveBeenCalled();
|
||||
expect(loadDdl).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
+184
@@ -0,0 +1,184 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import { createApp, h, nextTick, reactive, shallowRef } from "vue";
|
||||
import { createI18n } from "vue-i18n";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { useQueryEditorIntentions } from "../useQueryEditorIntentions";
|
||||
import QueryEditorIntentionPopup from "../QueryEditorIntentionPopup.vue";
|
||||
import type { QueryEditorProps } from "../queryEditorTypes";
|
||||
|
||||
const metadata = vi.hoisted(() => ({ loadTableMetadata: vi.fn() }));
|
||||
vi.mock("@/lib/metadata/tableMetadataCache", () => metadata);
|
||||
const cleanups: Array<() => void> = [];
|
||||
|
||||
afterEach(() => {
|
||||
for (const cleanup of cleanups.splice(0).reverse()) cleanup();
|
||||
vi.restoreAllMocks();
|
||||
metadata.loadTableMetadata.mockReset();
|
||||
});
|
||||
|
||||
function mountIntentions(sql = "SELECT user_id FROM sys_user AS su", cursor = 14) {
|
||||
const host = document.createElement("div");
|
||||
const editorHost = document.createElement("div");
|
||||
document.body.append(host, editorHost);
|
||||
const view = new EditorView({ doc: sql, parent: editorHost });
|
||||
view.dispatch({ selection: { anchor: cursor } });
|
||||
const coords = vi.spyOn(view, "coordsAtPos").mockReturnValue({ left: 10, right: 20, top: 30, bottom: 40 });
|
||||
const props = reactive<QueryEditorProps>({ modelValue: sql, databaseType: "mysql", dialect: "mysql", connectionId: "connection", database: "db" });
|
||||
let controller!: ReturnType<typeof useQueryEditorIntentions>;
|
||||
const app = createApp({
|
||||
setup() {
|
||||
controller = useQueryEditorIntentions({ props, view: shallowRef(view), sqlBehaviorDialect: () => props.dialect, focusEditor: () => view.focus() });
|
||||
return () =>
|
||||
h(QueryEditorIntentionPopup, {
|
||||
state: controller.intentionPopup.value,
|
||||
onClose: controller.closeIntentionPopup,
|
||||
onConfirm: controller.executeIntentionAction,
|
||||
onSelect: (index) => {
|
||||
if (controller.intentionPopup.value) controller.intentionPopup.value.selectedIndex = index;
|
||||
},
|
||||
});
|
||||
},
|
||||
});
|
||||
app.use(createI18n({ legacy: false, locale: "en", messages: { en: {} }, missingWarn: false, fallbackWarn: false }));
|
||||
app.mount(host);
|
||||
let mounted = true;
|
||||
const unmount = () => {
|
||||
if (!mounted) return;
|
||||
mounted = false;
|
||||
app.unmount();
|
||||
view.destroy();
|
||||
host.remove();
|
||||
editorHost.remove();
|
||||
};
|
||||
cleanups.push(unmount);
|
||||
return { controller, view, props, coords, unmount };
|
||||
}
|
||||
|
||||
function press(key: string) {
|
||||
const event = new KeyboardEvent("keydown", { key, bubbles: true, cancelable: true });
|
||||
document.dispatchEvent(event);
|
||||
return event;
|
||||
}
|
||||
|
||||
describe("QueryEditor intention popup extraction", () => {
|
||||
it("renders the real intention at the cursor and confirms it by keyboard", async () => {
|
||||
const { controller, view } = mountIntentions();
|
||||
expect(controller.handleSqlIntentionActions(view)).toBe(true);
|
||||
await nextTick();
|
||||
const popup = document.querySelector<HTMLElement>(".intention-popup")!;
|
||||
expect(popup.style.left).toBe("28px");
|
||||
expect(popup.style.top).toBe("44px");
|
||||
expect(popup.textContent).toContain("intentionQualifyIdentifier");
|
||||
expect(press("Enter").defaultPrevented).toBe(true);
|
||||
await nextTick();
|
||||
expect(view.state.doc.toString()).toBe("SELECT `su`.`user_id` FROM sys_user AS su");
|
||||
expect(document.querySelector(".intention-popup")).toBeNull();
|
||||
expect(view.hasFocus).toBe(true);
|
||||
expect(press("ArrowDown").defaultPrevented).toBe(false);
|
||||
});
|
||||
|
||||
it("keeps keyboard selection bounded and forwards mouse hover and click", async () => {
|
||||
const { controller, view } = mountIntentions();
|
||||
controller.handleSqlIntentionActions(view);
|
||||
const popup = controller.intentionPopup.value!;
|
||||
popup.actions.push({ ...popup.actions[0], label: "Alternative", replacement: "`other`.`user_id`" });
|
||||
press("ArrowDown");
|
||||
press("ArrowDown");
|
||||
expect(popup.selectedIndex).toBe(1);
|
||||
press("ArrowUp");
|
||||
press("ArrowUp");
|
||||
expect(popup.selectedIndex).toBe(0);
|
||||
await nextTick();
|
||||
const alternative = document.querySelectorAll<HTMLElement>(".intention-popup-item")[1];
|
||||
expect(alternative.textContent).toContain("Alternative");
|
||||
alternative.dispatchEvent(new MouseEvent("mouseenter"));
|
||||
expect(popup.selectedIndex).toBe(1);
|
||||
alternative.click();
|
||||
expect(view.state.doc.toString()).toBe("SELECT `other`.`user_id` FROM sys_user AS su");
|
||||
});
|
||||
|
||||
it.each(["Escape", "outside"])("cancels with %s and releases its keyboard handler", async (method) => {
|
||||
const { controller, view } = mountIntentions();
|
||||
const sql = view.state.doc.toString();
|
||||
controller.handleSqlIntentionActions(view);
|
||||
await nextTick();
|
||||
if (method === "Escape") expect(press("Escape").defaultPrevented).toBe(true);
|
||||
else document.querySelector<HTMLElement>(".intention-popup-overlay")!.click();
|
||||
expect(controller.intentionPopup.value).toBeNull();
|
||||
expect(view.state.doc.toString()).toBe(sql);
|
||||
expect(press("Enter").defaultPrevented).toBe(false);
|
||||
});
|
||||
|
||||
it("does not open for read-only editors, missing cursor coordinates or non-actionable SQL", () => {
|
||||
const { controller, view, props, coords } = mountIntentions();
|
||||
props.readOnly = true;
|
||||
expect(controller.handleSqlIntentionActions(view)).toBe(false);
|
||||
props.readOnly = false;
|
||||
coords.mockReturnValue(null);
|
||||
expect(controller.handleSqlIntentionActions(view)).toBe(false);
|
||||
view.dispatch({ changes: { from: 0, to: view.state.doc.length, insert: "SELECT 1" }, selection: { anchor: 0 } });
|
||||
expect(controller.handleSqlIntentionActions(view)).toBe(false);
|
||||
expect(controller.intentionPopup.value).toBeNull();
|
||||
});
|
||||
|
||||
it("applies batch replacements from right to left without offset drift", () => {
|
||||
const { controller, view } = mountIntentions("SELECT id, name FROM users", 8);
|
||||
controller.handleSqlIntentionActions(view);
|
||||
controller.executeIntentionAction({
|
||||
kind: "batch_qualify_identifiers",
|
||||
span: { start: 7, end: 15 },
|
||||
replacement: "",
|
||||
replacements: [
|
||||
{ span: { start: 7, end: 9 }, replacement: "users.id" },
|
||||
{ span: { start: 11, end: 15 }, replacement: "users.name" },
|
||||
],
|
||||
});
|
||||
expect(view.state.doc.toString()).toBe("SELECT users.id, users.name FROM users");
|
||||
});
|
||||
|
||||
it.each([false, true])("keeps asynchronous wildcard expansion guarded against a changed document (%s)", async (changeDocument) => {
|
||||
let resolveMetadata!: (value: unknown) => void;
|
||||
metadata.loadTableMetadata.mockReturnValue(
|
||||
new Promise((resolve) => {
|
||||
resolveMetadata = resolve;
|
||||
}),
|
||||
);
|
||||
const { controller, view } = mountIntentions("SELECT * FROM users", 8);
|
||||
expect(controller.handleSqlIntentionActions(view)).toBe(true);
|
||||
const action = controller.intentionPopup.value!.actions.find((candidate) => candidate.kind === "expand_wildcard")!;
|
||||
controller.executeIntentionAction(action);
|
||||
await vi.waitFor(() => expect(metadata.loadTableMetadata).toHaveBeenCalledTimes(1));
|
||||
if (changeDocument) view.dispatch({ changes: { from: 0, to: view.state.doc.length, insert: "SELECT 2" } });
|
||||
resolveMetadata({ metadata: { columns: [{ name: "id" }, { name: "name" }] } });
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
await vi.waitFor(() => {
|
||||
if (changeDocument) expect(view.state.doc.toString()).toBe("SELECT 2");
|
||||
else expect(view.state.doc.toString()).toMatch(/SELECT .*id.*name.* FROM users/);
|
||||
});
|
||||
await nextTick();
|
||||
if (changeDocument) expect(view.state.doc.toString()).toBe("SELECT 2");
|
||||
});
|
||||
|
||||
it("leaves the document unchanged when metadata loading fails", async () => {
|
||||
metadata.loadTableMetadata.mockRejectedValue(new Error("metadata unavailable"));
|
||||
const { controller, view } = mountIntentions("SELECT * FROM users", 8);
|
||||
controller.handleSqlIntentionActions(view);
|
||||
controller.executeIntentionAction(controller.intentionPopup.value!.actions[0]);
|
||||
await vi.waitFor(() => expect(metadata.loadTableMetadata).toHaveBeenCalledTimes(1));
|
||||
await nextTick();
|
||||
expect(view.state.doc.toString()).toBe("SELECT * FROM users");
|
||||
});
|
||||
|
||||
it("removes the teleported popup and keyboard handler on unmount", async () => {
|
||||
const { controller, view, unmount } = mountIntentions();
|
||||
const remove = vi.spyOn(document, "removeEventListener");
|
||||
controller.handleSqlIntentionActions(view);
|
||||
await nextTick();
|
||||
unmount();
|
||||
expect(remove.mock.calls.some(([event]) => event === "keydown")).toBe(true);
|
||||
expect(document.querySelector(".intention-popup-overlay")).toBeNull();
|
||||
expect(press("Enter").defaultPrevented).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,101 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import { createApp, h, ref } from "vue";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { useQueryEditorLayout } from "../useQueryEditorLayout";
|
||||
import { beginPanelResize, endPanelResize } from "@/lib/app/panelResizeState";
|
||||
import { uiTuning } from "@/lib/app/uiTuning";
|
||||
|
||||
const cleanups: Array<() => void> = [];
|
||||
|
||||
afterEach(() => {
|
||||
for (const cleanup of cleanups.splice(0).reverse()) cleanup();
|
||||
endPanelResize();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
function mountLayout(width = 800, height = 600) {
|
||||
const frames = new Map<number, FrameRequestCallback>();
|
||||
let nextFrame = 0;
|
||||
const request = vi.spyOn(window, "requestAnimationFrame").mockImplementation((callback) => {
|
||||
frames.set(++nextFrame, callback);
|
||||
return nextFrame;
|
||||
});
|
||||
const cancel = vi.spyOn(window, "cancelAnimationFrame").mockImplementation((frame) => {
|
||||
frames.delete(frame);
|
||||
});
|
||||
const host = document.createElement("div");
|
||||
Object.defineProperties(host, { clientWidth: { get: () => width }, clientHeight: { get: () => height } });
|
||||
document.body.append(host);
|
||||
const root = ref<HTMLDivElement>();
|
||||
const app = createApp({
|
||||
setup() {
|
||||
useQueryEditorLayout(root);
|
||||
return () => h("div", { ref: root });
|
||||
},
|
||||
});
|
||||
app.mount(host);
|
||||
let mounted = true;
|
||||
const unmount = () => {
|
||||
if (mounted) {
|
||||
app.unmount();
|
||||
host.remove();
|
||||
mounted = false;
|
||||
}
|
||||
};
|
||||
cleanups.push(unmount);
|
||||
const step = () => {
|
||||
const [frame, callback] = frames.entries().next().value!;
|
||||
frames.delete(frame);
|
||||
callback(0);
|
||||
};
|
||||
return {
|
||||
root: root.value!,
|
||||
frames,
|
||||
request,
|
||||
cancel,
|
||||
step,
|
||||
unmount,
|
||||
resize: (nextWidth: number) => {
|
||||
width = nextWidth;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe("QueryEditor resize layout extraction", () => {
|
||||
it("pins synchronously, throttles frame updates and releases on pointer-up", () => {
|
||||
const { root, frames, step, resize } = mountLayout();
|
||||
beginPanelResize();
|
||||
expect(root.style.width).toBe("800px");
|
||||
expect(root.style.height).toBe("600px");
|
||||
resize(900);
|
||||
for (let frame = 1; frame < uiTuning.value.panelResizeTrackEveryFrames; frame++) step();
|
||||
expect(root.style.width).toBe("800px");
|
||||
step();
|
||||
expect(root.style.width).toBe("900px");
|
||||
endPanelResize();
|
||||
expect(root.style.width).toBe("");
|
||||
expect(root.style.height).toBe("");
|
||||
expect(root.style.maxWidth).toBe("");
|
||||
expect(root.style.minHeight).toBe("");
|
||||
expect(frames.size).toBe(0);
|
||||
});
|
||||
|
||||
it("does not schedule frames for an invisible editor", () => {
|
||||
const { root, request } = mountLayout(0, 0);
|
||||
beginPanelResize();
|
||||
expect(request).not.toHaveBeenCalled();
|
||||
expect(root.style.width).toBe("");
|
||||
});
|
||||
|
||||
it("cancels the active frame and watcher when unmounted mid-drag", () => {
|
||||
const { unmount, frames, cancel, request } = mountLayout();
|
||||
beginPanelResize();
|
||||
unmount();
|
||||
expect(cancel).toHaveBeenCalledTimes(1);
|
||||
expect(frames.size).toBe(0);
|
||||
endPanelResize();
|
||||
beginPanelResize();
|
||||
expect(request).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
+179
@@ -0,0 +1,179 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import { EditorState, StateEffect } from "@codemirror/state";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { reactive, shallowRef } from "vue";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { createQueryEditorCodeMirrorRuntime } from "../queryEditorCodeMirrorRuntime";
|
||||
import { useQueryEditorCompletionMetadata } from "../useQueryEditorCompletionMetadata";
|
||||
import { useQueryEditorObjectNavigation } from "../useQueryEditorObjectNavigation";
|
||||
import type { QueryEditorProps } from "../queryEditorTypes";
|
||||
import type { SqlCompletionColumn, SqlCompletionObject, SqlCompletionTable } from "@/lib/sql/sqlCompletion";
|
||||
|
||||
vi.mock("@/stores/connectionStore", () => ({ COMPLETION_METADATA_CONCURRENCY: 4 }));
|
||||
vi.mock("@/lib/backend/api", () => ({}));
|
||||
type Options = Parameters<typeof useQueryEditorObjectNavigation>[0];
|
||||
const cleanups: Array<() => void> = [];
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
});
|
||||
afterEach(() => {
|
||||
for (const cleanup of cleanups.splice(0).reverse()) cleanup();
|
||||
vi.clearAllTimers();
|
||||
vi.useRealTimers();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
async function createHarness(overrides: Partial<QueryEditorProps> = {}, semanticCompletionEnabled = false) {
|
||||
const props = reactive<QueryEditorProps>({ modelValue: "SELECT * FROM users", databaseType: "postgres", dialect: "postgres", connectionId: "connection", database: "demo", schema: "public", ...overrides });
|
||||
const host = document.createElement("div");
|
||||
document.body.append(host);
|
||||
const currentView = new EditorView({ parent: host, state: EditorState.create({ doc: props.modelValue }) });
|
||||
const position = vi.spyOn(currentView, "posAtCoords").mockReturnValue(props.modelValue.lastIndexOf("users") + 2);
|
||||
vi.spyOn(currentView, "focus").mockImplementation(() => {});
|
||||
const view = shallowRef<EditorView | null>(currentView);
|
||||
const store = {
|
||||
getConfig: vi.fn(() => undefined),
|
||||
lookupLocalCompletionTables: vi.fn((): SqlCompletionTable[] => []),
|
||||
lookupLocalCompletionObjects: vi.fn((): SqlCompletionObject[] => []),
|
||||
listCompletionTables: vi.fn(async (): Promise<SqlCompletionTable[]> => []),
|
||||
listCompletionObjects: vi.fn(async (): Promise<SqlCompletionObject[]> => []),
|
||||
lookupLocalCompletionColumns: vi.fn((): SqlCompletionColumn[] => []),
|
||||
listCompletionColumns: vi.fn(async (): Promise<SqlCompletionColumn[]> => []),
|
||||
};
|
||||
const connectionStore = store as unknown as Options["connectionStore"];
|
||||
const metadata = useQueryEditorCompletionMetadata({ props, view, connectionStore, sqlBehaviorDialect: () => props.dialect, maxCompletionTables: 200, remoteLatencyBudgetMs: 40, onDemandMinPrefix: 2, semanticCompletionEnabled });
|
||||
const runtime = createQueryEditorCodeMirrorRuntime();
|
||||
await runtime.load();
|
||||
runtime.setResultSourceRangeEffect = StateEffect.define<{ from: number; to: number } | null>();
|
||||
const settings = { editorSettings: { tableHoverLookupMode: "current" } } as Options["settingsStore"];
|
||||
const emit = vi.fn();
|
||||
const dismissHoverTooltip = vi.fn();
|
||||
const startEditorSelectionDrag = vi.fn(() => false);
|
||||
const navigation = useQueryEditorObjectNavigation({ props, view, editorRef: shallowRef(host), settingsStore: settings, connectionStore, metadata, runtime, dismissHoverTooltip, startEditorSelectionDrag, emit, semanticCompletionEnabled, maxCompletionTables: 200 });
|
||||
navigation.attach();
|
||||
cleanups.push(() => {
|
||||
navigation.dispose();
|
||||
currentView.destroy();
|
||||
host.remove();
|
||||
});
|
||||
const event = (overrides: MouseEventInit = {}) => new MouseEvent("mousedown", { ctrlKey: true, button: 0, clientX: 20, clientY: 10, cancelable: true, ...overrides });
|
||||
const click = async (overrides: MouseEventInit = {}) => {
|
||||
const pointer = event(overrides);
|
||||
const handled = navigation.onEditorMouseDown(pointer);
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
return { handled, pointer };
|
||||
};
|
||||
return { props, view, currentView, position, host, store, metadata, runtime, emit, dismissHoverTooltip, startEditorSelectionDrag, navigation, event, click };
|
||||
}
|
||||
|
||||
describe("QueryEditor object navigation ownership", () => {
|
||||
it("gives existing selection dragging priority over object navigation", async () => {
|
||||
const harness = await createHarness();
|
||||
harness.startEditorSelectionDrag.mockReturnValue(true);
|
||||
expect((await harness.click()).handled).toBe(true);
|
||||
expect(harness.dismissHoverTooltip).toHaveBeenCalledOnce();
|
||||
expect(harness.store.lookupLocalCompletionTables).not.toHaveBeenCalled();
|
||||
expect(harness.emit).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each([{ ctrlKey: true, altKey: true }, { ctrlKey: true, button: 2 }, { ctrlKey: false }])("preserves non-navigation mouse gestures %j", async (modifiers) => {
|
||||
const { click, store, emit } = await createHarness();
|
||||
expect((await click(modifiers)).handled).toBe(false);
|
||||
expect(store.lookupLocalCompletionTables).not.toHaveBeenCalled();
|
||||
if (!modifiers.ctrlKey) expect(emit).toHaveBeenCalledWith("closeColumnPanel");
|
||||
else expect(emit).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("ignores missing connection contexts and non-identifier positions", async () => {
|
||||
const { props, position, click, store } = await createHarness();
|
||||
position.mockReturnValue(2);
|
||||
expect((await click()).handled).toBe(false);
|
||||
position.mockReturnValue(null);
|
||||
expect((await click()).handled).toBe(false);
|
||||
props.connectionId = undefined;
|
||||
expect((await click()).handled).toBe(false);
|
||||
expect(store.lookupLocalCompletionTables).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each(["control", "command"])("opens a cached table with the %s modifier before any routine or remote lookup", async (modifier) => {
|
||||
const { store, emit, click } = await createHarness();
|
||||
store.lookupLocalCompletionTables.mockReturnValue([{ name: "users", schema: "public", type: "table" }]);
|
||||
const result = await click(modifier === "command" ? { ctrlKey: false, metaKey: true } : {});
|
||||
expect(result.handled).toBe(true);
|
||||
expect(result.pointer.defaultPrevented).toBe(true);
|
||||
expect(emit).toHaveBeenCalledWith("clickTable", expect.objectContaining({ name: "users", schema: "public" }));
|
||||
expect(store.lookupLocalCompletionObjects).not.toHaveBeenCalled();
|
||||
expect(store.listCompletionTables).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("resolves relation column lists as tables rather than routine calls", async () => {
|
||||
const { store, emit, click } = await createHarness({ modelValue: "INSERT INTO users(id) VALUES (1)" });
|
||||
store.listCompletionTables.mockResolvedValue([{ name: "users", schema: "public" }]);
|
||||
await click();
|
||||
expect(store.listCompletionTables).toHaveBeenCalled();
|
||||
expect(store.listCompletionObjects).not.toHaveBeenCalled();
|
||||
expect(store.lookupLocalCompletionObjects).not.toHaveBeenCalled();
|
||||
expect(emit).toHaveBeenCalledWith("clickTable", expect.objectContaining({ name: "users" }));
|
||||
});
|
||||
|
||||
it("opens cached routine metadata without changing its stored identifier case", async () => {
|
||||
const { store, position, emit, click } = await createHarness({ modelValue: 'CALL "Cleanup"()', databaseType: "oracle", schema: "APP" });
|
||||
position.mockReturnValue(8);
|
||||
store.lookupLocalCompletionObjects.mockReturnValue([{ name: "Cleanup", schema: "APP", type: "procedure" }]);
|
||||
await click();
|
||||
expect(emit).toHaveBeenCalledWith("openObjectSource", expect.objectContaining({ name: "Cleanup", type: "procedure", nameQuoted: true }), false);
|
||||
expect(store.listCompletionObjects).not.toHaveBeenCalled();
|
||||
expect(store.listCompletionTables).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("jumps to CTE definitions without querying physical table metadata", async () => {
|
||||
const sql = "WITH picked AS (SELECT id FROM users) SELECT id FROM picked";
|
||||
const { position, currentView, runtime, emit, click, store } = await createHarness({ modelValue: sql }, true);
|
||||
position.mockReturnValue(sql.lastIndexOf("picked") + 2);
|
||||
const dispatch = vi.spyOn(currentView, "dispatch");
|
||||
await click();
|
||||
expect(currentView.state.sliceDoc(currentView.state.selection.main.from, currentView.state.selection.main.to)).toBe("picked");
|
||||
expect(currentView.state.selection.main.from).toBe(sql.indexOf("picked"));
|
||||
expect(dispatch).toHaveBeenCalledWith(expect.objectContaining({ effects: expect.arrayContaining([expect.objectContaining({ type: runtime.setResultSourceRangeEffect })]) }));
|
||||
expect(store.lookupLocalCompletionTables).not.toHaveBeenCalled();
|
||||
expect(emit).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("uses the shared column cache for qualified column navigation", async () => {
|
||||
const { position, metadata, store, emit, click } = await createHarness({ modelValue: "SELECT u.name FROM users u" });
|
||||
position.mockReturnValue(10);
|
||||
metadata.cachedColumnsByTable.set("public.users", [{ name: "name", table: "users", schema: "public" }]);
|
||||
await click();
|
||||
expect(emit).toHaveBeenCalledWith("clickColumn", [{ name: "name", table: "users", schema: "public" }]);
|
||||
expect(store.listCompletionColumns).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not emit a false column match when its metadata lookup fails", async () => {
|
||||
const { position, store, emit, click } = await createHarness({ modelValue: "SELECT u.name FROM users u" });
|
||||
position.mockReturnValue(10);
|
||||
store.listCompletionColumns.mockRejectedValue(new Error("offline"));
|
||||
await click();
|
||||
expect(store.listCompletionColumns).toHaveBeenCalled();
|
||||
expect(emit).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("keeps modifier-hover lookup bounded and cleans up global listeners", async () => {
|
||||
const { navigation, currentView, position, host, event } = await createHarness({ modelValue: " ".repeat(10000) + "users" });
|
||||
position.mockReturnValue(10002);
|
||||
const stringify = vi.spyOn(currentView.state.doc, "toString");
|
||||
expect(navigation.updateTableNavigationHover(currentView, event())).toBe(true);
|
||||
expect(host.classList.contains("query-editor--table-navigation-hover")).toBe(true);
|
||||
expect(stringify).not.toHaveBeenCalled();
|
||||
window.dispatchEvent(new KeyboardEvent("keyup"));
|
||||
expect(host.classList.contains("query-editor--table-navigation-hover")).toBe(false);
|
||||
navigation.updateTableNavigationHover(currentView, event());
|
||||
window.dispatchEvent(new Event("blur"));
|
||||
expect(host.classList.contains("query-editor--table-navigation-hover")).toBe(false);
|
||||
navigation.dispose();
|
||||
navigation.updateTableNavigationHover(currentView, event());
|
||||
window.dispatchEvent(new Event("blur"));
|
||||
expect(host.classList.contains("query-editor--table-navigation-hover")).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,126 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import { EditorState } from "@codemirror/state";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { useQueryEditorPointer } from "../useQueryEditorPointer";
|
||||
import { isTauriRuntime } from "@/lib/backend/tauriRuntime";
|
||||
import { isMacOS } from "@/lib/backend/platform";
|
||||
|
||||
vi.mock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: vi.fn(() => false) }));
|
||||
vi.mock("@/lib/backend/platform", () => ({ isMacOS: vi.fn(() => false) }));
|
||||
const cleanups: Array<() => void> = [];
|
||||
|
||||
afterEach(() => {
|
||||
for (const cleanup of cleanups.splice(0).reverse()) cleanup();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
function createHarness(readOnly = false) {
|
||||
const host = document.createElement("div");
|
||||
document.body.append(host);
|
||||
const view = new EditorView({ parent: host, state: EditorState.create({ doc: "abc def ghi", selection: { anchor: 4, head: 7 } }) });
|
||||
const position = vi.spyOn(view, "posAtCoords").mockReturnValue(5);
|
||||
vi.spyOn(view, "coordsAtPos").mockReturnValue({ left: 50, right: 51, top: 20, bottom: 38 });
|
||||
vi.spyOn(view, "focus").mockImplementation(() => {});
|
||||
const emit = vi.fn();
|
||||
const clearTableNavigationHover = vi.fn();
|
||||
const pointer = useQueryEditorPointer({ props: { modelValue: "abc def ghi", readOnly }, clearTableNavigationHover, emit });
|
||||
const start = (init: MouseEventInit = {}) => {
|
||||
const event = new MouseEvent("mousedown", { button: 0, detail: 1, clientX: 10, clientY: 10, cancelable: true, ...init });
|
||||
Object.defineProperty(event, "target", { value: view.contentDOM });
|
||||
return { handled: pointer.startEditorSelectionDrag(view, event), event };
|
||||
};
|
||||
const move = (init: MouseEventInit = {}) => document.dispatchEvent(new MouseEvent("mousemove", { clientX: 30, clientY: 10, cancelable: true, ...init }));
|
||||
const release = (init: MouseEventInit = {}) => document.dispatchEvent(new MouseEvent("mouseup", { clientX: 30, clientY: 10, cancelable: true, ...init }));
|
||||
cleanups.push(() => {
|
||||
pointer.dispose();
|
||||
view.destroy();
|
||||
host.remove();
|
||||
});
|
||||
return { host, view, position, emit, clearTableNavigationHover, pointer, start, move, release };
|
||||
}
|
||||
|
||||
describe("QueryEditor pointer ownership", () => {
|
||||
it.each(["read-only", "non-primary", "shift", "double-click", "empty-selection", "outside-selection"])("does not capture %s gestures", (kind) => {
|
||||
const { view, position, start, emit } = createHarness(kind === "read-only");
|
||||
if (kind === "empty-selection") view.dispatch({ selection: { anchor: 4 } });
|
||||
if (kind === "outside-selection") position.mockReturnValue(0);
|
||||
const { handled, event } = start({ button: kind === "non-primary" ? 2 : 0, shiftKey: kind === "shift", detail: kind === "double-click" ? 2 : 1 });
|
||||
expect(handled).toBe(false);
|
||||
expect(event.defaultPrevented).toBe(false);
|
||||
expect(emit).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("keeps clicks below the drag threshold as caret moves", () => {
|
||||
const { view, position, start, move, release, emit } = createHarness();
|
||||
expect(start().handled).toBe(true);
|
||||
move({ clientX: 12 });
|
||||
position.mockReturnValue(6);
|
||||
release({ clientX: 12 });
|
||||
expect(view.state.doc.toString()).toBe("abc def ghi");
|
||||
expect(view.state.selection.main.anchor).toBe(6);
|
||||
expect(view.state.selection.main.empty).toBe(true);
|
||||
expect(emit).toHaveBeenCalledWith("closeColumnPanel");
|
||||
expect(document.querySelector(".dbx-editor-selection-drop-cursor")).toBeNull();
|
||||
});
|
||||
|
||||
it.each(["move", "control-copy", "command-copy"])("preserves %s text and selection mapping", (kind) => {
|
||||
const { view, position, start, move, release, emit } = createHarness();
|
||||
const modifiers = { ctrlKey: kind === "control-copy", metaKey: kind === "command-copy" };
|
||||
start(modifiers);
|
||||
position.mockReturnValue(11);
|
||||
move(modifiers);
|
||||
expect(document.querySelector(".dbx-editor-selection-drop-cursor")).not.toBeNull();
|
||||
expect(view.contentDOM.style.cursor).toBe(kind === "move" ? "move" : "copy");
|
||||
release(modifiers);
|
||||
expect(view.state.doc.toString()).toBe(kind === "move" ? "abc ghidef" : "abc def ghidef");
|
||||
expect(view.state.sliceDoc(view.state.selection.main.from, view.state.selection.main.to)).toBe("def");
|
||||
expect(view.contentDOM.style.cursor).toBe("");
|
||||
expect(document.querySelector(".dbx-editor-selection-drop-cursor")).toBeNull();
|
||||
if (kind !== "move") expect(emit).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each(["escape", "dispose"])("cleans document listeners and overlays on %s", (action) => {
|
||||
const { view, position, pointer, start, move, release } = createHarness();
|
||||
start();
|
||||
position.mockReturnValue(11);
|
||||
move();
|
||||
const remove = vi.spyOn(document, "removeEventListener");
|
||||
if (action === "escape") document.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", cancelable: true }));
|
||||
else pointer.dispose();
|
||||
expect(document.querySelector(".dbx-editor-selection-drop-cursor")).toBeNull();
|
||||
expect(view.contentDOM.style.cursor).toBe("");
|
||||
for (const event of ["mousemove", "mouseup", "keydown"]) expect(remove).toHaveBeenCalledWith(event, expect.any(Function), true);
|
||||
release();
|
||||
expect(view.state.doc.toString()).toBe("abc def ghi");
|
||||
});
|
||||
|
||||
it("replaces scrollbar capture listeners and removes them on disposal", () => {
|
||||
const { view, host, pointer, clearTableNavigationHover } = createHarness();
|
||||
Object.defineProperties(view.scrollDOM, { scrollHeight: { configurable: true, value: 300 }, clientHeight: { configurable: true, value: 100 }, offsetWidth: { configurable: true, value: 100 }, clientWidth: { configurable: true, value: 90 } });
|
||||
vi.spyOn(view.scrollDOM, "getBoundingClientRect").mockReturnValue(new DOMRect(0, 0, 100, 100));
|
||||
const bubble = vi.fn();
|
||||
host.addEventListener("mousedown", bubble);
|
||||
pointer.registerEditorScrollbarPointerGuard(view);
|
||||
pointer.registerEditorScrollbarPointerGuard(view);
|
||||
view.scrollDOM.dispatchEvent(new MouseEvent("mousedown", { clientX: 95, clientY: 20, bubbles: true }));
|
||||
expect(clearTableNavigationHover).toHaveBeenCalledOnce();
|
||||
expect(bubble).not.toHaveBeenCalled();
|
||||
pointer.dispose();
|
||||
view.scrollDOM.dispatchEvent(new MouseEvent("mousedown", { clientX: 95, clientY: 20, bubbles: true }));
|
||||
expect(bubble).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("prevents native macOS Tauri scrollbar focus changes outside editor content", () => {
|
||||
const { view, pointer } = createHarness();
|
||||
vi.mocked(isTauriRuntime).mockReturnValue(true);
|
||||
vi.mocked(isMacOS).mockReturnValue(true);
|
||||
Object.defineProperties(view.scrollDOM, { scrollHeight: { configurable: true, value: 300 }, clientHeight: { configurable: true, value: 100 } });
|
||||
vi.spyOn(view.scrollDOM, "getBoundingClientRect").mockReturnValue(new DOMRect(0, 0, 100, 100));
|
||||
pointer.registerEditorScrollbarPointerGuard(view);
|
||||
const event = new MouseEvent("mousedown", { clientX: 95, clientY: 20, bubbles: true, cancelable: true });
|
||||
view.scrollDOM.dispatchEvent(event);
|
||||
expect(event.defaultPrevented).toBe(true);
|
||||
});
|
||||
});
|
||||
+103
@@ -0,0 +1,103 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import { EditorState, StateEffect } from "@codemirror/state";
|
||||
import { EditorView, ViewPlugin } from "@codemirror/view";
|
||||
import { shallowRef } from "vue";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { createQueryEditorCodeMirrorRuntime } from "../queryEditorCodeMirrorRuntime";
|
||||
import { useQueryEditorStatementBoundaries } from "../useQueryEditorStatementBoundaries";
|
||||
import { statementGutterStartIndexHasStartAt, type ExecutableStatementRangeCache } from "@/lib/sql/executableStatementRangeCache";
|
||||
|
||||
const cleanups: Array<() => void> = [];
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
});
|
||||
afterEach(() => {
|
||||
for (const cleanup of cleanups.splice(0).reverse()) cleanup();
|
||||
vi.clearAllTimers();
|
||||
vi.useRealTimers();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
function createHarness() {
|
||||
const view = shallowRef<EditorView | null>(null);
|
||||
const cache = { value: null as ExecutableStatementRangeCache | null };
|
||||
const runtime = createQueryEditorCodeMirrorRuntime();
|
||||
runtime.statementBoundariesRefreshEffect = StateEffect.define<null>();
|
||||
const boundaries = useQueryEditorStatementBoundaries({
|
||||
props: { modelValue: "", databaseType: "mysql" },
|
||||
view,
|
||||
cache,
|
||||
runtime,
|
||||
sqlStatementParameterOptions: () => ({}),
|
||||
});
|
||||
const parent = document.createElement("div");
|
||||
document.body.append(parent);
|
||||
const currentView = new EditorView({ parent, state: EditorState.create({ doc: "SELECT 1;\nSELECT 2;", extensions: [boundaries.createTrackingPlugin(ViewPlugin)] }) });
|
||||
view.value = currentView;
|
||||
cleanups.push(() => {
|
||||
currentView.destroy();
|
||||
parent.remove();
|
||||
});
|
||||
return { view, currentView, cache, runtime, boundaries, parent };
|
||||
}
|
||||
|
||||
describe("QueryEditor shared statement boundaries", () => {
|
||||
it("does not parse or schedule refreshes before any consumer requests boundaries", async () => {
|
||||
const { currentView, cache } = createHarness();
|
||||
currentView.dispatch({ changes: { from: 7, insert: "0" } });
|
||||
await vi.advanceTimersByTimeAsync(200);
|
||||
expect(cache.value).toBeNull();
|
||||
});
|
||||
|
||||
it("maps positions during typing and refreshes the shared cache only after the debounce", async () => {
|
||||
const { currentView, cache, boundaries } = createHarness();
|
||||
const initial = boundaries.statementBoundariesForState(currentView.state);
|
||||
const exactCache = cache.value;
|
||||
initial.frameRange = { from: 10, to: 18 };
|
||||
expect(boundaries.statementBoundariesForState(currentView.state)).toBe(initial);
|
||||
currentView.dispatch({ changes: { from: 0, insert: " " } });
|
||||
const mapped = boundaries.statementBoundariesForState(currentView.state);
|
||||
expect(mapped.fresh).toBe(false);
|
||||
expect(mapped.frameRange).toEqual({ from: 11, to: 19 });
|
||||
expect(statementGutterStartIndexHasStartAt(mapped.startsIndex, 11)).toBe(true);
|
||||
expect(cache.value).toBe(exactCache);
|
||||
await vi.advanceTimersByTimeAsync(100);
|
||||
currentView.dispatch({ changes: { from: 0, insert: " " } });
|
||||
await vi.advanceTimersByTimeAsync(149);
|
||||
expect(cache.value).toBe(exactCache);
|
||||
await vi.advanceTimersByTimeAsync(1);
|
||||
const refreshed = boundaries.statementBoundariesForState(currentView.state);
|
||||
expect(refreshed.fresh).toBe(true);
|
||||
expect(refreshed.doc).toBe(currentView.state.doc);
|
||||
expect(cache.value).not.toBe(exactCache);
|
||||
expect(refreshed.frameRange).toBeNull();
|
||||
});
|
||||
|
||||
it("rebuilds when the dialect generation or tab state changes", () => {
|
||||
const { currentView, boundaries } = createHarness();
|
||||
const initial = boundaries.statementBoundariesForState(currentView.state);
|
||||
boundaries.invalidate();
|
||||
const invalidated = boundaries.statementBoundariesForState(currentView.state);
|
||||
expect(invalidated).not.toBe(initial);
|
||||
expect(invalidated.generation).toBe(initial.generation + 1);
|
||||
const anotherTab = EditorState.create({ doc: "SELECT 3;" });
|
||||
expect(boundaries.statementBoundariesForState(anotherTab).doc).toBe(anotherTab.doc);
|
||||
expect(boundaries.statementBoundariesForState(currentView.state).doc).toBe(currentView.state.doc);
|
||||
});
|
||||
|
||||
it.each(["destroyed", "replaced", "detached"])("does not refresh an editor that was %s", async (reason) => {
|
||||
const { currentView, view, parent, boundaries, cache } = createHarness();
|
||||
boundaries.statementBoundariesForState(currentView.state);
|
||||
const previousCache = cache.value;
|
||||
currentView.dispatch({ changes: { from: 0, insert: " " } });
|
||||
if (reason === "destroyed") currentView.destroy();
|
||||
if (reason === "replaced") view.value = null;
|
||||
if (reason === "detached") parent.remove();
|
||||
const dispatch = vi.spyOn(currentView, "dispatch");
|
||||
await vi.advanceTimersByTimeAsync(200);
|
||||
expect(dispatch).not.toHaveBeenCalled();
|
||||
expect(cache.value).toBe(previousCache);
|
||||
});
|
||||
});
|
||||
+145
@@ -0,0 +1,145 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import { EditorState } from "@codemirror/state";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { reactive, shallowRef } from "vue";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { useQueryEditorTableDrop } from "../useQueryEditorTableDrop";
|
||||
import {
|
||||
activeTableReferencePayloadValue,
|
||||
createTableReferenceDragEndEvent,
|
||||
createTableReferenceDropEvent,
|
||||
createTableReferenceHoverEvent,
|
||||
DBX_TABLE_REFERENCE_MIME,
|
||||
serializeTableReferencePayload,
|
||||
setActiveTableReferencePayload,
|
||||
type QueryEditorTableReferencePayload,
|
||||
} from "@/lib/editor/queryEditorTableDrop";
|
||||
import type { QueryEditorProps } from "../queryEditorTypes";
|
||||
|
||||
type Options = Parameters<typeof useQueryEditorTableDrop>[0];
|
||||
const cleanups: Array<() => void> = [];
|
||||
const payload: QueryEditorTableReferencePayload = { kind: "dbx-table-reference", connectionId: "connection", database: "demo", tableName: "users", referenceType: "column", columnName: "id" };
|
||||
|
||||
afterEach(() => {
|
||||
for (const cleanup of cleanups.splice(0).reverse()) cleanup();
|
||||
setActiveTableReferencePayload(null);
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
function createHarness(overrides: Partial<QueryEditorProps> = {}, left = 0) {
|
||||
const props = reactive<QueryEditorProps>({ modelValue: "SELECT old", databaseType: "postgres", ...overrides });
|
||||
const host = document.createElement("div");
|
||||
document.body.append(host);
|
||||
const view = new EditorView({ parent: host, state: EditorState.create({ doc: props.modelValue, selection: { anchor: 7, head: 10 } }) });
|
||||
vi.spyOn(view, "focus").mockImplementation(() => {});
|
||||
const position = vi.spyOn(view, "posAtCoords").mockReturnValue(10);
|
||||
const coordinates = vi.spyOn(view, "coordsAtPos").mockReturnValue({ left: left + 25, right: left + 26, top: 30, bottom: 48 });
|
||||
vi.spyOn(host, "getBoundingClientRect").mockReturnValue(new DOMRect(left, 20, 200, 100));
|
||||
const settings = reactive({ editorSettings: { sidebarCopyTableNameSeparator: "comma", sidebarCopyTableNameIncludeSchema: false } });
|
||||
const drop = useQueryEditorTableDrop({ props, view: shallowRef(view), editorRef: shallowRef(host), settingsStore: settings as Options["settingsStore"] });
|
||||
cleanups.push(() => {
|
||||
drop.unregisterTableReferenceDropListener();
|
||||
view.destroy();
|
||||
host.remove();
|
||||
});
|
||||
const nativeEvent = (serialized = serializeTableReferencePayload(payload)) => {
|
||||
const dataTransfer = new DataTransfer();
|
||||
dataTransfer.setData(DBX_TABLE_REFERENCE_MIME, serialized);
|
||||
const event = new DragEvent("drop", { clientX: left + 30, clientY: 40, cancelable: true, bubbles: true });
|
||||
Object.defineProperty(event, "dataTransfer", { value: dataTransfer });
|
||||
return event;
|
||||
};
|
||||
return { props, host, view, position, coordinates, settings, drop, nativeEvent };
|
||||
}
|
||||
|
||||
describe("QueryEditor table-reference drop ownership", () => {
|
||||
it("inserts native references at the pointer and clears the hover caret", () => {
|
||||
const { view, drop, nativeEvent } = createHarness();
|
||||
drop.showQueryEditorDropCaretAt(30, 40);
|
||||
const event = nativeEvent();
|
||||
expect(drop.hasDroppedTableReference(event)).toBe(true);
|
||||
expect(drop.insertDroppedTableReference(view, event)).toBe(true);
|
||||
expect(view.state.doc.toString()).toBe("SELECT oldid");
|
||||
expect(view.state.selection.main.anchor).toBe(12);
|
||||
expect(event.defaultPrevented).toBe(true);
|
||||
expect(drop.queryEditorDropCaret.value).toBeNull();
|
||||
});
|
||||
|
||||
it("uses the active pointer payload before native transfer data", () => {
|
||||
const { view, drop, nativeEvent } = createHarness();
|
||||
setActiveTableReferencePayload({ ...payload, columnName: "name" });
|
||||
expect(drop.insertDroppedTableReference(view, nativeEvent())).toBe(true);
|
||||
expect(view.state.doc.toString()).toBe("SELECT oldname");
|
||||
expect(activeTableReferencePayloadValue()).toBeNull();
|
||||
});
|
||||
|
||||
it("falls back to replacing the selection when no pointer position is available", () => {
|
||||
const { view, position, drop, nativeEvent } = createHarness();
|
||||
position.mockReturnValue(null);
|
||||
expect(drop.insertDroppedTableReference(view, nativeEvent())).toBe(true);
|
||||
expect(view.state.doc.toString()).toBe("SELECT id");
|
||||
expect(view.state.selection.main.head).toBe(9);
|
||||
});
|
||||
|
||||
it("ignores malformed payloads without consuming unrelated drops", () => {
|
||||
const { view, drop, nativeEvent } = createHarness();
|
||||
const event = nativeEvent("not-json");
|
||||
expect(drop.insertDroppedTableReference(view, event)).toBe(false);
|
||||
expect(event.defaultPrevented).toBe(false);
|
||||
expect(view.state.doc.toString()).toBe("SELECT old");
|
||||
});
|
||||
|
||||
it("leaves read-only documents and active payloads unchanged", () => {
|
||||
const { view, drop, nativeEvent } = createHarness({ readOnly: true });
|
||||
setActiveTableReferencePayload(payload);
|
||||
expect(drop.insertDroppedTableReference(view, nativeEvent())).toBe(false);
|
||||
expect(view.state.doc.toString()).toBe("SELECT old");
|
||||
expect(activeTableReferencePayloadValue()).toBe(payload);
|
||||
drop.showQueryEditorDropCaretAt(30, 40);
|
||||
expect(drop.queryEditorDropCaret.value).toBeNull();
|
||||
});
|
||||
|
||||
it("converts viewport coordinates to the local caret and clears failed positions", () => {
|
||||
const { drop, position, coordinates } = createHarness({}, 100);
|
||||
drop.showQueryEditorDropCaretAt(130, 40);
|
||||
expect(drop.queryEditorDropCaretStyle.value).toEqual({ left: "25px", top: "10px", height: "18px" });
|
||||
coordinates.mockReturnValue(null);
|
||||
drop.showQueryEditorDropCaretAt(130, 40);
|
||||
expect(drop.queryEditorDropCaret.value).toBeNull();
|
||||
position.mockImplementation(() => {
|
||||
throw new Error("view unavailable");
|
||||
});
|
||||
expect(() => drop.showQueryEditorDropCaretAt(130, 40)).not.toThrow();
|
||||
expect(drop.queryEditorDropCaretStyle.value).toEqual({});
|
||||
});
|
||||
|
||||
it("registers global listeners once and supports unregistering and reactivation", () => {
|
||||
const { view, drop } = createHarness();
|
||||
drop.registerTableReferenceDropListener();
|
||||
drop.registerTableReferenceDropListener();
|
||||
window.dispatchEvent(createTableReferenceDropEvent({ payload, clientX: 30, clientY: 40 }));
|
||||
expect(view.state.doc.toString()).toBe("SELECT oldid");
|
||||
drop.unregisterTableReferenceDropListener();
|
||||
window.dispatchEvent(createTableReferenceDropEvent({ payload, clientX: 30, clientY: 40 }));
|
||||
expect(view.state.doc.toString()).toBe("SELECT oldid");
|
||||
drop.registerTableReferenceDropListener();
|
||||
window.dispatchEvent(createTableReferenceHoverEvent({ clientX: 30, clientY: 40 }));
|
||||
expect(drop.queryEditorDropCaret.value).not.toBeNull();
|
||||
window.dispatchEvent(createTableReferenceDragEndEvent());
|
||||
expect(drop.queryEditorDropCaret.value).toBeNull();
|
||||
});
|
||||
|
||||
it("keeps drops and hover carets isolated between editors", () => {
|
||||
const first = createHarness();
|
||||
const second = createHarness({}, 300);
|
||||
first.drop.registerTableReferenceDropListener();
|
||||
second.drop.registerTableReferenceDropListener();
|
||||
window.dispatchEvent(createTableReferenceHoverEvent({ clientX: 330, clientY: 40 }));
|
||||
expect(first.drop.queryEditorDropCaret.value).toBeNull();
|
||||
expect(second.drop.queryEditorDropCaret.value).not.toBeNull();
|
||||
window.dispatchEvent(createTableReferenceDropEvent({ payload, clientX: 330, clientY: 40 }));
|
||||
expect(first.view.state.doc.toString()).toBe("SELECT old");
|
||||
expect(second.view.state.doc.toString()).toBe("SELECT oldid");
|
||||
});
|
||||
});
|
||||
+184
@@ -0,0 +1,184 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import { computed, createApp, h, reactive, shallowRef } from "vue";
|
||||
import { createPinia, setActivePinia } from "pinia";
|
||||
import { createI18n } from "vue-i18n";
|
||||
import { EditorSelection, EditorState } from "@codemirror/state";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { history, undo, toggleLineComment, toggleBlockComment } from "@codemirror/commands";
|
||||
import { sql } from "@codemirror/lang-sql";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { useQueryEditorTextActions } from "../useQueryEditorTextActions";
|
||||
import { useSettingsStore } from "@/stores/settingsStore";
|
||||
import type { QueryEditorProps } from "../queryEditorTypes";
|
||||
|
||||
const clipboard = vi.hoisted(() => ({ copyToClipboard: vi.fn(), readTextFromClipboard: vi.fn(), copySqlAsRichText: vi.fn() }));
|
||||
vi.mock("@/lib/common/clipboard", () => clipboard);
|
||||
vi.mock("@/lib/sql/sqlRichText", () => ({ copySqlAsRichText: clipboard.copySqlAsRichText }));
|
||||
const cleanups: Array<() => void> = [];
|
||||
|
||||
afterEach(() => {
|
||||
for (const cleanup of cleanups.splice(0).reverse()) cleanup();
|
||||
vi.resetAllMocks();
|
||||
});
|
||||
|
||||
function mountActions(text = "alice\nbob") {
|
||||
const pinia = createPinia();
|
||||
setActivePinia(pinia);
|
||||
const settingsStore = useSettingsStore();
|
||||
const host = document.createElement("div");
|
||||
const editorHost = document.createElement("div");
|
||||
document.body.append(host, editorHost);
|
||||
const props = reactive<QueryEditorProps>({ modelValue: text, databaseType: "mysql", dialect: "mysql" });
|
||||
const state = shallowRef(EditorState.create({ doc: text, selection: { anchor: 0, head: text.length }, extensions: [sql(), history(), EditorState.allowMultipleSelections.of(true)] }));
|
||||
const editorView = new EditorView({
|
||||
state: state.value,
|
||||
parent: editorHost,
|
||||
dispatchTransactions: (transactions, currentView) => {
|
||||
currentView.update(transactions);
|
||||
state.value = currentView.state;
|
||||
},
|
||||
});
|
||||
vi.spyOn(editorView, "focus").mockImplementation(() => {});
|
||||
const view = shallowRef<EditorView | null>(editorView);
|
||||
const selectedSql = computed(() => state.value.sliceDoc(state.value.selection.main.from, state.value.selection.main.to));
|
||||
let actions!: ReturnType<typeof useQueryEditorTextActions>;
|
||||
const app = createApp({
|
||||
setup() {
|
||||
actions = useQueryEditorTextActions({ props, view, selectedSql, settingsStore, sqlBehaviorDialect: () => props.dialect, focusEditor: () => view.value?.focus(), getEditorSelection: () => EditorSelection, toggleLineComment, toggleBlockComment });
|
||||
return () => h("div");
|
||||
},
|
||||
});
|
||||
app.use(pinia);
|
||||
app.use(createI18n({ legacy: false, locale: "en", messages: { en: {} }, missingWarn: false, fallbackWarn: false }));
|
||||
app.mount(host);
|
||||
cleanups.push(() => {
|
||||
app.unmount();
|
||||
editorView.destroy();
|
||||
host.remove();
|
||||
editorHost.remove();
|
||||
});
|
||||
return { actions, view, editorView, props };
|
||||
}
|
||||
|
||||
describe("QueryEditor extracted text actions", () => {
|
||||
it("captures the delimited-list input and replaces the selection with one undoable edit", () => {
|
||||
const { actions, editorView } = mountActions();
|
||||
actions.openDelimitedListDialog();
|
||||
expect(actions.delimitedListOpen.value).toBe(true);
|
||||
expect(actions.delimitedListSelectedText.value).toBe("alice\nbob");
|
||||
actions.applyDelimitedListResult("'alice','bob'");
|
||||
expect(editorView.state.doc.toString()).toBe("'alice','bob'");
|
||||
expect(undo(editorView)).toBe(true);
|
||||
expect(editorView.state.doc.toString()).toBe("alice\nbob");
|
||||
});
|
||||
|
||||
it("guards delimited-list opening and confirmation with the current read-only state", () => {
|
||||
const { actions, editorView, props } = mountActions();
|
||||
props.readOnly = true;
|
||||
actions.openDelimitedListDialog();
|
||||
expect(actions.delimitedListOpen.value).toBe(false);
|
||||
props.readOnly = false;
|
||||
actions.openDelimitedListDialog();
|
||||
props.readOnly = true;
|
||||
actions.applyDelimitedListResult("changed");
|
||||
expect(editorView.state.doc.toString()).toBe("alice\nbob");
|
||||
});
|
||||
|
||||
it("does not open selection dialogs for whitespace-only input", () => {
|
||||
const { actions } = mountActions(" \n ");
|
||||
actions.openDelimitedListDialog();
|
||||
actions.openCodeSnapshot();
|
||||
expect(actions.delimitedListOpen.value).toBe(false);
|
||||
expect(actions.codeSnapshotOpen.value).toBe(false);
|
||||
});
|
||||
|
||||
it("captures the code snapshot without aliasing later selections", () => {
|
||||
const { actions, editorView } = mountActions("SELECT 1");
|
||||
actions.openCodeSnapshot();
|
||||
editorView.dispatch({ selection: { anchor: 0 } });
|
||||
expect(actions.codeSnapshotOpen.value).toBe(true);
|
||||
expect(actions.codeSnapshotSource.value).toEqual({ code: "SELECT 1", lang: "sql" });
|
||||
});
|
||||
|
||||
it("preserves plain and rich-text copying and undoable cutting", async () => {
|
||||
const { actions, editorView } = mountActions("SELECT 1");
|
||||
await actions.copySelectedSqlFromContextMenu();
|
||||
await actions.copySelectedSqlAsRichTextFromContextMenu();
|
||||
expect(clipboard.copyToClipboard).toHaveBeenCalledWith("SELECT 1");
|
||||
expect(clipboard.copySqlAsRichText).toHaveBeenCalledWith("SELECT 1");
|
||||
await actions.cutSelectedSqlFromContextMenu();
|
||||
expect(editorView.state.doc.toString()).toBe("");
|
||||
expect(undo(editorView)).toBe(true);
|
||||
expect(editorView.state.doc.toString()).toBe("SELECT 1");
|
||||
});
|
||||
|
||||
it("does not cut the selection when clipboard writing fails", async () => {
|
||||
clipboard.copyToClipboard.mockRejectedValue(new Error("clipboard unavailable"));
|
||||
const { actions, editorView } = mountActions();
|
||||
await actions.cutSelectedSqlFromContextMenu();
|
||||
expect(editorView.state.doc.toString()).toBe("alice\nbob");
|
||||
});
|
||||
|
||||
it("keeps clipboard normalization, caret placement, undo and read-only guards", async () => {
|
||||
clipboard.readTextFromClipboard.mockResolvedValue("one\r\ntwo");
|
||||
const { actions, editorView, props } = mountActions();
|
||||
await actions.pasteClipboardSqlFromContextMenu();
|
||||
expect(editorView.state.doc.toString()).toBe("one\ntwo");
|
||||
expect(editorView.state.selection.main.head).toBe(7);
|
||||
expect(undo(editorView)).toBe(true);
|
||||
expect(editorView.state.doc.toString()).toBe("alice\nbob");
|
||||
props.readOnly = true;
|
||||
await actions.pasteClipboardSqlFromContextMenu();
|
||||
expect(clipboard.readTextFromClipboard).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("preserves multi-range case conversion and selects each replacement", () => {
|
||||
const { actions, editorView } = mountActions("select id, name from users");
|
||||
editorView.dispatch({ selection: EditorSelection.create([EditorSelection.range(0, 6), EditorSelection.range(16, 20)]) });
|
||||
expect(actions.convertSelectedSqlCase("upper")).toBe(true);
|
||||
expect(editorView.state.doc.toString()).toBe("SELECT id, name FROM users");
|
||||
expect(editorView.state.selection.ranges.map((range) => editorView.state.sliceDoc(range.from, range.to))).toEqual(["SELECT", "FROM"]);
|
||||
expect(undo(editorView)).toBe(true);
|
||||
expect(editorView.state.doc.toString()).toBe("select id, name from users");
|
||||
});
|
||||
|
||||
it("preserves naming conversion and an undoable empty-line deletion", () => {
|
||||
const { actions, editorView } = mountActions("user_name");
|
||||
expect(actions.convertSelectedNamingStyle()).toBe(true);
|
||||
expect(editorView.state.doc.toString()).toBe("USER_NAME");
|
||||
editorView.setState(EditorState.create({ doc: "SELECT 1;\n\nSELECT 2;", extensions: [history()] }));
|
||||
actions.deleteEmptyLines();
|
||||
expect(editorView.state.doc.toString()).toBe("SELECT 1;\nSELECT 2;");
|
||||
expect(undo(editorView)).toBe(true);
|
||||
expect(editorView.state.doc.toString()).toBe("SELECT 1;\n\nSELECT 2;");
|
||||
});
|
||||
|
||||
it("does not apply a pending IN-list paste after the view or read-only state changes", async () => {
|
||||
let resolveClipboard!: (text: string) => void;
|
||||
clipboard.readTextFromClipboard.mockReturnValue(
|
||||
new Promise<string>((resolve) => {
|
||||
resolveClipboard = resolve;
|
||||
}),
|
||||
);
|
||||
const { actions, editorView, props } = mountActions("");
|
||||
const pending = actions.pasteClipboardAsSqlInCondition();
|
||||
props.readOnly = true;
|
||||
resolveClipboard("alice\nbob");
|
||||
expect(await pending).toBe(false);
|
||||
expect(editorView.state.doc.toString()).toBe("");
|
||||
});
|
||||
|
||||
it("tolerates missing views and empty selections without dispatching", async () => {
|
||||
const { actions, view } = mountActions("");
|
||||
view.value = null;
|
||||
expect(actions.convertSelectedSqlCase("upper")).toBe(false);
|
||||
expect(actions.convertSelectedNamingStyle()).toBe(false);
|
||||
expect(await actions.pasteClipboardAsSqlInCondition()).toBe(false);
|
||||
expect(() => {
|
||||
actions.applyDelimitedListResult("text");
|
||||
actions.deleteEmptyLines();
|
||||
actions.selectAllSqlFromContextMenu();
|
||||
}).not.toThrow();
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user