feat: 全站编辑状态自动保存 — 每分钟自动保存 + 右下角立即保存 + 离开拦截

- 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 拦截刷新关闭
  文案「当前内容还没保存,离开会丢失」确定=先保存再离开 取消=留在本页
- 用户开始编辑时「已恢复」提示立即让位给「未保存」
This commit is contained in:
jinghui committed 2026-11-15 01:56:28 +08:00
1 parent 7b6513c7de
commit f529d5e850
5 files changed
+456

No files matched your search

+2
View File
@@ -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']
+138
View File
@@ -0,0 +1,138 @@
<script setup lang="ts">
import { computed, ref } from 'vue';
import { restored, saveNow, savedAt, status } from '../composable/autosave';
const now = ref(Date.now());
setInterval(() => {
now.value = Date.now();
}, 10_000);
const timeLabel = computed(() => {
if (!savedAt.value) return '';
const d = new Date(savedAt.value);
const hh = String(d.getHours()).padStart(2, '0');
const mm = String(d.getMinutes()).padStart(2, '0');
return `${hh}:${mm}`;
});
const saving = ref(false);
async function onSave() {
if (saving.value) return;
saving.value = true;
try {
await saveNow();
} finally {
saving.value = false;
}
}
</script>
<template>
<div class="autosave-bar" :class="{ show: status !== 'idle' || restored }">
<!-- 已恢复上次内容 -->
<div v-if="restored" class="as-chip as-restore">
<span class="as-dot green" />
已恢复上次未保存的内容
</div>
<!-- 有未保存修改 -->
<div v-else-if="status === 'dirty'" class="as-chip as-dirty">
<span class="as-dot orange" />
<span class="as-text">未保存</span>
<button class="as-btn" :disabled="saving" @click="onSave">
{{ saving || status === 'saving' ? '保存中…' : '立即保存' }}
</button>
</div>
<!-- 保存中 -->
<div v-else-if="status === 'saving'" class="as-chip as-saving">
<span class="as-dot gray blink" />
<span class="as-text">保存中…</span>
</div>
<!-- 保存失败 -->
<div v-else-if="status === 'error'" class="as-chip as-error">
<span class="as-dot red" />
<span class="as-text">保存失败</span>
<button class="as-btn" @click="onSave">重试</button>
</div>
<!-- 已保存 -->
<div v-else-if="status === 'saved'" class="as-chip as-saved">
<span class="as-dot green" />
<span class="as-text">已保存 {{ timeLabel }}</span>
</div>
</div>
</template>
<style scoped>
.autosave-bar {
position: fixed;
right: 20px;
bottom: 20px;
z-index: 9999;
pointer-events: none;
opacity: 0;
transform: translateY(8px);
transition: opacity .25s ease, transform .25s ease;
}
.autosave-bar.show {
opacity: 1;
transform: translateY(0);
}
.as-chip {
display: inline-flex;
align-items: center;
gap: 8px;
padding: 7px 12px;
border-radius: 999px;
background: rgba(30, 30, 30, .92);
color: #eaeaea;
font-size: 12px;
line-height: 1;
box-shadow: 0 4px 16px rgba(0, 0, 0, .28);
backdrop-filter: blur(6px);
pointer-events: auto;
}
.as-text {
white-space: nowrap;
}
.as-dot {
width: 7px;
height: 7px;
border-radius: 50%;
flex: none;
}
.as-dot.green { background: #3ecf8e; }
.as-dot.orange { background: #f5a524; }
.as-dot.red { background: #f31260; }
.as-dot.gray { background: #a1a1aa; }
.blink { animation: as-blink 1s infinite; }
@keyframes as-blink {
0%, 100% { opacity: 1; }
50% { opacity: .25; }
}
.as-btn {
border: 0;
border-radius: 999px;
padding: 5px 11px;
font-size: 12px;
line-height: 1;
cursor: pointer;
background: #3ecf8e;
color: #08221a;
font-weight: 600;
transition: filter .15s ease;
}
.as-btn:hover { filter: brightness(1.08); }
.as-btn:disabled { opacity: .6; cursor: default; }
.as-error .as-btn {
background: #f31260;
color: #fff;
}
@media (max-width: 640px) {
.autosave-bar { right: 12px; bottom: 76px; }
}
</style>
+290
View File
@@ -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<AutosaveStatus>('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<HTMLElement>('.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<string, any> | null {
const r = root();
if (!r) return null;
const out: Record<string, any> = {};
const counters: Record<string, number> = {};
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<string, any>): number {
const r = root();
if (!r || !state) return 0;
let applied = 0;
restoring = true;
try {
const counters: Record<string, number> = {};
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<boolean> {
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<void> {
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<boolean> {
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);
}
+19
View File
@@ -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<HeadObject>(() => ({
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() {
<slot />
</div>
<!-- 右下角:自动保存状态 + 立即保存按钮 -->
<AutosaveBar />
<!-- 授权门:受控功能显示试用倒计时,到期锁定 -->
<LicenseGate :path="route.path" />
</BaseLayout>
+7
View File
@@ -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;