Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
<!-- default badges list -->
![](https://img.shields.io/endpoint?url=https://codecentral.devexpress.com/api/v1/VersionRange/1057257433/25.1.2%2B)
[![](https://img.shields.io/badge/Open_in_DevExpress_Support_Center-FF7200?style=flat-square&logo=DevExpress&logoColor=white)](https://supportcenter.devexpress.com/ticket/details/T1307369)
[![](https://img.shields.io/badge/📖_How_to_use_DevExpress_Examples-e9f6fc?style=flat-square)](https://docs.devexpress.com/GeneralInformation/403183)
[![](https://img.shields.io/badge/💬_Leave_Feedback-feecdd?style=flat-square)](#does-this-example-address-your-development-requirementsobjectives)
Expand Down
2 changes: 1 addition & 1 deletion React/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite + React + TS</title>
</head>
<body>
<body class="dx-viewport">
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
Expand Down
15 changes: 11 additions & 4 deletions React/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
"dev": "vite",
"build": "tsc -b && vite build",
"test": "vitest",
"lint:fix": "eslint --ext .js,.jsx,.ts,.tsx src/ --fix",
"test:watch": "vitest --watch",
"lint-ts": "eslint .",
"lint-css": "stylelint src/**/*.css --allow-empty-input",
Expand All @@ -16,18 +17,24 @@
"dependencies": {
"devextreme": "25.1.3",
"devextreme-react": "25.1.3",
"html-react-parser": "^5.2.6",
"react": "^18.2.0",
"react-dom": "^18.2.0"
"react-dom": "^18.2.0",
"rehype-stringify": "^10.0.1",
"remark-parse": "^11.0.0",
"remark-rehype": "^11.1.2",
"rxjs": "^7.8.2",
"unified": "^11.0.5"
},
"devDependencies": {
"@babel/plugin-proposal-private-property-in-object": "^7.21.11",
"@testing-library/jest-dom": "^5.16.5",
"@testing-library/react": "^14.1.2",
"@testing-library/user-event": "^14.4.3",
"@types/react": "^18.2.47",
"@types/react-dom": "^18.2.17",
"@vitejs/plugin-react": "^4.4.1",
"@vitest/coverage-v8": "^1.5.0",
"@babel/plugin-proposal-private-property-in-object": "^7.21.11",
"eslint": "^8.35.0",
"eslint-config-devextreme": "^1.1.4",
"eslint-plugin-no-only-tests": "2.6.0",
Expand All @@ -39,10 +46,10 @@
"npm-run-all": "^4.1.5",
"stylelint": "^15.6.1",
"stylelint-config-standard": "^33.0.0",
"ts-node": "10.9.2",
"typescript": "~5.8.2",
"typescript-eslint": "^8.18.2",
"vite": "^6.3.5",
"ts-node": "10.9.2",
"vitest": "^1.5.0"
}
}
}
72 changes: 68 additions & 4 deletions React/src/App.css
Original file line number Diff line number Diff line change
@@ -1,4 +1,68 @@
.main {
margin: 50px;
width: 90vw;
}
.demo-container {
display: flex;
margin-top: 20px;
justify-content: center;
height: 90vh;
}

.dx-chat {
max-width: 900px;
height: 100%;
}

.chat-disabled .dx-chat-messagebox {
opacity: 0.5;
pointer-events: none !important;
}

.dx-chat-messagelist-empty-image {
display: none;
}

.dx-chat-messagelist-empty-message {
font-size: var(--dx-font-size-heading-5);
}

.dx-chat-messagebubble-content,
.dx-chat-messagebubble-text {
display: flex;
flex-direction: column;
}

.dx-bubble-button-container {
display: none;
}

.dx-button {
display: inline-block;
color: var(--dx-color-icon);
}

.dx-chat-messagegroup-alignment-start:last-child .dx-chat-messagebubble:last-child .dx-bubble-button-container {
display: flex;
gap: 4px;
margin-top: 8px;
}

.dx-chat-messagebubble-content>div>p:first-child {
margin-top: 0;
}

.dx-chat-messagebubble-content>div>p:last-child {
margin-bottom: 0;
}

.dx-chat-messagebubble-content ol,
.dx-chat-messagebubble-content ul {
white-space: normal;
}

.dx-chat-messagebubble-content h1,
.dx-chat-messagebubble-content h2,
.dx-chat-messagebubble-content h3,
.dx-chat-messagebubble-content h4,
.dx-chat-messagebubble-content h5,
.dx-chat-messagebubble-content h6 {
font-size: revert;
font-weight: revert;
}
9 changes: 2 additions & 7 deletions React/src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,16 +1,11 @@
import { useCallback, useState } from 'react';
import ChatApp from './components/ChatApp.tsx';
import './App.css';
import 'devextreme/dist/css/dx.material.blue.light.compact.css';
import Button from 'devextreme-react/button';

function App(): JSX.Element {
var [count, setCount] = useState<number>(0);
const clickHandler = useCallback(() => {
setCount((prev) => prev + 1);
}, [setCount]);
return (
<div className="main">
<Button text={`Click count: ${count}`} onClick={clickHandler} />
<ChatApp />
</div>
);
}
Expand Down
177 changes: 177 additions & 0 deletions React/src/ChatService.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,177 @@
import { type ChatTypes } from 'devextreme-react/chat';
import { DataSource, CustomStore } from 'devextreme-react/common/data';
import { BehaviorSubject, Observable } from 'rxjs';
import { ALERT_TIMEOUT, assistant, sessionId } from './data.ts';

class AppService {
store: ChatTypes.Message[] = [];

lastMessageText: string | undefined;

messages: { role: 'user' | 'assistant' | 'system'; content: string }[] = [];

alerts: ChatTypes.Alert[] = [];

customStore?: CustomStore;

dataSource?: DataSource;

private readonly typingUsersSubject: BehaviorSubject<ChatTypes.User[]> = new BehaviorSubject<ChatTypes.User[]>([]);

private readonly alertsSubject: BehaviorSubject<ChatTypes.Alert[]> = new BehaviorSubject<ChatTypes.Alert[]>([]);

constructor() {
this.initDataSource();
this.typingUsersSubject.next([]);
this.alertsSubject.next([]);
}

get typingUsers$(): Observable<ChatTypes.User[]> {
return this.typingUsersSubject.asObservable();
}

get alerts$(): Observable<ChatTypes.Alert[]> {
return this.alertsSubject.asObservable();
}

getDictionary(): object {
return {
en: {
'dxChat-emptyListMessage': 'Chat is Empty',
'dxChat-emptyListPrompt': 'AI Assistant is ready to answer your questions.',
'dxChat-textareaPlaceholder': 'Ask AI Assistant...',
},
};
}

initDataSource(): void {
this.customStore = new CustomStore({
key: 'id',
load: () => new Promise((resolve): void => {
setTimeout(() => {
resolve([...this.store]);
}, 0);
}),
insert: (message: ChatTypes.Message) => new Promise((resolve): void => {
setTimeout(() => {
this.store.push(message);
resolve(message);
});
}),
});

this.dataSource = new DataSource({
store: this.customStore,
paginate: false,
});
}

async getAIResponse(text: string | undefined): Promise<string> {
let id = sessionId;
const response = await fetch('http://localhost:3000/webhook', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ message: text, sessionId: id }),
});

const data: { response: string } = await response.json();

return data.response;
}

async processMessageSending(setDisabled: Function, e: ChatTypes.MessageEnteredEvent): Promise<void> {
let { message } = e;
setDisabled(true);
(e.event?.target as HTMLElement).blur();
this.typingUsersSubject.next([assistant]);

try {
const aiResponse = await this.getAIResponse(message.text);
setTimeout(() => {
this.typingUsersSubject.next([]);
this.renderAssistantMessage(aiResponse ?? '');
}, 200);
} catch (error) {
(e.event?.target as HTMLElement).focus();
this.typingUsersSubject.next([]);
this.alertLimitReached(error);
} finally {
(e.event?.target as HTMLElement).focus();
setDisabled(false);
}
}

updateLastMessage(text?: string | null | undefined): void {
const items = this.dataSource?.items();
const lastMessage = items?.slice(-1)[0];
const data = {
text: text ?? 'Regeneration...',
};
this.lastMessageText = text ? '' : lastMessage.text;

this.dataSource?.store().push([{ type: 'remove', key: lastMessage.id }, {
type: 'insert',
data: { ...lastMessage, ...data },
}]);
}

renderAssistantMessage(text: string | null): void {
const message = {
id: Date.now(),
timestamp: new Date(),
author: assistant,
text,
};

this.dataSource?.store().push([{ type: 'insert', data: message }]);
}

alertLimitReached(error: any): void {
this.setAlerts([
{
message: error.message,
},
]);

setTimeout((): void => {
this.setAlerts([]);
}, ALERT_TIMEOUT);
}

setAlerts(alerts: ChatTypes.Alert[]): void {
this.alerts = alerts;
this.alertsSubject.next(alerts);
}

async regenerate(): Promise<void> {
try {
const aiResponse = await this.getAIResponse(this.lastMessageText);
this.updateLastMessage(aiResponse);
const lastMsg = this.messages.slice(-1)[0];
if (lastMsg) {
lastMsg.content = aiResponse ?? '';
this.messages = [...this.messages];
}
} catch (error) {
const lastMsg = this.messages.slice(-1)[0];
if (lastMsg) {
this.updateLastMessage(lastMsg.content);
}
this.alertLimitReached(error);
}
}

async onMessageEntered(event: ChatTypes.MessageEnteredEvent, setDisabled: Function): Promise<void> {
let { message } = event;
this.dataSource
?.store()
.push([{ type: 'insert', data: { id: Date.now(), ...message } }]);

this.messages.push({ role: 'user', content: message?.text ?? '' });
await this.processMessageSending(setDisabled, event);
}
}

export const appService = new AppService();
62 changes: 62 additions & 0 deletions React/src/components/ChatApp.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import { useState, useEffect, useCallback } from 'react';
import { loadMessages } from 'devextreme/localization';
import Chat, { type ChatTypes } from 'devextreme-react/chat';
import { appService } from '../ChatService';
import MessageTemplate from './MessageTemplate';
import { CHAT_DISABLED_CLASS, user as chatUser } from '../data.ts';

export default function ChatApp(): JSX.Element {
const user = chatUser;
const [isDisabled, setDisabled] = useState(false);
const [typingUsers, setTypingUsers] = useState<ChatTypes.User[]>([]);
const [alerts, setAlerts] = useState<ChatTypes.Alert[]>([]);

useEffect(() => {
const typingSubscription = appService.typingUsers$.subscribe(setTypingUsers);
const alertsSubscription = appService.alerts$.subscribe(setAlerts);
return (): void => {
typingSubscription.unsubscribe();
alertsSubscription.unsubscribe();
};
}, []);

const onMessageEntered = useCallback((e: ChatTypes.MessageEnteredEvent): void => {
appService.onMessageEntered(e, setDisabled);
}, [isDisabled]);

/* eslint-disable space-before-function-paren */
const onRegenerateButtonClick = useCallback(async (): Promise<void> => {
setDisabled(true);
appService.updateLastMessage();

try {
await appService.regenerate();
} finally {
setDisabled(false);
}
}, []);

const messageRender = useCallback(
({ message }: { message: ChatTypes.Message }) => <MessageTemplate text={message.text ?? ''} onRegenerateButtonClick={onRegenerateButtonClick} />,
[onRegenerateButtonClick],
);

return (
<div className="demo-container">
<Chat
className={isDisabled ? CHAT_DISABLED_CLASS : ''}
dataSource={appService.dataSource}
reloadOnChange={false}
showAvatar={false}
showDayHeaders={false}
user={user}
typingUsers={typingUsers}
alerts={alerts}
onMessageEntered={onMessageEntered}
messageRender={messageRender}
/>
</div>
);
}

loadMessages(appService.getDictionary());
Loading
Loading