Skip to content

Commit

Permalink
fix: implement change requests
Browse files Browse the repository at this point in the history
  • Loading branch information
ahmtslmngcl committed Dec 15, 2024
1 parent e844b45 commit 5823e9b
Show file tree
Hide file tree
Showing 8 changed files with 63 additions and 56 deletions.
26 changes: 13 additions & 13 deletions src/app/providers.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,19 +29,19 @@ export function Providers({ children, themeProps }: ProvidersProps) {
<NextUIProvider navigate={router.push}>
<NextThemesProvider defaultTheme="system" {...themeProps}>
<QueryClientProvider client={cachedQueryClient}>
<ChatbotProvider>
<SidebarProvider>
<SelectedMapProvider>
<SelectedAlertProvider>
<SelectedCountryIdProvider>
<AccordionsModalProvider>
<SnackbarProvider>{children}</SnackbarProvider>
</AccordionsModalProvider>
</SelectedCountryIdProvider>
</SelectedAlertProvider>
</SelectedMapProvider>
</SidebarProvider>
</ChatbotProvider>
<SidebarProvider>
<SelectedMapProvider>
<SelectedAlertProvider>
<SelectedCountryIdProvider>
<AccordionsModalProvider>
<SnackbarProvider>
<ChatbotProvider>{children}</ChatbotProvider>
</SnackbarProvider>
</AccordionsModalProvider>
</SelectedCountryIdProvider>
</SelectedAlertProvider>
</SelectedMapProvider>
</SidebarProvider>
<ReactQueryDevtools initialIsOpen={false} />
</QueryClientProvider>
</NextThemesProvider>
Expand Down
7 changes: 1 addition & 6 deletions src/components/Chatbot/Chatbot.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -302,16 +302,11 @@ export default function HungerMapChatbot() {
)}
<div
className={clsx(
'mb-5 rounded-lg max-w-[80%]',
'mb-5 rounded-lg max-w-[80%] break-words whitespace-normal',
message.role === SenderRole.USER
? 'rounded-xl p-2 bg-chatbotUserMsg dark:bg-chatbotUserMsg ml-12'
: 'bg-transparent pl-2 pr-2'
)}
style={{
wordWrap: 'break-word',
overflowWrap: 'break-word',
whiteSpace: 'normal',
}}
>
{message.role === SenderRole.USER ? (
<p className="break-words text-justify">{message.content}</p>
Expand Down
5 changes: 4 additions & 1 deletion src/components/DownloadPortal/CountryReports.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@ export default function CountryReports({ countryCodesData }: CountryReportsProps
const [error, setError] = useState<string | null>(null);
const [selectedCountry, setSelectedCountry] = useState<CountryCodesData | null>(null);

const chatBot = useChatbot();
const { initiateChatAboutReport } = chatBot;

const toggleModal = () => setModalOpen((prev) => !prev);

const filteredData = useMemo(() => {
Expand All @@ -34,7 +37,7 @@ export default function CountryReports({ countryCodesData }: CountryReportsProps
data={DownloadPortalOperations.formatTableData(
filteredData,
setSelectedCountry,
useChatbot().chatWithReport,
initiateChatAboutReport,
setPdfFile,
setError,
toggleModal
Expand Down
7 changes: 5 additions & 2 deletions src/components/Topbar/Topbar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ export function Topbar() {
return (
<Navbar onMenuOpenChange={setIsMenuOpen} maxWidth="full" className="fixed pr-10">
<NavbarContent className="flex-1 min-w-[200px] mt-4">
<NavbarMenuToggle aria-label={isMenuOpen ? 'Close menu' : 'Open menu'} className="md:hidden" />
<NavbarMenuToggle aria-label={isMenuOpen ? 'Close menu' : 'Open menu'} className="lg:hidden" />
<NavbarBrand>
<LogoWithText />
</NavbarBrand>
Expand All @@ -38,7 +38,7 @@ export function Topbar() {
</NavbarItem>
))}
</NavbarContent>
<NavbarContent justify="end" className="space-x-7">
<NavbarContent justify="end" className="hidden lg:flex space-x-7">
<NavbarItem className="mt-4">
<ThemeSwitch isIconOnly />
</NavbarItem>
Expand All @@ -56,6 +56,9 @@ export function Topbar() {
</Link>
</NavbarMenuItem>
))}
<NavbarMenuItem className="mt-4">
<ThemeSwitch isIconOnly />
</NavbarMenuItem>
</NavbarMenu>
</Navbar>
);
Expand Down
14 changes: 8 additions & 6 deletions src/domain/contexts/ChatbotContext.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import React, { createContext, ReactNode, useContext, useEffect, useMemo, useState } from 'react';

import { useSnackbar } from '@/domain/contexts/SnackbarContext';
import { IChat } from '@/domain/entities/chatbot/Chatbot';
import { SenderRole } from '@/domain/enums/SenderRole';
import ChatbotOperations from '@/operations/chatbot/Chatbot';
Expand All @@ -12,7 +13,7 @@ interface ChatbotContextType {
setCurrentChatIndex: React.Dispatch<React.SetStateAction<number>>;
openChat: (chatIndex: number) => void;
startNewChat: (newChat?: IChat) => void;
chatWithReport: (countryName: string, report: string) => Promise<void>;
initiateChatAboutReport: (countryName: string, report: string) => Promise<void>;
isOpen: boolean;
isMobile: boolean;
isSidebarOpen: boolean;
Expand All @@ -28,13 +29,14 @@ export function ChatbotProvider({ children }: { children: ReactNode }) {
const isMobile = useMediaQuery('(max-width: 640px)');
const [isSidebarOpen, setIsSidebarOpen] = useState(false);
const [chats, setChats] = useState<IChat[]>(ChatbotOperations.loadChatsFromStorage());
const { showSnackBar } = useSnackbar();

/**
* Saves chats to localStorage whenever they change
*/
useEffect(() => {
ChatbotOperations.saveChatsToStorage(chats);
}, [chats]);
ChatbotOperations.saveChatsToStorage(chats, showSnackBar);
}, [chats, showSnackBar]);

const openChat = (chatIndex: number) => {
setCurrentChatIndex(chatIndex);
Expand Down Expand Up @@ -83,7 +85,7 @@ export function ChatbotProvider({ children }: { children: ReactNode }) {
* @param countryName - The name of the country related to the report.
* @param reportURL - The URL of the report to be processed.
*/
const chatWithReport = async (countryName: string, reportURL: string) => {
const initiateChatAboutReport = async (countryName: string, reportURL: string) => {
const reportChatIndex = chats.findIndex((chat) => chat.title === `Report ${countryName}`);
const reportChatExists = reportChatIndex !== -1;

Expand All @@ -95,7 +97,7 @@ export function ChatbotProvider({ children }: { children: ReactNode }) {
const { extractPdfText } = await import('@/operations/chatbot/ExtractPdfText');
let reportText;
try {
reportText = await extractPdfText(reportURL);
reportText = await extractPdfText(reportURL, showSnackBar);
} catch {
reportText = '';
}
Expand Down Expand Up @@ -129,7 +131,7 @@ export function ChatbotProvider({ children }: { children: ReactNode }) {
setCurrentChatIndex,
startNewChat,
openChat,
chatWithReport,
initiateChatAboutReport,
isOpen,
isMobile,
isSidebarOpen,
Expand Down
39 changes: 14 additions & 25 deletions src/operations/chatbot/Chatbot.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
import { IChat } from '@/domain/entities/chatbot/Chatbot';
import { SNACKBAR_SHORT_DURATION } from '@/domain/entities/snackbar/Snackbar';
import { SenderRole } from '@/domain/enums/SenderRole';
import { SnackbarPosition, SnackbarStatus } from '@/domain/enums/Snackbar';
import { SnackbarProps } from '@/domain/props/SnackbarProps';

export default class ChatbotOperations {
static processInput(submitEvent: React.FormEvent, chats: IChat[], currentChatIndex: number, text: string): IChat[] {
Expand Down Expand Up @@ -33,34 +36,13 @@ export default class ChatbotOperations {
// Clean up localStorage by saving only the chats that are not older than 1 Week
localStorage.setItem('chatbotChatsWithTimestamp', JSON.stringify(recentChats));

// If no recent chats, return default chat
if (recentChats.length === 0) {
return [
{
id: 1,
title: 'Chat 1',
messages: [],
isTyping: false,
timestamp: currentTime,
},
];
if (recentChats.length !== 0) {
return recentChats;
}

return recentChats;
}

// If no stored data, return default chat
return [
{
id: 1,
title: 'Chat 1',
messages: [],
isTyping: false,
timestamp: Date.now(),
},
];
}

// Return default chat if no recent chats are found
return [
{
id: 1,
Expand All @@ -72,14 +54,21 @@ export default class ChatbotOperations {
];
}

static saveChatsToStorage(chats: IChat[]): void {
static saveChatsToStorage(chats: IChat[], showSnackBar: (snackbarProps: SnackbarProps) => void): void {
if (typeof window !== 'undefined') {
const chatsWithTimestamp = chats.map((chat) => ({
...chat,
timestamp: chat.timestamp || Date.now(),
}));

localStorage.setItem('chatbotChatsWithTimestamp', JSON.stringify(chatsWithTimestamp));
} else {
showSnackBar({
message: 'Unable to save chats.',
status: SnackbarStatus.Error,
position: SnackbarPosition.BottomRight,
duration: SNACKBAR_SHORT_DURATION,
});
}
}
}
17 changes: 16 additions & 1 deletion src/operations/chatbot/ExtractPdfText.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@

import { pdfjs } from 'react-pdf';

import { SNACKBAR_SHORT_DURATION } from '@/domain/entities/snackbar/Snackbar';
import { SnackbarPosition, SnackbarStatus } from '@/domain/enums/Snackbar';
import { SnackbarProps } from '@/domain/props/SnackbarProps';

pdfjs.GlobalWorkerOptions.workerSrc = `//cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjs.version}/pdf.worker.min.mjs`;

/**
Expand All @@ -12,7 +16,10 @@ pdfjs.GlobalWorkerOptions.workerSrc = `//cdnjs.cloudflare.com/ajax/libs/pdf.js/$
* @param url - The URL of the PDF document to extract text from.
* @returns A promise that resolves to the extracted text or undefined if an error occurs.
*/
export const extractPdfText = async (url: string): Promise<string> => {
export const extractPdfText = async (
url: string,
showSnackBar?: (snackbarProps: SnackbarProps) => void
): Promise<string> => {
try {
const pdf = await pdfjs.getDocument(url).promise;
let fullText = '';
Expand All @@ -39,6 +46,14 @@ export const extractPdfText = async (url: string): Promise<string> => {

return fullText.trim();
} catch (error) {
if (showSnackBar) {
showSnackBar({
message: 'Error extracting information from PDF',
status: SnackbarStatus.Error,
position: SnackbarPosition.BottomRight,
duration: SNACKBAR_SHORT_DURATION,
});
}
throw new Error(`Error extracting text from PDF: ${error}`);
}
};
4 changes: 2 additions & 2 deletions src/operations/download-portal/DownloadPortalOperations.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ export class DownloadPortalOperations {
static formatTableData(
data: CountryCodesData[],
setSelectedCountry: (countryData: CountryCodesData) => void,
chatWithReport: (country: string, report: string) => Promise<void>,
initiateChatAboutReport: (country: string, report: string) => Promise<void>,
setPdfFile: (file: Blob | null) => void,
setError: (error: string | null) => void,
toggleModal: () => void
Expand Down Expand Up @@ -50,7 +50,7 @@ export class DownloadPortalOperations {
<div className="flex justify-center items-center">
<Bot
size={20}
onClick={() => chatWithReport(item.country.name, item.url.summary)}
onClick={() => initiateChatAboutReport(item.country.name, item.url.summary)}
className="cursor-pointer"
/>
</div>
Expand Down

0 comments on commit 5823e9b

Please sign in to comment.