Debian Codegraph @

test/tests/ext/hx-live.js

raw symbols SCIP
1 describe('hx-live extension', function () {
2
3 let extBackup;
4
5 before(async () => {
6 extBackup = backupExtensions();
7 clearExtensions();
8 htmx.config.extensions = 'hx-live';
9 htmx.__approvedExt = 'hx-live';
10
11 let script = document.createElement('script');
12 script.src = '../src/ext/hx-live.js';
13 await new Promise(resolve => {
14 script.onload = resolve;
15 document.head.appendChild(script);
16 });
17 });
18
19 after(() => {
20 restoreExtensions(extBackup);
21 });
22
23 beforeEach(() => { setupTest(this.currentTest); });
24 afterEach(() => { cleanupTest(); });
25
26 // -------------------------------------------------------------------------
27 // hx-live attribute behavior
28 // -------------------------------------------------------------------------
29
30 it('runs initially when registered', function() {
31 let elt = createProcessedHTML('<output hx-live="this.dataset.v = \'init\'"></output>');
32 elt.dataset.v.should.equal('init');
33 });
34
35 it('recomputes on input event', async function() {
36 playground().innerHTML = `
37 <input id="src" value="hello">
38 <output hx-live="this.dataset.v = q('#src').value"></output>
39 `;
40 htmx.process(playground());
41 let out = playground().querySelector('output');
42 out.dataset.v.should.equal('hello');
43
44 let src = playground().querySelector('#src');
45 src.value = 'world';
46 src.dispatchEvent(new Event('input', { bubbles: true }));
47 await htmx.timeout(5);
48 out.dataset.v.should.equal('world');
49 });
50
51 it('recomputes on change event', async function() {
52 playground().innerHTML = `
53 <select id="sel"><option>a</option><option>b</option></select>
54 <output hx-live="this.dataset.v = q('#sel').value"></output>
55 `;
56 htmx.process(playground());
57 let sel = playground().querySelector('#sel');
58 let out = playground().querySelector('output');
59
60 sel.value = 'b';
61 sel.dispatchEvent(new Event('change', { bubbles: true }));
62 await htmx.timeout(5);
63 out.dataset.v.should.equal('b');
64 });
65
66 it('recomputes on DOM mutation (attribute change)', async function() {
67 playground().innerHTML = `
68 <div id="src" data-x="1"></div>
69 <output hx-live="this.dataset.v = q('#src').dataset.x"></output>
70 `;
71 htmx.process(playground());
72 let src = playground().querySelector('#src');
73 let out = playground().querySelector('output');
74 out.dataset.v.should.equal('1');
75
76 src.setAttribute('data-x', '2');
77 await htmx.timeout(5);
78 out.dataset.v.should.equal('2');
79 });
80
81 it('removes itself from liveFns when disconnected', async function() {
82 let elt = createProcessedHTML('<output hx-live="window.__liveCallCount = (window.__liveCallCount || 0) + 1"></output>');
83 let initial = window.__liveCallCount;
84 elt.remove();
85 document.body.setAttribute('data-test-trigger', '1');
86 await htmx.timeout(5);
87 document.body.removeAttribute('data-test-trigger');
88 await htmx.timeout(5);
89 assert.isAtMost(window.__liveCallCount, initial + 1);
90 delete window.__liveCallCount;
91 });
92
93 it('hx-ignore skips hx-live', function() {
94 playground().innerHTML = '<div hx-ignore><output hx-live="this.dataset.v = \'should-not-run\'"></output></div>';
95 htmx.process(playground());
96 let out = playground().querySelector('output');
97 assert.isUndefined(out.dataset.v);
98 });
99
100 it('coalesces multiple sync mutations into one recompute', async function() {
101 window.__liveCount = 0;
102 let elt = createProcessedHTML('<output hx-live="window.__liveCount++"></output>');
103 let initial = window.__liveCount;
104 document.body.setAttribute('data-a', '1');
105 document.body.setAttribute('data-b', '1');
106 document.body.setAttribute('data-c', '1');
107 await htmx.timeout(5);
108 document.body.removeAttribute('data-a');
109 document.body.removeAttribute('data-b');
110 document.body.removeAttribute('data-c');
111 await htmx.timeout(5);
112 let added = window.__liveCount - initial;
113 assert.isAtMost(added, 2, 'expected at most 2 coalesced recomputes');
114 delete window.__liveCount;
115 });
116
117 it('does not re-recompute when a binding writes its own attribute', async function() {
118 // A :hidden binding writing the hidden attribute would, if MutationObserver
119 // were active during the write, queue a record and trigger another recompute.
120 // Verify the change-event causes exactly one recompute, not two.
121 window.__selfWriteCount = 0;
122 playground().innerHTML = `
123 <input id="src" type="checkbox">
124 <div :hidden="(window.__selfWriteCount++, q('#src').checked)">x</div>
125 `;
126 htmx.process(playground());
127 await htmx.timeout(10);
128 let initial = window.__selfWriteCount;
129 let inp = playground().querySelector('#src');
130 inp.checked = true;
131 inp.dispatchEvent(new Event('change', { bubbles: true }));
132 await htmx.timeout(20);
133 let added = window.__selfWriteCount - initial;
134 assert.equal(added, 1, 'expected 1 recompute, got ' + added);
135 delete window.__selfWriteCount;
136 });
137
138 it('multiple hx-live elements all run', async function() {
139 playground().innerHTML = `
140 <output id="a" hx-live="this.dataset.v = '1'"></output>
141 <output id="b" hx-live="this.dataset.v = '2'"></output>
142 <output id="c" hx-live="this.dataset.v = '3'"></output>
143 `;
144 htmx.process(playground());
145 playground().querySelector('#a').dataset.v.should.equal('1');
146 playground().querySelector('#b').dataset.v.should.equal('2');
147 playground().querySelector('#c').dataset.v.should.equal('3');
148 });
149
150 it('timeout(ms) is available in scope', async function() {
151 let elt = createProcessedHTML('<output hx-live="(async () => { await timeout(1); this.dataset.v = \'done\'; })()"></output>');
152 await htmx.timeout(20);
153 elt.dataset.v.should.equal('done');
154 });
155
156 it('hx-live body supports top-level await directly', async function() {
157 let elt = createProcessedHTML(
158 `<output hx-live="!this.dataset.s && (this.dataset.s='1', this.dataset.v = 'pending', await timeout(5), this.dataset.v = 'done')"></output>`
159 );
160 elt.dataset.v.should.equal('pending');
161 await htmx.timeout(30);
162 elt.dataset.v.should.equal('done');
163 });
164
165 it('forEvent(event, ms) resolves on event before timeout', async function() {
166 let elt = createProcessedHTML('<output hx-live="(async () => { await forEvent(\'go\', 1000); this.dataset.v = \'fired\'; })()"></output>');
167 await htmx.timeout(5);
168 elt.dispatchEvent(new CustomEvent('go'));
169 await htmx.timeout(5);
170 elt.dataset.v.should.equal('fired');
171 });
172
173 it('forEvent(event, ms) resolves on timeout when event never fires', async function() {
174 let elt = createProcessedHTML('<output hx-live="(async () => { await forEvent(\'never\', 10); this.dataset.v = \'timed-out\'; })()"></output>');
175 await htmx.timeout(40);
176 elt.dataset.v.should.equal('timed-out');
177 });
178
179 it('forEvent resolves a timeout with the original arg (discriminator)', async function() {
180 window.__waitResultLive = null;
181 let elt = createProcessedHTML(
182 `<output hx-live="!this.dataset.s && (this.dataset.s='1', (async()=>{ window.__waitResultLive = await forEvent('never', 5) })())"></output>`
183 );
184 await htmx.timeout(30);
185 window.__waitResultLive.should.equal(5);
186 delete window.__waitResultLive;
187 });
188
189 it('forEvent races multiple events and timeouts', async function() {
190 let elt = createProcessedHTML('<output hx-live="(async () => { await forEvent(\'a\', \'b\', 1000); this.dataset.v = \'fired\'; })()"></output>');
191 await htmx.timeout(5);
192 elt.dispatchEvent(new CustomEvent('b'));
193 await htmx.timeout(5);
194 elt.dataset.v.should.equal('fired');
195 });
196
197 it('nextFrame() resolves on the next animation frame', async function() {
198 window.__liveFrameDone = false;
199 playground().innerHTML = `
200 <output hx-live="(async () => { await nextFrame(); window.__liveFrameDone = true; })()"></output>
201 `;
202 htmx.process(playground());
203 // Synchronously after process, nextFrame() hasn't resolved yet.
204 window.__liveFrameDone.should.equal(false);
205 await new Promise(r => requestAnimationFrame(() => requestAnimationFrame(r)));
206 window.__liveFrameDone.should.equal(true);
207 delete window.__liveFrameDone;
208 });
209
210 it('forEvent cleans up listeners after timeout wins', async function() {
211 let count = 0;
212 let elt = createProcessedHTML(
213 `<output hx-live="!this.dataset.started && (this.dataset.started='1', (async()=>{ await forEvent('cleanup-evt-live', 5); this.dataset.done='1' })())"></output>`
214 );
215 elt.addEventListener('cleanup-evt-live', () => count++);
216 await htmx.timeout(30);
217 elt.dataset.done.should.equal('1');
218 // forEvent timed out; its internal listener should be removed.
219 elt.dispatchEvent(new CustomEvent('cleanup-evt-live'));
220 count.should.equal(1);
221 });
222
223 it('trigger() fires a CustomEvent from the element', async function() {
224 let fired = null;
225 playground().innerHTML = '<output hx-live="trigger(\'live-fire\', { x: 1 })"></output>';
226 playground().querySelector('output').addEventListener('live-fire', e => fired = e);
227 htmx.process(playground());
228 await htmx.timeout(1);
229 assert.isNotNull(fired);
230 fired.detail.x.should.equal(1);
231 });
232
233 it('debounce(ms) supersedes prior calls', async function() {
234 window.__debounceCountLive = 0;
235 playground().innerHTML = `
236 <input id="in" value="1">
237 <output hx-live="(async () => { await debounce(20); window.__debounceCountLive++; q('#in').value; })()"></output>
238 `;
239 htmx.process(playground());
240 let inp = playground().querySelector('#in');
241 for (let i = 0; i < 5; i++) {
242 inp.value = String(i);
243 inp.dispatchEvent(new Event('input', { bubbles: true }));
244 await htmx.timeout(2);
245 }
246 await htmx.timeout(60);
247 assert.isAtMost(window.__debounceCountLive, 2, 'debounce should have superseded most calls');
248 delete window.__debounceCountLive;
249 });
250
251 it('debounce(ms, fn) runs the closure after the delay', async function() {
252 window.__debounceFnCountLive = 0;
253 playground().innerHTML = `
254 <input id="in" value="1">
255 <output hx-live="debounce(20, () => { window.__debounceFnCountLive++; }); q('#in').value;"></output>
256 `;
257 htmx.process(playground());
258 let inp = playground().querySelector('#in');
259 for (let i = 0; i < 5; i++) {
260 inp.value = String(i);
261 inp.dispatchEvent(new Event('input', { bubbles: true }));
262 await htmx.timeout(2);
263 }
264 await htmx.timeout(60);
265 assert.isAtMost(window.__debounceFnCountLive, 2, 'debounce(fn) should have superseded most calls');
266 assert.isAtLeast(window.__debounceFnCountLive, 1, 'debounce(fn) should have run at least once');
267 delete window.__debounceFnCountLive;
268 });
269
270 it('debounce(ms, fn) supersedes across separate hx-on events on the same element', async function() {
271 window.__hxOnDebounceCountLive = 0;
272 playground().innerHTML = `
273 <button hx-on:click="debounce(30, () => { window.__hxOnDebounceCountLive++; })">go</button>
274 `;
275 htmx.process(playground());
276 let btn = playground().querySelector('button');
277 for (let i = 0; i < 5; i++) {
278 btn.click();
279 await htmx.timeout(5);
280 }
281 await htmx.timeout(60);
282 window.__hxOnDebounceCountLive.should.equal(1);
283 delete window.__hxOnDebounceCountLive;
284 });
285
286 it('debounce(ms, fn) keeps distinct closures on independent channels', async function() {
287 window.__chALive = 0;
288 window.__chBLive = 0;
289 playground().innerHTML = `
290 <button id="a" hx-on:click="debounce(30, () => { window.__chALive++; })">A</button>
291 <button id="b" hx-on:click="debounce(30, () => { window.__chBLive++; })">B</button>
292 `;
293 htmx.process(playground());
294 // Different elements ⇒ different htmxProp ⇒ different debounce instances. Both should fire.
295 playground().querySelector('#a').click();
296 playground().querySelector('#b').click();
297 await htmx.timeout(60);
298 window.__chALive.should.equal(1);
299 window.__chBLive.should.equal(1);
300 delete window.__chALive;
301 delete window.__chBLive;
302 });
303
304 it('debounce(ms, fn) does not return a promise', function() {
305 // Use the htmx.live.q-adjacent debounce factory by running a live expression and capturing the return.
306 window.__debounceReturnLive = 'sentinel';
307 playground().innerHTML = `
308 <output hx-live="window.__debounceReturnLive = debounce(5, () => {});"></output>
309 `;
310 htmx.process(playground());
311 assert.isUndefined(window.__debounceReturnLive);
312 delete window.__debounceReturnLive;
313 });
314
315 it('processes hx-live added dynamically via htmx.process', function() {
316 playground().innerHTML = '';
317 let div = document.createElement('div');
318 div.innerHTML = '<output hx-live="this.dataset.v = \'dynamic\'"></output>';
319 playground().appendChild(div);
320 htmx.process(playground());
321 div.querySelector('output').dataset.v.should.equal('dynamic');
322 });
323
324 it('coalesces recomputes during a swap', async function() {
325 window.__swapCountLive = 0;
326 playground().innerHTML = `
327 <div id="content"><span data-id="1"></span></div>
328 <output hx-live="window.__swapCountLive++"></output>
329 `;
330 htmx.process(playground());
331 await htmx.timeout(30);
332 let beforeSwap = window.__swapCountLive;
333
334 mockResponse('GET', '/swap-coalesce-live', '<div id="content"><span data-id="2"></span></div>');
335 await htmx.ajax('GET', '/swap-coalesce-live', { target: '#content', swap: 'outerHTML' });
336 await htmx.timeout(50);
337
338 let added = window.__swapCountLive - beforeSwap;
339 // During-swap mutations are coalesced (swaps>0 guard). Pre/post-swap mutations
340 // (e.g. htmx-request indicator class) legitimately trigger a recompute each.
341 assert.isAtMost(added, 3, 'expected at most a few recomputes, got ' + added);
342 delete window.__swapCountLive;
343 });
344
345 it('iteration cap warns on runaway', async function() {
346 let warned = false;
347 let originalWarn = console.warn;
348 console.warn = (...args) => {
349 if (typeof args[0] === 'string' && args[0].includes('hx-live recompute exceeded')) warned = true;
350 originalWarn.apply(console, args);
351 };
352 try {
353 window.__runawayCountLive = 0;
354 playground().innerHTML = '<output hx-live="window.__runawayCountLive++"></output>';
355 htmx.process(playground());
356
357 for (let i = 0; i < 100; i++) {
358 document.body.setAttribute('data-runaway-test-live', String(i));
359 await htmx.timeout(5);
360 }
361
362 warned.should.equal(true);
363 document.body.removeAttribute('data-runaway-test-live');
364 delete window.__runawayCountLive;
365 } finally {
366 console.warn = originalWarn;
367 }
368 });
369
370 // -------------------------------------------------------------------------
371 // q() proxy
372 // -------------------------------------------------------------------------
373
374 it('q(string) selects elements', function() {
375 playground().innerHTML = '<div class="x">a</div><div class="x">b</div>';
376 let proxy = htmx.live.q('.x');
377 proxy.count.should.equal(2);
378 });
379
380 it('q returns 0-count proxy when no match', function() {
381 let proxy = htmx.live.q('.does-not-exist-anywhere');
382 proxy.count.should.equal(0);
383 });
384
385 it('q(element) wraps a single element', function() {
386 playground().innerHTML = '<div id="x"></div>';
387 let elt = playground().querySelector('#x');
388 let proxy = htmx.live.q(elt);
389 proxy.count.should.equal(1);
390 });
391
392 it('q(iterable) wraps multiple elements', function() {
393 playground().innerHTML = '<div class="x"></div><div class="x"></div>';
394 let nodes = playground().querySelectorAll('.x');
395 let proxy = htmx.live.q(nodes);
396 proxy.count.should.equal(2);
397 });
398
399 it('arr() returns a real array', function() {
400 playground().innerHTML = '<div class="x"></div><div class="x"></div>';
401 let arr = htmx.live.q('.x').arr();
402 assert.isArray(arr);
403 arr.length.should.equal(2);
404 });
405
406 it('iterable via for..of', function() {
407 playground().innerHTML = '<div class="x" data-i="0"></div><div class="x" data-i="1"></div>';
408 let collected = [];
409 for (let e of htmx.live.q('.x')) collected.push(e.dataset.i);
410 collected.should.deep.equal(['0', '1']);
411 });
412
413 it('property read returns first element value', function() {
414 playground().innerHTML = '<input class="x" value="first"><input class="x" value="second">';
415 htmx.live.q('.x').value.should.equal('first');
416 });
417
418 it('property set propagates to all elements', function() {
419 playground().innerHTML = '<input class="x" value="a"><input class="x" value="b">';
420 htmx.live.q('.x').value = 'changed';
421 let inputs = playground().querySelectorAll('.x');
422 inputs[0].value.should.equal('changed');
423 inputs[1].value.should.equal('changed');
424 });
425
426 it('chained property access returns proxy of subproperties', function() {
427 playground().innerHTML = '<div class="x" data-foo="a"></div><div class="x" data-foo="b"></div>';
428 let proxy = htmx.live.q('.x').dataset;
429 proxy.foo.should.equal('a');
430 });
431
432 it('method invocation calls each element, returns first result', function() {
433 playground().innerHTML = '<div class="x"><span>first</span></div><div class="x"><span>second</span></div>';
434 let result = htmx.live.q('.x').querySelector('span');
435 result.textContent.should.equal('first');
436 });
437
438 it('q().trigger() fires CustomEvent on each element', function() {
439 playground().innerHTML = '<div class="x"></div><div class="x"></div>';
440 let fires = 0;
441 for (let e of playground().querySelectorAll('.x')) {
442 e.addEventListener('zap', () => fires++);
443 }
444 htmx.live.q('.x').trigger('zap');
445 fires.should.equal(2);
446 });
447
448 it('q().insert() inserts HTML at the given position', function() {
449 playground().innerHTML = '<div class="x"><p>orig</p></div>';
450 htmx.live.q('.x').insert('end', '<span class="added">new</span>');
451 playground().querySelectorAll('.added').length.should.equal(1);
452 });
453
454 it('insert() scope helper inserts HTML relative to this', function() {
455 playground().innerHTML = `
456 <button hx-on:click="insert('after', '<span class=&quot;added&quot;>+</span>')">Add</button>
457 `;
458 htmx.process(playground());
459 let btn = playground().querySelector('button');
460 btn.click();
461 playground().querySelectorAll('.added').length.should.equal(1);
462 btn.nextElementSibling.classList.contains('added').should.equal(true);
463 });
464
465 it('q().take() moves a class from other elements to selected ones', function() {
466 playground().innerHTML = `
467 <button class="tab selected">a</button>
468 <button class="tab">b</button>
469 <button class="tab">c</button>
470 `;
471 let target = playground().querySelectorAll('.tab')[2];
472 htmx.live.q(target).take('.selected', '.tab');
473
474 let tabs = playground().querySelectorAll('.tab');
475 tabs[0].classList.contains('selected').should.equal(false);
476 tabs[1].classList.contains('selected').should.equal(false);
477 tabs[2].classList.contains('selected').should.equal(true);
478 });
479
480 it('htmx.live.q(target).take() moves a class between elements (selectors)', function() {
481 playground().innerHTML = `
482 <button class="tab selected">a</button>
483 <button class="tab">b</button>
484 <button class="tab" id="t3">c</button>
485 `;
486 htmx.live.q('#t3').take('.selected', '.tab');
487
488 let tabs = playground().querySelectorAll('.tab');
489 tabs[0].classList.contains('selected').should.equal(false);
490 tabs[1].classList.contains('selected').should.equal(false);
491 tabs[2].classList.contains('selected').should.equal(true);
492 });
493
494 it('take() is available at top-level in hx-on expressions', function() {
495 playground().innerHTML = `
496 <div class="tabs">
497 <button class="tab selected">a</button>
498 <button class="tab">b</button>
499 <button class="tab" hx-on:click="take('.selected', '.tab')">c</button>
500 </div>
501 `;
502 htmx.process(playground());
503
504 let tabs = playground().querySelectorAll('.tab');
505 tabs[2].click();
506 tabs[0].classList.contains('selected').should.equal(false);
507 tabs[1].classList.contains('selected').should.equal(false);
508 tabs[2].classList.contains('selected').should.equal(true);
509 });
510
511 it('take() with no scope defaults to parent (sibling scope)', function() {
512 playground().innerHTML = `
513 <nav>
514 <button class="active">a</button>
515 <button id="t">b</button>
516 <button class="active">c</button>
517 </nav>
518 <div class="active">unrelated</div>
519 `;
520 htmx.live.q('#t').take('.active');
521 // Siblings lose .active
522 let nav = playground().querySelector('nav');
523 nav.querySelectorAll('.active').length.should.equal(1);
524 playground().querySelector('#t').classList.contains('active').should.equal(true);
525 // Unrelated element outside parent is untouched
526 playground().querySelector('div').classList.contains('active').should.equal(true);
527 });
528
529 it('take() with element scope searches within that container', function() {
530 playground().innerHTML = `
531 <nav id="nav1">
532 <button class="active">a</button>
533 <button id="t">b</button>
534 </nav>
535 <nav id="nav2">
536 <button class="active">x</button>
537 <button>y</button>
538 </nav>
539 `;
540 let nav1 = playground().querySelector('#nav1');
541 htmx.live.q('#t').take('.active', nav1);
542 playground().querySelector('#t').classList.contains('active').should.equal(true);
543 playground().querySelector('#nav1 button').classList.contains('active').should.equal(false);
544 // nav2 is untouched
545 playground().querySelector('#nav2 .active').should.not.be.null;
546 });
547
548 it('take() in hx-on with this as scope (tabs pattern)', function() {
549 playground().innerHTML = `
550 <nav hx-on:click="
551 let btn = event.target.closest('button');
552 if (!btn) return;
553 q(btn).take('.active', this);
554 ">
555 <button class="active">Home</button>
556 <button>About</button>
557 <button id="click-me">Contact</button>
558 </nav>
559 <div class="active">unrelated</div>
560 `;
561 htmx.process(playground());
562 playground().querySelector('#click-me').click();
563 let buttons = playground().querySelectorAll('nav button');
564 buttons[0].classList.contains('active').should.equal(false);
565 buttons[1].classList.contains('active').should.equal(false);
566 buttons[2].classList.contains('active').should.equal(true);
567 // Unrelated element outside nav is untouched
568 playground().querySelector('div').classList.contains('active').should.equal(true);
569 });
570
571 it('take() canonical sibling form in hx-on', function() {
572 playground().innerHTML = `
573 <nav>
574 <button class="active" hx-on:click="take('.active')">A</button>
575 <button hx-on:click="take('.active')">B</button>
576 <button hx-on:click="take('.active')" id="click-me">C</button>
577 </nav>
578 <button class="active">unrelated</button>
579 `;
580 htmx.process(playground());
581 playground().querySelector('#click-me').click();
582 let navBtns = playground().querySelectorAll('nav button');
583 navBtns[0].classList.contains('active').should.equal(false);
584 navBtns[1].classList.contains('active').should.equal(false);
585 navBtns[2].classList.contains('active').should.equal(true);
586 // Unrelated button outside nav is untouched
587 playground().querySelector('nav + button').classList.contains('active').should.equal(true);
588 });
589
590 it('take() with ARIA and no scope defaults to parent', function() {
591 playground().innerHTML = `
592 <div role="tablist">
593 <button role="tab" aria-selected="true">a</button>
594 <button role="tab" aria-selected="false" id="t">b</button>
595 </div>
596 <button aria-selected="true">unrelated</button>
597 `;
598 htmx.live.q('#t').take('aria-selected');
599 let tabs = playground().querySelectorAll('[role=tab]');
600 tabs[0].getAttribute('aria-selected').should.equal('false');
601 tabs[1].getAttribute('aria-selected').should.equal('true');
602 // Unrelated element outside parent is untouched
603 playground().querySelector('div + button').getAttribute('aria-selected').should.equal('true');
604 });
605
606 it('take() accepts options object { from: selector }', function() {
607 playground().innerHTML = `
608 <button class="tab selected">a</button>
609 <button class="tab">b</button>
610 <button class="tab" id="t3">c</button>
611 <button class="other selected">outside</button>
612 `;
613 htmx.live.q('#t3').take('.selected', { from: '.tab' });
614 let tabs = playground().querySelectorAll('.tab');
615 tabs[0].classList.contains('selected').should.equal(false);
616 tabs[2].classList.contains('selected').should.equal(true);
617 // .other is NOT a .tab, so its .selected stays
618 playground().querySelector('.other').classList.contains('selected').should.equal(true);
619 });
620
621 it('take() with ARIA attribute writes true on me, false on others', function() {
622 playground().innerHTML = `
623 <button role="tab" aria-selected="true">a</button>
624 <button role="tab" aria-selected="false">b</button>
625 <button role="tab" id="t3" aria-selected="false">c</button>
626 `;
627 htmx.live.q('#t3').take('aria-selected', '[role=tab]');
628 let tabs = playground().querySelectorAll('[role=tab]');
629 tabs[0].getAttribute('aria-selected').should.equal('false');
630 tabs[1].getAttribute('aria-selected').should.equal('false');
631 tabs[2].getAttribute('aria-selected').should.equal('true');
632 });
633
634 it('toggle() is available at top-level in hx-on expressions and applies to current element', function() {
635 playground().innerHTML = `
636 <button aria-pressed="false" hx-on:click="toggle('.active'); toggle('aria-pressed')">x</button>
637 `;
638 htmx.process(playground());
639 let btn = playground().querySelector('button');
640 btn.click();
641 btn.classList.contains('active').should.equal(true);
642 btn.getAttribute('aria-pressed').should.equal('true');
643 btn.click();
644 btn.classList.contains('active').should.equal(false);
645 btn.getAttribute('aria-pressed').should.equal('false');
646 });
647
648 it('toggle() in hx-live applies to the current element on each recompute', async function() {
649 // Use a one-shot recompute to flip a class once and confirm targeting.
650 let elt = createProcessedHTML(
651 `<output hx-live="!this.dataset.s && (this.dataset.s='1', toggle('.flipped'))"></output>`
652 );
653 await htmx.timeout(5);
654 elt.classList.contains('flipped').should.equal(true);
655 });
656
657 it('directional: closest', function() {
658 playground().innerHTML = '<section><div id="inner"></div></section>';
659 let inner = playground().querySelector('#inner');
660 let proxy = htmx.live.q(inner);
661 proxy.count.should.equal(1);
662 });
663
664 it('directional: first picks the first match', function() {
665 playground().innerHTML = '<i class="z">a</i><i class="z">b</i><i class="z">c</i>';
666 let proxy = htmx.live.q('first .z');
667 proxy.count.should.equal(1);
668 proxy.textContent.should.equal('a');
669 });
670
671 it('directional: last picks the last match', function() {
672 playground().innerHTML = '<i class="z">a</i><i class="z">b</i><i class="z">c</i>';
673 let proxy = htmx.live.q('last .z');
674 proxy.count.should.equal(1);
675 proxy.textContent.should.equal('c');
676 });
677
678 it('"sel in #scope" scopes to a different root', function() {
679 playground().innerHTML = '<div class="z">outside</div><section id="scope"><div class="z">inside</div></section>';
680 let proxy = htmx.live.q('.z in #scope');
681 proxy.count.should.equal(1);
682 proxy.textContent.should.equal('inside');
683 });
684
685 it('"sel in #unknown" returns empty proxy when scope is missing', function() {
686 let proxy = htmx.live.q('.z in #does-not-exist');
687 proxy.count.should.equal(0);
688 });
689
690 it('"sel in .multi" unions matches across all root elements in document order', function() {
691 playground().innerHTML =
692 '<section class="bar"><span class="foo">a</span></section>' +
693 '<section><span class="foo">skip</span></section>' +
694 '<section class="bar"><span class="foo">b</span><span class="foo">c</span></section>';
695 let proxy = htmx.live.q('.foo in .bar');
696 proxy.count.should.equal(3);
697 proxy.arr().map(e => e.textContent).should.deep.equal(['a', 'b', 'c']);
698 });
699
700 it('"sel in me" scopes to the current hx-live element (alias of "this")', async function() {
701 playground().innerHTML = `
702 <div hx-live="this.dataset.v = q('span in me').count">
703 <span>a</span>
704 <span>b</span>
705 </div>
706 <span>outside</span>
707 `;
708 htmx.process(playground());
709 await htmx.timeout(5);
710 playground().querySelector('div').dataset.v.should.equal('2');
711 });
712
713 it('"sel in me" and "sel in this" return the same elements', async function() {
714 playground().innerHTML = `
715 <div id="me-vs-this" hx-live="
716 this.dataset.me = q('span in me').count;
717 this.dataset.this = q('span in this').count;
718 ">
719 <span>a</span>
720 <span>b</span>
721 <span>c</span>
722 </div>
723 `;
724 htmx.process(playground());
725 await htmx.timeout(5);
726 let div = playground().querySelector('#me-vs-this');
727 div.dataset.me.should.equal('3');
728 div.dataset.this.should.equal('3');
729 });
730
731 it('"first sel in .multi" picks the first match across all roots', function() {
732 playground().innerHTML =
733 '<section class="bar"><span class="foo">a</span></section>' +
734 '<section class="bar"><span class="foo">b</span></section>';
735 htmx.live.q('first .foo in .bar').textContent.should.equal('a');
736 htmx.live.q('last .foo in .bar').textContent.should.equal('b');
737 });
738
739 it('toggle(".foo") toggles a class', function() {
740 playground().innerHTML = '<div class="x"></div><div class="x active"></div>';
741 let p = htmx.live.q('.x');
742 p.toggle('.active');
743 playground().querySelectorAll('.x.active').length.should.equal(1);
744 playground().querySelectorAll('.x:not(.active)').length.should.equal(1);
745 });
746
747 it('toggle("attr") toggles boolean attribute presence', function() {
748 playground().innerHTML = '<input class="x"><input class="x" disabled>';
749 htmx.live.q('.x').toggle('disabled');
750 let inputs = playground().querySelectorAll('.x');
751 inputs[0].hasAttribute('disabled').should.equal(true);
752 inputs[1].hasAttribute('disabled').should.equal(false);
753 });
754
755 it('toggle("aria-*") flips between "true" and "false"', function() {
756 playground().innerHTML = '<button id="a"></button><button id="b" aria-pressed="true"></button>';
757 let p = htmx.live.q('button');
758 p.toggle('aria-pressed');
759 // a had no aria-pressed (effectively absent → not "true") → becomes "true"
760 playground().querySelector('#a').getAttribute('aria-pressed').should.equal('true');
761 // b had "true" → becomes "false"
762 playground().querySelector('#b').getAttribute('aria-pressed').should.equal('false');
763 // toggle again
764 p.toggle('aria-pressed');
765 playground().querySelector('#a').getAttribute('aria-pressed').should.equal('false');
766 playground().querySelector('#b').getAttribute('aria-pressed').should.equal('true');
767 });
768
769 it('toggle(name, "a|b|c") cycles attribute through values', function() {
770 playground().innerHTML = '<div></div>';
771 let div = playground().querySelector('div');
772 let p = htmx.live.q('div');
773 p.toggle('data-mode', 'light|dark|auto');
774 div.getAttribute('data-mode').should.equal('light');
775 p.toggle('data-mode', 'light|dark|auto');
776 div.getAttribute('data-mode').should.equal('dark');
777 p.toggle('data-mode', 'light|dark|auto');
778 div.getAttribute('data-mode').should.equal('auto');
779 p.toggle('data-mode', 'light|dark|auto');
780 div.getAttribute('data-mode').should.equal('light');
781 });
782
783 it('toggle(name, [array]) cycles attribute through values (array form)', function() {
784 playground().innerHTML = '<div></div>';
785 let div = playground().querySelector('div');
786 let p = htmx.live.q('div');
787 p.toggle('data-mode', ['light', 'dark', 'auto']);
788 div.getAttribute('data-mode').should.equal('light');
789 p.toggle('data-mode', ['light', 'dark', 'auto']);
790 div.getAttribute('data-mode').should.equal('dark');
791 });
792
793 it('toggle(name, "v|") cycles attribute between value and absent', function() {
794 playground().innerHTML = '<div></div>';
795 let div = playground().querySelector('div');
796 let p = htmx.live.q('div');
797 p.toggle('data-state', 'on|');
798 div.getAttribute('data-state').should.equal('on');
799 p.toggle('data-state', 'on|');
800 div.hasAttribute('data-state').should.equal(false);
801 p.toggle('data-state', 'on|');
802 div.getAttribute('data-state').should.equal('on');
803 });
804
805 it('toggle cycle snaps to first value when current is out-of-list', function() {
806 playground().innerHTML = '<div data-mode="weird"></div>';
807 let div = playground().querySelector('div');
808 htmx.live.q('div').toggle('data-mode', 'light|dark|auto');
809 div.getAttribute('data-mode').should.equal('light');
810 });
811
812 it('toggle(".class", "a|b|c") cycles through classes (only one at a time)', function() {
813 playground().innerHTML = '<div></div>';
814 let div = playground().querySelector('div');
815 let p = htmx.live.q('div');
816 p.toggle('.size', 'sm|md|lg');
817 div.classList.contains('sm').should.equal(true);
818 p.toggle('.size', 'sm|md|lg');
819 div.classList.contains('md').should.equal(true);
820 div.classList.contains('sm').should.equal(false);
821 p.toggle('.size', 'sm|md|lg');
822 div.classList.contains('lg').should.equal(true);
823 div.classList.contains('md').should.equal(false);
824 });
825
826 it('toggle is chainable', function() {
827 playground().innerHTML = '<button></button>';
828 let r = htmx.live.q('button').toggle('.active').toggle('aria-pressed').trigger('changed');
829 r.count.should.equal(1);
830 let btn = playground().querySelector('button');
831 btn.classList.contains('active').should.equal(true);
832 btn.getAttribute('aria-pressed').should.equal('true');
833 });
834
835 it('proxy.trigger/insert/take return the proxy for chaining', function() {
836 playground().innerHTML = '<div class="src">a</div><div class="dst"></div><div class="dst"></div>';
837 let dst = htmx.live.q('.dst');
838 let r = dst.take('.active', '.src').trigger('refresh').insert('end', '<span>x</span>');
839 r.count.should.equal(2);
840 playground().querySelectorAll('.dst.active').length.should.equal(2);
841 playground().querySelectorAll('.src.active').length.should.equal(0);
842 playground().querySelectorAll('.dst > span').length.should.equal(2);
843 });
844
845 it('proxy exposes array methods (map, filter, reduce, forEach)', function() {
846 playground().innerHTML = '<div class="x">a</div><div class="x">b</div><div class="x">c</div>';
847 let proxy = htmx.live.q('.x');
848 proxy.map(e => e.textContent).should.deep.equal(['a', 'b', 'c']);
849 proxy.filter(e => e.textContent !== 'b').length.should.equal(2);
850 proxy.reduce((acc, e) => acc + e.textContent, '').should.equal('abc');
851 let collected = [];
852 proxy.forEach(e => collected.push(e.textContent));
853 collected.should.deep.equal(['a', 'b', 'c']);
854 proxy.some(e => e.textContent === 'b').should.equal(true);
855 proxy.every(e => e.textContent.length === 1).should.equal(true);
856 proxy.find(e => e.textContent === 'b').textContent.should.equal('b');
857 proxy.at(-1).textContent.should.equal('c');
858 });
859
860 it('q is exposed on the htmx public API', function() {
861 assert.isFunction(htmx.live.q);
862 });
863
864 it('htmx.live namespace exposes q, debounce, and refresh', function() {
865 assert.isObject(htmx.live);
866 assert.isFunction(htmx.live.q);
867 assert.isFunction(htmx.live.debounce);
868 assert.isFunction(htmx.live.refresh);
869 assert.isFunction(htmx.live.toggle);
870 });
871
872 it('classList scope helper accesses this.classList', function() {
873 playground().innerHTML = `
874 <button hx-on:click="classList.add('done'); classList.remove('pending')">Go</button>
875 `;
876 htmx.process(playground());
877 let btn = playground().querySelector('button');
878 btn.classList.add('pending');
879 btn.click();
880 btn.classList.contains('done').should.equal(true);
881 btn.classList.contains('pending').should.equal(false);
882 });
883
884 it('htmx.live.toggle(target, name) toggles across matches', function() {
885 playground().innerHTML = `
886 <div class="tab"></div>
887 <div class="tab active"></div>
888 `;
889 htmx.live.toggle('.tab', '.active');
890 let tabs = playground().querySelectorAll('.tab');
891 tabs[0].classList.contains('active').should.equal(true);
892 tabs[1].classList.contains('active').should.equal(false);
893 });
894
895 it('htmx.live.refresh() recomputes live expressions even when no DOM event triggered', async function() {
896 // Using a non-reactive external value: the expression reads window.__refreshSrcLive.
897 // Mutating that value will not trigger any DOM input/change/mutation listener,
898 // so without an explicit refresh() the expression won't recompute.
899 window.__refreshSrcLive = 'first';
900 let elt = createProcessedHTML(
901 '<output hx-live="this.dataset.v = window.__refreshSrcLive"></output>'
902 );
903 elt.dataset.v.should.equal('first');
904
905 window.__refreshSrcLive = 'second';
906 // No DOM mutation happened; the expression should still hold the old value.
907 elt.dataset.v.should.equal('first');
908
909 htmx.live.refresh();
910 await htmx.timeout(5);
911 elt.dataset.v.should.equal('second');
912 delete window.__refreshSrcLive;
913 });
914
915 it('q in hx-live scope resolves directionals relative to the element', async function() {
916 playground().innerHTML = `
917 <div id="anchor">
918 <input value="seed">
919 </div>
920 <output hx-live="this.dataset.v = q('first input in #anchor').value"></output>
921 `;
922 htmx.process(playground());
923 await htmx.timeout(5);
924 playground().querySelector('output').dataset.v.should.equal('seed');
925 });
926
927 // -------------------------------------------------------------------------
928 // scope injection in hx-on (via htmx:scope hook)
929 // -------------------------------------------------------------------------
930
931 it('chained q: climb-and-collect via closest', function() {
932 playground().innerHTML = `
933 <div class="field"><input class="x invalid"></div>
934 <div class="field"><input class="x"></div>
935 <div class="field"><input class="x invalid"></div>
936 `;
937 let proxy = htmx.live.q('.invalid').q('closest .field');
938 proxy.count.should.equal(2);
939 });
940
941 it('chained q: first per group', function() {
942 playground().innerHTML = `
943 <section><span class="i">a</span><span class="i">b</span></section>
944 <section><span class="i">c</span><span class="i">d</span></section>
945 `;
946 let proxy = htmx.live.q('section').q('first .i');
947 proxy.count.should.equal(2);
948 proxy.arr().map(e => e.textContent).should.deep.equal(['a', 'c']);
949 });
950
951 it('chained q: plain selector scopes to descendants of each parent', function() {
952 playground().innerHTML = `
953 <article><p class="t">a</p></article>
954 <article><p class="t">b</p></article>
955 <p class="t">outside</p>
956 `;
957 let proxy = htmx.live.q('article').q('.t');
958 proxy.count.should.equal(2);
959 });
960
961 it('chained q: dedups overlapping results', function() {
962 playground().innerHTML = `
963 <div class="parent"><div class="parent"><span class="x"></span></div></div>
964 `;
965 let proxy = htmx.live.q('.parent').q('.x');
966 proxy.count.should.equal(1);
967 });
968
969 it('q is available in hx-on scope and bound to element', function() {
970 playground().innerHTML = '<button hx-on:click="window.fooLive = q(\'next #target\').textContent">x</button><div id="target">tgt</div>';
971 htmx.process(playground());
972 playground().querySelector('button').click();
973 window.fooLive.should.equal('tgt');
974 delete window.fooLive;
975 });
976
977 // -------------------------------------------------------------------------
978 // attr() scope helper
979 // -------------------------------------------------------------------------
980
981 it('attr() getter: boolean attr returns boolean', function() {
982 playground().innerHTML = '<input id="a" disabled><input id="b">';
983 htmx.live.attr('#a', 'disabled').should.equal(true);
984 htmx.live.attr('#b', 'disabled').should.equal(false);
985 });
986
987 it('attr() getter: ARIA returns boolean from "true"/"false"', function() {
988 playground().innerHTML = '<div id="a" aria-expanded="true"></div><div id="b" aria-expanded="false"></div>';
989 htmx.live.attr('#a', 'aria-expanded').should.equal(true);
990 htmx.live.attr('#b', 'aria-expanded').should.equal(false);
991 });
992
993 it('attr() getter: .class returns boolean (has class)', function() {
994 playground().innerHTML = '<div id="a" class="foo"></div><div id="b"></div>';
995 htmx.live.attr('#a', '.foo').should.equal(true);
996 htmx.live.attr('#b', '.foo').should.equal(false);
997 });
998
999 it('attr() getter: class returns full class string', function() {
1000 playground().innerHTML = '<div id="a" class="foo bar baz"></div>';
1001 htmx.live.attr('#a', 'class').should.equal('foo bar baz');
1002 });
1003
1004 it('attr() getter: regular attr returns string or null', function() {
1005 playground().innerHTML = '<div id="a" data-x="hello"></div><div id="b"></div>';
1006 htmx.live.attr('#a', 'data-x').should.equal('hello');
1007 assert.isNull(htmx.live.attr('#b', 'data-x'));
1008 });
1009
1010 it('attr() getter: checked returns property value', function() {
1011 playground().innerHTML = '<input id="a" type="checkbox" checked><input id="b" type="checkbox">';
1012 htmx.live.attr('#a', 'checked').should.equal(true);
1013 htmx.live.attr('#b', 'checked').should.equal(false);
1014 });
1015
1016 it('attr() getter: value returns property value', function() {
1017 playground().innerHTML = '<input id="a" value="hello">';
1018 let inp = playground().querySelector('#a');
1019 // After user interaction the property and attribute can diverge
1020 inp.value = 'world';
1021 htmx.live.attr('#a', 'value').should.equal('world');
1022 });
1023
1024 it('attr() setter: boolean attr truthy sets, falsy removes', function() {
1025 playground().innerHTML = '<input id="a">';
1026 htmx.live.attr('#a', 'disabled', true);
1027 playground().querySelector('#a').hasAttribute('disabled').should.equal(true);
1028 htmx.live.attr('#a', 'disabled', false);
1029 playground().querySelector('#a').hasAttribute('disabled').should.equal(false);
1030 });
1031
1032 it('attr() setter: ARIA writes "true"/"false", never removes', function() {
1033 playground().innerHTML = '<div id="a"></div>';
1034 let div = playground().querySelector('#a');
1035 htmx.live.attr('#a', 'aria-expanded', true);
1036 div.getAttribute('aria-expanded').should.equal('true');
1037 htmx.live.attr('#a', 'aria-expanded', false);
1038 div.getAttribute('aria-expanded').should.equal('false');
1039 // null/undefined also writes "false". ARIA is never removed.
1040 htmx.live.attr('#a', 'aria-expanded', null);
1041 div.getAttribute('aria-expanded').should.equal('false');
1042 });
1043
1044 it('attr() setter: aria-* strings and numbers pass through', function() {
1045 playground().innerHTML = '<div id="a"></div><div id="b"></div><div id="c"></div>';
1046 // String values (tristate, tokens) pass through unchanged.
1047 htmx.live.attr('#a', 'aria-pressed', 'mixed');
1048 playground().querySelector('#a').getAttribute('aria-pressed').should.equal('mixed');
1049 htmx.live.attr('#b', 'aria-current', 'page');
1050 playground().querySelector('#b').getAttribute('aria-current').should.equal('page');
1051 // Numbers stringify (e.g. aria-valuenow).
1052 htmx.live.attr('#c', 'aria-valuenow', 50);
1053 playground().querySelector('#c').getAttribute('aria-valuenow').should.equal('50');
1054 });
1055
1056 it('attr() setter: .class true/false add/remove', function() {
1057 playground().innerHTML = '<div id="a"></div>';
1058 let div = playground().querySelector('#a');
1059 htmx.live.attr('#a', '.active', true);
1060 div.classList.contains('active').should.equal(true);
1061 htmx.live.attr('#a', '.active', false);
1062 div.classList.contains('active').should.equal(false);
1063 });
1064
1065 it('attr() setter: class (string) sets managed class list', function() {
1066 playground().innerHTML = '<div id="a" class="external"></div>';
1067 let div = playground().querySelector('#a');
1068 htmx.live.attr('#a', 'class', 'foo bar');
1069 div.classList.contains('external').should.equal(true);
1070 div.classList.contains('foo').should.equal(true);
1071 div.classList.contains('bar').should.equal(true);
1072
1073 // Re-apply with different set. Previous managed dropped, external untouched.
1074 htmx.live.attr('#a', 'class', 'baz');
1075 div.classList.contains('external').should.equal(true);
1076 div.classList.contains('foo').should.equal(false);
1077 div.classList.contains('bar').should.equal(false);
1078 div.classList.contains('baz').should.equal(true);
1079 });
1080
1081 it('attr() setter: class (object) toggles each independently', function() {
1082 playground().innerHTML = '<div id="a" class="external"></div>';
1083 let div = playground().querySelector('#a');
1084 htmx.live.attr('#a', 'class', { foo: true, bar: false });
1085 div.classList.contains('foo').should.equal(true);
1086 div.classList.contains('bar').should.equal(false);
1087 div.classList.contains('external').should.equal(true);
1088
1089 // Flip foo, set bar
1090 htmx.live.attr('#a', 'class', { foo: false, bar: true });
1091 div.classList.contains('foo').should.equal(false);
1092 div.classList.contains('bar').should.equal(true);
1093 });
1094
1095 it('attr() setter: class (object) supports space-separated keys', function() {
1096 playground().innerHTML = '<div id="a"></div>';
1097 let div = playground().querySelector('#a');
1098 htmx.live.attr('#a', 'class', { 'foo bar': true, baz: false });
1099 div.classList.contains('foo').should.equal(true);
1100 div.classList.contains('bar').should.equal(true);
1101 div.classList.contains('baz').should.equal(false);
1102 });
1103
1104 it('attr() setter: checked syncs property and attribute', function() {
1105 playground().innerHTML = '<input id="a" type="checkbox">';
1106 let inp = playground().querySelector('#a');
1107 htmx.live.attr('#a', 'checked', true);
1108 inp.checked.should.equal(true);
1109 inp.hasAttribute('checked').should.equal(true);
1110 htmx.live.attr('#a', 'checked', false);
1111 inp.checked.should.equal(false);
1112 inp.hasAttribute('checked').should.equal(false);
1113 });
1114
1115 it('attr() setter: value syncs property and attribute', function() {
1116 playground().innerHTML = '<input id="a" type="text">';
1117 let inp = playground().querySelector('#a');
1118 htmx.live.attr('#a', 'value', 'hello');
1119 inp.value.should.equal('hello');
1120 inp.getAttribute('value').should.equal('hello');
1121 htmx.live.attr('#a', 'value', null);
1122 inp.value.should.equal('');
1123 inp.hasAttribute('value').should.equal(false);
1124 });
1125
1126 it('attr() setter: regular attr null removes', function() {
1127 playground().innerHTML = '<div id="a" data-x="hello"></div>';
1128 htmx.live.attr('#a', 'data-x', null);
1129 playground().querySelector('#a').hasAttribute('data-x').should.equal(false);
1130 });
1131
1132 it('attr() setter: regular attr stringifies non-string values', function() {
1133 playground().innerHTML = '<div id="a"></div>';
1134 htmx.live.attr('#a', 'data-x', 42);
1135 playground().querySelector('#a').getAttribute('data-x').should.equal('42');
1136 });
1137
1138 it('attr() setter: contenteditable false writes "false" string, not removes', function() {
1139 playground().innerHTML = '<div id="a"></div>';
1140 htmx.live.attr('#a', 'contenteditable', false);
1141 playground().querySelector('#a').getAttribute('contenteditable').should.equal('false');
1142 });
1143
1144 it('attr() setter: draggable false writes "false" string', function() {
1145 playground().innerHTML = '<div id="a"></div>';
1146 htmx.live.attr('#a', 'draggable', false);
1147 playground().querySelector('#a').getAttribute('draggable').should.equal('false');
1148 });
1149
1150 it('attr() setter: spellcheck false writes "false" string', function() {
1151 playground().innerHTML = '<div id="a"></div>';
1152 htmx.live.attr('#a', 'spellcheck', false);
1153 playground().querySelector('#a').getAttribute('spellcheck').should.equal('false');
1154 });
1155
1156 it('attr() setter: contenteditable null removes attribute', function() {
1157 playground().innerHTML = '<div id="a" contenteditable="true"></div>';
1158 htmx.live.attr('#a', 'contenteditable', null);
1159 playground().querySelector('#a').hasAttribute('contenteditable').should.equal(false);
1160 });
1161
1162 it('q().attr() applies setter to all matched elements', function() {
1163 playground().innerHTML = '<input class="x"><input class="x"><input class="x">';
1164 htmx.live.q('.x').attr('disabled', true);
1165 let inputs = playground().querySelectorAll('.x');
1166 for (let inp of inputs) inp.hasAttribute('disabled').should.equal(true);
1167 });
1168
1169 it('q().attr() getter returns from first matched element', function() {
1170 playground().innerHTML = '<div class="x" data-i="a"></div><div class="x" data-i="b"></div>';
1171 htmx.live.q('.x').attr('data-i').should.equal('a');
1172 });
1173
1174 it('q().attr() returns proxy for chaining', function() {
1175 playground().innerHTML = '<button class="x"></button>';
1176 let r = htmx.live.q('.x').attr('role', 'button').attr('.active', true);
1177 r.count.should.equal(1);
1178 let btn = playground().querySelector('.x');
1179 btn.getAttribute('role').should.equal('button');
1180 btn.classList.contains('active').should.equal(true);
1181 });
1182
1183 it('attr() is available in hx-on scope bound to element', function() {
1184 playground().innerHTML = '<button hx-on:click="attr(\'data-clicked\', \'yes\')">x</button>';
1185 htmx.process(playground());
1186 let btn = playground().querySelector('button');
1187 btn.click();
1188 btn.getAttribute('data-clicked').should.equal('yes');
1189 });
1190
1191 it('attr() in hx-live expression operates on current element', async function() {
1192 let elt = createProcessedHTML(
1193 `<output hx-live="!this.dataset.s && (this.dataset.s='1', attr('.flipped', true))"></output>`
1194 );
1195 await htmx.timeout(5);
1196 elt.classList.contains('flipped').should.equal(true);
1197 });
1198
1199 // -------------------------------------------------------------------------
1200 // matches() scope helper
1201 // -------------------------------------------------------------------------
1202
1203 it('matches() is available in hx-on scope bound to element', function() {
1204 playground().innerHTML = '<input id="i" type="text" required hx-on:click="window.__matchesLive = matches(\':required\')">';
1205 htmx.process(playground());
1206 playground().querySelector('#i').click();
1207 window.__matchesLive.should.equal(true);
1208 delete window.__matchesLive;
1209 });
1210
1211 it('matches() in hx-live expression operates on current element', async function() {
1212 playground().innerHTML = `
1213 <input id="src">
1214 <div hx-live="this.dataset.has = matches(':has(input)')">
1215 <input>
1216 </div>
1217 `;
1218 htmx.process(playground());
1219 await htmx.timeout(5);
1220 let div = playground().querySelector('[hx-live]');
1221 div.dataset.has.should.equal('true');
1222 });
1223
1224 it('htmx.live.attr is exposed on public API', function() {
1225 assert.isFunction(htmx.live.attr);
1226 });
1227
1228 // -------------------------------------------------------------------------
1229 // cascading data proxy
1230 // -------------------------------------------------------------------------
1231
1232 it('data.foo reads this.dataset.foo when present locally', async function() {
1233 playground().innerHTML = `
1234 <div id="me" data-foo="local"
1235 hx-on:click="this.dataset.v = data.foo">x</div>
1236 `;
1237 htmx.process(playground());
1238 let elt = playground().querySelector('#me');
1239 elt.click();
1240 elt.dataset.v.should.equal('local');
1241 });
1242
1243 it('data.foo cascades up to closest ancestor', async function() {
1244 playground().innerHTML = `
1245 <section data-currency="USD">
1246 <article>
1247 <span id="me" hx-on:click="this.dataset.v = data.currency">x</span>
1248 </article>
1249 </section>
1250 `;
1251 htmx.process(playground());
1252 let elt = playground().querySelector('#me');
1253 elt.click();
1254 elt.dataset.v.should.equal('USD');
1255 });
1256
1257 it('data.foo returns undefined when no ancestor has it', async function() {
1258 playground().innerHTML = `
1259 <div id="me" hx-on:click="this.dataset.v = (data.nonexistent === undefined ? 'undef' : 'set')">x</div>
1260 `;
1261 htmx.process(playground());
1262 let elt = playground().querySelector('#me');
1263 elt.click();
1264 elt.dataset.v.should.equal('undef');
1265 });
1266
1267 it('data.foo nested: innermost wins (shadowing)', async function() {
1268 playground().innerHTML = `
1269 <section data-mode="outer">
1270 <article data-mode="inner">
1271 <span id="me" hx-on:click="this.dataset.v = data.mode">x</span>
1272 </article>
1273 </section>
1274 `;
1275 htmx.process(playground());
1276 let elt = playground().querySelector('#me');
1277 elt.click();
1278 elt.dataset.v.should.equal('inner');
1279 });
1280
1281 it('data.foo = "x" writes to closest ancestor with data-foo', async function() {
1282 playground().innerHTML = `
1283 <section data-counter="0">
1284 <article>
1285 <button id="me" hx-on:click="data.counter = +data.counter + 1">+</button>
1286 </article>
1287 </section>
1288 `;
1289 htmx.process(playground());
1290 let btn = playground().querySelector('#me');
1291 let section = playground().querySelector('section');
1292 btn.click();
1293 section.dataset.counter.should.equal('1');
1294 btn.click();
1295 section.dataset.counter.should.equal('2');
1296 });
1297
1298 it('data.foo = "x" writes to this when no ancestor has data-foo', async function() {
1299 playground().innerHTML = `
1300 <button id="me" hx-on:click="data.fresh = 'created'">x</button>
1301 `;
1302 htmx.process(playground());
1303 let btn = playground().querySelector('#me');
1304 btn.click();
1305 btn.dataset.fresh.should.equal('created');
1306 });
1307
1308 it('data.foo++ works (auto-coerces to number)', async function() {
1309 playground().innerHTML = `
1310 <section data-counter="5">
1311 <button id="me" hx-on:click="data.counter++">+</button>
1312 </section>
1313 `;
1314 htmx.process(playground());
1315 let btn = playground().querySelector('#me');
1316 let section = playground().querySelector('section');
1317 btn.click();
1318 section.dataset.counter.should.equal('6');
1319 });
1320
1321 it('data proxy: boolean round-trips through JSON', async function() {
1322 playground().innerHTML = `
1323 <section data-active="false">
1324 <button id="me" hx-on:click="data.active = !data.active">toggle</button>
1325 </section>
1326 `;
1327 htmx.process(playground());
1328 let btn = playground().querySelector('#me');
1329 let section = playground().querySelector('section');
1330 btn.click();
1331 section.dataset.active.should.equal('true');
1332 btn.click();
1333 section.dataset.active.should.equal('false');
1334 });
1335
1336 it('data proxy: number round-trips through JSON', async function() {
1337 playground().innerHTML = `
1338 <section data-count="0">
1339 <button id="me" hx-on:click="data.count = data.count + 1">+</button>
1340 </section>
1341 `;
1342 htmx.process(playground());
1343 let btn = playground().querySelector('#me');
1344 let section = playground().querySelector('section');
1345 (typeof section.dataset.count).should.equal('string');
1346 btn.click();
1347 section.dataset.count.should.equal('1');
1348 btn.click();
1349 section.dataset.count.should.equal('2');
1350 });
1351
1352 it('data proxy: object round-trips through JSON', async function() {
1353 playground().innerHTML = `
1354 <section data-user='{"name":"alice","age":30}'>
1355 <button id="me" hx-on:click="data.user = {...data.user, age: data.user.age + 1}">bday</button>
1356 <span id="out" hx-on:click="this.dataset.v = data.user.name + ':' + data.user.age">read</span>
1357 </section>
1358 `;
1359 htmx.process(playground());
1360 let btn = playground().querySelector('#me');
1361 let out = playground().querySelector('#out');
1362 let section = playground().querySelector('section');
1363 out.click();
1364 out.dataset.v.should.equal('alice:30');
1365 btn.click();
1366 JSON.parse(section.dataset.user).age.should.equal(31);
1367 out.click();
1368 out.dataset.v.should.equal('alice:31');
1369 });
1370
1371 it('data proxy: array round-trips through JSON', async function() {
1372 playground().innerHTML = `
1373 <section data-items='[]'>
1374 <button id="add" hx-on:click="data.items = [...data.items, data.items.length]">add</button>
1375 <span id="out" hx-on:click="this.dataset.v = data.items.length">count</span>
1376 </section>
1377 `;
1378 htmx.process(playground());
1379 let add = playground().querySelector('#add');
1380 let out = playground().querySelector('#out');
1381 let section = playground().querySelector('section');
1382 out.click();
1383 out.dataset.v.should.equal('0');
1384 add.click();
1385 add.click();
1386 add.click();
1387 JSON.parse(section.dataset.items).should.deep.equal([0, 1, 2]);
1388 out.click();
1389 out.dataset.v.should.equal('3');
1390 });
1391
1392 it('data proxy: plain string stays as string', async function() {
1393 playground().innerHTML = `
1394 <div data-label="hello">
1395 <span id="me" hx-on:click="this.dataset.v = typeof data.label + ':' + data.label">x</span>
1396 </div>
1397 `;
1398 htmx.process(playground());
1399 let elt = playground().querySelector('#me');
1400 elt.click();
1401 elt.dataset.v.should.equal('string:hello');
1402 });
1403
1404 it('data proxy: null round-trips through JSON', async function() {
1405 playground().innerHTML = `
1406 <section data-val="null">
1407 <span id="me" hx-on:click="this.dataset.v = (data.val === null ? 'is-null' : 'not-null')">x</span>
1408 </section>
1409 `;
1410 htmx.process(playground());
1411 let elt = playground().querySelector('#me');
1412 elt.click();
1413 elt.dataset.v.should.equal('is-null');
1414 });
1415
1416 it('with (data) { foo++ } increments cascading value', async function() {
1417 playground().innerHTML = `
1418 <section data-counter="10">
1419 <button id="me" hx-on:click="with (data) { counter++ }">+</button>
1420 </section>
1421 `;
1422 htmx.process(playground());
1423 let btn = playground().querySelector('#me');
1424 let section = playground().querySelector('section');
1425 btn.click();
1426 section.dataset.counter.should.equal('11');
1427 });
1428
1429 it('with (data) destructuring works for read', async function() {
1430 playground().innerHTML = `
1431 <section data-x="5" data-y="3">
1432 <button id="me" hx-on:click="
1433 with (data) {
1434 this.dataset.sum = +x + +y;
1435 }
1436 ">x</button>
1437 </section>
1438 `;
1439 htmx.process(playground());
1440 let btn = playground().querySelector('#me');
1441 btn.click();
1442 btn.dataset.sum.should.equal('8');
1443 });
1444
1445 it('data.kebabKey camelCase translation works', async function() {
1446 playground().innerHTML = `
1447 <div data-my-value="hello">
1448 <span id="me" hx-on:click="this.dataset.v = data.myValue">x</span>
1449 </div>
1450 `;
1451 htmx.process(playground());
1452 let elt = playground().querySelector('#me');
1453 elt.click();
1454 elt.dataset.v.should.equal('hello');
1455 });
1456
1457 it('data proxy supports object spread with cascading values', async function() {
1458 playground().innerHTML = `
1459 <section data-x="1" data-y="2" data-user='{"name":"alice"}'>
1460 <article data-y="3">
1461 <button id="me" hx-on:click="window.__spreadDataLive = { ...data }">x</button>
1462 </article>
1463 </section>
1464 `;
1465 htmx.process(playground());
1466 playground().querySelector('#me').click();
1467 window.__spreadDataLive.x.should.equal(1);
1468 window.__spreadDataLive.y.should.equal(3);
1469 window.__spreadDataLive.user.should.deep.equal({ name: 'alice' });
1470 window.__spreadDataLive.should.not.have.property('htmxPowered');
1471 });
1472
1473 it('data proxy supports Object.keys/Object.values/Object.entries', async function() {
1474 playground().innerHTML = `
1475 <section data-x="1" data-y="2">
1476 <article data-y="3" data-z="4">
1477 <button id="me" hx-on:click="
1478 window.__keysDataLive = Object.keys(data);
1479 window.__valuesDataLive = Object.values(data);
1480 window.__entriesDataLive = Object.entries(data);
1481 ">x</button>
1482 </article>
1483 </section>
1484 `;
1485 htmx.process(playground());
1486 playground().querySelector('#me').click();
1487 window.__keysDataLive.slice(0, 3).should.deep.equal(['y', 'z', 'x']);
1488 window.__valuesDataLive.slice(0, 3).should.deep.equal([3, 4, 1]);
1489 window.__entriesDataLive.slice(0, 3).should.deep.equal([['y', 3], ['z', 4], ['x', 1]]);
1490 window.__keysDataLive.should.not.include('htmxPowered');
1491 });
1492
1493 it('data proxy supports object rest destructuring', async function() {
1494 playground().innerHTML = `
1495 <section data-x="1" data-y="2" data-z="3">
1496 <button id="me" hx-on:click="
1497 let { x, ...rest } = data;
1498 window.__restDataLive = rest;
1499 ">x</button>
1500 </section>
1501 `;
1502 htmx.process(playground());
1503 playground().querySelector('#me').click();
1504 window.__restDataLive.y.should.equal(2);
1505 window.__restDataLive.z.should.equal(3);
1506 window.__restDataLive.should.not.have.property('x');
1507 window.__restDataLive.should.not.have.property('htmxPowered');
1508 });
1509
1510 it('data is reactive in :attr expressions (re-runs on ancestor data change)', async function() {
1511 playground().innerHTML = `
1512 <section data-mode="light">
1513 <div :class="{ darkmode: data.mode === 'dark' }"></div>
1514 </section>
1515 `;
1516 htmx.process(playground());
1517 let div = playground().querySelector('div');
1518 div.classList.contains('darkmode').should.equal(false);
1519
1520 playground().querySelector('section').dataset.mode = 'dark';
1521 await new Promise(r => setTimeout(r, 20));
1522 div.classList.contains('darkmode').should.equal(true);
1523 });
1524
1525 it('style scope helper accesses this.style', async function() {
1526 playground().innerHTML = `
1527 <div id="me" hx-on:click="style.color = 'red'">x</div>
1528 `;
1529 htmx.process(playground());
1530 let elt = playground().querySelector('#me');
1531 elt.click();
1532 elt.style.color.should.equal('red');
1533 });
1534
1535 // -------------------------------------------------------------------------
1536 // Simple form: :attr / hx-live:attr
1537 // -------------------------------------------------------------------------
1538
1539 it(':hidden truthy sets attribute, falsy removes', async function() {
1540 playground().innerHTML = `
1541 <input id="src" type="checkbox">
1542 <div :hidden="q('#src').checked">content</div>
1543 `;
1544 htmx.process(playground());
1545 let div = playground().querySelector('div');
1546 div.hasAttribute('hidden').should.equal(false);
1547
1548 let inp = playground().querySelector('#src');
1549 inp.checked = true;
1550 inp.dispatchEvent(new Event('change', { bubbles: true }));
1551 await htmx.timeout(5);
1552 div.hasAttribute('hidden').should.equal(true);
1553
1554 inp.checked = false;
1555 inp.dispatchEvent(new Event('change', { bubbles: true }));
1556 await htmx.timeout(5);
1557 div.hasAttribute('hidden').should.equal(false);
1558 });
1559
1560 it(':disabled toggles boolean attribute', async function() {
1561 playground().innerHTML = `
1562 <input id="src" type="checkbox">
1563 <button :disabled="q('#src').checked">submit</button>
1564 `;
1565 htmx.process(playground());
1566 let btn = playground().querySelector('button');
1567 btn.hasAttribute('disabled').should.equal(false);
1568
1569 let inp = playground().querySelector('#src');
1570 inp.checked = true;
1571 inp.dispatchEvent(new Event('change', { bubbles: true }));
1572 await htmx.timeout(5);
1573 btn.hasAttribute('disabled').should.equal(true);
1574 });
1575
1576 it(':aria-expanded writes "true"/"false", never removes', async function() {
1577 playground().innerHTML = `
1578 <input id="src" type="checkbox">
1579 <button :aria-expanded="q('#src').checked">x</button>
1580 `;
1581 htmx.process(playground());
1582 let btn = playground().querySelector('button');
1583 btn.getAttribute('aria-expanded').should.equal('false');
1584
1585 let inp = playground().querySelector('#src');
1586 inp.checked = true;
1587 inp.dispatchEvent(new Event('change', { bubbles: true }));
1588 await htmx.timeout(5);
1589 btn.getAttribute('aria-expanded').should.equal('true');
1590
1591 inp.checked = false;
1592 inp.dispatchEvent(new Event('change', { bubbles: true }));
1593 await htmx.timeout(5);
1594 btn.getAttribute('aria-expanded').should.equal('false');
1595 });
1596
1597 it(':src sets string attribute, null removes', async function() {
1598 playground().innerHTML = `
1599 <input id="src" value="alice">
1600 <img :src="'/avatar/' + q('#src').value">
1601 `;
1602 htmx.process(playground());
1603 let img = playground().querySelector('img');
1604 img.getAttribute('src').should.equal('/avatar/alice');
1605
1606 let inp = playground().querySelector('#src');
1607 inp.value = 'bob';
1608 inp.dispatchEvent(new Event('input', { bubbles: true }));
1609 await htmx.timeout(5);
1610 img.getAttribute('src').should.equal('/avatar/bob');
1611 });
1612
1613 it('simple form supports top-level await', async function() {
1614 playground().innerHTML = `<output :text="await Promise.resolve('hello-async')"></output>`;
1615 htmx.process(playground());
1616 await htmx.timeout(20);
1617 playground().querySelector('output').textContent.should.equal('hello-async');
1618 });
1619
1620 it(':text writes textContent', async function() {
1621 playground().innerHTML = `
1622 <input id="src" value="hello">
1623 <output :text="q('#src').value"></output>
1624 `;
1625 htmx.process(playground());
1626 let out = playground().querySelector('output');
1627 out.textContent.should.equal('hello');
1628
1629 let inp = playground().querySelector('#src');
1630 inp.value = 'world';
1631 inp.dispatchEvent(new Event('input', { bubbles: true }));
1632 await htmx.timeout(5);
1633 out.textContent.should.equal('world');
1634 });
1635
1636 it(':html writes innerHTML', async function() {
1637 playground().innerHTML = `
1638 <input id="src" value="bold">
1639 <div :html="'<b>' + q('#src').value + '</b>'"></div>
1640 `;
1641 htmx.process(playground());
1642 let div = playground().querySelector('div');
1643 div.innerHTML.should.equal('<b>bold</b>');
1644 div.querySelector('b').textContent.should.equal('bold');
1645 });
1646
1647 it(':class string form tracks managed classes, leaves others untouched', async function() {
1648 playground().innerHTML = `
1649 <input id="src" value="">
1650 <div class="external transition" :class="q('#src').value ? 'visible' : 'hidden faded'"></div>
1651 `;
1652 htmx.process(playground());
1653 let div = playground().querySelector('div');
1654 div.classList.contains('external').should.equal(true);
1655 div.classList.contains('transition').should.equal(true);
1656 div.classList.contains('hidden').should.equal(true);
1657 div.classList.contains('faded').should.equal(true);
1658
1659 let inp = playground().querySelector('#src');
1660 inp.value = 'yes';
1661 inp.dispatchEvent(new Event('input', { bubbles: true }));
1662 await new Promise(r => setTimeout(r, 20));
1663 div.classList.contains('external').should.equal(true);
1664 div.classList.contains('transition').should.equal(true);
1665 div.classList.contains('hidden').should.equal(false);
1666 div.classList.contains('faded').should.equal(false);
1667 div.classList.contains('visible').should.equal(true);
1668 });
1669
1670 it(':class object form toggles each independently', async function() {
1671 playground().innerHTML = `
1672 <input id="size" value="lg">
1673 <div class="card" :class="{ large: q('#size').value === 'lg', small: q('#size').value === 'sm' }"></div>
1674 `;
1675 htmx.process(playground());
1676 let div = playground().querySelector('div');
1677 div.classList.contains('large').should.equal(true);
1678 div.classList.contains('small').should.equal(false);
1679 div.classList.contains('card').should.equal(true);
1680
1681 let inp = playground().querySelector('#size');
1682 inp.value = 'sm';
1683 inp.dispatchEvent(new Event('input', { bubbles: true }));
1684 await htmx.timeout(5);
1685 div.classList.contains('large').should.equal(false);
1686 div.classList.contains('small').should.equal(true);
1687 div.classList.contains('card').should.equal(true);
1688 });
1689
1690 it(':.foo shorthand toggles a single class on truthiness', async function() {
1691 playground().innerHTML = `
1692 <input id="src" type="checkbox">
1693 <div class="card" :.active="q('#src').checked"></div>
1694 `;
1695 htmx.process(playground());
1696 let div = playground().querySelector('div');
1697 div.classList.contains('active').should.equal(false);
1698 div.classList.contains('card').should.equal(true);
1699
1700 let inp = playground().querySelector('#src');
1701 inp.checked = true;
1702 inp.dispatchEvent(new Event('change', { bubbles: true }));
1703 await htmx.timeout(5);
1704 div.classList.contains('active').should.equal(true);
1705 div.classList.contains('card').should.equal(true);
1706
1707 inp.checked = false;
1708 inp.dispatchEvent(new Event('change', { bubbles: true }));
1709 await htmx.timeout(5);
1710 div.classList.contains('active').should.equal(false);
1711 div.classList.contains('card').should.equal(true);
1712 });
1713
1714 it(':style object form sets only managed properties', async function() {
1715 playground().innerHTML = `
1716 <input id="pct" value="50">
1717 <div style="color: red" :style="{ width: q('#pct').value + '%' }"></div>
1718 `;
1719 htmx.process(playground());
1720 let div = playground().querySelector('div');
1721 div.style.width.should.equal('50%');
1722 // Pre-existing inline style preserved
1723 div.style.color.should.equal('red');
1724 });
1725
1726 it(':style string form parses declarations', async function() {
1727 playground().innerHTML = `
1728 <input id="pct" value="0.7">
1729 <progress :style="'--pct: ' + q('#pct').value"></progress>
1730 `;
1731 htmx.process(playground());
1732 let pr = playground().querySelector('progress');
1733 pr.style.getPropertyValue('--pct').should.equal('0.7');
1734 });
1735
1736 it(':style re-renders drop managed properties no longer in expression', async function() {
1737 playground().innerHTML = `
1738 <input id="src" value="a">
1739 <div :style="q('#src').value === 'a' ? { width: '50%' } : { height: '20px' }"></div>
1740 `;
1741 htmx.process(playground());
1742 let div = playground().querySelector('div');
1743 div.style.width.should.equal('50%');
1744 div.style.height.should.equal('');
1745
1746 let inp = playground().querySelector('#src');
1747 inp.value = 'b';
1748 inp.dispatchEvent(new Event('input', { bubbles: true }));
1749 await htmx.timeout(5);
1750 div.style.width.should.equal('');
1751 div.style.height.should.equal('20px');
1752 });
1753
1754 it(':style overlap: binding overwrites matching static property', async function() {
1755 playground().innerHTML = `
1756 <input id="color" value="blue">
1757 <div style="color: red" :style="{ color: q('#color').value }"></div>
1758 `;
1759 htmx.process(playground());
1760 let div = playground().querySelector('div');
1761 div.style.color.should.equal('blue');
1762 });
1763
1764 it(':.foo overlap: binding manages a class also set statically', async function() {
1765 playground().innerHTML = `
1766 <input id="src" type="checkbox">
1767 <div class="active" :.active="q('#src').checked"></div>
1768 `;
1769 htmx.process(playground());
1770 let div = playground().querySelector('div');
1771 let inp = playground().querySelector('#src');
1772 // unchecked: binding removes the class even though it was in static class=""
1773 div.classList.contains('active').should.equal(false);
1774
1775 inp.checked = true;
1776 inp.dispatchEvent(new Event('change', { bubbles: true }));
1777 await htmx.timeout(5);
1778 div.classList.contains('active').should.equal(true);
1779 });
1780
1781 it(':checked syncs property and attribute', async function() {
1782 playground().innerHTML = `
1783 <input id="src" type="checkbox">
1784 <input id="mirror" type="checkbox" :checked="q('#src').checked">
1785 `;
1786 htmx.process(playground());
1787 let src = playground().querySelector('#src');
1788 let mirror = playground().querySelector('#mirror');
1789 mirror.checked.should.equal(false);
1790 mirror.hasAttribute('checked').should.equal(false);
1791
1792 src.checked = true;
1793 src.dispatchEvent(new Event('change', { bubbles: true }));
1794 await htmx.timeout(5);
1795 mirror.checked.should.equal(true);
1796 mirror.hasAttribute('checked').should.equal(true);
1797 });
1798
1799 it(':value syncs property and attribute', async function() {
1800 playground().innerHTML = `
1801 <input id="src" value="hello">
1802 <input id="mirror" :value="q('#src').value.toUpperCase()">
1803 `;
1804 htmx.process(playground());
1805 let src = playground().querySelector('#src');
1806 let mirror = playground().querySelector('#mirror');
1807 mirror.value.should.equal('HELLO');
1808 mirror.getAttribute('value').should.equal('HELLO');
1809
1810 src.value = 'world';
1811 src.dispatchEvent(new Event('input', { bubbles: true }));
1812 await htmx.timeout(5);
1813 mirror.value.should.equal('WORLD');
1814 mirror.getAttribute('value').should.equal('WORLD');
1815 });
1816
1817 it('hx-live:disabled (canonical form) works same as :disabled', async function() {
1818 playground().innerHTML = `
1819 <input id="src" type="checkbox">
1820 <button hx-live:disabled="q('#src').checked">submit</button>
1821 `;
1822 htmx.process(playground());
1823 let btn = playground().querySelector('button');
1824 btn.hasAttribute('disabled').should.equal(false);
1825
1826 let inp = playground().querySelector('#src');
1827 inp.checked = true;
1828 inp.dispatchEvent(new Event('change', { bubbles: true }));
1829 await htmx.timeout(5);
1830 btn.hasAttribute('disabled').should.equal(true);
1831 });
1832
1833 it('multiple :attrs on one element each reactive independently', async function() {
1834 playground().innerHTML = `
1835 <input id="src" type="number" value="0">
1836 <div :text="q('#src').value"
1837 :data-v="q('#src').valueAsNumber * 2"
1838 :class="{ big: q('#src').valueAsNumber > 5 }"></div>
1839 `;
1840 htmx.process(playground());
1841 let div = playground().querySelector('div');
1842 div.textContent.should.equal('0');
1843 div.dataset.v.should.equal('0');
1844 div.classList.contains('big').should.equal(false);
1845
1846 let inp = playground().querySelector('#src');
1847 inp.value = '10';
1848 inp.dispatchEvent(new Event('input', { bubbles: true }));
1849 await new Promise(r => setTimeout(r, 20));
1850 div.textContent.should.equal('10');
1851 div.dataset.v.should.equal('20');
1852 div.classList.contains('big').should.equal(true);
1853 });
1854
1855 it('simple form: hx-ignore skips :attr discovery', function() {
1856 playground().innerHTML = '<div hx-ignore><span :text="\'should-not-run\'"></span></div>';
1857 htmx.process(playground());
1858 let span = playground().querySelector('span');
1859 span.textContent.should.equal('');
1860 });
1861
1862 it('simple form: matches() works in :attr expressions', async function() {
1863 playground().innerHTML = `
1864 <fieldset :disabled="matches(':has(input:invalid)')">
1865 <input required>
1866 <button>submit</button>
1867 </fieldset>
1868 `;
1869 htmx.process(playground());
1870 let fs = playground().querySelector('fieldset');
1871 // input is required and empty → :invalid → fieldset has descendant input:invalid → disabled
1872 fs.hasAttribute('disabled').should.equal(true);
1873
1874 let inp = playground().querySelector('input');
1875 inp.value = 'something';
1876 inp.dispatchEvent(new Event('input', { bubbles: true }));
1877 await new Promise(r => setTimeout(r, 20));
1878 fs.hasAttribute('disabled').should.equal(false);
1879 });
1880
1881 it('simple form: registration is idempotent across re-process', function() {
1882 window.__liveCallCountSimple = 0;
1883 playground().innerHTML = '<output :text="(window.__liveCallCountSimple = (window.__liveCallCountSimple||0) + 1, \'ok\')"></output>';
1884 htmx.process(playground());
1885 let countAfterFirst = window.__liveCallCountSimple;
1886 // Process again, should not register a second time.
1887 htmx.process(playground());
1888 window.__liveCallCountSimple.should.equal(countAfterFirst);
1889 delete window.__liveCallCountSimple;
1890 });
1891
1892 // -------------------------------------------------------------------------
1893 // morph integration: cleanup + re-registration on attribute change
1894 // -------------------------------------------------------------------------
1895
1896 describe('morph integration', function() {
1897
1898 it('hx-live body: morph changing expression adopts new code, does not duplicate', async function() {
1899 window.__morphLiveCount = 0;
1900 playground().innerHTML = '<div id="wrap"><output id="o" hx-live="window.__morphLiveCount++"></output></div>';
1901 htmx.process(playground());
1902 await htmx.timeout(5);
1903 let before = window.__morphLiveCount;
1904
1905 // outerMorph the element with a changed hx-live expression — morph will
1906 // detect the attribute change, cleanup the old registration, and re-process.
1907 await htmx.swap({
1908 target: '#wrap',
1909 text: '<div id="wrap"><output id="o" hx-live="window.__morphLiveCount += 10"></output></div>',
1910 swap: 'outerMorph',
1911 sourceElement: playground()
1912 });
1913 await htmx.timeout(5);
1914
1915 // Should have incremented by 10 (new code), not 1 (old code).
1916 let delta = window.__morphLiveCount - before;
1917 assert.isAtLeast(delta, 10, 'new expression should run');
1918 assert.equal(delta % 10, 0, 'old expression should not still be running');
1919 delete window.__morphLiveCount;
1920 });
1921
1922 it('hx-live body: morph removing hx-live stops the fn from running', async function() {
1923 window.__morphRemovedCount = 0;
1924 playground().innerHTML = '<div id="wrap"><output id="o" hx-live="window.__morphRemovedCount++"></output></div>';
1925 htmx.process(playground());
1926 await htmx.timeout(5);
1927
1928 // outerMorph to a version with hx-live removed — morph cleans up the old fn.
1929 await htmx.swap({
1930 target: '#wrap',
1931 text: '<div id="wrap"><output id="o"></output></div>',
1932 swap: 'outerMorph',
1933 sourceElement: playground()
1934 });
1935
1936 let countAfterMorph = window.__morphRemovedCount;
1937 // Trigger a recompute cycle — the old fn should no longer be in fns.
1938 document.body.setAttribute('data-morph-test-trigger', '1');
1939 await htmx.timeout(5);
1940 document.body.removeAttribute('data-morph-test-trigger');
1941 await htmx.timeout(5);
1942
1943 window.__morphRemovedCount.should.equal(countAfterMorph);
1944 delete window.__morphRemovedCount;
1945 });
1946
1947 it(':attr binding: morph changing expression adopts new code, does not duplicate', async function() {
1948 playground().innerHTML = '<div id="wrap"><output id="o" :text="\'original\'"></output></div>';
1949 htmx.process(playground());
1950 await htmx.timeout(5);
1951 playground().querySelector('#o').textContent.should.equal('original');
1952
1953 await htmx.swap({
1954 target: '#wrap',
1955 text: '<div id="wrap"><output id="o" :text="\'updated\'"></output></div>',
1956 swap: 'outerMorph',
1957 sourceElement: playground()
1958 });
1959 await htmx.timeout(5);
1960
1961 playground().querySelector('#o').textContent.should.equal('updated');
1962 });
1963
1964 it(':attr binding: morph adding a new binding registers it', async function() {
1965 playground().innerHTML = '<div id="wrap"><output id="o" :text="\'hello\'"></output></div>';
1966 htmx.process(playground());
1967 await htmx.timeout(5);
1968
1969 await htmx.swap({
1970 target: '#wrap',
1971 text: '<div id="wrap"><output id="o" :text="\'hello\'" :data-extra="\'added\'"></output></div>',
1972 swap: 'outerMorph',
1973 sourceElement: playground()
1974 });
1975 await htmx.timeout(5);
1976
1977 playground().querySelector('#o').dataset.extra.should.equal('added');
1978 });
1979
1980 it(':attr binding: morph removing a binding stops it running', async function() {
1981 window.__morphAttrCount = 0;
1982 playground().innerHTML = '<div id="wrap"><output id="o" :data-v="(window.__morphAttrCount++, \'x\')"></output></div>';
1983 htmx.process(playground());
1984 await htmx.timeout(5);
1985
1986 await htmx.swap({
1987 target: '#wrap',
1988 text: '<div id="wrap"><output id="o"></output></div>',
1989 swap: 'outerMorph',
1990 sourceElement: playground()
1991 });
1992
1993 let countAfterMorph = window.__morphAttrCount;
1994 document.body.setAttribute('data-morph-attr-trigger', '1');
1995 await htmx.timeout(5);
1996 document.body.removeAttribute('data-morph-attr-trigger');
1997 await htmx.timeout(5);
1998
1999 window.__morphAttrCount.should.equal(countAfterMorph);
2000 delete window.__morphAttrCount;
2001 });
2002
2003 it('morph cycle does not accumulate duplicate fns across multiple morphs', async function() {
2004 window.__morphMultiCount = 0;
2005 playground().innerHTML = '<div id="wrap"><output id="o" :data-v="(window.__morphMultiCount++, \'x\')"></output></div>';
2006 htmx.process(playground());
2007 await htmx.timeout(5);
2008
2009 // 3 morph cycles with identical content — each should cleanup and re-register once.
2010 for (let i = 0; i < 3; i++) {
2011 await htmx.swap({
2012 target: '#wrap',
2013 text: '<div id="wrap"><output id="o" :data-v="(window.__morphMultiCount++, \'x\')"></output></div>',
2014 swap: 'outerMorph',
2015 sourceElement: playground()
2016 });
2017 await htmx.timeout(5);
2018 }
2019
2020 let baseline = window.__morphMultiCount;
2021 document.body.setAttribute('data-morph-multi-trigger', '1');
2022 await htmx.timeout(5);
2023 document.body.removeAttribute('data-morph-multi-trigger');
2024 await htmx.timeout(5);
2025
2026 // Should only fire once per binding, not once per morph cycle.
2027 let delta = window.__morphMultiCount - baseline;
2028 assert.isAtMost(delta, 2, 'should not accumulate duplicate fns across morph cycles');
2029 delete window.__morphMultiCount;
2030 });
2031
2032 });
2033
2034 });