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。
TypeScript aicliclickhousedatabasedatabase-clientdatabase-managementdockerguimcpmongodbmysqlpostgresqlredisrustsql-serversqlitetaurivue
feat(editor): add code snapshot export
Abeautifulsnow30f5c3472997
diff --git a/Cargo.lock b/Cargo.lockindex da4c4b239f..5d26dae9f6 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -8443,6 +8443,7 @@ dependencies = ["gtk","heck 0.5.0","http 1.5.0",+ "image","jni 0.21.1","libc","log",diff --git a/apps/desktop/src/components/codeSnapshot/CodeSnapshotDialog.vue b/apps/desktop/src/components/codeSnapshot/CodeSnapshotDialog.vuenew file mode 100644index 0000000000..0a389ea300--- /dev/null+++ b/apps/desktop/src/components/codeSnapshot/CodeSnapshotDialog.vue@@ -0,0 +1,221 @@+<script setup lang="ts">+import { computed, onBeforeUnmount, ref, watch } from "vue";+import { useI18n } from "vue-i18n";+import { Camera, Check, ClipboardCopy, Download, Moon, Sun } from "@lucide/vue";+import { Button } from "@/components/ui/button";+import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";+import { Input } from "@/components/ui/input";+import { Label } from "@/components/ui/label";+import { Switch } from "@/components/ui/switch";+import { useToast } from "@/composables/useToast";+import { useTheme } from "@/composables/useTheme";+import { renderCodeSnapshotHtml, snapshotElementToPng, copyPngDataUrlToClipboard, savePngDataUrlToFile, type CodeSnapshotSource } from "@/lib/codeSnapshot/codeSnapshot";++const { t } = useI18n();+const { toast } = useToast();+const { isDark } = useTheme();++const open = defineModel<boolean>("open", { default: false });++const props = defineProps<{+ source: CodeSnapshotSource | null;+}>();++const STORAGE_KEY = "dbx:code-snapshot-settings";++interface CodeSnapshotUiSettings {+ appearance: "light" | "dark";+ showTrafficLights: boolean;+ showLineNumbers: boolean;+}++function loadUiSettings(): CodeSnapshotUiSettings {+ const fallback: CodeSnapshotUiSettings = {+ appearance: isDark.value ? "dark" : "light",+ showTrafficLights: true,+ showLineNumbers: true,+ };+ try {+ const raw = localStorage.getItem(STORAGE_KEY);+ if (raw) return { ...fallback, ...JSON.parse(raw) };+ } catch {+ /* ignore */+ }+ return fallback;+}++const initialUiSettings = loadUiSettings();+const appearance = ref<"light" | "dark">(initialUiSettings.appearance);+const showTrafficLights = ref(initialUiSettings.showTrafficLights);+const showLineNumbers = ref(initialUiSettings.showLineNumbers);+const title = ref("");++function persistUiSettings() {+ try {+ const settings: CodeSnapshotUiSettings = {+ appearance: appearance.value,+ showTrafficLights: showTrafficLights.value,+ showLineNumbers: showLineNumbers.value,+ };+ localStorage.setItem(STORAGE_KEY, JSON.stringify(settings));+ } catch {+ /* ignore */+ }+}+watch([appearance, showTrafficLights, showLineNumbers], persistUiSettings);++const snapshotHtml = ref("");+const previewWrapRef = ref<HTMLDivElement>();+const exporting = ref(false);+const copied = ref(false);+let copyResetTimer: ReturnType<typeof setTimeout> | null = null;+let titleDebounceTimer: ReturnType<typeof setTimeout> | null = null;++function snapshotRoot(): HTMLElement | null {+ return previewWrapRef.value?.querySelector<HTMLElement>(".dbx-code-snapshot") ?? null;+}++async function renderSnapshot() {+ if (!open.value || !props.source) return;+ try {+ snapshotHtml.value = await renderCodeSnapshotHtml(+ {+ code: props.source.code,+ lang: props.source.lang,+ title: title.value.trim() || props.source.title,+ },+ {+ appearance: appearance.value,+ showTrafficLights: showTrafficLights.value,+ showLineNumbers: showLineNumbers.value,+ },+ );+ } catch (e: any) {+ snapshotHtml.value = "";+ toast(t("codeSnapshot.failed", { message: e?.message || String(e) }), 5000);+ }+}++// Reset the title for each new snapshot source instead of leaking the+// previous snapshot's title across opens.+watch(+ [open, () => props.source],+ ([isOpen, source]) => {+ if (isOpen && source) title.value = source.title ?? "";+ },+ { immediate: true },+);++// Appearance / toggle options re-render immediately; the title input is+// debounced so typing large code blocks stays responsive.+watch([open, () => props.source, appearance, showTrafficLights, showLineNumbers], renderSnapshot, {+ immediate: true,+});+watch(title, () => {+ if (titleDebounceTimer) clearTimeout(titleDebounceTimer);+ titleDebounceTimer = setTimeout(renderSnapshot, 300);+});++onBeforeUnmount(() => {+ if (copyResetTimer) clearTimeout(copyResetTimer);+ if (titleDebounceTimer) clearTimeout(titleDebounceTimer);+});++function sanitizeFileName(value: string): string {+ return value.replace(/[\\/:*?"<>|]/g, "-").trim() || "code-snapshot";+}++async function exportSnapshot(kind: "clipboard" | "file") {+ const root = snapshotRoot();+ if (!root || exporting.value) return;+ exporting.value = true;+ try {+ const dataUrl = await snapshotElementToPng(root);+ if (kind === "clipboard") {+ await copyPngDataUrlToClipboard(dataUrl);+ copied.value = true;+ toast(t("codeSnapshot.copied"));+ if (copyResetTimer) clearTimeout(copyResetTimer);+ copyResetTimer = setTimeout(() => {+ copied.value = false;+ }, 2000);+ } else {+ const base = sanitizeFileName(title.value.trim() || (props.source?.title ?? "code-snapshot"));+ const saved = await savePngDataUrlToFile(dataUrl, `${base}-${Date.now()}.png`);+ if (saved) toast(t("codeSnapshot.saved"));+ }+ } catch (e: any) {+ toast(t("codeSnapshot.failed", { message: e?.message || String(e) }), 5000);+ } finally {+ exporting.value = false;+ }+}++const previewVisible = computed(() => open.value && !!props.source);+</script>++<template>+ <Dialog v-model:open="open">+ <DialogContent class="max-h-[86vh] overflow-y-auto border border-border !bg-background text-foreground shadow-2xl !backdrop-blur-none sm:max-w-[860px]">+ <DialogHeader>+ <DialogTitle class="flex items-center gap-2">+ <Camera class="h-5 w-5 text-primary" />+ {{ t("codeSnapshot.title") }}+ </DialogTitle>+ </DialogHeader>++ <div v-if="previewVisible" class="flex flex-col gap-4 md:flex-row">+ <!-- Snapshot preview -->+ <div class="min-w-0 flex-1">+ <div ref="previewWrapRef" class="max-h-[56vh] overflow-auto rounded-md border bg-muted/30 p-3">+ <div v-html="snapshotHtml" class="inline-block min-w-[320px]" />+ </div>+ </div>++ <!-- Options -->+ <div class="w-full shrink-0 space-y-3 md:w-52">+ <div class="grid gap-1.5">+ <Label class="text-xs">{{ t("codeSnapshot.theme") }}</Label>+ <div class="flex gap-1.5">+ <Button size="sm" variant="outline" class="h-7 flex-1 gap-1 text-[11px]" :class="{ 'border-primary text-primary': appearance === 'light' }" @click="appearance = 'light'">+ <Sun class="h-3 w-3" />+ {{ t("codeSnapshot.themeLight") }}+ </Button>+ <Button size="sm" variant="outline" class="h-7 flex-1 gap-1 text-[11px]" :class="{ 'border-primary text-primary': appearance === 'dark' }" @click="appearance = 'dark'">+ <Moon class="h-3 w-3" />+ {{ t("codeSnapshot.themeDark") }}+ </Button>+ </div>+ </div>++ <div class="flex items-center justify-between gap-2">+ <Label class="text-xs">{{ t("codeSnapshot.windowControls") }}</Label>+ <Switch v-model:checked="showTrafficLights" />+ </div>+ <div class="flex items-center justify-between gap-2">+ <Label class="text-xs">{{ t("codeSnapshot.lineNumbers") }}</Label>+ <Switch v-model:checked="showLineNumbers" />+ </div>++ <div class="grid gap-1.5">+ <Label class="text-xs">{{ t("codeSnapshot.titleLabel") }}</Label>+ <Input v-model="title" class="h-8 text-xs" :placeholder="t('codeSnapshot.titlePlaceholder')" />+ </div>+ </div>+ </div>++ <DialogFooter>+ <Button variant="outline" @click="open = false">{{ t("codeSnapshot.close") }}</Button>+ <Button variant="outline" :disabled="exporting" @click="exportSnapshot('clipboard')">+ <Check v-if="copied" class="mr-1.5 h-4 w-4 text-green-500" />+ <ClipboardCopy v-else class="mr-1.5 h-4 w-4" />+ {{ copied ? t("codeSnapshot.copied") : t("codeSnapshot.copy") }}+ </Button>+ <Button :disabled="exporting" @click="exportSnapshot('file')">+ <Download class="mr-1.5 h-4 w-4" />+ {{ t("codeSnapshot.save") }}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+</template>diff --git a/apps/desktop/src/components/editor/AiAssistant.vue b/apps/desktop/src/components/editor/AiAssistant.vueindex c0e55aec09..2276d4bb4d 100644--- a/apps/desktop/src/components/editor/AiAssistant.vue+++ b/apps/desktop/src/components/editor/AiAssistant.vue@@ -9,6 +9,7 @@ import {ArrowRightLeft,AlertTriangle,Bot,+ Camera,Check,ChevronLeft,ChevronRight,@@ -44,6 +45,8 @@ import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@import { Popover, PopoverAnchor, PopoverContent, PopoverTrigger } from "@/components/ui/popover";import { ScrollArea } from "@/components/ui/scroll-area";import { useTheme } from "@/composables/useTheme";+import CodeSnapshotDialog from "@/components/codeSnapshot/CodeSnapshotDialog.vue";+import type { CodeSnapshotSource } from "@/lib/codeSnapshot/codeSnapshot";import { useSettingsStore, AI_PROVIDER_PRESETS, normalizeAiConfig } from "@/stores/settingsStore";import AiProviderLogo from "@/components/icons/AiProviderLogo.vue";import { useConnectionStore } from "@/stores/connectionStore";@@ -843,6 +846,14 @@ function sendProposalReply(positive: boolean) {const activePlaceholder = computed(() => `${t(`ai.placeholders.${activeAction.value}`)} ${t("ai.tableMentionPlaceholderHint")}`);const aiCodeAppearance = computed(() => (isDark.value ? "dark" : "light"));+const codeSnapshotOpen = ref(false);+const codeSnapshotSource = ref<CodeSnapshotSource | null>(null);++function openCodeSnapshot(seg: { content: string; lang: string }) {+ codeSnapshotSource.value = { code: seg.content, lang: seg.lang };+ codeSnapshotOpen.value = true;+}+const showActionButtons = computed(() => {if (!props.connection) return true;return !isVectorDbType(props.connection.db_type);@@ -2640,6 +2651,9 @@ async function openExternalUrl(url: string) {<Check v-if="copiedContentKey === `code:${i}:${j}`" class="h-3.5 w-3.5 text-green-400" /><Copy v-else class="h-3.5 w-3.5" /></button>+ <button class="rounded p-0.5 text-zinc-500 hover:bg-zinc-200 hover:text-zinc-900 dark:text-zinc-400 dark:hover:bg-zinc-700 dark:hover:text-zinc-200" :title="t('codeSnapshot.take')" @click="openCodeSnapshot(seg)">+ <Camera class="h-3.5 w-3.5" />+ </button></div></div><pre class="ai-code-block whitespace-pre-wrap break-words p-3 text-xs leading-relaxed text-zinc-900 dark:text-zinc-100"><code v-html="seg.html"></code></pre>@@ -3116,6 +3130,7 @@ async function openExternalUrl(url: string) {</div></div></div>+ <CodeSnapshotDialog v-model:open="codeSnapshotOpen" :source="codeSnapshotSource" /></div></div></template>diff --git a/apps/desktop/src/components/editor/QueryEditor.vue b/apps/desktop/src/components/editor/QueryEditor.vueindex d05d1a2655..b73f86c248 100644--- a/apps/desktop/src/components/editor/QueryEditor.vue+++ b/apps/desktop/src/components/editor/QueryEditor.vue@@ -1,6 +1,6 @@<script setup lang="ts">import { ref, onMounted, onBeforeUnmount, onActivated, onDeactivated, watch, shallowRef, computed, nextTick } from "vue";-import { AlignLeft, CaseLower, CaseUpper, ClipboardPaste, Code2, Download, FileCode, MessageSquareText, Minimize2, Pencil, PencilRuler, Play, Copy, List, Scissors, Search, Sparkles, Table2, TextSelect, Trash2 } from "@lucide/vue";+import { AlignLeft, Camera, CaseLower, CaseUpper, ClipboardPaste, Code2, Download, FileCode, MessageSquareText, Minimize2, Pencil, PencilRuler, Play, Copy, List, Scissors, Search, Sparkles, Table2, TextSelect, Trash2 } from "@lucide/vue";import { useI18n } from "vue-i18n";import type { CompletionContext } from "@codemirror/autocomplete";import { Transaction, StateEffect } from "@codemirror/state";@@ -9,7 +9,9 @@ import { search as cmSearch } from "@codemirror/search";import EditorSearchPanel from "./EditorSearchPanel.vue";import SqlExecutionTargetPicker from "./SqlExecutionTargetPicker.vue";import DelimitedListDialog from "./DelimitedListDialog.vue";+import CodeSnapshotDialog from "@/components/codeSnapshot/CodeSnapshotDialog.vue";import CustomContextMenu, { type ContextMenuItem } from "@/components/ui/CustomContextMenu.vue";+import type { CodeSnapshotSource } from "@/lib/codeSnapshot/codeSnapshot";import { copyToClipboard, readTextFromClipboard } from "@/lib/common/clipboard";import { completionMatchRanges } from "@/lib/common/completionMatch";import { executionCandidateForMode, resolveExecutableSql, type SqlExecutionSnapshot, type SqlExecutionOverride, type SqlExecutionCandidate } from "@/lib/sql/sqlExecutionTarget";@@ -368,6 +370,8 @@ const pickerAnchor = ref<{ left: number; top: number }>();// Delimited list dialog stateconst delimitedListOpen = ref(false);const delimitedListSelectedText = ref("");+const codeSnapshotOpen = ref(false);+const codeSnapshotSource = ref<CodeSnapshotSource | null>(null);function openDelimitedListDialog() {if (props.readOnly) return;@@ -1772,6 +1776,17 @@ const contextMenuItems = computed<ContextMenuItem[]>(() => {icon: Copy,shortcut: "Mod+C",},+ {+ label: t("editor.contextMenu.screenshotSelection"),+ action: () => {+ if (selectedSql.value.trim()) {+ codeSnapshotSource.value = { code: selectedSql.value, lang: "sql" };+ codeSnapshotOpen.value = true;+ }+ },+ disabled: !canCopySelectedSql.value,+ icon: Camera,+ },{label: t("editor.contextMenu.cutSelection"),action: cutSelectedSqlFromContextMenu,@@ -5843,6 +5858,7 @@ defineExpose({<EditorSearchPanel ref="searchPanelRef" :view="view" /><SqlExecutionTargetPicker v-if="pickerVisible" :candidates="pickerCandidates" :active-index="pickerActiveIndex" :anchor="pickerAnchor" @update:active-index="onPickerActiveIndexChange" @confirm="onPickerConfirm" @cancel="closePicker" /><DelimitedListDialog v-model:open="delimitedListOpen" :selected-text="delimitedListSelectedText" @confirm="applyDelimitedListResult" />+ <CodeSnapshotDialog v-model:open="codeSnapshotOpen" :source="codeSnapshotSource" /><!-- SQL 意图操作弹出菜单(参考 DataGrip Alt+Enter) --><Teleport to="body"><div v-if="intentionPopup?.visible" class="intention-popup-overlay" @click.self="closeIntentionPopup">diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.tsindex 6dde70208e..74d5353293 100644--- a/apps/desktop/src/i18n/locales/en.ts+++ b/apps/desktop/src/i18n/locales/en.ts@@ -1287,6 +1287,7 @@ export default {export: "Export",exportQueryResultTo: "Export current query result to {format}",copySelection: "Copy selection",+ screenshotSelection: "Screenshot Selected Code",commentSelection: "Comment selection",blockCommentSelection: "Block comment selection",formatSelectionSql: "Format selected SQL",@@ -8337,4 +8338,21 @@ export default {cellRowMissing: "Row does not exist",cellColumnMissing: "Column does not exist",},+ codeSnapshot: {+ title: "Code Snapshot",+ close: "Close",+ copy: "Copy to Clipboard",+ save: "Save PNG",+ copied: "Copied",+ saved: "Saved",+ failed: "Failed: {message}",+ take: "Snapshot Code",+ theme: "Theme",+ themeLight: "Light",+ themeDark: "Dark",+ windowControls: "Window Controls",+ lineNumbers: "Line Numbers",+ titleLabel: "Title (optional)",+ titlePlaceholder: "e.g. Query example",+ },};diff --git a/apps/desktop/src/i18n/locales/es.ts b/apps/desktop/src/i18n/locales/es.tsindex 12cf7275ae..7e8b1746e7 100644--- a/apps/desktop/src/i18n/locales/es.ts+++ b/apps/desktop/src/i18n/locales/es.ts@@ -1265,6 +1265,7 @@ export default withEnglishFallback({export: "Exportar",exportQueryResultTo: "Exportar el conjunto de resultados de la consulta actual a {format}",copySelection: "Copiar seleccion",+ screenshotSelection: "Capturar código seleccionado",commentSelection: "Comentar selección",blockCommentSelection: "Comentario de bloque en la selección",formatSelectionSql: "Formatear SQL seleccionado",@@ -8117,4 +8118,21 @@ export default withEnglishFallback({cellRowMissing: "La fila no existe",cellColumnMissing: "La columna no existe",},+ codeSnapshot: {+ title: "Captura de código",+ close: "Cerrar",+ copy: "Copiar al portapapeles",+ save: "Guardar PNG",+ copied: "Copiado",+ saved: "Guardado",+ failed: "Error: {message}",+ take: "Capturar código",+ theme: "Tema",+ themeLight: "Claro",+ themeDark: "Oscuro",+ windowControls: "Botones de ventana",+ lineNumbers: "Números de línea",+ titleLabel: "Título (opcional)",+ titlePlaceholder: "p. ej. Ejemplo de consulta",+ },});diff --git a/apps/desktop/src/i18n/locales/it.ts b/apps/desktop/src/i18n/locales/it.tsindex 34f85b7f62..013f8e93f0 100644--- a/apps/desktop/src/i18n/locales/it.ts+++ b/apps/desktop/src/i18n/locales/it.ts@@ -1263,6 +1263,7 @@ export default withEnglishFallback({export: "Esporta",exportQueryResultTo: "Esporta il set di risultati della query corrente in {format}",copySelection: "Copia selezione",+ screenshotSelection: "Cattura codice selezionato",commentSelection: "Commenta selezione",blockCommentSelection: "Commenta selezione a blocco",formatSelectionSql: "Formatta SQL selezionato",@@ -8117,4 +8118,21 @@ export default withEnglishFallback({cellRowMissing: "La riga non esiste",cellColumnMissing: "La colonna non esiste",},+ codeSnapshot: {+ title: "Cattura codice",+ close: "Chiudi",+ copy: "Copia negli appunti",+ save: "Salva PNG",+ copied: "Copiato",+ saved: "Salvato",+ failed: "Errore: {message}",+ take: "Cattura codice",+ theme: "Tema",+ themeLight: "Chiaro",+ themeDark: "Scuro",+ windowControls: "Pulsanti finestra",+ lineNumbers: "Numeri di riga",+ titleLabel: "Titolo (facoltativo)",+ titlePlaceholder: "es. Esempio di query",+ },});diff --git a/apps/desktop/src/i18n/locales/ja.ts b/apps/desktop/src/i18n/locales/ja.tsindex 97d7bce4f2..d4d4313b58 100644--- a/apps/desktop/src/i18n/locales/ja.ts+++ b/apps/desktop/src/i18n/locales/ja.ts@@ -1283,6 +1283,7 @@ export default withEnglishFallback({export: "エクスポート",exportQueryResultTo: "現在のクエリ結果セットを {format} にエクスポート",copySelection: "選択範囲をコピー",+ screenshotSelection: "選択したコードをスクリーンショット",commentSelection: "選択範囲をコメント化",blockCommentSelection: "選択範囲をブロックコメント化",formatSelectionSql: "選択した SQL をフォーマット",@@ -8170,4 +8171,21 @@ export default withEnglishFallback({cellRowMissing: "行が存在しません",cellColumnMissing: "列が存在しません",},+ codeSnapshot: {+ title: "コードスナップショット",+ close: "閉じる",+ copy: "クリップボードにコピー",+ save: "PNG を保存",+ copied: "コピーしました",+ saved: "保存しました",+ failed: "失敗: {message}",+ take: "コードをスナップショット",+ theme: "テーマ",+ themeLight: "ライト",+ themeDark: "ダーク",+ windowControls: "ウィンドウボタン",+ lineNumbers: "行番号",+ titleLabel: "タイトル(任意)",+ titlePlaceholder: "例:クエリの例",+ },});diff --git a/apps/desktop/src/i18n/locales/ko.ts b/apps/desktop/src/i18n/locales/ko.tsindex 6b85614aa3..b42820ea19 100644--- a/apps/desktop/src/i18n/locales/ko.ts+++ b/apps/desktop/src/i18n/locales/ko.ts@@ -1174,6 +1174,7 @@ export default withEnglishFallback({export: "내보내기",exportQueryResultTo: "현재 쿼리 결과를 {format}(으)로 내보내기",copySelection: "선택 영역 복사",+ screenshotSelection: "선택한 코드 스크린샷",commentSelection: "선택 항목 주석 처리",blockCommentSelection: "선택 항목 블록 주석 처리",formatSelectionSql: "선택한 SQL 서식 지정",@@ -7588,4 +7589,21 @@ export default withEnglishFallback({cellRowMissing: "행이 존재하지 않습니다",cellColumnMissing: "열이 존재하지 않습니다",},+ codeSnapshot: {+ title: "코드 스냅샷",+ close: "닫기",+ copy: "클립보드에 복사",+ save: "PNG 저장",+ copied: "복사됨",+ saved: "저장됨",+ failed: "실패: {message}",+ take: "코드 스냅샷",+ theme: "테마",+ themeLight: "라이트",+ themeDark: "다크",+ windowControls: "창 컨트롤",+ lineNumbers: "줄 번호",+ titleLabel: "제목 (선택)",+ titlePlaceholder: "예: 쿼리 예시",+ },});diff --git a/apps/desktop/src/i18n/locales/pt-BR.ts b/apps/desktop/src/i18n/locales/pt-BR.tsindex 23d1e012cf..ed65889b8f 100644--- a/apps/desktop/src/i18n/locales/pt-BR.ts+++ b/apps/desktop/src/i18n/locales/pt-BR.ts@@ -1264,6 +1264,7 @@ export default withEnglishFallback({export: "Exportar",exportQueryResultTo: "Exportar conjunto de resultados da consulta atual para {format}",copySelection: "Copiar seleção",+ screenshotSelection: "Capturar código selecionado",commentSelection: "Comentar seleção",blockCommentSelection: "Comentário de bloco na seleção",formatSelectionSql: "Formatar SQL selecionado",@@ -8119,4 +8120,21 @@ export default withEnglishFallback({cellRowMissing: "A linha não existe",cellColumnMissing: "A coluna não existe",},+ codeSnapshot: {+ title: "Captura de código",+ close: "Fechar",+ copy: "Copiar para a área de transferência",+ save: "Salvar PNG",+ copied: "Copiado",+ saved: "Salvo",+ failed: "Falha: {message}",+ take: "Capturar código",+ theme: "Tema",+ themeLight: "Claro",+ themeDark: "Escuro",+ windowControls: "Botões da janela",+ lineNumbers: "Números de linha",+ titleLabel: "Título (opcional)",+ titlePlaceholder: "ex.: Exemplo de consulta",+ },});diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.tsindex 1148e43839..0625a3813f 100644--- a/apps/desktop/src/i18n/locales/zh-CN.ts+++ b/apps/desktop/src/i18n/locales/zh-CN.ts@@ -1211,6 +1211,7 @@ export default withEnglishFallback({export: "导出",exportQueryResultTo: "导出当前查询结果集到 {format}",copySelection: "复制选中内容",+ screenshotSelection: "截图选中代码",commentSelection: "注释选中内容",blockCommentSelection: "块注释选中内容",formatSelectionSql: "格式化选中SQL",@@ -8320,4 +8321,21 @@ export default withEnglishFallback({cellRowMissing: "该行不存在",cellColumnMissing: "该列不存在",},+ codeSnapshot: {+ title: "代码截图",+ close: "关闭",+ copy: "复制到剪贴板",+ save: "保存 PNG",+ copied: "已复制",+ saved: "已保存",+ failed: "操作失败:{message}",+ take: "截图代码",+ theme: "主题",+ themeLight: "浅色",+ themeDark: "深色",+ windowControls: "窗口按钮",+ lineNumbers: "行号",+ titleLabel: "标题(可选)",+ titlePlaceholder: "例如:查询示例",+ },});diff --git a/apps/desktop/src/i18n/locales/zh-TW.ts b/apps/desktop/src/i18n/locales/zh-TW.tsindex 66c60a6b27..a342b3f39c 100644--- a/apps/desktop/src/i18n/locales/zh-TW.ts+++ b/apps/desktop/src/i18n/locales/zh-TW.ts@@ -1263,6 +1263,7 @@ export default withEnglishFallback({export: "匯出",exportQueryResultTo: "匯出目前查詢結果集到 {format}",copySelection: "複製選取內容",+ screenshotSelection: "截圖選中程式碼",commentSelection: "註解選取內容",blockCommentSelection: "區塊註解選取內容",formatSelectionSql: "格式化選取的 SQL",@@ -8109,4 +8110,21 @@ export default withEnglishFallback({cellRowMissing: "該列不存在",cellColumnMissing: "該欄不存在",},+ codeSnapshot: {+ title: "程式碼截圖",+ close: "關閉",+ copy: "複製到剪貼簿",+ save: "儲存 PNG",+ copied: "已複製",+ saved: "已儲存",+ failed: "操作失敗:{message}",+ take: "截圖程式碼",+ theme: "主題",+ themeLight: "淺色",+ themeDark: "深色",+ windowControls: "視窗按鈕",+ lineNumbers: "行號",+ titleLabel: "標題(可選)",+ titlePlaceholder: "例如:查詢範例",+ },});diff --git a/apps/desktop/src/lib/codeSnapshot/__tests__/codeSnapshot.spec.ts b/apps/desktop/src/lib/codeSnapshot/__tests__/codeSnapshot.spec.tsnew file mode 100644index 0000000000..36ae3ce5ac--- /dev/null+++ b/apps/desktop/src/lib/codeSnapshot/__tests__/codeSnapshot.spec.ts@@ -0,0 +1,123 @@+import { describe, expect, it, vi } from "vitest";+import { CODE_SNAPSHOT_CSS, renderCodeSnapshotHtml, savePngDataUrlToFile, snapshotElementToPng } from "@/lib/codeSnapshot/codeSnapshot";++const { toPng, isTauriRuntime, save, writeFile } = vi.hoisted(() => ({+ toPng: vi.fn(),+ isTauriRuntime: vi.fn(),+ save: vi.fn(),+ writeFile: vi.fn(),+}));++vi.mock("@/lib/ai/aiCodeHighlighter", () => ({+ createAiShikiCodeHighlighter: vi.fn().mockResolvedValue((content: string, _lang: string) => `<span class="line">${content}</span>`),+}));++vi.mock("dom-to-image-more", () => ({+ default: { toPng },+}));++vi.mock("@/lib/backend/tauriRuntime", () => ({+ isTauriRuntime,+}));++vi.mock("@tauri-apps/plugin-dialog", () => ({ save }));+vi.mock("@tauri-apps/plugin-fs", () => ({ writeFile }));++describe("renderCodeSnapshotHtml", () => {+ it("renders a self-contained snapshot with embedded styles", async () => {+ const html = await renderCodeSnapshotHtml({ code: "SELECT 1", lang: "sql" }, { appearance: "dark" });++ expect(html).toContain("<style>");+ expect(html).toContain(CODE_SNAPSHOT_CSS);+ expect(html).toContain('class="dbx-code-snapshot"');+ expect(html).toContain('data-snapshot-appearance="dark"');+ expect(html).toContain('class="dbx-code-snapshot__pre dbx-code-snapshot__pre--numbered"');+ });++ it("renders macOS traffic lights and an optional title by default", async () => {+ const html = await renderCodeSnapshotHtml({ code: "SELECT 1", lang: "sql", title: "Query example" }, { appearance: "dark" });++ expect(html).toContain('class="dbx-code-snapshot__bar"');+ expect(html).toContain("#ff5f57");+ expect(html).toContain("#febc2e");+ expect(html).toContain("#28c840");+ expect(html).toContain("Query example");+ });++ it("hides the bar when traffic lights are disabled and no title is set", async () => {+ const html = await renderCodeSnapshotHtml({ code: "SELECT 1", lang: "sql" }, { appearance: "light", showTrafficLights: false });++ expect(html).not.toContain('class="dbx-code-snapshot__bar"');+ });++ it("keeps the title bar but hides traffic lights when window controls are disabled", async () => {+ const html = await renderCodeSnapshotHtml({ code: "SELECT 1", lang: "sql", title: "Query example" }, { appearance: "dark", showTrafficLights: false });++ expect(html).toContain('class="dbx-code-snapshot__bar"');+ expect(html).toContain("Query example");+ expect(html).not.toContain('class="dbx-code-snapshot__dot"');+ });++ it("hides line numbers when disabled", async () => {+ const html = await renderCodeSnapshotHtml({ code: "SELECT 1", lang: "sql" }, { appearance: "light", showLineNumbers: false });++ expect(html).toContain('class="dbx-code-snapshot__pre"');+ expect(html).not.toContain('class="dbx-code-snapshot__pre dbx-code-snapshot__pre--numbered"');+ });++ it("escapes the snapshot title", async () => {+ const html = await renderCodeSnapshotHtml({ code: "SELECT 1", lang: "sql", title: `<script>alert(1)</script>` }, { appearance: "dark" });++ expect(html).toContain("<script>");+ expect(html).not.toContain("<script>alert(1)</script>");+ });++ it("applies the appearance-specific background and line-number color", async () => {+ const dark = await renderCodeSnapshotHtml({ code: "SELECT 1", lang: "sql" }, { appearance: "dark" });+ const light = await renderCodeSnapshotHtml({ code: "SELECT 1", lang: "sql" }, { appearance: "light" });++ expect(dark).toContain("background:#0d1117");+ expect(dark).toContain("--dbx-snapshot-line-number:#484f58");+ expect(light).toContain("background:#ffffff");+ expect(light).toContain("--dbx-snapshot-line-number:#d0d7de");+ });++ it("applies custom padding and font size", async () => {+ const html = await renderCodeSnapshotHtml({ code: "SELECT 1", lang: "sql" }, { appearance: "dark", padding: 24, fontSize: 15 });++ expect(html).toContain("font-size:15px");+ expect(html).toContain("padding:0 24px 24px");+ });++ it("exports at a capped device-pixel ratio for crisp high-DPI snapshots", async () => {+ toPng.mockResolvedValue("data:image/png;base64,test");+ vi.stubGlobal("window", { devicePixelRatio: 3 });+ try {+ await snapshotElementToPng({ offsetWidth: 320, offsetHeight: 160 } as HTMLElement);++ expect(toPng).toHaveBeenLastCalledWith(+ expect.anything(),+ expect.objectContaining({+ width: 320,+ height: 160,+ pixelRatio: 2,+ }),+ );++ vi.stubGlobal("window", { devicePixelRatio: 0 });+ await snapshotElementToPng({ offsetWidth: 320, offsetHeight: 160 } as HTMLElement);+ expect(toPng).toHaveBeenLastCalledWith(expect.anything(), expect.objectContaining({ pixelRatio: 1 }));+ } finally {+ vi.unstubAllGlobals();+ }+ });++ it("propagates a failed native save instead of reporting a browser download", async () => {+ isTauriRuntime.mockReturnValue(true);+ save.mockResolvedValue("C:\\Users\\example\\snapshot.png");+ writeFile.mockRejectedValue(new Error("disk full"));++ await expect(savePngDataUrlToFile("data:image/png;base64,AA==", "snapshot.png")).rejects.toThrow("disk full");+ expect(writeFile).toHaveBeenCalledOnce();+ });+});diff --git a/apps/desktop/src/lib/codeSnapshot/codeSnapshot.ts b/apps/desktop/src/lib/codeSnapshot/codeSnapshot.tsnew file mode 100644index 0000000000..a5b87211e7--- /dev/null+++ b/apps/desktop/src/lib/codeSnapshot/codeSnapshot.ts@@ -0,0 +1,246 @@+/**+ * Code snapshot rendering & export utilities (CodeSnap-style).+ *+ * Flow: selected code text -> shiki re-render (reusing the AI highlighter+ * singleton) -> CodeSnap-like shell DOM (traffic lights / title / line+ * numbers / background) -> PNG export either to the system clipboard+ * (Tauri `writeImage`) or to a file (dialog + fs, with a browser-download+ * fallback for web mode).+ *+ * The rendered snapshot DOM is fully self-contained: it embeds its own+ * `<style>` tag so `dom-to-image-more` captures identical styling when it+ * clones the node into a foreignObject.+ */+import type { AppThemeAppearance } from "@/lib/app/appTheme";+import { createAiShikiCodeHighlighter, type AiCodeHighlighter } from "@/lib/ai/aiCodeHighlighter";+import { isTauriRuntime } from "@/lib/backend/tauriRuntime";++export interface CodeSnapshotSource {+ code: string;+ /** Shiki language name or AI label (e.g. "sql", "python", "JSON"). */+ lang: string;+ /** Optional title shown in the snapshot bar next to the traffic lights. */+ title?: string;+}++export interface CodeSnapshotStyleOptions {+ appearance: AppThemeAppearance;+ /** Render the macOS-style traffic light dots. Defaults to true. */+ showTrafficLights?: boolean;+ /** Render line numbers via CSS counters. Defaults to true. */+ showLineNumbers?: boolean;+ /** Padding (px) around the code area. Defaults to 16. */+ padding?: number;+ /** Code font size (px). Defaults to 13. */+ fontSize?: number;+}++const SNAPSHOT_BACKGROUND: Record<AppThemeAppearance, string> = {+ light: "#ffffff",+ dark: "#0d1117",+};++const SNAPSHOT_BAR_BACKGROUND: Record<AppThemeAppearance, string> = {+ light: "#f6f8fa",+ dark: "#161b22",+};++const SNAPSHOT_BAR_TEXT: Record<AppThemeAppearance, string> = {+ light: "#57606a",+ dark: "#8b949e",+};++const SNAPSHOT_LINE_NUMBER: Record<AppThemeAppearance, string> = {+ light: "#d0d7de",+ dark: "#484f58",+};++const TRAFFIC_LIGHT_COLORS = ["#ff5f57", "#febc2e", "#28c840"] as const;+const MAX_EXPORT_PIXEL_RATIO = 2;++/**+ * Self-contained stylesheet embedded in every snapshot DOM. Keep it prefix+ * namespaced (`dbx-code-snapshot`) so it never leaks into the app chrome.+ */+export const CODE_SNAPSHOT_CSS = `+.dbx-code-snapshot {+ border-radius: 8px;+ overflow: hidden;+ font-family: "SF Mono", "Cascadia Code", "JetBrains Mono", Consolas, "Courier New", monospace;+ text-align: left;+ box-shadow: 0 8px 24px rgba(0, 0, 0, 0.35);+}+.dbx-code-snapshot__bar {+ display: flex;+ align-items: center;+ gap: 8px;+ padding: 10px 14px;+}+.dbx-code-snapshot__dot {+ width: 12px;+ height: 12px;+ border-radius: 50%;+ flex: none;+}+.dbx-code-snapshot__title {+ margin-left: 4px;+ font-size: 12px;+ font-weight: 500;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}+.dbx-code-snapshot__pre {+ margin: 0;+ overflow: hidden;+ line-height: 1.6;+ tab-size: 4;+}+.dbx-code-snapshot__pre code {+ font-family: inherit;+ font-size: inherit;+ background: transparent;+}+.dbx-code-snapshot__pre .line {+ display: block;+ min-height: 1.6em;+}+.dbx-code-snapshot__pre--numbered {+ counter-reset: dbx-snapshot-line;+}+.dbx-code-snapshot__pre--numbered .line {+ counter-increment: dbx-snapshot-line;+}+.dbx-code-snapshot__pre--numbered .line::before {+ content: counter(dbx-snapshot-line);+ display: inline-block;+ min-width: 2.2em;+ margin-right: 1.4em;+ text-align: right;+ color: var(--dbx-snapshot-line-number, #8b949e);+ font-variant-numeric: tabular-nums;+ user-select: none;+ -webkit-user-select: none;+}+`;++let highlighterPromise: Promise<AiCodeHighlighter> | undefined;++/** Lazy singleton reusing the AI assistant's shiki highlighter instance. */+export function getCodeSnapshotHighlighter(): Promise<AiCodeHighlighter> {+ highlighterPromise ??= createAiShikiCodeHighlighter({+ appearance: () => "dark",+ }).catch((err: unknown) => {+ // Reset so a transient highlighter failure can be retried on the next+ // render instead of permanently poisoning the singleton.+ highlighterPromise = undefined;+ throw err;+ });+ return highlighterPromise;+}++function escapeHtml(value: string): string {+ return value.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">").replaceAll('"', """).replaceAll("'", "'");+}++function renderSnapshotBar(title: string | undefined, appearance: AppThemeAppearance, showTrafficLights: boolean): string {+ const dots = showTrafficLights ? TRAFFIC_LIGHT_COLORS.map((color) => `<span class="dbx-code-snapshot__dot" style="background:${color}"></span>`).join("") : "";+ const titleHtml = title ? `<span class="dbx-code-snapshot__title" style="color:${SNAPSHOT_BAR_TEXT[appearance]}">${escapeHtml(title)}</span>` : "";+ return `<div class="dbx-code-snapshot__bar" style="background:${SNAPSHOT_BAR_BACKGROUND[appearance]};color:${SNAPSHOT_BAR_TEXT[appearance]}">${dots}${titleHtml}</div>`;+}++/**+ * Render a self-contained snapshot DOM (as an HTML string) for the given code.+ * The returned string includes its own `<style>` tag and can be injected via+ * `v-html`, then exported with `snapshotElementToPng`.+ */+export async function renderCodeSnapshotHtml(source: CodeSnapshotSource, options: CodeSnapshotStyleOptions): Promise<string> {+ const highlight = await getCodeSnapshotHighlighter();+ const body = highlight(source.code, source.lang, options.appearance);++ const appearance = options.appearance;+ const showBar = options.showTrafficLights !== false || !!source.title;+ const showLineNumbers = options.showLineNumbers !== false;+ const padding = options.padding ?? 16;+ const fontSize = options.fontSize ?? 13;++ const bar = showBar ? renderSnapshotBar(source.title, appearance, options.showTrafficLights !== false) : "";+ const preClass = `dbx-code-snapshot__pre${showLineNumbers ? " dbx-code-snapshot__pre--numbered" : ""}`;+ const lineNumberColor = SNAPSHOT_LINE_NUMBER[appearance];++ return (+ `<style>${CODE_SNAPSHOT_CSS}</style>` ++ `<div class="dbx-code-snapshot" data-snapshot-appearance="${appearance}" style="background:${SNAPSHOT_BACKGROUND[appearance]};font-size:${fontSize}px">` ++ bar ++ `<pre class="${preClass}" style="--dbx-snapshot-line-number:${lineNumberColor};padding:0 ${padding}px ${padding}px"><code>${body}</code></pre>` ++ `</div>`+ );+}++/** Convert a snapshot DOM element into a PNG data URL. */+export async function snapshotElementToPng(element: HTMLElement): Promise<string> {+ const domtoimage = (await import("dom-to-image-more")).default;+ return domtoimage.toPng(element, {+ quality: 1,+ width: element.offsetWidth,+ height: element.offsetHeight,+ // Preserve text sharpness on high-DPI displays without letting a large+ // selected block allocate an unbounded export canvas.+ pixelRatio: Math.min(MAX_EXPORT_PIXEL_RATIO, Math.max(1, typeof window === "undefined" ? 1 : window.devicePixelRatio || 1)),+ });+}++async function dataUrlToBlob(dataUrl: string): Promise<Blob> {+ return await (await fetch(dataUrl)).blob();+}++/**+ * Copy a PNG data URL to the system clipboard. Uses the Tauri+ * clipboard-manager `writeImage` on desktop and falls back to the Web+ * Clipboard API (`ClipboardItem`) for web mode.+ */+export async function copyPngDataUrlToClipboard(dataUrl: string): Promise<void> {+ const blob = await dataUrlToBlob(dataUrl);+ if (isTauriRuntime()) {+ const { writeImage } = await import("@tauri-apps/plugin-clipboard-manager");+ await writeImage(new Uint8Array(await blob.arrayBuffer()));+ return;+ }+ if (typeof ClipboardItem !== "undefined" && navigator.clipboard?.write) {+ await navigator.clipboard.write([new ClipboardItem({ "image/png": blob })]);+ return;+ }+ throw new Error("Clipboard image write is not supported in this environment");+}++/**+ * Save a PNG data URL to a file. On desktop this opens the native save+ * dialog; on web it downloads the image. Returns false when the user+ * cancels the native save dialog.+ */+export async function savePngDataUrlToFile(dataUrl: string, defaultName: string): Promise<boolean> {+ const blob = await dataUrlToBlob(dataUrl);+ if (isTauriRuntime()) {+ const { save } = await import("@tauri-apps/plugin-dialog");+ const { writeFile } = await import("@tauri-apps/plugin-fs");+ const path = await save({+ defaultPath: defaultName,+ filters: [{ name: "PNG", extensions: ["png"] }],+ });+ if (!path) return false;+ // Native write errors must reach the caller so the UI never claims the+ // user-selected path was saved when the filesystem rejected it.+ await writeFile(path, new Uint8Array(await blob.arrayBuffer()));+ return true;+ }+ const url = URL.createObjectURL(blob);+ try {+ const a = document.createElement("a");+ a.href = url;+ a.download = defaultName;+ a.click();+ } finally {+ URL.revokeObjectURL(url);+ }+ return true;+}diff --git a/flake.nix b/flake.nixindex 9ffa866261..1b7dea2e2c 100644--- a/flake.nix+++ b/flake.nix@@ -197,7 +197,7 @@fetcherVersion = 4;# Update with the hash reported by a failed fixed-output build:# nix build .#dbx-pnpm-deps 2>&1 | grep 'got:'- hash = "sha256-wkjQz/nNx4D7p5B/5NcdXnMGvOljM+nGKyKDxvMRCgw=";+ hash = "sha256-VYG+rEeTTcf3B4avT6UIAdwIymrrioAUtUP2MBYi6s0=";};# ── Step 2: vendor Cargo dependencies ───────────────────────────── #diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 15fee32408..4712fd719d 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -145,7 +145,7 @@ importers:version: 9.0.0dom-to-image-more:specifier: ^3.7.2- version: 3.7.2+ version: 3.10.2echarts:specifier: ^6.1.0version: 6.1.0@@ -2223,8 +2223,8 @@ packages:resolution: {integrity: sha512-wIkAryiqt/nV5EQKqQpo3SToSOV9J0DnbJqwK7Wv/Trc92zIAYZ4FlMu+JPFW1DfGFt81ZTCGgDEabffXeLyJg==}- resolution: {integrity: sha512-uQf+pHv6eQhgfI8t2bFuinV0KsPyT8TZgCLwcSU8uBVgN9v6leb0mMpvp6HQAlAcplP3NCcGjxbdqef6pTzvmw==}+ resolution: {integrity: sha512-+ZNbiRB7Fpsfzn8WSCmAIKUFSXp8uahlI+LsY8t8oWtAATqokeKS3eD3oQikheouap6aVMht8y0b4oAobWRr9w==}resolution: {integrity: sha512-OLETBj6w0OsagBwdXnPdN0cnMfF9opN69co+7ZrbfPGrdpPVNBUj02spi6B1N7wChLQiPn4CSH/zJvXw56gmHw==}@@ -5872,7 +5872,7 @@ snapshots:domhandler: 5.0.3entities: 4.5.0- [email protected]: {}+ [email protected]: {}diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.tomlindex b54255427f..24b0f0b156 100644--- a/src-tauri/Cargo.toml+++ b/src-tauri/Cargo.toml@@ -29,7 +29,7 @@ serde = { version = "1.0", features = ["derive"] }serde_json = "1.0"base64 = "0.22"log = "0.4"-tauri = { version = "2.10.3", features = ["tray-icon"] }+tauri = { version = "2.10.3", features = ["tray-icon", "image-png"] }tauri-plugin-log = "2"tokio-postgres = { version = "0.7", features = ["with-chrono-0_4", "with-uuid-1", "with-serde_json-1"] }deadpool-postgres = { version = "0.14", features = ["rt_tokio_1"] }diff --git a/src-tauri/capabilities/default.json b/src-tauri/capabilities/default.jsonindex 772922e238..8e7846975f 100644--- a/src-tauri/capabilities/default.json+++ b/src-tauri/capabilities/default.json@@ -20,6 +20,7 @@"core:webview:allow-set-webview-zoom","clipboard-manager:allow-read-text","clipboard-manager:allow-write-text",+ "clipboard-manager:allow-write-image","dialog:default","dialog:allow-save","dialog:allow-open",