diff --git a/accessibility/compliance.md b/accessibility/compliance.md index b6fcfbe25a..2cbb308388 100644 --- a/accessibility/compliance.md +++ b/accessibility/compliance.md @@ -47,6 +47,7 @@ Also check the [notes below the table](#accessibility-compliance-notes). | Card | AA | N/A | [Documentation](slug:card-wai-aria-support) | | Carousel | AA | [Enhanced](https://demos.telerik.com/blazor-ui/carousel/keyboard-navigation) | [Documentation](slug:carousel-wai-aria-support) | | Chart | AA | [Enhanced](https://demos.telerik.com/blazor-ui/chart/keyboard-navigation) | [Documentation](slug:chart-wai-aria-support ) | +| Chat | AA | [Enhanced](https://demos.telerik.com/blazor-ui/chat/overview) | [Documentation](slug:chat-wai-aria-support ) | | CheckBox | AA | [Standard](https://demos.telerik.com/blazor-ui/checkbox/overview) | [Documentation](slug:checkbox-wai-aria-support) | | Chip | AA | [Enhanced](https://demos.telerik.com/blazor-ui/chip/keyboard-navigation) | [Documentation](slug:chip-wai-aria-support) | | ChipList | AA | [Enhanced](https://demos.telerik.com/blazor-ui/chiplist/keyboard-navigation) | [Documentation](slug:chiplist-wai-aria-support) | diff --git a/components/chat/accessibility/wai-aria-support.md b/components/chat/accessibility/wai-aria-support.md new file mode 100644 index 0000000000..5bc4c625d7 --- /dev/null +++ b/components/chat/accessibility/wai-aria-support.md @@ -0,0 +1,57 @@ +--- +title: WAI-ARIA Support +page_title: Chat WAI-ARIA Support +slug: chat-wai-aria-support +position: 10 +description: Learn about WAI-ARIA accessibility support in the Telerik UI for Blazor Chat component, including ARIA roles, attributes, and screen reader compatibility. +tags: telerik,blazor,chat,accessibility,wai-aria +published: True +--- + +# WAI-ARIA Support in Telerik UI for Blazor Chat + +@[template](/_contentTemplates/common/parameters-table-styles.md#table-layout) + +Out of the box, the Telerik UI for Blazor Chat provides extensive accessibility support and enables users with disabilities to acquire complete control over its features. + + +The Chat is compliant with the [Web Content Accessibility Guidelines (WCAG) 2.2 AA](https://www.w3.org/TR/WCAG22/) standards and [Section 508](https://www.section508.gov/) requirements, follows the [Web Accessibility Initiative - Accessible Rich Internet Applications (WAI-ARIA)](https://www.w3.org/WAI/ARIA/apg/) best practices for implementing the [keyboard navigation](#keyboard-navigation) for its `component` role, provides options for managing its focus and is tested against the most popular screen readers. + +## ARIA Roles +- `role="log"` for the message list +- `role="textbox"` for the input area +- `role="button"` for actionable elements (send, upload, speech-to-text) + +## ARIA Attributes +- `aria-live` for dynamic message updates +- `aria-label` and `aria-labelledby` for descriptive labeling +- `aria-disabled` for disabled actions + +## Section 508 + +The Chat is fully compliant with the [Section 508 requirements](http://www.section508.gov/). + +## Testing + +The Chat has been extensively tested automatically with [axe-core](https://github.com/dequelabs/axe-core) and manually with the most popular screen readers. + +> To report any accessibility issues, contact the team through the [Telerik Support System](https://www.telerik.com/account/support-center). + +### Screen Readers + +The Chat has been tested with the following screen readers and browsers combinations: + +| Environment | Tool | +| ----------- | ---- | +| Firefox | NVDA | +| Chrome | JAWS | +| Microsoft Edge | JAWS | + +## Keyboard Navigation + +For details on how the keyboard navigation works in Telerik UI for Blazor, refer to the [Accessibility Overview](slug:accessibility-overview#keyboard-navigation) article. + +## See Also + +* [Blazor Chat Demos](https://demos.telerik.com/blazor-ui/chat/overview) +* [Accessibility in Telerik UI for Blazor](slug:accessibility-overview) diff --git a/components/chat/data-binding.md b/components/chat/data-binding.md new file mode 100644 index 0000000000..40d1995859 --- /dev/null +++ b/components/chat/data-binding.md @@ -0,0 +1,170 @@ +--- +title: Data Binding +page_title: Chat Data Binding +description: Learn how to bind data to the Telerik UI for Blazor Chat component, including message models and dynamic updates. +slug: chat-data-binding +tags: telerik,blazor,chat,data-binding,messages +published: True +position: 2 +--- + +# Data Binding + +The Telerik UI for Blazor Chat component supports data binding to collections of messages and provides flexible field mapping to accommodate different data models. + +## Bind to Data + +To bind the Chat to data, set its `Data` parameter to an `IEnumerable` where `T` represents your message model. + +>caption Basic data binding + +````Razor + + + +@code { + private List Messages { get; set; } = new List + { + new ChatMessage { Id = "1", Text = "Hello!", AuthorId = "user1", Timestamp = DateTime.Now.AddMinutes(-5) }, + new ChatMessage { Id = "2", Text = "Hi there!", AuthorId = "user2", Timestamp = DateTime.Now.AddMinutes(-3) } + }; + + private string CurrentUserId { get; set; } = "user1"; + + private void HandleSendMessage(ChatSendMessageEventArgs args) + { + var newMessage = new ChatMessage + { + Id = Guid.NewGuid().ToString(), + Text = args.Message, + AuthorId = CurrentUserId, + Timestamp = DateTime.Now + }; + + Messages.Add(newMessage); + } + + public class ChatMessage + { + public string Id { get; set; } + + public string AuthorId { get; set; } + + public string AuthorName { get; set; } + + public string AuthorImageUrl { get; set; } + + public string Text { get; set; } + + public string MessageToReplyId { get; set; } + + public string Status { get; set; } + + public bool IsDeleted { get; set; } + + public bool IsPinned { get; set; } + + public DateTime Timestamp { get; set; } + + public List SuggestedActions { get; set; } + + public IEnumerable Attachments { get; set; } = new List(); + } +} +```` + +## Field Mapping + +The Chat component provides field mapping parameters to work with different data models. Use these parameters to specify which properties in your data model correspond to Chat features: + +| Parameter | Description | Default Value | +|-----------|-------------|---------------| +| `TextField` | Field containing message text content | `"Text"` | +| `AuthorIdField` | Field containing the author/user ID | `"AuthorId"` | +| `AuthorNameField` | Field containing the author display name | `"AuthorName"` | +| `TimestampField` | Field containing the message timestamp | `"Timestamp"` | +| `IdField` | Field containing the unique message ID | `"Id"` | +| `FilesField` | Field containing file attachments | `"Files"` | +| `StatusField` | Field containing message status | `"Status"` | +| `IsDeletedField` | Field indicating if message is deleted | `"IsDeleted"` | +| `IsPinnedField` | Field indicating if message is pinned | `"IsPinned"` | +| `ReplyТоIdField` | Field containing the ID of replied message | `"ReplyТоId"` | +| `SuggestedActionsField` | Field containing suggested actions | `"SuggestedActions"` | + +## Dynamic Updates + +The Chat component automatically reflects changes to the bound data collection. You can add, modify, or remove messages programmatically: + +````Razor + + + +
+ Add System Message + Clear All Messages +
+ +@code { + private TelerikChat Chat1 { get; set; } + private List Messages { get; set; } = new List(); + private string CurrentUserId = "user1"; + + private void HandleSendMessage(ChatSendMessageEventArgs args) + { + var newMessage = new ChatMessage + { + Id = Guid.NewGuid().ToString(), + Content = args.Message, + AuthorId = CurrentUserId, + AuthorName = "User", + Timestamp = DateTime.Now + }; + + Messages.Add(newMessage); + + Chat1?.Refresh(); + } + + private void AddSystemMessage() + { + Messages.Add(new ChatMessage + { + Id = Guid.NewGuid().ToString(), + Content = "System notification: New user joined the chat", + AuthorId = "system", + AuthorName = "System", + Timestamp = DateTime.Now + }); + + Chat1?.Refresh(); + } + + private void ClearMessages() + { + Messages.Clear(); + Chat1?.Refresh(); + } + + public class ChatMessage + { + public string Id { get; set; } + public string AuthorId { get; set; } + public string AuthorName { get; set; } + public string Content { get; set; } + public DateTime Timestamp { get; set; } + public string Status { get; set; } + public IEnumerable Attachments { get; set; } = new List(); + } +} +```` + +## See Also + +* [Chat Overview](slug:chat-overview) +* [Chat Integrations](slug:chat-integrations) diff --git a/components/chat/events.md b/components/chat/events.md new file mode 100644 index 0000000000..a6999ca0a4 --- /dev/null +++ b/components/chat/events.md @@ -0,0 +1,204 @@ +--- +title: Events +page_title: Chat Events +description: Learn about the events exposed by the Telerik UI for Blazor Chat component for message handling, quick actions, uploads, and more. +slug: chat-events +tags: telerik,blazor,chat,events +published: True +position: 9 +--- + +# Chat Events + +The Telerik UI for Blazor Chat component exposes various events that allow you to implement custom functionality and handle user interactions. This article lists the available events and provides examples for the most common use cases. + +## OnSendMessage + +The `OnSendMessage` event fires when a user sends a new message. Use this event to handle message processing, validation, and persistence. + +>caption Handle the OnSendMessage event + +````Razor + + + +@code { + private List Messages { get; set; } = new List(); + + private string CurrentUserId { get; set; } = "user1"; + + private void HandleSendMessage(ChatSendMessageEventArgs args) + { + var newMessage = new ChatMessage + { + Id = Guid.NewGuid().ToString(), + Content = args.Message, + AuthorId = CurrentUserId, + Timestamp = DateTime.Now + }; + + Messages.Add(newMessage); + } + + public class ChatMessage + { + public string Id { get; set; } + + public string AuthorId { get; set; } + + public string AuthorName { get; set; } + + public string AuthorImageUrl { get; set; } + + public string Content { get; set; } + + public string MessageToReplyId { get; set; } + + public string Status { get; set; } + + public bool IsDeleted { get; set; } + + public bool IsPinned { get; set; } + + public DateTime Timestamp { get; set; } + + public List SuggestedActions { get; set; } + + public IEnumerable Attachments { get; set; } = new List(); + } +} +```` + +## OnSuggestionClick + +The `OnSuggestionClick` event fires when a user clicks on a quick reply suggestion. You can use this event to customize suggestion handling. + +>caption Handle suggestion clicks + +````Razor + + + +@code { + private TelerikChat Chat1; + + private List QuickReplies = new List + { + "Request project status update" + }; + + private void HandleSuggestionClick(ChatSuggestionClickEventArgs args) + { + string responseMessage = string.Empty; + + if (args.Suggestion == "Request project status update") + { + responseMessage = "Could you please provide the current status of all ongoing projects?"; + } + + Messages.Add(new ChatMessage + { + Id = Guid.NewGuid().ToString(), + AuthorId = "user2", + AuthorName = "Jane Doe", + Content = responseMessage, + Status = "Sent", + Timestamp = DateTime.Now + }); + + Chat1?.Refresh(); + } +} +```` + +## OnDownload + +The `OnDownload` event fires when a user downloads files from a message. Use this event to handle file access, logging, or custom download logic. + +>caption Handle file downloads + +````RAZOR.skip-repl + + + +@code { + private async Task HandleDownload(ChatDownloadEventArgs args) + { + foreach (var file in args.Files) + { + // Log download activity + await LogFileDownload(file.Name, args.MessageId); + + // Implement custom download logic + await ProcessFileDownload(file); + } + } +} +```` + +## OnMessageUnpin + +The `OnMessageUnpin` event fires when a user unpins a message. Handle this event to update your data model and persist the change. + +>caption Handle message unpinning + +````RAZOR.skip-repl + + + +@code { + private void HandleMessageUnpin(ChatMessageUnpinEventArgs args) + { + var message = Messages.FirstOrDefault(m => m.Id == args.MessageId); + if (message != null) + { + message.IsPinned = false; + } + } +} +```` + +## OnInputValueChanged + +The `OnInputValueChanged` event fires when the input value changes. Use this for real-time validation, auto-save drafts, or typing indicators. + +>caption Handle input value changes + +````RAZOR.skip-repl + + + +@code { + private string InputValue { get; set; } = string.Empty; + + private void HandleInputChange(string value) + { + InputValue = value; + } +} +```` + +## Event Arguments + +The Chat events provide specific argument types with relevant data: + +| Event | Arguments Type | Key Properties | +|-------|----------------|----------------| +| `OnSendMessage` | `ChatSendMessageEventArgs` | `Message`, `Files`, `ReplyMessageId` | +| `OnSuggestionClick` | `ChatSuggestionClickEventArgs` | `Suggestion`, `IsCancelled` | +| `OnDownload` | `ChatDownloadEventArgs` | `Files`, `MessageId` | +| `OnMessageUnpin` | `ChatMessageUnpinEventArgs` | `MessageId` | +| `OnInputValueChanged` | `string` | The current input value | + +## See Also + +* [Chat Overview](slug:chat-overview) +* [Chat File Uploads and Media](slug:chat-file-uploads-and-media) diff --git a/components/chat/file-uploads-and-media.md b/components/chat/file-uploads-and-media.md new file mode 100644 index 0000000000..a31caf7461 --- /dev/null +++ b/components/chat/file-uploads-and-media.md @@ -0,0 +1,345 @@ +--- +title: File Uploads and Media +page_title: Chat File Uploads and Media +description: Learn how to configure file uploads, media sharing, and speech-to-text features in the Telerik UI for Blazor Chat component. +slug: chat-file-uploads-and-media +tags: telerik,blazor,chat,file-upload,media,speech-to-text +published: True +position: 4 +--- + +# File Uploads and Media + +The Telerik UI for Blazor Chat component supports file uploads, media sharing, and speech-to-text functionality to enhance the messaging experience. + +## File Upload Configuration + +Enable file uploads by setting the `EnableFileUpload` parameter to `true`: + +````RAZOR.skip-repl + + +```` + +## File Upload Settings + +Configure file upload behavior using the `ChatFileSelectSettings` component: + +| Parameter | Type | Default | Description | +|-----------|------|---------|-------------| +| `AllowedExtensions` | `List` | `null` | Allowed file extensions for upload | +| `MaxFileSize` | `long` | `null` | Maximum file size in bytes | +| `Multiple` | `bool` | `true` | Allow multiple file selection | +| `OnSelect` | `EventCallback` | - | Event fired when files are selected | + +>caption An exemplary Chat file upload configuration is shown below + +````razor + + + + + + + + + + +@code { + private TelerikChat Chat1; + private List AllowedExtensions = new List { ".jpg", ".jpeg", ".png", ".pdf", ".docx", ".txt" }; + + private List ChatConversation = new List() + { + new ChatMessage() + { + Id = "1", + AuthorId = "support", + AuthorName = "File Support", + Content = "Welcome! You can upload files by clicking the attachment button or dragging files into the input area.", + Timestamp = DateTime.Now.AddMinutes(-5) + }, + new ChatMessage() + { + Id = "2", + AuthorId = "support", + AuthorName = "File Support", + Content = "Here's an example message with an attachment:", + Timestamp = DateTime.Now.AddMinutes(-3), + Attachments = new List + { + new FileSelectFileInfo + { + Id = "sample-doc", + Name = "sample-document.pdf", + Size = 245760, + Extension = ".pdf" + } + } + } + }; + + private void HandleSendMessage(ChatSendMessageEventArgs args) + { + var newMessage = new ChatMessage + { + Id = Guid.NewGuid().ToString(), + Content = args.Message, + AuthorId = "user", + AuthorName = "You", + Timestamp = DateTime.Now, + Attachments = args.Files?.ToList() ?? new List() + }; + + ChatConversation.Add(newMessage); + + if (args.Files?.Any() == true) + { + var fileNames = string.Join(", ", args.Files.Select(f => f.Name)); + var responseMessage = new ChatMessage + { + Id = Guid.NewGuid().ToString(), + Content = $"Thank you! I received {args.Files.Count()} file(s): {fileNames}", + AuthorId = "support", + AuthorName = "File Support", + Timestamp = DateTime.Now.AddSeconds(1) + }; + + ChatConversation.Add(responseMessage); + } + + Chat1?.Refresh(); + } + + public class ChatMessage + { + public string Id { get; set; } + public string AuthorId { get; set; } + public string AuthorName { get; set; } + public string AuthorImageUrl { get; set; } + public string Content { get; set; } + public string ReplyToMessageId { get; set; } + public string Status { get; set; } + public bool IsDeleted { get; set; } + public bool IsPinned { get; set; } + public DateTime Timestamp { get; set; } + public List SuggestedActions { get; set; } + public IEnumerable Attachments { get; set; } = new List(); + } +} +```` + +## Attachments + +Configure how file attachments are displayed and handled in chat messages using the `FilesField` parameter. This parameter specifies which property of your message model contains the file attachment information. + +The `FilesField` parameter binds to a collection of `FileSelectFileInfo` objects that represent the uploaded files. Each attachment includes metadata such as file name, size, extension, and unique identifier. + +````RAZOR.skip-repl + + + +@code { + public class ChatMessage + { + public string Id { get; set; } + public string AuthorId { get; set; } + public string AuthorName { get; set; } + public string Content { get; set; } + public DateTime Timestamp { get; set; } + + // This property is bound to FilesField="Attachments" + public IEnumerable Attachments { get; set; } = new List(); + } +} +```` + +When messages contain attachments, they are automatically displayed with file icons, names, and sizes. Users can interact with attachments through the configured file actions. + +## File Actions and Downloads + +Configure file actions and handle downloads using JavaScript interop and custom event handlers. + +1. Add JavaScript Interop + + Add this JavaScript function to enable file downloads: + + ````html + @inject IJSRuntime JS + + + ```` + +2. Configure File Actions + + Configure the `Download` file action: + + ````RAZOR.skip-repl + + + + + + + + ```` + +3. Implement a click handler for the `Download` file action. + + The click handler calls the js `downloadFileFromBytes` function. + + ````csharp + private async Task OnDirectFileDownload(ChatFileActionClickEventArgs args) + { + try + { + var filePath = Path.Combine(Environment.WebRootPath, "chat-files", args.File.Name); + + if (System.IO.File.Exists(filePath)) + { + var fileBytes = await System.IO.File.ReadAllBytesAsync(filePath); + + var base64String = Convert.ToBase64String(fileBytes); + + var mimeType = GetMimeType(args.File.Extension); + + await JS.InvokeVoidAsync("downloadFileFromBytes", base64String, args.File.Name, mimeType); + } + else + { + Console.WriteLine($"File not found: {filePath}"); + } + } + catch (Exception ex) + { + Console.WriteLine($"Error downloading file {args.File.Name}: {ex.Message}"); + } + } + ```` + + +## File Validation + +The Chat component provides built-in file validation through the `ChatFileSelectSettings` configuration. You can control which files users can upload and set size restrictions to ensure appropriate content and prevent system overload. + +### AllowedExtensions + +Use the `AllowedExtensions` parameter to restrict file uploads to specific file types. This helps ensure users only upload supported formats and prevents potential security issues. + +````RAZOR.skip-repl + + + + +@code { + private List AllowedExtensions = new List + { + ".jpg", ".jpeg", ".png", ".gif", // Images + ".pdf", ".doc", ".docx", // Documents + ".txt", ".csv", // Text files + ".zip", ".rar" // Archives + }; +} +```` + +When a user attempts to upload a file with an extension not in the allowed list, the Chat component will automatically prevent the upload. + +### MaxFileSize + +Set the `MaxFileSize` parameter to limit the size of uploaded files in bytes. This prevents users from uploading files that are too large for your system to handle efficiently. + +````RAZOR.skip-repl + + + +```` + +Files exceeding the specified size limit will be rejected. + +## Speech-to-Text + +The Chat component includes built-in speech-to-text functionality that allows users to input messages using voice commands. This feature leverages the browser's Web Speech API to convert spoken words into text, providing an accessible and convenient way to interact with the chat interface. + +Speech-to-text is particularly useful for mobile users, accessibility scenarios, or when typing is inconvenient. The component provides customizable settings to control language recognition, result accuracy, and interim feedback. + +### Configuration + +Enable speech-to-text functionality by setting `EnableSpeechToText` to `true`: + +````RAZOR.skip-repl + + + + + + +@code { + private async Task OnSpeechResult(SpeechToTextButtonResultEventArgs args) + { + if (args.IsFinal && args.Alternatives?.Any() == true) + { + var transcript = args.Alternatives.First().Transcript; + // Handle the speech recognition result + await ProcessSpeechInput(transcript); + } + } +} +```` + +### Settings + +Configure speech recognition behavior using `ChatSpeechToTextButtonSettings`: + +| Parameter | Type | Default | Description | +|-----------|------|---------|-------------| +| `Lang` | `string` | `"en-US"` | Recognition language code | +| `MaxAlternatives` | `int` | `1` | Maximum number of recognition alternatives | +| `InterimResults` | `bool` | `false` | Return interim recognition results | +| `OnResult` | `EventCallback` | - | Event fired when speech is recognized | + +## See Also + +* [Chat Overview](slug:chat-overview) +* [FileSelect Component](slug:fileselect-overview) +* [SpeechToTextButton Component](slug:speechtotextbutton-overview) diff --git a/components/chat/integrations.md b/components/chat/integrations.md new file mode 100644 index 0000000000..32c0e39a58 --- /dev/null +++ b/components/chat/integrations.md @@ -0,0 +1,135 @@ +--- +title: Integrations +page_title: Chat Integrations +description: Learn how to integrate the Telerik UI for Blazor Chat component with AI services, LLMs, and chatbot frameworks. +slug: chat-integrations +tags: telerik,blazor,chat,integrations,ai,llm,chatbot +published: True +position: 7 +--- + +# Chat Integrations + +The Chat component can be integrated with various AI services, Large Language Models (LLMs), and chatbot frameworks, and other messaging platforms to create intelligent conversational experiences. + +This article explains: + +* [AI and LLM Integration](#ai-and-llm-integration) - Connect to AI services and language models +* [Chatbot Integration](#chatbot-integration) - Integrate with chatbot frameworks +* [Message Processing](#message-processing) - Handle AI responses and user interactions + +## AI and LLM Integration + +The Chat component works seamlessly with AI services and Large Language Models. You can integrate with various providers like OpenAI, Azure OpenAI, or custom AI services. + +### Microsoft.Extensions.AI Integration Example + +The following example demonstrates using the `OnSendMessage` event to communicate with an AI service. The event handler passes user messages to the AI service, retrieves the response, and displays it in the Chat: + +````RAZOR.skip-repl +@using Microsoft.Extensions.AI +@using System.Threading +@using Microsoft.AspNetCore.Hosting +@inject AIPromptService AIPromptService +@inject IWebHostEnvironment Environment + + + +@code { + private TelerikChat AIChat; + private List AIChatConversation { get; set; } = new List(); + private CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); + + private async Task AskAI(ChatSendMessageEventArgs args) + { + cancellationTokenSource = new CancellationTokenSource(); + + var prompt = new ChatMessage() + { + Id = Guid.NewGuid().ToString(), + AuthorId = "user", + AuthorName = "John Doe", + Content = args.Message, + Timestamp = DateTime.Now, + Status = "Sent" + }; + + var response = new ChatMessage() + { + Id = Guid.NewGuid().ToString(), + AuthorId = "ai", + AuthorName = "AI Assistant", + AuthorImageUrl = "https://demos.telerik.com/blazor-ui/images/devcraft-ninja-small.svg", + Timestamp = DateTime.Now, + Status = "Sent" + }; + + AIChatConversation.Add(prompt); + AIChatConversation.Add(response); + AIChat?.Refresh(); + + var chatMessage = new Microsoft.Extensions.AI.ChatMessage(ChatRole.User, args.Message); + var fullResponse = string.Empty; + await foreach (var answer in AIPromptService.GetStreamingResponseAsync(chatMessage, cancellationToken: cancellationTokenSource.Token)) + { + fullResponse += answer.Text; + response.Content = fullResponse; + AIChat?.Refresh(); + } + } + + public class ChatMessage + { + public string Id { get; set; } + + public string AuthorId { get; set; } + + public string AuthorName { get; set; } + + public string AuthorImageUrl { get; set; } + + public string Content { get; set; } + + public string MessageToReplyId { get; set; } + + public string Status { get; set; } + + public bool IsDeleted { get; set; } + + public bool IsPinned { get; set; } + + public DateTime Timestamp { get; set; } + + public List SuggestedActions { get; set; } + + public IEnumerable Attachments { get; set; } = new List(); + } +} +```` + +## Chatbot Integration + +Chatbots are intelligent software solutions that replicate human-like conversations and can manage various tasks autonomously without requiring manual intervention. + +You can connect the Chat component to various chatbot platforms including Microsoft Bot Framework, custom REST APIs, or third-party chatbot services. The component handles the user interface while your bot service processes messages and generates appropriate responses. + +>tip The [Person to Bot demo](https://demos.telerik.com/blazor-ui/chat/person-to-bot) showcases chatbot functionality. This demo utilizes a Telerik-hosted AI service solely for illustration purposes. In production environments, you should develop your own AI service tailored to your specific business domain, requirements, and organizational needs. + +### Suggested Actions + +The Chat component supports suggested actions through the `SuggestedActions` parameter. This feature allows chatbots to provide quick reply options that users can click instead of typing responses manually. You can bind the `SuggestedActions` parameter to a field in your chatbot service response to display these interactive buttons. + +````RAZOR.skip-repl + + +```` + +## See Also + +* [Live Demo: Chat AI Integration](https://demos.telerik.com/blazor-ui/chat/ai-integration) +* [Microsoft.Extensions.AI Documentation](https://learn.microsoft.com/en-us/dotnet/ai/) diff --git a/components/chat/messages.md b/components/chat/messages.md new file mode 100644 index 0000000000..fd5c1dbbea --- /dev/null +++ b/components/chat/messages.md @@ -0,0 +1,227 @@ +--- +title: Messages +page_title: Chat Messages +description: Learn how to configure message actions, styling, and behavior in the Telerik UI for Blazor Chat component. +slug: chat-messages +tags: telerik,blazor,chat,messages,actions,styling +published: True +position: 5 +--- + +# Chat Messages + +The Telerik UI for Blazor Chat component provides comprehensive control over message display, interactions, and styling to create rich conversational experiences. + +## Context Menu Message Actions + +Configure context menu actions that appear when users right-click on messages. These actions provide quick access to common message operations. + +````Razor + + + + + + + + + +@code { + private TelerikChat Chat1; + + private List ChatConversation = new List() + { + new ChatMessage() + { + Id = "1", + AuthorId = "1", + AuthorName = "John Smith", + Content = "Hello, how are you today?", + Status = "Seen", + Timestamp = DateTime.Now.AddMinutes(-10) + }, + new ChatMessage() + { + Id = "2", + AuthorId = "2", + AuthorName = "Jane Doe", + Content = "Hi John! I'm doing great, thanks for asking.", + Status = "Seen", + Timestamp = DateTime.Now.AddMinutes(-8) + } + }; + + private void OnReplyClick(ChatMessageActionClickEventArgs args) + { + var message = ChatConversation.FirstOrDefault(m => m.Id == args.MessageId); + if (message != null) + { + // Set up reply context + Console.WriteLine($"Replying to message: {message.Content}"); + } + } + + private void OnCopyClick(ChatMessageActionClickEventArgs args) + { + var message = ChatConversation.FirstOrDefault(m => m.Id == args.MessageId); + if (message != null) + { + // Copy message content to clipboard + Console.WriteLine($"Copying message: {message.Content}"); + } + } + + private void OnPinClick(ChatMessageActionClickEventArgs args) + { + var message = ChatConversation.FirstOrDefault(m => m.Id == args.MessageId); + if (message != null) + { + message.IsPinned = !message.IsPinned; + Chat1?.Refresh(); + } + } + + private void OnDeleteClick(ChatMessageActionClickEventArgs args) + { + var message = ChatConversation.FirstOrDefault(m => m.Id == args.MessageId); + if (message != null) + { + message.IsDeleted = true; + Chat1?.Refresh(); + } + } + + public class ChatMessage + { + public string Id { get; set; } + public string AuthorId { get; set; } + public string AuthorName { get; set; } + public string AuthorImageUrl { get; set; } + public string Content { get; set; } + public string ReplyToMessageId { get; set; } + public string Status { get; set; } + public bool IsDeleted { get; set; } + public bool IsPinned { get; set; } + public DateTime Timestamp { get; set; } + public List SuggestedActions { get; set; } + public IEnumerable Attachments { get; set; } = new List(); + } +} +```` + +## Toolbar Message Actions + +Configure toolbar actions that appear when messages are selected or hovered. These provide quick access to frequently used operations. + +````RAZOR.skip-repl + + + + + + + +```` + +## Messages Styling + +The Chat component provides several styling options for messages, allowing you to customize their appearance, behavior, and layout to match your application's design. + +### Expanding and Collapsing Messages + +Control message collapsing behavior using the `EnableMessageCollapse` parameter. When enabled, long messages can be collapsed to save space and expanded when needed for better readability. + +Set `EnableMessageCollapse="true"` to allow users to collapse and expand messages in the chat interface. + +### Messages Width + +Control the width behavior of chat messages using the `MessageWidthMode` parameter: + +* `MessageWidthMode.Standard` - Messages take up a portion of the available space for better readability (default behavior) +* `MessageWidthMode.Full` - Messages span the full width of the chat container + +## Message Box Value Persistence + +The message box value represents the text that users have typed but haven't sent yet. + +The Chat component offers complete control over the message input using the `InputValue` property and `OnInputValueChange` event. + +Set the `InputValue` property to define the message box content and handle the `OnInputValueChange` event to track user typing in real-time. This enables implementing features such as draft auto-saving, input validation, or contextually pre-populating the message box. + +````Razor + + + +@code { + private List ChatConversation = new List() + { + new ChatMessage() + { + Id = "1", + AuthorId = "1", + AuthorName = "John Smith", + Content = "Hi there!", + Status = "Seen", + Timestamp = new System.DateTime(2025, 10, 1, 12, 0, 0) + } + }; + + private TelerikChat Chat1; + + private string CurrentInputValue { get; set; } = ""; + + private void OnInputValueChanged(string newValue) + { + CurrentInputValue = newValue; + // Implement real-time tracking, validation, or draft saving here + Console.WriteLine($"Input changed to: {newValue}"); + } + + private void HandleSendMessage(ChatSendMessageEventArgs args) + { + var newMessage = new ChatMessage + { + Id = Guid.NewGuid().ToString(), + Content = args.Message, + AuthorId = "1", + AuthorName = "John Smith", + Status = "Sent", + Timestamp = DateTime.Now + }; + + ChatConversation.Add(newMessage); + + CurrentInputValue = ""; + + Chat1?.Refresh(); + } + + public class ChatMessage + { + public string Id { get; set; } + public string AuthorId { get; set; } + public string AuthorName { get; set; } + public string Content { get; set; } + public string Status { get; set; } + public DateTime Timestamp { get; set; } + } +} +```` + +## See Also + +* [Live Demo: Chat Overview](https://demos.telerik.com/blazor-ui/chat/overview) +* [Chat Overview]({%slug chat-overview%}) diff --git a/components/chat/overview.md b/components/chat/overview.md new file mode 100644 index 0000000000..4852419e84 --- /dev/null +++ b/components/chat/overview.md @@ -0,0 +1,164 @@ +--- +title: Overview +page_title: Chat Overview +description: Discover the Telerik UI for Blazor Chat component. Learn how to add the component to your app and explore its features like messaging, AI integration, customization, and accessibility. +slug: chat-overview +tags: telerik,blazor,chat,messaging,ai,accessibility +published: True +position: 0 +--- + +# Blazor Chat Component Overview + +The Telerik UI for Blazor Chat component enables developers to build modern conversational interfaces in Blazor applications. It supports rich messaging, AI integrations, custom templates, file uploads, and accessibility features. The component is designed for extensibility, allowing integration with chatbots, LLMs, and custom business logic. + +## Creating Blazor Chat + +1. Add the `` tag to your page. +2. Set the `Data` parameter to a collection of messages. +3. Set the `AuthorId` parameter to identify the current user. +4. Subscribe to the `OnSendMessage` event to handle new messages. +5. (optional) Configure additional features like file uploads, speech-to-text, and quick actions. + +>caption Basic configuration of the Telerik Chat + +````razor + + + +@code { + private List Messages { get; set; } = new List() + { + new ChatMessage + { + Id = "1", + Content = "Hello! How can I help you today?", + UserId = "assistant", + SentAt = DateTime.Now.AddMinutes(-5) + }, + new ChatMessage + { + Id = "2", + Content = "Hi there! I'm looking for information about the new features.", + UserId = "user1", + SentAt = DateTime.Now.AddMinutes(-3) + } + }; + private string CurrentUserId = "user1"; + + private async Task HandleSendMessage(ChatSendMessageEventArgs args) + { + var newMessage = new ChatMessage + { + Id = Guid.NewGuid().ToString(), + Content = args.Message, + UserId = CurrentUserId, + SentAt = DateTime.Now + }; + + Messages.Add(newMessage); + await InvokeAsync(StateHasChanged); + } + + public class ChatMessage + { + public string Id { get; set; } + public string Content { get; set; } + public string UserId { get; set; } + public DateTime SentAt { get; set; } + public List Attachments { get; set; } + } +} +```` + +## Data Binding + +The Chat component supports binding to collections of messages and user data. The component provides flexible field mapping to accommodate different data models. [Read more about Chat data binding...](slug:chat-data-binding) + +## Messages + +The Chat component offers rich messaging capabilities including context menus, toolbars, appearance customization, and persistence features. Messages can include text, files, and custom content. [Read more about Chat messages...](slug:chat-messages) + +## Templates and Customization + +The Chat component provides extensive template support for customizing the appearance and behavior of messages, timestamps, suggestions, message box, and header. [Read more about Chat templates...](slug:chat-templates) + +## Integrations + +Connect the Chat component with AI services, chatbots, and external APIs to create intelligent conversational experiences. The component supports integration with popular AI services and custom bot frameworks. [Read more about Chat integrations...](slug:chat-integrations) + +## File Uploads and Media + +Enable file uploads and media sharing in your chat application. The component supports configurable file upload settings and speech-to-text functionality for enhanced user experience. [Read more about file uploads and media...](slug:chat-file-uploads-and-media) + +## Events + +The Chat component exposes various events that allow you to implement custom functionality and handle user interactions. Key events include message sending, file uploads, suggestion clicks, and message actions. [Read more about Chat events...](slug:chat-events) + +## Chat Parameters + +The Chat component provides a variety of parameters: + +@[template](/_contentTemplates/common/parameters-table-styles.md#table-layout) + +| Parameter | Type and Default Value | Description | +| --- | --- | --- | +| `Data` | `IEnumerable` | The data source for chat messages. | +| `AuthorId` | `string` | The ID of the current user sending messages. | +| `TextField` | `string`
(`"Text"`) | The name of the field containing the message content. | +| `AuthorIdField` | `string`
(`"AuthorId"`) | The name of the field containing the author identifier. | +| `TimestampField` | `string`
(`"Timestamp"`) | The name of the field containing the message timestamp. | +| `AuthorNameField` | `string`
(`"AuthorName"`) | The name of the field containing the author display name. | +| `AuthorImageUrlField` | `string`
(`"AuthorImageUrl"`) | The name of the field containing the author's avatar image URL. | +| `AttachmentsField` | `string`
(`"Attachments"`) | The name of the field containing message file attachments. | +| `Height` | `string` | The height of the chat component in CSS units. | +| `Width` | `string` | The width of the chat component in CSS units. | +| `EnableFileUpload` | `bool`
(`false`) | Enables file upload functionality in the chat input. | +| `EnableSpeechToText` | `bool`
(`true`) | Enables speech-to-text functionality with microphone input. | +| `MessageWidthMode` | `MessageWidthMode` enum
(`Standard`) | Controls the width behavior of messages (Standard or Full). | +| `Suggestions` | `IEnumerable` | Collection of quick reply suggestions. | + +## Chat Reference and Methods + +The Chat component exposes a `Refresh()` method that refreshes the component and scrolls to the latest messages. To execute the method, obtain a reference to the Chat instance via `@ref`. + +>caption How to obtain a Chat reference and call methods + +````RAZOR.skip-repl + + + +Refresh Chat + +@code { + private TelerikChat ChatRef { get; set; } + + private void RefreshChat() + { + ChatRef?.Refresh(); + } +} +```` + +## Next Steps + +* [Get started with Chat data binding](slug:chat-data-binding) +* [Customize Chat templates](slug:chat-templates) +* [Handle Chat events](slug:chat-events) +* [Configure file uploads and media](slug:chat-file-uploads-and-media) + +## See Also + +* [Live Demo: Chat Overview](https://demos.telerik.com/blazor-ui/chat/overview) +* [Live Demo: AI Integration](https://demos.telerik.com/blazor-ui/chat/ai-integration) diff --git a/components/chat/quick-actions.md b/components/chat/quick-actions.md new file mode 100644 index 0000000000..7a287e1500 --- /dev/null +++ b/components/chat/quick-actions.md @@ -0,0 +1,274 @@ +--- +title: Quick Actions +page_title: Chat Quick Actions +description: Learn how to configure and use quick actions and message suggestions in the Telerik UI for Blazor Chat component. +slug: chat-quick-actions +tags: telerik,blazor,chat,quick-actions,suggestions +published: True +position: 3 +--- + +# Quick Actions + +The Telerik UI for Blazor Chat component supports quick actions and message suggestions to enhance user experience and provide convenient interaction options. + +## Message Suggestions + +Message suggestions provide users with quick reply options that appear below the message input area. + +>caption Basic message suggestions + +````razor + + + +@code { + private string ChatInputValue { get; set; } + private TelerikChat Chat1; + + private List QuickReplies = new List + { + "Request project status update", + "Schedule a follow-up meeting" + }; + + private List ChatConversation = new List() + { + new ChatMessage() + { + Id="first", + AuthorId="1", + AuthorName="John Smith", + Content="Hello, I wanted to confirm the details of the project update.", + Status="Seen", + Timestamp=new System.DateTime(2023, 10, 1, 12, 0, 0) + }, + new ChatMessage() + { + Id="second", + AuthorId="2", + AuthorName="Jane Doe", + Content="Hi John, the project update has been finalized and shared with the team.", + Status="Seen", + Timestamp=new System.DateTime(2023, 10, 1, 12, 5, 0) + } + }; + + private void HandleSuggestionClick(ChatSuggestionClickEventArgs args) + { + string responseMessage = string.Empty; + + if (args.Suggestion == "Request project status update") + { + responseMessage = "Could you please provide the current status of all ongoing projects?"; + } + else if (args.Suggestion == "Schedule a follow-up meeting") + { + responseMessage = "Let's schedule a follow-up meeting to discuss the next steps."; + } + + ChatConversation.Add(new ChatMessage + { + Id = Guid.NewGuid().ToString(), + AuthorId = "2", + AuthorName = "Jane Doe", + Content = responseMessage, + Status = "Sent", + Timestamp = DateTime.Now + }); + + Chat1?.Refresh(); + } + + public class ChatMessage + { + public string Id { get; set; } + public string AuthorId { get; set; } + public string AuthorName { get; set; } + public string AuthorImageUrl { get; set; } + public string Content { get; set; } + public string ReplyToMessageId { get; set; } + public string Status { get; set; } + public bool IsDeleted { get; set; } + public bool IsPinned { get; set; } + public DateTime Timestamp { get; set; } + public List SuggestedActions { get; set; } + public IEnumerable Attachments { get; set; } = new List(); + } +} +```` + +## Custom Suggestion Templates + +Customize the appearance of suggestions using the Chat's `SuggestionTemplate`. + +````razor + + +
+ 💬 + @suggestionContext.Suggestion +
+
+
+ + + +@code { + private string ChatInputValue { get; set; } + private TelerikChat Chat1; + private List CurrentSuggestions = new List { "Yes, I need help with my order", "No, I was just checking in" }; + + private List ChatConversation = new List() + { + new ChatMessage() + { + Id="first", + AuthorId="1", + AuthorName="Customer Support", + Content="Welcome to TelerikStore! I'm here to help you today.", + Status="Seen", + Timestamp=new System.DateTime(2023, 10, 1, 14, 30, 0) + }, + new ChatMessage() + { + Id="second", + AuthorId="1", + AuthorName="Customer Support", + Content="I see you've been browsing our UI components. Is there anything specific you need assistance with?", + Status="Seen", + Timestamp=new System.DateTime(2023, 10, 1, 14, 31, 0) + } + }; + + private void HandleSuggestionClick(ChatSuggestionClickEventArgs args) + { + string responseMessage = string.Empty; + + // Initial responses + if (args.Suggestion == "Yes, I need help with my order") + { + responseMessage = "I'd be happy to help you with your order! Can you please provide your order number or the email address you used for the purchase?"; + } + else if (args.Suggestion == "No, I was just checking in") + { + responseMessage = "That's great! Feel free to browse around. If you have any questions about our Blazor components or need a demo, just let me know!"; + } + // Handle order suggestions if needed + else + { + responseMessage = "Thank you for that information. How else can I assist you today?"; + } + + // Add the support agent's response + ChatConversation.Add(new ChatMessage + { + Id = Guid.NewGuid().ToString(), + AuthorId = "1", + AuthorName = "Customer Support", + Content = responseMessage, + Status = "Sent", + Timestamp = DateTime.Now + }); + + Chat1?.Refresh(); + } + + public class ChatMessage + { + public string Id { get; set; } + public string AuthorId { get; set; } + public string AuthorName { get; set; } + public string AuthorImageUrl { get; set; } + public string Content { get; set; } + public string ReplyToMessageId { get; set; } + public string Status { get; set; } + public bool IsDeleted { get; set; } + public bool IsPinned { get; set; } + public DateTime Timestamp { get; set; } + public List SuggestedActions { get; set; } + public IEnumerable Attachments { get; set; } = new List(); + } +} +```` + +## Integration with AI Services + +Use suggestions to guide AI conversations. With the help of the Chat's `OnSuggestionClick` event, you can access the clicked suggestion and you can pass it to the AI service for processing. + +````RAZOR.skip-repl +private async Task OnSuggestionClick(ChatSuggestionClickEventArgs args) +{ + var userMessage = new ChatMessage() + { + Id = Guid.NewGuid().ToString(), + AuthorId = "user", + AuthorName = "John Doe", + Content = args.Suggestion, + Timestamp = DateTime.Now, + Status = "" + }; + + AIChatConversation.Add(userMessage); + + //pass the clicked suggestion to the AI service as a message + await AskAI(new ChatSendMessageEventArgs() + { + Message = args.Suggestion + }); + + return; +} +```` + +## See Also + +* [Chat Events](slug:chat-events) +* [Chat Templates](slug:chat-templates) diff --git a/components/chat/templates.md b/components/chat/templates.md new file mode 100644 index 0000000000..f8dca538d9 --- /dev/null +++ b/components/chat/templates.md @@ -0,0 +1,288 @@ +--- +title: Templates +page_title: Chat Templates +description: A comprehensive guide to the customizable templates available in the Telerik Chat component for Blazor. +slug: chat-templates +keywords: blazor, telerik, chat, templates, customization +published: True +position: 8 +--- + +# Chat Templates + +The Telerik Chat component in Blazor allows for a high degree of customization through various templates. Each template provides a way to customize the UI rendering of the Chat interface, making it more suitable for your application’s needs. + +Below are the available templates along with examplary usage. + +## HeaderTemplate + +This template allows you to customize the Chat header, where you can display titles, logos, or buttons. + + +````RAZOR.skip-repl + + + Chat with John Smith + + +```` + +## MessageTemplate + +Customize how individual messages are rendered within the Chat. + +````RAZOR.skip-repl + +
+ @context.Message.Content +
+
+```` + +## MessageStatusTemplate + +You can use this template to display the status of a message (e.g., Sent, Seen). + +````RAZOR.skip-repl + +
+ @context.Message.Status +
+
+```` + +## SuggestionTemplate + +This template allows you to customize how suggestion buttons are displayed in the Chat interface. Suggestions provide quick reply options for users. + +````RAZOR.skip-repl + +
+ @context.Suggestion +
+
+```` + +## MessageBoxTemplate + +This template allows you to customize the input area where users type their messages. + +````RAZOR.skip-repl + + + + +```` + +## TimestampTemplate + +This template allows you to customize how timestamps are displayed for messages. + +````RAZOR.skip-repl + + + @context.Timestamp.ToString("dddd, MMMM d, yyyy") + + +```` + +## ChatMessageContextMenuActions + +This allows you to define context menu actions that can be performed on Chat messages. + +````RAZOR.skip-repl + + + + + +```` + +## Complete Example + +>caption A complete example that integrates all templates into a Chat component + +````RAZOR + + + + Chat with John Smith + + + +
+ @context.Message.Status +
+
+ +
+ @context.Message.Content +
+
+ +
+ @context.Suggestion +
+
+ + + + + + + @context.Timestamp.ToString("dddd, MMMM d, yyyy") + + + + + + + +
+ +@code { + + private void OnUnpin(ChatMessageUnpinEventArgs args) + { + var message = ChatConversation.FirstOrDefault(x => x.Id == args.MessageId); + if (message != null) + { + message.IsPinned = false; + } + else + { + Console.WriteLine($"Message with ID {args.MessageId} not found."); + } + } + + private string FirstChatInputValue { get; set; } + + private void OnFirstInputValueChange(string value) + { + FirstChatInputValue = value; + } + + private void PinMessage(ChatMessageActionClickEventArgs args) + { + var message = ChatConversation.FirstOrDefault(m => m.Id == args.MessageId); + if (message != null) + { + ChatConversation.ForEach(m => m.IsPinned = false); + message.IsPinned = true; + } + } + + private void OnSendMessage(ChatSendMessageEventArgs args, string authorId) + { + var newMessage = new ChatMessage + { + Id = Guid.NewGuid().ToString(), + AuthorName = authorId == "1" ? "John Smith" : "Jane Doe", + AuthorId = authorId, + AuthorImageUrl = authorId == "1" ? FirstUserImage : SecondUserImage, + Content = args.Message, + MessageToReplyId = args.ReplyMessageId, + Status = "Sent", + Timestamp = DateTime.Now + }; + + ChatConversation.Add(newMessage); + RefreshChats(); + } + + private void RefreshChats() + { + Chat1?.Refresh(); + } + + private TelerikChat Chat1; + + private List ChatConversation = new List() + { + new ChatMessage() + { + Id="first", + AuthorId="1", + AuthorName="John Smith", + AuthorImageUrl=FirstUserImage, + Content="Hello, I wanted to confirm the details of the project update.", + Status="Seen", + Timestamp=new System.DateTime(2023, 10, 1, 12, 0, 0) + }, + new ChatMessage() + { + Id="second", + AuthorId="2", + AuthorName="Jane Doe", + AuthorImageUrl=SecondUserImage, + Content="Hi John, the project update has been finalized and shared with the team.", + Status="Seen", + Timestamp=new System.DateTime(2023, 10, 1, 12, 5, 0) + }, + new ChatMessage() + { + Id="third", + AuthorId="1", + AuthorName="John Smith", + AuthorImageUrl=FirstUserImage, + Content="Thank you, Jane. I will review it and provide feedback shortly.", + Status="Seen", + Timestamp=new System.DateTime(2023, 10, 1, 12, 10, 0) + }, + new ChatMessage() + { + Id="fourth", + AuthorId="2", + AuthorName="Jane Doe", + AuthorImageUrl=SecondUserImage, + Content="Sounds good, John. Let me know if you need any additional information.", + Status="Seen", + Timestamp=new System.DateTime(2023, 10, 1, 12, 15, 0) + } + }; + + private const string FirstUserImage = "images/user.webp"; + + private const string SecondUserImage = "images/user.webp"; + + public class ChatMessage + { + public string Id { get; set; } + + public string AuthorId { get; set; } + + public string AuthorName { get; set; } + + public string AuthorImageUrl { get; set; } + + public string Content { get; set; } + + public string MessageToReplyId { get; set; } + + public string Status { get; set; } + + public bool IsDeleted { get; set; } + + public bool IsPinned { get; set; } + + public DateTime Timestamp { get; set; } + + public List SuggestedActions { get; set; } + + public IEnumerable Attachments { get; set; } = new List(); + } +} +```` + +## See Also + +* [Live Demo: Chat Overview](https://demos.telerik.com/blazor-ui/chat/overview) diff --git a/docs-builder.yml b/docs-builder.yml index 510858f95e..0f68155168 100644 --- a/docs-builder.yml +++ b/docs-builder.yml @@ -320,6 +320,8 @@ meta: title: ColorPalette "*colorgradient": title: ColorGradient + "*chat": + title: Chat "*chunkprogressbar": title: ChunkProgressBar "*chiplist": diff --git a/introduction.md b/introduction.md index 5e0d327c29..986245e11c 100644 --- a/introduction.md +++ b/introduction.md @@ -185,6 +185,7 @@ You can watch a YouTube playlist of getting started tutorials for Telerik UI for +