htmgo/examples/chat/chat/component.go

52 lines
1.3 KiB
Go
Raw Normal View History

2024-09-30 22:31:09 +00:00
package chat
2024-10-01 03:08:52 +00:00
import (
2024-10-03 16:38:40 +00:00
"chat/internal/db"
2024-10-01 03:49:03 +00:00
"fmt"
2024-10-01 03:08:52 +00:00
"github.com/maddalax/htmgo/framework/h"
2024-10-01 03:49:03 +00:00
"strings"
2024-10-01 03:08:52 +00:00
"time"
)
2024-09-30 22:31:09 +00:00
2024-10-01 03:08:52 +00:00
func MessageRow(message *Message) *h.Element {
2024-09-30 22:31:09 +00:00
return h.Div(
h.Attribute("hx-swap-oob", "beforeend"),
2024-10-02 03:26:03 +00:00
h.Class("flex flex-col gap-4 w-full break-words whitespace-normal"), // Ensure container breaks long words
2024-09-30 22:31:09 +00:00
h.Id("messages"),
2024-10-01 03:08:52 +00:00
h.Div(
2024-10-01 17:42:01 +00:00
h.Class("flex flex-col gap-1"),
h.Div(
h.Class("flex gap-2 items-center"),
h.Pf(message.UserName, h.Class("font-bold")),
h.Pf(message.CreatedAt.In(time.Local).Format("01/02 03:04 PM")),
),
2024-10-02 03:26:03 +00:00
h.Article(
h.Class("break-words whitespace-normal"), // Ensure message text wraps correctly
h.P(h.Text(message.Message)),
),
2024-10-01 03:08:52 +00:00
),
2024-09-30 22:31:09 +00:00
)
}
2024-10-01 03:49:03 +00:00
2024-10-03 16:38:40 +00:00
func ConnectedUsers(users []db.User, myId string) *h.Element {
2024-10-01 03:49:03 +00:00
return h.Ul(
2024-10-03 16:38:40 +00:00
h.Attribute("hx-swap-oob", "outerHTML"),
2024-10-01 03:49:03 +00:00
h.Id("connected-users"),
2024-10-01 17:42:01 +00:00
h.Class("flex flex-col"),
2024-10-03 16:38:40 +00:00
h.List(users, func(user db.User, index int) *h.Element {
return connectedUser(user.Name, user.SessionID == myId)
}),
2024-10-01 03:49:03 +00:00
)
}
2024-10-03 16:38:40 +00:00
func connectedUser(username string, isMe bool) *h.Element {
2024-10-01 03:49:03 +00:00
id := fmt.Sprintf("connected-user-%s", strings.ReplaceAll(username, "#", "-"))
return h.Li(
h.Id(id),
2024-10-01 18:42:14 +00:00
h.ClassX("truncate text-slate-700", h.ClassMap{
"font-bold": isMe,
}),
2024-10-01 03:49:03 +00:00
h.Text(username),
)
}