xonecas.io
8058
Ir

irvc / commit 68d7913

feat: edit/remove own messages.

xonecas2026-10-15 68d7913dfff61368afed802f0132f569987447af parent 0fbc2cb

8 files changed

channels.go+64−2
@@ -36,7 +36,7 @@ func (s *Server) handleMessages(c *gin.Context) {
3636 return
3737 }
3838 rows, err := s.db.Query(
39- `SELECT m.id, m.channel_id, m.user_id, u.username, m.body, m.created_at
39+ `SELECT m.id, m.channel_id, m.user_id, u.username, m.body, m.created_at, COALESCE(m.edited_at, 0)
4040 FROM messages m JOIN users u ON u.id = m.user_id
4141 WHERE m.channel_id = ? ORDER BY m.id DESC LIMIT 200`,
4242 channelID,
@@ -49,7 +49,7 @@ func (s *Server) handleMessages(c *gin.Context) {
4949 messages := []Message{}
5050 for rows.Next() {
5151 var m Message
52- if err := rows.Scan(&m.ID, &m.ChannelID, &m.UserID, &m.Username, &m.Body, &m.CreatedAt); err != nil {
52+ if err := rows.Scan(&m.ID, &m.ChannelID, &m.UserID, &m.Username, &m.Body, &m.CreatedAt, &m.EditedAt); err != nil {
5353 c.JSON(http.StatusInternalServerError, gin.H{"error": "db"})
5454 return
5555 }
@@ -110,3 +110,65 @@ func (s *Server) handleSendMessage(c *gin.Context) {
110110 s.hub.broadcast(event{Type: "message", Message: &msg})
111111 c.JSON(http.StatusOK, msg)
112112 }
113+
114+func (s *Server) handleEditMessage(c *gin.Context) {
115+ msgID, err := strconv.ParseInt(c.Param("id"), 10, 64)
116+ if err != nil {
117+ c.JSON(http.StatusBadRequest, gin.H{"error": "bad message"})
118+ return
119+ }
120+ var req sendMessageRequest
121+ if err := c.ShouldBindJSON(&req); err != nil {
122+ c.JSON(http.StatusBadRequest, gin.H{"error": "invalid request"})
123+ return
124+ }
125+ body := strings.TrimSpace(req.Body)
126+ if body == "" || len(body) > maxMessageLen {
127+ c.JSON(http.StatusBadRequest, gin.H{"error": "invalid message"})
128+ return
129+ }
130+ user := c.MustGet("user").(User)
131+ now := time.Now().Unix()
132+ var m Message
133+ err = s.db.QueryRow(
134+ `UPDATE messages SET body = ?, edited_at = ?
135+ WHERE id = ? AND user_id = ?
136+ RETURNING id, channel_id, user_id, body, created_at, edited_at`,
137+ body, now, msgID, user.ID,
138+ ).Scan(&m.ID, &m.ChannelID, &m.UserID, &m.Body, &m.CreatedAt, &m.EditedAt)
139+ if err != nil {
140+ if err == sql.ErrNoRows {
141+ c.JSON(http.StatusNotFound, gin.H{"error": "message not found"})
142+ return
143+ }
144+ c.JSON(http.StatusInternalServerError, gin.H{"error": "db"})
145+ return
146+ }
147+ m.Username = user.Username
148+ s.hub.broadcast(event{Type: "message_edit", Message: &m})
149+ c.JSON(http.StatusOK, m)
150+}
151+
152+func (s *Server) handleDeleteMessage(c *gin.Context) {
153+ msgID, err := strconv.ParseInt(c.Param("id"), 10, 64)
154+ if err != nil {
155+ c.JSON(http.StatusBadRequest, gin.H{"error": "bad message"})
156+ return
157+ }
158+ user := c.MustGet("user").(User)
159+ var m Message
160+ err = s.db.QueryRow(
161+ `DELETE FROM messages WHERE id = ? AND user_id = ? RETURNING id, channel_id`,
162+ msgID, user.ID,
163+ ).Scan(&m.ID, &m.ChannelID)
164+ if err != nil {
165+ if err == sql.ErrNoRows {
166+ c.JSON(http.StatusNotFound, gin.H{"error": "message not found"})
167+ return
168+ }
169+ c.JSON(http.StatusInternalServerError, gin.H{"error": "db"})
170+ return
171+ }
172+ s.hub.broadcast(event{Type: "message_delete", Message: &m})
173+ c.Status(http.StatusNoContent)
174+}
db.go+4−1
@@ -29,6 +29,7 @@ type Message struct {
2929 Username string `json:"username"`
3030 Body string `json:"body"`
3131 CreatedAt int64 `json:"createdAt"`
32+ EditedAt int64 `json:"editedAt,omitempty"`
3233 }
3334
3435 func OpenDB(path string) *sql.DB {
@@ -75,7 +76,8 @@ CREATE TABLE IF NOT EXISTS messages (
7576 channel_id INTEGER NOT NULL,
7677 user_id INTEGER NOT NULL,
7778 body TEXT NOT NULL,
78- created_at INTEGER NOT NULL
79+ created_at INTEGER NOT NULL,
80+ edited_at INTEGER
7981 );
8082 CREATE INDEX IF NOT EXISTS idx_messages_channel ON messages(channel_id, id);
8183 `
@@ -84,6 +86,7 @@ func migrate(db *sql.DB) {
8486 if _, err := db.Exec(schema); err != nil {
8587 log.Fatalf("migrate: %v", err)
8688 }
89+ db.Exec(`ALTER TABLE messages ADD COLUMN edited_at INTEGER`)
8790 var n int
8891 if err := db.QueryRow(`SELECT COUNT(*) FROM channels`).Scan(&n); err != nil {
8992 log.Fatalf("count channels: %v", err)
irvc.md+3−3
@@ -10,7 +10,7 @@ Small, private chat + voice for 4–6 people on one VPS. No data gathering, full
1010
1111 **In:**
1212 - Server-side accounts, invite-only.
13-- Text channels with persisted history (IRC-like), GFM markdown, multiline compose, mentions.
13+- Text channels with persisted history (IRC-like), GFM markdown, multiline compose, mentions, message editing and deletion.
1414 - Image attachments (raster only), stored on disk.
1515 - Voice channels, ephemeral (not recorded), with mute, deafen, per-peer volume, mic processing, a level-based noise gate, and a join/leave tone.
1616 - Screen sharing into a voice channel, with tab/system audio, simulcast, and a 720p/1080p quality choice.
@@ -21,7 +21,7 @@ Small, private chat + voice for 4–6 people on one VPS. No data gathering, full
2121 **Out (now):**
2222 - Large scale, multi-node, clustering.
2323 - Recording, video, DMs.
24-- Message editing/deletion/search, channel CRUD.
24+- Message search, channel CRUD.
2525 - Email, OAuth, passkeys.
2626 - Backups.
2727 - Password reset via email (admin resets manually).
@@ -59,7 +59,7 @@ users (id, username, pass_hash, created_at)
5959 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
62-messages (id, channel_id, user_id, body, created_at)
62+messages (id, channel_id, user_id, body, created_at, edited_at)
6363 ```
6464
6565 - Messages are returned joined with their author's username.
main.go+2−0
@@ -134,6 +134,8 @@ func runServer(cfg *Config, db *sql.DB) {
134134 authed.GET("/channels", s.handleChannels)
135135 authed.GET("/channels/:id/messages", s.handleMessages)
136136 authed.POST("/channels/:id/messages", s.handleSendMessage)
137+ authed.PATCH("/messages/:id", s.handleEditMessage)
138+ authed.DELETE("/messages/:id", s.handleDeleteMessage)
137139 authed.POST("/channels/:id/voice", s.handleVoiceToken)
138140 authed.POST("/invites", s.handleCreateInvite)
139141 authed.POST("/upload", s.handleUpload)
web/src/components/ChatPane.tsx+78−3
@@ -8,7 +8,7 @@ import {
88 type FormEvent,
99 type KeyboardEvent,
1010 } from "react";
11-import { Paperclip, SendHorizontal } from "lucide-react";
11+import { Paperclip, Pencil, SendHorizontal, Trash2 } from "lucide-react";
1212 import { Button } from "@/components/ui/button";
1313 import { cn } from "cn";
1414 import { api, upload } from "../lib/api";
@@ -49,6 +49,8 @@ export default function ChatPane({
4949 username: string;
5050 }) {
5151 const [body, setBody] = useState("");
52+ const [editingId, setEditingId] = useState<number | null>(null);
53+ const [editBody, setEditBody] = useState("");
5254 const [collapsed, setCollapsed] = useState<Set<number>>(new Set());
5355 const [mention, setMention] = useState<{ query: string; start: number; index: number } | null>(
5456 null,
@@ -66,6 +68,7 @@ export default function ChatPane({
6668
6769 // Jump to the latest messages on channel switch, regardless of prior position.
6870 useLayoutEffect(() => {
71+ setEditingId(null);
6972 stickRef.current = true;
7073 scrollToBottom();
7174 }, [channel?.id, scrollToBottom]);
@@ -197,6 +200,25 @@ export default function ChatPane({
197200 setCollapsed(new Set(messages.filter((m) => hasImage(m.body)).map((m) => m.id)));
198201 }
199202
203+ function startEdit(m: Message) {
204+ setEditingId(m.id);
205+ setEditBody(m.body);
206+ }
207+
208+ async function saveEdit(id: number) {
209+ const text = editBody.trim();
210+ setEditingId(null);
211+ if (!text) return;
212+ await api(`/messages/${id}`, {
213+ method: "PATCH",
214+ body: JSON.stringify({ body: text }),
215+ }).catch(() => {});
216+ }
217+
218+ async function remove(id: number) {
219+ await api(`/messages/${id}`, { method: "DELETE" }).catch(() => {});
220+ }
221+
200222 async function send() {
201223 const text = body.trim();
202224 if (!text || !channel) return;
@@ -245,6 +267,14 @@ export default function ChatPane({
245267 return;
246268 }
247269 }
270+ if (e.key === "ArrowUp" && !body) {
271+ const last = [...messages].reverse().find((m) => m.username === username);
272+ if (last) {
273+ e.preventDefault();
274+ startEdit(last);
275+ }
276+ return;
277+ }
248278 if (e.key === "Enter" && !e.shiftKey && !e.nativeEvent.isComposing) {
249279 e.preventDefault();
250280 send();
@@ -262,11 +292,13 @@ export default function ChatPane({
262292 {messages.map((m) => {
263293 const action = m.body.startsWith("/me ") ? m.body.slice(4) : null;
264294 const hit = !action && isMentioned(m.body, username);
295+ const own = m.username === username;
296+ const editing = editingId === m.id;
265297 return (
266298 <div
267299 key={m.id}
268300 className={cn(
269- "-mx-1.5 flex gap-1.5 rounded px-1.5 py-0.5 text-sm leading-6",
301+ "group -mx-1.5 flex items-start gap-1.5 rounded px-1.5 py-0.5 text-sm leading-6 hover:bg-sepia/5",
270302 hit && "bg-[color-mix(in_srgb,var(--gold)_14%,transparent)]",
271303 )}
272304 >
@@ -274,9 +306,29 @@ export default function ChatPane({
274306 <span className="text-sepia/40">{clock(m.createdAt)}</span>{" "}
275307 {!action && <span className="text-gold/90">{m.username}</span>}
276308 </span>
277- {action ? (
309+ {editing ? (
310+ <textarea
311+ autoFocus
312+ rows={Math.min(editBody.split("\n").length, 8)}
313+ value={editBody}
314+ onChange={(e) => setEditBody(e.target.value)}
315+ onKeyDown={(e) => {
316+ if (e.key === "Escape") {
317+ e.preventDefault();
318+ setEditingId(null);
319+ } else if (e.key === "Enter" && !e.shiftKey && !e.nativeEvent.isComposing) {
320+ e.preventDefault();
321+ saveEdit(m.id);
322+ }
323+ }}
324+ 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"
325+ />
326+ ) : action ? (
278327 <div className="min-w-0 flex-1 break-words italic text-gold/90">
279328 * {m.username} {action}
329+ {m.editedAt ? (
330+ <span className="ml-1 not-italic text-xs text-sepia/40">(edited)</span>
331+ ) : null}
280332 </div>
281333 ) : (
282334 <div className={bodyClass}>
@@ -285,6 +337,29 @@ export default function ChatPane({
285337 collapsed={collapsed.has(m.id)}
286338 onToggle={() => toggleImage(m.id)}
287339 />
340+ {m.editedAt ? <span className="text-xs text-sepia/40">(edited)</span> : null}
341+ </div>
342+ )}
343+ {own && !editing && (
344+ <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>
288363 </div>
289364 )}
290365 </div>
web/src/components/Dot.tsx+5−1
@@ -2,5 +2,9 @@ import { cn } from "cn";
22
33 // Dim until active (speaking / online), then lights up.
44 export default function Dot({ on }: { on: boolean }) {
5- return <span className={cn("h-2 w-2 rounded-full transition-colors", on ? "bg-gold" : "bg-sepia/25")} />;
5+ return (
6+ <span
7+ className={cn("h-2 w-2 rounded-full transition-colors", on ? "bg-gold" : "bg-sepia/25")}
8+ />
9+ );
610 }
web/src/lib/types.ts+2−1
@@ -23,10 +23,11 @@ export interface Message {
2323 username: string;
2424 body: string;
2525 createdAt: number;
26+ editedAt?: number;
2627 }
2728
2829 export interface WSEvent {
29- type: "message" | "presence" | "pong";
30+ type: "message" | "message_edit" | "message_delete" | "presence" | "pong";
3031 message?: Message;
3132 users?: string[];
3233 roster?: UserSummary[];
web/src/views/Chat.tsx+7−1
@@ -38,7 +38,13 @@ export default function Chat({ user, onLogout }: { user: User; onLogout: () => v
3838 if (ev.roster) setUsers(ev.roster);
3939 setVoiceRooms(ev.voice ?? {});
4040 } else if (ev.message && ev.message.channelId === selectedId.current) {
41- setMessages((prev) => [...prev, ev.message!]);
41+ if (ev.type === "message") {
42+ setMessages((prev) => [...prev, ev.message!]);
43+ } else if (ev.type === "message_edit") {
44+ setMessages((prev) => prev.map((m) => (m.id === ev.message!.id ? ev.message! : m)));
45+ } else if (ev.type === "message_delete") {
46+ setMessages((prev) => prev.filter((m) => m.id !== ev.message!.id));
47+ }
4248 }
4349 },
4450 () => send(voiceMessage(voiceChannel.current)),