feat(phase5): docs channels - CRUD, wiki sidebar, markdown editor

This commit is contained in:
2026-06-30 11:19:32 -04:00
parent e65ce54e36
commit dbebc1f381
10 changed files with 368 additions and 8 deletions
+1 -1
View File
@@ -134,7 +134,7 @@
| # | Feature | Status |
|---|---------|--------|
| 5.1 | Calendar Channels | In progress |
| 5.1 | Calendar Channels | ✅ Events, RSVPs, month grid |
| 5.2 | Docs Channels | Pending |
| 5.3 | Lists Channels | Pending |
| 5.4 | Scheduling / Availability | Pending |
+206
View File
@@ -0,0 +1,206 @@
package channel
import (
"context"
"encoding/json"
"net/http"
"time"
"git.dustin.coffee/hobokenchicken/dumpsterChat/internal/middleware"
"github.com/go-chi/chi/v5"
)
type document struct {
ID string `json:"id"`
ChannelID string `json:"channel_id"`
CreatorID string `json:"creator_id"`
Title string `json:"title"`
Content string `json:"content"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
}
type createDocRequest struct {
Title string `json:"title"`
Content string `json:"content"`
}
// ponytail: no version history, no lock/unlock. Add when concurrent editing arises.
func (h *Handler) registerDocRoutes(r chi.Router) {
r.Get("/{channelID}/docs", h.ListDocs)
r.Post("/{channelID}/docs", h.CreateDoc)
r.Get("/docs/{docID}", h.GetDoc)
r.Patch("/docs/{docID}", h.UpdateDoc)
r.Delete("/docs/{docID}", h.DeleteDoc)
}
func (h *Handler) ListDocs(w http.ResponseWriter, r *http.Request) {
channelID := chi.URLParam(r, "channelID")
userID, _ := middleware.UserIDFromContext(r.Context())
allowed := h.checkAccess(r.Context(), w, channelID, userID)
if !allowed {
return
}
rows, err := h.db.QueryContext(r.Context(), `
SELECT id, channel_id, creator_id, title, created_at, updated_at
FROM documents WHERE channel_id = $1
ORDER BY updated_at DESC
`, channelID)
if err != nil {
http.Error(w, `{"error":"server error"}`, http.StatusInternalServerError)
return
}
defer rows.Close()
// ponytail: list returns title-only summary, not full content
type docSummary struct {
ID string `json:"id"`
ChannelID string `json:"channel_id"`
CreatorID string `json:"creator_id"`
Title string `json:"title"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
}
docs := make([]docSummary, 0)
for rows.Next() {
var d docSummary
if err := rows.Scan(&d.ID, &d.ChannelID, &d.CreatorID, &d.Title, &d.CreatedAt, &d.UpdatedAt); err != nil {
continue
}
docs = append(docs, d)
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(docs)
}
func (h *Handler) CreateDoc(w http.ResponseWriter, r *http.Request) {
channelID := chi.URLParam(r, "channelID")
userID, _ := middleware.UserIDFromContext(r.Context())
allowed := h.checkAccess(r.Context(), w, channelID, userID)
if !allowed {
return
}
var req createDocRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil || req.Title == "" {
http.Error(w, `{"error":"title required"}`, http.StatusBadRequest)
return
}
var d document
err := h.db.QueryRowContext(r.Context(), `
INSERT INTO documents (channel_id, creator_id, title, content)
VALUES ($1, $2, $3, $4)
RETURNING id, channel_id, creator_id, title, content, created_at, updated_at
`, channelID, userID, req.Title, req.Content).Scan(
&d.ID, &d.ChannelID, &d.CreatorID, &d.Title, &d.Content, &d.CreatedAt, &d.UpdatedAt,
)
if err != nil {
http.Error(w, `{"error":"failed to create doc"}`, http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(d)
}
func (h *Handler) GetDoc(w http.ResponseWriter, r *http.Request) {
docID := chi.URLParam(r, "docID")
// ponytail: check channel access via doc lookup
var channelID, creatorID, title, content, createdAt, updatedAt string
err := h.db.QueryRowContext(r.Context(), `
SELECT id, channel_id, creator_id, title, content, created_at, updated_at
FROM documents WHERE id = $1
`, docID).Scan(&docID, &channelID, &creatorID, &title, &content, &createdAt, &updatedAt)
if err != nil {
http.Error(w, `{"error":"doc not found"}`, http.StatusNotFound)
return
}
userID, _ := middleware.UserIDFromContext(r.Context())
allowed := h.checkAccess(r.Context(), w, channelID, userID)
if !allowed {
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(document{
ID: docID, ChannelID: channelID, CreatorID: creatorID,
Title: title, Content: content, CreatedAt: createdAt, UpdatedAt: updatedAt,
})
}
func (h *Handler) UpdateDoc(w http.ResponseWriter, r *http.Request) {
docID := chi.URLParam(r, "docID")
userID, _ := middleware.UserIDFromContext(r.Context())
// get channel_id first for access check
var channelID, creatorID string
err := h.db.QueryRowContext(r.Context(), `SELECT channel_id, creator_id FROM documents WHERE id = $1`, docID).Scan(&channelID, &creatorID)
if err != nil {
http.Error(w, `{"error":"doc not found"}`, http.StatusNotFound)
return
}
allowed := h.checkAccess(r.Context(), w, channelID, userID)
if !allowed {
return
}
var req createDocRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, `{"error":"invalid request"}`, http.StatusBadRequest)
return
}
var d document
err = h.db.QueryRowContext(r.Context(), `
UPDATE documents SET title = COALESCE(NULLIF($2, ''), title), content = $3, updated_at = $4
WHERE id = $1
RETURNING id, channel_id, creator_id, title, content, created_at, updated_at
`, docID, req.Title, req.Content, time.Now().UTC().Format(time.RFC3339)).Scan(
&d.ID, &d.ChannelID, &d.CreatorID, &d.Title, &d.Content, &d.CreatedAt, &d.UpdatedAt,
)
if err != nil {
http.Error(w, `{"error":"failed to update doc"}`, http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(d)
}
func (h *Handler) DeleteDoc(w http.ResponseWriter, r *http.Request) {
docID := chi.URLParam(r, "docID")
userID, _ := middleware.UserIDFromContext(r.Context())
var channelID, creatorID string
err := h.db.QueryRowContext(r.Context(), `SELECT channel_id, creator_id FROM documents WHERE id = $1`, docID).Scan(&channelID, &creatorID)
if err != nil {
http.Error(w, `{"error":"doc not found"}`, http.StatusNotFound)
return
}
allowed := h.checkAccess(r.Context(), w, channelID, userID)
if !allowed {
return
}
_, err = h.db.ExecContext(r.Context(), `DELETE FROM documents WHERE id = $1`, docID)
if err != nil {
http.Error(w, `{"error":"failed to delete doc"}`, http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusNoContent)
}
// ponytail: shared access check, reuses isMember. No permission fine-tuning.
func (h *Handler) checkAccess(ctx context.Context, w http.ResponseWriter, channelID, userID string) bool {
serverID, err := h.serverIDForChannel(ctx, channelID)
if err != nil {
http.Error(w, `{"error":"channel not found"}`, http.StatusNotFound)
return false
}
ok, _ := h.isMember(ctx, userID, serverID)
if !ok {
http.Error(w, `{"error":"forbidden"}`, http.StatusForbidden)
return false
}
return true
}
+1
View File
@@ -32,6 +32,7 @@ func (h *Handler) RegisterRoutes(r chi.Router) {
r.Patch("/threads/{threadID}", h.UpdateThread)
h.registerForumRoutes(r)
h.registerCalendarRoutes(r)
h.registerDocRoutes(r)
h.registerOverrideRoutes(r)
}
+13
View File
@@ -408,6 +408,19 @@ CREATE TABLE IF NOT EXISTS event_rsvps (
CREATE INDEX IF NOT EXISTS idx_event_rsvps_event ON event_rsvps(event_id);
-- Documents (wiki/docs channels)
CREATE TABLE IF NOT EXISTS documents (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
channel_id UUID NOT NULL REFERENCES channels(id) ON DELETE CASCADE,
creator_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
title VARCHAR(255) NOT NULL,
content TEXT NOT NULL DEFAULT '',
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE INDEX IF NOT EXISTS idx_documents_channel ON documents(channel_id, updated_at DESC);
-- Message full-text search
ALTER TABLE messages ADD COLUMN IF NOT EXISTS search_vector tsvector;
CREATE INDEX IF NOT EXISTS idx_messages_search ON messages USING GIN(search_vector);
+1 -1
View File
@@ -92,7 +92,7 @@ export function ChannelList() {
channel.id === activeChannelId ? 'terminal-active' : 'hover:bg-gb-bg-t text-gb-fg-s'
}`}
>
<span className="text-gb-fg-f">{channel.type === 'forum' ? '■' : channel.type === 'calendar' ? '○' : '#'}</span>
<span className="text-gb-fg-f">{channel.type === 'forum' ? '■' : channel.type === 'calendar' ? '○' : channel.type === 'docs' ? '☰' : '#'}</span>
<span className="truncate flex-1">{channel.name}</span>
<span
onClick={(e) => { e.stopPropagation(); setSettingsChannel({ id: channel.id, name: channel.name }); }}
+5
View File
@@ -11,6 +11,7 @@ import { ThreadListPanel } from "./ThreadListPanel.tsx";
import { ThreadPanel } from "./ThreadPanel.tsx";
import { ForumView } from "./ForumView.tsx";
import { CalendarView } from "./CalendarView.tsx";
import { DocsView } from "./DocsView.tsx";
import { UserProfileModal } from "./UserProfileModal.tsx";
import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";
@@ -248,6 +249,8 @@ export function ChatArea() {
? `${activeChannel.name}`
: activeChannel.type === 'calendar'
? `${activeChannel.name}`
: activeChannel.type === 'docs'
? `${activeChannel.name}`
: `# ${activeChannel.name}`
: activeChannelId
? `#${activeChannelId}`
@@ -326,6 +329,8 @@ export function ChatArea() {
<ForumView channelId={activeChannelId} channelName={activeChannel.name} onOpenThread={(t) => setActiveThread(t)} />
) : activeChannel && activeChannel.type === 'calendar' && activeChannelId ? (
<CalendarView channelId={activeChannelId} channelName={activeChannel.name} />
) : activeChannel && activeChannel.type === 'docs' && activeChannelId ? (
<DocsView channelId={activeChannelId} channelName={activeChannel.name} />
) : (
<>
<div className="flex-1 flex flex-col min-w-0">
+4 -3
View File
@@ -11,7 +11,7 @@ interface ChannelApiResponse {
id: string;
server_id: string;
name: string;
type: 'text' | 'voice' | 'forum' | 'calendar';
type: 'text' | 'voice' | 'forum' | 'calendar' | 'docs';
category: string;
position: number;
slowmode_seconds: number;
@@ -29,7 +29,7 @@ const SLOWMODE_OPTIONS = [
export function CreateChannelModal({ serverId, onClose }: CreateChannelModalProps) {
const [name, setName] = useState('');
const [type, setType] = useState<'text' | 'voice' | 'forum' | 'calendar'>('text');
const [type, setType] = useState<'text' | 'voice' | 'forum' | 'calendar' | 'docs'>('text');
const [category, setCategory] = useState('general');
const [slowmodeSeconds, setSlowmodeSeconds] = useState(0);
const [loading, setLoading] = useState(false);
@@ -107,13 +107,14 @@ export function CreateChannelModal({ serverId, onClose }: CreateChannelModalProp
<label className="text-xs text-gb-fg-f block mb-1">TYPE:</label>
<select
value={type}
onChange={(e) => setType(e.target.value as 'text' | 'voice' | 'forum' | 'calendar')}
onChange={(e) => setType(e.target.value as 'text' | 'voice' | 'forum' | 'calendar' | 'docs')}
className="terminal-input w-full"
>
<option value="text">text</option>
<option value="voice">voice</option>
<option value="forum">forum</option>
<option value="calendar">calendar</option>
<option value="docs">docs</option>
</select>
</div>
<div>
+134
View File
@@ -0,0 +1,134 @@
import { useEffect, useState } from 'react';
import { api } from '../lib/api.ts';
import ReactMarkdown from 'react-markdown';
import remarkGfm from 'remark-gfm';
interface DocSummary {
id: string;
channel_id: string;
creator_id: string;
title: string;
created_at: string;
updated_at: string;
}
interface DocDetail extends DocSummary {
content: string;
}
interface DocsViewProps {
channelId: string;
channelName: string;
}
export function DocsView({ channelId, channelName }: DocsViewProps) {
const [docs, setDocs] = useState<DocSummary[]>([]);
const [activeDoc, setActiveDoc] = useState<DocDetail | null>(null);
const [editing, setEditing] = useState(false);
const [title, setTitle] = useState('');
const [content, setContent] = useState('');
const [loading, setLoading] = useState(false);
const [showNew, setShowNew] = useState(false);
const [newTitle, setNewTitle] = useState('');
useEffect(() => {
setLoading(true);
api.get<DocSummary[]>(`/channels/${channelId}/docs`)
.then((data) => setDocs(Array.isArray(data) ? data : []))
.finally(() => setLoading(false));
}, [channelId]);
const openDoc = async (id: string) => {
const d = await api.get<DocDetail>(`/channels/docs/${id}`);
setActiveDoc(d);
setTitle(d.title);
setContent(d.content);
setEditing(false);
};
const createDoc = async () => {
if (!newTitle.trim()) return;
const d = await api.post<DocDetail>(`/channels/${channelId}/docs`, { title: newTitle, content: '' });
setDocs((prev) => [{ id: d.id, channel_id: d.channel_id, creator_id: d.creator_id, title: d.title, created_at: d.created_at, updated_at: d.updated_at }, ...prev]);
setShowNew(false);
setNewTitle('');
openDoc(d.id);
};
const saveDoc = async () => {
if (!activeDoc) return;
const d = await api.patch<DocDetail>(`/channels/docs/${activeDoc.id}`, { title, content });
setActiveDoc(d);
setDocs((prev) => prev.map((s) => s.id === d.id ? { ...s, title: d.title, updated_at: d.updated_at } : s));
setEditing(false);
};
const deleteDoc = async (id: string) => {
if (!confirm('Delete this doc?')) return;
await api.delete(`/channels/docs/${id}`);
setDocs((prev) => prev.filter((d) => d.id !== id));
if (activeDoc?.id === id) setActiveDoc(null);
};
return (
<div className="flex flex-col h-full bg-gb-bg">
<div className="terminal-border border-t-0 border-x-0 px-3 py-2 text-gb-fg-s flex items-center justify-between">
<span> {channelName}</span>
<button onClick={() => setShowNew((p) => !p)} className="text-xs text-gb-fg-f hover:text-gb-orange font-mono">[NEW DOC]</button>
</div>
{showNew && (
<div className="p-3 border-b border-gb-bg-t font-mono text-xs flex items-center gap-2">
<input value={newTitle} onChange={(e) => setNewTitle(e.target.value)} placeholder="doc title" className="terminal-input flex-1" />
<button onClick={createDoc} disabled={!newTitle.trim()} className="px-2 py-1 bg-gb-orange text-gb-bg disabled:opacity-50">[CREATE]</button>
</div>
)}
<div className="flex flex-1 min-h-0">
<div className="w-48 shrink-0 overflow-y-auto border-r border-gb-bg-t font-mono text-xs">
{loading && <div className="p-2 text-gb-fg-f">[loading...]</div>}
{!loading && docs.length === 0 && <div className="p-2 text-gb-fg-s">[no docs]</div>}
{docs.map((d) => (
<div
key={d.id}
onClick={() => openDoc(d.id)}
className={`p-2 cursor-pointer truncate ${activeDoc?.id === d.id ? 'bg-gb-bg-t text-gb-fg' : 'text-gb-fg-s hover:bg-gb-bg-s'}`}
>
{d.title}
<div className="text-[10px] text-gb-fg-f">updated {new Date(d.updated_at).toLocaleDateString()}</div>
</div>
))}
</div>
<div className="flex-1 flex flex-col min-w-0">
{!activeDoc && (
<div className="flex-1 flex items-center justify-center text-gb-fg-s font-mono text-xs">
select or create a doc
</div>
)}
{activeDoc && !editing && (
<div className="flex-1 overflow-y-auto p-3">
<div className="flex items-center justify-between mb-2">
<h2 className="text-gb-fg font-bold text-sm">{activeDoc.title}</h2>
<div className="flex gap-2 text-xs font-mono">
<button onClick={() => setEditing(true)} className="text-gb-fg-f hover:text-gb-orange">[EDIT]</button>
<button onClick={() => deleteDoc(activeDoc.id)} className="text-gb-red hover:text-gb-orange">[DEL]</button>
</div>
</div>
<div className="text-gb-fg text-sm prose prose-invert max-w-none">
<ReactMarkdown remarkPlugins={[remarkGfm]}>{activeDoc.content || '*empty*'}</ReactMarkdown>
</div>
</div>
)}
{activeDoc && editing && (
<div className="flex-1 flex flex-col p-3 gap-2">
<input value={title} onChange={(e) => setTitle(e.target.value)} className="terminal-input w-full text-sm font-bold" />
<textarea value={content} onChange={(e) => setContent(e.target.value)} className="terminal-input flex-1 font-mono text-xs resize-none" />
<div className="flex gap-2 text-xs font-mono">
<button onClick={saveDoc} className="px-2 py-1 bg-gb-orange text-gb-bg">[SAVE]</button>
<button onClick={() => setEditing(false)} className="text-gb-fg-f hover:text-gb-orange">[CANCEL]</button>
</div>
</div>
)}
</div>
</div>
</div>
);
}
+1 -1
View File
@@ -1,7 +1,7 @@
import { create } from 'zustand';
import { api } from '../lib/api.ts';
export type ChannelType = 'text' | 'voice' | 'forum' | 'calendar';
export type ChannelType = 'text' | 'voice' | 'forum' | 'calendar' | 'docs';
export interface Channel {
id: string;
+1 -1
View File
@@ -1 +1 @@
{"root":["./src/App.tsx","./src/main.tsx","./src/components/BotManager.tsx","./src/components/CalendarView.tsx","./src/components/ChannelList.tsx","./src/components/ChannelSettingsModal.tsx","./src/components/ChatArea.tsx","./src/components/CommandManager.tsx","./src/components/ConversationList.tsx","./src/components/CreateChannelModal.tsx","./src/components/CreateServerModal.tsx","./src/components/DMChat.tsx","./src/components/EmojiPicker.tsx","./src/components/ForumView.tsx","./src/components/GiphyPicker.tsx","./src/components/InstallPrompt.tsx","./src/components/InviteModal.tsx","./src/components/JoinServer.tsx","./src/components/JoinServerModal.tsx","./src/components/Layout.tsx","./src/components/LoginForm.tsx","./src/components/MemberContextMenu.tsx","./src/components/MemberList.tsx","./src/components/MemberRoleAssign.tsx","./src/components/MentionDropdown.tsx","./src/components/MentionPopup.tsx","./src/components/MessageSearch.tsx","./src/components/MobileDrawer.tsx","./src/components/MobileNav.tsx","./src/components/NewConversationModal.tsx","./src/components/ReactionBar.tsx","./src/components/ReplyBar.tsx","./src/components/RoleManager.tsx","./src/components/ServerBar.tsx","./src/components/ServerSettingsModal.tsx","./src/components/SlashCommandPopup.tsx","./src/components/ThemeToggle.tsx","./src/components/ThreadListPanel.tsx","./src/components/ThreadPanel.tsx","./src/components/TypingIndicator.tsx","./src/components/UserProfileModal.tsx","./src/components/UserSettings.tsx","./src/components/VoiceChannel.tsx","./src/components/VoiceControls.tsx","./src/components/VoicePanel.tsx","./src/lib/api.ts","./src/lib/usePermissions.ts","./src/stores/auth.ts","./src/stores/bot.ts","./src/stores/channel.ts","./src/stores/conversation.ts","./src/stores/layout.ts","./src/stores/member.ts","./src/stores/message.ts","./src/stores/moderation.ts","./src/stores/permissions.ts","./src/stores/presence.ts","./src/stores/push.ts","./src/stores/role.ts","./src/stores/server.ts","./src/stores/thread.ts","./src/stores/typing.ts","./src/stores/voice.ts","./src/stores/ws.ts"],"version":"5.9.3"}
{"root":["./src/App.tsx","./src/main.tsx","./src/components/BotManager.tsx","./src/components/CalendarView.tsx","./src/components/ChannelList.tsx","./src/components/ChannelSettingsModal.tsx","./src/components/ChatArea.tsx","./src/components/CommandManager.tsx","./src/components/ConversationList.tsx","./src/components/CreateChannelModal.tsx","./src/components/CreateServerModal.tsx","./src/components/DMChat.tsx","./src/components/DocsView.tsx","./src/components/EmojiPicker.tsx","./src/components/ForumView.tsx","./src/components/GiphyPicker.tsx","./src/components/InstallPrompt.tsx","./src/components/InviteModal.tsx","./src/components/JoinServer.tsx","./src/components/JoinServerModal.tsx","./src/components/Layout.tsx","./src/components/LoginForm.tsx","./src/components/MemberContextMenu.tsx","./src/components/MemberList.tsx","./src/components/MemberRoleAssign.tsx","./src/components/MentionDropdown.tsx","./src/components/MentionPopup.tsx","./src/components/MessageSearch.tsx","./src/components/MobileDrawer.tsx","./src/components/MobileNav.tsx","./src/components/NewConversationModal.tsx","./src/components/ReactionBar.tsx","./src/components/ReplyBar.tsx","./src/components/RoleManager.tsx","./src/components/ServerBar.tsx","./src/components/ServerSettingsModal.tsx","./src/components/SlashCommandPopup.tsx","./src/components/ThemeToggle.tsx","./src/components/ThreadListPanel.tsx","./src/components/ThreadPanel.tsx","./src/components/TypingIndicator.tsx","./src/components/UserProfileModal.tsx","./src/components/UserSettings.tsx","./src/components/VoiceChannel.tsx","./src/components/VoiceControls.tsx","./src/components/VoicePanel.tsx","./src/lib/api.ts","./src/lib/usePermissions.ts","./src/stores/auth.ts","./src/stores/bot.ts","./src/stores/channel.ts","./src/stores/conversation.ts","./src/stores/layout.ts","./src/stores/member.ts","./src/stores/message.ts","./src/stores/moderation.ts","./src/stores/permissions.ts","./src/stores/presence.ts","./src/stores/push.ts","./src/stores/role.ts","./src/stores/server.ts","./src/stores/thread.ts","./src/stores/typing.ts","./src/stores/voice.ts","./src/stores/ws.ts"],"version":"5.9.3"}