events on Tabs

This commit is contained in:
2026-04-13 22:23:10 +02:00
parent 3c3938b354
commit a29963563e
8 changed files with 804 additions and 885 deletions

View File

@@ -1,7 +1,9 @@
const isFunc = fn => typeof fn === "function"
// sigpro 1.2.0
const isFunc = f => typeof f === "function"
const isObj = o => o && typeof o === "object"
const isArr = Array.isArray
const doc = typeof document !== "undefined" ? document : null
const ensureNode = node => node?._isRuntime ? node.container : (node instanceof Node ? node : doc.createTextNode(node == null ? "" : String(node)))
const ensureNode = n => n?._isRuntime ? n.container : (n instanceof Node ? n : doc.createTextNode(n == null ? "" : String(n)))
let activeEffect = null
let activeOwner = null
@@ -9,55 +11,73 @@ let isFlushing = false
const effectQueue = new Set()
const MOUNTED_NODES = new WeakMap()
const dispose = effect => {
if (!effect || effect._disposed) return
effect._disposed = true
const stack = [effect]
// effect cleanup
const dispose = eff => {
if (!eff || eff._disposed) return
eff._disposed = true
const stack = [eff]
while (stack.length) {
const eff = stack.pop()
if (eff._cleanups) {
eff._cleanups.forEach(fn => fn())
eff._cleanups.clear()
const e = stack.pop()
if (e._cleanups) {
e._cleanups.forEach(fn => fn())
e._cleanups.clear()
}
if (eff._children) {
eff._children.forEach(child => stack.push(child))
eff._children.clear()
if (e._children) {
e._children.forEach(child => stack.push(child))
e._children.clear()
}
if (eff._deps) {
eff._deps.forEach(depSet => depSet.delete(eff))
eff._deps.clear()
if (e._deps) {
e._deps.forEach(depSet => depSet.delete(e))
e._deps.clear()
}
}
}
// helpers
const onMount = fn => {
if (activeOwner) (activeOwner._mounts ||= []).push(fn)
}
const onUnmount = fn => {
if (activeOwner) (activeOwner._cleanups ||= new Set()).add(fn)
}
const onMount = fn => {
if (activeOwner) (activeOwner._mounts ||= []).push(fn)
const set = (signal, path, value) => {
if (value === undefined) return signal(isFunc(path) ? path(signal()) : path)
const keys = path.split('.'), root = { ...signal() }
let acc = root, k
for (k of keys.slice(0, -1)) acc = acc[k] = { ...(acc[k] || {}) }
acc[keys.at(-1)] = value
signal(root)
}
const untrack = fn => {
const p = activeEffect
activeEffect = null
try { return fn() } finally { activeEffect = p }
}
// effect creation
const createEffect = (fn, isComputed = false) => {
const effect = () => {
if (effect._disposed) return
if (effect._deps) effect._deps.forEach(depSet => depSet.delete(effect))
if (effect._cleanups) {
effect._cleanups.forEach(cleanup => cleanup())
effect._cleanups.clear()
}
const prevEffect = activeEffect
const prevOwner = activeOwner
activeEffect = activeOwner = effect
try {
const res = isComputed ? fn() : (fn(), undefined)
if (!isComputed) effect._result = res
return res
} finally {
activeEffect = prevEffect
activeOwner = prevOwner
}
if (effect._disposed) return
if (effect._deps) effect._deps.forEach(s => s.delete(effect))
if (effect._cleanups) {
effect._cleanups.forEach(c => c())
effect._cleanups.clear()
}
const prevEffect = activeEffect
const prevOwner = activeOwner
activeEffect = activeOwner = effect
try {
return effect._result = fn()
} catch (e) {
console.error("[SigPro]", e)
} finally {
activeEffect = prevEffect
activeOwner = prevOwner
}
}
effect._deps = effect._cleanups = effect._children = null
effect._disposed = false
effect._isComputed = isComputed
@@ -73,23 +93,23 @@ const flush = () => {
isFlushing = true
const sorted = Array.from(effectQueue).sort((a, b) => a._depth - b._depth)
effectQueue.clear()
for (const eff of sorted) if (!eff._disposed) eff()
for (const e of sorted) if (!e._disposed) e()
isFlushing = false
}
const trackUpdate = (subs, trigger = false) => {
if (!trigger && activeEffect && !activeEffect._disposed) {
subs.add(activeEffect)
;(activeEffect._deps ||= new Set()).add(subs)
; (activeEffect._deps ||= new Set()).add(subs)
} else if (trigger) {
let hasQueue = false
subs.forEach(eff => {
if (eff === activeEffect || eff._disposed) return
if (eff._isComputed) {
eff._dirty = true
if (eff._subs) trackUpdate(eff._subs, true)
subs.forEach(e => {
if (e === activeEffect || e._disposed) return
if (e._isComputed) {
e._dirty = true
if (e._subs) trackUpdate(e._subs, true)
} else {
effectQueue.add(eff)
effectQueue.add(e)
hasQueue = true
}
})
@@ -97,22 +117,17 @@ const trackUpdate = (subs, trigger = false) => {
}
}
const untrack = fn => {
const prev = activeEffect
activeEffect = null
try { return fn() } finally { activeEffect = prev }
}
const $ = (initialValue, storageKey = null) => {
// signal creation
const $ = (val, key = null) => {
const subs = new Set()
if (isFunc(initialValue)) {
if (isFunc(val)) {
let cache, dirty = true
const computed = () => {
if (dirty) {
const prev = activeEffect
activeEffect = computed
try {
const next = initialValue()
const next = val()
if (!Object.is(cache, next)) {
cache = next
dirty = false
@@ -140,30 +155,31 @@ const $ = (initialValue, storageKey = null) => {
if (activeOwner) onUnmount(computed.stop)
return computed
}
if (storageKey) try { initialValue = JSON.parse(localStorage.getItem(storageKey)) ?? initialValue } catch (e) {}
if (key) try { val = JSON.parse(localStorage.getItem(key)) ?? val } catch (e) { }
return (...args) => {
if (args.length) {
const next = isFunc(args[0]) ? args[0](initialValue) : args[0]
if (!Object.is(initialValue, next)) {
initialValue = next
if (storageKey) localStorage.setItem(storageKey, JSON.stringify(initialValue))
const next = isFunc(args[0]) ? args[0](val) : args[0]
if (!Object.is(val, next)) {
val = next
if (key) localStorage.setItem(key, JSON.stringify(val))
trackUpdate(subs, true)
}
}
trackUpdate(subs)
return initialValue
return val
}
}
const Watch = (sources, callback) => {
if (callback === undefined) {
// create Watch
const Watch = (sources, cb) => {
if (cb === undefined) {
const effect = createEffect(sources)
effect()
return () => dispose(effect)
}
const effect = createEffect(() => {
const vals = isArr(sources) ? sources.map(src => src()) : sources()
untrack(() => callback(vals))
const vals = Array.isArray(sources) ? sources.map(s => s()) : sources()
untrack(() => cb(vals))
})
effect()
return () => dispose(effect)
@@ -181,109 +197,103 @@ const cleanupNode = node => {
const DANGEROUS_PROTOCOL = /^\s*(javascript|data|vbscript):/i
const isDangerousAttr = key => key === 'src' || key === 'href' || key.startsWith('on')
const applyProp = (elem, key, value, isSVG) => {
if (value == null || value === false) {
if (key === 'class' || key === 'className') elem.className = ''
else if (key in elem && !isSVG) elem[key] = ''
else elem.removeAttribute(key)
return
}
if (key === 'class' || key === 'className') {
elem.className = value
} else if (key === 'style' && typeof value === 'object') {
Object.assign(elem.style, value)
} else if (key in elem && !isSVG) {
elem[key] = value
} else if (isSVG) {
if (key.startsWith('xlink:')) {
elem.setAttributeNS('http://www.w3.org/1999/xlink', key, value)
} else if (key === 'xmlns' || key.startsWith('xmlns:')) {
elem.setAttributeNS('http://www.w3.org/2000/xmlns/', key, value)
} else {
elem.setAttribute(key, value === true ? '' : value)
const validateAttr = (key, val) => {
if (val == null || val === false) return null
if (isDangerousAttr(key)) {
const sVal = String(val)
if (DANGEROUS_PROTOCOL.test(sVal)) {
console.warn(`[SigPro] Bloqueado protocolo peligroso en ${key}`)
return '#'
}
} else {
elem.setAttribute(key, value === true ? '' : value)
}
return val
}
// create Tag
const Tag = (tag, props = {}, children = []) => {
if (props instanceof Node || isArr(props) || (props && typeof props !== 'object')) {
if (props instanceof Node || isArr(props) || !isObj(props)) {
children = props
props = {}
}
if (isFunc(tag)) {
const ctx = { _mounts: [], _cleanups: new Set() }
const effect = createEffect(() => {
const result = tag(props, {
children,
emit: (ev, ...args) => props[`on${ev[0].toUpperCase()}${ev.slice(1)}`]?.(...args)
})
effect._result = result
return result
const ctx = { _mounts: [], _cleanups: new Set() }
const effect = createEffect(() => {
const result = tag(props, {
children,
emit: (ev, ...args) => props[`on${ev[0].toUpperCase()}${ev.slice(1)}`]?.(...args)
})
effect()
ctx._mounts = effect._mounts || []
ctx._cleanups = effect._cleanups || new Set()
const result = effect._result
const attach = node => {
if (node && typeof node === 'object' && !node._isRuntime) {
node._mounts = ctx._mounts
node._cleanups = ctx._cleanups
node._ownerEffect = effect
}
effect._result = result
return result
})
effect()
const result = effect._result
if (result == null) return null
const node = (result instanceof Node || (isArr(result) && result.every(n => n instanceof Node)))
? result
: doc.createTextNode(String(result))
const attach = n => {
if (isObj(n) && !n._isRuntime) {
n._mounts = effect._mounts || []
n._cleanups = effect._cleanups || new Set()
n._ownerEffect = effect
}
isArr(result) ? result.forEach(attach) : attach(result)
if (result == null) return null
if (result instanceof Node || (isArr(result) && result.every(n => n instanceof Node))) return result
return doc.createTextNode(String(result))
}
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 elem = isSVG ? doc.createElementNS("http://www.w3.org/2000/svg", tag) : doc.createElement(tag)
elem._cleanups = new Set()
isArr(node) ? node.forEach(attach) : attach(node)
return node
}
const isSVG = /^(svg|path|circle|rect|line|polyline|polygon|g|defs|text|tspan|use)$/.test(tag)
const el = isSVG ? doc.createElementNS("http://www.w3.org/2000/svg", tag) : doc.createElement(tag)
el._cleanups = new Set()
for (let key in props) {
if (!props.hasOwnProperty(key)) continue
let value = props[key]
if (key === "ref") {
isFunc(value) ? value(elem) : (value.current = elem)
for (let k in props) {
if (!props.hasOwnProperty(k)) continue
let v = props[k]
if (k === "ref") {
isFunc(v) ? v(el) : (v.current = el)
continue
}
if (key.startsWith("on")) {
const event = key.slice(2).toLowerCase()
elem.addEventListener(event, value)
const off = () => elem.removeEventListener(event, value)
elem._cleanups.add(off)
if (k.startsWith("on")) {
const ev = k.slice(2).toLowerCase()
el.addEventListener(ev, v)
const off = () => el.removeEventListener(ev, v)
el._cleanups.add(off)
onUnmount(off)
} else if (isFunc(value)) {
} else if (isFunc(v)) {
const effect = createEffect(() => {
let val = value()
if (isDangerousAttr(key) && DANGEROUS_PROTOCOL.test(String(val))) val = '#'
applyProp(elem, key, val, isSVG)
const val = validateAttr(k, v())
if (k === "class") el.className = val || ""
else if (val == null) el.removeAttribute(k)
else if (k in el && !isSVG) el[k] = val
else el.setAttribute(k, val === true ? "" : val)
})
effect()
elem._cleanups.add(() => dispose(effect))
el._cleanups.add(() => dispose(effect))
onUnmount(() => dispose(effect))
if (/^(INPUT|TEXTAREA|SELECT)$/.test(elem.tagName) && (key === "value" || key === "checked")) {
const eventType = key === "checked" ? "change" : "input"
elem.addEventListener(eventType, ev => value(ev.target[key]))
if (/^(INPUT|TEXTAREA|SELECT)$/.test(el.tagName) && (k === "value" || k === "checked")) {
const evType = k === "checked" ? "change" : "input"
el.addEventListener(evType, ev => v(ev.target[k]))
}
} else {
let val = value
if (isDangerousAttr(key) && DANGEROUS_PROTOCOL.test(String(val))) val = '#'
if (val != null) applyProp(elem, key, val, isSVG)
const val = validateAttr(k, v)
if (val != null) {
if (k in el && !isSVG) el[k] = val
else el.setAttribute(k, val === true ? "" : val)
}
}
}
const mountChild = child => {
if (isArr(child)) return child.forEach(mountChild)
if (isFunc(child)) {
const append = c => {
if (isArr(c)) return c.forEach(append)
if (isFunc(c)) {
const anchor = doc.createTextNode("")
elem.appendChild(anchor)
el.appendChild(anchor)
let currentNodes = []
const effect = createEffect(() => {
const res = child()
const res = c()
const next = (isArr(res) ? res : [res]).map(ensureNode)
currentNodes.forEach(n => {
if (n._isRuntime) n.destroy()
@@ -300,59 +310,49 @@ const Tag = (tag, props = {}, children = []) => {
currentNodes = next
})
effect()
elem._cleanups.add(() => dispose(effect))
el._cleanups.add(() => dispose(effect))
onUnmount(() => dispose(effect))
} else {
const node = ensureNode(child)
elem.appendChild(node)
const node = ensureNode(c)
el.appendChild(node)
if (node._mounts) node._mounts.forEach(fn => fn())
}
}
mountChild(children)
return elem
append(children)
return el
}
const createView = (renderFn) => {
// create Render
const Render = renderFn => {
const cleanups = new Set()
const mounts = []
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 previousEffect = activeEffect
const container = doc.createElement("div")
container.style.display = "contents"
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)
container.setAttribute("role", "presentation") // ← único cambio real
activeOwner = { _cleanups: cleanups, _mounts: mounts }
activeEffect = null
const processResult = result => {
if (!result) return
if (result._isRuntime) {
cleanups.add(result.destroy)
container.appendChild(result.container)
} else if (isArr(result)) {
result.forEach(processResult)
} else {
container.appendChild(node instanceof Node ? node : doc.createTextNode(String(node)))
container.appendChild(result instanceof Node ? result : doc.createTextNode(String(result == null ? "" : result)))
}
}
process(result)
try {
processResult(renderFn({ onCleanup: fn => cleanups.add(fn) }))
} finally {
activeOwner = previousOwner
activeEffect = previousEffect
}
mounts.forEach(fn => fn())
return {
_isRuntime: true,
@@ -365,6 +365,7 @@ const createView = (renderFn) => {
}
}
// create If
const If = (cond, ifYes, ifNot = null, trans = null) => {
const anchor = doc.createTextNode("")
const root = Tag("div", { style: "display:contents" }, [anchor])
@@ -397,7 +398,7 @@ const If = (cond, ifYes, ifNot = null, trans = null) => {
const content = show ? ifYes : ifNot
if (content) {
currentView = createView(() => isFunc(content) ? content() : content)
currentView = Render(() => isFunc(content) ? content() : content)
root.insertBefore(currentView.container, anchor)
if (trans?.in) trans.in(currentView.container)
}
@@ -406,6 +407,7 @@ const If = (cond, ifYes, ifNot = null, trans = null) => {
return root
}
// create For
const For = (src, itemFn, keyFn) => {
const anchor = doc.createTextNode("")
const root = Tag("div", { style: "display:contents" }, [anchor])
@@ -418,7 +420,7 @@ const For = (src, itemFn, keyFn) => {
const item = newItems[i]
const key = keyFn ? keyFn(item, i) : (item?.id ?? i)
let view = cache.get(key)
if (!view) view = createView(() => itemFn(item, i))
if (!view) view = Render(() => itemFn(item, i))
else cache.delete(key)
nextCache.set(key, view)
nextOrder.push(view)
@@ -436,20 +438,21 @@ const For = (src, itemFn, keyFn) => {
return root
}
// create Router
const Router = routes => {
const getHash = () => window.location.hash.slice(1) || "/"
const path = $(getHash())
const handler = () => path(getHash())
window.addEventListener("hashchange", handler)
onUnmount(() => window.removeEventListener("hashchange", handler))
const outlet = Tag("div", { class: "router-outlet" })
const hook = Tag("div", { class: "router-hook" })
let currentView = null
Watch([path], () => {
const cur = path()
const route = routes.find(r => {
const rParts = r.path.split("/").filter(Boolean)
const curParts = cur.split("/").filter(Boolean)
return rParts.length === curParts.length && rParts.every((p, i) => p[0] === ":" || p === curParts[i])
const p1 = r.path.split("/").filter(Boolean)
const p2 = cur.split("/").filter(Boolean)
return p1.length === p2.length && p1.every((p, i) => p[0] === ":" || p === p2[i])
}) || routes.find(r => r.path === "*")
if (route) {
currentView?.destroy()
@@ -458,14 +461,14 @@ const Router = routes => {
if (p[0] === ":") params[p.slice(1)] = cur.split("/").filter(Boolean)[i]
})
Router.params(params)
currentView = createView(() => isFunc(route.component) ? route.component(params) : route.component)
outlet.replaceChildren(currentView.container)
currentView = Render(() => isFunc(route.component) ? route.component(params) : route.component)
hook.replaceChildren(currentView.container)
}
})
return outlet
return hook
}
Router.params = $({})
Router.to = path => window.location.hash = path.replace(/^#?\/?/, "#/")
Router.to = p => window.location.hash = p.replace(/^#?\/?/, "#/")
Router.back = () => window.history.back()
Router.path = () => window.location.hash.replace(/^#/, "") || "/"
@@ -473,26 +476,13 @@ const Mount = (comp, target) => {
const t = typeof target === "string" ? doc.querySelector(target) : target
if (!t) return
if (MOUNTED_NODES.has(t)) MOUNTED_NODES.get(t).destroy()
const inst = createView(() => isFunc(comp) ? comp() : comp)
const inst = Render(isFunc(comp) ? comp : () => comp)
t.replaceChildren(inst.container)
MOUNTED_NODES.set(t, inst)
return inst
}
const 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)
}
}
const SigPro = Object.freeze({ $, Watch, Tag, If, For, Router, Mount, onMount, onUnmount, set })
const SigPro = Object.freeze({ $, Watch, Tag, Render, If, For, Router, Mount, onMount, onUnmount, set })
if (typeof window !== "undefined") {
Object.assign(window, SigPro)
@@ -500,5 +490,5 @@ if (typeof window !== "undefined") {
.split(" ").forEach(t => window[t[0].toUpperCase() + t.slice(1)] = (p, c) => SigPro.Tag(t, p, c))
}
export { $, Watch, Tag, If, For, Router, Mount, onMount, onUnmount, set }
export { $, Watch, Tag, Render, If, For, Router, Mount, onMount, onUnmount, set }
export default SigPro