xonecas.io
8058
Ir

irvc / commit f6af39f

feat: unreads notif

xonecas2026-10-15 f6af39f9b9ded9fa343ab38f3228c7cb9290e569 parent 5dd0368

7 files changed

channels.go+43−2
@@ -55,7 +55,15 @@ func (s *Server) handleChannels(c *gin.Context) {
5555 for _, u := range s.hub.roster() {
5656 users[u.ID] = u.Username
5757 }
58- rows, err := s.db.Query(`SELECT id, type, name, position, permanent FROM channels ORDER BY position, id`)
58+ rows, err := s.db.Query(
59+ `SELECT c.id, c.type, c.name, c.position, c.permanent,
60+ (SELECT COUNT(*) FROM messages m
61+ WHERE m.channel_id = c.id AND m.user_id != ?
62+ AND m.id > COALESCE((SELECT r.last_read_message_id FROM read_state r
63+ WHERE r.user_id = ? AND r.channel_id = c.id), 0))
64+ FROM channels c ORDER BY c.position, c.id`,
65+ user.ID, user.ID,
66+ )
5967 if err != nil {
6068 c.JSON(http.StatusInternalServerError, gin.H{"error": "db"})
6169 return
@@ -64,7 +72,7 @@ func (s *Server) handleChannels(c *gin.Context) {
6472 channels := []Channel{}
6573 for rows.Next() {
6674 var ch Channel
67- if err := rows.Scan(&ch.ID, &ch.Type, &ch.Name, &ch.Position, &ch.Permanent); err != nil {
75+ if err := rows.Scan(&ch.ID, &ch.Type, &ch.Name, &ch.Position, &ch.Permanent, &ch.Unread); err != nil {
6876 c.JSON(http.StatusInternalServerError, gin.H{"error": "db"})
6977 return
7078 }
@@ -87,6 +95,39 @@ func (s *Server) handleChannels(c *gin.Context) {
8795 c.JSON(http.StatusOK, channels)
8896 }
8997
98+// handleMarkRead advances the caller's read cursor for a channel to the latest
99+// message, clearing its unread count for every device they use.
100+func (s *Server) handleMarkRead(c *gin.Context) {
101+ channelID, err := strconv.ParseInt(c.Param("id"), 10, 64)
102+ if err != nil {
103+ c.JSON(http.StatusBadRequest, gin.H{"error": "bad channel"})
104+ return
105+ }
106+ user := c.MustGet("user").(User)
107+ if _, _, ok := s.checkTextOrDM(c, channelID, user.ID); !ok {
108+ return
109+ }
110+ var lastID int64
111+ if err := s.db.QueryRow(
112+ `SELECT COALESCE(MAX(id), 0) FROM messages WHERE channel_id = ?`, channelID,
113+ ).Scan(&lastID); err != nil {
114+ c.JSON(http.StatusInternalServerError, gin.H{"error": "db"})
115+ return
116+ }
117+ if _, err := s.db.Exec(
118+ `INSERT INTO read_state (user_id, channel_id, last_read_message_id, updated_at)
119+ VALUES (?, ?, ?, ?)
120+ ON CONFLICT(user_id, channel_id) DO UPDATE SET
121+ last_read_message_id = MAX(last_read_message_id, excluded.last_read_message_id),
122+ updated_at = excluded.updated_at`,
123+ user.ID, channelID, lastID, time.Now().Unix(),
124+ ); err != nil {
125+ c.JSON(http.StatusInternalServerError, gin.H{"error": "db"})
126+ return
127+ }
128+ c.Status(http.StatusNoContent)
129+}
130+
90131 type createChannelRequest struct {
91132 Type string `json:"type"`
92133 Name string `json:"name"`
db.go+8−0
@@ -21,6 +21,7 @@ type Channel struct {
2121 Name string `json:"name"`
2222 Position int `json:"position"`
2323 Permanent bool `json:"permanent"`
24+ Unread int `json:"unread"`
2425 }
2526
2627 type Message struct {
@@ -88,6 +89,13 @@ CREATE TABLE IF NOT EXISTS reactions (
8889 reaction TEXT NOT NULL,
8990 PRIMARY KEY (message_id, user_id, reaction)
9091 );
92+CREATE TABLE IF NOT EXISTS read_state (
93+ user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
94+ channel_id INTEGER NOT NULL REFERENCES channels(id) ON DELETE CASCADE,
95+ last_read_message_id INTEGER NOT NULL DEFAULT 0,
96+ updated_at INTEGER NOT NULL,
97+ PRIMARY KEY (user_id, channel_id)
98+);
9199 CREATE INDEX IF NOT EXISTS idx_messages_channel ON messages(channel_id, id);
92100 CREATE UNIQUE INDEX IF NOT EXISTS idx_channels_dm ON channels(name) WHERE type = 'dm';
93101 CREATE UNIQUE INDEX IF NOT EXISTS idx_channels_name ON channels(type, name) WHERE type != 'dm';
irvc.md+3−0
@@ -60,6 +60,8 @@ invites (token, created_by, expires_at, used_by, used_at)
6060 sessions (id, user_id, expires_at)
6161 channels (id, type, name, position, created_at) -- type: text | voice | dm
6262 messages (id, channel_id, user_id, body, created_at, edited_at)
63+reactions (message_id, user_id, reaction)
64+read_state (user_id, channel_id, last_read_message_id, updated_at)
6365 ```
6466
6567 - Messages are returned joined with their author's username.
@@ -72,6 +74,7 @@ messages (id, channel_id, user_id, body, created_at, edited_at)
7274 - **Channels:** seeded (`#general` text, `general` voice) plus on-demand 1-on-1 DMs opened by clicking a user. Ordered by `position`. Public channel CRUD is out of scope.
7375 - **Text:** GFM markdown; single newlines are hard breaks. Messages persist; live append over WS. Rendered as timestamp, author, content.
7476 - **Mentions:** `@username` highlights the message for that user; typing `@` opens an autocomplete.
77+- **Unread:** `read_state` stores each user's last-read message per channel; `/channels` returns the count of newer messages by others. Opening a channel marks it read, so the count survives reload and is shared across devices.
7578 - **Commands:** `/me <action>` renders an emote as `* user action`; `/collapse` hides images in the current channel; `/gif [query]` opens a picker with the top Giphy results (trending when no query) to insert one.
7679 - **Images:** pasted or attached, uploaded, rendered inline with a click-to-zoom dialog. Collapsible per message or channel-wide. Gifs from Giphy can also be inserted with the gif picker.
7780 - **Voice:** joining a voice channel connects to its LiveKit room (`voice-<id>`). Not persisted, not recorded. Occupants are visible to everyone without joining.
main.go+1−0
@@ -137,6 +137,7 @@ func runServer(cfg *Config, db *sql.DB) {
137137 authed.POST("/dms/:userId", s.handleOpenDM)
138138 authed.GET("/channels/:id/messages", s.handleMessages)
139139 authed.POST("/channels/:id/messages", s.handleSendMessage)
140+ authed.POST("/channels/:id/read", s.handleMarkRead)
140141 authed.PATCH("/messages/:id", s.handleEditMessage)
141142 authed.DELETE("/messages/:id", s.handleDeleteMessage)
142143 authed.POST("/messages/:id/reactions", s.handleToggleReaction)
web/src/components/Sidebar.tsx+49−31
@@ -21,6 +21,7 @@ import {
2121 } from "lucide-react";
2222 import { Button } from "@/components/ui/button";
2323 import { Input } from "@/components/ui/input";
24+import { cn } from "cn";
2425 import { api } from "../lib/api";
2526 import type { Channel, UserSummary } from "../lib/types";
2627 import type { Mode } from "../lib/theme";
@@ -41,6 +42,7 @@ const byName = (a: Channel, b: Channel) => a.name.localeCompare(b.name);
4142
4243 export default function Sidebar({
4344 channels,
45+ unread,
4446 selected,
4547 onSelect,
4648 onCloseDM,
@@ -59,6 +61,7 @@ export default function Sidebar({
5961 onLogout,
6062 }: {
6163 channels: Channel[];
64+ unread: Record<number, number>;
6265 selected: Channel | null;
6366 onSelect: (c: Channel) => void;
6467 onCloseDM: (c: Channel) => void;
@@ -120,6 +123,7 @@ export default function Sidebar({
120123 <Group
121124 label="Text"
122125 channels={texts}
126+ unread={unread}
123127 selected={selected}
124128 onSelect={onSelect}
125129 onDelete={deleteChannel}
@@ -177,6 +181,7 @@ export default function Sidebar({
177181 <Group
178182 label="DMs"
179183 channels={dms}
184+ unread={unread}
180185 selected={selected}
181186 onSelect={onSelect}
182187 onClose={onCloseDM}
@@ -234,6 +239,7 @@ export default function Sidebar({
234239 function Group({
235240 label,
236241 channels,
242+ unread,
237243 selected,
238244 onSelect,
239245 onClose,
@@ -243,6 +249,7 @@ function Group({
243249 }: {
244250 label: string;
245251 channels: Channel[];
252+ unread: Record<number, number>;
246253 selected: Channel | null;
247254 onSelect: (c: Channel) => void;
248255 onClose?: (c: Channel) => void;
@@ -265,40 +272,51 @@ function Group({
265272 </Button>
266273 )}
267274 </div>
268- {channels.map((c) => (
269- <div key={c.id} className="group/dm relative">
270- <Button
271- variant={selected?.id === c.id ? "secondary" : "ghost"}
272- onClick={() => onSelect(c)}
273- className="w-full justify-start gap-2 pr-7 font-normal"
274- >
275- {icon}
276- {c.name}
277- </Button>
278- {onClose && (
279- <Button
280- variant="ghost"
281- size="icon-xs"
282- onClick={() => onClose(c)}
283- title="close dm"
284- className="absolute top-1/2 right-1 -translate-y-1/2 opacity-0 group-hover/dm:opacity-100"
285- >
286- <X />
287- </Button>
288- )}
289- {onDelete && !c.permanent && (
275+ {channels.map((c) => {
276+ const count = unread[c.id] ?? 0;
277+ return (
278+ <div key={c.id} className="group/dm relative">
290279 <Button
291- variant="ghost"
292- size="icon-xs"
293- onClick={() => onDelete(c)}
294- title="delete channel"
295- className="absolute top-1/2 right-1 -translate-y-1/2 opacity-0 group-hover/dm:opacity-100"
280+ variant={selected?.id === c.id ? "secondary" : "ghost"}
281+ onClick={() => onSelect(c)}
282+ className={cn(
283+ "w-full justify-start gap-2 pr-7 font-normal",
284+ count > 0 && "font-semibold text-gold",
285+ )}
296286 >
297- <Trash2 />
287+ {icon}
288+ <span className="flex-1 truncate text-left">{c.name}</span>
289+ {count > 0 && (
290+ <span className="shrink-0 rounded-full bg-gold px-1.5 text-xs leading-5 text-bg">
291+ {count}
292+ </span>
293+ )}
298294 </Button>
299- )}
300- </div>
301- ))}
295+ {onClose && (
296+ <Button
297+ variant="ghost"
298+ size="icon-xs"
299+ onClick={() => onClose(c)}
300+ title="close dm"
301+ className="absolute top-1/2 right-1 -translate-y-1/2 opacity-0 group-hover/dm:opacity-100"
302+ >
303+ <X />
304+ </Button>
305+ )}
306+ {onDelete && !c.permanent && (
307+ <Button
308+ variant="ghost"
309+ size="icon-xs"
310+ onClick={() => onDelete(c)}
311+ title="delete channel"
312+ className="absolute top-1/2 right-1 -translate-y-1/2 opacity-0 group-hover/dm:opacity-100"
313+ >
314+ <Trash2 />
315+ </Button>
316+ )}
317+ </div>
318+ );
319+ })}
302320 </div>
303321 );
304322 }
web/src/lib/types.ts+1−0
@@ -15,6 +15,7 @@ export interface Channel {
1515 name: string;
1616 position: number;
1717 permanent: boolean;
18+ unread?: number;
1819 }
1920
2021 export type Reaction = "+1" | "-1" | "heart" | "laugh";
web/src/views/Chat.tsx+31−0
@@ -30,6 +30,7 @@ export default function Chat({ user, onLogout }: { user: User; onLogout: () => v
3030 const [users, setUsers] = useState<UserSummary[]>([]);
3131 const [online, setOnline] = useState<Set<string>>(new Set());
3232 const [messages, setMessages] = useState<Message[]>([]);
33+ const [unread, setUnread] = useState<Record<number, number>>({});
3334 const [settingsOpen, setSettingsOpen] = useState(false);
3435 const [openShare, setOpenShare] = useState<string | null>(null);
3536 const desktop = useRef(window.matchMedia("(min-width: 768px)").matches);
@@ -61,6 +62,11 @@ export default function Chat({ user, onLogout }: { user: User; onLogout: () => v
6162 }
6263 return cs;
6364 });
65+ if (ev.message.channelId === selectedId.current) {
66+ markRead(ev.message.channelId);
67+ } else if (ev.message.username !== user.username) {
68+ setUnread((u) => ({ ...u, [ev.message!.channelId]: (u[ev.message!.channelId] ?? 0) + 1 }));
69+ }
6470 }
6571 if (ev.message.channelId === selectedId.current) {
6672 if (ev.type === "message") {
@@ -108,6 +114,9 @@ export default function Chat({ user, onLogout }: { user: User; onLogout: () => v
108114 api<Channel[]>("/channels")
109115 .then((cs) => {
110116 setChannels(cs);
117+ setUnread(
118+ Object.fromEntries(cs.filter((c) => c.unread).map((c) => [c.id, c.unread as number])),
119+ );
111120 setSelected(cs.find((c) => c.type === "text") ?? cs[0] ?? null);
112121 })
113122 .catch(() => {});
@@ -126,6 +135,27 @@ export default function Chat({ user, onLogout }: { user: User; onLogout: () => v
126135 .catch(() => {});
127136 }, [selected]);
128137
138+ // Opening a channel clears its unread badge and tells the server, so the
139+ // count stays right on the next cold start and on the user's other devices.
140+ useEffect(() => {
141+ if (selected && (selected.type === "text" || selected.type === "dm")) markRead(selected.id);
142+ }, [selected]);
143+
144+ const totalUnread = Object.values(unread).reduce((a, b) => a + b, 0);
145+ useEffect(() => {
146+ document.title = totalUnread > 0 ? `(${totalUnread}) irvc` : "irvc";
147+ }, [totalUnread]);
148+
149+ function markRead(id: number) {
150+ setUnread((u) => {
151+ if (!u[id]) return u;
152+ const next = { ...u };
153+ delete next[id];
154+ return next;
155+ });
156+ api(`/channels/${id}/read`, { method: "POST" }).catch(() => {});
157+ }
158+
129159 async function selectUser(u: UserSummary) {
130160 try {
131161 const dm = await api<Channel>(`/dms/${u.id}`, { method: "POST" });
@@ -178,6 +208,7 @@ export default function Chat({ user, onLogout }: { user: User; onLogout: () => v
178208 {sidebarOpen && (
179209 <Sidebar
180210 channels={channels.filter((c) => c.type !== "dm" || !hiddenDms.includes(c.id))}
211+ unread={unread}
181212 selected={selected}
182213 onSelect={selectChannel}
183214 onCloseDM={closeDM}