mosaic 2.0.0 → 2.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
@@ -31,11 +31,11 @@ const controller = Mosaic(root, {
31
31
  increment: (state, amount: number) => ({ ...state, count: state.count + amount }),
32
32
  reset: (state) => ({ ...state, count: 0 }),
33
33
  },
34
- elements: [
35
- { select: "[data-increment]", on: { click: ({ dispatch }) => dispatch("increment", 1) } },
36
- { select: "[data-reset]", on: { click: "reset" } },
37
- { select: "output", text: ({ state }) => state.count },
38
- ],
34
+ elements: {
35
+ "[data-increment]": { on: { click: ({ dispatch }) => dispatch("increment", 1) } },
36
+ "[data-reset]": { on: { click: "reset" } },
37
+ output: { text: ({ state }) => state.count },
38
+ },
39
39
  });
40
40
 
41
41
  await controller.dispatch("increment", 2);
@@ -55,10 +55,15 @@ are optional. Reducers receive `(state, payload)`, run synchronously, and return
55
55
  complete next state. State and action payload types are inferred from the config;
56
56
  annotate payload parameters in TypeScript.
57
57
 
58
- Each binding's `select` is an ordinary CSS selector. It binds **all matching
58
+ `elements` is an object whose keys are ordinary CSS selectors and whose values
59
+ describe the bindings. It is optional; an empty object is also valid. Each selector binds **all matching
59
60
  descendants** of the root, excluding the root itself. Use `:scope > button` for
60
61
  direct children. Empty match sets are valid. Invalid CSS selectors throw at mount.
61
62
 
63
+ Only own enumerable string keys are processed, in JavaScript `Object.entries()`
64
+ order (declaration order for ordinary CSS selector keys). Computed keys work too:
65
+ `elements: { [selector]: { text: ({ state }) => state.label } }`.
66
+
62
67
  Matches are captured once, in document order. Later insertions, reordering, and
63
68
  selector changes do not alter that collection or its indexes. Create the required
64
69
  nodes before mounting. Destroy and remount an enhancement when its binding
@@ -68,6 +73,25 @@ An optional configuration callback, `getState(state)`, transforms the complete
68
73
  state at initialization and after each write. It must be synchronous and return
69
74
  the complete state. Read current state through the controller's `getState()`.
70
75
 
76
+ ### Migrating from array bindings
77
+
78
+ Move each binding's `select` value to an object key and remove `select`:
79
+
80
+ ```ts
81
+ // Before
82
+ elements: [{ select: "output", text: ({ state }) => state.count }]
83
+
84
+ // After
85
+ elements: { output: { text: ({ state }) => state.count } }
86
+ ```
87
+
88
+ The array format is no longer supported and throws a `TypeError`, including for
89
+ empty arrays. Each selector key has one binding. Consolidate repeated selectors
90
+ into one binding, composing callbacks when necessary. Distinct selectors may still
91
+ match the same element and are processed independently in object-entry order.
92
+ When composing maps with object spread, later entries for the same selector
93
+ replace the entire earlier binding; handlers and rendering callbacks are not merged.
94
+
71
95
  ## Rendering
72
96
 
73
97
  Rendering callbacks receive `{ state, element, index }`. `element` is the bound
@@ -80,16 +104,17 @@ element and `index` is its position in the captured collection for that binding.
80
104
  | `class` | Map of class names to booleans | Toggles only returned class names |
81
105
 
82
106
  ```ts
83
- {
84
- select: "button",
85
- attribute: ({ state }) => ({
86
- "aria-expanded": String(state.open),
87
- "data-status": state.status,
88
- disabled: state.busy,
89
- tabindex: 0,
90
- }),
91
- text: ({ state }) => state.label,
92
- class: ({ state }) => ({ active: state.open }),
107
+ elements: {
108
+ button: {
109
+ attribute: ({ state }) => ({
110
+ "aria-expanded": String(state.open),
111
+ "data-status": state.status,
112
+ disabled: state.busy,
113
+ tabindex: 0,
114
+ }),
115
+ text: ({ state }) => state.label,
116
+ class: ({ state }) => ({ active: state.open }),
117
+ },
93
118
  }
94
119
  ```
95
120
 
@@ -121,7 +146,7 @@ const config = {
121
146
  actions: {
122
147
  choose: (state: { selected: number }, { index }: { index: number }) => ({ ...state, selected: index }),
123
148
  },
124
- elements: [{ select: "button", on: { click: "choose" } }],
149
+ elements: { button: { on: { click: "choose" } } },
125
150
  };
126
151
  ```
127
152
 
@@ -148,10 +173,10 @@ from user input requires no action or event handler:
148
173
  ```ts
149
174
  const controller = Mosaic(root, {
150
175
  state: { query: "", enabled: false },
151
- elements: [
152
- { select: "input.search", sync: "query" },
153
- { select: 'input[type="checkbox"]', sync: "enabled" },
154
- ],
176
+ elements: {
177
+ "input.search": { sync: "query" },
178
+ 'input[type="checkbox"]': { sync: "enabled" },
179
+ },
155
180
  });
156
181
  ```
157
182
 
@@ -163,7 +188,7 @@ inputs, and multi-selects cause a mount error.
163
188
 
164
189
  At mount, the DOM wins over configured state. When controls share a key, the first
165
190
  bound control supplies its initial value and the rest mirror it. Binding order
166
- follows the `elements` array, then document order within each binding. Keys with
191
+ follows the `elements` object's entry order, then document order within each binding. Keys with
167
192
  no matching controls retain their configured state. Multiple checkboxes sharing a
168
193
  key mirror one boolean; they do not collect an array of selected values. Mixing
169
194
  checkbox and string-value controls on the same key causes a mount error.
@@ -177,10 +202,11 @@ Add `on.input` only when you want additional behaviour, such as filtering
177
202
  suggestions. The handler sees state that `sync` has already updated:
178
203
 
179
204
  ```ts
180
- {
181
- select: "input.search",
182
- sync: "query",
183
- on: { input: ({ dispatch }) => dispatch("filterSuggestions") },
205
+ elements: {
206
+ "input.search": {
207
+ sync: "query",
208
+ on: { input: ({ dispatch }) => dispatch("filterSuggestions") },
209
+ },
184
210
  }
185
211
  ```
186
212
 
package/dist/mosaic.js CHANGED
@@ -25,9 +25,12 @@ function writeClasses(node, classes) {
25
25
  function initialise(rootNode, config, store) {
26
26
  const { controller } = store;
27
27
  let state = config.state ?? {};
28
- const elements = (config.elements ?? []).map((binding) => ({
28
+ if (Array.isArray(config.elements)) {
29
+ throw new TypeError("elements must be a selector-keyed object, not an array; move each select property to an object key");
30
+ }
31
+ const elements = Object.entries(config.elements ?? {}).map(([selector, binding]) => ({
29
32
  ...binding,
30
- targets: [...rootNode.querySelectorAll(binding.select)],
33
+ targets: [...rootNode.querySelectorAll(selector)],
31
34
  }));
32
35
  function listen(target, type, callback) {
33
36
  target.addEventListener(type, callback);
@@ -1 +1 @@
1
- function t(t,e){for(const[n,r]of Object.entries(e??{}))if(!1===r||null==r)t.hasAttribute(n)&&t.removeAttribute(n);else{const e=!0===r?"":String(r);t.getAttribute(n)!==e&&t.setAttribute(n,e)}}function e(t,e){const n=null==e?"":String(e);t.textContent!==n&&(t.textContent=n)}function n(t,e){for(const[n,r]of Object.entries(e??{}))t.classList.toggle(n,r)}function r(t){const e=t.localName,n=t;if("http://www.w3.org/1999/xhtml"===t.namespaceURI){if("input"===e&&"checkbox"===n.type)return{kind:"boolean",read:()=>n.checked,write:t=>{n.checked!==t&&(n.checked=t)}};if("textarea"===e||"select"===e&&!t.multiple||"input"===e&&!["radio","file"].includes(n.type)){const e=t;return{kind:"string",read:()=>e.value,write:t=>{e.value!==t&&(e.value=t)}}}}throw new TypeError("sync requires a checkbox, string-valued input, textarea, or single-select control")}function o({actions:t={},getState:e=t=>t}){let n,r,o=null,s=[],c=[],i=!1;const a=[],l=()=>new DOMException("Mosaic has been destroyed","AbortError"),u=(()=>{const t=new Set;return{clear(){t.clear()},subscribe(e){const n={callback:e};return t.add(n),()=>{t.delete(n)}},publish(...e){const n=[];for(const r of[...t])if(t.has(r))try{r.callback(...e)}catch(t){n.push(t)}return n}}})();function f(t){n=e({...t})}function d(){return{...n}}function h(){i||null!==o||(o=requestAnimationFrame(p))}function p(){if(o=null,i)return;const t=s;s=[],c=t;const e=d(),n=[];try{r(e)}catch(t){n.push(t)}if(i||n.push(...u.publish(e)),c=[],!i)if(n.length){const e=1===n.length?n[0]:new AggregateError(n,"Errors while publishing a state update");t.forEach(({reject:t})=>t(e)),0===t.length&&reportError(e)}else t.forEach(({resolve:t})=>t())}return{controller:{dispatch:(e,...n)=>{try{if(i)throw l();if(!Object.hasOwn(t,e))throw new Error(`Unknown action "${e}"`);if("function"!=typeof t[e])throw new TypeError(`Action "${e}" is not a function`);const r=t[e].call(t,d(),n[0]);if(i)throw l();return f(r),new Promise((t,e)=>{s.push({resolve:t,reject:e}),h()})}catch(t){return Promise.reject(t)}},getState:d,subscribe:t=>i?()=>{}:u.subscribe(t),destroy(){if(i)return;i=!0,null!==o&&cancelAnimationFrame(o),o=null;const t=l();[...c,...s].forEach(({reject:e})=>e(t)),c=[],s=[],u.clear(),a.splice(0).forEach(t=>t()),r=()=>{}}},own:t=>{a.push(t)},isDestroyed:()=>i,initialise:(t,e)=>{f(t),r=e,r(d())},patch:t=>{i||(f({...d(),...t}),h())}}}const s=(s,c)=>{const i=o({...c});try{!function(o,s,c){const{controller:i}=c;let a=s.state??{};const l=(s.elements??[]).map(t=>({...t,targets:[...o.querySelectorAll(t.select)]}));function u(t,e,n){t.addEventListener(e,n),c.own(()=>t.removeEventListener(e,n))}function f(t){t&&t.catch(t=>{c.isDestroyed()&&t instanceof DOMException&&"AbortError"===t.name||reportError(t)})}const d=new Map,h=new WeakMap,p=new WeakSet;for(const t of l){const{sync:e}=t;if(void 0!==e)for(const n of t.targets){const t=r(n);h.set(n,t);const o=d.get(e);if(void 0!==o&&o!==t.kind)throw new TypeError(`sync key "${e}" cannot mix checkbox and string controls`);void 0===o&&(a={...a,[e]:t.read()},d.set(e,t.kind));const s=()=>{const n=t.read();i.getState()[e]!==n&&c.patch({[e]:n})};"boolean"===t.kind?(u(n,"input",s),u(n,"change",s)):(u(n,"compositionstart",()=>{p.add(n)}),u(n,"input",t=>{t.isComposing&&p.add(n),s()}),u(n,"compositionend",()=>{p.delete(n),s()}))}}for(const t of l)t.targets.forEach((e,n)=>{for(const[r,o]of Object.entries(t.on??{}))o&&u(e,r,t=>{if(c.isDestroyed())return;const r={state:i.getState(),element:e,index:n,event:t,dispatch:i.dispatch,getState:i.getState};f("string"==typeof o?(0,i.dispatch)(o,r):o(r))})});c.initialise(a,r=>{for(const{targets:o,attribute:s,text:i,class:a,sync:u}of l)for(const[l,f]of o.entries()){if(c.isDestroyed())return;if(s){const e=s({state:r,element:f,index:l});if(c.isDestroyed())return;t(f,e)}if(i){const t=i({state:r,element:f,index:l});if(c.isDestroyed())return;e(f,t)}if(a){const t=a({state:r,element:f,index:l});if(c.isDestroyed())return;n(f,t)}void 0===u||p.has(f)||h.get(f).write(r[u])}})}(s,c,i)}catch(t){throw i.controller.destroy(),t}return i.controller},c=s;export{c as $,s as Mosaic};
1
+ function t(t,e){for(const[n,r]of Object.entries(e??{}))if(!1===r||null==r)t.hasAttribute(n)&&t.removeAttribute(n);else{const e=!0===r?"":String(r);t.getAttribute(n)!==e&&t.setAttribute(n,e)}}function e(t,e){const n=null==e?"":String(e);t.textContent!==n&&(t.textContent=n)}function n(t,e){for(const[n,r]of Object.entries(e??{}))t.classList.toggle(n,r)}function r(t){const e=t.localName,n=t;if("http://www.w3.org/1999/xhtml"===t.namespaceURI){if("input"===e&&"checkbox"===n.type)return{kind:"boolean",read:()=>n.checked,write:t=>{n.checked!==t&&(n.checked=t)}};if("textarea"===e||"select"===e&&!t.multiple||"input"===e&&!["radio","file"].includes(n.type)){const e=t;return{kind:"string",read:()=>e.value,write:t=>{e.value!==t&&(e.value=t)}}}}throw new TypeError("sync requires a checkbox, string-valued input, textarea, or single-select control")}function o({actions:t={},getState:e=t=>t}){let n,r,o=null,s=[],c=[],i=!1;const a=[],l=()=>new DOMException("Mosaic has been destroyed","AbortError"),u=(()=>{const t=new Set;return{clear(){t.clear()},subscribe(e){const n={callback:e};return t.add(n),()=>{t.delete(n)}},publish(...e){const n=[];for(const r of[...t])if(t.has(r))try{r.callback(...e)}catch(t){n.push(t)}return n}}})();function f(t){n=e({...t})}function d(){return{...n}}function h(){i||null!==o||(o=requestAnimationFrame(p))}function p(){if(o=null,i)return;const t=s;s=[],c=t;const e=d(),n=[];try{r(e)}catch(t){n.push(t)}if(i||n.push(...u.publish(e)),c=[],!i)if(n.length){const e=1===n.length?n[0]:new AggregateError(n,"Errors while publishing a state update");t.forEach(({reject:t})=>t(e)),0===t.length&&reportError(e)}else t.forEach(({resolve:t})=>t())}return{controller:{dispatch:(e,...n)=>{try{if(i)throw l();if(!Object.hasOwn(t,e))throw new Error(`Unknown action "${e}"`);if("function"!=typeof t[e])throw new TypeError(`Action "${e}" is not a function`);const r=t[e].call(t,d(),n[0]);if(i)throw l();return f(r),new Promise((t,e)=>{s.push({resolve:t,reject:e}),h()})}catch(t){return Promise.reject(t)}},getState:d,subscribe:t=>i?()=>{}:u.subscribe(t),destroy(){if(i)return;i=!0,null!==o&&cancelAnimationFrame(o),o=null;const t=l();[...c,...s].forEach(({reject:e})=>e(t)),c=[],s=[],u.clear(),a.splice(0).forEach(t=>t()),r=()=>{}}},own:t=>{a.push(t)},isDestroyed:()=>i,initialise:(t,e)=>{f(t),r=e,r(d())},patch:t=>{i||(f({...d(),...t}),h())}}}const s=(s,c)=>{const i=o({...c});try{!function(o,s,c){const{controller:i}=c;let a=s.state??{};if(Array.isArray(s.elements))throw new TypeError("elements must be a selector-keyed object, not an array; move each select property to an object key");const l=Object.entries(s.elements??{}).map(([t,e])=>({...e,targets:[...o.querySelectorAll(t)]}));function u(t,e,n){t.addEventListener(e,n),c.own(()=>t.removeEventListener(e,n))}function f(t){t&&t.catch(t=>{c.isDestroyed()&&t instanceof DOMException&&"AbortError"===t.name||reportError(t)})}const d=new Map,h=new WeakMap,p=new WeakSet;for(const t of l){const{sync:e}=t;if(void 0!==e)for(const n of t.targets){const t=r(n);h.set(n,t);const o=d.get(e);if(void 0!==o&&o!==t.kind)throw new TypeError(`sync key "${e}" cannot mix checkbox and string controls`);void 0===o&&(a={...a,[e]:t.read()},d.set(e,t.kind));const s=()=>{const n=t.read();i.getState()[e]!==n&&c.patch({[e]:n})};"boolean"===t.kind?(u(n,"input",s),u(n,"change",s)):(u(n,"compositionstart",()=>{p.add(n)}),u(n,"input",t=>{t.isComposing&&p.add(n),s()}),u(n,"compositionend",()=>{p.delete(n),s()}))}}for(const t of l)t.targets.forEach((e,n)=>{for(const[r,o]of Object.entries(t.on??{}))o&&u(e,r,t=>{if(c.isDestroyed())return;const r={state:i.getState(),element:e,index:n,event:t,dispatch:i.dispatch,getState:i.getState};f("string"==typeof o?(0,i.dispatch)(o,r):o(r))})});c.initialise(a,r=>{for(const{targets:o,attribute:s,text:i,class:a,sync:u}of l)for(const[l,f]of o.entries()){if(c.isDestroyed())return;if(s){const e=s({state:r,element:f,index:l});if(c.isDestroyed())return;t(f,e)}if(i){const t=i({state:r,element:f,index:l});if(c.isDestroyed())return;e(f,t)}if(a){const t=a({state:r,element:f,index:l});if(c.isDestroyed())return;n(f,t)}void 0===u||p.has(f)||h.get(f).write(r[u])}})}(s,c,i)}catch(t){throw i.controller.destroy(),t}return i.controller},c=s;export{c as $,s as Mosaic};
@@ -35,7 +35,6 @@ export type EventBindings<State extends object, Actions> = {
35
35
  [Name in keyof Events]?: (keyof Actions & string) | ((context: EventContext<State, Actions, Events[Name]>) => void | Promise<void>);
36
36
  };
37
37
  export interface ElementConfig<State extends object, Actions = {}> {
38
- select: string;
39
38
  attribute?: (context: RenderContext<State>) => Attributes | null | undefined;
40
39
  text?: (context: RenderContext<State>) => TextValue;
41
40
  class?: (context: RenderContext<State>) => Classes | null | undefined;
@@ -48,6 +47,6 @@ export interface StoreConfig<State extends object, Actions extends ActionHandler
48
47
  }
49
48
  export interface MosaicConfig<State extends object, Actions extends ActionHandlers<State> = {}> extends StoreConfig<State, Actions> {
50
49
  state?: State;
51
- elements?: ElementConfig<State, Actions>[];
50
+ elements?: Record<string, ElementConfig<State, Actions>>;
52
51
  }
53
52
  export {};
package/package.json CHANGED
@@ -1,13 +1,21 @@
1
1
  {
2
2
  "name": "mosaic",
3
3
  "type": "module",
4
- "version": "2.0.0",
4
+ "version": "2.1.0",
5
5
  "description": "A JavaScript library for progressive enhancing HTML",
6
6
  "main": "dist/mosaic.js",
7
7
  "browser": "dist/mosaic.js",
8
8
  "unpkg": "dist/mosaic.min.js",
9
9
  "module": "dist/mosaic.js",
10
10
  "types": "dist/types/index.d.ts",
11
+ "repository": {
12
+ "type": "git",
13
+ "url": "git+https://github.com/defx/mosaic.git"
14
+ },
15
+ "homepage": "https://github.com/defx/mosaic#readme",
16
+ "bugs": {
17
+ "url": "https://github.com/defx/mosaic/issues"
18
+ },
11
19
  "scripts": {
12
20
  "dev": "vite",
13
21
  "typecheck": "tsc --noEmit",