mosaic 1.0.20 → 1.1.0

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/dist/dynamo.js ADDED
@@ -0,0 +1,414 @@
1
+ function cast(v) {
2
+ if (typeof v === "string" && v.length) {
3
+ return isNaN(v) ? v : +v
4
+ }
5
+ return v
6
+ }
7
+
8
+ function castAll(o) {
9
+ return Object.fromEntries(Object.entries(o).map(([k, v]) => [k, cast(v)]))
10
+ }
11
+
12
+ const isPrimitive = (v) => v === null || typeof v !== "object";
13
+
14
+ function nodeFromString(str) {
15
+ const doc = new DOMParser().parseFromString(str.trim(), "text/html", {
16
+ includeShadowRoots: true, // @todo: required?
17
+ });
18
+
19
+ const errorNode = doc.querySelector("parsererror");
20
+
21
+ if (errorNode) ; else {
22
+ return doc.head.firstChild || doc.body.firstChild
23
+ }
24
+ }
25
+
26
+ function listItems(listContainerNode, listItemSelector) {
27
+ return [...listContainerNode.children].filter((node) =>
28
+ node.matches(listItemSelector)
29
+ )
30
+ }
31
+
32
+ function listData(listItems) {
33
+ return listItems.map((node) => ({
34
+ id: node.id,
35
+ ...castAll(node.dataset),
36
+ }))
37
+ }
38
+
39
+ function listSync(parentNode, nodes, curr, next, template) {
40
+ // check if anything has changed
41
+ const currIds = curr.map(({ id }) => id);
42
+ const nextIds = next.map(({ id }) => id);
43
+
44
+ if (currIds.toString() === nextIds.toString()) return
45
+
46
+ // removals
47
+ curr
48
+ .filter((c) => {
49
+ return next.find((n) => c.id === n.id) === undefined
50
+ })
51
+ .forEach(({ id }) => nodes.find((node) => node.id === id)?.remove());
52
+
53
+ const [first, ...rest] = next;
54
+
55
+ if (!first) return
56
+
57
+ let t = first && nodes.find((node) => node.id === first.id);
58
+
59
+ if (
60
+ !template &&
61
+ next.find((c) => {
62
+ return curr.find((n) => c.id === n.id) === false
63
+ })
64
+ ) {
65
+ console.error(`Missing template when trying to add items to a list`);
66
+ return
67
+ }
68
+
69
+ if (!t) {
70
+ t = nodeFromString(template(first));
71
+
72
+ if (nodes[0]) {
73
+ nodes[0].before(t);
74
+ } else {
75
+ parentNode.append(t);
76
+ }
77
+ }
78
+
79
+ rest.forEach((d) => {
80
+ let node =
81
+ nodes.find((node) => node.id === d.id) || nodeFromString(template(d));
82
+
83
+ if (node) {
84
+ if (t.nextElementSibling !== node) {
85
+ // is t.after already a no-op in this case?
86
+ t.after(node);
87
+ }
88
+ t = node;
89
+ }
90
+ });
91
+ }
92
+
93
+ const pascalToKebab = (string) =>
94
+ string.replace(/[\w]([A-Z])/g, function (m) {
95
+ return m[0] + "-" + m[1].toLowerCase()
96
+ });
97
+
98
+ const kebabToPascal = (string) =>
99
+ string.replace(/[\w]-([\w])/g, function (m) {
100
+ return m[0] + m[2].toUpperCase()
101
+ });
102
+
103
+ const objectToClasses = (v = {}) => {
104
+ return Object.entries(v)
105
+ .reduce((c, [k, v]) => {
106
+ if (v) c.push(k);
107
+ return c
108
+ }, [])
109
+ .join(" ")
110
+ };
111
+
112
+ const write = (node, attrs) => {
113
+ for (let [k, v] of Object.entries(attrs || {})) {
114
+ k = pascalToKebab(k);
115
+
116
+ if (k === "textContent" && node.textContent !== textContent) {
117
+ node.textContent = textContent;
118
+ continue
119
+ }
120
+
121
+ if (k === "class") {
122
+ v = objectToClasses(v);
123
+ }
124
+
125
+ if (typeof v === "boolean") {
126
+ if (k.startsWith("aria-")) {
127
+ v = "" + v;
128
+ } else if (v) {
129
+ v = "";
130
+ }
131
+ }
132
+
133
+ if (isPrimitive(v) === false) {
134
+ node[kebabToPascal(k)] = v;
135
+ continue
136
+ }
137
+
138
+ let current = node.getAttribute(k);
139
+
140
+ if (v === current) continue
141
+
142
+ if (typeof v === "string" || typeof v === "number") {
143
+ node.setAttribute(k, v);
144
+ } else {
145
+ node.removeAttribute(k);
146
+ }
147
+ }
148
+ return node
149
+ };
150
+
151
+ function initialise(rootNode, subscribe, config, store, state = {}) {
152
+ const event = {};
153
+
154
+ const { elements = [] } = config;
155
+
156
+ // derive initial state from input directives...
157
+ elements
158
+ .filter(({ input }) => input)
159
+ .forEach(({ select, input }) => {
160
+ const targets = [...rootNode.querySelectorAll(select)];
161
+ targets.forEach((target) => {
162
+ state = { ...state, [input]: target.value };
163
+
164
+ event.input = event.input || [];
165
+ event.input.push({
166
+ select,
167
+ callback: (event) => {
168
+ const { target } = event;
169
+ store.merge({ [input]: target.value });
170
+ },
171
+ });
172
+ });
173
+ });
174
+
175
+ // find event listeners
176
+ elements.forEach((c) => {
177
+ const { select, on } = c;
178
+ if (on) {
179
+ Object.entries(on).forEach(([type, callback]) => {
180
+ event[type] = event[type] || [];
181
+ event[type].push({
182
+ select,
183
+ callback,
184
+ });
185
+ });
186
+ }
187
+ });
188
+
189
+ //derive initial state from lists...
190
+ elements
191
+ .filter(({ list }) => list)
192
+ .forEach(({ select, list }) => {
193
+ const targets = [...rootNode.querySelectorAll(select)];
194
+ targets.forEach((target) => {
195
+ const items = listItems(target, list.select);
196
+ const curr = listData(items);
197
+ state[list.from] = curr;
198
+ });
199
+ });
200
+
201
+ // delegate from the root node
202
+ Object.entries(event).forEach(([type, listeners]) => {
203
+ rootNode.addEventListener(type, (e) => {
204
+ listeners
205
+ .filter(({ select }) => e.target.matches(select))
206
+ .forEach(({ select, callback }) => {
207
+ if (typeof callback === "function") {
208
+ callback(e, store);
209
+ }
210
+ if (typeof callback === "string") {
211
+ const { target } = e;
212
+
213
+ const targets = [...rootNode.querySelectorAll(select)];
214
+
215
+ const index = targets.indexOf(target);
216
+
217
+ store.dispatch(callback, { event: e, index });
218
+ }
219
+ });
220
+ });
221
+ });
222
+
223
+ const onChange = (state) => {
224
+ // lists first
225
+ elements
226
+ .filter(({ list }) => list)
227
+ .forEach(({ select, list }) => {
228
+ const targets = [...rootNode.querySelectorAll(select)];
229
+ targets.forEach((target) => {
230
+ const items = listItems(target, list.select);
231
+ const curr = listData(items);
232
+ const next = state[list.from];
233
+ listSync(target, items, curr, next, list.template);
234
+ });
235
+ });
236
+
237
+ // then the rest...
238
+ elements.forEach((c) => {
239
+ const { select, attribute, input } = c;
240
+
241
+ const targets = [...rootNode.querySelectorAll(select)];
242
+
243
+ targets.forEach((target, i) => {
244
+ if (attribute) {
245
+ write(target, attribute(state, i));
246
+ }
247
+ if (input) {
248
+ const value = state[input];
249
+
250
+ if (target.value !== value) target.value = value;
251
+ }
252
+ });
253
+ });
254
+ };
255
+
256
+ subscribe(onChange);
257
+
258
+ return state
259
+ }
260
+
261
+ function debounce(fn) {
262
+ let id;
263
+ return (...args) => {
264
+ if (!id) {
265
+ id = requestAnimationFrame(() => {
266
+ fn(...args);
267
+ id = null;
268
+ });
269
+ }
270
+ }
271
+ }
272
+
273
+ function Store({
274
+ action: actionHandlers = {},
275
+ getState: getStateWrapper = (v) => v,
276
+ onChangeCallback,
277
+ api = {},
278
+ }) {
279
+ let state;
280
+
281
+ const transition = debounce(() => onChangeCallback(getState()));
282
+
283
+ function set(o) {
284
+ state = getStateWrapper({ ...o });
285
+ }
286
+
287
+ function getState() {
288
+ return { ...state }
289
+ }
290
+
291
+ function dispatch(type, action) {
292
+ if (type in actionHandlers) {
293
+ const x = actionHandlers[type](getState(), action);
294
+ set(x);
295
+ transition();
296
+ }
297
+ }
298
+
299
+ return {
300
+ dispatch,
301
+ getState,
302
+ merge: (o) => {
303
+ set({ ...getState(), ...o });
304
+ transition();
305
+ },
306
+ set,
307
+ ...api,
308
+ }
309
+ }
310
+
311
+ const Message = (callbacks) => {
312
+ const subscribers = [];
313
+ return {
314
+ subscribe(fn) {
315
+ subscribers.push(fn);
316
+ },
317
+ publish(...args) {
318
+ subscribers.forEach((fn) => fn(...args));
319
+ callbacks.postPublish?.();
320
+ },
321
+ }
322
+ };
323
+
324
+ const define = (name, configFn) => {
325
+ if (customElements.get(name)) return
326
+
327
+ customElements.define(
328
+ name,
329
+ class extends HTMLElement {
330
+ async connectedCallback() {
331
+ let nextTickSubscribers = [];
332
+ const config = configFn(this);
333
+
334
+ const api = {
335
+ nextTick: (fn) => nextTickSubscribers.push(fn),
336
+ };
337
+
338
+ const message = Message({
339
+ postPublish: () => {
340
+ nextTickSubscribers.forEach((fn) => fn(state));
341
+ nextTickSubscribers = [];
342
+ },
343
+ });
344
+
345
+ const observed = new Set();
346
+ const host = this;
347
+
348
+ const wrap = (state) => {
349
+ return new Proxy(state, {
350
+ get(_, name) {
351
+ if (observed.has(name) === false) {
352
+ Object.defineProperty(host, name, {
353
+ get() {
354
+ return getState()[name]
355
+ },
356
+ set(value) {
357
+ merge({ [name]: value });
358
+ },
359
+ });
360
+
361
+ observed.add(name);
362
+ }
363
+ return Reflect.get(...arguments)
364
+ },
365
+ })
366
+ };
367
+
368
+ const onChangeCallback = (state) => {
369
+ message.publish(wrap(state), config);
370
+ };
371
+
372
+ const store = Store({
373
+ ...config,
374
+ api,
375
+ onChangeCallback,
376
+ });
377
+
378
+ const { getState, merge } = store;
379
+
380
+ const initialState = initialise(
381
+ this,
382
+ message.subscribe,
383
+ config,
384
+ store,
385
+ ((state) => (typeof state === "function" ? state({}) : state))(
386
+ config.state || {}
387
+ )
388
+ );
389
+
390
+ store.set(initialState);
391
+ onChangeCallback(store.getState());
392
+
393
+ const sa = this.setAttribute;
394
+ this.setAttribute = (name, value) => {
395
+ if (observed.has(name)) {
396
+ merge({ [name]: value });
397
+ }
398
+ return sa.apply(this, [name, value])
399
+ };
400
+ const ra = this.removeAttribute;
401
+ this.removeAttribute = (name) => {
402
+ if (observed.has(name)) {
403
+ merge({ [name]: null });
404
+ }
405
+ return ra.apply(this, [name])
406
+ };
407
+
408
+ config.connectedCallback?.(this, store);
409
+ }
410
+ }
411
+ );
412
+ };
413
+
414
+ export { define };
@@ -0,0 +1 @@
1
+ function t(t){return"string"==typeof t&&t.length?isNaN(t)?t:+t:t}const e=t=>null===t||"object"!=typeof t;function n(t){const e=(new DOMParser).parseFromString(t.trim(),"text/html",{includeShadowRoots:!0});if(!e.querySelector("parsererror"))return e.head.firstChild||e.body.firstChild}function r(t,e){return[...t.children].filter((t=>t.matches(e)))}function i(e){return e.map((e=>{return{id:e.id,...(n=e.dataset,Object.fromEntries(Object.entries(n).map((([e,n])=>[e,t(n)]))))};var n}))}const o=t=>t.replace(/[\w]-([\w])/g,(function(t){return t[0]+t[2].toUpperCase()})),s=(t={})=>Object.entries(t).reduce(((t,[e,n])=>(n&&t.push(e),t)),[]).join(" ");function c(t,c,l,a,u={}){const f={},{elements:h=[]}=l;h.filter((({input:t})=>t)).forEach((({select:e,input:n})=>{[...t.querySelectorAll(e)].forEach((t=>{u={...u,[n]:t.value},f.input=f.input||[],f.input.push({select:e,callback:t=>{const{target:e}=t;a.merge({[n]:e.value})}})}))})),h.forEach((t=>{const{select:e,on:n}=t;n&&Object.entries(n).forEach((([t,n])=>{f[t]=f[t]||[],f[t].push({select:e,callback:n})}))})),h.filter((({list:t})=>t)).forEach((({select:e,list:n})=>{[...t.querySelectorAll(e)].forEach((t=>{const e=i(r(t,n.select));u[n.from]=e}))})),Object.entries(f).forEach((([e,n])=>{t.addEventListener(e,(e=>{n.filter((({select:t})=>e.target.matches(t))).forEach((({select:n,callback:r})=>{if("function"==typeof r&&r(e,a),"string"==typeof r){const{target:i}=e,o=[...t.querySelectorAll(n)].indexOf(i);a.dispatch(r,{event:e,index:o})}}))}))}));return c((c=>{h.filter((({list:t})=>t)).forEach((({select:e,list:o})=>{[...t.querySelectorAll(e)].forEach((t=>{const e=r(t,o.select);!function(t,e,r,i,o){const s=r.map((({id:t})=>t)),c=i.map((({id:t})=>t));if(s.toString()===c.toString())return;r.filter((t=>void 0===i.find((e=>t.id===e.id)))).forEach((({id:t})=>e.find((e=>e.id===t))?.remove()));const[l,...a]=i;if(!l)return;let u=l&&e.find((t=>t.id===l.id));o||!i.find((t=>!1===r.find((e=>t.id===e.id))))?(u||(u=n(o(l)),e[0]?e[0].before(u):t.append(u)),a.forEach((t=>{let r=e.find((e=>e.id===t.id))||n(o(t));r&&(u.nextElementSibling!==r&&u.after(r),u=r)}))):console.error("Missing template when trying to add items to a list")}(t,e,i(e),c[o.from],o.template)}))})),h.forEach((n=>{const{select:r,attribute:i,input:l}=n;[...t.querySelectorAll(r)].forEach(((t,n)=>{if(i&&((t,n)=>{for(let[r,i]of Object.entries(n||{}))r=r.replace(/[\w]([A-Z])/g,(function(t){return t[0]+"-"+t[1].toLowerCase()})),"textContent"!==r||t.textContent===textContent?("class"===r&&(i=s(i)),"boolean"==typeof i&&(r.startsWith("aria-")?i=""+i:i&&(i="")),!1!==e(i)?i!==t.getAttribute(r)&&("string"==typeof i||"number"==typeof i?t.setAttribute(r,i):t.removeAttribute(r)):t[o(r)]=i):t.textContent=textContent})(t,i(c,n)),l){const e=c[l];t.value!==e&&(t.value=e)}}))}))})),u}function l({action:t={},getState:e=(t=>t),onChangeCallback:n,api:r={}}){let i;const o=function(t){let e;return(...n)=>{e||(e=requestAnimationFrame((()=>{t(...n),e=null})))}}((()=>n(c())));function s(t){i=e({...t})}function c(){return{...i}}return{dispatch:function(e,n){if(e in t){s(t[e](c(),n)),o()}},getState:c,merge:t=>{s({...c(),...t}),o()},set:s,...r}}const a=(t,e)=>{customElements.get(t)||customElements.define(t,class extends HTMLElement{async connectedCallback(){let t=[];const n=e(this),r={nextTick:e=>t.push(e)},i=(t=>{const e=[];return{subscribe(t){e.push(t)},publish(...n){e.forEach((t=>t(...n))),t.postPublish?.()}}})({postPublish:()=>{t.forEach((t=>t(state))),t=[]}}),o=new Set,s=this,a=t=>{i.publish((t=>new Proxy(t,{get(t,e){return!1===o.has(e)&&(Object.defineProperty(s,e,{get:()=>f()[e],set(t){h({[e]:t})}}),o.add(e)),Reflect.get(...arguments)}}))(t),n)},u=l({...n,api:r,onChangeCallback:a}),{getState:f,merge:h}=u,p=c(this,i.subscribe,n,u,(t=>"function"==typeof t?t({}):t)(n.state||{}));u.set(p),a(u.getState());const d=this.setAttribute;this.setAttribute=(t,e)=>(o.has(t)&&h({[t]:e}),d.apply(this,[t,e]));const b=this.removeAttribute;this.removeAttribute=t=>(o.has(t)&&h({[t]:null}),b.apply(this,[t])),n.connectedCallback?.(this,u)}})};export{a as define};
package/package.json CHANGED
@@ -1,28 +1,33 @@
1
1
  {
2
2
  "name": "mosaic",
3
3
  "type": "module",
4
- "version": "1.0.20",
5
- "description": "",
6
- "main": "src/index.js",
4
+ "version": "1.1.0",
5
+ "description": "A JavaScript library for progressive enhancing HTML",
6
+ "main": "dist/mosaic.min.js",
7
+ "browser": "dist/mosaic.min.js",
8
+ "unpkg": "dist/mosaic.min.js",
9
+ "module": "src/index.js",
7
10
  "scripts": {
8
- "test": "echo \"Error: no test specified\" && exit 1"
11
+ "test": "mocha-express --coverage",
12
+ "test:watch": "mocha-express --watch",
13
+ "size": "gzip -c9 ./dist/mosaic.min.js | wc -c",
14
+ "build": "rm -rf dist && rollup -c && npm run size",
15
+ "prepublish": "npm run build"
9
16
  },
10
17
  "keywords": [],
11
- "author": "defx",
18
+ "author": "",
12
19
  "license": "MIT",
13
- "dependencies": {
14
- "customelementincludes": "^1.0.2",
15
- "express": "^4.18.2",
16
- "fs-extra": "^11.1.0",
17
- "globby": "^13.1.3",
18
- "highlight.js": "^11.7.0",
19
- "markdown-it": "^13.0.1",
20
- "nodemon": "^2.0.20"
21
- },
22
- "bin": {
23
- "mosaic": "./src/index.js"
24
- },
25
20
  "files": [
26
- "src/"
27
- ]
21
+ "src",
22
+ "dist",
23
+ "cjs"
24
+ ],
25
+ "directories": {
26
+ "test": "test"
27
+ },
28
+ "devDependencies": {
29
+ "mocha-express": "^0.1.2",
30
+ "rollup": "^2.79.1",
31
+ "rollup-plugin-terser": "^7.0.2"
32
+ }
28
33
  }
package/src/define.js ADDED
@@ -0,0 +1,93 @@
1
+ import { initialise } from "./initialise.js"
2
+ import { Store } from "./store.js"
3
+ import { Message } from "./message.js"
4
+
5
+ export const define = (name, configFn) => {
6
+ if (customElements.get(name)) return
7
+
8
+ customElements.define(
9
+ name,
10
+ class extends HTMLElement {
11
+ async connectedCallback() {
12
+ let nextTickSubscribers = []
13
+ const config = configFn(this)
14
+
15
+ const api = {
16
+ nextTick: (fn) => nextTickSubscribers.push(fn),
17
+ }
18
+
19
+ const message = Message({
20
+ postPublish: () => {
21
+ nextTickSubscribers.forEach((fn) => fn(state))
22
+ nextTickSubscribers = []
23
+ },
24
+ })
25
+
26
+ const observed = new Set()
27
+ const host = this
28
+
29
+ const wrap = (state) => {
30
+ return new Proxy(state, {
31
+ get(_, name) {
32
+ if (observed.has(name) === false) {
33
+ Object.defineProperty(host, name, {
34
+ get() {
35
+ return getState()[name]
36
+ },
37
+ set(value) {
38
+ merge({ [name]: value })
39
+ },
40
+ })
41
+
42
+ observed.add(name)
43
+ }
44
+ return Reflect.get(...arguments)
45
+ },
46
+ })
47
+ }
48
+
49
+ const onChangeCallback = (state) => {
50
+ message.publish(wrap(state), config)
51
+ }
52
+
53
+ const store = Store({
54
+ ...config,
55
+ api,
56
+ onChangeCallback,
57
+ })
58
+
59
+ const { getState, merge } = store
60
+
61
+ const initialState = initialise(
62
+ this,
63
+ message.subscribe,
64
+ config,
65
+ store,
66
+ ((state) => (typeof state === "function" ? state({}) : state))(
67
+ config.state || {}
68
+ )
69
+ )
70
+
71
+ store.set(initialState)
72
+ onChangeCallback(store.getState())
73
+
74
+ const sa = this.setAttribute
75
+ this.setAttribute = (name, value) => {
76
+ if (observed.has(name)) {
77
+ merge({ [name]: value })
78
+ }
79
+ return sa.apply(this, [name, value])
80
+ }
81
+ const ra = this.removeAttribute
82
+ this.removeAttribute = (name) => {
83
+ if (observed.has(name)) {
84
+ merge({ [name]: null })
85
+ }
86
+ return ra.apply(this, [name])
87
+ }
88
+
89
+ config.connectedCallback?.(this, store)
90
+ }
91
+ }
92
+ )
93
+ }
package/src/helpers.js ADDED
@@ -0,0 +1,54 @@
1
+ export const last = (v = []) => v[v.length - 1]
2
+
3
+ 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
+
10
+ if (!isWhitespace(node)) {
11
+ let v = callback(node)
12
+ if (v === false) return
13
+ if (v?.nodeName) return walk(v, callback, deep)
14
+ }
15
+ if (deep) walk(node.firstChild, callback, deep)
16
+ walk(node.nextSibling, callback, deep)
17
+ }
18
+
19
+ export const serializable = (o) => JSON.parse(JSON.stringify(o))
20
+
21
+ export function cast(v) {
22
+ if (typeof v === "string" && v.length) {
23
+ return isNaN(v) ? v : +v
24
+ }
25
+ return v
26
+ }
27
+
28
+ export function castAll(o) {
29
+ return Object.fromEntries(Object.entries(o).map(([k, v]) => [k, cast(v)]))
30
+ }
31
+
32
+ export const isPrimitive = (v) => v === null || typeof v !== "object"
33
+
34
+ export const typeOf = (v) =>
35
+ Object.prototype.toString.call(v).match(/\s(.+[^\]])/)[1]
36
+
37
+ export const findIndex = (node, query) => {
38
+ const collection = [...rootNode.querySelectorAll(query)]
39
+ return collection.findIndex((n) => n === node)
40
+ }
41
+
42
+ export function nodeFromString(str) {
43
+ const doc = new DOMParser().parseFromString(str.trim(), "text/html", {
44
+ includeShadowRoots: true, // @todo: required?
45
+ })
46
+
47
+ const errorNode = doc.querySelector("parsererror")
48
+
49
+ if (errorNode) {
50
+ // @todo ...
51
+ } else {
52
+ return doc.head.firstChild || doc.body.firstChild
53
+ }
54
+ }