Here’s a minimal, SOLID + DRY + KISS implementation of a chat page with 4 components—using Shadcn/UI, TailwindCSS, React (Next.js 13 App Router)—that connects to your backend via Server‐Sent Events (SSE).
Folder structure:
app/
├─ chat/
│ └─ page.tsx
components/
├─ AppSidebar.tsx
├─ ChatHeader.tsx
├─ MessageContainer.tsx
├─ ChatFooter.tsx
hooks/
└─ useSSE.ts
1. hooks/useSSE.ts
A reusable hook for SSE streams.
// hooks/useSSE.ts
import { useEffect, useRef } from "react";
export function useSSE(
url: string,
onMessage: (data: any) => void,
onError?: (err: any) => void
) {
const esRef = useRef<EventSource>();
useEffect(() => {
const es = new EventSource(url);
esRef.current = es;
es.onmessage = (e) => {
try {
const data = JSON.parse(e.data);
onMessage(data);
} catch {
onMessage(e.data);
}
};
if (onError) es.onerror = onError;
return () => {
es.close();
};
}, [url, onMessage, onError]);
}
2. components/AppSidebar.tsx
A simple navigational sidebar.
// components/AppSidebar.tsx
"use client";
import { ScrollArea } from "@shadcn/ui";
export function AppSidebar() {
const chats = [
{ id: 1, name: "General" },
{ id: 2, name: "Support" },
];
return (
<aside className="w-60 border-r bg-white">
<h2 className="p-4 text-lg font-bold">Your Chats</h2>
<ScrollArea className="h-[calc(100vh-4rem)] px-2">
<ul>
{chats.map((c) => (
<li
key={c.id}
className="cursor-pointer rounded px-3 py-2 hover:bg-gray-100"
>
{c.name}
</li>
))}
</ul>
</ScrollArea>
</aside>
);
}
3. components/ChatHeader.tsx
Shows the AI model name.
// components/ChatHeader.tsx
"use client";
import { Separator } from "@shadcn/ui";
interface ChatHeaderProps {
modelName: string;
}
export function ChatHeader({ modelName }: ChatHeaderProps) {
return (
<header className="flex items-center justify-between p-4 bg-white border-b">
<h1 className="text-xl font-semibold">{modelName}</h1>
<Separator orientation="vertical" className="mx-2 h-6" />
{/* ... you can add buttons (settings, close) here */}
</header>
);
}
4. components/MessageContainer.tsx
Renders all messages side‐by‐side as user/AI bubbles.
// components/MessageContainer.tsx
"use client";
import { useRef, useEffect } from "react";
export type Message = {
id: string;
from: "user" | "ai";
text: string;
timestamp?: string;
};
interface MessageContainerProps {
messages: Message[];
}
export function MessageContainer({ messages }: MessageContainerProps) {
const endRef = useRef<HTMLDivElement>(null);
// auto-scroll
useEffect(() => {
endRef.current?.scrollIntoView({ behavior: "smooth" });
}, [messages]);
return (
<div className="flex-1 overflow-y-auto p-4 space-y-4 bg-gray-50">
{messages.map((m) => (
<div
key={m.id}
className={`max-w-[70%] px-4 py-2 rounded-lg ${
m.from === "user" ? "ml-auto bg-blue-500 text-white" : "bg-white"
}`}
>
{m.text}
</div>
))}
<div ref={endRef} />
</div>
);
}
5. components/ChatFooter.tsx
Handles text, file, image & (stub) voice input.
// components/ChatFooter.tsx
"use client";
import { useState, FormEvent } from "react";
import {
Button,
Input,
FileInput,
Toolbar,
ToolbarButton,
} from "@shadcn/ui";
import {
ImageIcon,
PaperClipIcon,
MicrophoneIcon,
SendIcon,
} from "@radix-ui/react-icons";
interface ChatFooterProps {
onSend: (text: string, file?: File) => void;
}
export function ChatFooter({ onSend }: ChatFooterProps) {
const [text, setText] = useState("");
const [file, setFile] = useState<File | undefined>(undefined);
function handleSubmit(e: FormEvent) {
e.preventDefault();
if (!text.trim() && !file) return;
onSend(text.trim(), file);
setText("");
setFile(undefined);
}
return (
<footer className="p-4 border-t bg-white">
<form onSubmit={handleSubmit} className="flex items-center gap-2">
<Toolbar>
<ToolbarButton asChild>
<label>
<PaperClipIcon />
<FileInput
className="sr-only"
onChange={(e) => setFile(e.target.files?.[0])}
/>
</label>
</ToolbarButton>
<ToolbarButton>
<ImageIcon />
</ToolbarButton>
<ToolbarButton>
<MicrophoneIcon />
</ToolbarButton>
</Toolbar>
<Input
placeholder="Type your message..."
value={text}
onChange={(e) => setText(e.target.value)}
className="flex-1"
/>
<Button type="submit" variant="primary" disabled={!text && !file}>
<SendIcon />
</Button>
</form>
</footer>
);
}
6. app/chat/page.tsx
Wires it all together, streams from /api/chat/stream SSE, sends to /api/chat/send.
// app/chat/page.tsx
"use client";
import { useState, useCallback } from "react";
import { AppSidebar } from "@/components/AppSidebar";
import { ChatHeader } from "@/components/ChatHeader";
import { MessageContainer, Message } from "@/components/MessageContainer";
import { ChatFooter } from "@/components/ChatFooter";
import { useSSE } from "@/hooks/useSSE";
import { v4 as uuid } from "uuid";
export default function ChatPage() {
const [messages, setMessages] = useState<Message[]>([]);
// handle incoming AI chunks
const handleIncoming = useCallback((data: any) => {
const aiMsg: Message = {
id: uuid(),
from: "ai",
text: data.text,
};
setMessages((prev) => [...prev, aiMsg]);
}, []);
// subscribe SSE when mounted
useSSE("/api/chat/stream", handleIncoming, console.error);
// send user message
const sendMessage = useCallback(async (text: string, file?: File) => {
const userMsg: Message = { id: uuid(), from: "user", text };
setMessages((prev) => [...prev, userMsg]);
const form = new FormData();
form.append("message", text);
if (file) form.append("file", file);
await fetch("/api/chat/send", {
method: "POST",
body: form,
});
// the SSE endpoint will stream the AI response
}, []);
return (
<div className="flex h-screen">
<AppSidebar />
<div className="flex flex-col flex-1">
<ChatHeader modelName="GPT-4 Turbo" />
<MessageContainer messages={messages} />
<ChatFooter onSend={sendMessage} />
</div>
</div>
);
}
Explanation of Patterns
- Single Responsibility (SOLID): Each component does one thing.
- DRY: Hook
useSSE is reusable across pages.
- KISS: No over‐engineering—straightforward state + SSE.
- Server‐Side Events:
EventSource opens GET /api/chat/stream, appends messages as they arrive.
You’ll just need to implement two backend routes:
- GET
/api/chat/stream: streams JSON‐encoded chunks via SSE.
- POST
/api/chat/send: accepts text+file, triggers the AI and SSE backend.
That’s it! You now have a lean, Shadcn‐powered AI chat UI ready to plug into your LLM backend. 🚀