mosaic 1.0.5 → 1.0.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/cjs/define.js CHANGED
@@ -17,7 +17,7 @@ const define = (name, factory, template) =>
17
17
 
18
18
  if (config instanceof Promise) config = await config;
19
19
 
20
- let { subscribe, shadow, initialState = {} } = config;
20
+ let { subscribe, shadow, initialState = {}, observe = [] } = config;
21
21
 
22
22
  this.connectedCallback = config.connectedCallback;
23
23
  this.disconnectedCallback = config.disconnectedCallback;
@@ -29,13 +29,9 @@ const define = (name, factory, template) =>
29
29
 
30
30
  initialState = getState();
31
31
 
32
- let observedProps = Object.keys(initialState).filter(
33
- (v) => v.charAt(0) === "$"
34
- );
32
+ observe = observe.map(helpers.kebabToPascal);
35
33
 
36
- let observedAttributes = observedProps
37
- .map((v) => v.slice(1))
38
- .map(helpers.pascalToKebab);
34
+ let observedAttributes = observe.map(helpers.pascalToKebab);
39
35
 
40
36
  let sa = this.setAttribute;
41
37
  this.setAttribute = (k, v) => {
@@ -43,7 +39,7 @@ const define = (name, factory, template) =>
43
39
  let { name, value } = helpers.attributeToProp(k, v);
44
40
  dispatch({
45
41
  type: "SET",
46
- payload: { name: "$" + name, value },
42
+ payload: { name, value },
47
43
  });
48
44
  }
49
45
  sa.apply(this, [k, v]);
@@ -51,23 +47,22 @@ const define = (name, factory, template) =>
51
47
 
52
48
  observedAttributes.forEach((name) => {
53
49
  let property = helpers.attributeToProp(name).name;
54
-
55
50
  let value;
56
51
 
57
52
  if (this.hasAttribute(name)) {
58
53
  value = this.getAttribute(name);
59
54
  } else {
60
- value = this[property] || initialState["$" + property];
55
+ value = this[property] || initialState[property];
61
56
  }
62
57
 
63
58
  Object.defineProperty(this, property, {
64
59
  get() {
65
- return getState()["$" + property]
60
+ return getState()[property]
66
61
  },
67
62
  set(v) {
68
63
  dispatch({
69
64
  type: "SET",
70
- payload: { name: "$" + property, value: v },
65
+ payload: { name: property, value: v },
71
66
  });
72
67
  if (helpers.isPrimitive(v)) {
73
68
  helpers.applyAttribute(this, property, v);
@@ -94,9 +89,9 @@ const define = (name, factory, template) =>
94
89
  { getState, dispatch },
95
90
  template,
96
91
  () => {
97
- observedProps.forEach((k) => {
92
+ observe.forEach((k) => {
98
93
  let v = getState()[k];
99
- if (helpers.isPrimitive(v)) helpers.applyAttribute(this, k.slice(1), v);
94
+ if (helpers.isPrimitive(v)) helpers.applyAttribute(this, k, v);
100
95
  });
101
96
  subscribe?.(getState());
102
97
  flush();
package/cjs/render.js CHANGED
@@ -96,33 +96,14 @@ const render = (
96
96
  { node, eventType, actionType, context },
97
97
  { dispatch, getState }
98
98
  ) => {
99
- /*
100
-
101
- NB that context is only passed for local actions not prefixed with "$"
102
-
103
- */
104
-
105
99
  node.addEventListener(eventType, (event) => {
106
- let isGlobal = actionType.startsWith("$");
107
-
108
100
  let action = {
109
101
  type: actionType,
110
102
  event,
103
+ context: context ? context.wrap(getState()) : getState(),
111
104
  };
112
105
 
113
- if (!isGlobal)
114
- action.context = context ? context.wrap(getState()) : getState();
115
-
116
106
  dispatch(action);
117
-
118
- if (isGlobal) {
119
- node.dispatchEvent(
120
- new CustomEvent(actionType, {
121
- detail: action,
122
- bubbles: true,
123
- })
124
- );
125
- }
126
107
  });
127
108
  return {
128
109
  handler: () => {},
package/cjs/update.js CHANGED
@@ -69,6 +69,16 @@ function configure(
69
69
 
70
70
  function dispatch(action) {
71
71
  const { type } = action;
72
+
73
+ if (type.startsWith("$") && !(type in update)) {
74
+ node.dispatchEvent(
75
+ new CustomEvent(type, {
76
+ detail: action,
77
+ bubbles: true,
78
+ })
79
+ );
80
+ }
81
+
72
82
  if (type === "SET" || type === "MERGE") {
73
83
  updateState(systemReducer(getState(), action));
74
84
  } else {
package/dist/mosaic.js CHANGED
@@ -65,6 +65,16 @@ function configure(
65
65
 
66
66
  function dispatch(action) {
67
67
  const { type } = action;
68
+
69
+ if (type.startsWith("$") && !(type in update)) {
70
+ node.dispatchEvent(
71
+ new CustomEvent(type, {
72
+ detail: action,
73
+ bubbles: true,
74
+ })
75
+ );
76
+ }
77
+
68
78
  if (type === "SET" || type === "MERGE") {
69
79
  updateState(systemReducer(getState(), action));
70
80
  } else {
@@ -669,33 +679,14 @@ const render = (
669
679
  { node, eventType, actionType, context },
670
680
  { dispatch, getState }
671
681
  ) => {
672
- /*
673
-
674
- NB that context is only passed for local actions not prefixed with "$"
675
-
676
- */
677
-
678
682
  node.addEventListener(eventType, (event) => {
679
- let isGlobal = actionType.startsWith("$");
680
-
681
683
  let action = {
682
684
  type: actionType,
683
685
  event,
686
+ context: context ? context.wrap(getState()) : getState(),
684
687
  };
685
688
 
686
- if (!isGlobal)
687
- action.context = context ? context.wrap(getState()) : getState();
688
-
689
689
  dispatch(action);
690
-
691
- if (isGlobal) {
692
- node.dispatchEvent(
693
- new CustomEvent(actionType, {
694
- detail: action,
695
- bubbles: true,
696
- })
697
- );
698
- }
699
690
  });
700
691
  return {
701
692
  handler: () => {},
@@ -1000,7 +991,7 @@ const define = (name, factory, template) =>
1000
991
 
1001
992
  if (config instanceof Promise) config = await config;
1002
993
 
1003
- let { subscribe, shadow, initialState = {} } = config;
994
+ let { subscribe, shadow, initialState = {}, observe = [] } = config;
1004
995
 
1005
996
  this.connectedCallback = config.connectedCallback;
1006
997
  this.disconnectedCallback = config.disconnectedCallback;
@@ -1012,13 +1003,9 @@ const define = (name, factory, template) =>
1012
1003
 
1013
1004
  initialState = getState();
1014
1005
 
1015
- let observedProps = Object.keys(initialState).filter(
1016
- (v) => v.charAt(0) === "$"
1017
- );
1006
+ observe = observe.map(kebabToPascal);
1018
1007
 
1019
- let observedAttributes = observedProps
1020
- .map((v) => v.slice(1))
1021
- .map(pascalToKebab);
1008
+ let observedAttributes = observe.map(pascalToKebab);
1022
1009
 
1023
1010
  let sa = this.setAttribute;
1024
1011
  this.setAttribute = (k, v) => {
@@ -1026,7 +1013,7 @@ const define = (name, factory, template) =>
1026
1013
  let { name, value } = attributeToProp(k, v);
1027
1014
  dispatch({
1028
1015
  type: "SET",
1029
- payload: { name: "$" + name, value },
1016
+ payload: { name, value },
1030
1017
  });
1031
1018
  }
1032
1019
  sa.apply(this, [k, v]);
@@ -1034,23 +1021,22 @@ const define = (name, factory, template) =>
1034
1021
 
1035
1022
  observedAttributes.forEach((name) => {
1036
1023
  let property = attributeToProp(name).name;
1037
-
1038
1024
  let value;
1039
1025
 
1040
1026
  if (this.hasAttribute(name)) {
1041
1027
  value = this.getAttribute(name);
1042
1028
  } else {
1043
- value = this[property] || initialState["$" + property];
1029
+ value = this[property] || initialState[property];
1044
1030
  }
1045
1031
 
1046
1032
  Object.defineProperty(this, property, {
1047
1033
  get() {
1048
- return getState()["$" + property]
1034
+ return getState()[property]
1049
1035
  },
1050
1036
  set(v) {
1051
1037
  dispatch({
1052
1038
  type: "SET",
1053
- payload: { name: "$" + property, value: v },
1039
+ payload: { name: property, value: v },
1054
1040
  });
1055
1041
  if (isPrimitive(v)) {
1056
1042
  applyAttribute(this, property, v);
@@ -1077,9 +1063,9 @@ const define = (name, factory, template) =>
1077
1063
  { getState, dispatch },
1078
1064
  template,
1079
1065
  () => {
1080
- observedProps.forEach((k) => {
1066
+ observe.forEach((k) => {
1081
1067
  let v = getState()[k];
1082
- if (isPrimitive(v)) applyAttribute(this, k.slice(1), v);
1068
+ if (isPrimitive(v)) applyAttribute(this, k, v);
1083
1069
  });
1084
1070
  subscribe?.(getState());
1085
1071
  flush();
@@ -1 +1 @@
1
- const e=(e=[])=>e[e.length-1],t=e=>e.nodeType===e.TEXT_NODE&&""===e.nodeValue.trim(),n=(e,r,i=!0)=>{if(e){if(!t(e)){let t=r(e);if(!1===t)return;if(t?.nodeName)return n(t,r,i)}i&&n(e.firstChild,r,i),n(e.nextSibling,r,i)}},r=(t,n)=>{let[i,a]=((t,n)=>{let i=((e="")=>e.split(/(\[[^\]]+\])/).filter((e=>e)).reduce(((e,t)=>e+("["===t.charAt(0)?"."+t.replace(/\./g,":"):t)),""))(t).split(".").map((e=>{if("["===e.charAt(0)){let t=e.slice(1,-1).replace(/:/g,".");return r(t,n)}return e}));return[i.slice(0,-1).reduce(((e,t)=>e&&e[t]),n)||n,e(i)]})(t,n),l=i?.[a];return"function"==typeof l?l.bind(i):l},i=e=>{if("string"==typeof e){let t=document.createElement("template");return t.innerHTML=e.trim(),t.content}return"TEMPLATE"===e.nodeName?e.cloneNode(!0).content:"defs"===e.nodeName?e.firstElementChild.cloneNode(!0):void 0},a=e=>null===e||"object"!=typeof e,l=e=>e.replace(/[\w]([A-Z])/g,(function(e){return e[0]+"-"+e[1].toLowerCase()})),c=(e,t,n)=>{t=l(t),"boolean"==typeof n&&(t.startsWith("aria-")?n=""+n:n&&(n="")),"string"==typeof n||"number"==typeof n?e.setAttribute(t,n):e.removeAttribute(t)},s=(e,t)=>{let n=e.replace(/[\w]-([\w])/g,(function(e){return e[0]+e[2].toUpperCase()}));return""===t&&(t=!0),e.startsWith("aria-")&&("true"===t&&(t=!0),"false"===t&&(t=!1)),{name:n,value:t}};const o=e=>{let t=0;return n(e.content?.firstChild||e.firstChild,(()=>t++),!1),t},u=e=>t(e.nextSibling)?u(e.nextSibling):e.nextSibling;const d=(e,t,n,r)=>{let i=e.getAttribute("length")||0,a=((e,t)=>{let n=o(e),r=[];if(t)for(;t--;){let t=document.createDocumentFragment(),i=n;for(;i--;)t.appendChild(u(e));r.push(t)}return r})(e,i),l=e;t.forEach(((e,t)=>{let i=-1===e?r(n[t][1],n[t][0]):a[e],c=(s=i).nodeType===s.DOCUMENT_FRAGMENT_NODE&&s.lastChild||s;var s;l.after(i),l=c})),e.setAttribute("length",t.length)},p=e=>e.trim().split(/({{[^{}]+}})/).filter((e=>e)).map((e=>{let t=e.match(/{{([^{}]+)}}/);if(!t)return{type:1,value:e,negated:!1};let n="!"===(e=t[1].trim()).charAt(0);return n&&(e=e.slice(1)),{type:2,value:e,negated:n}})),h=(e,t)=>t.reduce(((t,n)=>{let i,{type:a,value:l,negated:c}=n;if(1===a&&(i=l),2===a&&(i=r(l,e)),3===a){let t=n.args.map((t=>r(t,e)));i=r(n.method,e)?.(...t)}return c&&(i=!i),t||0===t?t+i:i}),""),f=e=>e.replace(/[\w]([A-Z])/g,(function(e){return e[0]+"-"+e[1].toLowerCase()})),m=e=>{let t=typeof e;return"string"===t?e.split(";").reduce(((e,t)=>{const[n,r]=t.split(":").map((e=>e.trim()));return n&&(e[n]=r),e}),{}):"object"===t?e:{}},b=(e,t,n)=>{if("style"===t)n=(e=>Object.entries(e).map((([e,t])=>`${e}: ${t};`)).join(" "))((l={...m(e.getAttribute("style")),...m(n)},Object.keys(l).reduce(((e,t)=>(e[f(t)]=l[t],e)),{})));else if("class"===t)switch(i=n,Object.prototype.toString.call(i).match(/\s(.+[^\]])/)[1]){case"Array":n=n.join(" ");break;case"Object":n=Object.keys(n).reduce(((e,t)=>(n[t]&&e.push(t),e)),[]).join(" ")}else if(!a(n))return e[(r=t,r.replace(/[\w]-([\w])/g,(function(e){return e[0]+e[2].toUpperCase()})))]=n;var r,i,l;t=f(t),"boolean"==typeof n&&(t.startsWith("aria-")?n=""+n:n&&(n=""));let c=e.getAttribute(t);n!==c&&("string"==typeof n||"number"==typeof n?e.setAttribute(t,n):e.removeAttribute(t))},y=(e=[])=>{let t=e;return{get:()=>t,push:e=>t.push(e),wrap:e=>t.reduce(((e,t)=>new Proxy(e,(({path:e,identifier:t,key:n,index:i,i:l,k:c})=>({get(a,s){let o=r(e,a);if(s===t)for(let e in o){let t=o[e];if(n){if(t[n]===c)return t}else if(e==l)return t}if(s===i)for(let e in o){let t=o[e];if(n){if(t[n]===c)return e}else if(e==l)return e}let u=n?o.find((e=>e[n]===c)):o[l];return u?.hasOwnProperty?.(s)?u[s]:Reflect.get(...arguments)},set(t,i,s){let o=r(e,t),u=n?o.find((e=>e[n]===c)):o[l];return u&&!a(u)?(u[i]=s,!0):Reflect.set(...arguments)}}))(t))),e)}},g=(t,{getState:a,dispatch:l},c,s,f)=>{const m={1:({value:e,node:t,context:n},{getState:r})=>({handler:()=>{let i=n?n.wrap(r()):r(),a=t.textContent,l=h(i,p(e));a!==l&&(t.textContent=l)}}),2:({value:e,node:t,name:n,context:i},{getState:a})=>({handler:()=>{let l=i?i.wrap(a()):a(),c=h(l,p(e));if(b(t,n,c),"OPTION"===t.nodeName){let e=t.parentNode.getAttribute("name"),n=r(e,l);t.selected=n===c}}}),3:({node:e,path:t,context:n},{getState:i,dispatch:a})=>(e.addEventListener("input",(()=>{let r="checkbox"===e.getAttribute("type")?e.checked:e.value;if(r.trim?.().length&&!isNaN(r)&&(r=+r),n){let e=n.wrap(i());e[t]=r,a({type:"MERGE",payload:e})}else a({type:"SET",payload:{name:t,value:r,context:n}})})),{handler:()=>{let a=n?n.wrap(i()):i();((e,t)=>{if("SELECT"===e.nodeName)return void Array.from(e.querySelectorAll("option")).forEach((e=>{e.selected=t.includes(e.value)}));let n;switch(e.getAttribute("type")){case"checkbox":if(n=t,e.checked===n)break;n?e.setAttribute("checked",""):e.removeAttribute("checked");break;case"radio":if(n=t===e.getAttribute("value"),e.checked===n)break;e.checked=n,n?e.setAttribute("checked",""):e.removeAttribute("checked");break;default:if(e.value===t)break;e.setAttribute("value",e.value=t||"")}})(e,r(t,a))}}),4:({node:e,eventType:t,actionType:n,context:r},{dispatch:i,getState:a})=>(e.addEventListener(t,(t=>{let l=n.startsWith("$"),c={type:n,event:t};l||(c.context=r?r.wrap(a()):a()),i(c),l&&e.dispatchEvent(new CustomEvent(n,{detail:c,bubbles:!0}))})),{handler:()=>{}}),5:({node:t,context:a,map:l,path:c,identifier:s,index:p,key:h,blockIndex:f,hydrate:m,pickupNode:b},{getState:g})=>{let E;t.$t=f-1;const A=(e,t,r,i)=>{n(e,k((e=>{if(e===i)return!1}),T(l,m,y((a?.get()||[]).concat({path:c,identifier:s,key:h,index:p,i:t,k:r}))),(e=>e.$t=f)))};const v=(e,n)=>{let r=e[h],a=i(t);var l;return A((l=a).nodeType===l.DOCUMENT_FRAGMENT_NODE&&l.firstChild||l,n,r),a};if(m){let n=r(c,g()),i=(e=>{let t=e.getAttribute("length"),n=o(e),r=[],i=e;if(t)for(;t--;){let e=[],t=n;for(;t--;)i=u(i),e.push(i);r.push(e)}return r})(t);i.forEach(((t,r)=>{let i=n[r]?.[h];A(t[0],r,i,e(t).nextSibling)})),b=e(e(i)).nextSibling}return{handler:()=>{let e=a?a.wrap(g()):g();const n=Object.entries(r(c,e)||[]),i=((e,t=[],n=[])=>{let r=n.map((([n,r])=>e?t.findIndex((([t,n])=>n[e]===r[e])):n in t?n:-1));if(t.length!==n.length||!r.every(((e,t)=>e===t)))return r})(h,E,n);i&&d(t,i,n,v),E=n.slice(0)},pickupNode:b}}},{bind:g,update:E}=(()=>{const e=(()=>{let e=new Set;return{publish:t=>{for(let t of e)t();t?.()},subscribe(t){e.add(t)}}})();return{bind(t){let n=m[t.type](t,{getState:a,dispatch:l});return e.subscribe(n.handler),n},update:t=>e.publish(t)}})();let A=0;const v=e=>{let t=0,r={};return n(e,(e=>{let n,i=[];switch(e.nodeType){case e.TEXT_NODE:{let t=e.textContent;t.match(/({{[^{}]+}})/)&&i.push({type:1,value:t});break}case e.ELEMENT_NODE:{let t=function(e){let t=e.getAttribute("each"),n=t?.match(/(.+)\s+in\s+(.+)/);if(!n)return t?{path:t.trim(),key:e.getAttribute("key")}:n;let[r,i,a]=n,l=i.match(/\(([^\)]+)\)/),[c,s]=(l?l[1].split(","):[i]).map((e=>e.trim()));return{path:a.trim(),identifier:s||c,index:s?c:s,key:e.getAttribute("key")}}(e);if(t){let r,a=e.namespaceURI;if(a.endsWith("/svg")){e.removeAttribute("each");let t=document.createElementNS(a,"defs");t.innerHTML=e.outerHTML,e.parentNode.replaceChild(t,e),r=v((e=t).firstChild)}else{if("TEMPLATE"!==e.nodeName){e.removeAttribute("each");let t=document.createElement("template");t.innerHTML=e.outerHTML,e.parentNode.replaceChild(t,e),e=t}r=v(e.content.firstChild)}n=e.nextSibling,i.push({type:5,map:r,blockIndex:A++,...t,pickupNode:n});break}let r=e.attributes,a=r.length;for(;a--;){let{name:t,value:n}=r[a];if(":name"!==t||!n||"INPUT"!==e.nodeName&&"SELECT"!==e.nodeName&&"TEXTAREA"!==e.nodeName){if(t.startsWith(":on")){e.removeAttribute(t);let r=t.split(":on")[1];i.push({type:4,eventType:r,actionType:n})}else if(t.startsWith(":")){let r=t.slice(1),a=n||r;a.includes("{{")||(a=`{{${a}}}`),i.push({type:2,name:r,value:a}),e.removeAttribute(t)}}else i.push({type:3,path:n}),e.removeAttribute(t),e.setAttribute("name",n)}}}return i.length&&(r[t]=i),t++,n})),r},k=(...e)=>(...t)=>{for(let n of e){if(!1===n(...t))return!1}},T=(e,t=0,n)=>{let r=0;return i=>{let a;return r in e&&(e[r].forEach((e=>{let r=g({...e,node:i,context:n,hydrate:t});a=r.pickupNode})),i.$i=r),r++,a}};let N=i(c),C=v(N);return n(N,T(C)),f?.(N),t.prepend(N),E(),(e=>{let t=!1,n=!1;return()=>{t?n=!0:(t=!0,e(),requestAnimationFrame((()=>{n&&e(),t=!1})))}})((()=>E(s)))},E=e=>{let t=document.createDocumentFragment();for(;e.firstChild;)t.appendChild(e.firstChild);return t},A=(e,t,n)=>customElements.define(e,class extends HTMLElement{async connectedCallback(){if(!this.initialised){let e=t(this);e instanceof Promise&&(e=await e);let{subscribe:r,shadow:i,initialState:o={}}=e;this.connectedCallback=e.connectedCallback,this.disconnectedCallback=e.disconnectedCallback;const{dispatch:u,getState:d,onUpdate:p,flush:h}=function({update:e={},middleware:t=[],derivations:n={},initialState:r={}},i){let a,l=[],c=()=>{};function s(e){a={...e};for(let t in n)a[t]=n[t](e)}function o(){return{...a}}function u(e){l.push(e)}function d(n){const{type:r}=n;if("SET"===r||"MERGE"===r)s(function(e,t){switch(t.type){case"SET":{const{name:n,value:r}=t.payload;return{...e,[n]:r}}case"MERGE":return{...e,...t.payload}}}(o(),n));else if(t.length){let i=t.slice(),a=t=>{if(i.length){let e=i.shift();t.type in e?e[t.type](t,a,{getState:o,dispatch:d,afterNextRender:u}):a(t)}else t.type in e&&s(e[t.type](o(),t))},l=i.shift();r in l?l[r](n,a,{getState:o,dispatch:d,afterNextRender:u}):a(n)}else r in e&&s(e[r](o(),n));c()}s(r);for(let t in e)t.startsWith("$")&&i.addEventListener(t,(({detail:e})=>d(e)));return{dispatch:d,getState:o,onUpdate:function(e){c=e},flush:function(){l.forEach((e=>e())),l=[]}}}(e,this);o=d();let f,m=Object.keys(o).filter((e=>"$"===e.charAt(0))),b=m.map((e=>e.slice(1))).map(l),y=this.setAttribute;this.setAttribute=(e,t)=>{if(b.includes(e)){let{name:n,value:r}=s(e,t);u({type:"SET",payload:{name:"$"+n,value:r}})}y.apply(this,[e,t])},b.forEach((e=>{let t,n=s(e).name;t=this.hasAttribute(e)?this.getAttribute(e):this[n]||o["$"+n],Object.defineProperty(this,n,{get:()=>d()["$"+n],set(e){u({type:"SET",payload:{name:"$"+n,value:e}}),a(e)&&c(this,n,e)}}),this[n]=t})),i?this.attachShadow({mode:i}):f=e=>((e,t)=>{t.querySelectorAll("slot[name]").forEach((t=>{let n=t.attributes.name.value,r=e.querySelector(`[slot="${n}"]`);r?(r.removeAttribute("slot"),t.parentNode.replaceChild(r,t)):t.parentNode.replaceChild(E(t),t)}));let n=t.querySelector("slot:not([name])");n&&n.parentNode.replaceChild(E(e.innerHTML.trim()?e:n),n)})(this,e),p(g(this.shadowRoot||this,{getState:d,dispatch:u},n,(()=>{m.forEach((e=>{let t=d()[e];a(t)&&c(this,e.slice(1),t)})),r?.(d()),h()}),f)),this.initialised=!0}this.connectedCallback?.()}disconnectedCallback(){this.disconnectedCallback?.()}});export{A as define};
1
+ const e=(e=[])=>e[e.length-1],t=e=>e.nodeType===e.TEXT_NODE&&""===e.nodeValue.trim(),n=(e,r,i=!0)=>{if(e){if(!t(e)){let t=r(e);if(!1===t)return;if(t?.nodeName)return n(t,r,i)}i&&n(e.firstChild,r,i),n(e.nextSibling,r,i)}},r=(t,n)=>{let[i,a]=((t,n)=>{let i=((e="")=>e.split(/(\[[^\]]+\])/).filter((e=>e)).reduce(((e,t)=>e+("["===t.charAt(0)?"."+t.replace(/\./g,":"):t)),""))(t).split(".").map((e=>{if("["===e.charAt(0)){let t=e.slice(1,-1).replace(/:/g,".");return r(t,n)}return e}));return[i.slice(0,-1).reduce(((e,t)=>e&&e[t]),n)||n,e(i)]})(t,n),l=i?.[a];return"function"==typeof l?l.bind(i):l},i=e=>{if("string"==typeof e){let t=document.createElement("template");return t.innerHTML=e.trim(),t.content}return"TEMPLATE"===e.nodeName?e.cloneNode(!0).content:"defs"===e.nodeName?e.firstElementChild.cloneNode(!0):void 0},a=e=>null===e||"object"!=typeof e,l=e=>e.replace(/[\w]([A-Z])/g,(function(e){return e[0]+"-"+e[1].toLowerCase()})),s=e=>e.replace(/[\w]-([\w])/g,(function(e){return e[0]+e[2].toUpperCase()})),c=(e,t,n)=>{t=l(t),"boolean"==typeof n&&(t.startsWith("aria-")?n=""+n:n&&(n="")),"string"==typeof n||"number"==typeof n?e.setAttribute(t,n):e.removeAttribute(t)},o=(e,t)=>{let n=s(e);return""===t&&(t=!0),e.startsWith("aria-")&&("true"===t&&(t=!0),"false"===t&&(t=!1)),{name:n,value:t}};const u=e=>{let t=0;return n(e.content?.firstChild||e.firstChild,(()=>t++),!1),t},d=e=>t(e.nextSibling)?d(e.nextSibling):e.nextSibling;const p=(e,t,n,r)=>{let i=e.getAttribute("length")||0,a=((e,t)=>{let n=u(e),r=[];if(t)for(;t--;){let t=document.createDocumentFragment(),i=n;for(;i--;)t.appendChild(d(e));r.push(t)}return r})(e,i),l=e;t.forEach(((e,t)=>{let i=-1===e?r(n[t][1],n[t][0]):a[e],s=(c=i).nodeType===c.DOCUMENT_FRAGMENT_NODE&&c.lastChild||c;var c;l.after(i),l=s})),e.setAttribute("length",t.length)},h=e=>e.trim().split(/({{[^{}]+}})/).filter((e=>e)).map((e=>{let t=e.match(/{{([^{}]+)}}/);if(!t)return{type:1,value:e,negated:!1};let n="!"===(e=t[1].trim()).charAt(0);return n&&(e=e.slice(1)),{type:2,value:e,negated:n}})),f=(e,t)=>t.reduce(((t,n)=>{let i,{type:a,value:l,negated:s}=n;if(1===a&&(i=l),2===a&&(i=r(l,e)),3===a){let t=n.args.map((t=>r(t,e)));i=r(n.method,e)?.(...t)}return s&&(i=!i),t||0===t?t+i:i}),""),m=e=>e.replace(/[\w]([A-Z])/g,(function(e){return e[0]+"-"+e[1].toLowerCase()})),b=e=>{let t=typeof e;return"string"===t?e.split(";").reduce(((e,t)=>{const[n,r]=t.split(":").map((e=>e.trim()));return n&&(e[n]=r),e}),{}):"object"===t?e:{}},y=(e,t,n)=>{if("style"===t)n=(e=>Object.entries(e).map((([e,t])=>`${e}: ${t};`)).join(" "))((l={...b(e.getAttribute("style")),...b(n)},Object.keys(l).reduce(((e,t)=>(e[m(t)]=l[t],e)),{})));else if("class"===t)switch(i=n,Object.prototype.toString.call(i).match(/\s(.+[^\]])/)[1]){case"Array":n=n.join(" ");break;case"Object":n=Object.keys(n).reduce(((e,t)=>(n[t]&&e.push(t),e)),[]).join(" ")}else if(!a(n))return e[(r=t,r.replace(/[\w]-([\w])/g,(function(e){return e[0]+e[2].toUpperCase()})))]=n;var r,i,l;t=m(t),"boolean"==typeof n&&(t.startsWith("aria-")?n=""+n:n&&(n=""));let s=e.getAttribute(t);n!==s&&("string"==typeof n||"number"==typeof n?e.setAttribute(t,n):e.removeAttribute(t))},g=(e=[])=>{let t=e;return{get:()=>t,push:e=>t.push(e),wrap:e=>t.reduce(((e,t)=>new Proxy(e,(({path:e,identifier:t,key:n,index:i,i:l,k:s})=>({get(a,c){let o=r(e,a);if(c===t)for(let e in o){let t=o[e];if(n){if(t[n]===s)return t}else if(e==l)return t}if(c===i)for(let e in o){let t=o[e];if(n){if(t[n]===s)return e}else if(e==l)return e}let u=n?o.find((e=>e[n]===s)):o[l];return u?.hasOwnProperty?.(c)?u[c]:Reflect.get(...arguments)},set(t,i,c){let o=r(e,t),u=n?o.find((e=>e[n]===s)):o[l];return u&&!a(u)?(u[i]=c,!0):Reflect.set(...arguments)}}))(t))),e)}},E=(t,{getState:a,dispatch:l},s,c,o)=>{const m={1:({value:e,node:t,context:n},{getState:r})=>({handler:()=>{let i=n?n.wrap(r()):r(),a=t.textContent,l=f(i,h(e));a!==l&&(t.textContent=l)}}),2:({value:e,node:t,name:n,context:i},{getState:a})=>({handler:()=>{let l=i?i.wrap(a()):a(),s=f(l,h(e));if(y(t,n,s),"OPTION"===t.nodeName){let e=t.parentNode.getAttribute("name"),n=r(e,l);t.selected=n===s}}}),3:({node:e,path:t,context:n},{getState:i,dispatch:a})=>(e.addEventListener("input",(()=>{let r="checkbox"===e.getAttribute("type")?e.checked:e.value;if(r.trim?.().length&&!isNaN(r)&&(r=+r),n){let e=n.wrap(i());e[t]=r,a({type:"MERGE",payload:e})}else a({type:"SET",payload:{name:t,value:r,context:n}})})),{handler:()=>{let a=n?n.wrap(i()):i();((e,t)=>{if("SELECT"===e.nodeName)return void Array.from(e.querySelectorAll("option")).forEach((e=>{e.selected=t.includes(e.value)}));let n;switch(e.getAttribute("type")){case"checkbox":if(n=t,e.checked===n)break;n?e.setAttribute("checked",""):e.removeAttribute("checked");break;case"radio":if(n=t===e.getAttribute("value"),e.checked===n)break;e.checked=n,n?e.setAttribute("checked",""):e.removeAttribute("checked");break;default:if(e.value===t)break;e.setAttribute("value",e.value=t||"")}})(e,r(t,a))}}),4:({node:e,eventType:t,actionType:n,context:r},{dispatch:i,getState:a})=>(e.addEventListener(t,(e=>{let t={type:n,event:e,context:r?r.wrap(a()):a()};i(t)})),{handler:()=>{}}),5:({node:t,context:a,map:l,path:s,identifier:c,index:o,key:h,blockIndex:f,hydrate:m,pickupNode:b},{getState:y})=>{let E;t.$t=f-1;const v=(e,t,r,i)=>{n(e,k((e=>{if(e===i)return!1}),T(l,m,g((a?.get()||[]).concat({path:s,identifier:c,key:h,index:o,i:t,k:r}))),(e=>e.$t=f)))};const A=(e,n)=>{let r=e[h],a=i(t);var l;return v((l=a).nodeType===l.DOCUMENT_FRAGMENT_NODE&&l.firstChild||l,n,r),a};if(m){let n=r(s,y()),i=(e=>{let t=e.getAttribute("length"),n=u(e),r=[],i=e;if(t)for(;t--;){let e=[],t=n;for(;t--;)i=d(i),e.push(i);r.push(e)}return r})(t);i.forEach(((t,r)=>{let i=n[r]?.[h];v(t[0],r,i,e(t).nextSibling)})),b=e(e(i)).nextSibling}return{handler:()=>{let e=a?a.wrap(y()):y();const n=Object.entries(r(s,e)||[]),i=((e,t=[],n=[])=>{let r=n.map((([n,r])=>e?t.findIndex((([t,n])=>n[e]===r[e])):n in t?n:-1));if(t.length!==n.length||!r.every(((e,t)=>e===t)))return r})(h,E,n);i&&p(t,i,n,A),E=n.slice(0)},pickupNode:b}}},{bind:b,update:E}=(()=>{const e=(()=>{let e=new Set;return{publish:t=>{for(let t of e)t();t?.()},subscribe(t){e.add(t)}}})();return{bind(t){let n=m[t.type](t,{getState:a,dispatch:l});return e.subscribe(n.handler),n},update:t=>e.publish(t)}})();let v=0;const A=e=>{let t=0,r={};return n(e,(e=>{let n,i=[];switch(e.nodeType){case e.TEXT_NODE:{let t=e.textContent;t.match(/({{[^{}]+}})/)&&i.push({type:1,value:t});break}case e.ELEMENT_NODE:{let t=function(e){let t=e.getAttribute("each"),n=t?.match(/(.+)\s+in\s+(.+)/);if(!n)return t?{path:t.trim(),key:e.getAttribute("key")}:n;let[r,i,a]=n,l=i.match(/\(([^\)]+)\)/),[s,c]=(l?l[1].split(","):[i]).map((e=>e.trim()));return{path:a.trim(),identifier:c||s,index:c?s:c,key:e.getAttribute("key")}}(e);if(t){let r,a=e.namespaceURI;if(a.endsWith("/svg")){e.removeAttribute("each");let t=document.createElementNS(a,"defs");t.innerHTML=e.outerHTML,e.parentNode.replaceChild(t,e),r=A((e=t).firstChild)}else{if("TEMPLATE"!==e.nodeName){e.removeAttribute("each");let t=document.createElement("template");t.innerHTML=e.outerHTML,e.parentNode.replaceChild(t,e),e=t}r=A(e.content.firstChild)}n=e.nextSibling,i.push({type:5,map:r,blockIndex:v++,...t,pickupNode:n});break}let r=e.attributes,a=r.length;for(;a--;){let{name:t,value:n}=r[a];if(":name"!==t||!n||"INPUT"!==e.nodeName&&"SELECT"!==e.nodeName&&"TEXTAREA"!==e.nodeName){if(t.startsWith(":on")){e.removeAttribute(t);let r=t.split(":on")[1];i.push({type:4,eventType:r,actionType:n})}else if(t.startsWith(":")){let r=t.slice(1),a=n||r;a.includes("{{")||(a=`{{${a}}}`),i.push({type:2,name:r,value:a}),e.removeAttribute(t)}}else i.push({type:3,path:n}),e.removeAttribute(t),e.setAttribute("name",n)}}}return i.length&&(r[t]=i),t++,n})),r},k=(...e)=>(...t)=>{for(let n of e){if(!1===n(...t))return!1}},T=(e,t=0,n)=>{let r=0;return i=>{let a;return r in e&&(e[r].forEach((e=>{let r=b({...e,node:i,context:n,hydrate:t});a=r.pickupNode})),i.$i=r),r++,a}};let N=i(s),C=A(N);return n(N,T(C)),o?.(N),t.prepend(N),E(),(e=>{let t=!1,n=!1;return()=>{t?n=!0:(t=!0,e(),requestAnimationFrame((()=>{n&&e(),t=!1})))}})((()=>E(c)))},v=e=>{let t=document.createDocumentFragment();for(;e.firstChild;)t.appendChild(e.firstChild);return t},A=(e,t,n)=>customElements.define(e,class extends HTMLElement{async connectedCallback(){if(!this.initialised){let e=t(this);e instanceof Promise&&(e=await e);let{subscribe:r,shadow:i,initialState:u={},observe:d=[]}=e;this.connectedCallback=e.connectedCallback,this.disconnectedCallback=e.disconnectedCallback;const{dispatch:p,getState:h,onUpdate:f,flush:m}=function({update:e={},middleware:t=[],derivations:n={},initialState:r={}},i){let a,l=[],s=()=>{};function c(e){a={...e};for(let t in n)a[t]=n[t](e)}function o(){return{...a}}function u(e){l.push(e)}function d(n){const{type:r}=n;if(r.startsWith("$")&&!(r in e)&&i.dispatchEvent(new CustomEvent(r,{detail:n,bubbles:!0})),"SET"===r||"MERGE"===r)c(function(e,t){switch(t.type){case"SET":{const{name:n,value:r}=t.payload;return{...e,[n]:r}}case"MERGE":return{...e,...t.payload}}}(o(),n));else if(t.length){let i=t.slice(),a=t=>{if(i.length){let e=i.shift();t.type in e?e[t.type](t,a,{getState:o,dispatch:d,afterNextRender:u}):a(t)}else t.type in e&&c(e[t.type](o(),t))},l=i.shift();r in l?l[r](n,a,{getState:o,dispatch:d,afterNextRender:u}):a(n)}else r in e&&c(e[r](o(),n));s()}c(r);for(let t in e)t.startsWith("$")&&i.addEventListener(t,(({detail:e})=>d(e)));return{dispatch:d,getState:o,onUpdate:function(e){s=e},flush:function(){l.forEach((e=>e())),l=[]}}}(e,this);u=h(),d=d.map(s);let b,y=d.map(l),g=this.setAttribute;this.setAttribute=(e,t)=>{if(y.includes(e)){let{name:n,value:r}=o(e,t);p({type:"SET",payload:{name:n,value:r}})}g.apply(this,[e,t])},y.forEach((e=>{let t,n=o(e).name;t=this.hasAttribute(e)?this.getAttribute(e):this[n]||u[n],Object.defineProperty(this,n,{get:()=>h()[n],set(e){p({type:"SET",payload:{name:n,value:e}}),a(e)&&c(this,n,e)}}),this[n]=t})),i?this.attachShadow({mode:i}):b=e=>((e,t)=>{t.querySelectorAll("slot[name]").forEach((t=>{let n=t.attributes.name.value,r=e.querySelector(`[slot="${n}"]`);r?(r.removeAttribute("slot"),t.parentNode.replaceChild(r,t)):t.parentNode.replaceChild(v(t),t)}));let n=t.querySelector("slot:not([name])");n&&n.parentNode.replaceChild(v(e.innerHTML.trim()?e:n),n)})(this,e),f(E(this.shadowRoot||this,{getState:h,dispatch:p},n,(()=>{d.forEach((e=>{let t=h()[e];a(t)&&c(this,e,t)})),r?.(h()),m()}),b)),this.initialised=!0}this.connectedCallback?.()}disconnectedCallback(){this.disconnectedCallback?.()}});export{A as define};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mosaic",
3
- "version": "1.0.5",
3
+ "version": "1.0.8",
4
4
  "description": "The Web UI Framework",
5
5
  "main": "dist/mosaic.min.js",
6
6
  "browser": "dist/mosaic.min.js",
package/src/define.js CHANGED
@@ -6,6 +6,7 @@ import {
6
6
  attributeToProp,
7
7
  isPrimitive,
8
8
  pascalToKebab,
9
+ kebabToPascal,
9
10
  } from "./helpers.js"
10
11
 
11
12
  export const define = (name, factory, template) =>
@@ -18,7 +19,7 @@ export const define = (name, factory, template) =>
18
19
 
19
20
  if (config instanceof Promise) config = await config
20
21
 
21
- let { subscribe, shadow, initialState = {} } = config
22
+ let { subscribe, shadow, initialState = {}, observe = [] } = config
22
23
 
23
24
  this.connectedCallback = config.connectedCallback
24
25
  this.disconnectedCallback = config.disconnectedCallback
@@ -30,13 +31,9 @@ export const define = (name, factory, template) =>
30
31
 
31
32
  initialState = getState()
32
33
 
33
- let observedProps = Object.keys(initialState).filter(
34
- (v) => v.charAt(0) === "$"
35
- )
34
+ observe = observe.map(kebabToPascal)
36
35
 
37
- let observedAttributes = observedProps
38
- .map((v) => v.slice(1))
39
- .map(pascalToKebab)
36
+ let observedAttributes = observe.map(pascalToKebab)
40
37
 
41
38
  let sa = this.setAttribute
42
39
  this.setAttribute = (k, v) => {
@@ -44,7 +41,7 @@ export const define = (name, factory, template) =>
44
41
  let { name, value } = attributeToProp(k, v)
45
42
  dispatch({
46
43
  type: "SET",
47
- payload: { name: "$" + name, value },
44
+ payload: { name, value },
48
45
  })
49
46
  }
50
47
  sa.apply(this, [k, v])
@@ -52,23 +49,22 @@ export const define = (name, factory, template) =>
52
49
 
53
50
  observedAttributes.forEach((name) => {
54
51
  let property = attributeToProp(name).name
55
-
56
52
  let value
57
53
 
58
54
  if (this.hasAttribute(name)) {
59
55
  value = this.getAttribute(name)
60
56
  } else {
61
- value = this[property] || initialState["$" + property]
57
+ value = this[property] || initialState[property]
62
58
  }
63
59
 
64
60
  Object.defineProperty(this, property, {
65
61
  get() {
66
- return getState()["$" + property]
62
+ return getState()[property]
67
63
  },
68
64
  set(v) {
69
65
  dispatch({
70
66
  type: "SET",
71
- payload: { name: "$" + property, value: v },
67
+ payload: { name: property, value: v },
72
68
  })
73
69
  if (isPrimitive(v)) {
74
70
  applyAttribute(this, property, v)
@@ -95,9 +91,9 @@ export const define = (name, factory, template) =>
95
91
  { getState, dispatch },
96
92
  template,
97
93
  () => {
98
- observedProps.forEach((k) => {
94
+ observe.forEach((k) => {
99
95
  let v = getState()[k]
100
- if (isPrimitive(v)) applyAttribute(this, k.slice(1), v)
96
+ if (isPrimitive(v)) applyAttribute(this, k, v)
101
97
  })
102
98
  subscribe?.(getState())
103
99
  flush()
package/src/render.js CHANGED
@@ -100,33 +100,14 @@ export const render = (
100
100
  { node, eventType, actionType, context },
101
101
  { dispatch, getState }
102
102
  ) => {
103
- /*
104
-
105
- NB that context is only passed for local actions not prefixed with "$"
106
-
107
- */
108
-
109
103
  node.addEventListener(eventType, (event) => {
110
- let isGlobal = actionType.startsWith("$")
111
-
112
104
  let action = {
113
105
  type: actionType,
114
106
  event,
107
+ context: context ? context.wrap(getState()) : getState(),
115
108
  }
116
109
 
117
- if (!isGlobal)
118
- action.context = context ? context.wrap(getState()) : getState()
119
-
120
110
  dispatch(action)
121
-
122
- if (isGlobal) {
123
- node.dispatchEvent(
124
- new CustomEvent(actionType, {
125
- detail: action,
126
- bubbles: true,
127
- })
128
- )
129
- }
130
111
  })
131
112
  return {
132
113
  handler: () => {},
package/src/update.js CHANGED
@@ -65,6 +65,16 @@ export function configure(
65
65
 
66
66
  function dispatch(action) {
67
67
  const { type } = action
68
+
69
+ if (type.startsWith("$") && !(type in update)) {
70
+ node.dispatchEvent(
71
+ new CustomEvent(type, {
72
+ detail: action,
73
+ bubbles: true,
74
+ })
75
+ )
76
+ }
77
+
68
78
  if (type === "SET" || type === "MERGE") {
69
79
  updateState(systemReducer(getState(), action))
70
80
  } else {