bigskysoftware / htmx

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

htmx inside svg `foreignObject` #2952

Closed jonmattgray closed 2 weeks ago

jonmattgray commented 1 month ago

I'm attempting to add a htmx button inside an svg foreignObject element but unfortunately no request is triggered when I click the button.

<foreignObject width="100" height="30">
    <button style="height: 100%; width: 100%;" hx-get="/api" hx-target="#someDiv"></button>
</foreignObject>

The button works correctly when placed outside of svg. Is it possible for htmx to work inside svg foreignObject?

Thanks

MichaelWest22 commented 1 month ago

I just pasted the above into a svg and it worked straight away for me with no issues on the current htmx version.

    <svg width="100" height="100" viewBox="0 0 100 100">
        <circle cx="50" cy="50" r="20" fill="blue" hx-get="api/svg" hx-swap="outerHTML" hx-select="#rect" id="circle3">
        </circle>
        <rect x="5" y="85" width="10" height="10" fill="purple"></rect>
        <foreignObject width="100" height="30">
            <button style="height: 100%; width: 100%;" hx-get="/api" hx-target="#foo">HELLO</button>
        </foreignObject>
      </svg>

And you don't even need to place a button inside your svg to do what you want as you can just add htmx attributes to any of svg native element like a rect or a circle etc.

Getting the svg elements width and heights right so you can see your foreign object could cause issues with svg's.

I added some useful notes about svg usage here: https://htmx.org/attributes/hx-swap-oob/ and you have to be aware of issues caused by svg namesapces. normally if you are adding the svg normally just by loading it as html on page load then namespaces should not cause any issues as long as you have svg tags properly formatted. If you are swapping in content into the middle of a svg you have to be very careful to make sure the new content has the right namespaces which it gets based on the wrapping tags returned in the response. I do not know what namespace wrapping content swapped into foreignObject tags would need so would have to test different options to find what works best.

jonmattgray commented 2 weeks ago

Thank you. The svg was being generated by Mermaid, which turns out uses DOMPurify, which was stripping the htmx attributes