Files
it-tools-pro/src/tools/translator/translator.vue
T
personal82555 311ab1b139 fix(footer): 功能页页脚改为独立底栏,显示在功能区外且不产生滚动条
上一版遗留两问题:
1) 页脚压住内容:/json-prettify 底部工具行 828-877、页脚 869-888 -> 实际被压住
2) 滚动条:上一版用 padding-bottom:56px 留白,而撑满视口型工具高度按
   window.innerHeight-top-12 算(正好到888),888+56=944>900 -> 凭空多44px滚动条

改法(预留独立底栏,不用 padding):
- base.layout.vue 功能页滚动区 height:calc(100% - 44px)、padding-bottom:0 -> 滚动区缩到856
  页脚固定在其下方独立底栏(869-888),不在功能区之内
- 12个撑满视口工具(json-viewer/label-designer/ai-chat/translator/image-ocr/pdf-ocr/
  doc-convert/pdf-tools/image-tools/code-reader/site-bookmarks/ai-retouch/barcode-batch-generator)
  高度改为按滚动区底边计算,不再用 window.innerHeight,随底栏自动收缩

验证(20个功能页):fixed / 页脚在滚动区外(856<869) / 滚到底零遮挡(余13-421px) 全通过;
12个页面滚动条由有变无;仅4个内容本身超长页保留滚动条(/ai-chat,/emoji-picker,
/text-to-image,/encryption)且底部不被遮挡;视觉核验 /json-prettify 底部工具行完整可见
2026-10-15 11:18:54 +08:00

835 lines
21 KiB
Vue
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<script setup lang="ts">
import GenHistory from '@/tools/gen-history/GenHistory.vue';
import { useGenHistory } from '@/tools/gen-history/gen-history';
const genHist = useGenHistory('translator');
interface Lang {
label: string;
value: string;
}
const langs: Lang[] = [
{ label: '自动检测', value: 'auto' },
{ label: '中文(简体)', value: 'zh-CN' },
{ label: '中文(繁体)', value: 'zh-TW' },
{ label: '英语', value: 'en' },
{ label: '日语', value: 'ja' },
{ label: '韩语', value: 'ko' },
{ label: '法语', value: 'fr' },
{ label: '德语', value: 'de' },
{ label: '西班牙语', value: 'es' },
{ label: '俄语', value: 'ru' },
{ label: '葡萄牙语', value: 'pt' },
{ label: '意大利语', value: 'it' },
{ label: '阿拉伯语', value: 'ar' },
{ label: '越南语', value: 'vi' },
{ label: '泰语', value: 'th' },
{ label: '印尼语', value: 'id' },
];
import { getMachineId, licenseHeaders } from '../license/license';
const source = ref('Hello! This is a handy developer tools website with barcode generation, OCR and translation.\n欢迎使用在线翻译工具,支持中英日韩等16种语言互译。');
const from = ref('auto');
const to = ref('zh-CN');
const result = ref('');
const detected = ref('');
const loading = ref(false);
const error = ref('');
const langName = (v: string) => langs.find(l => l.value === v)?.label ?? v;
function swap() {
if (from.value === 'auto') {
return;
}
const t = from.value;
from.value = to.value;
to.value = t;
}
async function translateText(allowAutoSwitch = true) {
const text = source.value.trim();
if (!text) {
result.value = '';
detected.value = '';
error.value = '';
return;
}
loading.value = true;
error.value = '';
try {
const url = `/api/translate?client=gtx&sl=${encodeURIComponent(from.value)}&tl=${encodeURIComponent(to.value)}&dt=t&q=${encodeURIComponent(text)}`;
const res = await fetch(url, { headers: licenseHeaders('translator') });
if (!res.ok) {
throw new Error(`HTTP ${res.status}`);
}
const data = await res.json();
const segments: string[] = (data?.[0] ?? []).map((seg: any[]) => seg?.[0] ?? '').filter(Boolean);
if (!segments.length) {
throw new Error('empty translation');
}
result.value = segments.join('');
detected.value = typeof data?.[2] === 'string' ? data[2] : '';
genHist.add({ title: text.slice(0, 40), detail: result.value.slice(0, 80), dedupeTitle: true });
// source equals target: auto-switch target language and retry once
if (allowAutoSwitch && from.value === 'auto' && detected.value && detected.value === to.value) {
to.value = detected.value.startsWith('zh') ? 'en' : 'zh-CN';
await translateText(false);
return;
}
}
catch (e: any) {
// fallback: MyMemory
try {
const pair = `${from.value === 'auto' ? 'Autodetect' : from.value}|${to.value}`;
const res = await fetch(`/api/translate-mm?q=${encodeURIComponent(text)}&langpair=${encodeURIComponent(pair)}`, { headers: licenseHeaders('translator') });
const data = await res.json();
const translated = data?.responseData?.translatedText;
if (!translated || /MYMEMORY WARNING|INVALID/i.test(String(translated))) {
throw new Error(String(translated || 'fallback failed'));
}
result.value = String(translated);
detected.value = '';
genHist.add({ title: text.slice(0, 40), detail: result.value.slice(0, 80), dedupeTitle: true });
}
catch (e2: any) {
error.value = `翻译失败:${e2?.message ?? e2}`;
result.value = '';
}
}
finally {
loading.value = false;
}
}
async function copyResult() {
if (!result.value) {
return;
}
try {
await navigator.clipboard.writeText(result.value);
}
catch {
const ta = document.createElement('textarea');
ta.value = result.value;
document.body.appendChild(ta);
ta.select();
document.execCommand('copy');
ta.remove();
}
}
function clearAll() {
source.value = '';
result.value = '';
detected.value = '';
error.value = '';
}
// debounce auto translate
let timer: ReturnType<typeof setTimeout> | undefined;
watch([source, from, to], () => {
clearTimeout(timer);
timer = setTimeout(translateText, 600);
});
// fit viewport: no page scroll
// ============ 文档翻译 ============
const mode = ref<'text' | 'doc'>('text');
const docTo = ref('zh-CN');
const docLangOptions = langs.filter(l => l.value !== 'auto');
const docInput = ref<HTMLInputElement>();
// 批量文档翻译:一次最多 10 个文件,每个文件一个任务
const MAX_DOC_FILES = 10;
const docJobs = ref<any[]>([]); // {file, status: pending|loading|done|error, text, info, error, docxDone, open}
const docLoading = ref(false);
const docProgress = ref({ done: 0, total: 0 });
const pendingCount = computed(() => docJobs.value.filter((j: any) => j.status !== 'done').length);
function pickDoc() {
docInput.value?.click();
}
function onDocInput(e: Event) {
const input = e.target as HTMLInputElement;
const incoming = [...(input.files ?? [])];
input.value = '';
const room = MAX_DOC_FILES - docJobs.value.length;
if (room <= 0) {
return;
}
for (const f of incoming.slice(0, room)) {
docJobs.value.push({ file: f, status: 'pending', text: '', info: '', error: '', docxDone: false, open: false });
}
}
function removeDocFile(i: number) {
if (!docLoading.value) {
docJobs.value.splice(i, 1);
}
}
function clearDocFiles() {
if (!docLoading.value) {
docJobs.value = [];
}
}
async function translateOne(job: any) {
job.status = 'loading';
job.error = '';
try {
const fd = new FormData();
fd.append('file', job.file);
fd.append('to', langName(docTo.value));
// 单文件超时保护:超过 8 分钟视为失败
const ctrl = new AbortController();
const timer = setTimeout(() => ctrl.abort(), 8 * 60 * 1000);
let res: Response;
try {
res = await fetch('/relay/translate-doc', { method: 'POST', body: fd, headers: licenseHeaders('translator'), signal: ctrl.signal });
}
finally {
clearTimeout(timer);
}
const j = await res.json().catch(() => ({}));
if (!res.ok || j.code !== 200) {
throw new Error(j.message || `HTTP ${res.status}`);
}
job.text = j.data.text;
job.info = `${j.data.chars} 字 · ${j.data.blocks} 块 · 译文 ${j.data.text.length} 字`;
job.status = 'done';
genHist.add({ title: `文档翻译: ${job.file.name}`, detail: `${j.data.chars} 字 → ${langName(docTo.value)}` });
}
catch (e: any) {
job.status = 'error';
job.error = e?.name === 'AbortError' ? '翻译超时(超过 8 分钟),请拆分文件后重试' : String(e?.message || e);
}
}
// 批量翻译:低并发(2)逐个处理,实时更新进度与每文件状态
async function translateDoc() {
const targets = docJobs.value.filter((j: any) => j.status !== 'done');
if (!targets.length || docLoading.value) {
return;
}
docLoading.value = true;
docProgress.value = { done: 0, total: targets.length };
let idx = 0;
const worker = async () => {
while (idx < targets.length) {
const job = targets[idx++];
await translateOne(job);
docProgress.value.done++;
}
};
await Promise.all(Array.from({ length: Math.min(2, targets.length) }, worker));
docLoading.value = false;
}
function downloadDocTxt(job: any) {
const blob = new Blob([job.text], { type: 'text/plain;charset=utf-8' });
const a = document.createElement('a');
a.href = URL.createObjectURL(blob);
a.download = (job.file.name.replace(/\.[^.]+$/, '') || '译文') + '-译文.txt';
a.click();
URL.revokeObjectURL(a.href);
}
async function downloadDocDocx(job: any) {
if (!job.text) {
return;
}
try {
const res = await fetch('/relay/txt-to-docx', {
method: 'POST',
headers: { ...licenseHeaders('translator'), 'Content-Type': 'application/json' },
body: JSON.stringify({ machine: getMachineId(), text: job.text }),
});
if (!res.ok) {
const j = await res.json().catch(() => ({}));
throw new Error(j.message || `HTTP ${res.status}`);
}
const blob = await res.blob();
const a = document.createElement('a');
a.href = URL.createObjectURL(blob);
a.download = (job.file.name.replace(/\.[^.]+$/, '') || '译文') + '-译文.docx';
a.click();
URL.revokeObjectURL(a.href);
job.docxDone = true;
}
catch (e: any) {
job.error = String(e?.message || e);
}
}
function copyJob(job: any) {
navigator.clipboard?.writeText(job.text);
}
function jobIcon(s: string) {
return s === 'done' ? '✅' : s === 'error' ? '❌' : s === 'loading' ? '⏳' : '▫️';
}
const rootEl = ref<HTMLElement>();
const rootStyle = ref<Record<string, string>>({});
function fit() {
const el = rootEl.value;
if (!el) {
return;
}
const top = el.getBoundingClientRect().top;
// 高度按「内容滚动区底边」计算,而不是 window.innerHeight:
// 功能页底部预留了固定页脚的空间,用视口高度会把内容撑到页脚下方,既遮挡又产生滚动条
const scroller = el.closest('.n-layout-scroll-container');
const bottom = scroller
? scroller.getBoundingClientRect().bottom - Number.parseFloat(getComputedStyle(scroller).paddingBottom || '0')
: window.innerHeight - 12;
const height = Math.max(300, bottom - top);
rootStyle.value = { height: `${height}px`, flex: '1 1 100%' };
}
let observer: ResizeObserver | undefined;
onMounted(() => {
fit();
window.addEventListener('resize', fit);
observer = new ResizeObserver(() => fit());
if (rootEl.value) {
observer.observe(rootEl.value);
}
translateText();
});
onUnmounted(() => {
window.removeEventListener('resize', fit);
observer?.disconnect();
});
</script>
<template>
<div ref="rootEl" class="tr-root" :style="rootStyle">
<div class="toolbar">
<div class="stats">
<template v-if="detected && from === 'auto'">
检测到语言:{{ langName(detected) || detected }}
</template>
</div>
<c-button type="primary" :disabled="loading" @click="translateText">
翻译
</c-button>
<c-button :disabled="!result" @click="copyResult">
复制译文
</c-button>
<c-button @click="clearAll">
清空
</c-button>
</div>
<div class="mode-row">
<button class="mode-chip" :class="{ on: mode === 'text' }" @click="mode = 'text'">
💬 文本翻译
</button>
<button class="mode-chip" :class="{ on: mode === 'doc' }" @click="mode = 'doc'">
📄 文档翻译
<span class="mode-new">新</span>
</button>
<span class="mode-hint">{{ mode === 'doc' ? '上传 Word / PDF / TXT 等文档,AI 整篇翻译并保留段落格式,可下载译文' : '输入文本自动翻译' }}</span>
</div>
<!-- 文档翻译面板 -->
<div v-if="mode === 'doc'" class="doc-panel">
<input ref="docInput" type="file" hidden multiple accept=".txt,.md,.docx,.doc,.pdf,.html,.htm,.epub,.rtf,.odt" @change="onDocInput">
<div class="doc-top">
<div class="doc-drop" @click="pickDoc">
<template v-if="!docJobs.length">
📁 点击选择文档(可多选,最多 10 个)<br><span>Word / PDF / TXT / MD / HTML / EPUB · 每个 ≤20MB</span>
</template>
<template v-else>
📄 已选 {{ docJobs.length }} 个文件<span v-if="docJobs.length >= MAX_DOC_FILES" class="doc-size">(已达 10 个上限)</span>
<a href="javascript:;" class="doc-clear" @click.stop="clearDocFiles">✕ 清空</a>
</template>
</div>
<div class="doc-side">
<div class="doc-lang">
译为:
<select v-model="docTo" class="doc-lang-sel">
<option v-for="l in docLangOptions" :key="l.value" :value="l.value">{{ l.label }}</option>
</select>
</div>
<button class="doc-go" :disabled="docLoading || !pendingCount" @click="translateDoc()">
{{ docLoading ? `⏳ 翻译中 ${docProgress.done}/${docProgress.total}…` : (pendingCount ? `🚀 翻译 ${pendingCount} 个文档` : '🚀 翻译文档') }}
</button>
</div>
</div>
<!-- 批量文件列表 -->
<div v-if="docJobs.length" class="doc-jobs">
<div v-for="(job, i) in docJobs" :key="i" class="doc-job">
<div class="doc-job-head" @click="job.status === 'done' && (job.open = !job.open)">
<span class="doc-job-ico">{{ jobIcon(job.status) }}</span>
<span class="doc-job-name">{{ job.file.name }}</span>
<span class="doc-job-size">{{ (job.file.size / 1024 / 1024).toFixed(1) }}MB</span>
<span v-if="job.status === 'done'" class="doc-job-info">{{ job.info }}</span>
<span class="doc-job-acts">
<template v-if="job.status === 'done'">
<button class="doc-mini" @click.stop="downloadDocTxt(job)">⬇TXT</button>
<button class="doc-mini" :disabled="job.docxDone" @click.stop="downloadDocDocx(job)">⬇DOCX</button>
<button class="doc-mini" @click.stop="copyJob(job)">📋</button>
</template>
<button v-if="!docLoading" class="doc-mini doc-job-del" @click.stop="removeDocFile(i)" title="移除">✕</button>
</span>
</div>
<div v-if="job.error" class="doc-job-err">⚠️ {{ job.error }}</div>
<div v-if="job.status === 'done' && job.open" class="doc-out">
<pre class="doc-text">{{ job.text }}</pre>
</div>
</div>
</div>
<div v-else class="doc-empty">
支持整篇文档批量翻译(最多 10 个):AI 分块处理并保留原段落结构,逐个文件出译文,可下载 TXT 或 Word(DOCX)。
</div>
<n-spin v-if="docLoading" :show="docLoading" class="doc-spin" />
</div>
<div v-else class="body">
<div class="pane">
<div class="lang-row">
<c-select v-model:value="from" :options="langs.map(l => ({ ...l }))" w-140px />
<c-button size="small" @click="swap">
⇄ 交换
</c-button>
<c-select v-model:value="to" :options="langs.filter(l => l.value !== 'auto').map(l => ({ ...l }))" w-140px />
</div>
<n-input
v-model:value="source"
type="textarea"
:rows="10"
placeholder="输入要翻译的文本..."
:autosize="{ minRows: 6, maxRows: 16 }"
/>
<div class="hint">
共 {{ source.length }} 字符,修改后自动翻译
</div>
</div>
<div class="pane">
<div class="lang-row">
<span class="target-label">译文({{ langName(to) }})</span>
</div>
<n-spin :show="loading" class="output-wrap">
<div class="output" :class="{ hasError: error }">
<template v-if="error">
{{ error }}
</template>
<template v-else-if="result">
{{ result }}
</template>
<template v-else>
<span class="placeholder">译文将显示在这里</span>
</template>
</div>
</n-spin>
<div class="hint">
<template v-if="result">
共 {{ result.length }} 字符
</template>
</div>
</div>
</div>
<GenHistory tool="translator" position="bottom" label="翻译记录" />
</div>
</template>
<style lang="less" scoped>
.mode-row {
display: flex;
align-items: center;
gap: 8px;
padding-bottom: 12px;
flex-shrink: 0;
}
.mode-chip {
border: 1px solid rgba(128, 128, 128, 0.3);
background: #fff;
border-radius: 999px;
padding: 7px 16px;
font-size: 13px;
cursor: pointer;
transition: all 0.14s;
display: flex;
align-items: center;
gap: 6px;
&.on {
background: #18a058;
border-color: #18a058;
color: #fff;
font-weight: 700;
}
.mode-new {
font-size: 10px;
background: #e60012;
color: #fff;
border-radius: 4px;
padding: 0 5px;
}
}
.mode-hint {
font-size: 12px;
opacity: 0.55;
}
.doc-panel {
position: relative;
flex: 1;
min-height: 0;
display: flex;
flex-direction: column;
}
.doc-top {
display: flex;
gap: 14px;
align-items: stretch;
margin-bottom: 12px;
flex-shrink: 0;
.doc-side {
width: 300px;
flex-shrink: 0;
display: flex;
flex-direction: column;
gap: 9px;
.doc-lang {
font-size: 12.5px;
opacity: 0.85;
background: rgba(128, 128, 128, 0.06);
border-radius: 8px;
padding: 8px 12px;
display: flex;
align-items: center;
gap: 8px;
}
.doc-lang-sel {
flex: 1;
border: 1px solid rgba(128, 128, 128, 0.35);
border-radius: 7px;
padding: 5px 8px;
font-size: 12.5px;
background: #fff;
outline: none;
&:focus {
border-color: #18a058;
}
}
.doc-go {
border: none;
background: #18a058;
color: #fff;
border-radius: 9px;
padding: 11px;
font-size: 13.5px;
font-weight: 700;
cursor: pointer;
flex: 1;
&:disabled {
opacity: 0.5;
cursor: not-allowed;
}
&:hover:not(:disabled) {
background: #15924e;
}
}
}
}
.doc-drop {
flex: 1;
border: 1.5px dashed rgba(128, 128, 128, 0.45);
border-radius: 10px;
padding: 22px 14px;
text-align: center;
cursor: pointer;
font-size: 14px;
font-weight: 600;
line-height: 1.8;
transition: border-color 0.15s;
word-break: break-all;
&:hover {
border-color: #18a058;
}
span {
font-size: 11.5px;
font-weight: 400;
opacity: 0.5;
}
.doc-size {
opacity: 0.55;
font-weight: 400;
}
.doc-clear {
color: #d03050;
margin-left: 8px;
text-decoration: none;
}
}
.doc-error {
color: #d03050;
font-size: 12.5px;
margin-bottom: 10px;
}
.doc-bar {
display: flex;
justify-content: space-between;
align-items: center;
gap: 10px;
margin-bottom: 8px;
flex-wrap: wrap;
.doc-info {
font-size: 12.5px;
color: #18a058;
font-weight: 700;
}
.doc-acts {
display: flex;
gap: 7px;
}
.doc-mini {
border: 1px solid rgba(128, 128, 128, 0.3);
background: #fff;
border-radius: 7px;
padding: 5px 12px;
font-size: 12px;
cursor: pointer;
&:hover:not(:disabled) {
border-color: #18a058;
color: #18a058;
}
&:disabled {
opacity: 0.5;
cursor: default;
}
}
}
.doc-out {
flex: 1;
min-height: 260px;
max-height: 55vh;
overflow-y: auto;
background: rgba(128, 128, 128, 0.05);
border: 1px solid rgba(128, 128, 128, 0.15);
border-radius: 10px;
padding: 14px 16px;
}
.doc-text {
margin: 0;
white-space: pre-wrap;
word-break: break-word;
font-family: inherit;
font-size: 13.5px;
line-height: 1.85;
}
.doc-empty {
font-size: 12.5px;
opacity: 0.5;
line-height: 1.8;
padding: 20px 4px;
}
// 批量文件列表
.doc-jobs {
display: flex;
flex-direction: column;
gap: 8px;
flex: 1;
min-height: 0;
overflow: auto;
}
.doc-job {
border: 1px solid rgba(128, 128, 128, 0.25);
border-radius: 9px;
background: rgba(128, 128, 128, 0.03);
overflow: hidden;
.doc-job-head {
display: flex;
align-items: center;
gap: 8px;
padding: 8px 10px;
cursor: pointer;
min-width: 0;
}
.doc-job-ico {
flex-shrink: 0;
font-size: 14px;
}
.doc-job-name {
font-size: 13px;
font-weight: 600;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
max-width: 45%;
}
.doc-job-size {
font-size: 11.5px;
opacity: 0.55;
flex-shrink: 0;
}
.doc-job-info {
font-size: 11.5px;
opacity: 0.6;
flex: 1;
min-width: 0;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.doc-job-acts {
display: flex;
gap: 5px;
flex-shrink: 0;
margin-left: auto;
}
.doc-job-err {
font-size: 12px;
color: #d03050;
padding: 0 10px 8px;
}
.doc-out {
border-top: 1px solid rgba(128, 128, 128, 0.18);
}
}
.doc-spin {
position: absolute;
inset: 0;
pointer-events: none;
}
.tr-root {
display: flex;
flex-direction: column;
width: 100%;
min-height: 0;
box-sizing: border-box;
}
.toolbar {
display: flex;
flex-direction: row;
align-items: center;
justify-content: flex-end;
gap: 10px;
padding-bottom: 12px;
flex-shrink: 0;
.stats {
margin-right: auto;
font-size: 13px;
opacity: 0.65;
}
}
.body {
display: flex;
flex-direction: row;
gap: 16px;
flex: 1;
min-height: 0;
@media (max-width: 760px) {
flex-direction: column;
}
}
.pane {
flex: 1;
min-width: 0;
min-height: 0;
display: flex;
flex-direction: column;
}
.lang-row {
display: flex;
align-items: center;
gap: 10px;
margin-bottom: 10px;
flex-shrink: 0;
.target-label {
font-size: 13px;
opacity: 0.7;
}
}
.hint {
font-size: 12px;
opacity: 0.55;
margin-top: 6px;
flex-shrink: 0;
}
.output-wrap {
flex: 1;
min-height: 0;
}
.output {
height: 100%;
min-height: 150px;
border: 1px solid rgba(128, 128, 128, 0.3);
border-radius: 6px;
padding: 12px;
font-size: 14px;
line-height: 1.7;
white-space: pre-wrap;
word-break: break-word;
overflow-y: auto;
box-sizing: border-box;
user-select: text;
&.hasError {
color: #d03050;
}
.placeholder {
opacity: 0.4;
}
}
</style>