翻译模块
This commit is contained in:
1 parent
79c43d5340
commit
f6c1cc250e
47 files changed
+10822
-104
No files matched your search
@@ -8,7 +8,8 @@ import {
|
||||
Download,
|
||||
Command,
|
||||
Wrench,
|
||||
Music
|
||||
Music,
|
||||
Languages
|
||||
} from '@lucide/vue'
|
||||
|
||||
/**
|
||||
@@ -27,7 +28,8 @@ export const moduleIconMap: Record<string, Component> = {
|
||||
downloader: Download,
|
||||
quickpanel: Command,
|
||||
devtools: Wrench,
|
||||
music: Music
|
||||
music: Music,
|
||||
translate: Languages
|
||||
}
|
||||
|
||||
/** 获取模块图标组件,未找到时回退到 Settings 图标 */
|
||||
|
||||
@@ -11,6 +11,7 @@ import { moduleConfig as quickpanel } from './quickpanel'
|
||||
import { moduleConfig as devtools } from './devtools'
|
||||
import { moduleConfig as settings } from './settings'
|
||||
import { moduleConfig as music } from './music'
|
||||
import { moduleConfig as translate } from './translate'
|
||||
|
||||
const allModules: ModuleConfig[] = [
|
||||
proxy,
|
||||
@@ -21,7 +22,8 @@ const allModules: ModuleConfig[] = [
|
||||
quickpanel,
|
||||
devtools,
|
||||
settings,
|
||||
music
|
||||
music,
|
||||
translate
|
||||
]
|
||||
|
||||
// 启动时注册所有模块
|
||||
|
||||
@@ -7,8 +7,9 @@ import { EVENTS, STORAGE_KEYS, WINDOWS } from '@/lib/constants'
|
||||
// Rust 端通过 tauri-specta 生成的命令绑定(bindings.ts)
|
||||
import { commands } from '@/lib/bindings'
|
||||
import {
|
||||
Undo2, Redo2, Eraser, Copy, Save, ChevronsDown,
|
||||
Undo2, Redo2, Eraser, Copy, Save, ChevronsDown, Languages,
|
||||
} from '@lucide/vue'
|
||||
import { resolveTargetLabel } from '@/lib/translate/languages'
|
||||
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'
|
||||
import { Slider } from '@/components/ui/slider'
|
||||
import { TooltipProvider, Tooltip, TooltipTrigger, TooltipContent } from '@/components/ui/tooltip'
|
||||
@@ -1577,14 +1578,59 @@ function composeCanvas(): HTMLCanvasElement | null {
|
||||
}
|
||||
|
||||
/** 纯导出(保存用,无副作用):canvas → toDataURL base64 */
|
||||
async function exportBase64(): Promise<ExportOut | null> {
|
||||
if (annotations.value.length === 0) return cropFromStored()
|
||||
async function exportBase64(): Promise<ExportOut | null> { if (annotations.value.length === 0) return cropFromStored()
|
||||
const canvas = composeCanvas()
|
||||
if (!canvas) return null
|
||||
const sp = selPhys.value
|
||||
return { b64: canvas.toDataURL('image/png').split(',')[1] ?? '', w: sp.w, h: sp.h }
|
||||
}
|
||||
|
||||
// ===== 截图翻译 =====
|
||||
const translating = ref(false)
|
||||
let cachedToLabel = ''
|
||||
|
||||
/** 目标语言的自然语言名(提示词用),从翻译设置读取并缓存 */
|
||||
async function resolveToLabel(): Promise<string> {
|
||||
if (cachedToLabel) return cachedToLabel
|
||||
try {
|
||||
const s = await invoke<{ defaultTarget: string }>('translate_get_settings')
|
||||
cachedToLabel = resolveTargetLabel(s.defaultTarget) || 'zh-Hans'
|
||||
} catch {
|
||||
cachedToLabel = 'zh-Hans'
|
||||
}
|
||||
return cachedToLabel
|
||||
}
|
||||
|
||||
/**
|
||||
* 翻译选区:把选区交给翻译模块(本地 OCR 或视觉直译 → 悬浮窗展示)。
|
||||
*
|
||||
* 与「复制」同样的先隐藏后处理模式:OCR 与翻译耗时不可控,先隐藏覆盖层给用户即时反馈;
|
||||
* 结果与失败提示都由非激活悬浮窗在选区旁展示,不在主界面 toast。
|
||||
*/
|
||||
async function onTranslate() {
|
||||
if (translating.value) return
|
||||
const sp = selPhys.value
|
||||
if (sp.w < 2 || sp.h < 2) return
|
||||
translating.value = true
|
||||
magVisible.value = false
|
||||
await win.hide().catch(() => {})
|
||||
try {
|
||||
await invoke('translate_screenshot_region', {
|
||||
x: sp.x,
|
||||
y: sp.y,
|
||||
w: sp.w,
|
||||
h: sp.h,
|
||||
toLabel: await resolveToLabel(),
|
||||
})
|
||||
// 裁剪已完成,释放全屏底图内存(与正常关闭路径共用清理逻辑,重复清空无害)
|
||||
await invoke('screenshot_clear_fullscreen')
|
||||
} catch (e) {
|
||||
console.error('[screenshot] 翻译选区失败', e)
|
||||
} finally {
|
||||
translating.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function finish() {
|
||||
if (exporting.value) return
|
||||
exporting.value = true
|
||||
@@ -2297,6 +2343,20 @@ onUnmounted(() => {
|
||||
|
||||
<div class="tb-sep" />
|
||||
|
||||
<!-- 翻译(截图翻译:选区 → 本地 OCR / 视觉直译 → 悬浮窗展示) -->
|
||||
<div class="tb-group">
|
||||
<Tooltip>
|
||||
<TooltipTrigger as-child>
|
||||
<button class="tb-icon" @click="onTranslate">
|
||||
<Languages class="tb-svg" />
|
||||
</button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>翻译选区</TooltipContent>
|
||||
</Tooltip>
|
||||
</div>
|
||||
|
||||
<div class="tb-sep" />
|
||||
|
||||
<!-- 复制 / 保存(置末) -->
|
||||
<div class="tb-group">
|
||||
<Tooltip>
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
<script setup lang="ts">
|
||||
import { onMounted, ref } from 'vue'
|
||||
import { History, Languages, Settings } from '@lucide/vue'
|
||||
import { useModuleTabs } from '@/lib/use-module-tabs'
|
||||
import { useTranslateStore } from '@/stores/translateStore'
|
||||
import { createLogger } from '@/lib/logger'
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'
|
||||
import TranslateWorkbench from './components/TranslateWorkbench.vue'
|
||||
import TranslateSettings from './components/TranslateSettings.vue'
|
||||
import TranslateHistory from './components/TranslateHistory.vue'
|
||||
|
||||
const logger = createLogger('translate')
|
||||
const store = useTranslateStore()
|
||||
|
||||
const activeTab = ref('workbench')
|
||||
const tabsListRef = useModuleTabs('translate', activeTab, [
|
||||
{ value: 'workbench', label: '翻译' },
|
||||
{ value: 'history', label: '历史' },
|
||||
{ value: 'settings', label: '设置' }
|
||||
])
|
||||
|
||||
onMounted(async () => {
|
||||
try {
|
||||
await store.init()
|
||||
} catch (e) {
|
||||
logger.error(`翻译模块初始化失败:${String(e)}`)
|
||||
}
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="h-full overflow-hidden p-6 flex flex-col">
|
||||
<Tabs v-model="activeTab" class="flex-1 min-h-0 flex flex-col">
|
||||
<div ref="tabsListRef" class="shrink-0">
|
||||
<TabsList class="grid w-full max-w-md grid-cols-3 !bg-transparent !p-0 !shadow-none">
|
||||
<TabsTrigger value="workbench" class="gap-1.5">
|
||||
<Languages class="size-3.5" />翻译
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="history" class="gap-1.5">
|
||||
<History class="size-3.5" />历史
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="settings" class="gap-1.5">
|
||||
<Settings class="size-3.5" />设置
|
||||
</TabsTrigger>
|
||||
</TabsList>
|
||||
</div>
|
||||
|
||||
<TabsContent value="workbench" class="flex-1 min-h-0 flex flex-col mt-4 tab-animate">
|
||||
<TranslateWorkbench />
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="history" class="flex-1 min-h-0 flex flex-col mt-4 tab-animate">
|
||||
<TranslateHistory />
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="settings" class="flex-1 min-h-0 overflow-hidden mt-4 tab-animate">
|
||||
<TranslateSettings />
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
</div>
|
||||
</template>
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,368 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, ref, watch } from 'vue'
|
||||
import { toast } from 'vue-sonner'
|
||||
import { CircleAlert, CircleCheck, Eraser, KeyRound, LoaderCircle, RefreshCw, Trash2, Zap } from '@lucide/vue'
|
||||
import { useTranslateStore } from '@/stores/translateStore'
|
||||
import { ERROR_HINTS, type EngineTestResult, type EngineView, type TranslateEngineConfig } from '@/types/translate'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Textarea } from '@/components/ui/textarea'
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue
|
||||
} from '@/components/ui/select'
|
||||
|
||||
const props = defineProps<{ view: EngineView }>()
|
||||
const emit = defineEmits<{
|
||||
(e: 'deleted'): void
|
||||
}>()
|
||||
|
||||
const store = useTranslateStore()
|
||||
|
||||
/** 编辑草稿。保存前的改动只在这里,不影响已生效配置 */
|
||||
const draft = ref<TranslateEngineConfig>({ ...props.view.config })
|
||||
const apiKey = ref('')
|
||||
const models = ref<string[]>([])
|
||||
const testResult = ref<EngineTestResult | null>(null)
|
||||
const busy = ref<'' | 'save' | 'key' | 'test' | 'models'>('')
|
||||
const confirmingDelete = ref(false)
|
||||
|
||||
// 外部刷新(保存成功、密钥变更后 store.reload)时重置草稿
|
||||
watch(
|
||||
() => props.view,
|
||||
v => {
|
||||
draft.value = { ...v.config }
|
||||
apiKey.value = ''
|
||||
testResult.value = null
|
||||
}
|
||||
)
|
||||
|
||||
const dirty = computed(() => {
|
||||
const a = JSON.stringify(draft.value)
|
||||
const b = JSON.stringify(props.view.config)
|
||||
return a !== b
|
||||
})
|
||||
|
||||
const canFetchModels = computed(() => props.view.hasApiKey && props.view.config.kind === 'ai')
|
||||
|
||||
/** 数值输入的收敛:NaN 一律退回默认值,避免把空输入写进配置 */
|
||||
function toNumber(raw: string | number, fallback: number, min: number, max: number): number {
|
||||
const n = typeof raw === 'number' ? raw : Number.parseFloat(raw)
|
||||
if (!Number.isFinite(n)) return fallback
|
||||
return Math.min(max, Math.max(min, n))
|
||||
}
|
||||
|
||||
async function withBusy(kind: typeof busy.value, fn: () => Promise<void>) {
|
||||
busy.value = kind
|
||||
try {
|
||||
await fn()
|
||||
} catch (e) {
|
||||
toast.error(String(e))
|
||||
} finally {
|
||||
busy.value = ''
|
||||
}
|
||||
}
|
||||
|
||||
const save = () =>
|
||||
withBusy('save', async () => {
|
||||
// extraBody 只接受 JSON 对象:留空视为「无额外参数」,写了但解析失败要拦下来,
|
||||
// 否则会静默传一份空参数,用户以为生效了其实没有
|
||||
const extra = draft.value.extraBody?.trim()
|
||||
if (extra) {
|
||||
try {
|
||||
const parsed = JSON.parse(extra)
|
||||
if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
|
||||
toast.error('额外请求体必须是 JSON 对象,例如 {"thinking":{"type":"disabled"}}')
|
||||
return
|
||||
}
|
||||
} catch {
|
||||
toast.error('额外请求体不是合法 JSON')
|
||||
return
|
||||
}
|
||||
}
|
||||
await store.saveEngine({ ...draft.value, extraBody: extra || null })
|
||||
toast.success('已保存')
|
||||
})
|
||||
|
||||
const saveKey = () =>
|
||||
withBusy('key', async () => {
|
||||
// 后端按「空串即清除」处理,因此这里必须挡住空提交,否则一次误点会清掉已有密钥
|
||||
if (!apiKey.value.trim()) {
|
||||
toast.error('请输入 API Key')
|
||||
return
|
||||
}
|
||||
await store.setSecret(props.view.config.id, apiKey.value.trim())
|
||||
apiKey.value = ''
|
||||
toast.success('密钥已写入系统凭据管理器')
|
||||
})
|
||||
|
||||
const clearKey = () =>
|
||||
withBusy('key', async () => {
|
||||
await store.clearSecret(props.view.config.id)
|
||||
toast.success('密钥已清除')
|
||||
})
|
||||
|
||||
const test = () =>
|
||||
withBusy('test', async () => {
|
||||
// 传草稿而非已保存配置:未保存的 Base URL 改动也能立刻测试
|
||||
testResult.value = await store.testEngine({ ...draft.value })
|
||||
if (testResult.value.ok) toast.success('连通正常')
|
||||
else toast.error(testResult.value.message)
|
||||
})
|
||||
|
||||
const fetchModels = () =>
|
||||
withBusy('models', async () => {
|
||||
models.value = await store.fetchModels(props.view.config.id)
|
||||
if (models.value.length === 0) toast.info('上游未返回任何模型')
|
||||
else toast.success(`拉取到 ${models.value.length} 个模型`)
|
||||
})
|
||||
|
||||
const remove = () =>
|
||||
withBusy('save', async () => {
|
||||
if (!confirmingDelete.value) {
|
||||
confirmingDelete.value = true
|
||||
return
|
||||
}
|
||||
await store.deleteEngine(props.view.config.id)
|
||||
toast.success('引擎已删除')
|
||||
emit('deleted')
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="space-y-3 rounded-lg border bg-muted/20 p-3">
|
||||
<div class="grid grid-cols-2 gap-3">
|
||||
<div class="space-y-1.5">
|
||||
<Label class="text-[12px]">名称</Label>
|
||||
<Input v-model="draft.name" class="h-8 text-[13px]" />
|
||||
</div>
|
||||
<div class="space-y-1.5">
|
||||
<Label class="text-[12px]">优先级(越小越先尝试)</Label>
|
||||
<Input
|
||||
:model-value="draft.priority"
|
||||
type="number"
|
||||
class="h-8 text-[13px]"
|
||||
@update:model-value="v => (draft.priority = toNumber(v, 100, 0, 9999))"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="draft.kind === 'ai' || draft.preset === 'libretranslate'"
|
||||
class="col-span-2 space-y-1.5"
|
||||
>
|
||||
<Label class="text-[12px]">Base URL</Label>
|
||||
<Input
|
||||
v-model="draft.baseUrl"
|
||||
:placeholder="draft.preset === 'libretranslate' ? 'https://translate.example.com' : 'https://api.deepseek.com'"
|
||||
class="h-8 text-[13px]"
|
||||
/>
|
||||
<p class="text-[11px] text-muted-foreground">
|
||||
<template v-if="draft.kind === 'ai'">
|
||||
填到 /v1 为止即可;若粘入了完整端点(…/chat/completions)后端会自动剥掉。
|
||||
</template>
|
||||
<template v-else>
|
||||
填 LibreTranslate 服务根地址;若粘入了 /translate 结尾后端会自动剥掉。
|
||||
</template>
|
||||
</p>
|
||||
</div>
|
||||
<div v-if="draft.kind === 'ai'" class="space-y-1.5">
|
||||
<Label class="text-[12px]">模型</Label>
|
||||
<Input v-model="draft.model" placeholder="deepseek-flash" class="h-8 text-[13px]" />
|
||||
</div>
|
||||
<div class="space-y-1.5">
|
||||
<Label class="text-[12px]">超时(毫秒)</Label>
|
||||
<Input
|
||||
:model-value="draft.timeoutMs"
|
||||
type="number"
|
||||
class="h-8 text-[13px]"
|
||||
@update:model-value="v => (draft.timeoutMs = toNumber(v, 30000, 1000, 600000))"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div v-if="draft.kind === 'ai'" class="space-y-1.5">
|
||||
<Label class="text-[12px]">温度(0~2)</Label>
|
||||
<Input
|
||||
:model-value="draft.temperature"
|
||||
type="number"
|
||||
step="0.1"
|
||||
class="h-8 text-[13px]"
|
||||
@update:model-value="v => (draft.temperature = toNumber(v, 0.3, 0, 2))"
|
||||
/>
|
||||
</div>
|
||||
<div v-if="draft.kind === 'ai'" class="space-y-1.5">
|
||||
<Label class="text-[12px]">最大输出 tokens</Label>
|
||||
<Input
|
||||
:model-value="draft.maxTokens"
|
||||
type="number"
|
||||
class="h-8 text-[13px]"
|
||||
@update:model-value="v => (draft.maxTokens = toNumber(v, 4096, 64, 384000))"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="draft.kind !== 'ai'"
|
||||
class="col-span-2 space-y-1 rounded-md border bg-background p-2.5 text-[11px] text-muted-foreground"
|
||||
>
|
||||
<p v-if="draft.preset === 'libretranslate'">
|
||||
LibreTranslate:文本发往你自己的服务器。API Key 可选——部署启用密钥校验时才必须填写。
|
||||
</p>
|
||||
<p v-else-if="draft.preset === 'mymemory'">
|
||||
MyMemory:需要显式源语言(源语言为「自动检测」时该源会被跳过),单次约 500 字节。
|
||||
</p>
|
||||
<p>免密钥源会把文本送交第三方接口,请自行判断内容是否适合外发。</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="draft.kind === 'ai'" class="flex items-start gap-3 rounded-md border bg-background p-2.5">
|
||||
<Switch
|
||||
:model-value="draft.supportsVision"
|
||||
@update:model-value="(v: boolean) => (draft.supportsVision = v)"
|
||||
/>
|
||||
<div class="min-w-0 flex-1">
|
||||
<Label class="text-[12px]">支持图像输入</Label>
|
||||
<p class="mt-0.5 text-[11px] text-muted-foreground">
|
||||
勾选后「截图翻译」可用视觉直译模式:把截图直接发给该模型,识别与翻译一步完成。
|
||||
仅对支持图像输入的模型勾选(如 GLM-4V、Qwen-VL、gpt-4o 等)。
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="draft.kind === 'ai' || draft.preset === 'libretranslate'"
|
||||
class="space-y-1.5 rounded-md border bg-background p-2.5"
|
||||
>
|
||||
<div class="flex items-center gap-1.5">
|
||||
<KeyRound class="size-3.5 text-muted-foreground" />
|
||||
<Label class="text-[12px]">
|
||||
{{ draft.preset === 'libretranslate' ? 'API Key(可选)' : 'API Key' }}
|
||||
</Label>
|
||||
<span class="text-[11px] text-muted-foreground">
|
||||
存入 Windows 凭据管理器,不写入配置文件、不回传前端明文
|
||||
</span>
|
||||
</div>
|
||||
<div class="flex gap-2">
|
||||
<Input
|
||||
v-model="apiKey"
|
||||
type="password"
|
||||
autocomplete="off"
|
||||
class="h-8 text-[13px]"
|
||||
:placeholder="view.hasApiKey ? `已配置:${view.apiKeyMasked}` : '尚未配置'"
|
||||
/>
|
||||
<Button size="sm" :disabled="busy === 'key' || !apiKey.trim()" @click="saveKey">
|
||||
<LoaderCircle v-if="busy === 'key'" class="animate-spin" />
|
||||
保存
|
||||
</Button>
|
||||
<Button
|
||||
v-if="view.hasApiKey"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
:disabled="busy === 'key'"
|
||||
@click="clearKey"
|
||||
>
|
||||
<Eraser />
|
||||
清除
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<details class="rounded-md border bg-background p-2.5">
|
||||
<summary class="cursor-pointer select-none text-[12px] font-medium">
|
||||
高级:自定义提示词与额外请求体
|
||||
</summary>
|
||||
<div class="mt-2 space-y-3">
|
||||
<div class="space-y-1.5">
|
||||
<Label class="text-[12px]">自定义 System Prompt</Label>
|
||||
<Textarea
|
||||
v-model="draft.systemPrompt"
|
||||
class="min-h-20 text-[12px]"
|
||||
placeholder="留空则使用「设置 → 提示词模板」中的模板;{target} 会替换为目标语言"
|
||||
/>
|
||||
</div>
|
||||
<div class="space-y-1.5">
|
||||
<Label class="text-[12px]">额外请求体(JSON 对象)</Label>
|
||||
<Textarea
|
||||
:model-value="draft.extraBody ?? ''"
|
||||
class="min-h-16 font-mono text-[12px]"
|
||||
placeholder='例如 {"thinking":{"type":"disabled"}}'
|
||||
@update:model-value="v => (draft.extraBody = String(v) || null)"
|
||||
/>
|
||||
<p class="text-[11px] text-muted-foreground">
|
||||
用于透传非标准参数。翻译场景默认不传 thinking / reasoning_effort。
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</details>
|
||||
|
||||
<div v-if="models.length > 0" class="space-y-1.5 rounded-md border bg-background p-2.5">
|
||||
<Label class="text-[12px]">从上游拉取到的模型(选择即填入上方「模型」)</Label>
|
||||
<Select :model-value="draft.model" @update:model-value="v => (draft.model = String(v))">
|
||||
<SelectTrigger class="h-8 text-[12px]"><SelectValue placeholder="选择模型" /></SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem v-for="m in models" :key="m" :value="m">{{ m }}</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-if="testResult"
|
||||
class="space-y-1 rounded-md border p-2.5 text-[12px]"
|
||||
:class="testResult.ok ? 'bg-emerald-50 dark:bg-emerald-950/20' : 'bg-red-50 dark:bg-red-950/20'"
|
||||
>
|
||||
<div class="flex items-start gap-2">
|
||||
<CircleCheck v-if="testResult.ok" class="mt-0.5 size-3.5 shrink-0" />
|
||||
<CircleAlert v-else class="mt-0.5 size-3.5 shrink-0" />
|
||||
<div class="min-w-0 flex-1">
|
||||
<p class="break-words">{{ testResult.message }}</p>
|
||||
<p v-if="!testResult.ok && testResult.errorKind" class="mt-0.5 text-muted-foreground">
|
||||
{{ ERROR_HINTS[testResult.errorKind] }}
|
||||
</p>
|
||||
<pre
|
||||
v-if="testResult.detail"
|
||||
class="mt-1 whitespace-pre-wrap break-all rounded bg-background/60 p-1.5 text-[11px]"
|
||||
>{{ testResult.detail }}</pre>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<Button size="sm" :disabled="busy === 'save' || !dirty" @click="save">
|
||||
<LoaderCircle v-if="busy === 'save'" class="animate-spin" />
|
||||
保存配置
|
||||
</Button>
|
||||
<Button variant="outline" size="sm" :disabled="busy === 'test'" @click="test">
|
||||
<LoaderCircle v-if="busy === 'test'" class="animate-spin" />
|
||||
<Zap v-else />
|
||||
测试连通性
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
:disabled="busy === 'models' || !canFetchModels"
|
||||
:title="canFetchModels ? '从上游拉取模型列表' : '需先配置 API Key'"
|
||||
@click="fetchModels"
|
||||
>
|
||||
<LoaderCircle v-if="busy === 'models'" class="animate-spin" />
|
||||
<RefreshCw v-else />
|
||||
拉取模型
|
||||
</Button>
|
||||
|
||||
<div class="flex-1" />
|
||||
|
||||
<Badge v-if="dirty" variant="outline" class="text-[11px]">有未保存的改动</Badge>
|
||||
<Button
|
||||
:variant="confirmingDelete ? 'destructive' : 'outline'"
|
||||
size="sm"
|
||||
:disabled="busy === 'save'"
|
||||
@click="remove"
|
||||
>
|
||||
<Trash2 />
|
||||
{{ confirmingDelete ? '确认删除?' : '删除' }}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,270 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue'
|
||||
import { toast } from 'vue-sonner'
|
||||
import { Copy, LoaderCircle, Search, Star, Trash2 } from '@lucide/vue'
|
||||
import { useTranslateStore } from '@/stores/translateStore'
|
||||
import { labelOf } from '@/lib/translate/languages'
|
||||
import { copyToClipboard } from '@/lib/translate/api'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { ScrollArea } from '@/components/ui/scroll-area'
|
||||
import { Switch } from '@/components/ui/switch'
|
||||
|
||||
const store = useTranslateStore()
|
||||
|
||||
const VIA_LABELS: Record<string, string> = {
|
||||
manual: '主面板',
|
||||
selection: '划词',
|
||||
clipboard: '剪贴板',
|
||||
screenshot: '截图',
|
||||
preview: '预览'
|
||||
}
|
||||
|
||||
function viaLabel(via: string): string {
|
||||
return VIA_LABELS[via] ?? via
|
||||
}
|
||||
|
||||
function formatTs(ts: number): string {
|
||||
const d = new Date(ts)
|
||||
const pad = (n: number) => `${n}`.padStart(2, '0')
|
||||
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`
|
||||
}
|
||||
|
||||
/** 是否处于筛选态:决定空列表该提示「还没记录」还是「没有匹配」 */
|
||||
const hasFilter = computed(() => store.historyQuery.trim().length > 0 || store.historyFavOnly)
|
||||
|
||||
/** 只有一条都没加载到时才让整块区域让位给加载态,否则改关键词时列表会闪没 */
|
||||
const showInitialLoading = computed(
|
||||
() => store.historyLoading && store.historyItems.length === 0
|
||||
)
|
||||
|
||||
/** 搜索是防抖的:逐键查询没有意义,200ms 停顿后再发 */
|
||||
let searchTimer: ReturnType<typeof setTimeout> | null = null
|
||||
function onSearchInput() {
|
||||
if (searchTimer) clearTimeout(searchTimer)
|
||||
searchTimer = setTimeout(() => void store.reloadHistory(), 200)
|
||||
}
|
||||
|
||||
async function copyItem(text: string) {
|
||||
try {
|
||||
await copyToClipboard(text)
|
||||
toast.success('已复制')
|
||||
} catch (e) {
|
||||
toast.error(String(e))
|
||||
}
|
||||
}
|
||||
|
||||
async function onDelete(id: number) {
|
||||
try {
|
||||
await store.deleteHistoryItem(id)
|
||||
} catch (e) {
|
||||
toast.error(String(e))
|
||||
}
|
||||
}
|
||||
|
||||
async function onClear() {
|
||||
if (!window.confirm('确定清空全部历史(含收藏)?此操作不可恢复。')) return
|
||||
try {
|
||||
await store.clearHistory()
|
||||
toast.success('历史已清空')
|
||||
} catch (e) {
|
||||
toast.error(String(e))
|
||||
}
|
||||
}
|
||||
|
||||
// ===== 触底加载下一页 =====
|
||||
/**
|
||||
* 哨兵放进滚动视口内(而不是监听 ScrollArea 的 scroll 事件):
|
||||
* 分页由 store 管,组件只需要知道「到达底部了」这一个信号。
|
||||
*/
|
||||
const loadMoreRef = ref<HTMLElement | null>(null)
|
||||
let loadMoreObserver: IntersectionObserver | null = null
|
||||
|
||||
onMounted(() => {
|
||||
loadMoreObserver = new IntersectionObserver(
|
||||
entries => {
|
||||
if (!entries.some(e => e.isIntersecting)) return
|
||||
void store.loadMoreHistory()
|
||||
// 追加后哨兵位置变了但可能仍处于交叉状态,此时不会再触发回调,必须重新 observe
|
||||
nextTick(() => {
|
||||
const el = loadMoreRef.value
|
||||
if (el && loadMoreObserver) {
|
||||
loadMoreObserver.unobserve(el)
|
||||
loadMoreObserver.observe(el)
|
||||
}
|
||||
})
|
||||
},
|
||||
// 提前一屏取数,滚到底时数据已就位,不会看到「停顿—跳出」
|
||||
{ rootMargin: '300px' }
|
||||
)
|
||||
|
||||
/**
|
||||
* 必须用 watch 而不是「挂载时 observe 一次」。
|
||||
*
|
||||
* 哨兵在 v-if/v-else 分支里:首屏是「加载中…」或「还没有记录」,哨兵根本不存在,
|
||||
* 挂载那一刻拿到的是 null。之后数据到了、哨兵被创建,ref 才会变——不监听就永远
|
||||
* 不会 observe,第二页永远加载不出来。
|
||||
*
|
||||
* watch 放在 onMounted 内注册:此时 loadMoreObserver 已就绪,immediate 能立刻接管
|
||||
* 已经存在的哨兵;放在 setup 顶层会在观察者创建之前跑,被守卫挡掉后再无第二次机会。
|
||||
*/
|
||||
watch(
|
||||
loadMoreRef,
|
||||
el => {
|
||||
if (!loadMoreObserver) return
|
||||
loadMoreObserver.disconnect()
|
||||
if (el) loadMoreObserver.observe(el)
|
||||
},
|
||||
{ immediate: true }
|
||||
)
|
||||
|
||||
void store.reloadHistory()
|
||||
})
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
if (searchTimer) clearTimeout(searchTimer)
|
||||
loadMoreObserver?.disconnect()
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex h-full min-h-0 flex-col">
|
||||
<div class="mx-auto flex min-h-0 w-full max-w-3xl flex-col gap-3">
|
||||
<!-- 工具条 -->
|
||||
<div class="flex shrink-0 flex-wrap items-center gap-2">
|
||||
<div class="relative min-w-56 flex-1">
|
||||
<Search class="absolute left-2.5 top-1/2 size-4 -translate-y-1/2 text-muted-foreground" />
|
||||
<Input
|
||||
v-model="store.historyQuery"
|
||||
class="h-8 pl-8 text-[13px]"
|
||||
placeholder="搜索原文或译文…"
|
||||
@input="onSearchInput"
|
||||
/>
|
||||
</div>
|
||||
<label class="flex items-center gap-1.5 text-[12px] text-muted-foreground">
|
||||
<Switch
|
||||
:model-value="store.historyFavOnly"
|
||||
@update:model-value="
|
||||
v => {
|
||||
store.historyFavOnly = Boolean(v)
|
||||
void store.reloadHistory()
|
||||
}
|
||||
"
|
||||
/>
|
||||
只看收藏
|
||||
</label>
|
||||
<Button variant="outline" size="sm" @click="onClear">
|
||||
<Trash2 />
|
||||
清空
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<!--
|
||||
这里把 Card 当「带固定标题栏的滚动容器」用,所以要在本地覆盖掉 Card 的
|
||||
内容卡片默认值:gap-6 会在标题与列表之间留 24px 空带、py-6 会在卡片底部
|
||||
留 24px 死区、缺 overflow-hidden 则滚动条会溢出圆角。
|
||||
-->
|
||||
<Card class="flex min-h-0 flex-1 flex-col gap-0 overflow-hidden py-0">
|
||||
<CardHeader class="shrink-0 gap-0 px-4 py-2.5">
|
||||
<CardTitle class="text-[13px]">翻译历史</CardTitle>
|
||||
</CardHeader>
|
||||
<!-- 分隔线放在内容侧:CardHeader 带 [.border-b]:pb-6,加 border-b 会把标题栏重新顶高 -->
|
||||
<CardContent class="min-h-0 flex-1 border-t p-0">
|
||||
<div
|
||||
v-if="showInitialLoading"
|
||||
class="flex items-center gap-2 px-4 py-6 text-[13px] text-muted-foreground"
|
||||
>
|
||||
<LoaderCircle class="size-3.5 animate-spin" />
|
||||
加载中…
|
||||
</div>
|
||||
|
||||
<p
|
||||
v-else-if="store.historyItems.length === 0"
|
||||
class="px-4 py-8 text-center text-[13px] text-muted-foreground"
|
||||
>
|
||||
{{ hasFilter ? '没有匹配的记录。' : '还没有翻译记录。' }}
|
||||
</p>
|
||||
|
||||
<ScrollArea v-else class="h-full min-h-0">
|
||||
<!--
|
||||
分割线容器里**只能放记录本身**。
|
||||
Tailwind v4 的 divide-y 展开成 `> :not(:last-child){border-bottom-width:1px}`,
|
||||
哨兵一旦放进这个容器,真正的末条就被挤成「非末位」而多画一条底部分割线;
|
||||
它又紧贴卡片下边框(中间只隔哨兵那 1px),看起来就是双线。
|
||||
-->
|
||||
<div class="divide-y">
|
||||
<div
|
||||
v-for="item in store.historyItems"
|
||||
:key="item.id"
|
||||
class="history-row group px-4 py-3"
|
||||
>
|
||||
<div class="flex flex-wrap items-center gap-2 text-[11px] text-muted-foreground">
|
||||
<span class="tabular-nums">{{ formatTs(item.ts) }}</span>
|
||||
<Badge variant="outline" class="text-[11px]">{{ viaLabel(item.via) }}</Badge>
|
||||
<span>{{ labelOf(item.fromLang) }} → {{ labelOf(item.toLang) }}</span>
|
||||
<span v-if="item.engineName">{{ item.engineName }}</span>
|
||||
<div class="flex-1" />
|
||||
<button
|
||||
class="rounded p-1 transition-colors hover:bg-accent"
|
||||
:class="{ 'text-amber-500': item.favorited }"
|
||||
:title="item.favorited ? '取消收藏' : '收藏'"
|
||||
@click="store.toggleHistoryFavorite(item.id)"
|
||||
>
|
||||
<Star class="size-3.5" />
|
||||
</button>
|
||||
<button
|
||||
class="rounded p-1 text-muted-foreground opacity-0 transition-all hover:bg-accent group-hover:opacity-100"
|
||||
title="复制译文"
|
||||
@click="copyItem(item.resultText)"
|
||||
>
|
||||
<Copy class="size-3.5" />
|
||||
</button>
|
||||
<button
|
||||
class="rounded p-1 text-muted-foreground opacity-0 transition-all hover:bg-accent group-hover:opacity-100"
|
||||
title="删除"
|
||||
@click="onDelete(item.id)"
|
||||
>
|
||||
<Trash2 class="size-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
<p class="mt-1 line-clamp-2 text-[12px] text-muted-foreground">{{ item.sourceText }}</p>
|
||||
<p class="mt-0.5 line-clamp-3 whitespace-pre-wrap break-words text-[13px]">
|
||||
{{ item.resultText }}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 触底哨兵:在分割线容器之外,本身不占位,只作 observer 的观察目标 -->
|
||||
<div ref="loadMoreRef" class="h-px" />
|
||||
|
||||
<div
|
||||
v-if="store.historyLoadingMore"
|
||||
class="flex items-center justify-center gap-2 py-3 text-[12px] text-muted-foreground"
|
||||
>
|
||||
<LoaderCircle class="size-3.5 animate-spin" />
|
||||
加载中…
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
/**
|
||||
* 行级渲染跳过。
|
||||
*
|
||||
* 分页后列表仍会随用户持续滚动累积到上千行,每行含原文、译文两段可变长文本。
|
||||
* `content-visibility: auto` 让浏览器跳过视口外行的布局与绘制,效果接近虚拟列表,
|
||||
* 但不需要自己接管滚动位置;`contain-intrinsic-size` 提供未渲染时的占位高度,
|
||||
* 其中 `auto` 关键字让浏览器按首次渲染的实际高度记忆,避免滚动条反复抖动。
|
||||
* 84px 只是首屏的估算值(py-3 + 三行文本),估偏只影响滚动条长度的第一帧。
|
||||
*/
|
||||
.history-row {
|
||||
content-visibility: auto;
|
||||
contain-intrinsic-size: auto 84px;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,731 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref, watch } from 'vue'
|
||||
import { toast } from 'vue-sonner'
|
||||
import { CircleAlert, LoaderCircle, Plus, Save, ScanText, Sparkles } from '@lucide/vue'
|
||||
import { useTranslateStore } from '@/stores/translateStore'
|
||||
import { orderedLanguages } from '@/lib/translate/languages'
|
||||
import {
|
||||
ENGINE_PRESETS,
|
||||
type HistorySettings,
|
||||
type PromptTemplates,
|
||||
type SelectionSettings,
|
||||
type TranslateEngineConfig,
|
||||
type TranslateSettings
|
||||
} from '@/types/translate'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import { Separator } from '@/components/ui/separator'
|
||||
import { Switch } from '@/components/ui/switch'
|
||||
import { Textarea } from '@/components/ui/textarea'
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue
|
||||
} from '@/components/ui/select'
|
||||
import EngineEditor from './EngineEditor.vue'
|
||||
|
||||
const store = useTranslateStore()
|
||||
|
||||
/** 展开编辑的引擎 id(空表示全部收起) */
|
||||
const editingId = ref('')
|
||||
const presetKey = ref(ENGINE_PRESETS[0].key)
|
||||
const newEngineName = ref('')
|
||||
const savingTemplates = ref(false)
|
||||
|
||||
/** 提示词模板是长文本,不做逐键落盘,改为本地草稿 + 显式保存 */
|
||||
const templates = ref<PromptTemplates | null>(null)
|
||||
|
||||
watch(
|
||||
() => store.settings?.promptTemplates,
|
||||
p => {
|
||||
if (p) templates.value = { ...p }
|
||||
},
|
||||
{ immediate: true }
|
||||
)
|
||||
|
||||
onMounted(async () => {
|
||||
try {
|
||||
await store.init()
|
||||
} catch (e) {
|
||||
toast.error(`读取设置失败:${String(e)}`)
|
||||
}
|
||||
})
|
||||
|
||||
const targetLanguages = computed(() => orderedLanguages(false))
|
||||
|
||||
const templatesDirty = computed(() => {
|
||||
if (!templates.value || !store.settings) return false
|
||||
return JSON.stringify(templates.value) !== JSON.stringify(store.settings.promptTemplates)
|
||||
})
|
||||
|
||||
/** 生成不与现有实例冲突的 id(id 会进入凭据键,必须唯一且字符集受限) */
|
||||
function nextEngineId(base: string): string {
|
||||
const used = new Set(store.engines.map(e => e.config.id))
|
||||
if (!used.has(base)) return base
|
||||
let i = 2
|
||||
while (used.has(`${base}-${i}`)) i += 1
|
||||
return `${base}-${i}`
|
||||
}
|
||||
|
||||
const selectedPreset = computed(() => ENGINE_PRESETS.find(p => p.key === presetKey.value))
|
||||
|
||||
async function addEngine() {
|
||||
const preset = selectedPreset.value
|
||||
if (!preset) return
|
||||
const name = newEngineName.value.trim() || preset.label
|
||||
const config: TranslateEngineConfig = {
|
||||
id: nextEngineId(preset.key),
|
||||
name,
|
||||
kind: 'ai',
|
||||
preset: preset.key,
|
||||
enabled: true,
|
||||
priority: 100,
|
||||
baseUrl: '',
|
||||
model: '',
|
||||
temperature: 0.3,
|
||||
maxTokens: 4096,
|
||||
timeoutMs: 30000,
|
||||
systemPrompt: '',
|
||||
extraBody: null,
|
||||
...preset.template,
|
||||
// 显式兜底:preset.template 是 Partial,缺省必须落成 false
|
||||
supportsVision: preset.template.supportsVision ?? false
|
||||
}
|
||||
try {
|
||||
await store.saveEngine(config)
|
||||
newEngineName.value = ''
|
||||
editingId.value = config.id
|
||||
toast.success(`已新增引擎「${name}」,请填写 API Key`)
|
||||
} catch (e) {
|
||||
toast.error(String(e))
|
||||
}
|
||||
}
|
||||
|
||||
async function patch(patch: Partial<TranslateSettings>) {
|
||||
try {
|
||||
await store.patchSettings(patch)
|
||||
} catch (e) {
|
||||
toast.error(String(e))
|
||||
}
|
||||
}
|
||||
|
||||
// ===== 翻译面板:快捷键与黑名单需要显式保存 =====
|
||||
// 快捷键是文本输入,逐键保存会在「Ctrl」这种半成品状态下反复注册/注销并报错;
|
||||
// 黑名单同理(一行一个进程名,输入到一半不该落盘)。这两项因此走草稿 + 保存按钮,
|
||||
// 其余开关类项改动即生效。
|
||||
const shortcutDraft = ref({ panelShortcut: '' })
|
||||
const blacklistDraft = ref('')
|
||||
const applyingShortcuts = ref(false)
|
||||
|
||||
watch(
|
||||
() => store.settings?.selection,
|
||||
s => {
|
||||
if (!s) return
|
||||
shortcutDraft.value = { panelShortcut: s.panelShortcut }
|
||||
blacklistDraft.value = s.blacklist.join('\n')
|
||||
},
|
||||
{ immediate: true, deep: true }
|
||||
)
|
||||
|
||||
const shortcutsDirty = computed(() => {
|
||||
const s = store.settings?.selection
|
||||
if (!s) return false
|
||||
return shortcutDraft.value.panelShortcut.trim() !== s.panelShortcut
|
||||
})
|
||||
|
||||
const blacklistDirty = computed(() => {
|
||||
const s = store.settings?.selection
|
||||
if (!s) return false
|
||||
return blacklistDraft.value !== s.blacklist.join('\n')
|
||||
})
|
||||
|
||||
async function patchSelection(next: Partial<SelectionSettings>) {
|
||||
if (!store.settings) return
|
||||
await patch({ selection: { ...store.settings.selection, ...next } })
|
||||
}
|
||||
|
||||
// ===== 历史:条数需要草稿 + 显式提交 =====
|
||||
// 与快捷键、黑名单同理,数字输入也不该逐键落盘:删掉「2000」的中间态是空串或「2」,
|
||||
// 一提交就把上限改成 2、随即触发一次大规模淘汰,是不可逆的。改成失焦 / 回车才写。
|
||||
|
||||
/** 后端默认上限,也是输入框的兜底值 */
|
||||
const HISTORY_MAX_ITEMS_MIN = 100
|
||||
const HISTORY_MAX_ITEMS_MAX = 20000
|
||||
|
||||
const maxItemsDraft = ref<number | undefined>(undefined)
|
||||
|
||||
watch(
|
||||
() => store.settings?.history.maxItems,
|
||||
v => {
|
||||
maxItemsDraft.value = v ?? undefined
|
||||
},
|
||||
{ immediate: true }
|
||||
)
|
||||
|
||||
async function patchHistory(next: Partial<HistorySettings>) {
|
||||
if (!store.settings) return
|
||||
await patch({ history: { ...store.settings.history, ...next } })
|
||||
}
|
||||
|
||||
/** 提交保留条数。越界就夹回区间,而不是静默丢弃用户输入。 */
|
||||
async function commitMaxItems() {
|
||||
const current = store.settings?.history.maxItems
|
||||
if (current === undefined) return
|
||||
const raw = Number(maxItemsDraft.value)
|
||||
if (!Number.isFinite(raw)) {
|
||||
maxItemsDraft.value = current
|
||||
return
|
||||
}
|
||||
const clamped = Math.min(HISTORY_MAX_ITEMS_MAX, Math.max(HISTORY_MAX_ITEMS_MIN, Math.round(raw)))
|
||||
maxItemsDraft.value = clamped
|
||||
if (clamped === current) return
|
||||
await patchHistory({ maxItems: clamped })
|
||||
toast.success(`保留条数已设为 ${clamped}`)
|
||||
}
|
||||
|
||||
/** 应用快捷键:保存设置后后端会立刻重新注册,无需重启应用 */
|
||||
async function applyShortcuts() {
|
||||
if (!store.settings) return
|
||||
applyingShortcuts.value = true
|
||||
try {
|
||||
await store.persist({
|
||||
...store.settings,
|
||||
selection: {
|
||||
...store.settings.selection,
|
||||
panelShortcut: shortcutDraft.value.panelShortcut.trim()
|
||||
}
|
||||
})
|
||||
toast.success('快捷键已应用')
|
||||
} catch (e) {
|
||||
toast.error(String(e))
|
||||
} finally {
|
||||
applyingShortcuts.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function saveBlacklist() {
|
||||
const list = blacklistDraft.value
|
||||
.split('\n')
|
||||
.map(line => line.trim())
|
||||
.filter(Boolean)
|
||||
await patchSelection({ blacklist: list })
|
||||
toast.success('名单已保存')
|
||||
}
|
||||
|
||||
async function previewPopup() {
|
||||
try {
|
||||
await store.previewPopup()
|
||||
} catch (e) {
|
||||
toast.error(String(e))
|
||||
}
|
||||
}
|
||||
|
||||
async function saveTemplates() {
|
||||
if (!templates.value || !store.settings) return
|
||||
savingTemplates.value = true
|
||||
try {
|
||||
await store.persist({ ...store.settings, promptTemplates: { ...templates.value } })
|
||||
toast.success('提示词模板已保存')
|
||||
} catch (e) {
|
||||
toast.error(String(e))
|
||||
} finally {
|
||||
savingTemplates.value = false
|
||||
}
|
||||
}
|
||||
|
||||
/** 模板占位符校验:漏了 {target} 会让模型不知道该译成什么语言 */
|
||||
function templateWarning(text: string): string {
|
||||
if (text.trim() && !text.includes('{target}')) {
|
||||
return '未包含 {target} 占位符,模型将无法得知目标语言'
|
||||
}
|
||||
return ''
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div v-if="store.loading && !store.settings" class="flex items-center gap-2 py-2 text-[13px] text-muted-foreground">
|
||||
<LoaderCircle class="size-3.5 animate-spin" />
|
||||
正在读取设置…
|
||||
</div>
|
||||
|
||||
<div v-else class="h-full overflow-y-auto pb-2">
|
||||
<div class="mx-auto max-w-3xl space-y-4">
|
||||
<!-- ===== 引擎 ===== -->
|
||||
<Card>
|
||||
<CardHeader class="pb-3">
|
||||
<CardTitle class="flex items-center gap-2 text-[14px]">
|
||||
<Sparkles class="size-4" />
|
||||
翻译引擎
|
||||
</CardTitle>
|
||||
<p class="text-[12px] text-muted-foreground">
|
||||
同一类引擎可配置多个实例(如官方 API 与本地 Ollama 并存)。「自动」模式会按优先级依次尝试。
|
||||
</p>
|
||||
</CardHeader>
|
||||
<CardContent class="space-y-3">
|
||||
<div
|
||||
v-for="view in store.engines"
|
||||
:key="view.config.id"
|
||||
class="rounded-lg border p-3"
|
||||
>
|
||||
<div class="flex items-center gap-2">
|
||||
<span class="text-[13px] font-medium">{{ view.config.name }}</span>
|
||||
<Badge variant="outline" class="text-[11px]">
|
||||
{{ view.config.kind === 'ai' ? 'AI · OpenAI 兼容' : view.config.kind }}
|
||||
</Badge>
|
||||
<Badge variant="secondary" class="text-[11px] tabular-nums">
|
||||
P{{ view.config.priority }}
|
||||
</Badge>
|
||||
<Badge v-if="view.ready" variant="secondary" class="text-[11px]">就绪</Badge>
|
||||
|
||||
<div class="flex-1" />
|
||||
|
||||
<span class="text-[11px] text-muted-foreground">{{ view.config.model }}</span>
|
||||
<Switch
|
||||
:model-value="view.config.enabled"
|
||||
@update:model-value="
|
||||
v =>
|
||||
store
|
||||
.saveEngine({ ...view.config, enabled: Boolean(v) })
|
||||
.catch(e => toast.error(String(e)))
|
||||
"
|
||||
/>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
@click="editingId = editingId === view.config.id ? '' : view.config.id"
|
||||
>
|
||||
{{ editingId === view.config.id ? '收起' : '编辑' }}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<p v-if="view.issue" class="mt-1.5 flex items-center gap-1.5 text-[12px] text-amber-700 dark:text-amber-300">
|
||||
<CircleAlert class="size-3.5 shrink-0" />
|
||||
{{ view.issue }}
|
||||
</p>
|
||||
|
||||
<div v-if="editingId === view.config.id" class="mt-3">
|
||||
<EngineEditor :view="view" @deleted="editingId = ''" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Separator />
|
||||
|
||||
<div class="space-y-2">
|
||||
<Label class="text-[12px]">新增引擎</Label>
|
||||
<div class="flex gap-2">
|
||||
<Select v-model="presetKey">
|
||||
<SelectTrigger class="h-8 w-44 text-[12px]"><SelectValue /></SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem v-for="p in ENGINE_PRESETS" :key="p.key" :value="p.key">
|
||||
{{ p.label }}
|
||||
</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<Input
|
||||
v-model="newEngineName"
|
||||
class="h-8 flex-1 text-[13px]"
|
||||
:placeholder="selectedPreset?.label ?? '引擎名称'"
|
||||
/>
|
||||
<Button size="sm" @click="addEngine">
|
||||
<Plus />
|
||||
新增
|
||||
</Button>
|
||||
</div>
|
||||
<p v-if="selectedPreset" class="text-[11px] text-muted-foreground">
|
||||
{{ selectedPreset.description }}
|
||||
</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<!-- ===== 通用 ===== -->
|
||||
<Card>
|
||||
<CardHeader class="pb-3">
|
||||
<CardTitle class="text-[14px]">通用</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent class="space-y-4">
|
||||
<div class="flex items-center gap-3">
|
||||
<Label class="w-32 shrink-0 text-[12px]">默认目标语言</Label>
|
||||
<Select
|
||||
:model-value="store.settings?.defaultTarget"
|
||||
@update:model-value="v => patch({ defaultTarget: String(v) })"
|
||||
>
|
||||
<SelectTrigger class="h-8 w-40 text-[12px]"><SelectValue /></SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem v-for="l in targetLanguages" :key="l.code" :value="l.code">
|
||||
{{ l.label }}
|
||||
</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<div class="flex items-center gap-3">
|
||||
<Label class="w-32 shrink-0 text-[12px]">默认引擎</Label>
|
||||
<Select
|
||||
:model-value="store.settings?.defaultEngineId"
|
||||
@update:model-value="v => patch({ defaultEngineId: String(v) })"
|
||||
>
|
||||
<SelectTrigger class="h-8 w-52 text-[12px]"><SelectValue /></SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="auto">自动(按优先级降级)</SelectItem>
|
||||
<SelectItem
|
||||
v-for="e in store.engines"
|
||||
:key="e.config.id"
|
||||
:value="e.config.id"
|
||||
>
|
||||
{{ e.config.name }}
|
||||
</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<div class="flex items-start gap-3">
|
||||
<Label class="w-32 shrink-0 pt-0.5 text-[12px]">失败自动降级</Label>
|
||||
<div>
|
||||
<Switch
|
||||
:model-value="store.settings?.autoFallback"
|
||||
@update:model-value="v => patch({ autoFallback: Boolean(v) })"
|
||||
/>
|
||||
<p class="mt-1 text-[11px] text-muted-foreground">
|
||||
开启后「自动」模式会在某个源失败时尝试下一个;关闭则只用默认引擎。
|
||||
<br />无论开关如何,手动指定某个引擎时都不会降级——否则「指定了 A 却拿到 B 的译文」更难排查。
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex items-start gap-3">
|
||||
<Label class="w-32 shrink-0 pt-0.5 text-[12px]">走代理模块</Label>
|
||||
<div>
|
||||
<Switch
|
||||
:model-value="store.settings?.useProxy"
|
||||
@update:model-value="v => patch({ useProxy: Boolean(v) })"
|
||||
/>
|
||||
<p class="mt-1 text-[11px] text-muted-foreground">
|
||||
默认关闭。自建 LibreTranslate 在境内、MyMemory 与 DeepSeek 均可直连;
|
||||
仅当翻译服务部署在境外或直连被拦截时打开。
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<!-- ===== 历史 ===== -->
|
||||
<Card v-if="store.settings">
|
||||
<CardHeader class="pb-3">
|
||||
<CardTitle class="text-[14px]">历史记录</CardTitle>
|
||||
<p class="text-[12px] text-muted-foreground">
|
||||
搜索走 SQLite FTS5 三元组索引;不足 3 个字符的关键词无法命中该索引,会退回全表扫描
|
||||
——仍然搜得到,只是更慢。
|
||||
</p>
|
||||
</CardHeader>
|
||||
<CardContent class="space-y-4">
|
||||
<div class="flex items-start gap-3">
|
||||
<Label class="w-32 shrink-0 pt-0.5 text-[12px]">记录历史</Label>
|
||||
<div>
|
||||
<Switch
|
||||
:model-value="store.settings.history.enabled"
|
||||
@update:model-value="v => patchHistory({ enabled: Boolean(v) })"
|
||||
/>
|
||||
<p class="mt-1 text-[11px] text-muted-foreground">
|
||||
关闭后不再写入新记录,已有记录不受影响。
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex items-start gap-3">
|
||||
<Label class="w-32 shrink-0 pt-1.5 text-[12px]">保留条数</Label>
|
||||
<div>
|
||||
<Input
|
||||
v-model.number="maxItemsDraft"
|
||||
type="number"
|
||||
:min="HISTORY_MAX_ITEMS_MIN"
|
||||
:max="HISTORY_MAX_ITEMS_MAX"
|
||||
step="100"
|
||||
class="h-8 w-32 text-[12px]"
|
||||
@blur="commitMaxItems"
|
||||
@keydown.enter="commitMaxItems"
|
||||
/>
|
||||
<p class="mt-1 text-[11px] text-muted-foreground">
|
||||
超出后按时间淘汰最旧的非收藏记录({{ HISTORY_MAX_ITEMS_MIN }}–{{ HISTORY_MAX_ITEMS_MAX }})。
|
||||
收藏条目不占这个额度,收藏得足够多时总占用会超过上限。
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<!-- ===== 提示词模板 ===== -->
|
||||
<Card v-if="templates">
|
||||
<CardHeader class="pb-3">
|
||||
<CardTitle class="text-[14px]">提示词模板</CardTitle>
|
||||
<p class="text-[12px] text-muted-foreground">
|
||||
<code class="rounded bg-muted px-1">{'{target}'}</code> 会替换为目标语言的自然语言名称,
|
||||
<code class="rounded bg-muted px-1">{'{source}'}</code> 为源语言名称。
|
||||
</p>
|
||||
</CardHeader>
|
||||
<CardContent class="space-y-3">
|
||||
<div class="space-y-1.5">
|
||||
<Label class="text-[12px]">翻译(默认模式)</Label>
|
||||
<Textarea v-model="templates.translate" class="min-h-24 text-[12px]" />
|
||||
<p v-if="templateWarning(templates.translate)" class="text-[11px] text-amber-700 dark:text-amber-300">
|
||||
{{ templateWarning(templates.translate) }}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<details class="rounded-md border p-2.5">
|
||||
<summary class="cursor-pointer select-none text-[12px] font-medium">
|
||||
备用模板:润色 / 解释 / 总结(计划 P3 接入划词弹窗)
|
||||
</summary>
|
||||
<div class="mt-2 space-y-3">
|
||||
<div class="space-y-1.5">
|
||||
<Label class="text-[12px]">润色</Label>
|
||||
<Textarea v-model="templates.polish" class="min-h-16 text-[12px]" />
|
||||
</div>
|
||||
<div class="space-y-1.5">
|
||||
<Label class="text-[12px]">解释</Label>
|
||||
<Textarea v-model="templates.explain" class="min-h-16 text-[12px]" />
|
||||
</div>
|
||||
<div class="space-y-1.5">
|
||||
<Label class="text-[12px]">总结</Label>
|
||||
<Textarea v-model="templates.summarize" class="min-h-16 text-[12px]" />
|
||||
</div>
|
||||
</div>
|
||||
</details>
|
||||
|
||||
<Button size="sm" :disabled="!templatesDirty || savingTemplates" @click="saveTemplates">
|
||||
<LoaderCircle v-if="savingTemplates" class="animate-spin" />
|
||||
<Save v-else />
|
||||
保存提示词
|
||||
</Button>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<!-- ===== 翻译面板与划词取词 ===== -->
|
||||
<Card v-if="store.settings">
|
||||
<CardHeader class="pb-3">
|
||||
<CardTitle class="text-[14px]">翻译面板</CardTitle>
|
||||
<p class="text-[12px] text-muted-foreground">
|
||||
按全局快捷键打开翻译面板:自动尝试读取<span class="text-foreground">当前划词</span>与
|
||||
<span class="text-foreground">剪贴板首条</span>作为候选,↑↓ 选择、Enter 直接翻译;
|
||||
也可以在原文框里手动输入(Enter 翻译,Alt+Enter 换行)。
|
||||
</p>
|
||||
</CardHeader>
|
||||
<CardContent class="space-y-4">
|
||||
<div class="flex items-center gap-3">
|
||||
<Label class="w-32 shrink-0 text-[12px]">面板快捷键</Label>
|
||||
<Input
|
||||
v-model="shortcutDraft.panelShortcut"
|
||||
class="h-8 w-40 text-[13px]"
|
||||
placeholder="Ctrl+2"
|
||||
/>
|
||||
<span class="text-[11px] text-muted-foreground">全局生效;留空禁用</span>
|
||||
</div>
|
||||
|
||||
<div class="flex flex-wrap items-center gap-2 pl-[8.75rem]">
|
||||
<Button size="sm" :disabled="!shortcutsDirty || applyingShortcuts" @click="applyShortcuts">
|
||||
<LoaderCircle v-if="applyingShortcuts" class="animate-spin" />
|
||||
<Save v-else />
|
||||
应用快捷键
|
||||
</Button>
|
||||
<Button variant="outline" size="sm" @click="previewPopup">
|
||||
<Sparkles />
|
||||
预览面板
|
||||
</Button>
|
||||
<span class="text-[11px] text-muted-foreground">
|
||||
预览用固定样例文本走完整链路,便于确认窗口与翻译都正常
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<Separator />
|
||||
|
||||
<div class="flex items-start gap-3">
|
||||
<Label class="w-32 shrink-0 pt-0.5 text-[12px]">读取当前划词</Label>
|
||||
<div>
|
||||
<Switch
|
||||
:model-value="store.settings.selection.enabled"
|
||||
@update:model-value="v => patchSelection({ enabled: Boolean(v) })"
|
||||
/>
|
||||
<p class="mt-1 text-[11px] text-muted-foreground">
|
||||
打开面板时尝试读取当前选中的文字作为第一条候选;关闭后仅提供剪贴板候选。
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex items-start gap-3">
|
||||
<Label class="w-32 shrink-0 pt-0.5 text-[12px]">取词方式</Label>
|
||||
<div class="space-y-1">
|
||||
<Select
|
||||
:model-value="store.settings.selection.mode || 'smart'"
|
||||
@update:model-value="v => patchSelection({ mode: String(v) })"
|
||||
>
|
||||
<SelectTrigger class="h-8 w-56 text-[12px]"><SelectValue /></SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="smart">智能(UIA 直读优先,失败再模拟复制)</SelectItem>
|
||||
<SelectItem value="compat">兼容(只用模拟 Ctrl+C)</SelectItem>
|
||||
<SelectItem value="clipboard">不取词(仅剪贴板候选)</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<p class="max-w-xl text-[11px] text-muted-foreground">
|
||||
「智能」直接从目标程序的无障碍接口读选区,<span class="text-foreground">不模拟按键、不占用剪贴板</span>,
|
||||
因此不受「目标窗口提权」影响;读不到时自动退回兼容方式。
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex items-start gap-3">
|
||||
<Label class="w-32 shrink-0 pt-0.5 text-[12px]">取词后还原剪贴板</Label>
|
||||
<div>
|
||||
<Switch
|
||||
:model-value="store.settings.selection.restoreClipboard"
|
||||
@update:model-value="v => patchSelection({ restoreClipboard: Boolean(v) })"
|
||||
/>
|
||||
<p class="mt-1 max-w-xl text-[11px] text-muted-foreground">
|
||||
取词会临时占用剪贴板,还原可保留你原来的内容。注意:只有文本 / 图片 / 文件三种格式
|
||||
能被备份还原;若原内容是不支持的格式(例如只含 HTML/RTF),选区文本会留在剪贴板上。
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex items-center gap-3">
|
||||
<Label class="w-32 shrink-0 text-[12px]">取词字数上限</Label>
|
||||
<Input
|
||||
:model-value="store.settings.selection.maxChars"
|
||||
type="number"
|
||||
class="h-8 w-24 text-[13px]"
|
||||
@update:model-value="
|
||||
v => patchSelection({ maxChars: Math.max(1, Number(v) || 2000) })
|
||||
"
|
||||
/>
|
||||
<span class="text-[11px] text-muted-foreground">
|
||||
超出直接拒绝并提示,避免误选整篇文档时发一个又慢又费钱的请求
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div class="space-y-1.5">
|
||||
<Label class="text-[12px]">跳过取词的应用(每行一个进程名)</Label>
|
||||
<Textarea v-model="blacklistDraft" class="min-h-20 text-[12px]" spellcheck="false" />
|
||||
<p class="text-[11px] text-muted-foreground">
|
||||
这些应用里 Ctrl+C 是中断信号,取词时自动跳过。
|
||||
</p>
|
||||
<Button size="sm" :disabled="!blacklistDirty" @click="saveBlacklist">保存名单</Button>
|
||||
</div>
|
||||
|
||||
<p class="rounded-md border bg-muted/30 p-2.5 text-[11px] leading-relaxed text-muted-foreground">
|
||||
取不到划词的常见原因:当前没有选中任何文字、目标窗口以管理员权限运行
|
||||
(兼容方式下系统会丢弃来自普通权限程序的模拟按键)、终端类应用(已默认跳过)、
|
||||
该程序没有暴露选区给无障碍接口(智能方式下会退回兼容方式)。<br />
|
||||
兜底路径:任何程序里都可以「选中 → 复制 → 打开翻译面板」,剪贴板首条会作为候选出现。
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<!-- ===== 截图翻译 ===== -->
|
||||
<Card v-if="store.settings">
|
||||
<CardHeader class="pb-3">
|
||||
<CardTitle class="flex items-center gap-2 text-[14px]">
|
||||
<ScanText class="size-4" />
|
||||
截图翻译
|
||||
</CardTitle>
|
||||
<p class="text-[12px] text-muted-foreground">
|
||||
在截图覆盖层框选区域后点「翻译选区」,识别结果以非激活悬浮窗展示在选区旁。
|
||||
</p>
|
||||
</CardHeader>
|
||||
<CardContent class="space-y-4">
|
||||
<div class="flex items-center gap-3">
|
||||
<Label class="w-32 shrink-0 text-[12px]">识别方式</Label>
|
||||
<Select
|
||||
:model-value="store.settings.screenshot.ocrMode"
|
||||
@update:model-value="
|
||||
v =>
|
||||
patch({
|
||||
screenshot: { ...store.settings!.screenshot, ocrMode: String(v) }
|
||||
})
|
||||
"
|
||||
>
|
||||
<SelectTrigger class="h-8 w-56 text-[12px]"><SelectValue /></SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="windows">本地 OCR(离线,零成本)</SelectItem>
|
||||
<SelectItem value="vision">视觉模型直译(质量更高,需图像模型)</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<p
|
||||
v-if="store.settings.screenshot.ocrMode === 'vision'"
|
||||
class="rounded-md border bg-muted/30 p-2.5 text-[11px] leading-relaxed text-muted-foreground"
|
||||
>
|
||||
视觉直译会把截图上传给所选引擎:请在引擎设置中勾选「支持图像输入」并确认该模型支持图像。
|
||||
识别与翻译一步完成,对表格、菜单等复杂排版效果更好。
|
||||
</p>
|
||||
|
||||
<template v-else>
|
||||
<div class="flex items-center gap-3">
|
||||
<Label class="w-32 shrink-0 text-[12px]">识别语言</Label>
|
||||
<Input
|
||||
:model-value="store.settings.screenshot.ocrLang"
|
||||
class="h-8 w-40 text-[13px]"
|
||||
placeholder="auto"
|
||||
@update:model-value="
|
||||
v =>
|
||||
patch({
|
||||
screenshot: {
|
||||
...store.settings!.screenshot,
|
||||
ocrLang: String(v) || 'auto'
|
||||
}
|
||||
})
|
||||
"
|
||||
/>
|
||||
<Button variant="outline" size="sm" :disabled="store.ocrLanguagesLoading" @click="store.loadOcrLanguages()">
|
||||
<LoaderCircle v-if="store.ocrLanguagesLoading" class="animate-spin" />
|
||||
{{ store.ocrLanguagesLoading ? '读取中…' : '可用语言' }}
|
||||
</Button>
|
||||
</div>
|
||||
<p class="pl-[8.75rem] text-[11px] text-muted-foreground">
|
||||
auto 跟随系统语言配置;也可填 BCP-47 标签(如 en-US、ja)。
|
||||
</p>
|
||||
<p
|
||||
v-if="store.ocrLanguagesError"
|
||||
class="rounded-md border border-destructive/40 bg-destructive/5 p-2.5 text-[11px] leading-relaxed text-destructive"
|
||||
>
|
||||
{{ store.ocrLanguagesError }}
|
||||
</p>
|
||||
<p
|
||||
v-else-if="store.ocrLanguages"
|
||||
class="rounded-md border bg-muted/30 p-2.5 text-[11px] leading-relaxed text-muted-foreground"
|
||||
>
|
||||
<span class="text-foreground">系统已装 {{ store.ocrLanguages.length }} 个 OCR 语言包:</span>
|
||||
{{ store.ocrLanguages.join('、') || '(无)' }}
|
||||
<br />缺语言时,在系统「设置 → 时间和语言 → 语言和区域」添加并勾选「文本识别」。
|
||||
</p>
|
||||
</template>
|
||||
|
||||
<div class="flex items-start gap-3">
|
||||
<Label class="w-32 shrink-0 pt-0.5 text-[12px]">自动翻译</Label>
|
||||
<div>
|
||||
<Switch
|
||||
:model-value="store.settings.screenshot.autoTranslate"
|
||||
@update:model-value="
|
||||
v =>
|
||||
patch({
|
||||
screenshot: {
|
||||
...store.settings!.screenshot,
|
||||
autoTranslate: Boolean(v)
|
||||
}
|
||||
})
|
||||
"
|
||||
/>
|
||||
<p class="mt-1 max-w-xl text-[11px] text-muted-foreground">
|
||||
关闭后框选只做识别,译文需在悬浮窗手动触发。
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,467 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, onMounted, onUnmounted, ref } from 'vue'
|
||||
import { toast } from 'vue-sonner'
|
||||
import {
|
||||
ArrowLeftRight,
|
||||
CircleAlert,
|
||||
Columns2,
|
||||
Copy,
|
||||
LoaderCircle,
|
||||
Sparkles,
|
||||
Square
|
||||
} from '@lucide/vue'
|
||||
import { useTranslateStore } from '@/stores/translateStore'
|
||||
import { labelOf, orderedLanguages, promptNameOf, resolveTargetLabel } from '@/lib/translate/languages'
|
||||
import { ERROR_HINTS } from '@/types/translate'
|
||||
import { copyToClipboard, StreamSession } from '@/lib/translate/api'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { ScrollArea } from '@/components/ui/scroll-area'
|
||||
import { Separator } from '@/components/ui/separator'
|
||||
import { Textarea } from '@/components/ui/textarea'
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue
|
||||
} from '@/components/ui/select'
|
||||
|
||||
const store = useTranslateStore()
|
||||
|
||||
/** 源语言可含「自动检测」,目标语言不能 */
|
||||
const sourceLanguages = computed(() => orderedLanguages(true))
|
||||
const targetLanguages = computed(() => orderedLanguages(false))
|
||||
|
||||
/** 无可用引擎时的引导(比让用户点下去才报错要好) */
|
||||
const showEngineWarning = computed(
|
||||
() => !store.loading && store.engines.length > 0 && store.usableEngines.length === 0
|
||||
)
|
||||
|
||||
/** 对比面板:与右侧单引擎结果并存(左列 = 输入 + 对比,右列 = 当前引擎译文) */
|
||||
const showCompare = ref(false)
|
||||
const comparing = computed(() => store.comparing)
|
||||
|
||||
function toggleCompare() {
|
||||
if (showCompare.value) {
|
||||
showCompare.value = false
|
||||
return
|
||||
}
|
||||
showCompare.value = true
|
||||
void store.compare()
|
||||
}
|
||||
|
||||
const errorHint = computed(() =>
|
||||
store.lastError ? ERROR_HINTS[store.lastError.kind] : ''
|
||||
)
|
||||
|
||||
/** 回车翻译:单行输入是主用法(与取词弹窗一致);Alt+Enter / Shift+Enter 换行 */
|
||||
function onKeydown(e: KeyboardEvent) {
|
||||
if (e.key !== 'Enter') return
|
||||
if (e.altKey) {
|
||||
// Alt+Enter:在光标处插入换行(textarea 默认行为不含 Alt 变体)
|
||||
e.preventDefault()
|
||||
const el = e.target as HTMLTextAreaElement
|
||||
const start = el.selectionStart ?? store.sourceText.length
|
||||
const end = el.selectionEnd ?? start
|
||||
store.sourceText = store.sourceText.slice(0, start) + '\n' + store.sourceText.slice(end)
|
||||
void nextTick(() => {
|
||||
el.selectionStart = el.selectionEnd = start + 1
|
||||
})
|
||||
return
|
||||
}
|
||||
// Shift+Enter:textarea 默认行为即换行,直接放行
|
||||
if (e.shiftKey) return
|
||||
e.preventDefault()
|
||||
if (streaming.value) stopStream()
|
||||
else runStreamed()
|
||||
}
|
||||
|
||||
// ===== 流式输出 =====
|
||||
// 主面板的翻译动作在组件内走 StreamSession:流式文本只属于当前视图,
|
||||
// Done 时回写 store.result(供复制与引擎信息展示),历史仍由后端统一记录。
|
||||
const streaming = ref(false)
|
||||
const streamText = ref('')
|
||||
let session: StreamSession | null = null
|
||||
|
||||
function runStreamed() {
|
||||
const text = store.sourceText.trim()
|
||||
if (!text || streaming.value) return
|
||||
store.normalizeDirection()
|
||||
streaming.value = true
|
||||
streamText.value = ''
|
||||
store.result = null
|
||||
store.lastError = null
|
||||
void session?.start({
|
||||
text,
|
||||
from: store.fromLang,
|
||||
to: store.toLang,
|
||||
toLabel: resolveTargetLabel(store.toLang),
|
||||
fromLabel: promptNameOf(store.fromLang),
|
||||
engineId: store.engineId,
|
||||
mode: 'translate',
|
||||
via: 'manual'
|
||||
})
|
||||
}
|
||||
|
||||
function stopStream() {
|
||||
session?.stop()
|
||||
streaming.value = false
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
const created = new StreamSession({
|
||||
onChunk: delta => {
|
||||
streamText.value += delta
|
||||
},
|
||||
onDone: r => {
|
||||
store.result = r
|
||||
streamText.value = ''
|
||||
streaming.value = false
|
||||
},
|
||||
onError: e => {
|
||||
store.lastError = e
|
||||
streamText.value = ''
|
||||
streaming.value = false
|
||||
}
|
||||
})
|
||||
session = created
|
||||
// 监听必须先于任何请求注册:注册晚于 start 会整批丢掉事件,
|
||||
// 表现为「历史里有译文、界面上一片空白」。
|
||||
await created.init()
|
||||
})
|
||||
|
||||
onUnmounted(() => {
|
||||
session?.dispose()
|
||||
session = null
|
||||
})
|
||||
|
||||
async function copyResult() {
|
||||
const ok = await store.copyResult()
|
||||
if (ok) toast.success('译文已复制')
|
||||
else toast.error('复制失败')
|
||||
}
|
||||
|
||||
async function copyText(text: string) {
|
||||
try {
|
||||
await copyToClipboard(text)
|
||||
toast.success('已复制')
|
||||
} catch (e) {
|
||||
toast.error(String(e))
|
||||
}
|
||||
}
|
||||
|
||||
// ===== 双栏滚动同步(与取词弹窗同一套比例映射) =====
|
||||
const sourceWrapRef = ref<HTMLElement | null>(null)
|
||||
const targetCardRef = ref<HTMLElement | null>(null)
|
||||
/** 抑制标志:程序化设置 scrollTop 会再次触发 scroll 事件,不同步回自己 */
|
||||
let syncingScroll = false
|
||||
|
||||
function sourceTextarea(): HTMLTextAreaElement | null {
|
||||
return sourceWrapRef.value?.querySelector('textarea') ?? null
|
||||
}
|
||||
|
||||
/** 译文卡的 ScrollArea 视口(真正的滚动容器) */
|
||||
function targetViewport(): HTMLElement | null {
|
||||
return (
|
||||
targetCardRef.value?.querySelector('[data-slot="scroll-area-viewport"]') as HTMLElement
|
||||
) ?? null
|
||||
}
|
||||
|
||||
/** 行高:两侧字号/行距一致(同 leading-relaxed),行高相同才谈得上整行对齐 */
|
||||
function lineHeightOf(el: HTMLElement): number {
|
||||
const v = parseFloat(getComputedStyle(el).lineHeight)
|
||||
return Number.isFinite(v) && v > 0 ? v : 20
|
||||
}
|
||||
|
||||
/**
|
||||
* 行级对齐的滚动同步:把源侧滚动位置换算成「整行行数」,按两侧总行数比例映射,
|
||||
* 再落到目标侧整行边界(顶部不切半行)。两侧换行一致时即逐行精确对齐;
|
||||
* 不一致时按行数比例,比纯像素比例更贴合译文对齐习惯。
|
||||
*
|
||||
* 抑制窗口用 rAF 而非定时器:程序化赋值引发的回声 scroll 事件在 rAF 前送达、
|
||||
* 一帧内即解除抑制——原先 80ms 定时器会把紧随其后的用户滚动也吞掉,产生抽搐感。
|
||||
*/
|
||||
function syncScroll(from: HTMLElement, to: HTMLElement) {
|
||||
if (syncingScroll) return
|
||||
const fromMax = from.scrollHeight - from.clientHeight
|
||||
const toMax = to.scrollHeight - to.clientHeight
|
||||
if (toMax <= 0) return
|
||||
const lineH = lineHeightOf(from)
|
||||
const fromLines = Math.max(1, Math.round(fromMax / lineH))
|
||||
const toLines = Math.max(1, Math.round(toMax / lineH))
|
||||
const scrolled = fromMax > 0 ? Math.round(from.scrollTop / lineH) : 0
|
||||
const target = Math.min(toMax, Math.round((scrolled / fromLines) * toLines) * lineH)
|
||||
if (Math.abs(to.scrollTop - target) < 1) return
|
||||
syncingScroll = true
|
||||
to.scrollTop = target
|
||||
window.requestAnimationFrame(() => {
|
||||
syncingScroll = false
|
||||
})
|
||||
}
|
||||
|
||||
function onSourceScroll(e: Event) {
|
||||
const to = targetViewport()
|
||||
if (to) syncScroll(e.target as HTMLElement, to)
|
||||
}
|
||||
|
||||
/** 只响应译文视口本身的滚动:嵌套滚动区(错误详情 pre 等)滚动不参与同步 */
|
||||
function onTargetScroll(e: Event) {
|
||||
const ta = sourceTextarea()
|
||||
if (!ta) return
|
||||
if (e.target !== targetViewport()) return
|
||||
syncScroll(e.target as HTMLElement, ta)
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex h-full min-h-0 flex-col">
|
||||
<div class="flex shrink-0 flex-wrap items-center gap-2 pb-3">
|
||||
<Select v-model="store.fromLang">
|
||||
<SelectTrigger class="h-8 w-32 text-[12px]"><SelectValue /></SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem v-for="l in sourceLanguages" :key="l.code" :value="l.code">
|
||||
{{ l.label }}
|
||||
</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
:disabled="store.fromLang === 'auto'"
|
||||
:title="store.fromLang === 'auto' ? '自动检测时无法互换' : '互换源与目标语言'"
|
||||
@click="store.swapLanguages()"
|
||||
>
|
||||
<ArrowLeftRight />
|
||||
</Button>
|
||||
|
||||
<Select v-model="store.toLang">
|
||||
<SelectTrigger class="h-8 w-32 text-[12px]"><SelectValue /></SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem v-for="l in targetLanguages" :key="l.code" :value="l.code">
|
||||
{{ l.label }}
|
||||
</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
|
||||
<Separator orientation="vertical" class="mx-1 h-5" />
|
||||
|
||||
<Select v-model="store.engineId">
|
||||
<SelectTrigger class="h-8 w-44 text-[12px]"><SelectValue /></SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="auto">自动(按优先级降级)</SelectItem>
|
||||
<SelectItem v-for="e in store.engines" :key="e.config.id" :value="e.config.id">
|
||||
{{ e.config.name }}{{ e.ready ? '' : '(未就绪)' }}
|
||||
</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
|
||||
<div class="flex-1" />
|
||||
|
||||
<span class="text-[12px] text-muted-foreground tabular-nums">
|
||||
{{ store.sourceText.length }} 字符
|
||||
</span>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
:disabled="!store.sourceText"
|
||||
@click="store.clear()"
|
||||
>
|
||||
清空
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
:disabled="!store.sourceText || comparing"
|
||||
:title="`把这句并发发给 ${store.usableEngines.length} 个就绪引擎`"
|
||||
@click="toggleCompare()"
|
||||
>
|
||||
<Columns2 v-if="!comparing" />
|
||||
<LoaderCircle v-else class="animate-spin" />
|
||||
对比
|
||||
</Button>
|
||||
<Button
|
||||
v-if="streaming"
|
||||
variant="destructive"
|
||||
size="sm"
|
||||
@click="stopStream()"
|
||||
>
|
||||
<Square />
|
||||
停止
|
||||
</Button>
|
||||
<Button v-else size="sm" :disabled="!store.canRun" @click="runStreamed()">
|
||||
<Sparkles />
|
||||
翻译
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
<div v-if="showEngineWarning" class="mb-3 shrink-0 rounded-lg border border-amber-300/60 bg-amber-50 px-3 py-2 text-[12px] text-amber-900 dark:bg-amber-950/30 dark:text-amber-200">
|
||||
<div class="flex items-start gap-2">
|
||||
<CircleAlert class="mt-0.5 size-3.5 shrink-0" />
|
||||
<span>
|
||||
还没有可用的翻译引擎。请到「设置」页填写引擎的 API Key,或新增一个引擎实例。
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="grid min-h-[26rem] flex-1 grid-cols-2 gap-3">
|
||||
<div class="flex h-full min-h-0 flex-col gap-3">
|
||||
<div ref="sourceWrapRef" class="flex min-h-0 flex-1">
|
||||
<Textarea
|
||||
v-model="store.sourceText"
|
||||
class="h-full w-full resize-none leading-relaxed [scrollbar-width:none] [&::-webkit-scrollbar]:hidden"
|
||||
placeholder="输入或粘贴要翻译的内容… Enter 翻译 · Alt+Enter / Shift+Enter 换行"
|
||||
@keydown="onKeydown"
|
||||
@scroll="onSourceScroll"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<!-- 多引擎并排对比 -->
|
||||
<div
|
||||
v-if="showCompare"
|
||||
class="min-h-0 flex-[1.2] overflow-hidden rounded-lg border bg-card"
|
||||
>
|
||||
<div class="flex items-center gap-2 border-b px-3 py-2">
|
||||
<span class="text-[12px] font-medium">多引擎对比</span>
|
||||
<span class="text-[11px] text-muted-foreground">
|
||||
{{ comparing ? '请求中…' : `${store.compareResults.length} 个引擎` }}
|
||||
</span>
|
||||
<div class="flex-1" />
|
||||
<button
|
||||
class="rounded p-1 text-[13px] leading-none text-muted-foreground hover:bg-accent"
|
||||
title="收起"
|
||||
@click="showCompare = false"
|
||||
>
|
||||
×
|
||||
</button>
|
||||
</div>
|
||||
<div class="h-[calc(100%-2.4rem)] overflow-y-auto p-2">
|
||||
<p
|
||||
v-if="store.compareResults.length === 0"
|
||||
class="px-1 py-2 text-[12px] text-muted-foreground"
|
||||
>
|
||||
{{ comparing ? '正在向各引擎并发请求…' : '点击「对比」开始。' }}
|
||||
</p>
|
||||
<div v-else class="space-y-2">
|
||||
<div
|
||||
v-for="entry in store.compareResults"
|
||||
:key="entry.engineId"
|
||||
class="rounded-md border px-2.5 py-2"
|
||||
>
|
||||
<div class="flex items-center gap-2">
|
||||
<span class="text-[12px] font-medium">{{ entry.engineName }}</span>
|
||||
<span v-if="entry.latencyMs" class="text-[11px] text-muted-foreground tabular-nums">
|
||||
{{ entry.latencyMs }}ms
|
||||
</span>
|
||||
<div class="flex-1" />
|
||||
<button
|
||||
v-if="entry.text"
|
||||
class="rounded p-1 text-muted-foreground hover:bg-accent"
|
||||
title="复制该译文"
|
||||
@click="copyText(entry.text)"
|
||||
>
|
||||
<Copy class="size-3" />
|
||||
</button>
|
||||
</div>
|
||||
<p v-if="entry.text" class="mt-1 select-text cursor-text whitespace-pre-wrap break-words text-[12px] leading-relaxed">
|
||||
{{ entry.text }}
|
||||
</p>
|
||||
<p v-else-if="entry.error" class="mt-1 break-words text-[11px] text-destructive">
|
||||
{{ entry.error.message }}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 右:译文(无标题栏;引擎信息与复制按钮在底部,与取词弹窗一致) -->
|
||||
<div
|
||||
ref="targetCardRef"
|
||||
class="flex h-full min-h-0 flex-col overflow-hidden rounded-lg border bg-muted/20"
|
||||
@scroll.capture="onTargetScroll"
|
||||
>
|
||||
<ScrollArea class="min-h-0 flex-1">
|
||||
<div class="px-3 py-2">
|
||||
<!-- 流式进行中:边到边显示,光标提示仍在输出 -->
|
||||
<div
|
||||
v-if="streaming"
|
||||
class="select-text cursor-text whitespace-pre-wrap break-words text-[13px] leading-relaxed"
|
||||
>{{ streamText }}<span class="animate-pulse">▍</span></div>
|
||||
|
||||
<div
|
||||
v-else-if="streamText && !store.result"
|
||||
class="select-text cursor-text whitespace-pre-wrap break-words text-[13px] text-muted-foreground leading-relaxed"
|
||||
>
|
||||
{{ streamText }}
|
||||
</div>
|
||||
|
||||
<div v-else-if="store.lastError" class="space-y-2 py-1">
|
||||
<div class="flex items-center gap-2">
|
||||
<Badge variant="destructive" class="text-[11px]">
|
||||
{{ store.lastError.kind }}
|
||||
</Badge>
|
||||
<span class="text-[13px]">{{ store.lastError.message }}</span>
|
||||
</div>
|
||||
<p v-if="errorHint" class="text-[12px] text-muted-foreground">
|
||||
{{ errorHint }}
|
||||
</p>
|
||||
<details v-if="store.lastError.detail" class="text-[11px] text-muted-foreground">
|
||||
<summary class="cursor-pointer select-none">上游原始响应</summary>
|
||||
<pre class="mt-1 whitespace-pre-wrap break-all rounded bg-muted/50 p-2">{{ store.lastError.detail }}</pre>
|
||||
</details>
|
||||
</div>
|
||||
|
||||
<div
|
||||
v-else-if="store.result"
|
||||
class="select-text cursor-text whitespace-pre-wrap break-words text-[13px] leading-relaxed"
|
||||
>
|
||||
{{ store.result.text }}
|
||||
</div>
|
||||
|
||||
<p v-else class="py-1 text-[13px] text-muted-foreground">
|
||||
译文会显示在这里。
|
||||
</p>
|
||||
</div>
|
||||
</ScrollArea>
|
||||
|
||||
<!-- 底部:引擎信息 + 复制(与取词弹窗的底栏一致) -->
|
||||
<div
|
||||
v-if="store.result || streaming"
|
||||
class="flex shrink-0 items-center gap-2 border-t px-3 py-1.5"
|
||||
>
|
||||
<template v-if="store.result">
|
||||
<Badge variant="secondary" class="text-[11px]">{{ store.result.engineName }}</Badge>
|
||||
<span
|
||||
v-if="store.result.detected"
|
||||
class="text-[11px] text-muted-foreground"
|
||||
>
|
||||
检测:{{ labelOf(store.result.detected) }}
|
||||
</span>
|
||||
<span class="text-[11px] text-muted-foreground tabular-nums">
|
||||
{{ store.result.latencyMs }}ms
|
||||
</span>
|
||||
<span
|
||||
v-if="store.result.usage"
|
||||
class="text-[11px] text-muted-foreground tabular-nums"
|
||||
>
|
||||
{{ store.result.usage.totalTokens }} tokens
|
||||
</span>
|
||||
</template>
|
||||
<span v-else class="text-[11px] text-muted-foreground">流式输出中…</span>
|
||||
<div class="flex-1" />
|
||||
<Button
|
||||
v-if="store.result"
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
title="复制译文"
|
||||
@click="copyResult()"
|
||||
>
|
||||
<Copy />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,66 @@
|
||||
import type { ModuleConfig } from '@/types/module'
|
||||
import type { SearchIndexItem } from '@/stores/searchIndex'
|
||||
|
||||
const searchItems: SearchIndexItem[] = [
|
||||
{
|
||||
title: '翻译',
|
||||
description: '多源翻译与 AI 翻译工作台',
|
||||
keywords: ['翻译', '译', 'translate', 'translation', '中英', '互译', '英文'],
|
||||
tab: 'workbench'
|
||||
},
|
||||
{
|
||||
title: '翻译引擎设置',
|
||||
description: '配置 AI 引擎、Base URL、模型与 API Key',
|
||||
keywords: ['引擎', '模型', 'api key', '密钥', 'deepseek', 'openai', 'ollama', '中转'],
|
||||
tab: 'settings'
|
||||
},
|
||||
{
|
||||
title: '默认目标语言',
|
||||
description: '设置默认翻译到的语言',
|
||||
keywords: ['语言', '目标语言', 'target', '中文', '英文', '日语'],
|
||||
tab: 'settings'
|
||||
},
|
||||
{
|
||||
title: '自动降级',
|
||||
description: '某个引擎失败时自动尝试下一个引擎',
|
||||
keywords: ['降级', 'fallback', '容错', '备用源', '自动'],
|
||||
tab: 'settings'
|
||||
},
|
||||
{
|
||||
title: '划词翻译',
|
||||
description: '选中文字后按快捷键,非激活悬浮窗显示译文',
|
||||
keywords: ['划词', '取词', '选中', '快捷键', 'selection', '悬浮窗', '弹窗'],
|
||||
tab: 'settings'
|
||||
},
|
||||
{
|
||||
title: '翻译剪贴板',
|
||||
description: '复制文字后按快捷键翻译剪贴板内容(终端类应用也能用)',
|
||||
keywords: ['剪贴板翻译', '复制翻译', '快捷键', 'clipboard'],
|
||||
tab: 'settings'
|
||||
},
|
||||
{
|
||||
title: '截图翻译',
|
||||
description: '框选屏幕区域,本地 OCR 或视觉直译后展示译文',
|
||||
keywords: ['截图', 'ocr', '识别', '图片翻译', '屏幕翻译', '翻译选区'],
|
||||
tab: 'settings'
|
||||
},
|
||||
{
|
||||
title: '翻译历史',
|
||||
description: '查看、搜索、收藏与清理翻译记录',
|
||||
keywords: ['历史', '记录', '收藏', 'history', '搜索'],
|
||||
tab: 'history'
|
||||
}
|
||||
]
|
||||
|
||||
export const moduleConfig: ModuleConfig = {
|
||||
id: 'translate',
|
||||
name: '翻译',
|
||||
icon: 'translate',
|
||||
description: '多源翻译与 AI 翻译,含划词、截图翻译',
|
||||
category: 'tool',
|
||||
defaultEnabled: true,
|
||||
loader: () => import('./TranslateModule.vue'),
|
||||
searchItems,
|
||||
// 排在剪贴板(20)之后、截图(30)之前
|
||||
order: 25
|
||||
}
|
||||
Reference in new issue
Block a user