feat: add ability to share chats (#594)
This commit is contained in:
parent
64d1aad2bb
commit
4d901ba066
20 changed files with 877 additions and 66 deletions
62
hooks/use-chat-visibility.ts
Normal file
62
hooks/use-chat-visibility.ts
Normal file
|
|
@ -0,0 +1,62 @@
|
|||
'use client';
|
||||
|
||||
import { updateChatVisibility } from '@/app/(chat)/actions';
|
||||
import { VisibilityType } from '@/components/visibility-selector';
|
||||
import { Chat } from '@/lib/db/schema';
|
||||
import { useMemo } from 'react';
|
||||
import useSWR, { useSWRConfig } from 'swr';
|
||||
|
||||
export function useChatVisibility({
|
||||
chatId,
|
||||
initialVisibility,
|
||||
}: {
|
||||
chatId: string;
|
||||
initialVisibility: VisibilityType;
|
||||
}) {
|
||||
const { mutate, cache } = useSWRConfig();
|
||||
const history: Array<Chat> = cache.get('/api/history')?.data;
|
||||
|
||||
const { data: localVisibility, mutate: setLocalVisibility } = useSWR(
|
||||
`${chatId}-visibility`,
|
||||
null,
|
||||
{
|
||||
fallbackData: initialVisibility,
|
||||
},
|
||||
);
|
||||
|
||||
const visibilityType = useMemo(() => {
|
||||
if (!history) return localVisibility;
|
||||
const chat = history.find((chat) => chat.id === chatId);
|
||||
if (!chat) return 'private';
|
||||
return chat.visibility;
|
||||
}, [history, chatId, localVisibility]);
|
||||
|
||||
const setVisibilityType = (updatedVisibilityType: VisibilityType) => {
|
||||
setLocalVisibility(updatedVisibilityType);
|
||||
|
||||
mutate<Array<Chat>>(
|
||||
'/api/history',
|
||||
(history) => {
|
||||
return history
|
||||
? history.map((chat) => {
|
||||
if (chat.id === chatId) {
|
||||
return {
|
||||
...chat,
|
||||
visibility: updatedVisibilityType,
|
||||
};
|
||||
}
|
||||
return chat;
|
||||
})
|
||||
: [];
|
||||
},
|
||||
{ revalidate: false },
|
||||
);
|
||||
|
||||
updateChatVisibility({
|
||||
chatId: chatId,
|
||||
visibility: updatedVisibilityType,
|
||||
});
|
||||
};
|
||||
|
||||
return { visibilityType, setVisibilityType };
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue