Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
70 changes: 52 additions & 18 deletions src/htmx.js
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,7 @@ var htmx = (() => {
history: true,
mode: 'same-origin',
defaultSwap: "innerHTML",
defaultFocusScroll: false,
indicatorClass: "htmx-indicator",
requestClass: "htmx-request",
includeIndicatorCSS: true,
Expand Down Expand Up @@ -1266,9 +1267,22 @@ var htmx = (() => {
return tasks;
}

__setFocus(elt, options, start, end) {
try {
if (start != null && elt.setSelectionRange) {
elt.setSelectionRange(start, end);
}
elt.focus(options);
} catch (e) {
// setSelectionRange or Web component focus may fail so ignore
}
}

__handleAutoFocus(elt) {
let autofocus = this.find(elt, "[autofocus]");
autofocus?.focus?.()
if (autofocus) {
this.__setFocus(autofocus);
}
}

__handleScroll(swapSpec, target) {
Expand Down Expand Up @@ -1386,14 +1400,15 @@ var htmx = (() => {

async __insertContent(task, cssTransition = true) {
let {target, swapSpec, fragment} = task;
let swapStyle = swapSpec.style;
if (typeof target === 'string') {
target = document.querySelector(target);
}
if (!target) return;
if (typeof swapSpec === 'string') {
swapSpec = this.__parseSwapSpec(swapSpec);
}
if (swapSpec.style === 'none') return;
if (swapStyle === 'none') return;
if (swapSpec.strip && fragment.firstElementChild) {
fragment = document.createDocumentFragment();
fragment.append(...(task.fragment.firstElementChild.content || task.fragment.firstElementChild).childNodes);
Expand All @@ -1404,61 +1419,73 @@ var htmx = (() => {
await this.timeout(task.swapSpec?.swap)
}

if (swapSpec.style === 'delete') {
if (swapStyle === 'delete') {
if (target.parentNode) {
this.__cleanup(target);
target.parentNode.removeChild(target);
}
return;
}

if (swapSpec.style === 'textContent') {
if (swapStyle === 'textContent') {
target.textContent = fragment.textContent;
target.classList.remove("htmx-swapping")
return;
}

let pantry = this.__handlePreservedElements(fragment);
// innerHTML/outerHTML swaps backup focus and handle CSS transitions
let focusInfo;
let settleTasks = []
let parentNode = target.parentNode;
if (swapStyle === 'innerHTML' || (swapStyle === 'outerHTML' && parentNode)) {
let activeElt = document.activeElement;
if (activeElt?.id) {
focusInfo = {
elt: activeElt,
start: activeElt.selectionStart,
end: activeElt.selectionEnd
};
}
settleTasks = cssTransition ? this.__startCSSTransitions(fragment, target) : []
}

let pantry = this.__handlePreservedElements(fragment);
let newContent = [...fragment.childNodes]
let settleTasks = []
try {
if (swapSpec.style === 'innerHTML') {
settleTasks = cssTransition ? this.__startCSSTransitions(fragment, target) : []
if (swapStyle === 'innerHTML') {
for (const child of target.children) {
this.__cleanup(child)
}
target.replaceChildren(...fragment.childNodes);
} else if (swapSpec.style === 'outerHTML') {
} else if (swapStyle === 'outerHTML') {
if (parentNode) {
settleTasks = cssTransition ? this.__startCSSTransitions(fragment, target) : []
this.__insertNodes(parentNode, target, fragment);
this.__cleanup(target)
parentNode.removeChild(target);
}
} else if (swapSpec.style === 'innerMorph') {
} else if (swapStyle === 'innerMorph') {
this.__morph(target, fragment, true);
newContent = [...target.childNodes];
} else if (swapSpec.style === 'outerMorph') {
} else if (swapStyle === 'outerMorph') {
this.__morph(target, fragment, false);
newContent.push(target);
} else if (swapSpec.style === 'beforebegin') {
} else if (swapStyle === 'beforebegin') {
if (parentNode) {
this.__insertNodes(parentNode, target, fragment);
}
} else if (swapSpec.style === 'afterbegin') {
} else if (swapStyle === 'afterbegin') {
this.__insertNodes(target, target.firstChild, fragment);
} else if (swapSpec.style === 'beforeend') {
} else if (swapStyle === 'beforeend') {
this.__insertNodes(target, null, fragment);
} else if (swapSpec.style === 'afterend') {
} else if (swapStyle === 'afterend') {
if (parentNode) {
this.__insertNodes(parentNode, target.nextSibling, fragment);
}
} else {
let methods = this.__extMethods.get('handle_swap')
let handled = false;
for (const method of methods) {
let result = method(swapSpec.style, target, fragment, swapSpec);
let result = method(swapStyle, target, fragment, swapSpec);
if (result) {
handled = true;
if (Array.isArray(result)) {
Expand All @@ -1468,13 +1495,20 @@ var htmx = (() => {
}
}
if (!handled) {
throw new Error(`Unknown swap style: ${swapSpec.style}`);
throw new Error(`Unknown swap style: ${swapStyle}`);
}
}
} finally {
target.classList.remove("htmx-swapping")
}
this.__restorePreservedElements(pantry);
if (focusInfo && !focusInfo.elt.isConnected) {
let newElt = document.getElementById(focusInfo.elt.id);
if (newElt) {
let focusOptions = { preventScroll: swapSpec.focusScroll !== undefined ? !swapSpec.focusScroll : !this.config.defaultFocusScroll };
this.__setFocus(newElt, focusOptions, focusInfo.start, focusInfo.end);
}
}

this.__trigger(target, "htmx:before:settle", {task, newContent, settleTasks})

Expand Down
72 changes: 71 additions & 1 deletion test/tests/unit/swap.js
Original file line number Diff line number Diff line change
Expand Up @@ -290,7 +290,6 @@ describe('swap() unit tests', function() {
})

it('triggers view transition events with transition:true', async function () {
htmx.config.logAll = true;
if (!document.startViewTransition) {
this.skip();
return;
Expand Down Expand Up @@ -428,4 +427,75 @@ describe('swap() unit tests', function() {
find('#target_oob').innerText.should.equal("OOB swap!");
})

it('restores focus after innerHTML swap when element has same id', async function () {
createProcessedHTML("<input id='focused-input' value='test'>")
let input = find('#focused-input')
input.focus()
input.setSelectionRange(2, 2)

await htmx.swap({"target":"#test-playground", "text":"<input id='focused-input' value='test'>"})

document.activeElement.id.should.equal('focused-input')
document.activeElement.selectionStart.should.equal(2)
document.activeElement.selectionEnd.should.equal(2)
})

it('restores focus after outerHTML swap when element has same id', async function () {
createProcessedHTML("<div id='container'><input id='focused-input' value='test'></div>")
let input = find('#focused-input')
input.focus()
input.setSelectionRange(1, 3)

await htmx.swap({"target":"#container", "text":"<div id='container'><input id='focused-input' value='test'></div>", "swap":"outerHTML"})

document.activeElement.id.should.equal('focused-input')
document.activeElement.selectionStart.should.equal(1)
document.activeElement.selectionEnd.should.equal(3)
})

it('does not restore focus when focused element has no id', async function () {
createProcessedHTML("<input value='test'>")
let input = playground().querySelector('input')
input.focus()

await htmx.swap({"target":"#test-playground", "text":"<input value='test'>"})

document.activeElement.should.not.equal(input)
})

it('does not restore focus when new content lacks matching id', async function () {
createProcessedHTML("<input id='focused-input' value='test'>")
let input = find('#focused-input')
input.focus()

await htmx.swap({"target":"#test-playground", "text":"<input id='different-input' value='test'>"})

document.activeElement.id.should.not.equal('focused-input')
})

it('does not restore focus for morph swaps', async function () {
createProcessedHTML("<input id='focused-input' value='test'>")
let input = find('#focused-input')
input.focus()
input.setSelectionRange(2, 2)

await htmx.swap({"target":"#test-playground", "text":"<input id='focused-input' value='test'>", "swap":"innerMorph"})

// Morph should maintain focus naturally, not through restoration
document.activeElement.should.equal(input)
})

it('restores focus to textarea after innerHTML swap', async function () {
createProcessedHTML("<textarea id='focused-textarea'>hello world</textarea>")
let textarea = find('#focused-textarea')
textarea.focus()
textarea.setSelectionRange(6, 11)

await htmx.swap({"target":"#test-playground", "text":"<textarea id='focused-textarea'>hello world</textarea>"})

document.activeElement.id.should.equal('focused-textarea')
document.activeElement.selectionStart.should.equal(6)
document.activeElement.selectionEnd.should.equal(11)
})

})