6
1
mirror of https://git.mills.io/saltyim/saltyim.git synced 2024-07-08 02:51:32 +00:00
prologic-saltyim/internal/pwa/components/chatbox.go
mlctrez 969a263d06 support for contacts, multiple chat threads, and persistence (#77)
Co-authored-by: James Mills <prologic@shortcircuit.net.au>
Co-authored-by: James Mills <james@mills.io>
Co-authored-by: mlctrez <mlctrez@gmail.com>
Reviewed-on: https://git.mills.io/saltyim/saltyim/pulls/77
Co-authored-by: mlctrez <mlctrez@noreply@mills.io>
Co-committed-by: mlctrez <mlctrez@noreply@mills.io>
2022-03-28 21:49:01 +00:00

69 lines
1.6 KiB
Go

package components
import (
"fmt"
"github.com/maxence-charriere/go-app/v9/pkg/app"
"github.com/mlctrez/goapp-mdc/pkg/base"
"go.mills.io/saltyim/internal/pwa/storage"
)
type ChatBox struct {
app.Compo
base.JsUtil
// User is who we're conversing with
User string
messages []string
}
func (c *ChatBox) OnMount(ctx app.Context) {
ctx.Handle("chatbox", c.actionHandler)
if c.User != "" {
c.messages = storage.ConversationsLocalStorage(ctx, c.User).Read()
}
ctx.Defer(func(context app.Context) {
c.Update()
c.scrollChatPane(ctx)
})
}
// actionHandler receives messages intended to update this component
func (c *ChatBox) actionHandler(ctx app.Context, action app.Action) {
c.User = action.Tags.Get("user")
c.messages = storage.ConversationsLocalStorage(ctx, c.User).Read()
c.Update()
}
func (c *ChatBox) UpdateMessages(ctx app.Context) {
if c.User == "" {
return
}
ctx.NewAction("chatbox", app.T("user", c.User))
c.scrollChatPane(ctx)
}
func (c *ChatBox) Render() app.UI {
return app.Div().ID("chatbox").Body(c.body())
}
func (c *ChatBox) body() app.UI {
if len(c.messages) == 0 {
return app.P().Text(fmt.Sprintf("no messages for user = %q", c.User))
} else {
return app.Range(c.messages).Slice(func(i int) app.UI {
return app.P().Class("chat-paragraph").Text(c.messages[i])
})
}
}
func (c *ChatBox) OnResize(ctx app.Context) {
c.scrollChatPane(ctx)
}
func (c *ChatBox) scrollChatPane(ctx app.Context) {
ctx.Defer(func(context app.Context) {
chatBoxDiv := c.JsUtil.JsValueAtPath("chatbox")
chatBoxDiv.Set("scrollTop", chatBoxDiv.Get("scrollHeight"))
})
}