feat: add connection status indicator with SSE heartbeat
- Add ConnectionIndicator component showing green/red dot - Send lastPing signal every 15 seconds via SSE - Indicator turns red if no ping received in 20 seconds - Gives users confidence the live connection is active
This commit is contained in:
@@ -4,6 +4,7 @@ import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/alexedwards/scs/v2"
|
||||
"github.com/go-chi/chi/v5"
|
||||
@@ -123,11 +124,21 @@ func HandleSnakeEvents(snakeStore *snake.SnakeStore, nc *nats.Conn, sm *scs.Sess
|
||||
return sse.PatchElementTempl(pages.GameContent(sg, mySlot, chatMessages(), chatCfg, gameID))
|
||||
}
|
||||
|
||||
// Send initial render
|
||||
sendPing := func() error {
|
||||
return sse.PatchSignals([]byte(fmt.Sprintf(`{"lastPing":%d}`, time.Now().UnixMilli())))
|
||||
}
|
||||
|
||||
// Send initial render and ping
|
||||
if err := sendPing(); err != nil {
|
||||
return
|
||||
}
|
||||
if err := patchAll(); err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
heartbeat := time.NewTicker(15 * time.Second)
|
||||
defer heartbeat.Stop()
|
||||
|
||||
// Subscribe to game updates via NATS
|
||||
gameCh := make(chan *nats.Msg, 64)
|
||||
gameSub, err := nc.ChanSubscribe(snake.GameSubject(gameID), gameCh)
|
||||
@@ -154,6 +165,11 @@ func HandleSnakeEvents(snakeStore *snake.SnakeStore, nc *nats.Conn, sm *scs.Sess
|
||||
case <-ctx.Done():
|
||||
return
|
||||
|
||||
case <-heartbeat.C:
|
||||
if err := sendPing(); err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
case <-gameCh:
|
||||
// Drain backed-up game updates
|
||||
for {
|
||||
|
||||
@@ -32,11 +32,12 @@ templ GamePage(sg *snake.SnakeGame, mySlot int, messages []chat.Message, chatCfg
|
||||
@layouts.Base("Snake") {
|
||||
<main
|
||||
class="snake-wrapper flex flex-col items-center gap-4 p-4"
|
||||
data-signals={ `{"chatMsg":""}` }
|
||||
data-signals={ `{"chatMsg":"","lastPing":0}` }
|
||||
data-init={ fmt.Sprintf("@get('/snake/%s/events',{requestCancellation:'disabled'})", gameID) }
|
||||
data-on:keydown__throttle.100ms={ keydownScript(gameID) }
|
||||
tabindex="0"
|
||||
>
|
||||
@components.ConnectionIndicator()
|
||||
@GameContent(sg, mySlot, messages, chatCfg, gameID)
|
||||
</main>
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user