Skip to content

Commit

Permalink
Chat: create storybook case for customized message (#28684)
Browse files Browse the repository at this point in the history
  • Loading branch information
anna-shakhova authored Jan 10, 2025
1 parent 1ceff00 commit c7005a7
Show file tree
Hide file tree
Showing 4 changed files with 328 additions and 10 deletions.
3 changes: 2 additions & 1 deletion apps/react-storybook/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@
"dependencies": {
"devextreme": "workspace:~",
"devextreme-react": "workspace:~",
"inferno": "^7.4.9"
"inferno": "^7.4.9",
"html-react-parser": "^5.2.2"
},
"devDependencies": {
"@storybook/addon-essentials": "7.6.19",
Expand Down
116 changes: 113 additions & 3 deletions apps/react-storybook/stories/chat/Chat.stories.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,24 @@
import React, { useState, useCallback, useEffect, useMemo } from 'react';
import {Chat, ChatTypes} from 'devextreme-react/chat'
import type {Meta, StoryObj} from '@storybook/react';
import { Chat, ChatTypes } from 'devextreme-react/chat'
import { Button } from "devextreme-react";
import type { Meta, StoryObj } from '@storybook/react';
import DataSource from 'devextreme/data/data_source';
import CustomStore from 'devextreme/data/custom_store';
import { firstAuthor, secondAuthor, thirdAuthor, fourthAuthor, initialMessages, longError } from './data';
import {
firstAuthor,
secondAuthor,
thirdAuthor,
fourthAuthor,
initialMessages,
longError,
REGENERATION_TEXT,
assistantReplies,
userRequest,
regenerationMessage,
assistant,
} from './data';
import { Popup } from 'devextreme-react/popup';
import HTMLReactParser from 'html-react-parser';

import './styles.css';

Expand Down Expand Up @@ -477,3 +491,99 @@ export const TypingUsers: Story = {
);
}
}

export const AIBotIntegration: Story = {
args: {
alerts: 'No alerts',
},
argTypes: {
alerts: {
control: 'select',
defaultValue: 'No alerts',
options: [
'No alerts',
'Limit reached',
],
mapping: {
['No alerts']: [],
['Limit reached']: [{ message: 'Request limit reached, try again in a minute.' }],
},
},
},
render: ({ alerts }) => {
const [isProcessing, setIsProcessing] = useState(false);
const [assistantReplyIndex, setAssistantReplyIndex] = useState<number>(0);
const [copyButtonIcon, setCopyButtonIcon] = useState('copy');

const items = useMemo(() => {
const repliesCount = assistantReplies.length;
const assistantReply = isProcessing ? regenerationMessage : assistantReplies[assistantReplyIndex % repliesCount];

return [userRequest, assistantReply];
}, [assistantReplyIndex, isProcessing]);

const onRegenerateButtonClick = useCallback(async (): Promise<void> => {
setIsProcessing(true);

await new Promise((resolve) => {
setTimeout(resolve, 300);
});
setAssistantReplyIndex((prev: number) => prev + 1);

setIsProcessing(false);
}, []);

const messageRender = useCallback(({ message }: { message: ChatTypes.Message }) => {
const { text = '', author } = message;

const onCopyButtonClick = () => {
navigator.clipboard?.writeText(text);
setCopyButtonIcon('check');

setTimeout(() => {
setCopyButtonIcon('copy');
}, 2500);
};

if (text === REGENERATION_TEXT || author !== assistant) {
return <span>{text}</span>;
}

return (
<>
<div>
{HTMLReactParser(text)}
</div>
<div>
<Button
icon={copyButtonIcon}
stylingMode='text'
hint='Copy'
onClick={onCopyButtonClick}
/>
<Button
icon='refresh'
stylingMode='text'
hint='Regenerate'
onClick={onRegenerateButtonClick}
/>
</div>
</>
);
}, [copyButtonIcon, onRegenerateButtonClick]);

return (
<div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center' }}>
<Chat
height={900}
width={500}
items={items}
showDayHeaders={false}
user={secondAuthor}
alerts={alerts}
messageRender={messageRender}
/>
</div>
);
}
}
139 changes: 138 additions & 1 deletion apps/react-storybook/stories/chat/data.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { SchedulerTypes } from 'devextreme-react/scheduler';
import { ChatTypes } from 'devextreme-react/chat';

export const REGENERATION_TEXT = 'Regeneration...';

export const firstAuthor: ChatTypes.User = {
id: "c94c0e76-fb49-4b9b-8f07-9f93ed93b4f3",
name: "John Doe",
Expand All @@ -22,6 +23,12 @@ export const fourthAuthor: ChatTypes.User = {
name: "Crash Bandicoot"
};

export const assistant: ChatTypes.User = {
id: 'assistant',
name: 'Virtual Assistant',
avatarUrl: "https://devexpress.github.io/DevExtreme/images/icons/bot.png",
};

const todayDate = new Date();

const date = new Date();
Expand Down Expand Up @@ -86,3 +93,133 @@ export const initialMessages: ChatTypes.Message[] = [
];

export const longError = { id: '1234', message: 'Error Message. An unexpected issue occurred while processing your request. Please check your internet connection or contact support for further assistance.' };

export const userRequest: ChatTypes.Message =
{
timestamp: todayDate,
author: secondAuthor,
text: "What is AI?"
}
;

export const regenerationMessage: ChatTypes.Message = {
timestamp: todayDate,
author: assistant,
text: REGENERATION_TEXT,
};

export const assistantReplies: ChatTypes.Message[] = [
{
timestamp: todayDate,
author: assistant,
text: `<p>Artificial Intelligence (AI) is a branch of computer science that focuses on
creating systems capable of performing tasks that typically require human intelligence.
These tasks include learning, reasoning, problem-solving, understanding natural
language, recognizing patterns, and even making decisions.</p>
<p>AI can be divided into several subfields and categories:</p>
<h3><strong>Types of AI Based on Capability</strong></h3>
<ul>
<li><strong>Narrow AI (Weak AI):</strong> Specialized in performing a single task
or a narrow range of tasks, like language translation, facial recognition,
or recommendation systems. Most AI systems today fall into this category.
</li>
<li><strong>General AI (Strong AI):</strong> A hypothetical form of AI that possesses
the ability to understand, learn, and apply knowledge across a broad range
of tasks, much like a human being.
</li>
<li><strong>Superintelligent AI:</strong> A theoretical concept where AI surpasses
human intelligence across all domains, potentially transforming or outstripping
human capabilities.
</li>
</ul>
<p>AI continues to evolve, impacting nearly every aspect of modern life while raising
ethical, societal, and technological challenges.</p>`.replace(/\s{2,}/gm, ''),
},
{
timestamp: todayDate,
author: assistant,
text: `<p>Artificial Intelligence (AI) is a branch of computer science that focuses on
creating systems capable of performing tasks that typically require human intelligence.
These tasks include learning, reasoning, problem-solving, understanding natural
language, recognizing patterns, and even making decisions.</p>
<p>AI can be divided into several subfields and categories:</p>
<h3><strong>Types of AI Based on Functionality</strong></h3>
<ol>
<li><strong>Reactive Machines:</strong> AI systems that respond to specific inputs
with predefined outputs, without memory or past experiences influencing their
decisions (e.g., IBM's Deep Blue chess-playing computer).
</li>
<li><strong>Limited Memory:</strong> AI systems that can use past data for a short
time to inform decisions, such as self-driving cars.
</li>
<li><strong>Theory of Mind:</strong> A more advanced concept where AI would
understand emotions, beliefs, and intentions, allowing it to interact more
naturally with humans. This remains largely in the research phase.
</li>
<li><strong>Self-Aware AI:</strong> A theoretical AI that has self-awareness and
consciousness.
</li>
</ol>
<p>AI continues to evolve, impacting nearly every aspect of modern life while raising
ethical, societal, and technological challenges.</p>`.replace(/\s{2,}/gm, ''),
},
{
timestamp: todayDate,
author: assistant,
text: `<p>Artificial Intelligence (AI) is a branch of computer science that focuses on
creating systems capable of performing tasks that typically require human intelligence.
These tasks include learning, reasoning, problem-solving, understanding natural
language, recognizing patterns, and even making decisions.</p>
<p>AI can be divided into several subfields and categories:</p>
<h3><strong>Key Subfields of AI</strong></h3>
<ul>
<li><strong>Machine Learning (ML):</strong> Enables systems to learn and improve
from data without explicit programming.
</li>
<li><strong>Deep Learning:</strong> A subset of ML that uses neural networks with
many layers to analyze complex patterns.
</li>
<li><strong>Natural Language Processing (NLP):</strong> Allows AI to understand,
interpret, and respond to human language.
</li>
<li><strong>Computer Vision:</strong> Enables AI to process and analyze visual data
from the world.
</li>
<li><strong>Robotics:</strong> Focuses on creating AI-driven robots to perform tasks
in the physical world.
</li>
<li><strong>Expert Systems:</strong> Mimic human decision-making using rule-based
systems.
</li>
</ul>
<p>AI continues to evolve, impacting nearly every aspect of modern life while raising
ethical, societal, and technological challenges.</p>`.replace(/\s{2,}/gm, ''),
},
{
timestamp: todayDate,
author: assistant,
text: `<p>Artificial Intelligence (AI) is a branch of computer science that focuses on
creating systems capable of performing tasks that typically require human intelligence.
These tasks include learning, reasoning, problem-solving, understanding natural
language, recognizing patterns, and even making decisions.</p>
<p>AI can be divided into several subfields and categories:</p>
<h3><strong>Applications of AI</strong></h3>
<ol>
<li><strong>Healthcare:</strong> Diagnosing diseases, drug discovery, and patient
care.
</li>
<li><strong>Finance:</strong> Fraud detection, stock market analysis, and personalized
financial advice.
</li>
<li><strong>Transportation:</strong> Autonomous vehicles and traffic management.</li>
<li><strong>Entertainment:</strong> Personalized content recommendations on platforms
like Netflix or Spotify.
</li>
<li><strong>Customer Service:</strong> Chatbots and virtual assistants like Siri,
Alexa, or Google Assistant.
</li>
</ol>
<p>AI continues to evolve, impacting nearly every aspect of modern life while raising
ethical, societal, and technological challenges.</p>`.replace(/\s{2,}/gm, ''),
}
];
Loading

0 comments on commit c7005a7

Please sign in to comment.