Files
sigpro-ui/src/sigpro.js

512 lines
16 KiB
JavaScript

const isFunc = fn => typeof fn === "function"
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)))
let activeEffect = null
let activeOwner = null
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]
while (stack.length) {
const eff = stack.pop()
if (eff._cleanups) {
eff._cleanups.forEach(fn => fn())
eff._cleanups.clear()
}
if (eff._children) {
eff._children.forEach(child => stack.push(child))
eff._children.clear()
}
if (eff._deps) {
eff._deps.forEach(depSet => depSet.delete(eff))
eff._deps.clear()
}
}
}
const onUnmount = fn => {
if (activeOwner) (activeOwner._cleanups ||= new Set()).add(fn)
}
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
}
}
effect._deps = effect._cleanups = effect._children = null
effect._disposed = false
effect._isComputed = isComputed
effect._depth = activeEffect ? activeEffect._depth + 1 : 0
effect._mounts = []
effect._parent = activeOwner
if (activeOwner) (activeOwner._children ||= new Set()).add(effect)
return effect
}
const flush = () => {
if (isFlushing) return
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()
isFlushing = false
}
const trackUpdate = (subs, trigger = false) => {
if (!trigger && activeEffect && !activeEffect._disposed) {
subs.add(activeEffect)
;(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)
} else {
effectQueue.add(eff)
hasQueue = true
}
})
if (hasQueue && !isFlushing) queueMicrotask(flush)
}
}
const untrack = fn => {
const prev = activeEffect
activeEffect = null
try { return fn() } finally { activeEffect = prev }
}
const onMount = fn => {
if (activeOwner) (activeOwner._mounts ||= []).push(fn)
}
const $ = (value, storageKey = null) => {
const subs = new Set()
if (isFunc(value)) {
let cache, dirty = true
const computed = () => {
if (dirty) {
const prev = activeEffect
activeEffect = computed
try {
const next = value()
if (!Object.is(cache, next)) {
cache = next
dirty = false
trackUpdate(subs, true)
}
} finally { activeEffect = prev }
}
trackUpdate(subs)
return cache
}
computed._isComputed = true
computed._subs = subs
computed._dirty = true
computed._deps = null
computed._disposed = false
computed.markDirty = () => { dirty = true }
computed.stop = () => {
computed._disposed = true
if (computed._deps) {
computed._deps.forEach(depSet => depSet.delete(computed))
computed._deps.clear()
}
subs.clear()
}
if (activeOwner) onUnmount(computed.stop)
return computed
}
if (storageKey) try { value = JSON.parse(localStorage.getItem(storageKey)) ?? value } catch (e) {}
return (...args) => {
if (args.length) {
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 value
}
}
const Watch = (sources, callback) => {
if (callback === undefined) {
const effect = createEffect(sources)
effect()
return () => dispose(effect)
}
const effect = createEffect(() => {
const vals = isArr(sources) ? sources.map(src => src()) : sources()
untrack(() => callback(vals))
})
effect()
return () => dispose(effect)
}
const cleanupNode = node => {
if (node._cleanups) {
node._cleanups.forEach(fn => fn())
node._cleanups.clear()
}
if (node._ownerEffect) dispose(node._ownerEffect)
if (node.childNodes) node.childNodes.forEach(cleanupNode)
}
const DANGEROUS_PROTOCOL = /^\s*(javascript|data|vbscript):/i
const isDangerousAttr = key => key === 'src' || key === 'href' || key.startsWith('on')
const validateAttr = (key, val) => {
if (val == null || val === false) return null
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) || (props && typeof props !== 'object')) {
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
})
effect()
ctx._mounts = effect._mounts || []
ctx._cleanups = effect._cleanups || new Set()
const result = effect._result
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|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 key in props) {
if (!props.hasOwnProperty(key)) continue
let value = props[key]
if (key === "ref") {
isFunc(value) ? value(elem) : (value.current = elem)
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)
onUnmount(off)
} else if (isFunc(value)) {
const effect = createEffect(() => {
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()
elem._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]))
}
} else {
const val = validateAttr(key, value)
if (val != null) {
if (key in elem && !isSVG) elem[key] = val
else elem.setAttribute(key, val === true ? "" : val)
}
}
}
const append = child => {
if (isArr(child)) return child.forEach(append)
if (isFunc(child)) {
const anchor = doc.createTextNode("")
elem.appendChild(anchor)
let currentNodes = []
const effect = createEffect(() => {
const res = child()
const next = (isArr(res) ? res : [res]).map(ensureNode)
currentNodes.forEach(n => {
if (n._isRuntime) n.destroy()
else cleanupNode(n)
if (n.parentNode) n.remove()
})
let ref = anchor
for (let i = next.length - 1; i >= 0; i--) {
const node = next[i]
if (node.parentNode !== ref.parentNode) ref.parentNode?.insertBefore(node, ref)
if (node._mounts) node._mounts.forEach(fn => fn())
ref = node
}
currentNodes = next
})
effect()
elem._cleanups.add(() => dispose(effect))
onUnmount(() => dispose(effect))
} else {
const node = ensureNode(child)
elem.appendChild(node)
if (node._mounts) node._mounts.forEach(fn => fn())
}
}
append(children)
return elem
}
const createView = (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 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,
container,
destroy: () => {
cleanups.forEach(fn => fn())
cleanupNode(container)
container.remove()
}
}
}
const If = (cond, ifYes, ifNot = null, trans = null) => {
const anchor = doc.createTextNode("")
const root = Tag("div", { style: "display:contents" }, [anchor])
let currentView = null
let last = null
let exitPromise = null
Watch(
() => !!(isFunc(cond) ? cond() : cond),
show => {
if (show === last) return
last = show
const disposeView = () => {
if (currentView) {
currentView.destroy()
currentView = null
}
}
if (currentView && !show && trans?.out) {
if (exitPromise && exitPromise.cancel) exitPromise.cancel()
const anim = trans.out(currentView.container, disposeView)
exitPromise = anim
if (anim && anim.finished) anim.finished.then(disposeView)
else disposeView()
} else {
disposeView()
}
const content = show ? ifYes : ifNot
if (content) {
currentView = createView(() => isFunc(content) ? content() : content)
root.insertBefore(currentView.container, anchor)
if (trans?.in) trans.in(currentView.container)
}
}
)
return root
}
const For = (src, itemFn, keyFn) => {
const anchor = doc.createTextNode("")
const root = Tag("div", { style: "display:contents" }, [anchor])
let cache = new Map()
Watch(() => (isFunc(src) ? src() : src) || [], items => {
const nextCache = new Map()
const nextOrder = []
const newItems = items || []
for (let i = 0; i < newItems.length; i++) {
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))
else cache.delete(key)
nextCache.set(key, view)
nextOrder.push(view)
}
cache.forEach(view => view.destroy())
let lastRef = anchor
for (let i = nextOrder.length - 1; i >= 0; i--) {
const view = nextOrder[i]
const node = view.container
if (node.nextSibling !== lastRef) root.insertBefore(node, lastRef)
lastRef = node
}
cache = nextCache
})
return root
}
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" })
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])
}) || routes.find(r => r.path === "*")
if (route) {
currentView?.destroy()
const params = {}
route.path.split("/").filter(Boolean).forEach((p, i) => {
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)
}
})
return outlet
}
Router.params = $({})
Router.to = path => window.location.hash = path.replace(/^#?\/?/, "#/")
Router.back = () => window.history.back()
Router.path = () => window.location.hash.replace(/^#/, "") || "/"
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)
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 })
if (typeof window !== "undefined") {
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))
}
export { $, Watch, Tag, If, For, Router, Mount, onMount, onUnmount, set }
export default SigPro