ok
This commit is contained in:
423
sigwork.js
423
sigwork.js
@@ -1,269 +1,260 @@
|
|||||||
// ---------------------------
|
/*
|
||||||
// SigPro v2
|
* SigPro
|
||||||
// ---------------------------
|
*/
|
||||||
|
|
||||||
// --- Scheduler ---
|
// --- Scheduler (Ciclo Completo) ---
|
||||||
let isScheduled = false;
|
let isScheduled = false;
|
||||||
const queue = new Set();
|
const queue = new Set();
|
||||||
const flushQueue = () => {
|
const tick = () => {
|
||||||
const runs = [...queue];
|
while (queue.size) {
|
||||||
queue.clear();
|
const runs = [...queue];
|
||||||
runs.forEach(fn => fn());
|
queue.clear();
|
||||||
isScheduled = false;
|
runs.forEach(fn => fn());
|
||||||
|
}
|
||||||
|
isScheduled = false;
|
||||||
};
|
};
|
||||||
|
|
||||||
// --- Core State & Ownership ---
|
// --- Estado Global y Contexto ---
|
||||||
let activeEffect = null;
|
let activeEffect = null;
|
||||||
let currentOwner = null;
|
|
||||||
let currentContext = null;
|
let currentContext = null;
|
||||||
const nodeContexts = new WeakMap();
|
const nodeContexts = new WeakMap();
|
||||||
|
|
||||||
// --- Security ---
|
// --- Seguridad ---
|
||||||
const DANGEROUS = /^(javascript|data|vbscript):/i;
|
const DANGEROUS = /^(javascript|data|vbscript):/i;
|
||||||
const sanitize = v => DANGEROUS.test(String(v)) ? '#' : v;
|
const sanitize = v => DANGEROUS.test(String(v)) ? '#' : v;
|
||||||
|
|
||||||
// --- Effect System ---
|
// --- Sistema de Efectos con Scope ---
|
||||||
export const Effect = (fn) => {
|
export const Effect = (fn, is_scope = false) => {
|
||||||
const owner = currentOwner;
|
let cleanup = null;
|
||||||
const runner = () => {
|
const runner = () => {
|
||||||
cleanup();
|
stop();
|
||||||
const prevOwner = currentOwner;
|
const prevContext = currentContext;
|
||||||
const prevEffect = activeEffect;
|
const prevEffect = activeEffect;
|
||||||
currentOwner = owner;
|
activeEffect = runner;
|
||||||
activeEffect = runner;
|
cleanup = fn();
|
||||||
runner.cleanupFns = [];
|
activeEffect = prevEffect;
|
||||||
try { fn(); }
|
currentContext = prevContext;
|
||||||
finally { currentOwner = prevOwner; activeEffect = prevEffect; }
|
};
|
||||||
};
|
|
||||||
const cleanup = () => {
|
const stop = () => {
|
||||||
runner.deps?.forEach(dep => dep.delete(runner));
|
runner.deps?.forEach(subs => subs.delete(runner));
|
||||||
runner.cleanupFns?.forEach(f => f());
|
runner.deps?.clear();
|
||||||
runner.deps?.clear();
|
if (typeof cleanup === 'function') cleanup();
|
||||||
};
|
runner.cleanups?.forEach(f => f());
|
||||||
runner.deps = new Set();
|
runner.cleanups = [];
|
||||||
runner.cleanupFns = [];
|
};
|
||||||
owner?.cleanups.add(cleanup);
|
|
||||||
runner();
|
runner.deps = new Set();
|
||||||
return cleanup;
|
runner.cleanups = [];
|
||||||
|
|
||||||
|
if (activeEffect) activeEffect.cleanups.push(stop);
|
||||||
|
else if (currentContext) currentContext.cleanups.add(stop);
|
||||||
|
|
||||||
|
runner();
|
||||||
|
return stop;
|
||||||
};
|
};
|
||||||
|
|
||||||
// --- Signals ---
|
// --- Signals & Reactividad ---
|
||||||
export const Signal = (value) => {
|
export const Signal = (value) => {
|
||||||
const subs = new Set();
|
const subs = new Set();
|
||||||
return {
|
return {
|
||||||
_isSig: true,
|
_isSig: true,
|
||||||
get value() {
|
get value() {
|
||||||
if (activeEffect) { subs.add(activeEffect); activeEffect.deps.add(subs); }
|
if (activeEffect) {
|
||||||
return value;
|
subs.add(activeEffect);
|
||||||
},
|
activeEffect.deps.add(subs);
|
||||||
set value(v) {
|
}
|
||||||
if (v === value) return;
|
return value;
|
||||||
value = v;
|
},
|
||||||
subs.forEach(fn => queue.add(fn));
|
set value(v) {
|
||||||
if (!isScheduled) { isScheduled = true; queueMicrotask(flushQueue); }
|
if (v === value) return;
|
||||||
}
|
value = v;
|
||||||
};
|
subs.forEach(fn => queue.add(fn));
|
||||||
|
if (!isScheduled) {
|
||||||
|
isScheduled = true;
|
||||||
|
queueMicrotask(tick);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
export const Computed = (fn) => {
|
export const Computed = (fn) => {
|
||||||
const c = Signal(fn());
|
const c = Signal(fn());
|
||||||
Effect(() => c.value = fn());
|
Effect(() => c.value = fn());
|
||||||
return { get value() { return c.value; } };
|
return { get value() { return c.value; } };
|
||||||
};
|
};
|
||||||
|
|
||||||
export const Storage = (key, val) => {
|
export const Storage = (key, val) => {
|
||||||
const saved = localStorage.getItem(key);
|
const saved = localStorage.getItem(key);
|
||||||
const s = Signal(saved !== null ? JSON.parse(saved) : val);
|
const s = Signal(saved !== null ? JSON.parse(saved) : val);
|
||||||
|
Effect(() => localStorage.setItem(key, JSON.stringify(s.value)));
|
||||||
Effect(() => {
|
return s;
|
||||||
localStorage.setItem(key, JSON.stringify(s.value));
|
|
||||||
});
|
|
||||||
|
|
||||||
return s;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const reactiveCache = new WeakMap();
|
// --- Renderer Core (Diffing Avanzado y SVG) ---
|
||||||
export const Reactive = (obj) => {
|
|
||||||
if (!obj || typeof obj !== 'object') return obj;
|
|
||||||
if (reactiveCache.has(obj)) return reactiveCache.get(obj);
|
|
||||||
const subs = {};
|
|
||||||
const proxy = new Proxy(obj, {
|
|
||||||
get(t, k) {
|
|
||||||
if (!subs[k]) subs[k] = new Set();
|
|
||||||
if (activeEffect) { subs[k].add(activeEffect); activeEffect.deps.add(subs[k]); }
|
|
||||||
const val = t[k];
|
|
||||||
return val && typeof val === 'object' ? Reactive(val) : val;
|
|
||||||
},
|
|
||||||
set(t, k, v) {
|
|
||||||
if (t[k] === v) return true;
|
|
||||||
t[k] = v;
|
|
||||||
subs[k]?.forEach(fn => queue.add(fn));
|
|
||||||
if (!isScheduled) { isScheduled = true; queueMicrotask(flushQueue); }
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
reactiveCache.set(obj, proxy);
|
|
||||||
return proxy;
|
|
||||||
};
|
|
||||||
|
|
||||||
// --- Watch with cleanup ---
|
|
||||||
export const Watch = (source, cb, options = {}) => {
|
|
||||||
let oldValue, firstRun = true, lastCleanup = null;
|
|
||||||
const stop = Effect(() => {
|
|
||||||
const newValue = typeof source === 'function' ? source() : source.value;
|
|
||||||
|
|
||||||
if (!firstRun || options.immediate) {
|
|
||||||
if (lastCleanup) { lastCleanup(); lastCleanup = null; }
|
|
||||||
const prevEffect = activeEffect;
|
|
||||||
activeEffect = null;
|
|
||||||
try { cb(newValue, oldValue, (fn) => { lastCleanup = fn; }); }
|
|
||||||
finally { activeEffect = prevEffect; }
|
|
||||||
}
|
|
||||||
|
|
||||||
oldValue = newValue;
|
|
||||||
firstRun = false;
|
|
||||||
});
|
|
||||||
|
|
||||||
return () => { stop(); if (lastCleanup) lastCleanup(); };
|
|
||||||
};
|
|
||||||
|
|
||||||
// --- Lifecycle ---
|
|
||||||
export const onMount = (fn) => currentContext?.mount.push(fn);
|
|
||||||
export const onUnmount = (fn) => currentContext?.unmount.push(fn);
|
|
||||||
export const Share = (key, value) => { if (currentContext) currentContext.Share[key] = value; };
|
|
||||||
export const Use = (key, def) => {
|
|
||||||
let ctx = currentContext;
|
|
||||||
while (ctx) {
|
|
||||||
if (ctx.Share[key] !== undefined) return ctx.Share[key];
|
|
||||||
ctx = ctx.parent;
|
|
||||||
}
|
|
||||||
return def;
|
|
||||||
};
|
|
||||||
|
|
||||||
// --- Renderer ---
|
|
||||||
const isNode = v => v instanceof Node;
|
const isNode = v => v instanceof Node;
|
||||||
|
|
||||||
export const destroy = (node) => {
|
export const destroy = (node) => {
|
||||||
if (!node) return;
|
if (!node) return;
|
||||||
const ctx = nodeContexts.get(node);
|
const ctx = nodeContexts.get(node);
|
||||||
if (ctx) {
|
if (ctx) {
|
||||||
ctx.unmount.forEach(fn => fn());
|
ctx.unmount.forEach(fn => fn());
|
||||||
ctx.cleanups.forEach(fn => fn());
|
ctx.cleanups.forEach(fn => fn());
|
||||||
nodeContexts.delete(node);
|
nodeContexts.delete(node);
|
||||||
}
|
}
|
||||||
node.childNodes?.forEach(destroy);
|
node.childNodes?.forEach(destroy);
|
||||||
node.remove();
|
node.remove();
|
||||||
};
|
};
|
||||||
|
|
||||||
const append = (parent, child) => {
|
const append = (parent, child) => {
|
||||||
if (child == null) return;
|
if (child == null) return;
|
||||||
if (typeof child === 'function') {
|
if (typeof child === 'function') {
|
||||||
const marker = document.createTextNode('');
|
const anchor = document.createTextNode('');
|
||||||
parent.appendChild(marker);
|
parent.appendChild(anchor);
|
||||||
let nodes = [];
|
let nodes = [];
|
||||||
Effect(() => {
|
Effect(() => {
|
||||||
const raw = child();
|
const raw = child();
|
||||||
const next = [raw].flat(Infinity)
|
const next = [raw].flat(Infinity)
|
||||||
.map(n => typeof n === 'function' ? n() : n)
|
.map(n => typeof n === 'function' ? n() : n)
|
||||||
.filter(n => n != null)
|
.flat(Infinity)
|
||||||
.map(n => isNode(n) ? n : document.createTextNode(String(n)));
|
.filter(n => n != null)
|
||||||
|
.map(n => isNode(n) ? n : document.createTextNode(String(n)));
|
||||||
|
|
||||||
const nextSet = new Set(next);
|
// Diffing Bidireccional (Estilo Sigwork)
|
||||||
nodes.forEach(n => { if (!nextSet.has(n)) destroy(n); });
|
const oldNodes = nodes.filter(n => {
|
||||||
next.forEach((n, i) => {
|
const keep = next.includes(n);
|
||||||
if (nodes[i] !== n) marker.parentNode.insertBefore(n, nodes[i] || marker);
|
if (!keep) destroy(n);
|
||||||
});
|
return keep;
|
||||||
nodes = next;
|
});
|
||||||
});
|
|
||||||
} else {
|
const oldIdxs = new Map(oldNodes.map((n, i) => [n, i]));
|
||||||
parent.appendChild(isNode(child) ? child : document.createTextNode(String(child)));
|
let p = oldNodes.length - 1;
|
||||||
}
|
|
||||||
|
for (let i = next.length - 1; i >= 0; i--) {
|
||||||
|
const node = next[i];
|
||||||
|
const ref = next[i + 1] || anchor;
|
||||||
|
if (!oldIdxs.has(node)) {
|
||||||
|
parent.insertBefore(node, ref);
|
||||||
|
} else if (oldNodes[p] !== node) {
|
||||||
|
parent.insertBefore(node, ref);
|
||||||
|
} else {
|
||||||
|
p--;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
nodes = next;
|
||||||
|
}, true);
|
||||||
|
} else {
|
||||||
|
parent.appendChild(isNode(child) ? child : document.createTextNode(String(child)));
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
export const h = (tag, props = {}, ...children) => {
|
export const h = (tag, props = {}, ...children) => {
|
||||||
if (typeof tag === 'function') {
|
props = props || {};
|
||||||
const prevCtx = currentContext;
|
const flatChildren = children.flat(Infinity);
|
||||||
const context = { mount: [], unmount: [], Share: {}, parent: prevCtx, cleanups: new Set() };
|
|
||||||
currentContext = context;
|
|
||||||
const prevOwner = currentOwner;
|
|
||||||
currentOwner = context;
|
|
||||||
|
|
||||||
const el = tag(props, { children: children.flat(Infinity) });
|
// 4. Fragments (Tag nulo o vacío)
|
||||||
if (isNode(el)) nodeContexts.set(el, context);
|
if (!tag) return () => flatChildren;
|
||||||
|
|
||||||
currentContext = prevCtx;
|
// 1. Componentes (Funciones)
|
||||||
currentOwner = prevOwner;
|
if (typeof tag === 'function') {
|
||||||
queueMicrotask(() => context.mount.forEach(fn => fn()));
|
const context = { mount: [], unmount: [], Share: {}, parent: currentContext, cleanups: new Set() };
|
||||||
return el;
|
const prevCtx = currentContext;
|
||||||
}
|
currentContext = context;
|
||||||
|
const el = tag(props, { children: flatChildren });
|
||||||
const el = document.createElement(tag);
|
if (isNode(el)) nodeContexts.set(el, context);
|
||||||
for (const key in props) {
|
currentContext = prevCtx;
|
||||||
const val = props[key];
|
queueMicrotask(() => context.mount.forEach(fn => fn()));
|
||||||
|
return el;
|
||||||
if (key.startsWith('on')) {
|
|
||||||
el.addEventListener(key.slice(2).toLowerCase(), val);
|
|
||||||
}
|
}
|
||||||
else if (typeof val === 'function' || (val && val._isSig)) {
|
|
||||||
Effect(() => {
|
// 1. Soporte SVG
|
||||||
const v = typeof val === 'function' ? val() : val.value;
|
let el;
|
||||||
el[key] = (key === 'href' || key === 'src') ? sanitize(v) : v;
|
const isSVG = tag === 'svg' || tag === 'path' || tag === 'circle' || tag === 'rect' || tag === 'g';
|
||||||
});
|
if (isSVG) {
|
||||||
|
el = document.createElementNS("http://www.w3.org/2000/svg", tag);
|
||||||
} else {
|
} else {
|
||||||
el[key] = (key === 'href' || key === 'src') ? sanitize(val) : val;
|
el = document.createElement(tag);
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
children.flat(Infinity).forEach(c => append(el, c));
|
for (const key in props) {
|
||||||
return el;
|
const val = props[key];
|
||||||
|
if (key.startsWith('on')) {
|
||||||
|
el.addEventListener(key.slice(2).toLowerCase(), val);
|
||||||
|
}
|
||||||
|
// 2. Soporte para Refs
|
||||||
|
else if (key === 'ref') {
|
||||||
|
if (typeof val === 'function') val(el);
|
||||||
|
else if (val && val._isSig) val.value = el;
|
||||||
|
}
|
||||||
|
else if (typeof val === 'function' || (val && val._isSig)) {
|
||||||
|
Effect(() => {
|
||||||
|
const v = typeof val === 'function' ? val() : val.value;
|
||||||
|
const attr = (key === 'href' || key === 'src') ? sanitize(v) : v;
|
||||||
|
if (!isSVG && key in el) el[key] = attr; else el.setAttribute(key, attr);
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
const attr = (key === 'href' || key === 'src') ? sanitize(val) : val;
|
||||||
|
if (!isSVG && key in el) el[key] = attr; else el.setAttribute(key, attr);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
flatChildren.forEach(c => append(el, c));
|
||||||
|
return el;
|
||||||
};
|
};
|
||||||
|
|
||||||
// --- Conditionals & Loops ---
|
// --- Helpers ---
|
||||||
export const If = (cond, a, b) => () => cond() ? a() : (b ? b() : null);
|
export const If = (cond, a, b) => () => cond() ? a() : (b ? b() : null);
|
||||||
|
|
||||||
export const For = (list, key, render) => {
|
export const For = (list, key, render) => {
|
||||||
let cache = new Map();
|
let cache = new Map();
|
||||||
return () => {
|
return () => {
|
||||||
const items = list();
|
const items = typeof list === 'function' ? list() : list.value;
|
||||||
const nextCache = new Map();
|
const nextCache = new Map();
|
||||||
const nodes = items.map((item, i) => {
|
const nodes = items.map((item, i) => {
|
||||||
const k = key ? key(item, i) : i;
|
const k = key ? key(item, i) : (item.id || i);
|
||||||
let node = cache.get(k);
|
let node = cache.get(k);
|
||||||
if (!node) node = render(item, i);
|
if (!node) node = render(item, i);
|
||||||
nextCache.set(k, node);
|
nextCache.set(k, node);
|
||||||
return node;
|
return node;
|
||||||
});
|
});
|
||||||
cache.forEach((n, k) => { if (!nextCache.has(k)) destroy(n); });
|
cache = nextCache;
|
||||||
cache = nextCache;
|
return nodes;
|
||||||
return nodes;
|
};
|
||||||
};
|
|
||||||
};
|
};
|
||||||
|
|
||||||
// --- Router ---
|
// --- Router ---
|
||||||
export const Router = (routes) => {
|
export const Router = (routes) => {
|
||||||
const path = Signal(window.location.hash.replace(/^#/, '') || '/');
|
const path = Signal(window.location.hash.replace(/^#/, '') || '/');
|
||||||
window.addEventListener('hashchange', () => path.value = window.location.hash.replace(/^#/, '') || '/');
|
window.addEventListener('hashchange', () => path.value = window.location.hash.replace(/^#/, '') || '/');
|
||||||
let view = null;
|
const outlet = h('div', { class: 'router-outlet' });
|
||||||
const outlet = h('div', { class: 'router-outlet' });
|
let currentView = null;
|
||||||
Effect(() => {
|
Effect(() => {
|
||||||
const route = routes.find(r => r.path === path.value) || routes.find(r => r.path === '*');
|
const route = routes.find(r => r.path === path.value) || routes.find(r => r.path === '*');
|
||||||
if (view) destroy(view);
|
if (currentView) destroy(currentView);
|
||||||
if (route) {
|
if (route) {
|
||||||
view = route.component();
|
currentView = route.component();
|
||||||
outlet.appendChild(view);
|
outlet.appendChild(currentView);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
return outlet;
|
return outlet;
|
||||||
};
|
};
|
||||||
|
|
||||||
// --- Mounting ---
|
|
||||||
export const Mount = (root, target) => {
|
export const Mount = (root, target) => {
|
||||||
const container = typeof target === 'string' ? document.querySelector(target) : target;
|
const container = typeof target === 'string' ? document.querySelector(target) : target;
|
||||||
const el = typeof root === 'function' ? root() : root;
|
const el = typeof root === 'function' ? root() : root;
|
||||||
container.replaceChildren(el);
|
container.replaceChildren(el);
|
||||||
return () => destroy(el);
|
return () => destroy(el);
|
||||||
};
|
};
|
||||||
|
|
||||||
// --- Export API ---
|
export const onMount = (fn) => currentContext?.mount.push(fn);
|
||||||
export default { Signal, Computed, Storage, Effect, Reactive, Watch, h, If, For, Router, Mount, Share, Use, onMount, onUnmount };
|
export const onUnmount = (fn) => currentContext?.unmount.push(fn);
|
||||||
export { h as jsx, h as jsxs, h as Fragment };
|
export const Share = (key, value) => { if (currentContext) currentContext.Share[key] = value; };
|
||||||
|
export const Use = (key, def) => {
|
||||||
|
let ctx = currentContext;
|
||||||
|
while (ctx) {
|
||||||
|
if (ctx.Share[key] !== undefined) return ctx.Share[key];
|
||||||
|
ctx = ctx.parent;
|
||||||
|
}
|
||||||
|
return def;
|
||||||
|
};
|
||||||
|
|
||||||
|
export default { Signal, Computed, Storage, Effect, h, If, For, Router, Mount, Share, Use, onMount, onUnmount };
|
||||||
Reference in New Issue
Block a user