Files
image-workbench-desktop/src/ui-workbench-hooks.js
T

226 lines
11 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)
let flushCache = null
const flushViewport = () => {
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(() => {
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, setNotice] = useState(null)
const [toast, setToast] = useState(null)
const toastTimer = useRef(null)
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)