xonecas.io
8058
Ir

irvc / commit 3ef5554

feat: adds lazy pagination

xonecas2026-10-24 3ef5554dbc02bdefdc29c2bbf4f086750a9bf40d parent a4f740b

5 files changed

channels.go+19−3
@@ -3,6 +3,7 @@ package main
33 import (
44 "database/sql"
55 "fmt"
6+ "math"
67 "net/http"
78 "strconv"
89 "strings"
@@ -312,6 +313,11 @@ func (s *Server) checkTextOrDM(c *gin.Context, channelID, userID int64) (string,
312313 return chType, chName, true
313314 }
314315
316+// messagePage is how many messages a page of history holds.
317+const messagePage = 100
318+
319+// handleMessages returns a page of history, newest page by default. ?before=<id>
320+// asks for the page just older than that message.
315321 func (s *Server) handleMessages(c *gin.Context) {
316322 channelID, err := strconv.ParseInt(c.Param("id"), 10, 64)
317323 if err != nil {
@@ -322,11 +328,16 @@ func (s *Server) handleMessages(c *gin.Context) {
322328 if _, _, ok := s.checkTextOrDM(c, channelID, user.ID); !ok {
323329 return
324330 }
331+ // Without a cursor, anything above every id: the newest page.
332+ before, _ := strconv.ParseInt(c.Query("before"), 10, 64)
333+ if before <= 0 {
334+ before = math.MaxInt64
335+ }
325336 rows, err := s.db.Query(
326337 `SELECT m.id, m.channel_id, m.user_id, u.username, m.body, m.created_at, COALESCE(m.edited_at, 0), m.preview
327338 FROM messages m JOIN users u ON u.id = m.user_id
328- WHERE m.channel_id = ? ORDER BY m.id DESC LIMIT 200`,
329- channelID,
339+ WHERE m.channel_id = ? AND m.id < ? ORDER BY m.id DESC LIMIT ?`,
340+ channelID, before, messagePage+1,
330341 )
331342 if err != nil {
332343 c.JSON(http.StatusInternalServerError, gin.H{"error": "db"})
@@ -344,6 +355,11 @@ func (s *Server) handleMessages(c *gin.Context) {
344355 m.Preview = decodePreview(preview.String)
345356 messages = append(messages, m)
346357 }
358+ // The extra row only says whether another page exists.
359+ hasMore := len(messages) > messagePage
360+ if hasMore {
361+ messages = messages[:messagePage]
362+ }
347363 // reverse to chronological order
348364 for i, j := 0, len(messages)-1; i < j; i, j = i+1, j-1 {
349365 messages[i], messages[j] = messages[j], messages[i]
@@ -376,7 +392,7 @@ func (s *Server) handleMessages(c *gin.Context) {
376392 }
377393 }
378394 }
379- c.JSON(http.StatusOK, messages)
395+ c.JSON(http.StatusOK, gin.H{"messages": messages, "hasMore": hasMore})
380396 }
381397
382398 func (s *Server) messageReactions(msgID int64) map[string][]string {
irvc.md+1−0
@@ -76,6 +76,7 @@ read_state (user_id, channel_id, last_read_message_id, updated_at)
7676
7777 - **Channels:** seeded (`#general` text, `general` voice, both permanent) plus on-demand 1-on-1 DMs opened by clicking a user. Text and voice channels can be created and deleted from the sidebar; permanent channels cannot be deleted, and a voice channel cannot be deleted while someone is in it. Ordered by `position`.
7878 - **Text:** GFM markdown; single newlines are hard breaks. Messages persist; live append over WS. Rendered as timestamp, author, content.
79+- **History:** a channel opens on its newest 100 messages. Reaching the top shows a "load 100 more" button and nothing loads by itself; a loaded page keeps the reader looking at the same messages.
7980 - **Mentions:** `@username` highlights the message for that user; typing `@` opens an autocomplete.
8081 - **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.
8182 - **Commands:** `/me <action>` renders an emote as `* user action`; `/collapse` hides media in the current channel; `/gif [query]` opens a picker with the top Giphy results (trending when no query) to insert one. The gif picker is disabled without `IRVC_GIPHY_API_KEY`.
web/src/components/MessageList.tsx+44−3
@@ -1,7 +1,7 @@
11 import { Fragment, useEffect, useLayoutEffect, useRef } from "react";
22 import { Heart, Laugh, MoreHorizontal, ThumbsDown, ThumbsUp } from "lucide-react";
33 import { cn } from "cn";
4-import { IconButton, TextArea } from "@/ui";
4+import { Button, IconButton, TextArea } from "@/ui";
55 import type { Message, Reaction } from "../lib/types";
66 import { Time, dayKey, formatDay } from "../lib/time";
77 import LinkPreview from "./LinkPreview";
@@ -22,6 +22,8 @@ export function isMentioned(body: string, username: string) {
2222
2323 export default function MessageList({
2424 messages,
25+ hasMore,
26+ loadingOlder,
2527 username,
2628 collapsed,
2729 previewCollapsed,
@@ -29,6 +31,7 @@ export default function MessageList({
2931 editing,
3032 activeId,
3133 onSelect,
34+ onLoadOlder,
3235 onToggleImages,
3336 onTogglePreview,
3437 onRemovePreview,
@@ -37,6 +40,8 @@ export default function MessageList({
3740 onSaveEdit,
3841 }: {
3942 messages: Message[];
43+ hasMore: boolean;
44+ loadingOlder: boolean;
4045 username: string;
4146 collapsed: Set<number>;
4247 previewCollapsed: (id: number) => boolean;
@@ -44,6 +49,7 @@ export default function MessageList({
4449 editing: { id: number; body: string } | null;
4550 activeId: number | null;
4651 onSelect: (msg: Message) => void;
52+ onLoadOlder: () => void;
4753 onToggleImages: (id: number) => void;
4854 onTogglePreview: (id: number) => void;
4955 onRemovePreview: (msg: Message) => void;
@@ -57,17 +63,44 @@ export default function MessageList({
5763 // scroll event that is handled only after a lazy image grows the list, so
5864 // the gap to the bottom reads large even though the reader never scrolled.
5965 const pinned = useRef(0);
66+ // How far the reader sits from the bottom. Older messages land above the
67+ // reader, so this is the one thing a prepend must leave untouched.
68+ const gap = useRef(0);
69+
70+ const measure = () => {
71+ const el = list.current;
72+ if (el) gap.current = el.scrollHeight - el.clientHeight - el.scrollTop;
73+ };
6074
6175 const pin = () => {
6276 const el = list.current;
6377 if (!el || !stick.current) return;
6478 el.scrollTop = el.scrollHeight;
6579 pinned.current = el.scrollTop;
80+ measure();
6681 };
6782
68- // Follow new messages while the reader stays at the bottom. The channel is
83+ // Follow new messages while the reader stays at the bottom, and hold the
84+ // reader's place when a page of older messages lands above. The channel is
6985 // remounted on switch, so this also lands on the newest message.
70- useLayoutEffect(pin);
86+ const head = useRef(messages[0]?.id);
87+ useLayoutEffect(() => {
88+ const el = list.current;
89+ if (!el) return;
90+ const id = messages[0]?.id;
91+ // A prepend lowers the first id and keeps the old one in the list.
92+ const older =
93+ id !== undefined &&
94+ head.current !== undefined &&
95+ id < head.current &&
96+ messages.some((m) => m.id === head.current);
97+ if (older) {
98+ el.scrollTop = el.scrollHeight - el.clientHeight - gap.current;
99+ pinned.current = el.scrollTop;
100+ } else pin();
101+ head.current = id;
102+ measure();
103+ });
71104
72105 useEffect(() => {
73106 const el = list.current;
@@ -79,6 +112,7 @@ export default function MessageList({
79112 // A scroll still sitting where we pinned is ours, so leave stick alone.
80113 if (el.scrollTop === pinned.current) return;
81114 stick.current = el.scrollTop + el.clientHeight >= el.scrollHeight - 2;
115+ measure();
82116 };
83117 el.addEventListener("scroll", onScroll, { passive: true });
84118 return () => {
@@ -93,6 +127,13 @@ export default function MessageList({
93127 className="min-h-0 flex-1 overflow-y-auto overscroll-contain py-2 [scrollbar-gutter:stable]"
94128 >
95129 <div>
130+ {hasMore && (
131+ <div className="flex justify-center px-3 py-2">
132+ <Button size="sm" disabled={loadingOlder} onClick={onLoadOlder}>
133+ {loadingOlder ? "loading…" : "load 100 more"}
134+ </Button>
135+ </div>
136+ )}
96137 {messages.map((m, i) => {
97138 const prev = messages[i - 1];
98139 const action = m.body.startsWith("/me ") ? m.body.slice(4) : null;
web/src/lib/types.ts+5−0
@@ -41,6 +41,11 @@ export interface Message {
4141 preview?: Preview;
4242 }
4343
44+export interface MessagePage {
45+ messages: Message[];
46+ hasMore: boolean;
47+}
48+
4449 export interface Gif {
4550 url: string;
4651 preview: string;
web/src/views/Chat.tsx+42−3
@@ -9,7 +9,7 @@ import { useSettings } from "../lib/settings";
99 import { useTheme } from "../lib/theme";
1010 import { toast } from "../lib/toast";
1111 import { beep, useVoice, type VoiceState } from "../lib/voice";
12-import type { Channel, Message, Reaction, User, UserSummary, VoiceOccupant } from "../lib/types";
12+import type { Channel, Message, MessagePage, Reaction, User, UserSummary, VoiceOccupant } from "../lib/types";
1313 import CallView from "../components/CallView";
1414 import Composer from "../components/Composer";
1515 import MessageActions from "../components/MessageActions";
@@ -92,6 +92,8 @@ export default function Chat({ user, onLogout }: { user: User; onLogout: () => v
9292 const [users, setUsers] = useState<UserSummary[]>([]);
9393 const [online, setOnline] = useState<Set<string>>(new Set());
9494 const [messages, setMessages] = useState<Message[]>([]);
95+ const [hasMore, setHasMore] = useState(false);
96+ const [loadingOlder, setLoadingOlder] = useState(false);
9597 const [unread, setUnread] = useState<Record<number, number>>({});
9698 const [collapsed, setCollapsed] = useState<Set<number>>(loadCollapsed);
9799 const [previewState, setPreviewState] = useState<Record<number, boolean>>(loadPreviewState);
@@ -104,6 +106,8 @@ export default function Chat({ user, onLogout }: { user: User; onLogout: () => v
104106 const desktop = useRef(matchMedia("(min-width: 768px)").matches);
105107 const [sidebarOpen, setSidebarOpen] = useState(desktop.current);
106108 const selectedId = useRef<number | null>(null);
109+ // The channel the messages in state came from.
110+ const loaded = useRef<number | null>(null);
107111 // The channel of the DM call we started, so we can tell the peer when it ends.
108112 const rangRef = useRef<number | null>(null);
109113 // The server drops our voice state when the socket dies, so keep the last
@@ -338,13 +342,45 @@ export default function Chat({ user, onLogout }: { user: User; onLogout: () => v
338342 useEffect(() => {
339343 if (selected?.type !== "text" && selected?.type !== "dm") {
340344 setMessages([]);
345+ setHasMore(false);
341346 return;
342347 }
343- api<Message[]>(`/channels/${selected.id}/messages`)
344- .then(setMessages)
348+ const id = selected.id;
349+ // The channel the loaded messages belong to, so a click on the hint can
350+ // never page a channel that is not on screen.
351+ loaded.current = null;
352+ setHasMore(false);
353+ setLoadingOlder(false);
354+ api<MessagePage>(`/channels/${id}/messages`)
355+ .then((page) => {
356+ if (selectedId.current !== id) return;
357+ loaded.current = id;
358+ setMessages(page.messages);
359+ setHasMore(page.hasMore);
360+ })
345361 .catch(() => {});
346362 }, [selected]);
347363
364+ // loadOlder appends the page above the first loaded message. It only runs
365+ // when the reader asks for it, so a slow channel costs nothing to scroll.
366+ async function loadOlder() {
367+ const id = selected?.id;
368+ const before = messages[0]?.id;
369+ if (id === undefined || before === undefined || loaded.current !== id || loadingOlder || !hasMore)
370+ return;
371+ setLoadingOlder(true);
372+ try {
373+ const page = await api<MessagePage>(`/channels/${id}/messages?before=${before}`);
374+ if (selectedId.current !== id) return;
375+ setMessages((prev) => [...page.messages, ...prev]);
376+ setHasMore(page.hasMore);
377+ } catch {
378+ // The hint stays put, so the reader can try again.
379+ } finally {
380+ if (selectedId.current === id) setLoadingOlder(false);
381+ }
382+ }
383+
348384 // Opening a channel clears its badge and tells the server, so the count stays
349385 // right on the next cold start and on the user's other devices.
350386 useEffect(() => {
@@ -617,6 +653,8 @@ export default function Chat({ user, onLogout }: { user: User; onLogout: () => v
617653 <MessageList
618654 key={selected.id}
619655 messages={messages}
656+ hasMore={hasMore}
657+ loadingOlder={loadingOlder}
620658 username={user.username}
621659 collapsed={collapsed}
622660 previewCollapsed={previewCollapsed}
@@ -626,6 +664,7 @@ export default function Chat({ user, onLogout }: { user: User; onLogout: () => v
626664 editing={editing}
627665 activeId={active?.id ?? null}
628666 onSelect={(m) => setActive((a) => (a?.id === m.id ? null : m))}
667+ onLoadOlder={loadOlder}
629668 onToggleImages={toggleImages}
630669 onEditBody={(body) => setEditing((e) => (e ? { ...e, body } : e))}
631670 onCancelEdit={() => setEditing(null)}