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。

8.9 KB
Raw Blame
<script setup lang="ts">
import { ref, computed, watch, onMounted, nextTick } from "vue";
import { useI18n } from "vue-i18n";
import { AlignLeft, Copy, ChevronDown, Undo2, Redo2 } from "@lucide/vue";
import { Button } from "@/components/ui/button";
import { Tooltip, TooltipTrigger, TooltipContent } from "@/components/ui/tooltip";
import { useTheme } from "@/composables/useTheme";
import { useToast } from "@/composables/useToast";
import { copyToClipboard, isPlainClipboardShortcut } from "@/lib/common/clipboard";
import { formatSqlText, type SqlFormatDialect } from "@/lib/sql/sqlFormatter";
import { createShikiSqlHighlighter, type SqlHighlighter } from "@/lib/sql/sqlHighlighter";
import { useSettingsStore } from "@/stores/settingsStore";

const props = defineProps<{
  sql: string;
  sqlFormatDialect?: SqlFormatDialect;
  loading?: boolean;
  emptyMessage?: string;
  canUndo?: boolean;
  canRedo?: boolean;
}>();

const emit = defineEmits<{
  close: [];
  undo: [];
  redo: [];
}>();

const { t } = useI18n();
const { isDark } = useTheme();
const { toast } = useToast();
const settingsStore = useSettingsStore();

const isFormatted = ref(false);
const formattedSql = ref("");
const formatting = ref(false);
const highlightedHtml = ref("");
const highlighterReady = ref(false);

let highlighter: SqlHighlighter | null = null;

const displaySql = computed(() => {
  if (isFormatted.value && formattedSql.value) {
    return formattedSql.value;
  }
  return props.sql;
});

const hasSql = computed(() => props.sql.trim().length > 0);

const contentRef = ref<HTMLPreElement | null>(null);

function selectPreviewContent() {
  const el = contentRef.value;
  if (!el) return false;
  const range = document.createRange();
  range.selectNodeContents(el);
  const selection = window.getSelection();
  selection?.removeAllRanges();
  selection?.addRange(range);
  return true;
}

/** Text the user actually highlighted inside the preview, if any. */
function selectedPreviewText(): string {
  const selection = window.getSelection();
  if (!selection || selection.isCollapsed || selection.rangeCount === 0) return "";
  const el = contentRef.value;
  if (!el) return "";
  // Only a selection that lives inside this preview counts; one leaked from the
  // surrounding grid must not be copied as if it were the preview text.
  for (let index = 0; index < selection.rangeCount; index += 1) {
    const range = selection.getRangeAt(index);
    if (!el.contains(range.commonAncestorContainer)) return "";
  }
  return selection.toString();
}

async function copySelectionOrAll(event: KeyboardEvent) {
  const text = selectedPreviewText() || displaySql.value;
  if (!text.trim()) return;
  event.preventDefault();
  event.stopPropagation();
  await copyPreviewText(text);
}

function onContentKeydown(event: KeyboardEvent) {
  if (isPlainClipboardShortcut(event, "a")) {
    // Claim the shortcut before it reaches the surrounding data grid, then select
    // the preview text instead of the grid cells.
    if (selectPreviewContent()) event.preventDefault();
    return;
  }
  // A programmatically built selection (Ctrl+A above) is not guaranteed to reach
  // the system clipboard through the webview's native copy, so copy it through the
  // app clipboard instead: the toast already claimed success that never happened
  // (#12167).
  if (isPlainClipboardShortcut(event, "c")) void copySelectionOrAll(event);
}

async function initHighlighter() {
  if (highlighter) return;
  try {
    highlighter = await createShikiSqlHighlighter({
      appearance: () => (isDark.value ? "dark" : "light"),
      themePreset: "preview",
    });
    highlighterReady.value = true;
    await highlightSql();
  } catch (e) {
    console.error("[DBX][SqlPreviewPanel] Failed to init shiki:", e);
  }
}

async function highlightSql() {
  if (!highlighter || !displaySql.value) return;
  try {
    highlightedHtml.value = highlighter(displaySql.value);
  } catch {
    // fallback to plain text
    highlightedHtml.value = "";
  }
}

async function toggleFormat() {
  if (formatting.value || !hasSql.value) return;
  if (isFormatted.value) {
    isFormatted.value = false;
    await highlightSql();
    return;
  }

  formatting.value = true;
  try {
    let diagnostic: "custom-rules-fallback" | undefined;
    formattedSql.value = await formatSqlText(props.sql, props.sqlFormatDialect ?? "generic", settingsStore.editorSettings.sqlFormatter, (value) => {
      diagnostic = value;
    });
    isFormatted.value = true;
    if (diagnostic === "custom-rules-fallback") toast(t("settings.sqlFormatterFallbackNotice"), 4000);
    await highlightSql();
  } catch {
    toast(t("toolbar.formatSqlFailed"), 3000);
  } finally {
    formatting.value = false;
  }
}

async function handleCopy() {
  const text = displaySql.value;
  if (!text.trim()) return;
  await copyPreviewText(text);
}

async function copyPreviewText(text: string) {
  try {
    await copyToClipboard(text);
    toast(t("grid.copied"));
  } catch (e: any) {
    toast(t("grid.copyFailed", { message: e?.message || String(e) }), 5000);
  }
}

watch(
  () => props.sql,
  async (newSql) => {
    isFormatted.value = false;
    formattedSql.value = "";
    if (highlighterReady.value && newSql.trim()) {
      await highlightSql();
    }
  },
);

watch(isDark, async () => {
  if (highlighterReady.value && displaySql.value) {
    await highlightSql();
  }
});

watch(displaySql, async () => {
  if (highlighterReady.value) {
    await highlightSql();
  }
});

onMounted(() => {
  nextTick(() => {
    void initHighlighter();
  });
});
</script>

<template>
  <div class="h-full flex flex-col bg-background border-t">
    <!-- Header bar -->
    <div class="h-8 shrink-0 border-b bg-muted/30 px-2 flex items-center gap-1 text-xs text-muted-foreground">
      <span class="font-medium text-muted-foreground/70 select-none">SQL</span>
      <span class="flex-1 min-w-0" />
      <Tooltip>
        <TooltipTrigger as-child>
          <Button variant="ghost" size="icon" class="h-6 w-6" :class="isFormatted ? 'text-amber-600 bg-amber-500/10' : 'text-amber-600/60 hover:text-amber-700 hover:bg-amber-500/10'" :disabled="formatting || !hasSql" :aria-label="t('toolbar.formatSql')" @click="toggleFormat">
            <AlignLeft class="h-3.5 w-3.5" />
          </Button>
        </TooltipTrigger>
        <TooltipContent>{{ t("toolbar.formatSql") }}</TooltipContent>
      </Tooltip>
      <Tooltip>
        <TooltipTrigger as-child>
          <Button variant="ghost" size="icon" class="h-6 w-6 text-muted-foreground/60 hover:text-foreground hover:bg-accent" :disabled="!canUndo" :aria-label="t('grid.undoChange')" @click="emit('undo')">
            <Undo2 class="h-3.5 w-3.5" />
          </Button>
        </TooltipTrigger>
        <TooltipContent>{{ t("grid.undoChange") }}</TooltipContent>
      </Tooltip>
      <Tooltip>
        <TooltipTrigger as-child>
          <Button variant="ghost" size="icon" class="h-6 w-6 text-muted-foreground/60 hover:text-foreground hover:bg-accent" :disabled="!canRedo" :aria-label="t('grid.redoChange')" @click="emit('redo')">
            <Redo2 class="h-3.5 w-3.5" />
          </Button>
        </TooltipTrigger>
        <TooltipContent>{{ t("grid.redoChange") }}</TooltipContent>
      </Tooltip>
      <Tooltip>
        <TooltipTrigger as-child>
          <Button variant="ghost" size="icon" class="h-6 w-6 text-muted-foreground/60 hover:text-foreground hover:bg-accent" :disabled="!hasSql" :aria-label="t('grid.copy')" @click="handleCopy">
            <Copy class="h-3.5 w-3.5" />
          </Button>
        </TooltipTrigger>
        <TooltipContent>{{ t("grid.copy") }}</TooltipContent>
      </Tooltip>
      <Tooltip>
        <TooltipTrigger as-child>
          <Button variant="ghost" size="icon" class="h-6 w-6 text-muted-foreground/60 hover:text-foreground hover:bg-accent" :aria-label="t('toolbar.hidePreviewSql')" @click="emit('close')">
            <ChevronDown class="h-3.5 w-3.5" />
          </Button>
        </TooltipTrigger>
        <TooltipContent>{{ t("toolbar.hidePreviewSql") }}</TooltipContent>
      </Tooltip>
    </div>

    <!-- Content -->
    <div class="flex-1 min-h-0 overflow-auto">
      <!-- Loading -->
      <div v-if="loading" class="flex items-center justify-center h-full text-xs text-muted-foreground">
        {{ t("common.loading") }}
      </div>

      <!-- Empty -->
      <div v-else-if="!hasSql" class="flex items-center justify-center h-full text-xs text-muted-foreground">
        {{ emptyMessage || t("grid.previewSqlEmpty") }}
      </div>

      <!-- Shiki highlighted SQL -->
      <pre v-else-if="highlightedHtml" ref="contentRef" data-native-clipboard tabindex="0" class="m-0 p-3 text-xs font-mono leading-relaxed whitespace-pre-wrap break-words select-text outline-none" v-html="highlightedHtml" @keydown="onContentKeydown"></pre>

      <!-- Plain text fallback -->
      <pre v-else ref="contentRef" data-native-clipboard tabindex="0" class="p-3 text-xs font-mono whitespace-pre-wrap select-text outline-none" @keydown="onContentKeydown">{{ displaySql }}</pre>
    </div>
  </div>
</template>