From f529d5e85042128b65f5f5ead56b85df0af4ea7a Mon Sep 17 00:00:00 2001 From: jinghui Date: Sun, 15 Nov 2026 01:56:28 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E5=85=A8=E7=AB=99=E7=BC=96=E8=BE=91?= =?UTF-8?q?=E7=8A=B6=E6=80=81=E8=87=AA=E5=8A=A8=E4=BF=9D=E5=AD=98=20?= =?UTF-8?q?=E2=80=94=20=E6=AF=8F=E5=88=86=E9=92=9F=E8=87=AA=E5=8A=A8?= =?UTF-8?q?=E4=BF=9D=E5=AD=98=20+=20=E5=8F=B3=E4=B8=8B=E8=A7=92=E7=AB=8B?= =?UTF-8?q?=E5=8D=B3=E4=BF=9D=E5=AD=98=20+=20=E7=A6=BB=E5=BC=80=E6=8B=A6?= =?UTF-8?q?=E6=88=AA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - composable/autosave.ts: 通用 DOM 快照(.tool-content 内 input/textarea/select/contenteditable) 字段定位 name > tag:type:组内序号(不用动态 id, 实测 Naive UI id 每次刷新都变) 60s 定时自动保存 + markDirty 变更检测 + 静默恢复(仅当页面基本为空) - components/AutosaveBar.vue: 右下角状态条 未保存/立即保存/已保存 HH:MM/已恢复 - tool.layout.vue: 按路由挂载(仅 isTool 页), 切页自动 detach - router.ts: confirmLeave 拦截站内导航 + beforeunload 拦截刷新关闭 文案「当前内容还没保存,离开会丢失」确定=先保存再离开 取消=留在本页 - 用户开始编辑时「已恢复」提示立即让位给「未保存」 --- components.d.ts | 2 + src/components/AutosaveBar.vue | 138 ++++++++++++++++ src/composable/autosave.ts | 290 +++++++++++++++++++++++++++++++++ src/layouts/tool.layout.vue | 19 +++ src/router.ts | 7 + 5 files changed, 456 insertions(+) create mode 100644 src/components/AutosaveBar.vue create mode 100644 src/composable/autosave.ts diff --git a/components.d.ts b/components.d.ts index bfae6b6..95a89ec 100644 --- a/components.d.ts +++ b/components.d.ts @@ -20,6 +20,7 @@ declare module '@vue/runtime-core' { App: typeof import('./src/App.vue')['default'] AsciiTextDrawer: typeof import('./src/tools/ascii-text-drawer/ascii-text-drawer.vue')['default'] AudioTools: typeof import('./src/tools/audio-tools/audio-tools.vue')['default'] + AutosaveBar: typeof import('./src/components/AutosaveBar.vue')['default'] BarcodeBatchGenerator: typeof import('./src/tools/batch-barcode-generator/barcode-batch-generator.vue')['default'] 'Base.layout': typeof import('./src/layouts/base.layout.vue')['default'] Base64FileConverter: typeof import('./src/tools/base64-file-converter/base64-file-converter.vue')['default'] @@ -130,6 +131,7 @@ declare module '@vue/runtime-core' { IconMdiVideo: typeof import('~icons/mdi/video')['default'] ImageOcr: typeof import('./src/tools/image-ocr/image-ocr.vue')['default'] ImageTools: typeof import('./src/tools/image-tools/image-tools.vue')['default'] + ImgEditor: typeof import('./src/tools/ai-gen/img-editor.vue')['default'] ImgHist: typeof import('./src/tools/img-hist/ImgHist.vue')['default'] InputCopyable: typeof import('./src/components/InputCopyable.vue')['default'] IntegerBaseConverter: typeof import('./src/tools/integer-base-converter/integer-base-converter.vue')['default'] diff --git a/src/components/AutosaveBar.vue b/src/components/AutosaveBar.vue new file mode 100644 index 0000000..23dc236 --- /dev/null +++ b/src/components/AutosaveBar.vue @@ -0,0 +1,138 @@ + + + + + diff --git a/src/composable/autosave.ts b/src/composable/autosave.ts new file mode 100644 index 0000000..adcee81 --- /dev/null +++ b/src/composable/autosave.ts @@ -0,0 +1,290 @@ +import { nextTick, ref } from 'vue'; + +import { getMachineId, licenseHeaders } from '../tools/license/license'; +import { apiFetch } from './user-auth'; + +/** + * 全站草稿自动保存(2026-11-15 用户需求): + * - 用户在任意工具页编辑时,每 1 分钟自动把当前修改状态保存到服务器 + * - 右下角提供「立即保存」按钮 + * - 未保存就刷新 / 关闭 / 前进后退时提示「当前内容还没保存离开会丢失,是否保存」 + * + * 覆盖方式:通用 DOM 快照(抓取 .tool-content 内全部 input/textarea/select/contenteditable), + * 因此对全部工具生效,无需逐个工具改造。file 输入与超大数据跳过。 + */ + +export type AutosaveStatus = 'idle' | 'dirty' | 'saving' | 'saved' | 'error'; + +export const status = ref('idle'); +export const savedAt = ref(0); +export const restored = ref(false); +export const hasUnsaved = ref(false); + +const INTERVAL_MS = 60_000; // 每 1 分钟 +const MAX_STATE_BYTES = 300 * 1024; // 与服务端限制一致 + +let toolKey = ''; +let timer: number | null = null; +let dirty = false; +let bound = false; +let restoring = false; + +const SKIP_TYPE = new Set(['file', 'image', 'button', 'submit', 'reset', 'color', 'range']); + +function root(): HTMLElement | null { + return document.querySelector('.tool-content'); +} + +/** + * 稳定字段定位:name > tag:type:组内序号。 + * 注意:不能用 element.id —— Naive UI 等框架的 id 每次刷新都会重新生成 + * (实测 id-omyyvzbgz8 → id-h0mksbmep7),会导致草稿无法匹配回填。 + */ +function fieldKey(e: Element, idx: number): string { + const el = e as HTMLInputElement; + const name = el.getAttribute?.('name'); + if (name) return `[${name}]`; + const tag = e.tagName.toLowerCase(); + const type = (el.type || '').toLowerCase(); + return `${tag}:${type}:${idx}`; +} + +/** 抓取当前工具页的可编辑状态 */ +export function snapshot(): Record | null { + const r = root(); + if (!r) return null; + const out: Record = {}; + const counters: Record = {}; + let n = 0; + + r.querySelectorAll('input, textarea, select').forEach(el => { + const e = el as HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement; + const tag = e.tagName.toLowerCase(); + const type = tag === 'input' ? ((e as HTMLInputElement).type || 'text').toLowerCase() : ''; + if (tag === 'input' && SKIP_TYPE.has(type)) return; + const grp = `${tag}:${type}`; + const idx = counters[grp] ?? 0; + counters[grp] = idx + 1; + const key = fieldKey(e, idx); + try { + if (tag === 'input' && (type === 'checkbox' || type === 'radio')) { + out[key] = (e as HTMLInputElement).checked; + } else if (tag === 'select' && (e as HTMLSelectElement).multiple) { + out[key] = Array.from((e as HTMLSelectElement).selectedOptions).map(o => o.value); + } else { + out[key] = (e as any).value; + } + n++; + } catch { + /* 某些自定义控件取值失败则跳过 */ + } + }); + + let ce = 0; + r.querySelectorAll('[contenteditable="true"]').forEach(el => { + const html = (el as HTMLElement).innerHTML || ''; + if (html) out[`ce:${ce}`] = html.slice(0, 50_000); + ce++; + n++; + }); + + return n > 0 ? out : null; +} + +/** 把服务器草稿写回页面(触发 input/change 让 v-model 同步) */ +function applyState(state: Record): number { + const r = root(); + if (!r || !state) return 0; + let applied = 0; + restoring = true; + try { + const counters: Record = {}; + r.querySelectorAll('input, textarea, select').forEach(el => { + const e = el as HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement; + const tag = e.tagName.toLowerCase(); + const type = tag === 'input' ? ((e as HTMLInputElement).type || 'text').toLowerCase() : ''; + if (tag === 'input' && SKIP_TYPE.has(type)) return; + const grp = `${tag}:${type}`; + const idx = counters[grp] ?? 0; + counters[grp] = idx + 1; + const key = fieldKey(e, idx); + if (!(key in state)) return; + const v = state[key]; + applied++; + try { + if (tag === 'input' && type === 'checkbox') { + (e as HTMLInputElement).checked = !!v; + } else if (tag === 'input' && type === 'radio') { + (e as HTMLInputElement).checked = v === true || v === (e as HTMLInputElement).value; + } else if (tag === 'select' && (e as HTMLSelectElement).multiple && Array.isArray(v)) { + const set = new Set(v.map(String)); + Array.from((e as HTMLSelectElement).options).forEach(o => { + o.selected = set.has(o.value); + }); + } else if (v !== undefined && v !== null) { + (e as any).value = String(v); + } + e.dispatchEvent(new Event('input', { bubbles: true })); + e.dispatchEvent(new Event('change', { bubbles: true })); + } catch { + /* 忽略单个字段失败 */ + } + }); + + let ce = 0; + r.querySelectorAll('[contenteditable="true"]').forEach(el => { + const key = `ce:${ce}`; + ce++; + if (key in state && state[key]) { + (el as HTMLElement).innerHTML = String(state[key]); + applied++; + } + }); + } finally { + // 等 Vue 完成一轮渲染再解除抑制 + setTimeout(() => { + restoring = false; + }, 300); + } + return applied; +} + +function markDirty(): void { + if (restoring || !toolKey) return; + // 用户开始编辑后,「已恢复」提示立即让位给「未保存」 + if (restored.value) restored.value = false; + if (!dirty) { + dirty = true; + hasUnsaved.value = true; + status.value = 'dirty'; + } +} + +function onEdit(): void { + markDirty(); +} + +/** 立即保存(右下角按钮 / 定时器 / 离开前调用) */ +export async function saveNow(): Promise { + if (!toolKey) return false; + const state = snapshot(); + if (!state) return false; + const json = JSON.stringify({ machine: getMachineId(), tool: toolKey, state }); + if (json.length > MAX_STATE_BYTES) { + status.value = 'error'; + return false; + } + status.value = 'saving'; + try { + const { status: st } = await apiFetch('/draft/save', { + method: 'POST', + headers: { 'Content-Type': 'application/json', ...licenseHeaders(toolKey) }, + body: json, + }); + if (st === 200) { + dirty = false; + hasUnsaved.value = false; + savedAt.value = Date.now(); + status.value = 'saved'; + return true; + } + status.value = 'error'; + return false; + } catch { + status.value = 'error'; + return false; + } +} + +/** 尝试恢复上次未保存的内容(仅当当前页面基本为空时,避免覆盖新输入) */ +async function tryRestore(): Promise { + if (!toolKey) return; + try { + const { status: st, body } = await apiFetch( + `/draft/load?machine=${encodeURIComponent(getMachineId())}&tool=${encodeURIComponent(toolKey)}`, + ); + if (st !== 200 || !body?.data?.state) return; + const cur = snapshot(); + if (cur) { + // 已有用户输入则不打扰,仅在几乎全空时恢复 + const filled = Object.values(cur).filter(v => { + if (typeof v === 'string') return v.trim() !== ''; + if (Array.isArray(v)) return v.length > 0; + return v === true; + }).length; + if (filled > 0) return; + } + await nextTick(); + const applied = applyState(body.data.state); + if (applied <= 0) return; // 字段对不上(工具改版等)则不打扰用户 + restored.value = true; + status.value = 'saved'; + savedAt.value = Number(body.data.ts) * 1000 || Date.now(); + setTimeout(() => { + restored.value = false; + }, 4000); + } catch { + /* 静默失败,不阻断编辑 */ + } +} + +function stopTimer(): void { + if (timer !== null) { + window.clearInterval(timer); + timer = null; + } +} + +/** 进入工具页:绑定事件 + 启动 1 分钟定时器 + 尝试恢复草稿 */ +export function attach(tool: string): void { + toolKey = tool; + dirty = false; + hasUnsaved.value = false; + restored.value = false; + status.value = 'idle'; + savedAt.value = 0; + if (!bound) { + document.addEventListener('input', onEdit, true); + document.addEventListener('change', onEdit, true); + bound = true; + } + stopTimer(); + timer = window.setInterval(() => { + if (dirty) void saveNow(); + }, INTERVAL_MS); + void tryRestore(); +} + +/** 离开工具页:停表(未保存内容保留在服务器草稿里) */ +export function detach(): void { + stopTimer(); + toolKey = ''; + dirty = false; + hasUnsaved.value = false; + status.value = 'idle'; +} + +/** 有未保存修改则提示,返回是否允许离开 */ +export async function confirmLeave(): Promise { + if (!dirty || !toolKey) return true; + const ok = window.confirm( + `当前内容还没保存,离开会丢失。\n\n是否保存后再离开?\n\n(点「确定」= 先保存再离开,点「取消」= 留在本页)`, + ); + if (ok) { + const saved = await saveNow(); + return saved; + } + return false; +} + +/** 刷新 / 关闭标签页时的原生拦截 */ +export function onBeforeUnload(e: BeforeUnloadEvent): void { + if (dirty && hasUnsaved.value) { + e.preventDefault(); + e.returnValue = ''; + } +} + +if (typeof window !== 'undefined') { + window.addEventListener('beforeunload', onBeforeUnload); +} diff --git a/src/layouts/tool.layout.vue b/src/layouts/tool.layout.vue index abd1695..7f7e86e 100644 --- a/src/layouts/tool.layout.vue +++ b/src/layouts/tool.layout.vue @@ -5,6 +5,8 @@ import { useHead } from '@vueuse/head'; import type { HeadObject } from '@vueuse/head'; import BaseLayout from './base.layout.vue'; +import AutosaveBar from '@/components/AutosaveBar.vue'; +import { attach as autosaveAttach, detach as autosaveDetach } from '@/composable/autosave'; import FavoriteButton from '@/components/FavoriteButton.vue'; import LicenseGate from '@/tools/license/LicenseGate.vue'; import type { Tool } from '@/tools/tools.types'; @@ -39,6 +41,20 @@ const head = computed(() => ({ useHead(head); const { t } = useI18n(); +// ===== 全站草稿自动保存:进入工具页绑定 1 分钟定时器,离开时停表 ===== +watch( + () => route.path, + () => { + if (route.meta.isTool) { + autosaveAttach(route.path.replace(/^\//, '')); + } else { + autosaveDetach(); + } + }, + { immediate: true }, +); +onUnmounted(() => autosaveDetach()); + // 宽屏工具:不受 600px 限宽,占满可用宽度(画布/多栏类工具) const WIDE_TOOLS = new Set(['/label-designer', '/json-prettify', '/pdf-tools', '/image-tools', '/doc-convert', '/video-tools', '/seal-maker', '/signature-pad', '/ai-image-lab', '/ai-chat', '/copywriting', '/ai-gen', '/code-reader', '/my-ip', '/mcp-connect', '/poster-maker', '/ai-text-edit', '/ai-retouch']); const isWide = computed(() => WIDE_TOOLS.has(route.path)); @@ -146,6 +162,9 @@ function retryAiHelp() { + + + diff --git a/src/router.ts b/src/router.ts index 2ef8f9f..a8e8ee5 100644 --- a/src/router.ts +++ b/src/router.ts @@ -5,6 +5,7 @@ import NotFound from './pages/404.page.vue'; import { tools } from './tools'; import { config } from './config'; import { reportToolUsage, startOnlineHeartbeat } from './tools/license/license'; +import { confirmLeave } from './composable/autosave'; import { routes as demoRoutes } from './ui/demo/demo.routes'; const toolsRoutes = tools.map(({ path, name, component, ...config }) => ({ @@ -68,4 +69,10 @@ router.afterEach((to) => { startOnlineHeartbeat(); }); +// ===== 全站草稿保护:有未保存修改时拦截站内前进/后退/跳转 ===== +// 「确定」= 先保存再离开;「取消」= 留在本页(返回 false 中断导航) +router.beforeEach(async () => { + return await confirmLeave(); +}); + export default router;