From 24e059dcb46b884c2dce878ffaa298a27f4ee110 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C2=96=C2=96AsTroLog?= Date: Mon, 20 Nov 2023 09:03:32 +0000 Subject: [PATCH 1/5] SA-194 add message entering --- .../Pages/Chat.razor | 17 ++- .../Pages/Chat.razor.cs | 119 ++++++++++-------- .../Pages/Index.razor | 20 ++- 3 files changed, 97 insertions(+), 59 deletions(-) diff --git a/ShoppingAssistantWebClient.Web/Pages/Chat.razor b/ShoppingAssistantWebClient.Web/Pages/Chat.razor index 88b9c82..a104726 100644 --- a/ShoppingAssistantWebClient.Web/Pages/Chat.razor +++ b/ShoppingAssistantWebClient.Web/Pages/Chat.razor @@ -76,7 +76,6 @@ } - } @@ -84,11 +83,10 @@
- + Send message
- @@ -102,6 +100,10 @@ } }; + window.clearInput = () => { + // Отримати елемент вводу за його ідентифікатором і обнулити його значення + document.getElementById('chatInput').value = ''; + }; document.getElementById('button_open').addEventListener('click', changetyle); @@ -114,12 +116,19 @@ { await LoadMessages(); } + private void InputChanged(ChangeEventArgs e) + { + inputValue = e.Value.ToString(); + + } public void Enter(KeyboardEventArgs e) { if (e.Code == "Enter" || e.Code == "NumpadEnter") { AddNewMessage(); + + } } diff --git a/ShoppingAssistantWebClient.Web/Pages/Chat.razor.cs b/ShoppingAssistantWebClient.Web/Pages/Chat.razor.cs index d361622..b66ffc7 100644 --- a/ShoppingAssistantWebClient.Web/Pages/Chat.razor.cs +++ b/ShoppingAssistantWebClient.Web/Pages/Chat.razor.cs @@ -6,8 +6,11 @@ using ShoppingAssistantWebClient.Web.Network; using ShoppingAssistantWebClient.Web.Models.Input; using ShoppingAssistantWebClient.Web.Models.Enums; using System.Text.RegularExpressions; +using Microsoft.JSInterop; + namespace ShoppingAssistantWebClient.Web.Pages; + public partial class Chat : ComponentBase { @@ -24,6 +27,7 @@ public partial class Chat : ComponentBase private CancellationTokenSource cancelTokenSource; private MessageCreateDto messageCreateDto; + private bool isWaitingForResponse = false; public bool isLoading = true; private string inputValue = ""; private string name = ""; @@ -96,74 +100,83 @@ public partial class Chat : ComponentBase } private async Task AddNewMessage() { - try{ - messageCreateDto = new MessageCreateDto { Text = inputValue };; - Message = new Messages(); - Message.Text = inputValue; - Message.Role = "User"; - Message.Id = ""; - Message.CreatedById = ""; - inputValue = ""; - Suggestion = new List(); - Messages.Add(Message); - StateHasChanged(); - cancelTokenSource = new CancellationTokenSource(); - var cancellationToken = cancelTokenSource.Token; - var serverSentEvent = _apiClient.GetServerSentEventStreamed($"ProductsSearch/search/{chatId}", messageCreateDto, cancellationToken); - bool first = true; - - await foreach (var sseEvent in serverSentEvent.WithCancellation(cancellationToken)) + if (!isWaitingForResponse && !string.IsNullOrWhiteSpace(inputValue)) { - Console.WriteLine($"Received SSE Event: {sseEvent.Event}, Data: {sseEvent.Data}"); - - - if(sseEvent.Event == SearchEventType.Message){ - - string input = sseEvent.Data; - Regex regex = new Regex("\"(.*?)\""); - Match match = regex.Match(input); - string result = match.Groups[1].Value; - - + JSRuntime.InvokeVoidAsync("clearInput"); + isWaitingForResponse = true; + try{ + + messageCreateDto = new MessageCreateDto { Text = inputValue };; Message = new Messages(); - Message.Text = result; - Message.Role = "bot"; + Message.Text = inputValue; + Message.Role = "User"; Message.Id = ""; Message.CreatedById = ""; - - if (first) - { - Messages.Add(Message); - first = false; - } - else - { - var lengt = Messages.Count(); - Messages[lengt-1].Text += Message.Text; - } - + inputValue = ""; + Suggestion = new List(); + Messages.Add(Message); StateHasChanged(); - - }else if(sseEvent.Event == SearchEventType.Product){ - var url = $"/chat/{chatId}/product"; - Navigation.NavigateTo(url); + cancelTokenSource = new CancellationTokenSource(); + var cancellationToken = cancelTokenSource.Token; - }else if(sseEvent.Event == SearchEventType.Suggestion){ + var serverSentEvent = _apiClient.GetServerSentEventStreamed($"ProductsSearch/search/{chatId}", messageCreateDto, cancellationToken); + bool first = true; + + await foreach (var sseEvent in serverSentEvent.WithCancellation(cancellationToken)) + { + Console.WriteLine($"Received SSE Event: {sseEvent.Event}, Data: {sseEvent.Data}"); + + + if(sseEvent.Event == SearchEventType.Message){ + + string input = sseEvent.Data; + Regex regex = new Regex("\"(.*?)\""); + Match match = regex.Match(input); + string result = match.Groups[1].Value; + + + + Message = new Messages(); + Message.Text = result; + Message.Role = "bot"; + Message.Id = ""; + Message.CreatedById = ""; + + if (first) + { + Messages.Add(Message); + first = false; + } + else + { + var lengt = Messages.Count(); + Messages[lengt-1].Text += Message.Text; + } + + StateHasChanged(); + + }else if(sseEvent.Event == SearchEventType.Product){ + + var url = $"/chat/{chatId}/product"; + Navigation.NavigateTo(url); + + }else if(sseEvent.Event == SearchEventType.Suggestion){ + + Suggestion.Add(sseEvent.Data); + } - Suggestion.Add(sseEvent.Data); } + isWaitingForResponse = false; + }catch(Exception ex){ + Console.WriteLine($"Error : {ex.Message}"); + } } - }catch(Exception ex){ - Console.WriteLine($"Error : {ex.Message}"); - } - - } } diff --git a/ShoppingAssistantWebClient.Web/Pages/Index.razor b/ShoppingAssistantWebClient.Web/Pages/Index.razor index a3db7bb..2dc266f 100644 --- a/ShoppingAssistantWebClient.Web/Pages/Index.razor +++ b/ShoppingAssistantWebClient.Web/Pages/Index.razor @@ -52,8 +52,8 @@
- + Send message
@@ -133,4 +133,20 @@ } + private void InputChanged(ChangeEventArgs e) + { + // Оновіть значення поля введення при кожному введенні тексту + inputValue = e.Value.ToString(); + } + public void Enter(KeyboardEventArgs e) + { + if (e.Code == "Enter" || e.Code == "NumpadEnter") + { + + if (!string.IsNullOrWhiteSpace(inputValue)) + { + CreateNewChat(); + } + } + } } From fb92899ce80fee9188292644c5a7d350ca67df1c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C2=96=C2=96AsTroLog?= Date: Tue, 21 Nov 2023 20:57:57 +0000 Subject: [PATCH 2/5] SA-195 fix initial message freeze --- .../Pages/Chat.razor | 17 ++- .../Pages/Chat.razor.cs | 123 +++++++++++++----- .../Pages/Index.razor | 18 --- .../Pages/Index.razor.cs | 67 ++-------- .../wwwroot/images/loading.svg | 42 ------ 5 files changed, 114 insertions(+), 153 deletions(-) delete mode 100644 ShoppingAssistantWebClient.Web/wwwroot/images/loading.svg diff --git a/ShoppingAssistantWebClient.Web/Pages/Chat.razor b/ShoppingAssistantWebClient.Web/Pages/Chat.razor index 88b9c82..dbc9d45 100644 --- a/ShoppingAssistantWebClient.Web/Pages/Chat.razor +++ b/ShoppingAssistantWebClient.Web/Pages/Chat.razor @@ -86,7 +86,7 @@
- Send message + Send message
@@ -103,6 +103,12 @@ } }; + function myJavaScriptFunction(wishlistId) { + + UpdateMenu(wishlistId); + + } + document.getElementById('button_open').addEventListener('click', changetyle); @@ -119,7 +125,7 @@ { if (e.Code == "Enter" || e.Code == "NumpadEnter") { - AddNewMessage(); + AddNewMessage(inputValue); } } @@ -136,4 +142,11 @@ inputValue = item; } + private async Task UpdateSideMenu(string wishlistId) + { + + await JSRuntime.InvokeVoidAsync("myJavaScriptFunction", wishlistId); + + } + } \ No newline at end of file diff --git a/ShoppingAssistantWebClient.Web/Pages/Chat.razor.cs b/ShoppingAssistantWebClient.Web/Pages/Chat.razor.cs index 0590f6f..865eb1d 100644 --- a/ShoppingAssistantWebClient.Web/Pages/Chat.razor.cs +++ b/ShoppingAssistantWebClient.Web/Pages/Chat.razor.cs @@ -34,12 +34,47 @@ public partial class Chat : ComponentBase private string name = ""; protected override async Task OnInitializedAsync() { + var input = _searchServise.firstMassage; + + if (input!=null){ + await LoadMessages(); + + await AddNewMessage(input); + + string wishlistId = chatId; + var request = new GraphQLRequest + { + Query = @"mutation GenerateNameForPersonalWishlist($wishlistId: String!) { + generateNameForPersonalWishlist(wishlistId: $wishlistId) { + id + name + } + }", + Variables = new + { + wishlistId + + } + }; + + var response = await _apiClient.QueryAsync(request); + _searchServise.SetFirstMassage(null); + isLoading = false; + await UpdateSideMenu(wishlistId); + StateHasChanged(); + + }else{ + await LoadMessages(); + } + } private async Task LoadMessages() { + + try{ string wishlistId = chatId; @@ -62,29 +97,29 @@ public partial class Chat : ComponentBase name = responseData.personalWishlist.name; - isLoading = true; - int pageNumber = 1; - request = new GraphQLRequest - { - Query = @"query MessagesPageFromPersonalWishlist($wishlistId: String!, $pageNumber: Int!, $pageSize: Int!) { - messagesPageFromPersonalWishlist( wishlistId: $wishlistId, pageNumber: $pageNumber, pageSize: $pageSize) - { - items { - id - text - role - createdById - } + isLoading = true; + int pageNumber = 1; + request = new GraphQLRequest + { + Query = @"query MessagesPageFromPersonalWishlist($wishlistId: String!, $pageNumber: Int!, $pageSize: Int!) { + messagesPageFromPersonalWishlist( wishlistId: $wishlistId, pageNumber: $pageNumber, pageSize: $pageSize) + { + items { + id + text + role + createdById } - }", + } + }", - Variables = new - { - wishlistId, - pageNumber, - pageSize = 200 - } - }; + Variables = new + { + wishlistId, + pageNumber, + pageSize = 200 + } + }; @@ -99,53 +134,69 @@ public partial class Chat : ComponentBase Console.WriteLine($"Error : {ex.Message}"); } } - private async Task AddNewMessage() + private async Task AddNewMessage(string inputMessage) { + + try{ - messageCreateDto = new MessageCreateDto { Text = inputValue };; + + messageCreateDto = new MessageCreateDto { Text = inputMessage };; Message = new Messages(); - Message.Text = inputValue; + Message.Text = inputMessage; Message.Role = "User"; Message.Id = ""; Message.CreatedById = ""; inputValue = ""; Suggestion = new List(); + Products = new List(); Messages.Add(Message); StateHasChanged(); cancelTokenSource = new CancellationTokenSource(); var cancellationToken = cancelTokenSource.Token; + const string animationChars = ".oOo"; + int animationIndex = 0; + var serverSentEvent = _apiClient.GetServerSentEventStreamed($"ProductsSearch/search/{chatId}", messageCreateDto, cancellationToken); bool first = true; + + Message = new Messages(); + Message.Role = "bot"; + Message.Id = ""; + Message.CreatedById = ""; + Message.Text = "Waiting for response"; + Messages.Add(Message); + + + + StateHasChanged(); + await Task.Delay(500); // Adjust delay as needed + animationIndex = (animationIndex + 1) % animationChars.Length; + await foreach (var sseEvent in serverSentEvent.WithCancellation(cancellationToken)) { + Console.WriteLine($"Received SSE Event: {sseEvent.Event}, Data: {sseEvent.Data}"); string input = sseEvent.Data; Regex regex = new Regex("\"(.*?)\""); Match match = regex.Match(input); string result = match.Groups[1].Value; - if(sseEvent.Event == SearchEventType.Message){ - Message = new Messages(); - Message.Text = result; - Message.Role = "bot"; - Message.Id = ""; - Message.CreatedById = ""; - if (first) { - Messages.Add(Message); + var lengt = Messages.Count(); + Messages[lengt-1].Text = result; first = false; } else { var lengt = Messages.Count(); - Messages[lengt-1].Text += Message.Text; - } + Messages[lengt-1].Text += result; + } StateHasChanged(); @@ -159,7 +210,9 @@ public partial class Chat : ComponentBase } } - if(Products != null) { + + + if(Products.Count!=0) { string n = name; _searchServise.SetProducts(Products); var url = $"/cards/{name}/{chatId}"; diff --git a/ShoppingAssistantWebClient.Web/Pages/Index.razor b/ShoppingAssistantWebClient.Web/Pages/Index.razor index a3db7bb..1fe2e9a 100644 --- a/ShoppingAssistantWebClient.Web/Pages/Index.razor +++ b/ShoppingAssistantWebClient.Web/Pages/Index.razor @@ -11,8 +11,6 @@ -@if(isLoading == false){ -
New chat
@@ -59,15 +57,6 @@
-}else{ - -
- - Loading chat - -
- -}
@@ -104,13 +93,6 @@ } - - - - - - - document.getElementById('choose_gift').addEventListener('click', switchGift); document.getElementById('choose_product').addEventListener('click', switchProduct); diff --git a/ShoppingAssistantWebClient.Web/Pages/Index.razor.cs b/ShoppingAssistantWebClient.Web/Pages/Index.razor.cs index 2cc2915..f6a3c2c 100644 --- a/ShoppingAssistantWebClient.Web/Pages/Index.razor.cs +++ b/ShoppingAssistantWebClient.Web/Pages/Index.razor.cs @@ -7,6 +7,7 @@ using Newtonsoft.Json; using ShoppingAssistantWebClient.Web.Network; using System; using Microsoft.JSInterop; +using ShoppingAssistantWebClient.Web.Services; namespace ShoppingAssistantWebClient.Web.Pages { @@ -20,14 +21,10 @@ namespace ShoppingAssistantWebClient.Web.Pages private NavigationManager Navigation { get; set; } [Inject] protected IJSRuntime JSRuntime { get; set; } + [Inject] + private SearchService _searchServise { get; set; } - private MessageCreateDto messageCreateDto; - - private CancellationTokenSource cancelTokenSource; - private string inputValue = ""; - public bool isLoading; - private async Task CreateNewChat() { @@ -38,9 +35,6 @@ namespace ShoppingAssistantWebClient.Web.Pages return; } - isLoading = true; - StateHasChanged(); - messageCreateDto = new MessageCreateDto { Text = inputValue }; var type = selectedChoice; var firstMessageText = $"What are you looking for?"; @@ -62,58 +56,19 @@ namespace ShoppingAssistantWebClient.Web.Pages var response = await _apiClient.QueryAsync(request); var responseData = response.Data; var chatId = responseData?.startPersonalWishlist?.id; - string wishlistId1 = chatId; - - var text = inputValue; - - cancelTokenSource = new CancellationTokenSource(); - var cancellationToken = cancelTokenSource.Token; - - var serverSentEvent = _apiClient.GetServerSentEventStreamed($"ProductsSearch/search/{chatId}", messageCreateDto, cancellationToken); - - await foreach (var sseEvent in serverSentEvent.WithCancellation(cancellationToken)) - { - // Handle each ServerSentEvent as needed - Console.WriteLine($"Received SSE Event: {sseEvent.Event}, Data: {sseEvent.Data}"); - } - string wishlistId = chatId; - request = new GraphQLRequest - { - Query = @"mutation GenerateNameForPersonalWishlist($wishlistId: String!) { - generateNameForPersonalWishlist(wishlistId: $wishlistId) { - id - name - } - }", - Variables = new - { - wishlistId - - } - }; - - response = await _apiClient.QueryAsync(request); - - isLoading = false; - StateHasChanged(); - - await UpdateSideMenu(wishlistId1); + _searchServise.SetFirstMassage(inputValue); + await UpdateSideMenu(wishlistId); var url = $"/chat/{chatId}"; Navigation.NavigateTo(url); - } - catch (Exception ex) - { - // Handle exceptions appropriately - Console.WriteLine($"Error in CreateNewChat: {ex.Message}"); - } - finally - { - isLoading = false; - cancelTokenSource?.Dispose(); - } + } + catch (Exception ex){ + + Console.WriteLine($"Error in CreateNewChat: {ex.Message}"); + } + } } diff --git a/ShoppingAssistantWebClient.Web/wwwroot/images/loading.svg b/ShoppingAssistantWebClient.Web/wwwroot/images/loading.svg deleted file mode 100644 index 4a32def..0000000 --- a/ShoppingAssistantWebClient.Web/wwwroot/images/loading.svg +++ /dev/null @@ -1,42 +0,0 @@ - - - - - - - - - - - - - - - - - - From 1b25cd368f6fb16cc099af843a995a46d5afbb35 Mon Sep 17 00:00:00 2001 From: Mykhailo Bilodid Date: Wed, 22 Nov 2023 15:48:13 +0200 Subject: [PATCH 3/5] Revert "SA-195 fix initial message freeze" This reverts commit fb92899ce80fee9188292644c5a7d350ca67df1c. --- .../Pages/Chat.razor | 17 +-- .../Pages/Chat.razor.cs | 125 +++++------------- .../Pages/Index.razor | 18 +++ .../Pages/Index.razor.cs | 67 ++++++++-- .../wwwroot/images/loading.svg | 42 ++++++ 5 files changed, 154 insertions(+), 115 deletions(-) create mode 100644 ShoppingAssistantWebClient.Web/wwwroot/images/loading.svg diff --git a/ShoppingAssistantWebClient.Web/Pages/Chat.razor b/ShoppingAssistantWebClient.Web/Pages/Chat.razor index 1c24cfe..09d53f3 100644 --- a/ShoppingAssistantWebClient.Web/Pages/Chat.razor +++ b/ShoppingAssistantWebClient.Web/Pages/Chat.razor @@ -85,7 +85,7 @@
- Send message + Send message
@@ -101,12 +101,6 @@ } }; - function myJavaScriptFunction(wishlistId) { - - UpdateMenu(wishlistId); - - } - document.getElementById('button_open').addEventListener('click', changetyle); @@ -123,7 +117,7 @@ { if (e.Code == "Enter" || e.Code == "NumpadEnter") { - AddNewMessage(inputValue); + AddNewMessage(); } } @@ -140,11 +134,4 @@ inputValue = item; } - private async Task UpdateSideMenu(string wishlistId) - { - - await JSRuntime.InvokeVoidAsync("myJavaScriptFunction", wishlistId); - - } - } \ No newline at end of file diff --git a/ShoppingAssistantWebClient.Web/Pages/Chat.razor.cs b/ShoppingAssistantWebClient.Web/Pages/Chat.razor.cs index 656b2c9..282567e 100644 --- a/ShoppingAssistantWebClient.Web/Pages/Chat.razor.cs +++ b/ShoppingAssistantWebClient.Web/Pages/Chat.razor.cs @@ -37,47 +37,12 @@ public partial class Chat : ComponentBase private string name = ""; protected override async Task OnInitializedAsync() { - var input = _searchServise.firstMassage; - - if (input!=null){ - await LoadMessages(); - - await AddNewMessage(input); - - string wishlistId = chatId; - var request = new GraphQLRequest - { - Query = @"mutation GenerateNameForPersonalWishlist($wishlistId: String!) { - generateNameForPersonalWishlist(wishlistId: $wishlistId) { - id - name - } - }", - Variables = new - { - wishlistId - - } - }; - - var response = await _apiClient.QueryAsync(request); - _searchServise.SetFirstMassage(null); - isLoading = false; - await UpdateSideMenu(wishlistId); - StateHasChanged(); - - }else{ - await LoadMessages(); - } - } private async Task LoadMessages() { - - try{ string wishlistId = chatId; @@ -100,29 +65,29 @@ public partial class Chat : ComponentBase name = responseData.personalWishlist.name; - isLoading = true; - int pageNumber = 1; - request = new GraphQLRequest - { - Query = @"query MessagesPageFromPersonalWishlist($wishlistId: String!, $pageNumber: Int!, $pageSize: Int!) { - messagesPageFromPersonalWishlist( wishlistId: $wishlistId, pageNumber: $pageNumber, pageSize: $pageSize) - { - items { - id - text - role - createdById - } - } - }", - - Variables = new + isLoading = true; + int pageNumber = 1; + request = new GraphQLRequest { - wishlistId, - pageNumber, - pageSize = 200 - } - }; + Query = @"query MessagesPageFromPersonalWishlist($wishlistId: String!, $pageNumber: Int!, $pageSize: Int!) { + messagesPageFromPersonalWishlist( wishlistId: $wishlistId, pageNumber: $pageNumber, pageSize: $pageSize) + { + items { + id + text + role + createdById + } + } + }", + + Variables = new + { + wishlistId, + pageNumber, + pageSize = 200 + } + }; @@ -137,69 +102,53 @@ public partial class Chat : ComponentBase Console.WriteLine($"Error : {ex.Message}"); } } - private async Task AddNewMessage(string inputMessage) + private async Task AddNewMessage() { - - try{ - - messageCreateDto = new MessageCreateDto { Text = inputMessage };; + messageCreateDto = new MessageCreateDto { Text = inputValue };; Message = new Messages(); - Message.Text = inputMessage; + Message.Text = inputValue; Message.Role = "User"; Message.Id = ""; Message.CreatedById = ""; inputValue = ""; Suggestion = new List(); - Products = new List(); Messages.Add(Message); StateHasChanged(); cancelTokenSource = new CancellationTokenSource(); var cancellationToken = cancelTokenSource.Token; - const string animationChars = ".oOo"; - int animationIndex = 0; - var serverSentEvent = _apiClient.GetServerSentEventStreamed($"ProductsSearch/search/{chatId}", messageCreateDto, cancellationToken); bool first = true; - - Message = new Messages(); - Message.Role = "bot"; - Message.Id = ""; - Message.CreatedById = ""; - Message.Text = "Waiting for response"; - Messages.Add(Message); - - - - StateHasChanged(); - await Task.Delay(500); // Adjust delay as needed - animationIndex = (animationIndex + 1) % animationChars.Length; - await foreach (var sseEvent in serverSentEvent.WithCancellation(cancellationToken)) { - Console.WriteLine($"Received SSE Event: {sseEvent.Event}, Data: {sseEvent.Data}"); string input = sseEvent.Data; Regex regex = new Regex("\"(.*?)\""); Match match = regex.Match(input); string result = match.Groups[1].Value; + if(sseEvent.Event == SearchEventType.Message){ + Message = new Messages(); + Message.Text = result; + Message.Role = "bot"; + Message.Id = ""; + Message.CreatedById = ""; + if (first) { - var lengt = Messages.Count(); - Messages[lengt-1].Text = result; + Messages.Add(Message); first = false; } else { var lengt = Messages.Count(); - Messages[lengt-1].Text += result; - } + Messages[lengt-1].Text += Message.Text; + } StateHasChanged(); @@ -213,9 +162,7 @@ public partial class Chat : ComponentBase } } - - - if(Products.Count!=0) { + if(Products != null) { string n = name; _searchServise.SetProducts(Products); var url = $"/cards/{name}/{chatId}"; diff --git a/ShoppingAssistantWebClient.Web/Pages/Index.razor b/ShoppingAssistantWebClient.Web/Pages/Index.razor index 1d81c33..2dc266f 100644 --- a/ShoppingAssistantWebClient.Web/Pages/Index.razor +++ b/ShoppingAssistantWebClient.Web/Pages/Index.razor @@ -11,6 +11,8 @@ +@if(isLoading == false){ +
New chat
@@ -57,6 +59,15 @@
+}else{ + +
+ + Loading chat + +
+ +}
@@ -93,6 +104,13 @@ } + + + + + + + document.getElementById('choose_gift').addEventListener('click', switchGift); document.getElementById('choose_product').addEventListener('click', switchProduct); diff --git a/ShoppingAssistantWebClient.Web/Pages/Index.razor.cs b/ShoppingAssistantWebClient.Web/Pages/Index.razor.cs index f6a3c2c..2cc2915 100644 --- a/ShoppingAssistantWebClient.Web/Pages/Index.razor.cs +++ b/ShoppingAssistantWebClient.Web/Pages/Index.razor.cs @@ -7,7 +7,6 @@ using Newtonsoft.Json; using ShoppingAssistantWebClient.Web.Network; using System; using Microsoft.JSInterop; -using ShoppingAssistantWebClient.Web.Services; namespace ShoppingAssistantWebClient.Web.Pages { @@ -21,10 +20,14 @@ namespace ShoppingAssistantWebClient.Web.Pages private NavigationManager Navigation { get; set; } [Inject] protected IJSRuntime JSRuntime { get; set; } - [Inject] - private SearchService _searchServise { get; set; } + private MessageCreateDto messageCreateDto; + + private CancellationTokenSource cancelTokenSource; + private string inputValue = ""; + public bool isLoading; + private async Task CreateNewChat() { @@ -35,6 +38,9 @@ namespace ShoppingAssistantWebClient.Web.Pages return; } + isLoading = true; + StateHasChanged(); + messageCreateDto = new MessageCreateDto { Text = inputValue }; var type = selectedChoice; var firstMessageText = $"What are you looking for?"; @@ -56,19 +62,58 @@ namespace ShoppingAssistantWebClient.Web.Pages var response = await _apiClient.QueryAsync(request); var responseData = response.Data; var chatId = responseData?.startPersonalWishlist?.id; + string wishlistId1 = chatId; + + var text = inputValue; + + cancelTokenSource = new CancellationTokenSource(); + var cancellationToken = cancelTokenSource.Token; + + var serverSentEvent = _apiClient.GetServerSentEventStreamed($"ProductsSearch/search/{chatId}", messageCreateDto, cancellationToken); + + await foreach (var sseEvent in serverSentEvent.WithCancellation(cancellationToken)) + { + // Handle each ServerSentEvent as needed + Console.WriteLine($"Received SSE Event: {sseEvent.Event}, Data: {sseEvent.Data}"); + } + string wishlistId = chatId; - _searchServise.SetFirstMassage(inputValue); - await UpdateSideMenu(wishlistId); + request = new GraphQLRequest + { + Query = @"mutation GenerateNameForPersonalWishlist($wishlistId: String!) { + generateNameForPersonalWishlist(wishlistId: $wishlistId) { + id + name + } + }", + Variables = new + { + wishlistId + + } + }; + + response = await _apiClient.QueryAsync(request); + + isLoading = false; + StateHasChanged(); + + await UpdateSideMenu(wishlistId1); var url = $"/chat/{chatId}"; Navigation.NavigateTo(url); - } - catch (Exception ex){ - - Console.WriteLine($"Error in CreateNewChat: {ex.Message}"); - } - + } + catch (Exception ex) + { + // Handle exceptions appropriately + Console.WriteLine($"Error in CreateNewChat: {ex.Message}"); + } + finally + { + isLoading = false; + cancelTokenSource?.Dispose(); + } } } diff --git a/ShoppingAssistantWebClient.Web/wwwroot/images/loading.svg b/ShoppingAssistantWebClient.Web/wwwroot/images/loading.svg new file mode 100644 index 0000000..4a32def --- /dev/null +++ b/ShoppingAssistantWebClient.Web/wwwroot/images/loading.svg @@ -0,0 +1,42 @@ + + + + + + + + + + + + + + + + + + From 31f94d32d0581a3cf2f438150a9bbd0cf3e69456 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C2=96=C2=96AsTroLog?= Date: Wed, 22 Nov 2023 16:42:47 +0000 Subject: [PATCH 4/5] fix bugs --- .../Pages/Chat.razor | 27 ++++++- .../Pages/Chat.razor.cs | 81 ++++++++++++++----- .../Pages/Index.razor | 12 --- .../Pages/Index.razor.cs | 63 +++------------ 4 files changed, 97 insertions(+), 86 deletions(-) diff --git a/ShoppingAssistantWebClient.Web/Pages/Chat.razor b/ShoppingAssistantWebClient.Web/Pages/Chat.razor index 09d53f3..bdef32e 100644 --- a/ShoppingAssistantWebClient.Web/Pages/Chat.razor +++ b/ShoppingAssistantWebClient.Web/Pages/Chat.razor @@ -83,9 +83,9 @@
- - Send message + + Send message
@@ -100,7 +100,13 @@ } }; + window.clearInput = () => { + document.getElementById('chatInput').value = ''; + }; + function myJavaScriptFunction(wishlistId) { + UpdateMenu(wishlistId); + } document.getElementById('button_open').addEventListener('click', changetyle); @@ -108,16 +114,24 @@ [Parameter] public string chatId { get; set; } + public string inputValue = ""; + protected override async Task OnParametersSetAsync() { await LoadMessages(); } + private void InputChanged(ChangeEventArgs e) + { + inputValue = e.Value.ToString(); + + } + public void Enter(KeyboardEventArgs e) { if (e.Code == "Enter" || e.Code == "NumpadEnter") { - AddNewMessage(); + AddNewMessage(inputValue); } } @@ -128,7 +142,12 @@ await JSRuntime.InvokeVoidAsync("scrollToBottom", chatMessageRef); } + private async Task UpdateSideMenu(string wishlistId) + { + await JSRuntime.InvokeVoidAsync("myJavaScriptFunction", wishlistId); + + } private void ClickOption(string item) { inputValue = item; diff --git a/ShoppingAssistantWebClient.Web/Pages/Chat.razor.cs b/ShoppingAssistantWebClient.Web/Pages/Chat.razor.cs index 282567e..476cdd1 100644 --- a/ShoppingAssistantWebClient.Web/Pages/Chat.razor.cs +++ b/ShoppingAssistantWebClient.Web/Pages/Chat.razor.cs @@ -24,20 +24,53 @@ public partial class Chat : ComponentBase public List Messages { get; set; } + public List Products { get; set; } = new List(); public List Suggestion { get; set; } = new List(); public Messages Message { get; set; } + public Messages MessageBot { get; set; } private CancellationTokenSource cancelTokenSource; - + private bool isWaitingForResponse = false; private MessageCreateDto messageCreateDto; public bool isLoading = true; - private string inputValue = ""; private string name = ""; protected override async Task OnInitializedAsync() { + var input = _searchServise.firstMassage; + + if (input!=null){ + await LoadMessages(); + + await AddNewMessage(input); + + string wishlistId = chatId; + var request = new GraphQLRequest + { + Query = @"mutation GenerateNameForPersonalWishlist($wishlistId: String!) { + generateNameForPersonalWishlist(wishlistId: $wishlistId) { + id + name + } + }", + Variables = new + { + wishlistId + + } + }; + + var response = await _apiClient.QueryAsync(request); + _searchServise.SetFirstMassage(null); + isLoading = false; + await UpdateSideMenu(wishlistId); + StateHasChanged(); + + }else{ + await LoadMessages(); + } } @@ -102,17 +135,24 @@ public partial class Chat : ComponentBase Console.WriteLine($"Error : {ex.Message}"); } } - private async Task AddNewMessage() + private async Task AddNewMessage(string inputMessage) { + + if (!isWaitingForResponse && !string.IsNullOrWhiteSpace(inputMessage)) + { + JSRuntime.InvokeVoidAsync("clearInput"); + isWaitingForResponse = true; + try{ - messageCreateDto = new MessageCreateDto { Text = inputValue };; + messageCreateDto = new MessageCreateDto { Text = inputMessage };; Message = new Messages(); - Message.Text = inputValue; + Message.Text = inputMessage; Message.Role = "User"; Message.Id = ""; Message.CreatedById = ""; - inputValue = ""; + Suggestion = new List(); + Products = new List(); Messages.Add(Message); StateHasChanged(); @@ -122,6 +162,15 @@ public partial class Chat : ComponentBase var serverSentEvent = _apiClient.GetServerSentEventStreamed($"ProductsSearch/search/{chatId}", messageCreateDto, cancellationToken); bool first = true; + MessageBot = new Messages(); + MessageBot.Role = "bot"; + MessageBot.Id = ""; + MessageBot.CreatedById = ""; + MessageBot.Text = "Waiting for response"; + Messages.Add(MessageBot); + var lengt = Messages.Count(); + StateHasChanged(); + await foreach (var sseEvent in serverSentEvent.WithCancellation(cancellationToken)) { Console.WriteLine($"Received SSE Event: {sseEvent.Event}, Data: {sseEvent.Data}"); @@ -133,21 +182,15 @@ public partial class Chat : ComponentBase if(sseEvent.Event == SearchEventType.Message){ - Message = new Messages(); - Message.Text = result; - Message.Role = "bot"; - Message.Id = ""; - Message.CreatedById = ""; - + if (first) { - Messages.Add(Message); + Messages[lengt-1].Text = result; first = false; } else { - var lengt = Messages.Count(); - Messages[lengt-1].Text += Message.Text; + Messages[lengt-1].Text += result; } StateHasChanged(); @@ -158,20 +201,20 @@ public partial class Chat : ComponentBase } else if(sseEvent.Event == SearchEventType.Suggestion){ - Suggestion.Add(sseEvent.Data); + Suggestion.Add(result); } } - if(Products != null) { + if(Products.Count!=0) { string n = name; _searchServise.SetProducts(Products); var url = $"/cards/{name}/{chatId}"; Navigation.NavigateTo(url); } - + isWaitingForResponse = false; } catch(Exception ex){ Console.WriteLine($"Error : {ex.Message}"); } } - + } } diff --git a/ShoppingAssistantWebClient.Web/Pages/Index.razor b/ShoppingAssistantWebClient.Web/Pages/Index.razor index 2dc266f..2ac3083 100644 --- a/ShoppingAssistantWebClient.Web/Pages/Index.razor +++ b/ShoppingAssistantWebClient.Web/Pages/Index.razor @@ -11,8 +11,6 @@ -@if(isLoading == false){ -
New chat
@@ -58,16 +56,6 @@
- -}else{ - -
- - Loading chat - -
- -} diff --git a/ShoppingAssistantWebClient.Web/Pages/Index.razor.cs b/ShoppingAssistantWebClient.Web/Pages/Index.razor.cs index 2cc2915..fdf4235 100644 --- a/ShoppingAssistantWebClient.Web/Pages/Index.razor.cs +++ b/ShoppingAssistantWebClient.Web/Pages/Index.razor.cs @@ -7,6 +7,7 @@ using Newtonsoft.Json; using ShoppingAssistantWebClient.Web.Network; using System; using Microsoft.JSInterop; +using ShoppingAssistantWebClient.Web.Services; namespace ShoppingAssistantWebClient.Web.Pages { @@ -20,13 +21,10 @@ namespace ShoppingAssistantWebClient.Web.Pages private NavigationManager Navigation { get; set; } [Inject] protected IJSRuntime JSRuntime { get; set; } - + [Inject] + private SearchService _searchServise { get; set; } private MessageCreateDto messageCreateDto; - - private CancellationTokenSource cancelTokenSource; - private string inputValue = ""; - public bool isLoading; private async Task CreateNewChat() { @@ -38,7 +36,6 @@ namespace ShoppingAssistantWebClient.Web.Pages return; } - isLoading = true; StateHasChanged(); messageCreateDto = new MessageCreateDto { Text = inputValue }; var type = selectedChoice; @@ -62,58 +59,22 @@ namespace ShoppingAssistantWebClient.Web.Pages var response = await _apiClient.QueryAsync(request); var responseData = response.Data; var chatId = responseData?.startPersonalWishlist?.id; - string wishlistId1 = chatId; - - var text = inputValue; - - cancelTokenSource = new CancellationTokenSource(); - var cancellationToken = cancelTokenSource.Token; - - var serverSentEvent = _apiClient.GetServerSentEventStreamed($"ProductsSearch/search/{chatId}", messageCreateDto, cancellationToken); - - await foreach (var sseEvent in serverSentEvent.WithCancellation(cancellationToken)) - { - // Handle each ServerSentEvent as needed - Console.WriteLine($"Received SSE Event: {sseEvent.Event}, Data: {sseEvent.Data}"); - } - string wishlistId = chatId; - request = new GraphQLRequest - { - Query = @"mutation GenerateNameForPersonalWishlist($wishlistId: String!) { - generateNameForPersonalWishlist(wishlistId: $wishlistId) { - id - name - } - }", - Variables = new - { - wishlistId - - } - }; - response = await _apiClient.QueryAsync(request); + _searchServise.SetFirstMassage(inputValue); + await UpdateSideMenu(wishlistId); - isLoading = false; - StateHasChanged(); - - await UpdateSideMenu(wishlistId1); var url = $"/chat/{chatId}"; Navigation.NavigateTo(url); - } - catch (Exception ex) - { - // Handle exceptions appropriately - Console.WriteLine($"Error in CreateNewChat: {ex.Message}"); - } - finally - { - isLoading = false; - cancelTokenSource?.Dispose(); - } + } + catch (Exception ex) + { + // Handle exceptions appropriately + Console.WriteLine($"Error in CreateNewChat: {ex.Message}"); + } + } } From 22d0311ec425da185c68845eff3a2f128906c44b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C2=96=C2=96AsTroLog?= Date: Wed, 22 Nov 2023 18:07:05 +0000 Subject: [PATCH 5/5] add error handling --- .../Pages/Chat.razor.cs | 55 ++++++++++--------- 1 file changed, 30 insertions(+), 25 deletions(-) diff --git a/ShoppingAssistantWebClient.Web/Pages/Chat.razor.cs b/ShoppingAssistantWebClient.Web/Pages/Chat.razor.cs index 476cdd1..5e1f65a 100644 --- a/ShoppingAssistantWebClient.Web/Pages/Chat.razor.cs +++ b/ShoppingAssistantWebClient.Web/Pages/Chat.razor.cs @@ -38,39 +38,44 @@ public partial class Chat : ComponentBase private string name = ""; protected override async Task OnInitializedAsync() { - var input = _searchServise.firstMassage; + try{ + var input = _searchServise.firstMassage; - if (input!=null){ + if (input!=null){ - await LoadMessages(); + await LoadMessages(); - await AddNewMessage(input); + await AddNewMessage(input); + + string wishlistId = chatId; + var request = new GraphQLRequest + { + Query = @"mutation GenerateNameForPersonalWishlist($wishlistId: String!) { + generateNameForPersonalWishlist(wishlistId: $wishlistId) { + id + name + } + }", + Variables = new + { + wishlistId - string wishlistId = chatId; - var request = new GraphQLRequest - { - Query = @"mutation GenerateNameForPersonalWishlist($wishlistId: String!) { - generateNameForPersonalWishlist(wishlistId: $wishlistId) { - id - name } - }", - Variables = new - { - wishlistId + }; + var response = await _apiClient.QueryAsync(request); + _searchServise.SetFirstMassage(null); + isLoading = false; + await UpdateSideMenu(wishlistId); + StateHasChanged(); + + }else{ + await LoadMessages(); } - }; - - var response = await _apiClient.QueryAsync(request); - _searchServise.SetFirstMassage(null); - isLoading = false; - await UpdateSideMenu(wishlistId); - StateHasChanged(); - - }else{ - await LoadMessages(); + }catch(Exception ex){ + Console.WriteLine($"Error OnInitializedAsync: {ex.Message}"); } + }