Kolostov

FW:DOM

Feb 8th, 2026 (edited)
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
JavaScript 39.37 KB | Source Code | 0 0
  1. /* This is my carefully crafted DOM Framework */
  2. self.hub = [];
  3.  
  4. /* The best designs emerge when you follow the constraints to their logical conclusion. */
  5. fw = (o, ...protocols) => {
  6.     if (Array.isArray(o)) return o.map((n) => fw(n)); /* allow decoration of multiple objects */
  7.  
  8.     /* Determine reference to this element */
  9.     o.ref =
  10.         o.id ||
  11.         (o.dataset?.id ?? o.name) ||
  12.         (o.dataset?.name ?? (o.classList && o.classList[0]) ?? o.tagName?.toLowerCase() ?? "");
  13.  
  14.     self.hub.push(o);
  15.  
  16.     /* escape dom elements that already have numeric indexes as attributes */
  17.     if (!o[0]) {
  18.         /* Merge all protocols */
  19.         let merged = [];
  20.         if (protocols && protocols.length > 0) {
  21.             /* Collect all protocol names and implementations */
  22.             let methods = [],
  23.                 bodies = [];
  24.  
  25.             protocols.forEach((proto) => {
  26.                 if (proto && proto.length > 0) {
  27.                     // Handle both protocol array and function that returns array
  28.                     let names = Array.isArray(proto)
  29.                         ? typeof proto[0] === "function"
  30.                             ? proto[0]()
  31.                             : proto[0]
  32.                         : proto();
  33.                     let implementations = Array.isArray(proto) ? proto.slice(1) : [];
  34.  
  35.                     names.forEach((name, i) => {
  36.                         let index = methods.indexOf(name);
  37.                         if (index !== -1) {
  38.                             bodies[index + 1] = implementations[i];
  39.                         } else {
  40.                             methods.push(name);
  41.                             bodies.push(implementations[i]);
  42.                         }
  43.                     });
  44.                 }
  45.             });
  46.  
  47.             /* Build merged protocol */
  48.             merged = [() => methods, ...bodies];
  49.         }
  50.  
  51.         /* Decorate with merged protocol */
  52.         if (merged && merged.length > 0) {
  53.             o[0] = merged[0](o);
  54.             for (let i = 1; i < merged.length; i++) {
  55.                 o[i] = merged[i];
  56.             }
  57.             o.length = merged.length;
  58.         }
  59.     }
  60.  
  61.     /* communication to other elements trough dynamic protocol */
  62.     /* communication between two stranger-to-eachoder elements: Decoupled Component Communication */
  63.     o.to = (other, call, ...args) => {
  64.         /* reaching for a protocol call on an element */
  65.         if (Array.isArray(other)) return other.map((n) => o.to(n, call, ...args)); /* allow multiple */
  66.  
  67.         let x = other;
  68.         if (other instanceof Node) {
  69.             while ((!x.length || x[0].indexOf(call) === -1) && (x.parentEl || x.parentNode)) {
  70.                 x = x.parentEl || x.parentNode; /* logical parent before physical */
  71.             }
  72.         }
  73.         return (
  74.             (x.length && x[0].indexOf(call) !== -1 && x[x[0].indexOf(call) + 1](x, o, ...args)) ||
  75.             /* try to call superglobal by string reference */
  76.             (typeof other === "string" &&
  77.                 self[other] &&
  78.                 self[other].length &&
  79.                 self[other][0].indexOf(call) !== -1 &&
  80.                 self[other][self[other][0].indexOf(call) + 1](self[other], o, ...args)) ||
  81.             /* try if other has attribute defined as function */
  82.             (typeof other[call] === "function" && other[call](other, o, ...args)) ||
  83.             /* try to access simple attribute */
  84.             other[call] ||
  85.             undefined
  86.         );
  87.     };
  88.  
  89.     /* allows for patterns like el.can(target, "save")?.(data); */
  90.     o.can = (other, call) => {
  91.         let x = other instanceof Node ? other : self[other];
  92.         while (x && (!x.length || x[0].indexOf(call) === -1)) {
  93.             x = x.parentEl || x.parentNode;
  94.         }
  95.         return !!(x && x.length && x[0].indexOf(call) !== -1)
  96.             ? (args) => o.to(other, call, ...args)
  97.             : /* allow self querying of capabilities */
  98.               typeof other == "string" && call === undefined && "0" in o
  99.               ? o[0].indexOf(other) !== -1
  100.               : null;
  101.     };
  102.  
  103.     /* this instance is known by the following list of representetives */
  104.     o.contacts = [];
  105.  
  106.     /* Sets self to be originating from 'origin[s]' with optional specification of 'store' */
  107.     o.of = (origin, store) => {
  108.         if (Array.isArray(origin)) {
  109.             if (store) return origin.map((n) => o.of(n, store)); /* allow multiple origins reference me */
  110.             /* Allow target origin of first existance */
  111.             for (let ref of origin) {
  112.                 let suspect = typeof ref === "string" ? o.g(ref) : ref;
  113.                 if (suspect instanceof Element) {
  114.                     return o.of(suspect);
  115.                 }
  116.             }
  117.         }
  118.         if (typeof origin === "object") {
  119.             let known = "known:" + o.ref;
  120.             return (
  121.                 (o.contacts.push(origin) /* always push origin on objects */ && origin instanceof Node
  122.                     ? ((origin.appendChild(o).parentEl = origin), o)
  123.                     : store
  124.                       ? store in origin /* set key = value in origin = this el */
  125.                           ? Array.isArray(origin[store])
  126.                               ? origin[store].push(o)
  127.                               : (origin[store][o.ref] = o)
  128.                           : "can" in origin
  129.                             ? origin.can("set")?.(store, o) && o /* return el for chaining even if set returns else */
  130.                             : "v" in origin
  131.                               ? origin.v(store, o)
  132.                               : "of" in origin[store] /* store itself has self management? */
  133.                                 ? origin[store].of(origin[store], store)
  134.                                 : ((origin[store] = {
  135.                                       [o.ref]: o,
  136.                                   }),
  137.                                   o) /* fallback to primitive property */
  138.                       : "can" in origin /* setting origin ref without any proper store */
  139.                         ? origin.can("set")?.(o.ref, o)
  140.                         : "v" in origin
  141.                           ? origin.v(o.ref, o)
  142.                           : known in origin /* fallback to known references */
  143.                             ? Array.isArray(origin[known])
  144.                                 ? origin[known].push(o)
  145.                                 : (origin[known] = [origin[known], o]) /* re-declare for known references to be array */
  146.                             : (origin[known] = [o])) /* initialize origin containing references */ || o
  147.             );
  148.         }
  149.         /* origin becomes a 'route' and store becomes literal db 'store' decaration array that this element is of */
  150.         let rn, ro, sn, cso, csr;
  151.         return origin
  152.             ? (origin[0] === "/"
  153.                   ? ((rn = store ?? o.v("router") ?? "router"),
  154.                     (ro = o.g(rn) ?? h(rn, o.v("routes") ?? {})) /* emergent origin */,
  155.                     o.contacts.push(ro) && o.to(ro, "book", origin))
  156.                   : (o.db = store
  157.                         ? ((sn = origin + "/" + store), o.contacts.push(sn) && o.g(sn)) /* direct database */
  158.                         : ((sn = origin + "/default"),
  159.                           (o.g(sn) && o.contacts.push(sn)) ||
  160.                               ((cso = o.v("db_origin") ?? origin),
  161.                               (csr = o.v("db_store") ?? "default"),
  162.                               s(cso, csr) && o.contacts.push(cso + "/" + csr)) ||
  163.                               undefined)) /* data origin could not be initiated */,
  164.               o)
  165.             : o.contacts /* no origin nor store - let's return array of contacts */;
  166.     };
  167.  
  168.     o.v = (key, val) => {
  169.         /* reaching for a property / value on an element */
  170.         if (Array.isArray(key)) return key.map((n) => o.v(n)); /* allow multiple */
  171.         /* start with self */
  172.         let x = o,
  173.             seekin = [];
  174.         while (
  175.             !x[key] &&
  176.             !(x.dataset ?? {})[key] &&
  177.             !(typeof x.hasAttribute === "function" && x.hasAttribute(key)) &&
  178.             (x.parentEl || x.parentNode) &&
  179.             (seekin.indexOf(x) === -1 || console.warn("Reference loop detected", seekin.slice(-2))) /* report */
  180.         ) {
  181.             seekin.push(x);
  182.             x = x.parentEl || x.parentNode; /* logical parent before physical */
  183.         }
  184.         if (val !== undefined) {
  185.             if (x[key] !== undefined) return (x[key] = val);
  186.             if (x.dataset && x.dataset[key] !== undefined) return (x.dataset[key] = val);
  187.             if (x.getAttribute && x.getAttribute(key) !== undefined) return x.setAttribute(key, val) || val;
  188.             if (self[key] !== undefined) return (self[key] = val);
  189.             return (x[key] = val); /* set to self element if no owner candidate found */
  190.         }
  191.         let gAttribute = x instanceof Element ? x.getAttribute.bind(x) : (_) => null;
  192.         return x[key] ?? (x.dataset ?? {})[key] ?? gAttribute(key) ?? self[key] ?? null;
  193.     };
  194.  
  195.     /* get by reference */
  196.     o.g = (ref, gobal = true) => {
  197.         if (Array.isArray(ref)) return ref.map((n) => o.g(n)); /* allow multiple */
  198.         /* query results of current scope including possibility to get 'self' as a member of results array */
  199.         let r = [o.ref === ref ? o : null, "v" in o ? o.v(ref) : null];
  200.         if (o[0] && Array.isArray(o[0]) && o[0].indexOf("get") !== -1) {
  201.             let getIndex = o[0].indexOf("get") + 1;
  202.             if (o[getIndex] && typeof o[getIndex] === "function") {
  203.                 r.push(o[getIndex](o, ref));
  204.             }
  205.         }
  206.         let known = "known:" + ref;
  207.         r.push(...(known in o ? o[known].filter((x) => x.ref === ref) : []));
  208.         o.q ? r.push(...o.q(`#${ref}, [data-id="${ref}"], [name="${ref}"], [data-name="${ref}"]`)) : null;
  209.         for (let k in o) {
  210.             if (o.hasOwnProperty(k) && typeof k === "object" && ref in o[k]) r.push(o[k][ref]);
  211.         }
  212.         let p = o.parentEl || o.parentNode;
  213.         return [
  214.             ...new Set(
  215.                 [...r, ...(p && p.g ? p.g(ref) : gobal ? self.hub.filter((x) => x.ref === ref) : undefined)].filter(
  216.                     (x) => x,
  217.                 ),
  218.             ),
  219.         ];
  220.     };
  221.  
  222.     o.might = (some, act, ...args) => {
  223.         /* when 'some' is an exact match which has the exact 'act' then return immediately. */
  224.         if (some && some[0] && Array.isArray(some[0]) && some[0].indexOf(act) !== -1) {
  225.             return o.to(some, act, ...args);
  226.         }
  227.  
  228.         /* ranking function */
  229.         const rank = (items, target, getString) => {
  230.             const scores = {};
  231.             items.forEach((item, index) => {
  232.                 let score = 0;
  233.                 const str = getString(item);
  234.  
  235.                 /* initial penalty for length difference */
  236.                 score += Math.abs(str.length - target.length) * -1;
  237.  
  238.                 /* reward matching substrings */
  239.                 for (let i = 0; i < target.length; i++) {
  240.                     const substr = target.substr(0, i + 1);
  241.                     score += str.indexOf(substr) !== -1 ? i + 1 : (i + 1) * -1;
  242.                 }
  243.  
  244.                 scores[index] = score;
  245.             });
  246.             return scores;
  247.         };
  248.  
  249.         /* deciding on 'some' */
  250.         let scores = rank(self.hub, some, (item) => item.ref || "");
  251.  
  252.         /* remove all negative ranking indexes */
  253.         let candidates = Object.keys(scores)
  254.             .filter((idx) => scores[idx] > 0)
  255.             .sort((a, b) => scores[b] - scores[a]);
  256.  
  257.         for (let idx of candidates) {
  258.             let candidate = self.hub[idx];
  259.             if (candidate && candidate.ref) {
  260.                 let r = o.g(candidate.ref, false);
  261.                 if (r && r.length > 0 && r[0]) {
  262.                     let found = r.find((item) => item && item !== o);
  263.                     if (found) {
  264.                         if (found[0] && Array.isArray(found[0]) && found[0].indexOf(act) !== -1) {
  265.                             return o.to(found, act, ...args);
  266.                         }
  267.  
  268.                         if (found[0] && Array.isArray(found[0])) {
  269.                             let acts = rank([{ actions: found[0] }], act, (item) => item.actions.join(","));
  270.                             let possibilities = Object.keys(acts)
  271.                                 .filter((actIdx) => acts[actIdx] > 0)
  272.                                 .sort((a, b) => acts[b] - acts[a]);
  273.  
  274.                             if (possibilities.length > 0) {
  275.                                 let decision = possibilities[0];
  276.                                 let ind = found[0].indexOf(found[0][decision]);
  277.                                 if (ind !== -1 && found[ind + 1]) {
  278.                                     return o.to(found, found[0][ind], ...args);
  279.                                 }
  280.                             }
  281.                         }
  282.                     }
  283.                 }
  284.             }
  285.         }
  286.  
  287.         return undefined;
  288.     };
  289.  
  290.     /* reference to decorated object */
  291.     return o;
  292. };
  293.  
  294. t = (text) => document.createTextNode(text);
  295. e = (...a) => {
  296.     /* arguments */
  297.     let call,
  298.         tgz,
  299.         protocol = [];
  300.     let i = null,
  301.         t,
  302.         c,
  303.         p = {}; /* id, tag, classes, properties */
  304.     if (typeof a[0] === "string") {
  305.         /* special case for parsing of existing dom */
  306.         if (a[0][0] === ":" && a[0].substr(1) && (tgz = Array.from(document.querySelectorAll(a[0].substr(1))))) {
  307.             if (tgz.length) {
  308.                 /* Parse element and reconstruct as e() element */
  309.                 let parse = (el) => {
  310.                     /* Build tag name with classes and id */
  311.                     let selector = el.tagName.toLowerCase();
  312.  
  313.                     /* Add id and classes */
  314.                     if (el.id) selector += "#" + el.id;
  315.                     if (el.classList.length > 0) {
  316.                         selector += "." + Array.from(el.classList).join(".");
  317.                     }
  318.  
  319.                     /* Collect attributes */
  320.                     const attrs = {};
  321.                     Array.from(el.attributes).forEach((a) => {
  322.                         if (a.name === "class") return; /* Already handled */
  323.                         if (a.name === "id" && a.value) {
  324.                             /* remove id or it won't get re-set */
  325.                             self[a.value] = undefined;
  326.                         }
  327.                         if (a.name.startsWith("data-")) {
  328.                             attrs["_" + a.name.substring(5)] = a.value;
  329.                         } else {
  330.                             attrs[a.name] = a.value;
  331.                         }
  332.                     });
  333.                     /* Collect child elements and text nodes */
  334.                     const children = [];
  335.                     Array.from(el.childNodes).forEach((child) => {
  336.                         if (child.nodeType === Node.ELEMENT_NODE) {
  337.                             children.push(parse(child));
  338.                         } else if (child.nodeType === Node.TEXT_NODE && child.textContent.trim()) {
  339.                             children.push(document.createTextNode(child.textContent));
  340.                         }
  341.                     });
  342.                     /* Reconstruct using e() */
  343.                     return e(selector, attrs, ...children);
  344.                 };
  345.                 return tgz.map((z) => ((x = parse(z)), z.parentNode.replaceChild(x, z), { new: x, old: z }));
  346.             }
  347.         }
  348.  
  349.         /* Element construction */
  350.         call = a[0];
  351.         c = a[0].split(".");
  352.         let f = c[0].split("#");
  353.         t = f.shift();
  354.         i = f.pop();
  355.         c = c
  356.             .slice(1)
  357.             .map((c) =>
  358.                 c.substring(
  359.                     0,
  360.                     (c.indexOf("#") !== -1 && (i = c.substr(c.indexOf("#") + 1)) && c.indexOf("#")) || c.length,
  361.                 ),
  362.             );
  363.         a.shift(); /* remove a[0] which was the tag */
  364.     } else {
  365.         ((c = []), (t = "div"));
  366.     }
  367.  
  368.     let el = document.createElement(t || "div");
  369.     i && !(i in self) && (el.id = i); /* id not already in use */
  370.     c && c.map((cn) => el.classList.add(cn));
  371.     /* after expected tag and props, expect children and functions of current element communication protocol */
  372.     while (a.length) {
  373.         if (typeof a[0] === "object" && !(a[0] instanceof Node)) {
  374.             for (let k in a[0]) {
  375.                 if (a[0].hasOwnProperty(k)) {
  376.                     let i = ["$", "_"].indexOf(k[0]) !== -1 ? k.substr(1) : k;
  377.                     if (a[0][k] instanceof Node) {
  378.                         /* property as node - an in memory element for cloning/templating */
  379.                         a[0][k].parentEl = el;
  380.                         el[i] = a[0][k];
  381.                     } else if (typeof a[0][k] === "object" || Array.isArray(a[0][k])) {
  382.                         el[i] = a[0][k];
  383.                     } else {
  384.                         k[0] === "_"
  385.                             ? (el.dataset[i] = a[0][k])
  386.                             : k[0] === "$"
  387.                               ? (el[i] = a[0][k])
  388.                               : el.setAttribute(k, a[0][k]);
  389.                     }
  390.                 }
  391.             }
  392.         } else if (Array.isArray(a[0])) {
  393.             /* Allows declaration of [..., {}, {}, {}, {}, ...] where each object becomes DOM element with properties */
  394.             /* example call with correct order (where spread-opertion of data is always mandatory):
  395.              * e("tr", ["td", x => x.age >= 18, ...users, (el, row) => row.map(...), [
  396.              *     () => ["open", "send", "save", ...],
  397.              *     (el, caller, id) => { ...open logic... },
  398.              *     (el, caller, ..) => { ...send logic... },
  399.              *     (el, caller, ..) => { ...save logic... },
  400.              *     protocol ...
  401.              * ]]);
  402.              * where order is: ?string call, ?function filter, ...object data, ?array protocol
  403.              */
  404.             let call = typeof a[0][0] === "string" ? a[0].shift() : call /* allow for custom tag call on each row */,
  405.                 filter = typeof a[0][0] === "function" ? a[0].shift() : null /* process on each row before passing */,
  406.                 callback =
  407.                     typeof a[0][a[0].length - 1] === "function"
  408.                         ? a[0].pop()
  409.                         : null /* process row element before mounting, eg: create children, register events, etc.. */,
  410.                 child_protocol = Array.isArray(a[0][a[0].length - 1]) ? a[0].pop() : [];
  411.             a[0].map(
  412.                 (row) => (
  413.                     (row = filter ? filter(row) : row) /* filter data before mounting */,
  414.                     (_ = row
  415.                         ? e(call, row, ...child_protocol).of(el) /* of(el) instantly calls appendChild on self */
  416.                         : null),
  417.                     callback ? callback(_, row) /* callback after mounting */ : _
  418.                 ),
  419.             );
  420.             a.shift(); /* remove a[0] which was cildren declaration data-arra */
  421.         } else if (a[0] !== null) {
  422.             /* where 0th function must always return a protocol array of callas ex: ["open", "save", "close"] */
  423.             /* when[fn] >= 1 then always called as (el, o) => {...} - see fw(); */
  424.             typeof a[0] === "function"
  425.                 ? protocol.push(a[0])
  426.                 : /* Simple child node of current element */
  427.                   el.appendChild(!(a[0] instanceof Node) ? document.createTextNode(a[0].toString()) : a[0]);
  428.         }
  429.         a.shift(); /* remove a[0] which was set of properties, child element or protocol */
  430.     }
  431.  
  432.     /* Decorate with base framework */
  433.     fw(el, protocol);
  434.  
  435.     el.on = (ev, cb) => el.addEventListener(ev, (x) => cb(x, el)) || el;
  436.  
  437.     /* query by selector */
  438.     el.q = (selector) => {
  439.         if (Array.isArray(selector)) return selector.map((n) => el.q(n)); /* allow multiple */
  440.         let x = el,
  441.             r = [];
  442.         do {
  443.             r.push(...Array.from(x.querySelectorAll(selector)));
  444.         } while ((x = x.parentEl || x.parentNode));
  445.         return [...new Set(r)];
  446.     };
  447.     /* after dom deployment */
  448.     el.then = (cb) => {
  449.         el.onmount = new IntersectionObserver((entries, obs) => {
  450.             if (entries[0].isIntersecting) {
  451.                 cb(el); /* We could trigger once by using obs.disconnect(); but we can be re-mounted. */
  452.             }
  453.         }).observe(el);
  454.         return el;
  455.     };
  456.     el.change = (cb) => new MutationObserver(() => cb(el)).observe(el, { childList: !0, subtree: !0 }) || el;
  457.  
  458.     return el;
  459. };
  460.  
  461. s = (dbName = "FW:DOM", storeName = "default", version = 1, url = null, since = null, ...a) => {
  462.     /* arguments processing in e() style */
  463.     let protocol = [];
  464.  
  465.     /* internal state */
  466.     const [cache, listeners] = [new Map(), new Map()];
  467.     let cfg = { dbName, storeName, version, url, since };
  468.  
  469.     /* parse configuration from arguments */
  470.     const args = (...a) => {
  471.         while (a.length) {
  472.             if (typeof a[0] === "object" && !Array.isArray(a[0])) {
  473.                 Object.assign(cfg, a[0]); /* merge config object */
  474.             } else if (typeof a[0] === "function") {
  475.                 protocol.push(a[0]); /* collect protocol functions */
  476.             }
  477.             /* Ignore arrays or throw error? */
  478.             a.shift();
  479.         }
  480.     };
  481.  
  482.     let db = null;
  483.     let [ready, syncing, queued, pushing] = [false, false, false, false];
  484.  
  485.     since ??= new Date();
  486.  
  487.     /* core storage engine */
  488.     const o = {
  489.         open: () =>
  490.             new Promise((resolve) => {
  491.                 const req = indexedDB.open(cfg.dbName, cfg.version);
  492.                 req.onupgradeneeded = (e) => {
  493.                     if (!e.target.result.objectStoreNames.contains(cfg.storeName)) {
  494.                         e.target.result.createObjectStore(cfg.storeName);
  495.                     }
  496.                 };
  497.                 req.onsuccess = (e) => {
  498.                     db = e.target.result;
  499.                     o.keys()
  500.                         .then((keys) =>
  501.                             Promise.all(keys.map((k) => o.get(k).then((v) => (cache.set(k, v), l("load", k, v))))),
  502.                         )
  503.                         .then(() => ((ready = true), l("ready", cache.size), resolve()));
  504.                 };
  505.                 req.onerror = () => ((ready = true), l("ready", 0), resolve());
  506.             }),
  507.  
  508.         get: (k) =>
  509.             new Promise((resolve) => {
  510.                 if (!db) return resolve(localStorage.getItem(k) ? JSON.parse(localStorage.getItem(k)) : null);
  511.  
  512.                 const tx = db.transaction(cfg.storeName, "readonly"),
  513.                     store = tx.objectStore(cfg.storeName),
  514.                     req = store.get(k);
  515.  
  516.                 req.onsuccess = () => resolve(req.result);
  517.                 req.onerror = () => resolve(null);
  518.             }),
  519.  
  520.         set: (k, v) =>
  521.             new Promise((resolve) => {
  522.                 if (l("beforeSet", k, v) || !db) {
  523.                     return localStorage.setItem(k, JSON.stringify(v)) || l("set", k, v) || resolve();
  524.                 }
  525.                 const tx = db.transaction(cfg.storeName, "readwrite");
  526.                 tx.objectStore(cfg.storeName).put(v, k);
  527.                 tx.oncomplete = () => (l("set", k, v), resolve());
  528.             }),
  529.  
  530.         del: (k) =>
  531.             new Promise((resolve) => {
  532.                 if (l("beforeDel", k) || !db) {
  533.                     return localStorage.removeItem(k) || l("del", k) || resolve();
  534.                 }
  535.                 const tx = db.transaction(cfg.storeName, "readwrite");
  536.                 tx.objectStore(cfg.storeName).delete(k);
  537.                 tx.oncomplete = () => (l("del", k), resolve());
  538.             }),
  539.  
  540.         keys: () =>
  541.             new Promise((resolve) => {
  542.                 if (!db) return resolve([...Array(localStorage.length)].map((_, i) => localStorage.key(i)));
  543.                 const tx = db.transaction(cfg.storeName, "readonly"),
  544.                     req = tx.objectStore(cfg.storeName).getAllKeys();
  545.                 req.onsuccess = () => resolve(req.result);
  546.                 req.onerror = () => resolve([]);
  547.             }),
  548.  
  549.         clear: () =>
  550.             new Promise((resolve) => {
  551.                 if (l("beforeClear") || !db) {
  552.                     return localStorage.clear() || cache.clear() || l("clear") || resolve();
  553.                 }
  554.                 const tx = db.transaction(cfg.storeName, "readwrite");
  555.                 tx.objectStore(cfg.storeName).clear();
  556.                 tx.oncomplete = () => (cache.clear(), l("clear"), resolve());
  557.             }),
  558.     };
  559.  
  560.     /* event-launcher system */
  561.     const l = (event, ...args) => {
  562.         (listeners.get(event) || []).forEach((fn) => fn(store, ...args));
  563.     };
  564.  
  565.     const relevant = (items, since) =>
  566.         items.filter(
  567.             (item) =>
  568.                 (item.mtime && new Date(item.mtime) > since) ||
  569.                 (item.ctime && new Date(item.ctime) > since) ||
  570.                 (item.dtime && new Date(item.dtime) > since),
  571.         );
  572.  
  573.     const send = async () => {
  574.         if (!cfg.url) return { success: true, message: "No backend URL" };
  575.  
  576.         const lastSync = store.get("lastSync")[0];
  577.  
  578.         if (!pushing && lastSync && new Date(lastSync) > since) {
  579.             const hasNewChanges = Array.from(cache.entries()).some(
  580.                 ([k, items]) =>
  581.                     !k.startsWith("_") &&
  582.                     k !== "lastSync" &&
  583.                     items.some((item) => item.mtime && new Date(item.mtime) > new Date(lastSync)),
  584.             );
  585.             if (!hasNewChanges) {
  586.                 return l("syncSkip", "No new changes") || { success: true, message: "No changes to sync" };
  587.             }
  588.         }
  589.  
  590.         const data = {};
  591.         cache.forEach((items, key) => {
  592.             if (key.startsWith("_") || key === "lastSync") return;
  593.             const recent = relevant(items, since);
  594.             if (recent.length) data[key] = recent;
  595.         });
  596.  
  597.         if (Object.keys(data).length) {
  598.             l(
  599.                 "syncStart",
  600.                 Object.values(data).reduce((s, a) => s + a.length, 0),
  601.             );
  602.             const response = await fetch(`${cfg.url}?action=store`, {
  603.                 method: "POST",
  604.                 headers: { "Content-Type": "application/json" },
  605.                 body: JSON.stringify({
  606.                     _sync: {
  607.                         timestamp: new Date().toISOString(),
  608.                         since: since.toISOString(),
  609.                         itemCount: Object.values(data).reduce((sum, arr) => sum + arr.length, 0),
  610.                     },
  611.                     ...data,
  612.                 }),
  613.             });
  614.             const result = await response.json();
  615.             if (result.success) {
  616.                 l("syncSuccess", result._sync?.itemCount);
  617.                 const temp = store.queue;
  618.                 store.queue = () => {};
  619.                 await store.set("lastSync", new Date().toISOString());
  620.                 store.queue = temp;
  621.             } else {
  622.                 l("syncError", result.error);
  623.             }
  624.             return result;
  625.         }
  626.         return l("syncSkip", "No recent changes") || { success: true, message: "No changes to sync" };
  627.     };
  628.  
  629.     const queue = async () => {
  630.         if (syncing) return (queued = true);
  631.         syncing = true;
  632.         try {
  633.             await send();
  634.         } finally {
  635.             syncing = false;
  636.             if (queued) {
  637.                 queued = false;
  638.                 setTimeout(queue, 5000);
  639.             }
  640.         }
  641.     };
  642.  
  643.     /* storage object */
  644.     const store = {
  645.         /* reference */
  646.         name: cfg.dbName + "/" + cfg.storeName,
  647.  
  648.         /* core storage methods */
  649.         get: (k, d = []) =>
  650.             ready ? (cache.get(k) || []).filter((x) => !x.dtime || new Date(x.dtime) > new Date()) : d,
  651.         set: (k, v) => (
  652.             cache.set(k, v),
  653.             o.set(k, v).catch((e) => console.error(`Save failed for ${k}:`, e)),
  654.             !k.startsWith("_") && k !== "lastSync" && queue()
  655.         ),
  656.         key: (k, id) => store.get(k).find((x) => String(x.id) === String(id)),
  657.         add: (k, v) => {
  658.             const item = {
  659.                 ...v,
  660.                 id: v.id ? String(v.id) : Date.now().toString(),
  661.                 mtime: new Date().toISOString(),
  662.                 ctime: v.ctime || new Date().toISOString(),
  663.             };
  664.             store.set(k, [...store.get(k), item]);
  665.             return item;
  666.         },
  667.         upd: (k, id, v) => {
  668.             const items = store
  669.                 .get(k)
  670.                 .map((x) => (String(x.id) === String(id) ? { ...x, ...v, mtime: new Date().toISOString() } : x));
  671.             store.set(k, items);
  672.             return items.find((x) => String(x.id) === String(id));
  673.         },
  674.         del: (k, id) => {
  675.             const items = store
  676.                 .get(k)
  677.                 .map((x) =>
  678.                     String(x.id) === String(id)
  679.                         ? { ...x, dtime: new Date().toISOString(), mtime: new Date().toISOString() }
  680.                         : x,
  681.                 );
  682.             store.set(k, items);
  683.             return items;
  684.         },
  685.         all: () => Object.fromEntries([...cache.entries()].filter(([k]) => !k.startsWith("_") && k !== "lastSync")),
  686.         clear: () => o.clear(),
  687.  
  688.         /* sync methods */
  689.         sync: () => o.open(),
  690.         queue: () => queue(),
  691.         push: async () => ((pushing = true), await send(), (pushing = false)),
  692.         pull: async (from = since, callback) => {
  693.             if (!cfg.url) return { success: true, message: "No backend URL" };
  694.             pushing = true;
  695.             const start = new Date(from).toISOString();
  696.             try {
  697.                 const response = await fetch(`${cfg.url}?action=restore&since=${encodeURIComponent(start)}`),
  698.                     data = await response.json(),
  699.                     temp = store.queue;
  700.                 store.queue = () => {};
  701.                 await Promise.all(
  702.                     Object.entries(data).map(
  703.                         ([key, items]) => Array.isArray(items) && o.set(key, [...store.get(key), ...items]),
  704.                     ),
  705.                 );
  706.                 store.queue = temp;
  707.  
  708.                 return (l("pull", data) || (callback && callback()), { success: true });
  709.             } catch (err) {
  710.                 return l("pullError", err.message) || { success: false, error: err.message };
  711.             } finally {
  712.                 pushing = false;
  713.             }
  714.         },
  715.  
  716.         /* events */
  717.         on: (event, fn) => (listeners.has(event) || listeners.set(event, []), listeners.get(event).push(fn), store),
  718.         off: (event, fn) => (listeners.get(event)?.splice(listeners.get(event)?.indexOf(fn) >>> 0, 1), store),
  719.  
  720.         /* utilities */
  721.         info: async () => {
  722.             const keys = await o.keys();
  723.             let size = 0;
  724.             keys.forEach((k) => {
  725.                 const v = cache.get(k);
  726.                 if (v) size += JSON.stringify(v).length;
  727.             });
  728.             return {
  729.                 count: keys.length,
  730.                 size: `${(size / (1024 * 1024)).toFixed(2)}MB`,
  731.                 backend: db ? "IndexedDB" : "localStorage",
  732.                 ready,
  733.                 url: cfg.url,
  734.             };
  735.         },
  736.         sorted:
  737.             (by = "mtime", dir = "desc") =>
  738.             (k) =>
  739.                 store
  740.                     .get(k)
  741.                     .sort((a, b) =>
  742.                         dir === "desc"
  743.                             ? (b[by] || "").localeCompare(a[by] || "")
  744.                             : (a[by] || "").localeCompare(b[by] || ""),
  745.                     ),
  746.         since: (date) => (k) => store.get(k).filter((x) => new Date(x.mtime || x.ctime || 0) > new Date(date)),
  747.         where: (k) => ({
  748.             get: (d) => store.get(k, d),
  749.             set: (v) => store.set(k, v),
  750.             add: (v) => store.add(k, v),
  751.             key: (id) => store.key(k, id),
  752.             upd: (id, v) => store.upd(k, id, v),
  753.             del: (id) => store.del(k, id),
  754.             sorted: store.sorted(),
  755.             since: store.since(),
  756.         }),
  757.  
  758.         /* internal */
  759.         cache: () => cache,
  760.         destroy: () => {
  761.             listeners.clear();
  762.             cache.clear();
  763.             db?.close();
  764.             db = null;
  765.             ready = syncing = queued = pushing = false;
  766.         },
  767.     };
  768.  
  769.     /* apply framework decoration */
  770.     args(dbName, storeName, version, url, since, ...a) ||
  771.         fw(store, [Object.keys(store).slice(1), ...Object.values(store).slice(1)], protocol); /* expose as protocol */
  772.  
  773.     /* initial synchonization of this store */
  774.     store.sync().catch(() => {});
  775.  
  776.     return store;
  777. };
  778.  
  779. h = (name, routes = {}, ...a) => {
  780.     /* arguments processing in e() style */
  781.     let protocol = [];
  782.  
  783.     /* parse configuration from arguments */
  784.     const args = (...a) => {
  785.         while (a.length) {
  786.             if (typeof a[0] === "object" && !Array.isArray(a[0])) {
  787.                 Object.assign(routes, a[0]); /* merge routes object */
  788.             } else if (typeof a[0] === "function") {
  789.                 protocol.push(a[0]); /* collect protocol functions */
  790.             }
  791.             /* Ignore arrays */
  792.             a.shift();
  793.         }
  794.     };
  795.  
  796.     /* internal state */
  797.     const listeners = new Map();
  798.     let current = null;
  799.     let history = [];
  800.     let index = -1;
  801.  
  802.     /* hash parsing */
  803.     const parse = (hash) => {
  804.         const path = hash.replace(/^#!?/, "") || "/";
  805.         const [route, query] = path.split("?");
  806.         const params = {};
  807.  
  808.         query?.split("&").forEach((pair) => {
  809.             const [k, v] = pair.split("=");
  810.             k && (params[decodeURIComponent(k)] = decodeURIComponent(v || ""));
  811.         });
  812.  
  813.         return { route, params, hash: path };
  814.     };
  815.  
  816.     /* route matching with parameter support */
  817.     const match = (route) => {
  818.         for (const [pattern, handler] of Object.entries(routes)) {
  819.             if (pattern === route) return { handler, params: {}, pattern };
  820.  
  821.             const names = [];
  822.             const regex = pattern.replace(/:\w+/g, (match) => (names.push(match.substring(1)), "([^/]+)"));
  823.  
  824.             const m = route.match(new RegExp(`^${regex}$`));
  825.             if (m) {
  826.                 const params = {};
  827.                 names.forEach((name, i) => (params[name] = decodeURIComponent(m[i + 1])));
  828.                 return { handler, params, pattern };
  829.             }
  830.         }
  831.         return null;
  832.     };
  833.  
  834.     /* navigation core */
  835.     const navigate = (to, replace = false) => {
  836.         const { route, params, hash } = parse(to.startsWith("#") ? to : `#${to}`);
  837.         const m = match(route) || { handler: () => {}, params: {} };
  838.  
  839.         if (!replace && current !== hash) {
  840.             history = history.slice(0, index + 1);
  841.             history.push(hash);
  842.             index++;
  843.         }
  844.  
  845.         current = hash;
  846.  
  847.         /* remove previous route marker */
  848.         document.querySelector("[data-route]")?.removeAttribute("data-route");
  849.  
  850.         /* create route element */
  851.         const el = m.handler(params, router);
  852.         if (el instanceof Node) {
  853.             el.dataset.route = route;
  854.             el.dataset.routePattern = m.pattern || "404";
  855.             el.dataset.routeParams = JSON.stringify(params);
  856.         }
  857.  
  858.         /* notify listeners */
  859.         (listeners.get("navigate") || []).forEach((fn) => fn(router, { route, params, hash, el, pattern: m.pattern }));
  860.         return el;
  861.     };
  862.  
  863.     /* handle hash changes */
  864.     const hashChange = () => navigate(window.location.hash, false);
  865.  
  866.     /* router instance */
  867.     let router = {
  868.             /* reference */
  869.             name: name,
  870.         },
  871.         method = ["navigate", "back", "forward", "go", "current", "history", "on", "off", "update", "book", "link"];
  872.  
  873.     /* apply framework decoration with merged protocol */
  874.     args(routes, ...a) ||
  875.         fw(
  876.             router,
  877.             /* baseprotocol of any router */ [
  878.                 () => method,
  879.                 (self, caller, to, replace = false) => (
  880.                     (window.location.hash = to.startsWith("#") ? to : `#${to}`),
  881.                     self
  882.                 ),
  883.                 (self, caller) => (index > 0 && (index--, (window.location.hash = `#${history[index]}`)), self),
  884.                 (self, caller) => (
  885.                     index < history.length - 1 && (index++, (window.location.hash = `#${history[index]}`)),
  886.                     self
  887.                 ),
  888.                 (self, caller, steps) => {
  889.                     const newIndex = index + steps;
  890.                     if (newIndex >= 0 && newIndex < history.length) {
  891.                         index = newIndex;
  892.                         window.location.hash = `#${history[index]}`;
  893.                     }
  894.                     return self;
  895.                 },
  896.                 (self, caller) => {
  897.                     const { route, params, hash } = parse(window.location.hash);
  898.                     const m = match(route);
  899.                     return { route, params, hash, pattern: m?.pattern, handler: m?.handler || notFound };
  900.                 },
  901.                 (self, caller) => ({
  902.                     list: [...history],
  903.                     index,
  904.                     current: history[index] || null,
  905.                     canBack: index > 0,
  906.                     canForward: index < history.length - 1,
  907.                 }),
  908.                 (self, caller, event, handler) => (
  909.                     listeners.has(event) || listeners.set(event, []),
  910.                     listeners.get(event).push(handler),
  911.                     self
  912.                 ),
  913.                 (self, caller, event, handler) => (
  914.                     listeners.get(event)?.splice(listeners.get(event)?.indexOf(handler) >>> 0, 1),
  915.                     self
  916.                 ),
  917.                 (self, caller, newRoutes) => (
  918.                     Object.assign(routes, newRoutes),
  919.                     (listeners.get("update") || []).forEach((fn) => fn(self, routes)),
  920.                     self
  921.                 ),
  922.                 (self, caller, url) => (
  923.                     Object.assign(routes, { [url]: caller }),
  924.                     (listeners.get("update") || []).forEach((fn) => fn(self, routes)),
  925.                     self
  926.                 ),
  927.                 (self, caller, to, ...children) =>
  928.                     e(
  929.                         "a",
  930.                         {
  931.                             href: `#${to}`,
  932.                             onclick: (e) => (e.preventDefault(), self[1](self, caller, to)),
  933.                         },
  934.                         ...children,
  935.                     ),
  936.             ],
  937.             protocol /* additional protocol */,
  938.         );
  939.  
  940.     /* router event system */
  941.     router.on = (event, fn) => (
  942.         listeners.has(event) || listeners.set(event, []),
  943.         listeners.get(event).push(fn),
  944.         router
  945.     );
  946.     router.off = (event, fn) => (listeners.get(event)?.splice(listeners.get(event)?.indexOf(fn) >>> 0, 1), router);
  947.  
  948.     /* initialize hash handling */
  949.     window.addEventListener("hashchange", hashChange);
  950.     navigate(window.location.hash || "#/", true);
  951.  
  952.     /* cleanup on page unload */
  953.     window.addEventListener("beforeunload", () => window.removeEventListener("hashchange", hashChange));
  954.  
  955.     return router;
  956. };
  957.  
Advertisement
Add Comment
Please, Sign In to add comment