mosaic 1.1.0 → 2.0.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,70 +1,252 @@
1
1
  # Mosaic
2
2
 
3
- ## Codify UI behaviour with declarative configuration
4
-
5
- 🚧 Please kindly note that this project is a work in progress 🚧
6
-
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
- }
3
+ Mosaic adds state-driven behaviour to existing HTML. Describe actions and DOM
4
+ bindings in a configuration, then mount it on an element. The application owns
5
+ the markup and the enhancement's lifetime.
6
+
7
+ ## Install and use
8
+
9
+ ```sh
10
+ npm install mosaic
11
+ ```
12
+
13
+ The package provides ESM JavaScript and TypeScript declarations. The example below
14
+ uses TypeScript; omit parameter type annotations in JavaScript.
15
+
16
+ ```html
17
+ <div id="counter">
18
+ <button type="button" data-increment>Add one</button>
19
+ <button type="button" data-reset>Reset</button>
20
+ <output aria-live="polite"></output>
21
+ </div>
22
+ ```
23
+
24
+ ```ts
25
+ import { Mosaic } from "mosaic";
26
+
27
+ const root = document.querySelector("#counter")!;
28
+ const controller = Mosaic(root, {
29
+ state: { count: 0 },
30
+ actions: {
31
+ increment: (state, amount: number) => ({ ...state, count: state.count + amount }),
32
+ reset: (state) => ({ ...state, count: 0 }),
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
+ ],
39
+ });
40
+
41
+ await controller.dispatch("increment", 2);
42
+ console.log(controller.getState().count); // 2, with the DOM updated
43
+
44
+ // When the application removes this enhancement:
45
+ controller.destroy();
46
+ ```
47
+
48
+ `$` is an alias of `Mosaic`. A minified ESM entry is available at
49
+ `mosaic/dist/mosaic.min.js`, including for use through an ESM-compatible CDN.
50
+
51
+ ## Configuration and selectors
52
+
53
+ `Mosaic(root, { state, actions, elements })` returns a controller. State and actions
54
+ are optional. Reducers receive `(state, payload)`, run synchronously, and return the
55
+ complete next state. State and action payload types are inferred from the config;
56
+ annotate payload parameters in TypeScript.
57
+
58
+ Each binding's `select` is an ordinary CSS selector. It binds **all matching
59
+ descendants** of the root, excluding the root itself. Use `:scope > button` for
60
+ direct children. Empty match sets are valid. Invalid CSS selectors throw at mount.
61
+
62
+ Matches are captured once, in document order. Later insertions, reordering, and
63
+ selector changes do not alter that collection or its indexes. Create the required
64
+ nodes before mounting. Destroy and remount an enhancement when its binding
65
+ collection needs to change.
66
+
67
+ An optional configuration callback, `getState(state)`, transforms the complete
68
+ state at initialization and after each write. It must be synchronous and return
69
+ the complete state. Read current state through the controller's `getState()`.
70
+
71
+ ## Rendering
72
+
73
+ Rendering callbacks receive `{ state, element, index }`. `element` is the bound
74
+ element and `index` is its position in the captured collection for that binding.
75
+
76
+ | Field | Callback result | Effect |
77
+ | --- | --- | --- |
78
+ | `attribute` | Map of exact DOM attribute names to values | Sets or removes the returned attributes |
79
+ | `text` | String, number, boolean, `null`, or `undefined` | Writes plain text content |
80
+ | `class` | Map of class names to booleans | Toggles only returned class names |
81
+
82
+ ```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 }),
53
93
  }
54
94
  ```
55
95
 
56
- ## Install
96
+ Attribute names pass directly to the DOM: use `"aria-expanded"`, `tabindex`, or
97
+ `viewBox` as appropriate. Strings and numbers set values; `true` adds an empty
98
+ presence attribute; `false`, `null`, and `undefined` remove it. String-valued
99
+ booleans stay explicit strings, so use `"false"` for an ARIA false state.
100
+ Omitted attributes remain untouched.
101
+
102
+ `text` treats nullish results as empty text and replaces existing content,
103
+ including child elements. It writes text rather than parsing HTML.
104
+
105
+ `class` preserves unrelated classes. Names omitted from later callback results
106
+ also remain untouched; return `false` explicitly to remove a class. Nullish class
107
+ or attribute maps leave the element unchanged.
108
+
109
+ ## Events
110
+
111
+ `on` maps DOM event names to callbacks or action names. Event callbacks receive
112
+ `{ state, element, index, event, dispatch, getState }`. `element` is the bound
113
+ element; `event.target` can be a descendant. `state` is a snapshot taken when the
114
+ listener runs, while `getState()` reads the latest committed state.
115
+
116
+ An action-name shorthand forwards the event context as its payload:
117
+
118
+ ```ts
119
+ const config = {
120
+ state: { selected: -1 },
121
+ actions: {
122
+ choose: (state: { selected: number }, { index }: { index: number }) => ({ ...state, selected: index }),
123
+ },
124
+ elements: [{ select: "button", on: { click: "choose" } }],
125
+ };
126
+ ```
127
+
128
+ Listeners attach directly to the matched elements, including for non-bubbling
129
+ events such as `focus`. Normal DOM propagation applies: overlapping bindings and
130
+ nested enhancements can both handle a bubbling event. Selectors can also match
131
+ controls inside nested components. Choose selectors and propagation controls to
132
+ suit the application; Mosaic does not isolate nested bindings.
133
+
134
+ Handle root-level, document, and window events in consumer code. For example,
135
+ a document listener can check `root.contains(event.target)` before dispatching an
136
+ outside-dismissal action. Remove that listener in the application's cleanup.
137
+
138
+ Async event callbacks can await dispatches or perform application work. Rejected
139
+ handler promises are reported through the browser's `reportError`; dispatch
140
+ cancellations caused by destruction are ignored. Reducers and subscribers remain
141
+ synchronous contracts.
57
142
 
58
- ### cdn
143
+ ## Two-way values with sync
59
144
 
60
- ```js
61
- import { define } from "https://unpkg.com/mosaic"
145
+ `sync` automatically keeps a control and a state field in sync. Updating state
146
+ from user input requires no action or event handler:
147
+
148
+ ```ts
149
+ const controller = Mosaic(root, {
150
+ state: { query: "", enabled: false },
151
+ elements: [
152
+ { select: "input.search", sync: "query" },
153
+ { select: 'input[type="checkbox"]', sync: "enabled" },
154
+ ],
155
+ });
62
156
  ```
63
157
 
64
- ### npm
158
+ Typing updates `query`; checking or unchecking the checkbox updates `enabled`.
159
+ String-valued inputs, textareas, and single-select controls use `.value` and require
160
+ string state fields. Checkboxes use `.checked` and require boolean state fields.
161
+ Checkbox `.value` and `.indeterminate` are left untouched. Radio buttons, file
162
+ inputs, and multi-selects cause a mount error.
163
+
164
+ At mount, the DOM wins over configured state. When controls share a key, the first
165
+ 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
167
+ no matching controls retain their configured state. Multiple checkboxes sharing a
168
+ key mirror one boolean; they do not collect an array of selected values. Mixing
169
+ checkbox and string-value controls on the same key causes a mount error.
170
+
171
+ String controls update state on `input`; checkboxes update on both `input` and
172
+ `change`. Sync runs before consumer handlers for those events. Actions can also
173
+ update control values or checked states on the next render. Equal values are left
174
+ untouched to avoid redundant assignments and preserve cursor position.
175
+
176
+ Add `on.input` only when you want additional behaviour, such as filtering
177
+ suggestions. The handler sees state that `sync` has already updated:
178
+
179
+ ```ts
180
+ {
181
+ select: "input.search",
182
+ sync: "query",
183
+ on: { input: ({ dispatch }) => dispatch("filterSuggestions") },
184
+ }
185
+ ```
186
+
187
+ Here `filterSuggestions` reads the current query from its reducer's state; it does
188
+ not need to copy the input value into state. Checkbox `on.change` handlers likewise
189
+ see the current boolean.
190
+
191
+ During IME composition, input events continue updating state, but Mosaic leaves
192
+ the composing string control's value untouched. Other controls sharing the key can
193
+ still update. On composition end, the final DOM value is committed and mirrored.
194
+ Numeric coercion, array-valued checkbox groups, radio groups, and automatic
195
+ form-reset handling belong in consumer code.
196
+
197
+ ## State, completion, and cleanup
198
+
199
+ | Controller method | Contract |
200
+ | --- | --- |
201
+ | `dispatch(name, payload)` | Commits state synchronously; returns a promise for the batch's DOM update and subscriber notifications |
202
+ | `getState()` | Returns a shallow snapshot of current state |
203
+ | `subscribe(callback)` | Registers a synchronous callback and returns an idempotent unsubscribe function |
204
+ | `destroy()` | Removes owned listeners/subscriptions and cancels pending rendering |
205
+
206
+ Several actions before the next animation frame share one render of their final
207
+ state. Rendering precedes subscriber notifications. Awaiting dispatch observes the
208
+ updated DOM; it does not wait for browser paint. Actions dispatched during
209
+ publication commit immediately and render in a later frame with their own promises.
210
+
211
+ Subscriptions start with the next publication. New subscriptions created during
212
+ publication start on the following batch; removals take effect immediately.
213
+ Async subscriber work is not awaited. State snapshots are shallow: update nested
214
+ objects and arrays immutably so changes pass through actions and publication.
215
+
216
+ Unknown actions and reducer errors reject dispatch. Render or subscriber errors
217
+ reject every dispatch in the affected batch; remaining subscribers still run.
218
+ Multiple publication errors become an `AggregateError`. State stays committed,
219
+ and failed rendering can leave partially updated DOM. Later updates can recover.
220
+ Sync-only batches have no dispatch promise, so errors are reported using the
221
+ browser's `reportError`.
222
+
223
+ Destroy is idempotent and leaves the current DOM content in place. Pending and
224
+ subsequent dispatches reject with `AbortError`; `getState()` remains readable.
225
+ Subscribing after destruction returns a no-op unsubscribe function. The same nodes
226
+ can be mounted again. The application must clean up its own timers, listeners,
227
+ and asynchronous work and destroy enhancements before removing a route or region.
228
+
229
+ ## Examples and development
230
+
231
+ The repository includes an [accordion](examples/accordion/README.md),
232
+ [tabs](examples/tabs/README.md), and a [combobox](examples/combobox/README.md).
233
+ These are application examples with their own markup contracts.
234
+
235
+ Use Node.js 22.12+, 24, or 26+ for development tooling:
65
236
 
66
237
  ```sh
67
- > npm i mosaic
238
+ npm ci
239
+ npm run test:install-browsers
240
+ npm test
241
+ npm run test:all
242
+ npm run typecheck
243
+ npm run test:package
68
244
  ```
69
245
 
70
- ## Usage
246
+ - `npm run dev` serves [the examples](http://localhost:1983/examples/) through Vite.
247
+ - `npm test` runs Vitest Browser Mode in headless Chromium; `test:all` also runs Firefox and WebKit.
248
+ - `npm run test:watch` watches Chromium tests. Add `-- --browser.headless=false` to see the browser.
249
+ - `npm run test:coverage` writes Chromium source coverage to `coverage/index.html`.
250
+ - `npm run build` checks types and generates ESM bundles and declarations in `dist`.
251
+ - `npm run test:package` builds and packs locally, installs into a temporary consumer, checks ESM and type resolution, and runs browser consumption checks. It does not publish.
252
+ - `npm pack` builds the package through `prepack`. Publishing is a separate manual action.
package/dist/mosaic.js ADDED
@@ -0,0 +1,332 @@
1
+ function write(node, attributes) {
2
+ for (const [name, value] of Object.entries(attributes ?? {})) {
3
+ if (value === false || value == null) {
4
+ if (node.hasAttribute(name))
5
+ node.removeAttribute(name);
6
+ }
7
+ else {
8
+ const text = value === true ? "" : String(value);
9
+ if (node.getAttribute(name) !== text)
10
+ node.setAttribute(name, text);
11
+ }
12
+ }
13
+ }
14
+ function writeText(node, value) {
15
+ const text = value == null ? "" : String(value);
16
+ if (node.textContent !== text)
17
+ node.textContent = text;
18
+ }
19
+ function writeClasses(node, classes) {
20
+ for (const [name, enabled] of Object.entries(classes ?? {})) {
21
+ node.classList.toggle(name, enabled);
22
+ }
23
+ }
24
+
25
+ function initialise(rootNode, config, store) {
26
+ const { controller } = store;
27
+ let state = config.state ?? {};
28
+ const elements = (config.elements ?? []).map((binding) => ({
29
+ ...binding,
30
+ targets: [...rootNode.querySelectorAll(binding.select)],
31
+ }));
32
+ function listen(target, type, callback) {
33
+ target.addEventListener(type, callback);
34
+ store.own(() => target.removeEventListener(type, callback));
35
+ }
36
+ function complete(result) {
37
+ if (!result)
38
+ return;
39
+ void result.catch((error) => {
40
+ if (store.isDestroyed() && error instanceof DOMException && error.name === "AbortError")
41
+ return;
42
+ reportError(error);
43
+ });
44
+ }
45
+ const initialisedKeys = new Map();
46
+ const controls = new WeakMap();
47
+ const composing = new WeakSet();
48
+ // Register sync first so consumer input/change handlers see the current state.
49
+ for (const binding of elements) {
50
+ const { sync } = binding;
51
+ if (sync === undefined)
52
+ continue;
53
+ for (const target of binding.targets) {
54
+ const control = syncControl(target);
55
+ controls.set(target, control);
56
+ const kind = initialisedKeys.get(sync);
57
+ if (kind !== undefined && kind !== control.kind) {
58
+ throw new TypeError(`sync key "${sync}" cannot mix checkbox and string controls`);
59
+ }
60
+ if (kind === undefined) {
61
+ state = { ...state, [sync]: control.read() };
62
+ initialisedKeys.set(sync, control.kind);
63
+ }
64
+ const update = () => {
65
+ const value = control.read();
66
+ if (controller.getState()[sync] !== value) {
67
+ store.patch({ [sync]: value });
68
+ }
69
+ };
70
+ if (control.kind === "boolean") {
71
+ listen(target, "input", update);
72
+ listen(target, "change", update);
73
+ }
74
+ else {
75
+ listen(target, "compositionstart", () => { composing.add(target); });
76
+ listen(target, "input", (event) => {
77
+ if (event.isComposing)
78
+ composing.add(target);
79
+ update();
80
+ });
81
+ listen(target, "compositionend", () => {
82
+ composing.delete(target);
83
+ update();
84
+ });
85
+ }
86
+ }
87
+ }
88
+ for (const binding of elements) {
89
+ binding.targets.forEach((element, index) => {
90
+ for (const [type, callback] of Object.entries(binding.on ?? {})) {
91
+ if (!callback)
92
+ continue;
93
+ listen(element, type, (event) => {
94
+ if (store.isDestroyed())
95
+ return;
96
+ const context = {
97
+ state: controller.getState(), element, index, event,
98
+ dispatch: controller.dispatch, getState: controller.getState,
99
+ };
100
+ if (typeof callback === "string") {
101
+ const dispatch = controller.dispatch;
102
+ complete(dispatch(callback, context));
103
+ }
104
+ else {
105
+ // Each event name retains its specific event type in the public configuration.
106
+ const handler = callback;
107
+ complete(handler(context));
108
+ }
109
+ });
110
+ }
111
+ });
112
+ }
113
+ store.initialise(state, (state) => {
114
+ for (const { targets, attribute, text, class: classes, sync } of elements) {
115
+ for (const [index, target] of targets.entries()) {
116
+ if (store.isDestroyed())
117
+ return;
118
+ if (attribute) {
119
+ const attributes = attribute({ state, element: target, index });
120
+ if (store.isDestroyed())
121
+ return;
122
+ write(target, attributes);
123
+ }
124
+ if (text) {
125
+ const value = text({ state, element: target, index });
126
+ if (store.isDestroyed())
127
+ return;
128
+ writeText(target, value);
129
+ }
130
+ if (classes) {
131
+ const value = classes({ state, element: target, index });
132
+ if (store.isDestroyed())
133
+ return;
134
+ writeClasses(target, value);
135
+ }
136
+ if (sync !== undefined && !composing.has(target)) {
137
+ controls.get(target).write(state[sync]);
138
+ }
139
+ }
140
+ }
141
+ });
142
+ }
143
+ function syncControl(target) {
144
+ const name = target.localName;
145
+ const input = target;
146
+ if (target.namespaceURI === "http://www.w3.org/1999/xhtml") {
147
+ if (name === "input" && input.type === "checkbox") {
148
+ return {
149
+ kind: "boolean",
150
+ read: () => input.checked,
151
+ write: (value) => {
152
+ if (input.checked !== value)
153
+ input.checked = value;
154
+ },
155
+ };
156
+ }
157
+ if (name === "textarea" ||
158
+ (name === "select" && !target.multiple) ||
159
+ (name === "input" && !["radio", "file"].includes(input.type))) {
160
+ const control = target;
161
+ return {
162
+ kind: "string",
163
+ read: () => control.value,
164
+ write: (value) => {
165
+ if (control.value !== value)
166
+ control.value = value;
167
+ },
168
+ };
169
+ }
170
+ }
171
+ throw new TypeError("sync requires a checkbox, string-valued input, textarea, or single-select control");
172
+ }
173
+
174
+ const Message = () => {
175
+ const subscribers = new Set();
176
+ return {
177
+ clear() { subscribers.clear(); },
178
+ subscribe(callback) {
179
+ const subscription = { callback };
180
+ subscribers.add(subscription);
181
+ return () => { subscribers.delete(subscription); };
182
+ },
183
+ publish(...args) {
184
+ const errors = [];
185
+ // New subscriptions start with the next publication; removals take effect immediately.
186
+ for (const subscription of [...subscribers]) {
187
+ if (!subscribers.has(subscription))
188
+ continue;
189
+ try {
190
+ subscription.callback(...args);
191
+ }
192
+ catch (error) {
193
+ errors.push(error);
194
+ }
195
+ }
196
+ return errors;
197
+ },
198
+ };
199
+ };
200
+
201
+ function Store({ actions: actionHandlers = {}, getState: getStateWrapper = (v) => v, }) {
202
+ let state;
203
+ let render;
204
+ let frame = null;
205
+ let pending = [];
206
+ let active = [];
207
+ let destroyed = false;
208
+ const cleanups = [];
209
+ const abort = () => new DOMException("Mosaic has been destroyed", "AbortError");
210
+ const message = Message();
211
+ function commit(next) {
212
+ state = getStateWrapper({ ...next });
213
+ }
214
+ function getState() {
215
+ return { ...state };
216
+ }
217
+ function schedule() {
218
+ if (!destroyed && frame === null)
219
+ frame = requestAnimationFrame(flush);
220
+ }
221
+ function flush() {
222
+ frame = null;
223
+ if (destroyed)
224
+ return;
225
+ const completions = pending;
226
+ pending = [];
227
+ active = completions;
228
+ const snapshot = getState();
229
+ const errors = [];
230
+ try {
231
+ render(snapshot);
232
+ }
233
+ catch (error) {
234
+ errors.push(error);
235
+ }
236
+ if (!destroyed)
237
+ errors.push(...message.publish(snapshot));
238
+ active = [];
239
+ if (destroyed)
240
+ return;
241
+ if (errors.length) {
242
+ const error = errors.length === 1
243
+ ? errors[0]
244
+ : new AggregateError(errors, "Errors while publishing a state update");
245
+ completions.forEach(({ reject }) => reject(error));
246
+ // Sync bindings can schedule a frame without a dispatch promise to reject.
247
+ if (completions.length === 0)
248
+ reportError(error);
249
+ }
250
+ else {
251
+ completions.forEach(({ resolve }) => resolve());
252
+ }
253
+ }
254
+ const dispatch = (type, ...payload) => {
255
+ try {
256
+ if (destroyed)
257
+ throw abort();
258
+ if (!Object.hasOwn(actionHandlers, type)) {
259
+ throw new Error(`Unknown action "${type}"`);
260
+ }
261
+ if (typeof actionHandlers[type] !== "function") {
262
+ throw new TypeError(`Action "${type}" is not a function`);
263
+ }
264
+ const handler = actionHandlers[type];
265
+ const next = handler.call(actionHandlers, getState(), payload[0]);
266
+ if (destroyed)
267
+ throw abort();
268
+ commit(next);
269
+ return new Promise((resolve, reject) => {
270
+ pending.push({ resolve, reject });
271
+ schedule();
272
+ });
273
+ }
274
+ catch (error) {
275
+ return Promise.reject(error);
276
+ }
277
+ };
278
+ const controller = {
279
+ dispatch,
280
+ getState,
281
+ subscribe: (callback) => destroyed ? () => { } : message.subscribe(callback),
282
+ destroy() {
283
+ if (destroyed)
284
+ return;
285
+ destroyed = true;
286
+ if (frame !== null)
287
+ cancelAnimationFrame(frame);
288
+ frame = null;
289
+ const error = abort();
290
+ const completions = [...active, ...pending];
291
+ completions.forEach(({ reject }) => reject(error));
292
+ active = [];
293
+ pending = [];
294
+ message.clear();
295
+ cleanups.splice(0).forEach((cleanup) => cleanup());
296
+ render = () => { };
297
+ },
298
+ };
299
+ return {
300
+ controller,
301
+ own: (cleanup) => { cleanups.push(cleanup); },
302
+ isDestroyed: () => destroyed,
303
+ initialise: (initial, onChange) => {
304
+ commit(initial);
305
+ render = onChange;
306
+ render(getState());
307
+ },
308
+ patch: (patch) => {
309
+ if (destroyed)
310
+ return;
311
+ commit({ ...getState(), ...patch });
312
+ schedule();
313
+ },
314
+ };
315
+ }
316
+
317
+ const Mosaic = (rootNode, config) => {
318
+ const store = Store({
319
+ ...config,
320
+ });
321
+ try {
322
+ initialise(rootNode, config, store);
323
+ }
324
+ catch (error) {
325
+ store.controller.destroy();
326
+ throw error;
327
+ }
328
+ return store.controller;
329
+ };
330
+ const $ = Mosaic;
331
+
332
+ export { $, Mosaic };
@@ -0,0 +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};
@@ -0,0 +1,4 @@
1
+ import type { ActionHandlers, Controller, MosaicConfig } from "./types.js";
2
+ export type { ActionHandlers, RenderContext, EventContext, Attributes, AttributeValue, Classes, TextValue, Controller, Dispatch, ElementConfig, EventBindings, MosaicConfig, StoreConfig, StringKey, SyncKey, } from "./types.js";
3
+ export declare const Mosaic: <State extends object = Record<string, never>, Actions extends ActionHandlers<State> = {}>(rootNode: Element, config: MosaicConfig<State, Actions>) => Controller<State, Actions>;
4
+ export declare const $: typeof Mosaic;
@@ -0,0 +1,3 @@
1
+ import type { StateStore } from "./store.js";
2
+ import type { ActionHandlers, MosaicConfig } from "./types.js";
3
+ export declare function initialise<State extends object, Actions extends ActionHandlers<State>>(rootNode: Element, config: MosaicConfig<State, Actions>, store: StateStore<State, Actions>): void;
@@ -0,0 +1,5 @@
1
+ export declare const Message: <Args extends unknown[]>() => {
2
+ clear(): void;
3
+ subscribe(callback: (...args: Args) => void): () => void;
4
+ publish(...args: Args): unknown[];
5
+ };
@@ -0,0 +1,9 @@
1
+ import type { ActionHandlers, Controller, StoreConfig } from "./types.js";
2
+ export interface StateStore<State extends object, Actions> {
3
+ controller: Controller<State, Actions>;
4
+ initialise(state: State, render: (state: State) => void): void;
5
+ patch(state: Partial<State>): void;
6
+ own(cleanup: () => void): void;
7
+ isDestroyed(): boolean;
8
+ }
9
+ export declare function Store<State extends object, Actions extends ActionHandlers<State> = {}>({ actions: actionHandlers, getState: getStateWrapper, }: StoreConfig<State, Actions>): StateStore<State, Actions>;