@tltdsh/mx 1.4.1 → 1.5.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/CLAUDE.md CHANGED
@@ -10,19 +10,23 @@ When transferring from React/Vue/Svelte, read [mxjs.dev/what-mx-is-not](https://
10
10
 
11
11
  ## Hard Rules
12
12
 
13
+ Destructuring defaults do not persist into $state. Controlled one-time defaults may be assigned inside $ (for example this.$state.count ??= 0); ordinary updates use this.$({...}) to render.
14
+
15
+ ESM imports provide no API globals. The default types describe those imports. Classic-script TypeScript projects may explicitly reference `@tltdsh/mx/classic` for window API declarations.
16
+
13
17
  | Rule | Do | Don't |
14
18
  |------|----|-------|
15
- | Component definition | `$(props) {}` (method shorthand) | `$: function(props) {}` - legacy |
19
+ | Component definition | `$(props) {}` (method shorthand) | `$: function(props) {}` also works; shorthand is preferred style |
16
20
  | Component name | `define('my-widget', {...})` kebab-case (camelCase also works — auto-converts to kebab) | Mismatched names between define and call site |
17
21
  | Call site | `mx.myWidget()` camelCase | `mx.MyWidget()` - PascalCase gives `-my-widget` (invalid) |
18
- | State updates | `this.$({ key: value })` | `this.$state.key = value` - bypasses the merge, forbidden |
22
+ | State updates | `this.$({ key: value })` | Direct assignment changes state without rendering; use only for controlled initialization |
19
23
  | Empty re-render | Pass actual changed data: `this.$({ key: newValue })` | `this.$({})` with empty object - code smell |
20
24
  | Numbers in render | `mx.span(count)` | `mx.span(String(count))` - auto-casts |
21
25
  | Event names | `onclick` (lowercase) | `onClick` - not React |
22
26
  | Class attribute | `class: 'active'` | `className: 'active'` - not React |
23
27
  | Label for | `for: 'input-id'` | `htmlFor: 'input-id'` - not React |
24
28
  | Inline styles | `style: 'width:' + pct + '%'` | `style: { width: pct + '%' }` - not supported |
25
- | Array children | `mx.ul(...items.map(i => mx.li(i)))` | `mx.ul(items.map(...))` - stringifies to `"1,2,3"` text |
29
+ | Array children | `mx.ul(items.map(i => mx.li(i)))` or `mx.ul(...items.map(i => mx.li(i)))` - both work, arrays flatten, nested ones too | Relying on flattening on mx 1.4.1 or earlier, which stringifies an unspread array to `"li,,1,li,,2"` |
26
30
  | No attrs, just children | `mx.div(child1, child2)` | `mx.div({}, child)` or `mx.div(null, child)` |
27
31
  | Boolean attributes | `disabled: true` sets `disabled="true"` | Expecting it to set a JS property |
28
32
  | First arg type | `mx.div({class: 'x'}, child)` | `mx.div(myMap, child)` - non-plain-Object treated as child |
@@ -32,10 +36,10 @@ When transferring from React/Vue/Svelte, read [mxjs.dev/what-mx-is-not](https://
32
36
  ## Common Mistakes
33
37
 
34
38
  ```js
35
- // ✗ Legacy method syntax
36
- define('foo', { $: function(props) { ... } });
39
+ // Valid function property; method shorthand below is preferred
40
+ define('foo', { $: function(props) { return []; } });
37
41
  // ✓ Method shorthand
38
- define('foo', { $(props) { ... } });
42
+ define('foo', { $(props) { return []; } });
39
43
 
40
44
  // ✗ Mutating $state directly bypasses the declarative flow
41
45
  this.$state.count = 5;
@@ -49,14 +53,9 @@ $() {
49
53
  }
50
54
  // ✓ Pass the actual change
51
55
  $({ items = [] }) {
52
- mx.button({ onclick: () => this.$({ items: [...items, newItem] }) }, 'Add');
56
+ return mx.button({ onclick: () => this.$({ items: [...items, newItem] }) }, 'Add');
53
57
  }
54
58
 
55
- // ✗ Arrays of children stringified to text
56
- mx.ul(items.map(i => mx.li(i.name)))
57
- // ✓ Spread so each li is a child
58
- mx.ul(...items.map(i => mx.li(i.name)))
59
-
60
59
  // ✗ Mutates parent's array
61
60
  assets.sort((a, b) => a.price - b.price);
62
61
  // ✓ Copy first
@@ -114,7 +113,7 @@ if (this.$state.items.length) this.$({ hasItems: true });
114
113
 
115
114
  ## Reserved Tag Names
116
115
 
117
- The internal tag cache is a plain object; it inherits `Object.prototype` methods. Don't use any of these as component names:
116
+ mx keeps two plain-object caches, one for the proxy's tag functions and one for tag names, and both inherit `Object.prototype` methods. Don't use any of these as component names:
118
117
 
119
118
  ```
120
119
  toString, valueOf, constructor, hasOwnProperty, isPrototypeOf,
@@ -122,7 +121,7 @@ propertyIsEnumerable, toLocaleString, __defineGetter__,
122
121
  __defineSetter__, __lookupGetter__, __lookupSetter__, __proto__
123
122
  ```
124
123
 
125
- `mx.toString()` produces a broken description that throws `InvalidCharacterError` at `createElement` time. Also applies to `define('toString', ...)`.
124
+ Property access returns the inherited method instead of a tag function: `mx.toString()` renders the text `"[object Function]"`, and `mx.valueOf()` or `mx.hasOwnProperty()` throw a `TypeError`. The call form `mx('toString')` throws `InvalidCharacterError` at `createElement` time. `define('toString', ...)` registers under the wrong key.
126
125
 
127
126
  Tag/component names only - **attribute** names are safe: the reconciler tracks attrs by own-key checks (`Object.hasOwn`), so `{ toString: 'x' }` sets and removes cleanly, and attrs objects with an own `constructor` key are still recognized as attrs.
128
127
 
@@ -136,7 +135,7 @@ Tag/component names only - **attribute** names are safe: the reconciler tracks a
136
135
  4. Use `this._name` for private caches (Maps, flags, intervals)
137
136
  5. Use `this._name ||= new Map` for persistent references
138
137
  6. Compute derived values once, reuse
139
- 7. Return mx nodes - single element or array
138
+ 7. Return a single mx description or an array (real `dom()` nodes go inside an array)
140
139
  8. Direct property assignment for events on `this`: `this.onclick = handler`
141
140
  9. Callbacks via `onchange?.(value)` or prop check
142
141
  10. Event bus for cross-component communication
@@ -145,7 +144,7 @@ Tag/component names only - **attribute** names are safe: the reconciler tracks a
145
144
  13. `clearInterval(this._interval)` at top of `$()`
146
145
  14. CSS transitions for animations, not JS
147
146
  15. Formatters in render, not in data prep
148
- 16. Never write `this.$state.x = ...` directly - always `this.$({...})`
147
+ 16. Updates use `this.$({...})`; controlled one-time `$state` defaults are valid but direct writes do not render
149
148
  17. Hoist constant arrays/objects out of `$()` - don't re-allocate per render
150
149
  18. Stateful list rows use a keyed `dom()` Map, not positional `mx()` rows
151
150
  19. Drive logic from `$state` / data attributes, never from rendered text
@@ -178,13 +177,21 @@ This is the single most common source of confusion for teams adopting mx. Pick t
178
177
 
179
178
  ---
180
179
 
181
- ## 4 Globals
180
+ ## 4 API Names
181
+
182
+ The classic CDN script exposes `mx`, `dom`, `define`, and `components` on `window`. The ESM build exports them instead and does not create globals:
183
+
184
+ ```js
185
+ import { mx, dom, define, components } from '@tltdsh/mx';
186
+ ```
187
+
188
+ Both builds require a browser DOM. See [Installation](https://mxjs.dev/installation) for script and CDN module URLs.
182
189
 
183
- | Global | Returns | Use for |
190
+ | Name | Returns | Use for |
184
191
  |--------|---------|---------|
185
192
  | `mx.tag(attrs?, ...nodes)` | Array (description) | Inside `render()` - efficient reconciliation |
186
193
  | `dom.tag(attrs?, ...nodes)` | HTMLElement | Persistent references, calling `.$()` later |
187
- | `define(name, { $() {} })` | void | Register a component |
194
+ | `define(name, { $() {} })` | void | Register a component in MX, not `customElements` |
188
195
  | `components` | object | Component registry lookup |
189
196
 
190
197
  Both `mx` and `dom` are Proxies. CamelCase auto-converts to kebab-case (memoized):
@@ -208,7 +215,7 @@ define('greeting', {
208
215
  });
209
216
  ```
210
217
 
211
- When parent calls `el.$({ count: 5 })`, count updates. When the component calls `this.$({ count: count + 1 })`, it self-updates. The destructuring default (`= 0`) applies whenever that key's value is `undefined` in `$state`.
218
+ When the parent calls `el.$({ name: 'Ada' })`, name updates. When the component calls `this.$({ name: next })`, it self-updates. The destructuring default (`= 'World'`) applies whenever that key's value is `undefined` in `$state`.
212
219
 
213
220
  ### The parent always wins the merge
214
221
 
@@ -223,9 +230,10 @@ Because `Object.assign` runs **before** your `$` function, a parent re-passing t
223
230
  | Input | Behavior |
224
231
  |-------|----------|
225
232
  | mx array (`._=true`) | Create/reuse by tag name, apply attrs, recurse children |
233
+ | Plain array (no `._`) | Flattened in place, nested arrays too, its items reconciled as siblings (1.5.0+) |
226
234
  | Real DOM node | Identity-match by reference. Same = no-op, different = move/insert |
227
235
  | String / Number | Create/update text node |
228
- | `null` / `false` | Skipped - use for conditional rendering |
236
+ | `null` / `undefined` / `false` | Skipped - use for conditional rendering |
229
237
 
230
238
  After processing all children, excess old DOM nodes are removed.
231
239
 
@@ -241,17 +249,17 @@ After processing all children, excess old DOM nodes are removed.
241
249
  | `name: true` | `setAttribute(name, 'true')` | `disabled: true` |
242
250
  | `onname: fn` | `el[name] = fn` (property) | `onclick: handler` |
243
251
 
244
- **Dual-track**: `value`, `checked`, `selected` automatically set both attribute AND property.
252
+ **Dual-track (render() only)**: in `render()`, `value`, `checked`, `selected` set both attribute AND property, re-asserted every render. `$attrs()` and `dom.tag(attrs)` only call `setAttribute`/`removeAttribute` for them; use `'.value'` / `'.checked'` / `'.selected'` there to set the property.
245
253
 
246
- **`el.$attrs(obj)`**: Applies attributes to the element using the same rules above. Useful for setting attributes on `this` inside `$()`:
254
+ **`el.$attrs(obj)`**: Applies attributes to the element using the table above, without the render() dual-track. Useful for setting attributes on `this` inside `$()`:
247
255
 
248
256
  ```js
249
257
  this.$attrs({ disabled, class: 'my-component' });
250
258
  ```
251
259
 
252
- Caveats vs `render()`: `$attrs` cannot clear event handlers (it calls `removeAttribute`, which is a no-op for handlers) and does not reset `value`/`checked`/`selected` properties on null. For full cleanup semantics, use `render()` with fresh descriptions. See [mxjs.dev/reference](https://mxjs.dev/reference).
260
+ Caveats vs `render()`: `$attrs` cannot clear event handlers (it calls `removeAttribute`, which is a no-op for handlers), and a plain `value`/`checked`/`selected` only writes the attribute, so after user input the property keeps the user's value. For full cleanup semantics, use `render()` with fresh descriptions. See [mxjs.dev/reference](https://mxjs.dev/reference).
253
261
 
254
- **Handler cleanup**: `render()` keeps a per-element cache of what it last applied; a handler or `.prop` present in render N but absent in render N+1 is nulled from that cache before the children reconcile. You never manually remove handlers.
262
+ **Handler cleanup**: `render()` keeps a per-element cache of what it last applied; a handler or `.prop` present in render N but absent in render N+1 is nulled from that cache before the children reconcile, except `.value`, `.checked` and `.selected`, which keep the user's form state when dropped. You never manually remove handlers.
255
263
 
256
264
  **Custom events**: `on*` attrs only register listeners for spec-known handler properties (`onclick`, `oninput`, ...). A custom event type (`onping: fn`) is a silent expando - use `addEventListener` once (guarded) for custom events.
257
265
 
@@ -332,12 +340,12 @@ let events = (() => {
332
340
 
333
341
  ## Memoization (cache the function, not the component)
334
342
 
335
- Before adding any cache, measure - the reconciler is cheap enough that component-level memoization is usually pointless. When a function is genuinely expensive, put the cache on the function itself:
343
+ Before adding any cache, measure component computation and browser work in the actual application. When a function is genuinely expensive, put the cache on the function itself:
336
344
 
337
345
  ```js
338
346
  function expensiveFormat(arg) {
339
- let c = expensiveFormat.lookup ||= {};
340
- return c[arg] ??= /* actual expensive work */;
347
+ let c = expensiveFormat.lookup ||= Object.create(null);
348
+ return c[arg] ??= new Intl.NumberFormat('en-US').format(arg);
341
349
  }
342
350
  ```
343
351
 
@@ -346,7 +354,7 @@ For object-identity inputs, use a Map (plain objects stringify keys):
346
354
  ```js
347
355
  function expensiveFormat(item) {
348
356
  let c = expensiveFormat.lookup ||= new Map;
349
- if (!c.has(item)) c.set(item, /* expensive work */);
357
+ if (!c.has(item)) c.set(item, JSON.stringify(item));
350
358
  return c.get(item);
351
359
  }
352
360
  ```
@@ -373,6 +381,8 @@ define('counter', {
373
381
 
374
382
  ### Sparkline (stateless, SVG)
375
383
 
384
+ Empty histories render nothing. A singleton produces one finite point; a visible line requires at least two points.
385
+
376
386
  ```js
377
387
  define('sparkline', {
378
388
  $({ history = [], width = 80, height = 24 }) {
@@ -384,7 +394,7 @@ define('sparkline', {
384
394
  let len = history.length;
385
395
 
386
396
  let points = history.map((v, i) =>
387
- (i / (len - 1) * width).toFixed(1) + ',' +
397
+ (i / Math.max(1, len - 1) * width).toFixed(1) + ',' +
388
398
  (height - ((v - min) / range * (height - 2) + 1)).toFixed(1)
389
399
  ).join(' ');
390
400
 
@@ -410,9 +420,10 @@ define('data-table', {
410
420
  });
411
421
 
412
422
  let header = (label, key) =>
413
- mx.th({
414
- onclick: () => this.$({ sortKey: key, sortDir: sortKey === key ? -sortDir : 1 })
415
- }, label, sortKey === key ? (sortDir > 0 ? ' ▲' : ' ▼') : null);
423
+ mx.th({ 'aria-sort': sortKey === key ? (sortDir > 0 ? 'ascending' : 'descending') : 'none' },
424
+ mx.button({
425
+ onclick: () => this.$({ sortKey: key, sortDir: sortKey === key ? -sortDir : 1 })
426
+ }, label, sortKey === key ? (sortDir > 0 ? ' ▲' : ' ▼') : null));
416
427
 
417
428
  return mx.table(
418
429
  mx.thead(mx.tr(header('Name', 'name'), header('Value', 'value'))),
@@ -426,15 +437,17 @@ define('data-table', {
426
437
 
427
438
  ```js
428
439
  define('my-form', {
429
- $({ title = '', saving = false, onsubmit, onclose }) {
440
+ $({ title = '', saving = false, error = '', onsubmit, onclose }) {
430
441
  let submit = async () => {
431
442
  if (!title.trim()) return;
432
- this.$({ saving: true });
433
- await onsubmit?.({ title });
434
- this.$({ saving: false });
443
+ this.$({ saving: true, error: '' });
444
+ try { await onsubmit?.({ title }); }
445
+ catch (error) { this.$({ error: error.message || String(error) }); }
446
+ finally { this.$({ saving: false }); }
435
447
  };
436
448
 
437
449
  return mx.div({ class: 'form' },
450
+ error && mx.p({ role: 'alert' }, error),
438
451
  mx.input({
439
452
  value: title,
440
453
  placeholder: 'Title',
@@ -463,7 +476,7 @@ function toast(message, type = 'info') {
463
476
  }
464
477
  let el = dom.div({ class: 'toast toast-' + type },
465
478
  mx.span(message),
466
- mx.button({ onclick() { el.remove() } }, '×')
479
+ mx.button({ 'aria-label': 'Dismiss', onclick() { el.remove() } }, '×')
467
480
  );
468
481
  toastContainer.append(el);
469
482
  setTimeout(() => el.remove(), 4000);
@@ -475,6 +488,8 @@ toast.error = msg => toast(msg, 'error');
475
488
 
476
489
  ### Timer component (reading latest state)
477
490
 
491
+ Append before the first tick. Detachment stops the interval on its next tick. After remounting, call `player.$({ isPlaying: true })` to rearm; attachment alone does not invoke `$`.
492
+
478
493
  ```js
479
494
  define('player-bar', {
480
495
  $({ track, isPlaying = false, progress = 0 }) {
@@ -483,8 +498,12 @@ define('player-bar', {
483
498
  if (isPlaying && track) {
484
499
  this._interval = setInterval(() => {
485
500
  // Read from $state, NOT the closed-over `progress` (that's stale from render time)
486
- let p = this.$state.progress + 1;
487
- if (p >= this.$state.track.duration) return;
501
+ if (!this.isConnected) { clearInterval(this._interval); return; }
502
+ let p = (this.$state.progress ?? 0) + 1;
503
+ if (p >= this.$state.track.duration) {
504
+ this.$({ progress: this.$state.track.duration, isPlaying: false });
505
+ return;
506
+ }
488
507
  this.$({ progress: p });
489
508
  }, 1000);
490
509
  }
@@ -494,7 +513,7 @@ define('player-bar', {
494
513
  return [
495
514
  mx.div(track.title),
496
515
  mx.div(track.artist),
497
- mx.progressBar({ value: progress, max: track.duration })
516
+ mx.progress({ value: progress, max: track.duration })
498
517
  ];
499
518
  }
500
519
  });
@@ -535,28 +554,39 @@ define('v-c', {
535
554
  ### Lazy-loaded async component
536
555
 
537
556
  ```js
557
+ // Integration contract: loadLibrary resolves a CodeMirror-compatible factory.
558
+ // Owner calls mount() after append and dispose() before every removal.
538
559
  define('code-editor', {
539
- $({ value = '', disabled, onChange }) {
540
- let me = this;
541
- me.$attrs({ disabled });
542
-
543
- if (!me._initialized) {
544
- me._initialized = true;
545
- me._container = dom.div();
546
-
547
- loadLibrary('codemirror').then(() => {
548
- me.$editor = CodeMirror(me._container, { lineNumbers: true });
549
- me.$editor.on('change', () => onChange?.(me.$editor.getValue()));
550
- me.$editor.setValue(value);
551
- });
560
+ $({ value = '', disabled = false }) {
561
+ this._container ||= dom.div();
562
+ this.$editor?.setOption('readOnly', disabled);
563
+ if (this.$editor && this.$editor.getValue() !== value)
564
+ this.$editor.setValue(value);
565
+ return [this._container];
566
+ },
567
+ async mount() {
568
+ if (!this.isConnected) throw new Error('Append before mount()');
569
+ if (this.$editor || this._loading) return;
570
+ let token = this._loading = {};
571
+ try {
572
+ let CodeMirror = await loadLibrary('codemirror');
573
+ if (this._loading !== token || !this.isConnected) return;
574
+ let { value = '', disabled = false } = this.$state;
575
+ this.$editor = CodeMirror(this._container, { lineNumbers: true, readOnly: disabled, value });
576
+ this.$editor.on('change', () => this.$state.onChange?.(this.$editor.getValue()));
577
+ } finally {
578
+ if (this._loading === token) this._loading = null;
552
579
  }
553
-
554
- if (me.$editor && me.$editor.getValue() !== value)
555
- me.$editor.setValue(value);
556
-
557
- return [me._container];
580
+ },
581
+ dispose() {
582
+ this._loading = null; // invalidates pending initialization
583
+ this.$editor?.destroy(); // adapter must release editor subscriptions and DOM
584
+ this.$editor = null;
558
585
  }
559
586
  });
587
+ // Owner handles load errors: await editor.mount() inside try/catch.
588
+ // Removal: editor.dispose(); editor.remove();
589
+ // Remount: append editor, then await editor.mount().
560
590
  ```
561
591
 
562
592
  ### Debounced search
package/README.md CHANGED
@@ -1,6 +1,11 @@
1
1
  # mx.js
2
2
 
3
- Sub-1KB reactive DOM reconciliation engine for building massive platforms and user interfaces at scale. **Under 1KB** brotli. 4 globals, zero dependencies, no virtual DOM, no build step. Small enough to fit in an AI context window.
3
+ [![npm](https://img.shields.io/npm/v/@tltdsh/mx)](https://www.npmjs.com/package/@tltdsh/mx)
4
+ [![size](https://deno.bundlejs.com/badge?q=@tltdsh/mx)](https://bundlejs.com/?q=@tltdsh/mx)
5
+ [![brotli](https://img.shields.io/badge/brotli-926_B-blue)](https://mxjs.dev)
6
+ [![license](https://img.shields.io/npm/l/@tltdsh/mx)](https://opensource.org/license/0bsd)
7
+
8
+ A DOM reconciliation engine for building user interfaces in plain JavaScript, from a single widget to a large platform. It is **under 1KB** with brotli, has four API names and no dependencies, and needs no virtual DOM or build step, so the whole library fits in an AI context window.
4
9
 
5
10
  **Full documentation & live playground: [mxjs.dev](https://mxjs.dev)**
6
11
 
@@ -21,7 +26,7 @@ Sub-1KB reactive DOM reconciliation engine for building massive platforms and us
21
26
  ### Pinned version
22
27
 
23
28
  ```html
24
- <script src="https://cdn.jsdelivr.net/npm/@tltdsh/mx@1.4.1/mx.min.js"></script>
29
+ <script src="https://cdn.jsdelivr.net/npm/@tltdsh/mx@1.5.0/mx.min.js"></script>
25
30
  ```
26
31
 
27
32
  ### npm / yarn / bun
@@ -42,17 +47,19 @@ import { mx, dom, define, components } from '@tltdsh/mx'
42
47
  const { mx, dom, define, components } = await import('https://cdn.jsdelivr.net/npm/@tltdsh/mx/mx.mjs')
43
48
  ```
44
49
 
45
- Works in any modern browser, with or without a bundler - no install, one line. Browser runtimes only: the module reads `document` at evaluation time, so importing it under Node, Deno, or Bun throws `ReferenceError: document is not defined`.
50
+ The CDN import works in any modern browser without a bundler or an install. It needs a browser, though: the module reads `document` when it loads, so importing it under Node, Deno or Bun throws `ReferenceError: document is not defined`.
46
51
 
47
- ## 4 Globals
52
+ ## 4 API bindings
48
53
 
49
- | Global | Returns | Use for |
54
+ | Binding | Returns | Use for |
50
55
  |--------|---------|---------|
51
56
  | `mx.tag(attrs?, ...children)` | Description array | Inside `render()` - efficient reconciliation |
52
57
  | `dom.tag(attrs?, ...children)` | HTMLElement | Persistent references, calling `.$()` later |
53
58
  | `define(name, { $() {} })` | void | Register a component |
54
59
  | `components` | object | Component registry |
55
60
 
61
+ Classic scripts expose these names as globals. ESM exposes named exports, so use the import above in each module that needs them. The following browser examples assume the library is loaded and the document body exists.
62
+
56
63
  CamelCase auto-converts to kebab-case: `mx.priceChart()` → `<price-chart>`.
57
64
 
58
65
  ## Quick start
@@ -75,6 +82,8 @@ document.body.render(mx.counter({ count: 10 }))
75
82
 
76
83
  ### SVG sparkline
77
84
 
85
+ Empty histories render nothing. A singleton produces one finite point at the left edge (a line needs at least two points to be visible).
86
+
78
87
  ```js
79
88
  define('sparkline', {
80
89
  $({ history = [], width = 80, height = 24 }) {
@@ -82,7 +91,7 @@ define('sparkline', {
82
91
  let min = Math.min(...history), max = Math.max(...history)
83
92
  let range = max - min || 1
84
93
  let points = history.map((v, i) =>
85
- (i / (history.length - 1) * width).toFixed(1) + ',' +
94
+ (i / Math.max(1, history.length - 1) * width).toFixed(1) + ',' +
86
95
  (height - ((v - min) / range * (height - 2) + 1)).toFixed(1)
87
96
  ).join(' ')
88
97
  return mx.svg({ viewBox: '0 0 ' + width + ' ' + height, width, height, fill: 'none' },
@@ -102,8 +111,10 @@ define('data-table', {
102
111
  return sortDir * (typeof va === 'string' ? va.localeCompare(vb) : va - vb)
103
112
  })
104
113
  let header = (label, key) =>
105
- mx.th({ onclick: _ => this.$({ sortKey: key, sortDir: sortKey === key ? -sortDir : 1 }) },
106
- label, sortKey === key ? (sortDir > 0 ? ' ▲' : ' ▼') : null
114
+ mx.th({ 'aria-sort': sortKey === key ? (sortDir > 0 ? 'ascending' : 'descending') : 'none' },
115
+ mx.button({ onclick: _ => this.$({ sortKey: key, sortDir: sortKey === key ? -sortDir : 1 }) },
116
+ label, sortKey === key ? (sortDir > 0 ? ' ▲' : ' ▼') : null
117
+ )
107
118
  )
108
119
  return mx.table(
109
120
  mx.thead(mx.tr(header('Name', 'name'), header('Value', 'value'))),
@@ -115,6 +126,8 @@ define('data-table', {
115
126
 
116
127
  ### Keyed list with persistent DOM
117
128
 
129
+ Integration example: define a `drink-row` component accepting `{ drink, onremove }` before creating this component.
130
+
118
131
  ```js
119
132
  define('drink-builder', {
120
133
  $({ drinks = [], onadd, onremove }) {
@@ -148,7 +161,7 @@ function toast(message, type = 'info') {
148
161
  }
149
162
  let el = dom.div({ class: 'toast toast-' + type },
150
163
  mx.span(message),
151
- mx.button({ onclick() { el.remove() } }, '×')
164
+ mx.button({ 'aria-label': 'Dismiss', onclick() { el.remove() } }, '×')
152
165
  )
153
166
  toastContainer.append(el)
154
167
  setTimeout(_ => el.remove(), 4000)
@@ -164,10 +177,11 @@ toast.error = msg => toast(msg, 'error')
164
177
 
165
178
  - `mx.*()` descriptions → create/reuse elements by tag, apply attrs, recurse
166
179
  - Real DOM nodes → identity-match by reference (keyed lists)
167
- - Strings / numbers → text nodes (auto-cast, no `String()` needed)
168
- - `null` / `false` → skipped (conditional rendering)
180
+ - Strings / numbers → text nodes (auto-cast, no `String()` needed). `true` renders as the text "true"
181
+ - Plain arrays (an unspread `.map()` result) → flattened, nested arrays too (1.5.0 and later, while 1.4.1 and earlier render them as text)
182
+ - `null` / `undefined` / `false` → skipped (conditional rendering)
169
183
 
170
- Excess old nodes are removed. That's it.
184
+ Excess old nodes are removed.
171
185
 
172
186
  ## Attributes
173
187
 
@@ -179,11 +193,11 @@ mx.button({ disabled: null }) // removeAttribute
179
193
  mx.button({ onclick: handler }) // el.onclick = handler (auto-cleaned)
180
194
  ```
181
195
 
182
- `value`, `checked`, `selected` set both attribute and property automatically.
196
+ In `render()`, `value`, `checked` and `selected` set both the attribute and the property, and every render sets them again. `dom.tag(attrs)` and `$attrs()` only set the attribute, so use `'.value'` there when you mean the property.
183
197
 
184
198
  ## Keyed lists
185
199
 
186
- Create persistent elements with `dom()`, store in a Map, render by reference:
200
+ Integration fragment: with a `table-row` component accepting `{ data }`, a `data` array with unique IDs, and an existing `container`, create persistent elements with `dom()`, store in a Map, and render by reference:
187
201
 
188
202
  ```js
189
203
  let rowMap = new Map(
@@ -208,16 +222,32 @@ container.render(...data.map(d => rowMap.get(d.id)))
208
222
 
209
223
  ## Limits
210
224
 
211
- `render(...children)` uses rest parameters, which are subject to the browser's maximum function argument count. This varies: ~65,536 in V8 (Chrome/Edge/Node), ~500,000 in SpiderMonkey (Firefox), ~65,536 in JavaScriptCore (Safari). If you're rendering more than ~60K children, pass an array and spread it, or use a `DocumentFragment`. In practice this only matters for flat lists with tens of thousands of items - use virtual scrolling at that scale instead.
225
+ `render(...children)` uses rest parameters and is subject to the browser's function argument limit, which varies by engine and runtime conditions. Passing the array unspread does not avoid it either, since mx flattens it with a spread internally. Keep rendered child counts bounded with pagination or virtual scrolling, and never pass an unbounded dataset to a single call.
226
+
227
+ ## Agent skill
228
+
229
+ The package ships an agent skill in `node_modules/@tltdsh/mx/skill/`: the mx rules, the readable engine source and a few canonical examples. Copy or symlink it into your skills directory, and your agent loads it whenever it sees mx code:
230
+
231
+ ```
232
+ ln -s "$PWD/node_modules/@tltdsh/mx/skill" ~/.claude/skills/mx
233
+ ```
234
+
235
+ The same skill is a zip at [mxjs.dev/mx-skill.zip](https://mxjs.dev/mx-skill.zip).
212
236
 
213
237
  ## TypeScript
214
238
 
215
- Full type definitions included. Provides autocomplete for all HTML/SVG elements and attributes.
239
+ Type definitions are included, with autocomplete for common HTML and SVG elements and attributes, and any other tag through an index signature. Children can be nested arrays, and every typed attribute also takes `null` or `false` to remove it.
216
240
 
217
241
  ```ts
218
242
  import { mx, dom, define, type MxChild, type MxAttrs } from '@tltdsh/mx'
219
243
  ```
220
244
 
245
+ Importing the package declares no globals. If you load the classic script and write TypeScript, reference the classic types once to get `mx`, `dom`, `define` and `components` as globals:
246
+
247
+ ```ts
248
+ /// <reference types="@tltdsh/mx/classic" />
249
+ ```
250
+
221
251
  ## License
222
252
 
223
253
  0BSD - do whatever you want.
package/classic.d.ts ADDED
@@ -0,0 +1,9 @@
1
+ // Opt-in API globals for the classic script; importing ESM does not create these.
2
+ import type * as api from './mx.js';
3
+ declare global {
4
+ var mx: typeof api.mx;
5
+ var dom: typeof api.dom;
6
+ var define: typeof api.define;
7
+ var components: typeof api.components;
8
+ }
9
+ export {};