-
Notifications
You must be signed in to change notification settings - Fork 35
Expand file tree
/
Copy pathChatbotDisplayMode.tsx
More file actions
464 lines (431 loc) · 15.7 KB
/
Copy pathChatbotDisplayMode.tsx
File metadata and controls
464 lines (431 loc) · 15.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
import React, { FunctionComponent, MouseEvent, useEffect, useRef, useState } from 'react';
import {
Brand,
DropdownList,
DropdownItem,
Page,
Masthead,
MastheadMain,
MastheadBrand,
MastheadLogo,
PageSidebarBody,
PageSidebar,
MastheadToggle,
PageToggleButton,
SkipToContent,
Drawer,
DrawerContent,
DrawerContentBody,
DrawerPanelContent,
DropdownGroup
} from '@patternfly/react-core';
import ChatbotToggle from '@patternfly/chatbot/dist/dynamic/ChatbotToggle';
import Chatbot, { ChatbotDisplayMode } from '@patternfly/chatbot/dist/dynamic/Chatbot';
import ChatbotContent from '@patternfly/chatbot/dist/dynamic/ChatbotContent';
import ChatbotWelcomePrompt from '@patternfly/chatbot/dist/dynamic/ChatbotWelcomePrompt';
import ChatbotFooter, { ChatbotFootnote } from '@patternfly/chatbot/dist/dynamic/ChatbotFooter';
import MessageBar from '@patternfly/chatbot/dist/dynamic/MessageBar';
import MessageBox from '@patternfly/chatbot/dist/dynamic/MessageBox';
import Message, { MessageProps } from '@patternfly/chatbot/dist/dynamic/Message';
import ChatbotConversationHistoryNav, {
Conversation
} from '@patternfly/chatbot/dist/dynamic/ChatbotConversationHistoryNav';
import ChatbotHeader, {
ChatbotHeaderMenu,
ChatbotHeaderMain,
ChatbotHeaderTitle,
ChatbotHeaderActions,
ChatbotHeaderSelectorDropdown,
ChatbotHeaderOptionsDropdown,
ChatbotHeaderCloseButton
} from '@patternfly/chatbot/dist/dynamic/ChatbotHeader';
import PFIconLogoColor from '../UI/PF-IconLogo-Color.svg';
import PFIconLogoReverse from '../UI/PF-IconLogo-Reverse.svg';
import { RhUiMenuBarsIcon } from '@patternfly/react-icons';
import ExpandIcon from '@patternfly/react-icons/dist/esm/icons/expand-icon';
import OpenDrawerRightIcon from '@patternfly/react-icons/dist/esm/icons/open-drawer-right-icon';
import OutlinedWindowRestoreIcon from '@patternfly/react-icons/dist/esm/icons/outlined-window-restore-icon';
import userAvatar from '../Messages/user_avatar.svg';
import '@patternfly/react-core/dist/styles/base.css';
import '@patternfly/chatbot/dist/css/main.css';
const footnoteProps = {
label: 'Always review AI-generated content prior to use.'
};
const markdown = `A paragraph with *emphasis* and **strong importance**.`;
const date = new Date();
const initialMessages: MessageProps[] = [
{
id: '1',
role: 'user',
content: 'Hello, can you give me an example of what you can do?',
name: 'User',
avatar: userAvatar,
timestamp: date.toLocaleString(),
avatarProps: { isBordered: true }
},
{
id: '2',
role: 'bot',
content: markdown,
name: 'Bot',
timestamp: date.toLocaleString(),
actions: {
// eslint-disable-next-line no-console
positive: { onClick: () => console.log('Good response') },
// eslint-disable-next-line no-console
negative: { onClick: () => console.log('Bad response') },
// eslint-disable-next-line no-console
copy: { onClick: () => console.log('Copy') },
// eslint-disable-next-line no-console
download: { onClick: () => console.log('Download') },
// eslint-disable-next-line no-console
listen: { onClick: () => console.log('Listen') }
}
}
];
const welcomePrompts = [
{
title: 'Topic 1',
message: 'Helpful prompt for Topic 1'
},
{
title: 'Topic 2',
message: 'Helpful prompt for Topic 2'
}
];
const initialConversations = {
Today: [{ id: '1', text: 'Hello, can you give me an example of what you can do?' }],
'This month': [
{
id: '2',
text: 'Enterprise Linux installation and setup'
}
]
};
export const ChatbotDisplayModeDemo: FunctionComponent = () => {
const [messages, setMessages] = useState<MessageProps[]>(initialMessages);
const [selectedModel, setSelectedModel] = useState('Granite 7B');
const [isSendButtonDisabled, setIsSendButtonDisabled] = useState(false);
const [isDrawerOpen, setIsDrawerOpen] = useState(false);
const [conversations, setConversations] = useState<Conversation[] | { [key: string]: Conversation[] }>(
initialConversations
);
const [isSidebarOpen, setIsSidebarOpen] = useState(false);
const [announcement, setAnnouncement] = useState<string>();
const scrollToBottomRef = useRef<HTMLDivElement>(null);
const historyRef = useRef<HTMLButtonElement>(null);
const drawerRef = useRef<HTMLDivElement>();
const [chatbotVisible, setChatbotVisible] = useState<boolean>(true);
const toggleRef = useRef<HTMLButtonElement>(null);
const chatbotRef = useRef<HTMLDivElement>(null);
const [shouldFocusOptions, setShouldFocusOptions] = useState(false);
const [displayMode, setDisplayMode] = useState<ChatbotDisplayMode>(ChatbotDisplayMode.default);
const isDrawerPanelExpanded = displayMode === ChatbotDisplayMode.drawer;
const onExpand = () => {
drawerRef.current && drawerRef.current.focus();
};
useEffect(() => {
if (messages.length > 2) {
scrollToBottomRef.current?.scrollIntoView({ behavior: 'smooth' });
}
}, [messages]);
// Focus options dropdown after display mode changes
useEffect(() => {
if (shouldFocusOptions) {
// Use a more reliable timeout to ensure DOM has updated
const timeoutId = setTimeout(() => {
// Find the options dropdown button via CSS selector since ref forwarding isn't supported
const optionsButton = document.querySelector('.pf-chatbot__button--toggle-options');
if (optionsButton instanceof HTMLElement) {
optionsButton.focus();
}
setShouldFocusOptions(false);
}, 100);
return () => clearTimeout(timeoutId);
}
}, [displayMode, shouldFocusOptions]);
const onSelectModel = (_event: MouseEvent<Element, MouseEvent> | undefined, value: string | number | undefined) => {
setSelectedModel(value as string);
};
const onSelectDisplayMode = (
_event: MouseEvent<Element, MouseEvent> | undefined,
value: string | number | undefined
) => {
setDisplayMode(value as ChatbotDisplayMode);
// Flag to focus options dropdown after render
setShouldFocusOptions(true);
};
const generateId = () => {
const id = Date.now() + Math.random();
return id.toString();
};
const handleSend = (message: string) => {
setIsSendButtonDisabled(true);
const newMessages: MessageProps[] = [...messages];
const date = new Date();
newMessages.push({
id: generateId(),
role: 'user',
content: message,
name: 'User',
avatar: userAvatar,
timestamp: date.toLocaleString(),
avatarProps: { isBordered: true }
});
newMessages.push({
id: generateId(),
role: 'bot',
content: 'API response goes here',
name: 'Bot',
isLoading: true,
timestamp: date.toLocaleString()
});
setMessages(newMessages);
setAnnouncement(`Message from User: ${message}. Message from Bot is loading.`);
setTimeout(() => {
const loadedMessages: MessageProps[] = [...newMessages];
loadedMessages.pop();
loadedMessages.push({
id: generateId(),
role: 'bot',
content: 'API response goes here',
name: 'Bot',
isLoading: false,
actions: {
// eslint-disable-next-line no-console
positive: { onClick: () => console.log('Good response') },
// eslint-disable-next-line no-console
negative: { onClick: () => console.log('Bad response') },
// eslint-disable-next-line no-console
copy: { onClick: () => console.log('Copy') },
// eslint-disable-next-line no-console
download: { onClick: () => console.log('Download') },
// eslint-disable-next-line no-console
listen: { onClick: () => console.log('Listen') }
},
timestamp: date.toLocaleString()
});
setMessages(loadedMessages);
setAnnouncement(`Message from Bot: API response goes here`);
setIsSendButtonDisabled(false);
}, 2000);
};
const findMatchingItems = (targetValue: string) => {
let filteredConversations = Object.entries(initialConversations).reduce((acc, [key, items]) => {
const filteredItems = items.filter((item) => item.text.toLowerCase().includes(targetValue.toLowerCase()));
if (filteredItems.length > 0) {
acc[key] = filteredItems;
}
return acc;
}, {});
if (Object.keys(filteredConversations).length === 0) {
filteredConversations = [{ id: '13', noIcon: true, text: 'No results found' }];
}
return filteredConversations;
};
const iconLogo = (
<>
<Brand className="show-light" src={PFIconLogoColor} alt="PatternFly" />
<Brand className="show-dark" src={PFIconLogoReverse} alt="PatternFly" />
</>
);
const masthead = (
<Masthead>
<MastheadMain>
<MastheadToggle>
<PageToggleButton
variant="plain"
aria-label="Global navigation"
isSidebarOpen={isSidebarOpen}
onSidebarToggle={() => setIsSidebarOpen(!isSidebarOpen)}
id="fill-nav-toggle"
>
<RhUiMenuBarsIcon />
</PageToggleButton>
</MastheadToggle>
<MastheadBrand>
<MastheadLogo href="https://patternfly.org" target="_blank">
Logo
</MastheadLogo>
</MastheadBrand>
</MastheadMain>
</Masthead>
);
const sidebar = (
<PageSidebar isSidebarOpen={isSidebarOpen} id="fill-sidebar">
<PageSidebarBody>Navigation</PageSidebarBody>
</PageSidebar>
);
const skipToChatbot = (e: MouseEvent) => {
e.preventDefault();
/* eslint-disable indent */
switch (displayMode) {
case ChatbotDisplayMode.default:
if (!chatbotVisible && toggleRef.current) {
toggleRef.current.focus();
}
if (chatbotVisible && chatbotRef.current) {
chatbotRef.current.focus();
}
break;
default:
if (historyRef.current) {
historyRef.current.focus();
}
break;
}
/* eslint-enable indent */
};
const skipToContent = (
<SkipToContent href="#" onClick={skipToChatbot}>
Skip to chatbot
</SkipToContent>
);
const handleChatbotVisibilityDrawer = () => {
setChatbotVisible(!chatbotVisible);
setDisplayMode(ChatbotDisplayMode.default);
};
const chatbotComponent = (
<Chatbot isVisible={chatbotVisible} displayMode={displayMode} ref={chatbotRef}>
<ChatbotConversationHistoryNav
displayMode={displayMode}
onDrawerToggle={() => {
setIsDrawerOpen(!isDrawerOpen);
setConversations(initialConversations);
}}
isDrawerOpen={isDrawerOpen}
setIsDrawerOpen={setIsDrawerOpen}
activeItemId="1"
conversations={conversations}
onNewChat={() => {
setIsDrawerOpen(!isDrawerOpen);
setMessages([]);
setConversations(initialConversations);
}}
handleTextInputChange={(value: string) => {
if (value === '') {
setConversations(initialConversations);
}
const newConversations: { [key: string]: Conversation[] } = findMatchingItems(value);
setConversations(newConversations);
}}
drawerContent={
<>
<ChatbotHeader>
<ChatbotHeaderMain>
<ChatbotHeaderMenu
ref={historyRef}
aria-expanded={isDrawerOpen}
onMenuToggle={() => setIsDrawerOpen(!isDrawerOpen)}
/>
<ChatbotHeaderTitle>{iconLogo}</ChatbotHeaderTitle>
</ChatbotHeaderMain>
<ChatbotHeaderActions>
<ChatbotHeaderSelectorDropdown value={selectedModel} onSelect={onSelectModel}>
<DropdownList>
<DropdownItem value="Granite 7B" key="granite">
Granite 7B
</DropdownItem>
<DropdownItem value="Llama 3.0" key="llama">
Llama 3.0
</DropdownItem>
</DropdownList>
</ChatbotHeaderSelectorDropdown>
<ChatbotHeaderOptionsDropdown onSelect={onSelectDisplayMode}>
<DropdownGroup label="Display mode">
<DropdownList>
<DropdownItem
value={ChatbotDisplayMode.default}
key="switchDisplayOverlay"
icon={<OutlinedWindowRestoreIcon aria-hidden />}
isSelected={displayMode === ChatbotDisplayMode.default}
>
<span>Overlay</span>
</DropdownItem>
<DropdownItem
value={ChatbotDisplayMode.drawer}
key="switchDisplayDock"
icon={<OpenDrawerRightIcon aria-hidden />}
isSelected={displayMode === ChatbotDisplayMode.drawer}
>
<span>Drawer</span>
</DropdownItem>
<DropdownItem
value={ChatbotDisplayMode.fullscreen}
key="switchDisplayFullscreen"
icon={<ExpandIcon aria-hidden />}
isSelected={displayMode === ChatbotDisplayMode.fullscreen}
>
<span>Fullscreen</span>
</DropdownItem>
</DropdownList>
</DropdownGroup>
</ChatbotHeaderOptionsDropdown>
{(displayMode === ChatbotDisplayMode.drawer || displayMode === ChatbotDisplayMode.fullscreen) && (
<ChatbotHeaderCloseButton onClick={handleChatbotVisibilityDrawer} />
)}
</ChatbotHeaderActions>
</ChatbotHeader>
<ChatbotContent>
<MessageBox announcement={announcement}>
<ChatbotWelcomePrompt
title="Hello, Chatbot User"
description="How may I help you today?"
prompts={welcomePrompts}
/>
{messages.map((message, index) => {
if (index === messages.length - 1) {
return (
<React.Fragment key={message.id}>
<div ref={scrollToBottomRef}></div>
<Message {...message} />
</React.Fragment>
);
}
return <Message key={message.id} {...message} />;
})}
</MessageBox>
</ChatbotContent>
<ChatbotFooter>
<MessageBar onSendMessage={handleSend} hasMicrophoneButton isSendButtonDisabled={isSendButtonDisabled} />
<ChatbotFootnote {...footnoteProps} />
</ChatbotFooter>
</>
}
/>
</Chatbot>
);
const chatbotToggle =
displayMode === ChatbotDisplayMode.default ? (
<ChatbotToggle
tooltipLabel="Chatbot"
isChatbotVisible={chatbotVisible}
onToggleChatbot={() => {
setChatbotVisible(!chatbotVisible);
}}
id="chatbot-toggle"
ref={toggleRef}
/>
) : null;
const panelContent = <DrawerPanelContent>{chatbotComponent}</DrawerPanelContent>;
const pageContent = (
<Page skipToContent={skipToContent} masthead={masthead} sidebar={sidebar} isContentFilled>
{displayMode === ChatbotDisplayMode.default && chatbotToggle}
</Page>
);
if (displayMode === ChatbotDisplayMode.drawer) {
return (
<Drawer isExpanded={isDrawerPanelExpanded} isInline onExpand={onExpand}>
<DrawerContent panelContent={panelContent}>
<DrawerContentBody>{pageContent}</DrawerContentBody>
</DrawerContent>
</Drawer>
);
}
return (
<>
{pageContent}
{chatbotComponent}
</>
);
};