1
0
mirror of https://github.com/jaandrle/deka-dom-el synced 2024-11-23 09:09:38 +01:00

dev-package (#15)

Reviewed-on: #15
This commit is contained in:
Jan Andrle 2023-09-05 09:25:47 +02:00
parent 421d1e9ede
commit ba3194f960
23 changed files with 3936 additions and 335 deletions

127
.gitignore vendored Normal file
View File

@ -0,0 +1,127 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
.pnpm-debug.log*
# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
*.lcov
# nyc test coverage
.nyc_output
# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# Bower dependency directory (https://bower.io/)
bower_components
# node-waf configuration
.lock-wscript
# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release
# Dependency directories
node_modules/
jspm_packages/
# Snowpack dependency directory (https://snowpack.dev/)
web_modules/
# TypeScript cache
*.tsbuildinfo
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Optional stylelint cache
.stylelintcache
# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
*.tgz
# Yarn Integrity file
.yarn-integrity
# dotenv environment variable files
.env
.env.development.local
.env.test.local
.env.production.local
.env.local
# parcel-bundler cache (https://parceljs.org/)
.cache
.parcel-cache
# Next.js build output
.next
out
# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and not Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public
# vuepress build output
.vuepress/dist
# vuepress v2.x temp and cache directory
.temp
.cache
# Docusaurus cache and generated files
.docusaurus
# Serverless directories
.serverless/
# FuseBox cache
.fusebox/
# DynamoDB Local files
.dynamodb/
# TernJS port file
.tern-port
# Stores VSCode versions used for testing VSCode extensions
.vscode-test
# yarn v2
.yarn/cache
.yarn/unplugged
.yarn/build-state.yml
.yarn/install-state.gz
.pnp.*

1
bs/.lint.toml Normal file
View File

@ -0,0 +1 @@
info= "Lint size of lib and jshint"

1
bs/README.md Normal file
View File

@ -0,0 +1 @@
[jaandrle/bs: The simplest possible build system using executables](https://github.com/jaandrle/bs/)

39
bs/build.js Executable file
View File

@ -0,0 +1,39 @@
#!/usr/bin/env -S npx nodejsscript
const files= [ "index.js", "index-with-signals.js" ];
const filesOut= (file, mark= "esm")=> "dist/"+file.replace("index", mark);
for(const file of files){
const out= filesOut(file);
s.run([
"npx esbuild '::file::'",
"--platform=neutral",
"--bundle",
//"--minify",
"--minify-syntax --minify-identifiers",
"--packages=external",
"--outfile='::out::'"
].join(" "), { file, out });
pipe(
f=> f.replace(/^ +/gm, m=> "\t".repeat(m.length/2)),
f=> s.echo(f).to(out)
)(s.cat(out));
toDDE(out, filesOut(file, "dde"));
}
$.exit(0);
function toDDE(file, out){
const name= "dde";
echo(`\n ${out} (${file} → globalThis.${name})\n`);
let content= s.cat(file).toString().split("export {");
content.splice(1, 0, `\nglobalThis.${name}= {`);
content[2]= content[2].replace(/^(\t*)(.*) as ([^,\n]*)(,?)$/mg, "$1$3: $2$4");
s.echo([
`//deka-dom-el library is available via global namespace \`${name}\``,
"(()=> {",
"\t"+content.join("").split("\n").join("\n "),
"})();"
].join("\n")).to(out);
echo("⚡ Done\n");
}

2
bs/lint.sh Executable file
View File

@ -0,0 +1,2 @@
#!/usr/bin/env bash
npx size-limit

354
dist/dde-with-signals.js vendored Normal file
View File

@ -0,0 +1,354 @@
//deka-dom-el library is available via global namespace `dde`
(()=> {
// src/helpers.js
function h(e) {
let t = typeof e;
return t !== "object" ? t : e === null ? "null" : Object.prototype.toString.call(e);
}
// src/signals-common.js
var m = {
isReactiveAtrribute(e, t) {
return !1;
},
isTextContent(e) {
return h(e) !== "[object Object]";
},
processReactiveAttribute(e, t, n, r) {
return !1;
},
reactiveElement(e, ...t) {
return document.createDocumentFragment();
}
};
function R(e, t = !0) {
return t ? Object.assign(m, e) : (Object.setPrototypeOf(e, m), e);
}
function A(e) {
return m.isPrototypeOf(e) && e !== m ? e : m;
}
// src/dom.js
var E = "html";
function K(e) {
return E = e === "svg" ? "http://www.w3.org/2000/svg" : e, {
append(t) {
return E = "html", t;
}
};
}
function Q(e, t, ...n) {
let r = A(this), o;
if (e === "<>") {
if (r.isReactiveAtrribute(t))
return r.reactiveElement(t, ...n);
o = document.createDocumentFragment();
}
switch (r.isTextContent(t) && (t = { textContent: t }), !0) {
case typeof e == "function":
o = e(t || void 0);
break;
case e === "#text":
o = C(document.createTextNode(""), t);
break;
case E !== "html":
o = C(document.createElementNS(E, e), t);
break;
default:
o = C(document.createElement(e), t);
}
return n.forEach((l) => l(o)), o;
}
function C(e, ...t) {
let n = A(this);
if (!t.length)
return e;
let r = e instanceof SVGElement, o = (r ? z : D).bind(null, e, "Attribute");
return Object.entries(Object.assign({}, ...t)).forEach(function l([s, f]) {
if (n.isReactiveAtrribute(f, s) && (f = n.processReactiveAttribute(el, s, f, l)), s[0] === "=")
return o(s.slice(1), f);
if (s[0] === ".")
return S(e, s.slice(1), f);
if (typeof f == "object")
switch (s) {
case "style":
return v(f, D.bind(null, e.style, "Property"));
case "dataset":
return v(f, S.bind(null, e.dataset));
case "ariaset":
return v(f, (p, b) => o("aria-" + p, b));
case "classList":
return q(e, f);
default:
return Reflect.set(e, s, f);
}
if (/(aria|data)([A-Z])/.test(s))
return s = s.replace(/([a-z])([A-Z])/g, "$1-$2").toLowerCase(), o(s, f);
switch (s) {
case "href":
return o(s, f);
case "xlink:href":
return o(s, f, "http://www.w3.org/1999/xlink");
case "textContent":
if (!r)
break;
return e.appendChild(document.createTextNode(f));
}
return s in e && !r ? S(e, s, f) : o(s, f);
}), e;
}
function q(e, t) {
return typeof t != "object" || v(
t,
(n, r) => e.classList.toggle(n, r === -1 ? void 0 : !!r)
), e;
}
function X(e) {
return Array.from(e.children).forEach((t) => t.remove()), e;
}
function v(e, t) {
return Object.entries(e).forEach(([n, r]) => t(n, r));
}
function j(e) {
return typeof e > "u";
}
function D(e, t, n, r) {
return e[(j(r) ? "remove" : "set") + t](n, r);
}
function z(e, t, n, r, o = null) {
return e[(j(r) ? "remove" : "set") + t + "NS"](o, n, r);
}
function S(e, t, n) {
return Reflect[j(n) ? "deleteProperty" : "set"](e, t, n);
}
// src/events.js
function _(e, t, n) {
return (r) => (r.addEventListener(e, t, n), r);
}
var w = M();
_.connected = function(e, t) {
return function(r) {
w.onConnected(r, e), t && t.signal && t.signal.addEventListener("abort", () => w.offConnected(r, e));
};
};
_.disconnected = function(e, t) {
return function(r) {
w.onDisconnected(r, e), t && t.signal && t.signal.addEventListener("abort", () => w.offDisconnected(r, e));
};
};
function M() {
let e = /* @__PURE__ */ new Map(), t = !1, n = new MutationObserver(function(c) {
for (let i of c)
if (i.type === "childList") {
if (b(i.addedNodes, !0)) {
s();
continue;
}
N(i.removedNodes, !0) && s();
}
});
return {
onConnected(c, i) {
l(), o(c).connected.push(i);
},
offConnected(c, i) {
if (!e.has(c))
return;
let u = e.get(c), a = u.connected;
a.splice(a.indexOf(i), 1), r(c, u);
},
onDisconnected(c, i) {
l(), o(c).disconnected.push(i);
},
offDisconnected(c, i) {
if (!e.has(c))
return;
let u = e.get(c), a = u.disconnected;
a.splice(a.indexOf(i), 1), r(c, u);
}
};
function r(c, i) {
i.connected.length || i.disconnect.length || (e.delete(c), s());
}
function o(c) {
if (e.has(c))
return e.get(c);
let i = { connected: [], disconnected: [] };
return e.set(c, i), i;
}
function l() {
t || (t = !0, n.observe(document.body, { childList: !0, subtree: !0 }));
}
function s() {
!t || e.size || (t = !1, n.disconnect());
}
function f() {
return new Promise(function(c) {
(requestIdleCallback || requestAnimationFrame)(c);
});
}
async function p(c) {
e.size > 30 && await f();
let i = [];
if (!(c instanceof Node))
return i;
for (let u of e.keys())
u === c || !(u instanceof Node) || c.contains(u) && i.push(u);
return i;
}
function b(c, i) {
for (let u of c) {
if (i && p(u).then(b), !e.has(u))
return !1;
let a = e.get(u);
return a.connected.forEach((O) => O(u)), a.connected.length = 0, a.disconnected.length || e.delete(u), !0;
}
}
function N(c, i) {
for (let u of c) {
if (i && p(u).then(N), !e.has(u))
return !1;
let a = e.get(u);
return a.disconnected.forEach((O) => O(u)), a.connected.length = 0, a.disconnected.length = 0, e.delete(u), !0;
}
}
}
// index.js
[HTMLElement, DocumentFragment].forEach((e) => {
let { append: t } = e.prototype;
e.prototype.append = function(...n) {
return t.apply(this, n), this;
};
});
// src/signals-lib.js
var d = Symbol.for("signal");
function x(e) {
try {
return Reflect.has(e, d);
} catch {
return !1;
}
}
function y(e, t) {
if (typeof e != "function")
return P(e, t);
if (x(e))
return e;
let n = P();
return F(() => n(e())), n;
}
y.action = function(e, t, ...n) {
if (!x(e))
throw new Error(`'${e}' is not a signal!`);
let r = e[d], { actions: o } = r;
if (!o || !Reflect.has(o, t))
throw new Error(`'${e}' has no action with name '${t}'!`);
if (o[t].apply(r, n), r.skip)
return Reflect.deleteProperty(r, "skip");
r.listeners.forEach((l) => l(r.value));
};
y.on = function e(t, n, r) {
if (Array.isArray(t))
return t.forEach((o) => e(o, n, r));
L(t, n), r && r.signal && r.signal.addEventListener("abort", () => $(t, n));
};
y.clear = function(...e) {
for (let t of e)
t[d].listeners.clear(), Reflect.deleteProperty(t, d);
};
var T = {
isReactiveAtrribute(e, t) {
return x(e);
},
isTextContent(e) {
return h(e) === "string" || x(e) && h(G(e)) === "string";
},
processReactiveAttribute(e, t, n, r) {
return L(n, (o) => r([t, o])), n();
},
reactiveElement(e, t) {
let n = document.createComment("<> #reactive"), r = document.createComment("</> #reactive"), o = document.createDocumentFragment();
o.append(n, r);
let l = (s) => {
if (!n.parentNode || !r.parentNode)
return $(e, l);
let f = t(s);
Array.isArray(f) || (f = [f]);
let p = n;
for (; (p = n.nextSibling) !== r; )
p.remove();
n.after(...f);
};
return L(e, l), l(e()), o;
}
};
function P(e, t) {
let n = (...r) => r.length ? B(n, r[0]) : k(n);
return W(n, e, t);
}
var I = Object.assign(/* @__PURE__ */ Object.create(null), {
stopPropagation() {
this.skip = !0;
}
});
function W(e, t, n) {
return h(n) !== "[object Object]" && (n = {}), e[d] = {
value: t,
actions: n,
listeners: /* @__PURE__ */ new Set()
}, Object.setPrototypeOf(e[d], I), e;
}
var g = [];
function F(e) {
let t = function() {
g.push(t), e(), g.pop();
};
g.push(t), e(), g.pop();
}
function Z() {
return g[g.length - 1];
}
function k(e) {
if (!e[d])
return;
let { value: t, listeners: n } = e[d], r = Z();
return r && n.add(r), t;
}
function B(e, t) {
if (!e[d])
return;
let n = e[d];
if (n.value !== t)
return n.value = t, n.listeners.forEach((r) => r(t)), t;
}
function G(e) {
return e[d].value;
}
function L(e, t) {
return e[d].listeners.add(t);
}
function $(e, t) {
return e[d].listeners.delete(t);
}
// src/signals.js
R(T);
globalThis.dde= {
S: y,
assign: C,
classListDeclartive: q,
createElement: Q,
el: Q,
empty: X,
isSignal: x,
namespace: K,
on: _,
registerReactivity: R,
watch: F
};
})();

237
dist/dde.js vendored Normal file
View File

@ -0,0 +1,237 @@
//deka-dom-el library is available via global namespace `dde`
(()=> {
// src/helpers.js
function R(e) {
let t = typeof e;
return t !== "object" ? t : e === null ? "null" : Object.prototype.toString.call(e);
}
// src/signals-common.js
var l = {
isReactiveAtrribute(e, t) {
return !1;
},
isTextContent(e) {
return R(e) !== "[object Object]";
},
processReactiveAttribute(e, t, o, n) {
return !1;
},
reactiveElement(e, ...t) {
return document.createDocumentFragment();
}
};
function y(e, t = !0) {
return t ? Object.assign(l, e) : (Object.setPrototypeOf(e, l), e);
}
function v(e) {
return l.isPrototypeOf(e) && e !== l ? e : l;
}
// src/dom.js
var b = "html";
function q(e) {
return b = e === "svg" ? "http://www.w3.org/2000/svg" : e, {
append(t) {
return b = "html", t;
}
};
}
function z(e, t, ...o) {
let n = v(this), u;
if (e === "<>") {
if (n.isReactiveAtrribute(t))
return n.reactiveElement(t, ...o);
u = document.createDocumentFragment();
}
switch (n.isTextContent(t) && (t = { textContent: t }), !0) {
case typeof e == "function":
u = e(t || void 0);
break;
case e === "#text":
u = E(document.createTextNode(""), t);
break;
case b !== "html":
u = E(document.createElementNS(b, e), t);
break;
default:
u = E(document.createElement(e), t);
}
return o.forEach((d) => d(u)), u;
}
function E(e, ...t) {
let o = v(this);
if (!t.length)
return e;
let n = e instanceof SVGElement, u = (n ? L : A).bind(null, e, "Attribute");
return Object.entries(Object.assign({}, ...t)).forEach(function d([i, f]) {
if (o.isReactiveAtrribute(f, i) && (f = o.processReactiveAttribute(el, i, f, d)), i[0] === "=")
return u(i.slice(1), f);
if (i[0] === ".")
return w(e, i.slice(1), f);
if (typeof f == "object")
switch (i) {
case "style":
return g(f, A.bind(null, e.style, "Property"));
case "dataset":
return g(f, w.bind(null, e.dataset));
case "ariaset":
return g(f, (p, h) => u("aria-" + p, h));
case "classList":
return N(e, f);
default:
return Reflect.set(e, i, f);
}
if (/(aria|data)([A-Z])/.test(i))
return i = i.replace(/([a-z])([A-Z])/g, "$1-$2").toLowerCase(), u(i, f);
switch (i) {
case "href":
return u(i, f);
case "xlink:href":
return u(i, f, "http://www.w3.org/1999/xlink");
case "textContent":
if (!n)
break;
return e.appendChild(document.createTextNode(f));
}
return i in e && !n ? w(e, i, f) : u(i, f);
}), e;
}
function N(e, t) {
return typeof t != "object" || g(
t,
(o, n) => e.classList.toggle(o, n === -1 ? void 0 : !!n)
), e;
}
function M(e) {
return Array.from(e.children).forEach((t) => t.remove()), e;
}
function g(e, t) {
return Object.entries(e).forEach(([o, n]) => t(o, n));
}
function O(e) {
return typeof e > "u";
}
function A(e, t, o, n) {
return e[(O(n) ? "remove" : "set") + t](o, n);
}
function L(e, t, o, n, u = null) {
return e[(O(n) ? "remove" : "set") + t + "NS"](u, o, n);
}
function w(e, t, o) {
return Reflect[O(o) ? "deleteProperty" : "set"](e, t, o);
}
// src/events.js
function j(e, t, o) {
return (n) => (n.addEventListener(e, t, o), n);
}
var m = D();
j.connected = function(e, t) {
return function(n) {
m.onConnected(n, e), t && t.signal && t.signal.addEventListener("abort", () => m.offConnected(n, e));
};
};
j.disconnected = function(e, t) {
return function(n) {
m.onDisconnected(n, e), t && t.signal && t.signal.addEventListener("abort", () => m.offDisconnected(n, e));
};
};
function D() {
let e = /* @__PURE__ */ new Map(), t = !1, o = new MutationObserver(function(r) {
for (let c of r)
if (c.type === "childList") {
if (h(c.addedNodes, !0)) {
i();
continue;
}
C(c.removedNodes, !0) && i();
}
});
return {
onConnected(r, c) {
d(), u(r).connected.push(c);
},
offConnected(r, c) {
if (!e.has(r))
return;
let s = e.get(r), a = s.connected;
a.splice(a.indexOf(c), 1), n(r, s);
},
onDisconnected(r, c) {
d(), u(r).disconnected.push(c);
},
offDisconnected(r, c) {
if (!e.has(r))
return;
let s = e.get(r), a = s.disconnected;
a.splice(a.indexOf(c), 1), n(r, s);
}
};
function n(r, c) {
c.connected.length || c.disconnect.length || (e.delete(r), i());
}
function u(r) {
if (e.has(r))
return e.get(r);
let c = { connected: [], disconnected: [] };
return e.set(r, c), c;
}
function d() {
t || (t = !0, o.observe(document.body, { childList: !0, subtree: !0 }));
}
function i() {
!t || e.size || (t = !1, o.disconnect());
}
function f() {
return new Promise(function(r) {
(requestIdleCallback || requestAnimationFrame)(r);
});
}
async function p(r) {
e.size > 30 && await f();
let c = [];
if (!(r instanceof Node))
return c;
for (let s of e.keys())
s === r || !(s instanceof Node) || r.contains(s) && c.push(s);
return c;
}
function h(r, c) {
for (let s of r) {
if (c && p(s).then(h), !e.has(s))
return !1;
let a = e.get(s);
return a.connected.forEach((x) => x(s)), a.connected.length = 0, a.disconnected.length || e.delete(s), !0;
}
}
function C(r, c) {
for (let s of r) {
if (c && p(s).then(C), !e.has(s))
return !1;
let a = e.get(s);
return a.disconnected.forEach((x) => x(s)), a.connected.length = 0, a.disconnected.length = 0, e.delete(s), !0;
}
}
}
// index.js
[HTMLElement, DocumentFragment].forEach((e) => {
let { append: t } = e.prototype;
e.prototype.append = function(...o) {
return t.apply(this, o), this;
};
});
globalThis.dde= {
assign: E,
classListDeclartive: N,
createElement: z,
el: z,
empty: M,
namespace: q,
on: j,
registerReactivity: y
};
})();

349
dist/esm-with-signals.js vendored Normal file
View File

@ -0,0 +1,349 @@
// src/helpers.js
function h(e) {
let t = typeof e;
return t !== "object" ? t : e === null ? "null" : Object.prototype.toString.call(e);
}
// src/signals-common.js
var m = {
isReactiveAtrribute(e, t) {
return !1;
},
isTextContent(e) {
return h(e) !== "[object Object]";
},
processReactiveAttribute(e, t, n, r) {
return !1;
},
reactiveElement(e, ...t) {
return document.createDocumentFragment();
}
};
function R(e, t = !0) {
return t ? Object.assign(m, e) : (Object.setPrototypeOf(e, m), e);
}
function A(e) {
return m.isPrototypeOf(e) && e !== m ? e : m;
}
// src/dom.js
var E = "html";
function K(e) {
return E = e === "svg" ? "http://www.w3.org/2000/svg" : e, {
append(t) {
return E = "html", t;
}
};
}
function Q(e, t, ...n) {
let r = A(this), o;
if (e === "<>") {
if (r.isReactiveAtrribute(t))
return r.reactiveElement(t, ...n);
o = document.createDocumentFragment();
}
switch (r.isTextContent(t) && (t = { textContent: t }), !0) {
case typeof e == "function":
o = e(t || void 0);
break;
case e === "#text":
o = C(document.createTextNode(""), t);
break;
case E !== "html":
o = C(document.createElementNS(E, e), t);
break;
default:
o = C(document.createElement(e), t);
}
return n.forEach((l) => l(o)), o;
}
function C(e, ...t) {
let n = A(this);
if (!t.length)
return e;
let r = e instanceof SVGElement, o = (r ? z : D).bind(null, e, "Attribute");
return Object.entries(Object.assign({}, ...t)).forEach(function l([s, f]) {
if (n.isReactiveAtrribute(f, s) && (f = n.processReactiveAttribute(el, s, f, l)), s[0] === "=")
return o(s.slice(1), f);
if (s[0] === ".")
return S(e, s.slice(1), f);
if (typeof f == "object")
switch (s) {
case "style":
return v(f, D.bind(null, e.style, "Property"));
case "dataset":
return v(f, S.bind(null, e.dataset));
case "ariaset":
return v(f, (p, b) => o("aria-" + p, b));
case "classList":
return q(e, f);
default:
return Reflect.set(e, s, f);
}
if (/(aria|data)([A-Z])/.test(s))
return s = s.replace(/([a-z])([A-Z])/g, "$1-$2").toLowerCase(), o(s, f);
switch (s) {
case "href":
return o(s, f);
case "xlink:href":
return o(s, f, "http://www.w3.org/1999/xlink");
case "textContent":
if (!r)
break;
return e.appendChild(document.createTextNode(f));
}
return s in e && !r ? S(e, s, f) : o(s, f);
}), e;
}
function q(e, t) {
return typeof t != "object" || v(
t,
(n, r) => e.classList.toggle(n, r === -1 ? void 0 : !!r)
), e;
}
function X(e) {
return Array.from(e.children).forEach((t) => t.remove()), e;
}
function v(e, t) {
return Object.entries(e).forEach(([n, r]) => t(n, r));
}
function j(e) {
return typeof e > "u";
}
function D(e, t, n, r) {
return e[(j(r) ? "remove" : "set") + t](n, r);
}
function z(e, t, n, r, o = null) {
return e[(j(r) ? "remove" : "set") + t + "NS"](o, n, r);
}
function S(e, t, n) {
return Reflect[j(n) ? "deleteProperty" : "set"](e, t, n);
}
// src/events.js
function _(e, t, n) {
return (r) => (r.addEventListener(e, t, n), r);
}
var w = M();
_.connected = function(e, t) {
return function(r) {
w.onConnected(r, e), t && t.signal && t.signal.addEventListener("abort", () => w.offConnected(r, e));
};
};
_.disconnected = function(e, t) {
return function(r) {
w.onDisconnected(r, e), t && t.signal && t.signal.addEventListener("abort", () => w.offDisconnected(r, e));
};
};
function M() {
let e = /* @__PURE__ */ new Map(), t = !1, n = new MutationObserver(function(c) {
for (let i of c)
if (i.type === "childList") {
if (b(i.addedNodes, !0)) {
s();
continue;
}
N(i.removedNodes, !0) && s();
}
});
return {
onConnected(c, i) {
l(), o(c).connected.push(i);
},
offConnected(c, i) {
if (!e.has(c))
return;
let u = e.get(c), a = u.connected;
a.splice(a.indexOf(i), 1), r(c, u);
},
onDisconnected(c, i) {
l(), o(c).disconnected.push(i);
},
offDisconnected(c, i) {
if (!e.has(c))
return;
let u = e.get(c), a = u.disconnected;
a.splice(a.indexOf(i), 1), r(c, u);
}
};
function r(c, i) {
i.connected.length || i.disconnect.length || (e.delete(c), s());
}
function o(c) {
if (e.has(c))
return e.get(c);
let i = { connected: [], disconnected: [] };
return e.set(c, i), i;
}
function l() {
t || (t = !0, n.observe(document.body, { childList: !0, subtree: !0 }));
}
function s() {
!t || e.size || (t = !1, n.disconnect());
}
function f() {
return new Promise(function(c) {
(requestIdleCallback || requestAnimationFrame)(c);
});
}
async function p(c) {
e.size > 30 && await f();
let i = [];
if (!(c instanceof Node))
return i;
for (let u of e.keys())
u === c || !(u instanceof Node) || c.contains(u) && i.push(u);
return i;
}
function b(c, i) {
for (let u of c) {
if (i && p(u).then(b), !e.has(u))
return !1;
let a = e.get(u);
return a.connected.forEach((O) => O(u)), a.connected.length = 0, a.disconnected.length || e.delete(u), !0;
}
}
function N(c, i) {
for (let u of c) {
if (i && p(u).then(N), !e.has(u))
return !1;
let a = e.get(u);
return a.disconnected.forEach((O) => O(u)), a.connected.length = 0, a.disconnected.length = 0, e.delete(u), !0;
}
}
}
// index.js
[HTMLElement, DocumentFragment].forEach((e) => {
let { append: t } = e.prototype;
e.prototype.append = function(...n) {
return t.apply(this, n), this;
};
});
// src/signals-lib.js
var d = Symbol.for("signal");
function x(e) {
try {
return Reflect.has(e, d);
} catch {
return !1;
}
}
function y(e, t) {
if (typeof e != "function")
return P(e, t);
if (x(e))
return e;
let n = P();
return F(() => n(e())), n;
}
y.action = function(e, t, ...n) {
if (!x(e))
throw new Error(`'${e}' is not a signal!`);
let r = e[d], { actions: o } = r;
if (!o || !Reflect.has(o, t))
throw new Error(`'${e}' has no action with name '${t}'!`);
if (o[t].apply(r, n), r.skip)
return Reflect.deleteProperty(r, "skip");
r.listeners.forEach((l) => l(r.value));
};
y.on = function e(t, n, r) {
if (Array.isArray(t))
return t.forEach((o) => e(o, n, r));
L(t, n), r && r.signal && r.signal.addEventListener("abort", () => $(t, n));
};
y.clear = function(...e) {
for (let t of e)
t[d].listeners.clear(), Reflect.deleteProperty(t, d);
};
var T = {
isReactiveAtrribute(e, t) {
return x(e);
},
isTextContent(e) {
return h(e) === "string" || x(e) && h(G(e)) === "string";
},
processReactiveAttribute(e, t, n, r) {
return L(n, (o) => r([t, o])), n();
},
reactiveElement(e, t) {
let n = document.createComment("<> #reactive"), r = document.createComment("</> #reactive"), o = document.createDocumentFragment();
o.append(n, r);
let l = (s) => {
if (!n.parentNode || !r.parentNode)
return $(e, l);
let f = t(s);
Array.isArray(f) || (f = [f]);
let p = n;
for (; (p = n.nextSibling) !== r; )
p.remove();
n.after(...f);
};
return L(e, l), l(e()), o;
}
};
function P(e, t) {
let n = (...r) => r.length ? B(n, r[0]) : k(n);
return W(n, e, t);
}
var I = Object.assign(/* @__PURE__ */ Object.create(null), {
stopPropagation() {
this.skip = !0;
}
});
function W(e, t, n) {
return h(n) !== "[object Object]" && (n = {}), e[d] = {
value: t,
actions: n,
listeners: /* @__PURE__ */ new Set()
}, Object.setPrototypeOf(e[d], I), e;
}
var g = [];
function F(e) {
let t = function() {
g.push(t), e(), g.pop();
};
g.push(t), e(), g.pop();
}
function Z() {
return g[g.length - 1];
}
function k(e) {
if (!e[d])
return;
let { value: t, listeners: n } = e[d], r = Z();
return r && n.add(r), t;
}
function B(e, t) {
if (!e[d])
return;
let n = e[d];
if (n.value !== t)
return n.value = t, n.listeners.forEach((r) => r(t)), t;
}
function G(e) {
return e[d].value;
}
function L(e, t) {
return e[d].listeners.add(t);
}
function $(e, t) {
return e[d].listeners.delete(t);
}
// src/signals.js
R(T);
export {
y as S,
C as assign,
q as classListDeclartive,
Q as createElement,
Q as el,
X as empty,
x as isSignal,
K as namespace,
_ as on,
R as registerReactivity,
F as watch
};

232
dist/esm.js vendored Normal file
View File

@ -0,0 +1,232 @@
// src/helpers.js
function R(e) {
let t = typeof e;
return t !== "object" ? t : e === null ? "null" : Object.prototype.toString.call(e);
}
// src/signals-common.js
var l = {
isReactiveAtrribute(e, t) {
return !1;
},
isTextContent(e) {
return R(e) !== "[object Object]";
},
processReactiveAttribute(e, t, o, n) {
return !1;
},
reactiveElement(e, ...t) {
return document.createDocumentFragment();
}
};
function y(e, t = !0) {
return t ? Object.assign(l, e) : (Object.setPrototypeOf(e, l), e);
}
function v(e) {
return l.isPrototypeOf(e) && e !== l ? e : l;
}
// src/dom.js
var b = "html";
function q(e) {
return b = e === "svg" ? "http://www.w3.org/2000/svg" : e, {
append(t) {
return b = "html", t;
}
};
}
function z(e, t, ...o) {
let n = v(this), u;
if (e === "<>") {
if (n.isReactiveAtrribute(t))
return n.reactiveElement(t, ...o);
u = document.createDocumentFragment();
}
switch (n.isTextContent(t) && (t = { textContent: t }), !0) {
case typeof e == "function":
u = e(t || void 0);
break;
case e === "#text":
u = E(document.createTextNode(""), t);
break;
case b !== "html":
u = E(document.createElementNS(b, e), t);
break;
default:
u = E(document.createElement(e), t);
}
return o.forEach((d) => d(u)), u;
}
function E(e, ...t) {
let o = v(this);
if (!t.length)
return e;
let n = e instanceof SVGElement, u = (n ? L : A).bind(null, e, "Attribute");
return Object.entries(Object.assign({}, ...t)).forEach(function d([i, f]) {
if (o.isReactiveAtrribute(f, i) && (f = o.processReactiveAttribute(el, i, f, d)), i[0] === "=")
return u(i.slice(1), f);
if (i[0] === ".")
return w(e, i.slice(1), f);
if (typeof f == "object")
switch (i) {
case "style":
return g(f, A.bind(null, e.style, "Property"));
case "dataset":
return g(f, w.bind(null, e.dataset));
case "ariaset":
return g(f, (p, h) => u("aria-" + p, h));
case "classList":
return N(e, f);
default:
return Reflect.set(e, i, f);
}
if (/(aria|data)([A-Z])/.test(i))
return i = i.replace(/([a-z])([A-Z])/g, "$1-$2").toLowerCase(), u(i, f);
switch (i) {
case "href":
return u(i, f);
case "xlink:href":
return u(i, f, "http://www.w3.org/1999/xlink");
case "textContent":
if (!n)
break;
return e.appendChild(document.createTextNode(f));
}
return i in e && !n ? w(e, i, f) : u(i, f);
}), e;
}
function N(e, t) {
return typeof t != "object" || g(
t,
(o, n) => e.classList.toggle(o, n === -1 ? void 0 : !!n)
), e;
}
function M(e) {
return Array.from(e.children).forEach((t) => t.remove()), e;
}
function g(e, t) {
return Object.entries(e).forEach(([o, n]) => t(o, n));
}
function O(e) {
return typeof e > "u";
}
function A(e, t, o, n) {
return e[(O(n) ? "remove" : "set") + t](o, n);
}
function L(e, t, o, n, u = null) {
return e[(O(n) ? "remove" : "set") + t + "NS"](u, o, n);
}
function w(e, t, o) {
return Reflect[O(o) ? "deleteProperty" : "set"](e, t, o);
}
// src/events.js
function j(e, t, o) {
return (n) => (n.addEventListener(e, t, o), n);
}
var m = D();
j.connected = function(e, t) {
return function(n) {
m.onConnected(n, e), t && t.signal && t.signal.addEventListener("abort", () => m.offConnected(n, e));
};
};
j.disconnected = function(e, t) {
return function(n) {
m.onDisconnected(n, e), t && t.signal && t.signal.addEventListener("abort", () => m.offDisconnected(n, e));
};
};
function D() {
let e = /* @__PURE__ */ new Map(), t = !1, o = new MutationObserver(function(r) {
for (let c of r)
if (c.type === "childList") {
if (h(c.addedNodes, !0)) {
i();
continue;
}
C(c.removedNodes, !0) && i();
}
});
return {
onConnected(r, c) {
d(), u(r).connected.push(c);
},
offConnected(r, c) {
if (!e.has(r))
return;
let s = e.get(r), a = s.connected;
a.splice(a.indexOf(c), 1), n(r, s);
},
onDisconnected(r, c) {
d(), u(r).disconnected.push(c);
},
offDisconnected(r, c) {
if (!e.has(r))
return;
let s = e.get(r), a = s.disconnected;
a.splice(a.indexOf(c), 1), n(r, s);
}
};
function n(r, c) {
c.connected.length || c.disconnect.length || (e.delete(r), i());
}
function u(r) {
if (e.has(r))
return e.get(r);
let c = { connected: [], disconnected: [] };
return e.set(r, c), c;
}
function d() {
t || (t = !0, o.observe(document.body, { childList: !0, subtree: !0 }));
}
function i() {
!t || e.size || (t = !1, o.disconnect());
}
function f() {
return new Promise(function(r) {
(requestIdleCallback || requestAnimationFrame)(r);
});
}
async function p(r) {
e.size > 30 && await f();
let c = [];
if (!(r instanceof Node))
return c;
for (let s of e.keys())
s === r || !(s instanceof Node) || r.contains(s) && c.push(s);
return c;
}
function h(r, c) {
for (let s of r) {
if (c && p(s).then(h), !e.has(s))
return !1;
let a = e.get(s);
return a.connected.forEach((x) => x(s)), a.connected.length = 0, a.disconnected.length || e.delete(s), !0;
}
}
function C(r, c) {
for (let s of r) {
if (c && p(s).then(C), !e.has(s))
return !1;
let a = e.get(s);
return a.disconnected.forEach((x) => x(s)), a.connected.length = 0, a.disconnected.length = 0, e.delete(s), !0;
}
}
}
// index.js
[HTMLElement, DocumentFragment].forEach((e) => {
let { append: t } = e.prototype;
e.prototype.append = function(...o) {
return t.apply(this, o), this;
};
});
export {
E as assign,
N as classListDeclartive,
z as createElement,
z as el,
M as empty,
q as namespace,
j as on,
y as registerReactivity
};

2
index-with-signals.js Normal file
View File

@ -0,0 +1,2 @@
export * from "./index.js";
export * from "./src/signals.js";

244
index.d.ts vendored
View File

@ -1,15 +1,14 @@
/** import { Signal } from "./src/signals";
* @private //TODO?
*/ declare global {
type T_DOM_HETNM= HTMLElementTagNameMap & SVGElementTagNameMap & { type ddeFires<T extends string[]>= ( (...a: any[])=> any ) & { events: T };
'<>': DocumentFragment, type ddeSignal<T, A>= Signal<T, A>;
'': HTMLElement,
'zzz_text': Text
} }
/** type ElementTagNameMap= HTMLElementTagNameMap & SVGElementTagNameMap & {
* @private '#text': Text
*/ }
type T_DOM_ATTRS_MODIFIED= { type Element= ElementTagNameMap[keyof ElementTagNameMap];
type AttrsModified= {
/** /**
* In fact argumen for `*.setAttribute("style", *)`. * In fact argumen for `*.setAttribute("style", *)`.
*/ */
@ -17,7 +16,11 @@ type T_DOM_ATTRS_MODIFIED= {
/** /**
* Provide option to add/remove/toggle CSS clasess (index of object) using 1/0/-1. In fact `el.classList.toggle(class_name)` for `-1` and `el.classList.toggle(class_name, Boolean(...))` for others. * Provide option to add/remove/toggle CSS clasess (index of object) using 1/0/-1. In fact `el.classList.toggle(class_name)` for `-1` and `el.classList.toggle(class_name, Boolean(...))` for others.
*/ */
classList: Record<string,-1|0|1> classList: Record<string,-1|0|1>,
/**
* Sets `aria-*` simiraly to `dataset`
* */
ariaset: Record<string,string>,
} }
/** /**
* Just element attributtes * Just element attributtes
@ -27,53 +30,172 @@ type T_DOM_ATTRS_MODIFIED= {
* There is added support for `data[A-Z].*`/`aria[A-Z].*` to be converted to the kebab-case alternatives. * There is added support for `data[A-Z].*`/`aria[A-Z].*` to be converted to the kebab-case alternatives.
* @private * @private
*/ */
type T_DOM_ATTRS<T extends keyof T_DOM_HETNM | T_DOM_HETNM[keyof T_DOM_HETNM]>= type ElementAttributes<T extends keyof ElementTagNameMap | ElementTagNameMap[keyof ElementTagNameMap]>=
T extends keyof T_DOM_HETNM ? T extends keyof ElementTagNameMap ?
Omit<T_DOM_HETNM[T],"classList"> & T_DOM_ATTRS_MODIFIED : Omit<ElementTagNameMap[T],"classList"> & AttrsModified :
Omit<T,"classList"> & T_DOM_ATTRS_MODIFIED; Omit<T,"classList"> & AttrsModified;
/** export function assign<El extends Element>(element: El, ...attrs_array: ElementAttributes<El>[]): El
* Procedure for merging object into the element properties.
* Very simple example: `$dom.assign(document.body, { className: "test" });` is equivalent to `document.body.className= "test";`.
* It is not deep copy in general, but it supports `style`, `style_vars` and `dataset` objects (see below).
*
* **#1: All together**
* ```javascript
* const el= document.body;
* const onclick= function(){ console.log(this.dataset.js_param); };
* $dom.assign(el, { textContent: "BODY", style: "color: red;", dataset: { js_param: "CLICKED" }, onclick });
* //result HTML: <body style="color: red;" data-js_param="CLICKED">BODY</body>
* //console output on click: "CLICKED"
* $dom.assign(el, { style: { color: "green" } });
* //result HTML: <body style="color: green;" data-js_param="CLICKED">BODY</body>
* //console output on click: "CLICKED"
* ```
*
* **`\*.classList.toggle`**
* ```javascript
* const el= document.body;
* $dom.assign(el, { classList: { testClass: -1 } });
* //result HTML: <body class="testClass">…</body>
* $dom.assign(el, { classList: { testClass: -1 } });
* //result HTML: <body class="">…</body>
*
* $dom.assign(el, { classList: { testClass: true } });//or 1
* //result HTML: <body class="testClass">…</body>
* $dom.assign(el, { classList: { testClass: false } });//or 0
* //result HTML: <body class="">…</body>
* //...
* ```
*
* **#3 Links and images**
* ```javascript
* $dom.assign(A_ELEMENT, { href: "www.google.com" });//=> <a href="www.google.com" …
* $dom.assign(IMG_ELEMENT, { src: "image.png" });//=> <img src="image.png" …
*
* **#4 data\* and aria\***
* $dom.assign(el, { ariaLabel: "The aria-label", dataExample: "data-example" });//=> <body aria-label="The aria-label" data-example="data-example">
* ```
* @category Public
* @version 2.0.0
*/
export function assign<EL extends HTMLElement>(element: EL, ...attrs_array: T_DOM_ATTRS<EL>[]): EL
export function el<TAG extends keyof T_DOM_HETNM>(tag_name: TAG, attrs: T_DOM_ATTRS<T_DOM_HETNM[TAG]>): T_DOM_HETNM[TAG] type ElementExtender<El extends Element>= (element: El)=> El;
type TagNameFragment= "<>";
export function el<TAG extends keyof ElementTagNameMap>(
tag_name: TAG,
attrs?: ElementAttributes<ElementTagNameMap[TAG]>,
...extenders: ElementExtender<ElementTagNameMap[TAG]>[]
): ElementTagNameMap[TAG]
export function el<T>(
tag_name: TagNameFragment,
signal?: Signal<T, any>,
cb?: (a: T)=> HTMLElement | HTMLElement[]
): DocumentFragment
export function el<T extends (...a: any)=> Element>(
fComponent: T,
attrs?: Parameters<T> & ElementAttributes<ReturnType<T>>,
...extenders: ElementExtender<ReturnType<T>>[]
): ReturnType<T>
interface On{
<
EE extends ElementExtender<Element>,
El extends ( EE extends ElementExtender<infer El> ? El : never ),
Event extends keyof DocumentEventMap>(
type: Event,
listener: (this: El, ev: DocumentEventMap[Event]) => any,
options?: AddEventListenerOptions
) : EE;
connected<
EE extends ElementExtender<Element>,
El extends ( EE extends ElementExtender<infer El> ? El : never )
>(
listener: (el: El) => any,
options?: AddEventListenerOptions
) : EE;
disconnected<
EE extends ElementExtender<Element>,
El extends ( EE extends ElementExtender<infer El> ? El : never )
>(
listener: (el: El) => any,
options?: AddEventListenerOptions
) : EE;
}
export const on: On;
//TODO?
export type Fires<T extends string[]>= ( (...a: any[])=> any ) & { events: T };
//TODO for SVG
declare global{
interface HTMLDivElement{ append(...nodes: (Node | string)[]): HTMLDivElement; }
interface HTMLAnchorElement{ append(...nodes: (Node | string)[]): HTMLAnchorElement; }
interface HTMLElement{ append(...nodes: (Node | string)[]): HTMLElement; }
interface HTMLElement{ append(...nodes: (Node | string)[]): HTMLElement; }
interface HTMLAreaElement{ append(...nodes: (Node | string)[]): HTMLAreaElement; }
interface HTMLElement{ append(...nodes: (Node | string)[]): HTMLElement; }
interface HTMLElement{ append(...nodes: (Node | string)[]): HTMLElement; }
interface HTMLAudioElement{ append(...nodes: (Node | string)[]): HTMLAudioElement; }
interface HTMLElement{ append(...nodes: (Node | string)[]): HTMLElement; }
interface HTMLBaseElement{ append(...nodes: (Node | string)[]): HTMLBaseElement; }
interface HTMLElement{ append(...nodes: (Node | string)[]): HTMLElement; }
interface HTMLElement{ append(...nodes: (Node | string)[]): HTMLElement; }
interface HTMLQuoteElement{ append(...nodes: (Node | string)[]): HTMLQuoteElement; }
interface HTMLBodyElement{ append(...nodes: (Node | string)[]): HTMLBodyElement; }
interface HTMLBRElement{ append(...nodes: (Node | string)[]): HTMLBRElement; }
interface HTMLButtonElement{ append(...nodes: (Node | string)[]): HTMLButtonElement; }
interface HTMLCanvasElement{ append(...nodes: (Node | string)[]): HTMLCanvasElement; }
interface HTMLTableCaptionElement{ append(...nodes: (Node | string)[]): HTMLTableCaptionElement; }
interface HTMLElement{ append(...nodes: (Node | string)[]): HTMLElement; }
interface HTMLElement{ append(...nodes: (Node | string)[]): HTMLElement; }
interface HTMLTableColElement{ append(...nodes: (Node | string)[]): HTMLTableColElement; }
interface HTMLTableColElement{ append(...nodes: (Node | string)[]): HTMLTableColElement; }
interface HTMLDataElement{ append(...nodes: (Node | string)[]): HTMLDataElement; }
interface HTMLDataListElement{ append(...nodes: (Node | string)[]): HTMLDataListElement; }
interface HTMLElement{ append(...nodes: (Node | string)[]): HTMLElement; }
interface HTMLModElement{ append(...nodes: (Node | string)[]): HTMLModElement; }
interface HTMLDetailsElement{ append(...nodes: (Node | string)[]): HTMLDetailsElement; }
interface HTMLElement{ append(...nodes: (Node | string)[]): HTMLElement; }
interface HTMLDialogElement{ append(...nodes: (Node | string)[]): HTMLDialogElement; }
interface HTMLDivElement{ append(...nodes: (Node | string)[]): HTMLDivElement; }
interface HTMLDListElement{ append(...nodes: (Node | string)[]): HTMLDListElement; }
interface HTMLElement{ append(...nodes: (Node | string)[]): HTMLElement; }
interface HTMLElement{ append(...nodes: (Node | string)[]): HTMLElement; }
interface HTMLEmbedElement{ append(...nodes: (Node | string)[]): HTMLEmbedElement; }
interface HTMLFieldSetElement{ append(...nodes: (Node | string)[]): HTMLFieldSetElement; }
interface HTMLElement{ append(...nodes: (Node | string)[]): HTMLElement; }
interface HTMLElement{ append(...nodes: (Node | string)[]): HTMLElement; }
interface HTMLElement{ append(...nodes: (Node | string)[]): HTMLElement; }
interface HTMLFormElement{ append(...nodes: (Node | string)[]): HTMLFormElement; }
interface HTMLHeadingElement{ append(...nodes: (Node | string)[]): HTMLHeadingElement; }
interface HTMLHeadingElement{ append(...nodes: (Node | string)[]): HTMLHeadingElement; }
interface HTMLHeadingElement{ append(...nodes: (Node | string)[]): HTMLHeadingElement; }
interface HTMLHeadingElement{ append(...nodes: (Node | string)[]): HTMLHeadingElement; }
interface HTMLHeadingElement{ append(...nodes: (Node | string)[]): HTMLHeadingElement; }
interface HTMLHeadingElement{ append(...nodes: (Node | string)[]): HTMLHeadingElement; }
interface HTMLHeadElement{ append(...nodes: (Node | string)[]): HTMLHeadElement; }
interface HTMLElement{ append(...nodes: (Node | string)[]): HTMLElement; }
interface HTMLElement{ append(...nodes: (Node | string)[]): HTMLElement; }
interface HTMLHRElement{ append(...nodes: (Node | string)[]): HTMLHRElement; }
interface HTMLHtmlElement{ append(...nodes: (Node | string)[]): HTMLHtmlElement; }
interface HTMLElement{ append(...nodes: (Node | string)[]): HTMLElement; }
interface HTMLIFrameElement{ append(...nodes: (Node | string)[]): HTMLIFrameElement; }
interface HTMLImageElement{ append(...nodes: (Node | string)[]): HTMLImageElement; }
interface HTMLInputElement{ append(...nodes: (Node | string)[]): HTMLInputElement; }
interface HTMLModElement{ append(...nodes: (Node | string)[]): HTMLModElement; }
interface HTMLElement{ append(...nodes: (Node | string)[]): HTMLElement; }
interface HTMLLabelElement{ append(...nodes: (Node | string)[]): HTMLLabelElement; }
interface HTMLLegendElement{ append(...nodes: (Node | string)[]): HTMLLegendElement; }
interface HTMLLIElement{ append(...nodes: (Node | string)[]): HTMLLIElement; }
interface HTMLLinkElement{ append(...nodes: (Node | string)[]): HTMLLinkElement; }
interface HTMLElement{ append(...nodes: (Node | string)[]): HTMLElement; }
interface HTMLMapElement{ append(...nodes: (Node | string)[]): HTMLMapElement; }
interface HTMLElement{ append(...nodes: (Node | string)[]): HTMLElement; }
interface HTMLMenuElement{ append(...nodes: (Node | string)[]): HTMLMenuElement; }
interface HTMLMetaElement{ append(...nodes: (Node | string)[]): HTMLMetaElement; }
interface HTMLMeterElement{ append(...nodes: (Node | string)[]): HTMLMeterElement; }
interface HTMLElement{ append(...nodes: (Node | string)[]): HTMLElement; }
interface HTMLElement{ append(...nodes: (Node | string)[]): HTMLElement; }
interface HTMLObjectElement{ append(...nodes: (Node | string)[]): HTMLObjectElement; }
interface HTMLOListElement{ append(...nodes: (Node | string)[]): HTMLOListElement; }
interface HTMLOptGroupElement{ append(...nodes: (Node | string)[]): HTMLOptGroupElement; }
interface HTMLOptionElement{ append(...nodes: (Node | string)[]): HTMLOptionElement; }
interface HTMLOutputElement{ append(...nodes: (Node | string)[]): HTMLOutputElement; }
interface HTMLParagraphElement{ append(...nodes: (Node | string)[]): HTMLParagraphElement; }
interface HTMLPictureElement{ append(...nodes: (Node | string)[]): HTMLPictureElement; }
interface HTMLPreElement{ append(...nodes: (Node | string)[]): HTMLPreElement; }
interface HTMLProgressElement{ append(...nodes: (Node | string)[]): HTMLProgressElement; }
interface HTMLQuoteElement{ append(...nodes: (Node | string)[]): HTMLQuoteElement; }
interface HTMLElement{ append(...nodes: (Node | string)[]): HTMLElement; }
interface HTMLElement{ append(...nodes: (Node | string)[]): HTMLElement; }
interface HTMLElement{ append(...nodes: (Node | string)[]): HTMLElement; }
interface HTMLElement{ append(...nodes: (Node | string)[]): HTMLElement; }
interface HTMLElement{ append(...nodes: (Node | string)[]): HTMLElement; }
interface HTMLScriptElement{ append(...nodes: (Node | string)[]): HTMLScriptElement; }
interface HTMLElement{ append(...nodes: (Node | string)[]): HTMLElement; }
interface HTMLSelectElement{ append(...nodes: (Node | string)[]): HTMLSelectElement; }
interface HTMLSlotElement{ append(...nodes: (Node | string)[]): HTMLSlotElement; }
interface HTMLElement{ append(...nodes: (Node | string)[]): HTMLElement; }
interface HTMLSourceElement{ append(...nodes: (Node | string)[]): HTMLSourceElement; }
interface HTMLSpanElement{ append(...nodes: (Node | string)[]): HTMLSpanElement; }
interface HTMLElement{ append(...nodes: (Node | string)[]): HTMLElement; }
interface HTMLStyleElement{ append(...nodes: (Node | string)[]): HTMLStyleElement; }
interface HTMLElement{ append(...nodes: (Node | string)[]): HTMLElement; }
interface HTMLElement{ append(...nodes: (Node | string)[]): HTMLElement; }
interface HTMLElement{ append(...nodes: (Node | string)[]): HTMLElement; }
interface HTMLTableElement{ append(...nodes: (Node | string)[]): HTMLTableElement; }
interface HTMLTableSectionElement{ append(...nodes: (Node | string)[]): HTMLTableSectionElement; }
interface HTMLTableCellElement{ append(...nodes: (Node | string)[]): HTMLTableCellElement; }
interface HTMLTemplateElement{ append(...nodes: (Node | string)[]): HTMLTemplateElement; }
interface HTMLTextAreaElement{ append(...nodes: (Node | string)[]): HTMLTextAreaElement; }
interface HTMLTableSectionElement{ append(...nodes: (Node | string)[]): HTMLTableSectionElement; }
interface HTMLTableCellElement{ append(...nodes: (Node | string)[]): HTMLTableCellElement; }
interface HTMLTableSectionElement{ append(...nodes: (Node | string)[]): HTMLTableSectionElement; }
interface HTMLTimeElement{ append(...nodes: (Node | string)[]): HTMLTimeElement; }
interface HTMLTitleElement{ append(...nodes: (Node | string)[]): HTMLTitleElement; }
interface HTMLTableRowElement{ append(...nodes: (Node | string)[]): HTMLTableRowElement; }
interface HTMLTrackElement{ append(...nodes: (Node | string)[]): HTMLTrackElement; }
interface HTMLElement{ append(...nodes: (Node | string)[]): HTMLElement; }
interface HTMLUListElement{ append(...nodes: (Node | string)[]): HTMLUListElement; }
interface HTMLElement{ append(...nodes: (Node | string)[]): HTMLElement; }
interface HTMLVideoElement{ append(...nodes: (Node | string)[]): HTMLVideoElement; }
interface HTMLElement{ append(...nodes: (Node | string)[]): HTMLElement; }
interface DocumentFragment{ append(...nodes: (Node | string)[]): DocumentFragment; }
}

1981
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

88
package.json Normal file
View File

@ -0,0 +1,88 @@
{
"name": "deka-dom-el",
"version": "0.1.0",
"description": "A low-code library that simplifies the creation of native DOM elements/components using small wrappers and tweaks.",
"author": "Jan Andrle <andrle.jan@centrum.cz>",
"license": "MIT",
"homepage": "https://gitea.jaandrle.cz/jaandrle/deka-dom-el",
"repository": {
"type": "git",
"url": "git@jaandrle.cz:jaandrle/deka-dom-el.git"
},
"bugs": {
"url": "https://gitea.jaandrle.cz/jaandrle/deka-dom-el/issues"
},
"main": "index.js",
"types": "./index.d.ts",
"exports": {
".": {
"import": "./index.js"
},
"./signals": {
"import": "./src/signals.js"
},
"./signals-lib": {
"import": "./src/signals-lib.js"
}
},
"typesVersions": {
"*": {
".": [
"./index.d.ts"
],
"./signals": [
"./src/signals.d.ts"
],
"./signals-lib": [
"./src/signals.d.ts"
]
}
},
"files": [
"index.js",
"index.d.ts",
"src"
],
"engines": {
"node": ">=18"
},
"jshintConfig": {
"esversion": 6,
"node": "true",
"undef": "true",
"latedef": "true",
"maxparams": 4,
"maxdepth": 3,
"maxcomplexity": 19
},
"size-limit": [
{
"path": "./index.js",
"limit": "10 kB",
"gzip": false
},
{
"path": "./index-with-signals.js",
"limit": "10 kB",
"gzip": false
}
],
"modifyEsbuildConfig": {
"platform": "browser"
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [
"dom",
"javascript",
"low-code",
"typescript"
],
"devDependencies": {
"@size-limit/preset-small-lib": "^8.2.6",
"esbuild": "^0.19.2",
"nodejsscript": "github:jaandrle/nodejsscript#dev-v1",
"size-limit-node-esbuild": "^0.2.0"
}
}

View File

@ -8,13 +8,15 @@ export function namespace(namespace){
}; };
} }
export function createElement(tag, attributes, ...connect){ export function createElement(tag, attributes, ...connect){
const s= signals(this);
let el; let el;
//TODO Array.isArray(tag) ⇒ set key (cache els)
if("<>"===tag){ if("<>"===tag){
if(signals.isReactiveAtrribute(attributes)) if(s.isReactiveAtrribute(attributes))
return signals.reactiveElement(attributes, ...connect); return s.reactiveElement(attributes, ...connect);
el= document.createDocumentFragment(); el= document.createDocumentFragment();
} }
if(signals.isTextContent(attributes)) if(s.isTextContent(attributes))
attributes= { textContent: attributes }; attributes= { textContent: attributes };
switch(true){ switch(true){
case typeof tag==="function": el= tag(attributes || undefined); break; case typeof tag==="function": el= tag(attributes || undefined); break;
@ -27,16 +29,19 @@ export function createElement(tag, attributes, ...connect){
} }
export { createElement as el }; export { createElement as el };
const prop_cache= new Map();
export function assign(element, ...attributes){ export function assign(element, ...attributes){
const s= signals(this);
if(!attributes.length) return element; if(!attributes.length) return element;
const is_svg= element instanceof SVGElement; const is_svg= element instanceof SVGElement;
const setRemoveAttr= (is_svg ? setRemoveNS : setRemove).bind(null, element, "Attribute"); const setRemoveAttr= (is_svg ? setRemoveNS : setRemove).bind(null, element, "Attribute");
Object.entries(Object.assign({}, ...attributes)).forEach(function assignNth([ key, attr ]){ Object.entries(Object.assign({}, ...attributes)).forEach(function assignNth([ key, attr ]){
if(signals.isReactiveAtrribute(attr, key)) if(s.isReactiveAtrribute(attr, key))
attr= signals.process(key, attr, assignNth); attr= s.processReactiveAttribute(el, key, attr, assignNth);
if(key[0]==="=") return setRemoveAttr(key.slice(1), attr); const [ k ]= key;
if(key[0]===".") return setDelete(element, key.slice(1), attr); if("="===k) return setRemoveAttr(key.slice(1), attr);
if("."===k) return setDelete(element, key.slice(1), attr);
if(typeof attr === "object"){ if(typeof attr === "object"){
switch(key){ switch(key){
case "style": return forEachEntries(attr, setRemove.bind(null, element.style, "Property")) case "style": return forEachEntries(attr, setRemove.bind(null, element.style, "Property"))
@ -51,17 +56,13 @@ export function assign(element, ...attributes){
return setRemoveAttr(key, attr); return setRemoveAttr(key, attr);
} }
switch(key){ switch(key){
case "href" || "src" || "style":
return setRemoveAttr(key, attr);
case "xlink:href": case "xlink:href":
return setRemoveAttr(key, attr, "http://www.w3.org/1999/xlink"); return setRemoveAttr(key, attr, "http://www.w3.org/1999/xlink");
case "textContent" || "innerText": case "textContent" || "innerText":
if(!is_svg) break; if(!is_svg) break;
return element.appendChild(document.createTextNode(attr)); return element.appendChild(document.createTextNode(attr));
} }
if(key in element && !is_svg) return isPropSetter(element, key) ? setDelete(element, key, attr) : setRemoveAttr(key, attr);
return setDelete(element, key, attr);
return setRemoveAttr(key, attr);
}); });
return element; return element;
} }
@ -73,8 +74,24 @@ export function classListDeclartive(element, toggle){
element.classList.toggle(class_name, val===-1 ? undefined : Boolean(val))) element.classList.toggle(class_name, val===-1 ? undefined : Boolean(val)))
return element; return element;
} }
export function empty(el){
export function empty(el){ Array.from(el.children).forEach(el=> el.remove()); return el; } Array.from(el.children).forEach(el=> el.remove());
return el;
}
function isPropSetter(el, key){
const cache_key= el.nodeName+","+key;
if(prop_cache.has(cache_key)) return prop_cache.get(cache_key);
const des= getPropDescriptor(el, key);
const is_set= !isUndef(des.set);
prop_cache.set(cache_key, is_set);
return is_set;
}
function getPropDescriptor(p, key){
p= Object.getPrototypeOf(p);
if(!p) return {};
const des= Object.getOwnPropertyDescriptor(p, key);
return des ? des : getPropDescriptor(p, key);
}
function forEachEntries(obj, cb){ return Object.entries(obj).forEach(([ key, val ])=> cb(key, val)); } function forEachEntries(obj, cb){ return Object.entries(obj).forEach(([ key, val ])=> cb(key, val)); }
function isUndef(value){ return typeof value==="undefined"; } function isUndef(value){ return typeof value==="undefined"; }

View File

@ -1,37 +1,25 @@
import { signals } from './signals-common.js';
export { registerReactivity } from './signals-common.js'; export { registerReactivity } from './signals-common.js';
export function on(event, listener, options){ export function on(event, listener, options){
if(!signals.isReactiveAtrribute(event)) return element=> {
return element=> element.addEventListener(event, listener, options); element.addEventListener(event, listener, options);
//TODO cleanup when signal removed (also TODO) return element;
if(options && options.signal) };
options.signal.addEventListener("abort", ()=> signals.off(event, listener));
return signals.on(event, listener);
}
export function off(){//TODO is needed?
const abort= new AbortController();
return new Proxy(()=> abort.abort(), {
get(_, p){ return Reflect.get(abort, p); },
ownKeys(){ return [ "signal" ]; }
})
}
export function dispatch(event, detail){
if(typeof event === "string")
event= typeof detail==="undefined" ? new Event(event) : new CustomEvent(event, { detail });
return element=> element.dispatchEvent(event);
} }
const connections_changes= connectionsChangesObserverConstructor(); const connections_changes= connectionsChangesObserverConstructor();
//TODO remove listener(s) options on.connected= function(listener, options){
on.connected= function(listener){
return function registerElement(element){ return function registerElement(element){
connections_changes.onConnected(element, listener); connections_changes.onConnected(element, listener);
if(options && options.signal)
options.signal.addEventListener("abort", ()=> connections_changes.offConnected(element, listener));
}; };
}; };
on.disconnected= function(listener){ on.disconnected= function(listener, options){
return function registerElement(element){ return function registerElement(element){
connections_changes.onDisconnected(element, listener); connections_changes.onDisconnected(element, listener);
if(options && options.signal)
options.signal.addEventListener("abort", ()=> connections_changes.offDisconnected(element, listener));
}; };
}; };

View File

@ -1,12 +1,15 @@
import { typeOf } from './helpers.js'; import { typeOf } from './helpers.js';
export const signals= { export const signals_global= {
isReactiveAtrribute(attr, key){ return false; }, isReactiveAtrribute(attr, key){ return false; },
isTextContent(attributes){ return typeOf(attributes)!=="[object Object]"; }, isTextContent(attributes){ return typeOf(attributes)!=="[object Object]"; },
process(key, attr, assignNth){ return false; }, processReactiveAttribute(el, key, attr, assignNth){ return false; },
on(signal, listener){ return false; },
off(signal, listener){ return false; },
reactiveElement(attributes, ...connect){ return document.createDocumentFragment(); } reactiveElement(attributes, ...connect){ return document.createDocumentFragment(); }
}; };
export function registerReactivity(def){ export function registerReactivity(def, global= true){
return Object.assign(signals, def); if(global) return Object.assign(signals_global, def);
Object.setPrototypeOf(def, signals_global);
return def;
}
export function signals(_this){
return signals_global.isPrototypeOf(_this) && _this!==signals_global ? _this : signals_global;
} }

131
src/signals-lib.js Normal file
View File

@ -0,0 +1,131 @@
export const mark= Symbol.for("signal");
export function isSignal(candidate){
try{ return Reflect.has(candidate, mark); }
catch(e){ return false; }
}
export function S(value, actions){
if(typeof value!=="function")
return create(value, actions);
if(isSignal(value)) return value;
const out= create();
watch(()=> out(value()));
return out;
}
S.action= function(signal, name, ...a){
if(!isSignal(signal))
throw new Error(`'${signal}' is not a signal!`);
const s= signal[mark], { actions }= s;
if(!actions || !Reflect.has(actions, name))
throw new Error(`'${signal}' has no action with name '${name}'!`);
actions[name].apply(s, a);
if(s.skip) return Reflect.deleteProperty(s, "skip");
s.listeners.forEach(l=> l(s.value));
};
S.on= function on(signals, listener, options){
if(Array.isArray(signals)) return signals.forEach(s=> on(s, listener, options));
addSignalListener(signals, listener);
if(options && options.signal)
options.signal.addEventListener("abort", ()=> removeSignalListener(signals, listener));
//TODO cleanup when signal removed (also TODO)
}
S.clear= function(...signals){
for(const signal of signals){
signal[mark].listeners.clear();
Reflect.deleteProperty(signal, mark);
}
};
import { typeOf } from './helpers.js';
export const signals_config= {
isReactiveAtrribute(attr, key){ return isSignal(attr); },
isTextContent(attributes){
return typeOf(attributes)==="string" || ( isSignal(attributes) && typeOf(valueOfSignal(attributes))==="string" );
},
processReactiveAttribute(_, key, attrS, assignNth){
addSignalListener(attrS, attr=> assignNth([ key, attr ]));
return attrS();
},
reactiveElement(signal, map){
const mark_start= document.createComment("<> #reactive");
const mark_end= document.createComment("</> #reactive");
const out= document.createDocumentFragment();
out.append(mark_start, mark_end);
const toEls= v=> {
if(!mark_start.parentNode || !mark_end.parentNode)
return removeSignalListener(signal, toEls);
let els= map(v);
if(!Array.isArray(els))
els= [ els ];
let el_r= mark_start;
while(( el_r= mark_start.nextSibling ) !== mark_end)
el_r.remove();
mark_start.after(...els);
};
addSignalListener(signal, toEls);
toEls(signal());
return out;
}
};
function create(value, actions){
const signal= (...value)=>
value.length ? write(signal, value[0]) : read(signal);
return toSignal(signal, value, actions);
}
const protoSigal= Object.assign(Object.create(null), {
stopPropagation(){
this.skip= true;
}
});
function toSignal(signal, value, actions){
if(typeOf(actions)!=="[object Object]")
actions= {};
signal[mark]= {
value, actions,
listeners: new Set(),
};
Object.setPrototypeOf(signal[mark], protoSigal);
return signal;
}
const stack_watch= [];
export function watch(context){
const contextReWatch= function(){
stack_watch.push(contextReWatch);
context();
stack_watch.pop();
};
stack_watch.push(contextReWatch);
context();
stack_watch.pop();
};
function currentContext(){
return stack_watch[stack_watch.length - 1];
}
function read(signal){
if(!signal[mark]) return;
const { value, listeners }= signal[mark];
const context= currentContext();
if(context) listeners.add(context);
return value;
}
function write(signal, value){
if(!signal[mark]) return;
const s= signal[mark];
if(s.value===value) return;
s.value= value;
s.listeners.forEach(fn=> fn(value))
return value;
}
function valueOfSignal(signal){
return signal[mark].value;
}
function addSignalListener(signal, listener){
return signal[mark].listeners.add(listener);
}
function removeSignalListener(signal, listener){
return signal[mark].listeners.delete(listener);
}

15
src/signals.d.ts vendored Normal file
View File

@ -0,0 +1,15 @@
export type Signal<V, A>= (set?: V)=> V & A;
type Action<V>= (this: { value: V }, ...a: any[])=> typeof S._ | void;
type Actions<V>= Record<string, Action<V>>;
interface S {
_: Symbol
<V, A extends Actions<V>>(value: V, actions?: A): Signal<V, A>;
action<S extends Signal<any, Actions<any>>, A extends (S extends Signal<any, infer A> ? A : never), N extends keyof A>(
signal: S,
name: N,
...params: A[N] extends (...args: infer P)=> any ? P : never
): void;
clear(...signals: Signal<any, any>): void;
on<T>(signal: Signal<T, any>, onchange: (a: T)=> void, options?: AddEventListenerOptions): void
}
export const S: S;

View File

@ -1,153 +1,4 @@
export const mark= Symbol.for("signal"); export { S, isSignal, watch } from "./signals-lib.js";
import { signals_config } from "./signals-lib.js";
export function isSignal(candidate){
try{ return Reflect.has(candidate, mark); }
catch(e){ return false; }
}
import { typeOf } from './helpers.js';
import { registerReactivity } from "./signals-common.js"; import { registerReactivity } from "./signals-common.js";
registerReactivity({ registerReactivity(signals_config);
isReactiveAtrribute(attr, key){ return isSignal(attr); },
isTextContent(attributes){
//TODO FIX el(…, S.reactive(…))
return typeOf(attributes)!=="[object Object]" || ( isSignal(attributes) && typeOf(valueOfSignal(attributes))!=="[object Object]" );
},
process(key, attr, assignNth){ //TODO: unmounted
addSignalListener(attr, attr=> assignNth([ key, attr ]));
return attr();
},
on: addSignalListener,
off: removeSignalListener,
reactiveElement(signal, map){
const mark= document.createComment("reactive");
const out= document.createDocumentFragment();
out.append(mark);
let cache;
const toEls= v=> {
let els= map(v);
if(!Array.isArray(els))
els= [ els ];
if(cache) cache.forEach(el=> el.remove());
cache= els;
mark.before(...els);
};
addSignalListener(signal, toEls);
toEls(signal());
return out;
}
});
export function S(value){
if(typeof value!=="function")
return create(value);
if(isSignal(value)) return value;
const out= create();
watch(()=> out(value()));
return out;
}
S.reactive= reactive;
function reactive(data){
if(isSignal(data))
return data;
if(typeof data!=="object" || data===null)
return create(data);
let type;
if(Array.isArray(data)){
type= "array";
data= data.map(v=> reactive(v));
} else if(data.toString()!=="[object Object]"){
return create(data);
} else {
type= "object";
data= Object.fromEntries(
Object.entries(data)
.map(([ key, value ])=> [ key, reactive(value) ])
);
}
const signal= (...value)=>
value.length ? write(signal, reactive(value[0])) : read(signal[mark]);
return createWrapObject(type, toSignal(signal, data));
};
function toSignal(signal, value){
signal[mark]= {
value,
listeners: new Set()
};
return signal;
}
const stack= [];
export function watch(context){
stack.push(function contextReWatch(){
stack.push(contextReWatch);
context();
stack.pop();
});
context();
stack.pop();
};
function currentContext(){
return stack[stack.length - 1];
}
function create(value){
if(isSignal(value)) return value;
const signal= (...value)=>
value.length ? write(signal, value[0]) : read(signal[mark]);
return toSignal(signal, value);
}
function createWrapObject(type, signal){
return new Proxy(signal, {
set(_, p, newValue){
const s= signal[mark];
if(p in s.value){
const v= s.value[p];
if(isSignal(v)) return v(newValue);
return (s.value[p]= newValue);
}
const v= reactive(newValue);
s.value[p]= v;
s.listeners.forEach(fn=> fn(s.value));
return v;
},
deleteProperty(_, p){
const s= signal[mark];
Reflect.deleteProperty(s.value, p);
s.listeners.forEach(fn=> fn(s.value));
},
get(_, p){
if(mark===p) return signal[mark];
if("array"!==type || !(p in Array.prototype) || p==="length")
return Reflect.get(signal[mark].value, p);
return (...a)=> {
const s= signal[mark];
const result= Array.prototype[p].call(s.value, ...a);
//TODO optimize!
s.value.forEach((v, i)=> Reflect.set(s.value, i, reactive(v)));
s.listeners.forEach(fn=> fn(s.value));
return result;
};
}
});
}
function read({ value, listeners }){
const context= currentContext();
if(context) listeners.add(context);
return value;
}
function write(signal, value){
signal[mark].value= value;
signal[mark].listeners.forEach(fn=> fn(value))
return value;
}
function valueOfSignal(signal){
return signal[mark].value;
}
export function addSignalListener(signal, listener){
return signal[mark].listeners.add(listener);
}
export function removeSignalListener(signal, listener){
return signal[mark].listeners.delete(listener);
}

View File

@ -0,0 +1,28 @@
import { style, el, on, S } from '../exports.js';
const className= style.host(fullNameComponent).css`
:host form{
display: flex;
flex-flow: column nowrap;
}
`;
export function fullNameComponent(){
const labels= [ "Name", "Surname" ];
const name= labels.map(_=> S(""));
const full_name= S(()=>
name.map(l=> l()).filter(Boolean).join(" ") || "-");
return el("div", { className }).append(
el("h2", "Simple form:"),
el("form", { onsubmit: ev=> ev.preventDefault() }).append(
...name.map((v, i)=>
el("label", labels[i]).append(
el("input", { type: "text", name: labels[i], value: v() }, on("change", ev=> v(ev.target.value)))
))
),
el("p").append(
el("strong", "Full name"),
el("#text", ": "),
el("#text", full_name)
)
);
}

View File

@ -0,0 +1,75 @@
import { style, el, on, S } from '../exports.js';
const className= style.host(todosComponent).css`
:host{
display: flex;
flex-flow: column nowrap;
}
:host input{
margin-inline-start: .5em;
}
:host button{
margin-inline-start: 1em;
}
`;
/** @param {{ todos: string[] }} */
export function todosComponent({ todos= [] }= {}){
const todosS= S(todos.map(v=> S(v)), {
/** @param {string} v */
add(v){ this.value.push(S(v)); },
/** @param {number} i */
remove(i){ this.value.splice(i, 1); }
});
console.log(todosS); //TODO
const name= "todoName";
const onsubmitAdd= on("submit", event=> {
const value= event.target.elements[name].value;
if(!value) return;
event.preventDefault();
S.action(todosS, "add", value);
event.target.elements[name].value= "";
});
const onremove= on("remove", event=>
S.action(todosS, "remove", event.detail));
const ul_todos= el("ul").append(
el("<>", todosS,
ts=> ts.map((t, i)=> el(todoComponent, { textContent: t, value: i, className }, onremove))
));
return el("div", { className }).append(
el("div").append(
el("h2", "Todos:"),
el("h3", "List of todos:"),
el("<>", todosS, ts=> !ts.length
? el("p", "No todos yet")
: ul_todos)
),
el("form", null, onsubmitAdd).append(
el("h3", "Add a todo:"),
el("label", "New todo: ").append(
el("input", { name, type: "text", required: true }),
),
el("button", "+")
)
)
}
/**
* @type {ddeFires<[ "click" ]>}
* @param {{
* textContent: string | ddeSignal<string, any>
* value: number
* }}
* */
function todoComponent({ textContent, value }){
const ref= S();
const onclick= on("click", event=> {
const value= Number(event.target.value);
event.preventDefault();
event.stopPropagation();
ref().dispatchEvent(new CustomEvent("remove", { detail: value }));
});
return el("li", null, ref).append(
el("#text", textContent),
el("button", { type: "button", value, textContent: "-" }, onclick)
);
}

30
test/exports.js Normal file
View File

@ -0,0 +1,30 @@
import { namespace, el, on, registerReactivity } from "../index.js";
import { S } from "../src/signals.js";
// import { empty, namespace, on, dispatch } from "../index.js";
// import "../dist/dde-with-signals.js";
// Object.assign(globalThis, dde);
// import { el, on, off, S } from "../dist/esm-with-signals.js";
const style= createStyle();
Object.assign(globalThis, { S, el, namespace, on, registerReactivity, style });
export { S, el, on, registerReactivity, style };
function createStyle(){
const element= el("style");
const store= new WeakSet();
let host;
return {
element,
host(k, h= k.name){
if(store.has(k)) return { css: ()=> {} };
store.add(k);
host= h;
return this;
},
css(...args){
const textContent= String.raw(...args).replaceAll(":host", "."+host);
const className= host;
element.appendChild(el("#text", { textContent }));
return className;
}
};
}

View File

@ -1,81 +1,9 @@
import { el, on, off } from "../index.js"; import { style, el } from './exports.js';
import { S } from "../src/signals.js";
//import { empty, namespace, on, dispatch } from "../index.js";
Object.assign(globalThis, { S, el, on, off });
const style= createStyle();
const app= el(todosComponent);
document.head.append(style.element); document.head.append(style.element);
document.body.append(app); import { fullNameComponent } from './components/fullNameComponent.js';
import { todosComponent } from './components/todosComponent.js';
function todosComponent({ todos= [] }= {}){ document.body.append(
const className= "basicTodoForm"; el("h1", "Experiments:"),
style.css` el(fullNameComponent),
.${className}{ el(todosComponent),
display: flex;
flex-flow: column nowrap;
}
.${className} input{
margin-inline-start: .5em;
}
`;
todos= S.reactive(todos);
globalThis.__todos__= todos; //TODO
const name= "todoName";
const onsubmit= on("submit", event=> {
const value= event.target.elements[name].value;
if(!value) return;
event.preventDefault();
todos.push(value)
event.target.elements[name].value= "";
});
const onremove= on("click", event=> {
const value= Number(event.target.value);
if(Number.isNaN(value)) return;
event.preventDefault();
todos.splice(value, 1);
});
return el("div", { className }).append(
el("div").append(
el("h1", "Todos:"),
el("<>", todos, ts=> !ts.length
? el("p", "No todos yet")
: ts.map((t, i)=> el(todoComponent, { textContent: t, value: i, className }, onremove)))
),
el("form", null, onsubmit).append(
el("h2", "Add:"),
el("label", "New todo: ").append(
el("input", { name, type: "text", required: true }),
),
el("button", "+")
)
)
}
function todoComponent({ textContent, className, value }){
style.key(todoComponent).css`
.${className} button{
margin-inline-start: 1em;
}
`;
return el("p").append(
el("#text", textContent),
el("button", { type: "button", value, textContent: "-" })
); );
}
function createStyle(){
const element= el("style");
const store= new WeakSet();
return {
element,
key(k){
if(store.has(k)) return { css: ()=> {} };
store.add(k);
return this;
},
css(...args){
element.appendChild(el("#text", { textContent: String.raw(...args) }));
}
};
}