bigskysoftware / htmx

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

Add hx-swap="attributes" #373

Closed maratori closed 3 years ago

maratori commented 3 years ago

Let's add new possible value for hx-swap="attributes".

Use case

Initial HTML

<div hx-target="this" hx-swap="attributes" class="initial-class">
    /* some stuff with css styles depending on div class */
    <input type="text" name="myinput" hx-get="/validate" hx-trigger="keyup changed" />
</div>

Response of /validate

<div hx-target="this" hx-swap="attributes" class="changed-class" />

Result HTML

<div hx-target="this" hx-swap="attributes" class="changed-class">
    /* some stuff with css styles depending on div class */
    <input type="text" name="myinput" hx-get="/validate" hx-trigger="keyup changed" />
</div>

Note

I can't use hx-swap="outerHTML" because of #372. As a workaround I use hx-swap-oob to replace the first children of <div>. But in that case I have to use strange selectors in css.

bencroker commented 3 years ago

It seems like you're asking for this as a workaround to https://github.com/bigskysoftware/htmx/issues/372. I'll defer to @1cg on this one.

benpate commented 3 years ago

This request seems odd to me. I love "Hypertext as the Engine of Application State" but this kind of validation should be handled on the client side. The "server side" validation usually only happens as a final check, after the whole transaction is posted.

If this absolutely must be done server-side, one possible solution would be to use Javascript (or hypersrcipt!) to handle this validation for you. Some of the new async-transparent features of hypersrcipt would make this a real breeze.

<div id="wrapper" class="initial-class">
    <input type="text" name="my input" 
        _="on keyup fetch /validate then put it into #wrapper.class">
</div>

Your /validate endpoint would just have to return the class attributes you want changed, and you're off to the races!

1cg commented 3 years ago

I would say that this should be implemented as a custom swap style, in the manner of the morphdom swap:

https://github.com/bigskysoftware/htmx/blob/master/src/ext/morphdom-swap.js

If it proves general enough we can consider merging it into the core.