From 8796b9f94d25d3323389116d469fab55a5794884 Mon Sep 17 00:00:00 2001 From: natxocc Date: Fri, 8 May 2026 14:56:57 +0200 Subject: [PATCH] Create plus --- dist/sigpro.js | 400 ++------------------------- dist/sigpro.min.js | 2 +- dist/{router.js => sigpro.plus.js} | 423 ++++------------------------- dist/sigpro.vite.js | 52 ++++ dist/utils.js | 24 -- docs/router.md | 6 +- docs/sigpro.js | 400 ++------------------------- package.json | 14 +- src/build_umd.js | 7 +- src/router.js | 101 ------- src/sigpro.plus.js | 89 ++++++ src/{vite.js => sigpro.vite.js} | 30 +- src/utils.js | 24 -- 13 files changed, 238 insertions(+), 1334 deletions(-) rename dist/{router.js => sigpro.plus.js} (50%) create mode 100644 dist/sigpro.vite.js delete mode 100644 dist/utils.js delete mode 100644 src/router.js create mode 100644 src/sigpro.plus.js rename src/{vite.js => sigpro.vite.js} (69%) delete mode 100644 src/utils.js diff --git a/dist/sigpro.js b/dist/sigpro.js index a413ecd..528c2e9 100644 --- a/dist/sigpro.js +++ b/dist/sigpro.js @@ -1,42 +1,4 @@ (() => { - var __create = Object.create; - var __getProtoOf = Object.getPrototypeOf; - var __defProp = Object.defineProperty; - var __getOwnPropNames = Object.getOwnPropertyNames; - var __hasOwnProp = Object.prototype.hasOwnProperty; - function __accessProp(key) { - return this[key]; - } - var __toESMCache_node; - var __toESMCache_esm; - var __toESM = (mod, isNodeMode, target) => { - var canCache = mod != null && typeof mod === "object"; - if (canCache) { - var cache = isNodeMode ? __toESMCache_node ??= new WeakMap : __toESMCache_esm ??= new WeakMap; - var cached = cache.get(mod); - if (cached) - return cached; - } - target = mod != null ? __create(__getProtoOf(mod)) : {}; - const to = isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target; - for (let key of __getOwnPropNames(mod)) - if (!__hasOwnProp.call(to, key)) - __defProp(to, key, { - get: __accessProp.bind(mod, key), - enumerable: true - }); - if (canCache) - cache.set(mod, to); - return to; - }; - var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, { - get: (a, b) => (typeof require !== "undefined" ? require : a)[b] - }) : x)(function(x) { - if (typeof require !== "undefined") - return require.apply(this, arguments); - throw Error('Dynamic require of "' + x + '" is not supported'); - }); - // src/sigpro.js var isFunc = (f) => typeof f === "function"; var isObj = (o) => o && typeof o === "object"; @@ -475,336 +437,12 @@ }); } - // src/router.js - var import_node_fs = (() => ({})); - - // node:path - function assertPath(path) { - if (typeof path !== "string") - throw TypeError("Path must be a string. Received " + JSON.stringify(path)); - } - function normalizeStringPosix(path, allowAboveRoot) { - var res = "", lastSegmentLength = 0, lastSlash = -1, dots = 0, code; - for (var i = 0;i <= path.length; ++i) { - if (i < path.length) - code = path.charCodeAt(i); - else if (code === 47) - break; - else - code = 47; - if (code === 47) { - if (lastSlash === i - 1 || dots === 1) - ; - else if (lastSlash !== i - 1 && dots === 2) { - if (res.length < 2 || lastSegmentLength !== 2 || res.charCodeAt(res.length - 1) !== 46 || res.charCodeAt(res.length - 2) !== 46) { - if (res.length > 2) { - var lastSlashIndex = res.lastIndexOf("/"); - if (lastSlashIndex !== res.length - 1) { - if (lastSlashIndex === -1) - res = "", lastSegmentLength = 0; - else - res = res.slice(0, lastSlashIndex), lastSegmentLength = res.length - 1 - res.lastIndexOf("/"); - lastSlash = i, dots = 0; - continue; - } - } else if (res.length === 2 || res.length === 1) { - res = "", lastSegmentLength = 0, lastSlash = i, dots = 0; - continue; - } - } - if (allowAboveRoot) { - if (res.length > 0) - res += "/.."; - else - res = ".."; - lastSegmentLength = 2; - } - } else { - if (res.length > 0) - res += "/" + path.slice(lastSlash + 1, i); - else - res = path.slice(lastSlash + 1, i); - lastSegmentLength = i - lastSlash - 1; - } - lastSlash = i, dots = 0; - } else if (code === 46 && dots !== -1) - ++dots; - else - dots = -1; - } - return res; - } - function _format(sep, pathObject) { - var dir = pathObject.dir || pathObject.root, base = pathObject.base || (pathObject.name || "") + (pathObject.ext || ""); - if (!dir) - return base; - if (dir === pathObject.root) - return dir + base; - return dir + sep + base; - } - function resolve() { - var resolvedPath = "", resolvedAbsolute = false, cwd; - for (var i = arguments.length - 1;i >= -1 && !resolvedAbsolute; i--) { - var path; - if (i >= 0) - path = arguments[i]; - else { - if (cwd === undefined) - cwd = process.cwd(); - path = cwd; - } - if (assertPath(path), path.length === 0) - continue; - resolvedPath = path + "/" + resolvedPath, resolvedAbsolute = path.charCodeAt(0) === 47; - } - if (resolvedPath = normalizeStringPosix(resolvedPath, !resolvedAbsolute), resolvedAbsolute) - if (resolvedPath.length > 0) - return "/" + resolvedPath; - else - return "/"; - else if (resolvedPath.length > 0) - return resolvedPath; - else - return "."; - } - function normalize(path) { - if (assertPath(path), path.length === 0) - return "."; - var isAbsolute = path.charCodeAt(0) === 47, trailingSeparator = path.charCodeAt(path.length - 1) === 47; - if (path = normalizeStringPosix(path, !isAbsolute), path.length === 0 && !isAbsolute) - path = "."; - if (path.length > 0 && trailingSeparator) - path += "/"; - if (isAbsolute) - return "/" + path; - return path; - } - function isAbsolute(path) { - return assertPath(path), path.length > 0 && path.charCodeAt(0) === 47; - } - function join() { - if (arguments.length === 0) - return "."; - var joined; - for (var i = 0;i < arguments.length; ++i) { - var arg = arguments[i]; - if (assertPath(arg), arg.length > 0) - if (joined === undefined) - joined = arg; - else - joined += "/" + arg; - } - if (joined === undefined) - return "."; - return normalize(joined); - } - function relative(from, to) { - if (assertPath(from), assertPath(to), from === to) - return ""; - if (from = resolve(from), to = resolve(to), from === to) - return ""; - var fromStart = 1; - for (;fromStart < from.length; ++fromStart) - if (from.charCodeAt(fromStart) !== 47) - break; - var fromEnd = from.length, fromLen = fromEnd - fromStart, toStart = 1; - for (;toStart < to.length; ++toStart) - if (to.charCodeAt(toStart) !== 47) - break; - var toEnd = to.length, toLen = toEnd - toStart, length = fromLen < toLen ? fromLen : toLen, lastCommonSep = -1, i = 0; - for (;i <= length; ++i) { - if (i === length) { - if (toLen > length) { - if (to.charCodeAt(toStart + i) === 47) - return to.slice(toStart + i + 1); - else if (i === 0) - return to.slice(toStart + i); - } else if (fromLen > length) { - if (from.charCodeAt(fromStart + i) === 47) - lastCommonSep = i; - else if (i === 0) - lastCommonSep = 0; - } - break; - } - var fromCode = from.charCodeAt(fromStart + i), toCode = to.charCodeAt(toStart + i); - if (fromCode !== toCode) - break; - else if (fromCode === 47) - lastCommonSep = i; - } - var out = ""; - for (i = fromStart + lastCommonSep + 1;i <= fromEnd; ++i) - if (i === fromEnd || from.charCodeAt(i) === 47) - if (out.length === 0) - out += ".."; - else - out += "/.."; - if (out.length > 0) - return out + to.slice(toStart + lastCommonSep); - else { - if (toStart += lastCommonSep, to.charCodeAt(toStart) === 47) - ++toStart; - return to.slice(toStart); - } - } - function _makeLong(path) { - return path; - } - function dirname(path) { - if (assertPath(path), path.length === 0) - return "."; - var code = path.charCodeAt(0), hasRoot = code === 47, end = -1, matchedSlash = true; - for (var i = path.length - 1;i >= 1; --i) - if (code = path.charCodeAt(i), code === 47) { - if (!matchedSlash) { - end = i; - break; - } - } else - matchedSlash = false; - if (end === -1) - return hasRoot ? "/" : "."; - if (hasRoot && end === 1) - return "//"; - return path.slice(0, end); - } - function basename(path, ext) { - if (ext !== undefined && typeof ext !== "string") - throw TypeError('"ext" argument must be a string'); - assertPath(path); - var start = 0, end = -1, matchedSlash = true, i; - if (ext !== undefined && ext.length > 0 && ext.length <= path.length) { - if (ext.length === path.length && ext === path) - return ""; - var extIdx = ext.length - 1, firstNonSlashEnd = -1; - for (i = path.length - 1;i >= 0; --i) { - var code = path.charCodeAt(i); - if (code === 47) { - if (!matchedSlash) { - start = i + 1; - break; - } - } else { - if (firstNonSlashEnd === -1) - matchedSlash = false, firstNonSlashEnd = i + 1; - if (extIdx >= 0) - if (code === ext.charCodeAt(extIdx)) { - if (--extIdx === -1) - end = i; - } else - extIdx = -1, end = firstNonSlashEnd; - } - } - if (start === end) - end = firstNonSlashEnd; - else if (end === -1) - end = path.length; - return path.slice(start, end); - } else { - for (i = path.length - 1;i >= 0; --i) - if (path.charCodeAt(i) === 47) { - if (!matchedSlash) { - start = i + 1; - break; - } - } else if (end === -1) - matchedSlash = false, end = i + 1; - if (end === -1) - return ""; - return path.slice(start, end); - } - } - function extname(path) { - assertPath(path); - var startDot = -1, startPart = 0, end = -1, matchedSlash = true, preDotState = 0; - for (var i = path.length - 1;i >= 0; --i) { - var code = path.charCodeAt(i); - if (code === 47) { - if (!matchedSlash) { - startPart = i + 1; - break; - } - continue; - } - if (end === -1) - matchedSlash = false, end = i + 1; - if (code === 46) { - if (startDot === -1) - startDot = i; - else if (preDotState !== 1) - preDotState = 1; - } else if (startDot !== -1) - preDotState = -1; - } - if (startDot === -1 || end === -1 || preDotState === 0 || preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) - return ""; - return path.slice(startDot, end); - } - function format(pathObject) { - if (pathObject === null || typeof pathObject !== "object") - throw TypeError('The "pathObject" argument must be of type Object. Received type ' + typeof pathObject); - return _format("/", pathObject); - } - function parse(path) { - assertPath(path); - var ret = { root: "", dir: "", base: "", ext: "", name: "" }; - if (path.length === 0) - return ret; - var code = path.charCodeAt(0), isAbsolute2 = code === 47, start; - if (isAbsolute2) - ret.root = "/", start = 1; - else - start = 0; - var startDot = -1, startPart = 0, end = -1, matchedSlash = true, i = path.length - 1, preDotState = 0; - for (;i >= start; --i) { - if (code = path.charCodeAt(i), code === 47) { - if (!matchedSlash) { - startPart = i + 1; - break; - } - continue; - } - if (end === -1) - matchedSlash = false, end = i + 1; - if (code === 46) { - if (startDot === -1) - startDot = i; - else if (preDotState !== 1) - preDotState = 1; - } else if (startDot !== -1) - preDotState = -1; - } - if (startDot === -1 || end === -1 || preDotState === 0 || preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) { - if (end !== -1) - if (startPart === 0 && isAbsolute2) - ret.base = ret.name = path.slice(1, end); - else - ret.base = ret.name = path.slice(startPart, end); - } else { - if (startPart === 0 && isAbsolute2) - ret.name = path.slice(1, startDot), ret.base = path.slice(1, end); - else - ret.name = path.slice(startPart, startDot), ret.base = path.slice(startPart, end); - ret.ext = path.slice(startDot, end); - } - if (startPart > 0) - ret.dir = path.slice(0, startPart - 1); - else if (isAbsolute2) - ret.dir = "/"; - return ret; - } - var sep = "/"; - var delimiter = ":"; - var posix = ((p) => (p.posix = p, p))({ resolve, normalize, isAbsolute, join, relative, _makeLong, dirname, basename, extname, format, parse, sep, delimiter, win32: null, posix: null }); - - // src/router.js + // src/sigpro.plus.js var 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 hook = h("div", { class: "router-hook" }); let currentView = null; watch([path], () => { @@ -826,37 +464,31 @@ hook.replaceChildren(currentView.container); } }); + hook.destroy = () => { + window.removeEventListener("hashchange", handler); + currentView?.destroy(); + }; return hook; }; router.params = $({}); router.to = (p) => window.location.hash = p.replace(/^#?\/?/, "#/"); router.back = () => window.history.back(); router.path = () => window.location.hash.replace(/^#/, "") || "/"; - - // src/utils.js - var db = async (url, data = {}, loading = null) => { - if (loading) - loading(true); - try { - const res = await fetch(url, { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify(data), - credentials: "include" - }); - if (!res.ok) { - const errorText = await res.text(); - throw new Error(`Error ${res.status}: ${errorText}`); - } - return await res.json(); - } finally { - if (loading) - loading(false); + var currentLocale = $("en"); + var translations = {}; + var addLang = (obj) => { + for (const locale of Object.keys(obj)) { + if (!translations[locale]) + translations[locale] = {}; + Object.assign(translations[locale], obj[locale]); } }; + var t = (key) => { + return () => translations[currentLocale()]?.[key] ?? key; + }; // src/build_umd.js if (typeof window !== "undefined") { - Object.assign(window, { $, watch, h, Fragment, when, each, router, mount, batch, onUnmount, isArr, isFunc, isObj, db }); + Object.assign(window, { $, watch, h, Fragment, when, each, router, addLang, t, mount, batch, isArr, isFunc, isObj }); } })(); diff --git a/dist/sigpro.min.js b/dist/sigpro.min.js index 6c70538..782bca0 100644 --- a/dist/sigpro.min.js +++ b/dist/sigpro.min.js @@ -1 +1 @@ -(()=>{var Y=Object.create;var{getPrototypeOf:Z,defineProperty:D,getOwnPropertyNames:H}=Object;var ee=Object.prototype.hasOwnProperty;function te(e){return this[e]}var ne,re,se=(e,n,t)=>{var r=e!=null&&typeof e==="object";if(r){var s=n?ne??=new WeakMap:re??=new WeakMap,o=s.get(e);if(o)return o}t=e!=null?Y(Z(e)):{};let i=n||!e||!e.__esModule?D(t,"default",{value:e,enumerable:!0}):t;for(let c of H(e))if(!ee.call(i,c))D(i,c,{get:te.bind(e,c),enumerable:!0});if(r)s.set(e,i);return i};var ie=((e)=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(n,t)=>(typeof require<"u"?require:n)[t]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var _=(e)=>typeof e==="function",L=(e)=>e&&typeof e==="object",w=Array.isArray,y=typeof document<"u"?document:null,J=(e)=>e?._isRuntime?e.container:e instanceof Node?e:y.createTextNode(e==null?"":String(e)),h=null,g=null,k=!1,R=0,j=new Set,G=new WeakMap,oe="http://www.w3.org/2000/svg",P="http://www.w3.org/1999/xlink",ce=new Set("svg,path,circle,rect,line,polyline,polygon,g,defs,text,textPath,tspan,use,symbol,image,marker,ellipse".split(",")),A=(e)=>{if(!e||e._disposed)return;e._disposed=!0;let n=[e];while(n.length){let t=n.pop();if(t._cleanups)t._cleanups.forEach((r)=>r()),t._cleanups.clear();if(t._children)t._children.forEach((r)=>n.push(r)),t._children.clear();if(t._deps)t._deps.forEach((r)=>r.delete(t)),t._deps.clear()}},S=(e)=>{if(g)(g._cleanups||=new Set).add(e)},le=(e)=>{let n=h;h=null;try{return e()}finally{h=n}},T=(e,n=!1)=>{let t=()=>{if(t._disposed)return;if(t._deps)t._deps.forEach((o)=>o.delete(t));if(t._cleanups)t._cleanups.forEach((o)=>o()),t._cleanups.clear();let r=h,s=g;h=g=t;try{return t._result=e()}catch(o){console.error("[SigPro]",o)}finally{h=r,g=s}};if(t._deps=t._cleanups=t._children=null,t._disposed=!1,t._isComputed=n,t._depth=h?h._depth+1:0,t._mounts=[],t._parent=g,g)(g._children||=new Set).add(t);return t},W=()=>{if(k)return;k=!0;let e=Array.from(j).sort((n,t)=>n._depth-t._depth);j.clear();for(let n of e)if(!n._disposed)n();k=!1},q=(e)=>{R++;try{return e()}finally{if(R--,R===0&&j.size>0&&!k)W()}},p=(e,n=!1)=>{if(!n&&h&&!h._disposed)e.add(h),(h._deps||=new Set).add(e);else if(n&&e.size>0){let t=!1;for(let r of e){if(r===h||r._disposed)continue;if(r._isComputed){if(r._dirty=!0,r._subs)p(r._subs,!0)}else j.add(r),t=!0}if(t&&!k&&R===0)queueMicrotask(W)}},O=(e,n=null)=>{let t=new Set;if(_(e)){let r,s=()=>{if(s._dirty){let o=h;h=s;try{let i=e();if(!Object.is(r,i))r=i,p(t,!0)}finally{h=o}s._dirty=!1}return p(t),r};return s._isComputed=!0,s._subs=t,s._dirty=!0,s._deps=null,s._disposed=!1,s}if(n)try{e=JSON.parse(localStorage.getItem(n))??e}catch(r){}return(...r)=>{if(r.length){let s=_(r[0])?r[0](e):r[0];if(!Object.is(e,s)){if(e=s,n)localStorage.setItem(n,JSON.stringify(e));p(t,!0)}}return p(t),e}},N=(e,n)=>{if(n===void 0){let r=T(e);return r(),()=>A(r)}let t=T(()=>{let r=w(e)?e.map((s)=>s()):e();le(()=>n(r))});return t(),()=>A(t)},$=(e)=>{if(!e)return;if(e._cleanups)e._cleanups.forEach((n)=>n()),e._cleanups.clear();if(e._ownerEffect)A(e._ownerEffect);if(e.childNodes)e.childNodes.forEach((n)=>$(n))},fe=/^\s*(javascript|data|vbscript):/i,ae=new Set(["src","href","formaction","action","background","code","archive"]),ue=(e)=>ae.has(e)||e.startsWith("on"),U=(e,n)=>{if(n==null||n===!1)return null;if(ue(e)){let t=String(n);if(fe.test(t))return"#"}return n},C=(e,n={},t=[])=>{if(n instanceof Node||w(n)||!L(n))t=n,n={};if(_(e)){let i=T(()=>{let f=e(n,{children:t,emit:(u,...m)=>n[`on${u[0].toUpperCase()}${u.slice(1)}`]?.(...m)});return i._result=f,f});i();let c=i._result;if(c==null)return null;let l=c instanceof Node||w(c)&&c.every((f)=>f instanceof Node)?c:y.createTextNode(String(c)),a=(f)=>{if(L(f)&&!f._isRuntime)f._mounts=i._mounts||[],f._cleanups=i._cleanups||new Set,f._ownerEffect=i};return w(l)?l.forEach(a):a(l),l}let r=ce.has(e),s=r?y.createElementNS(oe,e):y.createElement(e);s._cleanups=new Set;for(let i of Object.keys(n)){let c=n[i];if(i==="ref"){_(c)?c(s):c.current=s;continue}if(r&&i.startsWith("xlink:")){let l=U(i.slice(6),c);l==null?s.removeAttributeNS(P,i.slice(6)):s.setAttributeNS(P,i.slice(6),l);continue}if(i.startsWith("on")){let l=i.slice(2).toLowerCase();s.addEventListener(l,c);let a=()=>s.removeEventListener(l,c);s._cleanups.add(a),S(a)}else if(_(c)){let l=T(()=>{let a=U(i,c());if(i==="class")s.className=a||"";else if(a==null)s.removeAttribute(i);else if(i==="style"&&typeof a==="string")s.setAttribute("style",a);else if(i in s&&!r)s[i]=a;else s.setAttribute(i,a===!0?"":a)});if(l(),s._cleanups.add(()=>A(l)),S(()=>A(l)),/^(INPUT|TEXTAREA|SELECT)$/.test(s.tagName)&&(i==="value"||i==="checked")){let a=i==="checked"?"change":"input";s.addEventListener(a,(f)=>c(f.target[i]))}}else{let l=U(i,c);if(l!=null)if(i==="style"&&typeof l==="string")s.setAttribute("style",l);else if(i in s&&!r)s[i]=l;else s.setAttribute(i,l===!0?"":l)}}let o=(i)=>{if(w(i))return i.forEach(o);if(_(i)){let c=y.createTextNode("");s.appendChild(c);let l=[],a=T(()=>{let f=i(),u=(w(f)?f:[f]).map(J);l.forEach((d)=>{if(d._isRuntime)d.destroy();else $(d);if(d.parentNode)d.remove()});let m=c;for(let d=u.length-1;d>=0;d--){let v=u[d];if(v.parentNode!==m.parentNode)m.parentNode?.insertBefore(v,m);if(v._mounts)v._mounts.forEach((I)=>I());m=v}l=u});a(),s._cleanups.add(()=>A(a)),S(()=>A(a))}else{let c=J(i);if(s.appendChild(c),c._mounts)c._mounts.forEach((l)=>l())}};return o(t),s},x=(e)=>{let n=new Set,t=g,r=h,s=y.createElement("div");s.style.display="contents",s.setAttribute("role","presentation"),g={_cleanups:n},h=null;let o=(i)=>{if(!i)return;if(i._isRuntime)n.add(i.destroy),s.appendChild(i.container);else if(w(i))i.forEach(o);else s.appendChild(i instanceof Node?i:y.createTextNode(String(i==null?"":i)))};try{o(e({onCleanup:(i)=>n.add(i)}))}finally{g=t,h=r}return{_isRuntime:!0,container:s,destroy:()=>{n.forEach((i)=>i()),$(s),s.remove()}}},M=(e,n,t=null)=>{let r=y.createTextNode(""),s=C("div",{style:"display:contents"},[r]),o=null;return N(()=>!!(_(e)?e():e),(i)=>{if(o)o.destroy(),o=null;let c=i?n:t;if(c)o=x(()=>_(c)?c():c),s.insertBefore(o.container,r)}),S(()=>o?.destroy()),s},F=(e,n,t)=>{let r=y.createTextNode(""),s=C("div",{style:"display:contents"},[r]),o=new Map;return N(()=>(_(e)?e():e)||[],(i)=>{let c=new Map,l=[],a=i||[];for(let u=0;un(m,u));else o.delete(d);c.set(d,v),l.push(v)}o.forEach((u)=>u.destroy());let f=r;for(let u=l.length-1;u>=0;u--){let d=l[u].container;if(d.nextSibling!==f)s.insertBefore(d,f);f=d}o=c}),s},Q=(e)=>e.children,X=(e,n)=>{let t=typeof n==="string"?y.querySelector(n):n;if(!t)return;if(G.has(t))G.get(t).destroy();let r=x(_(e)?e:()=>e);return t.replaceChildren(r.container),G.set(t,r),r};if(typeof window<"u")"a abbr article aside audio b blockquote br button canvas caption cite code col colgroup datalist dd del details dfn dialog div dl dt em embed fieldset figcaption figure footer form h1 h2 h3 h4 h5 h6 header hr i iframe img input ins kbd label legend li main mark meter nav object ol optgroup option output p picture pre progress section select slot small source span strong sub summary sup svg table tbody td template textarea tfoot th thead time tr u ul video".split(" ").forEach((e)=>{window[e]=(n,t)=>C(e,n,t)});var Ee=(()=>({}));function b(e){if(typeof e!=="string")throw TypeError("Path must be a string. Received "+JSON.stringify(e))}function K(e,n){var t="",r=0,s=-1,o=0,i;for(var c=0;c<=e.length;++c){if(c2){var l=t.lastIndexOf("/");if(l!==t.length-1){if(l===-1)t="",r=0;else t=t.slice(0,l),r=t.length-1-t.lastIndexOf("/");s=c,o=0;continue}}else if(t.length===2||t.length===1){t="",r=0,s=c,o=0;continue}}if(n){if(t.length>0)t+="/..";else t="..";r=2}}else{if(t.length>0)t+="/"+e.slice(s+1,c);else t=e.slice(s+1,c);r=c-s-1}s=c,o=0}else if(i===46&&o!==-1)++o;else o=-1}return t}function de(e,n){var t=n.dir||n.root,r=n.base||(n.name||"")+(n.ext||"");if(!t)return r;if(t===n.root)return t+r;return t+e+r}function z(){var e="",n=!1,t;for(var r=arguments.length-1;r>=-1&&!n;r--){var s;if(r>=0)s=arguments[r];else{if(t===void 0)t=process.cwd();s=t}if(b(s),s.length===0)continue;e=s+"/"+e,n=s.charCodeAt(0)===47}if(e=K(e,!n),n)if(e.length>0)return"/"+e;else return"/";else if(e.length>0)return e;else return"."}function V(e){if(b(e),e.length===0)return".";var n=e.charCodeAt(0)===47,t=e.charCodeAt(e.length-1)===47;if(e=K(e,!n),e.length===0&&!n)e=".";if(e.length>0&&t)e+="/";if(n)return"/"+e;return e}function he(e){return b(e),e.length>0&&e.charCodeAt(0)===47}function me(){if(arguments.length===0)return".";var e;for(var n=0;n0)if(e===void 0)e=t;else e+="/"+t}if(e===void 0)return".";return V(e)}function _e(e,n){if(b(e),b(n),e===n)return"";if(e=z(e),n=z(n),e===n)return"";var t=1;for(;tl){if(n.charCodeAt(o+f)===47)return n.slice(o+f+1);else if(f===0)return n.slice(o+f)}else if(s>l){if(e.charCodeAt(t+f)===47)a=f;else if(f===0)a=0}break}var u=e.charCodeAt(t+f),m=n.charCodeAt(o+f);if(u!==m)break;else if(u===47)a=f}var d="";for(f=t+a+1;f<=r;++f)if(f===r||e.charCodeAt(f)===47)if(d.length===0)d+="..";else d+="/..";if(d.length>0)return d+n.slice(o+a);else{if(o+=a,n.charCodeAt(o)===47)++o;return n.slice(o)}}function ge(e){return e}function ve(e){if(b(e),e.length===0)return".";var n=e.charCodeAt(0),t=n===47,r=-1,s=!0;for(var o=e.length-1;o>=1;--o)if(n=e.charCodeAt(o),n===47){if(!s){r=o;break}}else s=!1;if(r===-1)return t?"/":".";if(t&&r===1)return"//";return e.slice(0,r)}function ye(e,n){if(n!==void 0&&typeof n!=="string")throw TypeError('"ext" argument must be a string');b(e);var t=0,r=-1,s=!0,o;if(n!==void 0&&n.length>0&&n.length<=e.length){if(n.length===e.length&&n===e)return"";var i=n.length-1,c=-1;for(o=e.length-1;o>=0;--o){var l=e.charCodeAt(o);if(l===47){if(!s){t=o+1;break}}else{if(c===-1)s=!1,c=o+1;if(i>=0)if(l===n.charCodeAt(i)){if(--i===-1)r=o}else i=-1,r=c}}if(t===r)r=c;else if(r===-1)r=e.length;return e.slice(t,r)}else{for(o=e.length-1;o>=0;--o)if(e.charCodeAt(o)===47){if(!s){t=o+1;break}}else if(r===-1)s=!1,r=o+1;if(r===-1)return"";return e.slice(t,r)}}function be(e){b(e);var n=-1,t=0,r=-1,s=!0,o=0;for(var i=e.length-1;i>=0;--i){var c=e.charCodeAt(i);if(c===47){if(!s){t=i+1;break}continue}if(r===-1)s=!1,r=i+1;if(c===46){if(n===-1)n=i;else if(o!==1)o=1}else if(n!==-1)o=-1}if(n===-1||r===-1||o===0||o===1&&n===r-1&&n===t+1)return"";return e.slice(n,r)}function we(e){if(e===null||typeof e!=="object")throw TypeError('The "pathObject" argument must be of type Object. Received type '+typeof e);return de("/",e)}function Se(e){b(e);var n={root:"",dir:"",base:"",ext:"",name:""};if(e.length===0)return n;var t=e.charCodeAt(0),r=t===47,s;if(r)n.root="/",s=1;else s=0;var o=-1,i=0,c=-1,l=!0,a=e.length-1,f=0;for(;a>=s;--a){if(t=e.charCodeAt(a),t===47){if(!l){i=a+1;break}continue}if(c===-1)l=!1,c=a+1;if(t===46){if(o===-1)o=a;else if(f!==1)f=1}else if(o!==-1)f=-1}if(o===-1||c===-1||f===0||f===1&&o===c-1&&o===i+1){if(c!==-1)if(i===0&&r)n.base=n.name=e.slice(1,c);else n.base=n.name=e.slice(i,c)}else{if(i===0&&r)n.name=e.slice(1,o),n.base=e.slice(1,c);else n.name=e.slice(i,o),n.base=e.slice(i,c);n.ext=e.slice(o,c)}if(i>0)n.dir=e.slice(0,i-1);else if(r)n.dir="/";return n}var Ae="/",Ce=":",ke=((e)=>(e.posix=e,e))({resolve:z,normalize:V,isAbsolute:he,join:me,relative:_e,_makeLong:ge,dirname:ve,basename:ye,extname:be,format:we,parse:Se,sep:Ae,delimiter:Ce,win32:null,posix:null});var E=(e)=>{let n=()=>window.location.hash.slice(1)||"/",t=O(n()),r=()=>t(n());window.addEventListener("hashchange",r),S(()=>window.removeEventListener("hashchange",r));let s=C("div",{class:"router-hook"}),o=null;return N([t],()=>{let i=t(),c=e.find((l)=>{let a=l.path.split("/").filter(Boolean),f=i.split("/").filter(Boolean);return a.length===f.length&&a.every((u,m)=>u[0]===":"||u===f[m])})||e.find((l)=>l.path==="*");if(c){o?.destroy();let l={};c.path.split("/").filter(Boolean).forEach((a,f)=>{if(a[0]===":")l[a.slice(1)]=i.split("/").filter(Boolean)[f]}),E.params(l),o=x(()=>_(c.component)?c.component(l):c.component),s.replaceChildren(o.container)}}),s};E.params=O({});E.to=(e)=>window.location.hash=e.replace(/^#?\/?/,"#/");E.back=()=>window.history.back();E.path=()=>window.location.hash.replace(/^#/,"")||"/";var B=async(e,n={},t=null)=>{if(t)t(!0);try{let r=await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n),credentials:"include"});if(!r.ok){let s=await r.text();throw Error(`Error ${r.status}: ${s}`)}return await r.json()}finally{if(t)t(!1)}};if(typeof window<"u")Object.assign(window,{$:O,watch:N,h:C,Fragment:Q,when:M,each:F,router:E,mount:X,batch:q,onUnmount:S,isArr:w,isFunc:_,isObj:L,db:B});})(); +(()=>{var h=(e)=>typeof e==="function",L=(e)=>e&&typeof e==="object",E=Array.isArray,y=typeof document<"u"?document:null,V=(e)=>e?._isRuntime?e.container:e instanceof Node?e:y.createTextNode(e==null?"":String(e)),u=null,m=null,O=!1,k=0,R=new Set,U=new WeakMap,Q="http://www.w3.org/2000/svg",D="http://www.w3.org/1999/xlink",X=new Set("svg,path,circle,rect,line,polyline,polygon,g,defs,text,textPath,tspan,use,symbol,image,marker,ellipse".split(",")),b=(e)=>{if(!e||e._disposed)return;e._disposed=!0;let n=[e];while(n.length){let t=n.pop();if(t._cleanups)t._cleanups.forEach((r)=>r()),t._cleanups.clear();if(t._children)t._children.forEach((r)=>n.push(r)),t._children.clear();if(t._deps)t._deps.forEach((r)=>r.delete(t)),t._deps.clear()}},C=(e)=>{if(m)(m._cleanups||=new Set).add(e)},H=(e)=>{let n=u;u=null;try{return e()}finally{u=n}},A=(e,n=!1)=>{let t=()=>{if(t._disposed)return;if(t._deps)t._deps.forEach((a)=>a.delete(t));if(t._cleanups)t._cleanups.forEach((a)=>a()),t._cleanups.clear();let r=u,o=m;u=m=t;try{return t._result=e()}catch(a){console.error("[SigPro]",a)}finally{u=r,m=o}};if(t._deps=t._cleanups=t._children=null,t._disposed=!1,t._isComputed=n,t._depth=u?u._depth+1:0,t._mounts=[],t._parent=m,m)(m._children||=new Set).add(t);return t},G=()=>{if(O)return;O=!0;let e=Array.from(R).sort((n,t)=>n._depth-t._depth);R.clear();for(let n of e)if(!n._disposed)n();O=!1},I=(e)=>{k++;try{return e()}finally{if(k--,k===0&&R.size>0&&!O)G()}},x=(e,n=!1)=>{if(!n&&u&&!u._disposed)e.add(u),(u._deps||=new Set).add(e);else if(n&&e.size>0){let t=!1;for(let r of e){if(r===u||r._disposed)continue;if(r._isComputed){if(r._dirty=!0,r._subs)x(r._subs,!0)}else R.add(r),t=!0}if(t&&!O&&k===0)queueMicrotask(G)}},v=(e,n=null)=>{let t=new Set;if(h(e)){let r,o=()=>{if(o._dirty){let a=u;u=o;try{let s=e();if(!Object.is(r,s))r=s,x(t,!0)}finally{u=a}o._dirty=!1}return x(t),r};return o._isComputed=!0,o._subs=t,o._dirty=!0,o._deps=null,o._disposed=!1,o}if(n)try{e=JSON.parse(localStorage.getItem(n))??e}catch(r){}return(...r)=>{if(r.length){let o=h(r[0])?r[0](e):r[0];if(!Object.is(e,o)){if(e=o,n)localStorage.setItem(n,JSON.stringify(e));x(t,!0)}}return x(t),e}},N=(e,n)=>{if(n===void 0){let r=A(e);return r(),()=>b(r)}let t=A(()=>{let r=E(e)?e.map((o)=>o()):e();H(()=>n(r))});return t(),()=>b(t)},B=(e)=>{if(!e)return;if(e._cleanups)e._cleanups.forEach((n)=>n()),e._cleanups.clear();if(e._ownerEffect)b(e._ownerEffect);if(e.childNodes)e.childNodes.forEach((n)=>B(n))},K=/^\s*(javascript|data|vbscript):/i,Y=new Set(["src","href","formaction","action","background","code","archive"]),Z=(e)=>Y.has(e)||e.startsWith("on"),$=(e,n)=>{if(n==null||n===!1)return null;if(Z(e)){let t=String(n);if(K.test(t))return"#"}return n},g=(e,n={},t=[])=>{if(n instanceof Node||E(n)||!L(n))t=n,n={};if(h(e)){let s=A(()=>{let f=e(n,{children:t,emit:(d,..._)=>n[`on${d[0].toUpperCase()}${d.slice(1)}`]?.(..._)});return s._result=f,f});s();let c=s._result;if(c==null)return null;let i=c instanceof Node||E(c)&&c.every((f)=>f instanceof Node)?c:y.createTextNode(String(c)),l=(f)=>{if(L(f)&&!f._isRuntime)f._mounts=s._mounts||[],f._cleanups=s._cleanups||new Set,f._ownerEffect=s};return E(i)?i.forEach(l):l(i),i}let r=X.has(e),o=r?y.createElementNS(Q,e):y.createElement(e);o._cleanups=new Set;for(let s of Object.keys(n)){let c=n[s];if(s==="ref"){h(c)?c(o):c.current=o;continue}if(r&&s.startsWith("xlink:")){let i=$(s.slice(6),c);i==null?o.removeAttributeNS(D,s.slice(6)):o.setAttributeNS(D,s.slice(6),i);continue}if(s.startsWith("on")){let i=s.slice(2).toLowerCase();o.addEventListener(i,c);let l=()=>o.removeEventListener(i,c);o._cleanups.add(l),C(l)}else if(h(c)){let i=A(()=>{let l=$(s,c());if(s==="class")o.className=l||"";else if(l==null)o.removeAttribute(s);else if(s==="style"&&typeof l==="string")o.setAttribute("style",l);else if(s in o&&!r)o[s]=l;else o.setAttribute(s,l===!0?"":l)});if(i(),o._cleanups.add(()=>b(i)),C(()=>b(i)),/^(INPUT|TEXTAREA|SELECT)$/.test(o.tagName)&&(s==="value"||s==="checked")){let l=s==="checked"?"change":"input";o.addEventListener(l,(f)=>c(f.target[s]))}}else{let i=$(s,c);if(i!=null)if(s==="style"&&typeof i==="string")o.setAttribute("style",i);else if(s in o&&!r)o[s]=i;else o.setAttribute(s,i===!0?"":i)}}let a=(s)=>{if(E(s))return s.forEach(a);if(h(s)){let c=y.createTextNode("");o.appendChild(c);let i=[],l=A(()=>{let f=s(),d=(E(f)?f:[f]).map(V);i.forEach((p)=>{if(p._isRuntime)p.destroy();else B(p);if(p.parentNode)p.remove()});let _=c;for(let p=d.length-1;p>=0;p--){let w=d[p];if(w.parentNode!==_.parentNode)_.parentNode?.insertBefore(w,_);if(w._mounts)w._mounts.forEach((z)=>z());_=w}i=d});l(),o._cleanups.add(()=>b(l)),C(()=>b(l))}else{let c=V(s);if(o.appendChild(c),c._mounts)c._mounts.forEach((i)=>i())}};return a(t),o},T=(e)=>{let n=new Set,t=m,r=u,o=y.createElement("div");o.style.display="contents",o.setAttribute("role","presentation"),m={_cleanups:n},u=null;let a=(s)=>{if(!s)return;if(s._isRuntime)n.add(s.destroy),o.appendChild(s.container);else if(E(s))s.forEach(a);else o.appendChild(s instanceof Node?s:y.createTextNode(String(s==null?"":s)))};try{a(e({onCleanup:(s)=>n.add(s)}))}finally{m=t,u=r}return{_isRuntime:!0,container:o,destroy:()=>{n.forEach((s)=>s()),B(o),o.remove()}}},F=(e,n,t=null)=>{let r=y.createTextNode(""),o=g("div",{style:"display:contents"},[r]),a=null;return N(()=>!!(h(e)?e():e),(s)=>{if(a)a.destroy(),a=null;let c=s?n:t;if(c)a=T(()=>h(c)?c():c),o.insertBefore(a.container,r)}),C(()=>a?.destroy()),o},M=(e,n,t)=>{let r=y.createTextNode(""),o=g("div",{style:"display:contents"},[r]),a=new Map;return N(()=>(h(e)?e():e)||[],(s)=>{let c=new Map,i=[],l=s||[];for(let d=0;dn(_,d));else a.delete(p);c.set(p,w),i.push(w)}a.forEach((d)=>d.destroy());let f=r;for(let d=i.length-1;d>=0;d--){let p=i[d].container;if(p.nextSibling!==f)o.insertBefore(p,f);f=p}a=c}),o},P=(e)=>e.children,W=(e,n)=>{let t=typeof n==="string"?y.querySelector(n):n;if(!t)return;if(U.has(t))U.get(t).destroy();let r=T(h(e)?e:()=>e);return t.replaceChildren(r.container),U.set(t,r),r};if(typeof window<"u")"a abbr article aside audio b blockquote br button canvas caption cite code col colgroup datalist dd del details dfn dialog div dl dt em embed fieldset figcaption figure footer form h1 h2 h3 h4 h5 h6 header hr i iframe img input ins kbd label legend li main mark meter nav object ol optgroup option output p picture pre progress section select slot small source span strong sub summary sup svg table tbody td template textarea tfoot th thead time tr u ul video".split(" ").forEach((e)=>{window[e]=(n,t)=>g(e,n,t)});var S=(e)=>{let n=()=>window.location.hash.slice(1)||"/",t=v(n()),r=()=>t(n());window.addEventListener("hashchange",r);let o=g("div",{class:"router-hook"}),a=null;return N([t],()=>{let s=t(),c=e.find((i)=>{let l=i.path.split("/").filter(Boolean),f=s.split("/").filter(Boolean);return l.length===f.length&&l.every((d,_)=>d[0]===":"||d===f[_])})||e.find((i)=>i.path==="*");if(c){a?.destroy();let i={};c.path.split("/").filter(Boolean).forEach((l,f)=>{if(l[0]===":")i[l.slice(1)]=s.split("/").filter(Boolean)[f]}),S.params(i),a=T(()=>h(c.component)?c.component(i):c.component),o.replaceChildren(a.container)}}),o.destroy=()=>{window.removeEventListener("hashchange",r),a?.destroy()},o};S.params=v({});S.to=(e)=>window.location.hash=e.replace(/^#?\/?/,"#/");S.back=()=>window.history.back();S.path=()=>window.location.hash.replace(/^#/,"")||"/";var ee=v("en"),j={},q=(e)=>{for(let n of Object.keys(e)){if(!j[n])j[n]={};Object.assign(j[n],e[n])}};var J=(e)=>{return()=>j[ee()]?.[e]??e};if(typeof window<"u")Object.assign(window,{$:v,watch:N,h:g,Fragment:P,when:F,each:M,router:S,addLang:q,t:J,mount:W,batch:I,isArr:E,isFunc:h,isObj:L});})(); diff --git a/dist/router.js b/dist/sigpro.plus.js similarity index 50% rename from dist/router.js rename to dist/sigpro.plus.js index 00e381f..7c3c9b8 100644 --- a/dist/router.js +++ b/dist/sigpro.plus.js @@ -364,337 +364,12 @@ if (typeof window !== "undefined") { }); } -// src/router.js -var { default: fs} = (() => ({})); - -// node:path -function assertPath(path) { - if (typeof path !== "string") - throw TypeError("Path must be a string. Received " + JSON.stringify(path)); -} -function normalizeStringPosix(path, allowAboveRoot) { - var res = "", lastSegmentLength = 0, lastSlash = -1, dots = 0, code; - for (var i = 0;i <= path.length; ++i) { - if (i < path.length) - code = path.charCodeAt(i); - else if (code === 47) - break; - else - code = 47; - if (code === 47) { - if (lastSlash === i - 1 || dots === 1) - ; - else if (lastSlash !== i - 1 && dots === 2) { - if (res.length < 2 || lastSegmentLength !== 2 || res.charCodeAt(res.length - 1) !== 46 || res.charCodeAt(res.length - 2) !== 46) { - if (res.length > 2) { - var lastSlashIndex = res.lastIndexOf("/"); - if (lastSlashIndex !== res.length - 1) { - if (lastSlashIndex === -1) - res = "", lastSegmentLength = 0; - else - res = res.slice(0, lastSlashIndex), lastSegmentLength = res.length - 1 - res.lastIndexOf("/"); - lastSlash = i, dots = 0; - continue; - } - } else if (res.length === 2 || res.length === 1) { - res = "", lastSegmentLength = 0, lastSlash = i, dots = 0; - continue; - } - } - if (allowAboveRoot) { - if (res.length > 0) - res += "/.."; - else - res = ".."; - lastSegmentLength = 2; - } - } else { - if (res.length > 0) - res += "/" + path.slice(lastSlash + 1, i); - else - res = path.slice(lastSlash + 1, i); - lastSegmentLength = i - lastSlash - 1; - } - lastSlash = i, dots = 0; - } else if (code === 46 && dots !== -1) - ++dots; - else - dots = -1; - } - return res; -} -function _format(sep, pathObject) { - var dir = pathObject.dir || pathObject.root, base = pathObject.base || (pathObject.name || "") + (pathObject.ext || ""); - if (!dir) - return base; - if (dir === pathObject.root) - return dir + base; - return dir + sep + base; -} -function resolve() { - var resolvedPath = "", resolvedAbsolute = false, cwd; - for (var i = arguments.length - 1;i >= -1 && !resolvedAbsolute; i--) { - var path; - if (i >= 0) - path = arguments[i]; - else { - if (cwd === undefined) - cwd = process.cwd(); - path = cwd; - } - if (assertPath(path), path.length === 0) - continue; - resolvedPath = path + "/" + resolvedPath, resolvedAbsolute = path.charCodeAt(0) === 47; - } - if (resolvedPath = normalizeStringPosix(resolvedPath, !resolvedAbsolute), resolvedAbsolute) - if (resolvedPath.length > 0) - return "/" + resolvedPath; - else - return "/"; - else if (resolvedPath.length > 0) - return resolvedPath; - else - return "."; -} -function normalize(path) { - if (assertPath(path), path.length === 0) - return "."; - var isAbsolute = path.charCodeAt(0) === 47, trailingSeparator = path.charCodeAt(path.length - 1) === 47; - if (path = normalizeStringPosix(path, !isAbsolute), path.length === 0 && !isAbsolute) - path = "."; - if (path.length > 0 && trailingSeparator) - path += "/"; - if (isAbsolute) - return "/" + path; - return path; -} -function isAbsolute(path) { - return assertPath(path), path.length > 0 && path.charCodeAt(0) === 47; -} -function join() { - if (arguments.length === 0) - return "."; - var joined; - for (var i = 0;i < arguments.length; ++i) { - var arg = arguments[i]; - if (assertPath(arg), arg.length > 0) - if (joined === undefined) - joined = arg; - else - joined += "/" + arg; - } - if (joined === undefined) - return "."; - return normalize(joined); -} -function relative(from, to) { - if (assertPath(from), assertPath(to), from === to) - return ""; - if (from = resolve(from), to = resolve(to), from === to) - return ""; - var fromStart = 1; - for (;fromStart < from.length; ++fromStart) - if (from.charCodeAt(fromStart) !== 47) - break; - var fromEnd = from.length, fromLen = fromEnd - fromStart, toStart = 1; - for (;toStart < to.length; ++toStart) - if (to.charCodeAt(toStart) !== 47) - break; - var toEnd = to.length, toLen = toEnd - toStart, length = fromLen < toLen ? fromLen : toLen, lastCommonSep = -1, i = 0; - for (;i <= length; ++i) { - if (i === length) { - if (toLen > length) { - if (to.charCodeAt(toStart + i) === 47) - return to.slice(toStart + i + 1); - else if (i === 0) - return to.slice(toStart + i); - } else if (fromLen > length) { - if (from.charCodeAt(fromStart + i) === 47) - lastCommonSep = i; - else if (i === 0) - lastCommonSep = 0; - } - break; - } - var fromCode = from.charCodeAt(fromStart + i), toCode = to.charCodeAt(toStart + i); - if (fromCode !== toCode) - break; - else if (fromCode === 47) - lastCommonSep = i; - } - var out = ""; - for (i = fromStart + lastCommonSep + 1;i <= fromEnd; ++i) - if (i === fromEnd || from.charCodeAt(i) === 47) - if (out.length === 0) - out += ".."; - else - out += "/.."; - if (out.length > 0) - return out + to.slice(toStart + lastCommonSep); - else { - if (toStart += lastCommonSep, to.charCodeAt(toStart) === 47) - ++toStart; - return to.slice(toStart); - } -} -function _makeLong(path) { - return path; -} -function dirname(path) { - if (assertPath(path), path.length === 0) - return "."; - var code = path.charCodeAt(0), hasRoot = code === 47, end = -1, matchedSlash = true; - for (var i = path.length - 1;i >= 1; --i) - if (code = path.charCodeAt(i), code === 47) { - if (!matchedSlash) { - end = i; - break; - } - } else - matchedSlash = false; - if (end === -1) - return hasRoot ? "/" : "."; - if (hasRoot && end === 1) - return "//"; - return path.slice(0, end); -} -function basename(path, ext) { - if (ext !== undefined && typeof ext !== "string") - throw TypeError('"ext" argument must be a string'); - assertPath(path); - var start = 0, end = -1, matchedSlash = true, i; - if (ext !== undefined && ext.length > 0 && ext.length <= path.length) { - if (ext.length === path.length && ext === path) - return ""; - var extIdx = ext.length - 1, firstNonSlashEnd = -1; - for (i = path.length - 1;i >= 0; --i) { - var code = path.charCodeAt(i); - if (code === 47) { - if (!matchedSlash) { - start = i + 1; - break; - } - } else { - if (firstNonSlashEnd === -1) - matchedSlash = false, firstNonSlashEnd = i + 1; - if (extIdx >= 0) - if (code === ext.charCodeAt(extIdx)) { - if (--extIdx === -1) - end = i; - } else - extIdx = -1, end = firstNonSlashEnd; - } - } - if (start === end) - end = firstNonSlashEnd; - else if (end === -1) - end = path.length; - return path.slice(start, end); - } else { - for (i = path.length - 1;i >= 0; --i) - if (path.charCodeAt(i) === 47) { - if (!matchedSlash) { - start = i + 1; - break; - } - } else if (end === -1) - matchedSlash = false, end = i + 1; - if (end === -1) - return ""; - return path.slice(start, end); - } -} -function extname(path) { - assertPath(path); - var startDot = -1, startPart = 0, end = -1, matchedSlash = true, preDotState = 0; - for (var i = path.length - 1;i >= 0; --i) { - var code = path.charCodeAt(i); - if (code === 47) { - if (!matchedSlash) { - startPart = i + 1; - break; - } - continue; - } - if (end === -1) - matchedSlash = false, end = i + 1; - if (code === 46) { - if (startDot === -1) - startDot = i; - else if (preDotState !== 1) - preDotState = 1; - } else if (startDot !== -1) - preDotState = -1; - } - if (startDot === -1 || end === -1 || preDotState === 0 || preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) - return ""; - return path.slice(startDot, end); -} -function format(pathObject) { - if (pathObject === null || typeof pathObject !== "object") - throw TypeError('The "pathObject" argument must be of type Object. Received type ' + typeof pathObject); - return _format("/", pathObject); -} -function parse(path) { - assertPath(path); - var ret = { root: "", dir: "", base: "", ext: "", name: "" }; - if (path.length === 0) - return ret; - var code = path.charCodeAt(0), isAbsolute2 = code === 47, start; - if (isAbsolute2) - ret.root = "/", start = 1; - else - start = 0; - var startDot = -1, startPart = 0, end = -1, matchedSlash = true, i = path.length - 1, preDotState = 0; - for (;i >= start; --i) { - if (code = path.charCodeAt(i), code === 47) { - if (!matchedSlash) { - startPart = i + 1; - break; - } - continue; - } - if (end === -1) - matchedSlash = false, end = i + 1; - if (code === 46) { - if (startDot === -1) - startDot = i; - else if (preDotState !== 1) - preDotState = 1; - } else if (startDot !== -1) - preDotState = -1; - } - if (startDot === -1 || end === -1 || preDotState === 0 || preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) { - if (end !== -1) - if (startPart === 0 && isAbsolute2) - ret.base = ret.name = path.slice(1, end); - else - ret.base = ret.name = path.slice(startPart, end); - } else { - if (startPart === 0 && isAbsolute2) - ret.name = path.slice(1, startDot), ret.base = path.slice(1, end); - else - ret.name = path.slice(startPart, startDot), ret.base = path.slice(startPart, end); - ret.ext = path.slice(startDot, end); - } - if (startPart > 0) - ret.dir = path.slice(0, startPart - 1); - else if (isAbsolute2) - ret.dir = "/"; - return ret; -} -var sep = "/"; -var delimiter = ":"; -var posix = ((p) => (p.posix = p, p))({ resolve, normalize, isAbsolute, join, relative, _makeLong, dirname, basename, extname, format, parse, sep, delimiter, win32: null, posix: null }); -var path_default = posix; - -// src/router.js +// src/sigpro.plus.js var 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 hook = h("div", { class: "router-hook" }); let currentView = null; watch([path], () => { @@ -716,61 +391,57 @@ var router = (routes) => { hook.replaceChildren(currentView.container); } }); + hook.destroy = () => { + window.removeEventListener("hashchange", handler); + currentView?.destroy(); + }; return hook; }; router.params = $({}); router.to = (p) => window.location.hash = p.replace(/^#?\/?/, "#/"); router.back = () => window.history.back(); router.path = () => window.location.hash.replace(/^#/, "") || "/"; -function sigproRouter() { - const virtualModuleId = "virtual:sigpro-routes"; - const resolvedVirtualModuleId = "\x00" + virtualModuleId; - const getFiles = (dir) => { - if (!fs.existsSync(dir)) - return []; - return fs.readdirSync(dir, { recursive: true }).filter((file) => /\.(js|jsx)$/.test(file) && !path_default.basename(file).startsWith("_")).map((file) => path_default.resolve(dir, file)); - }; - const pathToUrl = (pagesDir, filePath) => { - let relative2 = path_default.relative(pagesDir, filePath).replace(/\\/g, "/").replace(/\.(js|jsx)$/, "").replace(/\/index$/, "").replace(/^index$/, ""); - return ("/" + relative2).replace(/\/+/g, "/").replace(/\[\.\.\.([^\]]+)\]/g, "*").replace(/\[([^\]]+)\]/g, ":$1").replace(/\/$/, "") || "/"; - }; - return { - name: "sigpro-router", - resolveId(id) { - if (id === virtualModuleId) - return resolvedVirtualModuleId; - }, - load(id) { - if (id !== resolvedVirtualModuleId) - return; - const root = process.cwd(); - const pagesDir = path_default.resolve(root, "src/pages"); - const files = getFiles(pagesDir).sort((a, b) => { - const urlA = pathToUrl(pagesDir, a); - const urlB = pathToUrl(pagesDir, b); - if (urlA.includes(":") && !urlB.includes(":")) - return 1; - if (!urlA.includes(":") && urlB.includes(":")) - return -1; - return urlB.length - urlA.length; - }); - let routeEntries = ""; - files.forEach((fullPath) => { - const urlPath = pathToUrl(pagesDir, fullPath); - const relativeImport = "./" + path_default.relative(root, fullPath).replace(/\\/g, "/"); - routeEntries += ` { path: '${urlPath}', component: () => import('/${relativeImport}') }, -`; - }); - if (!routeEntries.includes("path: '*'")) { - routeEntries += ` { path: '*', component: () => ({ default: () => document.createTextNode('404 - Not Found') }) }, -`; - } - return `export const routes = [ -${routeEntries}];`; +var db = async (url, data = {}, loading = null) => { + if (loading) + loading(true); + try { + const res = await fetch(url, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(data), + credentials: "include" + }); + if (!res.ok) { + const errorText = await res.text(); + throw new Error(`Error ${res.status}: ${errorText}`); } - }; -} -export { - sigproRouter, - router + return await res.json(); + } finally { + if (loading) + loading(false); + } +}; +var currentLocale = $("en"); +var translations = {}; +var addLang = (obj) => { + for (const locale of Object.keys(obj)) { + if (!translations[locale]) + translations[locale] = {}; + Object.assign(translations[locale], obj[locale]); + } +}; +var setLocale = (locale) => { + if (locale && translations[locale]) { + currentLocale(locale); + } +}; +var t = (key) => { + return () => translations[currentLocale()]?.[key] ?? key; +}; +export { + t, + setLocale, + router, + db, + addLang }; diff --git a/dist/sigpro.vite.js b/dist/sigpro.vite.js new file mode 100644 index 0000000..9cf0cef --- /dev/null +++ b/dist/sigpro.vite.js @@ -0,0 +1,52 @@ +// src/sigpro.vite.js +function sigproRouter() { + const virtualModuleId = "virtual:sigpro-routes"; + const resolvedVirtualModuleId = "\x00" + virtualModuleId; + const getFiles = (dir) => { + if (!fs.existsSync(dir)) + return []; + return fs.readdirSync(dir, { recursive: true }).filter((file) => /\.(js|jsx)$/.test(file) && !path.basename(file).startsWith("_")).map((file) => path.resolve(dir, file)); + }; + const pathToUrl = (pagesDir, filePath) => { + let relative = path.relative(pagesDir, filePath).replace(/\\/g, "/").replace(/\.(js|jsx)$/, "").replace(/\/index$/, "").replace(/^index$/, ""); + return ("/" + relative).replace(/\/+/g, "/").replace(/\[\.\.\.([^\]]+)\]/g, "*").replace(/\[([^\]]+)\]/g, ":$1").replace(/\/$/, "") || "/"; + }; + return { + name: "sigpro-router", + resolveId(id) { + if (id === virtualModuleId) + return resolvedVirtualModuleId; + }, + load(id) { + if (id !== resolvedVirtualModuleId) + return; + const root = process.cwd(); + const pagesDir = path.resolve(root, "src/pages"); + const files = getFiles(pagesDir).sort((a, b) => { + const urlA = pathToUrl(pagesDir, a); + const urlB = pathToUrl(pagesDir, b); + if (urlA.includes(":") && !urlB.includes(":")) + return 1; + if (!urlA.includes(":") && urlB.includes(":")) + return -1; + return urlB.length - urlA.length; + }); + let routeEntries = ""; + files.forEach((fullPath) => { + const urlPath = pathToUrl(pagesDir, fullPath); + const relativeImport = "./" + path.relative(root, fullPath).replace(/\\/g, "/"); + routeEntries += ` { path: '${urlPath}', component: () => import('/${relativeImport}') }, +`; + }); + if (!routeEntries.includes("path: '*'")) { + routeEntries += ` { path: '*', component: () => ({ default: () => document.createTextNode('404 - Not Found') }) }, +`; + } + return `export const routes = [ +${routeEntries}];`; + } + }; +} +export { + sigproRouter +}; diff --git a/dist/utils.js b/dist/utils.js deleted file mode 100644 index 2dd25d3..0000000 --- a/dist/utils.js +++ /dev/null @@ -1,24 +0,0 @@ -// src/utils.js -var db = async (url, data = {}, loading = null) => { - if (loading) - loading(true); - try { - const res = await fetch(url, { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify(data), - credentials: "include" - }); - if (!res.ok) { - const errorText = await res.text(); - throw new Error(`Error ${res.status}: ${errorText}`); - } - return await res.json(); - } finally { - if (loading) - loading(false); - } -}; -export { - db -}; diff --git a/docs/router.md b/docs/router.md index 2653975..862bc64 100644 --- a/docs/router.md +++ b/docs/router.md @@ -17,7 +17,7 @@ router(routes: Route[]): HTMLElement **Returns:** A `div` element (with class `"router-hook"`) that acts as the router outlet. The router automatically destroys the previous view and mounts the matched component when the hash changes. -> **Availability:** `router` and its helper methods (`router.to`, `router.back`, `router.path`, `router.params`) are exported from the SigPro module. In **ESM** you must import them (`import { router } from 'sigpro/router'`). In the **IIFE** classic script, they are automatically available on `window`. The examples below assume the functions are already in scope. +> **Availability:** `router` and its helper methods (`router.to`, `router.back`, `router.path`, `router.params`) are exported from the SigPro module. In **ESM** you must import them (`import { router } from 'sigpro/plus'`). In the **IIFE** classic script, they are automatically available on `window`. The examples below assume the functions are already in scope. --- @@ -223,7 +223,7 @@ Add the plugin to your `vite.config.js`. It works out of the box with zero confi ```javascript // vite.config.js import { defineConfig } from 'vite'; -import { sigproRouter } from 'sigpro/router'; +import { sigproRouter } from 'sigpro/vite'; export default defineConfig({ plugins: [sigproRouter()] @@ -243,7 +243,7 @@ Thanks to **SigPro's synchronous initialization**, you no longer need to wrap yo ```javascript // src/main.js import { mount } from 'sigpro'; -import { router } from 'sigpro/router'; +import { router } from 'sigpro/plus'; import { routes } from 'virtual:sigpro-routes'; // The Core already has Router ready diff --git a/docs/sigpro.js b/docs/sigpro.js index a413ecd..528c2e9 100644 --- a/docs/sigpro.js +++ b/docs/sigpro.js @@ -1,42 +1,4 @@ (() => { - var __create = Object.create; - var __getProtoOf = Object.getPrototypeOf; - var __defProp = Object.defineProperty; - var __getOwnPropNames = Object.getOwnPropertyNames; - var __hasOwnProp = Object.prototype.hasOwnProperty; - function __accessProp(key) { - return this[key]; - } - var __toESMCache_node; - var __toESMCache_esm; - var __toESM = (mod, isNodeMode, target) => { - var canCache = mod != null && typeof mod === "object"; - if (canCache) { - var cache = isNodeMode ? __toESMCache_node ??= new WeakMap : __toESMCache_esm ??= new WeakMap; - var cached = cache.get(mod); - if (cached) - return cached; - } - target = mod != null ? __create(__getProtoOf(mod)) : {}; - const to = isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target; - for (let key of __getOwnPropNames(mod)) - if (!__hasOwnProp.call(to, key)) - __defProp(to, key, { - get: __accessProp.bind(mod, key), - enumerable: true - }); - if (canCache) - cache.set(mod, to); - return to; - }; - var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, { - get: (a, b) => (typeof require !== "undefined" ? require : a)[b] - }) : x)(function(x) { - if (typeof require !== "undefined") - return require.apply(this, arguments); - throw Error('Dynamic require of "' + x + '" is not supported'); - }); - // src/sigpro.js var isFunc = (f) => typeof f === "function"; var isObj = (o) => o && typeof o === "object"; @@ -475,336 +437,12 @@ }); } - // src/router.js - var import_node_fs = (() => ({})); - - // node:path - function assertPath(path) { - if (typeof path !== "string") - throw TypeError("Path must be a string. Received " + JSON.stringify(path)); - } - function normalizeStringPosix(path, allowAboveRoot) { - var res = "", lastSegmentLength = 0, lastSlash = -1, dots = 0, code; - for (var i = 0;i <= path.length; ++i) { - if (i < path.length) - code = path.charCodeAt(i); - else if (code === 47) - break; - else - code = 47; - if (code === 47) { - if (lastSlash === i - 1 || dots === 1) - ; - else if (lastSlash !== i - 1 && dots === 2) { - if (res.length < 2 || lastSegmentLength !== 2 || res.charCodeAt(res.length - 1) !== 46 || res.charCodeAt(res.length - 2) !== 46) { - if (res.length > 2) { - var lastSlashIndex = res.lastIndexOf("/"); - if (lastSlashIndex !== res.length - 1) { - if (lastSlashIndex === -1) - res = "", lastSegmentLength = 0; - else - res = res.slice(0, lastSlashIndex), lastSegmentLength = res.length - 1 - res.lastIndexOf("/"); - lastSlash = i, dots = 0; - continue; - } - } else if (res.length === 2 || res.length === 1) { - res = "", lastSegmentLength = 0, lastSlash = i, dots = 0; - continue; - } - } - if (allowAboveRoot) { - if (res.length > 0) - res += "/.."; - else - res = ".."; - lastSegmentLength = 2; - } - } else { - if (res.length > 0) - res += "/" + path.slice(lastSlash + 1, i); - else - res = path.slice(lastSlash + 1, i); - lastSegmentLength = i - lastSlash - 1; - } - lastSlash = i, dots = 0; - } else if (code === 46 && dots !== -1) - ++dots; - else - dots = -1; - } - return res; - } - function _format(sep, pathObject) { - var dir = pathObject.dir || pathObject.root, base = pathObject.base || (pathObject.name || "") + (pathObject.ext || ""); - if (!dir) - return base; - if (dir === pathObject.root) - return dir + base; - return dir + sep + base; - } - function resolve() { - var resolvedPath = "", resolvedAbsolute = false, cwd; - for (var i = arguments.length - 1;i >= -1 && !resolvedAbsolute; i--) { - var path; - if (i >= 0) - path = arguments[i]; - else { - if (cwd === undefined) - cwd = process.cwd(); - path = cwd; - } - if (assertPath(path), path.length === 0) - continue; - resolvedPath = path + "/" + resolvedPath, resolvedAbsolute = path.charCodeAt(0) === 47; - } - if (resolvedPath = normalizeStringPosix(resolvedPath, !resolvedAbsolute), resolvedAbsolute) - if (resolvedPath.length > 0) - return "/" + resolvedPath; - else - return "/"; - else if (resolvedPath.length > 0) - return resolvedPath; - else - return "."; - } - function normalize(path) { - if (assertPath(path), path.length === 0) - return "."; - var isAbsolute = path.charCodeAt(0) === 47, trailingSeparator = path.charCodeAt(path.length - 1) === 47; - if (path = normalizeStringPosix(path, !isAbsolute), path.length === 0 && !isAbsolute) - path = "."; - if (path.length > 0 && trailingSeparator) - path += "/"; - if (isAbsolute) - return "/" + path; - return path; - } - function isAbsolute(path) { - return assertPath(path), path.length > 0 && path.charCodeAt(0) === 47; - } - function join() { - if (arguments.length === 0) - return "."; - var joined; - for (var i = 0;i < arguments.length; ++i) { - var arg = arguments[i]; - if (assertPath(arg), arg.length > 0) - if (joined === undefined) - joined = arg; - else - joined += "/" + arg; - } - if (joined === undefined) - return "."; - return normalize(joined); - } - function relative(from, to) { - if (assertPath(from), assertPath(to), from === to) - return ""; - if (from = resolve(from), to = resolve(to), from === to) - return ""; - var fromStart = 1; - for (;fromStart < from.length; ++fromStart) - if (from.charCodeAt(fromStart) !== 47) - break; - var fromEnd = from.length, fromLen = fromEnd - fromStart, toStart = 1; - for (;toStart < to.length; ++toStart) - if (to.charCodeAt(toStart) !== 47) - break; - var toEnd = to.length, toLen = toEnd - toStart, length = fromLen < toLen ? fromLen : toLen, lastCommonSep = -1, i = 0; - for (;i <= length; ++i) { - if (i === length) { - if (toLen > length) { - if (to.charCodeAt(toStart + i) === 47) - return to.slice(toStart + i + 1); - else if (i === 0) - return to.slice(toStart + i); - } else if (fromLen > length) { - if (from.charCodeAt(fromStart + i) === 47) - lastCommonSep = i; - else if (i === 0) - lastCommonSep = 0; - } - break; - } - var fromCode = from.charCodeAt(fromStart + i), toCode = to.charCodeAt(toStart + i); - if (fromCode !== toCode) - break; - else if (fromCode === 47) - lastCommonSep = i; - } - var out = ""; - for (i = fromStart + lastCommonSep + 1;i <= fromEnd; ++i) - if (i === fromEnd || from.charCodeAt(i) === 47) - if (out.length === 0) - out += ".."; - else - out += "/.."; - if (out.length > 0) - return out + to.slice(toStart + lastCommonSep); - else { - if (toStart += lastCommonSep, to.charCodeAt(toStart) === 47) - ++toStart; - return to.slice(toStart); - } - } - function _makeLong(path) { - return path; - } - function dirname(path) { - if (assertPath(path), path.length === 0) - return "."; - var code = path.charCodeAt(0), hasRoot = code === 47, end = -1, matchedSlash = true; - for (var i = path.length - 1;i >= 1; --i) - if (code = path.charCodeAt(i), code === 47) { - if (!matchedSlash) { - end = i; - break; - } - } else - matchedSlash = false; - if (end === -1) - return hasRoot ? "/" : "."; - if (hasRoot && end === 1) - return "//"; - return path.slice(0, end); - } - function basename(path, ext) { - if (ext !== undefined && typeof ext !== "string") - throw TypeError('"ext" argument must be a string'); - assertPath(path); - var start = 0, end = -1, matchedSlash = true, i; - if (ext !== undefined && ext.length > 0 && ext.length <= path.length) { - if (ext.length === path.length && ext === path) - return ""; - var extIdx = ext.length - 1, firstNonSlashEnd = -1; - for (i = path.length - 1;i >= 0; --i) { - var code = path.charCodeAt(i); - if (code === 47) { - if (!matchedSlash) { - start = i + 1; - break; - } - } else { - if (firstNonSlashEnd === -1) - matchedSlash = false, firstNonSlashEnd = i + 1; - if (extIdx >= 0) - if (code === ext.charCodeAt(extIdx)) { - if (--extIdx === -1) - end = i; - } else - extIdx = -1, end = firstNonSlashEnd; - } - } - if (start === end) - end = firstNonSlashEnd; - else if (end === -1) - end = path.length; - return path.slice(start, end); - } else { - for (i = path.length - 1;i >= 0; --i) - if (path.charCodeAt(i) === 47) { - if (!matchedSlash) { - start = i + 1; - break; - } - } else if (end === -1) - matchedSlash = false, end = i + 1; - if (end === -1) - return ""; - return path.slice(start, end); - } - } - function extname(path) { - assertPath(path); - var startDot = -1, startPart = 0, end = -1, matchedSlash = true, preDotState = 0; - for (var i = path.length - 1;i >= 0; --i) { - var code = path.charCodeAt(i); - if (code === 47) { - if (!matchedSlash) { - startPart = i + 1; - break; - } - continue; - } - if (end === -1) - matchedSlash = false, end = i + 1; - if (code === 46) { - if (startDot === -1) - startDot = i; - else if (preDotState !== 1) - preDotState = 1; - } else if (startDot !== -1) - preDotState = -1; - } - if (startDot === -1 || end === -1 || preDotState === 0 || preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) - return ""; - return path.slice(startDot, end); - } - function format(pathObject) { - if (pathObject === null || typeof pathObject !== "object") - throw TypeError('The "pathObject" argument must be of type Object. Received type ' + typeof pathObject); - return _format("/", pathObject); - } - function parse(path) { - assertPath(path); - var ret = { root: "", dir: "", base: "", ext: "", name: "" }; - if (path.length === 0) - return ret; - var code = path.charCodeAt(0), isAbsolute2 = code === 47, start; - if (isAbsolute2) - ret.root = "/", start = 1; - else - start = 0; - var startDot = -1, startPart = 0, end = -1, matchedSlash = true, i = path.length - 1, preDotState = 0; - for (;i >= start; --i) { - if (code = path.charCodeAt(i), code === 47) { - if (!matchedSlash) { - startPart = i + 1; - break; - } - continue; - } - if (end === -1) - matchedSlash = false, end = i + 1; - if (code === 46) { - if (startDot === -1) - startDot = i; - else if (preDotState !== 1) - preDotState = 1; - } else if (startDot !== -1) - preDotState = -1; - } - if (startDot === -1 || end === -1 || preDotState === 0 || preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) { - if (end !== -1) - if (startPart === 0 && isAbsolute2) - ret.base = ret.name = path.slice(1, end); - else - ret.base = ret.name = path.slice(startPart, end); - } else { - if (startPart === 0 && isAbsolute2) - ret.name = path.slice(1, startDot), ret.base = path.slice(1, end); - else - ret.name = path.slice(startPart, startDot), ret.base = path.slice(startPart, end); - ret.ext = path.slice(startDot, end); - } - if (startPart > 0) - ret.dir = path.slice(0, startPart - 1); - else if (isAbsolute2) - ret.dir = "/"; - return ret; - } - var sep = "/"; - var delimiter = ":"; - var posix = ((p) => (p.posix = p, p))({ resolve, normalize, isAbsolute, join, relative, _makeLong, dirname, basename, extname, format, parse, sep, delimiter, win32: null, posix: null }); - - // src/router.js + // src/sigpro.plus.js var 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 hook = h("div", { class: "router-hook" }); let currentView = null; watch([path], () => { @@ -826,37 +464,31 @@ hook.replaceChildren(currentView.container); } }); + hook.destroy = () => { + window.removeEventListener("hashchange", handler); + currentView?.destroy(); + }; return hook; }; router.params = $({}); router.to = (p) => window.location.hash = p.replace(/^#?\/?/, "#/"); router.back = () => window.history.back(); router.path = () => window.location.hash.replace(/^#/, "") || "/"; - - // src/utils.js - var db = async (url, data = {}, loading = null) => { - if (loading) - loading(true); - try { - const res = await fetch(url, { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify(data), - credentials: "include" - }); - if (!res.ok) { - const errorText = await res.text(); - throw new Error(`Error ${res.status}: ${errorText}`); - } - return await res.json(); - } finally { - if (loading) - loading(false); + var currentLocale = $("en"); + var translations = {}; + var addLang = (obj) => { + for (const locale of Object.keys(obj)) { + if (!translations[locale]) + translations[locale] = {}; + Object.assign(translations[locale], obj[locale]); } }; + var t = (key) => { + return () => translations[currentLocale()]?.[key] ?? key; + }; // src/build_umd.js if (typeof window !== "undefined") { - Object.assign(window, { $, watch, h, Fragment, when, each, router, mount, batch, onUnmount, isArr, isFunc, isObj, db }); + Object.assign(window, { $, watch, h, Fragment, when, each, router, addLang, t, mount, batch, isArr, isFunc, isObj }); } })(); diff --git a/package.json b/package.json index c13be03..721084c 100644 --- a/package.json +++ b/package.json @@ -19,11 +19,11 @@ "script": "./dist/sigpro.min.js", "types": "./sigpro.d.ts" }, - "./router": { - "import": "./dist/router.js" + "./plus": { + "import": "./dist/sigpro.plus.js" }, - "./utils": { - "import": "./dist/utils.js" + "./vite": { + "import": "./dist/sigpro.vite.js" } }, "files": [ @@ -49,10 +49,10 @@ "build:iife:min": "bun build ./src/build_umd.js --bundle --outfile=./dist/sigpro.min.js --format=iife --global-name=sp --minify", "build:esm": "bun build ./src/sigpro.js --bundle --outfile=./dist/sigpro.esm.js --format=esm", "build:esm:min": "bun build ./src/sigpro.js --bundle --outfile=./dist/sigpro.esm.min.js --format=esm --minify", - "build:router": "bun build ./src/router.js --bundle --outfile=./dist/router.js --format=esm --external:fs --external:path", - "build:utils": "bun build ./src/utils.js --bundle --outfile=./dist/utils.js --format=esm --external:fs --external:path", + "build:plus": "bun build ./src/sigpro.plus.js --bundle --outfile=./dist/sigpro.plus.js --format=esm", + "build:vite": "bun build ./src/sigpro.vite.js --bundle --outfile=./dist/sigpro.vite.js --format=esm --external:fs --external:path", "build:copy": "cp ./dist/sigpro.js ./docs/sigpro.js", - "build": "bun run build:iife && bun run build:iife:min && bun run build:esm && bun run build:esm:min && bun run build:router && bun run build:utils && bun run build:copy", + "build": "bun run build:iife && bun run build:iife:min && bun run build:esm && bun run build:esm:min && bun run build:plus && bun run build:vite && bun run build:copy", "docs": "bun x serve docs" }, "keywords": [ diff --git a/src/build_umd.js b/src/build_umd.js index 9e5c87c..e8f95a4 100644 --- a/src/build_umd.js +++ b/src/build_umd.js @@ -1,7 +1,6 @@ -import { $, watch, batch, h, Fragment, mount, when, each, onUnmount, isArr, isFunc, isObj } from "./sigpro.js" -import { router } from "./router.js" -import { db } from "./utils.js" +import { $, watch, batch, h, Fragment, mount, when, each, isArr, isFunc, isObj } from "./sigpro.js" +import { router, addLang, t } from "./sigpro.plus.js" if (typeof window !== "undefined") { - Object.assign(window, { $, watch, h, Fragment, when, each, router, mount, batch, onUnmount, isArr, isFunc, isObj, db }) + Object.assign(window, { $, watch, h, Fragment, when, each, router, addLang, t, mount, batch, isArr, isFunc, isObj }) } \ No newline at end of file diff --git a/src/router.js b/src/router.js deleted file mode 100644 index 1767ee1..0000000 --- a/src/router.js +++ /dev/null @@ -1,101 +0,0 @@ -// src/router.js -import { h, watch, $, render, onUnmount, isFunc } from './sigpro.js'; -import fs from 'node:fs'; -import path from 'node:path'; - -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 hook = h("div", { class: "router-hook" }); - let currentView = null; - - 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]); - }) || 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 = render(() => isFunc(route.component) ? route.component(params) : route.component); - hook.replaceChildren(currentView.container); - } - }); - return hook; -}; - -router.params = $({}); -router.to = p => window.location.hash = p.replace(/^#?\/?/, "#/"); -router.back = () => window.history.back(); -router.path = () => window.location.hash.replace(/^#/, "") || "/"; - -function sigproRouter() { - const virtualModuleId = 'virtual:sigpro-routes'; - const resolvedVirtualModuleId = '\0' + virtualModuleId; - - const getFiles = (dir) => { - if (!fs.existsSync(dir)) return []; - return fs.readdirSync(dir, { recursive: true }) - .filter(file => /\.(js|jsx)$/.test(file) && !path.basename(file).startsWith('_')) - .map(file => path.resolve(dir, file)); - }; - - const pathToUrl = (pagesDir, filePath) => { - let relative = path.relative(pagesDir, filePath) - .replace(/\\/g, '/') - .replace(/\.(js|jsx)$/, '') - .replace(/\/index$/, '') - .replace(/^index$/, ''); - return ('/' + relative) - .replace(/\/+/g, '/') - .replace(/\[\.\.\.([^\]]+)\]/g, '*') - .replace(/\[([^\]]+)\]/g, ':$1') - .replace(/\/$/, '') || '/'; - }; - - return { - name: 'sigpro-router', - resolveId(id) { - if (id === virtualModuleId) return resolvedVirtualModuleId; - }, - load(id) { - if (id !== resolvedVirtualModuleId) return; - const root = process.cwd(); - const pagesDir = path.resolve(root, 'src/pages'); - const files = getFiles(pagesDir).sort((a, b) => { - const urlA = pathToUrl(pagesDir, a); - const urlB = pathToUrl(pagesDir, b); - if (urlA.includes(':') && !urlB.includes(':')) return 1; - if (!urlA.includes(':') && urlB.includes(':')) return -1; - return urlB.length - urlA.length; - }); - - let routeEntries = ''; - files.forEach((fullPath) => { - const urlPath = pathToUrl(pagesDir, fullPath); - const relativeImport = './' + path.relative(root, fullPath).replace(/\\/g, '/'); - routeEntries += ` { path: '${urlPath}', component: () => import('/${relativeImport}') },\n`; - }); - if (!routeEntries.includes("path: '*'")) { - routeEntries += ` { path: '*', component: () => ({ default: () => document.createTextNode('404 - Not Found') }) },\n`; - } - return `export const routes = [\n${routeEntries}];`; - } - }; -} - -// ============================================================ -// Exportación final (lo que se consume desde 'sigpro/router') -// ============================================================ -export { router, sigproRouter }; \ No newline at end of file diff --git a/src/sigpro.plus.js b/src/sigpro.plus.js new file mode 100644 index 0000000..2980f8a --- /dev/null +++ b/src/sigpro.plus.js @@ -0,0 +1,89 @@ +// plus +import { h, watch, $, render, isFunc } from './sigpro'; + +// router +export const router = routes => { + const getHash = () => window.location.hash.slice(1) || "/"; + const path = $(getHash()); + const handler = () => path(getHash()); + window.addEventListener("hashchange", handler); + + const hook = h("div", { class: "router-hook" }); + let currentView = null; + + 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]); + }) || 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 = render(() => isFunc(route.component) ? route.component(params) : route.component); + hook.replaceChildren(currentView.container); + } + }); + + hook.destroy = () => { + window.removeEventListener("hashchange", handler); + currentView?.destroy(); + }; + + return hook; +}; + +router.params = $({}); +router.to = p => window.location.hash = p.replace(/^#?\/?/, "#/"); +router.back = () => window.history.back(); +router.path = () => window.location.hash.replace(/^#/, "") || "/"; + +// db +export const db = async (url, data = {}, loading = null) => { + if (loading) loading(true); + try { + const res = await fetch(url, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(data), + credentials: 'include' + }); + if (!res.ok) { + const errorText = await res.text(); + throw new Error(`Error ${res.status}: ${errorText}`); + } + return await res.json(); + } finally { + if (loading) loading(false); + } +}; + +const currentLocale = $('en'); + +const translations = {}; + +// addLang +export const addLang = (obj) => { + for (const locale of Object.keys(obj)) { + if (!translations[locale]) translations[locale] = {}; + Object.assign(translations[locale], obj[locale]); + } +}; + +// setLocale +export const setLocale = (locale) => { + if (locale && translations[locale]) { + currentLocale(locale); + } +}; + +// t +export const t = (key) => { + return () => translations[currentLocale()]?.[key] ?? key; +}; \ No newline at end of file diff --git a/src/vite.js b/src/sigpro.vite.js similarity index 69% rename from src/vite.js rename to src/sigpro.vite.js index c092574..71cd040 100644 --- a/src/vite.js +++ b/src/sigpro.vite.js @@ -1,15 +1,8 @@ -/** - * SigPro Vite Plugin - File-based Routing - * @module sigpro/vite - */ -import fs from 'node:fs'; -import path from 'node:path'; - -export default function sigproRouter() { +// sigproRouter for Vite +export function sigproRouter() { const virtualModuleId = 'virtual:sigpro-routes'; const resolvedVirtualModuleId = '\0' + virtualModuleId; - // Helper para escanear archivos const getFiles = (dir) => { if (!fs.existsSync(dir)) return []; return fs.readdirSync(dir, { recursive: true }) @@ -17,14 +10,12 @@ export default function sigproRouter() { .map(file => path.resolve(dir, file)); }; - // Transformador de ruta de archivo a URL de router const pathToUrl = (pagesDir, filePath) => { let relative = path.relative(pagesDir, filePath) .replace(/\\/g, '/') .replace(/\.(js|jsx)$/, '') .replace(/\/index$/, '') .replace(/^index$/, ''); - return ('/' + relative) .replace(/\/+/g, '/') .replace(/\[\.\.\.([^\]]+)\]/g, '*') @@ -34,18 +25,13 @@ export default function sigproRouter() { return { name: 'sigpro-router', - resolveId(id) { if (id === virtualModuleId) return resolvedVirtualModuleId; }, - load(id) { if (id !== resolvedVirtualModuleId) return; - const root = process.cwd(); const pagesDir = path.resolve(root, 'src/pages'); - - // Obtenemos y ordenamos archivos (rutas estáticas primero, luego dinámicas) const files = getFiles(pagesDir).sort((a, b) => { const urlA = pathToUrl(pagesDir, a); const urlB = pathToUrl(pagesDir, b); @@ -55,23 +41,15 @@ export default function sigproRouter() { }); let routeEntries = ''; - files.forEach((fullPath) => { const urlPath = pathToUrl(pagesDir, fullPath); - // Hacemos la ruta relativa al proyecto para que el import de Vite sea limpio const relativeImport = './' + path.relative(root, fullPath).replace(/\\/g, '/'); - - routeEntries += ` { path: '${urlPath}', component: async () => (await import('/${relativeImport}')).default },\n`; + routeEntries += ` { path: '${urlPath}', component: () => import('/${relativeImport}') },\n`; }); - - // Fallback 404 si no existe una ruta comodín if (!routeEntries.includes("path: '*'")) { - routeEntries += ` { path: '*', component: () => document.createTextNode('404 - Not Found') },\n`; + routeEntries += ` { path: '*', component: () => ({ default: () => document.createTextNode('404 - Not Found') }) },\n`; } - return `export const routes = [\n${routeEntries}];`; } }; } - -export { sigproRouter }; \ No newline at end of file diff --git a/src/utils.js b/src/utils.js deleted file mode 100644 index e756bce..0000000 --- a/src/utils.js +++ /dev/null @@ -1,24 +0,0 @@ -// utils.js - -export const db = async (url, data = {}, loading = null) => { - if (loading) loading(true); - - try { - const res = await fetch(url, { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify(data), - credentials: 'include' - }); - - if (!res.ok) { - const errorText = await res.text(); - throw new Error(`Error ${res.status}: ${errorText}`); - } - - return await res.json(); - - } finally { - if (loading) loading(false); - } -}; \ No newline at end of file