| 3 | const HANDLE_NONE = -1; |
| 4 | |
| 5 | export const makeState = () => { |
| 6 | const nodes = []; |
| 7 | // Reverse lookup Element->handles for O(1) subtree sweep. WeakMap so detached refs can GC. |
| 8 | const handleByEl = new WeakMap(); |
| 9 | const bindings = []; |
| 10 | const intersectionObservers = []; |
| 11 | const resizeObservers = []; |
| 12 | const mutationObservers = []; |
| 13 | const animations = []; |
| 14 | const files = []; |
| 15 | |
| 16 | const alloc = (n) => { |
| 17 | if (n === null || n === undefined) return HANDLE_NONE; |
| 18 | nodes.push(n); |
| 19 | const h = nodes.length - 1; |
| 20 | let set = handleByEl.get(n); |
| 21 | if (!set) { set = new Set(); handleByEl.set(n, set); } |
| 22 | set.add(h); |
| 23 | return h; |
| 24 | }; |
| 25 | |
| 26 | const node = (h) => { |
| 27 | if (h < 0 || h >= nodes.length || nodes[h] === null) { |
| 28 | throw new Error('invalid DOM node handle: ' + h); |
| 29 | } |
| 30 | return nodes[h]; |
| 31 | }; |
| 32 | |
| 33 | const allocList = (list) => { |
| 34 | if (!list || list.length === 0) return ''; |
| 35 | const out = new Array(list.length); |
| 36 | for (let i = 0; i < list.length; i++) out[i] = alloc(list[i]); |
| 37 | return out.join(','); |
| 38 | }; |
| 39 | |
| 40 | // Targets: handles in `nodes[]`, listeners in `bindings[]`, running `animations[]` rooted in `el` (inclusive). Slots nulled, not spliced. |
| 41 | const cleanSubtree = (el) => { |
| 42 | const all = new Set([el, ...el.querySelectorAll('*')]); |
| 43 | for (const e of all) { |
| 44 | const set = handleByEl.get(e); |
| 45 | if (set) { |
| 46 | for (const h of set) nodes[h] = null; |
| 47 | handleByEl.delete(e); |
| 48 | } |
| 49 | } |
| 50 | for (let i = 0; i < bindings.length; i++) { |
| 51 | const b = bindings[i]; |
| 52 | if (b && all.has(b.target)) { |
| 53 | b.target.removeEventListener(b.type, b.listener, { capture: b.capture }); |
| 54 | bindings[i] = null; |
| 55 | } |
| 56 | } |
| 57 | for (let i = 0; i < animations.length; i++) { |
| 58 | const a = animations[i]; |
| 59 | if (a && a.effect && all.has(a.effect.target)) { |
| 60 | a.cancel(); |
| 61 | animations[i] = null; |
| 62 | } |