htmgo/examples/sse-with-state/partials/index.go

72 lines
1.5 KiB
Go
Raw Normal View History

2024-10-08 17:48:28 +00:00
package partials
import (
2024-10-16 20:29:01 +00:00
"github.com/maddalax/htmgo/extensions/websocket/state"
"github.com/maddalax/htmgo/extensions/websocket/ws"
2024-10-08 17:48:28 +00:00
"github.com/maddalax/htmgo/framework/h"
)
type Counter struct {
Count func() int
Increment func()
Decrement func()
2024-10-08 17:48:28 +00:00
}
func UseCounter(sessionId state.SessionId, id string) Counter {
2024-10-16 20:23:36 +00:00
get, set := state.Use(sessionId, id, 0)
2024-10-08 17:48:28 +00:00
var increment = func() {
set(get() + 1)
}
var decrement = func() {
set(get() - 1)
}
2024-10-08 17:48:28 +00:00
return Counter{
Count: get,
Increment: increment,
Decrement: decrement,
2024-10-08 17:48:28 +00:00
}
}
type CounterProps struct {
Id string
}
func CounterForm(ctx *h.RequestContext, props CounterProps) *h.Element {
if props.Id == "" {
2024-10-15 18:51:26 +00:00
props.Id = h.GenId(6)
2024-10-08 17:48:28 +00:00
}
counter := UseCounter(state.GetSessionId(ctx), props.Id)
2024-10-16 19:13:51 +00:00
2024-10-08 17:48:28 +00:00
return h.Div(
h.Attribute("hx-swap", "none"),
h.Class("flex flex-col gap-3 items-center"),
h.Id(props.Id),
h.P(
h.Id("counter-text-"+props.Id),
h.AttributePairs(
"id", "counter",
"class", "text-xl",
"name", "count",
"text", "count",
),
h.TextF("Count: %d", counter.Count()),
),
h.Button(
h.Class("bg-rose-400 hover:bg-rose-500 text-white font-bold py-2 px-4 rounded"),
h.Type("submit"),
h.Text("Increment"),
2024-10-16 20:23:36 +00:00
ws.OnServerSideEvent(ctx, "increment", func(data ws.HandlerData) {
2024-10-08 17:48:28 +00:00
counter.Increment()
2024-10-16 20:23:36 +00:00
ws.PushElement(data, CounterForm(ctx, props))
2024-10-08 17:48:28 +00:00
}),
2024-10-16 20:23:36 +00:00
ws.OnServerSideEvent(ctx, "decrement", func(data ws.HandlerData) {
counter.Decrement()
2024-10-16 20:23:36 +00:00
ws.PushElement(data, CounterForm(ctx, props))
}),
2024-10-08 17:48:28 +00:00
),
)
}