// 状态模型 epic · Pilot 2 第一片:画布会话容器(sessions Map + LRU + 激活 id + 驱逐策略)→ src/。 // // 语义 1:1 对齐 app.js 既有实现(openSession / ensureSessionFor / 驱逐循环): // · 驱逐上限 W_SESSION_MAX=5,**绝不驱逐激活 session**,按 LRU 顺序(最旧优先) // · 被驱逐时回调 onEvict(id):**在从容器移除前**调用,故回调仍可取到该 session // (app.js 里是回收该 session 的 objectURL,需要读它的 nodes) // · 第二片已接线 app.js(refs 不再自持 sessions/LRU/激活 id,store 是唯一权威) ;(function (global) { 'use strict' const W_SESSION_MAX = 5 const createSessionsStore = (options) => { const opt = options || {} const makeSession = typeof opt.makeSession === 'function' ? opt.makeSession : ((id) => ({ id })) const onEvict = typeof opt.onEvict === 'function' ? opt.onEvict : null const log = typeof opt.log === 'function' ? opt.log : (() => {}) const sessions = new Map() let lru = [] let activeId = '' const keyOf = (id) => String(id === undefined || id === null ? '' : id) const get = (id) => sessions.get(keyOf(id)) || null const has = (id) => sessions.has(keyOf(id)) const ids = () => Array.from(sessions.keys()) const size = () => sessions.size const getActiveId = () => activeId const lruIds = () => lru.slice() const ensure = (id, seed) => { const key = keyOf(id) if (!key) return null let s = sessions.get(key) if (!s) { s = makeSession(key) if (seed && typeof seed === 'object') { s.nodes = seed.nodes || [] s.edges = seed.edges || [] s.groups = seed.groups || [] } sessions.set(key, s) } return s } const touch = (id) => { const key = keyOf(id) if (!key) return lru.slice() lru = lru.filter((x) => x !== key).concat([key]) return lru.slice() } const evict = () => { const evicted = [] while (lru.length > W_SESSION_MAX) { const oldest = lru[0] if (oldest === activeId) break // 先在容器仍持有该 session 时回调(宿主据此回收其 objectURL 等资源),再从容器移除 if (onEvict) { try { onEvict(oldest) } catch (e) { log('sessions-evict-failed', oldest) } } lru.shift() sessions.delete(oldest) evicted.push(oldest) } return evicted } const open = (id) => { const key = keyOf(id) if (!key) return null const s = ensure(key) activeId = key touch(key) evict() return s } const setActive = (id) => { const key = keyOf(id) activeId = key if (key) touch(key) return activeId } const drop = (id) => { const key = keyOf(id) sessions.delete(key) lru = lru.filter((x) => x !== key) if (activeId === key) activeId = '' } const markAllClean = () => { for (const s of sessions.values()) if (s && typeof s === 'object') s.dirty = false } const dirtyIds = () => { const out = [] for (const [id, s] of sessions) if (s && typeof s === 'object' && s.dirty) out.push(id) return out } return { get, has, ids, size, getActiveId, lruIds, ensure, open, setActive, touch, evict, drop, markAllClean, dirtyIds, W_SESSION_MAX, } } global.IWBSessionsStore = Object.freeze({ create: createSessionsStore, W_SESSION_MAX }) })(typeof window !== 'undefined' ? window : globalThis)