@tltdsh/mx 1.0.8 → 1.0.9

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.
Files changed (3) hide show
  1. package/CLAUDE.md +471 -0
  2. package/README.md +2 -2
  3. package/package.json +2 -2
package/CLAUDE.md ADDED
@@ -0,0 +1,471 @@
1
+ # AGENTS.md - mx.js
2
+
3
+ Instructions for AI coding agents working with mx.js codebases.
4
+
5
+ ---
6
+
7
+ ## Hard Rules
8
+
9
+ | Rule | Do | Don't |
10
+ |------|----|-------|
11
+ | Numbers in render | `mx.span(count)` | `mx.span(String(count))` - auto-casts |
12
+ | Event names | `onclick` (lowercase) | `onClick` - not React |
13
+ | Class attribute | `class: 'active'` | `className: 'active'` - not React |
14
+ | Label for | `for: 'input-id'` | `htmlFor: 'input-id'` - not React |
15
+ | Inline styles | `style: 'width:' + pct + '%'` | `style: { width: pct + '%' }` - not supported |
16
+ | No attrs, just children | `mx.div(child1, child2)` | `mx.div({}, child)` or `mx.div(null, child)` |
17
+ | Boolean attributes | `disabled: true` sets `disabled=""` | Expecting it to set a JS property |
18
+ | First arg type | `mx.div({class: 'x'}, child)` | `mx.div(myMap, child)` - non-plain-Object treated as child |
19
+
20
+ ---
21
+
22
+ ## Common Mistakes
23
+
24
+ ```js
25
+ // ✗ Mutates parent's array
26
+ assets.sort((a, b) => a.price - b.price);
27
+ // ✓ Copy first
28
+ let sorted = [...assets].sort((a, b) => a.price - b.price);
29
+
30
+ // ✗ Stacks listeners on every re-render
31
+ $() { this.addEventListener('scroll', () => doStuff()); }
32
+ // ✓ Property assignment overwrites safely
33
+ $() { this.onscroll = handler; }
34
+
35
+ // ✗ Unnecessary wrapping
36
+ mx.span(String(count))
37
+ // ✓ Numbers auto-cast
38
+ mx.span(count)
39
+
40
+ // ✗ React-style event names
41
+ mx.button({ onClick: handler })
42
+ // ✓ Lowercase
43
+ mx.button({ onclick: handler })
44
+
45
+ // ✗ Number leaks into render as text node "0"
46
+ items.length && mx.div('Has items')
47
+ // ✓ Coerce to boolean
48
+ !!items.length && mx.div('Has items')
49
+ ```
50
+
51
+ ---
52
+
53
+ ## Checklist for New Components
54
+
55
+ 1. `define('kebab-name', { $({ props }) {} })`
56
+ 2. Destructure all props with defaults in `$()` signature
57
+ 3. Early return on empty state: `if (!data) return [];`
58
+ 4. Use `this._name` for private caches (Maps, flags, intervals)
59
+ 5. Use `this._name ||= new Map` for persistent references
60
+ 6. Compute derived values once, reuse
61
+ 7. Return mx nodes - single element or array
62
+ 8. Direct property assignment for events on `this`: `this.onclick = handler`
63
+ 9. Callbacks via `onchange?.(value)` or prop check
64
+ 10. Event bus for cross-component communication
65
+ 11. Never mutate input arrays - copy before sort/filter
66
+ 12. `null` / `false` for conditional elements
67
+ 13. `clearInterval(this._interval)` at top of `$()`
68
+ 14. CSS transitions for animations, not JS
69
+ 15. Formatters in render, not in data prep
70
+
71
+ ---
72
+
73
+ ## Decision Tree
74
+
75
+ ```
76
+ Description for render to reconcile? → mx.tag()
77
+ Real element to hold a reference? → dom.tag()
78
+ Need to call .$() on it later? → dom.tag()
79
+ ```
80
+
81
+ State in `$state` (survives re-renders, drives render logic) vs `this._name` (private caches, Maps, flags, intervals that should NOT be in `$state`).
82
+
83
+ ---
84
+
85
+ ## 4 Globals
86
+
87
+ | Global | Returns | Use for |
88
+ |--------|---------|---------|
89
+ | `mx.tag(attrs?, ...nodes)` | Array (description) | Inside `render()` - efficient reconciliation |
90
+ | `dom.tag(attrs?, ...nodes)` | HTMLElement | Persistent references, calling `.$()` later |
91
+ | `define(name, { $() {} })` | void | Register a component |
92
+ | `components` | object | Component registry lookup |
93
+
94
+ Both `mx` and `dom` are Proxies. CamelCase auto-converts to kebab-case (memoized):
95
+
96
+ ```js
97
+ mx.priceChart() // → <price-chart>
98
+ dom.vC() // → <v-c>
99
+ ```
100
+
101
+ ---
102
+
103
+ ## How `$()` Works
104
+
105
+ The `$` wrapper does `Object.assign(this.$state ||= {}, props)` then calls your function with the merged state object. Incoming keys merge in; keys not passed survive untouched.
106
+
107
+ ```js
108
+ define('greeting', {
109
+ $({ name = 'World' }) {
110
+ return mx.div('Hello, ' + name);
111
+ }
112
+ });
113
+ ```
114
+
115
+ When parent calls `el.$({ count: 5 })`, count updates. When the component calls `this.$({ count: count + 1 })`, it self-updates. The destructuring default `= 0` only applies on first render when the key is undefined.
116
+
117
+ ---
118
+
119
+ ## render() Algorithm
120
+
121
+ `el.render(...children)` reconciles children left-to-right against existing DOM:
122
+
123
+ | Input | Behavior |
124
+ |-------|----------|
125
+ | mx array (`._=true`) | Create/reuse by tag name, apply attrs, recurse children |
126
+ | Real DOM node | Identity-match by reference. Same = no-op, different = move/insert |
127
+ | String / Number | Create/update text node |
128
+ | `null` / `false` | Skipped - use for conditional rendering |
129
+
130
+ After processing all children, excess old DOM nodes are removed.
131
+
132
+ ---
133
+
134
+ ## Attribute System
135
+
136
+ | Syntax | Behavior | Example |
137
+ |--------|----------|---------|
138
+ | `name: 'value'` | `setAttribute` | `class: 'active'` |
139
+ | `'.name': value` | `el[name] = value` (property) | `'.value': text` |
140
+ | `name: null` / `false` | `removeAttribute` | `disabled: null` |
141
+ | `name: true` | `setAttribute(name, '')` | `disabled: true` |
142
+ | `onname: fn` | `el[name] = fn` (property) | `onclick: handler` |
143
+
144
+ **Dual-track**: `value`, `checked`, `selected` automatically set both attribute AND property.
145
+
146
+ **`el.$attrs(obj)`**: Applies attributes to the element using the same rules above. Useful for setting attributes on `this` inside `$()`:
147
+
148
+ ```js
149
+ this.$attrs({ disabled, class: 'my-component' });
150
+ ```
151
+
152
+ **Stamp system**: Event handlers in render N but absent in render N+1 are auto-nullified. You never manually remove handlers.
153
+
154
+ ---
155
+
156
+ ## Conditional Rendering
157
+
158
+ ```js
159
+ // Short-circuit (preferred)
160
+ isPlaying && mx.div({ class: 'waveform' })
161
+ !!results.length && mx.div({ class: 'results' }, ...items)
162
+
163
+ // Inside arrays - falsy values skipped
164
+ return [
165
+ mx.div({ class: 'header' }, title),
166
+ showClear && mx.button({ onclick: clear }, 'x'),
167
+ mx.div({ class: 'footer' })
168
+ ];
169
+ ```
170
+
171
+ `false`, `null`, and `undefined` are skipped. `0` is not - it's a valid number that renders as a text node.
172
+
173
+ ---
174
+
175
+ ## Keyed Lists (Identity Matching)
176
+
177
+ Create real elements with `dom()`, store references, render them - mx physically moves nodes:
178
+
179
+ ```js
180
+ this._rowMap ||= new Map;
181
+ let rowMap = this._rowMap;
182
+
183
+ // Clean removed items
184
+ for (let [id] of rowMap) {
185
+ if (!items.find(d => d.id === id)) rowMap.delete(id);
186
+ }
187
+
188
+ // Create/update persistent elements
189
+ for (let d of items) {
190
+ let el = rowMap.get(d.id);
191
+ if (!el) { el = dom.myRow(); rowMap.set(d.id, el); }
192
+ el.$({ data: d });
193
+ }
194
+
195
+ // Render - nodes move by identity, internal state preserved
196
+ container.render(...items.map(d => rowMap.get(d.id)));
197
+ ```
198
+
199
+ ---
200
+
201
+ ## Class Binding
202
+
203
+ ```js
204
+ class: 'nav-link' + (path === href ? ' active' : '')
205
+ class: 'col-change ' + (pct >= 0 ? 'positive' : 'negative')
206
+ ```
207
+
208
+ ---
209
+
210
+ ## Event Bus
211
+
212
+ ```js
213
+ let events = (() => {
214
+ let listeners = new Map;
215
+ return {
216
+ send(event, data) { listeners.get(event)?.forEach(fn => fn(data)); },
217
+ on(event, fn) {
218
+ let s = listeners.get(event);
219
+ s ? s.add(fn) : listeners.set(event, new Set([fn]));
220
+ }
221
+ };
222
+ })();
223
+ ```
224
+
225
+ ---
226
+
227
+ ## Pattern Library
228
+
229
+ ### Counter (minimal stateful component)
230
+
231
+ ```js
232
+ define('counter', {
233
+ $({ count = 0 }) {
234
+ return [
235
+ mx.button({ onclick: () => this.$({ count: count + 1 }) }, '+'),
236
+ mx.span(count),
237
+ mx.button({ onclick: () => this.$({ count: count - 1 }) }, '-')
238
+ ];
239
+ }
240
+ });
241
+ ```
242
+
243
+ ### Sparkline (stateless, SVG)
244
+
245
+ ```js
246
+ define('sparkline', {
247
+ $({ history = [], width = 80, height = 24 }) {
248
+ if (!history.length) return [];
249
+
250
+ let min = Math.min(...history);
251
+ let max = Math.max(...history);
252
+ let range = max - min || 1;
253
+ let len = history.length;
254
+
255
+ let points = history.map((v, i) =>
256
+ (i / (len - 1) * width).toFixed(1) + ',' +
257
+ (height - ((v - min) / range * (height - 2) + 1)).toFixed(1)
258
+ ).join(' ');
259
+
260
+ let color = history[len - 1] >= history[0] ? '#22c55e' : '#ef4444';
261
+
262
+ return [
263
+ mx.svg({ viewBox: '0 0 ' + width + ' ' + height, width, height, fill: 'none' },
264
+ mx.polyline({ points, stroke: color, 'stroke-width': '1.5', 'stroke-linecap': 'round' })
265
+ )
266
+ ];
267
+ }
268
+ });
269
+ ```
270
+
271
+ ### Sortable table (self-updating state)
272
+
273
+ ```js
274
+ define('data-table', {
275
+ $({ rows = [], sortKey = 'name', sortDir = 1 }) {
276
+ let sorted = [...rows].sort((a, b) => {
277
+ let va = a[sortKey], vb = b[sortKey];
278
+ return sortDir * (typeof va === 'string' ? va.localeCompare(vb) : va - vb);
279
+ });
280
+
281
+ let header = (label, key) =>
282
+ mx.th({
283
+ onclick: () => this.$({ sortKey: key, sortDir: sortKey === key ? -sortDir : 1 })
284
+ }, label, sortKey === key ? (sortDir > 0 ? ' ▲' : ' ▼') : null);
285
+
286
+ return mx.table(
287
+ mx.thead(mx.tr(header('Name', 'name'), header('Value', 'value'))),
288
+ mx.tbody(...sorted.map(r => mx.tr(mx.td(r.name), mx.td(r.value))))
289
+ );
290
+ }
291
+ });
292
+ ```
293
+
294
+ ### Form with callbacks
295
+
296
+ ```js
297
+ define('my-form', {
298
+ $({ title = '', saving = false, onsubmit, onclose }) {
299
+ let submit = async () => {
300
+ if (!title.trim()) return;
301
+ this.$({ saving: true });
302
+ await onsubmit?.({ title });
303
+ this.$({ saving: false });
304
+ };
305
+
306
+ return mx.div({ class: 'form' },
307
+ mx.input({
308
+ value: title,
309
+ placeholder: 'Title',
310
+ oninput: e => this.$({ title: e.target.value })
311
+ }),
312
+ mx.div({ class: 'flex gap-3' },
313
+ mx.button({ onclick: onclose }, 'Cancel'),
314
+ mx.button({ onclick: submit, disabled: saving },
315
+ saving ? 'Saving...' : 'Save'
316
+ )
317
+ )
318
+ );
319
+ }
320
+ });
321
+ ```
322
+
323
+ ### Toast notifications
324
+
325
+ ```js
326
+ let toastContainer = null;
327
+
328
+ function toast(message, type = 'info') {
329
+ if (!toastContainer) {
330
+ toastContainer = dom.div({ class: 'toast-container' });
331
+ document.body.append(toastContainer);
332
+ }
333
+ let el = dom.div({ class: 'toast toast-' + type },
334
+ mx.span(message),
335
+ mx.button({ onclick() { el.remove() } }, '×')
336
+ );
337
+ toastContainer.append(el);
338
+ setTimeout(() => el.remove(), 4000);
339
+ }
340
+
341
+ toast.success = msg => toast(msg, 'success');
342
+ toast.error = msg => toast(msg, 'error');
343
+ ```
344
+
345
+ ### Timer component
346
+
347
+ ```js
348
+ define('player-bar', {
349
+ $({ track, isPlaying = false, progress = 0 }) {
350
+ clearInterval(this._interval);
351
+
352
+ if (isPlaying && track) {
353
+ this._interval = setInterval(() => {
354
+ let p = this.$state.progress + 1;
355
+ if (p >= this.$state.track.duration) return;
356
+ this.$({ progress: p });
357
+ }, 1000);
358
+ }
359
+
360
+ if (!track) return [mx.div('No track selected')];
361
+
362
+ return [
363
+ mx.div(track.title),
364
+ mx.div(track.artist),
365
+ mx.progressBar({ value: progress, max: track.duration })
366
+ ];
367
+ }
368
+ });
369
+ ```
370
+
371
+ ### Virtual scroll
372
+
373
+ ```js
374
+ define('v-c', {
375
+ $({ height = 400, rowHeight = 56, rows = [] }) {
376
+ this._visibleRows = Math.floor((height - 1) / rowHeight);
377
+ this._lastOffset = 0;
378
+ this.style.height = height + 'px';
379
+
380
+ let renderVisible = offset => {
381
+ let visible = rows.slice(offset, offset + this._visibleRows + 1);
382
+ return [
383
+ mx.div({ style: 'height:' + (offset * rowHeight) + 'px' }),
384
+ ...visible,
385
+ mx.div({ style: 'height:' + ((rows.length - offset - visible.length) * rowHeight) + 'px' })
386
+ ];
387
+ };
388
+
389
+ this.onscroll = e => {
390
+ let scrollTop = Math.max(0, e.target.scrollTop);
391
+ let offset = Math.floor(scrollTop / rowHeight);
392
+ if (offset === this._lastOffset) return;
393
+ this._lastOffset = offset;
394
+ this.render(...renderVisible(offset));
395
+ this.scrollTop = scrollTop;
396
+ };
397
+
398
+ return renderVisible(0);
399
+ }
400
+ });
401
+ ```
402
+
403
+ ### Lazy-loaded async component
404
+
405
+ ```js
406
+ define('code-editor', {
407
+ $({ value = '', disabled, onChange }) {
408
+ let me = this;
409
+ me.$attrs({ disabled });
410
+
411
+ if (!me.$state.initialized) {
412
+ me.$state.initialized = true;
413
+ me._container = dom.div();
414
+
415
+ loadLibrary('codemirror').then(() => {
416
+ me.$editor = CodeMirror(me._container, { lineNumbers: true });
417
+ me.$editor.on('change', () => onChange?.(me.$editor.getValue()));
418
+ me.$editor.setValue(me.$state.value || '');
419
+ });
420
+ }
421
+
422
+ if (me.$editor && me.$editor.getValue() !== value)
423
+ me.$editor.setValue(value);
424
+
425
+ return [me._container];
426
+ }
427
+ });
428
+ ```
429
+
430
+ ### Debounced search
431
+
432
+ ```js
433
+ define('search-bar', {
434
+ $({ value = '', onsearch }) {
435
+ return mx.input({
436
+ value,
437
+ placeholder: 'Search...',
438
+ oninput: e => {
439
+ let query = e.target.value;
440
+ this.$({ value: query });
441
+ clearTimeout(this._debounce);
442
+ this._debounce = setTimeout(() => onsearch?.(query), 300);
443
+ }
444
+ });
445
+ }
446
+ });
447
+ ```
448
+
449
+ ### Icon helper (SVG)
450
+
451
+ ```js
452
+ let icons = {
453
+ check: 'M20 6L9 17l-5-5',
454
+ x: 'M18 6L6 18M6 6l12 12',
455
+ menu: 'M4 12h16M4 6h16M4 18h16',
456
+ };
457
+
458
+ function icon(name, size = 24) {
459
+ return mx.svg({
460
+ viewBox: '0 0 24 24', width: size, height: size,
461
+ fill: 'none', stroke: 'currentColor', 'stroke-width': '2',
462
+ 'stroke-linecap': 'round', 'stroke-linejoin': 'round'
463
+ }, mx.path({ d: icons[name] || '' }));
464
+ }
465
+ ```
466
+
467
+ ### Dynamic styles
468
+
469
+ ```js
470
+ mx.div({ style: 'width:' + pct + '%;background:' + color })
471
+ ```
package/README.md CHANGED
@@ -19,7 +19,7 @@ Sub-1KB reactive DOM reconciliation engine for building massive platforms and us
19
19
  ### Pinned version
20
20
 
21
21
  ```html
22
- <script src="https://cdn.jsdelivr.net/npm/@tltdsh/mx@1.0.8/mx.min.js"></script>
22
+ <script src="https://cdn.jsdelivr.net/npm/@tltdsh/mx@1.0.9/mx.min.js"></script>
23
23
  ```
24
24
 
25
25
  ### npm / yarn / bun
@@ -206,7 +206,7 @@ container.render(...data.map(d => rowMap.get(d.id)))
206
206
 
207
207
  ## Limits
208
208
 
209
- `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.
209
+ `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.
210
210
 
211
211
  ## TypeScript
212
212
 
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@tltdsh/mx",
3
- "version": "1.0.8",
4
- "description": "<1KB UI engine. Build big. Ship small & fast.",
3
+ "version": "1.0.9",
4
+ "description": "<1KB UI engine. Build big. Ship small, ship fast.",
5
5
  "license": "0BSD",
6
6
  "author": "tltdsh",
7
7
  "homepage": "https://mxjs.dev",