@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 +87 -73
- package/CLAUDE.md +87 -73
- package/README.md +46 -16
- package/classic.d.ts +9 -0
- package/mx.d.ts +68 -30
- package/mx.min.js +1 -1
- package/mx.mjs +1 -1
- package/package.json +7 -6
- package/skill/SKILL.md +135 -0
- package/skill/examples.md +107 -0
- package/skill/ui-mx.js +256 -0
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) {}`
|
|
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 })` |
|
|
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(
|
|
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
|
-
//
|
|
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
|
|
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.
|
|
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
|
|
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
|
-
|
|
|
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.$({
|
|
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`
|
|
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
|
|
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
|
|
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
|
|
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] ??=
|
|
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,
|
|
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
|
-
|
|
415
|
-
|
|
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.$({
|
|
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
|
-
|
|
487
|
-
|
|
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.
|
|
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
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
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
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
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
|
package/README.md
CHANGED
|
@@ -1,6 +1,11 @@
|
|
|
1
1
|
# mx.js
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
[](https://www.npmjs.com/package/@tltdsh/mx)
|
|
4
|
+
[](https://bundlejs.com/?q=@tltdsh/mx)
|
|
5
|
+
[](https://mxjs.dev)
|
|
6
|
+
[](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.
|
|
29
|
+
<script src="https://cdn.jsdelivr.net/npm/@tltdsh/mx@1.6.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
|
-
|
|
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
|
|
52
|
+
## 4 API bindings
|
|
48
53
|
|
|
49
|
-
|
|
|
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({
|
|
106
|
-
|
|
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
|
-
-
|
|
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.
|
|
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
|
|
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
|
-
|
|
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
|
|
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
|
-
|
|
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 {};
|