htmx
htmx copied to clipboard
A way to reset/block hx-select and HX-Reselect. IMPROVEMENT
The problem
An element has the attributes hx-target, hx-swap, and hx-select. When the service called from htmx responds with the correct document the behaviour is correct, htmx takes a fragment of the document based on hx-select and swaps it with the style and target we have specified. However, when the service replaces hx-target and hx-swap with their respective headers (HX-Retarget and HX-Reswap) htmx still takes into consideration the hx-select attribute we have set on the element, this can cause errors where no UI is updated, mainly because htmx looks for a fragment on our response that does not exist.
Possible solutions
- HX-Reselect: I have experiment with it, but I have not been able to find a way to "reset" the behaviour, htmx always tries to find a way to select a fragment from the response. Maybe I'm wrong and there is actually a way to do so
- Not using hx-select: It could be a good alternative, however I do consider there should be a way of "resetting" its behaviour
Implementation
Just like the swapStyle
we could implement some sort of keyword that blocks completely the check of fragments when hx-select or HX-Reselect have been specified. maybe some sort of "none"?
function maybeSelectFromResponse(elt, fragment, selectOverride) {
var selector = selectOverride || getClosestAttributeValue(elt, "hx-select");
if (selector) {
if (selector === "none") {
return fragment
}
var newFragment = getDocument().createDocumentFragment();
forEach(fragment.querySelectorAll(selector), function (node) {
newFragment.appendChild(node);
});
fragment = newFragment;
}
return fragment;
}
sorry for the indentation
I'd be happy to open a PR with this improvement if it is accepted