@patternfly/chatbot 6.3.0-prerelease.14 → 6.3.0-prerelease.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,536 @@
1
+ import React from 'react';
2
+
3
+ import { Bullseye, Brand, DropdownList, DropdownItem, DropdownGroup, SkipToContent } from '@patternfly/react-core';
4
+
5
+ import ChatbotToggle from '@patternfly/chatbot/dist/dynamic/ChatbotToggle';
6
+ import Chatbot, { ChatbotDisplayMode } from '@patternfly/chatbot/dist/dynamic/Chatbot';
7
+ import ChatbotContent from '@patternfly/chatbot/dist/dynamic/ChatbotContent';
8
+ import ChatbotWelcomePrompt from '@patternfly/chatbot/dist/dynamic/ChatbotWelcomePrompt';
9
+ import ChatbotFooter, { ChatbotFootnote } from '@patternfly/chatbot/dist/dynamic/ChatbotFooter';
10
+ import MessageBar from '@patternfly/chatbot/dist/dynamic/MessageBar';
11
+ import MessageBox, { MessageBoxHandle } from '@patternfly/chatbot/dist/dynamic/MessageBox';
12
+ import Message, { MessageProps } from '@patternfly/chatbot/dist/dynamic/Message';
13
+ import ChatbotConversationHistoryNav, {
14
+ Conversation
15
+ } from '@patternfly/chatbot/dist/dynamic/ChatbotConversationHistoryNav';
16
+ import ChatbotHeader, {
17
+ ChatbotHeaderMenu,
18
+ ChatbotHeaderMain,
19
+ ChatbotHeaderTitle,
20
+ ChatbotHeaderActions,
21
+ ChatbotHeaderSelectorDropdown,
22
+ ChatbotHeaderOptionsDropdown
23
+ } from '@patternfly/chatbot/dist/dynamic/ChatbotHeader';
24
+
25
+ import ExpandIcon from '@patternfly/react-icons/dist/esm/icons/expand-icon';
26
+ import OpenDrawerRightIcon from '@patternfly/react-icons/dist/esm/icons/open-drawer-right-icon';
27
+ import OutlinedWindowRestoreIcon from '@patternfly/react-icons/dist/esm/icons/outlined-window-restore-icon';
28
+
29
+ import PFHorizontalLogoColor from '../UI/PF-HorizontalLogo-Color.svg';
30
+ import PFHorizontalLogoReverse from '../UI/PF-HorizontalLogo-Reverse.svg';
31
+ import PFIconLogoColor from '../UI/PF-IconLogo-Color.svg';
32
+ import PFIconLogoReverse from '../UI/PF-IconLogo-Reverse.svg';
33
+ import userAvatar from '../Messages/user_avatar.svg';
34
+ import patternflyAvatar from '../Messages/patternfly_avatar.jpg';
35
+ import '@patternfly/react-core/dist/styles/base.css';
36
+ import '@patternfly/chatbot/dist/css/main.css';
37
+
38
+ const footnoteProps = {
39
+ label: 'ChatBot uses AI. Check for mistakes.',
40
+ popover: {
41
+ title: 'Verify information',
42
+ description: `While ChatBot strives for accuracy, AI is experimental and can make mistakes. We cannot guarantee that all information provided by ChatBot is up to date or without error. You should always verify responses using reliable sources, especially for crucial information and decision making.`,
43
+ bannerImage: {
44
+ src: 'https://cdn.dribbble.com/userupload/10651749/file/original-8a07b8e39d9e8bf002358c66fce1223e.gif',
45
+ alt: 'Example image for footnote popover'
46
+ },
47
+ cta: {
48
+ label: 'Dismiss',
49
+ onClick: () => {
50
+ alert('Do something!');
51
+ }
52
+ },
53
+ link: {
54
+ label: 'View AI policy',
55
+ url: 'https://www.redhat.com/'
56
+ }
57
+ }
58
+ };
59
+
60
+ const markdown = `A paragraph with *emphasis* and **strong importance**.
61
+
62
+ > A block quote with ~strikethrough~ and a URL: https://reactjs.org.
63
+
64
+ Here is an inline code - \`() => void\`
65
+
66
+ Here is some YAML code:
67
+
68
+ ~~~yaml
69
+ apiVersion: helm.openshift.io/v1beta1/
70
+ kind: HelmChartRepository
71
+ metadata:
72
+ name: azure-sample-repo0oooo00ooo
73
+ spec:
74
+ connectionConfig:
75
+ url: https://raw.githubusercontent.com/Azure-Samples/helm-charts/master/docs
76
+ ~~~
77
+
78
+ Here is some JavaScript code:
79
+
80
+ ~~~js
81
+ import React from 'react';
82
+
83
+ const MessageLoading = () => (
84
+ <div className="pf-chatbot__message-loading">
85
+ <span className="pf-chatbot__message-loading-dots">
86
+ <span className="pf-v6-screen-reader">Loading message</span>
87
+ </span>
88
+ </div>
89
+ );
90
+
91
+ export default MessageLoading;
92
+
93
+ ~~~
94
+ `;
95
+
96
+ // It's important to set a date and timestamp prop since the Message components re-render.
97
+ // The timestamps re-render with them.
98
+ const date = new Date();
99
+
100
+ const initialMessages: MessageProps[] = [
101
+ {
102
+ id: '1',
103
+ role: 'user',
104
+ content: 'Hello, can you give me an example of what you can do?',
105
+ name: 'User',
106
+ avatar: userAvatar,
107
+ timestamp: date.toLocaleString(),
108
+ avatarProps: { isBordered: true }
109
+ },
110
+ {
111
+ id: '2',
112
+ role: 'bot',
113
+ content: markdown,
114
+ name: 'Bot',
115
+ avatar: patternflyAvatar,
116
+ timestamp: date.toLocaleString(),
117
+ actions: {
118
+ // eslint-disable-next-line no-console
119
+ positive: { onClick: () => console.log('Good response') },
120
+ // eslint-disable-next-line no-console
121
+ negative: { onClick: () => console.log('Bad response') },
122
+ // eslint-disable-next-line no-console
123
+ copy: { onClick: () => console.log('Copy') },
124
+ // eslint-disable-next-line no-console
125
+ share: { onClick: () => console.log('Share') },
126
+ // eslint-disable-next-line no-console
127
+ listen: { onClick: () => console.log('Listen') }
128
+ }
129
+ }
130
+ ];
131
+
132
+ const welcomePrompts = [
133
+ {
134
+ title: 'Set up account',
135
+ message: 'Choose the necessary settings and preferences for your account.'
136
+ },
137
+ {
138
+ title: 'Troubleshoot issue',
139
+ message: 'Find documentation and instructions to resolve your issue.'
140
+ }
141
+ ];
142
+
143
+ const initialConversations = {
144
+ Today: [{ id: '1', text: 'Hello, can you give me an example of what you can do?' }],
145
+ 'This month': [
146
+ {
147
+ id: '2',
148
+ text: 'Enterprise Linux installation and setup'
149
+ },
150
+ { id: '3', text: 'Troubleshoot system crash' }
151
+ ],
152
+ March: [
153
+ { id: '4', text: 'Ansible security and updates' },
154
+ { id: '5', text: 'Red Hat certification' },
155
+ { id: '6', text: 'Lightspeed user documentation' }
156
+ ],
157
+ February: [
158
+ { id: '7', text: 'Crashing pod assistance' },
159
+ { id: '8', text: 'OpenShift AI pipelines' },
160
+ { id: '9', text: 'Updating subscription plan' },
161
+ { id: '10', text: 'Red Hat licensing options' }
162
+ ],
163
+ January: [
164
+ { id: '11', text: 'RHEL system performance' },
165
+ { id: '12', text: 'Manage user accounts' }
166
+ ]
167
+ };
168
+
169
+ export const ChatbotScrollingDemo: React.FunctionComponent = () => {
170
+ const [chatbotVisible, setChatbotVisible] = React.useState<boolean>(true);
171
+ const [displayMode, setDisplayMode] = React.useState<ChatbotDisplayMode>(ChatbotDisplayMode.default);
172
+ const [messages, setMessages] = React.useState<MessageProps[]>(initialMessages);
173
+ const [selectedModel, setSelectedModel] = React.useState('Granite 7B');
174
+ const [isSendButtonDisabled, setIsSendButtonDisabled] = React.useState(false);
175
+ const [isDrawerOpen, setIsDrawerOpen] = React.useState(false);
176
+ const [conversations, setConversations] = React.useState<Conversation[] | { [key: string]: Conversation[] }>(
177
+ initialConversations
178
+ );
179
+ const [announcement, setAnnouncement] = React.useState<string>();
180
+ const toggleRef = React.useRef<HTMLButtonElement>(null);
181
+ const chatbotRef = React.useRef<HTMLDivElement>(null);
182
+ const historyRef = React.useRef<HTMLButtonElement>(null);
183
+ const messageBoxRef = React.useRef<MessageBoxHandle>(null); // ref to MessageBox will have isSmartScrollActive, scrollToTop and scrollToBottom
184
+ const scrollQueued = React.useRef(false);
185
+
186
+ // Auto-scrolls to the latest message
187
+ React.useLayoutEffect(() => {
188
+ if (!messageBoxRef.current?.isSmartScrollActive() || scrollQueued.current) {
189
+ return undefined;
190
+ }
191
+
192
+ let rafId = 0;
193
+ // don't scroll the first load - in this demo, we know we start with two messages
194
+ if (messages.length > 2) {
195
+ scrollQueued.current = true;
196
+
197
+ rafId = requestAnimationFrame(() => {
198
+ messageBoxRef.current?.scrollToBottom();
199
+ scrollQueued.current = false;
200
+ });
201
+ }
202
+
203
+ return () => {
204
+ cancelAnimationFrame(rafId);
205
+ scrollQueued.current = false;
206
+ };
207
+ // To scroll to the top of latest message just once, Use messages.length as a dependency instead of messages.
208
+ }, [messages, messageBoxRef]);
209
+
210
+ const onSelectModel = (
211
+ _event: React.MouseEvent<Element, MouseEvent> | undefined,
212
+ value: string | number | undefined
213
+ ) => {
214
+ setSelectedModel(value as string);
215
+ };
216
+
217
+ const onSelectDisplayMode = (
218
+ _event: React.MouseEvent<Element, MouseEvent> | undefined,
219
+ value: string | number | undefined
220
+ ) => {
221
+ setDisplayMode(value as ChatbotDisplayMode);
222
+ };
223
+
224
+ // you will likely want to come up with your own unique id function; this is for demo purposes only
225
+ const generateId = () => {
226
+ const id = Date.now() + Math.random();
227
+ return id.toString();
228
+ };
229
+
230
+ const handleSend = (message) => {
231
+ setIsSendButtonDisabled(true);
232
+ const newMessages: MessageProps[] = [];
233
+ // We can't use structuredClone since messages contains functions, but we can't mutate
234
+ // items that are going into state or the UI won't update correctly
235
+ messages.forEach((message) => newMessages.push(message));
236
+ // It's important to set a timestamp prop since the Message components re-render.
237
+ // The timestamps re-render with them.
238
+ const date = new Date();
239
+ newMessages.push({
240
+ id: generateId(),
241
+ role: 'user',
242
+ content: message,
243
+ name: 'User',
244
+ avatar: userAvatar,
245
+ timestamp: date.toLocaleString(),
246
+ avatarProps: { isBordered: true }
247
+ });
248
+ newMessages.push({
249
+ id: generateId(),
250
+ role: 'bot',
251
+ content: 'API response goes here',
252
+ name: 'Bot',
253
+ isLoading: true,
254
+ avatar: patternflyAvatar,
255
+ timestamp: date.toLocaleString()
256
+ });
257
+ setMessages(newMessages);
258
+ messageBoxRef.current?.scrollToBottom();
259
+ // make announcement to assistive devices that new messages have been added
260
+ setAnnouncement(`Message from User: ${message}. Message from Bot is loading.`);
261
+
262
+ // this is for demo purposes only; in a real situation, there would be an API response we would wait for
263
+ setTimeout(() => {
264
+ const loadedMessages: MessageProps[] = [];
265
+ // We can't use structuredClone since messages contains functions, but we can't mutate
266
+ // items that are going into state or the UI won't update correctly
267
+ newMessages.forEach((message) => loadedMessages.push(message));
268
+ const messageIndex = loadedMessages.length - 1;
269
+ loadedMessages.pop();
270
+ loadedMessages.push({
271
+ id: generateId(),
272
+ role: 'bot',
273
+ content: 'API response goes here.',
274
+ name: 'Bot',
275
+ isLoading: false,
276
+ avatar: patternflyAvatar,
277
+ timestamp: date.toLocaleString(),
278
+ actions: {
279
+ // eslint-disable-next-line no-console
280
+ positive: { onClick: () => console.log('Good response') },
281
+ // eslint-disable-next-line no-console
282
+ negative: { onClick: () => console.log('Bad response') },
283
+ // eslint-disable-next-line no-console
284
+ copy: { onClick: () => console.log('Copy') },
285
+ // eslint-disable-next-line no-console
286
+ share: { onClick: () => console.log('Share') },
287
+ // eslint-disable-next-line no-console
288
+ listen: { onClick: () => console.log('Listen') }
289
+ }
290
+ });
291
+
292
+ const longMessage =
293
+ `It includes a long message. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore
294
+ magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
295
+ consequat. Duis aute irure dolor in reprehenderit in voluptatevelit esse cillum dolore eu fugiat nulla
296
+ pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id
297
+ est laborum.`.repeat(2);
298
+
299
+ const contentChunks = longMessage.split(' ');
300
+ let chunkIndex = 0;
301
+
302
+ setMessages(loadedMessages);
303
+
304
+ let accumulatedContent = '';
305
+ let lastUpdateTime = 0;
306
+ const interval = setInterval(() => {
307
+ if (chunkIndex < contentChunks.length) {
308
+ accumulatedContent += ` ${contentChunks[chunkIndex]}`;
309
+ chunkIndex++;
310
+
311
+ // Only update every 100 ms or every 10 chunks
312
+ const now = Date.now();
313
+ const shouldUpdate = now - lastUpdateTime > 100 || chunkIndex % 10 === 0;
314
+
315
+ if (shouldUpdate) {
316
+ const updatedMessages = loadedMessages.map((msg, i) => {
317
+ if (i === messageIndex) {
318
+ return {
319
+ ...msg,
320
+ content: msg.content + accumulatedContent
321
+ };
322
+ }
323
+ return msg;
324
+ });
325
+
326
+ setMessages(updatedMessages);
327
+ lastUpdateTime = now;
328
+ }
329
+ } else {
330
+ setIsSendButtonDisabled(false);
331
+ clearInterval(interval);
332
+ }
333
+ }, 50);
334
+
335
+ // Scrolls to the bottom of the message box and resumes auto-scrolling
336
+ messageBoxRef.current?.scrollToBottom({ resumeSmartScroll: true });
337
+ // make announcement to assistive devices that new message has loaded
338
+ setAnnouncement(`Message from Bot: API response goes here`);
339
+ }, 100);
340
+ };
341
+
342
+ const findMatchingItems = (targetValue: string) => {
343
+ let filteredConversations = Object.entries(initialConversations).reduce((acc, [key, items]) => {
344
+ const filteredItems = items.filter((item) => item.text.toLowerCase().includes(targetValue.toLowerCase()));
345
+ if (filteredItems.length > 0) {
346
+ acc[key] = filteredItems;
347
+ }
348
+ return acc;
349
+ }, {});
350
+
351
+ // append message if no items are found
352
+ if (Object.keys(filteredConversations).length === 0) {
353
+ filteredConversations = [{ id: '13', noIcon: true, text: 'No results found' }];
354
+ }
355
+ return filteredConversations;
356
+ };
357
+
358
+ const horizontalLogo = (
359
+ <Bullseye>
360
+ <Brand className="show-light" src={PFHorizontalLogoColor} alt="PatternFly" />
361
+ <Brand className="show-dark" src={PFHorizontalLogoReverse} alt="PatternFly" />
362
+ </Bullseye>
363
+ );
364
+
365
+ const iconLogo = (
366
+ <>
367
+ <Brand className="show-light" src={PFIconLogoColor} alt="PatternFly" />
368
+ <Brand className="show-dark" src={PFIconLogoReverse} alt="PatternFly" />
369
+ </>
370
+ );
371
+
372
+ const handleSkipToContent = (e) => {
373
+ e.preventDefault();
374
+ /* eslint-disable indent */
375
+ switch (displayMode) {
376
+ case ChatbotDisplayMode.default:
377
+ if (!chatbotVisible && toggleRef.current) {
378
+ toggleRef.current.focus();
379
+ }
380
+ if (chatbotVisible && chatbotRef.current) {
381
+ chatbotRef.current.focus();
382
+ }
383
+ break;
384
+
385
+ case ChatbotDisplayMode.docked:
386
+ if (chatbotRef.current) {
387
+ chatbotRef.current.focus();
388
+ }
389
+ break;
390
+ default:
391
+ if (historyRef.current) {
392
+ historyRef.current.focus();
393
+ }
394
+ break;
395
+ }
396
+ /* eslint-enable indent */
397
+ };
398
+
399
+ return (
400
+ <>
401
+ <SkipToContent onClick={handleSkipToContent} href="#">
402
+ Skip to chatbot
403
+ </SkipToContent>
404
+ <ChatbotToggle
405
+ tooltipLabel="Chatbot"
406
+ isChatbotVisible={chatbotVisible}
407
+ onToggleChatbot={function () {
408
+ setChatbotVisible(!chatbotVisible);
409
+ }}
410
+ id="chatbot-toggle"
411
+ ref={toggleRef}
412
+ />
413
+ <Chatbot isVisible={chatbotVisible} displayMode={displayMode} ref={chatbotRef}>
414
+ <ChatbotConversationHistoryNav
415
+ displayMode={displayMode}
416
+ onDrawerToggle={() => {
417
+ setIsDrawerOpen(!isDrawerOpen);
418
+ setConversations(initialConversations);
419
+ }}
420
+ isDrawerOpen={isDrawerOpen}
421
+ setIsDrawerOpen={setIsDrawerOpen}
422
+ activeItemId="1"
423
+ // eslint-disable-next-line no-console
424
+ onSelectActiveItem={(e, selectedItem) => console.log(`Selected history item with id ${selectedItem}`)}
425
+ conversations={conversations}
426
+ onNewChat={() => {
427
+ setIsDrawerOpen(!isDrawerOpen);
428
+ setMessages([]);
429
+ setConversations(initialConversations);
430
+ }}
431
+ handleTextInputChange={(value: string) => {
432
+ if (value === '') {
433
+ setConversations(initialConversations);
434
+ }
435
+ // this is where you would perform search on the items in the drawer
436
+ // and update the state
437
+ const newConversations: { [key: string]: Conversation[] } = findMatchingItems(value);
438
+ setConversations(newConversations);
439
+ }}
440
+ drawerContent={
441
+ <>
442
+ <ChatbotHeader>
443
+ <ChatbotHeaderMain>
444
+ <ChatbotHeaderMenu
445
+ ref={historyRef}
446
+ aria-expanded={isDrawerOpen}
447
+ onMenuToggle={() => setIsDrawerOpen(!isDrawerOpen)}
448
+ />
449
+ <ChatbotHeaderTitle
450
+ displayMode={displayMode}
451
+ showOnFullScreen={horizontalLogo}
452
+ showOnDefault={iconLogo}
453
+ ></ChatbotHeaderTitle>
454
+ </ChatbotHeaderMain>
455
+ <ChatbotHeaderActions>
456
+ <ChatbotHeaderSelectorDropdown value={selectedModel} onSelect={onSelectModel}>
457
+ <DropdownList>
458
+ <DropdownItem value="Granite 7B" key="granite">
459
+ Granite 7B
460
+ </DropdownItem>
461
+ <DropdownItem value="Llama 3.0" key="llama">
462
+ Llama 3.0
463
+ </DropdownItem>
464
+ <DropdownItem value="Mistral 3B" key="mistral">
465
+ Mistral 3B
466
+ </DropdownItem>
467
+ </DropdownList>
468
+ </ChatbotHeaderSelectorDropdown>
469
+ <ChatbotHeaderOptionsDropdown onSelect={onSelectDisplayMode}>
470
+ <DropdownGroup label="Display mode">
471
+ <DropdownList>
472
+ <DropdownItem
473
+ value={ChatbotDisplayMode.default}
474
+ key="switchDisplayOverlay"
475
+ icon={<OutlinedWindowRestoreIcon aria-hidden />}
476
+ isSelected={displayMode === ChatbotDisplayMode.default}
477
+ >
478
+ <span>Overlay</span>
479
+ </DropdownItem>
480
+ <DropdownItem
481
+ value={ChatbotDisplayMode.docked}
482
+ key="switchDisplayDock"
483
+ icon={<OpenDrawerRightIcon aria-hidden />}
484
+ isSelected={displayMode === ChatbotDisplayMode.docked}
485
+ >
486
+ <span>Dock to window</span>
487
+ </DropdownItem>
488
+ <DropdownItem
489
+ value={ChatbotDisplayMode.fullscreen}
490
+ key="switchDisplayFullscreen"
491
+ icon={<ExpandIcon aria-hidden />}
492
+ isSelected={displayMode === ChatbotDisplayMode.fullscreen}
493
+ >
494
+ <span>Fullscreen</span>
495
+ </DropdownItem>
496
+ </DropdownList>
497
+ </DropdownGroup>
498
+ </ChatbotHeaderOptionsDropdown>
499
+ </ChatbotHeaderActions>
500
+ </ChatbotHeader>
501
+ <ChatbotContent>
502
+ {/* Update the announcement prop on MessageBox whenever a new message is sent
503
+ so that users of assistive devices receive sufficient context */}
504
+ <MessageBox announcement={announcement} enableSmartScroll ref={messageBoxRef}>
505
+ <ChatbotWelcomePrompt
506
+ title="Hi, ChatBot User!"
507
+ description="How can I help you today?"
508
+ prompts={welcomePrompts}
509
+ />
510
+ {messages.map((message, index) => {
511
+ if (index === messages.length - 1) {
512
+ return (
513
+ <>
514
+ <Message key={message.id} {...message} />
515
+ </>
516
+ );
517
+ }
518
+ return <Message key={message.id} {...message} />;
519
+ })}
520
+ </MessageBox>
521
+ </ChatbotContent>
522
+ <ChatbotFooter>
523
+ <MessageBar
524
+ onSendMessage={handleSend}
525
+ hasMicrophoneButton
526
+ isSendButtonDisabled={isSendButtonDisabled}
527
+ />
528
+ <ChatbotFootnote {...footnoteProps} />
529
+ </ChatbotFooter>
530
+ </>
531
+ }
532
+ ></ChatbotConversationHistoryNav>
533
+ </Chatbot>
534
+ </>
535
+ );
536
+ };
@@ -28,6 +28,8 @@ export interface ChatbotHeaderSelectorDropdownProps extends Omit<DropdownProps,
28
28
  isCompact?: boolean;
29
29
  /** Additional props passed to toggle */
30
30
  toggleProps?: MenuToggleProps;
31
+ /** Custom width for the dropdown */
32
+ dropdownWidth?: string;
31
33
  }
32
34
 
33
35
  export const ChatbotHeaderSelectorDropdown: FunctionComponent<ChatbotHeaderSelectorDropdownProps> = ({
@@ -40,6 +42,7 @@ export const ChatbotHeaderSelectorDropdown: FunctionComponent<ChatbotHeaderSelec
40
42
  menuToggleAriaLabel,
41
43
  isCompact,
42
44
  toggleProps,
45
+ dropdownWidth,
43
46
  ...props
44
47
  }: ChatbotHeaderSelectorDropdownProps) => {
45
48
  const [isOptionsMenuOpen, setIsOptionsMenuOpen] = useState(false);
@@ -63,6 +66,9 @@ export const ChatbotHeaderSelectorDropdown: FunctionComponent<ChatbotHeaderSelec
63
66
  size={isCompact ? 'sm' : undefined}
64
67
  className={`${isCompact ? 'pf-m-compact' : ''}`}
65
68
  {...toggleProps}
69
+ style={{
70
+ width: dropdownWidth
71
+ }}
66
72
  >
67
73
  {value}
68
74
  </MenuToggle>