diff --git a/README.md b/README.md index f765216..a43d058 100644 --- a/README.md +++ b/README.md @@ -29,7 +29,7 @@ In the meaning of size, complexity and usability. An another goal is making clear library logic. Starting from pure native JavaScript (DOM API), then using small utils (`assign`, `S`, …, `el`, …) and end up with way to write complex code. Therefore, you can use any „internal” function to make live with native JavaScript easier -(`assign`, `classListDeclarative`, `on`, `dispatchEvent`, …, `S`, …) regarding if you don’t +(`assign`, `classListDeclarative`, `on`, `dispatchEvent`, …, `S`, …) regarding if you need complex library/framework. As consequence of that, it shouldn’t be hard to incorporate the library into existing projects. diff --git a/dist/dde-with-signals.js b/dist/dde-with-signals.js index 32c3b60..fe68e7e 100644 --- a/dist/dde-with-signals.js +++ b/dist/dde-with-signals.js @@ -1,21 +1,23 @@ //deka-dom-el library is available via global namespace `dde` (()=> { -var w={isSignal(t){return!1},processReactiveAttribute(t,e,n,r){return n}};function k(t,e=!0){return e?Object.assign(w,t):(Object.setPrototypeOf(t,w),t)}function O(t){return w.isPrototypeOf(t)&&t!==w?t:w}function _(t){return typeof t>"u"}function W(t){let e=typeof t;return e!=="object"?e:t===null?"null":Object.prototype.toString.call(t)}function R(t,e){if(!t||!(t instanceof AbortSignal))return!0;if(!t.aborted)return t.addEventListener("abort",e),function(){t.removeEventListener("abort",e)}}var $={setDeleteAttr:K};function K(t,e,n){if(Reflect.set(t,e,n),!!_(n)){if(Reflect.deleteProperty(t,e),t instanceof HTMLElement&&t.getAttribute(e)==="undefined")return t.removeAttribute(e);if(Reflect.get(t,e)==="undefined")return Reflect.set(t,e,"")}}var y=[{scope:document.body,namespace:"html",host:t=>t?t(document.body):document.body,prevent:!0}],z=t=>t==="svg"?"http://www.w3.org/2000/svg":t,b={get current(){return y[y.length-1]},get host(){return this.current.host},get namespace(){return this.current.namespace},set namespace(t){return this.current.namespace=z(t)},preventDefault(){let{current:t}=this;return t.prevent=!0,t},elNamespace(t){let e=this.namespace;return this.namespace=t,{append(...n){return b.namespace=e,n.length===1?n[0]:document.createDocumentFragment().append(...n)}}},get state(){return[...y]},push(t={}){return t.namespace&&(t.namespace=z(t.namespace)),y.push(Object.assign({},this.current,{prevent:!1},t))},pop(){return y.pop()}};function ht(t,e,...n){let r=O(this),{namespace:o}=b,c=0,s,d;switch((Object(e)!==e||r.isSignal(e))&&(e={textContent:e}),!0){case typeof t=="function":{c=1,b.push({scope:t,host:E=>E?(c===1?n.unshift(E):E(d),void 0):d}),s=t(e||void 0);let a=s instanceof DocumentFragment,g=document.createComment(``);s.prepend(g),a&&(d=g);break}case t==="#text":s=C.call(this,document.createTextNode(""),e);break;case(t==="<>"||!t):s=C.call(this,document.createDocumentFragment(),e);break;case o!=="html":s=C.call(this,document.createElementNS(o,t),e);break;case!s:s=C.call(this,document.createElement(t),e)}return d||(d=s),n.forEach(a=>a(d)),c&&b.pop(),c=2,s}var{setDeleteAttr:H}=$,L=new WeakMap;function C(t,...e){if(!e.length)return t;L.set(t,B(t,this));for(let[n,r]of Object.entries(Object.assign({},...e)))q.call(this,t,n,r);return L.delete(t),t}function q(t,e,n){let{setRemoveAttr:r,s:o}=B(t,this),c=this;n=o.processReactiveAttribute(t,e,n,(d,a)=>q.call(c,t,d,a));let[s]=e;if(s==="=")return r(e.slice(1),n);if(s===".")return U(t,e.slice(1),n);if(/(aria|data)([A-Z])/.test(e))return e=e.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase(),r(e,n);switch(e==="className"&&(e="class"),e){case"xlink:href":return r(e,n,"http://www.w3.org/1999/xlink");case"textContent":return H(t,e,n);case"style":if(typeof n!="object")break;case"dataset":return T(o,n,U.bind(null,t[e]));case"ariaset":return T(o,n,(d,a)=>r("aria-"+d,a));case"classList":return Q.call(c,t,n)}return X(t,e)?H(t,e,n):r(e,n)}function B(t,e){if(L.has(t))return L.get(t);let r=(t instanceof SVGElement?tt:Y).bind(null,t,"Attribute"),o=O(e);return{setRemoveAttr:r,s:o}}function Q(t,e){let n=O(this);return T(n,e,(r,o)=>t.classList.toggle(r,o===-1?void 0:!!o)),t}function gt(t){return Array.from(t.children).forEach(e=>e.remove()),t}function X(t,e){if(!Reflect.has(t,e))return!1;let n=G(t,e);return!_(n.set)}function G(t,e){if(t=Object.getPrototypeOf(t),!t)return{};let n=Object.getOwnPropertyDescriptor(t,e);return n||G(t,e)}function T(t,e,n){if(!(typeof e!="object"||e===null))return Object.entries(e).forEach(function([o,c]){o&&(c=t.processReactiveAttribute(e,o,c,n),n(o,c))})}function I(t){return Array.isArray(t)?t.filter(Boolean).join(" "):t}function Y(t,e,n,r){return t[(_(r)?"remove":"set")+e](n,I(r))}function tt(t,e,n,r,o=null){return t[(_(r)?"remove":"set")+e+"NS"](o,n,I(r))}function U(t,e,n){if(Reflect.set(t,e,n),!!_(n))return Reflect.deleteProperty(t,e)}function Et(t,e,...n){let r=n.length?new CustomEvent(e,{detail:n[0]}):new Event(e);return t.dispatchEvent(r)}function v(t,e,n){return function(o){return o.addEventListener(t,e,n),o}}var D=nt(),et=new WeakSet;v.connected=function(t,e){let n="connected";return typeof e!="object"&&(e={}),e.once=!0,function(o){let c="dde:"+n;return o.addEventListener(c,t,e),o.__dde_lifecycleToEvents?o:o.isConnected?(o.dispatchEvent(new Event(c)),o):(R(e.signal,()=>D.offConnected(o,t))&&D.onConnected(o,t),o)}};v.disconnected=function(t,e){let n="disconnected";return typeof e!="object"&&(e={}),e.once=!0,function(o){let c="dde:"+n;return o.addEventListener(c,t,e),o.__dde_lifecycleToEvents||R(e.signal,()=>D.offDisconnected(o,t))&&D.onDisconnected(o,t),o}};v.attributeChanged=function(t,e){let n="attributeChanged";return typeof e!="object"&&(e={}),function(o){let c="dde:"+n;if(o.addEventListener(c,t,e),o.__dde_lifecycleToEvents||et.has(o))return o;let s=new MutationObserver(function(a){for(let{attributeName:g,target:E}of a)E.dispatchEvent(new CustomEvent(c,{detail:[g,E.getAttribute(g)]}))});return R(e.signal,()=>s.disconnect())&&s.observe(o,{attributes:!0}),o}};function nt(){let t=new Map,e=!1,n=new MutationObserver(function(i){for(let u of i)if(u.type==="childList"){if(g(u.addedNodes,!0)){s();continue}E(u.removedNodes,!0)&&s()}});return{onConnected(i,u){c();let f=o(i);f.connected.has(u)||(f.connected.add(u),f.length_c+=1)},offConnected(i,u){if(!t.has(i))return;let f=t.get(i);f.connected.has(u)&&(f.connected.delete(u),f.length_c-=1,r(i,f))},onDisconnected(i,u){c();let f=o(i);f.disconnected.has(u)||(f.disconnected.add(u),f.length_d+=1)},offDisconnected(i,u){if(!t.has(i))return;let f=t.get(i);f.disconnected.has(u)&&(f.disconnected.delete(u),f.length_d-=1,r(i,f))}};function r(i,u){u.length_c||u.length_d||(t.delete(i),s())}function o(i){if(t.has(i))return t.get(i);let u={connected:new WeakSet,length_c:0,disconnected:new WeakSet,length_d:0};return t.set(i,u),u}function c(){e||(e=!0,n.observe(document.body,{childList:!0,subtree:!0}))}function s(){!e||t.size||(e=!1,n.disconnect())}function d(){return new Promise(function(i){(requestIdleCallback||requestAnimationFrame)(i)})}async function a(i){t.size>30&&await d();let u=[];if(!(i instanceof Node))return u;for(let f of t.keys())f===i||!(f instanceof Node)||i.contains(f)&&u.push(f);return u}function g(i,u){let f=!1;for(let m of i){if(u&&a(m).then(g),!t.has(m))continue;let x=t.get(m);x.length_c&&(m.dispatchEvent(new Event("dde:connected")),x.connected=new WeakSet,x.length_c=0,x.length_d||t.delete(m),f=!0)}return f}function E(i,u){let f=!1;for(let m of i)u&&a(m).then(E),!(!t.has(m)||!t.get(m).length_d)&&(m.dispatchEvent(new Event("dde:disconnected")),t.delete(m),f=!0);return f}}typeof document.createDocumentFragment().append()>"u"&&[HTMLElement,SVGElement,DocumentFragment].forEach(t=>{let{append:e}=t.prototype;t.prototype.append=function(...n){return e.apply(this,n),this}});var p=Symbol.for("Signal");function P(t){try{return Reflect.has(t,p)}catch{return!1}}var j=[],h=new WeakMap;function l(t,e){if(typeof t!="function")return J(t,e);if(P(t))return t;let n=J(),r=function(){let[o,...c]=h.get(r);if(h.set(r,new Set([o])),j.push(r),n(t()),j.pop(),!c.length)return;let s=h.get(r);for(let d of c)s.has(d)||A(d,r)};return h.set(n[p],r),h.set(r,new Set([n])),r(),n}l.action=function(t,e,...n){let r=t[p],{actions:o}=r;if(!o||!Reflect.has(o,e))throw new Error(`'${t}' has no action with name '${e}'!`);if(o[e].apply(r,n),r.skip)return Reflect.deleteProperty(r,"skip");r.listeners.forEach(c=>c(r.value))};l.on=function t(e,n,r={}){let{signal:o}=r;if(!(o&&o.aborted)){if(Array.isArray(e))return e.forEach(c=>t(c,n,r));M(e,n),o&&o.addEventListener("abort",()=>A(e,n))}};l.symbols={signal:p,onclear:Symbol.for("Signal.onclear")};var S="__dde_attributes";l.attribute=function(t,e=void 0){let n=l(e);return b.host(r=>{if(r instanceof HTMLElement?r.hasAttribute(t)&&n(r.getAttribute(t)):r.hasAttributeNS(null,t)&&n(r.getAttributeNS(null,t)),r[S]){r[S][t]=n;return}return r[S]={[t]:n},v.attributeChanged(function({detail:c}){/*! This maps attributes to signals (`S.attribute`). -* Investigate `__dde_attributes` key of the element.*/let[s,d]=c,a=r[S][s];a&&a(d)})(r),v.disconnected(function(){/*! This removes all signals mapped to attributes (`S.attribute`). -* Investigate `__dde_attributes` key of the element.*/l.clear(...Object.values(r[S]))})(r),r}),n};l.clear=function(...t){for(let n of t){Reflect.deleteProperty(n,"toJSON");let r=n[p];r.onclear.forEach(o=>o.call(r)),e(n,r),Reflect.deleteProperty(n,p)}function e(n,r){r.listeners.forEach(o=>{if(r.listeners.delete(o),!h.has(o))return;let c=h.get(o);c.delete(n),!(c.size>1)&&(l.clear(...c),h.delete(o))})}};var N="__dde_reactive";l.el=function(t,e){let n=document.createComment(''),r=document.createComment(""),o=document.createDocumentFragment();o.append(n,r);let{current:c}=b,s=d=>{if(!n.parentNode||!r.parentNode)return A(t,s);b.push(c);let a=e(d);b.pop(),Array.isArray(a)||(a=[a]);let g=n;for(;(g=n.nextSibling)!==r;)g.remove();n.after(...a)};return M(t,s),Z(t,s,n,e),s(t()),o};var V={isSignal:P,processReactiveAttribute(t,e,n,r){if(!P(n))return n;let o=c=>r(e,c);return M(n,o),Z(n,o,t,e),n()}};function Z(t,e,...n){let{current:r}=b;r.prevent||r.host(function(o){o[N]||(o[N]=[],v.disconnected(()=>o[N].forEach(([[c,s]])=>A(c,s,c[p]?.host()===o)))(o)),o[N].push([[t,e],...n])})}function J(t,e){let n=(...r)=>r.length?it(n,...r):st(n);return ot(n,t,e)}var rt=Object.assign(Object.create(null),{stopPropagation(){this.skip=!0}}),F=class extends Error{constructor(){super();let[e,...n]=this.stack.split(` -`),r=e.slice(e.indexOf("@"),e.indexOf(".js:")+4);this.stack=n.find(o=>!o.includes(r))}};function ot(t,e,n){let r=[];W(n)!=="[object Object]"&&(n={});let{onclear:o}=l.symbols;n[o]&&(r.push(n[o]),Reflect.deleteProperty(n,o));let{host:c}=b;return Reflect.defineProperty(t,p,{value:{value:e,actions:n,onclear:r,host:c,listeners:new Set,defined:new F},enumerable:!1,writable:!1,configurable:!0}),t.toJSON=()=>t(),Object.setPrototypeOf(t[p],rt),t}function ct(){return j[j.length-1]}function st(t){if(!t[p])return;let{value:e,listeners:n}=t[p],r=ct();return r&&n.add(r),h.has(r)&&h.get(r).add(t),e}function it(t,e,n){if(!t[p])return;let r=t[p];if(!(!n&&r.value===e))return r.value=e,r.listeners.forEach(o=>o(e)),e}function M(t,e){if(t[p])return t[p].listeners.add(e)}function A(t,e,n){let r=t[p];if(!r)return;let o=r.listeners.delete(e);if(n&&!r.listeners.size){if(l.clear(t),!h.has(r))return o;let c=h.get(r);if(!h.has(c))return o;h.get(c).forEach(s=>A(s,c,!0))}return o}k(V); -globalThis.dde= {S: l, -assign: C, -assignAttribute: q, -classListDeclarative: Q, -createElement: ht, -dispatchEvent: Et, -el: ht, -empty: gt, -isSignal: P, +var y={isSignal(t){return!1},processReactiveAttribute(t,e,n,r){return n}};function W(t,e=!0){return e?Object.assign(y,t):(Object.setPrototypeOf(t,y),t)}function R(t){return y.isPrototypeOf(t)&&t!==y?t:y}function _(t){return typeof t>"u"}function F(t){let e=typeof t;return e!=="object"?e:t===null?"null":Object.prototype.toString.call(t)}function C(t,e){if(!t||!(t instanceof AbortSignal))return!0;if(!t.aborted)return t.addEventListener("abort",e),function(){t.removeEventListener("abort",e)}}var U={setDeleteAttr:X};function X(t,e,n){if(Reflect.set(t,e,n),!!_(n)){if(Reflect.deleteProperty(t,e),t instanceof HTMLElement&&t.getAttribute(e)==="undefined")return t.removeAttribute(e);if(Reflect.get(t,e)==="undefined")return Reflect.set(t,e,"")}}var w=[{scope:document.body,host:t=>t?t(document.body):document.body,prevent:!0}],E={get current(){return w[w.length-1]},get host(){return this.current.host},preventDefault(){let{current:t}=this;return t.prevent=!0,t},get state(){return[...w]},push(t={}){return w.push(Object.assign({},this.current,{prevent:!1},t))},pop(){return w.pop()}},L;function m(t,e,...n){let r=R(this),o=0,c,s;switch((Object(e)!==e||r.isSignal(e))&&(e={textContent:e}),!0){case typeof t=="function":{o=1,E.push({scope:t,host:h=>h?(o===1?n.unshift(h):h(s),void 0):s}),c=t(e||void 0);let d=c instanceof DocumentFragment,a=m.mark({type:"component",name:t.name,host:d?"this":c.nodeName==="#comment"?"previousLater":"parentElement"});c.prepend(a),d&&(s=a);break}case t==="#text":c=N.call(this,document.createTextNode(""),e);break;case(t==="<>"||!t):c=N.call(this,document.createDocumentFragment(),e);break;case L:c=N.call(this,document.createElementNS(L,t),e);break;case!c:c=N.call(this,document.createElement(t),e)}return rt(c),s||(s=c),n.forEach(d=>d(s)),o&&E.pop(),o=2,c}m.mark=function(t,e=!1){t=Object.entries(t).map(([o,c])=>o+`="${c}"`).join(" ");let n=e?"":"/",r=document.createComment(``);return e||(r.end=document.createComment("")),r};m.later=function(){let t=m.mark({type:"later"});return t.append=t.prepend=function(...e){return t.after(...e),t},t};function bt(t){let e=this;return function(...r){L=t;let o=m.call(e,...r);return L=void 0,o}}var{setDeleteAttr:q}=U,j=new WeakMap;function N(t,...e){if(!e.length)return t;j.set(t,J(t,this));for(let[n,r]of Object.entries(Object.assign({},...e)))I.call(this,t,n,r);return j.delete(t),t}function I(t,e,n){let{setRemoveAttr:r,s:o}=J(t,this),c=this;n=o.processReactiveAttribute(t,e,n,(d,a)=>I.call(c,t,d,a));let[s]=e;if(s==="=")return r(e.slice(1),n);if(s===".")return B(t,e.slice(1),n);if(/(aria|data)([A-Z])/.test(e))return e=e.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase(),r(e,n);switch(e==="className"&&(e="class"),e){case"xlink:href":return r(e,n,"http://www.w3.org/1999/xlink");case"textContent":return q(t,e,n);case"style":if(typeof n!="object")break;case"dataset":return M(o,n,B.bind(null,t[e]));case"ariaset":return M(o,n,(d,a)=>r("aria-"+d,a));case"classList":return Y.call(c,t,n)}return tt(t,e)?q(t,e,n):r(e,n)}function J(t,e){if(j.has(t))return j.get(t);let r=(t instanceof SVGElement?nt:et).bind(null,t,"Attribute"),o=R(e);return{setRemoveAttr:r,s:o}}function Y(t,e){let n=R(this);return M(n,e,(r,o)=>t.classList.toggle(r,o===-1?void 0:!!o)),t}function _t(t){return Array.from(t.children).forEach(e=>e.remove()),t}function tt(t,e){if(!Reflect.has(t,e))return!1;let n=Z(t,e);return!_(n.set)}function Z(t,e){if(t=Object.getPrototypeOf(t),!t)return{};let n=Object.getOwnPropertyDescriptor(t,e);return n||Z(t,e)}function M(t,e,n){if(!(typeof e!="object"||e===null))return Object.entries(e).forEach(function([o,c]){o&&(c=t.processReactiveAttribute(e,o,c,n),n(o,c))})}function G(t){return Array.isArray(t)?t.filter(Boolean).join(" "):t}function et(t,e,n,r){return t[(_(r)?"remove":"set")+e](n,G(r))}function nt(t,e,n,r,o=null){return t[(_(r)?"remove":"set")+e+"NS"](o,n,G(r))}function B(t,e,n){if(Reflect.set(t,e,n),!!_(n))return Reflect.deleteProperty(t,e)}function H(...t){return this.appendOrig(...t),this}function rt(t){return t.append===H||(t.appendOrig=t.append,t.append=H),t}function xt(t,e,...n){let r=n.length?new CustomEvent(e,{detail:n[0]}):new Event(e);return t.dispatchEvent(r)}function v(t,e,n){return function(o){return o.addEventListener(t,e,n),o}}var P=ct(),ot=new WeakSet;v.connected=function(t,e){let n="connected";return typeof e!="object"&&(e={}),e.once=!0,function(o){let c="dde:"+n;return o.addEventListener(c,t,e),o.__dde_lifecycleToEvents?o:o.isConnected?(o.dispatchEvent(new Event(c)),o):(C(e.signal,()=>P.offConnected(o,t))&&P.onConnected(o,t),o)}};v.disconnected=function(t,e){let n="disconnected";return typeof e!="object"&&(e={}),e.once=!0,function(o){let c="dde:"+n;return o.addEventListener(c,t,e),o.__dde_lifecycleToEvents||C(e.signal,()=>P.offDisconnected(o,t))&&P.onDisconnected(o,t),o}};v.attributeChanged=function(t,e){let n="attributeChanged";return typeof e!="object"&&(e={}),function(o){let c="dde:"+n;if(o.addEventListener(c,t,e),o.__dde_lifecycleToEvents||ot.has(o))return o;let s=new MutationObserver(function(a){for(let{attributeName:h,target:x}of a)x.dispatchEvent(new CustomEvent(c,{detail:[h,x.getAttribute(h)]}))});return C(e.signal,()=>s.disconnect())&&s.observe(o,{attributes:!0}),o}};function ct(){let t=new Map,e=!1,n=new MutationObserver(function(i){for(let u of i)if(u.type==="childList"){if(h(u.addedNodes,!0)){s();continue}x(u.removedNodes,!0)&&s()}});return{onConnected(i,u){c();let f=o(i);f.connected.has(u)||(f.connected.add(u),f.length_c+=1)},offConnected(i,u){if(!t.has(i))return;let f=t.get(i);f.connected.has(u)&&(f.connected.delete(u),f.length_c-=1,r(i,f))},onDisconnected(i,u){c();let f=o(i);f.disconnected.has(u)||(f.disconnected.add(u),f.length_d+=1)},offDisconnected(i,u){if(!t.has(i))return;let f=t.get(i);f.disconnected.has(u)&&(f.disconnected.delete(u),f.length_d-=1,r(i,f))}};function r(i,u){u.length_c||u.length_d||(t.delete(i),s())}function o(i){if(t.has(i))return t.get(i);let u={connected:new WeakSet,length_c:0,disconnected:new WeakSet,length_d:0};return t.set(i,u),u}function c(){e||(e=!0,n.observe(document.body,{childList:!0,subtree:!0}))}function s(){!e||t.size||(e=!1,n.disconnect())}function d(){return new Promise(function(i){(requestIdleCallback||requestAnimationFrame)(i)})}async function a(i){t.size>30&&await d();let u=[];if(!(i instanceof Node))return u;for(let f of t.keys())f===i||!(f instanceof Node)||i.contains(f)&&u.push(f);return u}function h(i,u){let f=!1;for(let b of i){if(u&&a(b).then(h),!t.has(b))continue;let S=t.get(b);S.length_c&&(b.dispatchEvent(new Event("dde:connected")),S.connected=new WeakSet,S.length_c=0,S.length_d||t.delete(b),f=!0)}return f}function x(i,u){let f=!1;for(let b of i)u&&a(b).then(x),!(!t.has(b)||!t.get(b).length_d)&&(b.dispatchEvent(new Event("dde:disconnected")),t.delete(b),f=!0);return f}}var p=Symbol.for("Signal");function D(t){try{return Reflect.has(t,p)}catch{return!1}}var T=[],l=new WeakMap;function g(t,e){if(typeof t!="function")return V(t,e);if(D(t))return t;let n=V(),r=function(){let[o,...c]=l.get(r);if(l.set(r,new Set([o])),T.push(r),n(t()),T.pop(),!c.length)return;let s=l.get(r);for(let d of c)s.has(d)||O(d,r)};return l.set(n[p],r),l.set(r,new Set([n])),r(),n}g.action=function(t,e,...n){let r=t[p],{actions:o}=r;if(!o||!Reflect.has(o,e))throw new Error(`'${t}' has no action with name '${e}'!`);if(o[e].apply(r,n),r.skip)return Reflect.deleteProperty(r,"skip");r.listeners.forEach(c=>c(r.value))};g.on=function t(e,n,r={}){let{signal:o}=r;if(!(o&&o.aborted)){if(Array.isArray(e))return e.forEach(c=>t(c,n,r));z(e,n),o&&o.addEventListener("abort",()=>O(e,n))}};g.symbols={signal:p,onclear:Symbol.for("Signal.onclear")};var A="__dde_attributes";g.attribute=function(t,e=void 0){let n=g(e);return E.host(r=>{if(r instanceof HTMLElement?r.hasAttribute(t)&&n(r.getAttribute(t)):r.hasAttributeNS(null,t)&&n(r.getAttributeNS(null,t)),r[A]){r[A][t]=n;return}return r[A]={[t]:n},v.attributeChanged(function({detail:c}){/*! This maps attributes to signals (`S.attribute`). +* Investigate `__dde_attributes` key of the element.*/let[s,d]=c,a=r[A][s];a&&a(d)})(r),v.disconnected(function(){/*! This removes all signals mapped to attributes (`S.attribute`). +* Investigate `__dde_attributes` key of the element.*/g.clear(...Object.values(r[A]))})(r),r}),n};g.clear=function(...t){for(let n of t){Reflect.deleteProperty(n,"toJSON");let r=n[p];r.onclear.forEach(o=>o.call(r)),e(n,r),Reflect.deleteProperty(n,p)}function e(n,r){r.listeners.forEach(o=>{if(r.listeners.delete(o),!l.has(o))return;let c=l.get(o);c.delete(n),!(c.size>1)&&(g.clear(...c),l.delete(o))})}};var k="__dde_reactive";g.el=function(t,e){let n=m.mark({type:"reactive"},!1),r=n.end,o=document.createDocumentFragment();o.append(n,r);let{current:c}=E,s=d=>{if(!n.parentNode||!r.parentNode)return O(t,s);E.push(c);let a=e(d);E.pop(),Array.isArray(a)||(a=[a]);let h=n;for(;(h=n.nextSibling)!==r;)h.remove();n.after(...a)};return z(t,s),Q(t,s,n,e),s(t()),o};var K={isSignal:D,processReactiveAttribute(t,e,n,r){if(!D(n))return n;let o=c=>r(e,c);return z(n,o),Q(n,o,t,e),n()}};function Q(t,e,...n){let{current:r}=E;r.prevent||r.host(function(o){o[k]||(o[k]=[],v.disconnected(()=>o[k].forEach(([[c,s]])=>O(c,s,c[p]?.host()===o)))(o)),o[k].push([[t,e],...n])})}function V(t,e){let n=(...r)=>r.length?at(n,...r):ft(n);return it(n,t,e)}var st=Object.assign(Object.create(null),{stopPropagation(){this.skip=!0}}),$=class extends Error{constructor(){super();let[e,...n]=this.stack.split(` +`),r=e.slice(e.indexOf("@"),e.indexOf(".js:")+4);this.stack=n.find(o=>!o.includes(r))}};function it(t,e,n){let r=[];F(n)!=="[object Object]"&&(n={});let{onclear:o}=g.symbols;n[o]&&(r.push(n[o]),Reflect.deleteProperty(n,o));let{host:c}=E;return Reflect.defineProperty(t,p,{value:{value:e,actions:n,onclear:r,host:c,listeners:new Set,defined:new $},enumerable:!1,writable:!1,configurable:!0}),t.toJSON=()=>t(),Object.setPrototypeOf(t[p],st),t}function ut(){return T[T.length-1]}function ft(t){if(!t[p])return;let{value:e,listeners:n}=t[p],r=ut();return r&&n.add(r),l.has(r)&&l.get(r).add(t),e}function at(t,e,n){if(!t[p])return;let r=t[p];if(!(!n&&r.value===e))return r.value=e,r.listeners.forEach(o=>o(e)),e}function z(t,e){if(t[p])return t[p].listeners.add(e)}function O(t,e,n){let r=t[p];if(!r)return;let o=r.listeners.delete(e);if(n&&!r.listeners.size){if(g.clear(t),!l.has(r))return o;let c=l.get(r);if(!l.has(c))return o;l.get(c).forEach(s=>O(s,c,!0))}return o}W(K); +globalThis.dde= {S: g, +assign: N, +assignAttribute: I, +classListDeclarative: Y, +createElement: m, +createElementNS: bt, +dispatchEvent: xt, +el: m, +elNS: bt, +empty: _t, +isSignal: D, on: v, -registerReactivity: k, -scope: b +registerReactivity: W, +scope: E }; })(); \ No newline at end of file diff --git a/dist/dde.js b/dist/dde.js index 2d0b1a9..a114fce 100644 --- a/dist/dde.js +++ b/dist/dde.js @@ -1,16 +1,18 @@ //deka-dom-el library is available via global namespace `dde` (()=> { -var b={isSignal(t){return!1},processReactiveAttribute(t,e,n,c){return n}};function F(t,e=!0){return e?Object.assign(b,t):(Object.setPrototypeOf(t,b),t)}function E(t){return b.isPrototypeOf(t)&&t!==b?t:b}function g(t){return typeof t>"u"}function _(t,e){if(!t||!(t instanceof AbortSignal))return!0;if(!t.aborted)return t.addEventListener("abort",e),function(){t.removeEventListener("abort",e)}}var R={setDeleteAttr:M};function M(t,e,n){if(Reflect.set(t,e,n),!!g(n)){if(Reflect.deleteProperty(t,e),t instanceof HTMLElement&&t.getAttribute(e)==="undefined")return t.removeAttribute(e);if(Reflect.get(t,e)==="undefined")return Reflect.set(t,e,"")}}var v=[{scope:document.body,namespace:"html",host:t=>t?t(document.body):document.body,prevent:!0}],D=t=>t==="svg"?"http://www.w3.org/2000/svg":t,x={get current(){return v[v.length-1]},get host(){return this.current.host},get namespace(){return this.current.namespace},set namespace(t){return this.current.namespace=D(t)},preventDefault(){let{current:t}=this;return t.prevent=!0,t},elNamespace(t){let e=this.namespace;return this.namespace=t,{append(...n){return x.namespace=e,n.length===1?n[0]:document.createDocumentFragment().append(...n)}}},get state(){return[...v]},push(t={}){return t.namespace&&(t.namespace=D(t.namespace)),v.push(Object.assign({},this.current,{prevent:!1},t))},pop(){return v.pop()}};function J(t,e,...n){let c=E(this),{namespace:r}=x,u=0,f,a;switch((Object(e)!==e||c.isSignal(e))&&(e={textContent:e}),!0){case typeof t=="function":{u=1,x.push({scope:t,host:h=>h?(u===1?n.unshift(h):h(a),void 0):a}),f=t(e||void 0);let d=f instanceof DocumentFragment,l=document.createComment(``);f.prepend(l),d&&(a=l);break}case t==="#text":f=w.call(this,document.createTextNode(""),e);break;case(t==="<>"||!t):f=w.call(this,document.createDocumentFragment(),e);break;case r!=="html":f=w.call(this,document.createElementNS(r,t),e);break;case!f:f=w.call(this,document.createElement(t),e)}return a||(a=f),n.forEach(d=>d(a)),u&&x.pop(),u=2,f}var{setDeleteAttr:S}=R,A=new WeakMap;function w(t,...e){if(!e.length)return t;A.set(t,P(t,this));for(let[n,c]of Object.entries(Object.assign({},...e)))N.call(this,t,n,c);return A.delete(t),t}function N(t,e,n){let{setRemoveAttr:c,s:r}=P(t,this),u=this;n=r.processReactiveAttribute(t,e,n,(a,d)=>N.call(u,t,a,d));let[f]=e;if(f==="=")return c(e.slice(1),n);if(f===".")return L(t,e.slice(1),n);if(/(aria|data)([A-Z])/.test(e))return e=e.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase(),c(e,n);switch(e==="className"&&(e="class"),e){case"xlink:href":return c(e,n,"http://www.w3.org/1999/xlink");case"textContent":return S(t,e,n);case"style":if(typeof n!="object")break;case"dataset":return O(r,n,L.bind(null,t[e]));case"ariaset":return O(r,n,(a,d)=>c("aria-"+a,d));case"classList":return W.call(u,t,n)}return U(t,e)?S(t,e,n):c(e,n)}function P(t,e){if(A.has(t))return A.get(t);let c=(t instanceof SVGElement?q:$).bind(null,t,"Attribute"),r=E(e);return{setRemoveAttr:c,s:r}}function W(t,e){let n=E(this);return O(n,e,(c,r)=>t.classList.toggle(c,r===-1?void 0:!!r)),t}function Q(t){return Array.from(t.children).forEach(e=>e.remove()),t}function U(t,e){if(!Reflect.has(t,e))return!1;let n=j(t,e);return!g(n.set)}function j(t,e){if(t=Object.getPrototypeOf(t),!t)return{};let n=Object.getOwnPropertyDescriptor(t,e);return n||j(t,e)}function O(t,e,n){if(!(typeof e!="object"||e===null))return Object.entries(e).forEach(function([r,u]){r&&(u=t.processReactiveAttribute(e,r,u,n),n(r,u))})}function T(t){return Array.isArray(t)?t.filter(Boolean).join(" "):t}function $(t,e,n,c){return t[(g(c)?"remove":"set")+e](n,T(c))}function q(t,e,n,c,r=null){return t[(g(c)?"remove":"set")+e+"NS"](r,n,T(c))}function L(t,e,n){if(Reflect.set(t,e,n),!!g(n))return Reflect.deleteProperty(t,e)}function k(t,e,...n){let c=n.length?new CustomEvent(e,{detail:n[0]}):new Event(e);return t.dispatchEvent(c)}function C(t,e,n){return function(r){return r.addEventListener(t,e,n),r}}var y=H(),z=new WeakSet;C.connected=function(t,e){let n="connected";return typeof e!="object"&&(e={}),e.once=!0,function(r){let u="dde:"+n;return r.addEventListener(u,t,e),r.__dde_lifecycleToEvents?r:r.isConnected?(r.dispatchEvent(new Event(u)),r):(_(e.signal,()=>y.offConnected(r,t))&&y.onConnected(r,t),r)}};C.disconnected=function(t,e){let n="disconnected";return typeof e!="object"&&(e={}),e.once=!0,function(r){let u="dde:"+n;return r.addEventListener(u,t,e),r.__dde_lifecycleToEvents||_(e.signal,()=>y.offDisconnected(r,t))&&y.onDisconnected(r,t),r}};C.attributeChanged=function(t,e){let n="attributeChanged";return typeof e!="object"&&(e={}),function(r){let u="dde:"+n;if(r.addEventListener(u,t,e),r.__dde_lifecycleToEvents||z.has(r))return r;let f=new MutationObserver(function(d){for(let{attributeName:l,target:h}of d)h.dispatchEvent(new CustomEvent(u,{detail:[l,h.getAttribute(l)]}))});return _(e.signal,()=>f.disconnect())&&f.observe(r,{attributes:!0}),r}};function H(){let t=new Map,e=!1,n=new MutationObserver(function(o){for(let s of o)if(s.type==="childList"){if(l(s.addedNodes,!0)){f();continue}h(s.removedNodes,!0)&&f()}});return{onConnected(o,s){u();let i=r(o);i.connected.has(s)||(i.connected.add(s),i.length_c+=1)},offConnected(o,s){if(!t.has(o))return;let i=t.get(o);i.connected.has(s)&&(i.connected.delete(s),i.length_c-=1,c(o,i))},onDisconnected(o,s){u();let i=r(o);i.disconnected.has(s)||(i.disconnected.add(s),i.length_d+=1)},offDisconnected(o,s){if(!t.has(o))return;let i=t.get(o);i.disconnected.has(s)&&(i.disconnected.delete(s),i.length_d-=1,c(o,i))}};function c(o,s){s.length_c||s.length_d||(t.delete(o),f())}function r(o){if(t.has(o))return t.get(o);let s={connected:new WeakSet,length_c:0,disconnected:new WeakSet,length_d:0};return t.set(o,s),s}function u(){e||(e=!0,n.observe(document.body,{childList:!0,subtree:!0}))}function f(){!e||t.size||(e=!1,n.disconnect())}function a(){return new Promise(function(o){(requestIdleCallback||requestAnimationFrame)(o)})}async function d(o){t.size>30&&await a();let s=[];if(!(o instanceof Node))return s;for(let i of t.keys())i===o||!(i instanceof Node)||o.contains(i)&&s.push(i);return s}function l(o,s){let i=!1;for(let p of o){if(s&&d(p).then(l),!t.has(p))continue;let m=t.get(p);m.length_c&&(p.dispatchEvent(new Event("dde:connected")),m.connected=new WeakSet,m.length_c=0,m.length_d||t.delete(p),i=!0)}return i}function h(o,s){let i=!1;for(let p of o)s&&d(p).then(h),!(!t.has(p)||!t.get(p).length_d)&&(p.dispatchEvent(new Event("dde:disconnected")),t.delete(p),i=!0);return i}}typeof document.createDocumentFragment().append()>"u"&&[HTMLElement,SVGElement,DocumentFragment].forEach(t=>{let{append:e}=t.prototype;t.prototype.append=function(...n){return e.apply(this,n),this}}); +var m={isSignal(t){return!1},processReactiveAttribute(t,e,n,o){return n}};function $(t,e=!0){return e?Object.assign(m,t):(Object.setPrototypeOf(t,m),t)}function _(t){return m.isPrototypeOf(t)&&t!==m?t:m}function l(t){return typeof t>"u"}function x(t,e){if(!t||!(t instanceof AbortSignal))return!0;if(!t.aborted)return t.addEventListener("abort",e),function(){t.removeEventListener("abort",e)}}var y={setDeleteAttr:U};function U(t,e,n){if(Reflect.set(t,e,n),!!l(n)){if(Reflect.deleteProperty(t,e),t instanceof HTMLElement&&t.getAttribute(e)==="undefined")return t.removeAttribute(e);if(Reflect.get(t,e)==="undefined")return Reflect.set(t,e,"")}}var v=[{scope:document.body,host:t=>t?t(document.body):document.body,prevent:!0}],L={get current(){return v[v.length-1]},get host(){return this.current.host},preventDefault(){let{current:t}=this;return t.prevent=!0,t},get state(){return[...v]},push(t={}){return v.push(Object.assign({},this.current,{prevent:!1},t))},pop(){return v.pop()}},A;function E(t,e,...n){let o=_(this),r=0,c,f;switch((Object(e)!==e||o.isSignal(e))&&(e={textContent:e}),!0){case typeof t=="function":{r=1,L.push({scope:t,host:h=>h?(r===1?n.unshift(h):h(f),void 0):f}),c=t(e||void 0);let d=c instanceof DocumentFragment,a=E.mark({type:"component",name:t.name,host:d?"this":c.nodeName==="#comment"?"previousLater":"parentElement"});c.prepend(a),d&&(f=a);break}case t==="#text":c=w.call(this,document.createTextNode(""),e);break;case(t==="<>"||!t):c=w.call(this,document.createDocumentFragment(),e);break;case A:c=w.call(this,document.createElementNS(A,t),e);break;case!c:c=w.call(this,document.createElement(t),e)}return B(c),f||(f=c),n.forEach(d=>d(f)),r&&L.pop(),r=2,c}E.mark=function(t,e=!1){t=Object.entries(t).map(([r,c])=>r+`="${c}"`).join(" ");let n=e?"":"/",o=document.createComment(``);return e||(o.end=document.createComment("")),o};E.later=function(){let t=E.mark({type:"later"});return t.append=t.prepend=function(...e){return t.after(...e),t},t};function Q(t){let e=this;return function(...o){A=t;let r=E.call(e,...o);return A=void 0,r}}var{setDeleteAttr:N}=y,O=new WeakMap;function w(t,...e){if(!e.length)return t;O.set(t,T(t,this));for(let[n,o]of Object.entries(Object.assign({},...e)))P.call(this,t,n,o);return O.delete(t),t}function P(t,e,n){let{setRemoveAttr:o,s:r}=T(t,this),c=this;n=r.processReactiveAttribute(t,e,n,(d,a)=>P.call(c,t,d,a));let[f]=e;if(f==="=")return o(e.slice(1),n);if(f===".")return D(t,e.slice(1),n);if(/(aria|data)([A-Z])/.test(e))return e=e.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase(),o(e,n);switch(e==="className"&&(e="class"),e){case"xlink:href":return o(e,n,"http://www.w3.org/1999/xlink");case"textContent":return N(t,e,n);case"style":if(typeof n!="object")break;case"dataset":return S(r,n,D.bind(null,t[e]));case"ariaset":return S(r,n,(d,a)=>o("aria-"+d,a));case"classList":return q.call(c,t,n)}return z(t,e)?N(t,e,n):o(e,n)}function T(t,e){if(O.has(t))return O.get(t);let o=(t instanceof SVGElement?k:F).bind(null,t,"Attribute"),r=_(e);return{setRemoveAttr:o,s:r}}function q(t,e){let n=_(this);return S(n,e,(o,r)=>t.classList.toggle(o,r===-1?void 0:!!r)),t}function Y(t){return Array.from(t.children).forEach(e=>e.remove()),t}function z(t,e){if(!Reflect.has(t,e))return!1;let n=W(t,e);return!l(n.set)}function W(t,e){if(t=Object.getPrototypeOf(t),!t)return{};let n=Object.getOwnPropertyDescriptor(t,e);return n||W(t,e)}function S(t,e,n){if(!(typeof e!="object"||e===null))return Object.entries(e).forEach(function([r,c]){r&&(c=t.processReactiveAttribute(e,r,c,n),n(r,c))})}function M(t){return Array.isArray(t)?t.filter(Boolean).join(" "):t}function F(t,e,n,o){return t[(l(o)?"remove":"set")+e](n,M(o))}function k(t,e,n,o,r=null){return t[(l(o)?"remove":"set")+e+"NS"](r,n,M(o))}function D(t,e,n){if(Reflect.set(t,e,n),!!l(n))return Reflect.deleteProperty(t,e)}function j(...t){return this.appendOrig(...t),this}function B(t){return t.append===j||(t.appendOrig=t.append,t.append=j),t}function nt(t,e,...n){let o=n.length?new CustomEvent(e,{detail:n[0]}):new Event(e);return t.dispatchEvent(o)}function R(t,e,n){return function(r){return r.addEventListener(t,e,n),r}}var C=Z(),I=new WeakSet;R.connected=function(t,e){let n="connected";return typeof e!="object"&&(e={}),e.once=!0,function(r){let c="dde:"+n;return r.addEventListener(c,t,e),r.__dde_lifecycleToEvents?r:r.isConnected?(r.dispatchEvent(new Event(c)),r):(x(e.signal,()=>C.offConnected(r,t))&&C.onConnected(r,t),r)}};R.disconnected=function(t,e){let n="disconnected";return typeof e!="object"&&(e={}),e.once=!0,function(r){let c="dde:"+n;return r.addEventListener(c,t,e),r.__dde_lifecycleToEvents||x(e.signal,()=>C.offDisconnected(r,t))&&C.onDisconnected(r,t),r}};R.attributeChanged=function(t,e){let n="attributeChanged";return typeof e!="object"&&(e={}),function(r){let c="dde:"+n;if(r.addEventListener(c,t,e),r.__dde_lifecycleToEvents||I.has(r))return r;let f=new MutationObserver(function(a){for(let{attributeName:h,target:g}of a)g.dispatchEvent(new CustomEvent(c,{detail:[h,g.getAttribute(h)]}))});return x(e.signal,()=>f.disconnect())&&f.observe(r,{attributes:!0}),r}};function Z(){let t=new Map,e=!1,n=new MutationObserver(function(s){for(let i of s)if(i.type==="childList"){if(h(i.addedNodes,!0)){f();continue}g(i.removedNodes,!0)&&f()}});return{onConnected(s,i){c();let u=r(s);u.connected.has(i)||(u.connected.add(i),u.length_c+=1)},offConnected(s,i){if(!t.has(s))return;let u=t.get(s);u.connected.has(i)&&(u.connected.delete(i),u.length_c-=1,o(s,u))},onDisconnected(s,i){c();let u=r(s);u.disconnected.has(i)||(u.disconnected.add(i),u.length_d+=1)},offDisconnected(s,i){if(!t.has(s))return;let u=t.get(s);u.disconnected.has(i)&&(u.disconnected.delete(i),u.length_d-=1,o(s,u))}};function o(s,i){i.length_c||i.length_d||(t.delete(s),f())}function r(s){if(t.has(s))return t.get(s);let i={connected:new WeakSet,length_c:0,disconnected:new WeakSet,length_d:0};return t.set(s,i),i}function c(){e||(e=!0,n.observe(document.body,{childList:!0,subtree:!0}))}function f(){!e||t.size||(e=!1,n.disconnect())}function d(){return new Promise(function(s){(requestIdleCallback||requestAnimationFrame)(s)})}async function a(s){t.size>30&&await d();let i=[];if(!(s instanceof Node))return i;for(let u of t.keys())u===s||!(u instanceof Node)||s.contains(u)&&i.push(u);return i}function h(s,i){let u=!1;for(let p of s){if(i&&a(p).then(h),!t.has(p))continue;let b=t.get(p);b.length_c&&(p.dispatchEvent(new Event("dde:connected")),b.connected=new WeakSet,b.length_c=0,b.length_d||t.delete(p),u=!0)}return u}function g(s,i){let u=!1;for(let p of s)i&&a(p).then(g),!(!t.has(p)||!t.get(p).length_d)&&(p.dispatchEvent(new Event("dde:disconnected")),t.delete(p),u=!0);return u}} globalThis.dde= {assign: w, -assignAttribute: N, -classListDeclarative: W, -createElement: J, -dispatchEvent: k, -el: J, -empty: Q, -on: C, -registerReactivity: F, -scope: x +assignAttribute: P, +classListDeclarative: q, +createElement: E, +createElementNS: Q, +dispatchEvent: nt, +el: E, +elNS: Q, +empty: Y, +on: R, +registerReactivity: $, +scope: L }; })(); \ No newline at end of file diff --git a/dist/esm-with-signals.d.ts b/dist/esm-with-signals.d.ts index 0c0dacb..43a145c 100644 --- a/dist/esm-with-signals.d.ts +++ b/dist/esm-with-signals.d.ts @@ -1,16 +1,18 @@ +type CustomElementTagNameMap= { '#text': Text, '#comment': Comment } +type SupportedElement= + HTMLElementTagNameMap[keyof HTMLElementTagNameMap] + | SVGElementTagNameMap[keyof SVGElementTagNameMap] + | MathMLElementTagNameMap[keyof MathMLElementTagNameMap] + | CustomElementTagNameMap[keyof CustomElementTagNameMap]; declare global { type ddeComponentAttributes= Record | undefined | string; - type ddeElementModifier= (element: El)=> El; + type ddeElementModifier= (element: El)=> El; } -type ElementTagNameMap= HTMLElementTagNameMap & { // & SVGElementTagNameMap - '#text': Text -} -type Element= ElementTagNameMap[keyof ElementTagNameMap]; type AttrsModified= { /** - * In fact argumen for `*.setAttribute("style", *)`. + * Use string like in HTML (internally uses `*.setAttribute("style", *)`), or object representation (like DOM API). */ - style: string + style: string | Partial /** * 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. */ @@ -32,36 +34,59 @@ type AttrsModified= { * There is added support for `data[A-Z].*`/`aria[A-Z].*` to be converted to the kebab-case alternatives. * @private */ -type ElementAttributes= - T extends keyof ElementTagNameMap ? - Omit & AttrsModified : - Omit & AttrsModified; -export function assign(element: El, ...attrs_array: Partial>[]): El -export function el( +type ElementAttributes= Omit & AttrsModified; +export function assign(element: El, ...attrs_array: Partial>[]): El +type ExtendedHTMLElementTagNameMap= HTMLElementTagNameMap & CustomElementTagNameMap +interface element{ + prototype: el; + append(...els: (SupportedElement | DocumentFragment | string | element)[]): el +} +export function el( tag_name: TAG, - attrs?: Partial>, - ...modifiers: ddeElementModifier[] -): ElementTagNameMap[TAG] + attrs?: string | Partial>, + ...modifiers: ddeElementModifier[] +): element export function el( tag_name?: "<>", -): DocumentFragment +): element export function el< A extends ddeComponentAttributes, - C extends (attr: A)=> Element | DocumentFragment>( + C extends (attr: A)=> SupportedElement | DocumentFragment>( fComponent: C, attrs?: A, ...modifiers: ddeElementModifier>[] -): ReturnType +): element> export function el( tag_name: string, - attrs?: Record, - ...modifiers: ddeElementModifier[] -): HTMLElement -export function dispatchEvent(element: HTMLElement, name: keyof DocumentEventMap): void; -export function dispatchEvent(element: HTMLElement, name: string, data: any): void; + attrs?: string | Record, + ...modifiers: ddeElementModifier[] +): element +export function elNS( + namespace: "http://www.w3.org/2000/svg" +): ( + tag_name: TAG, + attrs?: string | Partial<{ [key in KEYS]: SVGElementTagNameMap[TAG][key] | string | number | boolean }>, + ...modifiers: ddeElementModifier[] +)=> element +export function elNS( + namespace: "http://www.w3.org/1998/Math/MathML" +): ( + tag_name: TAG, + attrs?: string | Partial<{ [key in KEYS]: MathMLElementTagNameMap[TAG][key] | string | number | boolean }>, + ...modifiers: ddeElementModifier[] +)=> element +export function elNS( + namespace: string +): ( + tag_name: string, + attrs?: string | Record, + ...modifiers: ddeElementModifier[] +)=> element +export function dispatchEvent(element: SupportedElement, name: keyof DocumentEventMap): void; +export function dispatchEvent(element: SupportedElement, name: string, data: any): void; interface On{ < - EE extends ddeElementModifier, + EE extends ddeElementModifier, El extends ( EE extends ddeElementModifier ? El : never ), Event extends keyof DocumentEventMap>( type: Event, @@ -69,14 +94,14 @@ interface On{ options?: AddEventListenerOptions ) : EE; connected< - EE extends ddeElementModifier, + EE extends ddeElementModifier, El extends ( EE extends ddeElementModifier ? El : never ) >( listener: (el: El) => any, options?: AddEventListenerOptions ) : EE; disconnected< - EE extends ddeElementModifier, + EE extends ddeElementModifier, El extends ( EE extends ddeElementModifier ? El : never ) >( listener: (el: El) => any, @@ -85,126 +110,8 @@ interface On{ } export const on: On; export const scope: { - namespace: string, host: ddeElementModifier, - elNamespace: (ns: string)=> ({ append(...els: (HTMLElement | SVGElement)[]): HTMLElement | SVGElement | DocumentFragment }) }; -//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; } -} export type Signal= (set?: V)=> V & A; type Action= (this: { value: V }, ...a: any[])=> typeof S._ | void; type SymbolOnclear= Symbol; diff --git a/dist/esm-with-signals.js b/dist/esm-with-signals.js index d39c21c..d2ff843 100644 --- a/dist/esm-with-signals.js +++ b/dist/esm-with-signals.js @@ -1,4 +1,4 @@ -var w={isSignal(t){return!1},processReactiveAttribute(t,e,n,r){return n}};function k(t,e=!0){return e?Object.assign(w,t):(Object.setPrototypeOf(t,w),t)}function O(t){return w.isPrototypeOf(t)&&t!==w?t:w}function _(t){return typeof t>"u"}function W(t){let e=typeof t;return e!=="object"?e:t===null?"null":Object.prototype.toString.call(t)}function R(t,e){if(!t||!(t instanceof AbortSignal))return!0;if(!t.aborted)return t.addEventListener("abort",e),function(){t.removeEventListener("abort",e)}}var $={setDeleteAttr:K};function K(t,e,n){if(Reflect.set(t,e,n),!!_(n)){if(Reflect.deleteProperty(t,e),t instanceof HTMLElement&&t.getAttribute(e)==="undefined")return t.removeAttribute(e);if(Reflect.get(t,e)==="undefined")return Reflect.set(t,e,"")}}var y=[{scope:document.body,namespace:"html",host:t=>t?t(document.body):document.body,prevent:!0}],z=t=>t==="svg"?"http://www.w3.org/2000/svg":t,b={get current(){return y[y.length-1]},get host(){return this.current.host},get namespace(){return this.current.namespace},set namespace(t){return this.current.namespace=z(t)},preventDefault(){let{current:t}=this;return t.prevent=!0,t},elNamespace(t){let e=this.namespace;return this.namespace=t,{append(...n){return b.namespace=e,n.length===1?n[0]:document.createDocumentFragment().append(...n)}}},get state(){return[...y]},push(t={}){return t.namespace&&(t.namespace=z(t.namespace)),y.push(Object.assign({},this.current,{prevent:!1},t))},pop(){return y.pop()}};function ht(t,e,...n){let r=O(this),{namespace:o}=b,c=0,s,d;switch((Object(e)!==e||r.isSignal(e))&&(e={textContent:e}),!0){case typeof t=="function":{c=1,b.push({scope:t,host:E=>E?(c===1?n.unshift(E):E(d),void 0):d}),s=t(e||void 0);let a=s instanceof DocumentFragment,g=document.createComment(``);s.prepend(g),a&&(d=g);break}case t==="#text":s=C.call(this,document.createTextNode(""),e);break;case(t==="<>"||!t):s=C.call(this,document.createDocumentFragment(),e);break;case o!=="html":s=C.call(this,document.createElementNS(o,t),e);break;case!s:s=C.call(this,document.createElement(t),e)}return d||(d=s),n.forEach(a=>a(d)),c&&b.pop(),c=2,s}var{setDeleteAttr:H}=$,L=new WeakMap;function C(t,...e){if(!e.length)return t;L.set(t,B(t,this));for(let[n,r]of Object.entries(Object.assign({},...e)))q.call(this,t,n,r);return L.delete(t),t}function q(t,e,n){let{setRemoveAttr:r,s:o}=B(t,this),c=this;n=o.processReactiveAttribute(t,e,n,(d,a)=>q.call(c,t,d,a));let[s]=e;if(s==="=")return r(e.slice(1),n);if(s===".")return U(t,e.slice(1),n);if(/(aria|data)([A-Z])/.test(e))return e=e.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase(),r(e,n);switch(e==="className"&&(e="class"),e){case"xlink:href":return r(e,n,"http://www.w3.org/1999/xlink");case"textContent":return H(t,e,n);case"style":if(typeof n!="object")break;case"dataset":return T(o,n,U.bind(null,t[e]));case"ariaset":return T(o,n,(d,a)=>r("aria-"+d,a));case"classList":return Q.call(c,t,n)}return X(t,e)?H(t,e,n):r(e,n)}function B(t,e){if(L.has(t))return L.get(t);let r=(t instanceof SVGElement?tt:Y).bind(null,t,"Attribute"),o=O(e);return{setRemoveAttr:r,s:o}}function Q(t,e){let n=O(this);return T(n,e,(r,o)=>t.classList.toggle(r,o===-1?void 0:!!o)),t}function gt(t){return Array.from(t.children).forEach(e=>e.remove()),t}function X(t,e){if(!Reflect.has(t,e))return!1;let n=G(t,e);return!_(n.set)}function G(t,e){if(t=Object.getPrototypeOf(t),!t)return{};let n=Object.getOwnPropertyDescriptor(t,e);return n||G(t,e)}function T(t,e,n){if(!(typeof e!="object"||e===null))return Object.entries(e).forEach(function([o,c]){o&&(c=t.processReactiveAttribute(e,o,c,n),n(o,c))})}function I(t){return Array.isArray(t)?t.filter(Boolean).join(" "):t}function Y(t,e,n,r){return t[(_(r)?"remove":"set")+e](n,I(r))}function tt(t,e,n,r,o=null){return t[(_(r)?"remove":"set")+e+"NS"](o,n,I(r))}function U(t,e,n){if(Reflect.set(t,e,n),!!_(n))return Reflect.deleteProperty(t,e)}function Et(t,e,...n){let r=n.length?new CustomEvent(e,{detail:n[0]}):new Event(e);return t.dispatchEvent(r)}function v(t,e,n){return function(o){return o.addEventListener(t,e,n),o}}var D=nt(),et=new WeakSet;v.connected=function(t,e){let n="connected";return typeof e!="object"&&(e={}),e.once=!0,function(o){let c="dde:"+n;return o.addEventListener(c,t,e),o.__dde_lifecycleToEvents?o:o.isConnected?(o.dispatchEvent(new Event(c)),o):(R(e.signal,()=>D.offConnected(o,t))&&D.onConnected(o,t),o)}};v.disconnected=function(t,e){let n="disconnected";return typeof e!="object"&&(e={}),e.once=!0,function(o){let c="dde:"+n;return o.addEventListener(c,t,e),o.__dde_lifecycleToEvents||R(e.signal,()=>D.offDisconnected(o,t))&&D.onDisconnected(o,t),o}};v.attributeChanged=function(t,e){let n="attributeChanged";return typeof e!="object"&&(e={}),function(o){let c="dde:"+n;if(o.addEventListener(c,t,e),o.__dde_lifecycleToEvents||et.has(o))return o;let s=new MutationObserver(function(a){for(let{attributeName:g,target:E}of a)E.dispatchEvent(new CustomEvent(c,{detail:[g,E.getAttribute(g)]}))});return R(e.signal,()=>s.disconnect())&&s.observe(o,{attributes:!0}),o}};function nt(){let t=new Map,e=!1,n=new MutationObserver(function(i){for(let u of i)if(u.type==="childList"){if(g(u.addedNodes,!0)){s();continue}E(u.removedNodes,!0)&&s()}});return{onConnected(i,u){c();let f=o(i);f.connected.has(u)||(f.connected.add(u),f.length_c+=1)},offConnected(i,u){if(!t.has(i))return;let f=t.get(i);f.connected.has(u)&&(f.connected.delete(u),f.length_c-=1,r(i,f))},onDisconnected(i,u){c();let f=o(i);f.disconnected.has(u)||(f.disconnected.add(u),f.length_d+=1)},offDisconnected(i,u){if(!t.has(i))return;let f=t.get(i);f.disconnected.has(u)&&(f.disconnected.delete(u),f.length_d-=1,r(i,f))}};function r(i,u){u.length_c||u.length_d||(t.delete(i),s())}function o(i){if(t.has(i))return t.get(i);let u={connected:new WeakSet,length_c:0,disconnected:new WeakSet,length_d:0};return t.set(i,u),u}function c(){e||(e=!0,n.observe(document.body,{childList:!0,subtree:!0}))}function s(){!e||t.size||(e=!1,n.disconnect())}function d(){return new Promise(function(i){(requestIdleCallback||requestAnimationFrame)(i)})}async function a(i){t.size>30&&await d();let u=[];if(!(i instanceof Node))return u;for(let f of t.keys())f===i||!(f instanceof Node)||i.contains(f)&&u.push(f);return u}function g(i,u){let f=!1;for(let m of i){if(u&&a(m).then(g),!t.has(m))continue;let x=t.get(m);x.length_c&&(m.dispatchEvent(new Event("dde:connected")),x.connected=new WeakSet,x.length_c=0,x.length_d||t.delete(m),f=!0)}return f}function E(i,u){let f=!1;for(let m of i)u&&a(m).then(E),!(!t.has(m)||!t.get(m).length_d)&&(m.dispatchEvent(new Event("dde:disconnected")),t.delete(m),f=!0);return f}}typeof document.createDocumentFragment().append()>"u"&&[HTMLElement,SVGElement,DocumentFragment].forEach(t=>{let{append:e}=t.prototype;t.prototype.append=function(...n){return e.apply(this,n),this}});var p=Symbol.for("Signal");function P(t){try{return Reflect.has(t,p)}catch{return!1}}var j=[],h=new WeakMap;function l(t,e){if(typeof t!="function")return J(t,e);if(P(t))return t;let n=J(),r=function(){let[o,...c]=h.get(r);if(h.set(r,new Set([o])),j.push(r),n(t()),j.pop(),!c.length)return;let s=h.get(r);for(let d of c)s.has(d)||A(d,r)};return h.set(n[p],r),h.set(r,new Set([n])),r(),n}l.action=function(t,e,...n){let r=t[p],{actions:o}=r;if(!o||!Reflect.has(o,e))throw new Error(`'${t}' has no action with name '${e}'!`);if(o[e].apply(r,n),r.skip)return Reflect.deleteProperty(r,"skip");r.listeners.forEach(c=>c(r.value))};l.on=function t(e,n,r={}){let{signal:o}=r;if(!(o&&o.aborted)){if(Array.isArray(e))return e.forEach(c=>t(c,n,r));M(e,n),o&&o.addEventListener("abort",()=>A(e,n))}};l.symbols={signal:p,onclear:Symbol.for("Signal.onclear")};var S="__dde_attributes";l.attribute=function(t,e=void 0){let n=l(e);return b.host(r=>{if(r instanceof HTMLElement?r.hasAttribute(t)&&n(r.getAttribute(t)):r.hasAttributeNS(null,t)&&n(r.getAttributeNS(null,t)),r[S]){r[S][t]=n;return}return r[S]={[t]:n},v.attributeChanged(function({detail:c}){/*! This maps attributes to signals (`S.attribute`). -* Investigate `__dde_attributes` key of the element.*/let[s,d]=c,a=r[S][s];a&&a(d)})(r),v.disconnected(function(){/*! This removes all signals mapped to attributes (`S.attribute`). -* Investigate `__dde_attributes` key of the element.*/l.clear(...Object.values(r[S]))})(r),r}),n};l.clear=function(...t){for(let n of t){Reflect.deleteProperty(n,"toJSON");let r=n[p];r.onclear.forEach(o=>o.call(r)),e(n,r),Reflect.deleteProperty(n,p)}function e(n,r){r.listeners.forEach(o=>{if(r.listeners.delete(o),!h.has(o))return;let c=h.get(o);c.delete(n),!(c.size>1)&&(l.clear(...c),h.delete(o))})}};var N="__dde_reactive";l.el=function(t,e){let n=document.createComment(''),r=document.createComment(""),o=document.createDocumentFragment();o.append(n,r);let{current:c}=b,s=d=>{if(!n.parentNode||!r.parentNode)return A(t,s);b.push(c);let a=e(d);b.pop(),Array.isArray(a)||(a=[a]);let g=n;for(;(g=n.nextSibling)!==r;)g.remove();n.after(...a)};return M(t,s),Z(t,s,n,e),s(t()),o};var V={isSignal:P,processReactiveAttribute(t,e,n,r){if(!P(n))return n;let o=c=>r(e,c);return M(n,o),Z(n,o,t,e),n()}};function Z(t,e,...n){let{current:r}=b;r.prevent||r.host(function(o){o[N]||(o[N]=[],v.disconnected(()=>o[N].forEach(([[c,s]])=>A(c,s,c[p]?.host()===o)))(o)),o[N].push([[t,e],...n])})}function J(t,e){let n=(...r)=>r.length?it(n,...r):st(n);return ot(n,t,e)}var rt=Object.assign(Object.create(null),{stopPropagation(){this.skip=!0}}),F=class extends Error{constructor(){super();let[e,...n]=this.stack.split(` -`),r=e.slice(e.indexOf("@"),e.indexOf(".js:")+4);this.stack=n.find(o=>!o.includes(r))}};function ot(t,e,n){let r=[];W(n)!=="[object Object]"&&(n={});let{onclear:o}=l.symbols;n[o]&&(r.push(n[o]),Reflect.deleteProperty(n,o));let{host:c}=b;return Reflect.defineProperty(t,p,{value:{value:e,actions:n,onclear:r,host:c,listeners:new Set,defined:new F},enumerable:!1,writable:!1,configurable:!0}),t.toJSON=()=>t(),Object.setPrototypeOf(t[p],rt),t}function ct(){return j[j.length-1]}function st(t){if(!t[p])return;let{value:e,listeners:n}=t[p],r=ct();return r&&n.add(r),h.has(r)&&h.get(r).add(t),e}function it(t,e,n){if(!t[p])return;let r=t[p];if(!(!n&&r.value===e))return r.value=e,r.listeners.forEach(o=>o(e)),e}function M(t,e){if(t[p])return t[p].listeners.add(e)}function A(t,e,n){let r=t[p];if(!r)return;let o=r.listeners.delete(e);if(n&&!r.listeners.size){if(l.clear(t),!h.has(r))return o;let c=h.get(r);if(!h.has(c))return o;h.get(c).forEach(s=>A(s,c,!0))}return o}k(V);export{l as S,C as assign,q as assignAttribute,Q as classListDeclarative,ht as createElement,Et as dispatchEvent,ht as el,gt as empty,P as isSignal,v as on,k as registerReactivity,b as scope}; +var y={isSignal(t){return!1},processReactiveAttribute(t,e,n,r){return n}};function W(t,e=!0){return e?Object.assign(y,t):(Object.setPrototypeOf(t,y),t)}function R(t){return y.isPrototypeOf(t)&&t!==y?t:y}function _(t){return typeof t>"u"}function F(t){let e=typeof t;return e!=="object"?e:t===null?"null":Object.prototype.toString.call(t)}function C(t,e){if(!t||!(t instanceof AbortSignal))return!0;if(!t.aborted)return t.addEventListener("abort",e),function(){t.removeEventListener("abort",e)}}var U={setDeleteAttr:X};function X(t,e,n){if(Reflect.set(t,e,n),!!_(n)){if(Reflect.deleteProperty(t,e),t instanceof HTMLElement&&t.getAttribute(e)==="undefined")return t.removeAttribute(e);if(Reflect.get(t,e)==="undefined")return Reflect.set(t,e,"")}}var w=[{scope:document.body,host:t=>t?t(document.body):document.body,prevent:!0}],E={get current(){return w[w.length-1]},get host(){return this.current.host},preventDefault(){let{current:t}=this;return t.prevent=!0,t},get state(){return[...w]},push(t={}){return w.push(Object.assign({},this.current,{prevent:!1},t))},pop(){return w.pop()}},L;function m(t,e,...n){let r=R(this),o=0,c,s;switch((Object(e)!==e||r.isSignal(e))&&(e={textContent:e}),!0){case typeof t=="function":{o=1,E.push({scope:t,host:h=>h?(o===1?n.unshift(h):h(s),void 0):s}),c=t(e||void 0);let d=c instanceof DocumentFragment,a=m.mark({type:"component",name:t.name,host:d?"this":c.nodeName==="#comment"?"previousLater":"parentElement"});c.prepend(a),d&&(s=a);break}case t==="#text":c=N.call(this,document.createTextNode(""),e);break;case(t==="<>"||!t):c=N.call(this,document.createDocumentFragment(),e);break;case L:c=N.call(this,document.createElementNS(L,t),e);break;case!c:c=N.call(this,document.createElement(t),e)}return rt(c),s||(s=c),n.forEach(d=>d(s)),o&&E.pop(),o=2,c}m.mark=function(t,e=!1){t=Object.entries(t).map(([o,c])=>o+`="${c}"`).join(" ");let n=e?"":"/",r=document.createComment(``);return e||(r.end=document.createComment("")),r};m.later=function(){let t=m.mark({type:"later"});return t.append=t.prepend=function(...e){return t.after(...e),t},t};function bt(t){let e=this;return function(...r){L=t;let o=m.call(e,...r);return L=void 0,o}}var{setDeleteAttr:q}=U,j=new WeakMap;function N(t,...e){if(!e.length)return t;j.set(t,J(t,this));for(let[n,r]of Object.entries(Object.assign({},...e)))I.call(this,t,n,r);return j.delete(t),t}function I(t,e,n){let{setRemoveAttr:r,s:o}=J(t,this),c=this;n=o.processReactiveAttribute(t,e,n,(d,a)=>I.call(c,t,d,a));let[s]=e;if(s==="=")return r(e.slice(1),n);if(s===".")return B(t,e.slice(1),n);if(/(aria|data)([A-Z])/.test(e))return e=e.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase(),r(e,n);switch(e==="className"&&(e="class"),e){case"xlink:href":return r(e,n,"http://www.w3.org/1999/xlink");case"textContent":return q(t,e,n);case"style":if(typeof n!="object")break;case"dataset":return M(o,n,B.bind(null,t[e]));case"ariaset":return M(o,n,(d,a)=>r("aria-"+d,a));case"classList":return Y.call(c,t,n)}return tt(t,e)?q(t,e,n):r(e,n)}function J(t,e){if(j.has(t))return j.get(t);let r=(t instanceof SVGElement?nt:et).bind(null,t,"Attribute"),o=R(e);return{setRemoveAttr:r,s:o}}function Y(t,e){let n=R(this);return M(n,e,(r,o)=>t.classList.toggle(r,o===-1?void 0:!!o)),t}function _t(t){return Array.from(t.children).forEach(e=>e.remove()),t}function tt(t,e){if(!Reflect.has(t,e))return!1;let n=Z(t,e);return!_(n.set)}function Z(t,e){if(t=Object.getPrototypeOf(t),!t)return{};let n=Object.getOwnPropertyDescriptor(t,e);return n||Z(t,e)}function M(t,e,n){if(!(typeof e!="object"||e===null))return Object.entries(e).forEach(function([o,c]){o&&(c=t.processReactiveAttribute(e,o,c,n),n(o,c))})}function G(t){return Array.isArray(t)?t.filter(Boolean).join(" "):t}function et(t,e,n,r){return t[(_(r)?"remove":"set")+e](n,G(r))}function nt(t,e,n,r,o=null){return t[(_(r)?"remove":"set")+e+"NS"](o,n,G(r))}function B(t,e,n){if(Reflect.set(t,e,n),!!_(n))return Reflect.deleteProperty(t,e)}function H(...t){return this.appendOrig(...t),this}function rt(t){return t.append===H||(t.appendOrig=t.append,t.append=H),t}function xt(t,e,...n){let r=n.length?new CustomEvent(e,{detail:n[0]}):new Event(e);return t.dispatchEvent(r)}function v(t,e,n){return function(o){return o.addEventListener(t,e,n),o}}var P=ct(),ot=new WeakSet;v.connected=function(t,e){let n="connected";return typeof e!="object"&&(e={}),e.once=!0,function(o){let c="dde:"+n;return o.addEventListener(c,t,e),o.__dde_lifecycleToEvents?o:o.isConnected?(o.dispatchEvent(new Event(c)),o):(C(e.signal,()=>P.offConnected(o,t))&&P.onConnected(o,t),o)}};v.disconnected=function(t,e){let n="disconnected";return typeof e!="object"&&(e={}),e.once=!0,function(o){let c="dde:"+n;return o.addEventListener(c,t,e),o.__dde_lifecycleToEvents||C(e.signal,()=>P.offDisconnected(o,t))&&P.onDisconnected(o,t),o}};v.attributeChanged=function(t,e){let n="attributeChanged";return typeof e!="object"&&(e={}),function(o){let c="dde:"+n;if(o.addEventListener(c,t,e),o.__dde_lifecycleToEvents||ot.has(o))return o;let s=new MutationObserver(function(a){for(let{attributeName:h,target:x}of a)x.dispatchEvent(new CustomEvent(c,{detail:[h,x.getAttribute(h)]}))});return C(e.signal,()=>s.disconnect())&&s.observe(o,{attributes:!0}),o}};function ct(){let t=new Map,e=!1,n=new MutationObserver(function(i){for(let u of i)if(u.type==="childList"){if(h(u.addedNodes,!0)){s();continue}x(u.removedNodes,!0)&&s()}});return{onConnected(i,u){c();let f=o(i);f.connected.has(u)||(f.connected.add(u),f.length_c+=1)},offConnected(i,u){if(!t.has(i))return;let f=t.get(i);f.connected.has(u)&&(f.connected.delete(u),f.length_c-=1,r(i,f))},onDisconnected(i,u){c();let f=o(i);f.disconnected.has(u)||(f.disconnected.add(u),f.length_d+=1)},offDisconnected(i,u){if(!t.has(i))return;let f=t.get(i);f.disconnected.has(u)&&(f.disconnected.delete(u),f.length_d-=1,r(i,f))}};function r(i,u){u.length_c||u.length_d||(t.delete(i),s())}function o(i){if(t.has(i))return t.get(i);let u={connected:new WeakSet,length_c:0,disconnected:new WeakSet,length_d:0};return t.set(i,u),u}function c(){e||(e=!0,n.observe(document.body,{childList:!0,subtree:!0}))}function s(){!e||t.size||(e=!1,n.disconnect())}function d(){return new Promise(function(i){(requestIdleCallback||requestAnimationFrame)(i)})}async function a(i){t.size>30&&await d();let u=[];if(!(i instanceof Node))return u;for(let f of t.keys())f===i||!(f instanceof Node)||i.contains(f)&&u.push(f);return u}function h(i,u){let f=!1;for(let b of i){if(u&&a(b).then(h),!t.has(b))continue;let S=t.get(b);S.length_c&&(b.dispatchEvent(new Event("dde:connected")),S.connected=new WeakSet,S.length_c=0,S.length_d||t.delete(b),f=!0)}return f}function x(i,u){let f=!1;for(let b of i)u&&a(b).then(x),!(!t.has(b)||!t.get(b).length_d)&&(b.dispatchEvent(new Event("dde:disconnected")),t.delete(b),f=!0);return f}}var p=Symbol.for("Signal");function D(t){try{return Reflect.has(t,p)}catch{return!1}}var T=[],l=new WeakMap;function g(t,e){if(typeof t!="function")return V(t,e);if(D(t))return t;let n=V(),r=function(){let[o,...c]=l.get(r);if(l.set(r,new Set([o])),T.push(r),n(t()),T.pop(),!c.length)return;let s=l.get(r);for(let d of c)s.has(d)||O(d,r)};return l.set(n[p],r),l.set(r,new Set([n])),r(),n}g.action=function(t,e,...n){let r=t[p],{actions:o}=r;if(!o||!Reflect.has(o,e))throw new Error(`'${t}' has no action with name '${e}'!`);if(o[e].apply(r,n),r.skip)return Reflect.deleteProperty(r,"skip");r.listeners.forEach(c=>c(r.value))};g.on=function t(e,n,r={}){let{signal:o}=r;if(!(o&&o.aborted)){if(Array.isArray(e))return e.forEach(c=>t(c,n,r));z(e,n),o&&o.addEventListener("abort",()=>O(e,n))}};g.symbols={signal:p,onclear:Symbol.for("Signal.onclear")};var A="__dde_attributes";g.attribute=function(t,e=void 0){let n=g(e);return E.host(r=>{if(r instanceof HTMLElement?r.hasAttribute(t)&&n(r.getAttribute(t)):r.hasAttributeNS(null,t)&&n(r.getAttributeNS(null,t)),r[A]){r[A][t]=n;return}return r[A]={[t]:n},v.attributeChanged(function({detail:c}){/*! This maps attributes to signals (`S.attribute`). +* Investigate `__dde_attributes` key of the element.*/let[s,d]=c,a=r[A][s];a&&a(d)})(r),v.disconnected(function(){/*! This removes all signals mapped to attributes (`S.attribute`). +* Investigate `__dde_attributes` key of the element.*/g.clear(...Object.values(r[A]))})(r),r}),n};g.clear=function(...t){for(let n of t){Reflect.deleteProperty(n,"toJSON");let r=n[p];r.onclear.forEach(o=>o.call(r)),e(n,r),Reflect.deleteProperty(n,p)}function e(n,r){r.listeners.forEach(o=>{if(r.listeners.delete(o),!l.has(o))return;let c=l.get(o);c.delete(n),!(c.size>1)&&(g.clear(...c),l.delete(o))})}};var k="__dde_reactive";g.el=function(t,e){let n=m.mark({type:"reactive"},!1),r=n.end,o=document.createDocumentFragment();o.append(n,r);let{current:c}=E,s=d=>{if(!n.parentNode||!r.parentNode)return O(t,s);E.push(c);let a=e(d);E.pop(),Array.isArray(a)||(a=[a]);let h=n;for(;(h=n.nextSibling)!==r;)h.remove();n.after(...a)};return z(t,s),Q(t,s,n,e),s(t()),o};var K={isSignal:D,processReactiveAttribute(t,e,n,r){if(!D(n))return n;let o=c=>r(e,c);return z(n,o),Q(n,o,t,e),n()}};function Q(t,e,...n){let{current:r}=E;r.prevent||r.host(function(o){o[k]||(o[k]=[],v.disconnected(()=>o[k].forEach(([[c,s]])=>O(c,s,c[p]?.host()===o)))(o)),o[k].push([[t,e],...n])})}function V(t,e){let n=(...r)=>r.length?at(n,...r):ft(n);return it(n,t,e)}var st=Object.assign(Object.create(null),{stopPropagation(){this.skip=!0}}),$=class extends Error{constructor(){super();let[e,...n]=this.stack.split(` +`),r=e.slice(e.indexOf("@"),e.indexOf(".js:")+4);this.stack=n.find(o=>!o.includes(r))}};function it(t,e,n){let r=[];F(n)!=="[object Object]"&&(n={});let{onclear:o}=g.symbols;n[o]&&(r.push(n[o]),Reflect.deleteProperty(n,o));let{host:c}=E;return Reflect.defineProperty(t,p,{value:{value:e,actions:n,onclear:r,host:c,listeners:new Set,defined:new $},enumerable:!1,writable:!1,configurable:!0}),t.toJSON=()=>t(),Object.setPrototypeOf(t[p],st),t}function ut(){return T[T.length-1]}function ft(t){if(!t[p])return;let{value:e,listeners:n}=t[p],r=ut();return r&&n.add(r),l.has(r)&&l.get(r).add(t),e}function at(t,e,n){if(!t[p])return;let r=t[p];if(!(!n&&r.value===e))return r.value=e,r.listeners.forEach(o=>o(e)),e}function z(t,e){if(t[p])return t[p].listeners.add(e)}function O(t,e,n){let r=t[p];if(!r)return;let o=r.listeners.delete(e);if(n&&!r.listeners.size){if(g.clear(t),!l.has(r))return o;let c=l.get(r);if(!l.has(c))return o;l.get(c).forEach(s=>O(s,c,!0))}return o}W(K);export{g as S,N as assign,I as assignAttribute,Y as classListDeclarative,m as createElement,bt as createElementNS,xt as dispatchEvent,m as el,bt as elNS,_t as empty,D as isSignal,v as on,W as registerReactivity,E as scope}; diff --git a/dist/esm.d.ts b/dist/esm.d.ts index 2c88f96..a696c74 100644 --- a/dist/esm.d.ts +++ b/dist/esm.d.ts @@ -1,16 +1,18 @@ +type CustomElementTagNameMap= { '#text': Text, '#comment': Comment } +type SupportedElement= + HTMLElementTagNameMap[keyof HTMLElementTagNameMap] + | SVGElementTagNameMap[keyof SVGElementTagNameMap] + | MathMLElementTagNameMap[keyof MathMLElementTagNameMap] + | CustomElementTagNameMap[keyof CustomElementTagNameMap]; declare global { type ddeComponentAttributes= Record | undefined | string; - type ddeElementModifier= (element: El)=> El; + type ddeElementModifier= (element: El)=> El; } -type ElementTagNameMap= HTMLElementTagNameMap & { // & SVGElementTagNameMap - '#text': Text -} -type Element= ElementTagNameMap[keyof ElementTagNameMap]; type AttrsModified= { /** - * In fact argumen for `*.setAttribute("style", *)`. + * Use string like in HTML (internally uses `*.setAttribute("style", *)`), or object representation (like DOM API). */ - style: string + style: string | Partial /** * 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. */ @@ -32,36 +34,59 @@ type AttrsModified= { * There is added support for `data[A-Z].*`/`aria[A-Z].*` to be converted to the kebab-case alternatives. * @private */ -type ElementAttributes= - T extends keyof ElementTagNameMap ? - Omit & AttrsModified : - Omit & AttrsModified; -export function assign(element: El, ...attrs_array: Partial>[]): El -export function el( +type ElementAttributes= Omit & AttrsModified; +export function assign(element: El, ...attrs_array: Partial>[]): El +type ExtendedHTMLElementTagNameMap= HTMLElementTagNameMap & CustomElementTagNameMap +interface element{ + prototype: el; + append(...els: (SupportedElement | DocumentFragment | string | element)[]): el +} +export function el( tag_name: TAG, - attrs?: Partial>, - ...modifiers: ddeElementModifier[] -): ElementTagNameMap[TAG] + attrs?: string | Partial>, + ...modifiers: ddeElementModifier[] +): element export function el( tag_name?: "<>", -): DocumentFragment +): element export function el< A extends ddeComponentAttributes, - C extends (attr: A)=> Element | DocumentFragment>( + C extends (attr: A)=> SupportedElement | DocumentFragment>( fComponent: C, attrs?: A, ...modifiers: ddeElementModifier>[] -): ReturnType +): element> export function el( tag_name: string, - attrs?: Record, - ...modifiers: ddeElementModifier[] -): HTMLElement -export function dispatchEvent(element: HTMLElement, name: keyof DocumentEventMap): void; -export function dispatchEvent(element: HTMLElement, name: string, data: any): void; + attrs?: string | Record, + ...modifiers: ddeElementModifier[] +): element +export function elNS( + namespace: "http://www.w3.org/2000/svg" +): ( + tag_name: TAG, + attrs?: string | Partial<{ [key in KEYS]: SVGElementTagNameMap[TAG][key] | string | number | boolean }>, + ...modifiers: ddeElementModifier[] +)=> element +export function elNS( + namespace: "http://www.w3.org/1998/Math/MathML" +): ( + tag_name: TAG, + attrs?: string | Partial<{ [key in KEYS]: MathMLElementTagNameMap[TAG][key] | string | number | boolean }>, + ...modifiers: ddeElementModifier[] +)=> element +export function elNS( + namespace: string +): ( + tag_name: string, + attrs?: string | Record, + ...modifiers: ddeElementModifier[] +)=> element +export function dispatchEvent(element: SupportedElement, name: keyof DocumentEventMap): void; +export function dispatchEvent(element: SupportedElement, name: string, data: any): void; interface On{ < - EE extends ddeElementModifier, + EE extends ddeElementModifier, El extends ( EE extends ddeElementModifier ? El : never ), Event extends keyof DocumentEventMap>( type: Event, @@ -69,14 +94,14 @@ interface On{ options?: AddEventListenerOptions ) : EE; connected< - EE extends ddeElementModifier, + EE extends ddeElementModifier, El extends ( EE extends ddeElementModifier ? El : never ) >( listener: (el: El) => any, options?: AddEventListenerOptions ) : EE; disconnected< - EE extends ddeElementModifier, + EE extends ddeElementModifier, El extends ( EE extends ddeElementModifier ? El : never ) >( listener: (el: El) => any, @@ -85,123 +110,5 @@ interface On{ } export const on: On; export const scope: { - namespace: string, host: ddeElementModifier, - elNamespace: (ns: string)=> ({ append(...els: (HTMLElement | SVGElement)[]): HTMLElement | SVGElement | DocumentFragment }) -}; -//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; } -} \ No newline at end of file +}; \ No newline at end of file diff --git a/dist/esm.js b/dist/esm.js index 99421c4..34b4ad1 100644 --- a/dist/esm.js +++ b/dist/esm.js @@ -1 +1 @@ -var b={isSignal(t){return!1},processReactiveAttribute(t,e,n,c){return n}};function F(t,e=!0){return e?Object.assign(b,t):(Object.setPrototypeOf(t,b),t)}function E(t){return b.isPrototypeOf(t)&&t!==b?t:b}function g(t){return typeof t>"u"}function _(t,e){if(!t||!(t instanceof AbortSignal))return!0;if(!t.aborted)return t.addEventListener("abort",e),function(){t.removeEventListener("abort",e)}}var R={setDeleteAttr:M};function M(t,e,n){if(Reflect.set(t,e,n),!!g(n)){if(Reflect.deleteProperty(t,e),t instanceof HTMLElement&&t.getAttribute(e)==="undefined")return t.removeAttribute(e);if(Reflect.get(t,e)==="undefined")return Reflect.set(t,e,"")}}var v=[{scope:document.body,namespace:"html",host:t=>t?t(document.body):document.body,prevent:!0}],D=t=>t==="svg"?"http://www.w3.org/2000/svg":t,x={get current(){return v[v.length-1]},get host(){return this.current.host},get namespace(){return this.current.namespace},set namespace(t){return this.current.namespace=D(t)},preventDefault(){let{current:t}=this;return t.prevent=!0,t},elNamespace(t){let e=this.namespace;return this.namespace=t,{append(...n){return x.namespace=e,n.length===1?n[0]:document.createDocumentFragment().append(...n)}}},get state(){return[...v]},push(t={}){return t.namespace&&(t.namespace=D(t.namespace)),v.push(Object.assign({},this.current,{prevent:!1},t))},pop(){return v.pop()}};function J(t,e,...n){let c=E(this),{namespace:r}=x,u=0,f,a;switch((Object(e)!==e||c.isSignal(e))&&(e={textContent:e}),!0){case typeof t=="function":{u=1,x.push({scope:t,host:h=>h?(u===1?n.unshift(h):h(a),void 0):a}),f=t(e||void 0);let d=f instanceof DocumentFragment,l=document.createComment(``);f.prepend(l),d&&(a=l);break}case t==="#text":f=w.call(this,document.createTextNode(""),e);break;case(t==="<>"||!t):f=w.call(this,document.createDocumentFragment(),e);break;case r!=="html":f=w.call(this,document.createElementNS(r,t),e);break;case!f:f=w.call(this,document.createElement(t),e)}return a||(a=f),n.forEach(d=>d(a)),u&&x.pop(),u=2,f}var{setDeleteAttr:S}=R,A=new WeakMap;function w(t,...e){if(!e.length)return t;A.set(t,P(t,this));for(let[n,c]of Object.entries(Object.assign({},...e)))N.call(this,t,n,c);return A.delete(t),t}function N(t,e,n){let{setRemoveAttr:c,s:r}=P(t,this),u=this;n=r.processReactiveAttribute(t,e,n,(a,d)=>N.call(u,t,a,d));let[f]=e;if(f==="=")return c(e.slice(1),n);if(f===".")return L(t,e.slice(1),n);if(/(aria|data)([A-Z])/.test(e))return e=e.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase(),c(e,n);switch(e==="className"&&(e="class"),e){case"xlink:href":return c(e,n,"http://www.w3.org/1999/xlink");case"textContent":return S(t,e,n);case"style":if(typeof n!="object")break;case"dataset":return O(r,n,L.bind(null,t[e]));case"ariaset":return O(r,n,(a,d)=>c("aria-"+a,d));case"classList":return W.call(u,t,n)}return U(t,e)?S(t,e,n):c(e,n)}function P(t,e){if(A.has(t))return A.get(t);let c=(t instanceof SVGElement?q:$).bind(null,t,"Attribute"),r=E(e);return{setRemoveAttr:c,s:r}}function W(t,e){let n=E(this);return O(n,e,(c,r)=>t.classList.toggle(c,r===-1?void 0:!!r)),t}function Q(t){return Array.from(t.children).forEach(e=>e.remove()),t}function U(t,e){if(!Reflect.has(t,e))return!1;let n=j(t,e);return!g(n.set)}function j(t,e){if(t=Object.getPrototypeOf(t),!t)return{};let n=Object.getOwnPropertyDescriptor(t,e);return n||j(t,e)}function O(t,e,n){if(!(typeof e!="object"||e===null))return Object.entries(e).forEach(function([r,u]){r&&(u=t.processReactiveAttribute(e,r,u,n),n(r,u))})}function T(t){return Array.isArray(t)?t.filter(Boolean).join(" "):t}function $(t,e,n,c){return t[(g(c)?"remove":"set")+e](n,T(c))}function q(t,e,n,c,r=null){return t[(g(c)?"remove":"set")+e+"NS"](r,n,T(c))}function L(t,e,n){if(Reflect.set(t,e,n),!!g(n))return Reflect.deleteProperty(t,e)}function k(t,e,...n){let c=n.length?new CustomEvent(e,{detail:n[0]}):new Event(e);return t.dispatchEvent(c)}function C(t,e,n){return function(r){return r.addEventListener(t,e,n),r}}var y=H(),z=new WeakSet;C.connected=function(t,e){let n="connected";return typeof e!="object"&&(e={}),e.once=!0,function(r){let u="dde:"+n;return r.addEventListener(u,t,e),r.__dde_lifecycleToEvents?r:r.isConnected?(r.dispatchEvent(new Event(u)),r):(_(e.signal,()=>y.offConnected(r,t))&&y.onConnected(r,t),r)}};C.disconnected=function(t,e){let n="disconnected";return typeof e!="object"&&(e={}),e.once=!0,function(r){let u="dde:"+n;return r.addEventListener(u,t,e),r.__dde_lifecycleToEvents||_(e.signal,()=>y.offDisconnected(r,t))&&y.onDisconnected(r,t),r}};C.attributeChanged=function(t,e){let n="attributeChanged";return typeof e!="object"&&(e={}),function(r){let u="dde:"+n;if(r.addEventListener(u,t,e),r.__dde_lifecycleToEvents||z.has(r))return r;let f=new MutationObserver(function(d){for(let{attributeName:l,target:h}of d)h.dispatchEvent(new CustomEvent(u,{detail:[l,h.getAttribute(l)]}))});return _(e.signal,()=>f.disconnect())&&f.observe(r,{attributes:!0}),r}};function H(){let t=new Map,e=!1,n=new MutationObserver(function(o){for(let s of o)if(s.type==="childList"){if(l(s.addedNodes,!0)){f();continue}h(s.removedNodes,!0)&&f()}});return{onConnected(o,s){u();let i=r(o);i.connected.has(s)||(i.connected.add(s),i.length_c+=1)},offConnected(o,s){if(!t.has(o))return;let i=t.get(o);i.connected.has(s)&&(i.connected.delete(s),i.length_c-=1,c(o,i))},onDisconnected(o,s){u();let i=r(o);i.disconnected.has(s)||(i.disconnected.add(s),i.length_d+=1)},offDisconnected(o,s){if(!t.has(o))return;let i=t.get(o);i.disconnected.has(s)&&(i.disconnected.delete(s),i.length_d-=1,c(o,i))}};function c(o,s){s.length_c||s.length_d||(t.delete(o),f())}function r(o){if(t.has(o))return t.get(o);let s={connected:new WeakSet,length_c:0,disconnected:new WeakSet,length_d:0};return t.set(o,s),s}function u(){e||(e=!0,n.observe(document.body,{childList:!0,subtree:!0}))}function f(){!e||t.size||(e=!1,n.disconnect())}function a(){return new Promise(function(o){(requestIdleCallback||requestAnimationFrame)(o)})}async function d(o){t.size>30&&await a();let s=[];if(!(o instanceof Node))return s;for(let i of t.keys())i===o||!(i instanceof Node)||o.contains(i)&&s.push(i);return s}function l(o,s){let i=!1;for(let p of o){if(s&&d(p).then(l),!t.has(p))continue;let m=t.get(p);m.length_c&&(p.dispatchEvent(new Event("dde:connected")),m.connected=new WeakSet,m.length_c=0,m.length_d||t.delete(p),i=!0)}return i}function h(o,s){let i=!1;for(let p of o)s&&d(p).then(h),!(!t.has(p)||!t.get(p).length_d)&&(p.dispatchEvent(new Event("dde:disconnected")),t.delete(p),i=!0);return i}}typeof document.createDocumentFragment().append()>"u"&&[HTMLElement,SVGElement,DocumentFragment].forEach(t=>{let{append:e}=t.prototype;t.prototype.append=function(...n){return e.apply(this,n),this}});export{w as assign,N as assignAttribute,W as classListDeclarative,J as createElement,k as dispatchEvent,J as el,Q as empty,C as on,F as registerReactivity,x as scope}; +var m={isSignal(t){return!1},processReactiveAttribute(t,e,n,o){return n}};function $(t,e=!0){return e?Object.assign(m,t):(Object.setPrototypeOf(t,m),t)}function _(t){return m.isPrototypeOf(t)&&t!==m?t:m}function l(t){return typeof t>"u"}function x(t,e){if(!t||!(t instanceof AbortSignal))return!0;if(!t.aborted)return t.addEventListener("abort",e),function(){t.removeEventListener("abort",e)}}var y={setDeleteAttr:U};function U(t,e,n){if(Reflect.set(t,e,n),!!l(n)){if(Reflect.deleteProperty(t,e),t instanceof HTMLElement&&t.getAttribute(e)==="undefined")return t.removeAttribute(e);if(Reflect.get(t,e)==="undefined")return Reflect.set(t,e,"")}}var v=[{scope:document.body,host:t=>t?t(document.body):document.body,prevent:!0}],L={get current(){return v[v.length-1]},get host(){return this.current.host},preventDefault(){let{current:t}=this;return t.prevent=!0,t},get state(){return[...v]},push(t={}){return v.push(Object.assign({},this.current,{prevent:!1},t))},pop(){return v.pop()}},A;function E(t,e,...n){let o=_(this),r=0,c,f;switch((Object(e)!==e||o.isSignal(e))&&(e={textContent:e}),!0){case typeof t=="function":{r=1,L.push({scope:t,host:h=>h?(r===1?n.unshift(h):h(f),void 0):f}),c=t(e||void 0);let d=c instanceof DocumentFragment,a=E.mark({type:"component",name:t.name,host:d?"this":c.nodeName==="#comment"?"previousLater":"parentElement"});c.prepend(a),d&&(f=a);break}case t==="#text":c=w.call(this,document.createTextNode(""),e);break;case(t==="<>"||!t):c=w.call(this,document.createDocumentFragment(),e);break;case A:c=w.call(this,document.createElementNS(A,t),e);break;case!c:c=w.call(this,document.createElement(t),e)}return B(c),f||(f=c),n.forEach(d=>d(f)),r&&L.pop(),r=2,c}E.mark=function(t,e=!1){t=Object.entries(t).map(([r,c])=>r+`="${c}"`).join(" ");let n=e?"":"/",o=document.createComment(``);return e||(o.end=document.createComment("")),o};E.later=function(){let t=E.mark({type:"later"});return t.append=t.prepend=function(...e){return t.after(...e),t},t};function Q(t){let e=this;return function(...o){A=t;let r=E.call(e,...o);return A=void 0,r}}var{setDeleteAttr:N}=y,O=new WeakMap;function w(t,...e){if(!e.length)return t;O.set(t,T(t,this));for(let[n,o]of Object.entries(Object.assign({},...e)))P.call(this,t,n,o);return O.delete(t),t}function P(t,e,n){let{setRemoveAttr:o,s:r}=T(t,this),c=this;n=r.processReactiveAttribute(t,e,n,(d,a)=>P.call(c,t,d,a));let[f]=e;if(f==="=")return o(e.slice(1),n);if(f===".")return D(t,e.slice(1),n);if(/(aria|data)([A-Z])/.test(e))return e=e.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase(),o(e,n);switch(e==="className"&&(e="class"),e){case"xlink:href":return o(e,n,"http://www.w3.org/1999/xlink");case"textContent":return N(t,e,n);case"style":if(typeof n!="object")break;case"dataset":return S(r,n,D.bind(null,t[e]));case"ariaset":return S(r,n,(d,a)=>o("aria-"+d,a));case"classList":return q.call(c,t,n)}return z(t,e)?N(t,e,n):o(e,n)}function T(t,e){if(O.has(t))return O.get(t);let o=(t instanceof SVGElement?k:F).bind(null,t,"Attribute"),r=_(e);return{setRemoveAttr:o,s:r}}function q(t,e){let n=_(this);return S(n,e,(o,r)=>t.classList.toggle(o,r===-1?void 0:!!r)),t}function Y(t){return Array.from(t.children).forEach(e=>e.remove()),t}function z(t,e){if(!Reflect.has(t,e))return!1;let n=W(t,e);return!l(n.set)}function W(t,e){if(t=Object.getPrototypeOf(t),!t)return{};let n=Object.getOwnPropertyDescriptor(t,e);return n||W(t,e)}function S(t,e,n){if(!(typeof e!="object"||e===null))return Object.entries(e).forEach(function([r,c]){r&&(c=t.processReactiveAttribute(e,r,c,n),n(r,c))})}function M(t){return Array.isArray(t)?t.filter(Boolean).join(" "):t}function F(t,e,n,o){return t[(l(o)?"remove":"set")+e](n,M(o))}function k(t,e,n,o,r=null){return t[(l(o)?"remove":"set")+e+"NS"](r,n,M(o))}function D(t,e,n){if(Reflect.set(t,e,n),!!l(n))return Reflect.deleteProperty(t,e)}function j(...t){return this.appendOrig(...t),this}function B(t){return t.append===j||(t.appendOrig=t.append,t.append=j),t}function nt(t,e,...n){let o=n.length?new CustomEvent(e,{detail:n[0]}):new Event(e);return t.dispatchEvent(o)}function R(t,e,n){return function(r){return r.addEventListener(t,e,n),r}}var C=Z(),I=new WeakSet;R.connected=function(t,e){let n="connected";return typeof e!="object"&&(e={}),e.once=!0,function(r){let c="dde:"+n;return r.addEventListener(c,t,e),r.__dde_lifecycleToEvents?r:r.isConnected?(r.dispatchEvent(new Event(c)),r):(x(e.signal,()=>C.offConnected(r,t))&&C.onConnected(r,t),r)}};R.disconnected=function(t,e){let n="disconnected";return typeof e!="object"&&(e={}),e.once=!0,function(r){let c="dde:"+n;return r.addEventListener(c,t,e),r.__dde_lifecycleToEvents||x(e.signal,()=>C.offDisconnected(r,t))&&C.onDisconnected(r,t),r}};R.attributeChanged=function(t,e){let n="attributeChanged";return typeof e!="object"&&(e={}),function(r){let c="dde:"+n;if(r.addEventListener(c,t,e),r.__dde_lifecycleToEvents||I.has(r))return r;let f=new MutationObserver(function(a){for(let{attributeName:h,target:g}of a)g.dispatchEvent(new CustomEvent(c,{detail:[h,g.getAttribute(h)]}))});return x(e.signal,()=>f.disconnect())&&f.observe(r,{attributes:!0}),r}};function Z(){let t=new Map,e=!1,n=new MutationObserver(function(s){for(let i of s)if(i.type==="childList"){if(h(i.addedNodes,!0)){f();continue}g(i.removedNodes,!0)&&f()}});return{onConnected(s,i){c();let u=r(s);u.connected.has(i)||(u.connected.add(i),u.length_c+=1)},offConnected(s,i){if(!t.has(s))return;let u=t.get(s);u.connected.has(i)&&(u.connected.delete(i),u.length_c-=1,o(s,u))},onDisconnected(s,i){c();let u=r(s);u.disconnected.has(i)||(u.disconnected.add(i),u.length_d+=1)},offDisconnected(s,i){if(!t.has(s))return;let u=t.get(s);u.disconnected.has(i)&&(u.disconnected.delete(i),u.length_d-=1,o(s,u))}};function o(s,i){i.length_c||i.length_d||(t.delete(s),f())}function r(s){if(t.has(s))return t.get(s);let i={connected:new WeakSet,length_c:0,disconnected:new WeakSet,length_d:0};return t.set(s,i),i}function c(){e||(e=!0,n.observe(document.body,{childList:!0,subtree:!0}))}function f(){!e||t.size||(e=!1,n.disconnect())}function d(){return new Promise(function(s){(requestIdleCallback||requestAnimationFrame)(s)})}async function a(s){t.size>30&&await d();let i=[];if(!(s instanceof Node))return i;for(let u of t.keys())u===s||!(u instanceof Node)||s.contains(u)&&i.push(u);return i}function h(s,i){let u=!1;for(let p of s){if(i&&a(p).then(h),!t.has(p))continue;let b=t.get(p);b.length_c&&(p.dispatchEvent(new Event("dde:connected")),b.connected=new WeakSet,b.length_c=0,b.length_d||t.delete(p),u=!0)}return u}function g(s,i){let u=!1;for(let p of s)i&&a(p).then(g),!(!t.has(p)||!t.get(p).length_d)&&(p.dispatchEvent(new Event("dde:disconnected")),t.delete(p),u=!0);return u}}export{w as assign,P as assignAttribute,q as classListDeclarative,E as createElement,Q as createElementNS,nt as dispatchEvent,E as el,Q as elNS,Y as empty,R as on,$ as registerReactivity,L as scope}; diff --git a/docs/elements.html b/docs/elements.html index 0ddfa65..43cac5a 100644 --- a/docs/elements.html +++ b/docs/elements.html @@ -1,4 +1,4 @@ -`deka-dom-el` — Elements

`deka-dom-el` — Elements

Basic concepts of elements modifications and creations.

Native JavaScript DOM elements creations

Let’s go through all patterns we would like to use and what needs to be improved for better experience.

Creating element(s) (with custom attributes)

You can create a native DOM element by using the document.createElement(). It is also possible to provide a some attribute(s) declaratively using Object.assign(). More precisely, this way you can sets some IDL.

document.body.append(
+`deka-dom-el` — Elements

`deka-dom-el` — Elements

Basic concepts of elements modifications and creations.

Native JavaScript DOM elements creations

Let’s go through all patterns we would like to use and what needs to be improved for better experience.

Creating element(s) (with custom attributes)

You can create a native DOM element by using the document.createElement(). It is also possible to provide a some attribute(s) declaratively using Object.assign(). More precisely, this way you can sets some IDL.

document.body.append(
 	document.createElement("div")
 );
 console.log(
@@ -12,7 +12,7 @@ document.body.append(
 		{ textContent: "Element’s text content.", style: "color: coral;" }
 	)
 );
-

To make this easier, you can use the el function. Internally in basic examples, it is wrapper around assign(document.createElement(…), { … }).

import { el, assign } from "https://cdn.jsdelivr.net/gh/jaandrle/deka-dom-el/dist/esm-with-signals.js";
+

To make this easier, you can use the el function. Internally in basic examples, it is wrapper around assign(document.createElement(…), { … }).

import { el, assign } from "https://cdn.jsdelivr.net/gh/jaandrle/deka-dom-el/dist/esm-with-signals.js";
 const color= "lightcoral";
 document.body.append(
 	el("p", { textContent: "Hello (first time)", style: { color } })
@@ -23,7 +23,7 @@ document.body.append(
 		{ textContent: "Hello (second time)", style: { color } }
 	)
 );
-

The assign function provides improved behaviour of Object.assign(). You can declaratively sets any IDL and attribute of the given element. Function prefers IDL and fallback to the element.setAttribute if there is no writable property in the element prototype.

You can study all JavaScript elements interfaces to the corresponding HTML elements. All HTML elements inherits from HTMLElement. To see all available IDLs for example for paragraphs, see HTMLParagraphElement. Moreover, the assign provides a way to sets declaratively some convenient properties:

  • It is possible to sets data-*/aria-* attributes using object notation.
  • In opposite, it is also possible to sets data-*/aria-* attribute using camelCase notation.
  • You can use string or object as a value for style property.
  • className (IDL – preffered)/class are ways to add CSS class to the element. You can use string (similarly to class="…" syntax in HTML) or array of strings. This is handy to concat conditional classes.
  • Use classList to toggle specific classes. This will be handy later when the reactivity via signals is beeing introduced.
  • The assign also accepts the undefined as a value for any property to remove it from the element declaratively. Also for some IDL the corresponding attribute is removed as it can be confusing. For example, natievly the element’s id is removed by setting the IDL to an empty string.

For processing, the assign internally uses assignAttribute and classListDeclarative.

import { assignAttribute, classListDeclarative } from "https://cdn.jsdelivr.net/gh/jaandrle/deka-dom-el/dist/esm-with-signals.js";
+

The assign function provides improved behaviour of Object.assign(). You can declaratively sets any IDL and attribute of the given element. Function prefers IDL and fallback to the element.setAttribute if there is no writable property in the element prototype.

You can study all JavaScript elements interfaces to the corresponding HTML elements. All HTML elements inherits from HTMLElement. To see all available IDLs for example for paragraphs, see HTMLParagraphElement. Moreover, the assign provides a way to sets declaratively some convenient properties:

  • It is possible to sets data-*/aria-* attributes using object notation.
  • In opposite, it is also possible to sets data-*/aria-* attribute using camelCase notation.
  • You can use string or object as a value for style property.
  • className (IDL – preffered)/class are ways to add CSS class to the element. You can use string (similarly to class="…" syntax in HTML) or array of strings. This is handy to concat conditional classes.
  • Use classList to toggle specific classes. This will be handy later when the reactivity via signals is beeing introduced.
  • The assign also accepts the undefined as a value for any property to remove it from the element declaratively. Also for some IDL the corresponding attribute is removed as it can be confusing. For example, natievly the element’s id is removed by setting the IDL to an empty string.

For processing, the assign internally uses assignAttribute and classListDeclarative.

import { assignAttribute, classListDeclarative } from "https://cdn.jsdelivr.net/gh/jaandrle/deka-dom-el/dist/esm-with-signals.js";
 const paragraph= document.createElement("p");
 
 assignAttribute(paragraph, "textContent", "Hello, world!");
@@ -48,7 +48,7 @@ console.log(paragraph.outerHTML);
 document.body.append(
 	paragraph
 );
-

Native JavaScript templating

By default, the native JS has no good way to define HTML template using DOM API:

document.body.append(
+

Native JavaScript templating

By default, the native JS has no good way to define HTML template using DOM API:

document.body.append(
 	document.createElement("div"),
 	document.createElement("span"),
 	document.createElement("main")
@@ -59,7 +59,7 @@ const template= document.createElement("main").append(
 	document.createElement("span"),
 );
 console.log(typeof template==="undefined");
-

This library therefore ooverwrites the append method to always return parent element.

import { el } from "https://cdn.jsdelivr.net/gh/jaandrle/deka-dom-el/dist/esm-with-signals.js";
+

This library therefore overwrites the append method of created elements to always return parent element.

import { el } from "https://cdn.jsdelivr.net/gh/jaandrle/deka-dom-el/dist/esm-with-signals.js";
 document.head.append(
 	el("style").append(
 		"tr, td{ border: 1px solid red; padding: 1em; }",
@@ -83,7 +83,7 @@ document.body.append(
 		)
 	)
 );
-

Creating advanced (reactive) templates and components

Basic components

You can use functions for encapsulation (repeating) logic. The el accepts function as first argument. In that case, the function should return dom elements and the second argument for el is argument for given element.

import { el } from "https://cdn.jsdelivr.net/gh/jaandrle/deka-dom-el/dist/esm-with-signals.js";
+

Creating advanced (reactive) templates and components

Basic components

You can use functions for encapsulation (repeating) logic. The el accepts function as first argument. In that case, the function should return dom elements and the second argument for el is argument for given element.

import { el } from "https://cdn.jsdelivr.net/gh/jaandrle/deka-dom-el/dist/esm-with-signals.js";
 document.head.append(
 	el("style").append(
 		".class1{ font-weight: bold; }",
@@ -100,4 +100,4 @@ function component({ className, textContent }){
 		el("p", textContent)
 	);
 }
-

It is nice to use similar naming convention as native DOM API.

\ No newline at end of file +

It is nice to use similar naming convention as native DOM API.

\ No newline at end of file diff --git a/docs/index.html b/docs/index.html index 9f1255d..eb46131 100644 --- a/docs/index.html +++ b/docs/index.html @@ -1,4 +1,4 @@ -`deka-dom-el` — Introduction

`deka-dom-el` — Introduction

Introducing a library and motivations.

The library tries to provide pure JavaScript tool(s) to create reactive interfaces.

import { el, S } from "https://cdn.jsdelivr.net/gh/jaandrle/deka-dom-el/dist/esm-with-signals.js";
+`deka-dom-el` — Introduction

`deka-dom-el` — Introduction

Introducing a library and motivations.

The library tries to provide pure JavaScript tool(s) to create reactive interfaces.

import { el, S } from "https://cdn.jsdelivr.net/gh/jaandrle/deka-dom-el/dist/esm-with-signals.js";
 const clicks= S(0);
 document.body.append(
 	el().append(
@@ -12,4 +12,4 @@ document.body.append(
 		})
 	)
 );
-
\ No newline at end of file +
\ No newline at end of file diff --git a/docs_src/elements.html.js b/docs_src/elements.html.js index 39c7df3..023a648 100644 --- a/docs_src/elements.html.js +++ b/docs_src/elements.html.js @@ -88,7 +88,7 @@ export function page({ pkg, info, path_target, pages, registerClientFile }){ el("p", "By default, the native JS has no good way to define HTML template using DOM API:"), el(example, { src: new URL("./components/examples/nativeAppend.js", import.meta.url), page_id, registerClientFile }), el("p").append( - "This library therefore ooverwrites the ", el("code", "append"), " method to always return parent element." + "This library therefore overwrites the ", el("code", "append"), " method of created elements to always return parent element." ), el(example, { src: new URL("./components/examples/dekaAppend.js", import.meta.url), page_id, registerClientFile }), diff --git a/docs_src/layout/head.html.js b/docs_src/layout/head.html.js index b892615..1a60d6e 100644 --- a/docs_src/layout/head.html.js +++ b/docs_src/layout/head.html.js @@ -1,4 +1,4 @@ -import { el, scope } from "deka-dom-el"; +import { el, elNS, scope } from "deka-dom-el"; /** * @param {object} def * @param {import("../types.d.ts").Info} def.info @@ -66,7 +66,7 @@ function stylesheetHref(path_target, name){ return path_target.css.replace(path_target.root, "")+name+".css"; } function iconGitHub(){ - scope.namespace= "svg"; + const el= elNS("http://www.w3.org/2000/svg"); return el("svg", { className: "icon", viewBox: "0 0 32 32" }).append( el("path", { d: [ //see https://svg-path-visualizer.netlify.app/#M16%200.395c-8.836%200-16%207.163-16%2016%200%207.069%204.585%2013.067%2010.942%2015.182%200.8%200.148%201.094-0.347%201.094-0.77%200-0.381-0.015-1.642-0.022-2.979-4.452%200.968-5.391-1.888-5.391-1.888-0.728-1.849-1.776-2.341-1.776-2.341-1.452-0.993%200.11-0.973%200.11-0.973%201.606%200.113%202.452%201.649%202.452%201.649%201.427%202.446%203.743%201.739%204.656%201.33%200.143-1.034%200.558-1.74%201.016-2.14-3.554-0.404-7.29-1.777-7.29-7.907%200-1.747%200.625-3.174%201.649-4.295-0.166-0.403-0.714-2.030%200.155-4.234%200%200%201.344-0.43%204.401%201.64%201.276-0.355%202.645-0.532%204.005-0.539%201.359%200.006%202.729%200.184%204.008%200.539%203.054-2.070%204.395-1.64%204.395-1.64%200.871%202.204%200.323%203.831%200.157%204.234%201.026%201.12%201.647%202.548%201.647%204.295%200%206.145-3.743%207.498-7.306%207.895%200.574%200.497%201.085%201.47%201.085%202.963%200%202.141-0.019%203.864-0.019%204.391%200%200.426%200.288%200.925%201.099%200.768%206.354-2.118%2010.933-8.113%2010.933-15.18%200-8.837-7.164-16-16-16z "M 16,0.395", diff --git a/examples/components/fullNameComponent.js b/examples/components/fullNameComponent.js index f577a5c..a084685 100644 --- a/examples/components/fullNameComponent.js +++ b/examples/components/fullNameComponent.js @@ -1,4 +1,4 @@ -import { style, el, on, S, scope } from '../exports.js'; +import { style, el, elNS, on, S, scope } from '../exports.js'; const className= style.host(fullNameComponent).css` :host form{ display: flex; @@ -13,6 +13,7 @@ export function fullNameComponent(){ scope.host(on.connected(()=> console.log(fullNameComponent))); scope.host(on.disconnected(()=> console.log(fullNameComponent))) + const elSVG= elNS("http://www.w3.org/2000/svg"); return el("div", { className }).append( el("h2", "Simple form:"), el("form", { onsubmit: ev=> ev.preventDefault() }).append( @@ -26,11 +27,9 @@ export function fullNameComponent(){ ": ", el("#text", full_name) ), - scope.elNamespace("svg").append( - el("svg", { viewBox: "0 0 240 80", style: { height: "80px", display: "block" } }).append( - //el("style", { }) - el("text", { x: 20, y: 35, textContent: "Text" }) - ) + elSVG("svg", { viewBox: "0 0 240 80", style: { height: "80px", display: "block" } }).append( + //elSVG("style", { }) + elSVG("text", { x: 20, y: 35, textContent: "Text" }) ) ); } diff --git a/index.d.ts b/index.d.ts index e7dbb53..90becc2 100644 --- a/index.d.ts +++ b/index.d.ts @@ -1,16 +1,18 @@ +type CustomElementTagNameMap= { '#text': Text, '#comment': Comment } +type SupportedElement= + HTMLElementTagNameMap[keyof HTMLElementTagNameMap] + | SVGElementTagNameMap[keyof SVGElementTagNameMap] + | MathMLElementTagNameMap[keyof MathMLElementTagNameMap] + | CustomElementTagNameMap[keyof CustomElementTagNameMap]; declare global { type ddeComponentAttributes= Record | undefined | string; - type ddeElementModifier= (element: El)=> El; + type ddeElementModifier= (element: El)=> El; } -type ElementTagNameMap= HTMLElementTagNameMap & { // & SVGElementTagNameMap - '#text': Text -} -type Element= ElementTagNameMap[keyof ElementTagNameMap]; type AttrsModified= { /** - * In fact argumen for `*.setAttribute("style", *)`. + * Use string like in HTML (internally uses `*.setAttribute("style", *)`), or object representation (like DOM API). */ - style: string + style: string | Partial /** * 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. */ @@ -32,40 +34,64 @@ type AttrsModified= { * There is added support for `data[A-Z].*`/`aria[A-Z].*` to be converted to the kebab-case alternatives. * @private */ -type ElementAttributes= - T extends keyof ElementTagNameMap ? - Omit & AttrsModified : - Omit & AttrsModified; -export function assign(element: El, ...attrs_array: Partial>[]): El +type ElementAttributes= Omit & AttrsModified; +export function assign(element: El, ...attrs_array: Partial>[]): El -export function el( +type ExtendedHTMLElementTagNameMap= HTMLElementTagNameMap & CustomElementTagNameMap +interface element{ + prototype: el; + append(...els: (SupportedElement | DocumentFragment | string | element)[]): el +} +export function el( tag_name: TAG, - attrs?: Partial>, - ...modifiers: ddeElementModifier[] -): ElementTagNameMap[TAG] + attrs?: string | Partial>, + ...modifiers: ddeElementModifier[] +): element export function el( tag_name?: "<>", -): DocumentFragment +): element export function el< A extends ddeComponentAttributes, - C extends (attr: A)=> Element | DocumentFragment>( + C extends (attr: A)=> SupportedElement | DocumentFragment>( fComponent: C, attrs?: A, ...modifiers: ddeElementModifier>[] -): ReturnType +): element> export function el( tag_name: string, - attrs?: Record, - ...modifiers: ddeElementModifier[] -): HTMLElement + attrs?: string | Record, + ...modifiers: ddeElementModifier[] +): element -export function dispatchEvent(element: HTMLElement, name: keyof DocumentEventMap): void; -export function dispatchEvent(element: HTMLElement, name: string, data: any): void; +export function elNS( + namespace: "http://www.w3.org/2000/svg" +): ( + tag_name: TAG, + attrs?: string | Partial<{ [key in KEYS]: SVGElementTagNameMap[TAG][key] | string | number | boolean }>, + ...modifiers: ddeElementModifier[] +)=> element +export function elNS( + namespace: "http://www.w3.org/1998/Math/MathML" +): ( + tag_name: TAG, + attrs?: string | Partial<{ [key in KEYS]: MathMLElementTagNameMap[TAG][key] | string | number | boolean }>, + ...modifiers: ddeElementModifier[] +)=> element +export function elNS( + namespace: string +): ( + tag_name: string, + attrs?: string | Record, + ...modifiers: ddeElementModifier[] +)=> element + +export function dispatchEvent(element: SupportedElement, name: keyof DocumentEventMap): void; +export function dispatchEvent(element: SupportedElement, name: string, data: any): void; interface On{ < - EE extends ddeElementModifier, + EE extends ddeElementModifier, El extends ( EE extends ddeElementModifier ? El : never ), Event extends keyof DocumentEventMap>( type: Event, @@ -73,14 +99,14 @@ interface On{ options?: AddEventListenerOptions ) : EE; connected< - EE extends ddeElementModifier, + EE extends ddeElementModifier, El extends ( EE extends ddeElementModifier ? El : never ) >( listener: (el: El) => any, options?: AddEventListenerOptions ) : EE; disconnected< - EE extends ddeElementModifier, + EE extends ddeElementModifier, El extends ( EE extends ddeElementModifier ? El : never ) >( listener: (el: El) => any, @@ -90,124 +116,5 @@ interface On{ export const on: On; export const scope: { - namespace: string, host: ddeElementModifier, - elNamespace: (ns: string)=> ({ append(...els: (HTMLElement | SVGElement)[]): HTMLElement | SVGElement | DocumentFragment }) }; - -//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; } -} diff --git a/index.js b/index.js index 3f8cada..0ba4366 100644 --- a/index.js +++ b/index.js @@ -1,7 +1,2 @@ -if(typeof document.createDocumentFragment().append()==="undefined") - [ HTMLElement, SVGElement, DocumentFragment ].forEach(c=> { - const { append }= c.prototype; - c.prototype.append= function(...els){ append.apply(this, els); return this; }; - }); export * from "./src/dom.js"; export * from "./src/events.js"; diff --git a/jsdom.js b/jsdom.js index 34cf428..b5684fb 100644 --- a/jsdom.js +++ b/jsdom.js @@ -19,11 +19,6 @@ export function register(dom, keys_aditional= []){ globalThis.window= w; w.console= globalThis.console; } - if(typeof document.createDocumentFragment().append()==="undefined") - [ HTMLElement, SVGElement, DocumentFragment ].forEach(c=> { - const { append }= c.prototype; - c.prototype.append= function(...els){ append.apply(this, els); return this; }; - }); dom_last= dom; return import("./index.js"); diff --git a/package.json b/package.json index 4445d9a..d89ab5e 100644 --- a/package.json +++ b/package.json @@ -63,7 +63,7 @@ }, { "path": "./signals.js", - "limit": "8.5 kB", + "limit": "11 kB", "gzip": false }, { diff --git a/src/dom.js b/src/dom.js index fc00d68..6b27f71 100644 --- a/src/dom.js +++ b/src/dom.js @@ -1,47 +1,31 @@ import { signals } from "./signals-common.js"; -/** @type {{ scope: object, prevent: boolean, namespace: "html"|string, host: function }[]} */ +/** @type {{ scope: object, prevent: boolean, host: function }[]} */ const scopes= [ { scope: document.body, - namespace: "html", host: c=> c ? c(document.body) : document.body, prevent: true } ]; -const namespaceHelper= ns=> ns==="svg" ? "http://www.w3.org/2000/svg" : ns; export const scope= { get current(){ return scopes[scopes.length-1]; }, get host(){ return this.current.host; }, - get namespace(){ return this.current.namespace; }, - set namespace(namespace){ return ( this.current.namespace= namespaceHelper(namespace)); }, preventDefault(){ const { current }= this; current.prevent= true; return current; }, - elNamespace(namespace){ - const ns= this.namespace; - this.namespace= namespace; - return { - append(...els){ - scope.namespace= ns; - if(els.length===1) return els[0]; - const f= document.createDocumentFragment(); - return f.append(...els); - } - }; - }, get state(){ return [ ...scopes ]; }, push(s= {}){ - if(s.namespace) s.namespace= namespaceHelper(s.namespace); return scopes.push(Object.assign({}, this.current, { prevent: false }, s)); }, pop(){ return scopes.pop(); }, }; +let namespace; export function createElement(tag, attributes, ...modifiers){ + /* jshint maxcomplexity: 15 */ const s= signals(this); - const { namespace }= scope; let scoped= 0; let el, el_host; //TODO Array.isArray(tag) ⇒ set key (cache els) @@ -53,24 +37,57 @@ export function createElement(tag, attributes, ...modifiers){ scope.push({ scope: tag, host: c=> c ? (scoped===1 ? modifiers.unshift(c) : c(el_host), undefined) : el_host }); el= tag(attributes || undefined); const is_fragment= el instanceof DocumentFragment; - const el_mark= document.createComment(``); + const el_mark= createElement.mark({ + type: "component", + name: tag.name, + host: is_fragment ? "this" : ( el.nodeName==="#comment" ? "previousLater" : "parentElement" ) + }); el.prepend(el_mark); if(is_fragment) el_host= el_mark; break; } case tag==="#text": el= assign.call(this, document.createTextNode(""), attributes); break; case tag==="<>" || !tag: el= assign.call(this, document.createDocumentFragment(), attributes); break; - case namespace!=="html": el= assign.call(this, document.createElementNS(namespace, tag), attributes); break; + case namespace: el= assign.call(this, document.createElementNS(namespace, tag), attributes); break; case !el: el= assign.call(this, document.createElement(tag), attributes); } + chainableAppend(el); if(!el_host) el_host= el; modifiers.forEach(c=> c(el_host)); if(scoped) scope.pop(); scoped= 2; return el; } +/** + * @param { { type: "component", name: string, host: "this" | "parentElement" } | { type: "reactive" | "later" } } attrs + * @param {boolean} [is_open=false] + * */ +createElement.mark= function(attrs, is_open= false){ + attrs= Object.entries(attrs).map(([ n, v ])=> n+`="${v}"`).join(" "); + const end= is_open ? "" : "/"; + const out= document.createComment(``); + if(!is_open) out.end= document.createComment(""); + return out; +}; +createElement.later= function(){ + const el= createElement.mark({ type: "later" }); + el.append= el.prepend= function(...els){ el.after(...els); return el; }; + return el; +}; export { createElement as el }; +//const namespaceHelper= ns=> ns==="svg" ? "http://www.w3.org/2000/svg" : ns; +export function createElementNS(ns){ + const _this= this; + return function createElementNSCurried(...rest){ + namespace= ns; + const el= createElement.call(_this, ...rest); + namespace= undefined; + return el; + }; +} +export { createElementNS as elNS }; + import { prop_process } from './dom-common.js'; const { setDeleteAttr }= prop_process; const assign_context= new WeakMap(); @@ -161,3 +178,6 @@ function attrArrToStr(attr){ return Array.isArray(attr) ? attr.filter(Boolean).j function setRemove(obj, prop, key, val){ return obj[ (isUndef(val) ? "remove" : "set") + prop ](key, attrArrToStr(val)); } function setRemoveNS(obj, prop, key, val, ns= null){ return obj[ (isUndef(val) ? "remove" : "set") + prop + "NS" ](ns, key, attrArrToStr(val)); } function setDelete(obj, key, val){ Reflect.set(obj, key, val); if(!isUndef(val)) return; return Reflect.deleteProperty(obj, key); } + +function append(...els){ this.appendOrig(...els); return this; } +function chainableAppend(el){ if(el.append===append) return el; el.appendOrig= el.append; el.append= append; return el; } diff --git a/src/signals-lib.js b/src/signals-lib.js index 69f06f2..8598c71 100644 --- a/src/signals-lib.js +++ b/src/signals-lib.js @@ -117,9 +117,10 @@ S.clear= function(...signals){ } }; const key_reactive= "__dde_reactive"; +import { el } from "./dom.js"; S.el= function(signal, map){ - const mark_start= document.createComment(``); - const mark_end= document.createComment(""); + const mark_start= el.mark({ type: "reactive" }, false); + const mark_end= mark_start.end; const out= document.createDocumentFragment(); out.append(mark_start, mark_end); const { current }= scope;