xonecas.io
53129
Pa

PAT / commit e236b80

feat: refactor home component

- breakdown into smaller components and hooks
- Remove auto loading latest thread
- Add new "hello" component

xonecas2025-12-16 e236b80f4e92d3d2babc3e6afc7f8a163dafd418 parent 874406f

7 files changed

AGENTS.md+52−13
@@ -32,6 +32,10 @@ Agents MUST use only these existing dependencies. Do NOT add new dependencies wi
3232 - **postcss**: ^8.4.30 - CSS transformation tool
3333 - **drizzle-orm**: ^0.45.1 - TypeScript ORM for SQL databases
3434 - **better-sqlite3**: ^12.5.0 - Fast SQLite3 database driver
35+- **react-markdown**: ^10.1.0 - React component for rendering markdown
36+- **remark-gfm**: ^4.0.1 - GitHub Flavored Markdown plugin for remark
37+- **rehype-highlight**: ^7.0.2 - Syntax highlighting plugin for rehype
38+- **highlight.js**: ^11.11.1 - Syntax highlighting library
3539
3640 ### Dev Dependencies
3741
@@ -62,6 +66,8 @@ Agents MUST use only these existing dependencies. Do NOT add new dependencies wi
6266 - Library utilities in `src/lib/`
6367 - Reusable components in `src/components/`
6468 - Icon components in `src/components/icons/`
69+ - Custom React hooks in `src/hooks/`
70+ - Shared TypeScript types in `src/types.ts`
6571 - Use TypeScript for all code files (`.ts`, `.tsx`)
6672
6773 2. **Component Style**:
@@ -90,9 +96,10 @@ Agents MUST use only these existing dependencies. Do NOT add new dependencies wi
9096 6. **Styling**:
9197 - Use TailwindCSS utility classes exclusively
9298 - Inline Tailwind classes in JSX
93- - Follow existing patterns: `className="flex flex-col bg-slate-200 dark:bg-slate-900 p-4"`
99+ - Follow existing patterns: `className="flex flex-col bg-neutral-200 dark:bg-neutral-900 p-4"`
94100 - Use responsive design utilities when appropriate
95- - Set default text colors on topmost container to cascade: `text-slate-800 dark:text-slate-200`
101+ - Set default text colors on topmost container to cascade: `text-neutral-800 dark:text-neutral-200`
102+ - Use neutral color palette (not slate or gray)
96103
97104 7. **Code Formatting**:
98105 - Use Prettier for code formatting: `npm run format` to format all files
@@ -124,20 +131,32 @@ Agents MUST use only these existing dependencies. Do NOT add new dependencies wi
124131 /home/xonecas/src/personal-assistant-thing/
125132 ├── app/
126133 │ ├── api/
127-│ │ └── chat/
128-│ │ └── route.ts # Chat API endpoint
134+│ │ ├── chat/
135+│ │ │ └── route.ts # Chat API endpoint
136+│ │ └── threads/
137+│ │ ├── route.ts # Threads API endpoint (GET, POST)
138+│ │ └── [id]/
139+│ │ └── messages/
140+│ │ └── route.ts # Thread messages API endpoint
129141 │ ├── globals.css # Global styles
142+│ ├── highlight-theme.css # Syntax highlighting theme
130143 │ ├── layout.tsx # Root layout component
131144 │ └── page.tsx # Main page component
132145 ├── src/
133146 │ ├── components/
134-│ │ └── icons/
135-│ │ └── PaperPlaneIcon.tsx # Reusable icon components
136-│ └── lib/
137-│ ├── db/
138-│ │ ├── index.ts # Database connection and setup
139-│ │ └── schema.ts # Drizzle ORM schema definitions
140-│ └── ollama.ts # Ollama API wrapper
147+│ │ ├── icons/
148+│ │ │ └── PaperPlaneIcon.tsx # Reusable icon components
149+│ │ ├── MessageInput.tsx # Message input form component
150+│ │ ├── NoThreadSelected.tsx # Welcome screen when no thread selected
151+│ │ └── Sidebar.tsx # Sidebar component with thread selection
152+│ ├── hooks/
153+│ │ └── useTheme.ts # Custom hook for theme management
154+│ ├── lib/
155+│ │ ├── db/
156+│ │ │ ├── index.ts # Database connection and setup
157+│ │ │ └── schema.ts # Drizzle ORM schema definitions
158+│ │ └── ollama.ts # Ollama API wrapper
159+│ └── types.ts # Shared TypeScript type definitions
141160 ├── drizzle/ # Generated migration files
142161 │ ├── meta/ # Migration metadata
143162 │ └── *.sql # SQL migration files
@@ -181,14 +200,28 @@ Agents MUST use only these existing dependencies. Do NOT add new dependencies wi
181200 - **Connection**: Exported from `src/lib/db/index.ts` as `db`
182201 - **Tables**:
183202 - `threads`: Stores conversation threads with id, title, createdAt, updatedAt
184- - `messages`: Stores messages with id, threadId, role, content, createdAt
203+ - `messages`: Stores messages with id, threadId, role, content, createdAt, generationTimeMs
185204 - **Relations**: Messages belong to threads (one-to-many)
186-- **Types**: Exported types `Thread`, `NewThread`, `Message`, `NewMessage`
205+- **Types**: Type definitions for `Thread` and `Message` are in `src/types.ts` (shared across the application)
187206 - **Configuration**: `drizzle.config.ts` defines schema path and database location
188207 - **Migrations**: Generated in `drizzle/` directory using `npm run db:generate`
189208 - **Foreign Keys**: Enabled automatically in database connection
190209 - **Usage**: Import `db` from `src/lib/db/index.ts` to query the database
191210
211+### Component Structure
212+
213+- **Home** (`app/page.tsx`): Main page component that orchestrates the chat interface. Loads threads on mount but does not automatically select the latest thread - user must manually select a thread or create a new one.
214+- **Sidebar** (`src/components/Sidebar.tsx`): Sidebar with thread selection, new thread button, and theme selector
215+- **MessageInput** (`src/components/MessageInput.tsx`): Input form for sending messages with keyboard history navigation (ArrowUp/ArrowDown to cycle through previous user messages)
216+- **NoThreadSelected** (`src/components/NoThreadSelected.tsx`): Welcome screen displayed when no thread is selected, shows PAT introduction, current time (updates every second), and thread count
217+- **useTheme** (`src/hooks/useTheme.ts`): Custom hook managing theme state (device/dark/light) with localStorage persistence and automatic device preference detection
218+
219+### Type Definitions
220+
221+- **Types** (`src/types.ts`): Shared TypeScript types
222+ - `Thread`: Thread type with id, title, createdAt, updatedAt
223+ - `Message`: Message type with id, threadId, role, content, createdAt, generationTimeMs
224+
192225 ### Chat API Flow
193226
194227 1. Client sends POST request to `/api/chat` with `{ message: string, threadId: number }`
@@ -198,6 +231,12 @@ Agents MUST use only these existing dependencies. Do NOT add new dependencies wi
198231 5. API route stores the assistant response with generation time
199232 6. API route returns `{ answer: string }`
200233
234+### Threads API
235+
236+- **GET** `/api/threads`: Returns list of all threads sorted by most recent
237+- **POST** `/api/threads`: Creates a new thread with optional title, returns the created thread
238+- **GET** `/api/threads/[id]/messages`: Returns all messages for a specific thread
239+
201240 ## Development Workflow
202241
203242 1. Start development server: `npm run dev`
app/page.tsx+28−174
@@ -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 }
src/components/MessageInput.tsx+75−0
@@ -0,0 +1,75 @@
1+"use client";
2+
3+import { useState } from "react";
4+import PaperPlaneIcon from "@/src/components/icons/PaperPlaneIcon";
5+import type { Message } from "@/src/types";
6+
7+type MessageInputProps = {
8+ isLoading: boolean;
9+ messages: Message[];
10+ onSubmit: (message: string) => void;
11+};
12+
13+export default function MessageInput({ isLoading, messages, onSubmit }: MessageInputProps) {
14+ const [input, setInput] = useState("");
15+ const [historyIndex, setHistoryIndex] = useState<number | null>(null);
16+
17+ const handleSubmit = (e: React.FormEvent) => {
18+ e.preventDefault();
19+ if (!input.trim() || isLoading) return;
20+
21+ const inputValue = input.trim();
22+ onSubmit(inputValue);
23+ setInput("");
24+ setHistoryIndex(null);
25+ };
26+
27+ const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
28+ // Only cycle through user messages, not assistant messages
29+ const userMessages = messages.filter((m) => m.role === "user");
30+
31+ if (e.key === "ArrowUp") {
32+ e.preventDefault();
33+ const idx = historyIndex ?? userMessages.length;
34+ if (idx > 0) {
35+ const newIdx = idx - 1;
36+ setHistoryIndex(newIdx);
37+ setInput(userMessages[newIdx].content);
38+ }
39+ } else if (e.key === "ArrowDown") {
40+ e.preventDefault();
41+ if (historyIndex !== null) {
42+ const newIdx = historyIndex + 1;
43+ if (newIdx < userMessages.length) {
44+ setHistoryIndex(newIdx);
45+ setInput(userMessages[newIdx].content);
46+ } else {
47+ setHistoryIndex(null);
48+ setInput("");
49+ }
50+ }
51+ }
52+ };
53+
54+ return (
55+ <form onSubmit={handleSubmit} 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)]">
56+ <input
57+ type="text"
58+ value={input}
59+ onChange={(e) => setInput(e.target.value)}
60+ onKeyDown={handleKeyDown}
61+ placeholder={isLoading ? "Loading answer..." : "Type a message..."}
62+ disabled={isLoading}
63+ 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"
64+ />
65+ <button
66+ type="submit"
67+ disabled={isLoading}
68+ 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"
69+ >
70+ <PaperPlaneIcon className={`h-5 w-5 ${isLoading ? "animate-spin" : ""}`} />
71+ </button>
72+ </form>
73+ );
74+}
75+
src/components/NoThreadSelected.tsx+48−0
@@ -0,0 +1,48 @@
1+"use client";
2+
3+import { useState, useEffect } from "react";
4+import ReactMarkdown from "react-markdown";
5+import remarkGfm from "remark-gfm";
6+import rehypeHighlight from "rehype-highlight";
7+
8+type NoThreadSelectedProps = {
9+ threadCount: number;
10+};
11+
12+export default function NoThreadSelected({ threadCount }: NoThreadSelectedProps) {
13+ const [currentTime, setCurrentTime] = useState<Date | null>(null);
14+
15+ useEffect(() => {
16+ // Set initial time only on client side to avoid hydration mismatch
17+ setCurrentTime(new Date());
18+ const timer = setInterval(() => {
19+ setCurrentTime(new Date());
20+ }, 1000);
21+
22+ return () => clearInterval(timer);
23+ }, []);
24+
25+ const formatTime = (date: Date): string => {
26+ return date.toLocaleString();
27+ };
28+
29+ const timeDisplay = currentTime ? formatTime(currentTime) : "";
30+
31+ return (
32+ <div className="min-w-0">
33+ <div className="markdown-content p-1 bg-neutral-200 text-neutral-800 dark:bg-neutral-900 dark:text-neutral-200">
34+ <ReactMarkdown remarkPlugins={[remarkGfm]} rehypePlugins={[rehypeHighlight]}>
35+ {`# Welcome to PAT 👋
36+
37+**PAT** (Personal Assistant Thing) is your personal assistant. To get started, click the **"New Thread"** button in the sidebar or start typing below to create your a conversation thread.
38+
39+---
40+
41+${timeDisplay ? `*Current time: ${timeDisplay}*` : ""}
42+*${threadCount} ${threadCount === 1 ? "thread" : "threads"} available*`}
43+ </ReactMarkdown>
44+ </div>
45+ </div>
46+ );
47+}
48+
src/components/Sidebar.tsx+67−0
@@ -0,0 +1,67 @@
1+"use client";
2+
3+import type { Thread } from "@/src/types";
4+
5+type SidebarProps = {
6+ threads: Thread[];
7+ currentThreadId: number | null;
8+ themeMode: "device" | "dark" | "light";
9+ onCreateNewThread: () => Promise<void>;
10+ onThreadSelect: (threadId: number) => void;
11+ onThemeChange: (mode: "device" | "dark" | "light") => void;
12+};
13+
14+export default function Sidebar({
15+ threads,
16+ currentThreadId,
17+ themeMode,
18+ onCreateNewThread,
19+ onThreadSelect,
20+ onThemeChange,
21+}: SidebarProps) {
22+ return (
23+ <div className="w-64 bg-neutral-200 p-1 dark:bg-neutral-900">
24+ <div className="flex flex-col gap-2 p-4">
25+ <button
26+ onClick={() => onCreateNewThread()}
27+ 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"
28+ >
29+ New Thread
30+ </button>
31+ <div className="flex flex-col gap-2">
32+ <label className="text-sm font-semibold">Threads</label>
33+ <select
34+ value={currentThreadId || ""}
35+ onChange={(e) => {
36+ const threadId = e.target.value ? parseInt(e.target.value) : null;
37+ if (threadId) {
38+ onThreadSelect(threadId);
39+ }
40+ }}
41+ className="bg-neutral-100 px-3 py-1 text-neutral-800 focus:outline-none dark:bg-neutral-950 dark:text-neutral-200"
42+ >
43+ <option value="">Select a thread...</option>
44+ {threads.map((thread) => (
45+ <option key={thread.id} value={thread.id}>
46+ {thread.title || `Thread ${thread.id}`}
47+ </option>
48+ ))}
49+ </select>
50+ </div>
51+ <div className="flex flex-col gap-2">
52+ <label className="text-sm font-semibold">Theme</label>
53+ <select
54+ value={themeMode}
55+ onChange={(e) => onThemeChange(e.target.value as "device" | "dark" | "light")}
56+ className="bg-neutral-100 px-3 py-1 text-neutral-800 focus:outline-none dark:bg-neutral-950 dark:text-neutral-200"
57+ >
58+ <option value="device">Device</option>
59+ <option value="dark">Dark</option>
60+ <option value="light">Light</option>
61+ </select>
62+ </div>
63+ </div>
64+ </div>
65+ );
66+}
67+
src/hooks/useTheme.ts+45−0
@@ -0,0 +1,45 @@
1+import { useState, useEffect } from "react";
2+
3+export function useTheme() {
4+ const [themeMode, setThemeMode] = useState<"device" | "dark" | "light">("device");
5+
6+ const applyTheme = (mode: "device" | "dark" | "light") => {
7+ let shouldBeDark = false;
8+ if (mode === "device") {
9+ shouldBeDark = window.matchMedia("(prefers-color-scheme: dark)").matches;
10+ } else {
11+ shouldBeDark = mode === "dark";
12+ }
13+
14+ if (shouldBeDark) {
15+ document.documentElement.classList.add("dark");
16+ } else {
17+ document.documentElement.classList.remove("dark");
18+ }
19+ };
20+
21+ useEffect(() => {
22+ const savedMode = localStorage.getItem("themeMode") as "device" | "dark" | "light" | null;
23+ const mode = savedMode || "device";
24+ setThemeMode(mode);
25+ applyTheme(mode);
26+ }, []);
27+
28+ useEffect(() => {
29+ if (themeMode === "device") {
30+ const mediaQuery = window.matchMedia("(prefers-color-scheme: dark)");
31+ const handleChange = () => applyTheme("device");
32+ mediaQuery.addEventListener("change", handleChange);
33+ return () => mediaQuery.removeEventListener("change", handleChange);
34+ }
35+ }, [themeMode]);
36+
37+ const handleThemeChange = (mode: "device" | "dark" | "light") => {
38+ setThemeMode(mode);
39+ localStorage.setItem("themeMode", mode);
40+ applyTheme(mode);
41+ };
42+
43+ return { themeMode, handleThemeChange };
44+}
45+
src/types.ts+16−0
@@ -0,0 +1,16 @@
1+export type Thread = {
2+ id: number;
3+ title: string | null;
4+ createdAt: Date;
5+ updatedAt: Date;
6+};
7+
8+export type Message = {
9+ id: number;
10+ threadId: number;
11+ role: string;
12+ content: string;
13+ createdAt: Date;
14+ generationTimeMs: number | null;
15+};
16+