feat(autosave): 找回历史版本——「找回」面板一键恢复任意保存档
- AutosaveBar 新增「找回」按钮与历史面板:列出该工具近20份保存留档(时间精确到秒),点任意一条立即恢复成该版继续编辑 - autosave.ts 导出 loadHistory/restoreVersion - relay 新增 /draft/history 与 /draft/load?ts= 端点;save 落盘留档20份,同秒连续保存只覆盖不重复占档 - README 自动保存章节补「找回历史版本」;Home NEW_FEATURES 置顶条目 - 同步 in-repo relay 副本 server.py
This commit is contained in:
1 parent
ce512f1966
commit
9cbec90347
5 files changed
+352
-13
No files matched your search
@@ -121,8 +121,9 @@
|
||||
- **「立即保存」按钮全程可点**(保存中除外):idle 态点一下即保存当前内容
|
||||
- **离开拦截**:未保存就刷新、关闭、站内前进后退时提示「当前内容还没保存,离开会丢失」——点「确定」= 先保存再离开,点「取消」= 留在本页
|
||||
- **刷新自动恢复**:重新进入工具页自动还原上次未保存的内容
|
||||
- **找回历史版本**(2026-11-15 新增):状态条上的「找回」按钮列出该工具的保存历史(服务端留档 20 份,时间精确到秒),点任意一条立即把页面内容恢复成那一版,随后可继续编辑;内容没有变化的重复保存只更新时间,不会重复占档
|
||||
|
||||
> 实现:通用 DOM 快照一次性覆盖全部工具(无需逐个改造),字段定位用 `name > tag:type:组内序号`(框架动态 id 每次刷新都会变,实测不能用);服务端三端点 `/draft/save|load|delete`,按机器码隔离。
|
||||
> 实现:通用 DOM 快照一次性覆盖全部工具(无需逐个改造),字段定位用 `name > tag:type:组内序号`(框架动态 id 每次刷新都会变,实测不能用);服务端四端点 `/draft/save|load|history|delete`,按机器码隔离。
|
||||
|
||||
### 历史记录 100 条上限(2026.11 新增)
|
||||
|
||||
|
||||
@@ -2417,6 +2417,12 @@ class Handler(BaseHTTPRequestHandler):
|
||||
if parsed.path == "/ai/img-history":
|
||||
self._handle_img_history()
|
||||
return
|
||||
if parsed.path == "/draft/load":
|
||||
self._handle_draft_load(parsed)
|
||||
return
|
||||
if parsed.path == "/draft/history":
|
||||
self._handle_draft_history(parsed)
|
||||
return
|
||||
if parsed.path.startswith("/ai/img/"):
|
||||
self._handle_img_file(parsed)
|
||||
return
|
||||
@@ -3435,6 +3441,12 @@ class Handler(BaseHTTPRequestHandler):
|
||||
if parsed.path == "/ai/img-save":
|
||||
self._handle_img_save()
|
||||
return
|
||||
if parsed.path == "/draft/save":
|
||||
self._handle_draft_save()
|
||||
return
|
||||
if parsed.path == "/draft/delete":
|
||||
self._handle_draft_delete()
|
||||
return
|
||||
if parsed.path == "/ai/edit-image":
|
||||
self._handle_edit_image()
|
||||
return
|
||||
@@ -3850,6 +3862,150 @@ class Handler(BaseHTTPRequestHandler):
|
||||
log_usage(machine, tool)
|
||||
self._reply(200, json.dumps({"code": 200, "message": "ok", "data": {"img_url": img_url}}, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
|
||||
# ---------- 全站草稿自动保存(每 1 分钟 / 立即保存按钮 / 离开拦截)----------
|
||||
@staticmethod
|
||||
def _draft_path(machine: str, tool: str) -> str:
|
||||
"""校验并映射到 DATA_DIR/drafts/<machine>/<tool>.json;非法返回空串。"""
|
||||
m = MACHINE_RE.match(machine or "")
|
||||
t = re.sub(r"[^A-Za-z0-9_-]", "", tool or "")[:64]
|
||||
if not m or not t:
|
||||
return ""
|
||||
return os.path.join(DATA_DIR, "drafts", m.group(0), t + ".json")
|
||||
|
||||
def _handle_draft_save(self):
|
||||
payload = self._read_payload()
|
||||
machine = str(payload.get("machine") or "")
|
||||
tool = str(payload.get("tool") or "")
|
||||
path = self._draft_path(machine, tool)
|
||||
if not path:
|
||||
self._reply(400, json.dumps({"code": 400, "message": "bad machine/tool"}, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
return
|
||||
state = payload.get("state")
|
||||
try:
|
||||
raw = json.dumps(state, ensure_ascii=False)
|
||||
except (TypeError, ValueError):
|
||||
self._reply(400, json.dumps({"code": 400, "message": "bad state"}, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
return
|
||||
if len(raw.encode("utf-8")) > 300 * 1024:
|
||||
self._reply(413, json.dumps({"code": 413, "message": "草稿超过 300KB 限制"}, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
return
|
||||
try:
|
||||
os.makedirs(os.path.dirname(path), exist_ok=True)
|
||||
rec = {"tool": tool[:64], "machine": machine, "ts": int(time.time()), "state": state}
|
||||
tmp = path + ".tmp"
|
||||
with open(tmp, "w", encoding="utf-8") as f:
|
||||
json.dump(rec, f, ensure_ascii=False)
|
||||
os.replace(tmp, path)
|
||||
except OSError:
|
||||
self._reply(500, json.dumps({"code": 500, "message": "保存失败"}, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
return
|
||||
# 追加历史版本(保留最近 20 版,供前端「找回」面板选择回填)
|
||||
try:
|
||||
hpath = path[:-5] + ".hist.json"
|
||||
hist = []
|
||||
if os.path.isfile(hpath):
|
||||
with open(hpath, "r", encoding="utf-8") as f:
|
||||
loaded = json.load(f)
|
||||
if isinstance(loaded, list):
|
||||
hist = [h for h in loaded if isinstance(h, dict)]
|
||||
# 连续保存相同内容不重复入档(只更新最新一条时间戳)
|
||||
if hist and hist[0].get("state") == state:
|
||||
hist[0]["ts"] = rec["ts"]
|
||||
elif hist and hist[0].get("ts") == rec["ts"]:
|
||||
# 同一秒内的连续保存:按最新内容覆盖,避免出现两条同时间条目
|
||||
hist[0] = {"ts": rec["ts"], "state": state}
|
||||
else:
|
||||
hist.insert(0, {"ts": rec["ts"], "state": state})
|
||||
hist = hist[:20]
|
||||
tmp2 = hpath + ".tmp"
|
||||
with open(tmp2, "w", encoding="utf-8") as f:
|
||||
json.dump(hist, f, ensure_ascii=False)
|
||||
os.replace(tmp2, hpath)
|
||||
except (OSError, ValueError, TypeError):
|
||||
pass # 历史写入失败不影响主保存
|
||||
self._reply(200, json.dumps({"code": 200, "message": "ok", "data": {"ts": rec["ts"]}}, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
|
||||
def _handle_draft_load(self, parsed):
|
||||
qs = parse.parse_qs(parsed.query)
|
||||
machine = str((qs.get("machine") or [""])[0] or "")
|
||||
tool = str((qs.get("tool") or [""])[0] or "")
|
||||
try:
|
||||
want_ts = int((qs.get("ts") or ["0"])[0] or 0)
|
||||
except ValueError:
|
||||
want_ts = 0
|
||||
path = self._draft_path(machine, tool)
|
||||
if not path:
|
||||
self._reply(400, json.dumps({"code": 400, "message": "bad machine/tool"}, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
return
|
||||
data = None
|
||||
# 指定 ts:从历史版本里找回该条
|
||||
if want_ts > 0:
|
||||
hpath = path[:-5] + ".hist.json"
|
||||
if os.path.isfile(hpath):
|
||||
try:
|
||||
with open(hpath, "r", encoding="utf-8") as f:
|
||||
hist = json.load(f)
|
||||
if isinstance(hist, list):
|
||||
for h in hist:
|
||||
if isinstance(h, dict) and int(h.get("ts") or 0) == want_ts:
|
||||
data = {"state": h.get("state"), "ts": want_ts}
|
||||
break
|
||||
except (OSError, ValueError, TypeError):
|
||||
data = None
|
||||
else:
|
||||
if os.path.isfile(path):
|
||||
try:
|
||||
with open(path, "r", encoding="utf-8") as f:
|
||||
rec = json.load(f)
|
||||
data = {"state": rec.get("state"), "ts": int(rec.get("ts") or 0)}
|
||||
except (OSError, ValueError):
|
||||
data = None
|
||||
self._reply(200, json.dumps({"code": 200, "message": "ok", "data": data}, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
|
||||
def _handle_draft_history(self, parsed):
|
||||
"""历史版本清单(只回 ts/bytes,不回 state,面板按需逐条取)。"""
|
||||
qs = parse.parse_qs(parsed.query)
|
||||
machine = str((qs.get("machine") or [""])[0] or "")
|
||||
tool = str((qs.get("tool") or [""])[0] or "")
|
||||
path = self._draft_path(machine, tool)
|
||||
if not path:
|
||||
self._reply(400, json.dumps({"code": 400, "message": "bad machine/tool"}, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
return
|
||||
items = []
|
||||
hpath = path[:-5] + ".hist.json"
|
||||
if os.path.isfile(hpath):
|
||||
try:
|
||||
with open(hpath, "r", encoding="utf-8") as f:
|
||||
hist = json.load(f)
|
||||
if isinstance(hist, list):
|
||||
for h in hist:
|
||||
if not isinstance(h, dict):
|
||||
continue
|
||||
st = h.get("state")
|
||||
try:
|
||||
b = len(json.dumps(st, ensure_ascii=False).encode("utf-8")) if st is not None else 0
|
||||
except (TypeError, ValueError):
|
||||
b = 0
|
||||
items.append({"ts": int(h.get("ts") or 0), "bytes": b})
|
||||
except (OSError, ValueError):
|
||||
items = []
|
||||
self._reply(200, json.dumps({"code": 200, "message": "ok", "data": {"items": items}}, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
|
||||
def _handle_draft_delete(self):
|
||||
payload = self._read_payload()
|
||||
machine = str(payload.get("machine") or "")
|
||||
tool = str(payload.get("tool") or "")
|
||||
path = self._draft_path(machine, tool)
|
||||
if not path:
|
||||
self._reply(400, json.dumps({"code": 400, "message": "bad machine/tool"}, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
return
|
||||
try:
|
||||
if os.path.isfile(path):
|
||||
os.remove(path)
|
||||
except OSError:
|
||||
pass
|
||||
self._reply(200, json.dumps({"code": 200, "message": "ok"}, ensure_ascii=False).encode("utf-8"), "application/json")
|
||||
|
||||
def _handle_img_history(self):
|
||||
parsed = parse.urlparse(self.path)
|
||||
qs = parse.parse_qs(parsed.query)
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, ref } from 'vue';
|
||||
|
||||
import { restored, saveNow, savedAt, status } from '../composable/autosave';
|
||||
import { loadHistory, restored, restoreVersion, saveNow, savedAt, status } from '../composable/autosave';
|
||||
|
||||
const now = ref(Date.now());
|
||||
setInterval(() => {
|
||||
@@ -28,9 +28,52 @@ async function onSave() {
|
||||
}
|
||||
}
|
||||
|
||||
/** ---- 找回历史版本 ---- */
|
||||
const histOpen = ref(false);
|
||||
const histLoading = ref(false);
|
||||
const histItems = ref<{ ts: number; bytes: number }[]>([]);
|
||||
const picking = ref(false);
|
||||
|
||||
async function toggleHist() {
|
||||
if (histOpen.value) {
|
||||
histOpen.value = false;
|
||||
return;
|
||||
}
|
||||
histOpen.value = true;
|
||||
histLoading.value = true;
|
||||
try {
|
||||
histItems.value = await loadHistory();
|
||||
} finally {
|
||||
histLoading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function onPick(ts: number) {
|
||||
if (picking.value) return;
|
||||
picking.value = true;
|
||||
try {
|
||||
const ok = await restoreVersion(ts);
|
||||
if (ok) histOpen.value = false;
|
||||
} finally {
|
||||
picking.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function fmtTime(ts: number): string {
|
||||
const d = new Date(ts * 1000);
|
||||
const p = (n: number) => String(n).padStart(2, '0');
|
||||
return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}:${p(d.getSeconds())}`;
|
||||
}
|
||||
|
||||
function fmtSize(b: number): string {
|
||||
if (b < 1024) return `${b} B`;
|
||||
if (b < 1024 * 1024) return `${(b / 1024).toFixed(1)} KB`;
|
||||
return `${(b / 1024 / 1024).toFixed(1)} MB`;
|
||||
}
|
||||
|
||||
/** 当前状态文案 —— 打开页面即常驻可见(idle = 自动保存已开启) */
|
||||
const textLabel = computed(() => {
|
||||
if (restored.value) return '已恢复上次未保存的内容';
|
||||
if (restored.value) return '已恢复保存的内容';
|
||||
switch (status.value) {
|
||||
case 'dirty':
|
||||
return '未保存';
|
||||
@@ -74,9 +117,40 @@ const btnLabel = computed(() => (status.value === 'error' ? '重试' : '立即
|
||||
<template>
|
||||
<!-- 常驻右下角:任何工具页打开即可见 -->
|
||||
<div class="autosave-bar show">
|
||||
<!-- 找回历史版本面板 -->
|
||||
<div v-if="histOpen" class="as-panel">
|
||||
<div class="as-panel-hd">
|
||||
<span>找回历史版本</span>
|
||||
<button class="as-x" @click="histOpen = false">×</button>
|
||||
</div>
|
||||
<div class="as-panel-body">
|
||||
<div v-if="histLoading" class="as-empty">加载中…</div>
|
||||
<div v-else-if="!histItems.length" class="as-empty">暂无历史版本<br /><small>每次保存都会自动留档</small></div>
|
||||
<button
|
||||
v-for="it in histItems"
|
||||
:key="it.ts"
|
||||
class="as-hitem"
|
||||
:disabled="picking"
|
||||
:title="`点击恢复到 ${fmtTime(it.ts)} 的内容`"
|
||||
@click="onPick(it.ts)"
|
||||
>
|
||||
<span class="as-hdate">{{ fmtTime(it.ts) }}</span>
|
||||
<span class="as-hsize">{{ fmtSize(it.bytes) }}</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="as-chip" :class="chipClass">
|
||||
<span class="as-dot" :class="dotClass" />
|
||||
<span class="as-text">{{ textLabel }}</span>
|
||||
<button
|
||||
class="as-btn ghost"
|
||||
:disabled="saving || histLoading || picking"
|
||||
title="找回历史保存的版本,点击恢复后可继续编辑"
|
||||
@click="toggleHist"
|
||||
>
|
||||
{{ picking ? '恢复中…' : '找回' }}
|
||||
</button>
|
||||
<button
|
||||
v-if="status !== 'saving'"
|
||||
class="as-btn"
|
||||
@@ -150,10 +224,86 @@ const btnLabel = computed(() => (status.value === 'error' ? '重试' : '立即
|
||||
}
|
||||
.as-btn:hover { filter: brightness(1.08); }
|
||||
.as-btn:disabled { opacity: .6; cursor: default; }
|
||||
.as-btn.ghost {
|
||||
background: transparent;
|
||||
color: #cfcfcf;
|
||||
border: 1px solid rgba(255, 255, 255, .28);
|
||||
font-weight: 500;
|
||||
}
|
||||
.as-btn.ghost:hover { border-color: rgba(255, 255, 255, .55); color: #fff; filter: none; }
|
||||
.as-error .as-btn {
|
||||
background: #f31260;
|
||||
color: #fff;
|
||||
}
|
||||
/* 历史版本面板 */
|
||||
.as-panel {
|
||||
position: absolute;
|
||||
right: 0;
|
||||
bottom: calc(100% + 8px);
|
||||
width: 258px;
|
||||
background: rgba(30, 30, 30, .97);
|
||||
border: 1px solid rgba(255, 255, 255, .12);
|
||||
border-radius: 12px;
|
||||
box-shadow: 0 8px 28px rgba(0, 0, 0, .4);
|
||||
pointer-events: auto;
|
||||
overflow: hidden;
|
||||
color: #eaeaea;
|
||||
}
|
||||
.as-panel-hd {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: 9px 12px;
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
border-bottom: 1px solid rgba(255, 255, 255, .1);
|
||||
}
|
||||
.as-x {
|
||||
border: 0;
|
||||
background: transparent;
|
||||
color: #a1a1aa;
|
||||
font-size: 16px;
|
||||
line-height: 1;
|
||||
cursor: pointer;
|
||||
padding: 0 2px;
|
||||
}
|
||||
.as-x:hover { color: #fff; }
|
||||
.as-panel-body {
|
||||
max-height: 250px;
|
||||
overflow-y: auto;
|
||||
padding: 6px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
}
|
||||
.as-empty {
|
||||
text-align: center;
|
||||
color: #a1a1aa;
|
||||
font-size: 12px;
|
||||
padding: 18px 8px;
|
||||
line-height: 1.6;
|
||||
}
|
||||
.as-empty small { opacity: .7; }
|
||||
.as-hitem {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 8px;
|
||||
width: 100%;
|
||||
border: 0;
|
||||
border-radius: 8px;
|
||||
padding: 7px 9px;
|
||||
background: rgba(255, 255, 255, .06);
|
||||
color: #eaeaea;
|
||||
font-size: 12px;
|
||||
cursor: pointer;
|
||||
text-align: left;
|
||||
transition: background .15s ease;
|
||||
}
|
||||
.as-hitem:hover { background: rgba(62, 207, 142, .22); }
|
||||
.as-hitem:disabled { opacity: .6; cursor: default; }
|
||||
.as-hdate { white-space: nowrap; }
|
||||
.as-hsize { color: #a1a1aa; white-space: nowrap; }
|
||||
@media (max-width: 640px) {
|
||||
.autosave-bar { right: 12px; bottom: 76px; }
|
||||
}
|
||||
|
||||
+41
-10
@@ -204,16 +204,8 @@ async function tryRestore(): Promise<void> {
|
||||
`/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;
|
||||
}
|
||||
// 往返期间用户已开始编辑则不打扰;进页面时页面值都是工具默认值,直接恢复
|
||||
if (dirty) return;
|
||||
await nextTick();
|
||||
const applied = applyState(body.data.state);
|
||||
if (applied <= 0) return; // 字段对不上(工具改版等)则不打扰用户
|
||||
@@ -228,6 +220,45 @@ async function tryRestore(): Promise<void> {
|
||||
}
|
||||
}
|
||||
|
||||
/** 历史版本清单(右下角「找回」面板用),失败返回空数组 */
|
||||
export async function loadHistory(): Promise<{ ts: number; bytes: number }[]> {
|
||||
if (!toolKey) return [];
|
||||
try {
|
||||
const { status: st, body } = await apiFetch(
|
||||
`/draft/history?machine=${encodeURIComponent(getMachineId())}&tool=${encodeURIComponent(toolKey)}`,
|
||||
);
|
||||
if (st !== 200 || !Array.isArray(body?.data?.items)) return [];
|
||||
return body.data.items;
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/** 回填指定历史版本到当前页面(找回重新编辑),返回是否成功 */
|
||||
export async function restoreVersion(ts: number): Promise<boolean> {
|
||||
if (!toolKey || !ts) return false;
|
||||
try {
|
||||
const { status: st, body } = await apiFetch(
|
||||
`/draft/load?machine=${encodeURIComponent(getMachineId())}&tool=${encodeURIComponent(toolKey)}&ts=${ts}`,
|
||||
);
|
||||
if (st !== 200 || !body?.data?.state) return false;
|
||||
await nextTick();
|
||||
const applied = applyState(body.data.state);
|
||||
if (applied <= 0) return false;
|
||||
restored.value = true;
|
||||
dirty = false;
|
||||
hasUnsaved.value = false;
|
||||
status.value = 'saved';
|
||||
savedAt.value = ts * 1000 || Date.now();
|
||||
window.setTimeout(() => {
|
||||
restored.value = false;
|
||||
}, 4000);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function stopTimer(): void {
|
||||
if (timer !== null) {
|
||||
window.clearInterval(timer);
|
||||
|
||||
@@ -11,6 +11,7 @@ import { useRecentTools } from '@/composable/recent-tools';
|
||||
// 近期新功能亮点(手动维护,新工具上线时加一条)
|
||||
// ★铁规则:每完成一批新功能/新工具,必须在这里最前面加条目(新→旧),否则首页看不到
|
||||
const NEW_FEATURES = [
|
||||
{ path: '/qrcode-generator', icon: '🕘', name: '草稿找回历史版本', desc: '右下角自动保存条新增「找回」按钮,列出该工具近 20 份保存历史(时间精确到秒),点任意一条立即恢复成那一版继续编辑' },
|
||||
{ path: '/admin', icon: '📁', name: '后台文件管理', desc: '默认聚合所有用户文件与AI生成图片,每页50条自动分页显示总记录数,图片100×100缩略图、其他文件显示类型,全部支持单独下载' },
|
||||
{ path: '/ai-gen', icon: '🗂️', name: '图片历史铁规则', desc: '所有生图功能右侧 50×50 缩略图历史竖排、点击看大图,按登录账号/机器码只看本人的,生成即保存到后台指定目录,全部功能历史最多显示100条' },
|
||||
{ path: '/face-swap', icon: '🎭', name: 'AI 换脸', desc: '上传源人脸与目标照片,本地 AI 一键换脸(insightface 人脸检测+inswapper),授权功能支持免费试用' },
|
||||
|
||||
Reference in new issue
Block a user