@@ -3,29 +3,16 @@ import { useState, useEffect, useRef } from "react";
33 import ReactMarkdown from "react-markdown";
44 import remarkGfm from "remark-gfm";
55 import rehypeHighlight from "rehype-highlight";
6-import PaperPlaneIcon from "@/src/components/icons/PaperPlaneIcon";
6+import Sidebar from "@/src/components/Sidebar";
7+import MessageInput from "@/src/components/MessageInput";
8+import NoThreadSelected from "@/src/components/NoThreadSelected";
9+import { useTheme } from "@/src/hooks/useTheme";
10+import type { Thread, Message } from "@/src/types";
711 import "./highlight-theme.css";
812
9-type Thread = {
10- id: number;
11- title: string | null;
12- createdAt: Date;
13- updatedAt: Date;
14-};
15-
16-type Message = {
17- id: number;
18- threadId: number;
19- role: string;
20- content: string;
21- createdAt: Date;
22- generationTimeMs: number | null;
23-};
24-
2513 export default function Home() {
2614 const [messages, setMessages] = useState<Message[]>([]);
27- const [input, setInput] = useState("");
28- const [themeMode, setThemeMode] = useState<"device" | "dark" | "light">("device");
15+ const { themeMode, handleThemeChange } = useTheme();
2916 const [currentThreadId, setCurrentThreadId] = useState<number | null>(null);
3017 const [threads, setThreads] = useState<Thread[]>([]);
3118 const [isLoading, setIsLoading] = useState(false);
@@ -33,36 +20,6 @@ export default function Home() {
3320 const messageRefs = useRef<Map<number, HTMLDivElement>>(new Map());
3421 const prevMessagesLengthRef = useRef<number>(0);
3522
36- const applyTheme = (mode: "device" | "dark" | "light") => {
37- let shouldBeDark = false;
38- if (mode === "device") {
39- shouldBeDark = window.matchMedia("(prefers-color-scheme: dark)").matches;
40- } else {
41- shouldBeDark = mode === "dark";
42- }
43-
44- if (shouldBeDark) {
45- document.documentElement.classList.add("dark");
46- } else {
47- document.documentElement.classList.remove("dark");
48- }
49- };
50-
51- useEffect(() => {
52- const savedMode = localStorage.getItem("themeMode") as "device" | "dark" | "light" | null;
53- const mode = savedMode || "device";
54- setThemeMode(mode);
55- applyTheme(mode);
56- }, []);
57-
58- useEffect(() => {
59- if (themeMode === "device") {
60- const mediaQuery = window.matchMedia("(prefers-color-scheme: dark)");
61- const handleChange = () => applyTheme("device");
62- mediaQuery.addEventListener("change", handleChange);
63- return () => mediaQuery.removeEventListener("change", handleChange);
64- }
65- }, [themeMode]);
6623
6724 useEffect(() => {
6825 const loadThreads = async () => {
@@ -71,13 +28,6 @@ export default function Home() {
7128 const data = await res.json();
7229 const threadsList = data.threads || [];
7330 setThreads(threadsList);
74-
75- // Load the most recent thread if available
76- if (threadsList.length > 0) {
77- const mostRecentThread = threadsList[0];
78- setCurrentThreadId(mostRecentThread.id);
79- await loadMessages(mostRecentThread.id);
80- }
8131 } catch (error) {
8232 console.error("Failed to load threads", error);
8333 }
@@ -103,11 +53,6 @@ export default function Home() {
10353 }
10454 }, [messages]);
10555
106- const handleThemeChange = (mode: "device" | "dark" | "light") => {
107- setThemeMode(mode);
108- localStorage.setItem("themeMode", mode);
109- applyTheme(mode);
110- };
11156
11257 const loadMessages = async (threadId: number) => {
11358 try {
@@ -121,9 +66,9 @@ export default function Home() {
12166 }
12267 };
12368
124- const createNewThread = async (titleOverride?: string): Promise<number | null> => {
69+ const createNewThread = async (titleOverride?: string, firstMessage?: string): Promise<number | null> => {
12570 try {
126- const title = titleOverride || (input.trim() ? input.substring(0, 20) : "New Thread");
71+ const title = titleOverride || (firstMessage ? firstMessage.substring(0, 20) : "New Thread");
12772 const res = await fetch("/api/threads", {
12873 method: "POST",
12974 headers: { "Content-Type": "application/json" },
@@ -150,16 +95,18 @@ export default function Home() {
15095 loadMessages(threadId);
15196 };
15297
153- const [historyIndex, setHistoryIndex] = useState<number | null>(null);
154- const sendMessage = async (e: React.FormEvent) => {
155- e.preventDefault();
156- if (!input.trim() || isLoading) return;
98+ const handleCreateNewThread = async () => {
99+ await createNewThread();
100+ };
101+
102+ const sendMessage = async (message: string) => {
103+ if (!message.trim() || isLoading) return;
157104
158105 setIsLoading(true);
159106 let threadId = currentThreadId;
160107 if (!threadId) {
161108 // Create a new thread if none exists
162- threadId = await createNewThread(input.substring(0, 20));
109+ threadId = await createNewThread(message.substring(0, 20), message);
163110 if (!threadId) {
164111 setIsLoading(false);
165112 return;
@@ -170,20 +117,17 @@ export default function Home() {
170117 id: Date.now(),
171118 threadId: threadId!,
172119 role: "user",
173- content: input,
120+ content: message,
174121 createdAt: new Date(),
175122 generationTimeMs: null,
176123 };
177124 setMessages((prev) => [...prev, userMsg]);
178- const inputValue = input.trim();
179- if (!inputValue) return;
180- setInput("");
181125
182126 try {
183127 const res = await fetch("/api/chat", {
184128 method: "POST",
185129 headers: { "Content-Type": "application/json" },
186- body: JSON.stringify({ message: inputValue, threadId }),
130+ body: JSON.stringify({ message: message.trim(), threadId }),
187131 });
188132
189133 const data = await res.json();
@@ -210,35 +154,6 @@ export default function Home() {
210154 } finally {
211155 setIsLoading(false);
212156 }
213-
214- setInput("");
215- setHistoryIndex(null);
216- };
217- const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
218- // Only cycle through user messages, not assistant messages
219- const userMessages = messages.filter((m) => m.role === "user");
220-
221- if (e.key === "ArrowUp") {
222- e.preventDefault();
223- const idx = historyIndex ?? userMessages.length;
224- if (idx > 0) {
225- const newIdx = idx - 1;
226- setHistoryIndex(newIdx);
227- setInput(userMessages[newIdx].content);
228- }
229- } else if (e.key === "ArrowDown") {
230- e.preventDefault();
231- if (historyIndex !== null) {
232- const newIdx = historyIndex + 1;
233- if (newIdx < userMessages.length) {
234- setHistoryIndex(newIdx);
235- setInput(userMessages[newIdx].content);
236- } else {
237- setHistoryIndex(null);
238- setInput("");
239- }
240- }
241- }
242157 };
243158
244159 const formatTimestamp = (date: Date | string): string => {
@@ -260,18 +175,8 @@ export default function Home() {
260175 className="text-sm p-4 flex-1 overflow-y-auto overflow-x-hidden bg-neutral-100 dark:bg-neutral-950"
261176 >
262177 <div className="flex min-h-full flex-col justify-end gap-8">
263- {threads.length === 0 && messages.length === 0 && currentThreadId === null ? (
264- <div className="min-w-0">
265- <div className="markdown-content p-1 bg-neutral-200 text-neutral-800 dark:bg-neutral-900 dark:text-neutral-200">
266- <ReactMarkdown remarkPlugins={[remarkGfm]} rehypePlugins={[rehypeHighlight]}>
267- {`# Welcome! 👋
268-
269-I'm your personal assistant. To get started, click the **"New Thread"** button in the sidebar to create your first conversation thread.
270-
271-Once you've created a thread, you can start chatting with me by typing a message below.`}
272- </ReactMarkdown>
273- </div>
274- </div>
178+ {currentThreadId === null ? (
179+ <NoThreadSelected threadCount={threads.length} />
275180 ) : (
276181 messages.map((msg) => (
277182 <div
@@ -311,67 +216,16 @@ Once you've created a thread, you can start chatting with me by typing a message
311216 )}
312217 </div>
313218 </div>
314- <form onSubmit={sendMessage} className="flex shadow-[0_-4px_6px_-1px_rgba(0,0,0,0.1),0_-2px_4px_-1px_rgba(0,0,0,0.06)] dark:shadow-[0_-4px_6px_-1px_rgba(0,0,0,0.3),0_-2px_4px_-1px_rgba(0,0,0,0.2)]">
315- <input
316- type="text"
317- value={input}
318- onChange={(e) => setInput(e.target.value)}
319- onKeyDown={handleKeyDown}
320- placeholder={isLoading ? "Loading answer..." : "Type a message..."}
321- disabled={isLoading}
322- className="flex-1 bg-neutral-200 px-2 py-2 placeholder:italic placeholder:text-neutral-600 focus:outline-none disabled:opacity-50 disabled:cursor-not-allowed dark:bg-neutral-900 dark:placeholder:text-neutral-400"
323- />
324- <button
325- type="submit"
326- disabled={isLoading}
327- className="bg-green-900 px-3 py-1 text-neutral-100 hover:bg-green-800 disabled:opacity-50 disabled:cursor-not-allowed dark:bg-green-500 dark:text-neutral-900 dark:hover:bg-green-600"
328- >
329- <PaperPlaneIcon className={`h-5 w-5 ${isLoading ? "animate-spin" : ""}`} />
330- </button>
331- </form>
332- </div>
333- <div className="w-64 bg-neutral-200 p-1 dark:bg-neutral-900">
334- <div className="flex flex-col gap-2 p-4">
335- <button
336- onClick={() => createNewThread()}
337- className="bg-green-900 px-1 py-1 text-neutral-100 hover:bg-green-800 dark:bg-green-500 dark:text-neutral-900 dark:hover:bg-green-600"
338- >
339- New Thread
340- </button>
341- <div className="flex flex-col gap-2">
342- <label className="text-sm font-semibold">Threads</label>
343- <select
344- value={currentThreadId || ""}
345- onChange={(e) => {
346- const threadId = e.target.value ? parseInt(e.target.value) : null;
347- if (threadId) {
348- handleThreadSelect(threadId);
349- }
350- }}
351- className="bg-neutral-100 px-3 py-1 text-neutral-800 focus:outline-none dark:bg-neutral-950 dark:text-neutral-200"
352- >
353- <option value="">Select a thread...</option>
354- {threads.map((thread) => (
355- <option key={thread.id} value={thread.id}>
356- {thread.title || `Thread ${thread.id}`}
357- </option>
358- ))}
359- </select>
360- </div>
361- <div className="flex flex-col gap-2">
362- <label className="text-sm font-semibold">Theme</label>
363- <select
364- value={themeMode}
365- onChange={(e) => handleThemeChange(e.target.value as "device" | "dark" | "light")}
366- className="bg-neutral-100 px-3 py-1 text-neutral-800 focus:outline-none dark:bg-neutral-950 dark:text-neutral-200"
367- >
368- <option value="device">Device</option>
369- <option value="dark">Dark</option>
370- <option value="light">Light</option>
371- </select>
372- </div>
373- </div>
219+ <MessageInput isLoading={isLoading} messages={messages} onSubmit={sendMessage} />
374220 </div>
221+ <Sidebar
222+ threads={threads}
223+ currentThreadId={currentThreadId}
224+ themeMode={themeMode}
225+ onCreateNewThread={handleCreateNewThread}
226+ onThreadSelect={handleThreadSelect}
227+ onThemeChange={handleThemeChange}
228+ />
375229 </div>
376230 );
377231 }