mosaic 1.0.3 → 1.0.6

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.
Files changed (88) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +63 -8
  3. package/cjs/attribute.js +90 -0
  4. package/cjs/constants.js +15 -0
  5. package/cjs/context.js +66 -0
  6. package/cjs/define.js +117 -0
  7. package/cjs/formControl.js +42 -0
  8. package/cjs/helpers.js +140 -0
  9. package/cjs/index.js +9 -0
  10. package/cjs/list.js +109 -0
  11. package/cjs/mergeSlots.js +37 -0
  12. package/cjs/proxy.js +42 -0
  13. package/cjs/render.js +384 -0
  14. package/cjs/token.js +63 -0
  15. package/cjs/update.js +128 -0
  16. package/dist/mosaic.js +1096 -0
  17. package/dist/mosaic.min.js +1 -0
  18. package/package.json +42 -25
  19. package/src/attribute.js +84 -0
  20. package/src/constants.js +5 -0
  21. package/src/context.js +60 -0
  22. package/src/define.js +116 -0
  23. package/src/formControl.js +36 -0
  24. package/src/helpers.js +123 -0
  25. package/src/index.js +1 -0
  26. package/src/list.js +100 -0
  27. package/src/mergeSlots.js +31 -0
  28. package/src/proxy.js +36 -0
  29. package/src/render.js +386 -0
  30. package/src/token.js +55 -0
  31. package/src/update.js +122 -0
  32. package/SCRATCH.md +0 -31
  33. package/cli.js +0 -17
  34. package/conf.json +0 -0
  35. package/docs/assets/css/main.css +0 -2638
  36. package/docs/assets/images/icons.png +0 -0
  37. package/docs/assets/images/icons@2x.png +0 -0
  38. package/docs/assets/images/widgets.png +0 -0
  39. package/docs/assets/images/widgets@2x.png +0 -0
  40. package/docs/assets/js/main.js +0 -248
  41. package/docs/assets/js/search.js +0 -1
  42. package/docs/index.html +0 -111
  43. package/docs/modules.html +0 -131
  44. package/example/components/x-drawer.html +0 -41
  45. package/example/mosaic/templates/mocha/index.html +0 -39
  46. package/example/mosaic/tests.d.ts +0 -13
  47. package/example/mosaic/tests.js +0 -28
  48. package/example/mosaic/website.d.ts +0 -31
  49. package/example/mosaic/website.js +0 -64
  50. package/example/mosaic.config.d.ts +0 -7
  51. package/example/mosaic.config.js +0 -8
  52. package/example/package-lock.json +0 -899
  53. package/example/package.json +0 -20
  54. package/example/pages/index.html +0 -12
  55. package/example/test/x-drawer.d.ts +0 -0
  56. package/example/test/x-drawer.js +0 -94
  57. package/index.d.ts +0 -85
  58. package/index.js +0 -125
  59. package/index.wdocs.js +0 -37
  60. package/out/fonts/OpenSans-Bold-webfont.eot +0 -0
  61. package/out/fonts/OpenSans-Bold-webfont.svg +0 -1830
  62. package/out/fonts/OpenSans-Bold-webfont.woff +0 -0
  63. package/out/fonts/OpenSans-BoldItalic-webfont.eot +0 -0
  64. package/out/fonts/OpenSans-BoldItalic-webfont.svg +0 -1830
  65. package/out/fonts/OpenSans-BoldItalic-webfont.woff +0 -0
  66. package/out/fonts/OpenSans-Italic-webfont.eot +0 -0
  67. package/out/fonts/OpenSans-Italic-webfont.svg +0 -1830
  68. package/out/fonts/OpenSans-Italic-webfont.woff +0 -0
  69. package/out/fonts/OpenSans-Light-webfont.eot +0 -0
  70. package/out/fonts/OpenSans-Light-webfont.svg +0 -1831
  71. package/out/fonts/OpenSans-Light-webfont.woff +0 -0
  72. package/out/fonts/OpenSans-LightItalic-webfont.eot +0 -0
  73. package/out/fonts/OpenSans-LightItalic-webfont.svg +0 -1835
  74. package/out/fonts/OpenSans-LightItalic-webfont.woff +0 -0
  75. package/out/fonts/OpenSans-Regular-webfont.eot +0 -0
  76. package/out/fonts/OpenSans-Regular-webfont.svg +0 -1831
  77. package/out/fonts/OpenSans-Regular-webfont.woff +0 -0
  78. package/out/global.html +0 -912
  79. package/out/index.html +0 -65
  80. package/out/index.js.html +0 -239
  81. package/out/scripts/linenumber.js +0 -25
  82. package/out/scripts/prettify/Apache-License-2.0.txt +0 -202
  83. package/out/scripts/prettify/lang-css.js +0 -2
  84. package/out/scripts/prettify/prettify.js +0 -28
  85. package/out/styles/jsdoc-default.css +0 -358
  86. package/out/styles/prettify-jsdoc.css +0 -111
  87. package/out/styles/prettify-tomorrow.css +0 -132
  88. package/tsconfig.json +0 -11
@@ -0,0 +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={type:n,event:t,context:r?r.wrap(a()):a()};i(l),n.startsWith("$")&&e.dispatchEvent(new CustomEvent(n,{detail:l,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};
package/package.json CHANGED
@@ -1,36 +1,53 @@
1
1
  {
2
2
  "name": "mosaic",
3
- "type": "module",
4
- "version": "1.0.3",
5
- "description": "Mosaic is a node command line utility made primarily for transforming and combining HTML assets.",
6
- "main": "index.js",
3
+ "version": "1.0.6",
4
+ "description": "The Web UI Framework",
5
+ "main": "dist/mosaic.min.js",
6
+ "browser": "dist/mosaic.min.js",
7
+ "unpkg": "dist/mosaic.min.js",
8
+ "module": "src/index.js",
9
+ "types": "types/index.d.ts",
10
+ "files": [
11
+ "src",
12
+ "dist",
13
+ "cjs"
14
+ ],
15
+ "directories": {
16
+ "test": "test"
17
+ },
18
+ "scripts": {
19
+ "test": "mocha-express --coverage",
20
+ "test:watch": "mocha-express --watch",
21
+ "build": "rm -rf dist && rollup -c && npm run size",
22
+ "size": "gzip -c9 ./dist/mosaic.min.js | wc -c",
23
+ "coveralls": "cat ./coverage/lcov-report/lcov.info | coveralls",
24
+ "prepublishOnly": "npm t && npm run build",
25
+ "release": "npm t && standard-version"
26
+ },
7
27
  "repository": {
8
28
  "type": "git",
9
29
  "url": "git+https://github.com/defx/mosaic.git"
10
30
  },
11
- "keywords": [],
12
- "author": "defx",
13
- "license": "ISC",
31
+ "keywords": [
32
+ "simple",
33
+ "declarative",
34
+ "dom",
35
+ "ui",
36
+ "user interface",
37
+ "web components",
38
+ "framework"
39
+ ],
40
+ "author": "Matt Donkin",
41
+ "license": "MIT",
14
42
  "bugs": {
15
43
  "url": "https://github.com/defx/mosaic/issues"
16
44
  },
17
- "homepage": "https://github.com/defx/mosaic#readme",
18
- "dependencies": {
19
- "chokidar": "^3.4.3",
20
- "express": "^4.17.1",
21
- "fs": "0.0.1-security",
22
- "fs-extra": "^9.1.0",
23
- "glob": "^7.1.6",
24
- "glob-promise": "^3.4.0",
25
- "lodash.debounce": "^4.0.8",
26
- "path": "^0.12.7",
27
- "ws": "^7.4.2"
28
- },
29
- "bin": {
30
- "mosaic": "cli.js"
31
- },
32
- "devDependencies": {},
33
- "scripts": {
34
- "test": "echo \"Error: no test specified\" && exit 1"
45
+ "homepage": "https://github.com/defx/mosaic",
46
+ "devDependencies": {
47
+ "coveralls": "^3.1.0",
48
+ "mocha-express": "^0.1.2",
49
+ "rollup": "^2.26.4",
50
+ "rollup-plugin-terser": "^7.0.1",
51
+ "standard-version": "^9.1.1"
35
52
  }
36
53
  }
@@ -0,0 +1,84 @@
1
+ import { isPrimitive, typeOf } from "./helpers.js"
2
+
3
+ const pascalToKebab = (string) =>
4
+ string.replace(/[\w]([A-Z])/g, function (m) {
5
+ return m[0] + "-" + m[1].toLowerCase()
6
+ })
7
+
8
+ const kebabToPascal = (string) =>
9
+ string.replace(/[\w]-([\w])/g, function (m) {
10
+ return m[0] + m[2].toUpperCase()
11
+ })
12
+
13
+ const parseStyles = (value) => {
14
+ let type = typeof value
15
+
16
+ if (type === "string")
17
+ return value.split(";").reduce((o, value) => {
18
+ const [k, v] = value.split(":").map((v) => v.trim())
19
+ if (k) o[k] = v
20
+ return o
21
+ }, {})
22
+
23
+ if (type === "object") return value
24
+
25
+ return {}
26
+ }
27
+
28
+ const joinStyles = (value) =>
29
+ Object.entries(value)
30
+ .map(([k, v]) => `${k}: ${v};`)
31
+ .join(" ")
32
+
33
+ const convertStyles = (o) =>
34
+ Object.keys(o).reduce((a, k) => {
35
+ a[pascalToKebab(k)] = o[k]
36
+ return a
37
+ }, {})
38
+
39
+ export const applyAttribute = (node, name, value) => {
40
+ if (name === "style") {
41
+ value = joinStyles(
42
+ convertStyles({
43
+ ...parseStyles(node.getAttribute("style")),
44
+ ...parseStyles(value),
45
+ })
46
+ )
47
+ } else if (name === "class") {
48
+ switch (typeOf(value)) {
49
+ case "Array":
50
+ value = value.join(" ")
51
+ break
52
+ case "Object":
53
+ value = Object.keys(value)
54
+ .reduce((a, k) => {
55
+ if (value[k]) a.push(k)
56
+ return a
57
+ }, [])
58
+ .join(" ")
59
+ break
60
+ }
61
+ } else if (!isPrimitive(value)) {
62
+ return (node[kebabToPascal(name)] = value)
63
+ }
64
+
65
+ name = pascalToKebab(name)
66
+
67
+ if (typeof value === "boolean") {
68
+ if (name.startsWith("aria-")) {
69
+ value = "" + value
70
+ } else if (value) {
71
+ value = ""
72
+ }
73
+ }
74
+
75
+ let current = node.getAttribute(name)
76
+
77
+ if (value === current) return
78
+
79
+ if (typeof value === "string" || typeof value === "number") {
80
+ node.setAttribute(name, value)
81
+ } else {
82
+ node.removeAttribute(name)
83
+ }
84
+ }
@@ -0,0 +1,5 @@
1
+ export const TEXT = 1
2
+ export const ATTRIBUTE = 2
3
+ export const INPUT = 3
4
+ export const EVENT = 4
5
+ export const REPEAT = 5
package/src/context.js ADDED
@@ -0,0 +1,60 @@
1
+ import { getValueAtPath, isPrimitive } from "./helpers.js"
2
+
3
+ const handler = ({ path, identifier, key, index, i, k }) => ({
4
+ get(target, property) {
5
+ let x = getValueAtPath(path, target)
6
+
7
+ // x === the collection
8
+
9
+ if (property === identifier) {
10
+ for (let n in x) {
11
+ let v = x[n]
12
+ if (key) {
13
+ if (v[key] === k) return v
14
+ } else {
15
+ if (n == i) return v
16
+ }
17
+ }
18
+ }
19
+
20
+ if (property === index) {
21
+ for (let n in x) {
22
+ let v = x[n]
23
+ if (key) {
24
+ if (v[key] === k) return n
25
+ } else {
26
+ if (n == i) return n
27
+ }
28
+ }
29
+ }
30
+
31
+ let t = key ? x.find((v) => v[key] === k) : x[i]
32
+ if (t?.hasOwnProperty?.(property)) return t[property]
33
+
34
+ return Reflect.get(...arguments)
35
+ },
36
+ set(target, property, value) {
37
+ let x = getValueAtPath(path, target)
38
+ let t = key ? x.find((v) => v[key] === k) : x[i]
39
+ if (t && !isPrimitive(t)) {
40
+ t[property] = value
41
+ return true
42
+ }
43
+
44
+ return Reflect.set(...arguments)
45
+ },
46
+ })
47
+
48
+ export const createContext = (v = []) => {
49
+ let context = v
50
+ return {
51
+ get: () => context,
52
+ push: (v) => context.push(v),
53
+ wrap: (state) => {
54
+ return context.reduce(
55
+ (target, ctx) => new Proxy(target, handler(ctx)),
56
+ state
57
+ )
58
+ },
59
+ }
60
+ }
package/src/define.js ADDED
@@ -0,0 +1,116 @@
1
+ import { configure } from "./update.js"
2
+ import { render } from "./render.js"
3
+ import { mergeSlots } from "./mergeSlots.js"
4
+ import {
5
+ applyAttribute,
6
+ attributeToProp,
7
+ isPrimitive,
8
+ pascalToKebab,
9
+ } from "./helpers.js"
10
+
11
+ export const define = (name, factory, template) =>
12
+ customElements.define(
13
+ name,
14
+ class extends HTMLElement {
15
+ async connectedCallback() {
16
+ if (!this.initialised) {
17
+ let config = factory(this)
18
+
19
+ if (config instanceof Promise) config = await config
20
+
21
+ let { subscribe, shadow, initialState = {} } = config
22
+
23
+ this.connectedCallback = config.connectedCallback
24
+ this.disconnectedCallback = config.disconnectedCallback
25
+
26
+ const { dispatch, getState, onUpdate, flush } = configure(
27
+ config,
28
+ this
29
+ )
30
+
31
+ initialState = getState()
32
+
33
+ let observedProps = Object.keys(initialState).filter(
34
+ (v) => v.charAt(0) === "$"
35
+ )
36
+
37
+ let observedAttributes = observedProps
38
+ .map((v) => v.slice(1))
39
+ .map(pascalToKebab)
40
+
41
+ let sa = this.setAttribute
42
+ this.setAttribute = (k, v) => {
43
+ if (observedAttributes.includes(k)) {
44
+ let { name, value } = attributeToProp(k, v)
45
+ dispatch({
46
+ type: "SET",
47
+ payload: { name: "$" + name, value },
48
+ })
49
+ }
50
+ sa.apply(this, [k, v])
51
+ }
52
+
53
+ observedAttributes.forEach((name) => {
54
+ let property = attributeToProp(name).name
55
+
56
+ let value
57
+
58
+ if (this.hasAttribute(name)) {
59
+ value = this.getAttribute(name)
60
+ } else {
61
+ value = this[property] || initialState["$" + property]
62
+ }
63
+
64
+ Object.defineProperty(this, property, {
65
+ get() {
66
+ return getState()["$" + property]
67
+ },
68
+ set(v) {
69
+ dispatch({
70
+ type: "SET",
71
+ payload: { name: "$" + property, value: v },
72
+ })
73
+ if (isPrimitive(v)) {
74
+ applyAttribute(this, property, v)
75
+ }
76
+ },
77
+ })
78
+
79
+ this[property] = value
80
+ })
81
+
82
+ let beforeMountCallback
83
+
84
+ if (shadow) {
85
+ this.attachShadow({
86
+ mode: shadow,
87
+ })
88
+ } else {
89
+ beforeMountCallback = (frag) => mergeSlots(this, frag)
90
+ }
91
+
92
+ onUpdate(
93
+ render(
94
+ this.shadowRoot || this,
95
+ { getState, dispatch },
96
+ template,
97
+ () => {
98
+ observedProps.forEach((k) => {
99
+ let v = getState()[k]
100
+ if (isPrimitive(v)) applyAttribute(this, k.slice(1), v)
101
+ })
102
+ subscribe?.(getState())
103
+ flush()
104
+ },
105
+ beforeMountCallback
106
+ )
107
+ )
108
+ this.initialised = true
109
+ }
110
+ this.connectedCallback?.()
111
+ }
112
+ disconnectedCallback() {
113
+ this.disconnectedCallback?.()
114
+ }
115
+ }
116
+ )
@@ -0,0 +1,36 @@
1
+ export const updateFormControl = (node, value) => {
2
+ if (node.nodeName === "SELECT") {
3
+ Array.from(node.querySelectorAll("option")).forEach((option) => {
4
+ option.selected = value.includes(option.value)
5
+ })
6
+ return
7
+ }
8
+
9
+ let checked
10
+
11
+ switch (node.getAttribute("type")) {
12
+ case "checkbox":
13
+ checked = value
14
+ if (node.checked === checked) break
15
+ if (checked) {
16
+ node.setAttribute("checked", "")
17
+ } else {
18
+ node.removeAttribute("checked")
19
+ }
20
+ break
21
+ case "radio":
22
+ checked = value === node.getAttribute("value")
23
+ if (node.checked === checked) break
24
+ node.checked = checked
25
+ if (checked) {
26
+ node.setAttribute("checked", "")
27
+ } else {
28
+ node.removeAttribute("checked")
29
+ }
30
+ break
31
+ default:
32
+ if (node.value === value) break
33
+ node.setAttribute("value", (node.value = value || ""))
34
+ break
35
+ }
36
+ }
package/src/helpers.js ADDED
@@ -0,0 +1,123 @@
1
+ export const last = (v = []) => v[v.length - 1]
2
+
3
+ export const isWhitespace = (node) => {
4
+ return node.nodeType === node.TEXT_NODE && node.nodeValue.trim() === ""
5
+ }
6
+
7
+ export const walk = (node, callback, deep = true) => {
8
+ if (!node) return
9
+ if (!isWhitespace(node)) {
10
+ let v = callback(node)
11
+ if (v === false) return
12
+ if (v?.nodeName) return walk(v, callback, deep)
13
+ }
14
+ if (deep) walk(node.firstChild, callback, deep)
15
+ walk(node.nextSibling, callback, deep)
16
+ }
17
+
18
+ const transformBrackets = (str = "") => {
19
+ let parts = str.split(/(\[[^\]]+\])/).filter((v) => v)
20
+ return parts.reduce((a, part) => {
21
+ let v = part.charAt(0) === "[" ? "." + part.replace(/\./g, ":") : part
22
+ return a + v
23
+ }, "")
24
+ }
25
+
26
+ const getTarget = (path, target) => {
27
+ let parts = transformBrackets(path)
28
+ .split(".")
29
+ .map((k) => {
30
+ if (k.charAt(0) === "[") {
31
+ let p = k.slice(1, -1).replace(/:/g, ".")
32
+ return getValueAtPath(p, target)
33
+ } else {
34
+ return k
35
+ }
36
+ })
37
+
38
+ let t =
39
+ parts.slice(0, -1).reduce((o, k) => {
40
+ return o && o[k]
41
+ }, target) || target
42
+ return [t, last(parts)]
43
+ }
44
+
45
+ export const getValueAtPath = (path, target) => {
46
+ let [a, b] = getTarget(path, target)
47
+ let v = a?.[b]
48
+ if (typeof v === "function") return v.bind(a)
49
+ return v
50
+ }
51
+
52
+ export const fragmentFromTemplate = (v) => {
53
+ if (typeof v === "string") {
54
+ let tpl = document.createElement("template")
55
+ tpl.innerHTML = v.trim()
56
+ return tpl.content
57
+ }
58
+ if (v.nodeName === "TEMPLATE") return v.cloneNode(true).content
59
+ if (v.nodeName === "defs") return v.firstElementChild.cloneNode(true)
60
+ }
61
+
62
+ export const debounce = (fn) => {
63
+ let wait = false
64
+ let invoke = false
65
+ return () => {
66
+ if (wait) {
67
+ invoke = true
68
+ } else {
69
+ wait = true
70
+ fn()
71
+ requestAnimationFrame(() => {
72
+ if (invoke) fn()
73
+ wait = false
74
+ })
75
+ }
76
+ }
77
+ }
78
+
79
+ export const isPrimitive = (v) => v === null || typeof v !== "object"
80
+
81
+ export const typeOf = (v) =>
82
+ Object.prototype.toString.call(v).match(/\s(.+[^\]])/)[1]
83
+
84
+ export const pascalToKebab = (string) =>
85
+ string.replace(/[\w]([A-Z])/g, function (m) {
86
+ return m[0] + "-" + m[1].toLowerCase()
87
+ })
88
+
89
+ export const kebabToPascal = (string) =>
90
+ string.replace(/[\w]-([\w])/g, function (m) {
91
+ return m[0] + m[2].toUpperCase()
92
+ })
93
+
94
+ export const applyAttribute = (node, name, value) => {
95
+ name = pascalToKebab(name)
96
+
97
+ if (typeof value === "boolean") {
98
+ if (name.startsWith("aria-")) {
99
+ value = "" + value
100
+ } else if (value) {
101
+ value = ""
102
+ }
103
+ }
104
+
105
+ if (typeof value === "string" || typeof value === "number") {
106
+ node.setAttribute(name, value)
107
+ } else {
108
+ node.removeAttribute(name)
109
+ }
110
+ }
111
+
112
+ export const attributeToProp = (k, v) => {
113
+ let name = kebabToPascal(k)
114
+ if (v === "") v = true
115
+ if (k.startsWith("aria-")) {
116
+ if (v === "true") v = true
117
+ if (v === "false") v = false
118
+ }
119
+ return {
120
+ name,
121
+ value: v,
122
+ }
123
+ }
package/src/index.js ADDED
@@ -0,0 +1 @@
1
+ export { define } from "./define.js"
package/src/list.js ADDED
@@ -0,0 +1,100 @@
1
+ import { isWhitespace, walk } from "./helpers.js"
2
+
3
+ export function parseEach(node) {
4
+ let each = node.getAttribute("each")
5
+ let m = each?.match(/(.+)\s+in\s+(.+)/)
6
+ if (!m) {
7
+ if (!each) return m
8
+ return {
9
+ path: each.trim(),
10
+ key: node.getAttribute("key"),
11
+ }
12
+ }
13
+ let [_, left, right] = m
14
+ let parts = left.match(/\(([^\)]+)\)/)
15
+ let [a, b] = (parts ? parts[1].split(",") : [left]).map((v) => v.trim())
16
+
17
+ return {
18
+ path: right.trim(),
19
+ identifier: b ? b : a,
20
+ index: b ? a : b,
21
+ key: node.getAttribute("key"),
22
+ }
23
+ }
24
+
25
+ const getBlockSize = (template) => {
26
+ let i = 0
27
+ walk(template.content?.firstChild || template.firstChild, () => i++, false)
28
+ return i
29
+ }
30
+
31
+ const nextNonWhitespaceSibling = (node) => {
32
+ return isWhitespace(node.nextSibling)
33
+ ? nextNonWhitespaceSibling(node.nextSibling)
34
+ : node.nextSibling
35
+ }
36
+
37
+ const getBlockFragments = (template, numBlocks) => {
38
+ let blockSize = getBlockSize(template)
39
+
40
+ let r = []
41
+ if (numBlocks) {
42
+ while (numBlocks--) {
43
+ let f = document.createDocumentFragment()
44
+ let n = blockSize
45
+ while (n--) {
46
+ f.appendChild(nextNonWhitespaceSibling(template))
47
+ }
48
+ r.push(f)
49
+ }
50
+ }
51
+ return r
52
+ }
53
+
54
+ export const getBlocks = (template) => {
55
+ let numBlocks = template.getAttribute("length")
56
+ let blockSize = getBlockSize(template)
57
+ let r = []
58
+ let node = template
59
+ if (numBlocks) {
60
+ while (numBlocks--) {
61
+ let f = []
62
+ let n = blockSize
63
+ while (n--) {
64
+ node = nextNonWhitespaceSibling(node)
65
+ f.push(node)
66
+ }
67
+ r.push(f)
68
+ }
69
+ }
70
+ return r
71
+ }
72
+
73
+ export const compareKeyedLists = (key, a = [], b = []) => {
74
+ let delta = b.map(([k, item]) =>
75
+ !key ? (k in a ? k : -1) : a.findIndex(([_, v]) => v[key] === item[key])
76
+ )
77
+ if (a.length !== b.length || !delta.every((a, b) => a === b)) return delta
78
+ }
79
+
80
+ function lastChild(v) {
81
+ return (v.nodeType === v.DOCUMENT_FRAGMENT_NODE && v.lastChild) || v
82
+ }
83
+
84
+ export const updateList = (template, delta, entries, createListItem) => {
85
+ let n = template.getAttribute("length") || 0
86
+ let blocks = getBlockFragments(template, n)
87
+ let t = template
88
+
89
+ delta.forEach((i, newIndex) => {
90
+ let frag =
91
+ i === -1
92
+ ? createListItem(entries[newIndex][1], entries[newIndex][0])
93
+ : blocks[i]
94
+ let x = lastChild(frag)
95
+ t.after(frag)
96
+ t = x
97
+ })
98
+
99
+ template.setAttribute("length", delta.length)
100
+ }
@@ -0,0 +1,31 @@
1
+ const childNodes = (node) => {
2
+ let frag = document.createDocumentFragment()
3
+ while (node.firstChild) {
4
+ frag.appendChild(node.firstChild)
5
+ }
6
+ return frag
7
+ }
8
+
9
+ export const mergeSlots = (targetNode, sourceNode) => {
10
+ let namedSlots = sourceNode.querySelectorAll("slot[name]")
11
+
12
+ namedSlots.forEach((slot) => {
13
+ let name = slot.attributes.name.value
14
+ let node = targetNode.querySelector(`[slot="${name}"]`)
15
+ if (!node) {
16
+ slot.parentNode.replaceChild(childNodes(slot), slot)
17
+ return
18
+ }
19
+ node.removeAttribute("slot")
20
+ slot.parentNode.replaceChild(node, slot)
21
+ })
22
+
23
+ let defaultSlot = sourceNode.querySelector("slot:not([name])")
24
+
25
+ if (defaultSlot) {
26
+ defaultSlot.parentNode.replaceChild(
27
+ childNodes(targetNode.innerHTML.trim() ? targetNode : defaultSlot),
28
+ defaultSlot
29
+ )
30
+ }
31
+ }