2025-07-23 18:25:15 +00:00
|
|
|
'use client';
|
|
|
|
|
|
|
|
|
|
import { useCallback, useState } from "react";
|
|
|
|
|
import { Descendant } from "slate";
|
|
|
|
|
import { createUIMessage, getAllMentionElements } from "./utils";
|
|
|
|
|
import { slateContentToString } from "./utils";
|
|
|
|
|
import { useDomain } from "@/hooks/useDomain";
|
|
|
|
|
import { useToast } from "@/components/hooks/use-toast";
|
|
|
|
|
import { useRouter } from "next/navigation";
|
|
|
|
|
import { createChat } from "./actions";
|
|
|
|
|
import { isServiceError } from "@/lib/utils";
|
|
|
|
|
import { createPathWithQueryParams } from "@/lib/utils";
|
2025-07-31 23:38:10 +00:00
|
|
|
import { SearchScope, SET_CHAT_STATE_SESSION_STORAGE_KEY, SetChatStatePayload } from "./types";
|
|
|
|
|
import { useSessionStorage } from "usehooks-ts";
|
2025-07-23 18:25:15 +00:00
|
|
|
|
|
|
|
|
export const useCreateNewChatThread = () => {
|
|
|
|
|
const domain = useDomain();
|
|
|
|
|
const [isLoading, setIsLoading] = useState(false);
|
|
|
|
|
const { toast } = useToast();
|
|
|
|
|
const router = useRouter();
|
|
|
|
|
|
2025-07-31 23:38:10 +00:00
|
|
|
const [, setChatState] = useSessionStorage<SetChatStatePayload | null>(SET_CHAT_STATE_SESSION_STORAGE_KEY, null);
|
|
|
|
|
|
|
|
|
|
|
2025-07-29 01:12:21 +00:00
|
|
|
const createNewChatThread = useCallback(async (children: Descendant[], selectedSearchScopes: SearchScope[]) => {
|
2025-07-23 18:25:15 +00:00
|
|
|
const text = slateContentToString(children);
|
|
|
|
|
const mentions = getAllMentionElements(children);
|
2025-07-26 23:16:07 +00:00
|
|
|
|
2025-07-29 01:12:21 +00:00
|
|
|
const inputMessage = createUIMessage(text, mentions.map((mention) => mention.data), selectedSearchScopes);
|
2025-07-23 18:25:15 +00:00
|
|
|
|
|
|
|
|
setIsLoading(true);
|
|
|
|
|
const response = await createChat(domain);
|
|
|
|
|
if (isServiceError(response)) {
|
|
|
|
|
toast({
|
|
|
|
|
description: `❌ Failed to create chat. Reason: ${response.message}`
|
|
|
|
|
});
|
|
|
|
|
setIsLoading(false);
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
2025-07-31 23:38:10 +00:00
|
|
|
setChatState({
|
|
|
|
|
inputMessage,
|
|
|
|
|
selectedSearchScopes,
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
const url = createPathWithQueryParams(`/${domain}/chat/${response.id}`);
|
2025-07-23 18:25:15 +00:00
|
|
|
|
|
|
|
|
router.push(url);
|
|
|
|
|
router.refresh();
|
2025-07-31 23:38:10 +00:00
|
|
|
}, [domain, router, toast, setChatState]);
|
2025-07-23 18:25:15 +00:00
|
|
|
|
|
|
|
|
return {
|
|
|
|
|
createNewChatThread,
|
|
|
|
|
isLoading,
|
|
|
|
|
};
|
|
|
|
|
}
|