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/README.md CHANGED
@@ -1,7 +1,70 @@
1
- # mosaic
1
+ # Mosaic
2
2
 
3
- 🚧 This library is currently under construction and not ready for public use 🚧
3
+ ## Codify UI behaviour with declarative configuration
4
4
 
5
- ## [![npm](https://img.shields.io/npm/v/mosaic.svg)](http://npm.im/mosaic) [![Build Status](https://travis-ci.com/defx/mosaic.svg?branch=master)](https://travis-ci.com/defx/mosaic) [![Coverage Status](https://coveralls.io/repos/github/defx/mosaic/badge.svg?branch=master)](https://coveralls.io/github/defx/mosaic?branch=master) [![gzip size](https://img.badgesize.io/https://unpkg.com/mosaic/dist/mosaic.min.js?compression=gzip&label=gzip)]()
5
+ 🚧 Please kindly note that this project is a work in progress 🚧
6
6
 
7
- Mosaic is CLI for building web sites and apps with Synergy components
7
+ [![npm](https://shields.io/npm/v/mosaic)](https://www.npmjs.com/package/mosaic)
8
+ [![gzip size](https://img.badgesize.io/https://unpkg.com/mosaic/dist/mosaic.min.js?compression=gzip&label=gzip)](https://unpkg.com/mosaic/dist/mosaic.min.js)
9
+
10
+ Mosaic's declarative configuration enables common UI behaviours to be reused effectively between different projects, ensuring a high level of performance and accessibility, whilst allowing developers to concentrate on the things that are particular to their specific business and project requirements: the markup and styles.
11
+
12
+ ## Example
13
+
14
+ The following configuration implements the Accordion pattern:
15
+
16
+ ```js
17
+ let counter = 0
18
+
19
+ export const Accordion = () => {
20
+ const id = counter++
21
+ return {
22
+ state: {
23
+ openPanel: 0,
24
+ },
25
+ action: {
26
+ togglePanel: (state, { index }) => ({
27
+ ...state,
28
+ openPanel: state.openPanel === index ? -1 : index,
29
+ }),
30
+ },
31
+ elements: [
32
+ {
33
+ select: "button[accordion-toggle]",
34
+ attribute: (state, i) => ({
35
+ id: `trigger_${id}_${i}`,
36
+ ariaControls: `panel_${id}_${i}`,
37
+ ariaExpanded: state.openPanel === i,
38
+ }),
39
+ on: {
40
+ click: "togglePanel",
41
+ },
42
+ },
43
+ {
44
+ select: "[accordion-panel]",
45
+ attribute: (state, i) => ({
46
+ id: `panel_${id}_${i}`,
47
+ ariaLabelledby: `trigger_${id}_${i}`,
48
+ hidden: state.openPanel !== i,
49
+ }),
50
+ },
51
+ ],
52
+ }
53
+ }
54
+ ```
55
+
56
+ ## Install
57
+
58
+ ### cdn
59
+
60
+ ```js
61
+ import { define } from "https://unpkg.com/mosaic"
62
+ ```
63
+
64
+ ### npm
65
+
66
+ ```sh
67
+ > npm i mosaic
68
+ ```
69
+
70
+ ## Usage
package/cjs/define.js ADDED
@@ -0,0 +1,99 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ var initialise = require('./initialise.js');
6
+ var store = require('./store.js');
7
+ var message = require('./message.js');
8
+
9
+ const define = (name, configFn) => {
10
+ if (customElements.get(name)) return
11
+
12
+ customElements.define(
13
+ name,
14
+ class extends HTMLElement {
15
+ async connectedCallback() {
16
+ let nextTickSubscribers = [];
17
+ const config = configFn(this);
18
+
19
+ const api = {
20
+ nextTick: (fn) => nextTickSubscribers.push(fn),
21
+ };
22
+
23
+ const message$1 = message.Message({
24
+ postPublish: () => {
25
+ nextTickSubscribers.forEach((fn) => fn(state));
26
+ nextTickSubscribers = [];
27
+ },
28
+ });
29
+
30
+ const observed = new Set();
31
+ const host = this;
32
+
33
+ const wrap = (state) => {
34
+ return new Proxy(state, {
35
+ get(_, name) {
36
+ if (observed.has(name) === false) {
37
+ Object.defineProperty(host, name, {
38
+ get() {
39
+ return getState()[name]
40
+ },
41
+ set(value) {
42
+ merge({ [name]: value });
43
+ },
44
+ });
45
+
46
+ observed.add(name);
47
+ }
48
+ return Reflect.get(...arguments)
49
+ },
50
+ })
51
+ };
52
+
53
+ const onChangeCallback = (state) => {
54
+ message$1.publish(wrap(state), config);
55
+ };
56
+
57
+ const store$1 = store.Store({
58
+ ...config,
59
+ api,
60
+ onChangeCallback,
61
+ });
62
+
63
+ const { getState, merge } = store$1;
64
+
65
+ const initialState = initialise.initialise(
66
+ this,
67
+ message$1.subscribe,
68
+ config,
69
+ store$1,
70
+ ((state) => (typeof state === "function" ? state({}) : state))(
71
+ config.state || {}
72
+ )
73
+ );
74
+
75
+ store$1.set(initialState);
76
+ onChangeCallback(store$1.getState());
77
+
78
+ const sa = this.setAttribute;
79
+ this.setAttribute = (name, value) => {
80
+ if (observed.has(name)) {
81
+ merge({ [name]: value });
82
+ }
83
+ return sa.apply(this, [name, value])
84
+ };
85
+ const ra = this.removeAttribute;
86
+ this.removeAttribute = (name) => {
87
+ if (observed.has(name)) {
88
+ merge({ [name]: null });
89
+ }
90
+ return ra.apply(this, [name])
91
+ };
92
+
93
+ config.connectedCallback?.(this, store$1);
94
+ }
95
+ }
96
+ );
97
+ };
98
+
99
+ exports.define = define;
package/cjs/helpers.js ADDED
@@ -0,0 +1,33 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ function cast(v) {
6
+ if (typeof v === "string" && v.length) {
7
+ return isNaN(v) ? v : +v
8
+ }
9
+ return v
10
+ }
11
+
12
+ function castAll(o) {
13
+ return Object.fromEntries(Object.entries(o).map(([k, v]) => [k, cast(v)]))
14
+ }
15
+
16
+ const isPrimitive = (v) => v === null || typeof v !== "object";
17
+
18
+ function nodeFromString(str) {
19
+ const doc = new DOMParser().parseFromString(str.trim(), "text/html", {
20
+ includeShadowRoots: true, // @todo: required?
21
+ });
22
+
23
+ const errorNode = doc.querySelector("parsererror");
24
+
25
+ if (errorNode) ; else {
26
+ return doc.head.firstChild || doc.body.firstChild
27
+ }
28
+ }
29
+
30
+ exports.cast = cast;
31
+ exports.castAll = castAll;
32
+ exports.isPrimitive = isPrimitive;
33
+ exports.nodeFromString = nodeFromString;
@@ -0,0 +1,118 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ var list = require('./list.js');
6
+ var xo = require('./xo.js');
7
+
8
+ function initialise(rootNode, subscribe, config, store, state = {}) {
9
+ const event = {};
10
+
11
+ const { elements = [] } = config;
12
+
13
+ // derive initial state from input directives...
14
+ elements
15
+ .filter(({ input }) => input)
16
+ .forEach(({ select, input }) => {
17
+ const targets = [...rootNode.querySelectorAll(select)];
18
+ targets.forEach((target) => {
19
+ state = { ...state, [input]: target.value };
20
+
21
+ event.input = event.input || [];
22
+ event.input.push({
23
+ select,
24
+ callback: (event) => {
25
+ const { target } = event;
26
+ store.merge({ [input]: target.value });
27
+ },
28
+ });
29
+ });
30
+ });
31
+
32
+ // find event listeners
33
+ elements.forEach((c) => {
34
+ const { select, on } = c;
35
+ if (on) {
36
+ Object.entries(on).forEach(([type, callback]) => {
37
+ event[type] = event[type] || [];
38
+ event[type].push({
39
+ select,
40
+ callback,
41
+ });
42
+ });
43
+ }
44
+ });
45
+
46
+ //derive initial state from lists...
47
+ elements
48
+ .filter(({ list }) => list)
49
+ .forEach(({ select, list: list$1 }) => {
50
+ const targets = [...rootNode.querySelectorAll(select)];
51
+ targets.forEach((target) => {
52
+ const items = list.listItems(target, list$1.select);
53
+ const curr = list.listData(items);
54
+ state[list$1.from] = curr;
55
+ });
56
+ });
57
+
58
+ // delegate from the root node
59
+ Object.entries(event).forEach(([type, listeners]) => {
60
+ rootNode.addEventListener(type, (e) => {
61
+ listeners
62
+ .filter(({ select }) => e.target.matches(select))
63
+ .forEach(({ select, callback }) => {
64
+ if (typeof callback === "function") {
65
+ callback(e, store);
66
+ }
67
+ if (typeof callback === "string") {
68
+ const { target } = e;
69
+
70
+ const targets = [...rootNode.querySelectorAll(select)];
71
+
72
+ const index = targets.indexOf(target);
73
+
74
+ store.dispatch(callback, { event: e, index });
75
+ }
76
+ });
77
+ });
78
+ });
79
+
80
+ const onChange = (state) => {
81
+ // lists first
82
+ elements
83
+ .filter(({ list }) => list)
84
+ .forEach(({ select, list: list$1 }) => {
85
+ const targets = [...rootNode.querySelectorAll(select)];
86
+ targets.forEach((target) => {
87
+ const items = list.listItems(target, list$1.select);
88
+ const curr = list.listData(items);
89
+ const next = state[list$1.from];
90
+ list.listSync(target, items, curr, next, list$1.template);
91
+ });
92
+ });
93
+
94
+ // then the rest...
95
+ elements.forEach((c) => {
96
+ const { select, attribute, input } = c;
97
+
98
+ const targets = [...rootNode.querySelectorAll(select)];
99
+
100
+ targets.forEach((target, i) => {
101
+ if (attribute) {
102
+ xo.write(target, attribute(state, i));
103
+ }
104
+ if (input) {
105
+ const value = state[input];
106
+
107
+ if (target.value !== value) target.value = value;
108
+ }
109
+ });
110
+ });
111
+ };
112
+
113
+ subscribe(onChange);
114
+
115
+ return state
116
+ }
117
+
118
+ exports.initialise = initialise;
package/cjs/list.js ADDED
@@ -0,0 +1,76 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ var helpers = require('./helpers.js');
6
+
7
+ function listItems(listContainerNode, listItemSelector) {
8
+ return [...listContainerNode.children].filter((node) =>
9
+ node.matches(listItemSelector)
10
+ )
11
+ }
12
+
13
+ function listData(listItems) {
14
+ return listItems.map((node) => ({
15
+ id: node.id,
16
+ ...helpers.castAll(node.dataset),
17
+ }))
18
+ }
19
+
20
+ function listSync(parentNode, nodes, curr, next, template) {
21
+ // check if anything has changed
22
+ const currIds = curr.map(({ id }) => id);
23
+ const nextIds = next.map(({ id }) => id);
24
+
25
+ if (currIds.toString() === nextIds.toString()) return
26
+
27
+ // removals
28
+ curr
29
+ .filter((c) => {
30
+ return next.find((n) => c.id === n.id) === undefined
31
+ })
32
+ .forEach(({ id }) => nodes.find((node) => node.id === id)?.remove());
33
+
34
+ const [first, ...rest] = next;
35
+
36
+ if (!first) return
37
+
38
+ let t = first && nodes.find((node) => node.id === first.id);
39
+
40
+ if (
41
+ !template &&
42
+ next.find((c) => {
43
+ return curr.find((n) => c.id === n.id) === false
44
+ })
45
+ ) {
46
+ console.error(`Missing template when trying to add items to a list`);
47
+ return
48
+ }
49
+
50
+ if (!t) {
51
+ t = helpers.nodeFromString(template(first));
52
+
53
+ if (nodes[0]) {
54
+ nodes[0].before(t);
55
+ } else {
56
+ parentNode.append(t);
57
+ }
58
+ }
59
+
60
+ rest.forEach((d) => {
61
+ let node =
62
+ nodes.find((node) => node.id === d.id) || helpers.nodeFromString(template(d));
63
+
64
+ if (node) {
65
+ if (t.nextElementSibling !== node) {
66
+ // is t.after already a no-op in this case?
67
+ t.after(node);
68
+ }
69
+ t = node;
70
+ }
71
+ });
72
+ }
73
+
74
+ exports.listData = listData;
75
+ exports.listItems = listItems;
76
+ exports.listSync = listSync;
package/cjs/message.js ADDED
@@ -0,0 +1,18 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ const Message = (callbacks) => {
6
+ const subscribers = [];
7
+ return {
8
+ subscribe(fn) {
9
+ subscribers.push(fn);
10
+ },
11
+ publish(...args) {
12
+ subscribers.forEach((fn) => fn(...args));
13
+ callbacks.postPublish?.();
14
+ },
15
+ }
16
+ };
17
+
18
+ exports.Message = Message;
package/cjs/store.js ADDED
@@ -0,0 +1,55 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ function debounce(fn) {
6
+ let id;
7
+ return (...args) => {
8
+ if (!id) {
9
+ id = requestAnimationFrame(() => {
10
+ fn(...args);
11
+ id = null;
12
+ });
13
+ }
14
+ }
15
+ }
16
+
17
+ function Store({
18
+ action: actionHandlers = {},
19
+ getState: getStateWrapper = (v) => v,
20
+ onChangeCallback,
21
+ api = {},
22
+ }) {
23
+ let state;
24
+
25
+ const transition = debounce(() => onChangeCallback(getState()));
26
+
27
+ function set(o) {
28
+ state = getStateWrapper({ ...o });
29
+ }
30
+
31
+ function getState() {
32
+ return { ...state }
33
+ }
34
+
35
+ function dispatch(type, action) {
36
+ if (type in actionHandlers) {
37
+ const x = actionHandlers[type](getState(), action);
38
+ set(x);
39
+ transition();
40
+ }
41
+ }
42
+
43
+ return {
44
+ dispatch,
45
+ getState,
46
+ merge: (o) => {
47
+ set({ ...getState(), ...o });
48
+ transition();
49
+ },
50
+ set,
51
+ ...api,
52
+ }
53
+ }
54
+
55
+ exports.Store = Store;
package/cjs/xo.js ADDED
@@ -0,0 +1,66 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ var helpers = require('./helpers.js');
6
+
7
+ const pascalToKebab = (string) =>
8
+ string.replace(/[\w]([A-Z])/g, function (m) {
9
+ return m[0] + "-" + m[1].toLowerCase()
10
+ });
11
+
12
+ const kebabToPascal = (string) =>
13
+ string.replace(/[\w]-([\w])/g, function (m) {
14
+ return m[0] + m[2].toUpperCase()
15
+ });
16
+
17
+ const objectToClasses = (v = {}) => {
18
+ return Object.entries(v)
19
+ .reduce((c, [k, v]) => {
20
+ if (v) c.push(k);
21
+ return c
22
+ }, [])
23
+ .join(" ")
24
+ };
25
+
26
+ const write = (node, attrs) => {
27
+ for (let [k, v] of Object.entries(attrs || {})) {
28
+ k = pascalToKebab(k);
29
+
30
+ if (k === "textContent" && node.textContent !== textContent) {
31
+ node.textContent = textContent;
32
+ continue
33
+ }
34
+
35
+ if (k === "class") {
36
+ v = objectToClasses(v);
37
+ }
38
+
39
+ if (typeof v === "boolean") {
40
+ if (k.startsWith("aria-")) {
41
+ v = "" + v;
42
+ } else if (v) {
43
+ v = "";
44
+ }
45
+ }
46
+
47
+ if (helpers.isPrimitive(v) === false) {
48
+ node[kebabToPascal(k)] = v;
49
+ continue
50
+ }
51
+
52
+ let current = node.getAttribute(k);
53
+
54
+ if (v === current) continue
55
+
56
+ if (typeof v === "string" || typeof v === "number") {
57
+ node.setAttribute(k, v);
58
+ } else {
59
+ node.removeAttribute(k);
60
+ }
61
+ }
62
+ return node
63
+ };
64
+
65
+ exports.objectToClasses = objectToClasses;
66
+ exports.write = write;