xonecas.io
53129
Pa

PAT / commit f4fe683

refactor: our hooks are a mess

xonecas2025-12-19 f4fe68369e1ed139891bae5e5c9b5073a8202be0 parent efc9557

6 files changed

src/components/DeleteConfirmationModal.tsx+0−62
@@ -1,62 +0,0 @@
1-"use client";
2-
3-import Modal from "@/src/components/Modal";
4-import SecondaryButton from "@/src/components/buttons/SecondaryButton";
5-import PrimaryButton from "@/src/components/buttons/PrimaryButton";
6-
7-type DeleteConfirmationModalProps = {
8- isOpen: boolean;
9- onClose: () => void;
10- onConfirm: () => void | Promise<void>;
11- title: string;
12- message: string;
13- isDeleting?: boolean;
14- confirmLabel?: string;
15- cancelLabel?: string;
16-};
17-
18-export default function DeleteConfirmationModal({
19- isOpen,
20- onClose,
21- onConfirm,
22- title,
23- message,
24- isDeleting = false,
25- confirmLabel = "Delete",
26- cancelLabel = "Cancel",
27-}: DeleteConfirmationModalProps) {
28- const handleConfirm = async () => {
29- await onConfirm();
30- };
31-
32- return (
33- <Modal isOpen={isOpen} onClose={onClose}>
34- <div className="flex flex-col gap-4">
35- <h2 className="text-xl font-semibold">{title}</h2>
36- <p className="text-neutral-600 dark:text-neutral-400">{message}</p>
37- <div className="flex justify-end gap-2">
38- <SecondaryButton
39- onClick={(e) => {
40- e.preventDefault();
41- if (!isDeleting) {
42- onClose();
43- }
44- }}
45- >
46- {cancelLabel}
47- </SecondaryButton>
48- <PrimaryButton
49- onClick={(e) => {
50- e.preventDefault();
51- handleConfirm();
52- }}
53- disabled={isDeleting}
54- color="red"
55- >
56- {isDeleting ? "Deleting..." : confirmLabel}
57- </PrimaryButton>
58- </div>
59- </div>
60- </Modal>
61- );
62-}
src/components/ErrorNotification.tsx+3−3
@@ -1,6 +1,7 @@
11 "use client";
22
33 import ErrorIcon from "@/src/components/icons/ErrorIcon";
4+import Notification from "@/src/components/Notification";
45
56 type ErrorNotificationProps = {
67 message: string;
@@ -8,9 +9,8 @@ type ErrorNotificationProps = {
89
910 export default function ErrorNotification({ message }: ErrorNotificationProps) {
1011 return (
11- <div className="pointer-events-auto mb-2 flex w-fit items-center gap-2 rounded-lg bg-neutral-300/80 px-3 py-1 dark:bg-neutral-800/80">
12- <ErrorIcon className="h-4 w-4 text-red-600 dark:text-red-400" />
12+ <Notification icon={<ErrorIcon className="h-4 w-4 text-red-600 dark:text-red-400" />}>
1313 <span className="text-xs text-neutral-600 dark:text-neutral-400">{message}</span>
14- </div>
14+ </Notification>
1515 );
1616 }
src/components/ThinkingNotification.tsx+17−13
@@ -2,6 +2,7 @@
22
33 import SecondaryButton from "@/src/components/buttons/SecondaryButton";
44 import StopIcon from "@/src/components/icons/StopIcon";
5+import Notification from "@/src/components/Notification";
56
67 type ThinkingNotificationProps = {
78 onStop: () => void;
@@ -9,21 +10,24 @@ type ThinkingNotificationProps = {
910
1011 export default function ThinkingNotification({ onStop }: ThinkingNotificationProps) {
1112 return (
12- <div className="pointer-events-auto mb-2 flex w-fit items-center gap-2 rounded-lg bg-neutral-300/80 px-3 py-1 dark:bg-neutral-800/80">
13+ <Notification
14+ action={
15+ <SecondaryButton
16+ href="#"
17+ className="text-xs"
18+ onClick={(e) => {
19+ e.preventDefault();
20+ onStop();
21+ }}
22+ >
23+ <StopIcon className="h-4 w-4" />
24+ Stop
25+ </SecondaryButton>
26+ }
27+ >
1328 <span className="text-xs text-neutral-600 dark:text-neutral-400">
1429 <span className="animate-color-cycle">thinking</span>
1530 </span>
16- <SecondaryButton
17- href="#"
18- className="text-xs"
19- onClick={(e) => {
20- e.preventDefault();
21- onStop();
22- }}
23- >
24- <StopIcon className="h-4 w-4" />
25- Stop
26- </SecondaryButton>
27- </div>
31+ </Notification>
2832 );
2933 }
src/hooks/useMessages.ts+21−22
@@ -1,7 +1,8 @@
11 import { useState, useEffect, useCallback, useRef } from "react";
22 import type { Message } from "@/src/lib/db/schema";
3-import { getParseErrorMessage, handleError } from "@/src/lib/errors";
3+import { handleError } from "@/src/lib/errors";
44 import { useMessageDisplaySettings } from "./useMessageDisplaySettings";
5+import { useFetch } from "./useFetch";
56 import {
67 createUserMessage,
78 createAssistantMessage,
@@ -39,6 +40,7 @@ export function useMessages(
3940 const sendingToThreadIdRef = useRef<number | null>(null);
4041 const abortControllerRef = useRef<AbortController | null>(null);
4142 const [messageDisplaySettings] = useMessageDisplaySettings();
43+ const fetchWithErrorHandling = useFetch();
4244
4345 const loadMessages = useCallback(
4446 async (id: number, onError?: (error: string) => void) => {
@@ -57,20 +59,23 @@ export function useMessages(
5759 url += `?optional_roles=${optionalRoles.join(",")}`;
5860 }
5961
60- const res = await fetch(url);
61- if (!res.ok) {
62- throw new Error(`Failed to load messages: ${res.status}`);
62+ const data = await fetchWithErrorHandling<{ messages: Message[] }>(url, {
63+ errorMessage: "Failed to load messages",
64+ onError,
65+ });
66+ if (data) {
67+ const loadedMessages = data.messages || [];
68+ setMessages(loadedMessages);
6369 }
64- const data = await res.json();
65- const loadedMessages = data.messages || [];
66- setMessages(loadedMessages);
67- } catch (error) {
68- handleError(error, onError);
6970 } finally {
7071 setIsLoadingMessages(false);
7172 }
7273 },
73- [messageDisplaySettings.showSystemMessages, messageDisplaySettings.showToolMessages]
74+ [
75+ messageDisplaySettings.showSystemMessages,
76+ messageDisplaySettings.showToolMessages,
77+ fetchWithErrorHandling,
78+ ]
7479 );
7580
7681 const updateAssistantMessage = (
@@ -316,20 +321,14 @@ export function useMessages(
316321 threadId: number,
317322 onError?: (error: string) => void
318323 ) => {
319- try {
320- const res = await fetch(`/api/threads/${threadId}/messages/${messageId}`, {
321- method: "DELETE",
322- });
323- if (!res.ok) {
324- const errorData = await res.json().catch((parseError) => {
325- throw new Error(getParseErrorMessage(parseError));
326- });
327- throw new Error(errorData.error || "Failed to delete message");
328- }
324+ const result = await fetchWithErrorHandling(`/api/threads/${threadId}/messages/${messageId}`, {
325+ method: "DELETE",
326+ errorMessage: "Failed to delete message",
327+ onError,
328+ });
329+ if (result !== null) {
329330 // Remove the message from local state
330331 setMessages((prev) => prev.filter((msg) => msg.id !== messageId));
331- } catch (error) {
332- handleError(error, onError);
333332 }
334333 };
335334
src/hooks/useModels.ts+14−22
@@ -1,5 +1,5 @@
11 import { useState, useEffect } from "react";
2-import { handleError } from "@/src/lib/errors";
2+import { useFetch } from "./useFetch";
33
44 export type Model = {
55 name: string;
@@ -14,34 +14,27 @@ export type Model = {
1414 export function useModels(onError?: (error: string) => void) {
1515 const [models, setModels] = useState<Model[]>([]);
1616 const [isLoading, setIsLoading] = useState(true);
17+ const fetchWithErrorHandling = useFetch();
1718
1819 useEffect(() => {
1920 let cancelled = false;
2021
21- fetch("/api/models")
22- .then(async (res) => {
23- if (!res.ok) {
24- throw new Error(`Failed to fetch models: ${res.status}`);
25- }
26- return res.json();
27- })
28- .then((data) => {
29- if (!cancelled) {
30- setModels(data.models || []);
31- setIsLoading(false);
32- }
33- })
34- .catch((error) => {
35- if (!cancelled) {
36- setIsLoading(false);
37- handleError(error, onError);
38- }
39- });
22+ fetchWithErrorHandling<{ models: Model[] }>("/api/models", {
23+ errorMessage: "Failed to fetch models",
24+ onError,
25+ }).then((data) => {
26+ if (!cancelled && data) {
27+ setModels(data.models || []);
28+ setIsLoading(false);
29+ } else if (!cancelled) {
30+ setIsLoading(false);
31+ }
32+ });
4033
4134 return () => {
4235 cancelled = true;
4336 };
44- }, [onError]);
37+ }, [fetchWithErrorHandling, onError]);
4538
4639 return { models, isLoading };
4740 }
@@ -55,4 +48,3 @@ export function useModels(onError?: (error: string) => void) {
5548 export function isValidModel(modelName: string, models: Model[]): boolean {
5649 return models.some((m) => m.model === modelName);
5750 }
58-
tsconfig.tsbuildinfo+1−1
@@ -1 +1 @@
1-{"fileNames":["./node_modules/typescript/lib/lib.es5.d.ts","./node_modules/typescript/lib/lib.es2015.d.ts","./node_modules/typescript/lib/lib.es2016.d.ts","./node_modules/typescript/lib/lib.es2017.d.ts","./node_modules/typescript/lib/lib.es2018.d.ts","./node_modules/typescript/lib/lib.es2019.d.ts","./node_modules/typescript/lib/lib.es2020.d.ts","./node_modules/typescript/lib/lib.es2021.d.ts","./node_modules/typescript/lib/lib.es2022.d.ts","./node_modules/typescript/lib/lib.es2023.d.ts","./node_m …
1+{"fileNames":["./node_modules/typescript/lib/lib.es5.d.ts","./node_modules/typescript/lib/lib.es2015.d.ts","./node_modules/typescript/lib/lib.es2016.d.ts","./node_modules/typescript/lib/lib.es2017.d.ts","./node_modules/typescript/lib/lib.es2018.d.ts","./node_modules/typescript/lib/lib.es2019.d.ts","./node_modules/typescript/lib/lib.es2020.d.ts","./node_modules/typescript/lib/lib.es2021.d.ts","./node_modules/typescript/lib/lib.es2022.d.ts","./node_modules/typescript/lib/lib.es2023.d.ts","./node_m …