xonecas.io
8058
Ir

irvc / commit 3b812d8

feat: react to messages

xonecas2026-10-15 3b812d826304e14cde95f45a42f839953c7674a8 parent e31be5d

5 files changed

channels.go+114−0
@@ -163,9 +163,59 @@ func (s *Server) handleMessages(c *gin.Context) {
163163 for i, j := 0, len(messages)-1; i < j; i, j = i+1, j-1 {
164164 messages[i], messages[j] = messages[j], messages[i]
165165 }
166+ if len(messages) > 0 {
167+ byID := make(map[int64]*Message, len(messages))
168+ for i := range messages {
169+ byID[messages[i].ID] = &messages[i]
170+ }
171+ rRows, err := s.db.Query(
172+ `SELECT r.message_id, r.reaction, u.username
173+ FROM reactions r JOIN users u ON u.id = r.user_id
174+ WHERE r.message_id >= ? AND r.message_id <= ?
175+ ORDER BY r.rowid`,
176+ messages[0].ID, messages[len(messages)-1].ID,
177+ )
178+ if err == nil {
179+ defer rRows.Close()
180+ for rRows.Next() {
181+ var mid int64
182+ var react, uname string
183+ if rRows.Scan(&mid, &react, &uname) == nil {
184+ if m := byID[mid]; m != nil {
185+ if m.Reactions == nil {
186+ m.Reactions = map[string][]string{}
187+ }
188+ m.Reactions[react] = append(m.Reactions[react], uname)
189+ }
190+ }
191+ }
192+ }
193+ }
166194 c.JSON(http.StatusOK, messages)
167195 }
168196
197+func (s *Server) messageReactions(msgID int64) map[string][]string {
198+ rows, err := s.db.Query(
199+ `SELECT r.reaction, u.username FROM reactions r JOIN users u ON u.id = r.user_id WHERE r.message_id = ? ORDER BY r.rowid`,
200+ msgID,
201+ )
202+ if err != nil {
203+ return nil
204+ }
205+ defer rows.Close()
206+ var out map[string][]string
207+ for rows.Next() {
208+ var react, uname string
209+ if rows.Scan(&react, &uname) == nil {
210+ if out == nil {
211+ out = map[string][]string{}
212+ }
213+ out[react] = append(out[react], uname)
214+ }
215+ }
216+ return out
217+}
218+
169219 type sendMessageRequest struct {
170220 Body string `json:"body"`
171221 }
@@ -240,12 +290,76 @@ func (s *Server) handleEditMessage(c *gin.Context) {
240290 return
241291 }
242292 m.Username = user.Username
293+ m.Reactions = s.messageReactions(m.ID)
243294 var chType, chName string
244295 s.db.QueryRow(`SELECT type, name FROM channels WHERE id = ?`, m.ChannelID).Scan(&chType, &chName)
245296 s.notifyChannel(chType, chName, event{Type: "message_edit", Message: &m})
246297 c.JSON(http.StatusOK, m)
247298 }
248299
300+var validReactions = map[string]bool{
301+ "+1": true,
302+ "-1": true,
303+ "heart": true,
304+ "laugh": true,
305+}
306+
307+type reactionRequest struct {
308+ Reaction string `json:"reaction"`
309+}
310+
311+func (s *Server) handleToggleReaction(c *gin.Context) {
312+ msgID, err := strconv.ParseInt(c.Param("id"), 10, 64)
313+ if err != nil {
314+ c.JSON(http.StatusBadRequest, gin.H{"error": "bad message"})
315+ return
316+ }
317+ var req reactionRequest
318+ if err := c.ShouldBindJSON(&req); err != nil || !validReactions[req.Reaction] {
319+ c.JSON(http.StatusBadRequest, gin.H{"error": "invalid reaction"})
320+ return
321+ }
322+ var m Message
323+ err = s.db.QueryRow(
324+ `SELECT m.id, m.channel_id, m.user_id, u.username, m.body, m.created_at, COALESCE(m.edited_at, 0)
325+ FROM messages m JOIN users u ON u.id = m.user_id WHERE m.id = ?`,
326+ msgID,
327+ ).Scan(&m.ID, &m.ChannelID, &m.UserID, &m.Username, &m.Body, &m.CreatedAt, &m.EditedAt)
328+ if err != nil {
329+ if err == sql.ErrNoRows {
330+ c.JSON(http.StatusNotFound, gin.H{"error": "message not found"})
331+ return
332+ }
333+ c.JSON(http.StatusInternalServerError, gin.H{"error": "db"})
334+ return
335+ }
336+ user := c.MustGet("user").(User)
337+ chType, chName, ok := s.checkTextOrDM(c, m.ChannelID, user.ID)
338+ if !ok {
339+ return
340+ }
341+ res, err := s.db.Exec(
342+ `DELETE FROM reactions WHERE message_id = ? AND user_id = ? AND reaction = ?`,
343+ msgID, user.ID, req.Reaction,
344+ )
345+ if err != nil {
346+ c.JSON(http.StatusInternalServerError, gin.H{"error": "db"})
347+ return
348+ }
349+ if n, _ := res.RowsAffected(); n == 0 {
350+ if _, err := s.db.Exec(
351+ `INSERT INTO reactions (message_id, user_id, reaction) VALUES (?, ?, ?)`,
352+ msgID, user.ID, req.Reaction,
353+ ); err != nil {
354+ c.JSON(http.StatusInternalServerError, gin.H{"error": "db"})
355+ return
356+ }
357+ }
358+ m.Reactions = s.messageReactions(m.ID)
359+ s.notifyChannel(chType, chName, event{Type: "message_edit", Message: &m})
360+ c.JSON(http.StatusOK, m)
361+}
362+
249363 func (s *Server) handleDeleteMessage(c *gin.Context) {
250364 msgID, err := strconv.ParseInt(c.Param("id"), 10, 64)
251365 if err != nil {
db.go+14−7
@@ -23,13 +23,14 @@ type Channel struct {
2323 }
2424
2525 type Message struct {
26- ID int64 `json:"id"`
27- ChannelID int64 `json:"channelId"`
28- UserID int64 `json:"userId"`
29- Username string `json:"username"`
30- Body string `json:"body"`
31- CreatedAt int64 `json:"createdAt"`
32- EditedAt int64 `json:"editedAt,omitempty"`
26+ ID int64 `json:"id"`
27+ ChannelID int64 `json:"channelId"`
28+ UserID int64 `json:"userId"`
29+ Username string `json:"username"`
30+ Body string `json:"body"`
31+ CreatedAt int64 `json:"createdAt"`
32+ EditedAt int64 `json:"editedAt,omitempty"`
33+ Reactions map[string][]string `json:"reactions,omitempty"`
3334 }
3435
3536 func OpenDB(path string) *sql.DB {
@@ -79,6 +80,12 @@ CREATE TABLE IF NOT EXISTS messages (
7980 created_at INTEGER NOT NULL,
8081 edited_at INTEGER
8182 );
83+CREATE TABLE IF NOT EXISTS reactions (
84+ message_id INTEGER NOT NULL REFERENCES messages(id) ON DELETE CASCADE,
85+ user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
86+ reaction TEXT NOT NULL,
87+ PRIMARY KEY (message_id, user_id, reaction)
88+);
8289 CREATE INDEX IF NOT EXISTS idx_messages_channel ON messages(channel_id, id);
8390 CREATE UNIQUE INDEX IF NOT EXISTS idx_channels_dm ON channels(name) WHERE type = 'dm';
8491 `
main.go+1−0
@@ -137,6 +137,7 @@ func runServer(cfg *Config, db *sql.DB) {
137137 authed.POST("/channels/:id/messages", s.handleSendMessage)
138138 authed.PATCH("/messages/:id", s.handleEditMessage)
139139 authed.DELETE("/messages/:id", s.handleDeleteMessage)
140+ authed.POST("/messages/:id/reactions", s.handleToggleReaction)
140141 authed.POST("/channels/:id/voice", s.handleVoiceToken)
141142 authed.POST("/invites", s.handleCreateInvite)
142143 authed.POST("/upload", s.handleUpload)
web/src/components/ChatPane.tsx+106−35
@@ -8,13 +8,29 @@ import {
88 type FormEvent,
99 type KeyboardEvent,
1010 } from "react";
11-import { Paperclip, Pencil, SendHorizontal, Trash2 } from "lucide-react";
11+import {
12+ Heart,
13+ Laugh,
14+ Paperclip,
15+ Pencil,
16+ SendHorizontal,
17+ ThumbsDown,
18+ ThumbsUp,
19+ Trash2,
20+} from "lucide-react";
1221 import { Button } from "@/components/ui/button";
1322 import { cn } from "cn";
1423 import { api, upload } from "../lib/api";
15-import type { Channel, Message, UserSummary } from "../lib/types";
24+import type { Channel, Message, Reaction, UserSummary } from "../lib/types";
1625 import Markdown from "./Markdown";
1726
27+const reactions: { key: Reaction; label: string; Icon: typeof ThumbsUp }[] = [
28+ { key: "+1", label: "+1", Icon: ThumbsUp },
29+ { key: "-1", label: "-1", Icon: ThumbsDown },
30+ { key: "heart", label: "like", Icon: Heart },
31+ { key: "laugh", label: "laugh", Icon: Laugh },
32+];
33+
1834 const maxInputHeight = 200;
1935 const maxSuggestions = 8;
2036
@@ -219,6 +235,13 @@ export default function ChatPane({
219235 await api(`/messages/${id}`, { method: "DELETE" }).catch(() => {});
220236 }
221237
238+ async function toggleReaction(id: number, reaction: Reaction) {
239+ await api(`/messages/${id}/reactions`, {
240+ method: "POST",
241+ body: JSON.stringify({ reaction }),
242+ }).catch(() => {});
243+ }
244+
222245 async function send() {
223246 const text = body.trim();
224247 if (!text || !channel) return;
@@ -323,43 +346,91 @@ export default function ChatPane({
323346 }}
324347 className="max-h-[200px] min-w-0 flex-1 resize-none rounded border border-input bg-transparent px-2 py-0.5 text-sm leading-6 outline-none focus-visible:border-ring focus-visible:ring-2 focus-visible:ring-ring/50 dark:bg-input/30"
325348 />
326- ) : action ? (
327- <div className="min-w-0 flex-1 break-words italic text-gold/90">
328- * {m.username} {action}
329- {m.editedAt ? (
330- <span className="ml-1 not-italic text-xs text-sepia/40">(edited)</span>
331- ) : null}
332- </div>
333349 ) : (
334- <div className={bodyClass}>
335- <Markdown
336- text={m.body}
337- collapsed={collapsed.has(m.id)}
338- onToggle={() => toggleImage(m.id)}
339- />
340- {m.editedAt ? <span className="text-xs text-sepia/40">(edited)</span> : null}
350+ <div className="min-w-0 flex-1">
351+ {action ? (
352+ <div className="break-words italic text-gold/90">
353+ * {m.username} {action}
354+ {m.editedAt ? (
355+ <span className="ml-1 not-italic text-xs text-sepia/40">(edited)</span>
356+ ) : null}
357+ </div>
358+ ) : (
359+ <div className={bodyClass}>
360+ <Markdown
361+ text={m.body}
362+ collapsed={collapsed.has(m.id)}
363+ onToggle={() => toggleImage(m.id)}
364+ />
365+ {m.editedAt ? (
366+ <span className="text-xs text-sepia/40">(edited)</span>
367+ ) : null}
368+ </div>
369+ )}
370+ {m.reactions && Object.keys(m.reactions).length > 0 && (
371+ <div className="mt-0.5 flex flex-wrap gap-1 pb-0.5">
372+ {reactions.map(({ key, Icon }) => {
373+ const list = m.reactions?.[key];
374+ if (!list?.length) return null;
375+ const active = list.includes(username);
376+ return (
377+ <button
378+ key={key}
379+ type="button"
380+ title={list.join(", ")}
381+ onClick={() => toggleReaction(m.id, key)}
382+ className={cn(
383+ "inline-flex items-center gap-1 rounded border px-1.5 py-0.5 text-xs leading-none transition-colors",
384+ active
385+ ? "border-gold/50 bg-gold/15 text-gold"
386+ : "border-sepia/20 bg-sepia/5 text-sepia/70 hover:border-sepia/40",
387+ )}
388+ >
389+ <Icon className="size-3" />
390+ {list.length}
391+ </button>
392+ );
393+ })}
394+ </div>
395+ )}
341396 </div>
342397 )}
343- {own && !editing && (
398+ {!editing && (
344399 <div className="invisible flex shrink-0 items-center gap-0.5 group-hover:visible">
345- <Button
346- type="button"
347- variant="ghost"
348- size="icon-xs"
349- title="edit message"
350- onClick={() => startEdit(m)}
351- >
352- <Pencil />
353- </Button>
354- <Button
355- type="button"
356- variant="ghost"
357- size="icon-xs"
358- title="delete message"
359- onClick={() => remove(m.id)}
360- >
361- <Trash2 />
362- </Button>
400+ {reactions.map(({ key, label, Icon }) => (
401+ <Button
402+ key={key}
403+ type="button"
404+ variant="ghost"
405+ size="icon-xs"
406+ title={label}
407+ onClick={() => toggleReaction(m.id, key)}
408+ >
409+ <Icon />
410+ </Button>
411+ ))}
412+ {own && (
413+ <>
414+ <Button
415+ type="button"
416+ variant="ghost"
417+ size="icon-xs"
418+ title="edit message"
419+ onClick={() => startEdit(m)}
420+ >
421+ <Pencil />
422+ </Button>
423+ <Button
424+ type="button"
425+ variant="ghost"
426+ size="icon-xs"
427+ title="delete message"
428+ onClick={() => remove(m.id)}
429+ >
430+ <Trash2 />
431+ </Button>
432+ </>
433+ )}
363434 </div>
364435 )}
365436 </div>
web/src/lib/types.ts+3−0
@@ -16,6 +16,8 @@ export interface Channel {
1616 position: number;
1717 }
1818
19+export type Reaction = "+1" | "-1" | "heart" | "laugh";
20+
1921 export interface Message {
2022 id: number;
2123 channelId: number;
@@ -24,6 +26,7 @@ export interface Message {
2426 body: string;
2527 createdAt: number;
2628 editedAt?: number;
29+ reactions?: Partial<Record<Reaction, string[]>>;
2730 }
2831
2932 export interface WSEvent {