Fixed HTMX listeners.

This commit is contained in:
mikestefanello 2025-04-01 10:23:32 -04:00
parent 9441014517
commit efab433d5c
4 changed files with 32 additions and 22 deletions

View file

@ -1,7 +1,6 @@
package components package components
import ( import (
"fmt"
"strings" "strings"
"github.com/mikestefanello/pagoda/pkg/ui" "github.com/mikestefanello/pagoda/pkg/ui"
@ -10,30 +9,9 @@ import (
) )
func JS(r *ui.Request) Node { func JS(r *ui.Request) Node {
const htmxErr = `
document.body.addEventListener('htmx:beforeSwap', function(evt) {
if (evt.detail.xhr.status >= 400){
evt.detail.shouldSwap = true;
evt.detail.target = htmx.find("body");
}
});
`
const htmxCSRF = `
document.body.addEventListener('htmx:configRequest', function(evt) {
if (evt.detail.verb !== "get") {
evt.detail.parameters['csrf'] = '%s';
}
})
`
return Group{ return Group{
Script(Src("https://unpkg.com/htmx.org@2.0.0/dist/htmx.min.js")), Script(Src("https://unpkg.com/htmx.org@2.0.0/dist/htmx.min.js")),
Script(Src("https://unpkg.com/alpinejs@3.x.x/dist/cdn.min.js"), Defer()), Script(Src("https://unpkg.com/alpinejs@3.x.x/dist/cdn.min.js"), Defer()),
Script(Raw(htmxErr)),
Iff(len(r.CSRF) > 0, func() Node {
return Script(Raw(fmt.Sprintf(htmxCSRF, r.CSRF)))
}),
} }
} }

View file

@ -1,9 +1,39 @@
package components package components
import ( import (
"fmt"
"github.com/mikestefanello/pagoda/pkg/ui"
. "maragu.dev/gomponents" . "maragu.dev/gomponents"
. "maragu.dev/gomponents/html"
) )
func HtmxListeners(r *ui.Request) Node {
const htmxErr = `
document.body.addEventListener('htmx:beforeSwap', function(evt) {
if (evt.detail.xhr.status >= 400){
evt.detail.shouldSwap = true;
evt.detail.target = htmx.find("body");
}
});
`
const htmxCSRF = `
document.body.addEventListener('htmx:configRequest', function(evt) {
if (evt.detail.verb !== "get") {
evt.detail.parameters['csrf'] = '%s';
}
})
`
return Group{
Script(Raw(htmxErr)),
Iff(len(r.CSRF) > 0, func() Node {
return Script(Raw(fmt.Sprintf(htmxCSRF, r.CSRF)))
}),
}
}
func HxBoost() Node { func HxBoost() Node {
return Attr("hx-boost", "true") return Attr("hx-boost", "true")
} }

View file

@ -41,6 +41,7 @@ func Auth(r *ui.Request, content Node) Node {
), ),
), ),
), ),
HtmxListeners(r),
), ),
), ),
) )

View file

@ -36,6 +36,7 @@ func Primary(r *ui.Request, content Node) Node {
), ),
), ),
), ),
HtmxListeners(r),
), ),
), ),
) )