revert Agrupacion de funciones en linea (visual)
This commit is contained in:
2026-04-08 12:04:27 +02:00
parent 20022a361c
commit 2ac429c3f8

382
sw.js
View File

@@ -1,15 +1,15 @@
/*
* Fixed: Memory Leaks, Fragment Lifecycle, and List Reconciler.
* Refactored: Compact & Descriptive naming.
*/
// --- Utilities --- const isFunction = (value) => typeof value === 'function';
const isFunction = (v) => typeof v === 'function', isNode = (v) => v instanceof Node; const isNode = (value) => value instanceof Node;
// --- Schedule System --- // --- Schedule System ---
let isScheduled = false; let isScheduled = false;
const updateQueue = new Set(); const updateQueue = new Set();
const processQueue = () => { updateQueue.forEach(cb => cb()); updateQueue.clear(); isScheduled = false; }; const processQueue = () => {
updateQueue.forEach(callback => callback());
updateQueue.clear();
isScheduled = false;
}
// --- Effects System --- // --- Effects System ---
let activeEffect = null; let activeEffect = null;
@@ -17,193 +17,309 @@ export const effect = (fn, isScope = false) => {
let cleanup = null; let cleanup = null;
const run = () => { const run = () => {
stop(); stop();
const prev = activeEffect; activeEffect = run; const previousEffect = activeEffect;
try { cleanup = fn(); } finally { activeEffect = prev; } activeEffect = run;
}; try { cleanup = fn(); } finally { activeEffect = previousEffect; }
}
const stop = () => { const stop = () => {
run.subscriptions.forEach(subs => subs.delete(run)); run.subscriptions.clear(); run.subscriptions.forEach(subscribers => subscribers.delete(run));
run.subscriptions.clear();
if (isFunction(cleanup)) cleanup(); if (isFunction(cleanup)) cleanup();
if (run.childEffects) { run.childEffects.forEach(s => s()); run.childEffects.length = 0; } if (run.childEffects) {
}; run.childEffects.forEach(stopChild => stopChild());
run.subscriptions = new Set(); if (isScope) run.childEffects = []; run.childEffects.length = 0;
run(); if (activeEffect?.childEffects) activeEffect.childEffects.push(stop); }
}
run.subscriptions = new Set();
if (isScope) run.childEffects = [];
run();
if (activeEffect?.childEffects) activeEffect.childEffects.push(stop);
return stop; return stop;
}; }
export const scope = (fn) => effect(fn, true); export const scope = (fn) => effect(fn, true);
const track = (subs) => { if (activeEffect && !activeEffect.childEffects) { subs.add(activeEffect); activeEffect.subscriptions.add(subs); } };
const track = (subscribers) => {
if (activeEffect && !activeEffect.childEffects) {
subscribers.add(activeEffect);
activeEffect.subscriptions.add(subscribers);
}
}
// --- Signals Core --- // --- Signals Core ---
export const signal = (val, key = null) => { export const signal = (initialValue, storageKey = null) => {
const subs = new Set(), storage = typeof localStorage !== 'undefined'; const subscribers = new Set();
let current = val; const hasStorage = typeof localStorage !== 'undefined';
if (key && storage) { const saved = localStorage.getItem(key); if (saved !== null) try { current = JSON.parse(saved); } catch {} } let currentValue = initialValue;
const sig = { if (storageKey && hasStorage) {
const saved = localStorage.getItem(storageKey);
if (saved !== null) try { currentValue = JSON.parse(saved); } catch {}
}
const signalObject = {
_isSignal: true, _isSignal: true,
get value() { track(subs); return current; }, get value() { track(subscribers); return currentValue; },
set value(v) { set value(newValue) {
if (v === current) return; if (newValue === currentValue) return;
current = v; subs.forEach(cb => updateQueue.add(cb)); currentValue = newValue;
subscribers.forEach(callback => updateQueue.add(callback));
if (!isScheduled) { isScheduled = true; queueMicrotask(processQueue); } if (!isScheduled) { isScheduled = true; queueMicrotask(processQueue); }
} }
}; };
if (key && storage) effect(() => localStorage.setItem(key, JSON.stringify(sig.value)));
return sig; if (storageKey && hasStorage) {
effect(() => localStorage.setItem(storageKey, JSON.stringify(signalObject.value)));
}
return signalObject;
}; };
export const untrack = (fn) => { const prev = activeEffect; activeEffect = null; const res = fn(); activeEffect = prev; return res; }; export const untrack = (fn) => {
export const computed = (fn) => { const sig = signal(); effect(() => sig.value = fn()); return { get value() { return sig.value; } }; }; 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(); const reactiveCache = new WeakMap();
export const reactive = (obj) => { export const reactive = (targetObject) => {
if (reactiveCache.has(obj)) return reactiveCache.get(obj); if (reactiveCache.has(targetObject)) return reactiveCache.get(targetObject);
const subsMap = {}; const subscribersMap = {};
const proxy = new Proxy(obj, { const proxy = new Proxy(targetObject, {
get(t, k) { track(subsMap[k] ??= new Set()); const v = t[k]; return (v && typeof v === 'object') ? reactive(v) : v; }, get(target, key) {
set(t, k, v) { track(subscribersMap[key] ??= new Set());
if (t[k] === v) return true; const value = target[key];
t[k] = v; if (subsMap[k]) { subsMap[k].forEach(cb => updateQueue.add(cb)); if (!isScheduled) { isScheduled = true; queueMicrotask(processQueue); } } 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; return true;
} }
}); });
reactiveCache.set(obj, proxy); return proxy; reactiveCache.set(targetObject, proxy);
}; return proxy;
}
export const watch = (src, cb) => { export const watch = (source, callback) => {
let first = true, old; let isFirstRun = true, oldValue;
return effect(() => { return effect(() => {
const val = isFunction(src) ? src() : src.value; const newValue = isFunction(source) ? source() : source.value;
if (!first) untrack(() => cb(val, old)); else first = false; if (!isFirstRun) untrack(() => callback(newValue, oldValue));
old = val; else isFirstRun = false;
oldValue = newValue;
}); });
}; }
// --- Rendering System --- // --- Rendering System ---
let currentContext = null; let currentContext = null;
export const onMount = (fn) => currentContext?.mountHooks.push(fn); export const onMount = (fn) => currentContext?.mountHooks.push(fn);
export const onUnmount = (fn) => currentContext?.unmountHooks.push(fn); export const onUnmount = (fn) => currentContext?.unmountHooks.push(fn);
export const provide = (k, v) => currentContext && (currentContext.providers[k] = v); export const provide = (key, value) => currentContext && (currentContext.providers[key] = value);
export const inject = (k, dft) => currentContext && (k in currentContext.providers ? currentContext.providers[k] : dft); export const inject = (key, defaultValue) => currentContext && (key in currentContext.providers ? currentContext.providers[key] : defaultValue);
const remove = (node) => { const remove = (node) => {
if (Array.isArray(node)) return node.forEach(remove); if (Array.isArray(node)) return node.forEach(remove);
node.$stopEffect?.(); if (node.$context) node.$context.unmountHooks.forEach(h => h()); node.$stopEffect?.();
const done = () => node.remove(); if (node.$context) node.$context.unmountHooks.forEach(hook => hook());
node.$leave ? node.$leave(done) : done(); const finalize = () => node.remove();
}; node.$leaveTransition ? node.$leaveTransition(finalize) : finalize();
}
const render = (fn, ...data) => { const render = (renderFn, ...data) => {
let node; const stop = effect(() => { node = fn(...data); if (isFunction(node)) node = node(); }, true); let node;
if (node) node.$stopEffect = stop; return 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) => { export const h = (tag, props = {}, ...children) => {
children = children.flat(Infinity); children = children.flat(Infinity);
if (isFunction(tag)) { if (isFunction(tag)) {
const prev = currentContext; const previousContext = currentContext;
currentContext = { mountHooks: [], unmountHooks: [], providers: { ...(prev?.providers || {}) } }; currentContext = { mountHooks: [], unmountHooks: [], providers: { ...(previousContext?.providers || {}) } };
const ctx = currentContext; let el; const localContext = currentContext;
let element;
const stop = effect(() => { const stop = effect(() => {
el = tag(props, { children, emit: (e, ...a) => props[`on${e[0].toUpperCase()}${e.slice(1)}`]?.(...a) }); element = tag(props, {
return () => ctx.unmountHooks.forEach(h => h()); children,
emit: (event, ...args) => props[`on${event[0].toUpperCase()}${event.slice(1)}`]?.(...args)
});
return () => localContext.unmountHooks.forEach(hook => hook());
}, true); }, true);
const out = isNode(el) ? el : document.createTextNode(String(el));
out.$context = ctx; out.$stopEffect = stop; currentContext = prev; return out; const output = isNode(element) ? element : document.createTextNode(String(element));
output.$context = localContext;
output.$stopEffect = stop;
currentContext = previousContext;
return output;
} }
if (!tag) return children; if (!tag) return children;
const el = ['svg', 'path', 'circle'].includes(tag) ? document.createElementNS("http://www.w3.org/2000/svg", tag) : document.createElement(tag);
for (const k in props) { const isSvg = ['svg', 'path', 'circle'].includes(tag);
if (k.startsWith('on')) el.addEventListener(k.slice(2).toLowerCase(), props[k]); const element = isSvg
else if (k === "ref") isFunction(props[k]) ? props[k](el) : props[k].value = el; ? document.createElementNS("http://www.w3.org/2000/svg", tag)
else if (isFunction(props[k])) effect(() => el[k] = props[k]()); : document.createElement(tag);
else el[k] = props[k];
for (const key in props) {
if (key.startsWith('on')) element.addEventListener(key.slice(2).toLowerCase(), props[key]);
else if (key === "ref") isFunction(props[key]) ? props[key](element) : props[key].value = element;
else if (isFunction(props[key])) effect(() => element[key] = props[key]());
else element[key] = props[key];
}
children.forEach(child => append(element, child));
return element;
} }
children.forEach(c => append(el, c)); return el;
};
const append = (parent, child) => { const append = (parent, child) => {
if (child == null) return; if (child == null) return;
if (isFunction(child)) { if (isFunction(child)) {
const anchor = document.createTextNode(''); parent.appendChild(anchor); const anchor = document.createTextNode('');
let nodes = []; parent.appendChild(anchor);
let currentNodes = [];
effect(() => { effect(() => {
const raw = [child()].flat(Infinity).filter(n => n != null); const rawChildren = [child()].flat(Infinity).filter(node => node != null);
const next = raw.map(n => isNode(n) ? n : document.createTextNode(String(n))); const nextNodes = rawChildren.map(node => isNode(node) ? node : document.createTextNode(String(node)));
nodes.forEach(n => { if (!next.includes(n)) remove(n); }); currentNodes.forEach(node => { if (!nextNodes.includes(node)) remove(node); });
next.forEach((n, i) => { if (!nodes.includes(n)) { parent.insertBefore(n, next[i+1] || anchor); if (n.$context) n.$context.mountHooks.forEach(h => h()); } }); nextNodes.forEach((node, index) => {
nodes = next; if (!currentNodes.includes(node)) {
parent.insertBefore(node, nextNodes[index + 1] || anchor);
if (node.$context) node.$context.mountHooks.forEach(hook => hook());
}
});
currentNodes = nextNodes;
}, true); }, true);
} else parent.appendChild(isNode(child) ? child : document.createTextNode(String(child))); } else {
}; parent.appendChild(isNode(child) ? child : document.createTextNode(String(child)));
}
}
// --- Components & Router --- // --- Control Flow & Built-in Components ---
export const If = (cond, renderFn, fallback = null) => { export const If = (condition, renderFn, fallback = null) => {
let cached, current; let cachedNode, currentCondition;
return () => { return () => {
const show = !!cond(); const show = !!condition();
if (show !== current) { if (cached) remove(cached); cached = show ? render(renderFn) : (isFunction(fallback) ? render(fallback) : fallback); current = show; } if (show !== currentCondition) {
return cached; if (cachedNode) remove(cachedNode);
}; cachedNode = show ? render(renderFn) : (isFunction(fallback) ? render(fallback) : fallback);
}; currentCondition = show;
}
return cachedNode;
}
}
export const For = (list, keyFn, renderFn) => { export const For = (list, keyFn, renderFn) => {
let cache = new Map(); let nodeCache = new Map();
return () => { return () => {
const next = new Map(), items = isFunction(list) ? list() : (list.value || list); const nextCache = new Map();
const res = items.map((item, i) => { const items = isFunction(list) ? list() : (list.value || list);
const id = isFunction(keyFn) ? keyFn(item, i) : (keyFn ? item[keyFn] : item); const results = items.map((item, index) => {
let node = cache.get(id) || render(renderFn, item, i); const id = isFunction(keyFn) ? keyFn(item, index) : (keyFn ? item[keyFn] : item);
next.set(id, node); return node; let node = nodeCache.get(id);
if (!node) node = render(renderFn, item, index);
nextCache.set(id, node);
return node;
}); });
cache.forEach((n, id) => { if (!next.has(id)) remove(n); }); cache = next; return res; 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) => { export const Router = (routes) => {
const path = signal(window.location.hash.slice(1) || '/'); const currentPath = signal(window.location.hash.slice(1) || '/');
window.onhashchange = () => path.value = window.location.hash.slice(1) || '/'; window.onhashchange = () => currentPath.value = window.location.hash.slice(1) || '/';
return h('div', { class: 'router-view' }, () => { return h('div', { class: 'router-view' }, () => {
const cur = path.value; const pathValue = currentPath.value;
for (const r of routes) { for (const route of routes) {
const match = cur.match(new RegExp(`^${r.path.replace(/:[^\s/]+/g, '([^/]+)')}$`)); const pattern = new RegExp(`^${route.path.replace(/:[^\s/]+/g, '([^/]+)')}$`);
const match = pathValue.match(pattern);
if (match) { if (match) {
const params = {}; (r.path.match(/:[^\s/]+/g) || []).forEach((k, i) => params[k.slice(1)] = match[i+1]); const params = {};
return h(r.component, { params, path: cur }); const keys = route.path.match(/:[^\s/]+/g) || [];
keys.forEach((key, index) => params[key.slice(1)] = match[index + 1]);
return h(route.component, { params, path: pathValue });
} }
} }
const fbk = routes.find(r => r.path === '*'); return fbk ? h(fbk.component) : '404'; const fallback = routes.find(r => r.path === '*');
return fallback ? h(fallback.component) : '404';
}); });
}; };
export const Transition = ({ enter: e, idle, leave: l }, { children: [c] }) => { export const mount = (rootComponent, target, props = {}) => {
const decorate = (el) => { const destination = typeof target === 'string' ? document.querySelector(target) : target;
if (!isNode(el)) return el; if (!destination) return;
const cls = (css, add = true) => css && el.classList[add ? 'add' : 'remove'](...css.split(' '));
if (e) { while (destination.firstChild) remove(destination.firstChild);
cls(e[1]);
requestAnimationFrame(() => { const element = h(rootComponent, props);
cls(e[0]); cls(e[2]); cls(e[1], false); destination.appendChild(element);
el.addEventListener('transitionend', () => { cls(e[2], false); cls(e[0], false); cls(idle); }, { once: true });
}); if (element.$context) {
element.$context.mountHooks.forEach(hook => hook());
element.$context.mountHooks.length = 0;
} }
if (l) el.$leave = (done) => {
cls(idle, false); cls(l[1]); return () => remove(element);
requestAnimationFrame(() => {
cls(l[0]); cls(l[2]); cls(l[1], false);
el.addEventListener('transitionend', () => { cls(l[2], false); cls(l[0], false); done(); }, { once: true });
});
};
return el;
};
return isFunction(c) ? () => decorate(c()) : decorate(c);
}; };
export const mount = (root, target, props = {}) => { export default (target, rootComponent, props) => {
const dest = typeof target === 'string' ? document.querySelector(target) : target; const element = h(rootComponent, props);
if (!dest) return; target.appendChild(element);
while (dest.firstChild) remove(dest.firstChild); if (element.$context) element.$context.mountHooks.forEach(hook => hook());
const el = h(root, props); dest.appendChild(el); return () => remove(element);
if (el.$context) { el.$context.mountHooks.forEach(h => h()); el.$context.mountHooks.length = 0; } }
return () => remove(el);
};