Katheryne/Frontend/Shared/ChatZone.razor

132 lines
3.5 KiB
Plaintext

@using Frontend.Models
@using Katheryne.Abstractions
@inject IJSRuntime JsRuntime
@inject IMessageService MessageService
<div class="content-zone">
<div class="chat-zone" id="chat-scroll-zone">
<AntList TItem="ChatMessage" DataSource="@Messages" Split="@false">
<ListItem>
@if (context.Left)
{
<div>
<MessageBubble Message="context"/>
</div>
}
else
{
<div style="margin-left: auto">
<MessageBubble Message="context"/>
</div>
}
</ListItem>
</AntList>
<div style="height: 200px; width: 100%; flex: none">
</div>
</div>
<div class="control-zone">
<div style="padding: 10px 82px 20px">
<div class="input-zone">
<GridRow>
<GridCol Span="22">
<Input TValue="@string" @bind-Value="@MessageSending"
Placeholder="输入以对话" Bordered="@false" OnPressEnter="@SendMessageClicked"/>
</GridCol>
<GridCol Span="2">
<Button Type="@ButtonType.Primary" @onclick="@SendMessageClicked">
发送
</Button>
</GridCol>
</GridRow>
</div>
</div>
</div>
<Modal Title="设置您的昵称"
Visible="@_setUsernameVisible"
OnOk="@SetUsernameOkClicked"
OnCancel="@SetUsernameCancelClicked">
<div>
<Input TValue="@string" Placeholder="用户名"
@bind-Value="@_username"
OnPressEnter="@SetUsernameOkClicked"/>
</div>
</Modal>
</div>
@code
{
private string MessageSending { get; set; } = string.Empty;
private string _username = string.Empty;
private bool _setUsernameVisible = false;
[Parameter]
public List<ChatMessage> Messages { get; set; } = null!;
[Parameter]
public IChatRobot Robot { get; set; } = null!;
protected override void OnInitialized()
{
if (string.IsNullOrEmpty(_username))
{
_setUsernameVisible = true;
}
base.OnInitialized();
}
protected override void OnAfterRender(bool firstRender)
{
if (!firstRender)
{
JsRuntime.InvokeVoidAsync("scrollToSection");
}
base.OnAfterRender(firstRender);
}
private void SendMessageClicked()
{
if (string.IsNullOrWhiteSpace(MessageSending))
{
return;
}
Messages.Add(new ChatMessage
{
Left = false,
Sender = string.IsNullOrEmpty(_username) ? "default" : _username,
Text = MessageSending
});
foreach (string answer in Robot.ChatNext(MessageSending))
{
Messages.Add(new ChatMessage
{
Left = true,
Sender = Robot.RobotName,
Text = answer
});
}
MessageSending = string.Empty;
}
private void SetUsernameOkClicked()
{
if (string.IsNullOrEmpty(_username))
{
MessageService.Warning("昵称不能为空");
return;
}
_setUsernameVisible = false;
}
private void SetUsernameCancelClicked()
{
_setUsernameVisible = false;
}
}