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/ws"
|
2024-10-08 17:48:28 +00:00
|
|
|
"github.com/maddalax/htmgo/framework/h"
|
2024-10-16 20:43:34 +00:00
|
|
|
"github.com/maddalax/htmgo/framework/session"
|
2024-10-08 17:48:28 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
|
|
type Counter struct {
|
|
|
|
|
Count func() int
|
|
|
|
|
Increment func()
|
2024-10-16 19:35:02 +00:00
|
|
|
Decrement func()
|
2024-10-08 17:48:28 +00:00
|
|
|
}
|
|
|
|
|
|
2024-10-17 14:53:30 +00:00
|
|
|
func UseCounter(ctx *h.RequestContext, id string) Counter {
|
|
|
|
|
sessionId := session.GetSessionId(ctx)
|
2024-10-16 20:43:34 +00:00
|
|
|
get, set := session.UseState(sessionId, id, 0)
|
2024-10-08 17:48:28 +00:00
|
|
|
|
|
|
|
|
var increment = func() {
|
|
|
|
|
set(get() + 1)
|
|
|
|
|
}
|
|
|
|
|
|
2024-10-16 19:35:02 +00:00
|
|
|
var decrement = func() {
|
|
|
|
|
set(get() - 1)
|
|
|
|
|
}
|
|
|
|
|
|
2024-10-08 17:48:28 +00:00
|
|
|
return Counter{
|
|
|
|
|
Count: get,
|
|
|
|
|
Increment: increment,
|
2024-10-16 19:35:02 +00:00
|
|
|
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
|
|
|
}
|
2024-10-17 14:53:30 +00:00
|
|
|
counter := UseCounter(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) {
|
2024-10-16 19:35:02 +00:00
|
|
|
counter.Decrement()
|
2024-10-16 20:23:36 +00:00
|
|
|
ws.PushElement(data, CounterForm(ctx, props))
|
2024-10-16 19:35:02 +00:00
|
|
|
}),
|
2024-10-08 17:48:28 +00:00
|
|
|
),
|
|
|
|
|
)
|
|
|
|
|
}
|