This commit is contained in:
2026-04-07 23:37:20 +02:00
parent 20d9023575
commit 9069d44284

View File

@@ -1,587 +1,258 @@
const DANGEROUS_PROTOCOLS = /^(javascript|data|vbscript):/i; // ---------------------------
const DANGEROUS_ATTRIBUTES = /^on/i; // SigPro v2
// ---------------------------
const sanitizeUrl = (url) => { // --- Scheduler ---
const str = String(url ?? '').trim().toLowerCase();
if (DANGEROUS_PROTOCOLS.test(str)) return '#';
return str;
};
const sanitizeAttribute = (name, value) => {
if (value == null) return null;
const strValue = String(value);
if (DANGEROUS_ATTRIBUTES.test(name)) {
console.warn(`[SigPro] XSS prevention: blocked attribute "${name}"`);
return null;
}
if (name === 'src' || name === 'href') {
return sanitizeUrl(strValue);
}
return strValue;
};
let activeEffect = null;
let isScheduled = false; let isScheduled = false;
const queue = new Set(); const queue = new Set();
const flushQueue = () => {
const tick = () => {
while (queue.size) {
const runs = [...queue]; const runs = [...queue];
queue.clear(); queue.clear();
runs.forEach(fn => fn()); runs.forEach(fn => fn());
}
isScheduled = false; isScheduled = false;
}; };
const schedule = (fn) => { // --- Core State & Ownership ---
if (fn.d) return; let activeEffect = null;
queue.add(fn); let currentOwner = null;
if (!isScheduled) { let currentContext = null;
queueMicrotask(tick); const nodeContexts = new WeakMap();
isScheduled = true;
}
};
const depend = (subs) => { // --- Security ---
if (activeEffect && !activeEffect.c) { const DANGEROUS = /^(javascript|data|vbscript):/i;
subs.add(activeEffect); const sanitize = v => DANGEROUS.test(String(v)) ? '#' : v;
activeEffect.e.add(subs);
}
};
export const effect = (fn, isScope = false) => { // --- Effect System ---
let cleanup = null; export const effect = (fn) => {
const owner = currentOwner;
const run = () => { const runner = () => {
if (run.d) return; cleanup();
const prev = activeEffect; const prevOwner = currentOwner;
activeEffect = run; const prevEffect = activeEffect;
const result = fn(); currentOwner = owner;
if (typeof result === 'function') cleanup = result; activeEffect = runner;
activeEffect = prev; runner.cleanupFns = [];
try { fn(); }
finally { currentOwner = prevOwner; activeEffect = prevEffect; }
}; };
const cleanup = () => {
const stop = () => { runner.deps?.forEach(dep => dep.delete(runner));
if (run.d) return; runner.cleanupFns?.forEach(f => f());
run.d = true; runner.deps?.clear();
run.e.forEach(subs => subs.delete(run));
run.e.clear();
cleanup?.();
run.c?.forEach(f => f());
}; };
runner.deps = new Set();
run.e = new Set(); runner.cleanupFns = [];
run.d = false; owner?.cleanups.add(cleanup);
if (isScope) run.c = []; runner();
return cleanup;
run();
activeEffect?.c?.push(stop);
return stop;
}; };
effect.react = (fn) => { // --- Signals ---
const prev = activeEffect; export const signal = (value) => {
activeEffect = null;
const result = fn();
activeEffect = prev;
return result;
};
export function $(initial, storageKey) {
const isComputed = typeof initial === 'function';
if (!isComputed) {
let value = initial;
const subs = new Set(); const subs = new Set();
return {
if (storageKey) { _isSig: true,
try { get value() {
const saved = localStorage.getItem(storageKey); if (activeEffect) { subs.add(activeEffect); activeEffect.deps.add(subs); }
if (saved !== null) value = JSON.parse(saved);
} catch { }
}
const signalFn = (...args) => {
if (args.length === 0) {
return value; return value;
},
set value(v) {
if (v === value) return;
value = v;
subs.forEach(fn => queue.add(fn));
if (!isScheduled) { isScheduled = true; queueMicrotask(flushQueue); }
} }
const next = typeof args[0] === 'function' ? args[0](value) : args[0];
if (Object.is(value, next)) return value;
value = next;
if (storageKey) {
try {
localStorage.setItem(storageKey, JSON.stringify(value));
} catch { }
}
subs.forEach(fn => schedule(fn));
return value;
}; };
};
signalFn.react = () => { export const computed = (fn) => {
depend(subs); const c = signal(fn());
return value; effect(() => c.value = fn());
}; return { get value() { return c.value; } };
return signalFn;
}
let cached;
let dirty = true;
const subs = new Set();
const fn = initial;
effect(() => {
const newValue = fn();
if (!Object.is(cached, newValue) || dirty) {
cached = newValue;
dirty = false;
subs.forEach(fn => schedule(fn));
}
});
const computedFn = () => {
return cached;
};
computedFn.react = () => {
depend(subs);
return cached;
};
return computedFn;
}
export const scope = (fn) => effect(fn, true);
export const watch = (source, callback) => {
let first = true;
let oldValue;
return effect(() => {
const newValue = source();
if (!first) {
effect.react(() => callback(newValue, oldValue));
} else {
first = false;
}
oldValue = newValue;
});
}; };
const reactiveCache = new WeakMap(); const reactiveCache = new WeakMap();
export const reactive = (obj) => {
export function $$(obj) { if (!obj || typeof obj !== 'object') return obj;
if (reactiveCache.has(obj)) { if (reactiveCache.has(obj)) return reactiveCache.get(obj);
return reactiveCache.get(obj);
}
const subs = {}; const subs = {};
const proxy = new Proxy(obj, { const proxy = new Proxy(obj, {
get(target, key, receiver) { get(t, k) {
const subsForKey = subs[key] ??= new Set(); if (!subs[k]) subs[k] = new Set();
depend(subsForKey); if (activeEffect) { subs[k].add(activeEffect); activeEffect.deps.add(subs[k]); }
const val = Reflect.get(target, key, receiver); const val = t[k];
return (val && typeof val === 'object') ? $$(val) : val; return val && typeof val === 'object' ? reactive(val) : val;
}, },
set(target, key, val, receiver) { set(t, k, v) {
if (Object.is(target[key], val)) return true; if (t[k] === v) return true;
const success = Reflect.set(target, key, val, receiver); t[k] = v;
if (subs[key]) { subs[k]?.forEach(fn => queue.add(fn));
subs[key].forEach(fn => schedule(fn)); if (!isScheduled) { isScheduled = true; queueMicrotask(flushQueue); }
if (!isScheduled) { return true;
queueMicrotask(tick);
isScheduled = true;
}
}
return success;
} }
}); });
reactiveCache.set(obj, proxy); reactiveCache.set(obj, proxy);
return proxy; return proxy;
}
let context = null;
export const onMount = (fn) => {
context?.m.push(fn);
}; };
export const onUnmount = (fn) => { // --- Watch with cleanup ---
context?.u.push(fn); export const watch = (source, cb, options = {}) => {
let oldValue, firstRun = true, lastCleanup = null;
const stop = effect(() => {
const newValue = typeof source === 'function' ? source() : source.value;
if (!firstRun || options.immediate) {
if (lastCleanup) { lastCleanup(); lastCleanup = null; }
const prevEffect = activeEffect;
activeEffect = null;
try { cb(newValue, oldValue, (fn) => { lastCleanup = fn; }); }
finally { activeEffect = prevEffect; }
}
oldValue = newValue;
firstRun = false;
});
return () => { stop(); if (lastCleanup) lastCleanup(); };
}; };
export const share = (key, value) => { // --- Lifecycle ---
if (context) context.p[key] = value; export const onMount = (fn) => currentContext?.mount.push(fn);
export const onUnmount = (fn) => currentContext?.unmount.push(fn);
export const provide = (key, value) => { if (currentContext) currentContext.provide[key] = value; };
export const inject = (key, def) => {
let ctx = currentContext;
while (ctx) {
if (ctx.provide[key] !== undefined) return ctx.provide[key];
ctx = ctx.parent;
}
return def;
}; };
export const use = (key, defaultValue) => { // --- Renderer ---
if (context && key in context.p) return context.p[key]; const isNode = v => v instanceof Node;
return defaultValue;
export const destroy = (node) => {
if (!node) return;
const ctx = nodeContexts.get(node);
if (ctx) {
ctx.unmount.forEach(fn => fn());
ctx.cleanups.forEach(fn => fn());
nodeContexts.delete(node);
}
node.childNodes?.forEach(destroy);
node.remove();
}; };
export function createContext(defaultValue) {
const key = Symbol('context');
const useContext = () => {
let current = context;
while (current) {
if (key in current.p) {
return current.p[key];
}
current = null;
}
if (defaultValue !== undefined) return defaultValue;
throw new Error(`Context not found: ${String(key)}`);
};
const Provider = ({ value, children }) => {
const prevContext = context;
if (!context) {
context = { m: [], u: [], p: {} };
}
context.p[key] = value;
const result = h('div', { style: 'display: contents' }, children);
context = prevContext;
return result;
};
return { Provider, use: useContext };
}
export function createSharedContext(key, initialValue) {
if (context && !(key in context.p)) {
share(key, initialValue);
}
return {
set: (value) => share(key, value),
get: () => use(key)
};
}
const isFn = (v) => typeof v === 'function';
const isNode = (v) => v instanceof Node;
const append = (parent, child) => { const append = (parent, child) => {
if (child === null) return; if (child == null) return;
if (typeof child === 'function') {
if (isFn(child)) { const marker = document.createTextNode('');
const anchor = document.createTextNode(''); parent.appendChild(marker);
parent.appendChild(anchor);
let nodes = []; let nodes = [];
effect(() => { effect(() => {
effect(() => { const raw = child();
const newNodes = [child()] const next = [raw].flat(Infinity)
.flat(Infinity) .map(n => typeof n === 'function' ? n() : n)
.map((node) => isFn(node) ? node() : node) .filter(n => n != null)
.flat(Infinity) .map(n => isNode(n) ? n : document.createTextNode(String(n)));
.filter((node) => node !== null)
.map((node) => isNode(node) ? node : document.createTextNode(String(node)));
const oldNodes = nodes.filter(node => { const nextSet = new Set(next);
const keep = newNodes.includes(node); nodes.forEach(n => { if (!nextSet.has(n)) destroy(n); });
if (!keep) remove(node); next.forEach((n, i) => {
return keep; if (nodes[i] !== n) marker.parentNode.insertBefore(n, nodes[i] || marker);
});
nodes = next;
}); });
const oldIdxs = new Map(oldNodes.map((node, i) => [node, i]));
for (let i = newNodes.length - 1, p = oldNodes.length - 1; i >= 0; i--) {
const node = newNodes[i];
const ref = newNodes[i + 1] || anchor;
if (!oldIdxs.has(node)) {
anchor.parentNode?.insertBefore(node, ref);
node.$c?.m.forEach(fn => fn());
} else if (oldNodes[p] !== node) {
if (newNodes[i - 1] !== oldNodes[p]) {
anchor.parentNode?.insertBefore(oldNodes[p], node);
oldNodes[oldIdxs.get(node)] = oldNodes[p];
oldNodes[p] = node;
p--;
}
anchor.parentNode?.insertBefore(node, ref);
} else { } else {
p--; parent.appendChild(isNode(child) ? child : document.createTextNode(String(child)));
}
}
nodes = newNodes;
});
}, true);
} else if (isNode(child)) {
parent.appendChild(child);
} else {
parent.appendChild(document.createTextNode(String(child)));
} }
}; };
const remove = (node) => { export const h = (tag, props = {}, ...children) => {
const el = node; if (typeof tag === 'function') {
el.$s?.(); const prevCtx = currentContext;
el.$l?.(() => node.remove()); const context = { mount: [], unmount: [], provide: {}, parent: prevCtx, cleanups: new Set() };
if (!el.$l) node.remove(); currentContext = context;
}; const prevOwner = currentOwner;
currentOwner = context;
const render = (fn, ...data) => { const el = tag(props, { children: children.flat(Infinity) });
let node; if (isNode(el)) nodeContexts.set(el, context);
const stop = effect(() => {
node = fn(...data);
if (isFn(node)) node = node();
}, true);
if (node) node.$s = stop;
return node;
};
export const h = (tag, props, ...children) => { currentContext = prevCtx;
props = props || {}; currentOwner = prevOwner;
children = children.flat(Infinity); queueMicrotask(() => context.mount.forEach(fn => fn()));
if (isFn(tag)) {
const prev = context;
context = { m: [], u: [], p: { ...(prev?.p || {}) } };
let el;
const stop = effect(() => {
el = tag(props, {
children,
emit: (evt, ...args) =>
props[`on${evt[0].toUpperCase()}${evt.slice(1)}`]?.(...args),
});
return () => el.$c.u.forEach(fn => fn());
}, true);
if (isNode(el) || isFn(el)) {
el.$c = context;
el.$s = stop;
}
context = prev;
return el; return el;
} }
if (!tag) return () => children; const el = document.createElement(tag);
let el;
let is_svg = false;
try {
el = document.createElement(tag);
if (el instanceof HTMLUnknownElement) {
is_svg = true;
el = document.createElementNS("http://www.w3.org/2000/svg", tag);
}
} catch {
is_svg = true;
el = document.createElementNS("http://www.w3.org/2000/svg", tag);
}
const booleanAttributes = ["disabled", "checked", "required", "readonly", "selected", "multiple", "autofocus"];
for (const key in props) { for (const key in props) {
const val = props[key];
if (key.startsWith('on')) { if (key.startsWith('on')) {
const eventName = key.slice(2).toLowerCase(); el.addEventListener(key.slice(2).toLowerCase(), val);
el.addEventListener(eventName, props[key]);
} else if (key === "ref") {
if (isFn(props[key])) {
props[key](el);
} else {
props[key].current = el;
} }
} else if (isFn(props[key])) { else if (typeof val === 'function' || (val && val._isSig)) {
effect(() => { effect(() => {
const val = props[key](); const v = typeof val === 'function' ? val() : val.value;
if (key === 'className') { el[key] = (key === 'href' || key === 'src') ? sanitize(v) : v;
el.setAttribute('class', String(val ?? ''));
} else if (booleanAttributes.includes(key)) {
el[key] = !!val;
val ? el.setAttribute(key, '') : el.removeAttribute(key);
} else if (key in el && !is_svg) {
el[key] = val;
} else {
const safeVal = sanitizeAttribute(key, val);
if (safeVal !== null) el.setAttribute(key, safeVal);
}
}); });
} else { } else {
const value = props[key]; el[key] = (key === 'href' || key === 'src') ? sanitize(val) : val;
if (key === 'className') {
el.setAttribute('class', String(value ?? ''));
} else if (booleanAttributes.includes(key)) {
el[key] = !!value;
value ? el.setAttribute(key, '') : el.removeAttribute(key);
} else if (key in el && !is_svg) {
el[key] = value;
} else {
const safeVal = sanitizeAttribute(key, value);
if (safeVal !== null) el.setAttribute(key, safeVal);
}
} }
} }
children.forEach((child) => append(el, child)); children.flat(Infinity).forEach(c => append(el, c));
return el; return el;
}; };
export const If = (cond, renderFn, fallback = null) => { // --- Conditionals & Loops ---
let cached; export const If = (cond, a, b) => () => cond() ? a() : (b ? b() : null);
let current = null;
return () => { export const For = (list, key, render) => {
const show = isFn(cond) ? cond() : cond;
if (show !== current) {
cached = show ? render(renderFn) : (isFn(fallback) ? render(fallback) : fallback);
}
current = show;
return cached;
};
};
export const For = (list, key, renderFn) => {
let cache = new Map(); let cache = new Map();
return () => { return () => {
const next = new Map(); const items = list();
const items = (isFn(list) ? list() : list.value || list); const nextCache = new Map();
const nodes = items.map((item, i) => {
const nodes = items.map((item, index) => { const k = key ? key(item, i) : i;
const idx = isFn(key) ? key(item, index) : key ? item[key] : index; let node = cache.get(k);
let node = cache.get(idx); if (!node) node = render(item, i);
if (!node) { nextCache.set(k, node);
node = render(renderFn, item, index);
}
next.set(idx, node);
return node; return node;
}); });
cache.forEach((n, k) => { if (!nextCache.has(k)) destroy(n); });
cache = next; cache = nextCache;
return nodes; return nodes;
}; };
}; };
export const Transition = ({ enter: e, idle, leave: l }, { children: [c] }) => { // --- Router ---
const decorate = (el) => {
if (!isNode(el)) return el;
const addClass = (c) => c && el.classList.add(...c.split(' '));
const removeClass = (c) => c && el.classList.remove(...c.split(' '));
if (e) {
requestAnimationFrame(() => {
addClass(e[1]);
requestAnimationFrame(() => {
addClass(e[0]);
removeClass(e[1]);
addClass(e[2]);
el.addEventListener('transitionend', () => {
removeClass(e[2]);
removeClass(e[0]);
addClass(idle);
}, { once: true });
});
});
}
if (l) {
el.$l = (done) => {
removeClass(idle);
addClass(l[1]);
requestAnimationFrame(() => {
addClass(l[0]);
removeClass(l[1]);
addClass(l[2]);
el.addEventListener('transitionend', () => {
removeClass(l[2]);
removeClass(l[0]);
done();
}, { once: true });
});
};
}
return el;
};
if (!c) return null;
if (isFn(c)) {
return () => decorate(c());
}
return decorate(c);
};
export const Router = (routes) => { export const Router = (routes) => {
const getPath = () => window.location.hash.slice(1) || "/"; const path = signal(window.location.hash.replace(/^#/, '') || '/');
const path = $(getPath()); window.addEventListener('hashchange', () => path.value = window.location.hash.replace(/^#/, '') || '/');
const params = $({}); let view = null;
const outlet = h('div', { class: 'router-outlet' });
const matchRoute = (path) => {
for (const route of routes) {
const routeParts = route.path.split("/").filter(Boolean);
const pathParts = path.split("/").filter(Boolean);
if (routeParts.length !== pathParts.length) continue;
const matchedParams = {};
let ok = true;
for (let i = 0; i < routeParts.length; i++) {
if (routeParts[i].startsWith(":")) {
matchedParams[routeParts[i].slice(1)] = pathParts[i];
} else if (routeParts[i] !== pathParts[i]) {
ok = false;
break;
}
}
if (ok) return { component: route.component, params: matchedParams };
}
const wildcard = routes.find(r => r.path === "*");
if (wildcard) return { component: wildcard.component, params: {} };
return null;
};
window.addEventListener("hashchange", () => path(getPath()));
const outlet = h("div");
effect(() => { effect(() => {
const matched = matchRoute(path()); const route = routes.find(r => r.path === path.value) || routes.find(r => r.path === '*');
if (!matched) return; if (view) destroy(view);
if (route) {
params(matched.params); view = route.component();
outlet.appendChild(view);
while (outlet.firstChild) outlet.removeChild(outlet.firstChild); }
outlet.appendChild(h(matched.component));
}); });
return outlet;
return {
view: outlet,
to: (p) => { window.location.hash = p; },
back: () => window.history.back(),
params: () => params,
};
}; };
export const mount = (component, target, props) => { // --- Mounting ---
const targetEl = typeof target === "string" ? document.querySelector(target) : target; export const mount = (root, target) => {
if (!targetEl) throw new Error("Target element not found"); const container = typeof target === 'string' ? document.querySelector(target) : target;
const el = h(component, props); const el = typeof root === 'function' ? root() : root;
targetEl.appendChild(el); container.replaceChildren(el);
el.$c?.m.forEach(fn => fn()); return () => destroy(el);
return () => remove(el);
};
export default (target, root, props) => {
const el = h(root, props);
target.appendChild(el);
el.$c?.m.forEach(fn => fn());
return () => remove(el);
}; };
// --- Export API ---
export default { signal, computed, effect, reactive, watch, h, If, For, Router, mount, provide, inject, onMount, onUnmount };
export { h as jsx, h as jsxs, h as Fragment }; export { h as jsx, h as jsxs, h as Fragment };