@tltdsh/mx 1.4.1 → 1.6.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
@@ -112,22 +111,6 @@ if (this.$state.items.length) this.$({ hasItems: true });
112
111
 
113
112
  ---
114
113
 
115
- ## Reserved Tag Names
116
-
117
- The internal tag cache is a plain object; it inherits `Object.prototype` methods. Don't use any of these as component names:
118
-
119
- ```
120
- toString, valueOf, constructor, hasOwnProperty, isPrototypeOf,
121
- propertyIsEnumerable, toLocaleString, __defineGetter__,
122
- __defineSetter__, __lookupGetter__, __lookupSetter__, __proto__
123
- ```
124
-
125
- `mx.toString()` produces a broken description that throws `InvalidCharacterError` at `createElement` time. Also applies to `define('toString', ...)`.
126
-
127
- 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
-
129
- ---
130
-
131
114
  ## Checklist for New Components
132
115
 
133
116
  1. `define('kebab-name', { $(props) {} })` - kebab-case only in define()
@@ -136,7 +119,7 @@ Tag/component names only - **attribute** names are safe: the reconciler tracks a
136
119
  4. Use `this._name` for private caches (Maps, flags, intervals)
137
120
  5. Use `this._name ||= new Map` for persistent references
138
121
  6. Compute derived values once, reuse
139
- 7. Return mx nodes - single element or array
122
+ 7. Return a single mx description or an array (real `dom()` nodes go inside an array)
140
123
  8. Direct property assignment for events on `this`: `this.onclick = handler`
141
124
  9. Callbacks via `onchange?.(value)` or prop check
142
125
  10. Event bus for cross-component communication
@@ -145,7 +128,7 @@ Tag/component names only - **attribute** names are safe: the reconciler tracks a
145
128
  13. `clearInterval(this._interval)` at top of `$()`
146
129
  14. CSS transitions for animations, not JS
147
130
  15. Formatters in render, not in data prep
148
- 16. Never write `this.$state.x = ...` directly - always `this.$({...})`
131
+ 16. Updates use `this.$({...})`; controlled one-time `$state` defaults are valid but direct writes do not render
149
132
  17. Hoist constant arrays/objects out of `$()` - don't re-allocate per render
150
133
  18. Stateful list rows use a keyed `dom()` Map, not positional `mx()` rows
151
134
  19. Drive logic from `$state` / data attributes, never from rendered text
@@ -178,13 +161,21 @@ This is the single most common source of confusion for teams adopting mx. Pick t
178
161
 
179
162
  ---
180
163
 
181
- ## 4 Globals
164
+ ## 4 API Names
165
+
166
+ The classic CDN script exposes `mx`, `dom`, `define`, and `components` on `window`. The ESM build exports them instead and does not create globals:
167
+
168
+ ```js
169
+ import { mx, dom, define, components } from '@tltdsh/mx';
170
+ ```
171
+
172
+ Both builds require a browser DOM. See [Installation](https://mxjs.dev/installation) for script and CDN module URLs.
182
173
 
183
- | Global | Returns | Use for |
174
+ | Name | Returns | Use for |
184
175
  |--------|---------|---------|
185
176
  | `mx.tag(attrs?, ...nodes)` | Array (description) | Inside `render()` - efficient reconciliation |
186
177
  | `dom.tag(attrs?, ...nodes)` | HTMLElement | Persistent references, calling `.$()` later |
187
- | `define(name, { $() {} })` | void | Register a component |
178
+ | `define(name, { $() {} })` | void | Register a component in MX, not `customElements` |
188
179
  | `components` | object | Component registry lookup |
189
180
 
190
181
  Both `mx` and `dom` are Proxies. CamelCase auto-converts to kebab-case (memoized):
@@ -208,7 +199,7 @@ define('greeting', {
208
199
  });
209
200
  ```
210
201
 
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`.
202
+ 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
203
 
213
204
  ### The parent always wins the merge
214
205
 
@@ -223,9 +214,10 @@ Because `Object.assign` runs **before** your `$` function, a parent re-passing t
223
214
  | Input | Behavior |
224
215
  |-------|----------|
225
216
  | mx array (`._=true`) | Create/reuse by tag name, apply attrs, recurse children |
217
+ | Plain array (no `._`) | Flattened in place, nested arrays too, its items reconciled as siblings (1.5.0+) |
226
218
  | Real DOM node | Identity-match by reference. Same = no-op, different = move/insert |
227
219
  | String / Number | Create/update text node |
228
- | `null` / `false` | Skipped - use for conditional rendering |
220
+ | `null` / `undefined` / `false` | Skipped - use for conditional rendering |
229
221
 
230
222
  After processing all children, excess old DOM nodes are removed.
231
223
 
@@ -241,17 +233,17 @@ After processing all children, excess old DOM nodes are removed.
241
233
  | `name: true` | `setAttribute(name, 'true')` | `disabled: true` |
242
234
  | `onname: fn` | `el[name] = fn` (property) | `onclick: handler` |
243
235
 
244
- **Dual-track**: `value`, `checked`, `selected` automatically set both attribute AND property.
236
+ **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
237
 
246
- **`el.$attrs(obj)`**: Applies attributes to the element using the same rules above. Useful for setting attributes on `this` inside `$()`:
238
+ **`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
239
 
248
240
  ```js
249
241
  this.$attrs({ disabled, class: 'my-component' });
250
242
  ```
251
243
 
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).
244
+ 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
245
 
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.
246
+ **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
247
 
256
248
  **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
249
 
@@ -332,12 +324,12 @@ let events = (() => {
332
324
 
333
325
  ## Memoization (cache the function, not the component)
334
326
 
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:
327
+ 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
328
 
337
329
  ```js
338
330
  function expensiveFormat(arg) {
339
- let c = expensiveFormat.lookup ||= {};
340
- return c[arg] ??= /* actual expensive work */;
331
+ let c = expensiveFormat.lookup ||= Object.create(null);
332
+ return c[arg] ??= new Intl.NumberFormat('en-US').format(arg);
341
333
  }
342
334
  ```
343
335
 
@@ -346,7 +338,7 @@ For object-identity inputs, use a Map (plain objects stringify keys):
346
338
  ```js
347
339
  function expensiveFormat(item) {
348
340
  let c = expensiveFormat.lookup ||= new Map;
349
- if (!c.has(item)) c.set(item, /* expensive work */);
341
+ if (!c.has(item)) c.set(item, JSON.stringify(item));
350
342
  return c.get(item);
351
343
  }
352
344
  ```
@@ -373,6 +365,8 @@ define('counter', {
373
365
 
374
366
  ### Sparkline (stateless, SVG)
375
367
 
368
+ Empty histories render nothing. A singleton produces one finite point; a visible line requires at least two points.
369
+
376
370
  ```js
377
371
  define('sparkline', {
378
372
  $({ history = [], width = 80, height = 24 }) {
@@ -384,7 +378,7 @@ define('sparkline', {
384
378
  let len = history.length;
385
379
 
386
380
  let points = history.map((v, i) =>
387
- (i / (len - 1) * width).toFixed(1) + ',' +
381
+ (i / Math.max(1, len - 1) * width).toFixed(1) + ',' +
388
382
  (height - ((v - min) / range * (height - 2) + 1)).toFixed(1)
389
383
  ).join(' ');
390
384
 
@@ -410,9 +404,10 @@ define('data-table', {
410
404
  });
411
405
 
412
406
  let header = (label, key) =>
413
- mx.th({
414
- onclick: () => this.$({ sortKey: key, sortDir: sortKey === key ? -sortDir : 1 })
415
- }, label, sortKey === key ? (sortDir > 0 ? ' ▲' : ' ▼') : null);
407
+ mx.th({ 'aria-sort': sortKey === key ? (sortDir > 0 ? 'ascending' : 'descending') : 'none' },
408
+ mx.button({
409
+ onclick: () => this.$({ sortKey: key, sortDir: sortKey === key ? -sortDir : 1 })
410
+ }, label, sortKey === key ? (sortDir > 0 ? ' ▲' : ' ▼') : null));
416
411
 
417
412
  return mx.table(
418
413
  mx.thead(mx.tr(header('Name', 'name'), header('Value', 'value'))),
@@ -426,15 +421,17 @@ define('data-table', {
426
421
 
427
422
  ```js
428
423
  define('my-form', {
429
- $({ title = '', saving = false, onsubmit, onclose }) {
424
+ $({ title = '', saving = false, error = '', onsubmit, onclose }) {
430
425
  let submit = async () => {
431
426
  if (!title.trim()) return;
432
- this.$({ saving: true });
433
- await onsubmit?.({ title });
434
- this.$({ saving: false });
427
+ this.$({ saving: true, error: '' });
428
+ try { await onsubmit?.({ title }); }
429
+ catch (error) { this.$({ error: error.message || String(error) }); }
430
+ finally { this.$({ saving: false }); }
435
431
  };
436
432
 
437
433
  return mx.div({ class: 'form' },
434
+ error && mx.p({ role: 'alert' }, error),
438
435
  mx.input({
439
436
  value: title,
440
437
  placeholder: 'Title',
@@ -463,7 +460,7 @@ function toast(message, type = 'info') {
463
460
  }
464
461
  let el = dom.div({ class: 'toast toast-' + type },
465
462
  mx.span(message),
466
- mx.button({ onclick() { el.remove() } }, '×')
463
+ mx.button({ 'aria-label': 'Dismiss', onclick() { el.remove() } }, '×')
467
464
  );
468
465
  toastContainer.append(el);
469
466
  setTimeout(() => el.remove(), 4000);
@@ -475,6 +472,8 @@ toast.error = msg => toast(msg, 'error');
475
472
 
476
473
  ### Timer component (reading latest state)
477
474
 
475
+ 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 `$`.
476
+
478
477
  ```js
479
478
  define('player-bar', {
480
479
  $({ track, isPlaying = false, progress = 0 }) {
@@ -483,8 +482,12 @@ define('player-bar', {
483
482
  if (isPlaying && track) {
484
483
  this._interval = setInterval(() => {
485
484
  // 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;
485
+ if (!this.isConnected) { clearInterval(this._interval); return; }
486
+ let p = (this.$state.progress ?? 0) + 1;
487
+ if (p >= this.$state.track.duration) {
488
+ this.$({ progress: this.$state.track.duration, isPlaying: false });
489
+ return;
490
+ }
488
491
  this.$({ progress: p });
489
492
  }, 1000);
490
493
  }
@@ -494,7 +497,7 @@ define('player-bar', {
494
497
  return [
495
498
  mx.div(track.title),
496
499
  mx.div(track.artist),
497
- mx.progressBar({ value: progress, max: track.duration })
500
+ mx.progress({ value: progress, max: track.duration })
498
501
  ];
499
502
  }
500
503
  });
@@ -535,28 +538,39 @@ define('v-c', {
535
538
  ### Lazy-loaded async component
536
539
 
537
540
  ```js
541
+ // Integration contract: loadLibrary resolves a CodeMirror-compatible factory.
542
+ // Owner calls mount() after append and dispose() before every removal.
538
543
  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
- });
544
+ $({ value = '', disabled = false }) {
545
+ this._container ||= dom.div();
546
+ this.$editor?.setOption('readOnly', disabled);
547
+ if (this.$editor && this.$editor.getValue() !== value)
548
+ this.$editor.setValue(value);
549
+ return [this._container];
550
+ },
551
+ async mount() {
552
+ if (!this.isConnected) throw new Error('Append before mount()');
553
+ if (this.$editor || this._loading) return;
554
+ let token = this._loading = {};
555
+ try {
556
+ let CodeMirror = await loadLibrary('codemirror');
557
+ if (this._loading !== token || !this.isConnected) return;
558
+ let { value = '', disabled = false } = this.$state;
559
+ this.$editor = CodeMirror(this._container, { lineNumbers: true, readOnly: disabled, value });
560
+ this.$editor.on('change', () => this.$state.onChange?.(this.$editor.getValue()));
561
+ } finally {
562
+ if (this._loading === token) this._loading = null;
552
563
  }
553
-
554
- if (me.$editor && me.$editor.getValue() !== value)
555
- me.$editor.setValue(value);
556
-
557
- return [me._container];
564
+ },
565
+ dispose() {
566
+ this._loading = null; // invalidates pending initialization
567
+ this.$editor?.destroy(); // adapter must release editor subscriptions and DOM
568
+ this.$editor = null;
558
569
  }
559
570
  });
571
+ // Owner handles load errors: await editor.mount() inside try/catch.
572
+ // Removal: editor.dispose(); editor.remove();
573
+ // Remount: append editor, then await editor.mount().
560
574
  ```
561
575
 
562
576
  ### Debounced search