kk1
This commit is contained in:
311
sigpro.deep.js
Normal file
311
sigpro.deep.js
Normal file
@@ -0,0 +1,311 @@
|
||||
/**
|
||||
* SigPro v2.1 - Minimalista pero seguro (con árbol de owners y limpieza completa)
|
||||
*/
|
||||
const SigPro = (() => {
|
||||
const doc = typeof document !== "undefined" ? document : null;
|
||||
const isArr = Array.isArray, assign = Object.assign, isFunc = (f) => typeof f === "function", isObj = (o) => o && typeof o === "object";
|
||||
const ensureNode = (n) => n?._isRuntime ? n.container : (n instanceof Node ? n : doc.createTextNode(n == null ? "" : String(n)));
|
||||
|
||||
// --- ÁRBOL DE CONTEXTO (OWNER TREE) minimalista ---
|
||||
let activeOwner = null, activeEffect = null, isFlushing = false;
|
||||
const effectQueue = new Set(), MOUNTED_NODES = new WeakMap();
|
||||
|
||||
const createOwner = () => {
|
||||
const o = { c: new Set(), x: new Set(), d: new Set(), depth: activeOwner ? activeOwner.depth + 1 : 0 };
|
||||
if (activeOwner) activeOwner.c.add(o);
|
||||
return o;
|
||||
};
|
||||
|
||||
const dispose = (o) => {
|
||||
if (!o) return;
|
||||
o.c?.forEach(dispose); // hijos
|
||||
o.x?.forEach(fn => fn()); // limpiezas
|
||||
o.d?.forEach(s => s.delete(o)); // desuscribir señales
|
||||
o.c?.clear(); o.x?.clear(); o.d?.clear();
|
||||
};
|
||||
|
||||
const runWithOwner = (o, cb) => {
|
||||
const prev = activeOwner; activeOwner = o;
|
||||
try { return cb(); } finally { activeOwner = prev; }
|
||||
};
|
||||
|
||||
const onUnmount = (fn) => activeOwner?.x.add(fn);
|
||||
|
||||
// --- Limpieza de nodos (simple y recursiva) ---
|
||||
const cleanupNode = (node) => {
|
||||
if (node._cleanups) {
|
||||
node._cleanups.forEach(fn => fn());
|
||||
node._cleanups.clear();
|
||||
}
|
||||
if (node._owner) dispose(node._owner);
|
||||
if (node.childNodes) node.childNodes.forEach(cleanupNode);
|
||||
};
|
||||
|
||||
// --- Scheduler ---
|
||||
const flush = () => {
|
||||
if (isFlushing) return; isFlushing = true;
|
||||
const sorted = Array.from(effectQueue).sort((a, b) => a.depth - b.depth);
|
||||
effectQueue.clear();
|
||||
sorted.forEach(e => !e._deleted && e.run());
|
||||
isFlushing = false;
|
||||
};
|
||||
|
||||
const trackUpdate = (subs, trigger = false) => {
|
||||
if (!trigger && activeEffect && !activeEffect._deleted) {
|
||||
subs.add(activeEffect);
|
||||
activeEffect.d.add(subs);
|
||||
} else if (trigger) {
|
||||
subs.forEach(e => {
|
||||
if (e === activeEffect || e._deleted) return;
|
||||
if (e._isComputed) { e.markDirty(); if (e._subs) trackUpdate(e._subs, true); }
|
||||
else effectQueue.add(e);
|
||||
});
|
||||
if (!isFlushing) queueMicrotask(flush);
|
||||
}
|
||||
};
|
||||
|
||||
const untrack = (fn) => {
|
||||
const p = activeEffect; activeEffect = null;
|
||||
try { return fn(); } finally { activeEffect = p; }
|
||||
};
|
||||
|
||||
// --- CORE API (señales, efectos, reactivo) ---
|
||||
const $ = (val, key = null) => {
|
||||
const subs = new Set();
|
||||
if (isFunc(val)) {
|
||||
let cache, dirty = true;
|
||||
const e = createOwner();
|
||||
assign(e, { _isComputed: true, _subs: subs, markDirty: () => (dirty = true) });
|
||||
e.run = () => {
|
||||
if (e._deleted) return;
|
||||
dispose(e);
|
||||
const prevE = activeEffect; activeEffect = e;
|
||||
runWithOwner(e, () => {
|
||||
const next = val();
|
||||
if (!Object.is(cache, next) || dirty) { cache = next; dirty = false; trackUpdate(subs, true); }
|
||||
});
|
||||
activeEffect = prevE;
|
||||
};
|
||||
onUnmount(() => { e._deleted = true; dispose(e); subs.clear(); });
|
||||
return () => { if (dirty) e.run(); trackUpdate(subs); return cache; };
|
||||
}
|
||||
if (key) try { val = JSON.parse(localStorage.getItem(key)) ?? val; } catch(e) {}
|
||||
return (...args) => {
|
||||
if (args.length) {
|
||||
const next = isFunc(args[0]) ? args[0](val) : args[0];
|
||||
if (!Object.is(val, next)) {
|
||||
val = next; if (key) localStorage.setItem(key, JSON.stringify(val));
|
||||
trackUpdate(subs, true);
|
||||
}
|
||||
}
|
||||
trackUpdate(subs); return val;
|
||||
};
|
||||
};
|
||||
|
||||
const $$ = (obj, cache = new WeakMap()) => {
|
||||
if (!isObj(obj)) return obj;
|
||||
if (cache.has(obj)) return cache.get(obj);
|
||||
const subs = {};
|
||||
const proxy = new Proxy(obj, {
|
||||
get: (t, k) => { trackUpdate(subs[k] ??= new Set()); return isObj(t[k]) ? $$(t[k], cache) : t[k]; },
|
||||
set: (t, k, v) => { if (!Object.is(t[k], v)) { t[k] = v; if (subs[k]) trackUpdate(subs[k], true); } return true; }
|
||||
});
|
||||
cache.set(obj, proxy); return proxy;
|
||||
};
|
||||
|
||||
const Watch = (target, cb) => {
|
||||
const explicit = isArr(target), e = createOwner();
|
||||
e.run = () => {
|
||||
if (e._deleted) return;
|
||||
dispose(e);
|
||||
const prevE = activeEffect; activeEffect = e;
|
||||
runWithOwner(e, () => {
|
||||
explicit ? (untrack(cb), target.forEach(d => isFunc(d) && d())) : cb();
|
||||
});
|
||||
activeEffect = prevE;
|
||||
};
|
||||
onUnmount(() => { e._deleted = true; dispose(e); });
|
||||
e.run();
|
||||
return () => { e._deleted = true; dispose(e); };
|
||||
};
|
||||
|
||||
// --- RENDERER (Tag, Render, If, For) con limpieza total ---
|
||||
const Tag = (tag, props = {}, children = []) => {
|
||||
if (props instanceof Node || isArr(props) || !isObj(props)) { children = props; props = {}; }
|
||||
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);
|
||||
el._cleanups = new Set(); // para limpieza independiente
|
||||
|
||||
for (let [k, v] of Object.entries(props)) {
|
||||
if (k === "ref") { isFunc(v) ? v(el) : (v.current = el); continue; }
|
||||
if (k.startsWith("on")) {
|
||||
const ev = k.slice(2).toLowerCase();
|
||||
el.addEventListener(ev, v);
|
||||
const off = () => el.removeEventListener(ev, v);
|
||||
el._cleanups.add(off);
|
||||
onUnmount(off);
|
||||
} else if (isFunc(v)) {
|
||||
const stop = Watch(() => {
|
||||
const val = v();
|
||||
const safe = (k === 'src' || k === 'href') && String(val).includes('javascript:') ? '#' : val;
|
||||
if (k === "class") el.className = safe || "";
|
||||
else if (safe == null || safe === false) el.removeAttribute(k);
|
||||
else el.setAttribute(k, safe === true ? "" : safe);
|
||||
});
|
||||
el._cleanups.add(stop);
|
||||
onUnmount(stop);
|
||||
if (/^(INPUT|TEXTAREA|SELECT)$/.test(el.tagName) && (k === "value" || k === "checked")) {
|
||||
const evType = k === "checked" ? "change" : "input";
|
||||
el.addEventListener(evType, (ev) => v(ev.target[k]));
|
||||
}
|
||||
} else {
|
||||
el.setAttribute(k, v);
|
||||
}
|
||||
}
|
||||
|
||||
const append = (c) => {
|
||||
if (isArr(c)) return c.forEach(append);
|
||||
if (isFunc(c)) {
|
||||
const anchor = doc.createTextNode("");
|
||||
el.appendChild(anchor);
|
||||
let currentNodes = [];
|
||||
const stop = Watch(() => {
|
||||
const res = c();
|
||||
const next = (isArr(res) ? res : [res]).map(ensureNode);
|
||||
// Limpiar antiguos (destruir componentes y nodos)
|
||||
currentNodes.forEach(n => {
|
||||
if (n._isRuntime) n.destroy();
|
||||
else cleanupNode(n);
|
||||
});
|
||||
let ref = anchor;
|
||||
for (let i = next.length-1; i >= 0; i--) {
|
||||
const node = next[i];
|
||||
if (node.parentNode !== ref.parentNode) ref.parentNode?.insertBefore(node, ref);
|
||||
ref = node;
|
||||
}
|
||||
currentNodes = next;
|
||||
});
|
||||
el._cleanups.add(stop);
|
||||
onUnmount(stop);
|
||||
} else {
|
||||
el.appendChild(ensureNode(c));
|
||||
}
|
||||
};
|
||||
append(children);
|
||||
return el;
|
||||
};
|
||||
|
||||
const Render = (fn) => {
|
||||
const root = createOwner();
|
||||
const container = doc.createElement("div");
|
||||
container.style.display = "contents";
|
||||
runWithOwner(root, () => {
|
||||
const res = fn({ onCleanup: onUnmount });
|
||||
(isArr(res) ? res : [res]).forEach(r => container.appendChild(ensureNode(r)));
|
||||
});
|
||||
return { _isRuntime: true, container, destroy: () => { dispose(root); container.remove(); } };
|
||||
};
|
||||
|
||||
const If = (cond, t, f = null, trans = null) => {
|
||||
const anchor = doc.createTextNode("");
|
||||
const root = Tag("div", { style: "display:contents" }, [anchor]);
|
||||
let currentView = null, last = null;
|
||||
Watch(() => {
|
||||
const show = !!(isFunc(cond) ? cond() : cond);
|
||||
if (show === last) return; last = show;
|
||||
const disposeView = () => { if (currentView) { currentView.destroy(); currentView = null; } };
|
||||
if (currentView && !show && trans?.out) trans.out(currentView.container, disposeView);
|
||||
else disposeView();
|
||||
const content = show ? t : f;
|
||||
if (content) {
|
||||
currentView = Render(() => isFunc(content) ? content() : content);
|
||||
root.insertBefore(currentView.container, anchor);
|
||||
if (trans?.in) trans.in(currentView.container);
|
||||
}
|
||||
});
|
||||
return root;
|
||||
};
|
||||
|
||||
const For = (src, itemFn, keyFn) => {
|
||||
const anchor = doc.createTextNode("");
|
||||
const root = Tag("div", { style: "display:contents" }, [anchor]);
|
||||
let cache = new Map();
|
||||
Watch(() => {
|
||||
const items = (isFunc(src) ? src() : src) || [];
|
||||
const next = new Map();
|
||||
const order = [];
|
||||
for (let i = 0; i < items.length; i++) {
|
||||
const item = items[i];
|
||||
const key = keyFn ? keyFn(item, i) : i;
|
||||
let view = cache.get(key);
|
||||
if (!view) view = Render(() => itemFn(item, i));
|
||||
next.set(key, view);
|
||||
order.push(key);
|
||||
cache.delete(key);
|
||||
}
|
||||
cache.forEach(v => v.destroy());
|
||||
cache = next;
|
||||
let ref = anchor;
|
||||
for (let i = order.length-1; i >= 0; i--) {
|
||||
const view = next.get(order[i]);
|
||||
if (view.container.nextSibling !== ref) root.insertBefore(view.container, ref);
|
||||
ref = view.container;
|
||||
}
|
||||
});
|
||||
return root;
|
||||
};
|
||||
|
||||
// --- Router (con limpieza del evento global) ---
|
||||
const Router = (routes) => {
|
||||
const getHash = () => window.location.hash.slice(1) || "/";
|
||||
const path = $(getHash());
|
||||
const handler = () => path(getHash());
|
||||
window.addEventListener("hashchange", handler);
|
||||
onUnmount(() => window.removeEventListener("hashchange", handler));
|
||||
|
||||
const outlet = Tag("div", { class: "router-outlet" });
|
||||
let currentView = null;
|
||||
Watch([path], () => {
|
||||
const cur = path();
|
||||
const route = routes.find(r => {
|
||||
const p1 = r.path.split("/").filter(Boolean);
|
||||
const p2 = cur.split("/").filter(Boolean);
|
||||
return p1.length === p2.length && p1.every((p, i) => p[0] === ":" || p === p2[i]);
|
||||
}) || routes.find(r => r.path === "*");
|
||||
if (route) {
|
||||
currentView?.destroy();
|
||||
const params = {};
|
||||
route.path.split("/").filter(Boolean).forEach((p, i) => {
|
||||
if (p[0] === ":") params[p.slice(1)] = cur.split("/").filter(Boolean)[i];
|
||||
});
|
||||
Router.params(params);
|
||||
currentView = Render(() => isFunc(route.component) ? route.component(params) : route.component);
|
||||
outlet.replaceChildren(currentView.container);
|
||||
}
|
||||
});
|
||||
return outlet;
|
||||
};
|
||||
Router.params = $({});
|
||||
Router.to = (p) => window.location.hash = p.replace(/^#?\/?/, "#/");
|
||||
Router.back = () => window.history.back();
|
||||
Router.path = () => window.location.hash.replace(/^#/, "") || "/";
|
||||
|
||||
const Mount = (comp, target) => {
|
||||
const t = typeof target === "string" ? doc.querySelector(target) : target;
|
||||
if (!t) return;
|
||||
if (MOUNTED_NODES.has(t)) MOUNTED_NODES.get(t).destroy();
|
||||
const inst = Render(isFunc(comp) ? comp : () => comp);
|
||||
t.replaceChildren(inst.container);
|
||||
MOUNTED_NODES.set(t, inst);
|
||||
return inst;
|
||||
};
|
||||
|
||||
return { $, $$, Watch, Tag, Render, If, For, Router, Mount, untrack, onUnmount };
|
||||
})();
|
||||
|
||||
if (typeof window !== "undefined") {
|
||||
Object.assign(window, SigPro);
|
||||
"div span p h1 h2 h3 h4 h5 h6 br hr section article aside nav main header footer ul ol li a em strong pre code form label input textarea select button img svg"
|
||||
.split(" ").forEach(t => window[t[0].toUpperCase() + t.slice(1)] = (p, c) => SigPro.Tag(t, p, c));
|
||||
}
|
||||
export default SigPro;
|
||||
139
sigpro3.js
139
sigpro3.js
@@ -1,139 +0,0 @@
|
||||
const SigPro = (() => {
|
||||
const doc = typeof document !== "undefined" ? document : null;
|
||||
const isFunc = (f) => typeof f === "function";
|
||||
const isArr = Array.isArray;
|
||||
|
||||
let activeEffect = null, currentOwner = null;
|
||||
const queue = new Set();
|
||||
|
||||
const tick = () => {
|
||||
const runs = [...queue]; queue.clear();
|
||||
runs.forEach(fn => fn());
|
||||
if (queue.size) tick();
|
||||
};
|
||||
|
||||
const onUnmount = (fn) => currentOwner?._cleanups.add(fn);
|
||||
|
||||
const cleanupNode = (node) => {
|
||||
if (node._cleanups) { node._cleanups.forEach(f => f()); node._cleanups.clear(); }
|
||||
node.childNodes?.forEach(cleanupNode);
|
||||
};
|
||||
|
||||
const effect = (fn) => {
|
||||
const runner = () => {
|
||||
stop();
|
||||
const prevEff = activeEffect, prevOwn = currentOwner;
|
||||
activeEffect = runner; currentOwner = runner;
|
||||
try { runner._cb = fn(); } finally { activeEffect = prevEff; currentOwner = prevOwn; }
|
||||
};
|
||||
const stop = () => {
|
||||
runner._deps?.forEach(subs => subs.delete(runner)); runner._deps?.clear();
|
||||
if (isFunc(runner._cb)) runner._cb();
|
||||
runner._cleanups?.forEach(f => f()); runner._cleanups?.clear();
|
||||
};
|
||||
Object.assign(runner, { _deps: new Set(), _cleanups: new Set(), stop });
|
||||
if (currentOwner) onUnmount(stop);
|
||||
runner(); return stop;
|
||||
};
|
||||
|
||||
const signal = (val) => {
|
||||
const subs = new Set();
|
||||
return (...args) => {
|
||||
if (args.length) {
|
||||
const next = isFunc(args[0]) ? args[0](val) : args[0];
|
||||
if (!Object.is(val, next)) {
|
||||
val = next;
|
||||
subs.forEach(e => { queue.add(e); if (queue.size === 1) queueMicrotask(tick); });
|
||||
}
|
||||
} else {
|
||||
if (activeEffect) { subs.add(activeEffect); activeEffect._deps.add(subs); }
|
||||
return val;
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
const computed = (fn) => {
|
||||
const s = signal();
|
||||
effect(() => s(fn()));
|
||||
return () => s();
|
||||
};
|
||||
|
||||
const h = (tag, props = {}, children = []) => {
|
||||
if (props instanceof Node || isArr(props) || typeof props !== 'object') { children = props; props = {}; }
|
||||
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);
|
||||
el._cleanups = new Set();
|
||||
|
||||
for (let [k, v] of Object.entries(props)) {
|
||||
if (k === "ref") { isFunc(v) ? v(el) : (v.current = el); continue; }
|
||||
if (k.startsWith("on")) {
|
||||
const ev = k.slice(2).toLowerCase(); el.addEventListener(ev, v);
|
||||
el._cleanups.add(() => el.removeEventListener(ev, v));
|
||||
} else if (isFunc(v)) {
|
||||
el._cleanups.add(effect(() => {
|
||||
const val = v(), safe = (k === 'src' || k === 'href') && String(val).includes('javascript:') ? '#' : val;
|
||||
k === "class" ? (el.className = safe || "") : (safe == null || safe === false ? el.removeAttribute(k) : el.setAttribute(k, safe === true ? "" : safe));
|
||||
}));
|
||||
if (/^(INPUT|TEXTAREA|SELECT)$/.test(el.tagName) && (k === "value" || k === "checked")) {
|
||||
el.addEventListener(k === "checked" ? "change" : "input", (e) => v(e.target[k === "checked" ? "checked" : "value"]));
|
||||
}
|
||||
} else el.setAttribute(k, v);
|
||||
}
|
||||
|
||||
const ensureNode = (n) => n instanceof Node ? n : doc.createTextNode(String(n ?? ""));
|
||||
const append = (c) => {
|
||||
if (isArr(c)) return c.forEach(append);
|
||||
if (isFunc(c)) {
|
||||
const m = doc.createTextNode(""); el.appendChild(m); let curr = [];
|
||||
el._cleanups.add(effect(() => {
|
||||
const res = c(), next = (isArr(res) ? res : [res]).flat().map(ensureNode);
|
||||
curr.forEach(n => { cleanupNode(n); n.remove(); });
|
||||
next.forEach(n => m.parentNode?.insertBefore(n, m)); curr = next;
|
||||
}));
|
||||
} else if (c !== null && c !== false) el.appendChild(ensureNode(c));
|
||||
};
|
||||
append(children);
|
||||
if (currentOwner) onUnmount(() => cleanupNode(el));
|
||||
return el;
|
||||
};
|
||||
|
||||
const If = (cond, thenFn, elseFn = null) => {
|
||||
let last, cached;
|
||||
return () => {
|
||||
const v = !!(isFunc(cond) ? cond() : cond);
|
||||
if (v === last) return cached;
|
||||
last = v;
|
||||
const target = v ? thenFn : elseFn;
|
||||
return cached = isFunc(target) ? target() : target;
|
||||
};
|
||||
};
|
||||
|
||||
const For = (list, keyFn, itemFn) => {
|
||||
let cache = new Map();
|
||||
return () => {
|
||||
const items = (isFunc(list) ? list() : list) || [];
|
||||
const nextCache = new Map();
|
||||
const nodes = items.map((item, i) => {
|
||||
const key = keyFn(item, i);
|
||||
const node = cache.get(key) || itemFn(item, i);
|
||||
nextCache.set(key, node); return node;
|
||||
});
|
||||
for (const [k, n] of cache) if (!nextCache.has(k)) { cleanupNode(n); n.remove(); }
|
||||
cache = nextCache; return nodes;
|
||||
};
|
||||
};
|
||||
|
||||
const mount = (comp, target) => {
|
||||
const t = typeof target === "string" ? doc.querySelector(target) : target;
|
||||
cleanupNode(t);
|
||||
const prev = currentOwner, _cleanups = new Set();
|
||||
currentOwner = { _cleanups };
|
||||
const node = h(comp);
|
||||
currentOwner = prev;
|
||||
node._cleanups = new Set([...(node._cleanups || []), ..._cleanups]);
|
||||
t.replaceChildren(node);
|
||||
return () => cleanupNode(node);
|
||||
};
|
||||
|
||||
return { signal, computed, effect, h, If, For, mount, onUnmount };
|
||||
})();
|
||||
261
sigpro_gemini.js
Normal file
261
sigpro_gemini.js
Normal file
@@ -0,0 +1,261 @@
|
||||
/**
|
||||
* SigPro v2 G
|
||||
*/
|
||||
const SigPro = (() => {
|
||||
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 ensureNode = (n) => n?._isRuntime ? n.container : (n instanceof Node ? n : doc.createTextNode(String(n ?? "")));
|
||||
|
||||
// --- ÁRBOL DE CONTEXTO (OWNER TREE) ---
|
||||
// c: Hijos (children), x: Limpiezas (cleanups), d: Dependencias/Señales (deps)
|
||||
let activeOwner = null, activeEffect = null, isFlushing = false;
|
||||
const effectQueue = new Set(), MOUNTED_NODES = new WeakMap();
|
||||
|
||||
const createOwner = () => {
|
||||
const o = { c: new Set(), x: new Set(), d: new Set(), depth: activeOwner ? activeOwner.depth + 1 : 0 };
|
||||
if (activeOwner) activeOwner.c.add(o);
|
||||
return o;
|
||||
};
|
||||
|
||||
const dispose = (o) => {
|
||||
if (!o) return;
|
||||
o.c?.forEach(dispose); // 1. Destruye hijos recursivamente
|
||||
o.x?.forEach(f => f()); // 2. Ejecuta limpiezas (eventos, timers)
|
||||
o.d?.forEach(s => s.delete(o)); // 3. Se desuscribe de las señales
|
||||
o.c?.clear(); o.x?.clear(); o.d?.clear();
|
||||
};
|
||||
|
||||
const runWithOwner = (o, cb) => {
|
||||
const prev = activeOwner; activeOwner = o;
|
||||
try { return cb(); } finally { activeOwner = prev; }
|
||||
};
|
||||
|
||||
const onUnmount = (fn) => activeOwner?.x.add(fn);
|
||||
|
||||
// --- SCHEDULER ---
|
||||
const flush = () => {
|
||||
if (isFlushing) return; isFlushing = true;
|
||||
const sorted = Array.from(effectQueue).sort((a, b) => a.depth - b.depth);
|
||||
effectQueue.clear();
|
||||
sorted.forEach(e => !e._deleted && e.run());
|
||||
isFlushing = false;
|
||||
};
|
||||
|
||||
const trackUpdate = (subs, trigger = false) => {
|
||||
if (!trigger && activeEffect && !activeEffect._deleted) {
|
||||
subs.add(activeEffect); activeEffect.d.add(subs);
|
||||
} else if (trigger) {
|
||||
subs.forEach(e => {
|
||||
if (e === activeEffect || e._deleted) return;
|
||||
if (e._isComputed) { e.markDirty(); if (e._subs) trackUpdate(e._subs, true); }
|
||||
else effectQueue.add(e);
|
||||
});
|
||||
if (!isFlushing) queueMicrotask(flush);
|
||||
}
|
||||
};
|
||||
|
||||
const untrack = (fn) => {
|
||||
const p = activeEffect; activeEffect = null;
|
||||
try { return fn(); } finally { activeEffect = p; }
|
||||
};
|
||||
|
||||
// --- CORE API ---
|
||||
const $ = (val, key = null) => {
|
||||
const subs = new Set();
|
||||
if (isFunc(val)) {
|
||||
let cache, dirty = true;
|
||||
const e = createOwner();
|
||||
assign(e, { _isComputed: true, _subs: subs, markDirty: () => (dirty = true) });
|
||||
|
||||
e.run = () => {
|
||||
if (e._deleted) return;
|
||||
dispose(e); // Limpia la ejecución anterior
|
||||
const prevE = activeEffect; activeEffect = e;
|
||||
runWithOwner(e, () => {
|
||||
const next = val();
|
||||
if (!Object.is(cache, next) || dirty) { cache = next; dirty = false; trackUpdate(subs, true); }
|
||||
});
|
||||
activeEffect = prevE;
|
||||
};
|
||||
|
||||
onUnmount(() => { e._deleted = true; dispose(e); subs.clear(); });
|
||||
return () => { if (dirty) e.run(); trackUpdate(subs); return cache; };
|
||||
}
|
||||
if (key) try { val = JSON.parse(localStorage.getItem(key)) ?? val; } catch (e) { }
|
||||
return (...args) => {
|
||||
if (args.length) {
|
||||
const next = isFunc(args[0]) ? args[0](val) : args[0];
|
||||
if (!Object.is(val, next)) {
|
||||
val = next; if (key) localStorage.setItem(key, JSON.stringify(val));
|
||||
trackUpdate(subs, true);
|
||||
}
|
||||
}
|
||||
trackUpdate(subs); return val;
|
||||
};
|
||||
};
|
||||
|
||||
const $$ = (obj, cache = new WeakMap()) => {
|
||||
if (!isObj(obj)) return obj;
|
||||
if (cache.has(obj)) return cache.get(obj);
|
||||
const subs = {};
|
||||
const proxy = new Proxy(obj, {
|
||||
get: (t, k) => { trackUpdate(subs[k] ??= new Set()); return isObj(t[k]) ? $$(t[k], cache) : t[k]; },
|
||||
set: (t, k, v) => { if (!Object.is(t[k], v)) { t[k] = v; if (subs[k]) trackUpdate(subs[k], true); } return true; }
|
||||
});
|
||||
cache.set(obj, proxy); return proxy;
|
||||
};
|
||||
|
||||
const Watch = (target, cb) => {
|
||||
const explicit = isArr(target), e = createOwner();
|
||||
e.run = () => {
|
||||
if (e._deleted) return;
|
||||
dispose(e);
|
||||
const prevE = activeEffect; activeEffect = e;
|
||||
runWithOwner(e, () => {
|
||||
explicit ? (untrack(cb), target.forEach(d => isFunc(d) && d())) : cb();
|
||||
});
|
||||
activeEffect = prevE;
|
||||
};
|
||||
onUnmount(() => { e._deleted = true; dispose(e); });
|
||||
e.run(); return () => { e._deleted = true; dispose(e); };
|
||||
};
|
||||
|
||||
const Tag = (tag, props = {}, children = []) => {
|
||||
if (props instanceof Node || isArr(props) || !isObj(props)) { children = props; props = {}; }
|
||||
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);
|
||||
|
||||
for (let [k, v] of Object.entries(props)) {
|
||||
if (k === "ref") { isFunc(v) ? v(el) : (v.current = el); continue; }
|
||||
if (k.startsWith("on")) {
|
||||
const ev = k.slice(2).toLowerCase(); el.addEventListener(ev, v);
|
||||
onUnmount(() => el.removeEventListener(ev, v)); // Se adjunta al Owner activo!
|
||||
} else if (isFunc(v)) {
|
||||
Watch(() => {
|
||||
const val = v(), safe = (k === 'src' || k === 'href') && String(val).includes('javascript:') ? '#' : val;
|
||||
k === "class" ? (el.className = safe || "") : (safe == null || safe === false ? el.removeAttribute(k) : el.setAttribute(k, safe === true ? "" : safe));
|
||||
});
|
||||
if (/^(INPUT|TEXTAREA|SELECT)$/.test(el.tagName) && (k === "value" || k === "checked")) {
|
||||
el.addEventListener(k === "checked" ? "change" : "input", (ev) => v(ev.target[k]));
|
||||
}
|
||||
} else el.setAttribute(k, v);
|
||||
}
|
||||
|
||||
const append = (c) => {
|
||||
if (isArr(c)) return c.forEach(append);
|
||||
if (isFunc(c)) {
|
||||
const m = doc.createTextNode(""); el.appendChild(m); let curr = [];
|
||||
Watch(() => {
|
||||
const res = c(), next = (isArr(res) ? res : [res]).map(ensureNode);
|
||||
curr.forEach(n => { if (n instanceof Node) n.remove(); }); // Adiós cleanupNode()
|
||||
next.forEach(n => m.parentNode?.insertBefore(n, m)); curr = next;
|
||||
});
|
||||
} else el.appendChild(ensureNode(c));
|
||||
};
|
||||
append(children); return el;
|
||||
};
|
||||
|
||||
const Render = (fn) => {
|
||||
const root = createOwner(), container = doc.createElement("div");
|
||||
container.style.display = "contents";
|
||||
runWithOwner(root, () => {
|
||||
const res = fn({ onCleanup: onUnmount });
|
||||
(isArr(res) ? res : [res]).forEach(r => container.appendChild(ensureNode(r)));
|
||||
});
|
||||
return { _isRuntime: true, container, destroy: () => { dispose(root); container.remove(); } };
|
||||
};
|
||||
|
||||
const If = (cond, t, f = null, trans = null) => {
|
||||
const m = doc.createTextNode(""), root = Tag("div", { style: "display:contents" }, [m]);
|
||||
let view = null, last = null;
|
||||
Watch(() => {
|
||||
const s = !!(isFunc(cond) ? cond() : cond);
|
||||
if (s === last) return; last = s;
|
||||
const disposeView = () => { if (view) { view.destroy(); view = null; } };
|
||||
if (view && !s && trans?.out) trans.out(view.container, disposeView); else disposeView();
|
||||
const b = s ? t : f;
|
||||
if (b) {
|
||||
view = Render(() => isFunc(b) ? b() : b);
|
||||
root.insertBefore(view.container, m);
|
||||
if (trans?.in) trans.in(view.container);
|
||||
}
|
||||
});
|
||||
return root;
|
||||
};
|
||||
|
||||
const For = (src, itemFn, keyFn) => {
|
||||
const m = doc.createTextNode(""), root = Tag("div", { style: "display:contents" }, [m]);
|
||||
let cache = new Map();
|
||||
Watch(() => {
|
||||
const items = (isFunc(src) ? src() : src) || [], next = new Map(), order = [];
|
||||
items.forEach((item, i) => {
|
||||
const k = keyFn ? keyFn(item, i) : i;
|
||||
let v = cache.get(k) || Render(() => itemFn(item, i));
|
||||
cache.delete(k); next.set(k, v); order.push(k);
|
||||
});
|
||||
cache.forEach(v => v.destroy());
|
||||
let anchor = m;
|
||||
for (let i = order.length - 1; i >= 0; i--) {
|
||||
const v = next.get(order[i]);
|
||||
if (v.container.nextSibling !== anchor) root.insertBefore(v.container, anchor);
|
||||
anchor = v.container;
|
||||
}
|
||||
cache = next;
|
||||
});
|
||||
return root;
|
||||
};
|
||||
|
||||
const Router = (routes) => {
|
||||
const getHash = () => window.location.hash.slice(1) || "/";
|
||||
const path = $(getHash());
|
||||
const listener = () => path(getHash());
|
||||
window.addEventListener("hashchange", listener);
|
||||
onUnmount(() => window.removeEventListener("hashchange", listener)); // Ahora el router se limpia solo
|
||||
|
||||
const outlet = Tag("div", { class: "router-outlet" });
|
||||
let currentView = null;
|
||||
|
||||
Watch([path], () => {
|
||||
const cur = path();
|
||||
const route = routes.find(r => {
|
||||
const p1 = r.path.split("/").filter(Boolean);
|
||||
const p2 = cur.split("/").filter(Boolean);
|
||||
return p1.length === p2.length && p1.every((p, i) => p[0] === ":" || p === p2[i]);
|
||||
}) || routes.find(r => r.path === "*");
|
||||
|
||||
if (route) {
|
||||
currentView?.destroy();
|
||||
const params = {};
|
||||
route.path.split("/").filter(Boolean).forEach((p, i) => {
|
||||
if (p[0] === ":") params[p.slice(1)] = cur.split("/").filter(Boolean)[i];
|
||||
});
|
||||
|
||||
Router.params(params);
|
||||
currentView = Render(() => isFunc(route.component) ? route.component(params) : route.component);
|
||||
outlet.replaceChildren(currentView.container);
|
||||
}
|
||||
});
|
||||
return outlet;
|
||||
};
|
||||
|
||||
Router.params = $({});
|
||||
Router.to = (p) => window.location.hash = p.replace(/^#?\/?/, "#/");
|
||||
Router.back = () => window.history.back();
|
||||
Router.path = () => window.location.hash.replace(/^#/, "") || "/";
|
||||
|
||||
const Mount = (comp, target) => {
|
||||
const t = typeof target === "string" ? doc.querySelector(target) : target;
|
||||
if (!t) return; if (MOUNTED_NODES.has(t)) MOUNTED_NODES.get(t).destroy();
|
||||
const inst = Render(isFunc(comp) ? comp : () => comp);
|
||||
t.replaceChildren(inst.container); MOUNTED_NODES.set(t, inst); return inst;
|
||||
};
|
||||
|
||||
return { $, $$, Watch, Tag, Render, If, For, Router, Mount, untrack, onUnmount };
|
||||
})();
|
||||
|
||||
if (typeof window !== "undefined") {
|
||||
Object.assign(window, SigPro);
|
||||
"div span p h1 h2 h3 h4 h5 h6 br hr section article aside nav main header footer ul ol li a em strong pre code form label input textarea select button img svg"
|
||||
.split(" ").forEach(t => window[t[0].toUpperCase() + t.slice(1)] = (p, c) => SigPro.Tag(t, p, c));
|
||||
}
|
||||
export default SigPro;
|
||||
@@ -1,276 +0,0 @@
|
||||
const isFn = (v) => typeof v === 'function';
|
||||
const isNode = (v) => v instanceof Node;
|
||||
const DANGEROUS = /^(javascript|data|vbscript):/i;
|
||||
const sanitize = v => DANGEROUS.test(String(v)) ? '#' : v;
|
||||
|
||||
let isScheduled = false, activeEffect = null, context = null;
|
||||
const queue = new Set(), reactiveCache = new WeakMap();
|
||||
|
||||
const tick = () => {
|
||||
while (queue.size) {
|
||||
const runs = [...queue];
|
||||
queue.clear();
|
||||
runs.forEach(fn => fn());
|
||||
}
|
||||
isScheduled = false;
|
||||
}
|
||||
|
||||
const get = (v) => (v?._isSig ? v.value : (isFn(v) ? v() : v));
|
||||
|
||||
export const effect = (fn, is_scope = false) => {
|
||||
let cleanup = null;
|
||||
const run = () => {
|
||||
stop();
|
||||
const prev = activeEffect;
|
||||
activeEffect = run;
|
||||
try { cleanup = fn(); } finally { activeEffect = prev; }
|
||||
}
|
||||
const stop = () => {
|
||||
run.e.forEach(subs => subs.delete(run));
|
||||
run.e.clear();
|
||||
if (isFn(cleanup)) cleanup();
|
||||
if (run.c) { run.c.forEach(s => s()); run.c.length = 0; }
|
||||
}
|
||||
run.e = new Set();
|
||||
if (is_scope) run.c = [];
|
||||
run();
|
||||
if (activeEffect?.c) activeEffect.c.push(stop);
|
||||
return stop;
|
||||
}
|
||||
|
||||
const track = (subs) => {
|
||||
if (activeEffect && !activeEffect.c) {
|
||||
subs.add(activeEffect);
|
||||
activeEffect.e.add(subs);
|
||||
}
|
||||
}
|
||||
|
||||
export const signal = (value, key = null) => {
|
||||
const subs = new Set();
|
||||
if (key && typeof localStorage !== 'undefined') {
|
||||
const saved = localStorage.getItem(key);
|
||||
if (saved !== null) try { value = JSON.parse(saved); } catch {}
|
||||
}
|
||||
const sig = {
|
||||
_isSig: true,
|
||||
get value() { track(subs); return value; },
|
||||
set value(v) {
|
||||
if (v === value) return;
|
||||
value = v;
|
||||
subs.forEach(f => queue.add(f));
|
||||
if (!isScheduled) { isScheduled = true; queueMicrotask(tick); }
|
||||
}
|
||||
};
|
||||
if (key && typeof localStorage !== 'undefined') {
|
||||
effect(() => localStorage.setItem(key, JSON.stringify(sig.value)));
|
||||
}
|
||||
return sig;
|
||||
};
|
||||
|
||||
export const untrack = (fn) => {
|
||||
const prev = activeEffect;
|
||||
activeEffect = null;
|
||||
const res = fn();
|
||||
activeEffect = prev;
|
||||
return res;
|
||||
}
|
||||
|
||||
export const computed = (fn) => {
|
||||
const sig = signal();
|
||||
effect(() => sig.value = fn());
|
||||
return { get value() { return sig.value; } };
|
||||
}
|
||||
|
||||
export const reactive = (obj) => {
|
||||
if (reactiveCache.has(obj)) return reactiveCache.get(obj);
|
||||
const subs = {};
|
||||
const proxy = new Proxy(obj, {
|
||||
get(t, k) {
|
||||
track(subs[k] ??= new Set());
|
||||
const v = t[k];
|
||||
return (v && typeof v === 'object') ? reactive(v) : v;
|
||||
},
|
||||
set(t, k, v) {
|
||||
if (t[k] === v) return true;
|
||||
t[k] = v;
|
||||
if (subs[k]) {
|
||||
subs[k].forEach(f => queue.add(f));
|
||||
if (!isScheduled) { isScheduled = true; queueMicrotask(tick); }
|
||||
}
|
||||
return true;
|
||||
}
|
||||
});
|
||||
reactiveCache.set(obj, proxy);
|
||||
return proxy;
|
||||
}
|
||||
|
||||
export const storage = (key, val) => persist(key, signal(val));
|
||||
|
||||
export const watch = (source, cb) => {
|
||||
let first = true, old;
|
||||
return effect(() => {
|
||||
const val = get(source);
|
||||
if (!first) untrack(() => cb(val, old));
|
||||
first = false; old = val;
|
||||
});
|
||||
}
|
||||
|
||||
export const onMount = (f) => context?.m.push(f);
|
||||
export const onUnmount = (f) => context?.u.push(f);
|
||||
export const share = (k, v) => context && (context.p[k] = v);
|
||||
export const use = (k, d) => context && (k in context.p ? context.p[k] : d);
|
||||
|
||||
const remove = async (n) => {
|
||||
if (Array.isArray(n)) return Promise.all(n.map(remove));
|
||||
if (n.$off) await n.$off(n);
|
||||
else if (n.$l) await new Promise(r => n.$l(r));
|
||||
n.$s?.();
|
||||
if (n.$c) n.$c.u.forEach(f => f());
|
||||
n.remove();
|
||||
}
|
||||
|
||||
const render = (fn, ...d) => {
|
||||
let n;
|
||||
const s = effect(() => { n = fn(...d); if (isFn(n)) n = n(); }, true);
|
||||
if (n) n.$s = s;
|
||||
return n;
|
||||
}
|
||||
|
||||
export const h = (tag, props = {}, ...children) => {
|
||||
children = children.flat(Infinity);
|
||||
if (isFn(tag)) {
|
||||
const prev = context;
|
||||
context = { m: [], u: [], p: { ...(prev?.p || {}) } };
|
||||
const ctx = context;
|
||||
let el;
|
||||
const s = effect(() => {
|
||||
el = tag(props, { children, emit: (e, ...a) => props[`on${e[0].toUpperCase()}${e.slice(1)}`]?.(...a) });
|
||||
return () => ctx.u.forEach(f => f());
|
||||
}, true);
|
||||
const out = isNode(el) ? el : document.createTextNode(String(el));
|
||||
out.$c = ctx; out.$s = s;
|
||||
if (props.on) out.$on = props.on;
|
||||
if (props.off) out.$off = props.off;
|
||||
context = prev;
|
||||
return out;
|
||||
}
|
||||
if (!tag) return children;
|
||||
const isSvg = /^(svg|path|circle|rect|line|polyline|polygon|g|text|defs|use|symbol)$/.test(tag);
|
||||
const el = isSvg ? document.createElementNS("http://www.w3.org/2000/svg", tag) : document.createElement(tag);
|
||||
for (const k in props) {
|
||||
const v = props[k];
|
||||
if (k.startsWith('on') && k !== 'on' && k !== 'off') el.addEventListener(k.slice(2).toLowerCase(), v);
|
||||
else if (k === "ref") isFn(v) ? v(el) : v.value = el;
|
||||
else if (k === "on") el.$on = v;
|
||||
else if (k === "off") el.$off = v;
|
||||
else if (isFn(v) || v?._isSig) effect(() => {
|
||||
const val = get(v);
|
||||
const attr = (k === 'href' || k === 'src') ? sanitize(val) : val;
|
||||
isSvg ? el.setAttribute(k, attr) : (el[k] = attr);
|
||||
});
|
||||
else {
|
||||
const attr = (k === 'href' || k === 'src') ? sanitize(v) : v;
|
||||
isSvg ? el.setAttribute(k, attr) : (el[k] = attr);
|
||||
}
|
||||
}
|
||||
children.forEach(c => append(el, c));
|
||||
return el;
|
||||
}
|
||||
|
||||
const append = (p, c) => {
|
||||
if (c == null || c === false || c === true) return;
|
||||
if (isFn(c) || c?._isSig) {
|
||||
const anchor = document.createTextNode('');
|
||||
p.appendChild(anchor);
|
||||
let nodes = [];
|
||||
effect(async () => {
|
||||
const raw = [get(c)].flat(Infinity).filter(n => n != null && n !== false && n !== true);
|
||||
const next = raw.map(n => isNode(n) ? n : document.createTextNode(String(n)));
|
||||
for (const n of nodes) { if (!next.includes(n)) await remove(n); }
|
||||
next.forEach((n, i) => {
|
||||
if (!nodes.includes(n)) {
|
||||
p.insertBefore(n, next[i + 1] || anchor);
|
||||
if (n.$on) n.$on(n);
|
||||
if (n.$c) n.$c.m.forEach(f => f());
|
||||
}
|
||||
});
|
||||
nodes = next;
|
||||
}, true);
|
||||
} else {
|
||||
const n = isNode(c) ? c : document.createTextNode(String(c));
|
||||
p.appendChild(n);
|
||||
if (n.$on) n.$on(n);
|
||||
}
|
||||
}
|
||||
|
||||
export const If = (cond, t, f = null, trans = {}) => {
|
||||
let cached, current;
|
||||
return () => {
|
||||
const show = !!get(cond);
|
||||
if (show !== current) {
|
||||
const up = async () => {
|
||||
if (cached) await remove(cached);
|
||||
cached = show ? render(t) : (isFn(f) ? render(f) : f);
|
||||
if (isNode(cached)) {
|
||||
if (trans.on) cached.$on = trans.on;
|
||||
if (trans.off) cached.$off = trans.off;
|
||||
}
|
||||
current = show;
|
||||
};
|
||||
up();
|
||||
}
|
||||
return cached;
|
||||
}
|
||||
}
|
||||
|
||||
export const For = (list, key, renderFn) => {
|
||||
let cache = new Map();
|
||||
return () => {
|
||||
const next = new Map();
|
||||
const items = get(list);
|
||||
const res = items.map((item, i) => {
|
||||
const id = isFn(key) ? key(item, i) : (key ? item[id] : item);
|
||||
let n = cache.get(id);
|
||||
if (!n) n = render(renderFn, item, i);
|
||||
next.set(id, n);
|
||||
return n;
|
||||
});
|
||||
cache.forEach(async (n, id) => { if (!next.has(id)) await remove(n); });
|
||||
cache = next;
|
||||
return res;
|
||||
}
|
||||
}
|
||||
|
||||
export const Router = (routes) => {
|
||||
const path = signal(window.location.hash.slice(1) || '/');
|
||||
window.onhashchange = () => path.value = window.location.hash.slice(1) || '/';
|
||||
|
||||
return h('div', { class: 'router-view' }, () => {
|
||||
const cur = path.value;
|
||||
for (const r of routes) {
|
||||
const reg = new RegExp(`^${r.path.replace(/:[^\s/]+/g, '([^/]+)')}$`);
|
||||
const match = cur.match(reg);
|
||||
|
||||
if (match) {
|
||||
const params = {};
|
||||
const keys = r.path.match(/:[^\s/]+/g) || [];
|
||||
keys.forEach((key, i) => params[key.slice(1)] = match[i + 1]);
|
||||
return h(r.component, { params, path: cur });
|
||||
}
|
||||
}
|
||||
const fallback = routes.find(x => x.path === '*');
|
||||
return fallback ? h(fallback.component) : '404';
|
||||
});
|
||||
};
|
||||
|
||||
export const mount = (root, target, props = {}) => {
|
||||
const container = typeof target === 'string' ? document.querySelector(target) : target;
|
||||
container.replaceChildren();
|
||||
const el = h(root, props);
|
||||
container.appendChild(el);
|
||||
if (el.$on) el.$on(el);
|
||||
if (el.$c) el.$c.m.forEach(f => f());
|
||||
return () => remove(el);
|
||||
};
|
||||
|
||||
export default { signal, effect, reactive, computed, watch, storage, h, mount, If, For, Router, onMount, onUnmount, share, use };
|
||||
335
sw.js
335
sw.js
@@ -1,335 +0,0 @@
|
||||
const isFunction = (value) => typeof value === 'function';
|
||||
const isNode = (value) => value instanceof Node;
|
||||
const get = (sig) => (sig?._isSignal ? sig.value : (isFunction(sig) ? sig() : sig));
|
||||
|
||||
// --- Schedule System ---
|
||||
let isScheduled = false;
|
||||
const updateQueue = new Set();
|
||||
const processQueue = () => {
|
||||
updateQueue.forEach(callback => callback());
|
||||
updateQueue.clear();
|
||||
isScheduled = false;
|
||||
}
|
||||
|
||||
// --- Effects System ---
|
||||
let activeEffect = null;
|
||||
export const effect = (fn, isScope = false) => {
|
||||
let cleanup = null;
|
||||
const run = () => {
|
||||
stop();
|
||||
const previousEffect = activeEffect;
|
||||
activeEffect = run;
|
||||
try { cleanup = fn(); } finally { activeEffect = previousEffect; }
|
||||
}
|
||||
const stop = () => {
|
||||
run.subscriptions.forEach(subscribers => subscribers.delete(run));
|
||||
run.subscriptions.clear();
|
||||
if (isFunction(cleanup)) cleanup();
|
||||
if (run.childEffects) {
|
||||
run.childEffects.forEach(stopChild => stopChild());
|
||||
run.childEffects.length = 0;
|
||||
}
|
||||
}
|
||||
run.subscriptions = new Set();
|
||||
if (isScope) run.childEffects = [];
|
||||
run();
|
||||
if (activeEffect?.childEffects) activeEffect.childEffects.push(stop);
|
||||
return stop;
|
||||
}
|
||||
|
||||
export const scope = (fn) => effect(fn, true);
|
||||
|
||||
const track = (subscribers) => {
|
||||
if (activeEffect && !activeEffect.childEffects) {
|
||||
subscribers.add(activeEffect);
|
||||
activeEffect.subscriptions.add(subscribers);
|
||||
}
|
||||
}
|
||||
|
||||
// --- Signals Core ---
|
||||
export const signal = (initialValue, storageKey = null) => {
|
||||
const subscribers = new Set();
|
||||
const hasStorage = typeof localStorage !== 'undefined';
|
||||
let currentValue = initialValue;
|
||||
|
||||
if (storageKey && hasStorage) {
|
||||
const saved = localStorage.getItem(storageKey);
|
||||
if (saved !== null) try { currentValue = JSON.parse(saved); } catch { }
|
||||
}
|
||||
|
||||
const signalObject = {
|
||||
_isSignal: true,
|
||||
get value() { track(subscribers); return currentValue; },
|
||||
set value(newValue) {
|
||||
if (newValue === currentValue) return;
|
||||
currentValue = newValue;
|
||||
subscribers.forEach(callback => updateQueue.add(callback));
|
||||
if (!isScheduled) { isScheduled = true; queueMicrotask(processQueue); }
|
||||
}
|
||||
};
|
||||
|
||||
if (storageKey && hasStorage) {
|
||||
effect(() => localStorage.setItem(storageKey, JSON.stringify(signalObject.value)));
|
||||
}
|
||||
|
||||
return signalObject;
|
||||
};
|
||||
|
||||
export const untrack = (fn) => {
|
||||
const previousEffect = activeEffect;
|
||||
activeEffect = null;
|
||||
const result = fn();
|
||||
activeEffect = previousEffect;
|
||||
return result;
|
||||
}
|
||||
|
||||
export const computed = (fn) => {
|
||||
const sig = signal();
|
||||
effect(() => sig.value = fn());
|
||||
return { get value() { return sig.value; } };
|
||||
}
|
||||
|
||||
const reactiveCache = new WeakMap();
|
||||
export const reactive = (targetObject) => {
|
||||
if (reactiveCache.has(targetObject)) return reactiveCache.get(targetObject);
|
||||
const subscribersMap = {};
|
||||
const proxy = new Proxy(targetObject, {
|
||||
get(target, key) {
|
||||
track(subscribersMap[key] ??= new Set());
|
||||
const value = target[key];
|
||||
return (value && typeof value === 'object') ? reactive(value) : value;
|
||||
},
|
||||
set(target, key, value) {
|
||||
if (target[key] === value) return true;
|
||||
target[key] = value;
|
||||
if (subscribersMap[key]) {
|
||||
subscribersMap[key].forEach(callback => updateQueue.add(callback));
|
||||
if (!isScheduled) { isScheduled = true; queueMicrotask(processQueue); }
|
||||
}
|
||||
return true;
|
||||
}
|
||||
});
|
||||
reactiveCache.set(targetObject, proxy);
|
||||
return proxy;
|
||||
}
|
||||
|
||||
export const watch = (source, callback) => {
|
||||
let isFirstRun = true, oldValue;
|
||||
return effect(() => {
|
||||
const newValue = isFunction(source) ? source() : source.value;
|
||||
if (!isFirstRun) untrack(() => callback(newValue, oldValue));
|
||||
else isFirstRun = false;
|
||||
oldValue = newValue;
|
||||
});
|
||||
}
|
||||
|
||||
// --- Rendering System ---
|
||||
let currentContext = null;
|
||||
export const onMount = (fn) => currentContext?.mountHooks.push(fn);
|
||||
export const onUnmount = (fn) => currentContext?.unmountHooks.push(fn);
|
||||
export const provide = (key, value) => currentContext && (currentContext.providers[key] = value);
|
||||
export const inject = (key, defaultValue) => currentContext && (key in currentContext.providers ? currentContext.providers[key] : defaultValue);
|
||||
|
||||
const remove = (node) => {
|
||||
if (Array.isArray(node)) return node.forEach(remove);
|
||||
node.$stopEffect?.();
|
||||
if (node.$context) node.$context.unmountHooks.forEach(hook => hook());
|
||||
const finalize = () => node.remove();
|
||||
node.$leaveTransition ? node.$leaveTransition(finalize) : finalize();
|
||||
}
|
||||
|
||||
const render = (renderFn, ...data) => {
|
||||
let node;
|
||||
const stop = effect(() => {
|
||||
node = renderFn(...data);
|
||||
if (isFunction(node)) node = node();
|
||||
}, true);
|
||||
if (node) node.$stopEffect = stop;
|
||||
return node;
|
||||
}
|
||||
|
||||
export const h = (tag, props = {}, ...children) => {
|
||||
children = children.flat(Infinity);
|
||||
|
||||
if (isFunction(tag)) {
|
||||
const previousContext = currentContext;
|
||||
currentContext = { mountHooks: [], unmountHooks: [], providers: { ...(previousContext?.providers || {}) } };
|
||||
const localContext = currentContext;
|
||||
let element;
|
||||
const stop = effect(() => {
|
||||
element = tag(props, {
|
||||
children,
|
||||
emit: (event, ...args) => props[`on${event[0].toUpperCase()}${event.slice(1)}`]?.(...args)
|
||||
});
|
||||
return () => localContext.unmountHooks.forEach(hook => hook());
|
||||
}, true);
|
||||
|
||||
const output = isNode(element) ? element : document.createTextNode(String(element));
|
||||
output.$context = localContext;
|
||||
output.$stopEffect = stop;
|
||||
currentContext = previousContext;
|
||||
return output;
|
||||
}
|
||||
|
||||
if (!tag) return children;
|
||||
|
||||
const isSvg = /^(svg|path|circle|rect|line|polyline|polygon|g|text|defs|use|symbol)$/.test(tag);
|
||||
const element = isSvg ? document.createElementNS("http://www.w3.org/2000/svg", tag) : document.createElement(tag);
|
||||
|
||||
const set = (k, v) => isSvg ? element.setAttribute(k, v) : (element[k] = v);
|
||||
|
||||
for (const key in props) {
|
||||
const val = props[key];
|
||||
if (key.startsWith('on')) element.addEventListener(key.slice(2).toLowerCase(), val);
|
||||
else if (key === "ref") isFunction(val) ? val(element) : val.value = element;
|
||||
else if (isFunction(val) || val?._isSignal) effect(() => set(key, get(val)));
|
||||
else set(key, val);
|
||||
}
|
||||
|
||||
children.forEach(child => append(element, child));
|
||||
return element;
|
||||
}
|
||||
|
||||
const append = (parent, child) => {
|
||||
if (child == null) return;
|
||||
if (isFunction(child)) {
|
||||
const anchor = document.createTextNode('');
|
||||
parent.appendChild(anchor);
|
||||
let currentNodes = [];
|
||||
effect(() => {
|
||||
const rawChildren = [child()].flat(Infinity).filter(node => node != null);
|
||||
const nextNodes = rawChildren.map(node => isNode(node) ? node : document.createTextNode(String(node)));
|
||||
currentNodes.forEach(node => { if (!nextNodes.includes(node)) remove(node); });
|
||||
nextNodes.forEach((node, index) => {
|
||||
if (!currentNodes.includes(node)) {
|
||||
parent.insertBefore(node, nextNodes[index + 1] || anchor);
|
||||
if (node.$context) node.$context.mountHooks.forEach(hook => hook());
|
||||
}
|
||||
});
|
||||
currentNodes = nextNodes;
|
||||
}, true);
|
||||
} else {
|
||||
parent.appendChild(isNode(child) ? child : document.createTextNode(String(child)));
|
||||
}
|
||||
}
|
||||
|
||||
// --- Control Flow & Built-in Components ---
|
||||
export const If = (condition, renderFn, fallback = null, trans = {}) => {
|
||||
let cachedNode, currentCondition;
|
||||
return () => {
|
||||
const show = !!get(condition);
|
||||
if (show !== currentCondition) {
|
||||
currentCondition = show;
|
||||
if (cachedNode) remove(cachedNode);
|
||||
cachedNode = show ? render(renderFn) : (isFunction(fallback) ? render(fallback) : fallback);
|
||||
if (isNode(cachedNode)) {
|
||||
if (trans.enter) cachedNode.$enterTransition = trans.enter;
|
||||
if (trans.exit) cachedNode.$leaveTransition = (done) => trans.exit(cachedNode, done);
|
||||
cachedNode.$enterTransition?.(cachedNode);
|
||||
}
|
||||
}
|
||||
return cachedNode;
|
||||
}
|
||||
}
|
||||
|
||||
export const For = (list, keyFn, renderFn) => {
|
||||
let nodeCache = new Map();
|
||||
return () => {
|
||||
const nextCache = new Map();
|
||||
const items = isFunction(list) ? list() : (list.value || list);
|
||||
const results = items.map((item, index) => {
|
||||
const id = isFunction(keyFn) ? keyFn(item, index) : (keyFn ? item[keyFn] : item);
|
||||
let node = nodeCache.get(id);
|
||||
if (!node) node = render(renderFn, item, index);
|
||||
nextCache.set(id, node);
|
||||
return node;
|
||||
});
|
||||
nodeCache.forEach((node, id) => { if (!nextCache.has(id)) remove(node); });
|
||||
nodeCache = nextCache;
|
||||
return results;
|
||||
}
|
||||
}
|
||||
|
||||
export const Component = ({ is, ...props }, { children }) => () => h(isFunction(is) ? is() : is, props, children);
|
||||
|
||||
export const Transition = ({ enter, idle, leave }, { children: [child] }) => {
|
||||
const decorate = (element) => {
|
||||
if (!isNode(element)) return element;
|
||||
const addClasses = css => css && element.classList.add(...css.split(' '));
|
||||
const removeClasses = css => css && element.classList.remove(...css.split(' '));
|
||||
|
||||
if (enter) {
|
||||
requestAnimationFrame(() => {
|
||||
addClasses(enter[1]);
|
||||
requestAnimationFrame(() => {
|
||||
addClasses(enter[0]); removeClasses(enter[1]); addClasses(enter[2]);
|
||||
element.addEventListener('transitionend', () => {
|
||||
removeClasses(enter[2]); removeClasses(enter[0]); addClasses(idle);
|
||||
}, { once: true });
|
||||
});
|
||||
});
|
||||
}
|
||||
if (leave) {
|
||||
element.$leaveTransition = (done) => {
|
||||
removeClasses(idle); addClasses(leave[1]);
|
||||
requestAnimationFrame(() => {
|
||||
addClasses(leave[0]); removeClasses(leave[1]); addClasses(leave[2]);
|
||||
element.addEventListener('transitionend', () => {
|
||||
removeClasses(leave[2]); removeClasses(leave[0]); done();
|
||||
}, { once: true });
|
||||
});
|
||||
}
|
||||
}
|
||||
return element;
|
||||
}
|
||||
return isFunction(child) ? () => decorate(child()) : decorate(child);
|
||||
}
|
||||
|
||||
// --- Routing & Application Entry ---
|
||||
export const Router = (routes) => {
|
||||
const path = signal(window.location.hash.slice(1) || '/'), params = signal({});
|
||||
Router.path = path;
|
||||
Router.params = params;
|
||||
Router.to = (p) => window.location.hash = p;
|
||||
Router.back = () => window.history.back();
|
||||
window.onhashchange = () => path.value = window.location.hash.slice(1) || '/';
|
||||
return h('div', { class: 'router-view' }, () => {
|
||||
const cur = path.value;
|
||||
for (const r of routes) {
|
||||
const match = cur.match(new RegExp(`^${r.path.replace(/:[^\s/]+/g, '([^/]+)')}$`));
|
||||
if (match) {
|
||||
const p = {};
|
||||
(r.path.match(/:[^\s/]+/g) || []).forEach((k, i) => p[k.slice(1)] = match[i + 1]);
|
||||
untrack(() => params.value = p);
|
||||
return h(r.component, { params: p, path: cur });
|
||||
}
|
||||
}
|
||||
const fallback = routes.find(r => r.path === '*');
|
||||
return fallback ? h(fallback.component) : '404';
|
||||
});
|
||||
};
|
||||
|
||||
|
||||
export const mount = (root, target, props = {}) => {
|
||||
const container = typeof target === 'string' ? document.querySelector(target) : target;
|
||||
if (!container) return;
|
||||
|
||||
container.replaceChildren();
|
||||
|
||||
const el = h(root, props);
|
||||
container.appendChild(el);
|
||||
|
||||
if (el.$context) {
|
||||
el.$context.mountHooks.forEach(hook => hook());
|
||||
el.$context.mountHooks.length = 0;
|
||||
}
|
||||
|
||||
return () => remove(el);
|
||||
};
|
||||
|
||||
export default (target, rootComponent, props) => {
|
||||
const element = h(rootComponent, props);
|
||||
target.appendChild(element);
|
||||
if (element.$context) element.$context.mountHooks.forEach(hook => hook());
|
||||
return () => remove(element);
|
||||
}
|
||||
Reference in New Issue
Block a user