fix: append chat messages instead of re-rendering entire game
Previously patchAll() re-rendered the full GameContent on every chat message, which was inefficient and could cause UI glitches. Now we append just the new ChatMessage to the chat history element.
This commit is contained in:
@@ -23,16 +23,21 @@ type Config struct {
|
||||
StopKeyPropagation bool
|
||||
}
|
||||
|
||||
templ Chat(messages []chat.Message, cfg Config) {
|
||||
<div id={ cfg.CSSPrefix + "-chat" } class={ cfg.CSSPrefix + "-chat" }>
|
||||
<div class={ cfg.CSSPrefix + "-chat-history" }>
|
||||
for _, m := range messages {
|
||||
// ChatMessage renders a single chat message. Used for appending new messages via SSE.
|
||||
templ ChatMessage(m chat.Message, cfg Config) {
|
||||
<div class={ cfg.CSSPrefix + "-chat-msg" }>
|
||||
<span style={ fmt.Sprintf("color:%s;font-weight:bold;", cfg.Color(m.Slot)) }>
|
||||
{ m.Nickname + ": " }
|
||||
</span>
|
||||
<span>{ m.Message }</span>
|
||||
</div>
|
||||
}
|
||||
|
||||
templ Chat(messages []chat.Message, cfg Config) {
|
||||
<div id={ cfg.CSSPrefix + "-chat" } class={ cfg.CSSPrefix + "-chat" }>
|
||||
<div id={ cfg.CSSPrefix + "-chat-history" } class={ cfg.CSSPrefix + "-chat-history" }>
|
||||
for _, m := range messages {
|
||||
@ChatMessage(m, cfg)
|
||||
}
|
||||
</div>
|
||||
<div class={ cfg.CSSPrefix + "-chat-input" } data-morph-ignore>
|
||||
|
||||
@@ -148,8 +148,13 @@ func HandleGameEvents(store *connect4.Store, nc *nats.Conn, sm *scs.SessionManag
|
||||
return
|
||||
}
|
||||
case msg := <-chatCh:
|
||||
room.Receive(msg.Data)
|
||||
if err := patchAll(); err != nil {
|
||||
chatMsg, _ := room.Receive(msg.Data)
|
||||
err := sse.PatchElementTempl(
|
||||
chatcomponents.ChatMessage(chatMsg, chatCfg),
|
||||
datastar.WithSelectorID("c4-chat-history"),
|
||||
datastar.WithModeAppend(),
|
||||
)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
@@ -172,8 +172,13 @@ func HandleSnakeEvents(snakeStore *snake.SnakeStore, nc *nats.Conn, sm *scs.Sess
|
||||
if msg == nil {
|
||||
continue
|
||||
}
|
||||
room.Receive(msg.Data)
|
||||
if err := patchAll(); err != nil {
|
||||
chatMsg, _ := room.Receive(msg.Data)
|
||||
err := sse.PatchElementTempl(
|
||||
chatcomponents.ChatMessage(chatMsg, chatCfg),
|
||||
datastar.WithSelectorID("snake-chat-history"),
|
||||
datastar.WithModeAppend(),
|
||||
)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user