Files
image-workbench-desktop/src/ui-workbench-hooks.js
T
qiqi 8035c01fb7 fix(canvas): 停靠栏未就绪时不落盘视口(修 6 条 e2e 超时)+ 4 条用例按现 UI 修正
根因(trace 定位,6 条同一原因):
首页视图里启动 fit 早于停靠栏挂载(--iwb-dock-l 首帧为空)⇒ 算出 ins=0 的坏视口
(实测 translate(-92,-84));这份坏值被 useViewportPersistence 落盘,打开画布时又被当作
「用户保存的视口」恢复 ⇒ 节点停在 x=29(压在 318px 左栏下),dblclick 命中浏览器面板的
.iwb-cwv-url / .iwb-cwv-empty,Playwright 重试到 30s 超时。
修法:flushViewport 增加 insetsReady 门槛(--iwb-dock-l 为空串时跳过落盘);
画布打开后 loadWsInto 走 doFit,此时占位就绪,落盘的是正确视口。

4 条用例按现 UI 修正:
- tooltip-labels ②:单选气泡现为 改名/复制/删除/添加到提示词库…(收藏只在多选气泡)
- image-original:收藏入口已收进「选中操作 ▸」子菜单(且需先选中节点)
- resume-scope:运行入口已收进「该节点 ▸」子菜单
- download-cors:同源代理 /api/img 已随网页版删除,桌面走原生 HTTP 另存为 ⇒ 该条标 fixme(需 Tauri 环境)

验证:
- 组 A(typing-perf / storage-incremental / close-flush / history-sweep)6/6 绿
- 组 B(image-original / resize-perf / tooltip-labels / resume-scope / download-cors)12/12 绿
- verify:ci 全绿(facts 数字已 sync)
- 已知红基线 17 → 7 条(只剩 clipboard-audit 3 + image-memory-parity 4,均为环境限制)
2026-11-27 07:01:06 +08:00

251 lines
13 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
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.
/* Workbench 状态簇 hooks(阶段二,2026-11-07)
*
* 从 app.js 的 `Workbench()` 抽出的自洽状态簇。纪律:
* ① hook 内部**只能**访问参数与全局(React / global API),不得闭包 Workbench 的其它局部变量
* ② 返回值解构后**沿用原变量名**,调用点与下游 JSX / handler 零改动
* ③ 每抽一个就下调 tests/source-text-ratchet-test.js 的 MAX_WORKBENCH_LINES
*/
;(function (global) {
'use strict'
const React = global.React || {}
const useEffect = React.useEffect
const useState = React.useState
const useRef = React.useRef
const useMemo = React.useMemo
/* 视口持久化(自 Workbench 抽出)
* - 手势停下 300ms 后写一次 localStorage(避免每帧写)
* - 离开页面前 beforeunload 兜底落盘最新视口
* 入参:activeWsId(当前画布 id,随画布切换写入分板键)、viewport(当前视口)
* 返回:viewportRef / activeWsRef(实时镜像)、flushViewport(立即落盘)
*/
function useViewportPersistence (activeWsId, viewport) {
const viewportRef = useRef(viewport); viewportRef.current = viewport
const activeWsRef = useRef(activeWsId); activeWsRef.current = activeWsId
const saveTimer = useRef(null)
// 2026-11-27:首帧的「初始默认视口」不能落盘。
// 否则下次打开画布会把它当成「用户保存的视口」,跳过 doFit ⇒ 节点留在默认位置(被停靠栏盖住)。
const mountedRef = useRef(false) // 首次 effect 运行 = 还没发生任何视口变化
const userRef = useRef(false) // 发生过「适应视图 / 用户平移缩放」才算真实视口
let flushCache = null
// 2026-11-27:停靠栏还没挂载时(--iwb-dock-l 为空串)算出来的视口是「ins=0 的坏值」,
// 不能落盘 —— 否则打开画布时会被当成用户保存的视口恢复,节点永远压在侧栏底下。
const insetsReady = () => {
try {
if (typeof global.getComputedStyle !== 'function' || !global.document) return false
return String(global.getComputedStyle(global.document.documentElement).getPropertyValue('--iwb-dock-l') || '').trim() !== ''
} catch (e) { return false }
}
const flushViewport = () => {
if (!userRef.current) return
if (!insetsReady()) return
const v = viewportRef.current, ws = activeWsRef.current
try {
const st = (typeof global.IWBStorageLocal !== 'undefined' && global.IWBStorageLocal.getStore) ? global.IWBStorageLocal.getStore() : null
if (st) {
st.set('iwb_viewport', v)
if (ws) st.set('iwb_viewport_' + ws, v)
}
} catch (e) { /* ignore */ }
}
useEffect(() => {
if (!mountedRef.current) { mountedRef.current = true; return } // 跳过初始值
userRef.current = true
clearTimeout(saveTimer.current)
saveTimer.current = setTimeout(flushViewport, 300)
return () => clearTimeout(saveTimer.current)
}, [viewport])
useEffect(() => {
const h = () => { if (saveTimer.current) clearTimeout(saveTimer.current); flushViewport() }
global.addEventListener('beforeunload', h)
return () => global.removeEventListener('beforeunload', h)
}, [])
return { viewportRef, activeWsRef, flushViewport }
}
/* 通知通道(notice + toast,自 Workbench 抽出)
* - notice:常驻于顶栏的状态条(错误/成功)
* - toast:2.6s 自动消失的浮层提示
* - 同时注册两条模块级 sink(导入失败兜底 / 通用失败上报),保证模块层失败**可见**而非静默
* 入参:{ sinks: [{ obj, defaultText }] } —— 形如 { fn } 的可写对象由宿主提供
* 返回:notice / setNotice / toast / setToast / showToast
*/
function useNotifications (opts) {
const [notice, setNoticeState] = useState(null)
const [toast, setToast] = useState(null)
const toastTimer = useRef(null)
const noticeTimer = useRef(null)
/* 错误/进行中提示 5.2s 自动收(2026-11-26)。
* 旧行为只有 toast 会消失,notice 会一直挂在状态栏 —— 粘贴失败那句"剪贴板里没有可粘贴的内容"
* 粘在顶部不动,用户过一会儿再看会以为功能坏了。成功提示(ok)保持常驻,它是"最后一次操作结果"。 */
const setNotice = (n) => {
clearTimeout(noticeTimer.current)
setNoticeState(n)
if (n && n.type && n.type !== 'ok') noticeTimer.current = setTimeout(() => setNoticeState(null), 5200)
}
const showToast = (text, type) => {
clearTimeout(toastTimer.current)
setToast({ text, type: type || 'ok' })
toastTimer.current = setTimeout(() => setToast(null), 2600)
}
const sinks = (opts && opts.sinks) || []
useEffect(() => {
sinks.forEach((s) => {
if (!s || !s.obj) return
s.obj.fn = (p) => { try { setNotice({ type: (p && p.type === 'ok') ? 'ok' : 'err', text: (p && p.text) || s.defaultText || '' }) } catch (e) { /* ignore */ } }
})
return () => { sinks.forEach((s) => { if (s && s.obj) s.obj.fn = null }) }
}, [])
return { notice, setNotice, toast, setToast, showToast }
}
/* 持久化存储状态(2026-11-07)
* - 延迟 3s 请求一次 navigator.storage.persist(),避开首屏
* - 拒绝/失败**不打扰用户**,只返回状态供「设置 → 诊断」展示
* 返回 { status: 'unknown'|'granted'|'denied'|'unsupported', error? }
*/
function useStoragePersist (delayMs) {
const [persist, setPersist] = useState({ status: 'unknown' })
useEffect(() => {
let alive = true
const t = setTimeout(() => {
try {
const health = global.IWBStorageHealth || null
if (!health || typeof health.requestPersistent !== 'function') return
// 两条链(持久化授权 / 配额)并行写同一 state ⇒ 一律用**函数式合并**,
// 否则 estimate 先回来时会被 requestPersistent 的整对象 set 覆盖掉配额(2026-11-07 竞态修复)
Promise.resolve(health.requestPersistent())
.then((r) => { if (alive && r) setPersist((p) => Object.assign({}, p, r)) })
.catch((e) => { if (alive) setPersist((p) => Object.assign({}, p, { status: 'denied', error: String((e && e.message) || e) })) })
// 配额信息(2026-11-07 收尾):estimate() 加了就要有人消费 —— 供「设置 → 诊断」
// 显示「存储配额 已用/总量」。浏览器不支持时保持 undefined,诊断页不显示该项。
if (typeof health.estimate === 'function') {
Promise.resolve(health.estimate())
.then((q) => { if (alive && q) setPersist((p) => Object.assign({}, p, { usage: q.usage, quota: q.quota })) })
.catch(() => {})
}
} catch (e) { /* 环境不支持:保持 unknown */ }
}, Number(delayMs) || 3000)
return () => { alive = false; clearTimeout(t) }
}, [])
return persist
}
/* 本地自动备份(2026-11-07)
* - 页面加载后延迟 delayMs,若距上次备份 ≥24h 则做一次 localStorage 快照 → IndexedDB kv
* - 保留最近 7 份;返回 list/restore/saveNow 供「设置 → 备份」使用
* - 注意:只防误删/键损坏,**不防浏览器清空整个站点数据**(那只能靠导出文件)
*/
function useAutoBackup (delayMs) {
const [state, setState] = useState({ list: [], lastAt: 0, busy: false, error: null, savedAt: 0 })
const beRef = useRef(null)
const getBe = () => {
if (beRef.current) return beRef.current
try {
const f = global.IWBStorageAutoBackup
if (!f || typeof f.create !== 'function') return null
beRef.current = f.create({ version: (global.__IWB_BUILD_META__ && global.__IWB_BUILD_META__.version) || '' })
} catch (e) { beRef.current = null }
return beRef.current
}
const refresh = React.useCallback(async () => {
const be = getBe()
if (!be) return
try {
const list = await be.list()
setState((s) => Object.assign({}, s, { list: list, lastAt: list.length ? list[0].at : 0 }))
} catch (e) { /* 列表读失败不打扰用户 */ }
}, [])
const saveNow = React.useCallback(async () => {
const be = getBe()
if (!be) return { ok: false, error: 'indexedDB 不可用' }
setState((s) => Object.assign({}, s, { busy: true, error: null }))
const r = await be.save('manual').catch((e) => ({ ok: false, error: String((e && e.message) || e) }))
setState((s) => Object.assign({}, s, { busy: false, error: r.ok ? null : r.error, savedAt: r.ok ? r.at : s.savedAt }))
await refresh()
return r
}, [refresh])
const restore = React.useCallback(async (name) => {
const be = getBe()
if (!be) return { ok: false, error: 'indexedDB 不可用' }
const r = await be.restore(name).catch((e) => ({ ok: false, error: String((e && e.message) || e) }))
return r
}, [])
useEffect(() => {
// 桌面端(资料目录已生效)不做自动快照:数据本身就落盘了,再存一份 IndexedDB 快照是纯冗余
// 调用方传 0 表示关闭;仍保留手动「立即备份」与列表读取。
if (!(Number(delayMs) > 0)) return undefined
let alive = true
const t = setTimeout(async () => {
try {
const be = getBe()
if (!be) return
await refresh()
if (!alive) return
if (await be.due()) { await be.save('auto'); await refresh() }
} catch (e) { /* 自动备份失败绝不能影响使用 */ }
}, Number(delayMs) || 30000)
return () => { alive = false; clearTimeout(t) }
}, [refresh])
return { autoBackup: state, autoBackupSave: saveNow, autoBackupRestore: restore, autoBackupRefresh: refresh }
}
/* 导出备份提醒(2026-11-07)
* 自动备份与数据同在浏览器里,**清站点数据时一起没** —— 唯一的异地保险是"导出到磁盘"。
* 规则:有画布数据 且 距上次导出 > days 天 ⇒ 轻提示;当天关闭过就不再出现(不弹窗不打断)。
* 键:iwb_backup_last_export_at(导出成功时由备份弹窗写)/ iwb_backup_remind_dismiss(关闭日)
*/
function useExportReminder (opts) {
const days = Number((opts && opts.days) || 14)
const hasData = !!(opts && opts.hasData)
const [dismissTick, setDismissTick] = useState(0)
const st = () => (global.IWBStorageLocal && typeof global.IWBStorageLocal.getStore === 'function') ? global.IWBStorageLocal.getStore() : null
const info = React.useMemo(() => {
const s2 = st()
const last = s2 ? Number(s2.rawGet('iwb_backup_last_export_at', 0)) || 0 : 0
const dismissed = s2 ? String(s2.rawGet('iwb_backup_remind_dismiss', '') || '') : ''
const today = new Date().toISOString().slice(0, 10)
// 从未导出过(last=0)**不提示**(2026-11-07 修正):新用户第一天就催是打扰;
// 且横幅会占画布顶部空间,实测把「视口中心落点/适应视图」两条 e2e 顶偏了。
// 提醒只面向"导出过一次、之后 ≥14 天没再导出"的场景。
if (!last) return { show: false, ageDays: null }
const ageDays = Math.floor((Date.now() - last) / 86400000)
return { show: hasData && ageDays > days && dismissed !== today, ageDays }
}, [hasData, days, dismissTick])
const dismiss = React.useCallback(() => {
const s2 = st()
if (s2) s2.rawSet('iwb_backup_remind_dismiss', new Date().toISOString().slice(0, 10))
setDismissTick((v) => v + 1)
}, [])
return { show: info.show, ageDays: info.ageDays, dismiss }
}
/* 跨标签页输出索引同步(P1):其它标签写 localStorage[key](如 iwb_web_outputs)后,
* 本标签收到 storage 事件即刷新图库;BroadcastChannel 兜底。onSync 用 ref 保持最新,避免每次渲染重绑监听。 */
function useOutputsSync (key, channelName, onSync) {
const cbRef = useRef(onSync); cbRef.current = onSync
useEffect(() => {
const fire = () => { try { if (cbRef.current) cbRef.current() } catch (e) { /* ignore */ } }
const handler = (e) => { if (!e || e.key === key || e.key === null) fire() }
global.addEventListener('storage', handler)
let bc = null
try {
if (typeof global.BroadcastChannel === 'function') {
bc = new global.BroadcastChannel(channelName || 'iwb_outputs_sync')
bc.onmessage = fire
}
} catch (e) { /* ignore */ }
return () => {
global.removeEventListener('storage', handler)
try { if (bc) bc.close() } catch (e) { /* ignore */ }
}
}, [key, channelName])
}
global.IWBWorkbenchHooks = { useViewportPersistence, useNotifications, useStoragePersist, useAutoBackup, useExportReminder, useOutputsSync }
})(typeof window !== 'undefined' ? window : globalThis)