feat(editor): add code snapshot export

This commit is contained in:
Abeautifulsnow authored and GitHub committed 2026-08-19 15:49:15 +08:00
1 parent a40dc02825
commit 30f5c34729
18 files changed
+774 -7

No files matched your search

Generated
+1
View File
@@ -8443,6 +8443,7 @@ dependencies = [
"gtk", "gtk",
"heck 0.5.0", "heck 0.5.0",
"http 1.5.0", "http 1.5.0",
"image",
"jni 0.21.1", "jni 0.21.1",
"libc", "libc",
"log", "log",
@@ -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>
@@ -9,6 +9,7 @@ import {
ArrowRightLeft, ArrowRightLeft,
AlertTriangle, AlertTriangle,
Bot, Bot,
Camera,
Check, Check,
ChevronLeft, ChevronLeft,
ChevronRight, ChevronRight,
@@ -44,6 +45,8 @@ import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@
import { Popover, PopoverAnchor, PopoverContent, PopoverTrigger } from "@/components/ui/popover"; import { Popover, PopoverAnchor, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { ScrollArea } from "@/components/ui/scroll-area"; import { ScrollArea } from "@/components/ui/scroll-area";
import { useTheme } from "@/composables/useTheme"; 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 { useSettingsStore, AI_PROVIDER_PRESETS, normalizeAiConfig } from "@/stores/settingsStore";
import AiProviderLogo from "@/components/icons/AiProviderLogo.vue"; import AiProviderLogo from "@/components/icons/AiProviderLogo.vue";
import { useConnectionStore } from "@/stores/connectionStore"; 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 activePlaceholder = computed(() => `${t(`ai.placeholders.${activeAction.value}`)} ${t("ai.tableMentionPlaceholderHint")}`);
const aiCodeAppearance = computed(() => (isDark.value ? "dark" : "light")); 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(() => { const showActionButtons = computed(() => {
if (!props.connection) return true; if (!props.connection) return true;
return !isVectorDbType(props.connection.db_type); 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" /> <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" /> <Copy v-else class="h-3.5 w-3.5" />
</button> </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>
</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> <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> </div>
</div> </div>
<CodeSnapshotDialog v-model:open="codeSnapshotOpen" :source="codeSnapshotSource" />
</div> </div>
</div> </div>
</template> </template>
@@ -1,6 +1,6 @@
<script setup lang="ts"> <script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, onActivated, onDeactivated, watch, shallowRef, computed, nextTick } from "vue"; 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 { useI18n } from "vue-i18n";
import type { CompletionContext } from "@codemirror/autocomplete"; import type { CompletionContext } from "@codemirror/autocomplete";
import { Transaction, StateEffect } from "@codemirror/state"; import { Transaction, StateEffect } from "@codemirror/state";
@@ -9,7 +9,9 @@ import { search as cmSearch } from "@codemirror/search";
import EditorSearchPanel from "./EditorSearchPanel.vue"; import EditorSearchPanel from "./EditorSearchPanel.vue";
import SqlExecutionTargetPicker from "./SqlExecutionTargetPicker.vue"; import SqlExecutionTargetPicker from "./SqlExecutionTargetPicker.vue";
import DelimitedListDialog from "./DelimitedListDialog.vue"; import DelimitedListDialog from "./DelimitedListDialog.vue";
import CodeSnapshotDialog from "@/components/codeSnapshot/CodeSnapshotDialog.vue";
import CustomContextMenu, { type ContextMenuItem } from "@/components/ui/CustomContextMenu.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 { copyToClipboard, readTextFromClipboard } from "@/lib/common/clipboard";
import { completionMatchRanges } from "@/lib/common/completionMatch"; import { completionMatchRanges } from "@/lib/common/completionMatch";
import { executionCandidateForMode, resolveExecutableSql, type SqlExecutionSnapshot, type SqlExecutionOverride, type SqlExecutionCandidate } from "@/lib/sql/sqlExecutionTarget"; 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 state // Delimited list dialog state
const delimitedListOpen = ref(false); const delimitedListOpen = ref(false);
const delimitedListSelectedText = ref(""); const delimitedListSelectedText = ref("");
const codeSnapshotOpen = ref(false);
const codeSnapshotSource = ref<CodeSnapshotSource | null>(null);
function openDelimitedListDialog() { function openDelimitedListDialog() {
if (props.readOnly) return; if (props.readOnly) return;
@@ -1772,6 +1776,17 @@ const contextMenuItems = computed<ContextMenuItem[]>(() => {
icon: Copy, icon: Copy,
shortcut: "Mod+C", 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"), label: t("editor.contextMenu.cutSelection"),
action: cutSelectedSqlFromContextMenu, action: cutSelectedSqlFromContextMenu,
@@ -5843,6 +5858,7 @@ defineExpose({
<EditorSearchPanel ref="searchPanelRef" :view="view" /> <EditorSearchPanel ref="searchPanelRef" :view="view" />
<SqlExecutionTargetPicker v-if="pickerVisible" :candidates="pickerCandidates" :active-index="pickerActiveIndex" :anchor="pickerAnchor" @update:active-index="onPickerActiveIndexChange" @confirm="onPickerConfirm" @cancel="closePicker" /> <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" /> <DelimitedListDialog v-model:open="delimitedListOpen" :selected-text="delimitedListSelectedText" @confirm="applyDelimitedListResult" />
<CodeSnapshotDialog v-model:open="codeSnapshotOpen" :source="codeSnapshotSource" />
<!-- SQL 意图操作弹出菜单(参考 DataGrip Alt+Enter) --> <!-- SQL 意图操作弹出菜单(参考 DataGrip Alt+Enter) -->
<Teleport to="body"> <Teleport to="body">
<div v-if="intentionPopup?.visible" class="intention-popup-overlay" @click.self="closeIntentionPopup"> <div v-if="intentionPopup?.visible" class="intention-popup-overlay" @click.self="closeIntentionPopup">
+18
View File
@@ -1287,6 +1287,7 @@ export default {
export: "Export", export: "Export",
exportQueryResultTo: "Export current query result to {format}", exportQueryResultTo: "Export current query result to {format}",
copySelection: "Copy selection", copySelection: "Copy selection",
screenshotSelection: "Screenshot Selected Code",
commentSelection: "Comment selection", commentSelection: "Comment selection",
blockCommentSelection: "Block comment selection", blockCommentSelection: "Block comment selection",
formatSelectionSql: "Format selected SQL", formatSelectionSql: "Format selected SQL",
@@ -8337,4 +8338,21 @@ export default {
cellRowMissing: "Row does not exist", cellRowMissing: "Row does not exist",
cellColumnMissing: "Column 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",
},
}; };
+18
View File
@@ -1265,6 +1265,7 @@ export default withEnglishFallback({
export: "Exportar", export: "Exportar",
exportQueryResultTo: "Exportar el conjunto de resultados de la consulta actual a {format}", exportQueryResultTo: "Exportar el conjunto de resultados de la consulta actual a {format}",
copySelection: "Copiar seleccion", copySelection: "Copiar seleccion",
screenshotSelection: "Capturar código seleccionado",
commentSelection: "Comentar selección", commentSelection: "Comentar selección",
blockCommentSelection: "Comentario de bloque en la selección", blockCommentSelection: "Comentario de bloque en la selección",
formatSelectionSql: "Formatear SQL seleccionado", formatSelectionSql: "Formatear SQL seleccionado",
@@ -8117,4 +8118,21 @@ export default withEnglishFallback({
cellRowMissing: "La fila no existe", cellRowMissing: "La fila no existe",
cellColumnMissing: "La columna 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",
},
}); });
+18
View File
@@ -1263,6 +1263,7 @@ export default withEnglishFallback({
export: "Esporta", export: "Esporta",
exportQueryResultTo: "Esporta il set di risultati della query corrente in {format}", exportQueryResultTo: "Esporta il set di risultati della query corrente in {format}",
copySelection: "Copia selezione", copySelection: "Copia selezione",
screenshotSelection: "Cattura codice selezionato",
commentSelection: "Commenta selezione", commentSelection: "Commenta selezione",
blockCommentSelection: "Commenta selezione a blocco", blockCommentSelection: "Commenta selezione a blocco",
formatSelectionSql: "Formatta SQL selezionato", formatSelectionSql: "Formatta SQL selezionato",
@@ -8117,4 +8118,21 @@ export default withEnglishFallback({
cellRowMissing: "La riga non esiste", cellRowMissing: "La riga non esiste",
cellColumnMissing: "La colonna 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",
},
}); });
+18
View File
@@ -1283,6 +1283,7 @@ export default withEnglishFallback({
export: "エクスポート", export: "エクスポート",
exportQueryResultTo: "現在のクエリ結果セットを {format} にエクスポート", exportQueryResultTo: "現在のクエリ結果セットを {format} にエクスポート",
copySelection: "選択範囲をコピー", copySelection: "選択範囲をコピー",
screenshotSelection: "選択したコードをスクリーンショット",
commentSelection: "選択範囲をコメント化", commentSelection: "選択範囲をコメント化",
blockCommentSelection: "選択範囲をブロックコメント化", blockCommentSelection: "選択範囲をブロックコメント化",
formatSelectionSql: "選択した SQL をフォーマット", formatSelectionSql: "選択した SQL をフォーマット",
@@ -8170,4 +8171,21 @@ export default withEnglishFallback({
cellRowMissing: "行が存在しません", cellRowMissing: "行が存在しません",
cellColumnMissing: "列が存在しません", cellColumnMissing: "列が存在しません",
}, },
codeSnapshot: {
title: "コードスナップショット",
close: "閉じる",
copy: "クリップボードにコピー",
save: "PNG を保存",
copied: "コピーしました",
saved: "保存しました",
failed: "失敗: {message}",
take: "コードをスナップショット",
theme: "テーマ",
themeLight: "ライト",
themeDark: "ダーク",
windowControls: "ウィンドウボタン",
lineNumbers: "行番号",
titleLabel: "タイトル(任意)",
titlePlaceholder: "例:クエリの例",
},
}); });
+18
View File
@@ -1174,6 +1174,7 @@ export default withEnglishFallback({
export: "내보내기", export: "내보내기",
exportQueryResultTo: "현재 쿼리 결과를 {format}(으)로 내보내기", exportQueryResultTo: "현재 쿼리 결과를 {format}(으)로 내보내기",
copySelection: "선택 영역 복사", copySelection: "선택 영역 복사",
screenshotSelection: "선택한 코드 스크린샷",
commentSelection: "선택 항목 주석 처리", commentSelection: "선택 항목 주석 처리",
blockCommentSelection: "선택 항목 블록 주석 처리", blockCommentSelection: "선택 항목 블록 주석 처리",
formatSelectionSql: "선택한 SQL 서식 지정", formatSelectionSql: "선택한 SQL 서식 지정",
@@ -7588,4 +7589,21 @@ export default withEnglishFallback({
cellRowMissing: "행이 존재하지 않습니다", cellRowMissing: "행이 존재하지 않습니다",
cellColumnMissing: "열이 존재하지 않습니다", cellColumnMissing: "열이 존재하지 않습니다",
}, },
codeSnapshot: {
title: "코드 스냅샷",
close: "닫기",
copy: "클립보드에 복사",
save: "PNG 저장",
copied: "복사됨",
saved: "저장됨",
failed: "실패: {message}",
take: "코드 스냅샷",
theme: "테마",
themeLight: "라이트",
themeDark: "다크",
windowControls: "창 컨트롤",
lineNumbers: "줄 번호",
titleLabel: "제목 (선택)",
titlePlaceholder: "예: 쿼리 예시",
},
}); });
+18
View File
@@ -1264,6 +1264,7 @@ export default withEnglishFallback({
export: "Exportar", export: "Exportar",
exportQueryResultTo: "Exportar conjunto de resultados da consulta atual para {format}", exportQueryResultTo: "Exportar conjunto de resultados da consulta atual para {format}",
copySelection: "Copiar seleção", copySelection: "Copiar seleção",
screenshotSelection: "Capturar código selecionado",
commentSelection: "Comentar seleção", commentSelection: "Comentar seleção",
blockCommentSelection: "Comentário de bloco na seleção", blockCommentSelection: "Comentário de bloco na seleção",
formatSelectionSql: "Formatar SQL selecionado", formatSelectionSql: "Formatar SQL selecionado",
@@ -8119,4 +8120,21 @@ export default withEnglishFallback({
cellRowMissing: "A linha não existe", cellRowMissing: "A linha não existe",
cellColumnMissing: "A coluna 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",
},
}); });
+18
View File
@@ -1211,6 +1211,7 @@ export default withEnglishFallback({
export: "导出", export: "导出",
exportQueryResultTo: "导出当前查询结果集到 {format}", exportQueryResultTo: "导出当前查询结果集到 {format}",
copySelection: "复制选中内容", copySelection: "复制选中内容",
screenshotSelection: "截图选中代码",
commentSelection: "注释选中内容", commentSelection: "注释选中内容",
blockCommentSelection: "块注释选中内容", blockCommentSelection: "块注释选中内容",
formatSelectionSql: "格式化选中SQL", formatSelectionSql: "格式化选中SQL",
@@ -8320,4 +8321,21 @@ export default withEnglishFallback({
cellRowMissing: "该行不存在", cellRowMissing: "该行不存在",
cellColumnMissing: "该列不存在", cellColumnMissing: "该列不存在",
}, },
codeSnapshot: {
title: "代码截图",
close: "关闭",
copy: "复制到剪贴板",
save: "保存 PNG",
copied: "已复制",
saved: "已保存",
failed: "操作失败:{message}",
take: "截图代码",
theme: "主题",
themeLight: "浅色",
themeDark: "深色",
windowControls: "窗口按钮",
lineNumbers: "行号",
titleLabel: "标题(可选)",
titlePlaceholder: "例如:查询示例",
},
}); });
+18
View File
@@ -1263,6 +1263,7 @@ export default withEnglishFallback({
export: "匯出", export: "匯出",
exportQueryResultTo: "匯出目前查詢結果集到 {format}", exportQueryResultTo: "匯出目前查詢結果集到 {format}",
copySelection: "複製選取內容", copySelection: "複製選取內容",
screenshotSelection: "截圖選中程式碼",
commentSelection: "註解選取內容", commentSelection: "註解選取內容",
blockCommentSelection: "區塊註解選取內容", blockCommentSelection: "區塊註解選取內容",
formatSelectionSql: "格式化選取的 SQL", formatSelectionSql: "格式化選取的 SQL",
@@ -8109,4 +8110,21 @@ export default withEnglishFallback({
cellRowMissing: "該列不存在", cellRowMissing: "該列不存在",
cellColumnMissing: "該欄不存在", cellColumnMissing: "該欄不存在",
}, },
codeSnapshot: {
title: "程式碼截圖",
close: "關閉",
copy: "複製到剪貼簿",
save: "儲存 PNG",
copied: "已複製",
saved: "已儲存",
failed: "操作失敗:{message}",
take: "截圖程式碼",
theme: "主題",
themeLight: "淺色",
themeDark: "深色",
windowControls: "視窗按鈕",
lineNumbers: "行號",
titleLabel: "標題(可選)",
titlePlaceholder: "例如:查詢範例",
},
}); });
@@ -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("&lt;script&gt;");
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();
});
});
@@ -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("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;").replaceAll("'", "&#39;");
}
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;
}
+1 -1
View File
@@ -197,7 +197,7 @@
fetcherVersion = 4; fetcherVersion = 4;
# Update with the hash reported by a failed fixed-output build: # Update with the hash reported by a failed fixed-output build:
# nix build .#dbx-pnpm-deps 2>&1 | grep 'got:' # nix build .#dbx-pnpm-deps 2>&1 | grep 'got:'
hash = "sha256-wkjQz/nNx4D7p5B/5NcdXnMGvOljM+nGKyKDxvMRCgw="; hash = "sha256-VYG+rEeTTcf3B4avT6UIAdwIymrrioAUtUP2MBYi6s0=";
}; };
# ── Step 2: vendor Cargo dependencies ───────────────────────────── # # ── Step 2: vendor Cargo dependencies ───────────────────────────── #
+4 -4
View File
@@ -145,7 +145,7 @@ importers:
version: 9.0.0 version: 9.0.0
dom-to-image-more: dom-to-image-more:
specifier: ^3.7.2 specifier: ^3.7.2
version: 3.7.2 version: 3.10.2
echarts: echarts:
specifier: ^6.1.0 specifier: ^6.1.0
version: 6.1.0 version: 6.1.0
@@ -2223,8 +2223,8 @@ packages:
dom-serializer@2.0.0: dom-serializer@2.0.0:
resolution: {integrity: sha512-wIkAryiqt/nV5EQKqQpo3SToSOV9J0DnbJqwK7Wv/Trc92zIAYZ4FlMu+JPFW1DfGFt81ZTCGgDEabffXeLyJg==} resolution: {integrity: sha512-wIkAryiqt/nV5EQKqQpo3SToSOV9J0DnbJqwK7Wv/Trc92zIAYZ4FlMu+JPFW1DfGFt81ZTCGgDEabffXeLyJg==}
dom-to-image-more@3.7.2: dom-to-image-more@3.10.2:
resolution: {integrity: sha512-uQf+pHv6eQhgfI8t2bFuinV0KsPyT8TZgCLwcSU8uBVgN9v6leb0mMpvp6HQAlAcplP3NCcGjxbdqef6pTzvmw==} resolution: {integrity: sha512-+ZNbiRB7Fpsfzn8WSCmAIKUFSXp8uahlI+LsY8t8oWtAATqokeKS3eD3oQikheouap6aVMht8y0b4oAobWRr9w==}
domelementtype@2.3.0: domelementtype@2.3.0:
resolution: {integrity: sha512-OLETBj6w0OsagBwdXnPdN0cnMfF9opN69co+7ZrbfPGrdpPVNBUj02spi6B1N7wChLQiPn4CSH/zJvXw56gmHw==} resolution: {integrity: sha512-OLETBj6w0OsagBwdXnPdN0cnMfF9opN69co+7ZrbfPGrdpPVNBUj02spi6B1N7wChLQiPn4CSH/zJvXw56gmHw==}
@@ -5872,7 +5872,7 @@ snapshots:
domhandler: 5.0.3 domhandler: 5.0.3
entities: 4.5.0 entities: 4.5.0
dom-to-image-more@3.7.2: {} dom-to-image-more@3.10.2: {}
domelementtype@2.3.0: {} domelementtype@2.3.0: {}
+1 -1
View File
@@ -29,7 +29,7 @@ serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0" serde_json = "1.0"
base64 = "0.22" base64 = "0.22"
log = "0.4" 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" tauri-plugin-log = "2"
tokio-postgres = { version = "0.7", features = ["with-chrono-0_4", "with-uuid-1", "with-serde_json-1"] } 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"] } deadpool-postgres = { version = "0.14", features = ["rt_tokio_1"] }
+1
View File
@@ -20,6 +20,7 @@
"core:webview:allow-set-webview-zoom", "core:webview:allow-set-webview-zoom",
"clipboard-manager:allow-read-text", "clipboard-manager:allow-read-text",
"clipboard-manager:allow-write-text", "clipboard-manager:allow-write-text",
"clipboard-manager:allow-write-image",
"dialog:default", "dialog:default",
"dialog:allow-save", "dialog:allow-save",
"dialog:allow-open", "dialog:allow-open",