describe('hx-live extension', function () {
let extBackup;
before(async () => {
extBackup = backupExtensions();
clearExtensions();
htmx.config.extensions = 'hx-live';
htmx.__approvedExt = 'hx-live';
let script = document.createElement('script');
script.src = '../src/ext/hx-live.js';
await new Promise(resolve => {
script.onload = resolve;
document.head.appendChild(script);
});
});
after(() => {
restoreExtensions(extBackup);
});
beforeEach(() => { setupTest(this.currentTest); });
afterEach(() => { cleanupTest(); });
// -------------------------------------------------------------------------
// hx-live attribute behavior
// -------------------------------------------------------------------------
it('runs initially when registered', function() {
let elt = createProcessedHTML('');
elt.dataset.v.should.equal('init');
});
it('recomputes on input event', async function() {
playground().innerHTML = `
`;
htmx.process(playground());
let out = playground().querySelector('output');
out.dataset.v.should.equal('hello');
let src = playground().querySelector('#src');
src.value = 'world';
src.dispatchEvent(new Event('input', { bubbles: true }));
await htmx.timeout(5);
out.dataset.v.should.equal('world');
});
it('recomputes on change event', async function() {
playground().innerHTML = `
`;
htmx.process(playground());
let sel = playground().querySelector('#sel');
let out = playground().querySelector('output');
sel.value = 'b';
sel.dispatchEvent(new Event('change', { bubbles: true }));
await htmx.timeout(5);
out.dataset.v.should.equal('b');
});
it('recomputes on DOM mutation (attribute change)', async function() {
playground().innerHTML = `
`;
htmx.process(playground());
let src = playground().querySelector('#src');
let out = playground().querySelector('output');
out.dataset.v.should.equal('1');
src.setAttribute('data-x', '2');
await htmx.timeout(5);
out.dataset.v.should.equal('2');
});
it('removes itself from liveFns when disconnected', async function() {
let elt = createProcessedHTML('');
let initial = window.__liveCallCount;
elt.remove();
document.body.setAttribute('data-test-trigger', '1');
await htmx.timeout(5);
document.body.removeAttribute('data-test-trigger');
await htmx.timeout(5);
assert.isAtMost(window.__liveCallCount, initial + 1);
delete window.__liveCallCount;
});
it('hx-ignore skips hx-live', function() {
playground().innerHTML = '';
htmx.process(playground());
let out = playground().querySelector('output');
assert.isUndefined(out.dataset.v);
});
it('coalesces multiple sync mutations into one recompute', async function() {
window.__liveCount = 0;
let elt = createProcessedHTML('');
let initial = window.__liveCount;
document.body.setAttribute('data-a', '1');
document.body.setAttribute('data-b', '1');
document.body.setAttribute('data-c', '1');
await htmx.timeout(5);
document.body.removeAttribute('data-a');
document.body.removeAttribute('data-b');
document.body.removeAttribute('data-c');
await htmx.timeout(5);
let added = window.__liveCount - initial;
assert.isAtMost(added, 2, 'expected at most 2 coalesced recomputes');
delete window.__liveCount;
});
it('does not re-recompute when a binding writes its own attribute', async function() {
// A :hidden binding writing the hidden attribute would, if MutationObserver
// were active during the write, queue a record and trigger another recompute.
// Verify the change-event causes exactly one recompute, not two.
window.__selfWriteCount = 0;
playground().innerHTML = `
x
`;
htmx.process(playground());
await htmx.timeout(10);
let initial = window.__selfWriteCount;
let inp = playground().querySelector('#src');
inp.checked = true;
inp.dispatchEvent(new Event('change', { bubbles: true }));
await htmx.timeout(20);
let added = window.__selfWriteCount - initial;
assert.equal(added, 1, 'expected 1 recompute, got ' + added);
delete window.__selfWriteCount;
});
it('multiple hx-live elements all run', async function() {
playground().innerHTML = `
`;
htmx.process(playground());
playground().querySelector('#a').dataset.v.should.equal('1');
playground().querySelector('#b').dataset.v.should.equal('2');
playground().querySelector('#c').dataset.v.should.equal('3');
});
it('timeout(ms) is available in scope', async function() {
let elt = createProcessedHTML('');
await htmx.timeout(20);
elt.dataset.v.should.equal('done');
});
it('hx-live body supports top-level await directly', async function() {
let elt = createProcessedHTML(
``
);
elt.dataset.v.should.equal('pending');
await htmx.timeout(30);
elt.dataset.v.should.equal('done');
});
it('forEvent(event, ms) resolves on event before timeout', async function() {
let elt = createProcessedHTML('');
await htmx.timeout(5);
elt.dispatchEvent(new CustomEvent('go'));
await htmx.timeout(5);
elt.dataset.v.should.equal('fired');
});
it('forEvent(event, ms) resolves on timeout when event never fires', async function() {
let elt = createProcessedHTML('');
await htmx.timeout(40);
elt.dataset.v.should.equal('timed-out');
});
it('forEvent resolves a timeout with the original arg (discriminator)', async function() {
window.__waitResultLive = null;
let elt = createProcessedHTML(
``
);
await htmx.timeout(30);
window.__waitResultLive.should.equal(5);
delete window.__waitResultLive;
});
it('forEvent races multiple events and timeouts', async function() {
let elt = createProcessedHTML('');
await htmx.timeout(5);
elt.dispatchEvent(new CustomEvent('b'));
await htmx.timeout(5);
elt.dataset.v.should.equal('fired');
});
it('nextFrame() resolves on the next animation frame', async function() {
window.__liveFrameDone = false;
playground().innerHTML = `
`;
htmx.process(playground());
// Synchronously after process, nextFrame() hasn't resolved yet.
window.__liveFrameDone.should.equal(false);
await new Promise(r => requestAnimationFrame(() => requestAnimationFrame(r)));
window.__liveFrameDone.should.equal(true);
delete window.__liveFrameDone;
});
it('forEvent cleans up listeners after timeout wins', async function() {
let count = 0;
let elt = createProcessedHTML(
``
);
elt.addEventListener('cleanup-evt-live', () => count++);
await htmx.timeout(30);
elt.dataset.done.should.equal('1');
// forEvent timed out; its internal listener should be removed.
elt.dispatchEvent(new CustomEvent('cleanup-evt-live'));
count.should.equal(1);
});
it('trigger() fires a CustomEvent from the element', async function() {
let fired = null;
playground().innerHTML = '';
playground().querySelector('output').addEventListener('live-fire', e => fired = e);
htmx.process(playground());
await htmx.timeout(1);
assert.isNotNull(fired);
fired.detail.x.should.equal(1);
});
it('debounce(ms) supersedes prior calls', async function() {
window.__debounceCountLive = 0;
playground().innerHTML = `
`;
htmx.process(playground());
let inp = playground().querySelector('#in');
for (let i = 0; i < 5; i++) {
inp.value = String(i);
inp.dispatchEvent(new Event('input', { bubbles: true }));
await htmx.timeout(2);
}
await htmx.timeout(60);
assert.isAtMost(window.__debounceCountLive, 2, 'debounce should have superseded most calls');
delete window.__debounceCountLive;
});
it('debounce(ms, fn) runs the closure after the delay', async function() {
window.__debounceFnCountLive = 0;
playground().innerHTML = `
`;
htmx.process(playground());
let inp = playground().querySelector('#in');
for (let i = 0; i < 5; i++) {
inp.value = String(i);
inp.dispatchEvent(new Event('input', { bubbles: true }));
await htmx.timeout(2);
}
await htmx.timeout(60);
assert.isAtMost(window.__debounceFnCountLive, 2, 'debounce(fn) should have superseded most calls');
assert.isAtLeast(window.__debounceFnCountLive, 1, 'debounce(fn) should have run at least once');
delete window.__debounceFnCountLive;
});
it('debounce(ms, fn) supersedes across separate hx-on events on the same element', async function() {
window.__hxOnDebounceCountLive = 0;
playground().innerHTML = `
`;
htmx.process(playground());
let btn = playground().querySelector('button');
for (let i = 0; i < 5; i++) {
btn.click();
await htmx.timeout(5);
}
await htmx.timeout(60);
window.__hxOnDebounceCountLive.should.equal(1);
delete window.__hxOnDebounceCountLive;
});
it('debounce(ms, fn) keeps distinct closures on independent channels', async function() {
window.__chALive = 0;
window.__chBLive = 0;
playground().innerHTML = `
`;
htmx.process(playground());
// Different elements ⇒ different htmxProp ⇒ different debounce instances. Both should fire.
playground().querySelector('#a').click();
playground().querySelector('#b').click();
await htmx.timeout(60);
window.__chALive.should.equal(1);
window.__chBLive.should.equal(1);
delete window.__chALive;
delete window.__chBLive;
});
it('debounce(ms, fn) does not return a promise', function() {
// Use the htmx.live.q-adjacent debounce factory by running a live expression and capturing the return.
window.__debounceReturnLive = 'sentinel';
playground().innerHTML = `
`;
htmx.process(playground());
assert.isUndefined(window.__debounceReturnLive);
delete window.__debounceReturnLive;
});
it('processes hx-live added dynamically via htmx.process', function() {
playground().innerHTML = '';
let div = document.createElement('div');
div.innerHTML = '';
playground().appendChild(div);
htmx.process(playground());
div.querySelector('output').dataset.v.should.equal('dynamic');
});
it('coalesces recomputes during a swap', async function() {
window.__swapCountLive = 0;
playground().innerHTML = `
');
await htmx.ajax('GET', '/swap-coalesce-live', { target: '#content', swap: 'outerHTML' });
await htmx.timeout(50);
let added = window.__swapCountLive - beforeSwap;
// During-swap mutations are coalesced (swaps>0 guard). Pre/post-swap mutations
// (e.g. htmx-request indicator class) legitimately trigger a recompute each.
assert.isAtMost(added, 3, 'expected at most a few recomputes, got ' + added);
delete window.__swapCountLive;
});
it('iteration cap warns on runaway', async function() {
let warned = false;
let originalWarn = console.warn;
console.warn = (...args) => {
if (typeof args[0] === 'string' && args[0].includes('hx-live recompute exceeded')) warned = true;
originalWarn.apply(console, args);
};
try {
window.__runawayCountLive = 0;
playground().innerHTML = '';
htmx.process(playground());
for (let i = 0; i < 100; i++) {
document.body.setAttribute('data-runaway-test-live', String(i));
await htmx.timeout(5);
}
warned.should.equal(true);
document.body.removeAttribute('data-runaway-test-live');
delete window.__runawayCountLive;
} finally {
console.warn = originalWarn;
}
});
// -------------------------------------------------------------------------
// q() proxy
// -------------------------------------------------------------------------
it('q(string) selects elements', function() {
playground().innerHTML = '
a
b
';
let proxy = htmx.live.q('.x');
proxy.count.should.equal(2);
});
it('q returns 0-count proxy when no match', function() {
let proxy = htmx.live.q('.does-not-exist-anywhere');
proxy.count.should.equal(0);
});
it('q(element) wraps a single element', function() {
playground().innerHTML = '';
let elt = playground().querySelector('#x');
let proxy = htmx.live.q(elt);
proxy.count.should.equal(1);
});
it('q(iterable) wraps multiple elements', function() {
playground().innerHTML = '';
let nodes = playground().querySelectorAll('.x');
let proxy = htmx.live.q(nodes);
proxy.count.should.equal(2);
});
it('arr() returns a real array', function() {
playground().innerHTML = '';
let arr = htmx.live.q('.x').arr();
assert.isArray(arr);
arr.length.should.equal(2);
});
it('iterable via for..of', function() {
playground().innerHTML = '';
let collected = [];
for (let e of htmx.live.q('.x')) collected.push(e.dataset.i);
collected.should.deep.equal(['0', '1']);
});
it('property read returns first element value', function() {
playground().innerHTML = '';
htmx.live.q('.x').value.should.equal('first');
});
it('property set propagates to all elements', function() {
playground().innerHTML = '';
htmx.live.q('.x').value = 'changed';
let inputs = playground().querySelectorAll('.x');
inputs[0].value.should.equal('changed');
inputs[1].value.should.equal('changed');
});
it('chained property access returns proxy of subproperties', function() {
playground().innerHTML = '';
let proxy = htmx.live.q('.x').dataset;
proxy.foo.should.equal('a');
});
it('method invocation calls each element, returns first result', function() {
playground().innerHTML = '
first
second
';
let result = htmx.live.q('.x').querySelector('span');
result.textContent.should.equal('first');
});
it('q().trigger() fires CustomEvent on each element', function() {
playground().innerHTML = '';
let fires = 0;
for (let e of playground().querySelectorAll('.x')) {
e.addEventListener('zap', () => fires++);
}
htmx.live.q('.x').trigger('zap');
fires.should.equal(2);
});
it('q().insert() inserts HTML at the given position', function() {
playground().innerHTML = '
orig
';
htmx.live.q('.x').insert('end', 'new');
playground().querySelectorAll('.added').length.should.equal(1);
});
it('insert() scope helper inserts HTML relative to this', function() {
playground().innerHTML = `
`;
htmx.process(playground());
let btn = playground().querySelector('button');
btn.click();
playground().querySelectorAll('.added').length.should.equal(1);
btn.nextElementSibling.classList.contains('added').should.equal(true);
});
it('q().take() moves a class from other elements to selected ones', function() {
playground().innerHTML = `
`;
let target = playground().querySelectorAll('.tab')[2];
htmx.live.q(target).take('.selected', '.tab');
let tabs = playground().querySelectorAll('.tab');
tabs[0].classList.contains('selected').should.equal(false);
tabs[1].classList.contains('selected').should.equal(false);
tabs[2].classList.contains('selected').should.equal(true);
});
it('htmx.live.q(target).take() moves a class between elements (selectors)', function() {
playground().innerHTML = `
`;
htmx.live.q('#t3').take('.selected', '.tab');
let tabs = playground().querySelectorAll('.tab');
tabs[0].classList.contains('selected').should.equal(false);
tabs[1].classList.contains('selected').should.equal(false);
tabs[2].classList.contains('selected').should.equal(true);
});
it('take() is available at top-level in hx-on expressions', function() {
playground().innerHTML = `
`;
htmx.process(playground());
let tabs = playground().querySelectorAll('.tab');
tabs[2].click();
tabs[0].classList.contains('selected').should.equal(false);
tabs[1].classList.contains('selected').should.equal(false);
tabs[2].classList.contains('selected').should.equal(true);
});
it('take() with no scope defaults to parent (sibling scope)', function() {
playground().innerHTML = `
unrelated
`;
htmx.live.q('#t').take('.active');
// Siblings lose .active
let nav = playground().querySelector('nav');
nav.querySelectorAll('.active').length.should.equal(1);
playground().querySelector('#t').classList.contains('active').should.equal(true);
// Unrelated element outside parent is untouched
playground().querySelector('div').classList.contains('active').should.equal(true);
});
it('take() with element scope searches within that container', function() {
playground().innerHTML = `
`;
let nav1 = playground().querySelector('#nav1');
htmx.live.q('#t').take('.active', nav1);
playground().querySelector('#t').classList.contains('active').should.equal(true);
playground().querySelector('#nav1 button').classList.contains('active').should.equal(false);
// nav2 is untouched
playground().querySelector('#nav2 .active').should.not.be.null;
});
it('take() in hx-on with this as scope (tabs pattern)', function() {
playground().innerHTML = `
unrelated
`;
htmx.process(playground());
playground().querySelector('#click-me').click();
let buttons = playground().querySelectorAll('nav button');
buttons[0].classList.contains('active').should.equal(false);
buttons[1].classList.contains('active').should.equal(false);
buttons[2].classList.contains('active').should.equal(true);
// Unrelated element outside nav is untouched
playground().querySelector('div').classList.contains('active').should.equal(true);
});
it('take() canonical sibling form in hx-on', function() {
playground().innerHTML = `
`;
htmx.process(playground());
playground().querySelector('#click-me').click();
let navBtns = playground().querySelectorAll('nav button');
navBtns[0].classList.contains('active').should.equal(false);
navBtns[1].classList.contains('active').should.equal(false);
navBtns[2].classList.contains('active').should.equal(true);
// Unrelated button outside nav is untouched
playground().querySelector('nav + button').classList.contains('active').should.equal(true);
});
it('take() with ARIA and no scope defaults to parent', function() {
playground().innerHTML = `
`;
htmx.live.q('#t').take('aria-selected');
let tabs = playground().querySelectorAll('[role=tab]');
tabs[0].getAttribute('aria-selected').should.equal('false');
tabs[1].getAttribute('aria-selected').should.equal('true');
// Unrelated element outside parent is untouched
playground().querySelector('div + button').getAttribute('aria-selected').should.equal('true');
});
it('take() accepts options object { from: selector }', function() {
playground().innerHTML = `
`;
htmx.live.q('#t3').take('.selected', { from: '.tab' });
let tabs = playground().querySelectorAll('.tab');
tabs[0].classList.contains('selected').should.equal(false);
tabs[2].classList.contains('selected').should.equal(true);
// .other is NOT a .tab, so its .selected stays
playground().querySelector('.other').classList.contains('selected').should.equal(true);
});
it('take() with ARIA attribute writes true on me, false on others', function() {
playground().innerHTML = `
`;
htmx.live.q('#t3').take('aria-selected', '[role=tab]');
let tabs = playground().querySelectorAll('[role=tab]');
tabs[0].getAttribute('aria-selected').should.equal('false');
tabs[1].getAttribute('aria-selected').should.equal('false');
tabs[2].getAttribute('aria-selected').should.equal('true');
});
it('toggle() is available at top-level in hx-on expressions and applies to current element', function() {
playground().innerHTML = `
`;
htmx.process(playground());
let btn = playground().querySelector('button');
btn.click();
btn.classList.contains('active').should.equal(true);
btn.getAttribute('aria-pressed').should.equal('true');
btn.click();
btn.classList.contains('active').should.equal(false);
btn.getAttribute('aria-pressed').should.equal('false');
});
it('toggle() in hx-live applies to the current element on each recompute', async function() {
// Use a one-shot recompute to flip a class once and confirm targeting.
let elt = createProcessedHTML(
``
);
await htmx.timeout(5);
elt.classList.contains('flipped').should.equal(true);
});
it('directional: closest', function() {
playground().innerHTML = '';
let inner = playground().querySelector('#inner');
let proxy = htmx.live.q(inner);
proxy.count.should.equal(1);
});
it('directional: first picks the first match', function() {
playground().innerHTML = 'abc';
let proxy = htmx.live.q('first .z');
proxy.count.should.equal(1);
proxy.textContent.should.equal('a');
});
it('directional: last picks the last match', function() {
playground().innerHTML = 'abc';
let proxy = htmx.live.q('last .z');
proxy.count.should.equal(1);
proxy.textContent.should.equal('c');
});
it('"sel in #scope" scopes to a different root', function() {
playground().innerHTML = '
outside
inside
';
let proxy = htmx.live.q('.z in #scope');
proxy.count.should.equal(1);
proxy.textContent.should.equal('inside');
});
it('"sel in #unknown" returns empty proxy when scope is missing', function() {
let proxy = htmx.live.q('.z in #does-not-exist');
proxy.count.should.equal(0);
});
it('"sel in .multi" unions matches across all root elements in document order', function() {
playground().innerHTML =
'a' +
'skip' +
'bc';
let proxy = htmx.live.q('.foo in .bar');
proxy.count.should.equal(3);
proxy.arr().map(e => e.textContent).should.deep.equal(['a', 'b', 'c']);
});
it('"sel in me" scopes to the current hx-live element (alias of "this")', async function() {
playground().innerHTML = `
ab
outside
`;
htmx.process(playground());
await htmx.timeout(5);
playground().querySelector('div').dataset.v.should.equal('2');
});
it('"sel in me" and "sel in this" return the same elements', async function() {
playground().innerHTML = `
abc
`;
htmx.process(playground());
await htmx.timeout(5);
let div = playground().querySelector('#me-vs-this');
div.dataset.me.should.equal('3');
div.dataset.this.should.equal('3');
});
it('"first sel in .multi" picks the first match across all roots', function() {
playground().innerHTML =
'a' +
'b';
htmx.live.q('first .foo in .bar').textContent.should.equal('a');
htmx.live.q('last .foo in .bar').textContent.should.equal('b');
});
it('toggle(".foo") toggles a class', function() {
playground().innerHTML = '';
let p = htmx.live.q('.x');
p.toggle('.active');
playground().querySelectorAll('.x.active').length.should.equal(1);
playground().querySelectorAll('.x:not(.active)').length.should.equal(1);
});
it('toggle("attr") toggles boolean attribute presence', function() {
playground().innerHTML = '';
htmx.live.q('.x').toggle('disabled');
let inputs = playground().querySelectorAll('.x');
inputs[0].hasAttribute('disabled').should.equal(true);
inputs[1].hasAttribute('disabled').should.equal(false);
});
it('toggle("aria-*") flips between "true" and "false"', function() {
playground().innerHTML = '';
let p = htmx.live.q('button');
p.toggle('aria-pressed');
// a had no aria-pressed (effectively absent → not "true") → becomes "true"
playground().querySelector('#a').getAttribute('aria-pressed').should.equal('true');
// b had "true" → becomes "false"
playground().querySelector('#b').getAttribute('aria-pressed').should.equal('false');
// toggle again
p.toggle('aria-pressed');
playground().querySelector('#a').getAttribute('aria-pressed').should.equal('false');
playground().querySelector('#b').getAttribute('aria-pressed').should.equal('true');
});
it('toggle(name, "a|b|c") cycles attribute through values', function() {
playground().innerHTML = '';
let div = playground().querySelector('div');
let p = htmx.live.q('div');
p.toggle('data-mode', 'light|dark|auto');
div.getAttribute('data-mode').should.equal('light');
p.toggle('data-mode', 'light|dark|auto');
div.getAttribute('data-mode').should.equal('dark');
p.toggle('data-mode', 'light|dark|auto');
div.getAttribute('data-mode').should.equal('auto');
p.toggle('data-mode', 'light|dark|auto');
div.getAttribute('data-mode').should.equal('light');
});
it('toggle(name, [array]) cycles attribute through values (array form)', function() {
playground().innerHTML = '';
let div = playground().querySelector('div');
let p = htmx.live.q('div');
p.toggle('data-mode', ['light', 'dark', 'auto']);
div.getAttribute('data-mode').should.equal('light');
p.toggle('data-mode', ['light', 'dark', 'auto']);
div.getAttribute('data-mode').should.equal('dark');
});
it('toggle(name, "v|") cycles attribute between value and absent', function() {
playground().innerHTML = '';
let div = playground().querySelector('div');
let p = htmx.live.q('div');
p.toggle('data-state', 'on|');
div.getAttribute('data-state').should.equal('on');
p.toggle('data-state', 'on|');
div.hasAttribute('data-state').should.equal(false);
p.toggle('data-state', 'on|');
div.getAttribute('data-state').should.equal('on');
});
it('toggle cycle snaps to first value when current is out-of-list', function() {
playground().innerHTML = '';
let div = playground().querySelector('div');
htmx.live.q('div').toggle('data-mode', 'light|dark|auto');
div.getAttribute('data-mode').should.equal('light');
});
it('toggle(".class", "a|b|c") cycles through classes (only one at a time)', function() {
playground().innerHTML = '';
let div = playground().querySelector('div');
let p = htmx.live.q('div');
p.toggle('.size', 'sm|md|lg');
div.classList.contains('sm').should.equal(true);
p.toggle('.size', 'sm|md|lg');
div.classList.contains('md').should.equal(true);
div.classList.contains('sm').should.equal(false);
p.toggle('.size', 'sm|md|lg');
div.classList.contains('lg').should.equal(true);
div.classList.contains('md').should.equal(false);
});
it('toggle is chainable', function() {
playground().innerHTML = '';
let r = htmx.live.q('button').toggle('.active').toggle('aria-pressed').trigger('changed');
r.count.should.equal(1);
let btn = playground().querySelector('button');
btn.classList.contains('active').should.equal(true);
btn.getAttribute('aria-pressed').should.equal('true');
});
it('proxy.trigger/insert/take return the proxy for chaining', function() {
playground().innerHTML = '
`;
let proxy = htmx.live.q('.parent').q('.x');
proxy.count.should.equal(1);
});
it('q is available in hx-on scope and bound to element', function() {
playground().innerHTML = '
tgt
';
htmx.process(playground());
playground().querySelector('button').click();
window.fooLive.should.equal('tgt');
delete window.fooLive;
});
// -------------------------------------------------------------------------
// attr() scope helper
// -------------------------------------------------------------------------
it('attr() getter: boolean attr returns boolean', function() {
playground().innerHTML = '';
htmx.live.attr('#a', 'disabled').should.equal(true);
htmx.live.attr('#b', 'disabled').should.equal(false);
});
it('attr() getter: ARIA returns boolean from "true"/"false"', function() {
playground().innerHTML = '';
htmx.live.attr('#a', 'aria-expanded').should.equal(true);
htmx.live.attr('#b', 'aria-expanded').should.equal(false);
});
it('attr() getter: .class returns boolean (has class)', function() {
playground().innerHTML = '';
htmx.live.attr('#a', '.foo').should.equal(true);
htmx.live.attr('#b', '.foo').should.equal(false);
});
it('attr() getter: class returns full class string', function() {
playground().innerHTML = '';
htmx.live.attr('#a', 'class').should.equal('foo bar baz');
});
it('attr() getter: regular attr returns string or null', function() {
playground().innerHTML = '';
htmx.live.attr('#a', 'data-x').should.equal('hello');
assert.isNull(htmx.live.attr('#b', 'data-x'));
});
it('attr() getter: checked returns property value', function() {
playground().innerHTML = '';
htmx.live.attr('#a', 'checked').should.equal(true);
htmx.live.attr('#b', 'checked').should.equal(false);
});
it('attr() getter: value returns property value', function() {
playground().innerHTML = '';
let inp = playground().querySelector('#a');
// After user interaction the property and attribute can diverge
inp.value = 'world';
htmx.live.attr('#a', 'value').should.equal('world');
});
it('attr() setter: boolean attr truthy sets, falsy removes', function() {
playground().innerHTML = '';
htmx.live.attr('#a', 'disabled', true);
playground().querySelector('#a').hasAttribute('disabled').should.equal(true);
htmx.live.attr('#a', 'disabled', false);
playground().querySelector('#a').hasAttribute('disabled').should.equal(false);
});
it('attr() setter: ARIA writes "true"/"false", never removes', function() {
playground().innerHTML = '';
let div = playground().querySelector('#a');
htmx.live.attr('#a', 'aria-expanded', true);
div.getAttribute('aria-expanded').should.equal('true');
htmx.live.attr('#a', 'aria-expanded', false);
div.getAttribute('aria-expanded').should.equal('false');
// null/undefined also writes "false". ARIA is never removed.
htmx.live.attr('#a', 'aria-expanded', null);
div.getAttribute('aria-expanded').should.equal('false');
});
it('attr() setter: aria-* strings and numbers pass through', function() {
playground().innerHTML = '';
// String values (tristate, tokens) pass through unchanged.
htmx.live.attr('#a', 'aria-pressed', 'mixed');
playground().querySelector('#a').getAttribute('aria-pressed').should.equal('mixed');
htmx.live.attr('#b', 'aria-current', 'page');
playground().querySelector('#b').getAttribute('aria-current').should.equal('page');
// Numbers stringify (e.g. aria-valuenow).
htmx.live.attr('#c', 'aria-valuenow', 50);
playground().querySelector('#c').getAttribute('aria-valuenow').should.equal('50');
});
it('attr() setter: .class true/false add/remove', function() {
playground().innerHTML = '';
let div = playground().querySelector('#a');
htmx.live.attr('#a', '.active', true);
div.classList.contains('active').should.equal(true);
htmx.live.attr('#a', '.active', false);
div.classList.contains('active').should.equal(false);
});
it('attr() setter: class (string) sets managed class list', function() {
playground().innerHTML = '';
let div = playground().querySelector('#a');
htmx.live.attr('#a', 'class', 'foo bar');
div.classList.contains('external').should.equal(true);
div.classList.contains('foo').should.equal(true);
div.classList.contains('bar').should.equal(true);
// Re-apply with different set. Previous managed dropped, external untouched.
htmx.live.attr('#a', 'class', 'baz');
div.classList.contains('external').should.equal(true);
div.classList.contains('foo').should.equal(false);
div.classList.contains('bar').should.equal(false);
div.classList.contains('baz').should.equal(true);
});
it('attr() setter: class (object) toggles each independently', function() {
playground().innerHTML = '';
let div = playground().querySelector('#a');
htmx.live.attr('#a', 'class', { foo: true, bar: false });
div.classList.contains('foo').should.equal(true);
div.classList.contains('bar').should.equal(false);
div.classList.contains('external').should.equal(true);
// Flip foo, set bar
htmx.live.attr('#a', 'class', { foo: false, bar: true });
div.classList.contains('foo').should.equal(false);
div.classList.contains('bar').should.equal(true);
});
it('attr() setter: class (object) supports space-separated keys', function() {
playground().innerHTML = '';
let div = playground().querySelector('#a');
htmx.live.attr('#a', 'class', { 'foo bar': true, baz: false });
div.classList.contains('foo').should.equal(true);
div.classList.contains('bar').should.equal(true);
div.classList.contains('baz').should.equal(false);
});
it('attr() setter: checked syncs property and attribute', function() {
playground().innerHTML = '';
let inp = playground().querySelector('#a');
htmx.live.attr('#a', 'checked', true);
inp.checked.should.equal(true);
inp.hasAttribute('checked').should.equal(true);
htmx.live.attr('#a', 'checked', false);
inp.checked.should.equal(false);
inp.hasAttribute('checked').should.equal(false);
});
it('attr() setter: value syncs property and attribute', function() {
playground().innerHTML = '';
let inp = playground().querySelector('#a');
htmx.live.attr('#a', 'value', 'hello');
inp.value.should.equal('hello');
inp.getAttribute('value').should.equal('hello');
htmx.live.attr('#a', 'value', null);
inp.value.should.equal('');
inp.hasAttribute('value').should.equal(false);
});
it('attr() setter: regular attr null removes', function() {
playground().innerHTML = '';
htmx.live.attr('#a', 'data-x', null);
playground().querySelector('#a').hasAttribute('data-x').should.equal(false);
});
it('attr() setter: regular attr stringifies non-string values', function() {
playground().innerHTML = '';
htmx.live.attr('#a', 'data-x', 42);
playground().querySelector('#a').getAttribute('data-x').should.equal('42');
});
it('attr() setter: contenteditable false writes "false" string, not removes', function() {
playground().innerHTML = '';
htmx.live.attr('#a', 'contenteditable', false);
playground().querySelector('#a').getAttribute('contenteditable').should.equal('false');
});
it('attr() setter: draggable false writes "false" string', function() {
playground().innerHTML = '';
htmx.live.attr('#a', 'draggable', false);
playground().querySelector('#a').getAttribute('draggable').should.equal('false');
});
it('attr() setter: spellcheck false writes "false" string', function() {
playground().innerHTML = '';
htmx.live.attr('#a', 'spellcheck', false);
playground().querySelector('#a').getAttribute('spellcheck').should.equal('false');
});
it('attr() setter: contenteditable null removes attribute', function() {
playground().innerHTML = '';
htmx.live.attr('#a', 'contenteditable', null);
playground().querySelector('#a').hasAttribute('contenteditable').should.equal(false);
});
it('q().attr() applies setter to all matched elements', function() {
playground().innerHTML = '';
htmx.live.q('.x').attr('disabled', true);
let inputs = playground().querySelectorAll('.x');
for (let inp of inputs) inp.hasAttribute('disabled').should.equal(true);
});
it('q().attr() getter returns from first matched element', function() {
playground().innerHTML = '';
htmx.live.q('.x').attr('data-i').should.equal('a');
});
it('q().attr() returns proxy for chaining', function() {
playground().innerHTML = '';
let r = htmx.live.q('.x').attr('role', 'button').attr('.active', true);
r.count.should.equal(1);
let btn = playground().querySelector('.x');
btn.getAttribute('role').should.equal('button');
btn.classList.contains('active').should.equal(true);
});
it('attr() is available in hx-on scope bound to element', function() {
playground().innerHTML = '';
htmx.process(playground());
let btn = playground().querySelector('button');
btn.click();
btn.getAttribute('data-clicked').should.equal('yes');
});
it('attr() in hx-live expression operates on current element', async function() {
let elt = createProcessedHTML(
``
);
await htmx.timeout(5);
elt.classList.contains('flipped').should.equal(true);
});
// -------------------------------------------------------------------------
// matches() scope helper
// -------------------------------------------------------------------------
it('matches() is available in hx-on scope bound to element', function() {
playground().innerHTML = '';
htmx.process(playground());
playground().querySelector('#i').click();
window.__matchesLive.should.equal(true);
delete window.__matchesLive;
});
it('matches() in hx-live expression operates on current element', async function() {
playground().innerHTML = `
`;
htmx.process(playground());
await htmx.timeout(5);
let div = playground().querySelector('[hx-live]');
div.dataset.has.should.equal('true');
});
it('htmx.live.attr is exposed on public API', function() {
assert.isFunction(htmx.live.attr);
});
// -------------------------------------------------------------------------
// cascading data proxy
// -------------------------------------------------------------------------
it('data.foo reads this.dataset.foo when present locally', async function() {
playground().innerHTML = `
x
`;
htmx.process(playground());
let elt = playground().querySelector('#me');
elt.click();
elt.dataset.v.should.equal('local');
});
it('data.foo cascades up to closest ancestor', async function() {
playground().innerHTML = `
x
`;
htmx.process(playground());
let elt = playground().querySelector('#me');
elt.click();
elt.dataset.v.should.equal('USD');
});
it('data.foo returns undefined when no ancestor has it', async function() {
playground().innerHTML = `
x
`;
htmx.process(playground());
let elt = playground().querySelector('#me');
elt.click();
elt.dataset.v.should.equal('undef');
});
it('data.foo nested: innermost wins (shadowing)', async function() {
playground().innerHTML = `
x
`;
htmx.process(playground());
let elt = playground().querySelector('#me');
elt.click();
elt.dataset.v.should.equal('inner');
});
it('data.foo = "x" writes to closest ancestor with data-foo', async function() {
playground().innerHTML = `
`;
htmx.process(playground());
let btn = playground().querySelector('#me');
let section = playground().querySelector('section');
btn.click();
section.dataset.counter.should.equal('1');
btn.click();
section.dataset.counter.should.equal('2');
});
it('data.foo = "x" writes to this when no ancestor has data-foo', async function() {
playground().innerHTML = `
`;
htmx.process(playground());
let btn = playground().querySelector('#me');
btn.click();
btn.dataset.fresh.should.equal('created');
});
it('data.foo++ works (auto-coerces to number)', async function() {
playground().innerHTML = `
`;
htmx.process(playground());
let btn = playground().querySelector('#me');
let section = playground().querySelector('section');
btn.click();
section.dataset.counter.should.equal('6');
});
it('data proxy: boolean round-trips through JSON', async function() {
playground().innerHTML = `
`;
htmx.process(playground());
let btn = playground().querySelector('#me');
let section = playground().querySelector('section');
btn.click();
section.dataset.active.should.equal('true');
btn.click();
section.dataset.active.should.equal('false');
});
it('data proxy: number round-trips through JSON', async function() {
playground().innerHTML = `
`;
htmx.process(playground());
let btn = playground().querySelector('#me');
let section = playground().querySelector('section');
(typeof section.dataset.count).should.equal('string');
btn.click();
section.dataset.count.should.equal('1');
btn.click();
section.dataset.count.should.equal('2');
});
it('data proxy: object round-trips through JSON', async function() {
playground().innerHTML = `
read
`;
htmx.process(playground());
let btn = playground().querySelector('#me');
let out = playground().querySelector('#out');
let section = playground().querySelector('section');
out.click();
out.dataset.v.should.equal('alice:30');
btn.click();
JSON.parse(section.dataset.user).age.should.equal(31);
out.click();
out.dataset.v.should.equal('alice:31');
});
it('data proxy: array round-trips through JSON', async function() {
playground().innerHTML = `
count
`;
htmx.process(playground());
let add = playground().querySelector('#add');
let out = playground().querySelector('#out');
let section = playground().querySelector('section');
out.click();
out.dataset.v.should.equal('0');
add.click();
add.click();
add.click();
JSON.parse(section.dataset.items).should.deep.equal([0, 1, 2]);
out.click();
out.dataset.v.should.equal('3');
});
it('data proxy: plain string stays as string', async function() {
playground().innerHTML = `
x
`;
htmx.process(playground());
let elt = playground().querySelector('#me');
elt.click();
elt.dataset.v.should.equal('string:hello');
});
it('data proxy: null round-trips through JSON', async function() {
playground().innerHTML = `
x
`;
htmx.process(playground());
let elt = playground().querySelector('#me');
elt.click();
elt.dataset.v.should.equal('is-null');
});
it('with (data) { foo++ } increments cascading value', async function() {
playground().innerHTML = `
`;
htmx.process(playground());
let btn = playground().querySelector('#me');
let section = playground().querySelector('section');
btn.click();
section.dataset.counter.should.equal('11');
});
it('with (data) destructuring works for read', async function() {
playground().innerHTML = `
`;
htmx.process(playground());
let btn = playground().querySelector('#me');
btn.click();
btn.dataset.sum.should.equal('8');
});
it('data.kebabKey camelCase translation works', async function() {
playground().innerHTML = `