Este sigpro es optimizado leible y con For muy rapido tipo Sigwork
This commit is contained in:
290
src/sigpro.js
290
src/sigpro.js
@@ -1,8 +1,7 @@
|
||||
const isFunc = f => typeof f === "function"
|
||||
const isObj = o => o && typeof o === "object"
|
||||
const isFunc = fn => typeof fn === "function"
|
||||
const isArr = Array.isArray
|
||||
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 activeOwner = null
|
||||
@@ -10,23 +9,23 @@ let isFlushing = false
|
||||
const effectQueue = new Set()
|
||||
const MOUNTED_NODES = new WeakMap()
|
||||
|
||||
const dispose = eff => {
|
||||
if (!eff || eff._disposed) return
|
||||
eff._disposed = true
|
||||
const stack = [eff]
|
||||
const dispose = effect => {
|
||||
if (!effect || effect._disposed) return
|
||||
effect._disposed = true
|
||||
const stack = [effect]
|
||||
while (stack.length) {
|
||||
const e = stack.pop()
|
||||
if (e._cleanups) {
|
||||
e._cleanups.forEach(fn => fn())
|
||||
e._cleanups.clear()
|
||||
const eff = stack.pop()
|
||||
if (eff._cleanups) {
|
||||
eff._cleanups.forEach(fn => fn())
|
||||
eff._cleanups.clear()
|
||||
}
|
||||
if (e._children) {
|
||||
e._children.forEach(child => stack.push(child))
|
||||
e._children.clear()
|
||||
if (eff._children) {
|
||||
eff._children.forEach(child => stack.push(child))
|
||||
eff._children.clear()
|
||||
}
|
||||
if (e._deps) {
|
||||
e._deps.forEach(depSet => depSet.delete(e))
|
||||
e._deps.clear()
|
||||
if (eff._deps) {
|
||||
eff._deps.forEach(depSet => depSet.delete(eff))
|
||||
eff._deps.clear()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -40,7 +39,7 @@ const createEffect = (fn, isComputed = false) => {
|
||||
if (effect._disposed) return
|
||||
if (effect._deps) effect._deps.forEach(depSet => depSet.delete(effect))
|
||||
if (effect._cleanups) {
|
||||
effect._cleanups.forEach(cl => cl())
|
||||
effect._cleanups.forEach(cleanup => cleanup())
|
||||
effect._cleanups.clear()
|
||||
}
|
||||
const prevEffect = activeEffect
|
||||
@@ -70,7 +69,7 @@ const flush = () => {
|
||||
isFlushing = true
|
||||
const sorted = Array.from(effectQueue).sort((a, b) => a._depth - b._depth)
|
||||
effectQueue.clear()
|
||||
for (const e of sorted) if (!e._disposed) e()
|
||||
for (const eff of sorted) if (!eff._disposed) eff()
|
||||
isFlushing = false
|
||||
}
|
||||
|
||||
@@ -80,13 +79,13 @@ const trackUpdate = (subs, trigger = false) => {
|
||||
;(activeEffect._deps ||= new Set()).add(subs)
|
||||
} else if (trigger) {
|
||||
let hasQueue = false
|
||||
subs.forEach(e => {
|
||||
if (e === activeEffect || e._disposed) return
|
||||
if (e._isComputed) {
|
||||
e._dirty = true
|
||||
if (e._subs) trackUpdate(e._subs, true)
|
||||
subs.forEach(eff => {
|
||||
if (eff === activeEffect || eff._disposed) return
|
||||
if (eff._isComputed) {
|
||||
eff._dirty = true
|
||||
if (eff._subs) trackUpdate(eff._subs, true)
|
||||
} else {
|
||||
effectQueue.add(e)
|
||||
effectQueue.add(eff)
|
||||
hasQueue = true
|
||||
}
|
||||
})
|
||||
@@ -95,25 +94,25 @@ const trackUpdate = (subs, trigger = false) => {
|
||||
}
|
||||
|
||||
const untrack = fn => {
|
||||
const p = activeEffect
|
||||
const prev = activeEffect
|
||||
activeEffect = null
|
||||
try { return fn() } finally { activeEffect = p }
|
||||
try { return fn() } finally { activeEffect = prev }
|
||||
}
|
||||
|
||||
const onMount = fn => {
|
||||
if (activeOwner) (activeOwner._mounts ||= []).push(fn)
|
||||
}
|
||||
|
||||
const $ = (val, key = null) => {
|
||||
const $ = (value, storageKey = null) => {
|
||||
const subs = new Set()
|
||||
if (isFunc(val)) {
|
||||
if (isFunc(value)) {
|
||||
let cache, dirty = true
|
||||
const computed = () => {
|
||||
if (dirty) {
|
||||
const prev = activeEffect
|
||||
activeEffect = computed
|
||||
try {
|
||||
const next = val()
|
||||
const next = value()
|
||||
if (!Object.is(cache, next)) {
|
||||
cache = next
|
||||
dirty = false
|
||||
@@ -141,30 +140,30 @@ const $ = (val, key = null) => {
|
||||
if (activeOwner) onUnmount(computed.stop)
|
||||
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) => {
|
||||
if (args.length) {
|
||||
const next = isFunc(args[0]) ? args[0](val) : args[0]
|
||||
if (!Object.is(val, next)) {
|
||||
val = next
|
||||
if (key) localStorage.setItem(key, JSON.stringify(val))
|
||||
const next = isFunc(args[0]) ? args[0](value) : args[0]
|
||||
if (!Object.is(value, next)) {
|
||||
value = next
|
||||
if (storageKey) localStorage.setItem(storageKey, JSON.stringify(value))
|
||||
trackUpdate(subs, true)
|
||||
}
|
||||
}
|
||||
trackUpdate(subs)
|
||||
return val
|
||||
return value
|
||||
}
|
||||
}
|
||||
|
||||
const Watch = (sources, cb) => {
|
||||
if (cb === undefined) {
|
||||
const Watch = (sources, callback) => {
|
||||
if (callback === undefined) {
|
||||
const effect = createEffect(sources)
|
||||
effect()
|
||||
return () => dispose(effect)
|
||||
}
|
||||
const effect = createEffect(() => {
|
||||
const vals = Array.isArray(sources) ? sources.map(s => s()) : sources()
|
||||
untrack(() => cb(vals))
|
||||
const vals = isArr(sources) ? sources.map(src => src()) : sources()
|
||||
untrack(() => callback(vals))
|
||||
})
|
||||
effect()
|
||||
return () => dispose(effect)
|
||||
@@ -184,18 +183,36 @@ const isDangerousAttr = key => key === 'src' || key === 'href' || key.startsWith
|
||||
|
||||
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 '#'
|
||||
}
|
||||
}
|
||||
if (isDangerousAttr(key) && DANGEROUS_PROTOCOL.test(String(val))) return '#'
|
||||
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 = []) => {
|
||||
if (props instanceof Node || isArr(props) || !isObj(props)) {
|
||||
if (props instanceof Node || isArr(props) || (props && typeof props !== 'object')) {
|
||||
children = props
|
||||
props = {}
|
||||
}
|
||||
@@ -213,65 +230,68 @@ const Tag = (tag, props = {}, children = []) => {
|
||||
ctx._mounts = effect._mounts || []
|
||||
ctx._cleanups = effect._cleanups || new Set()
|
||||
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)
|
||||
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)$/.test(tag)
|
||||
const el = isSVG ? doc.createElementNS("http://www.w3.org/2000/svg", tag) : doc.createElement(tag)
|
||||
el._cleanups = new Set()
|
||||
|
||||
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()
|
||||
|
||||
for (let k in props) {
|
||||
if (!props.hasOwnProperty(k)) continue
|
||||
let v = props[k]
|
||||
if (k === "ref") {
|
||||
isFunc(v) ? v(el) : (v.current = el)
|
||||
for (let key in props) {
|
||||
if (!props.hasOwnProperty(key)) continue
|
||||
let value = props[key]
|
||||
if (key === "ref") {
|
||||
isFunc(value) ? value(elem) : (value.current = elem)
|
||||
continue
|
||||
}
|
||||
if (k.startsWith("on")) {
|
||||
const ev = k.slice(2).toLowerCase()
|
||||
el.addEventListener(ev, v)
|
||||
const off = () => el.removeEventListener(ev, v)
|
||||
el._cleanups.add(off)
|
||||
if (key.startsWith("on")) {
|
||||
const event = key.slice(2).toLowerCase()
|
||||
elem.addEventListener(event, value)
|
||||
const off = () => elem.removeEventListener(event, value)
|
||||
elem._cleanups.add(off)
|
||||
onUnmount(off)
|
||||
} else if (isFunc(v)) {
|
||||
} else if (isFunc(value)) {
|
||||
const effect = createEffect(() => {
|
||||
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)
|
||||
const val = validateAttr(key, value())
|
||||
if (key === "class") elem.className = val || ""
|
||||
else if (val == null) elem.removeAttribute(key)
|
||||
else if (key in elem && !isSVG) elem[key] = val
|
||||
else elem.setAttribute(key, val === true ? "" : val)
|
||||
})
|
||||
effect()
|
||||
el._cleanups.add(() => dispose(effect))
|
||||
elem._cleanups.add(() => dispose(effect))
|
||||
onUnmount(() => dispose(effect))
|
||||
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]))
|
||||
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]))
|
||||
}
|
||||
} else {
|
||||
const val = validateAttr(k, v)
|
||||
const val = validateAttr(key, value)
|
||||
if (val != null) {
|
||||
if (k in el && !isSVG) el[k] = val
|
||||
else el.setAttribute(k, val === true ? "" : val)
|
||||
if (key in elem && !isSVG) elem[key] = val
|
||||
else elem.setAttribute(key, val === true ? "" : val)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const append = c => {
|
||||
if (isArr(c)) return c.forEach(append)
|
||||
if (isFunc(c)) {
|
||||
const append = child => {
|
||||
if (isArr(child)) return child.forEach(append)
|
||||
if (isFunc(child)) {
|
||||
const anchor = doc.createTextNode("")
|
||||
el.appendChild(anchor)
|
||||
elem.appendChild(anchor)
|
||||
let currentNodes = []
|
||||
const effect = createEffect(() => {
|
||||
const res = c()
|
||||
const res = child()
|
||||
const next = (isArr(res) ? res : [res]).map(ensureNode)
|
||||
currentNodes.forEach(n => {
|
||||
if (n._isRuntime) n.destroy()
|
||||
@@ -288,43 +308,59 @@ const Tag = (tag, props = {}, children = []) => {
|
||||
currentNodes = next
|
||||
})
|
||||
effect()
|
||||
el._cleanups.add(() => dispose(effect))
|
||||
elem._cleanups.add(() => dispose(effect))
|
||||
onUnmount(() => dispose(effect))
|
||||
} else {
|
||||
const node = ensureNode(c)
|
||||
el.appendChild(node)
|
||||
const node = ensureNode(child)
|
||||
elem.appendChild(node)
|
||||
if (node._mounts) node._mounts.forEach(fn => fn())
|
||||
}
|
||||
}
|
||||
append(children)
|
||||
return el
|
||||
return elem
|
||||
}
|
||||
|
||||
const Render = renderFn => {
|
||||
const createView = (renderFn) => {
|
||||
const cleanups = new Set()
|
||||
const mounts = []
|
||||
const previousOwner = activeOwner
|
||||
const container = doc.createElement("div")
|
||||
container.style.display = "contents"
|
||||
container.setAttribute("role", "presentation") // ← único cambio real
|
||||
activeOwner = { _cleanups: cleanups, _mounts: mounts }
|
||||
|
||||
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(result instanceof Node ? result : doc.createTextNode(String(result == null ? "" : result)))
|
||||
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()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
processResult(renderFn({ onCleanup: fn => cleanups.add(fn) }))
|
||||
} finally { activeOwner = previousOwner }
|
||||
|
||||
|
||||
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)
|
||||
} else {
|
||||
container.appendChild(node instanceof Node ? node : doc.createTextNode(String(node)))
|
||||
}
|
||||
}
|
||||
process(result)
|
||||
|
||||
mounts.forEach(fn => fn())
|
||||
return {
|
||||
_isRuntime: true,
|
||||
@@ -369,7 +405,7 @@ const If = (cond, ifYes, ifNot = null, trans = null) => {
|
||||
|
||||
const content = show ? ifYes : ifNot
|
||||
if (content) {
|
||||
currentView = Render(() => isFunc(content) ? content() : content)
|
||||
currentView = createView(() => isFunc(content) ? content() : content)
|
||||
root.insertBefore(currentView.container, anchor)
|
||||
if (trans?.in) trans.in(currentView.container)
|
||||
}
|
||||
@@ -390,7 +426,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 = Render(() => itemFn(item, i))
|
||||
if (!view) view = createView(() => itemFn(item, i))
|
||||
else cache.delete(key)
|
||||
nextCache.set(key, view)
|
||||
nextOrder.push(view)
|
||||
@@ -419,9 +455,9 @@ const Router = routes => {
|
||||
Watch([path], () => {
|
||||
const cur = path()
|
||||
const route = routes.find(r => {
|
||||
const p1 = r.path.split("/").filter(Boolean)
|
||||
const p2 = cur.split("/").filter(Boolean)
|
||||
return p1.length === p2.length && p1.every((p, i) => p[0] === ":" || p === p2[i])
|
||||
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])
|
||||
}) || routes.find(r => r.path === "*")
|
||||
if (route) {
|
||||
currentView?.destroy()
|
||||
@@ -430,14 +466,14 @@ const Router = routes => {
|
||||
if (p[0] === ":") params[p.slice(1)] = cur.split("/").filter(Boolean)[i]
|
||||
})
|
||||
Router.params(params)
|
||||
currentView = Render(() => isFunc(route.component) ? route.component(params) : route.component)
|
||||
currentView = createView(() => isFunc(route.component) ? route.component(params) : route.component)
|
||||
outlet.replaceChildren(currentView.container)
|
||||
}
|
||||
})
|
||||
return outlet
|
||||
}
|
||||
Router.params = $({})
|
||||
Router.to = p => window.location.hash = p.replace(/^#?\/?/, "#/")
|
||||
Router.to = path => window.location.hash = path.replace(/^#?\/?/, "#/")
|
||||
Router.back = () => window.history.back()
|
||||
Router.path = () => window.location.hash.replace(/^#/, "") || "/"
|
||||
|
||||
@@ -445,26 +481,26 @@ const Mount = (comp, target) => {
|
||||
const t = typeof target === "string" ? doc.querySelector(target) : target
|
||||
if (!t) return
|
||||
if (MOUNTED_NODES.has(t)) MOUNTED_NODES.get(t).destroy()
|
||||
const inst = Render(isFunc(comp) ? comp : () => comp)
|
||||
const inst = createView(() => 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);
|
||||
}
|
||||
};
|
||||
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, 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") {
|
||||
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))
|
||||
}
|
||||
|
||||
export { $, Watch, Tag, Render, If, For, Router, Mount, onMount, onUnmount, set }
|
||||
export { $, Watch, Tag, If, For, Router, Mount, onMount, onUnmount, set }
|
||||
export default SigPro
|
||||
Reference in New Issue
Block a user