diff --git a/dist/dde-with-signals.js b/dist/dde-with-signals.js index ff03486..2481706 100644 --- a/dist/dde-with-signals.js +++ b/dist/dde-with-signals.js @@ -1,6 +1,6 @@ //deka-dom-el library is available via global namespace `dde` (()=> { -var w={isSignal(t){return!1},processReactiveAttribute(t,e,n,r){return n}};function T(t,e=!0){return e?Object.assign(w,t):(Object.setPrototypeOf(t,w),t)}function R(t){return w.isPrototypeOf(t)&&t!==w?t:w}function x(t){return typeof t>"u"}function q(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 W={setDeleteAttr:Y,ssr:""};function Y(t,e,n){if(Reflect.set(t,e,n),!!x(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 E=[{scope:document.body,host:t=>t?t(document.body):document.body,custom_element:!1,prevent:!0}],g={get current(){return E[E.length-1]},get host(){return this.current.host},preventDefault(){let{current:t}=this;return t.prevent=!0,t},get state(){return[...E]},push(t={}){return E.push(Object.assign({},this.current,{prevent:!1},t))},pushRoot(){return E.push(E[0])},pop(){if(E.length!==1)return E.pop()}};function B(...t){return this.appendOriginal(...t),this}function tt(t){return t.append===B||(t.appendOriginal=t.append,t.append=B),t}var L;function y(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,g.push({scope:t,host:(...p)=>p.length?(o===1?n.unshift(...p):p.forEach(v=>v(s)),void 0):s}),c=t(e||void 0);let a=c instanceof DocumentFragment;if(c.nodeName==="#comment")break;let d=y.mark({type:"component",name:t.name,host:a?"this":"parentElement"});c.prepend(d),a&&(s=d);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 tt(c),s||(s=c),n.forEach(a=>a(s)),o&&g.pop(),o=2,c}y.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};function _t(t){let e=this;return function(...r){L=t;let o=y.call(e,...r);return L=void 0,o}}var{setDeleteAttr:H}=W,j=new WeakMap;function N(t,...e){if(!e.length)return t;j.set(t,Z(t,this));for(let[n,r]of Object.entries(Object.assign({},...e)))J.call(this,t,n,r);return j.delete(t),t}function J(t,e,n){let{setRemoveAttr:r,s:o}=Z(t,this),c=this;n=o.processReactiveAttribute(t,e,n,(a,d)=>J.call(c,t,a,d));let[s]=e;if(s==="=")return r(e.slice(1),n);if(s===".")return I(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 $(o,n,I.bind(null,t[e]));case"ariaset":return $(o,n,(a,d)=>r("aria-"+a,d));case"classList":return et.call(c,t,n)}return nt(t,e)?H(t,e,n):r(e,n)}function Z(t,e){if(j.has(t))return j.get(t);let r=(t instanceof SVGElement?ot:rt).bind(null,t,"Attribute"),o=R(e);return{setRemoveAttr:r,s:o}}function et(t,e){let n=R(this);return $(n,e,(r,o)=>t.classList.toggle(r,o===-1?void 0:!!o)),t}function Et(t){return Array.from(t.children).forEach(e=>e.remove()),t}function nt(t,e){if(!Reflect.has(t,e))return!1;let n=G(t,e);return!x(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,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 V(t){return Array.isArray(t)?t.filter(Boolean).join(" "):t}function rt(t,e,n,r){return t[(x(r)?"remove":"set")+e](n,V(r))}function ot(t,e,n,r,o=null){return t[(x(r)?"remove":"set")+e+"NS"](o,n,V(r))}function I(t,e,n){if(Reflect.set(t,e,n),!!x(n))return Reflect.deleteProperty(t,e)}function St(t,e,...n){let r=n.length?new CustomEvent(e,{detail:n[0]}):new Event(e);return t.dispatchEvent(r)}function _(t,e,n){return function(o){return o.addEventListener(t,e,n),o}}var P=st(),ct=new WeakSet;_.connected=function(t,e){let{custom_element:n}=g.current,r="connected";return typeof e!="object"&&(e={}),e.once=!0,function(c){n&&(c=n);let s="dde:"+r;return c.addEventListener(s,t,e),c.__dde_lifecycleToEvents?c:c.isConnected?(c.dispatchEvent(new Event(s)),c):(C(e.signal,()=>P.offConnected(c,t))&&P.onConnected(c,t),c)}};_.disconnected=function(t,e){let{custom_element:n}=g.current,r="disconnected";return typeof e!="object"&&(e={}),e.once=!0,function(c){n&&(c=n);let s="dde:"+r;return c.addEventListener(s,t,e),c.__dde_lifecycleToEvents||C(e.signal,()=>P.offDisconnected(c,t))&&P.onDisconnected(c,t),c}};var z=new WeakMap;_.disconnectedAsAbort=function(t){if(z.has(t))return z.get(t);let e=new AbortController;return z.set(t,e),t(_.disconnected(()=>e.abort())),e};_.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||ct.has(o))return o;let s=new MutationObserver(function(d){for(let{attributeName:p,target:v}of d)v.dispatchEvent(new CustomEvent(c,{detail:[p,v.getAttribute(p)]}))});return C(e.signal,()=>s.disconnect())&&s.observe(o,{attributes:!0}),o}};function st(){let t=new Map,e=!1,n=new MutationObserver(function(i){for(let u of i)if(u.type==="childList"){if(p(u.addedNodes,!0)){s();continue}v(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 a(){return new Promise(function(i){(requestIdleCallback||requestAnimationFrame)(i)})}async function d(i){t.size>30&&await a();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 p(i,u){let f=!1;for(let m of i){if(u&&d(m).then(p),!t.has(m))continue;let S=t.get(m);S.length_c&&(m.dispatchEvent(new Event("dde:connected")),S.connected=new WeakSet,S.length_c=0,S.length_d||t.delete(m),f=!0)}return f}function v(i,u){let f=!1;for(let m of i)u&&d(m).then(v),!(!t.has(m)||!t.get(m).length_d)&&(m.dispatchEvent(new Event("dde:disconnected")),t.delete(m),f=!0);return f}}var l=Symbol.for("Signal");function D(t){try{return Reflect.has(t,l)}catch{return!1}}var M=[],h=new WeakMap;function b(t,e){if(typeof t!="function")return K(t,e);if(D(t))return t;let n=K(),r=function(){let[o,...c]=h.get(r);if(h.set(r,new Set([o])),M.push(r),n(t()),M.pop(),!c.length)return;let s=h.get(r);for(let a of c)s.has(a)||O(a,r)};return h.set(n[l],r),h.set(r,new Set([n])),r(),n}b.action=function(t,e,...n){let r=t[l],{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))};b.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));U(e,n),o&&o.addEventListener("abort",()=>O(e,n))}};b.symbols={signal:l,onclear:Symbol.for("Signal.onclear")};var A="__dde_attributes";b.attribute=function(t,e=void 0){let n=b(e),r;return g.host(o=>{if(r=o,o instanceof HTMLElement?o.hasAttribute(t)&&n(o.getAttribute(t)):o.hasAttributeNS(null,t)&&n(o.getAttributeNS(null,t)),o[A]){o[A][t]=n;return}return o[A]={[t]:n},_.attributeChanged(function({detail:s}){/*! This maps attributes to signals (`S.attribute`). +var w={isSignal(t){return!1},processReactiveAttribute(t,e,n,r){return n}};function T(t,e=!0){return e?Object.assign(w,t):(Object.setPrototypeOf(t,w),t)}function R(t){return w.isPrototypeOf(t)&&t!==w?t:w}function x(t){return typeof t>"u"}function q(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 W={setDeleteAttr:Y,ssr:""};function Y(t,e,n){if(Reflect.set(t,e,n),!!x(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 E=[{scope:document.body,host:t=>t?t(document.body):document.body,custom_element:!1,prevent:!0}],g={get current(){return E[E.length-1]},get host(){return this.current.host},preventDefault(){let{current:t}=this;return t.prevent=!0,t},get state(){return[...E]},push(t={}){return E.push(Object.assign({},this.current,{prevent:!1},t))},pushRoot(){return E.push(E[0])},pop(){if(E.length!==1)return E.pop()}};function B(...t){return this.appendOriginal(...t),this}function tt(t){return t.append===B||(t.appendOriginal=t.append,t.append=B),t}var L;function y(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,g.push({scope:t,host:(...p)=>p.length?(o===1?n.unshift(...p):p.forEach(v=>v(s)),void 0):s}),c=t(e||void 0);let a=c instanceof DocumentFragment;if(c.nodeName==="#comment")break;let d=y.mark({type:"component",name:t.name,host:a?"this":"parentElement"});c.prepend(d),a&&(s=d);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 tt(c),s||(s=c),n.forEach(a=>a(s)),o&&g.pop(),o=2,c}y.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};function _t(t){let e=this;return function(...r){L=t;let o=y.call(e,...r);return L=void 0,o}}var{setDeleteAttr:H}=W,j=new WeakMap;function N(t,...e){if(!e.length)return t;j.set(t,Z(t,this));for(let[n,r]of Object.entries(Object.assign({},...e)))J.call(this,t,n,r);return j.delete(t),t}function J(t,e,n){let{setRemoveAttr:r,s:o}=Z(t,this),c=this;n=o.processReactiveAttribute(t,e,n,(a,d)=>J.call(c,t,a,d));let[s]=e;if(s==="=")return r(e.slice(1),n);if(s===".")return I(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 $(o,n,I.bind(null,t[e]));case"ariaset":return $(o,n,(a,d)=>r("aria-"+a,d));case"classList":return et.call(c,t,n)}return nt(t,e)?H(t,e,n):r(e,n)}function Z(t,e){if(j.has(t))return j.get(t);let r=(t instanceof SVGElement?ot:rt).bind(null,t,"Attribute"),o=R(e);return{setRemoveAttr:r,s:o}}function et(t,e){let n=R(this);return $(n,e,(r,o)=>t.classList.toggle(r,o===-1?void 0:!!o)),t}function Et(t){return Array.from(t.children).forEach(e=>e.remove()),t}function nt(t,e){if(!Reflect.has(t,e))return!1;let n=G(t,e);return!x(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,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 V(t){return Array.isArray(t)?t.filter(Boolean).join(" "):t}function rt(t,e,n,r){return t[(x(r)?"remove":"set")+e](n,V(r))}function ot(t,e,n,r,o=null){return t[(x(r)?"remove":"set")+e+"NS"](o,n,V(r))}function I(t,e,n){if(Reflect.set(t,e,n),!!x(n))return Reflect.deleteProperty(t,e)}function St(t,e={}){return function(r,...o){let c=o.length?new CustomEvent(t,Object.assign({detail:o[0]},e)):new Event(t,e);return r.dispatchEvent(c)}}function _(t,e,n){return function(o){return o.addEventListener(t,e,n),o}}var P=st(),ct=new WeakSet;_.connected=function(t,e){let{custom_element:n}=g.current,r="connected";return typeof e!="object"&&(e={}),e.once=!0,function(c){n&&(c=n);let s="dde:"+r;return c.addEventListener(s,t,e),c.__dde_lifecycleToEvents?c:c.isConnected?(c.dispatchEvent(new Event(s)),c):(C(e.signal,()=>P.offConnected(c,t))&&P.onConnected(c,t),c)}};_.disconnected=function(t,e){let{custom_element:n}=g.current,r="disconnected";return typeof e!="object"&&(e={}),e.once=!0,function(c){n&&(c=n);let s="dde:"+r;return c.addEventListener(s,t,e),c.__dde_lifecycleToEvents||C(e.signal,()=>P.offDisconnected(c,t))&&P.onDisconnected(c,t),c}};var z=new WeakMap;_.disconnectedAsAbort=function(t){if(z.has(t))return z.get(t);let e=new AbortController;return z.set(t,e),t(_.disconnected(()=>e.abort())),e};_.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||ct.has(o))return o;let s=new MutationObserver(function(d){for(let{attributeName:p,target:v}of d)v.dispatchEvent(new CustomEvent(c,{detail:[p,v.getAttribute(p)]}))});return C(e.signal,()=>s.disconnect())&&s.observe(o,{attributes:!0}),o}};function st(){let t=new Map,e=!1,n=new MutationObserver(function(i){for(let u of i)if(u.type==="childList"){if(p(u.addedNodes,!0)){s();continue}v(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 a(){return new Promise(function(i){(requestIdleCallback||requestAnimationFrame)(i)})}async function d(i){t.size>30&&await a();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 p(i,u){let f=!1;for(let m of i){if(u&&d(m).then(p),!t.has(m))continue;let S=t.get(m);S.length_c&&(m.dispatchEvent(new Event("dde:connected")),S.connected=new WeakSet,S.length_c=0,S.length_d||t.delete(m),f=!0)}return f}function v(i,u){let f=!1;for(let m of i)u&&d(m).then(v),!(!t.has(m)||!t.get(m).length_d)&&(m.dispatchEvent(new Event("dde:disconnected")),t.delete(m),f=!0);return f}}var l=Symbol.for("Signal");function D(t){try{return Reflect.has(t,l)}catch{return!1}}var M=[],h=new WeakMap;function b(t,e){if(typeof t!="function")return K(t,e);if(D(t))return t;let n=K(),r=function(){let[o,...c]=h.get(r);if(h.set(r,new Set([o])),M.push(r),n(t()),M.pop(),!c.length)return;let s=h.get(r);for(let a of c)s.has(a)||O(a,r)};return h.set(n[l],r),h.set(r,new Set([n])),r(),n}b.action=function(t,e,...n){let r=t[l],{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))};b.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));U(e,n),o&&o.addEventListener("abort",()=>O(e,n))}};b.symbols={signal:l,onclear:Symbol.for("Signal.onclear")};var A="__dde_attributes";b.attribute=function(t,e=void 0){let n=b(e),r;return g.host(o=>{if(r=o,o instanceof HTMLElement?o.hasAttribute(t)&&n(o.getAttribute(t)):o.hasAttributeNS(null,t)&&n(o.getAttributeNS(null,t)),o[A]){o[A][t]=n;return}return o[A]={[t]:n},_.attributeChanged(function({detail:s}){/*! This maps attributes to signals (`S.attribute`). * Investigate `__dde_attributes` key of the element.*/let[a,d]=s,p=o[A][a];if(p)return p(d)})(o),_.disconnected(function(){/*! This removes all signals mapped to attributes (`S.attribute`). * Investigate `__dde_attributes` key of the element.*/b.clear(...Object.values(o[A])),r=null})(o),o}),new Proxy(n,{apply(o,c,s){if(!s.length)return o();if(!r)return;let a=s[0];return r instanceof HTMLElement?r.setAttribute(t,a):r.setAttributeNS(null,t,a)}})};b.clear=function(...t){for(let n of t){Reflect.deleteProperty(n,"toJSON");let r=n[l];r.onclear.forEach(o=>o.call(r)),e(n,r),Reflect.deleteProperty(n,l)}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)&&(b.clear(...c),h.delete(o))})}};var k="__dde_reactive";b.el=function(t,e){let n=y.mark({type:"reactive"},!1),r=n.end,o=document.createDocumentFragment();o.append(n,r);let{current:c}=g,s=a=>{if(!n.parentNode||!r.parentNode)return O(t,s);g.push(c);let d=e(a);g.pop(),Array.isArray(d)||(d=[d]);let p=n;for(;(p=n.nextSibling)!==r;)p.remove();n.after(...d)};return U(t,s),X(t,s,n,e),s(t()),o};var Q={isSignal:D,processReactiveAttribute(t,e,n,r){if(!D(n))return n;let o=c=>r(e,c);return U(n,o),X(n,o,t,e),n()}};function X(t,e,...n){let{current:r}=g;r.prevent||r.host(function(o){o[k]||(o[k]=[],_.disconnected(()=>o[k].forEach(([[c,s]])=>O(c,s,c[l]?.host()===o)))(o)),o[k].push([[t,e],...n])})}function K(t,e){let n=(...r)=>r.length?dt(n,...r):at(n);return ut(n,t,e)}var it=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 ut(t,e,n){let r=[];q(n)!=="[object Object]"&&(n={});let{onclear:o}=b.symbols;n[o]&&(r.push(n[o]),Reflect.deleteProperty(n,o));let{host:c}=g;return Reflect.defineProperty(t,l,{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[l],it),t}function ft(){return M[M.length-1]}function at(t){if(!t[l])return;let{value:e,listeners:n}=t[l],r=ft();return r&&n.add(r),h.has(r)&&h.get(r).add(t),e}function dt(t,e,n){if(!t[l])return;let r=t[l];if(!(!n&&r.value===e))return r.value=e,r.listeners.forEach(o=>o(e)),e}function U(t,e){if(t[l])return t[l].listeners.add(e)}function O(t,e,n){let r=t[l];if(!r)return;let o=r.listeners.delete(e);if(n&&!r.listeners.size){if(b.clear(t),!h.has(r))return o;let c=h.get(r);if(!h.has(c))return o;h.get(c).forEach(s=>O(s,c,!0))}return o}T(Q); diff --git a/dist/dde.js b/dist/dde.js index 659af6f..89305cc 100644 --- a/dist/dde.js +++ b/dist/dde.js @@ -1,6 +1,6 @@ //deka-dom-el library is available via global namespace `dde` (()=> { -var v={isSignal(t){return!1},processReactiveAttribute(t,e,n,c){return n}};function U(t,e=!0){return e?Object.assign(v,t):(Object.setPrototypeOf(t,v),t)}function x(t){return v.isPrototypeOf(t)&&t!==v?t:v}function b(t){return typeof t>"u"}function A(t,e){if(!t||!(t instanceof AbortSignal))return!0;if(!t.aborted)return t.addEventListener("abort",e),function(){t.removeEventListener("abort",e)}}var S={setDeleteAttr:k,ssr:""};function k(t,e,n){if(Reflect.set(t,e,n),!!b(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 l=[{scope:document.body,host:t=>t?t(document.body):document.body,custom_element:!1,prevent:!0}],E={get current(){return l[l.length-1]},get host(){return this.current.host},preventDefault(){let{current:t}=this;return t.prevent=!0,t},get state(){return[...l]},push(t={}){return l.push(Object.assign({},this.current,{prevent:!1},t))},pushRoot(){return l.push(l[0])},pop(){if(l.length!==1)return l.pop()}};function L(...t){return this.appendOriginal(...t),this}function q(t){return t.append===L||(t.appendOriginal=t.append,t.append=L),t}var O;function N(t,e,...n){let c=x(this),o=0,r,f;switch((Object(e)!==e||c.isSignal(e))&&(e={textContent:e}),!0){case typeof t=="function":{o=1,E.push({scope:t,host:(...h)=>h.length?(o===1?n.unshift(...h):h.forEach(g=>g(f)),void 0):f}),r=t(e||void 0);let d=r instanceof DocumentFragment;if(r.nodeName==="#comment")break;let a=N.mark({type:"component",name:t.name,host:d?"this":"parentElement"});r.prepend(a),d&&(f=a);break}case t==="#text":r=w.call(this,document.createTextNode(""),e);break;case(t==="<>"||!t):r=w.call(this,document.createDocumentFragment(),e);break;case!!O:r=w.call(this,document.createElementNS(O,t),e);break;case!r:r=w.call(this,document.createElement(t),e)}return q(r),f||(f=r),n.forEach(d=>d(f)),o&&E.pop(),o=2,r}N.mark=function(t,e=!1){t=Object.entries(t).map(([o,r])=>o+`="${r}"`).join(" ");let n=e?"":"/",c=document.createComment(``);return e||(c.end=document.createComment("")),c};function Y(t){let e=this;return function(...c){O=t;let o=N.call(e,...c);return O=void 0,o}}var{setDeleteAttr:j}=S,C=new WeakMap;function w(t,...e){if(!e.length)return t;C.set(t,M(t,this));for(let[n,c]of Object.entries(Object.assign({},...e)))W.call(this,t,n,c);return C.delete(t),t}function W(t,e,n){let{setRemoveAttr:c,s:o}=M(t,this),r=this;n=o.processReactiveAttribute(t,e,n,(d,a)=>W.call(r,t,d,a));let[f]=e;if(f==="=")return c(e.slice(1),n);if(f===".")return P(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 j(t,e,n);case"style":if(typeof n!="object")break;case"dataset":return y(o,n,P.bind(null,t[e]));case"ariaset":return y(o,n,(d,a)=>c("aria-"+d,a));case"classList":return z.call(r,t,n)}return B(t,e)?j(t,e,n):c(e,n)}function M(t,e){if(C.has(t))return C.get(t);let c=(t instanceof SVGElement?I:F).bind(null,t,"Attribute"),o=x(e);return{setRemoveAttr:c,s:o}}function z(t,e){let n=x(this);return y(n,e,(c,o)=>t.classList.toggle(c,o===-1?void 0:!!o)),t}function tt(t){return Array.from(t.children).forEach(e=>e.remove()),t}function B(t,e){if(!Reflect.has(t,e))return!1;let n=T(t,e);return!b(n.set)}function T(t,e){if(t=Object.getPrototypeOf(t),!t)return{};let n=Object.getOwnPropertyDescriptor(t,e);return n||T(t,e)}function y(t,e,n){if(!(typeof e!="object"||e===null))return Object.entries(e).forEach(function([o,r]){o&&(r=t.processReactiveAttribute(e,o,r,n),n(o,r))})}function $(t){return Array.isArray(t)?t.filter(Boolean).join(" "):t}function F(t,e,n,c){return t[(b(c)?"remove":"set")+e](n,$(c))}function I(t,e,n,c,o=null){return t[(b(c)?"remove":"set")+e+"NS"](o,n,$(c))}function P(t,e,n){if(Reflect.set(t,e,n),!!b(n))return Reflect.deleteProperty(t,e)}function rt(t,e,...n){let c=n.length?new CustomEvent(e,{detail:n[0]}):new Event(e);return t.dispatchEvent(c)}function _(t,e,n){return function(o){return o.addEventListener(t,e,n),o}}var R=G(),Z=new WeakSet;_.connected=function(t,e){let{custom_element:n}=E.current,c="connected";return typeof e!="object"&&(e={}),e.once=!0,function(r){n&&(r=n);let f="dde:"+c;return r.addEventListener(f,t,e),r.__dde_lifecycleToEvents?r:r.isConnected?(r.dispatchEvent(new Event(f)),r):(A(e.signal,()=>R.offConnected(r,t))&&R.onConnected(r,t),r)}};_.disconnected=function(t,e){let{custom_element:n}=E.current,c="disconnected";return typeof e!="object"&&(e={}),e.once=!0,function(r){n&&(r=n);let f="dde:"+c;return r.addEventListener(f,t,e),r.__dde_lifecycleToEvents||A(e.signal,()=>R.offDisconnected(r,t))&&R.onDisconnected(r,t),r}};var D=new WeakMap;_.disconnectedAsAbort=function(t){if(D.has(t))return D.get(t);let e=new AbortController;return D.set(t,e),t(_.disconnected(()=>e.abort())),e};_.attributeChanged=function(t,e){let n="attributeChanged";return typeof e!="object"&&(e={}),function(o){let r="dde:"+n;if(o.addEventListener(r,t,e),o.__dde_lifecycleToEvents||Z.has(o))return o;let f=new MutationObserver(function(a){for(let{attributeName:h,target:g}of a)g.dispatchEvent(new CustomEvent(r,{detail:[h,g.getAttribute(h)]}))});return A(e.signal,()=>f.disconnect())&&f.observe(o,{attributes:!0}),o}};function G(){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){r();let u=o(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,c(s,u))},onDisconnected(s,i){r();let u=o(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,c(s,u))}};function c(s,i){i.length_c||i.length_d||(t.delete(s),f())}function o(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 r(){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 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),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}} +var v={isSignal(t){return!1},processReactiveAttribute(t,e,n,c){return n}};function U(t,e=!0){return e?Object.assign(v,t):(Object.setPrototypeOf(t,v),t)}function x(t){return v.isPrototypeOf(t)&&t!==v?t:v}function b(t){return typeof t>"u"}function A(t,e){if(!t||!(t instanceof AbortSignal))return!0;if(!t.aborted)return t.addEventListener("abort",e),function(){t.removeEventListener("abort",e)}}var S={setDeleteAttr:k,ssr:""};function k(t,e,n){if(Reflect.set(t,e,n),!!b(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 l=[{scope:document.body,host:t=>t?t(document.body):document.body,custom_element:!1,prevent:!0}],E={get current(){return l[l.length-1]},get host(){return this.current.host},preventDefault(){let{current:t}=this;return t.prevent=!0,t},get state(){return[...l]},push(t={}){return l.push(Object.assign({},this.current,{prevent:!1},t))},pushRoot(){return l.push(l[0])},pop(){if(l.length!==1)return l.pop()}};function L(...t){return this.appendOriginal(...t),this}function q(t){return t.append===L||(t.appendOriginal=t.append,t.append=L),t}var O;function N(t,e,...n){let c=x(this),o=0,r,f;switch((Object(e)!==e||c.isSignal(e))&&(e={textContent:e}),!0){case typeof t=="function":{o=1,E.push({scope:t,host:(...p)=>p.length?(o===1?n.unshift(...p):p.forEach(g=>g(f)),void 0):f}),r=t(e||void 0);let d=r instanceof DocumentFragment;if(r.nodeName==="#comment")break;let a=N.mark({type:"component",name:t.name,host:d?"this":"parentElement"});r.prepend(a),d&&(f=a);break}case t==="#text":r=w.call(this,document.createTextNode(""),e);break;case(t==="<>"||!t):r=w.call(this,document.createDocumentFragment(),e);break;case!!O:r=w.call(this,document.createElementNS(O,t),e);break;case!r:r=w.call(this,document.createElement(t),e)}return q(r),f||(f=r),n.forEach(d=>d(f)),o&&E.pop(),o=2,r}N.mark=function(t,e=!1){t=Object.entries(t).map(([o,r])=>o+`="${r}"`).join(" ");let n=e?"":"/",c=document.createComment(``);return e||(c.end=document.createComment("")),c};function Y(t){let e=this;return function(...c){O=t;let o=N.call(e,...c);return O=void 0,o}}var{setDeleteAttr:j}=S,C=new WeakMap;function w(t,...e){if(!e.length)return t;C.set(t,M(t,this));for(let[n,c]of Object.entries(Object.assign({},...e)))W.call(this,t,n,c);return C.delete(t),t}function W(t,e,n){let{setRemoveAttr:c,s:o}=M(t,this),r=this;n=o.processReactiveAttribute(t,e,n,(d,a)=>W.call(r,t,d,a));let[f]=e;if(f==="=")return c(e.slice(1),n);if(f===".")return P(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 j(t,e,n);case"style":if(typeof n!="object")break;case"dataset":return y(o,n,P.bind(null,t[e]));case"ariaset":return y(o,n,(d,a)=>c("aria-"+d,a));case"classList":return z.call(r,t,n)}return B(t,e)?j(t,e,n):c(e,n)}function M(t,e){if(C.has(t))return C.get(t);let c=(t instanceof SVGElement?I:F).bind(null,t,"Attribute"),o=x(e);return{setRemoveAttr:c,s:o}}function z(t,e){let n=x(this);return y(n,e,(c,o)=>t.classList.toggle(c,o===-1?void 0:!!o)),t}function tt(t){return Array.from(t.children).forEach(e=>e.remove()),t}function B(t,e){if(!Reflect.has(t,e))return!1;let n=T(t,e);return!b(n.set)}function T(t,e){if(t=Object.getPrototypeOf(t),!t)return{};let n=Object.getOwnPropertyDescriptor(t,e);return n||T(t,e)}function y(t,e,n){if(!(typeof e!="object"||e===null))return Object.entries(e).forEach(function([o,r]){o&&(r=t.processReactiveAttribute(e,o,r,n),n(o,r))})}function $(t){return Array.isArray(t)?t.filter(Boolean).join(" "):t}function F(t,e,n,c){return t[(b(c)?"remove":"set")+e](n,$(c))}function I(t,e,n,c,o=null){return t[(b(c)?"remove":"set")+e+"NS"](o,n,$(c))}function P(t,e,n){if(Reflect.set(t,e,n),!!b(n))return Reflect.deleteProperty(t,e)}function rt(t,e={}){return function(c,...o){let r=o.length?new CustomEvent(t,Object.assign({detail:o[0]},e)):new Event(t,e);return c.dispatchEvent(r)}}function _(t,e,n){return function(o){return o.addEventListener(t,e,n),o}}var R=G(),Z=new WeakSet;_.connected=function(t,e){let{custom_element:n}=E.current,c="connected";return typeof e!="object"&&(e={}),e.once=!0,function(r){n&&(r=n);let f="dde:"+c;return r.addEventListener(f,t,e),r.__dde_lifecycleToEvents?r:r.isConnected?(r.dispatchEvent(new Event(f)),r):(A(e.signal,()=>R.offConnected(r,t))&&R.onConnected(r,t),r)}};_.disconnected=function(t,e){let{custom_element:n}=E.current,c="disconnected";return typeof e!="object"&&(e={}),e.once=!0,function(r){n&&(r=n);let f="dde:"+c;return r.addEventListener(f,t,e),r.__dde_lifecycleToEvents||A(e.signal,()=>R.offDisconnected(r,t))&&R.onDisconnected(r,t),r}};var D=new WeakMap;_.disconnectedAsAbort=function(t){if(D.has(t))return D.get(t);let e=new AbortController;return D.set(t,e),t(_.disconnected(()=>e.abort())),e};_.attributeChanged=function(t,e){let n="attributeChanged";return typeof e!="object"&&(e={}),function(o){let r="dde:"+n;if(o.addEventListener(r,t,e),o.__dde_lifecycleToEvents||Z.has(o))return o;let f=new MutationObserver(function(a){for(let{attributeName:p,target:g}of a)g.dispatchEvent(new CustomEvent(r,{detail:[p,g.getAttribute(p)]}))});return A(e.signal,()=>f.disconnect())&&f.observe(o,{attributes:!0}),o}};function G(){let t=new Map,e=!1,n=new MutationObserver(function(s){for(let i of s)if(i.type==="childList"){if(p(i.addedNodes,!0)){f();continue}g(i.removedNodes,!0)&&f()}});return{onConnected(s,i){r();let u=o(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,c(s,u))},onDisconnected(s,i){r();let u=o(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,c(s,u))}};function c(s,i){i.length_c||i.length_d||(t.delete(s),f())}function o(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 r(){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 p(s,i){let u=!1;for(let h of s){if(i&&a(h).then(p),!t.has(h))continue;let m=t.get(h);m.length_c&&(h.dispatchEvent(new Event("dde:connected")),m.connected=new WeakSet,m.length_c=0,m.length_d||t.delete(h),u=!0)}return u}function g(s,i){let u=!1;for(let h of s)i&&a(h).then(g),!(!t.has(h)||!t.get(h).length_d)&&(h.dispatchEvent(new Event("dde:disconnected")),t.delete(h),u=!0);return u}} globalThis.dde= {assign: w, assignAttribute: W, chainableAppend: q, diff --git a/dist/esm-with-signals.d.ts b/dist/esm-with-signals.d.ts index af78f55..5bca319 100644 --- a/dist/esm-with-signals.d.ts +++ b/dist/esm-with-signals.d.ts @@ -10,7 +10,7 @@ type SupportedElement= | CustomElementTagNameMap[keyof CustomElementTagNameMap] | ddePublicElementTagNameMap[keyof ddePublicElementTagNameMap]; declare global { - type ddeComponentAttributes= Record | undefined | string; + type ddeComponentAttributes= Record | undefined; type ddeElementAddon= (element: El)=> El | void; } type PascalCase= @@ -50,7 +50,7 @@ type ExtendedHTMLElementTagNameMap= HTMLElementTagNameMap & CustomElementTagName export function el( tag_name: TAG, attrs?: string | Partial>, - ...modifiers: ddeElementAddon[] + ...addons: ddeElementAddon[] ): ExtendedHTMLElementTagNameMap[TAG] export function el( tag_name?: "<>", @@ -58,16 +58,16 @@ export function el( export function el< A extends ddeComponentAttributes, - C extends (attr: A)=> SupportedElement | DocumentFragment>( + C extends (attr: Partial)=> SupportedElement | DocumentFragment>( fComponent: C, - attrs?: A, - ...modifiers: ddeElementAddon>[] + attrs?: A | string, + ...addons: ddeElementAddon>[] ): ReturnType export function el( tag_name: string, attrs?: string | Record, - ...modifiers: ddeElementAddon[] + ...addons: ddeElementAddon[] ): HTMLElement export function elNS( @@ -75,27 +75,27 @@ export function elNS( ): ( tag_name: TAG, attrs?: string | Partial<{ [key in KEYS]: SVGElementTagNameMap[TAG][key] | string | number | boolean }>, - ...modifiers: ddeElementAddon[] + ...addons: ddeElementAddon[] )=> SVGElementTagNameMap[TAG] 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: ddeElementAddon[] + ...addons: ddeElementAddon[] )=> MathMLElementTagNameMap[TAG] export function elNS( namespace: string ): ( tag_name: string, attrs?: string | Record, - ...modifiers: ddeElementAddon[] + ...addons: ddeElementAddon[] )=> SupportedElement export function chainableAppend(el: EL): EL; -export function dispatchEvent(element: SupportedElement, name: keyof DocumentEventMap): void; -export function dispatchEvent(element: SupportedElement, name: string, data: any): void; +export function dispatchEvent(name: keyof DocumentEventMap | string, options?: EventInit): + (element: SupportedElement, data?: any)=> void; interface On{ /** Listens to the DOM event. See {@link Document.addEventListener} */ < @@ -106,12 +106,19 @@ interface On{ listener: (this: El, ev: DocumentEventMap[Event]) => any, options?: AddEventListenerOptions ) : EE; + < + EE extends ddeElementAddon, + El extends ( EE extends ddeElementAddon ? El : never )>( + type: string, + listener: (this: El, ev: Event | CustomEvent ) => any, + options?: AddEventListenerOptions + ) : EE; /** Listens to the element is connected to the live DOM. In case of custom elements uses [`connectedCallback`](https://developer.mozilla.org/en-US/docs/Web/API/Web_components/Using_custom_elements#custom_element_lifecycle_callbacks), or {@link MutationObserver} else where */ connected< EE extends ddeElementAddon, El extends ( EE extends ddeElementAddon ? El : never ) >( - listener: (el: El) => any, + listener: (this: El, event: CustomEvent) => any, options?: AddEventListenerOptions ) : EE; /** Listens to the element is disconnected from the live DOM. In case of custom elements uses [`disconnectedCallback`](https://developer.mozilla.org/en-US/docs/Web/API/Web_components/Using_custom_elements#custom_element_lifecycle_callbacks), or {@link MutationObserver} else where */ @@ -119,7 +126,7 @@ interface On{ EE extends ddeElementAddon, El extends ( EE extends ddeElementAddon ? El : never ) >( - listener: (el: El) => any, + listener: (this: El, event: CustomEvent) => any, options?: AddEventListenerOptions ) : EE; /** Listens to the element attribute changes. In case of custom elements uses [`attributeChangedCallback`](https://developer.mozilla.org/en-US/docs/Web/API/Web_components/Using_custom_elements#custom_element_lifecycle_callbacks), or {@link MutationObserver} else where */ @@ -127,7 +134,7 @@ interface On{ EE extends ddeElementAddon, El extends ( EE extends ddeElementAddon ? El : never ) >( - listener: (el: El) => any, + listener: (this: El, event: CustomEvent<[ string, string ]>) => any, options?: AddEventListenerOptions ) : EE; } diff --git a/dist/esm-with-signals.js b/dist/esm-with-signals.js index ac9291d..df5ecaa 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 T(t,e=!0){return e?Object.assign(w,t):(Object.setPrototypeOf(t,w),t)}function R(t){return w.isPrototypeOf(t)&&t!==w?t:w}function x(t){return typeof t>"u"}function q(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 W={setDeleteAttr:Y,ssr:""};function Y(t,e,n){if(Reflect.set(t,e,n),!!x(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 E=[{scope:document.body,host:t=>t?t(document.body):document.body,custom_element:!1,prevent:!0}],g={get current(){return E[E.length-1]},get host(){return this.current.host},preventDefault(){let{current:t}=this;return t.prevent=!0,t},get state(){return[...E]},push(t={}){return E.push(Object.assign({},this.current,{prevent:!1},t))},pushRoot(){return E.push(E[0])},pop(){if(E.length!==1)return E.pop()}};function B(...t){return this.appendOriginal(...t),this}function tt(t){return t.append===B||(t.appendOriginal=t.append,t.append=B),t}var L;function y(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,g.push({scope:t,host:(...p)=>p.length?(o===1?n.unshift(...p):p.forEach(v=>v(s)),void 0):s}),c=t(e||void 0);let a=c instanceof DocumentFragment;if(c.nodeName==="#comment")break;let d=y.mark({type:"component",name:t.name,host:a?"this":"parentElement"});c.prepend(d),a&&(s=d);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 tt(c),s||(s=c),n.forEach(a=>a(s)),o&&g.pop(),o=2,c}y.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};function _t(t){let e=this;return function(...r){L=t;let o=y.call(e,...r);return L=void 0,o}}var{setDeleteAttr:H}=W,j=new WeakMap;function N(t,...e){if(!e.length)return t;j.set(t,Z(t,this));for(let[n,r]of Object.entries(Object.assign({},...e)))J.call(this,t,n,r);return j.delete(t),t}function J(t,e,n){let{setRemoveAttr:r,s:o}=Z(t,this),c=this;n=o.processReactiveAttribute(t,e,n,(a,d)=>J.call(c,t,a,d));let[s]=e;if(s==="=")return r(e.slice(1),n);if(s===".")return I(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 $(o,n,I.bind(null,t[e]));case"ariaset":return $(o,n,(a,d)=>r("aria-"+a,d));case"classList":return et.call(c,t,n)}return nt(t,e)?H(t,e,n):r(e,n)}function Z(t,e){if(j.has(t))return j.get(t);let r=(t instanceof SVGElement?ot:rt).bind(null,t,"Attribute"),o=R(e);return{setRemoveAttr:r,s:o}}function et(t,e){let n=R(this);return $(n,e,(r,o)=>t.classList.toggle(r,o===-1?void 0:!!o)),t}function Et(t){return Array.from(t.children).forEach(e=>e.remove()),t}function nt(t,e){if(!Reflect.has(t,e))return!1;let n=G(t,e);return!x(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,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 V(t){return Array.isArray(t)?t.filter(Boolean).join(" "):t}function rt(t,e,n,r){return t[(x(r)?"remove":"set")+e](n,V(r))}function ot(t,e,n,r,o=null){return t[(x(r)?"remove":"set")+e+"NS"](o,n,V(r))}function I(t,e,n){if(Reflect.set(t,e,n),!!x(n))return Reflect.deleteProperty(t,e)}function St(t,e,...n){let r=n.length?new CustomEvent(e,{detail:n[0]}):new Event(e);return t.dispatchEvent(r)}function _(t,e,n){return function(o){return o.addEventListener(t,e,n),o}}var P=st(),ct=new WeakSet;_.connected=function(t,e){let{custom_element:n}=g.current,r="connected";return typeof e!="object"&&(e={}),e.once=!0,function(c){n&&(c=n);let s="dde:"+r;return c.addEventListener(s,t,e),c.__dde_lifecycleToEvents?c:c.isConnected?(c.dispatchEvent(new Event(s)),c):(C(e.signal,()=>P.offConnected(c,t))&&P.onConnected(c,t),c)}};_.disconnected=function(t,e){let{custom_element:n}=g.current,r="disconnected";return typeof e!="object"&&(e={}),e.once=!0,function(c){n&&(c=n);let s="dde:"+r;return c.addEventListener(s,t,e),c.__dde_lifecycleToEvents||C(e.signal,()=>P.offDisconnected(c,t))&&P.onDisconnected(c,t),c}};var z=new WeakMap;_.disconnectedAsAbort=function(t){if(z.has(t))return z.get(t);let e=new AbortController;return z.set(t,e),t(_.disconnected(()=>e.abort())),e};_.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||ct.has(o))return o;let s=new MutationObserver(function(d){for(let{attributeName:p,target:v}of d)v.dispatchEvent(new CustomEvent(c,{detail:[p,v.getAttribute(p)]}))});return C(e.signal,()=>s.disconnect())&&s.observe(o,{attributes:!0}),o}};function st(){let t=new Map,e=!1,n=new MutationObserver(function(i){for(let u of i)if(u.type==="childList"){if(p(u.addedNodes,!0)){s();continue}v(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 a(){return new Promise(function(i){(requestIdleCallback||requestAnimationFrame)(i)})}async function d(i){t.size>30&&await a();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 p(i,u){let f=!1;for(let m of i){if(u&&d(m).then(p),!t.has(m))continue;let S=t.get(m);S.length_c&&(m.dispatchEvent(new Event("dde:connected")),S.connected=new WeakSet,S.length_c=0,S.length_d||t.delete(m),f=!0)}return f}function v(i,u){let f=!1;for(let m of i)u&&d(m).then(v),!(!t.has(m)||!t.get(m).length_d)&&(m.dispatchEvent(new Event("dde:disconnected")),t.delete(m),f=!0);return f}}var l=Symbol.for("Signal");function D(t){try{return Reflect.has(t,l)}catch{return!1}}var M=[],h=new WeakMap;function b(t,e){if(typeof t!="function")return K(t,e);if(D(t))return t;let n=K(),r=function(){let[o,...c]=h.get(r);if(h.set(r,new Set([o])),M.push(r),n(t()),M.pop(),!c.length)return;let s=h.get(r);for(let a of c)s.has(a)||O(a,r)};return h.set(n[l],r),h.set(r,new Set([n])),r(),n}b.action=function(t,e,...n){let r=t[l],{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))};b.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));U(e,n),o&&o.addEventListener("abort",()=>O(e,n))}};b.symbols={signal:l,onclear:Symbol.for("Signal.onclear")};var A="__dde_attributes";b.attribute=function(t,e=void 0){let n=b(e),r;return g.host(o=>{if(r=o,o instanceof HTMLElement?o.hasAttribute(t)&&n(o.getAttribute(t)):o.hasAttributeNS(null,t)&&n(o.getAttributeNS(null,t)),o[A]){o[A][t]=n;return}return o[A]={[t]:n},_.attributeChanged(function({detail:s}){/*! This maps attributes to signals (`S.attribute`). +var w={isSignal(t){return!1},processReactiveAttribute(t,e,n,r){return n}};function T(t,e=!0){return e?Object.assign(w,t):(Object.setPrototypeOf(t,w),t)}function R(t){return w.isPrototypeOf(t)&&t!==w?t:w}function x(t){return typeof t>"u"}function q(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 W={setDeleteAttr:Y,ssr:""};function Y(t,e,n){if(Reflect.set(t,e,n),!!x(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 E=[{scope:document.body,host:t=>t?t(document.body):document.body,custom_element:!1,prevent:!0}],g={get current(){return E[E.length-1]},get host(){return this.current.host},preventDefault(){let{current:t}=this;return t.prevent=!0,t},get state(){return[...E]},push(t={}){return E.push(Object.assign({},this.current,{prevent:!1},t))},pushRoot(){return E.push(E[0])},pop(){if(E.length!==1)return E.pop()}};function B(...t){return this.appendOriginal(...t),this}function tt(t){return t.append===B||(t.appendOriginal=t.append,t.append=B),t}var L;function y(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,g.push({scope:t,host:(...p)=>p.length?(o===1?n.unshift(...p):p.forEach(v=>v(s)),void 0):s}),c=t(e||void 0);let a=c instanceof DocumentFragment;if(c.nodeName==="#comment")break;let d=y.mark({type:"component",name:t.name,host:a?"this":"parentElement"});c.prepend(d),a&&(s=d);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 tt(c),s||(s=c),n.forEach(a=>a(s)),o&&g.pop(),o=2,c}y.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};function _t(t){let e=this;return function(...r){L=t;let o=y.call(e,...r);return L=void 0,o}}var{setDeleteAttr:H}=W,j=new WeakMap;function N(t,...e){if(!e.length)return t;j.set(t,Z(t,this));for(let[n,r]of Object.entries(Object.assign({},...e)))J.call(this,t,n,r);return j.delete(t),t}function J(t,e,n){let{setRemoveAttr:r,s:o}=Z(t,this),c=this;n=o.processReactiveAttribute(t,e,n,(a,d)=>J.call(c,t,a,d));let[s]=e;if(s==="=")return r(e.slice(1),n);if(s===".")return I(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 $(o,n,I.bind(null,t[e]));case"ariaset":return $(o,n,(a,d)=>r("aria-"+a,d));case"classList":return et.call(c,t,n)}return nt(t,e)?H(t,e,n):r(e,n)}function Z(t,e){if(j.has(t))return j.get(t);let r=(t instanceof SVGElement?ot:rt).bind(null,t,"Attribute"),o=R(e);return{setRemoveAttr:r,s:o}}function et(t,e){let n=R(this);return $(n,e,(r,o)=>t.classList.toggle(r,o===-1?void 0:!!o)),t}function Et(t){return Array.from(t.children).forEach(e=>e.remove()),t}function nt(t,e){if(!Reflect.has(t,e))return!1;let n=G(t,e);return!x(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,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 V(t){return Array.isArray(t)?t.filter(Boolean).join(" "):t}function rt(t,e,n,r){return t[(x(r)?"remove":"set")+e](n,V(r))}function ot(t,e,n,r,o=null){return t[(x(r)?"remove":"set")+e+"NS"](o,n,V(r))}function I(t,e,n){if(Reflect.set(t,e,n),!!x(n))return Reflect.deleteProperty(t,e)}function St(t,e={}){return function(r,...o){let c=o.length?new CustomEvent(t,Object.assign({detail:o[0]},e)):new Event(t,e);return r.dispatchEvent(c)}}function _(t,e,n){return function(o){return o.addEventListener(t,e,n),o}}var P=st(),ct=new WeakSet;_.connected=function(t,e){let{custom_element:n}=g.current,r="connected";return typeof e!="object"&&(e={}),e.once=!0,function(c){n&&(c=n);let s="dde:"+r;return c.addEventListener(s,t,e),c.__dde_lifecycleToEvents?c:c.isConnected?(c.dispatchEvent(new Event(s)),c):(C(e.signal,()=>P.offConnected(c,t))&&P.onConnected(c,t),c)}};_.disconnected=function(t,e){let{custom_element:n}=g.current,r="disconnected";return typeof e!="object"&&(e={}),e.once=!0,function(c){n&&(c=n);let s="dde:"+r;return c.addEventListener(s,t,e),c.__dde_lifecycleToEvents||C(e.signal,()=>P.offDisconnected(c,t))&&P.onDisconnected(c,t),c}};var z=new WeakMap;_.disconnectedAsAbort=function(t){if(z.has(t))return z.get(t);let e=new AbortController;return z.set(t,e),t(_.disconnected(()=>e.abort())),e};_.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||ct.has(o))return o;let s=new MutationObserver(function(d){for(let{attributeName:p,target:v}of d)v.dispatchEvent(new CustomEvent(c,{detail:[p,v.getAttribute(p)]}))});return C(e.signal,()=>s.disconnect())&&s.observe(o,{attributes:!0}),o}};function st(){let t=new Map,e=!1,n=new MutationObserver(function(i){for(let u of i)if(u.type==="childList"){if(p(u.addedNodes,!0)){s();continue}v(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 a(){return new Promise(function(i){(requestIdleCallback||requestAnimationFrame)(i)})}async function d(i){t.size>30&&await a();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 p(i,u){let f=!1;for(let m of i){if(u&&d(m).then(p),!t.has(m))continue;let S=t.get(m);S.length_c&&(m.dispatchEvent(new Event("dde:connected")),S.connected=new WeakSet,S.length_c=0,S.length_d||t.delete(m),f=!0)}return f}function v(i,u){let f=!1;for(let m of i)u&&d(m).then(v),!(!t.has(m)||!t.get(m).length_d)&&(m.dispatchEvent(new Event("dde:disconnected")),t.delete(m),f=!0);return f}}var l=Symbol.for("Signal");function D(t){try{return Reflect.has(t,l)}catch{return!1}}var M=[],h=new WeakMap;function b(t,e){if(typeof t!="function")return K(t,e);if(D(t))return t;let n=K(),r=function(){let[o,...c]=h.get(r);if(h.set(r,new Set([o])),M.push(r),n(t()),M.pop(),!c.length)return;let s=h.get(r);for(let a of c)s.has(a)||O(a,r)};return h.set(n[l],r),h.set(r,new Set([n])),r(),n}b.action=function(t,e,...n){let r=t[l],{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))};b.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));U(e,n),o&&o.addEventListener("abort",()=>O(e,n))}};b.symbols={signal:l,onclear:Symbol.for("Signal.onclear")};var A="__dde_attributes";b.attribute=function(t,e=void 0){let n=b(e),r;return g.host(o=>{if(r=o,o instanceof HTMLElement?o.hasAttribute(t)&&n(o.getAttribute(t)):o.hasAttributeNS(null,t)&&n(o.getAttributeNS(null,t)),o[A]){o[A][t]=n;return}return o[A]={[t]:n},_.attributeChanged(function({detail:s}){/*! This maps attributes to signals (`S.attribute`). * Investigate `__dde_attributes` key of the element.*/let[a,d]=s,p=o[A][a];if(p)return p(d)})(o),_.disconnected(function(){/*! This removes all signals mapped to attributes (`S.attribute`). * Investigate `__dde_attributes` key of the element.*/b.clear(...Object.values(o[A])),r=null})(o),o}),new Proxy(n,{apply(o,c,s){if(!s.length)return o();if(!r)return;let a=s[0];return r instanceof HTMLElement?r.setAttribute(t,a):r.setAttributeNS(null,t,a)}})};b.clear=function(...t){for(let n of t){Reflect.deleteProperty(n,"toJSON");let r=n[l];r.onclear.forEach(o=>o.call(r)),e(n,r),Reflect.deleteProperty(n,l)}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)&&(b.clear(...c),h.delete(o))})}};var k="__dde_reactive";b.el=function(t,e){let n=y.mark({type:"reactive"},!1),r=n.end,o=document.createDocumentFragment();o.append(n,r);let{current:c}=g,s=a=>{if(!n.parentNode||!r.parentNode)return O(t,s);g.push(c);let d=e(a);g.pop(),Array.isArray(d)||(d=[d]);let p=n;for(;(p=n.nextSibling)!==r;)p.remove();n.after(...d)};return U(t,s),X(t,s,n,e),s(t()),o};var Q={isSignal:D,processReactiveAttribute(t,e,n,r){if(!D(n))return n;let o=c=>r(e,c);return U(n,o),X(n,o,t,e),n()}};function X(t,e,...n){let{current:r}=g;r.prevent||r.host(function(o){o[k]||(o[k]=[],_.disconnected(()=>o[k].forEach(([[c,s]])=>O(c,s,c[l]?.host()===o)))(o)),o[k].push([[t,e],...n])})}function K(t,e){let n=(...r)=>r.length?dt(n,...r):at(n);return ut(n,t,e)}var it=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 ut(t,e,n){let r=[];q(n)!=="[object Object]"&&(n={});let{onclear:o}=b.symbols;n[o]&&(r.push(n[o]),Reflect.deleteProperty(n,o));let{host:c}=g;return Reflect.defineProperty(t,l,{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[l],it),t}function ft(){return M[M.length-1]}function at(t){if(!t[l])return;let{value:e,listeners:n}=t[l],r=ft();return r&&n.add(r),h.has(r)&&h.get(r).add(t),e}function dt(t,e,n){if(!t[l])return;let r=t[l];if(!(!n&&r.value===e))return r.value=e,r.listeners.forEach(o=>o(e)),e}function U(t,e){if(t[l])return t[l].listeners.add(e)}function O(t,e,n){let r=t[l];if(!r)return;let o=r.listeners.delete(e);if(n&&!r.listeners.size){if(b.clear(t),!h.has(r))return o;let c=h.get(r);if(!h.has(c))return o;h.get(c).forEach(s=>O(s,c,!0))}return o}T(Q);export{b as S,N as assign,J as assignAttribute,tt as chainableAppend,et as classListDeclarative,y as createElement,_t as createElementNS,St as dispatchEvent,y as el,_t as elNS,Et as empty,D as isSignal,_ as on,T as registerReactivity,g as scope}; diff --git a/dist/esm.d.ts b/dist/esm.d.ts index 5aab9ef..e16f5cb 100644 --- a/dist/esm.d.ts +++ b/dist/esm.d.ts @@ -10,7 +10,7 @@ type SupportedElement= | CustomElementTagNameMap[keyof CustomElementTagNameMap] | ddePublicElementTagNameMap[keyof ddePublicElementTagNameMap]; declare global { - type ddeComponentAttributes= Record | undefined | string; + type ddeComponentAttributes= Record | undefined; type ddeElementAddon= (element: El)=> El | void; } type PascalCase= @@ -50,7 +50,7 @@ type ExtendedHTMLElementTagNameMap= HTMLElementTagNameMap & CustomElementTagName export function el( tag_name: TAG, attrs?: string | Partial>, - ...modifiers: ddeElementAddon[] + ...addons: ddeElementAddon[] ): ExtendedHTMLElementTagNameMap[TAG] export function el( tag_name?: "<>", @@ -58,16 +58,16 @@ export function el( export function el< A extends ddeComponentAttributes, - C extends (attr: A)=> SupportedElement | DocumentFragment>( + C extends (attr: Partial)=> SupportedElement | DocumentFragment>( fComponent: C, - attrs?: A, - ...modifiers: ddeElementAddon>[] + attrs?: A | string, + ...addons: ddeElementAddon>[] ): ReturnType export function el( tag_name: string, attrs?: string | Record, - ...modifiers: ddeElementAddon[] + ...addons: ddeElementAddon[] ): HTMLElement export function elNS( @@ -75,27 +75,27 @@ export function elNS( ): ( tag_name: TAG, attrs?: string | Partial<{ [key in KEYS]: SVGElementTagNameMap[TAG][key] | string | number | boolean }>, - ...modifiers: ddeElementAddon[] + ...addons: ddeElementAddon[] )=> SVGElementTagNameMap[TAG] 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: ddeElementAddon[] + ...addons: ddeElementAddon[] )=> MathMLElementTagNameMap[TAG] export function elNS( namespace: string ): ( tag_name: string, attrs?: string | Record, - ...modifiers: ddeElementAddon[] + ...addons: ddeElementAddon[] )=> SupportedElement export function chainableAppend(el: EL): EL; -export function dispatchEvent(element: SupportedElement, name: keyof DocumentEventMap): void; -export function dispatchEvent(element: SupportedElement, name: string, data: any): void; +export function dispatchEvent(name: keyof DocumentEventMap | string, options?: EventInit): + (element: SupportedElement, data?: any)=> void; interface On{ /** Listens to the DOM event. See {@link Document.addEventListener} */ < @@ -106,12 +106,19 @@ interface On{ listener: (this: El, ev: DocumentEventMap[Event]) => any, options?: AddEventListenerOptions ) : EE; + < + EE extends ddeElementAddon, + El extends ( EE extends ddeElementAddon ? El : never )>( + type: string, + listener: (this: El, ev: Event | CustomEvent ) => any, + options?: AddEventListenerOptions + ) : EE; /** Listens to the element is connected to the live DOM. In case of custom elements uses [`connectedCallback`](https://developer.mozilla.org/en-US/docs/Web/API/Web_components/Using_custom_elements#custom_element_lifecycle_callbacks), or {@link MutationObserver} else where */ connected< EE extends ddeElementAddon, El extends ( EE extends ddeElementAddon ? El : never ) >( - listener: (el: El) => any, + listener: (this: El, event: CustomEvent) => any, options?: AddEventListenerOptions ) : EE; /** Listens to the element is disconnected from the live DOM. In case of custom elements uses [`disconnectedCallback`](https://developer.mozilla.org/en-US/docs/Web/API/Web_components/Using_custom_elements#custom_element_lifecycle_callbacks), or {@link MutationObserver} else where */ @@ -119,7 +126,7 @@ interface On{ EE extends ddeElementAddon, El extends ( EE extends ddeElementAddon ? El : never ) >( - listener: (el: El) => any, + listener: (this: El, event: CustomEvent) => any, options?: AddEventListenerOptions ) : EE; /** Listens to the element attribute changes. In case of custom elements uses [`attributeChangedCallback`](https://developer.mozilla.org/en-US/docs/Web/API/Web_components/Using_custom_elements#custom_element_lifecycle_callbacks), or {@link MutationObserver} else where */ @@ -127,7 +134,7 @@ interface On{ EE extends ddeElementAddon, El extends ( EE extends ddeElementAddon ? El : never ) >( - listener: (el: El) => any, + listener: (this: El, event: CustomEvent<[ string, string ]>) => any, options?: AddEventListenerOptions ) : EE; } diff --git a/dist/esm.js b/dist/esm.js index fbf8660..b10384e 100644 --- a/dist/esm.js +++ b/dist/esm.js @@ -1 +1 @@ -var v={isSignal(t){return!1},processReactiveAttribute(t,e,n,c){return n}};function U(t,e=!0){return e?Object.assign(v,t):(Object.setPrototypeOf(t,v),t)}function x(t){return v.isPrototypeOf(t)&&t!==v?t:v}function b(t){return typeof t>"u"}function A(t,e){if(!t||!(t instanceof AbortSignal))return!0;if(!t.aborted)return t.addEventListener("abort",e),function(){t.removeEventListener("abort",e)}}var S={setDeleteAttr:k,ssr:""};function k(t,e,n){if(Reflect.set(t,e,n),!!b(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 l=[{scope:document.body,host:t=>t?t(document.body):document.body,custom_element:!1,prevent:!0}],E={get current(){return l[l.length-1]},get host(){return this.current.host},preventDefault(){let{current:t}=this;return t.prevent=!0,t},get state(){return[...l]},push(t={}){return l.push(Object.assign({},this.current,{prevent:!1},t))},pushRoot(){return l.push(l[0])},pop(){if(l.length!==1)return l.pop()}};function L(...t){return this.appendOriginal(...t),this}function q(t){return t.append===L||(t.appendOriginal=t.append,t.append=L),t}var O;function N(t,e,...n){let c=x(this),o=0,r,f;switch((Object(e)!==e||c.isSignal(e))&&(e={textContent:e}),!0){case typeof t=="function":{o=1,E.push({scope:t,host:(...h)=>h.length?(o===1?n.unshift(...h):h.forEach(g=>g(f)),void 0):f}),r=t(e||void 0);let d=r instanceof DocumentFragment;if(r.nodeName==="#comment")break;let a=N.mark({type:"component",name:t.name,host:d?"this":"parentElement"});r.prepend(a),d&&(f=a);break}case t==="#text":r=w.call(this,document.createTextNode(""),e);break;case(t==="<>"||!t):r=w.call(this,document.createDocumentFragment(),e);break;case!!O:r=w.call(this,document.createElementNS(O,t),e);break;case!r:r=w.call(this,document.createElement(t),e)}return q(r),f||(f=r),n.forEach(d=>d(f)),o&&E.pop(),o=2,r}N.mark=function(t,e=!1){t=Object.entries(t).map(([o,r])=>o+`="${r}"`).join(" ");let n=e?"":"/",c=document.createComment(``);return e||(c.end=document.createComment("")),c};function Y(t){let e=this;return function(...c){O=t;let o=N.call(e,...c);return O=void 0,o}}var{setDeleteAttr:j}=S,C=new WeakMap;function w(t,...e){if(!e.length)return t;C.set(t,M(t,this));for(let[n,c]of Object.entries(Object.assign({},...e)))W.call(this,t,n,c);return C.delete(t),t}function W(t,e,n){let{setRemoveAttr:c,s:o}=M(t,this),r=this;n=o.processReactiveAttribute(t,e,n,(d,a)=>W.call(r,t,d,a));let[f]=e;if(f==="=")return c(e.slice(1),n);if(f===".")return P(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 j(t,e,n);case"style":if(typeof n!="object")break;case"dataset":return y(o,n,P.bind(null,t[e]));case"ariaset":return y(o,n,(d,a)=>c("aria-"+d,a));case"classList":return z.call(r,t,n)}return B(t,e)?j(t,e,n):c(e,n)}function M(t,e){if(C.has(t))return C.get(t);let c=(t instanceof SVGElement?I:F).bind(null,t,"Attribute"),o=x(e);return{setRemoveAttr:c,s:o}}function z(t,e){let n=x(this);return y(n,e,(c,o)=>t.classList.toggle(c,o===-1?void 0:!!o)),t}function tt(t){return Array.from(t.children).forEach(e=>e.remove()),t}function B(t,e){if(!Reflect.has(t,e))return!1;let n=T(t,e);return!b(n.set)}function T(t,e){if(t=Object.getPrototypeOf(t),!t)return{};let n=Object.getOwnPropertyDescriptor(t,e);return n||T(t,e)}function y(t,e,n){if(!(typeof e!="object"||e===null))return Object.entries(e).forEach(function([o,r]){o&&(r=t.processReactiveAttribute(e,o,r,n),n(o,r))})}function $(t){return Array.isArray(t)?t.filter(Boolean).join(" "):t}function F(t,e,n,c){return t[(b(c)?"remove":"set")+e](n,$(c))}function I(t,e,n,c,o=null){return t[(b(c)?"remove":"set")+e+"NS"](o,n,$(c))}function P(t,e,n){if(Reflect.set(t,e,n),!!b(n))return Reflect.deleteProperty(t,e)}function rt(t,e,...n){let c=n.length?new CustomEvent(e,{detail:n[0]}):new Event(e);return t.dispatchEvent(c)}function _(t,e,n){return function(o){return o.addEventListener(t,e,n),o}}var R=G(),Z=new WeakSet;_.connected=function(t,e){let{custom_element:n}=E.current,c="connected";return typeof e!="object"&&(e={}),e.once=!0,function(r){n&&(r=n);let f="dde:"+c;return r.addEventListener(f,t,e),r.__dde_lifecycleToEvents?r:r.isConnected?(r.dispatchEvent(new Event(f)),r):(A(e.signal,()=>R.offConnected(r,t))&&R.onConnected(r,t),r)}};_.disconnected=function(t,e){let{custom_element:n}=E.current,c="disconnected";return typeof e!="object"&&(e={}),e.once=!0,function(r){n&&(r=n);let f="dde:"+c;return r.addEventListener(f,t,e),r.__dde_lifecycleToEvents||A(e.signal,()=>R.offDisconnected(r,t))&&R.onDisconnected(r,t),r}};var D=new WeakMap;_.disconnectedAsAbort=function(t){if(D.has(t))return D.get(t);let e=new AbortController;return D.set(t,e),t(_.disconnected(()=>e.abort())),e};_.attributeChanged=function(t,e){let n="attributeChanged";return typeof e!="object"&&(e={}),function(o){let r="dde:"+n;if(o.addEventListener(r,t,e),o.__dde_lifecycleToEvents||Z.has(o))return o;let f=new MutationObserver(function(a){for(let{attributeName:h,target:g}of a)g.dispatchEvent(new CustomEvent(r,{detail:[h,g.getAttribute(h)]}))});return A(e.signal,()=>f.disconnect())&&f.observe(o,{attributes:!0}),o}};function G(){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){r();let u=o(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,c(s,u))},onDisconnected(s,i){r();let u=o(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,c(s,u))}};function c(s,i){i.length_c||i.length_d||(t.delete(s),f())}function o(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 r(){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 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),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,W as assignAttribute,q as chainableAppend,z as classListDeclarative,N as createElement,Y as createElementNS,rt as dispatchEvent,N as el,Y as elNS,tt as empty,_ as on,U as registerReactivity,E as scope}; +var v={isSignal(t){return!1},processReactiveAttribute(t,e,n,c){return n}};function U(t,e=!0){return e?Object.assign(v,t):(Object.setPrototypeOf(t,v),t)}function x(t){return v.isPrototypeOf(t)&&t!==v?t:v}function b(t){return typeof t>"u"}function A(t,e){if(!t||!(t instanceof AbortSignal))return!0;if(!t.aborted)return t.addEventListener("abort",e),function(){t.removeEventListener("abort",e)}}var S={setDeleteAttr:k,ssr:""};function k(t,e,n){if(Reflect.set(t,e,n),!!b(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 l=[{scope:document.body,host:t=>t?t(document.body):document.body,custom_element:!1,prevent:!0}],E={get current(){return l[l.length-1]},get host(){return this.current.host},preventDefault(){let{current:t}=this;return t.prevent=!0,t},get state(){return[...l]},push(t={}){return l.push(Object.assign({},this.current,{prevent:!1},t))},pushRoot(){return l.push(l[0])},pop(){if(l.length!==1)return l.pop()}};function L(...t){return this.appendOriginal(...t),this}function q(t){return t.append===L||(t.appendOriginal=t.append,t.append=L),t}var O;function N(t,e,...n){let c=x(this),o=0,r,f;switch((Object(e)!==e||c.isSignal(e))&&(e={textContent:e}),!0){case typeof t=="function":{o=1,E.push({scope:t,host:(...p)=>p.length?(o===1?n.unshift(...p):p.forEach(g=>g(f)),void 0):f}),r=t(e||void 0);let d=r instanceof DocumentFragment;if(r.nodeName==="#comment")break;let a=N.mark({type:"component",name:t.name,host:d?"this":"parentElement"});r.prepend(a),d&&(f=a);break}case t==="#text":r=w.call(this,document.createTextNode(""),e);break;case(t==="<>"||!t):r=w.call(this,document.createDocumentFragment(),e);break;case!!O:r=w.call(this,document.createElementNS(O,t),e);break;case!r:r=w.call(this,document.createElement(t),e)}return q(r),f||(f=r),n.forEach(d=>d(f)),o&&E.pop(),o=2,r}N.mark=function(t,e=!1){t=Object.entries(t).map(([o,r])=>o+`="${r}"`).join(" ");let n=e?"":"/",c=document.createComment(``);return e||(c.end=document.createComment("")),c};function Y(t){let e=this;return function(...c){O=t;let o=N.call(e,...c);return O=void 0,o}}var{setDeleteAttr:j}=S,C=new WeakMap;function w(t,...e){if(!e.length)return t;C.set(t,M(t,this));for(let[n,c]of Object.entries(Object.assign({},...e)))W.call(this,t,n,c);return C.delete(t),t}function W(t,e,n){let{setRemoveAttr:c,s:o}=M(t,this),r=this;n=o.processReactiveAttribute(t,e,n,(d,a)=>W.call(r,t,d,a));let[f]=e;if(f==="=")return c(e.slice(1),n);if(f===".")return P(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 j(t,e,n);case"style":if(typeof n!="object")break;case"dataset":return y(o,n,P.bind(null,t[e]));case"ariaset":return y(o,n,(d,a)=>c("aria-"+d,a));case"classList":return z.call(r,t,n)}return B(t,e)?j(t,e,n):c(e,n)}function M(t,e){if(C.has(t))return C.get(t);let c=(t instanceof SVGElement?I:F).bind(null,t,"Attribute"),o=x(e);return{setRemoveAttr:c,s:o}}function z(t,e){let n=x(this);return y(n,e,(c,o)=>t.classList.toggle(c,o===-1?void 0:!!o)),t}function tt(t){return Array.from(t.children).forEach(e=>e.remove()),t}function B(t,e){if(!Reflect.has(t,e))return!1;let n=T(t,e);return!b(n.set)}function T(t,e){if(t=Object.getPrototypeOf(t),!t)return{};let n=Object.getOwnPropertyDescriptor(t,e);return n||T(t,e)}function y(t,e,n){if(!(typeof e!="object"||e===null))return Object.entries(e).forEach(function([o,r]){o&&(r=t.processReactiveAttribute(e,o,r,n),n(o,r))})}function $(t){return Array.isArray(t)?t.filter(Boolean).join(" "):t}function F(t,e,n,c){return t[(b(c)?"remove":"set")+e](n,$(c))}function I(t,e,n,c,o=null){return t[(b(c)?"remove":"set")+e+"NS"](o,n,$(c))}function P(t,e,n){if(Reflect.set(t,e,n),!!b(n))return Reflect.deleteProperty(t,e)}function rt(t,e={}){return function(c,...o){let r=o.length?new CustomEvent(t,Object.assign({detail:o[0]},e)):new Event(t,e);return c.dispatchEvent(r)}}function _(t,e,n){return function(o){return o.addEventListener(t,e,n),o}}var R=G(),Z=new WeakSet;_.connected=function(t,e){let{custom_element:n}=E.current,c="connected";return typeof e!="object"&&(e={}),e.once=!0,function(r){n&&(r=n);let f="dde:"+c;return r.addEventListener(f,t,e),r.__dde_lifecycleToEvents?r:r.isConnected?(r.dispatchEvent(new Event(f)),r):(A(e.signal,()=>R.offConnected(r,t))&&R.onConnected(r,t),r)}};_.disconnected=function(t,e){let{custom_element:n}=E.current,c="disconnected";return typeof e!="object"&&(e={}),e.once=!0,function(r){n&&(r=n);let f="dde:"+c;return r.addEventListener(f,t,e),r.__dde_lifecycleToEvents||A(e.signal,()=>R.offDisconnected(r,t))&&R.onDisconnected(r,t),r}};var D=new WeakMap;_.disconnectedAsAbort=function(t){if(D.has(t))return D.get(t);let e=new AbortController;return D.set(t,e),t(_.disconnected(()=>e.abort())),e};_.attributeChanged=function(t,e){let n="attributeChanged";return typeof e!="object"&&(e={}),function(o){let r="dde:"+n;if(o.addEventListener(r,t,e),o.__dde_lifecycleToEvents||Z.has(o))return o;let f=new MutationObserver(function(a){for(let{attributeName:p,target:g}of a)g.dispatchEvent(new CustomEvent(r,{detail:[p,g.getAttribute(p)]}))});return A(e.signal,()=>f.disconnect())&&f.observe(o,{attributes:!0}),o}};function G(){let t=new Map,e=!1,n=new MutationObserver(function(s){for(let i of s)if(i.type==="childList"){if(p(i.addedNodes,!0)){f();continue}g(i.removedNodes,!0)&&f()}});return{onConnected(s,i){r();let u=o(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,c(s,u))},onDisconnected(s,i){r();let u=o(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,c(s,u))}};function c(s,i){i.length_c||i.length_d||(t.delete(s),f())}function o(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 r(){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 p(s,i){let u=!1;for(let h of s){if(i&&a(h).then(p),!t.has(h))continue;let m=t.get(h);m.length_c&&(h.dispatchEvent(new Event("dde:connected")),m.connected=new WeakSet,m.length_c=0,m.length_d||t.delete(h),u=!0)}return u}function g(s,i){let u=!1;for(let h of s)i&&a(h).then(g),!(!t.has(h)||!t.get(h).length_d)&&(h.dispatchEvent(new Event("dde:disconnected")),t.delete(h),u=!0);return u}}export{w as assign,W as assignAttribute,q as chainableAppend,z as classListDeclarative,N as createElement,Y as createElementNS,rt as dispatchEvent,N as el,Y as elNS,tt as empty,_ as on,U as registerReactivity,E as scope}; diff --git a/docs/elements.html b/docs/elements.html index 374d3f0..e841ecb 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 also known as a JavaScript property.

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 also known as a JavaScript property.

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.
  • You can use = or . to force processing given key as attribute/property of the element.

For processing, the assign internally uses assignAttribute and classListDeclarative.

import { assign, 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.
  • You can use = or . to force processing given key as attribute/property of the element.

For processing, the assign internally uses assignAttribute and classListDeclarative.

import { assign, 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!"); @@ -56,7 +56,7 @@ console.log("paragraph.something=", paragraph.something); 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") @@ -67,7 +67,7 @@ const template= document.createElement("main").append( document.createElement("span"), ); console.log(typeof template==="undefined"); -

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"; +

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; }", @@ -102,7 +102,7 @@ document.body.append( ) ) ); -

Basic (state-less) 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"; +

§ Basic (state-less) 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; }", @@ -119,7 +119,7 @@ function component({ className, textContent }){ el("p", textContent) ); } -

As you can see, in case of state-less/basic components there is no difference between calling component function directly or using el function.

It is nice to use similar naming convention as native DOM API. This allows us to use the destructuring assignment syntax and keep track of the native API (things are best remembered through regular use).

Creating non-HTML elements

Similarly to the native DOM API (document.createElementNS) for non-HTML elements we need to tell JavaScript which kind of the element to create. We can use the elNS function:

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

As you can see, in case of state-less/basic components there is no difference between calling component function directly or using el function.

It is nice to use similar naming convention as native DOM API. This allows us to use the destructuring assignment syntax and keep track of the native API (things are best remembered through regular use).

§ Creating non-HTML elements

Similarly to the native DOM API (document.createElementNS) for non-HTML elements we need to tell JavaScript which kind of the element to create. We can use the elNS function:

import { elNS, assign } from "https://cdn.jsdelivr.net/gh/jaandrle/deka-dom-el/dist/esm-with-signals.js"; const elSVG= elNS("http://www.w3.org/2000/svg"); const elMath= elNS("http://www.w3.org/1998/Math/MathML"); document.body.append( @@ -130,4 +130,4 @@ document.body.append( console.log( document.body.innerHTML.includes("<svg></svg><math></math>") ) -
\ No newline at end of file +
\ No newline at end of file diff --git a/docs/events.html b/docs/events.html index f8aca87..97d574d 100644 --- a/docs/events.html +++ b/docs/events.html @@ -1,4 +1,4 @@ -`deka-dom-el` — Events and Addons

`deka-dom-el` — Events and Addons

Using not only events in UI declaratively.

Listenning to the native DOM events and other Addons

We quickly introduce helper to listening to the native DOM events. And library syntax/pattern so-called Addon to incorporate not only this in UI templates declaratively.

Events and listenners

In JavaScript you can listen to the native DOM events of the given element by using element.addEventListener(type, listener, options). The library provides an alternative (on) accepting the differen order of the arguments:

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

`deka-dom-el` — Events and Addons

Using not only events in UI declaratively.

Listenning to the native DOM events and other Addons

We quickly introduce helper to listening to the native DOM events. And library syntax/pattern so-called Addon to incorporate not only this in UI templates declaratively.

§ Events and listenners

In JavaScript you can listen to the native DOM events of the given element by using element.addEventListener(type, listener, options). The library provides an alternative (on) accepting the differen order of the arguments:

import { el, on } from "https://cdn.jsdelivr.net/gh/jaandrle/deka-dom-el/dist/esm-with-signals.js"; const log= mark=> console.log.bind(console, mark); const button= el("button", "Test click"); @@ -8,7 +8,7 @@ on("click", log("`on`"), { once: true })(button); document.body.append( button ); -

…this is actually one of the two differences. The another one is thaton accepts only object as the options (but it is still optional).

The other difference is that there is no off function. You can remove listener declaratively using AbortSignal:

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

…this is actually one of the two differences. The another one is that on accepts only object as the options (but it is still optional).

The other difference is that there is no off function. You can remove listener declaratively using AbortSignal:

import { el, on } from "https://cdn.jsdelivr.net/gh/jaandrle/deka-dom-el/dist/esm-with-signals.js"; const log= mark=> console.log.bind(console, mark); const abort_controller= new AbortController(); @@ -21,7 +21,7 @@ on("click", log("`on`"), { signal })(button); document.body.append( button, " ", el("button", { textContent: "Off", onclick: ()=> abort_controller.abort() }) ); -

Addons

From practical point of view, Addons are just functions that accept any html element as their first parameter. You can see that the on(…) fullfills this requirement.

You can use Addons as ≥3rd argument of el function. This way is possible to extends you templates by additional (3rd party) functionalities. But for now mainly, you can add events listeners:

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

So, there are (typically) three ways to handle events. You can use:

  • el("button", { textContent: "click me", "=onclick": "console.log(event)" })
  • el("button", { textContent: "click me", onclick: console.log })
  • el("button", { textContent: "click me" }, on("click", console.log))

In the first example we force to use HTML attribute (it corresponds to <button onclick="console.log(event)">click me</button>). Side note: this can be useful in case of SSR. To study difference, you can read a nice summary here: GIST @WebReflection/web_events.md.

§ Addons

From practical point of view, Addons are just functions that accept any html element as their first parameter. You can see that the on(…) fullfills this requirement.

You can use Addons as ≥3rd argument of el function. This way is possible to extends you templates by additional (3rd party) functionalities. But for now mainly, you can add events listeners:

import { el, on } from "https://cdn.jsdelivr.net/gh/jaandrle/deka-dom-el/dist/esm-with-signals.js"; const abort_controller= new AbortController(); const { signal }= abort_controller; /** @type {ddeElementAddon<HTMLButtonElement>} */ @@ -45,4 +45,36 @@ function update(event){ "\n" ); } -

As the example shows, you can also provide types in JSDoc+TypeScript by using global type ddeElementAddon. Also notice, you can use Addons to get element reference.

Life cycle events

Addons are called immediately when the element is created, event it is not connected to live DOM yet.

\ No newline at end of file +

As the example shows, you can also provide types in JSDoc+TypeScript by using global type ddeElementAddon. Also notice, you can use Addons to get element reference.

§ Life-cycle events

Addons are called immediately when the element is created, even it is not connected to live DOM yet. Therefore, you can understand the Addon to be “oncreate” event.

The library provide three additional live-cycle events corresponding to how they are named in a case of custom elements: on.connected, on.disconnected and on.attributeChanged.

import { el, on } from "https://cdn.jsdelivr.net/gh/jaandrle/deka-dom-el/dist/esm-with-signals.js"; +const paragraph= el("p", "See live-cycle events in console.", + el=> log({ type: "dde:created", detail: el }), + on.connected(log), + on.disconnected(log), + on.attributeChanged(log)); + +document.body.append( + paragraph, + el("button", "Update attribute", on("click", ()=> paragraph.setAttribute("test", Math.random().toString()))), + " ", + el("button", "Remove", on("click", ()=> paragraph.remove())) +); + +/** @param {Partial<CustomEvent>} event */ +function log({ type, detail }){ + console.log({ _this: this, type, detail }); +} +

For Custom elements, we will later introduce a way to replace *Callback syntax with dde:* events. The on.* functions then listen to the appropriate Custom Elements events (see Custom element lifecycle callbacks | MDN).

But, in case of regular elemnets the MutationObserver | MDN is internaly used to track these events. Therefore, there are some drawbacks:

  • To proper listener registration, you need to use on.* not `on("dde:*", …)`!
  • Use sparingly! Internally, library must loop of all registered events and fires event properly. It is good practice to use the fact that if an element is removed, its children are also removed! In this spirit, we will introduce later the host syntax to register clean up procedures when the component is removed from the app.

§ Final notes

The library also provides a method to dispatch the events.

import { el, on, dispatchEvent } from "https://cdn.jsdelivr.net/gh/jaandrle/deka-dom-el/dist/esm-with-signals.js"; +document.body.append( + el("p", "Listenning to `test` event.", on("test", console.log)).append( + el("br"), + el("button", "native", on("click", native)), + " ", + el("button", "dde", on("click", dde)), + " ", + el("button", "dde with options", on("click", ddeOptions)) + ) +); +function native(){ this.dispatchEvent(new CustomEvent("test", { bubbles: true, detail: "hi" })); } +function dde(){ dispatchEvent(this.parentElement, "test", "hi"); } +function ddeOptions(){ dispatchEvent(this, { name: "test", bubbles: true }, "hi"); } +
\ No newline at end of file diff --git a/docs/index.html b/docs/index.html index bbb3d0a..e9927c3 100644 --- a/docs/index.html +++ b/docs/index.html @@ -1,4 +1,4 @@ -`deka-dom-el` — Introduction

`deka-dom-el` — Introduction

Introducing a library.

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

We start with creating and modifying a static elements and end up with UI templates. From document.createElement to el. Then we go through the native events system and the way to include it declaratively in UI templates. From element.addEventListener to on.

Next step is providing interactivity not only for our UI templates. We introduce signals (S) and how them incorporate to UI templates.

Now we will clarify how the signals are incorporated into our templates with regard to application performance. This is not the only reason the library uses scopes. We will look at how they work in components represented in JavaScript by functions.

import { el } 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.

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

We start with creating and modifying a static elements and end up with UI templates. From document.createElement to el. Then we go through the native events system and the way to include it declaratively in UI templates. From element.addEventListener to on.

Next step is providing interactivity not only for our UI templates. We introduce signals (S) and how them incorporate to UI templates.

Now we will clarify how the signals are incorporated into our templates with regard to application performance. This is not the only reason the library uses scopes. We will look at how they work in components represented in JavaScript by functions.

import { el } from "https://cdn.jsdelivr.net/gh/jaandrle/deka-dom-el/dist/esm-with-signals.js"; import { S } from "https://cdn.jsdelivr.net/gh/jaandrle/deka-dom-el/dist/esm-with-signals.js"; const clicks= S(0); document.body.append( @@ -13,4 +13,4 @@ document.body.append( }) ) ); -
\ No newline at end of file +
\ No newline at end of file diff --git a/docs_src/components/examples/events/compareDispatch.js b/docs_src/components/examples/events/compareDispatch.js new file mode 100644 index 0000000..107cf5b --- /dev/null +++ b/docs_src/components/examples/events/compareDispatch.js @@ -0,0 +1,14 @@ +import { el, on, dispatchEvent } from "deka-dom-el"; +document.body.append( + el("p", "Listenning to `test` event.", on("test", console.log)).append( + el("br"), + el("button", "native", on("click", native)), + " ", + el("button", "dde", on("click", dde)), + " ", + el("button", "dde with options", on("click", ddeOptions)) + ) +); +function native(){ this.dispatchEvent(new CustomEvent("test", { bubbles: true, detail: "hi" })); } +function dde(){ dispatchEvent("test")(this.parentElement, "hi"); } +function ddeOptions(){ dispatchEvent("test", { bubbles: true })(this, "hi"); } diff --git a/docs_src/components/examples/events/live-cycle.js b/docs_src/components/examples/events/live-cycle.js new file mode 100644 index 0000000..166f856 --- /dev/null +++ b/docs_src/components/examples/events/live-cycle.js @@ -0,0 +1,18 @@ +import { el, on } from "deka-dom-el"; +const paragraph= el("p", "See live-cycle events in console.", + el=> log({ type: "dde:created", detail: el }), + on.connected(log), + on.disconnected(log), + on.attributeChanged(log)); + +document.body.append( + paragraph, + el("button", "Update attribute", on("click", ()=> paragraph.setAttribute("test", Math.random().toString()))), + " ", + el("button", "Remove", on("click", ()=> paragraph.remove())) +); + +/** @param {Partial} event */ +function log({ type, detail }){ + console.log({ _this: this, type, detail }); +} diff --git a/docs_src/components/prevNext.html.js b/docs_src/components/pageUtils.html.js similarity index 73% rename from docs_src/components/prevNext.html.js rename to docs_src/components/pageUtils.html.js index a61472f..3223914 100644 --- a/docs_src/components/prevNext.html.js +++ b/docs_src/components/pageUtils.html.js @@ -15,6 +15,18 @@ styles.scope(prevNext).css` } `; import { el } from "../../index.js"; +/** + * @param {Object} attrs + * @param {string} attrs.textContent + * @param {string} [attrs.id] + * */ +export function h3({ textContent, id }){ + if(!id) id= "h-"+textContent.toLowerCase().replaceAll(/\s/g, "-").replaceAll(/[^a-z-]/g, ""); + return el("h3", { id }).append( + el("a", { textContent: "§", href: "#"+id, tabIndex: -1 }), + " ", textContent + ); +} /** * @param {import("../types.d.ts").Info} page * */ diff --git a/docs_src/elements.html.js b/docs_src/elements.html.js index 5258a70..5d46f8c 100644 --- a/docs_src/elements.html.js +++ b/docs_src/elements.html.js @@ -3,7 +3,7 @@ import { el } from "deka-dom-el"; import { header } from "./layout/head.html.js"; import { example } from "./components/example.html.js"; -import { prevNext } from "./components/prevNext.html.js"; +import { h3, prevNext } from "./components/pageUtils.html.js"; /** @param {string} url */ const fileURL= url=> new URL(url, import.meta.url); @@ -17,7 +17,7 @@ export function page({ pkg, info }){ el("h2", "Native JavaScript DOM elements creations"), el("p", "Let’s go through all patterns we would like to use and what needs to be improved for better experience."), - el("h3", "Creating element(s) (with custom attributes)"), + el(h3, "Creating element(s) (with custom attributes)"), el("p").append( "You can create a native DOM element by using the ", el("a", { href: "https://developer.mozilla.org/en-US/docs/Web/API/Document/createElement", title: "MDN documentation for document.createElement()" }).append( @@ -83,7 +83,7 @@ export function page({ pkg, info }){ ), el(example, { src: fileURL("./components/examples/elements/dekaAssign.js"), page_id }), - el("h3", "Native JavaScript templating"), + el(h3, "Native JavaScript templating"), el("p", "By default, the native JS has no good way to define HTML template using DOM API:"), el(example, { src: fileURL("./components/examples/elements/nativeAppend.js"), page_id }), el("p").append( @@ -92,7 +92,7 @@ export function page({ pkg, info }){ el(example, { src: fileURL("./components/examples/elements/dekaAppend.js"), page_id }), - el("h3", "Basic (state-less) components"), + el(h3, "Basic (state-less) components"), el("p").append( "You can use functions for encapsulation (repeating) logic. ", "The ", el("code", "el"), " accepts function as first argument. ", @@ -109,7 +109,7 @@ export function page({ pkg, info }){ " and keep track of the native API (things are best remembered through regular use).", ), - el("h3", "Creating non-HTML elements"), + el(h3, "Creating non-HTML elements"), el("p").append( "Similarly to the native DOM API (", el("a", { href: "https://developer.mozilla.org/en-US/docs/Web/API/Document/createElementNS", title: "MDN" }).append(el("code", "document.createElementNS")), ") for non-HTML elements", " we need to tell JavaScript which kind of the element to create.", diff --git a/docs_src/events.html.js b/docs_src/events.html.js index 53ca9db..a3845ce 100644 --- a/docs_src/events.html.js +++ b/docs_src/events.html.js @@ -3,7 +3,7 @@ import { el } from "deka-dom-el"; import { header } from "./layout/head.html.js"; import { example } from "./components/example.html.js"; -import { prevNext } from "./components/prevNext.html.js"; +import { h3, prevNext } from "./components/pageUtils.html.js"; /** @param {string} url */ const fileURL= url=> new URL(url, import.meta.url); @@ -22,7 +22,7 @@ export function page({ pkg, info }){ " incorporate not only this in UI templates declaratively." ), - el("h3", "Events and listenners"), + el(h3, "Events and listenners"), el("p").append( "In JavaScript you can listen to the native DOM events of the given element by using ", el("a", { href: "https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener", title: "addEventListener on MDN" }).append( @@ -34,18 +34,33 @@ export function page({ pkg, info }){ ), el(example, { src: fileURL("./components/examples/events/compare.js"), page_id }), el("p").append( - "…this is actually one of the two differences. The another one is that", el("code", "on"), + "…this is actually one of the two differences. The another one is that ", el("code", "on"), " accepts only object as the ", el("code", "options"), " (but it is still optional)." ), - el("p").append( + el("p", { className: "notice" }).append( "The other difference is that there is ", el("strong", "no"), " ", el("code", "off"), " function.", " ", "You can remove listener declaratively using ", el("a", { textContent: "AbortSignal", href: "https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#signal", title: "part of addEventListener on MDN" }), ":" ), el(example, { src: fileURL("./components/examples/events/abortSignal.js"), page_id }), + el("div", { className: "notice" }).append( + el("p", "So, there are (typically) three ways to handle events. You can use:"), + el("ul").append( + el("li").append( el("code", `el("button", { textContent: "click me", "=onclick": "console.log(event)" })`)), + el("li").append( el("code", `el("button", { textContent: "click me", onclick: console.log })`)), + el("li").append( el("code", `el("button", { textContent: "click me" }, on("click", console.log))`)) + ), + el("p").append( + "In the first example we force to use HTML attribute (it corresponds to ", el("code", ``), ").", + " ", + el("em", "Side note: this can be useful in case of SSR."), + " ", + "To study difference, you can read a nice summary here: ", el("a", { href: "https://gist.github.com/WebReflection/b404c36f46371e3b1173bf5492acc944", textContent: "GIST @WebReflection/web_events.md" }), "." + ) + ), - el("h3", "Addons"), + el(h3, "Addons"), el("p").append( "From practical point of view, ", el("em", "Addons"), " are just functions that accept any html element", " as their first parameter. You can see that the ", el("code", "on(…)"), " fullfills this requirement." @@ -60,11 +75,44 @@ export function page({ pkg, info }){ " ", "Also notice, you can use Addons to get element reference.", ), - el("h3", "Life cycle events"), - el("p", "Addons are called immediately when the element is created, event it is not connected to live DOM yet."), - // todo + el(h3, "Life-cycle events"), + el("p").append( + "Addons are called immediately when the element is created, even it is not connected to live DOM yet.", + " ", + "Therefore, you can understand the Addon to be “oncreate” event." + ), + el("p").append( + "The library provide three additional live-cycle events corresponding to how they are named in", + " a case of custom elements: ", el("code", "on.connected"), ", ", el("code", "on.disconnected"), + " and ", el("code", "on.attributeChanged"), "." + ), + el(example, { src: fileURL("./components/examples/events/live-cycle.js"), page_id }), + el("p").append( + "For Custom elements, we will later introduce a way to replace ", el("code", "*Callback"), + " syntax with ", el("code", "dde:*"), " events. The ", el("code", "on.*"), " functions then", + " listen to the appropriate Custom Elements events (see ", el("a", { textContent: "Custom element lifecycle callbacks | MDN", href: "https://developer.mozilla.org/en-US/docs/Web/API/Web_components/Using_custom_elements#custom_element_lifecycle_callbacks" }), ")." + ), + el("p").append( + "But, in case of regular elemnets the ", el("a", { href: "https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver" }).append(el("code", "MutationObserver"), " | MDN"), + " is internaly used to track these events. Therefore, there are some drawbacks:", + ), + el("ul").append( + el("li").append( + "To proper listener registration, you need to use ", el("code", "on.*"), " not `on(\"dde:*\", …)`!" + ), + el("li").append( + "Use sparingly! Internally, library must loop of all registered events and fires event properly.", + " ", + el("strong", "It is good practice to use the fact that if an element is removed, its children are also removed!"), + " ", + "In this spirit, we will introduce later the ", el("strong", "host"), " syntax to register", + " clean up procedures when the component is removed from the app." + ), + ), - // dispatchEvent + el(h3, "Final notes"), + el("p", "The library also provides a method to dispatch the events."), + el(example, { src: fileURL("./components/examples/events/compareDispatch.js"), page_id }), el(prevNext, info) ) diff --git a/docs_src/index.html.js b/docs_src/index.html.js index 1ae31e2..f43b82e 100644 --- a/docs_src/index.html.js +++ b/docs_src/index.html.js @@ -3,7 +3,7 @@ import { el } from "deka-dom-el"; import { header } from "./layout/head.html.js"; import { example } from "./components/example.html.js"; -import { prevNext } from "./components/prevNext.html.js"; +import { prevNext } from "./components/pageUtils.html.js"; /** @param {import("./types.d.ts").PageAttrs} attrs */ export function page({ pkg, info }){ diff --git a/examples/components/todosComponent.js b/examples/components/todosComponent.js index df43f7e..e6d9c13 100644 --- a/examples/components/todosComponent.js +++ b/examples/components/todosComponent.js @@ -67,7 +67,7 @@ function todoComponent({ textContent, value }){ const value= Number(event.target.value); event.preventDefault(); event.stopPropagation(); - dispatchEvent(host(), "remove", value); + dispatchEvent("remove")(host(), value); }); const is_editable= S(false); const onedited= on("change", ev=> { diff --git a/index.d.ts b/index.d.ts index 038750a..69595d2 100644 --- a/index.d.ts +++ b/index.d.ts @@ -10,7 +10,7 @@ type SupportedElement= | CustomElementTagNameMap[keyof CustomElementTagNameMap] | ddePublicElementTagNameMap[keyof ddePublicElementTagNameMap]; declare global { - type ddeComponentAttributes= Record | undefined | string; + type ddeComponentAttributes= Record | undefined; type ddeElementAddon= (element: El)=> El | void; } type PascalCase= `${Capitalize}${string}`; @@ -49,7 +49,7 @@ type ExtendedHTMLElementTagNameMap= HTMLElementTagNameMap & CustomElementTagName export function el( tag_name: TAG, attrs?: string | Partial>, - ...modifiers: ddeElementAddon[] + ...addons: ddeElementAddon[] ): ExtendedHTMLElementTagNameMap[TAG] export function el( tag_name?: "<>", @@ -57,16 +57,16 @@ export function el( export function el< A extends ddeComponentAttributes, - C extends (attr: A)=> SupportedElement | DocumentFragment>( + C extends (attr: Partial)=> SupportedElement | DocumentFragment>( fComponent: C, - attrs?: A, - ...modifiers: ddeElementAddon>[] + attrs?: A | string, + ...addons: ddeElementAddon>[] ): ReturnType export function el( tag_name: string, attrs?: string | Record, - ...modifiers: ddeElementAddon[] + ...addons: ddeElementAddon[] ): HTMLElement export function elNS( @@ -74,27 +74,27 @@ export function elNS( ): ( tag_name: TAG, attrs?: string | Partial<{ [key in KEYS]: SVGElementTagNameMap[TAG][key] | string | number | boolean }>, - ...modifiers: ddeElementAddon[] + ...addons: ddeElementAddon[] )=> SVGElementTagNameMap[TAG] 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: ddeElementAddon[] + ...addons: ddeElementAddon[] )=> MathMLElementTagNameMap[TAG] export function elNS( namespace: string ): ( tag_name: string, attrs?: string | Record, - ...modifiers: ddeElementAddon[] + ...addons: ddeElementAddon[] )=> SupportedElement export function chainableAppend(el: EL): EL; -export function dispatchEvent(element: SupportedElement, name: keyof DocumentEventMap): void; -export function dispatchEvent(element: SupportedElement, name: string, data: any): void; +export function dispatchEvent(name: keyof DocumentEventMap | string, options?: EventInit): + (element: SupportedElement, data?: any)=> void; interface On{ /** Listens to the DOM event. See {@link Document.addEventListener} */ < @@ -105,12 +105,19 @@ interface On{ listener: (this: El, ev: DocumentEventMap[Event]) => any, options?: AddEventListenerOptions ) : EE; + < + EE extends ddeElementAddon, + El extends ( EE extends ddeElementAddon ? El : never )>( + type: string, + listener: (this: El, ev: Event | CustomEvent ) => any, + options?: AddEventListenerOptions + ) : EE; /** Listens to the element is connected to the live DOM. In case of custom elements uses [`connectedCallback`](https://developer.mozilla.org/en-US/docs/Web/API/Web_components/Using_custom_elements#custom_element_lifecycle_callbacks), or {@link MutationObserver} else where */ connected< EE extends ddeElementAddon, El extends ( EE extends ddeElementAddon ? El : never ) >( - listener: (el: El) => any, + listener: (this: El, event: CustomEvent) => any, options?: AddEventListenerOptions ) : EE; /** Listens to the element is disconnected from the live DOM. In case of custom elements uses [`disconnectedCallback`](https://developer.mozilla.org/en-US/docs/Web/API/Web_components/Using_custom_elements#custom_element_lifecycle_callbacks), or {@link MutationObserver} else where */ @@ -118,7 +125,7 @@ interface On{ EE extends ddeElementAddon, El extends ( EE extends ddeElementAddon ? El : never ) >( - listener: (el: El) => any, + listener: (this: El, event: CustomEvent) => any, options?: AddEventListenerOptions ) : EE; /** Listens to the element attribute changes. In case of custom elements uses [`attributeChangedCallback`](https://developer.mozilla.org/en-US/docs/Web/API/Web_components/Using_custom_elements#custom_element_lifecycle_callbacks), or {@link MutationObserver} else where */ @@ -126,7 +133,7 @@ interface On{ EE extends ddeElementAddon, El extends ( EE extends ddeElementAddon ? El : never ) >( - listener: (el: El) => any, + listener: (this: El, event: CustomEvent<[ string, string ]>) => any, options?: AddEventListenerOptions ) : EE; } diff --git a/package.json b/package.json index d40ce58..42c4608 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "deka-dom-el", - "version": "0.7.0", + "version": "0.7.1", "description": "A low-code library that simplifies the creation of native DOM elements/components using small wrappers and tweaks.", "author": "Jan Andrle ", "license": "MIT", diff --git a/src/events.js b/src/events.js index 996cfbe..7ff1e7d 100644 --- a/src/events.js +++ b/src/events.js @@ -1,8 +1,10 @@ export { registerReactivity } from './signals-common.js'; -export function dispatchEvent(element, name, ...d){ - const event= d.length ? new CustomEvent(name, { detail: d[0] }) : new Event(name); - return element.dispatchEvent(event); +export function dispatchEvent(name, options= {}){ + return function dispatch(element, ...d){ + const event= d.length ? new CustomEvent(name, Object.assign({ detail: d[0] }, options)) : new Event(name, options); + return element.dispatchEvent(event); + }; } export function on(event, listener, options){ return function registerElement(element){