Added Wails3/HTMX example GUI

This commit is contained in:
2024-11-05 05:17:27 -07:00
parent d99293dba1
commit 90a87af526
31 changed files with 1481 additions and 47 deletions

68
desktop/routes/app.go Normal file
View File

@ -0,0 +1,68 @@
package routes
import (
"log/slog"
"net/http"
"git.codemonkeysoftware.net/b/peachy-go/desktop/components"
"git.codemonkeysoftware.net/b/peachy-go/desktop/pages"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
"github.com/go-chi/httplog/v2"
)
/*
Create a new chi router, configure it and return it.
*/
func NewChiRouter() *chi.Mux {
r := chi.NewRouter()
// Useful middleware, see : https://pkg.go.dev/github.com/go-chi/httplog/v2@v2.1.1#NewLogger
logger := httplog.NewLogger("app-logger", httplog.Options{
// All log
LogLevel: slog.LevelInfo,
Concise: true,
})
// Use the logger and recoverer middleware.
r.Use(httplog.RequestLogger(logger))
r.Use(middleware.Recoverer)
/*
// ULTRA IMPORTANT : This middleware is used to prevent caching of the pages.
// Sometimes, HX requests may be cached by the browser, which may cause unexpected behavior.
r.Use(func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "no-store")
next.ServeHTTP(w, r)
})
})
*/
// Serve static files.
r.Handle("/static/*", http.StripPrefix("/static/", http.FileServer(http.Dir("static"))))
// Home page
r.Get("/", func(w http.ResponseWriter, r *http.Request) {
// Render home page
HXRender(w, r, pages.HomePage)
// 200 OK status
w.WriteHeader(http.StatusOK)
})
// Hello page
r.Get("/hello", func(w http.ResponseWriter, r *http.Request) {
// Render hello
HXRender(w, r, components.HelloWorld)
// 200 OK status
w.WriteHeader(http.StatusOK)
})
// Listen to port 3000.
go http.ListenAndServe(":9245", r)
return r
}

27
desktop/routes/util.go Normal file
View File

@ -0,0 +1,27 @@
package routes
import (
"net/http"
"git.codemonkeysoftware.net/b/hatmill"
"git.codemonkeysoftware.net/b/peachy-go/desktop/pages"
"github.com/mavolin/go-htmx"
)
/*
Render the component, and if it's an HX request, only render the component.
*/
func HXRender[T hatmill.Term](w http.ResponseWriter, r *http.Request, component func() T) {
hxRequest := htmx.Request(r)
w.Header().Set("Content-Type", "text/html")
// If it's an HX request, we only render the component.
// If it's not, we render the whole page.
if hxRequest == nil {
hatmill.WriteDocument(w, pages.Page(component))
pages.Page(component)
} else {
component().WriteTo(w)
}
}