onMOunt on UnMount

This commit is contained in:
2026-04-08 15:31:16 +02:00
parent d586af52b6
commit 7350633a63

View File

@@ -1,15 +1,16 @@
// sigpro
const doc = typeof document !== "undefined" ? document : null; const doc = typeof document !== "undefined" ? document : null;
const isArr = Array.isArray, assign = Object.assign, isFunc = (f) => typeof f === "function", isObj = (o) => typeof o === "object" && o !== null; const isArr = Array.isArray, assign = Object.assign, isFunc = (f) => typeof f === "function", isObj = (o) => typeof o === "object" && o !== null;
const ensureNode = (n) => n?._isRuntime ? n.container : (n instanceof Node ? n : doc.createTextNode(String(n ?? ""))); const ensureNode = (n) => n?._isRuntime ? n.container : (n instanceof Node ? n : doc.createTextNode(String(n ?? "")));
// --- STATE & SYSTEM VARIABLES --- let activeEffect = null, currentCtx = null, isFlushing = false;
let activeEffect = null, currentOwner = null, currentCtx = null, isFlushing = false; let pendingMounts = [];
const effectQueue = new Set(), MOUNTED_NODES = new WeakMap(); const effectQueue = new Set(), MOUNTED_NODES = new WeakMap();
const runCleanups = (s) => { s?.forEach(f => f()); s?.clear(); }; const runCleanups = (s) => { s?.forEach(f => f()); s?.clear(); };
const clearDeps = (e) => { e._deps.forEach(d => d.delete(e)); e._deps.clear(); }; const clearDeps = (e) => { e._deps.forEach(d => d.delete(e)); e._deps.clear(); };
const onUnmount = (fn) => currentOwner && currentOwner.cleanups.add(fn);
export const onMount = (fn) => currentCtx?.m.push(fn);
export const onUnmount = (fn) => currentCtx?.u.add(fn);
const cleanupNode = (node) => { const cleanupNode = (node) => {
if (node._cleanups) runCleanups(node._cleanups); if (node._cleanups) runCleanups(node._cleanups);
@@ -42,7 +43,6 @@ const trackUpdate = (subs, trigger = false) => {
} }
}; };
// --- THE ATOM (Internal Kernel) ---
const _sub = (fn, cb) => { const _sub = (fn, cb) => {
const e = () => { const e = () => {
if (e._deleted) return; if (e._deleted) return;
@@ -60,20 +60,14 @@ const _sub = (fn, cb) => {
return e; return e;
}; };
// --- PUBLIC API ---
const ignore = (fn) => { const ignore = (fn) => {
const p = activeEffect; const p = activeEffect; activeEffect = null;
activeEffect = null; try { return fn(); } finally { activeEffect = p; }
try { return fn(); }
finally { activeEffect = p; }
}; };
const Watch = (target, cb) => { const Watch = (target, cb) => {
const isA = isArr(target); const isA = isArr(target);
return _sub( return _sub(isA ? () => target.forEach(s => isFunc(s) ? s() : s) : target, isA ? () => ignore(cb) : null);
isA ? () => target.forEach(s => isFunc(s) ? s() : s) : target,
isA ? () => ignore(cb) : null
);
}; };
const Share = (k, v) => currentCtx && (currentCtx.p[k] = v); const Share = (k, v) => currentCtx && (currentCtx.p[k] = v);
@@ -118,7 +112,6 @@ const Tag = (tag, props = {}, children = []) => {
const isSVG = /^(svg|path|circle|rect|line|polyline|polygon|g|defs|text|tspan|use)$/.test(tag); const isSVG = /^(svg|path|circle|rect|line|polyline|polygon|g|defs|text|tspan|use)$/.test(tag);
const el = isSVG ? doc.createElementNS("http://www.w3.org/2000/svg", tag) : doc.createElement(tag); const el = isSVG ? doc.createElementNS("http://www.w3.org/2000/svg", tag) : doc.createElement(tag);
el._cleanups = new Set(); el._cleanups = new Set();
for (let [k, v] of Object.entries(props)) { for (let [k, v] of Object.entries(props)) {
if (k === "ref") { isFunc(v) ? v(el) : (v.current = el); continue; } if (k === "ref") { isFunc(v) ? v(el) : (v.current = el); continue; }
if (k.startsWith("on")) { if (k.startsWith("on")) {
@@ -135,7 +128,6 @@ const Tag = (tag, props = {}, children = []) => {
} }
} else el.setAttribute(k, v); } else el.setAttribute(k, v);
} }
const append = (c) => { const append = (c) => {
if (isArr(c)) return c.forEach(append); if (isArr(c)) return c.forEach(append);
if (isFunc(c)) { if (isFunc(c)) {
@@ -151,15 +143,16 @@ const Tag = (tag, props = {}, children = []) => {
}; };
const Render = (fn) => { const Render = (fn) => {
const cleanups = new Set(), prevOwner = currentOwner, prevCtx = currentCtx; const prevCtx = currentCtx;
currentCtx = { p: { ...(prevCtx?.p || {}) } }; const ctx = { p: { ...(prevCtx?.p || {}) }, u: new Set(), m: [] };
currentCtx = ctx;
const container = doc.createElement("div"); const container = doc.createElement("div");
container.style.display = "contents"; container.style.display = "contents";
currentOwner = { cleanups }; const res = fn();
const res = fn({ onCleanup: (f) => cleanups.add(f) }); if (ctx.m.length) pendingMounts.push(...ctx.m);
(isArr(res) ? res : [res]).forEach(r => container.appendChild(ensureNode(r))); (isArr(res) ? res : [res]).forEach(r => container.appendChild(ensureNode(r)));
currentCtx = prevCtx; currentOwner = prevOwner; currentCtx = prevCtx;
return { _isRuntime: true, container, destroy: () => { runCleanups(cleanups); cleanupNode(container); container.remove(); } }; return { _isRuntime: true, container, destroy: () => { runCleanups(ctx.u); cleanupNode(container); container.remove(); } };
}; };
const If = (cond, t, f = null, trans = null) => { const If = (cond, t, f = null, trans = null) => {
@@ -174,6 +167,7 @@ const If = (cond, t, f = null, trans = null) => {
view = Render(() => isFunc(b) ? b() : b); view = Render(() => isFunc(b) ? b() : b);
root.appendChild(view.container); root.appendChild(view.container);
if (trans?.in) trans.in(view.container); if (trans?.in) trans.in(view.container);
if (root.isConnected) { const ms = [...pendingMounts]; pendingMounts = []; ms.forEach(f => f()); }
} }
}); });
return root; return root;
@@ -197,6 +191,7 @@ const For = (src, itemFn, keyFn) => {
anchor = v.container; anchor = v.container;
} }
cache = next; cache = next;
if (root.isConnected && pendingMounts.length) { const ms = [...pendingMounts]; pendingMounts = []; ms.forEach(f => f()); }
}); });
return root; return root;
}; };
@@ -207,13 +202,11 @@ const Router = (routes) => {
window.addEventListener("hashchange", () => path(getHash())); window.addEventListener("hashchange", () => path(getHash()));
const outlet = Tag("div", { class: "router-outlet" }); const outlet = Tag("div", { class: "router-outlet" });
let currentView = null; let currentView = null;
_sub(path, async (cur) => { _sub(path, async (cur) => {
const route = routes.find(r => { const route = routes.find(r => {
const p1 = r.path.split("/").filter(Boolean), p2 = cur.split("/").filter(Boolean); const p1 = r.path.split("/").filter(Boolean), p2 = cur.split("/").filter(Boolean);
return p1.length === p2.length && p1.every((p, i) => p.startsWith(":") || p === p2[i]); return p1.length === p2.length && p1.every((p, i) => p.startsWith(":") || p === p2[i]);
}) || routes.find(r => r.path === "*"); }) || routes.find(r => r.path === "*");
if (route) { if (route) {
let comp = route.component; let comp = route.component;
if (isFunc(comp) && comp.toString().includes('import')) comp = (await comp()).default; if (isFunc(comp) && comp.toString().includes('import')) comp = (await comp()).default;
@@ -223,6 +216,7 @@ const Router = (routes) => {
Router.params(params); Router.params(params);
currentView = Render(() => isFunc(comp) ? comp(params) : comp); currentView = Render(() => isFunc(comp) ? comp(params) : comp);
outlet.appendChild(currentView.container); outlet.appendChild(currentView.container);
const ms = [...pendingMounts]; pendingMounts = []; ms.forEach(f => f());
} }
}); });
return outlet; return outlet;
@@ -237,10 +231,12 @@ const Mount = (comp, target) => {
const t = typeof target === "string" ? doc.querySelector(target) : target; const t = typeof target === "string" ? doc.querySelector(target) : target;
if (!t) return; if (MOUNTED_NODES.has(t)) MOUNTED_NODES.get(t).destroy(); if (!t) return; if (MOUNTED_NODES.has(t)) MOUNTED_NODES.get(t).destroy();
const inst = Render(isFunc(comp) ? comp : () => comp); const inst = Render(isFunc(comp) ? comp : () => comp);
t.replaceChildren(inst.container); MOUNTED_NODES.set(t, inst); return inst; t.replaceChildren(inst.container);
const ms = [...pendingMounts]; pendingMounts = []; ms.forEach(f => f());
MOUNTED_NODES.set(t, inst); return inst;
}; };
const SigPro = Object.freeze({ $, $$, Share, Use, Watch, Tag, Render, If, For, Router, Mount, ignore, onUnmount }); const SigPro = Object.freeze({ $, $$, Share, Use, Watch, Tag, Render, If, For, Router, Mount, ignore, onMount, onUnmount });
if (typeof window !== "undefined") { if (typeof window !== "undefined") {
Object.assign(window, SigPro); Object.assign(window, SigPro);
@@ -248,5 +244,5 @@ if (typeof window !== "undefined") {
.split(" ").forEach(t => window[t[0].toUpperCase() + t.slice(1)] = (p, c) => SigPro.Tag(t, p, c)); .split(" ").forEach(t => window[t[0].toUpperCase() + t.slice(1)] = (p, c) => SigPro.Tag(t, p, c));
} }
export { $, $$, Share, Use, Watch, Tag, Render, If, For, Router, Mount, ignore, onUnmount }; export { $, $$, Share, Use, Watch, Tag, Render, If, For, Router, Mount, ignore, onMount, onUnmount };
export default SigPro; export default SigPro;