Skip to content

armgit / dbx

Public Imported from GitHub
0

25 MB lightweight cross-platform database client for 100+ databases, including MySQL, PostgreSQL, SQLite, Redis, MongoDB, DuckDB, SQL Server, and Dameng. Built-in AI, MCP Server, CLI, desktop and Docker. | 轻量级跨平台数据库管理工具,支持 MySQL、PostgreSQL、SQLite、Redis、MongoDB、达梦等 100+ 数据库,提供桌面端、Docker、CLI、内置 AI 助手和 MCP。

9.3 KB
Raw Blame
// @vitest-environment happy-dom

import { EditorState } from "@codemirror/state";
import { EditorView } from "@codemirror/view";
import { createApp, defineComponent, h, inject, nextTick, provide, reactive, toRef, type App, type Ref, watch } from "vue";
import { afterEach, describe, expect, it, vi } from "vitest";
import i18n from "@/i18n";
import DangerConfirmDialog from "@/components/editor/DangerConfirmDialog.vue";

vi.mock("@/composables/useSqlHighlighter", () => ({
  useSqlHighlighter: () => ({ highlight: (sql: string) => sql }),
}));

const dialogHarness = vi.hoisted(() => {
  const pendingCloseAutoFocus: Array<() => Event> = [];
  const pendingOpenAutoFocus: Array<() => Event> = [];
  return {
    pendingCloseAutoFocus,
    pendingOpenAutoFocus,
    flushCloseAutoFocus: () => pendingCloseAutoFocus.shift()?.(),
    flushOpenAutoFocus: () => pendingOpenAutoFocus.shift()?.(),
    reset: () => {
      pendingCloseAutoFocus.splice(0);
      pendingOpenAutoFocus.splice(0);
    },
  };
});

vi.mock("@/components/ui/dialog", () => {
  const dialogContextKey = Symbol("dialog-focus-test");
  type DialogContext = { open: Readonly<Ref<boolean>>; trigger: Element | null };

  const passthrough = () =>
    defineComponent({
      setup:
        (_, { slots }) =>
        () =>
          h("div", slots.default?.()),
    });

  const Dialog = defineComponent({
    props: { open: { type: Boolean, default: false } },
    setup(props, { slots }) {
      provide<DialogContext>(dialogContextKey, {
        open: toRef(props, "open"),
        trigger: document.activeElement,
      });
      return () => h("div", slots.default?.());
    },
  });

  const DialogContent = defineComponent({
    emits: ["openAutoFocus", "closeAutoFocus"],
    setup(_, { emit, slots }) {
      const context = inject<DialogContext>(dialogContextKey);
      if (!context) throw new Error("DialogContent must be nested in Dialog");

      const queueOpenAutoFocus = () => {
        dialogHarness.pendingOpenAutoFocus.push(() => {
          const event = new Event("open-auto-focus", { cancelable: true });
          emit("openAutoFocus", event);
          return event;
        });
      };

      if (context.open.value) {
        queueOpenAutoFocus();
      }

      watch(context.open, (isOpen, wasOpen) => {
        if (isOpen && !wasOpen) {
          queueOpenAutoFocus();
          return;
        }
        if (isOpen || !wasOpen) return;
        dialogHarness.pendingCloseAutoFocus.push(() => {
          const event = new Event("close-auto-focus", { cancelable: true });
          emit("closeAutoFocus", event);
          if (!event.defaultPrevented && context.trigger instanceof HTMLElement && context.trigger.isConnected) {
            context.trigger.focus();
            context.trigger.dispatchEvent(new Event("test-native-focus-restoration"));
          }
          return event;
        });
      });

      return () => h("div", slots.default?.());
    },
  });

  return {
    Dialog,
    DialogContent,
    DialogFooter: passthrough(),
    DialogHeader: passthrough(),
    DialogTitle: passthrough(),
  };
});

const mountedApps: App[] = [];
const editorViews: EditorView[] = [];

afterEach(() => {
  dialogHarness.reset();
  for (const app of mountedApps.splice(0)) app.unmount();
  for (const view of editorViews.splice(0)) view.destroy();
  document.body.innerHTML = "";
});

function mountDialog(state: { open: boolean }, extraProps: Record<string, unknown> = {}) {
  const dialogHost = document.createElement("div");
  document.body.append(dialogHost);
  const app = createApp(
    defineComponent({
      setup: () => () =>
        h(DangerConfirmDialog, {
          open: state.open,
          sql: "UPDATE users SET active = 0;",
          confirmLabel: "Execute",
          ...extraProps,
          "onUpdate:open": (open: boolean) => {
            state.open = open;
          },
        }),
    }),
  );
  mountedApps.push(app);
  app.use(i18n);
  app.mount(dialogHost);
  return dialogHost;
}

function findCancelButton(host: HTMLElement) {
  const button = [...host.querySelectorAll<HTMLButtonElement>("button")].find((candidate) => candidate.textContent?.includes("Cancel"));
  if (!button) throw new Error("Cancel button not found");
  return button;
}

function createEditor() {
  const editorHost = document.createElement("div");
  document.body.append(editorHost);
  const view = new EditorView({
    state: EditorState.create({
      doc: "SELECT 1;\nUPDATE users SET active = 0;\nSELECT 2;",
      selection: { anchor: 20 },
    }),
    parent: editorHost,
  });
  editorViews.push(view);
  view.focus();
  view.contentDOM.addEventListener("test-native-focus-restoration", () => {
    view.dispatch({ selection: { anchor: 0 } });
  });
  return view;
}

function findConfirmButton(host: HTMLElement) {
  const button = [...host.querySelectorAll<HTMLButtonElement>("button")].find((candidate) => candidate.textContent?.includes("Execute"));
  if (!button) throw new Error("Confirm button not found");
  return button;
}

describe("DangerConfirmDialog focus restoration", () => {
  it("prevents native restoration and keeps the CodeMirror selection after confirm", async () => {
    const view = createEditor();
    const state = reactive({ open: true });
    const dialogHost = mountDialog(state);
    await nextTick();

    const confirm = findConfirmButton(dialogHost);
    confirm.focus();
    confirm.click();
    await nextTick();

    const closeAutoFocus = dialogHarness.flushCloseAutoFocus();
    expect(closeAutoFocus?.defaultPrevented).toBe(true);
    await vi.waitFor(() => expect(document.activeElement).toBe(view.contentDOM));
    expect(view.state.selection.main.head).toBe(20);
  });

  it("leaves default restoration available for non-CodeMirror triggers", async () => {
    const trigger = document.createElement("button");
    document.body.append(trigger);
    trigger.focus();

    const state = reactive({ open: true });
    const dialogHost = mountDialog(state);
    await nextTick();
    const confirm = findConfirmButton(dialogHost);
    confirm.focus();
    confirm.click();
    await nextTick();

    const closeAutoFocus = dialogHarness.flushCloseAutoFocus();
    expect(closeAutoFocus?.defaultPrevented).toBe(false);
    expect(document.activeElement).toBe(trigger);
  });

  it("preserves the pending editor across an interrupted close and reopen", async () => {
    const view = createEditor();
    const state = reactive({ open: true });
    const dialogHost = mountDialog(state);
    await nextTick();
    const confirm = findConfirmButton(dialogHost);

    confirm.focus();
    confirm.click();
    await nextTick();
    state.open = true;
    await nextTick();
    confirm.focus();

    const interruptedClose = dialogHarness.flushCloseAutoFocus();
    expect(interruptedClose?.defaultPrevented).toBe(true);
    expect(document.activeElement).toBe(confirm);
    expect(view.state.selection.main.head).toBe(20);

    confirm.click();
    await nextTick();
    const finalClose = dialogHarness.flushCloseAutoFocus();
    expect(finalClose?.defaultPrevented).toBe(true);
    await vi.waitFor(() => expect(document.activeElement).toBe(view.contentDOM));
    expect(view.state.selection.main.head).toBe(20);
  });
});

describe("DangerConfirmDialog initial focus on open", () => {
  it("defaults to focusing the confirm button on open", async () => {
    const state = reactive({ open: true });
    const dialogHost = mountDialog(state);
    await nextTick();

    const openEvent = dialogHarness.flushOpenAutoFocus();
    expect(openEvent?.defaultPrevented).toBe(true);

    const confirm = findConfirmButton(dialogHost);
    expect(document.activeElement).toBe(confirm);
  });

  it("focuses the cancel button on open when initialFocus is 'cancel'", async () => {
    const state = reactive({ open: true });
    const dialogHost = mountDialog(state, { initialFocus: "cancel" });
    await nextTick();

    const openEvent = dialogHarness.flushOpenAutoFocus();
    expect(openEvent?.defaultPrevented).toBe(true);

    const cancel = findCancelButton(dialogHost);
    expect(document.activeElement).toBe(cancel);
  });

  it("does not override default focus when initialFocus is 'default'", async () => {
    const state = reactive({ open: true });
    const dialogHost = mountDialog(state, { initialFocus: "default" });
    await nextTick();

    const openEvent = dialogHarness.flushOpenAutoFocus();
    expect(openEvent?.defaultPrevented).toBe(false);

    const confirm = findConfirmButton(dialogHost);
    expect(document.activeElement).not.toBe(confirm);
  });

  it("does not override default focus when confirmDisabled is true", async () => {
    const state = reactive({ open: true });
    const dialogHost = mountDialog(state, { confirmDisabled: true });
    await nextTick();

    const openEvent = dialogHarness.flushOpenAutoFocus();
    expect(openEvent?.defaultPrevented).toBe(false);

    const confirm = findConfirmButton(dialogHost);
    expect(document.activeElement).not.toBe(confirm);
  });

  it("does not override default focus when loading is true", async () => {
    const state = reactive({ open: true });
    const dialogHost = mountDialog(state, { loading: true });
    await nextTick();

    const openEvent = dialogHarness.flushOpenAutoFocus();
    expect(openEvent?.defaultPrevented).toBe(false);

    const confirm = findConfirmButton(dialogHost);
    expect(document.activeElement).not.toBe(confirm);
  });
});