Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* This is my carefully crafted DOM Framework */
- self.hub = [];
- /* The best designs emerge when you follow the constraints to their logical conclusion. */
- fw = (o, ...protocols) => {
- if (Array.isArray(o)) return o.map((n) => fw(n)); /* allow decoration of multiple objects */
- /* Determine reference to this element */
- o.ref =
- o.id ||
- (o.dataset?.id ?? o.name) ||
- (o.dataset?.name ?? (o.classList && o.classList[0]) ?? o.tagName?.toLowerCase() ?? "");
- self.hub.push(o);
- /* escape dom elements that already have numeric indexes as attributes */
- if (!o[0]) {
- /* Merge all protocols */
- let merged = [];
- if (protocols && protocols.length > 0) {
- /* Collect all protocol names and implementations */
- let methods = [],
- bodies = [];
- protocols.forEach((proto) => {
- if (proto && proto.length > 0) {
- // Handle both protocol array and function that returns array
- let names = Array.isArray(proto)
- ? typeof proto[0] === "function"
- ? proto[0]()
- : proto[0]
- : proto();
- let implementations = Array.isArray(proto) ? proto.slice(1) : [];
- names.forEach((name, i) => {
- let index = methods.indexOf(name);
- if (index !== -1) {
- bodies[index + 1] = implementations[i];
- } else {
- methods.push(name);
- bodies.push(implementations[i]);
- }
- });
- }
- });
- /* Build merged protocol */
- merged = [() => methods, ...bodies];
- }
- /* Decorate with merged protocol */
- if (merged && merged.length > 0) {
- o[0] = merged[0](o);
- for (let i = 1; i < merged.length; i++) {
- o[i] = merged[i];
- }
- o.length = merged.length;
- }
- }
- /* communication to other elements trough dynamic protocol */
- /* communication between two stranger-to-eachoder elements: Decoupled Component Communication */
- o.to = (other, call, ...args) => {
- /* reaching for a protocol call on an element */
- if (Array.isArray(other)) return other.map((n) => o.to(n, call, ...args)); /* allow multiple */
- let x = other;
- if (other instanceof Node) {
- while ((!x.length || x[0].indexOf(call) === -1) && (x.parentEl || x.parentNode)) {
- x = x.parentEl || x.parentNode; /* logical parent before physical */
- }
- }
- return (
- (x.length && x[0].indexOf(call) !== -1 && x[x[0].indexOf(call) + 1](x, o, ...args)) ||
- /* try to call superglobal by string reference */
- (typeof other === "string" &&
- self[other] &&
- self[other].length &&
- self[other][0].indexOf(call) !== -1 &&
- self[other][self[other][0].indexOf(call) + 1](self[other], o, ...args)) ||
- /* try if other has attribute defined as function */
- (typeof other[call] === "function" && other[call](other, o, ...args)) ||
- /* try to access simple attribute */
- other[call] ||
- undefined
- );
- };
- /* allows for patterns like el.can(target, "save")?.(data); */
- o.can = (other, call) => {
- let x = other instanceof Node ? other : self[other];
- while (x && (!x.length || x[0].indexOf(call) === -1)) {
- x = x.parentEl || x.parentNode;
- }
- return !!(x && x.length && x[0].indexOf(call) !== -1)
- ? (args) => o.to(other, call, ...args)
- : /* allow self querying of capabilities */
- typeof other == "string" && call === undefined && "0" in o
- ? o[0].indexOf(other) !== -1
- : null;
- };
- /* this instance is known by the following list of representetives */
- o.contacts = [];
- /* Sets self to be originating from 'origin[s]' with optional specification of 'store' */
- o.of = (origin, store) => {
- if (Array.isArray(origin)) {
- if (store) return origin.map((n) => o.of(n, store)); /* allow multiple origins reference me */
- /* Allow target origin of first existance */
- for (let ref of origin) {
- let suspect = typeof ref === "string" ? o.g(ref) : ref;
- if (suspect instanceof Element) {
- return o.of(suspect);
- }
- }
- }
- if (typeof origin === "object") {
- let known = "known:" + o.ref;
- return (
- (o.contacts.push(origin) /* always push origin on objects */ && origin instanceof Node
- ? ((origin.appendChild(o).parentEl = origin), o)
- : store
- ? store in origin /* set key = value in origin = this el */
- ? Array.isArray(origin[store])
- ? origin[store].push(o)
- : (origin[store][o.ref] = o)
- : "can" in origin
- ? origin.can("set")?.(store, o) && o /* return el for chaining even if set returns else */
- : "v" in origin
- ? origin.v(store, o)
- : "of" in origin[store] /* store itself has self management? */
- ? origin[store].of(origin[store], store)
- : ((origin[store] = {
- [o.ref]: o,
- }),
- o) /* fallback to primitive property */
- : "can" in origin /* setting origin ref without any proper store */
- ? origin.can("set")?.(o.ref, o)
- : "v" in origin
- ? origin.v(o.ref, o)
- : known in origin /* fallback to known references */
- ? Array.isArray(origin[known])
- ? origin[known].push(o)
- : (origin[known] = [origin[known], o]) /* re-declare for known references to be array */
- : (origin[known] = [o])) /* initialize origin containing references */ || o
- );
- }
- /* origin becomes a 'route' and store becomes literal db 'store' decaration array that this element is of */
- let rn, ro, sn, cso, csr;
- return origin
- ? (origin[0] === "/"
- ? ((rn = store ?? o.v("router") ?? "router"),
- (ro = o.g(rn) ?? h(rn, o.v("routes") ?? {})) /* emergent origin */,
- o.contacts.push(ro) && o.to(ro, "book", origin))
- : (o.db = store
- ? ((sn = origin + "/" + store), o.contacts.push(sn) && o.g(sn)) /* direct database */
- : ((sn = origin + "/default"),
- (o.g(sn) && o.contacts.push(sn)) ||
- ((cso = o.v("db_origin") ?? origin),
- (csr = o.v("db_store") ?? "default"),
- s(cso, csr) && o.contacts.push(cso + "/" + csr)) ||
- undefined)) /* data origin could not be initiated */,
- o)
- : o.contacts /* no origin nor store - let's return array of contacts */;
- };
- o.v = (key, val) => {
- /* reaching for a property / value on an element */
- if (Array.isArray(key)) return key.map((n) => o.v(n)); /* allow multiple */
- /* start with self */
- let x = o,
- seekin = [];
- while (
- !x[key] &&
- !(x.dataset ?? {})[key] &&
- !(typeof x.hasAttribute === "function" && x.hasAttribute(key)) &&
- (x.parentEl || x.parentNode) &&
- (seekin.indexOf(x) === -1 || console.warn("Reference loop detected", seekin.slice(-2))) /* report */
- ) {
- seekin.push(x);
- x = x.parentEl || x.parentNode; /* logical parent before physical */
- }
- if (val !== undefined) {
- if (x[key] !== undefined) return (x[key] = val);
- if (x.dataset && x.dataset[key] !== undefined) return (x.dataset[key] = val);
- if (x.getAttribute && x.getAttribute(key) !== undefined) return x.setAttribute(key, val) || val;
- if (self[key] !== undefined) return (self[key] = val);
- return (x[key] = val); /* set to self element if no owner candidate found */
- }
- let gAttribute = x instanceof Element ? x.getAttribute.bind(x) : (_) => null;
- return x[key] ?? (x.dataset ?? {})[key] ?? gAttribute(key) ?? self[key] ?? null;
- };
- /* get by reference */
- o.g = (ref, gobal = true) => {
- if (Array.isArray(ref)) return ref.map((n) => o.g(n)); /* allow multiple */
- /* query results of current scope including possibility to get 'self' as a member of results array */
- let r = [o.ref === ref ? o : null, "v" in o ? o.v(ref) : null];
- if (o[0] && Array.isArray(o[0]) && o[0].indexOf("get") !== -1) {
- let getIndex = o[0].indexOf("get") + 1;
- if (o[getIndex] && typeof o[getIndex] === "function") {
- r.push(o[getIndex](o, ref));
- }
- }
- let known = "known:" + ref;
- r.push(...(known in o ? o[known].filter((x) => x.ref === ref) : []));
- o.q ? r.push(...o.q(`#${ref}, [data-id="${ref}"], [name="${ref}"], [data-name="${ref}"]`)) : null;
- for (let k in o) {
- if (o.hasOwnProperty(k) && typeof k === "object" && ref in o[k]) r.push(o[k][ref]);
- }
- let p = o.parentEl || o.parentNode;
- return [
- ...new Set(
- [...r, ...(p && p.g ? p.g(ref) : gobal ? self.hub.filter((x) => x.ref === ref) : undefined)].filter(
- (x) => x,
- ),
- ),
- ];
- };
- o.might = (some, act, ...args) => {
- /* when 'some' is an exact match which has the exact 'act' then return immediately. */
- if (some && some[0] && Array.isArray(some[0]) && some[0].indexOf(act) !== -1) {
- return o.to(some, act, ...args);
- }
- /* ranking function */
- const rank = (items, target, getString) => {
- const scores = {};
- items.forEach((item, index) => {
- let score = 0;
- const str = getString(item);
- /* initial penalty for length difference */
- score += Math.abs(str.length - target.length) * -1;
- /* reward matching substrings */
- for (let i = 0; i < target.length; i++) {
- const substr = target.substr(0, i + 1);
- score += str.indexOf(substr) !== -1 ? i + 1 : (i + 1) * -1;
- }
- scores[index] = score;
- });
- return scores;
- };
- /* deciding on 'some' */
- let scores = rank(self.hub, some, (item) => item.ref || "");
- /* remove all negative ranking indexes */
- let candidates = Object.keys(scores)
- .filter((idx) => scores[idx] > 0)
- .sort((a, b) => scores[b] - scores[a]);
- for (let idx of candidates) {
- let candidate = self.hub[idx];
- if (candidate && candidate.ref) {
- let r = o.g(candidate.ref, false);
- if (r && r.length > 0 && r[0]) {
- let found = r.find((item) => item && item !== o);
- if (found) {
- if (found[0] && Array.isArray(found[0]) && found[0].indexOf(act) !== -1) {
- return o.to(found, act, ...args);
- }
- if (found[0] && Array.isArray(found[0])) {
- let acts = rank([{ actions: found[0] }], act, (item) => item.actions.join(","));
- let possibilities = Object.keys(acts)
- .filter((actIdx) => acts[actIdx] > 0)
- .sort((a, b) => acts[b] - acts[a]);
- if (possibilities.length > 0) {
- let decision = possibilities[0];
- let ind = found[0].indexOf(found[0][decision]);
- if (ind !== -1 && found[ind + 1]) {
- return o.to(found, found[0][ind], ...args);
- }
- }
- }
- }
- }
- }
- }
- return undefined;
- };
- /* reference to decorated object */
- return o;
- };
- t = (text) => document.createTextNode(text);
- e = (...a) => {
- /* arguments */
- let call,
- tgz,
- protocol = [];
- let i = null,
- t,
- c,
- p = {}; /* id, tag, classes, properties */
- if (typeof a[0] === "string") {
- /* special case for parsing of existing dom */
- if (a[0][0] === ":" && a[0].substr(1) && (tgz = Array.from(document.querySelectorAll(a[0].substr(1))))) {
- if (tgz.length) {
- /* Parse element and reconstruct as e() element */
- let parse = (el) => {
- /* Build tag name with classes and id */
- let selector = el.tagName.toLowerCase();
- /* Add id and classes */
- if (el.id) selector += "#" + el.id;
- if (el.classList.length > 0) {
- selector += "." + Array.from(el.classList).join(".");
- }
- /* Collect attributes */
- const attrs = {};
- Array.from(el.attributes).forEach((a) => {
- if (a.name === "class") return; /* Already handled */
- if (a.name === "id" && a.value) {
- /* remove id or it won't get re-set */
- self[a.value] = undefined;
- }
- if (a.name.startsWith("data-")) {
- attrs["_" + a.name.substring(5)] = a.value;
- } else {
- attrs[a.name] = a.value;
- }
- });
- /* Collect child elements and text nodes */
- const children = [];
- Array.from(el.childNodes).forEach((child) => {
- if (child.nodeType === Node.ELEMENT_NODE) {
- children.push(parse(child));
- } else if (child.nodeType === Node.TEXT_NODE && child.textContent.trim()) {
- children.push(document.createTextNode(child.textContent));
- }
- });
- /* Reconstruct using e() */
- return e(selector, attrs, ...children);
- };
- return tgz.map((z) => ((x = parse(z)), z.parentNode.replaceChild(x, z), { new: x, old: z }));
- }
- }
- /* Element construction */
- call = a[0];
- c = a[0].split(".");
- let f = c[0].split("#");
- t = f.shift();
- i = f.pop();
- c = c
- .slice(1)
- .map((c) =>
- c.substring(
- 0,
- (c.indexOf("#") !== -1 && (i = c.substr(c.indexOf("#") + 1)) && c.indexOf("#")) || c.length,
- ),
- );
- a.shift(); /* remove a[0] which was the tag */
- } else {
- ((c = []), (t = "div"));
- }
- let el = document.createElement(t || "div");
- i && !(i in self) && (el.id = i); /* id not already in use */
- c && c.map((cn) => el.classList.add(cn));
- /* after expected tag and props, expect children and functions of current element communication protocol */
- while (a.length) {
- if (typeof a[0] === "object" && !(a[0] instanceof Node)) {
- for (let k in a[0]) {
- if (a[0].hasOwnProperty(k)) {
- let i = ["$", "_"].indexOf(k[0]) !== -1 ? k.substr(1) : k;
- if (a[0][k] instanceof Node) {
- /* property as node - an in memory element for cloning/templating */
- a[0][k].parentEl = el;
- el[i] = a[0][k];
- } else if (typeof a[0][k] === "object" || Array.isArray(a[0][k])) {
- el[i] = a[0][k];
- } else {
- k[0] === "_"
- ? (el.dataset[i] = a[0][k])
- : k[0] === "$"
- ? (el[i] = a[0][k])
- : el.setAttribute(k, a[0][k]);
- }
- }
- }
- } else if (Array.isArray(a[0])) {
- /* Allows declaration of [..., {}, {}, {}, {}, ...] where each object becomes DOM element with properties */
- /* example call with correct order (where spread-opertion of data is always mandatory):
- * e("tr", ["td", x => x.age >= 18, ...users, (el, row) => row.map(...), [
- * () => ["open", "send", "save", ...],
- * (el, caller, id) => { ...open logic... },
- * (el, caller, ..) => { ...send logic... },
- * (el, caller, ..) => { ...save logic... },
- * protocol ...
- * ]]);
- * where order is: ?string call, ?function filter, ...object data, ?array protocol
- */
- let call = typeof a[0][0] === "string" ? a[0].shift() : call /* allow for custom tag call on each row */,
- filter = typeof a[0][0] === "function" ? a[0].shift() : null /* process on each row before passing */,
- callback =
- typeof a[0][a[0].length - 1] === "function"
- ? a[0].pop()
- : null /* process row element before mounting, eg: create children, register events, etc.. */,
- child_protocol = Array.isArray(a[0][a[0].length - 1]) ? a[0].pop() : [];
- a[0].map(
- (row) => (
- (row = filter ? filter(row) : row) /* filter data before mounting */,
- (_ = row
- ? e(call, row, ...child_protocol).of(el) /* of(el) instantly calls appendChild on self */
- : null),
- callback ? callback(_, row) /* callback after mounting */ : _
- ),
- );
- a.shift(); /* remove a[0] which was cildren declaration data-arra */
- } else if (a[0] !== null) {
- /* where 0th function must always return a protocol array of callas ex: ["open", "save", "close"] */
- /* when[fn] >= 1 then always called as (el, o) => {...} - see fw(); */
- typeof a[0] === "function"
- ? protocol.push(a[0])
- : /* Simple child node of current element */
- el.appendChild(!(a[0] instanceof Node) ? document.createTextNode(a[0].toString()) : a[0]);
- }
- a.shift(); /* remove a[0] which was set of properties, child element or protocol */
- }
- /* Decorate with base framework */
- fw(el, protocol);
- el.on = (ev, cb) => el.addEventListener(ev, (x) => cb(x, el)) || el;
- /* query by selector */
- el.q = (selector) => {
- if (Array.isArray(selector)) return selector.map((n) => el.q(n)); /* allow multiple */
- let x = el,
- r = [];
- do {
- r.push(...Array.from(x.querySelectorAll(selector)));
- } while ((x = x.parentEl || x.parentNode));
- return [...new Set(r)];
- };
- /* after dom deployment */
- el.then = (cb) => {
- el.onmount = new IntersectionObserver((entries, obs) => {
- if (entries[0].isIntersecting) {
- cb(el); /* We could trigger once by using obs.disconnect(); but we can be re-mounted. */
- }
- }).observe(el);
- return el;
- };
- el.change = (cb) => new MutationObserver(() => cb(el)).observe(el, { childList: !0, subtree: !0 }) || el;
- return el;
- };
- s = (dbName = "FW:DOM", storeName = "default", version = 1, url = null, since = null, ...a) => {
- /* arguments processing in e() style */
- let protocol = [];
- /* internal state */
- const [cache, listeners] = [new Map(), new Map()];
- let cfg = { dbName, storeName, version, url, since };
- /* parse configuration from arguments */
- const args = (...a) => {
- while (a.length) {
- if (typeof a[0] === "object" && !Array.isArray(a[0])) {
- Object.assign(cfg, a[0]); /* merge config object */
- } else if (typeof a[0] === "function") {
- protocol.push(a[0]); /* collect protocol functions */
- }
- /* Ignore arrays or throw error? */
- a.shift();
- }
- };
- let db = null;
- let [ready, syncing, queued, pushing] = [false, false, false, false];
- since ??= new Date();
- /* core storage engine */
- const o = {
- open: () =>
- new Promise((resolve) => {
- const req = indexedDB.open(cfg.dbName, cfg.version);
- req.onupgradeneeded = (e) => {
- if (!e.target.result.objectStoreNames.contains(cfg.storeName)) {
- e.target.result.createObjectStore(cfg.storeName);
- }
- };
- req.onsuccess = (e) => {
- db = e.target.result;
- o.keys()
- .then((keys) =>
- Promise.all(keys.map((k) => o.get(k).then((v) => (cache.set(k, v), l("load", k, v))))),
- )
- .then(() => ((ready = true), l("ready", cache.size), resolve()));
- };
- req.onerror = () => ((ready = true), l("ready", 0), resolve());
- }),
- get: (k) =>
- new Promise((resolve) => {
- if (!db) return resolve(localStorage.getItem(k) ? JSON.parse(localStorage.getItem(k)) : null);
- const tx = db.transaction(cfg.storeName, "readonly"),
- store = tx.objectStore(cfg.storeName),
- req = store.get(k);
- req.onsuccess = () => resolve(req.result);
- req.onerror = () => resolve(null);
- }),
- set: (k, v) =>
- new Promise((resolve) => {
- if (l("beforeSet", k, v) || !db) {
- return localStorage.setItem(k, JSON.stringify(v)) || l("set", k, v) || resolve();
- }
- const tx = db.transaction(cfg.storeName, "readwrite");
- tx.objectStore(cfg.storeName).put(v, k);
- tx.oncomplete = () => (l("set", k, v), resolve());
- }),
- del: (k) =>
- new Promise((resolve) => {
- if (l("beforeDel", k) || !db) {
- return localStorage.removeItem(k) || l("del", k) || resolve();
- }
- const tx = db.transaction(cfg.storeName, "readwrite");
- tx.objectStore(cfg.storeName).delete(k);
- tx.oncomplete = () => (l("del", k), resolve());
- }),
- keys: () =>
- new Promise((resolve) => {
- if (!db) return resolve([...Array(localStorage.length)].map((_, i) => localStorage.key(i)));
- const tx = db.transaction(cfg.storeName, "readonly"),
- req = tx.objectStore(cfg.storeName).getAllKeys();
- req.onsuccess = () => resolve(req.result);
- req.onerror = () => resolve([]);
- }),
- clear: () =>
- new Promise((resolve) => {
- if (l("beforeClear") || !db) {
- return localStorage.clear() || cache.clear() || l("clear") || resolve();
- }
- const tx = db.transaction(cfg.storeName, "readwrite");
- tx.objectStore(cfg.storeName).clear();
- tx.oncomplete = () => (cache.clear(), l("clear"), resolve());
- }),
- };
- /* event-launcher system */
- const l = (event, ...args) => {
- (listeners.get(event) || []).forEach((fn) => fn(store, ...args));
- };
- const relevant = (items, since) =>
- items.filter(
- (item) =>
- (item.mtime && new Date(item.mtime) > since) ||
- (item.ctime && new Date(item.ctime) > since) ||
- (item.dtime && new Date(item.dtime) > since),
- );
- const send = async () => {
- if (!cfg.url) return { success: true, message: "No backend URL" };
- const lastSync = store.get("lastSync")[0];
- if (!pushing && lastSync && new Date(lastSync) > since) {
- const hasNewChanges = Array.from(cache.entries()).some(
- ([k, items]) =>
- !k.startsWith("_") &&
- k !== "lastSync" &&
- items.some((item) => item.mtime && new Date(item.mtime) > new Date(lastSync)),
- );
- if (!hasNewChanges) {
- return l("syncSkip", "No new changes") || { success: true, message: "No changes to sync" };
- }
- }
- const data = {};
- cache.forEach((items, key) => {
- if (key.startsWith("_") || key === "lastSync") return;
- const recent = relevant(items, since);
- if (recent.length) data[key] = recent;
- });
- if (Object.keys(data).length) {
- l(
- "syncStart",
- Object.values(data).reduce((s, a) => s + a.length, 0),
- );
- const response = await fetch(`${cfg.url}?action=store`, {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- _sync: {
- timestamp: new Date().toISOString(),
- since: since.toISOString(),
- itemCount: Object.values(data).reduce((sum, arr) => sum + arr.length, 0),
- },
- ...data,
- }),
- });
- const result = await response.json();
- if (result.success) {
- l("syncSuccess", result._sync?.itemCount);
- const temp = store.queue;
- store.queue = () => {};
- await store.set("lastSync", new Date().toISOString());
- store.queue = temp;
- } else {
- l("syncError", result.error);
- }
- return result;
- }
- return l("syncSkip", "No recent changes") || { success: true, message: "No changes to sync" };
- };
- const queue = async () => {
- if (syncing) return (queued = true);
- syncing = true;
- try {
- await send();
- } finally {
- syncing = false;
- if (queued) {
- queued = false;
- setTimeout(queue, 5000);
- }
- }
- };
- /* storage object */
- const store = {
- /* reference */
- name: cfg.dbName + "/" + cfg.storeName,
- /* core storage methods */
- get: (k, d = []) =>
- ready ? (cache.get(k) || []).filter((x) => !x.dtime || new Date(x.dtime) > new Date()) : d,
- set: (k, v) => (
- cache.set(k, v),
- o.set(k, v).catch((e) => console.error(`Save failed for ${k}:`, e)),
- !k.startsWith("_") && k !== "lastSync" && queue()
- ),
- key: (k, id) => store.get(k).find((x) => String(x.id) === String(id)),
- add: (k, v) => {
- const item = {
- ...v,
- id: v.id ? String(v.id) : Date.now().toString(),
- mtime: new Date().toISOString(),
- ctime: v.ctime || new Date().toISOString(),
- };
- store.set(k, [...store.get(k), item]);
- return item;
- },
- upd: (k, id, v) => {
- const items = store
- .get(k)
- .map((x) => (String(x.id) === String(id) ? { ...x, ...v, mtime: new Date().toISOString() } : x));
- store.set(k, items);
- return items.find((x) => String(x.id) === String(id));
- },
- del: (k, id) => {
- const items = store
- .get(k)
- .map((x) =>
- String(x.id) === String(id)
- ? { ...x, dtime: new Date().toISOString(), mtime: new Date().toISOString() }
- : x,
- );
- store.set(k, items);
- return items;
- },
- all: () => Object.fromEntries([...cache.entries()].filter(([k]) => !k.startsWith("_") && k !== "lastSync")),
- clear: () => o.clear(),
- /* sync methods */
- sync: () => o.open(),
- queue: () => queue(),
- push: async () => ((pushing = true), await send(), (pushing = false)),
- pull: async (from = since, callback) => {
- if (!cfg.url) return { success: true, message: "No backend URL" };
- pushing = true;
- const start = new Date(from).toISOString();
- try {
- const response = await fetch(`${cfg.url}?action=restore&since=${encodeURIComponent(start)}`),
- data = await response.json(),
- temp = store.queue;
- store.queue = () => {};
- await Promise.all(
- Object.entries(data).map(
- ([key, items]) => Array.isArray(items) && o.set(key, [...store.get(key), ...items]),
- ),
- );
- store.queue = temp;
- return (l("pull", data) || (callback && callback()), { success: true });
- } catch (err) {
- return l("pullError", err.message) || { success: false, error: err.message };
- } finally {
- pushing = false;
- }
- },
- /* events */
- on: (event, fn) => (listeners.has(event) || listeners.set(event, []), listeners.get(event).push(fn), store),
- off: (event, fn) => (listeners.get(event)?.splice(listeners.get(event)?.indexOf(fn) >>> 0, 1), store),
- /* utilities */
- info: async () => {
- const keys = await o.keys();
- let size = 0;
- keys.forEach((k) => {
- const v = cache.get(k);
- if (v) size += JSON.stringify(v).length;
- });
- return {
- count: keys.length,
- size: `${(size / (1024 * 1024)).toFixed(2)}MB`,
- backend: db ? "IndexedDB" : "localStorage",
- ready,
- url: cfg.url,
- };
- },
- sorted:
- (by = "mtime", dir = "desc") =>
- (k) =>
- store
- .get(k)
- .sort((a, b) =>
- dir === "desc"
- ? (b[by] || "").localeCompare(a[by] || "")
- : (a[by] || "").localeCompare(b[by] || ""),
- ),
- since: (date) => (k) => store.get(k).filter((x) => new Date(x.mtime || x.ctime || 0) > new Date(date)),
- where: (k) => ({
- get: (d) => store.get(k, d),
- set: (v) => store.set(k, v),
- add: (v) => store.add(k, v),
- key: (id) => store.key(k, id),
- upd: (id, v) => store.upd(k, id, v),
- del: (id) => store.del(k, id),
- sorted: store.sorted(),
- since: store.since(),
- }),
- /* internal */
- cache: () => cache,
- destroy: () => {
- listeners.clear();
- cache.clear();
- db?.close();
- db = null;
- ready = syncing = queued = pushing = false;
- },
- };
- /* apply framework decoration */
- args(dbName, storeName, version, url, since, ...a) ||
- fw(store, [Object.keys(store).slice(1), ...Object.values(store).slice(1)], protocol); /* expose as protocol */
- /* initial synchonization of this store */
- store.sync().catch(() => {});
- return store;
- };
- h = (name, routes = {}, ...a) => {
- /* arguments processing in e() style */
- let protocol = [];
- /* parse configuration from arguments */
- const args = (...a) => {
- while (a.length) {
- if (typeof a[0] === "object" && !Array.isArray(a[0])) {
- Object.assign(routes, a[0]); /* merge routes object */
- } else if (typeof a[0] === "function") {
- protocol.push(a[0]); /* collect protocol functions */
- }
- /* Ignore arrays */
- a.shift();
- }
- };
- /* internal state */
- const listeners = new Map();
- let current = null;
- let history = [];
- let index = -1;
- /* hash parsing */
- const parse = (hash) => {
- const path = hash.replace(/^#!?/, "") || "/";
- const [route, query] = path.split("?");
- const params = {};
- query?.split("&").forEach((pair) => {
- const [k, v] = pair.split("=");
- k && (params[decodeURIComponent(k)] = decodeURIComponent(v || ""));
- });
- return { route, params, hash: path };
- };
- /* route matching with parameter support */
- const match = (route) => {
- for (const [pattern, handler] of Object.entries(routes)) {
- if (pattern === route) return { handler, params: {}, pattern };
- const names = [];
- const regex = pattern.replace(/:\w+/g, (match) => (names.push(match.substring(1)), "([^/]+)"));
- const m = route.match(new RegExp(`^${regex}$`));
- if (m) {
- const params = {};
- names.forEach((name, i) => (params[name] = decodeURIComponent(m[i + 1])));
- return { handler, params, pattern };
- }
- }
- return null;
- };
- /* navigation core */
- const navigate = (to, replace = false) => {
- const { route, params, hash } = parse(to.startsWith("#") ? to : `#${to}`);
- const m = match(route) || { handler: () => {}, params: {} };
- if (!replace && current !== hash) {
- history = history.slice(0, index + 1);
- history.push(hash);
- index++;
- }
- current = hash;
- /* remove previous route marker */
- document.querySelector("[data-route]")?.removeAttribute("data-route");
- /* create route element */
- const el = m.handler(params, router);
- if (el instanceof Node) {
- el.dataset.route = route;
- el.dataset.routePattern = m.pattern || "404";
- el.dataset.routeParams = JSON.stringify(params);
- }
- /* notify listeners */
- (listeners.get("navigate") || []).forEach((fn) => fn(router, { route, params, hash, el, pattern: m.pattern }));
- return el;
- };
- /* handle hash changes */
- const hashChange = () => navigate(window.location.hash, false);
- /* router instance */
- let router = {
- /* reference */
- name: name,
- },
- method = ["navigate", "back", "forward", "go", "current", "history", "on", "off", "update", "book", "link"];
- /* apply framework decoration with merged protocol */
- args(routes, ...a) ||
- fw(
- router,
- /* baseprotocol of any router */ [
- () => method,
- (self, caller, to, replace = false) => (
- (window.location.hash = to.startsWith("#") ? to : `#${to}`),
- self
- ),
- (self, caller) => (index > 0 && (index--, (window.location.hash = `#${history[index]}`)), self),
- (self, caller) => (
- index < history.length - 1 && (index++, (window.location.hash = `#${history[index]}`)),
- self
- ),
- (self, caller, steps) => {
- const newIndex = index + steps;
- if (newIndex >= 0 && newIndex < history.length) {
- index = newIndex;
- window.location.hash = `#${history[index]}`;
- }
- return self;
- },
- (self, caller) => {
- const { route, params, hash } = parse(window.location.hash);
- const m = match(route);
- return { route, params, hash, pattern: m?.pattern, handler: m?.handler || notFound };
- },
- (self, caller) => ({
- list: [...history],
- index,
- current: history[index] || null,
- canBack: index > 0,
- canForward: index < history.length - 1,
- }),
- (self, caller, event, handler) => (
- listeners.has(event) || listeners.set(event, []),
- listeners.get(event).push(handler),
- self
- ),
- (self, caller, event, handler) => (
- listeners.get(event)?.splice(listeners.get(event)?.indexOf(handler) >>> 0, 1),
- self
- ),
- (self, caller, newRoutes) => (
- Object.assign(routes, newRoutes),
- (listeners.get("update") || []).forEach((fn) => fn(self, routes)),
- self
- ),
- (self, caller, url) => (
- Object.assign(routes, { [url]: caller }),
- (listeners.get("update") || []).forEach((fn) => fn(self, routes)),
- self
- ),
- (self, caller, to, ...children) =>
- e(
- "a",
- {
- href: `#${to}`,
- onclick: (e) => (e.preventDefault(), self[1](self, caller, to)),
- },
- ...children,
- ),
- ],
- protocol /* additional protocol */,
- );
- /* router event system */
- router.on = (event, fn) => (
- listeners.has(event) || listeners.set(event, []),
- listeners.get(event).push(fn),
- router
- );
- router.off = (event, fn) => (listeners.get(event)?.splice(listeners.get(event)?.indexOf(fn) >>> 0, 1), router);
- /* initialize hash handling */
- window.addEventListener("hashchange", hashChange);
- navigate(window.location.hash || "#/", true);
- /* cleanup on page unload */
- window.addEventListener("beforeunload", () => window.removeEventListener("hashchange", hashChange));
- return router;
- };
Advertisement
Add Comment
Please, Sign In to add comment