@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/AGENTS.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