bigskysoftware / htmx

</> htmx - high power tools for HTML
https://htmx.org
Other
38.19k stars 1.3k forks source link

Hx-Retarget and this #1962

Open ThePrimeagen opened 12 months ago

ThePrimeagen commented 12 months ago

Hx-Retarget and this as target causes null error and prevents htmx from operating any more on the site

the docs claim that this

This example uses hx-target="this" to make a link that updates itself when clicked:

context

doing a little 422 swap and from the server i was going to target the originating form to show the error

form

<form hx-post="/thing" hx-swap="beforeend" hx-target="#things">
    ...

server

name := c.FormValue("name")
email := c.FormValue("email")

if contactExists(data.Contacts, email) {
    c.Response().Header().Set("HX-Retarget", "this")
    c.Response().Header().Set("HX-Reswap", "outerHTML")
    return c.Render(422, "test", data)
}

this will result in the target code executing, notice no special handling for this

if (hasHeader(xhr,/HX-Retarget:/i)) {
  responseInfo.target = getDocument().querySelector(xhr.getResponseHeader("HX-Retarget"));
}
ThePrimeagen commented 12 months ago

i cannot use the Request header's Hx-Target since that is the target in the form not the form itself

ThePrimeagen commented 12 months ago

also glad to submit a pr to fix this

Telroshan commented 12 months ago

Indeed, the HX-Retarget header works differently than hx-target, as its doc says:

HX-Retarget a CSS selector that updates the target of the content update to a different element on the page

I don't know if this was forgotten at the time extended selectors were added in, I don't see any reason to oppose to add support for those extended selectors for this header, relatively to the element that triggered the request

Feel free to submit a PR for it!

ThePrimeagen commented 12 months ago

i'll try to get something up in a bit

alexpetros commented 12 months ago

This is another consequence of the extended CSS selectors being a construct that exists in a lot of places, so it looks like "one thing", but isn't necessarily supported everywhere that CSS selectors are.

You probably don't have to do too much more than change the line you identified to use findAttributeTarget (although the "this" behavior is a little weird).

Also another reason to unify their documentation: #1601

ThePrimeagen commented 11 months ago

@alexpetros thanks for the direction! this is great. i will still take care of this, just preparing for my talk still :)