Este sigpro es optimizado leible y con For muy rapido tipo Sigwork

This commit is contained in:
2026-04-13 11:28:14 +02:00
parent d0b55ff354
commit 00b9b8f911
10 changed files with 597 additions and 497 deletions

View File

@@ -6129,11 +6129,6 @@
.filter { .filter {
filter: var(--tw-blur,) var(--tw-brightness,) var(--tw-contrast,) var(--tw-grayscale,) var(--tw-hue-rotate,) var(--tw-invert,) var(--tw-saturate,) var(--tw-sepia,) var(--tw-drop-shadow,); filter: var(--tw-blur,) var(--tw-brightness,) var(--tw-contrast,) var(--tw-grayscale,) var(--tw-hue-rotate,) var(--tw-invert,) var(--tw-saturate,) var(--tw-sepia,) var(--tw-drop-shadow,);
} }
.transition {
transition-property: color, background-color, border-color, outline-color, text-decoration-color, fill, stroke, --tw-gradient-from, --tw-gradient-via, --tw-gradient-to, opacity, box-shadow, transform, translate, scale, rotate, filter, -webkit-backdrop-filter, backdrop-filter, display, content-visibility, overlay, pointer-events;
transition-timing-function: var(--tw-ease, var(--default-transition-timing-function));
transition-duration: var(--tw-duration, var(--default-transition-duration));
}
.transition-all { .transition-all {
transition-property: all; transition-property: all;
transition-timing-function: var(--tw-ease, var(--default-transition-timing-function)); transition-timing-function: var(--tw-ease, var(--default-transition-timing-function));

2
css/sigpro.min.css vendored

File diff suppressed because one or more lines are too long

259
dist/sigpro-ui.esm.js vendored
View File

@@ -10,34 +10,33 @@ var __export = (target, all) => {
}; };
// src/sigpro.js // src/sigpro.js
var isFunc = (f) => typeof f === "function"; var isFunc = (fn) => typeof fn === "function";
var isObj = (o) => o && typeof o === "object";
var isArr = Array.isArray; var isArr = Array.isArray;
var doc = typeof document !== "undefined" ? document : null; var doc = typeof document !== "undefined" ? document : null;
var ensureNode = (n) => n?._isRuntime ? n.container : n instanceof Node ? n : doc.createTextNode(n == null ? "" : String(n)); var ensureNode = (node) => node?._isRuntime ? node.container : node instanceof Node ? node : doc.createTextNode(node == null ? "" : String(node));
var activeEffect = null; var activeEffect = null;
var activeOwner = null; var activeOwner = null;
var isFlushing = false; var isFlushing = false;
var effectQueue = new Set; var effectQueue = new Set;
var MOUNTED_NODES = new WeakMap; var MOUNTED_NODES = new WeakMap;
var dispose = (eff) => { var dispose = (effect) => {
if (!eff || eff._disposed) if (!effect || effect._disposed)
return; return;
eff._disposed = true; effect._disposed = true;
const stack = [eff]; const stack = [effect];
while (stack.length) { while (stack.length) {
const e = stack.pop(); const eff = stack.pop();
if (e._cleanups) { if (eff._cleanups) {
e._cleanups.forEach((fn) => fn()); eff._cleanups.forEach((fn) => fn());
e._cleanups.clear(); eff._cleanups.clear();
} }
if (e._children) { if (eff._children) {
e._children.forEach((child) => stack.push(child)); eff._children.forEach((child) => stack.push(child));
e._children.clear(); eff._children.clear();
} }
if (e._deps) { if (eff._deps) {
e._deps.forEach((depSet) => depSet.delete(e)); eff._deps.forEach((depSet) => depSet.delete(eff));
e._deps.clear(); eff._deps.clear();
} }
} }
}; };
@@ -52,7 +51,7 @@ var createEffect = (fn, isComputed = false) => {
if (effect._deps) if (effect._deps)
effect._deps.forEach((depSet) => depSet.delete(effect)); effect._deps.forEach((depSet) => depSet.delete(effect));
if (effect._cleanups) { if (effect._cleanups) {
effect._cleanups.forEach((cl) => cl()); effect._cleanups.forEach((cleanup) => cleanup());
effect._cleanups.clear(); effect._cleanups.clear();
} }
const prevEffect = activeEffect; const prevEffect = activeEffect;
@@ -84,9 +83,9 @@ var flush = () => {
isFlushing = true; isFlushing = true;
const sorted = Array.from(effectQueue).sort((a, b) => a._depth - b._depth); const sorted = Array.from(effectQueue).sort((a, b) => a._depth - b._depth);
effectQueue.clear(); effectQueue.clear();
for (const e of sorted) for (const eff of sorted)
if (!e._disposed) if (!eff._disposed)
e(); eff();
isFlushing = false; isFlushing = false;
}; };
var trackUpdate = (subs, trigger = false) => { var trackUpdate = (subs, trigger = false) => {
@@ -95,15 +94,15 @@ var trackUpdate = (subs, trigger = false) => {
(activeEffect._deps ||= new Set).add(subs); (activeEffect._deps ||= new Set).add(subs);
} else if (trigger) { } else if (trigger) {
let hasQueue = false; let hasQueue = false;
subs.forEach((e) => { subs.forEach((eff) => {
if (e === activeEffect || e._disposed) if (eff === activeEffect || eff._disposed)
return; return;
if (e._isComputed) { if (eff._isComputed) {
e._dirty = true; eff._dirty = true;
if (e._subs) if (eff._subs)
trackUpdate(e._subs, true); trackUpdate(eff._subs, true);
} else { } else {
effectQueue.add(e); effectQueue.add(eff);
hasQueue = true; hasQueue = true;
} }
}); });
@@ -112,28 +111,28 @@ var trackUpdate = (subs, trigger = false) => {
} }
}; };
var untrack = (fn) => { var untrack = (fn) => {
const p = activeEffect; const prev = activeEffect;
activeEffect = null; activeEffect = null;
try { try {
return fn(); return fn();
} finally { } finally {
activeEffect = p; activeEffect = prev;
} }
}; };
var onMount = (fn) => { var onMount = (fn) => {
if (activeOwner) if (activeOwner)
(activeOwner._mounts ||= []).push(fn); (activeOwner._mounts ||= []).push(fn);
}; };
var $2 = (val, key = null) => { var $2 = (value, storageKey = null) => {
const subs = new Set; const subs = new Set;
if (isFunc(val)) { if (isFunc(value)) {
let cache, dirty = true; let cache, dirty = true;
const computed = () => { const computed = () => {
if (dirty) { if (dirty) {
const prev = activeEffect; const prev = activeEffect;
activeEffect = computed; activeEffect = computed;
try { try {
const next = val(); const next = value();
if (!Object.is(cache, next)) { if (!Object.is(cache, next)) {
cache = next; cache = next;
dirty = false; dirty = false;
@@ -166,33 +165,33 @@ var $2 = (val, key = null) => {
onUnmount(computed.stop); onUnmount(computed.stop);
return computed; return computed;
} }
if (key) if (storageKey)
try { try {
val = JSON.parse(localStorage.getItem(key)) ?? val; value = JSON.parse(localStorage.getItem(storageKey)) ?? value;
} catch (e) {} } catch (e) {}
return (...args) => { return (...args) => {
if (args.length) { if (args.length) {
const next = isFunc(args[0]) ? args[0](val) : args[0]; const next = isFunc(args[0]) ? args[0](value) : args[0];
if (!Object.is(val, next)) { if (!Object.is(value, next)) {
val = next; value = next;
if (key) if (storageKey)
localStorage.setItem(key, JSON.stringify(val)); localStorage.setItem(storageKey, JSON.stringify(value));
trackUpdate(subs, true); trackUpdate(subs, true);
} }
} }
trackUpdate(subs); trackUpdate(subs);
return val; return value;
}; };
}; };
var Watch2 = (sources, cb) => { var Watch2 = (sources, callback) => {
if (cb === undefined) { if (callback === undefined) {
const effect2 = createEffect(sources); const effect2 = createEffect(sources);
effect2(); effect2();
return () => dispose(effect2); return () => dispose(effect2);
} }
const effect = createEffect(() => { const effect = createEffect(() => {
const vals = Array.isArray(sources) ? sources.map((s) => s()) : sources(); const vals = isArr(sources) ? sources.map((src) => src()) : sources();
untrack(() => cb(vals)); untrack(() => callback(vals));
}); });
effect(); effect();
return () => dispose(effect); return () => dispose(effect);
@@ -212,17 +211,12 @@ var isDangerousAttr = (key) => key === "src" || key === "href" || key.startsWith
var validateAttr = (key, val) => { var validateAttr = (key, val) => {
if (val == null || val === false) if (val == null || val === false)
return null; return null;
if (isDangerousAttr(key)) { if (isDangerousAttr(key) && DANGEROUS_PROTOCOL.test(String(val)))
const sVal = String(val); return "#";
if (DANGEROUS_PROTOCOL.test(sVal)) {
console.warn(`[SigPro] Bloqueado protocolo peligroso en ${key}`);
return "#";
}
}
return val; return val;
}; };
var Tag2 = (tag, props = {}, children = []) => { var Tag2 = (tag, props = {}, children = []) => {
if (props instanceof Node || isArr(props) || !isObj(props)) { if (props instanceof Node || isArr(props) || props && typeof props !== "object") {
children = props; children = props;
props = {}; props = {};
} }
@@ -240,7 +234,13 @@ var Tag2 = (tag, props = {}, children = []) => {
ctx._mounts = effect._mounts || []; ctx._mounts = effect._mounts || [];
ctx._cleanups = effect._cleanups || new Set; ctx._cleanups = effect._cleanups || new Set;
const result = effect._result; const result = effect._result;
const attachLifecycle = (node) => node && typeof node === "object" && !node._isRuntime && (node._mounts = ctx._mounts, node._cleanups = ctx._cleanups, node._ownerEffect = effect); const attachLifecycle = (node) => {
if (node && typeof node === "object" && !node._isRuntime) {
node._mounts = ctx._mounts;
node._cleanups = ctx._cleanups;
node._ownerEffect = effect;
}
};
isArr(result) ? result.forEach(attachLifecycle) : attachLifecycle(result); isArr(result) ? result.forEach(attachLifecycle) : attachLifecycle(result);
if (result == null) if (result == null)
return null; return null;
@@ -248,61 +248,61 @@ var Tag2 = (tag, props = {}, children = []) => {
return result; return result;
return doc.createTextNode(String(result)); return doc.createTextNode(String(result));
} }
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|image|ellipse|foreignObject|linearGradient|radialGradient|stop|pattern|mask|clipPath|filter|feColorMatrix|feBlend|feGaussianBlur|animate|animateTransform|set|metadata|desc|title|symbol|marker|view)$/i.test(tag);
const el = isSVG ? doc.createElementNS("http://www.w3.org/2000/svg", tag) : doc.createElement(tag); const elem = isSVG ? doc.createElementNS("http://www.w3.org/2000/svg", tag) : doc.createElement(tag);
el._cleanups = new Set; elem._cleanups = new Set;
for (let k in props) { for (let key in props) {
if (!props.hasOwnProperty(k)) if (!props.hasOwnProperty(key))
continue; continue;
let v = props[k]; let value = props[key];
if (k === "ref") { if (key === "ref") {
isFunc(v) ? v(el) : v.current = el; isFunc(value) ? value(elem) : value.current = elem;
continue; continue;
} }
if (k.startsWith("on")) { if (key.startsWith("on")) {
const ev = k.slice(2).toLowerCase(); const event = key.slice(2).toLowerCase();
el.addEventListener(ev, v); elem.addEventListener(event, value);
const off = () => el.removeEventListener(ev, v); const off = () => elem.removeEventListener(event, value);
el._cleanups.add(off); elem._cleanups.add(off);
onUnmount(off); onUnmount(off);
} else if (isFunc(v)) { } else if (isFunc(value)) {
const effect = createEffect(() => { const effect = createEffect(() => {
const val = validateAttr(k, v()); const val = validateAttr(key, value());
if (k === "class") if (key === "class")
el.className = val || ""; elem.className = val || "";
else if (val == null) else if (val == null)
el.removeAttribute(k); elem.removeAttribute(key);
else if (k in el && !isSVG) else if (key in elem && !isSVG)
el[k] = val; elem[key] = val;
else else
el.setAttribute(k, val === true ? "" : val); elem.setAttribute(key, val === true ? "" : val);
}); });
effect(); effect();
el._cleanups.add(() => dispose(effect)); elem._cleanups.add(() => dispose(effect));
onUnmount(() => dispose(effect)); onUnmount(() => dispose(effect));
if (/^(INPUT|TEXTAREA|SELECT)$/.test(el.tagName) && (k === "value" || k === "checked")) { if (/^(INPUT|TEXTAREA|SELECT)$/.test(elem.tagName) && (key === "value" || key === "checked")) {
const evType = k === "checked" ? "change" : "input"; const eventType = key === "checked" ? "change" : "input";
el.addEventListener(evType, (ev) => v(ev.target[k])); elem.addEventListener(eventType, (ev) => value(ev.target[key]));
} }
} else { } else {
const val = validateAttr(k, v); const val = validateAttr(key, value);
if (val != null) { if (val != null) {
if (k in el && !isSVG) if (key in elem && !isSVG)
el[k] = val; elem[key] = val;
else else
el.setAttribute(k, val === true ? "" : val); elem.setAttribute(key, val === true ? "" : val);
} }
} }
} }
const append = (c) => { const append = (child) => {
if (isArr(c)) if (isArr(child))
return c.forEach(append); return child.forEach(append);
if (isFunc(c)) { if (isFunc(child)) {
const anchor = doc.createTextNode(""); const anchor = doc.createTextNode("");
el.appendChild(anchor); elem.appendChild(anchor);
let currentNodes = []; let currentNodes = [];
const effect = createEffect(() => { const effect = createEffect(() => {
const res = c(); const res = child();
const next = (isArr(res) ? res : [res]).map(ensureNode); const next = (isArr(res) ? res : [res]).map(ensureNode);
currentNodes.forEach((n) => { currentNodes.forEach((n) => {
if (n._isRuntime) if (n._isRuntime)
@@ -324,43 +324,55 @@ var Tag2 = (tag, props = {}, children = []) => {
currentNodes = next; currentNodes = next;
}); });
effect(); effect();
el._cleanups.add(() => dispose(effect)); elem._cleanups.add(() => dispose(effect));
onUnmount(() => dispose(effect)); onUnmount(() => dispose(effect));
} else { } else {
const node = ensureNode(c); const node = ensureNode(child);
el.appendChild(node); elem.appendChild(node);
if (node._mounts) if (node._mounts)
node._mounts.forEach((fn) => fn()); node._mounts.forEach((fn) => fn());
} }
}; };
append(children); append(children);
return el; return elem;
}; };
var Render = (renderFn) => { var createView = (renderFn) => {
const cleanups = new Set; const cleanups = new Set;
const mounts = []; const mounts = [];
const previousOwner = activeOwner; const previousOwner = activeOwner;
activeOwner = { _cleanups: cleanups, _mounts: mounts };
const result = renderFn({ onCleanup: (fn) => cleanups.add(fn) });
activeOwner = previousOwner;
if (result == null)
return null;
if (result instanceof Node) {
mounts.forEach((fn) => fn());
return {
_isRuntime: true,
container: result,
destroy: () => {
cleanups.forEach((fn) => fn());
cleanupNode(result);
result.remove();
}
};
}
const container = doc.createElement("div"); const container = doc.createElement("div");
container.style.display = "contents"; container.style.display = "contents";
container.setAttribute("role", "presentation"); container.setAttribute("role", "presentation");
activeOwner = { _cleanups: cleanups, _mounts: mounts }; const process = (node) => {
const processResult = (result) => { if (!node)
if (!result)
return; return;
if (result._isRuntime) { if (node._isRuntime) {
cleanups.add(result.destroy); cleanups.add(node.destroy);
container.appendChild(result.container); container.appendChild(node.container);
} else if (isArr(result)) { } else if (isArr(node)) {
result.forEach(processResult); node.forEach(process);
} else { } else {
container.appendChild(result instanceof Node ? result : doc.createTextNode(String(result == null ? "" : result))); container.appendChild(node instanceof Node ? node : doc.createTextNode(String(node)));
} }
}; };
try { process(result);
processResult(renderFn({ onCleanup: (fn) => cleanups.add(fn) }));
} finally {
activeOwner = previousOwner;
}
mounts.forEach((fn) => fn()); mounts.forEach((fn) => fn());
return { return {
_isRuntime: true, _isRuntime: true,
@@ -402,7 +414,7 @@ var If2 = (cond, ifYes, ifNot = null, trans = null) => {
} }
const content = show ? ifYes : ifNot; const content = show ? ifYes : ifNot;
if (content) { if (content) {
currentView = Render(() => isFunc(content) ? content() : content); currentView = createView(() => isFunc(content) ? content() : content);
root.insertBefore(currentView.container, anchor); root.insertBefore(currentView.container, anchor);
if (trans?.in) if (trans?.in)
trans.in(currentView.container); trans.in(currentView.container);
@@ -423,7 +435,7 @@ var For2 = (src, itemFn, keyFn) => {
const key = keyFn ? keyFn(item, i) : item?.id ?? i; const key = keyFn ? keyFn(item, i) : item?.id ?? i;
let view = cache.get(key); let view = cache.get(key);
if (!view) if (!view)
view = Render(() => itemFn(item, i)); view = createView(() => itemFn(item, i));
else else
cache.delete(key); cache.delete(key);
nextCache.set(key, view); nextCache.set(key, view);
@@ -453,9 +465,9 @@ var Router = (routes) => {
Watch2([path], () => { Watch2([path], () => {
const cur = path(); const cur = path();
const route = routes.find((r) => { const route = routes.find((r) => {
const p1 = r.path.split("/").filter(Boolean); const rParts = r.path.split("/").filter(Boolean);
const p2 = cur.split("/").filter(Boolean); const curParts = cur.split("/").filter(Boolean);
return p1.length === p2.length && p1.every((p, i) => p[0] === ":" || p === p2[i]); return rParts.length === curParts.length && rParts.every((p, i) => p[0] === ":" || p === curParts[i]);
}) || routes.find((r) => r.path === "*"); }) || routes.find((r) => r.path === "*");
if (route) { if (route) {
currentView?.destroy(); currentView?.destroy();
@@ -465,14 +477,14 @@ var Router = (routes) => {
params[p.slice(1)] = cur.split("/").filter(Boolean)[i]; params[p.slice(1)] = cur.split("/").filter(Boolean)[i];
}); });
Router.params(params); Router.params(params);
currentView = Render(() => isFunc(route.component) ? route.component(params) : route.component); currentView = createView(() => isFunc(route.component) ? route.component(params) : route.component);
outlet.replaceChildren(currentView.container); outlet.replaceChildren(currentView.container);
} }
}); });
return outlet; return outlet;
}; };
Router.params = $2({}); Router.params = $2({});
Router.to = (p) => window.location.hash = p.replace(/^#?\/?/, "#/"); Router.to = (path) => window.location.hash = path.replace(/^#?\/?/, "#/");
Router.back = () => window.history.back(); Router.back = () => window.history.back();
Router.path = () => window.location.hash.replace(/^#/, "") || "/"; Router.path = () => window.location.hash.replace(/^#/, "") || "/";
var Mount2 = (comp, target) => { var Mount2 = (comp, target) => {
@@ -481,12 +493,24 @@ var Mount2 = (comp, target) => {
return; return;
if (MOUNTED_NODES.has(t)) if (MOUNTED_NODES.has(t))
MOUNTED_NODES.get(t).destroy(); MOUNTED_NODES.get(t).destroy();
const inst = Render(isFunc(comp) ? comp : () => comp); const inst = createView(() => isFunc(comp) ? comp() : comp);
t.replaceChildren(inst.container); t.replaceChildren(inst.container);
MOUNTED_NODES.set(t, inst); MOUNTED_NODES.set(t, inst);
return inst; return inst;
}; };
var SigPro = Object.freeze({ $: $2, Watch: Watch2, Tag: Tag2, Render, If: If2, For: For2, Router, Mount: Mount2, onMount, onUnmount }); var set = (signal, path, value) => {
if (value === undefined) {
signal(isFunc(path) ? path(signal()) : path);
} else {
const keys = path.split(".");
const last = keys.pop();
const current = signal();
const obj = keys.reduce((o, k) => ({ ...o, [k]: { ...o[k] } }), { ...current });
obj[last] = value;
signal(obj);
}
};
var SigPro = Object.freeze({ $: $2, Watch: Watch2, Tag: Tag2, If: If2, For: For2, Router, Mount: Mount2, onMount, onUnmount, set });
if (typeof window !== "undefined") { if (typeof window !== "undefined") {
Object.assign(window, SigPro); 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)); "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));
@@ -1960,7 +1984,6 @@ export {
Stack, Stack,
Select, Select,
Router, Router,
Render,
Rating, Rating,
Range, Range,
Radio, Radio,

File diff suppressed because one or more lines are too long

259
dist/sigpro-ui.js vendored
View File

@@ -46,7 +46,6 @@
Stack: () => Stack, Stack: () => Stack,
Select: () => Select, Select: () => Select,
Router: () => Router, Router: () => Router,
Render: () => Render,
Rating: () => Rating, Rating: () => Rating,
Range: () => Range, Range: () => Range,
Radio: () => Radio, Radio: () => Radio,
@@ -77,34 +76,33 @@
}); });
// src/sigpro.js // src/sigpro.js
var isFunc = (f) => typeof f === "function"; var isFunc = (fn) => typeof fn === "function";
var isObj = (o) => o && typeof o === "object";
var isArr = Array.isArray; var isArr = Array.isArray;
var doc = typeof document !== "undefined" ? document : null; var doc = typeof document !== "undefined" ? document : null;
var ensureNode = (n) => n?._isRuntime ? n.container : n instanceof Node ? n : doc.createTextNode(n == null ? "" : String(n)); var ensureNode = (node) => node?._isRuntime ? node.container : node instanceof Node ? node : doc.createTextNode(node == null ? "" : String(node));
var activeEffect = null; var activeEffect = null;
var activeOwner = null; var activeOwner = null;
var isFlushing = false; var isFlushing = false;
var effectQueue = new Set; var effectQueue = new Set;
var MOUNTED_NODES = new WeakMap; var MOUNTED_NODES = new WeakMap;
var dispose = (eff) => { var dispose = (effect) => {
if (!eff || eff._disposed) if (!effect || effect._disposed)
return; return;
eff._disposed = true; effect._disposed = true;
const stack = [eff]; const stack = [effect];
while (stack.length) { while (stack.length) {
const e = stack.pop(); const eff = stack.pop();
if (e._cleanups) { if (eff._cleanups) {
e._cleanups.forEach((fn) => fn()); eff._cleanups.forEach((fn) => fn());
e._cleanups.clear(); eff._cleanups.clear();
} }
if (e._children) { if (eff._children) {
e._children.forEach((child) => stack.push(child)); eff._children.forEach((child) => stack.push(child));
e._children.clear(); eff._children.clear();
} }
if (e._deps) { if (eff._deps) {
e._deps.forEach((depSet) => depSet.delete(e)); eff._deps.forEach((depSet) => depSet.delete(eff));
e._deps.clear(); eff._deps.clear();
} }
} }
}; };
@@ -119,7 +117,7 @@
if (effect._deps) if (effect._deps)
effect._deps.forEach((depSet) => depSet.delete(effect)); effect._deps.forEach((depSet) => depSet.delete(effect));
if (effect._cleanups) { if (effect._cleanups) {
effect._cleanups.forEach((cl) => cl()); effect._cleanups.forEach((cleanup) => cleanup());
effect._cleanups.clear(); effect._cleanups.clear();
} }
const prevEffect = activeEffect; const prevEffect = activeEffect;
@@ -151,9 +149,9 @@
isFlushing = true; isFlushing = true;
const sorted = Array.from(effectQueue).sort((a, b) => a._depth - b._depth); const sorted = Array.from(effectQueue).sort((a, b) => a._depth - b._depth);
effectQueue.clear(); effectQueue.clear();
for (const e of sorted) for (const eff of sorted)
if (!e._disposed) if (!eff._disposed)
e(); eff();
isFlushing = false; isFlushing = false;
}; };
var trackUpdate = (subs, trigger = false) => { var trackUpdate = (subs, trigger = false) => {
@@ -162,15 +160,15 @@
(activeEffect._deps ||= new Set).add(subs); (activeEffect._deps ||= new Set).add(subs);
} else if (trigger) { } else if (trigger) {
let hasQueue = false; let hasQueue = false;
subs.forEach((e) => { subs.forEach((eff) => {
if (e === activeEffect || e._disposed) if (eff === activeEffect || eff._disposed)
return; return;
if (e._isComputed) { if (eff._isComputed) {
e._dirty = true; eff._dirty = true;
if (e._subs) if (eff._subs)
trackUpdate(e._subs, true); trackUpdate(eff._subs, true);
} else { } else {
effectQueue.add(e); effectQueue.add(eff);
hasQueue = true; hasQueue = true;
} }
}); });
@@ -179,28 +177,28 @@
} }
}; };
var untrack = (fn) => { var untrack = (fn) => {
const p = activeEffect; const prev = activeEffect;
activeEffect = null; activeEffect = null;
try { try {
return fn(); return fn();
} finally { } finally {
activeEffect = p; activeEffect = prev;
} }
}; };
var onMount = (fn) => { var onMount = (fn) => {
if (activeOwner) if (activeOwner)
(activeOwner._mounts ||= []).push(fn); (activeOwner._mounts ||= []).push(fn);
}; };
var $2 = (val, key = null) => { var $2 = (value, storageKey = null) => {
const subs = new Set; const subs = new Set;
if (isFunc(val)) { if (isFunc(value)) {
let cache, dirty = true; let cache, dirty = true;
const computed = () => { const computed = () => {
if (dirty) { if (dirty) {
const prev = activeEffect; const prev = activeEffect;
activeEffect = computed; activeEffect = computed;
try { try {
const next = val(); const next = value();
if (!Object.is(cache, next)) { if (!Object.is(cache, next)) {
cache = next; cache = next;
dirty = false; dirty = false;
@@ -233,33 +231,33 @@
onUnmount(computed.stop); onUnmount(computed.stop);
return computed; return computed;
} }
if (key) if (storageKey)
try { try {
val = JSON.parse(localStorage.getItem(key)) ?? val; value = JSON.parse(localStorage.getItem(storageKey)) ?? value;
} catch (e) {} } catch (e) {}
return (...args) => { return (...args) => {
if (args.length) { if (args.length) {
const next = isFunc(args[0]) ? args[0](val) : args[0]; const next = isFunc(args[0]) ? args[0](value) : args[0];
if (!Object.is(val, next)) { if (!Object.is(value, next)) {
val = next; value = next;
if (key) if (storageKey)
localStorage.setItem(key, JSON.stringify(val)); localStorage.setItem(storageKey, JSON.stringify(value));
trackUpdate(subs, true); trackUpdate(subs, true);
} }
} }
trackUpdate(subs); trackUpdate(subs);
return val; return value;
}; };
}; };
var Watch2 = (sources, cb) => { var Watch2 = (sources, callback) => {
if (cb === undefined) { if (callback === undefined) {
const effect2 = createEffect(sources); const effect2 = createEffect(sources);
effect2(); effect2();
return () => dispose(effect2); return () => dispose(effect2);
} }
const effect = createEffect(() => { const effect = createEffect(() => {
const vals = Array.isArray(sources) ? sources.map((s) => s()) : sources(); const vals = isArr(sources) ? sources.map((src) => src()) : sources();
untrack(() => cb(vals)); untrack(() => callback(vals));
}); });
effect(); effect();
return () => dispose(effect); return () => dispose(effect);
@@ -279,17 +277,12 @@
var validateAttr = (key, val) => { var validateAttr = (key, val) => {
if (val == null || val === false) if (val == null || val === false)
return null; return null;
if (isDangerousAttr(key)) { if (isDangerousAttr(key) && DANGEROUS_PROTOCOL.test(String(val)))
const sVal = String(val); return "#";
if (DANGEROUS_PROTOCOL.test(sVal)) {
console.warn(`[SigPro] Bloqueado protocolo peligroso en ${key}`);
return "#";
}
}
return val; return val;
}; };
var Tag2 = (tag, props = {}, children = []) => { var Tag2 = (tag, props = {}, children = []) => {
if (props instanceof Node || isArr(props) || !isObj(props)) { if (props instanceof Node || isArr(props) || props && typeof props !== "object") {
children = props; children = props;
props = {}; props = {};
} }
@@ -307,7 +300,13 @@
ctx._mounts = effect._mounts || []; ctx._mounts = effect._mounts || [];
ctx._cleanups = effect._cleanups || new Set; ctx._cleanups = effect._cleanups || new Set;
const result = effect._result; const result = effect._result;
const attachLifecycle = (node) => node && typeof node === "object" && !node._isRuntime && (node._mounts = ctx._mounts, node._cleanups = ctx._cleanups, node._ownerEffect = effect); const attachLifecycle = (node) => {
if (node && typeof node === "object" && !node._isRuntime) {
node._mounts = ctx._mounts;
node._cleanups = ctx._cleanups;
node._ownerEffect = effect;
}
};
isArr(result) ? result.forEach(attachLifecycle) : attachLifecycle(result); isArr(result) ? result.forEach(attachLifecycle) : attachLifecycle(result);
if (result == null) if (result == null)
return null; return null;
@@ -315,61 +314,61 @@
return result; return result;
return doc.createTextNode(String(result)); return doc.createTextNode(String(result));
} }
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|image|ellipse|foreignObject|linearGradient|radialGradient|stop|pattern|mask|clipPath|filter|feColorMatrix|feBlend|feGaussianBlur|animate|animateTransform|set|metadata|desc|title|symbol|marker|view)$/i.test(tag);
const el = isSVG ? doc.createElementNS("http://www.w3.org/2000/svg", tag) : doc.createElement(tag); const elem = isSVG ? doc.createElementNS("http://www.w3.org/2000/svg", tag) : doc.createElement(tag);
el._cleanups = new Set; elem._cleanups = new Set;
for (let k in props) { for (let key in props) {
if (!props.hasOwnProperty(k)) if (!props.hasOwnProperty(key))
continue; continue;
let v = props[k]; let value = props[key];
if (k === "ref") { if (key === "ref") {
isFunc(v) ? v(el) : v.current = el; isFunc(value) ? value(elem) : value.current = elem;
continue; continue;
} }
if (k.startsWith("on")) { if (key.startsWith("on")) {
const ev = k.slice(2).toLowerCase(); const event = key.slice(2).toLowerCase();
el.addEventListener(ev, v); elem.addEventListener(event, value);
const off = () => el.removeEventListener(ev, v); const off = () => elem.removeEventListener(event, value);
el._cleanups.add(off); elem._cleanups.add(off);
onUnmount(off); onUnmount(off);
} else if (isFunc(v)) { } else if (isFunc(value)) {
const effect = createEffect(() => { const effect = createEffect(() => {
const val = validateAttr(k, v()); const val = validateAttr(key, value());
if (k === "class") if (key === "class")
el.className = val || ""; elem.className = val || "";
else if (val == null) else if (val == null)
el.removeAttribute(k); elem.removeAttribute(key);
else if (k in el && !isSVG) else if (key in elem && !isSVG)
el[k] = val; elem[key] = val;
else else
el.setAttribute(k, val === true ? "" : val); elem.setAttribute(key, val === true ? "" : val);
}); });
effect(); effect();
el._cleanups.add(() => dispose(effect)); elem._cleanups.add(() => dispose(effect));
onUnmount(() => dispose(effect)); onUnmount(() => dispose(effect));
if (/^(INPUT|TEXTAREA|SELECT)$/.test(el.tagName) && (k === "value" || k === "checked")) { if (/^(INPUT|TEXTAREA|SELECT)$/.test(elem.tagName) && (key === "value" || key === "checked")) {
const evType = k === "checked" ? "change" : "input"; const eventType = key === "checked" ? "change" : "input";
el.addEventListener(evType, (ev) => v(ev.target[k])); elem.addEventListener(eventType, (ev) => value(ev.target[key]));
} }
} else { } else {
const val = validateAttr(k, v); const val = validateAttr(key, value);
if (val != null) { if (val != null) {
if (k in el && !isSVG) if (key in elem && !isSVG)
el[k] = val; elem[key] = val;
else else
el.setAttribute(k, val === true ? "" : val); elem.setAttribute(key, val === true ? "" : val);
} }
} }
} }
const append = (c) => { const append = (child) => {
if (isArr(c)) if (isArr(child))
return c.forEach(append); return child.forEach(append);
if (isFunc(c)) { if (isFunc(child)) {
const anchor = doc.createTextNode(""); const anchor = doc.createTextNode("");
el.appendChild(anchor); elem.appendChild(anchor);
let currentNodes = []; let currentNodes = [];
const effect = createEffect(() => { const effect = createEffect(() => {
const res = c(); const res = child();
const next = (isArr(res) ? res : [res]).map(ensureNode); const next = (isArr(res) ? res : [res]).map(ensureNode);
currentNodes.forEach((n) => { currentNodes.forEach((n) => {
if (n._isRuntime) if (n._isRuntime)
@@ -391,43 +390,55 @@
currentNodes = next; currentNodes = next;
}); });
effect(); effect();
el._cleanups.add(() => dispose(effect)); elem._cleanups.add(() => dispose(effect));
onUnmount(() => dispose(effect)); onUnmount(() => dispose(effect));
} else { } else {
const node = ensureNode(c); const node = ensureNode(child);
el.appendChild(node); elem.appendChild(node);
if (node._mounts) if (node._mounts)
node._mounts.forEach((fn) => fn()); node._mounts.forEach((fn) => fn());
} }
}; };
append(children); append(children);
return el; return elem;
}; };
var Render = (renderFn) => { var createView = (renderFn) => {
const cleanups = new Set; const cleanups = new Set;
const mounts = []; const mounts = [];
const previousOwner = activeOwner; const previousOwner = activeOwner;
activeOwner = { _cleanups: cleanups, _mounts: mounts };
const result = renderFn({ onCleanup: (fn) => cleanups.add(fn) });
activeOwner = previousOwner;
if (result == null)
return null;
if (result instanceof Node) {
mounts.forEach((fn) => fn());
return {
_isRuntime: true,
container: result,
destroy: () => {
cleanups.forEach((fn) => fn());
cleanupNode(result);
result.remove();
}
};
}
const container = doc.createElement("div"); const container = doc.createElement("div");
container.style.display = "contents"; container.style.display = "contents";
container.setAttribute("role", "presentation"); container.setAttribute("role", "presentation");
activeOwner = { _cleanups: cleanups, _mounts: mounts }; const process = (node) => {
const processResult = (result) => { if (!node)
if (!result)
return; return;
if (result._isRuntime) { if (node._isRuntime) {
cleanups.add(result.destroy); cleanups.add(node.destroy);
container.appendChild(result.container); container.appendChild(node.container);
} else if (isArr(result)) { } else if (isArr(node)) {
result.forEach(processResult); node.forEach(process);
} else { } else {
container.appendChild(result instanceof Node ? result : doc.createTextNode(String(result == null ? "" : result))); container.appendChild(node instanceof Node ? node : doc.createTextNode(String(node)));
} }
}; };
try { process(result);
processResult(renderFn({ onCleanup: (fn) => cleanups.add(fn) }));
} finally {
activeOwner = previousOwner;
}
mounts.forEach((fn) => fn()); mounts.forEach((fn) => fn());
return { return {
_isRuntime: true, _isRuntime: true,
@@ -469,7 +480,7 @@
} }
const content = show ? ifYes : ifNot; const content = show ? ifYes : ifNot;
if (content) { if (content) {
currentView = Render(() => isFunc(content) ? content() : content); currentView = createView(() => isFunc(content) ? content() : content);
root.insertBefore(currentView.container, anchor); root.insertBefore(currentView.container, anchor);
if (trans?.in) if (trans?.in)
trans.in(currentView.container); trans.in(currentView.container);
@@ -490,7 +501,7 @@
const key = keyFn ? keyFn(item, i) : item?.id ?? i; const key = keyFn ? keyFn(item, i) : item?.id ?? i;
let view = cache.get(key); let view = cache.get(key);
if (!view) if (!view)
view = Render(() => itemFn(item, i)); view = createView(() => itemFn(item, i));
else else
cache.delete(key); cache.delete(key);
nextCache.set(key, view); nextCache.set(key, view);
@@ -520,9 +531,9 @@
Watch2([path], () => { Watch2([path], () => {
const cur = path(); const cur = path();
const route = routes.find((r) => { const route = routes.find((r) => {
const p1 = r.path.split("/").filter(Boolean); const rParts = r.path.split("/").filter(Boolean);
const p2 = cur.split("/").filter(Boolean); const curParts = cur.split("/").filter(Boolean);
return p1.length === p2.length && p1.every((p, i) => p[0] === ":" || p === p2[i]); return rParts.length === curParts.length && rParts.every((p, i) => p[0] === ":" || p === curParts[i]);
}) || routes.find((r) => r.path === "*"); }) || routes.find((r) => r.path === "*");
if (route) { if (route) {
currentView?.destroy(); currentView?.destroy();
@@ -532,14 +543,14 @@
params[p.slice(1)] = cur.split("/").filter(Boolean)[i]; params[p.slice(1)] = cur.split("/").filter(Boolean)[i];
}); });
Router.params(params); Router.params(params);
currentView = Render(() => isFunc(route.component) ? route.component(params) : route.component); currentView = createView(() => isFunc(route.component) ? route.component(params) : route.component);
outlet.replaceChildren(currentView.container); outlet.replaceChildren(currentView.container);
} }
}); });
return outlet; return outlet;
}; };
Router.params = $2({}); Router.params = $2({});
Router.to = (p) => window.location.hash = p.replace(/^#?\/?/, "#/"); Router.to = (path) => window.location.hash = path.replace(/^#?\/?/, "#/");
Router.back = () => window.history.back(); Router.back = () => window.history.back();
Router.path = () => window.location.hash.replace(/^#/, "") || "/"; Router.path = () => window.location.hash.replace(/^#/, "") || "/";
var Mount2 = (comp, target) => { var Mount2 = (comp, target) => {
@@ -548,12 +559,24 @@
return; return;
if (MOUNTED_NODES.has(t)) if (MOUNTED_NODES.has(t))
MOUNTED_NODES.get(t).destroy(); MOUNTED_NODES.get(t).destroy();
const inst = Render(isFunc(comp) ? comp : () => comp); const inst = createView(() => isFunc(comp) ? comp() : comp);
t.replaceChildren(inst.container); t.replaceChildren(inst.container);
MOUNTED_NODES.set(t, inst); MOUNTED_NODES.set(t, inst);
return inst; return inst;
}; };
var SigPro = Object.freeze({ $: $2, Watch: Watch2, Tag: Tag2, Render, If: If2, For: For2, Router, Mount: Mount2, onMount, onUnmount }); var set = (signal, path, value) => {
if (value === undefined) {
signal(isFunc(path) ? path(signal()) : path);
} else {
const keys = path.split(".");
const last = keys.pop();
const current = signal();
const obj = keys.reduce((o, k) => ({ ...o, [k]: { ...o[k] } }), { ...current });
obj[last] = value;
signal(obj);
}
};
var SigPro = Object.freeze({ $: $2, Watch: Watch2, Tag: Tag2, If: If2, For: For2, Router, Mount: Mount2, onMount, onUnmount, set });
if (typeof window !== "undefined") { if (typeof window !== "undefined") {
Object.assign(window, SigPro); 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)); "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));

File diff suppressed because one or more lines are too long

259
docs/sigpro-ui.min.js vendored
View File

@@ -46,7 +46,6 @@
Stack: () => Stack, Stack: () => Stack,
Select: () => Select, Select: () => Select,
Router: () => Router, Router: () => Router,
Render: () => Render,
Rating: () => Rating, Rating: () => Rating,
Range: () => Range, Range: () => Range,
Radio: () => Radio, Radio: () => Radio,
@@ -77,34 +76,33 @@
}); });
// src/sigpro.js // src/sigpro.js
var isFunc = (f) => typeof f === "function"; var isFunc = (fn) => typeof fn === "function";
var isObj = (o) => o && typeof o === "object";
var isArr = Array.isArray; var isArr = Array.isArray;
var doc = typeof document !== "undefined" ? document : null; var doc = typeof document !== "undefined" ? document : null;
var ensureNode = (n) => n?._isRuntime ? n.container : n instanceof Node ? n : doc.createTextNode(n == null ? "" : String(n)); var ensureNode = (node) => node?._isRuntime ? node.container : node instanceof Node ? node : doc.createTextNode(node == null ? "" : String(node));
var activeEffect = null; var activeEffect = null;
var activeOwner = null; var activeOwner = null;
var isFlushing = false; var isFlushing = false;
var effectQueue = new Set; var effectQueue = new Set;
var MOUNTED_NODES = new WeakMap; var MOUNTED_NODES = new WeakMap;
var dispose = (eff) => { var dispose = (effect) => {
if (!eff || eff._disposed) if (!effect || effect._disposed)
return; return;
eff._disposed = true; effect._disposed = true;
const stack = [eff]; const stack = [effect];
while (stack.length) { while (stack.length) {
const e = stack.pop(); const eff = stack.pop();
if (e._cleanups) { if (eff._cleanups) {
e._cleanups.forEach((fn) => fn()); eff._cleanups.forEach((fn) => fn());
e._cleanups.clear(); eff._cleanups.clear();
} }
if (e._children) { if (eff._children) {
e._children.forEach((child) => stack.push(child)); eff._children.forEach((child) => stack.push(child));
e._children.clear(); eff._children.clear();
} }
if (e._deps) { if (eff._deps) {
e._deps.forEach((depSet) => depSet.delete(e)); eff._deps.forEach((depSet) => depSet.delete(eff));
e._deps.clear(); eff._deps.clear();
} }
} }
}; };
@@ -119,7 +117,7 @@
if (effect._deps) if (effect._deps)
effect._deps.forEach((depSet) => depSet.delete(effect)); effect._deps.forEach((depSet) => depSet.delete(effect));
if (effect._cleanups) { if (effect._cleanups) {
effect._cleanups.forEach((cl) => cl()); effect._cleanups.forEach((cleanup) => cleanup());
effect._cleanups.clear(); effect._cleanups.clear();
} }
const prevEffect = activeEffect; const prevEffect = activeEffect;
@@ -151,9 +149,9 @@
isFlushing = true; isFlushing = true;
const sorted = Array.from(effectQueue).sort((a, b) => a._depth - b._depth); const sorted = Array.from(effectQueue).sort((a, b) => a._depth - b._depth);
effectQueue.clear(); effectQueue.clear();
for (const e of sorted) for (const eff of sorted)
if (!e._disposed) if (!eff._disposed)
e(); eff();
isFlushing = false; isFlushing = false;
}; };
var trackUpdate = (subs, trigger = false) => { var trackUpdate = (subs, trigger = false) => {
@@ -162,15 +160,15 @@
(activeEffect._deps ||= new Set).add(subs); (activeEffect._deps ||= new Set).add(subs);
} else if (trigger) { } else if (trigger) {
let hasQueue = false; let hasQueue = false;
subs.forEach((e) => { subs.forEach((eff) => {
if (e === activeEffect || e._disposed) if (eff === activeEffect || eff._disposed)
return; return;
if (e._isComputed) { if (eff._isComputed) {
e._dirty = true; eff._dirty = true;
if (e._subs) if (eff._subs)
trackUpdate(e._subs, true); trackUpdate(eff._subs, true);
} else { } else {
effectQueue.add(e); effectQueue.add(eff);
hasQueue = true; hasQueue = true;
} }
}); });
@@ -179,28 +177,28 @@
} }
}; };
var untrack = (fn) => { var untrack = (fn) => {
const p = activeEffect; const prev = activeEffect;
activeEffect = null; activeEffect = null;
try { try {
return fn(); return fn();
} finally { } finally {
activeEffect = p; activeEffect = prev;
} }
}; };
var onMount = (fn) => { var onMount = (fn) => {
if (activeOwner) if (activeOwner)
(activeOwner._mounts ||= []).push(fn); (activeOwner._mounts ||= []).push(fn);
}; };
var $2 = (val, key = null) => { var $2 = (value, storageKey = null) => {
const subs = new Set; const subs = new Set;
if (isFunc(val)) { if (isFunc(value)) {
let cache, dirty = true; let cache, dirty = true;
const computed = () => { const computed = () => {
if (dirty) { if (dirty) {
const prev = activeEffect; const prev = activeEffect;
activeEffect = computed; activeEffect = computed;
try { try {
const next = val(); const next = value();
if (!Object.is(cache, next)) { if (!Object.is(cache, next)) {
cache = next; cache = next;
dirty = false; dirty = false;
@@ -233,33 +231,33 @@
onUnmount(computed.stop); onUnmount(computed.stop);
return computed; return computed;
} }
if (key) if (storageKey)
try { try {
val = JSON.parse(localStorage.getItem(key)) ?? val; value = JSON.parse(localStorage.getItem(storageKey)) ?? value;
} catch (e) {} } catch (e) {}
return (...args) => { return (...args) => {
if (args.length) { if (args.length) {
const next = isFunc(args[0]) ? args[0](val) : args[0]; const next = isFunc(args[0]) ? args[0](value) : args[0];
if (!Object.is(val, next)) { if (!Object.is(value, next)) {
val = next; value = next;
if (key) if (storageKey)
localStorage.setItem(key, JSON.stringify(val)); localStorage.setItem(storageKey, JSON.stringify(value));
trackUpdate(subs, true); trackUpdate(subs, true);
} }
} }
trackUpdate(subs); trackUpdate(subs);
return val; return value;
}; };
}; };
var Watch2 = (sources, cb) => { var Watch2 = (sources, callback) => {
if (cb === undefined) { if (callback === undefined) {
const effect2 = createEffect(sources); const effect2 = createEffect(sources);
effect2(); effect2();
return () => dispose(effect2); return () => dispose(effect2);
} }
const effect = createEffect(() => { const effect = createEffect(() => {
const vals = Array.isArray(sources) ? sources.map((s) => s()) : sources(); const vals = isArr(sources) ? sources.map((src) => src()) : sources();
untrack(() => cb(vals)); untrack(() => callback(vals));
}); });
effect(); effect();
return () => dispose(effect); return () => dispose(effect);
@@ -279,17 +277,12 @@
var validateAttr = (key, val) => { var validateAttr = (key, val) => {
if (val == null || val === false) if (val == null || val === false)
return null; return null;
if (isDangerousAttr(key)) { if (isDangerousAttr(key) && DANGEROUS_PROTOCOL.test(String(val)))
const sVal = String(val); return "#";
if (DANGEROUS_PROTOCOL.test(sVal)) {
console.warn(`[SigPro] Bloqueado protocolo peligroso en ${key}`);
return "#";
}
}
return val; return val;
}; };
var Tag2 = (tag, props = {}, children = []) => { var Tag2 = (tag, props = {}, children = []) => {
if (props instanceof Node || isArr(props) || !isObj(props)) { if (props instanceof Node || isArr(props) || props && typeof props !== "object") {
children = props; children = props;
props = {}; props = {};
} }
@@ -307,7 +300,13 @@
ctx._mounts = effect._mounts || []; ctx._mounts = effect._mounts || [];
ctx._cleanups = effect._cleanups || new Set; ctx._cleanups = effect._cleanups || new Set;
const result = effect._result; const result = effect._result;
const attachLifecycle = (node) => node && typeof node === "object" && !node._isRuntime && (node._mounts = ctx._mounts, node._cleanups = ctx._cleanups, node._ownerEffect = effect); const attachLifecycle = (node) => {
if (node && typeof node === "object" && !node._isRuntime) {
node._mounts = ctx._mounts;
node._cleanups = ctx._cleanups;
node._ownerEffect = effect;
}
};
isArr(result) ? result.forEach(attachLifecycle) : attachLifecycle(result); isArr(result) ? result.forEach(attachLifecycle) : attachLifecycle(result);
if (result == null) if (result == null)
return null; return null;
@@ -315,61 +314,61 @@
return result; return result;
return doc.createTextNode(String(result)); return doc.createTextNode(String(result));
} }
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|image|ellipse|foreignObject|linearGradient|radialGradient|stop|pattern|mask|clipPath|filter|feColorMatrix|feBlend|feGaussianBlur|animate|animateTransform|set|metadata|desc|title|symbol|marker|view)$/i.test(tag);
const el = isSVG ? doc.createElementNS("http://www.w3.org/2000/svg", tag) : doc.createElement(tag); const elem = isSVG ? doc.createElementNS("http://www.w3.org/2000/svg", tag) : doc.createElement(tag);
el._cleanups = new Set; elem._cleanups = new Set;
for (let k in props) { for (let key in props) {
if (!props.hasOwnProperty(k)) if (!props.hasOwnProperty(key))
continue; continue;
let v = props[k]; let value = props[key];
if (k === "ref") { if (key === "ref") {
isFunc(v) ? v(el) : v.current = el; isFunc(value) ? value(elem) : value.current = elem;
continue; continue;
} }
if (k.startsWith("on")) { if (key.startsWith("on")) {
const ev = k.slice(2).toLowerCase(); const event = key.slice(2).toLowerCase();
el.addEventListener(ev, v); elem.addEventListener(event, value);
const off = () => el.removeEventListener(ev, v); const off = () => elem.removeEventListener(event, value);
el._cleanups.add(off); elem._cleanups.add(off);
onUnmount(off); onUnmount(off);
} else if (isFunc(v)) { } else if (isFunc(value)) {
const effect = createEffect(() => { const effect = createEffect(() => {
const val = validateAttr(k, v()); const val = validateAttr(key, value());
if (k === "class") if (key === "class")
el.className = val || ""; elem.className = val || "";
else if (val == null) else if (val == null)
el.removeAttribute(k); elem.removeAttribute(key);
else if (k in el && !isSVG) else if (key in elem && !isSVG)
el[k] = val; elem[key] = val;
else else
el.setAttribute(k, val === true ? "" : val); elem.setAttribute(key, val === true ? "" : val);
}); });
effect(); effect();
el._cleanups.add(() => dispose(effect)); elem._cleanups.add(() => dispose(effect));
onUnmount(() => dispose(effect)); onUnmount(() => dispose(effect));
if (/^(INPUT|TEXTAREA|SELECT)$/.test(el.tagName) && (k === "value" || k === "checked")) { if (/^(INPUT|TEXTAREA|SELECT)$/.test(elem.tagName) && (key === "value" || key === "checked")) {
const evType = k === "checked" ? "change" : "input"; const eventType = key === "checked" ? "change" : "input";
el.addEventListener(evType, (ev) => v(ev.target[k])); elem.addEventListener(eventType, (ev) => value(ev.target[key]));
} }
} else { } else {
const val = validateAttr(k, v); const val = validateAttr(key, value);
if (val != null) { if (val != null) {
if (k in el && !isSVG) if (key in elem && !isSVG)
el[k] = val; elem[key] = val;
else else
el.setAttribute(k, val === true ? "" : val); elem.setAttribute(key, val === true ? "" : val);
} }
} }
} }
const append = (c) => { const append = (child) => {
if (isArr(c)) if (isArr(child))
return c.forEach(append); return child.forEach(append);
if (isFunc(c)) { if (isFunc(child)) {
const anchor = doc.createTextNode(""); const anchor = doc.createTextNode("");
el.appendChild(anchor); elem.appendChild(anchor);
let currentNodes = []; let currentNodes = [];
const effect = createEffect(() => { const effect = createEffect(() => {
const res = c(); const res = child();
const next = (isArr(res) ? res : [res]).map(ensureNode); const next = (isArr(res) ? res : [res]).map(ensureNode);
currentNodes.forEach((n) => { currentNodes.forEach((n) => {
if (n._isRuntime) if (n._isRuntime)
@@ -391,43 +390,55 @@
currentNodes = next; currentNodes = next;
}); });
effect(); effect();
el._cleanups.add(() => dispose(effect)); elem._cleanups.add(() => dispose(effect));
onUnmount(() => dispose(effect)); onUnmount(() => dispose(effect));
} else { } else {
const node = ensureNode(c); const node = ensureNode(child);
el.appendChild(node); elem.appendChild(node);
if (node._mounts) if (node._mounts)
node._mounts.forEach((fn) => fn()); node._mounts.forEach((fn) => fn());
} }
}; };
append(children); append(children);
return el; return elem;
}; };
var Render = (renderFn) => { var createView = (renderFn) => {
const cleanups = new Set; const cleanups = new Set;
const mounts = []; const mounts = [];
const previousOwner = activeOwner; const previousOwner = activeOwner;
activeOwner = { _cleanups: cleanups, _mounts: mounts };
const result = renderFn({ onCleanup: (fn) => cleanups.add(fn) });
activeOwner = previousOwner;
if (result == null)
return null;
if (result instanceof Node) {
mounts.forEach((fn) => fn());
return {
_isRuntime: true,
container: result,
destroy: () => {
cleanups.forEach((fn) => fn());
cleanupNode(result);
result.remove();
}
};
}
const container = doc.createElement("div"); const container = doc.createElement("div");
container.style.display = "contents"; container.style.display = "contents";
container.setAttribute("role", "presentation"); container.setAttribute("role", "presentation");
activeOwner = { _cleanups: cleanups, _mounts: mounts }; const process = (node) => {
const processResult = (result) => { if (!node)
if (!result)
return; return;
if (result._isRuntime) { if (node._isRuntime) {
cleanups.add(result.destroy); cleanups.add(node.destroy);
container.appendChild(result.container); container.appendChild(node.container);
} else if (isArr(result)) { } else if (isArr(node)) {
result.forEach(processResult); node.forEach(process);
} else { } else {
container.appendChild(result instanceof Node ? result : doc.createTextNode(String(result == null ? "" : result))); container.appendChild(node instanceof Node ? node : doc.createTextNode(String(node)));
} }
}; };
try { process(result);
processResult(renderFn({ onCleanup: (fn) => cleanups.add(fn) }));
} finally {
activeOwner = previousOwner;
}
mounts.forEach((fn) => fn()); mounts.forEach((fn) => fn());
return { return {
_isRuntime: true, _isRuntime: true,
@@ -469,7 +480,7 @@
} }
const content = show ? ifYes : ifNot; const content = show ? ifYes : ifNot;
if (content) { if (content) {
currentView = Render(() => isFunc(content) ? content() : content); currentView = createView(() => isFunc(content) ? content() : content);
root.insertBefore(currentView.container, anchor); root.insertBefore(currentView.container, anchor);
if (trans?.in) if (trans?.in)
trans.in(currentView.container); trans.in(currentView.container);
@@ -490,7 +501,7 @@
const key = keyFn ? keyFn(item, i) : item?.id ?? i; const key = keyFn ? keyFn(item, i) : item?.id ?? i;
let view = cache.get(key); let view = cache.get(key);
if (!view) if (!view)
view = Render(() => itemFn(item, i)); view = createView(() => itemFn(item, i));
else else
cache.delete(key); cache.delete(key);
nextCache.set(key, view); nextCache.set(key, view);
@@ -520,9 +531,9 @@
Watch2([path], () => { Watch2([path], () => {
const cur = path(); const cur = path();
const route = routes.find((r) => { const route = routes.find((r) => {
const p1 = r.path.split("/").filter(Boolean); const rParts = r.path.split("/").filter(Boolean);
const p2 = cur.split("/").filter(Boolean); const curParts = cur.split("/").filter(Boolean);
return p1.length === p2.length && p1.every((p, i) => p[0] === ":" || p === p2[i]); return rParts.length === curParts.length && rParts.every((p, i) => p[0] === ":" || p === curParts[i]);
}) || routes.find((r) => r.path === "*"); }) || routes.find((r) => r.path === "*");
if (route) { if (route) {
currentView?.destroy(); currentView?.destroy();
@@ -532,14 +543,14 @@
params[p.slice(1)] = cur.split("/").filter(Boolean)[i]; params[p.slice(1)] = cur.split("/").filter(Boolean)[i];
}); });
Router.params(params); Router.params(params);
currentView = Render(() => isFunc(route.component) ? route.component(params) : route.component); currentView = createView(() => isFunc(route.component) ? route.component(params) : route.component);
outlet.replaceChildren(currentView.container); outlet.replaceChildren(currentView.container);
} }
}); });
return outlet; return outlet;
}; };
Router.params = $2({}); Router.params = $2({});
Router.to = (p) => window.location.hash = p.replace(/^#?\/?/, "#/"); Router.to = (path) => window.location.hash = path.replace(/^#?\/?/, "#/");
Router.back = () => window.history.back(); Router.back = () => window.history.back();
Router.path = () => window.location.hash.replace(/^#/, "") || "/"; Router.path = () => window.location.hash.replace(/^#/, "") || "/";
var Mount2 = (comp, target) => { var Mount2 = (comp, target) => {
@@ -548,12 +559,24 @@
return; return;
if (MOUNTED_NODES.has(t)) if (MOUNTED_NODES.has(t))
MOUNTED_NODES.get(t).destroy(); MOUNTED_NODES.get(t).destroy();
const inst = Render(isFunc(comp) ? comp : () => comp); const inst = createView(() => isFunc(comp) ? comp() : comp);
t.replaceChildren(inst.container); t.replaceChildren(inst.container);
MOUNTED_NODES.set(t, inst); MOUNTED_NODES.set(t, inst);
return inst; return inst;
}; };
var SigPro = Object.freeze({ $: $2, Watch: Watch2, Tag: Tag2, Render, If: If2, For: For2, Router, Mount: Mount2, onMount, onUnmount }); var set = (signal, path, value) => {
if (value === undefined) {
signal(isFunc(path) ? path(signal()) : path);
} else {
const keys = path.split(".");
const last = keys.pop();
const current = signal();
const obj = keys.reduce((o, k) => ({ ...o, [k]: { ...o[k] } }), { ...current });
obj[last] = value;
signal(obj);
}
};
var SigPro = Object.freeze({ $: $2, Watch: Watch2, Tag: Tag2, If: If2, For: For2, Router, Mount: Mount2, onMount, onUnmount, set });
if (typeof window !== "undefined") { if (typeof window !== "undefined") {
Object.assign(window, SigPro); 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)); "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));

File diff suppressed because one or more lines are too long

View File

@@ -1,15 +1,15 @@
// import './src/sigpro.js'; // import './src/sigpro.js';
import { $, Render, Watch, Tag, If, For, Router, Mount } from './src/sigpro.js'; import { $, Watch, Tag, If, For, Router, Mount } from './src/sigpro.js';
import * as Components from './src/components/index.js'; import * as Components from './src/components/index.js';
import * as Utils from './src/core/utils.js'; import * as Utils from './src/core/utils.js';
import { tt } from './src/core/i18n.js'; import { tt } from './src/core/i18n.js';
export * from './src/components/index.js'; export * from './src/components/index.js';
export * from './src/core/utils.js'; export * from './src/core/utils.js';
export { $, Render, Watch, Tag, If, For, Router, Mount, tt }; export { $, Watch, Tag, If, For, Router, Mount, tt };
if (typeof window !== 'undefined') { if (typeof window !== 'undefined') {
// const CoreAPI = { $, $$, Render, Watch, Tag, If, For, Router, Mount } = SigPro; // const CoreAPI = { $, $$, ender, Watch, Tag, If, For, Router, Mount } = SigPro;
// Object.entries(CoreAPI).forEach(([name, fn]) => { // Object.entries(CoreAPI).forEach(([name, fn]) => {
// Object.defineProperty(window, name, { // Object.defineProperty(window, name, {

View File

@@ -1,8 +1,7 @@
const isFunc = f => typeof f === "function" const isFunc = fn => typeof fn === "function"
const isObj = o => o && typeof o === "object"
const isArr = Array.isArray const isArr = Array.isArray
const doc = typeof document !== "undefined" ? document : null const doc = typeof document !== "undefined" ? document : null
const ensureNode = n => n?._isRuntime ? n.container : (n instanceof Node ? n : doc.createTextNode(n == null ? "" : String(n))) const ensureNode = node => node?._isRuntime ? node.container : (node instanceof Node ? node : doc.createTextNode(node == null ? "" : String(node)))
let activeEffect = null let activeEffect = null
let activeOwner = null let activeOwner = null
@@ -10,23 +9,23 @@ let isFlushing = false
const effectQueue = new Set() const effectQueue = new Set()
const MOUNTED_NODES = new WeakMap() const MOUNTED_NODES = new WeakMap()
const dispose = eff => { const dispose = effect => {
if (!eff || eff._disposed) return if (!effect || effect._disposed) return
eff._disposed = true effect._disposed = true
const stack = [eff] const stack = [effect]
while (stack.length) { while (stack.length) {
const e = stack.pop() const eff = stack.pop()
if (e._cleanups) { if (eff._cleanups) {
e._cleanups.forEach(fn => fn()) eff._cleanups.forEach(fn => fn())
e._cleanups.clear() eff._cleanups.clear()
} }
if (e._children) { if (eff._children) {
e._children.forEach(child => stack.push(child)) eff._children.forEach(child => stack.push(child))
e._children.clear() eff._children.clear()
} }
if (e._deps) { if (eff._deps) {
e._deps.forEach(depSet => depSet.delete(e)) eff._deps.forEach(depSet => depSet.delete(eff))
e._deps.clear() eff._deps.clear()
} }
} }
} }
@@ -40,7 +39,7 @@ const createEffect = (fn, isComputed = false) => {
if (effect._disposed) return if (effect._disposed) return
if (effect._deps) effect._deps.forEach(depSet => depSet.delete(effect)) if (effect._deps) effect._deps.forEach(depSet => depSet.delete(effect))
if (effect._cleanups) { if (effect._cleanups) {
effect._cleanups.forEach(cl => cl()) effect._cleanups.forEach(cleanup => cleanup())
effect._cleanups.clear() effect._cleanups.clear()
} }
const prevEffect = activeEffect const prevEffect = activeEffect
@@ -70,7 +69,7 @@ const flush = () => {
isFlushing = true isFlushing = true
const sorted = Array.from(effectQueue).sort((a, b) => a._depth - b._depth) const sorted = Array.from(effectQueue).sort((a, b) => a._depth - b._depth)
effectQueue.clear() effectQueue.clear()
for (const e of sorted) if (!e._disposed) e() for (const eff of sorted) if (!eff._disposed) eff()
isFlushing = false isFlushing = false
} }
@@ -80,13 +79,13 @@ const trackUpdate = (subs, trigger = false) => {
;(activeEffect._deps ||= new Set()).add(subs) ;(activeEffect._deps ||= new Set()).add(subs)
} else if (trigger) { } else if (trigger) {
let hasQueue = false let hasQueue = false
subs.forEach(e => { subs.forEach(eff => {
if (e === activeEffect || e._disposed) return if (eff === activeEffect || eff._disposed) return
if (e._isComputed) { if (eff._isComputed) {
e._dirty = true eff._dirty = true
if (e._subs) trackUpdate(e._subs, true) if (eff._subs) trackUpdate(eff._subs, true)
} else { } else {
effectQueue.add(e) effectQueue.add(eff)
hasQueue = true hasQueue = true
} }
}) })
@@ -95,25 +94,25 @@ const trackUpdate = (subs, trigger = false) => {
} }
const untrack = fn => { const untrack = fn => {
const p = activeEffect const prev = activeEffect
activeEffect = null activeEffect = null
try { return fn() } finally { activeEffect = p } try { return fn() } finally { activeEffect = prev }
} }
const onMount = fn => { const onMount = fn => {
if (activeOwner) (activeOwner._mounts ||= []).push(fn) if (activeOwner) (activeOwner._mounts ||= []).push(fn)
} }
const $ = (val, key = null) => { const $ = (value, storageKey = null) => {
const subs = new Set() const subs = new Set()
if (isFunc(val)) { if (isFunc(value)) {
let cache, dirty = true let cache, dirty = true
const computed = () => { const computed = () => {
if (dirty) { if (dirty) {
const prev = activeEffect const prev = activeEffect
activeEffect = computed activeEffect = computed
try { try {
const next = val() const next = value()
if (!Object.is(cache, next)) { if (!Object.is(cache, next)) {
cache = next cache = next
dirty = false dirty = false
@@ -141,30 +140,30 @@ const $ = (val, key = null) => {
if (activeOwner) onUnmount(computed.stop) if (activeOwner) onUnmount(computed.stop)
return computed return computed
} }
if (key) try { val = JSON.parse(localStorage.getItem(key)) ?? val } catch (e) {} if (storageKey) try { value = JSON.parse(localStorage.getItem(storageKey)) ?? value } catch (e) {}
return (...args) => { return (...args) => {
if (args.length) { if (args.length) {
const next = isFunc(args[0]) ? args[0](val) : args[0] const next = isFunc(args[0]) ? args[0](value) : args[0]
if (!Object.is(val, next)) { if (!Object.is(value, next)) {
val = next value = next
if (key) localStorage.setItem(key, JSON.stringify(val)) if (storageKey) localStorage.setItem(storageKey, JSON.stringify(value))
trackUpdate(subs, true) trackUpdate(subs, true)
} }
} }
trackUpdate(subs) trackUpdate(subs)
return val return value
} }
} }
const Watch = (sources, cb) => { const Watch = (sources, callback) => {
if (cb === undefined) { if (callback === undefined) {
const effect = createEffect(sources) const effect = createEffect(sources)
effect() effect()
return () => dispose(effect) return () => dispose(effect)
} }
const effect = createEffect(() => { const effect = createEffect(() => {
const vals = Array.isArray(sources) ? sources.map(s => s()) : sources() const vals = isArr(sources) ? sources.map(src => src()) : sources()
untrack(() => cb(vals)) untrack(() => callback(vals))
}) })
effect() effect()
return () => dispose(effect) return () => dispose(effect)
@@ -184,18 +183,36 @@ const isDangerousAttr = key => key === 'src' || key === 'href' || key.startsWith
const validateAttr = (key, val) => { const validateAttr = (key, val) => {
if (val == null || val === false) return null if (val == null || val === false) return null
if (isDangerousAttr(key)) { if (isDangerousAttr(key) && DANGEROUS_PROTOCOL.test(String(val))) return '#'
const sVal = String(val)
if (DANGEROUS_PROTOCOL.test(sVal)) {
console.warn(`[SigPro] Bloqueado protocolo peligroso en ${key}`)
return '#'
}
}
return val return val
} }
const setProperty = (elem, key, val, isSVG) => {
val = validateAttr(key, val)
if (key === 'class' || key === 'className') elem.className = val || ''
else if (key === 'style' && typeof val === 'object') Object.assign(elem.style, val)
else if (key in elem && !isSVG) elem[key] = val
else if (isSVG) {
if (key.startsWith('xlink:')) {
if (val == null || val === false) elem.removeAttributeNS('http://www.w3.org/1999/xlink', key.slice(6))
else elem.setAttributeNS('http://www.w3.org/1999/xlink', key, val)
} else if (key === 'xmlns' || key.startsWith('xmlns:')) {
if (val == null || val === false) elem.removeAttributeNS('http://www.w3.org/2000/xmlns/', key)
else elem.setAttributeNS('http://www.w3.org/2000/xmlns/', key, val)
} else {
if (val == null || val === false) elem.removeAttribute(key)
else if (val === true) elem.setAttribute(key, '')
else elem.setAttribute(key, val)
}
} else {
if (val == null || val === false) elem.removeAttribute(key)
else if (val === true) elem.setAttribute(key, '')
else elem.setAttribute(key, val)
}
}
const Tag = (tag, props = {}, children = []) => { const Tag = (tag, props = {}, children = []) => {
if (props instanceof Node || isArr(props) || !isObj(props)) { if (props instanceof Node || isArr(props) || (props && typeof props !== 'object')) {
children = props children = props
props = {} props = {}
} }
@@ -213,65 +230,68 @@ const Tag = (tag, props = {}, children = []) => {
ctx._mounts = effect._mounts || [] ctx._mounts = effect._mounts || []
ctx._cleanups = effect._cleanups || new Set() ctx._cleanups = effect._cleanups || new Set()
const result = effect._result const result = effect._result
const attachLifecycle = node => node && typeof node === 'object' && !node._isRuntime && ( const attachLifecycle = node => {
node._mounts = ctx._mounts, if (node && typeof node === 'object' && !node._isRuntime) {
node._cleanups = ctx._cleanups, node._mounts = ctx._mounts
node._ownerEffect = effect node._cleanups = ctx._cleanups
) node._ownerEffect = effect
}
}
isArr(result) ? result.forEach(attachLifecycle) : attachLifecycle(result) isArr(result) ? result.forEach(attachLifecycle) : attachLifecycle(result)
if (result == null) return null if (result == null) return null
if (result instanceof Node || (isArr(result) && result.every(n => n instanceof Node))) return result if (result instanceof Node || (isArr(result) && result.every(n => n instanceof Node))) return result
return doc.createTextNode(String(result)) return doc.createTextNode(String(result))
} }
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 isSVG = /^(svg|path|circle|rect|line|polyline|polygon|g|defs|text|tspan|use|image|ellipse|foreignObject|linearGradient|radialGradient|stop|pattern|mask|clipPath|filter|feColorMatrix|feBlend|feGaussianBlur|animate|animateTransform|set|metadata|desc|title|symbol|marker|view)$/i.test(tag)
el._cleanups = new Set() const elem = isSVG ? doc.createElementNS("http://www.w3.org/2000/svg", tag) : doc.createElement(tag)
elem._cleanups = new Set()
for (let k in props) { for (let key in props) {
if (!props.hasOwnProperty(k)) continue if (!props.hasOwnProperty(key)) continue
let v = props[k] let value = props[key]
if (k === "ref") { if (key === "ref") {
isFunc(v) ? v(el) : (v.current = el) isFunc(value) ? value(elem) : (value.current = elem)
continue continue
} }
if (k.startsWith("on")) { if (key.startsWith("on")) {
const ev = k.slice(2).toLowerCase() const event = key.slice(2).toLowerCase()
el.addEventListener(ev, v) elem.addEventListener(event, value)
const off = () => el.removeEventListener(ev, v) const off = () => elem.removeEventListener(event, value)
el._cleanups.add(off) elem._cleanups.add(off)
onUnmount(off) onUnmount(off)
} else if (isFunc(v)) { } else if (isFunc(value)) {
const effect = createEffect(() => { const effect = createEffect(() => {
const val = validateAttr(k, v()) const val = validateAttr(key, value())
if (k === "class") el.className = val || "" if (key === "class") elem.className = val || ""
else if (val == null) el.removeAttribute(k) else if (val == null) elem.removeAttribute(key)
else if (k in el && !isSVG) el[k] = val else if (key in elem && !isSVG) elem[key] = val
else el.setAttribute(k, val === true ? "" : val) else elem.setAttribute(key, val === true ? "" : val)
}) })
effect() effect()
el._cleanups.add(() => dispose(effect)) elem._cleanups.add(() => dispose(effect))
onUnmount(() => dispose(effect)) onUnmount(() => dispose(effect))
if (/^(INPUT|TEXTAREA|SELECT)$/.test(el.tagName) && (k === "value" || k === "checked")) { if (/^(INPUT|TEXTAREA|SELECT)$/.test(elem.tagName) && (key === "value" || key === "checked")) {
const evType = k === "checked" ? "change" : "input" const eventType = key === "checked" ? "change" : "input"
el.addEventListener(evType, ev => v(ev.target[k])) elem.addEventListener(eventType, ev => value(ev.target[key]))
} }
} else { } else {
const val = validateAttr(k, v) const val = validateAttr(key, value)
if (val != null) { if (val != null) {
if (k in el && !isSVG) el[k] = val if (key in elem && !isSVG) elem[key] = val
else el.setAttribute(k, val === true ? "" : val) else elem.setAttribute(key, val === true ? "" : val)
} }
} }
} }
const append = c => { const append = child => {
if (isArr(c)) return c.forEach(append) if (isArr(child)) return child.forEach(append)
if (isFunc(c)) { if (isFunc(child)) {
const anchor = doc.createTextNode("") const anchor = doc.createTextNode("")
el.appendChild(anchor) elem.appendChild(anchor)
let currentNodes = [] let currentNodes = []
const effect = createEffect(() => { const effect = createEffect(() => {
const res = c() const res = child()
const next = (isArr(res) ? res : [res]).map(ensureNode) const next = (isArr(res) ? res : [res]).map(ensureNode)
currentNodes.forEach(n => { currentNodes.forEach(n => {
if (n._isRuntime) n.destroy() if (n._isRuntime) n.destroy()
@@ -288,43 +308,59 @@ const Tag = (tag, props = {}, children = []) => {
currentNodes = next currentNodes = next
}) })
effect() effect()
el._cleanups.add(() => dispose(effect)) elem._cleanups.add(() => dispose(effect))
onUnmount(() => dispose(effect)) onUnmount(() => dispose(effect))
} else { } else {
const node = ensureNode(c) const node = ensureNode(child)
el.appendChild(node) elem.appendChild(node)
if (node._mounts) node._mounts.forEach(fn => fn()) if (node._mounts) node._mounts.forEach(fn => fn())
} }
} }
append(children) append(children)
return el return elem
} }
const Render = renderFn => { const createView = (renderFn) => {
const cleanups = new Set() const cleanups = new Set()
const mounts = [] const mounts = []
const previousOwner = activeOwner const previousOwner = activeOwner
const container = doc.createElement("div")
container.style.display = "contents"
container.setAttribute("role", "presentation") // ← único cambio real
activeOwner = { _cleanups: cleanups, _mounts: mounts } activeOwner = { _cleanups: cleanups, _mounts: mounts }
const processResult = result => { const result = renderFn({ onCleanup: fn => cleanups.add(fn) })
if (!result) return
if (result._isRuntime) { activeOwner = previousOwner
cleanups.add(result.destroy)
container.appendChild(result.container) if (result == null) return null
} else if (isArr(result)) { if (result instanceof Node) {
result.forEach(processResult) mounts.forEach(fn => fn())
} else { return {
container.appendChild(result instanceof Node ? result : doc.createTextNode(String(result == null ? "" : result))) _isRuntime: true,
container: result,
destroy: () => {
cleanups.forEach(fn => fn())
cleanupNode(result)
result.remove()
}
} }
} }
try { const container = doc.createElement("div")
processResult(renderFn({ onCleanup: fn => cleanups.add(fn) })) container.style.display = "contents"
} finally { activeOwner = previousOwner } container.setAttribute("role", "presentation")
const process = node => {
if (!node) return
if (node._isRuntime) {
cleanups.add(node.destroy)
container.appendChild(node.container)
} else if (isArr(node)) {
node.forEach(process)
} else {
container.appendChild(node instanceof Node ? node : doc.createTextNode(String(node)))
}
}
process(result)
mounts.forEach(fn => fn()) mounts.forEach(fn => fn())
return { return {
_isRuntime: true, _isRuntime: true,
@@ -369,7 +405,7 @@ const If = (cond, ifYes, ifNot = null, trans = null) => {
const content = show ? ifYes : ifNot const content = show ? ifYes : ifNot
if (content) { if (content) {
currentView = Render(() => isFunc(content) ? content() : content) currentView = createView(() => isFunc(content) ? content() : content)
root.insertBefore(currentView.container, anchor) root.insertBefore(currentView.container, anchor)
if (trans?.in) trans.in(currentView.container) if (trans?.in) trans.in(currentView.container)
} }
@@ -390,7 +426,7 @@ const For = (src, itemFn, keyFn) => {
const item = newItems[i] const item = newItems[i]
const key = keyFn ? keyFn(item, i) : (item?.id ?? i) const key = keyFn ? keyFn(item, i) : (item?.id ?? i)
let view = cache.get(key) let view = cache.get(key)
if (!view) view = Render(() => itemFn(item, i)) if (!view) view = createView(() => itemFn(item, i))
else cache.delete(key) else cache.delete(key)
nextCache.set(key, view) nextCache.set(key, view)
nextOrder.push(view) nextOrder.push(view)
@@ -419,9 +455,9 @@ const Router = routes => {
Watch([path], () => { Watch([path], () => {
const cur = path() const cur = path()
const route = routes.find(r => { const route = routes.find(r => {
const p1 = r.path.split("/").filter(Boolean) const rParts = r.path.split("/").filter(Boolean)
const p2 = cur.split("/").filter(Boolean) const curParts = cur.split("/").filter(Boolean)
return p1.length === p2.length && p1.every((p, i) => p[0] === ":" || p === p2[i]) return rParts.length === curParts.length && rParts.every((p, i) => p[0] === ":" || p === curParts[i])
}) || routes.find(r => r.path === "*") }) || routes.find(r => r.path === "*")
if (route) { if (route) {
currentView?.destroy() currentView?.destroy()
@@ -430,14 +466,14 @@ const Router = routes => {
if (p[0] === ":") params[p.slice(1)] = cur.split("/").filter(Boolean)[i] if (p[0] === ":") params[p.slice(1)] = cur.split("/").filter(Boolean)[i]
}) })
Router.params(params) Router.params(params)
currentView = Render(() => isFunc(route.component) ? route.component(params) : route.component) currentView = createView(() => isFunc(route.component) ? route.component(params) : route.component)
outlet.replaceChildren(currentView.container) outlet.replaceChildren(currentView.container)
} }
}) })
return outlet return outlet
} }
Router.params = $({}) Router.params = $({})
Router.to = p => window.location.hash = p.replace(/^#?\/?/, "#/") Router.to = path => window.location.hash = path.replace(/^#?\/?/, "#/")
Router.back = () => window.history.back() Router.back = () => window.history.back()
Router.path = () => window.location.hash.replace(/^#/, "") || "/" Router.path = () => window.location.hash.replace(/^#/, "") || "/"
@@ -445,26 +481,26 @@ 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 (!t) return
if (MOUNTED_NODES.has(t)) MOUNTED_NODES.get(t).destroy() if (MOUNTED_NODES.has(t)) MOUNTED_NODES.get(t).destroy()
const inst = Render(isFunc(comp) ? comp : () => comp) const inst = createView(() => isFunc(comp) ? comp() : comp)
t.replaceChildren(inst.container) t.replaceChildren(inst.container)
MOUNTED_NODES.set(t, inst) MOUNTED_NODES.set(t, inst)
return inst return inst
} }
const set = (signal, path, value) => { const set = (signal, path, value) => {
if (value === undefined) { if (value === undefined) {
signal(isFunc(path) ? path(signal()) : path); signal(isFunc(path) ? path(signal()) : path)
} else { } else {
const keys = path.split('.'); const keys = path.split('.')
const last = keys.pop(); const last = keys.pop()
const current = signal(); const current = signal()
const obj = keys.reduce((o, k) => ({ ...o, [k]: { ...o[k] } }), { ...current }); const obj = keys.reduce((o, k) => ({ ...o, [k]: { ...o[k] } }), { ...current })
obj[last] = value; obj[last] = value
signal(obj); signal(obj)
} }
}; }
const SigPro = Object.freeze({ $, Watch, Tag, Render, If, For, Router, Mount, onMount, onUnmount, set }) const SigPro = Object.freeze({ $, Watch, Tag, If, For, Router, Mount, onMount, onUnmount, set })
if (typeof window !== "undefined") { if (typeof window !== "undefined") {
Object.assign(window, SigPro) Object.assign(window, SigPro)
@@ -472,5 +508,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 { $, Watch, Tag, Render, If, For, Router, Mount, onMount, onUnmount, set } export { $, Watch, Tag, If, For, Router, Mount, onMount, onUnmount, set }
export default SigPro export default SigPro