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

310 lines
16 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 }
}
// v3.26.109:写入口必须和读入口一致。桌面端 lsGet('iwb_viewport_<ws>') 走的是资料目录底座
// (IWBStorageFile.runtime),而这里原来用 IWBStorageLocal.getStore()(WebView localStorage)——
// 写进 A、读的是 B,于是关掉应用再打开视口永远是「适应视图」。统一走「文件底座优先」的写入。
const writeKey = (k, v) => {
try {
const fs = global.IWBStorageFile
const rt = (fs && typeof fs.enabled === 'function' && fs.enabled() && fs.runtime) ? fs.runtime : global.IWBStorageRuntime
if (rt && typeof rt.set === 'function') return rt.set(k, v)
const st = (typeof global.IWBStorageLocal !== 'undefined' && global.IWBStorageLocal.getStore) ? global.IWBStorageLocal.getStore() : null
if (st) st.set(k, v)
} catch (e) { /* ignore */ }
}
const flushViewport = () => {
if (!userRef.current) return
// 停靠栏/insets 还没就绪时先不写坏值,但要在 1 秒后补一次(否则这次平移就永久丢)
if (!insetsReady()) { try { setTimeout(() => { try { flushViewport() } catch (e) { /* ignore */ } }, 1000) } catch (e) { /* ignore */ } return }
const v = viewportRef.current, ws = activeWsRef.current
writeKey('iwb_viewport', v)
if (ws) writeKey('iwb_viewport_' + ws, v)
// 桌面端刚写进内存表,关窗时要把内存表尽快落盘(flush 异步,尽力而为)
try { const fs = global.IWBStorageFile; if (fs && typeof fs.flush === 'function') fs.flush().catch(function () {}) } 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)
global.addEventListener('pagehide', h) // 桌面端关窗不一定有 beforeunload,补一个
if (global.document) global.document.addEventListener('visibilitychange', () => { if (global.document.visibilityState === 'hidden') h() })
return () => {
global.removeEventListener('beforeunload', h)
global.removeEventListener('pagehide', 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])
}
/* 图库缩略图空闲预热(v3.26.134,2026-11-30)
* 背景:宫格第一次打开要给每张图做 320 缩略图(139 张 × 200~600ms),只能排队等。
* 这里在启动后空闲时按 1 路补齐,之后打开就是全命中。
* 纪律:生成中/保存中让路;每张之间让出主线程;单张失败不重试;进度写进 state(诊断读)。
* 入参:len(outputs 条数) / refs / storage()=>IWBStorageFile / state(模块级对象,诊断共享)
*/
function useGalleryPrewarm (d) {
const o = d || {}
useEffect(() => {
let alive = true
const run = async () => {
const st = o.state
const F = typeof o.storage === 'function' ? o.storage() : null
if (!alive || !st || st.busy || !F || typeof F.galleryThumbOfEntry !== 'function') return
const n = Number(o.len) || 0
if (!n || st.forN === n) return
const list = typeof o.list === 'function' ? o.list() : []
if (!list.length) return
st.busy = true; st.forN = n; st.done = 0; st.total = list.length
try {
for (const f of list) {
if (!alive) break
const refs = o.refs || {}
// 用户正在平移/拖拽/缩放时暂停预热:缩略图生成会解码 320px 图,抢主线程会让手势掉帧。
while (alive && (refs.pan || refs.drag || refs.resize || refs.box)) await new Promise((r) => setTimeout(r, 250))
if (!alive) break
if (refs.genRuns && refs.genRuns.size) break
if (refs.saving) { await new Promise((r) => setTimeout(r, 1200)); continue }
try { await F.galleryThumbOfEntry(f, 320) } catch (e) { /* 单张失败忽略 */ }
st.done++
await new Promise((r) => setTimeout(r, 120))
}
} finally { st.busy = false }
}
const kick = () => { Promise.resolve().then(run).catch(() => {}) }
const t = setTimeout(() => {
if (!alive) return
if (typeof requestIdleCallback === 'function') requestIdleCallback(kick, { timeout: 8000 })
else kick()
}, 30000)
return () => { alive = false; clearTimeout(t) }
}, [o.len])
}
global.IWBWorkbenchHooks = { useViewportPersistence, useNotifications, useStoragePersist, useAutoBackup, useExportReminder, useOutputsSync, useGalleryPrewarm }
})(typeof window !== 'undefined' ? window : globalThis)