Katheryne/Frontend/Components/Pages/Editor.razor
2023-11-19 12:55:02 +08:00

138 lines
4.3 KiB
Plaintext

@page "/editor"
@using Katheryne.Exceptions
@using Katheryne.Abstractions
@using Frontend.Services
@inject NavigationManager Navigation
@inject IChatRobotFactory RobotFactory
@inject GrammarStorageService GrammarStorage
<Layout>
<Content>
<div class="editor-zone">
<div class="control-zone">
<Space Size="@("0")">
<SpaceItem>
<Tooltip Placement="@Placement.Bottom"
Title="退出语法编辑器">
<Button Type="@ButtonType.Text" OnClick="@QuitButtonClicked">
退出
</Button>
</Tooltip>
</SpaceItem>
<SpaceItem>
<Tooltip Placement="@Placement.Bottom"
Title="编译文法并保存在浏览器缓存中">
<Button Type="@ButtonType.Text" @onclick="@CompileGrammarClicked">
编译
</Button>
</Tooltip>
</SpaceItem>
<SpaceItem>
<Tooltip Placement="@Placement.Bottom"
Title="清除浏览器缓存中的文法">
<Button Type="@ButtonType.Text" @onclick="@ClearGrammarClicked">
清除
</Button>
</Tooltip>
</SpaceItem>
<SpaceItem>
<Button Type="@ButtonType.Text" @onclick="HelpButtonClicked">
帮助
</Button>
</SpaceItem>
</Space>
</div>
<StandaloneCodeEditor Id="code-editor" @ref="@_editor"
ConstructionOptions="GetEditorConstructionOptions"/>
<div class="logging-zone">
<AntList TItem="@string" DataSource="@_logs" Split="@false" @ref="@_logList">
<ListItem Style="padding: 0 0 0">
<p class="logging-item">@context</p>
</ListItem>
</AntList>
</div>
</div>
</Content>
</Layout>
<GrammarHelp @ref="@_grammarHelp"/>
@code {
private StandaloneCodeEditor _editor = null!;
private AntList<string> _logList = null!;
private GrammarHelp _grammarHelp = null!;
private readonly List<string> _logs = new();
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
{
Log("编辑器加载完成");
if (await GrammarStorage.RestoreGrammar())
{
await _editor.SetValue(RobotFactory.GrammarText);
Log("从浏览器中恢复成功");
}
else
{
Log("尚未设置语法");
}
}
await base.OnAfterRenderAsync(firstRender);
}
private StandaloneEditorConstructionOptions GetEditorConstructionOptions(StandaloneCodeEditor editor)
{
return new StandaloneEditorConstructionOptions
{
Language = "yaml",
Value = !string.IsNullOrEmpty(RobotFactory.GrammarText) ? RobotFactory.GrammarText : string.Empty
};
}
private async Task CompileGrammarClicked()
{
string grammarText = await _editor.GetValue();
try
{
Log("编译文法...");
RobotFactory.SetGrammar(grammarText);
Log("编译成功!");
await GrammarStorage.StoreGrammar();
}
catch (GrammarException e)
{
Log($"编译文法遇到错误:{e.Message}");
}
}
private void QuitButtonClicked()
{
Navigation.NavigateTo("/", replace: true);
}
private async Task ClearGrammarClicked()
{
await GrammarStorage.RemoveGrammar();
Log("清除浏览器中的语法成功");
}
private void HelpButtonClicked()
{
_grammarHelp.Show();
}
private void Log(string message)
{
_logs.Add($"{DateTime.Now:HH:mm:ss} {message}");
StateHasChanged();
}
}