first commit -push

This commit is contained in:
dungtt
2025-10-15 15:15:53 +07:00
parent 674ae395be
commit a9577c5756
885 changed files with 74595 additions and 0 deletions

View File

@@ -0,0 +1,31 @@
<MudTooltip Text="@Tooltip" Delay="500">
<button type="button" class="@Class" @onclick="Click">
<span class="mdi @Icon"></span>
</button>
</MudTooltip>
@code {
[Parameter]
public string Icon { get; set; } = "mdi-alpha";
[Parameter]
public string Tooltip { get; set; } = "";
[Parameter]
public bool Large { get; set; }
[Parameter]
public bool Disabled { get; set; }
[Parameter]
public EventCallback OnClick { get; set; }
public string Class => $"{(Large ? "large" : "")} {(Disabled ? "disabled" : "")}";
private async Task Click()
{
if (Disabled) return;
await OnClick.InvokeAsync();
}
}

View File

@@ -0,0 +1,31 @@
button {
width: 22px;
height: 22px;
display: flex;
align-items: center;
justify-content: center;
overflow: hidden;
font-size: 20px;
border-radius: 3px;
margin-left: 5px;
color: white;
}
button:not(.disabled):hover {
background-color: rgba(255,255,255,0.3);
}
button:not(.disabled):active {
background-color: transparent;
}
button.disabled > span.mdi {
color: rgba(255,255,255,0.3) !important;
}
button.large {
width: 32px;
height: 32px;
font-size: 28px;
border-radius: 6px;
}

View File

@@ -0,0 +1,34 @@
@implements IDisposable
@using Microsoft.CodeAnalysis
<pre class="@Class">
@this.Model.Message
</pre>
@code {
[Parameter, EditorRequired]
public ConsoleItemModel Model { get; set; } = null!;
string Class => this.Model.Severity switch
{
DiagnosticSeverity.Info => "console-info",
DiagnosticSeverity.Warning => "console-warning",
DiagnosticSeverity.Error => "console-error",
_ => "console-none"
};
public void Dispose()
{
Model.Changed -= StateHasChanged;
}
protected override void OnAfterRender(bool firstRender)
{
base.OnAfterRender(firstRender);
if(firstRender)
{
Model.Changed += StateHasChanged;
}
}
}

View File

@@ -0,0 +1,21 @@
.console-none {
display: none;
}
.console-info {
color: grey;
margin: 0px;
text-wrap: auto;
}
.console-warning {
color: yellow;
margin: 0px;
text-wrap: auto;
}
.console-error {
color: red;
margin: 0px;
text-wrap: auto;
}

View File

@@ -0,0 +1,216 @@
@using RobotNet.Shares
@using RobotNet.Clients
@using RobotNet.WebApp.Scripts.Models
@inject ISnackbar Snackbar
@inject IHttpClientFactory httpFactory
<MudDialog>
<TitleContent>
<MudText Typo="Typo.h6">
@Title
</MudText>
</TitleContent>
<DialogContent>
<div class="d-flex flex-column" style="width: 500px;">
@foreach (var param in Model.Parameters)
{
<div class="d-flex align-items-center mb-2">
<div class="d-flex flex-row-reverse me-2" style="width: 200px;">
<MudText>@param.Name : </MudText>
</div>
<div style="flex: 1;">
@switch (param.Type)
{
case "System.Boolean":
<MudSwitch T="bool" Color="Color.Primary" @bind-Value="@param.BoolValue" />
break;
case "System.Byte":
<MudNumericField T="byte"
@bind-Value="@param.ByteValue"
Min="@System.Byte.MinValue"
Max="@System.Byte.MaxValue"
Label="@param.Type"
ShrinkLabel="true"
Variant="Variant.Outlined"
Margin="Margin.Dense" />
break;
case "System.SByte":
<MudNumericField T="sbyte"
@bind-Value="@param.SByteValue"
Min="@System.SByte.MinValue"
Max="@System.SByte.MaxValue"
Label="@param.Type"
ShrinkLabel="true"
Variant="Variant.Outlined"
Margin="Margin.Dense" />
break;
case "System.Int16":
<MudNumericField T="short"
@bind-Value="@param.ShortValue"
Min="@System.Int16.MinValue"
Max="@System.Int16.MaxValue"
Label="@param.Type"
ShrinkLabel="true"
Variant="Variant.Outlined"
Margin="Margin.Dense" />
break;
case "System.UInt16":
<MudNumericField T="ushort"
@bind-Value="@param.UShortValue"
Min="@System.UInt16.MinValue"
Max="@System.UInt16.MaxValue"
Label="@param.Type"
ShrinkLabel="true"
Variant="Variant.Outlined"
Margin="Margin.Dense" />
break;
case "System.Int32":
<MudNumericField T="int"
@bind-Value="@param.IntValue"
Min="@System.Int32.MinValue"
Max="@System.Int32.MaxValue"
Label="@param.Type"
ShrinkLabel="true"
Variant="Variant.Outlined"
Margin="Margin.Dense" />
break;
case "System.UInt32":
<MudNumericField T="uint"
@bind-Value="@param.UIntValue"
Min="@System.UInt32.MinValue"
Max="@System.UInt32.MaxValue"
Label="@param.Type"
ShrinkLabel="true"
Variant="Variant.Outlined"
Margin="Margin.Dense" />
break;
case "System.Int64":
<MudNumericField T="long"
@bind-Value="@param.LongValue"
Min="@System.Int64.MinValue"
Max="@System.Int64.MaxValue"
Label="@param.Type"
ShrinkLabel="true"
Variant="Variant.Outlined"
Margin="Margin.Dense" />
break;
case "System.UInt64":
<MudNumericField T="ulong"
@bind-Value="@param.ULongValue"
Min="@System.UInt64.MinValue"
Max="@System.UInt64.MaxValue"
Label="@param.Type"
ShrinkLabel="true"
Variant="Variant.Outlined"
Margin="Margin.Dense" />
break;
case "System.Single":
<MudNumericField T="float"
@bind-Value="@param.FloatValue"
Min="@System.Single.MinValue"
Max="@System.Single.MaxValue"
Label="@param.Type"
ShrinkLabel="true"
Variant="Variant.Outlined"
Margin="Margin.Dense" />
break;
case "System.Double":
<MudNumericField T="double"
@bind-Value="@param.DoubleValue"
Min="@System.Double.MinValue"
Max="@System.Double.MaxValue"
Label="@param.Type"
ShrinkLabel="true"
Variant="Variant.Outlined"
Margin="Margin.Dense" />
break;
case "System.Decimal":
<MudNumericField T="decimal"
@bind-Value="@param.DecimalValue"
Label="@param.Type"
ShrinkLabel="true"
Variant="Variant.Outlined"
Margin="Margin.Dense" />
break;
case "System.String":
<MudTextField @bind-Value="@param.StringValue"
Label="@param.Type"
ShrinkLabel="true"
Variant="Variant.Outlined"
Margin="Margin.Dense" />
break;
case "System.Char":
<MudTextField @bind-Value="@param.CharValue"
MaxLength="1"
Label="@param.Type"
ShrinkLabel="true"
Variant="Variant.Outlined"
Margin="Margin.Dense" />
break;
case "System.Threading.CancellationToken":
<span>
&lt;CancellationToken&gt;
</span>
break;
default:
<MudAlert Severity="Severity.Error" Dense>Unsupport parameter with type @param.Type</MudAlert>
break;
}
</div>
</div>
}
</div>
</DialogContent>
<DialogActions>
<MudButton OnClick="OnCancel">Cancel</MudButton>
<MudButton Color="Color.Primary" OnClick="Instantiate" Disabled="@IsInstantiating">Instantiate</MudButton>
</DialogActions>
</MudDialog>
@code {
[CascadingParameter]
private IMudDialogInstance Dialog { get; set; } = null!;
[Parameter, EditorRequired]
public ScriptMissionModel Model { get; set; } = default!;
public string Title => $"Instantiate Mission {Model.Name}";
private HttpClient http = default!;
private bool IsInstantiating = false;
protected override void OnInitialized()
{
base.OnInitialized();
http = httpFactory.CreateClient("ScriptManagerAPI");
}
private void OnCancel() => Dialog.Cancel();
private async Task Instantiate()
{
if (IsInstantiating) return;
IsInstantiating = true;
StateHasChanged(); // Force UI update to reflect instantiation state
var parameters = Model.Parameters
.Where(p => p.Type != "RobotNet.Script.IRobot")
.ToDictionary(p => p.Name, p => p.ToString());
var result = await http.PostFromJsonAsync<MessageResult<Guid>>("api/ScriptMissions/Runner", new InstanceMissionCreateModel(Model.Name, parameters));
if (result is null)
{
Snackbar.Add("Failed to instantiate mission: server response null", Severity.Error);
}
else if (result.IsSuccess)
{
Snackbar.Add($"Mission {Model.Name} instantiated successfully with ID: {result.Data}", Severity.Success);
Dialog.Close(DialogResult.Ok(Model.Name));
}
else
{
Snackbar.Add($"Failed to instantiate mission: {result.Message}", Severity.Error);
}
}
}

View File

@@ -0,0 +1,259 @@
@implements IDisposable
@using Microsoft.AspNetCore.SignalR.Client
@using RobotNet.WebApp.Scripts.Models
@inject IHttpClientFactory httpFactory
@inject IDialogService DialogService
<div class="flex-grow-1 h-100 position-relative overflow-hidden">
<div @ref="divRef" class="w-100 h-100 position-absolute top-0 start-0 overflow-hidden">
<MudTable Style="margin: 10px;" Items="scriptMissions" Height="@TableHeight" FixedHeader Virtualize Hover Elevation="6">
<ToolBarContent>
<div @ref="toolbarRef" class="w-100 d-flex flex-row">
<h3>Danh sách Script Missions</h3>
<MudSpacer />
</div>
</ToolBarContent>
<ColGroup>
<col style="width:60px;" />
<col />
<col />
<col style="width:60px;" />
<col style="width:60px;" />
</ColGroup>
<HeaderContent>
<MudTh>STT</MudTh>
<MudTh>Tên</MudTh>
<MudTh>Parameters</MudTh>
<MudTh>Script</MudTh>
</HeaderContent>
<RowTemplate>
<MudTd>@context.Index</MudTd>
<MudTd DataLabel="Tên">@context.Name</MudTd>
<MudTd DataLabel="Parameters">
<span>
@if (context.Parameters?.Any() == true)
{
<MudIconButton Icon="@Icons.Material.Filled.Info" Color="Color.Primary" Size="Size.Small"
OnClick="@(() => ShowParametersDialog(context))" />
}
else
{
<span>Không có</span>
}
</span>
</MudTd>
<MudTd DataLabel="Script">
<span>
<MudIconButton Icon="@Icons.Material.Filled.Visibility" Color="Color.Primary" Size="Size.Small"
OnClick="@(() => ShowCodeDialog(context.Code))" />
</span>
</MudTd>
<MudTd>
<span>
<MudIconButton Icon="@Icons.Material.Filled.PlayArrow" Color="Color.Success" Size="Size.Small"
Disabled="@CallDisabled" OnClick="@(() => ShowInstantiateMissionDialog(context))" />
</span>
</MudTd>
</RowTemplate>
</MudTable>
</div>
</div>
<MudDialog @bind-Visible="_parametersDialogOpen">
<DialogContent>
<h6>Thông tin Parameters</h6>
@if (_selectedParameters != null)
{
<MudTable Items="_selectedParameters" Style="min-width: 400px;">
<HeaderContent>
<MudTh>Tên</MudTh>
<MudTh>Kiểu</MudTh>
<MudTh>Default</MudTh>
</HeaderContent>
<RowTemplate>
<MudTd>@context.Name</MudTd>
<MudTd>@context.Type</MudTd>
<MudTd>@context.Default</MudTd>
</RowTemplate>
</MudTable>
}
</DialogContent>
<DialogActions>
<MudButton OnClick="CloseParametersDialog">Đóng</MudButton>
</DialogActions>
</MudDialog>
<MudDialog @bind-Visible="_codeDialogOpen" Style="min-width: 900px;">
<DialogContent>
<h6>Mã Script đầy đủ</h6>
<MudPaper Class="pa-2" Style="overflow-x:auto;">
<pre style="white-space:pre-wrap;word-break:break-all;">@_selectedCode</pre>
</MudPaper>
</DialogContent>
<DialogActions>
<MudButton OnClick="CloseCodeDialog">Đóng</MudButton>
</DialogActions>
</MudDialog>
@code {
[CascadingParameter]
private ProcessorHubClient ProcessorHub { get; set; } = null!;
private string TableHeight = "0px";
private ElementReference divRef;
private ElementReference toolbarRef;
private HttpClient http = default!;
private List<ScriptMissionModel> scriptMissions = [];
// Dialog state
private bool _parametersDialogOpen = false;
private IEnumerable<ScriptValueModel>? _selectedParameters;
private bool _codeDialogOpen = false;
private string? _selectedCode;
protected override async Task OnAfterRenderAsync(bool firstRender)
{
await base.OnAfterRenderAsync(firstRender);
if (firstRender)
{
var rect = await divRef.MudGetBoundingClientRectAsync();
var toolbarRect = await toolbarRef.MudGetBoundingClientRectAsync();
TableHeight = $"{rect.Height - 25 - Math.Max(toolbarRect.Height, 64)}px";
StateHasChanged();
}
}
protected override async Task OnInitializedAsync()
{
await base.OnInitializedAsync();
http = httpFactory.CreateClient("ScriptManagerAPI");
await ReloadData();
if (ProcessorHub.IsConnected)
{
OnProcessorStateChanged(await ProcessorHub.GetState());
}
ProcessorHub.StateChanged += OnProcessorStateChanged;
ProcessorHub.ConnectionStateChanged += OnConnectionStateChanged;
}
private void OnConnectionStateChanged(HubConnectionState state)
{
if (state == HubConnectionState.Connected)
{
_ = InvokeAsync(async Task () =>
{
OnProcessorStateChanged(await ProcessorHub.GetState());
});
}
}
private bool isRebuild = false;
private bool CallDisabled = true;
private void OnProcessorStateChanged(ProcessorState state)
{
if (state == ProcessorState.Building)
{
isRebuild = true;
}
else if (state == ProcessorState.Ready)
{
if (isRebuild)
{
isRebuild = false;
_ = InvokeAsync(async Task () =>
{
await ReloadData();
});
}
}
if (CallDisabled)
{
if (state == ProcessorState.Running)
{
CallDisabled = false;
StateHasChanged();
}
}
else
{
if (state != ProcessorState.Running)
{
CallDisabled = true;
StateHasChanged();
}
}
}
private async Task ReloadData()
{
scriptMissions.Clear();
var missions = await http.GetFromJsonAsync<List<ScriptMissionDto>>("/api/ScriptMissions") ?? [];
foreach (var item in missions.Select((value, index) => (value, index)))
{
scriptMissions.Add(new ScriptMissionModel(item.index + 1, item.value));
}
StateHasChanged();
}
private void ShowParametersDialog(ScriptMissionModel model)
{
_selectedParameters = model.Parameters;
_parametersDialogOpen = true;
StateHasChanged();
}
private void CloseParametersDialog()
{
_parametersDialogOpen = false;
_selectedParameters = null;
StateHasChanged();
}
private void ShowCodeDialog(string code)
{
_selectedCode = code;
_codeDialogOpen = true;
StateHasChanged();
}
private void CloseCodeDialog()
{
_codeDialogOpen = false;
_selectedCode = null;
StateHasChanged();
}
private async Task ShowInstantiateMissionDialog(ScriptMissionModel model)
{
if (CallDisabled) return;
foreach (var parameter in model.Parameters)
{
parameter.Reset();
}
;
var parameters = new DialogParameters<InstantiateMissionDialog>()
{
{x => x.Model, model},
};
var dialog = await DialogService.ShowAsync<InstantiateMissionDialog>("Instantiate new mission", parameters);
var resultDialog = await dialog.Result;
}
public void Dispose()
{
ProcessorHub.StateChanged -= OnProcessorStateChanged;
ProcessorHub.ConnectionStateChanged -= OnConnectionStateChanged;
}
}

View File

@@ -0,0 +1,127 @@
@using Microsoft.AspNetCore.SignalR.Client
@using Microsoft.CodeAnalysis
@implements IDisposable
@inject ISnackbar Snackbar
@inject IDialogService DialogService
<div class="w-100">
<MudCard Class="m-2" Style="height: 300px" Elevation="6">
<MudCardHeader>
<CardHeaderContent>
<MudText Typo="Typo.h6">Process Controller - @State</MudText>
</CardHeaderContent>
<CardHeaderActions>
<ActionButton Icon="mdi-receipt-text-remove" Large Tooltip="Clear console" OnClick="ClearConsole" />
<ActionButton Icon="mdi-refresh text-primary" Large Tooltip="Reset" Disabled="@ResetDisable" OnClick="Reset" />
<ActionButton Icon="mdi-cog-play text-primary" Large Tooltip="Build" Disabled="@BuildDisable" OnClick="Build" />
<ActionButton Icon="mdi-play text-success" Large Tooltip="Run" Disabled="@RunDisable" OnClick="Run" />
<ActionButton Icon="mdi-stop text-danger" Large Tooltip="Stop" Disabled="@StopDisable" OnClick="Stop" />
</CardHeaderActions>
</MudCardHeader>
<MudCardContent>
<ProcessorConsole @ref="processorConsole" />
</MudCardContent>
</MudCard>
</div>
@code {
[CascadingParameter]
private ProcessorHubClient ProcessorHub { get; set; } = null!;
private ProcessorConsole? processorConsole;
public ProcessorState State { get; private set; } = ProcessorState.Idle;
private ProcessorRequest Request = ProcessorRequest.None;
private bool ResetDisable => State != ProcessorState.Idle && State != ProcessorState.Ready && State != ProcessorState.Error && State != ProcessorState.BuildError;
private bool BuildDisable => State != ProcessorState.Idle && State != ProcessorState.Ready && State != ProcessorState.Error && State != ProcessorState.BuildError;
private bool RunDisable => State != ProcessorState.Ready;
private bool StopDisable => State != ProcessorState.Running;
protected override async Task OnInitializedAsync()
{
if (ProcessorHub.IsConnected)
{
OnProcessorStateChanged(await ProcessorHub.GetState());
}
ProcessorHub.StateChanged += OnProcessorStateChanged;
ProcessorHub.RequestChanged += OnRequestChanged;
ProcessorHub.ConnectionStateChanged += OnConnectionStateChanged;
await base.OnInitializedAsync();
}
private void OnConnectionStateChanged(HubConnectionState state)
{
if (state == HubConnectionState.Connected)
{
_ = InvokeAsync(async Task () =>
{
OnProcessorStateChanged(await ProcessorHub.GetState());
});
}
}
private void OnProcessorStateChanged(ProcessorState state)
{
if (State == state) return;
State = state;
StateHasChanged();
}
private void OnRequestChanged(ProcessorRequest request)
{
Request = request;
StateHasChanged();
}
private async Task Reset()
{
var result = await ProcessorHub.Reset();
if (!result.IsSuccess)
{
Snackbar.Add($"Failed to reset processor: {result.Message}", Severity.Error);
}
}
private async Task Build()
{
var result = await ProcessorHub.Build();
if (!result.IsSuccess)
{
Snackbar.Add($"Failed to build processor: {result.Message}", Severity.Error);
}
}
private async Task Run()
{
var result = await ProcessorHub.Run();
if (!result.IsSuccess)
{
Snackbar.Add($"Failed to run processor: {result.Message}", Severity.Error);
}
}
private async Task Stop()
{
var result = await ProcessorHub.Stop();
if (!result.IsSuccess)
{
Snackbar.Add($"Failed to stop processor: {result.Message}", Severity.Error);
}
}
private void ClearConsole()
{
processorConsole?.Clear();
}
public void Dispose()
{
ProcessorHub.StateChanged -= OnProcessorStateChanged;
ProcessorHub.RequestChanged -= OnRequestChanged;
ProcessorHub.ConnectionStateChanged -= OnConnectionStateChanged;
}
}

View File

@@ -0,0 +1,253 @@
@using RobotNet.Shares
@using RobotNet.Clients
@using RobotNet.WebApp.Scripts.Models
@inject ISnackbar Snackbar
@inject IHttpClientFactory httpFactory
<MudDialog>
<TitleContent>
<MudText Typo="Typo.h6">
@Title
</MudText>
</TitleContent>
<DialogContent>
<div class="d-flex flex-column" style="width: 500px;">
<div class="d-flex align-items-center mb-2">
<div class="d-flex flex-row-reverse me-2" style="width: 200px;">
<MudText>@Model.Name : </MudText>
</div>
<div style="flex: 1;">
@switch (Model.TypeName)
{
case "System.Boolean":
<MudSwitch T="bool" Color="Color.Primary" @bind-Value="@ValueModel.BoolValue" />
break;
case "System.Byte":
<MudNumericField T="byte"
@bind-Value="@ValueModel.ByteValue"
Min="@System.Byte.MinValue"
Max="@System.Byte.MaxValue"
Label="@ValueModel.Type"
ShrinkLabel="true"
Variant="Variant.Outlined"
Margin="Margin.Dense" />
break;
case "System.SByte":
<MudNumericField T="sbyte"
@bind-Value="@ValueModel.SByteValue"
Min="@System.SByte.MinValue"
Max="@System.SByte.MaxValue"
Label="@ValueModel.Type"
ShrinkLabel="true"
Variant="Variant.Outlined"
Margin="Margin.Dense" />
break;
case "System.Int16":
<MudNumericField T="short"
@bind-Value="@ValueModel.ShortValue"
Min="@System.Int16.MinValue"
Max="@System.Int16.MaxValue"
Label="@ValueModel.Type"
ShrinkLabel="true"
Variant="Variant.Outlined"
Margin="Margin.Dense" />
break;
case "System.UInt16":
<MudNumericField T="ushort"
@bind-Value="@ValueModel.UShortValue"
Min="@System.UInt16.MinValue"
Max="@System.UInt16.MaxValue"
Label="@ValueModel.Type"
ShrinkLabel="true"
Variant="Variant.Outlined"
Margin="Margin.Dense" />
break;
case "System.Int32":
<MudNumericField T="int"
@bind-Value="@ValueModel.IntValue"
Min="@System.Int32.MinValue"
Max="@System.Int32.MaxValue"
Label="@ValueModel.Type"
ShrinkLabel="true"
Variant="Variant.Outlined"
Margin="Margin.Dense" />
break;
case "System.UInt32":
<MudNumericField T="uint"
@bind-Value="@ValueModel.UIntValue"
Min="@System.UInt32.MinValue"
Max="@System.UInt32.MaxValue"
Label="@ValueModel.Type"
ShrinkLabel="true"
Variant="Variant.Outlined"
Margin="Margin.Dense" />
break;
case "System.Int64":
<MudNumericField T="long"
@bind-Value="@ValueModel.LongValue"
Min="@System.Int64.MinValue"
Max="@System.Int64.MaxValue"
Label="@ValueModel.Type"
ShrinkLabel="true"
Variant="Variant.Outlined"
Margin="Margin.Dense" />
break;
case "System.UInt64":
<MudNumericField T="ulong"
@bind-Value="@ValueModel.ULongValue"
Min="@System.UInt64.MinValue"
Max="@System.UInt64.MaxValue"
Label="@ValueModel.Type"
ShrinkLabel="true"
Variant="Variant.Outlined"
Margin="Margin.Dense" />
break;
case "System.Single":
<MudNumericField T="float"
@bind-Value="@ValueModel.FloatValue"
Min="@System.Single.MinValue"
Max="@System.Single.MaxValue"
Label="@ValueModel.Type"
ShrinkLabel="true"
Variant="Variant.Outlined"
Margin="Margin.Dense" />
break;
case "System.Double":
<MudNumericField T="double"
@bind-Value="@ValueModel.DoubleValue"
Min="@System.Double.MinValue"
Max="@System.Double.MaxValue"
Label="@ValueModel.Type"
ShrinkLabel="true"
Variant="Variant.Outlined"
Margin="Margin.Dense" />
break;
case "System.Decimal":
<MudNumericField T="decimal"
@bind-Value="@ValueModel.DecimalValue"
Label="@ValueModel.Type"
ShrinkLabel="true"
Variant="Variant.Outlined"
Margin="Margin.Dense" />
break;
case "System.String":
<MudTextField @bind-Value="@ValueModel.StringValue"
Label="@ValueModel.Type"
ShrinkLabel="true"
Variant="Variant.Outlined"
Margin="Margin.Dense" />
break;
case "System.Char":
<MudTextField @bind-Value="@ValueModel.CharValue"
MaxLength="1"
Label="@ValueModel.Type"
ShrinkLabel="true"
Variant="Variant.Outlined"
Margin="Margin.Dense" />
break;
case "System.Threading.CancellationToken":
<span>
&lt;CancellationToken&gt;
</span>
break;
default:
<MudAlert Severity="Severity.Error" Dense>Unsupport parameter with type @ValueModel.Type</MudAlert>
break;
}
</div>
</div>
</div>
</DialogContent>
<DialogActions>
<MudButton OnClick="OnCancel">Cancel</MudButton>
<MudButton Color="Color.Primary" OnClick="RequestSetValue" Disabled="@IsRequesing">Update</MudButton>
</DialogActions>
</MudDialog>
@code {
[CascadingParameter]
private IMudDialogInstance Dialog { get; set; } = null!;
[Parameter, EditorRequired]
public ScriptVariableModel Model { get; set; } = default!;
public string Title => $"Set Variable \"{Model.Name}\"";
private HttpClient http = default!;
private ScriptValueModel ValueModel = null!;
private bool IsRequesing = false;
protected override void OnInitialized()
{
base.OnInitialized();
ValueModel = new ScriptValueModel(Model.Name, Model.TypeName, "");
switch (Model.TypeName)
{
case "System.Boolean":
ValueModel.BoolValue = default;
break;
case "System.Byte":
ValueModel.ByteValue = default;
break;
case "System.SByte":
ValueModel.SByteValue = default;
break;
case "System.Int16":
ValueModel.ShortValue = default;
break;
case "System.UInt16":
ValueModel.UShortValue = default;
break;
case "System.Int32":
ValueModel.IntValue = default;
break;
case "System.UInt32":
ValueModel.UIntValue = default;
break;
case "System.Int64":
ValueModel.LongValue = default;
break;
case "System.UInt64":
ValueModel.ULongValue = default;
break;
case "System.Single":
ValueModel.FloatValue = default;
break;
case "System.Double":
ValueModel.DoubleValue = default;
break;
case "System.Decimal":
ValueModel.DecimalValue = default;
break;
}
http = httpFactory.CreateClient("ScriptManagerAPI");
}
private async Task RequestSetValue()
{
if (IsRequesing) return;
IsRequesing = true;
StateHasChanged(); // Force UI update to reflect instantiation state
var result = await http.PutFromJsonAsync<MessageResult>($"/api/ScriptVariables/{ValueModel.Name}", new UpdateVariableModel(ValueModel.Name, ValueModel.ToString()));
if (result == null)
{
Snackbar.Add("Failed to instantiate mission: server response null", Severity.Error);
}
else if (result.IsSuccess)
{
Snackbar.Add(result.Message, Severity.Success);
Dialog.Close();
}
else
{
Snackbar.Add($"Failed to reset variable value: {result.Message}", Severity.Error);
Dialog.Close();
}
}
private void OnCancel() => Dialog.Cancel();
}

View File

@@ -0,0 +1,263 @@
@implements IAsyncDisposable
@using Microsoft.AspNetCore.SignalR.Client
@using RobotNet.WebApp.Scripts.Models
@inject IHttpClientFactory httpFactory
@inject ScriptTaskHubClient ScriptTaskHub
@inject ISnackbar Snackbar
<div class="flex-grow-1 h-100 position-relative overflow-hidden">
<div @ref="divRef" class="w-100 h-100 position-absolute top-0 start-0 overflow-hidden">
<MudTable Style="margin: 10px;" Items="scriptTasks" Height="@TableHeight" FixedHeader Virtualize Hover Elevation="6">
<ToolBarContent>
<div @ref="toolbarRef" class="w-100 d-flex flex-row">
<h3>Danh sách Script Tasks</h3>
<MudSpacer />
</div>
</ToolBarContent>
<ColGroup>
<col style="width:60px;" />
<col />
<col />
<col style="width:60px;" />
<col style="width:60px;" />
</ColGroup>
<HeaderContent>
<MudTh></MudTh>
<MudTh>Tên</MudTh>
<MudTh>Khoảng thời gian (ms)</MudTh>
<MudTh>Enable</MudTh>
<MudTh>Script</MudTh>
</HeaderContent>
<RowTemplate>
<MudTd>@context.Index</MudTd>
<MudTd DataLabel="Tên">@context.Name</MudTd>
<MudTd DataLabel="Khoảng thời gian">@context.Interval</MudTd>
<MudTd DataLabel="Enable">
<MudSwitch T="bool" @bind-Value="context.Enable" @bind-Value:after="@(() => RequestTaskAction(context.Name, context.Enable))" Color="Color.Primary" Disabled="@actionDisable" />
</MudTd>
<MudTd DataLabel="Script">
<MudIconButton Icon="@Icons.Material.Filled.Visibility" Color="Color.Primary" Size="Size.Small"
OnClick="@(() => ShowCodeDialog(context.Code))" />
</MudTd>
</RowTemplate>
</MudTable>
</div>
</div>
<MudDialog @bind-Visible="_codeDialogOpen" Style="min-width: 900px;">
<DialogContent>
<h6>Mã Script đầy đủ</h6>
<MudPaper Class="pa-2" Style="overflow-x:auto;">
<pre style="white-space:pre-wrap;word-break:break-all;">@_selectedCode</pre>
</MudPaper>
</DialogContent>
<DialogActions>
<MudButton OnClick="CloseCodeDialog">Đóng</MudButton>
</DialogActions>
</MudDialog>
@code {
[CascadingParameter]
private ProcessorHubClient ProcessorHub { get; set; } = null!;
private string TableHeight = "0px";
private ElementReference divRef;
private ElementReference toolbarRef;
private HttpClient http = default!;
private List<ScriptTaskModel> scriptTasks = [];
protected override async Task OnAfterRenderAsync(bool firstRender)
{
await base.OnAfterRenderAsync(firstRender);
if (firstRender)
{
var rect = await divRef.MudGetBoundingClientRectAsync();
var toolbarRect = await toolbarRef.MudGetBoundingClientRectAsync();
TableHeight = $"{rect.Height - 25 - Math.Max(toolbarRect.Height, 64)}px";
StateHasChanged();
}
}
// Dialog state
private bool _codeDialogOpen = false;
private string? _selectedCode;
protected override async Task OnInitializedAsync()
{
await base.OnInitializedAsync();
http = httpFactory.CreateClient("ScriptManagerAPI");
await ReloadData();
if (ProcessorHub.IsConnected)
{
OnProcessorStateChanged(await ProcessorHub.GetState());
}
ProcessorHub.StateChanged += OnProcessorStateChanged;
ProcessorHub.ConnectionStateChanged += OnConnectionStateChanged;
ScriptTaskHub.TaskResumed += OnTaskResumed;
ScriptTaskHub.TaskPaused += OnTaskPaused;
await ScriptTaskHub.StartAsync();
}
private void OnConnectionStateChanged(HubConnectionState state)
{
if (state == HubConnectionState.Connected)
{
_ = InvokeAsync(async Task () =>
{
OnProcessorStateChanged(await ProcessorHub.GetState());
});
}
}
private bool isRebuild = false;
private bool actionDisable = true;
private void OnProcessorStateChanged(ProcessorState state)
{
if (state == ProcessorState.Building)
{
isRebuild = true;
}
else if (state == ProcessorState.Ready)
{
if (isRebuild)
{
isRebuild = false;
_ = InvokeAsync(async Task () =>
{
await ReloadData();
});
}
}
if (actionDisable)
{
if (state == ProcessorState.Running)
{
actionDisable = false;
StateHasChanged();
}
}
else
{
if (state != ProcessorState.Running)
{
actionDisable = true;
StateHasChanged();
}
}
if (state == ProcessorState.Running)
{
_ = InvokeAsync(async Task () =>
{
var states = await ScriptTaskHub.GetTaskStates();
foreach (var task in scriptTasks)
{
task.Enable = states.ContainsKey(task.Name) && states[task.Name];
}
StateHasChanged();
});
}
}
private async Task ReloadData()
{
await InvokeAsync(async Task () =>
{
scriptTasks.Clear();
var tasks = await http.GetFromJsonAsync<List<ScriptTaskDto>>("/api/ScriptTasks") ?? [];
foreach (var item in tasks.Select((value, index) => (value, index)))
{
scriptTasks.Add(new ScriptTaskModel(item.index + 1, item.value));
}
if (!actionDisable)
{
var states = await ScriptTaskHub.GetTaskStates();
foreach (var task in scriptTasks)
{
task.Enable = states.ContainsKey(task.Name) && states[task.Name];
}
}
StateHasChanged();
});
}
private void ShowCodeDialog(string code)
{
_selectedCode = code;
_codeDialogOpen = true;
}
private void CloseCodeDialog()
{
_codeDialogOpen = false;
_selectedCode = null;
}
private void OnTaskResumed(string taskName)
{
foreach (var task in scriptTasks)
{
if (task.Name == taskName)
{
task.Enable = true;
StateHasChanged();
break;
}
}
}
private void OnTaskPaused(string taskName)
{
foreach (var task in scriptTasks)
{
if (task.Name == taskName)
{
task.Enable = false;
StateHasChanged();
break;
}
}
}
private async Task RequestTaskAction(string name, bool enable)
{
if (actionDisable) return;
if (enable)
{
var result = await ScriptTaskHub.Resume(name);
if (!result.IsSuccess)
{
Snackbar.Add(result.Message, Severity.Error);
OnTaskPaused(name);
}
}
else
{
var result = await ScriptTaskHub.Pause(name);
if (!result.IsSuccess)
{
Snackbar.Add(result.Message, Severity.Error);
OnTaskResumed(name);
}
}
}
public async ValueTask DisposeAsync()
{
ProcessorHub.StateChanged -= OnProcessorStateChanged;
ProcessorHub.ConnectionStateChanged -= OnConnectionStateChanged;
ScriptTaskHub.TaskResumed -= OnTaskResumed;
ScriptTaskHub.TaskPaused -= OnTaskPaused;
await ScriptTaskHub.StartAsync();
}
}

View File

@@ -0,0 +1,185 @@
@implements IDisposable
@using Microsoft.AspNetCore.SignalR.Client
@using RobotNet.Clients
@using RobotNet.Shares
@inject IHttpClientFactory httpFactory
@inject ISnackbar Snackbar
@inject IDialogService DialogService
<div class="flex-grow-1 h-100 position-relative overflow-hidden">
<div @ref="divRef" class="w-100 h-100 position-absolute top-0 start-0 overflow-hidden">
<MudTable Style="margin: 10px;" Items="_items" Height="@TableHeight" FixedHeader Virtualize Hover Elevation="6">
<ToolBarContent>
<div @ref="toolbarRef" class="w-100 d-flex flex-row">
<h3>Global Variables</h3>
<MudSpacer />
<ActionButton Icon="mdi-refresh text-primary" Large Tooltip="Reset" OnClick="ReloadData" />
</div>
</ToolBarContent>
<ColGroup>
<col style="width:60px;" />
<col />
<col />
<col />
<col style="width:90px;" />
</ColGroup>
<HeaderContent>
<MudTh></MudTh>
<MudTh>Name</MudTh>
<MudTh>Type</MudTh>
<MudTh>Value</MudTh>
<MudTh></MudTh>
</HeaderContent>
<RowTemplate>
<MudTd>@context.Index</MudTd>
<MudTd DataLabel="Name">@context.Name</MudTd>
<MudTd DataLabel="Type">@context.TypeName</MudTd>
<MudTd DataLabel="Value">@context.Value</MudTd>
<MudTd>
<span>
<MudIconButton Icon="@Icons.Material.Filled.Edit" Color="Color.Primary" Size="Size.Small"
Disabled="@CallDisabled" OnClick="@(() => ShowSetValueDialog(context))" />
</span>
<span>
<MudIconButton Icon="@Icons.Material.Filled.Refresh" Color="Color.Secondary" Size="Size.Small"
Disabled="@CallDisabled" OnClick="@(() => ResetValue(context))" />
</span>
</MudTd>
</RowTemplate>
</MudTable>
</div>
</div>
@code {
[CascadingParameter]
private ProcessorHubClient ProcessorHub { get; set; } = null!;
private string TableHeight = "0px";
private ElementReference divRef;
private ElementReference toolbarRef;
private HttpClient http = default!;
private List<ScriptVariableModel> _items = [];
protected override async Task OnAfterRenderAsync(bool firstRender)
{
await base.OnAfterRenderAsync(firstRender);
if (firstRender)
{
var rect = await divRef.MudGetBoundingClientRectAsync();
var toolbarRect = await toolbarRef.MudGetBoundingClientRectAsync();
TableHeight = $"{rect.Height - 25 - Math.Max(toolbarRect.Height, 64)}px";
StateHasChanged();
}
}
protected override async Task OnInitializedAsync()
{
await base.OnInitializedAsync();
http = httpFactory.CreateClient("ScriptManagerAPI");
await ReloadData();
if (ProcessorHub.IsConnected)
{
OnProcessorStateChanged(await ProcessorHub.GetState());
}
ProcessorHub.StateChanged += OnProcessorStateChanged;
ProcessorHub.ConnectionStateChanged += OnConnectionStateChanged;
}
private void OnConnectionStateChanged(HubConnectionState state)
{
if (state == HubConnectionState.Connected)
{
_ = InvokeAsync(async Task () =>
{
OnProcessorStateChanged(await ProcessorHub.GetState());
});
}
}
private bool CallDisabled = true;
private void OnProcessorStateChanged(ProcessorState state)
{
if (state == ProcessorState.Ready)
{
_ = InvokeAsync(async Task () =>
{
await ReloadData();
});
}
if (CallDisabled)
{
if (state == ProcessorState.Running)
{
CallDisabled = false;
StateHasChanged();
}
}
else
{
if (state != ProcessorState.Running)
{
CallDisabled = true;
StateHasChanged();
}
}
}
private async Task ReloadData()
{
_items.Clear();
var vars = await http.GetFromJsonAsync<IEnumerable<ScriptVariableDto>>("/api/ScriptVariables") ?? [];
foreach (var item in vars.Select((value, index) => (value, index)))
{
_items.Add(new ScriptVariableModel(item.index + 1, item.value));
}
StateHasChanged();
}
private async Task ResetValue(ScriptVariableModel model)
{
if (CallDisabled) return;
var result = await http.PutFromJsonAsync<MessageResult>($"/api/ScriptVariables/{model.Name}/Reset", new UpdateVariableModel(model.Name, ""));
if(result == null)
{
Snackbar.Add("Failed to reset variable value: server response null", Severity.Error);
}
else if (result.IsSuccess)
{
Snackbar.Add(result.Message, Severity.Success);
}
else
{
Snackbar.Add($"Failed to reset variable value: {result.Message}", Severity.Error);
}
}
private async Task ShowSetValueDialog(ScriptVariableModel model)
{
if (CallDisabled) return;
var parameters = new DialogParameters<SetVariableValueDialog>()
{
{x => x.Model, model},
};
var dialog = await DialogService.ShowAsync<SetVariableValueDialog>("Set Variable Value", parameters);
var resultDialog = await dialog.Result;
}
public void Dispose()
{
ProcessorHub.StateChanged -= OnProcessorStateChanged;
ProcessorHub.ConnectionStateChanged -= OnConnectionStateChanged;
}
}

View File

@@ -0,0 +1,64 @@
@inject ISnackbar Snackbar
<MudDialog>
<TitleContent>
<MudText Typo="Typo.h6">
@Title
</MudText>
</TitleContent>
<DialogContent>
<div class="d-flex flex-column" style="width: 500px;">
<MudTextField @bind-Value="FileName" Label="@Label" Class="mb-3" ShrinkLabel Variant="Variant.Outlined"
DebounceInterval="500" OnDebounceIntervalElapsed="ValidateName" OnBlur="ValidateName"
Error="@NameError" ErrorText="@NameErrorText" Adornment="@AdornmentVisible" AdornmentText=".cs" />
</div>
</DialogContent>
<DialogActions>
<MudButton OnClick="OnCancel">Cancel</MudButton>
<MudButton Color="Color.Primary" OnClick="OnCreate" Disabled="@CreateButtonDisable">Create</MudButton>
</DialogActions>
</MudDialog>
@code {
[CascadingParameter]
private IMudDialogInstance Dialog { get; set; } = null!;
[Parameter]
public string FolderName { get; set; } = "";
[Parameter]
public bool IsFolder { get; set; } = false;
private string Title => $"Tạo mới {(IsFolder ? "folder" : "file code")}";
private string Label => $"/{FolderName}";
private Adornment AdornmentVisible => IsFolder ? Adornment.None : Adornment.End;
private string FileName { get; set; } = "";
private string NameErrorText = "";
private bool NameError = false;
private bool CreateButtonDisable => NameError;
private void OnCancel() => Dialog.Cancel();
public void OnCreate()
{
ValidateName();
if (NameError)
{
Snackbar.Add("Tên chưa đúng!", Severity.Error);
}
else
{
Dialog.Close(DialogResult.Ok(FileName));
}
}
private void ValidateName()
{
NameErrorText = string.IsNullOrEmpty(FileName) ? "Tên không được để trống" : "";
NameError = !string.IsNullOrEmpty(NameErrorText);
}
}

View File

@@ -0,0 +1,98 @@
@inject ISnackbar Snackbar
<MudDialog>
<TitleContent>
<MudText Typo="Typo.h6">
Danh sách script sẽ xóa
</MudText>
</TitleContent>
<DialogContent>
<div class="d-flex flex-column ms-3 overflow-y-scroll overflow-x-auto" style="height: 200px; width: 500px;">
@foreach (var file in DeleteList)
{
<span>
@file
</span>
}
</div>
</DialogContent>
<DialogActions>
<MudButton OnClick="OnCancel">Cancel</MudButton>
<MudButton Color="Color.Primary" OnClick="OnDelete">Delete</MudButton>
</DialogActions>
</MudDialog>
@code {
[CascadingParameter]
private IMudDialogInstance Dialog { get; set; } = null!;
[Parameter]
public ScriptWorkspace Workspace { get; set; } = null!;
private IEnumerable<string> DeleteList = [];
protected override void OnInitialized()
{
base.OnInitialized();
if (Workspace.SelectedFile is not null)
{
DeleteList = [Workspace.SelectedFile.Path];
StateHasChanged();
}
else if (Workspace.SelectedFolder is not null)
{
DeleteList = GetListFromFolder(Workspace.SelectedFolder);
StateHasChanged();
}
}
private IEnumerable<string> GetListFromFolder(ScriptFolderModel folder)
{
var list = new List<string>();
list.Add(folder.Path);
foreach (var dir in folder.Folders)
{
list.AddRange(GetListFromFolder(dir));
}
foreach (var file in folder.Files)
{
list.Add(file.Path);
}
return list;
}
private void OnCancel() => Dialog.Cancel();
private async Task OnDelete()
{
if (Workspace.SelectedFile is not null)
{
var result = await Workspace.DeleteFile(Workspace.SelectedFile);
if (result.IsSuccess)
{
Dialog.Close();
}
else
{
Snackbar.Add(result.Message, Severity.Error);
}
}
else if (Workspace.SelectedFolder is not null)
{
var result = await Workspace.DeleteFolder(Workspace.SelectedFolder);
if (result.IsSuccess)
{
Dialog.Close();
}
else
{
Snackbar.Add(result.Message, Severity.Error);
}
}
}
}

View File

@@ -0,0 +1,107 @@
@inject ISnackbar Snackbar
<MudDialog>
<TitleContent>
<MudText Typo="Typo.h6">
@Title
</MudText>
</TitleContent>
<DialogContent>
<div class="d-flex flex-column" style="width: 500px;">
<MudTextField @bind-Value="FileName" Label="@Label" Class="mb-3" ShrinkLabel Variant="Variant.Outlined"
DebounceInterval="500" OnDebounceIntervalElapsed="ValidateName" OnBlur="ValidateName"
Error="@NameError" ErrorText="@NameErrorText" Adornment="@AdornmentVisible" AdornmentText=".cs" />
</div>
</DialogContent>
<DialogActions>
<MudButton OnClick="OnCancel">Cancel</MudButton>
<MudButton Color="Color.Primary" OnClick="OnRename" Disabled="@RenameDisabled">Rename</MudButton>
</DialogActions>
</MudDialog>
@code {
[CascadingParameter]
private IMudDialogInstance Dialog { get; set; } = null!;
[Parameter]
public ScriptWorkspace Workspace { get; set; } = null!;
private bool IsFolder;
private string Label = "";
private string Title => IsFolder ? "Rename folder" : "Rename file";
private string NameErrorText = "";
private bool NameError = false;
private string FileName = "";
private string OldName = "";
private bool RenameDisabled => FileName == OldName;
private Adornment AdornmentVisible => IsFolder ? Adornment.None : Adornment.End;
protected override void OnInitialized()
{
base.OnInitialized();
if (Workspace.SelectedFile is not null)
{
IsFolder = false;
Label = Workspace.SelectedFile.Parrent?.Name ?? "/";
FileName = Workspace.SelectedFile.Name;
if (FileName.EndsWith(".cs"))
{
FileName = FileName.Substring(0, FileName.Length - 3);
}
OldName = FileName;
}
else if (Workspace.SelectedFolder is not null)
{
IsFolder = true;
Label = Workspace.SelectedFolder.Parrent?.Name ?? "/";
FileName = Workspace.SelectedFolder.Name;
OldName = FileName;
}
}
private void ValidateName()
{
NameErrorText = string.IsNullOrEmpty(FileName) ? "Tên không được để trống" : "";
NameError = !string.IsNullOrEmpty(NameErrorText);
}
private void OnCancel() => Dialog.Cancel();
private async Task OnRename()
{
ValidateName();
if (NameError)
{
Snackbar.Add("Tên chưa đúng!", Severity.Error);
}
else
{
if (Workspace.SelectedFile is not null)
{
var result = await Workspace.Rename(Workspace.SelectedFile, FileName.EndsWith(".cs") ? FileName : FileName + ".cs");
if (result.IsSuccess)
{
Dialog.Close();
}
else
{
Snackbar.Add(result.Message, Severity.Error);
}
}
else if (Workspace.SelectedFolder is not null)
{
var result = await Workspace.Rename(Workspace.SelectedFolder, FileName);
if (result.IsSuccess)
{
Dialog.Close();
}
else
{
Snackbar.Add(result.Message, Severity.Error);
}
}
}
}
}

View File

@@ -0,0 +1,262 @@
@implements IAsyncDisposable
@using Microsoft.AspNetCore.Components
@using Microsoft.CodeAnalysis
@using Microsoft.CodeAnalysis.Text
@using Microsoft.JSInterop
@using RobotNet.WebApp.Scripts.Monaco
@using RobotNet.WebApp.Scripts.Monaco.Editor
@using RobotNet.WebApp.Scripts.Monaco.Languages
@using System.Timers
@inject IJSRuntime JsRuntime
@inject ISnackbar Snackbar
<div class="w-100 h-100 d-flex flex-column" tabindex="0" @onkeyup:preventDefault @onkeyup:stopPropagation @onkeyup="OnKeyPress">
<div class="w-100 d-flex align-items-center justify-content-between">
<div></div>
<div>@NameFile</div>
<div></div>
</div>
<div @ref=EditorContainer class="flex-grow-1 w-100"></div>
</div>
@code {
[CascadingParameter]
private ScriptWorkspace Workspace { get; set; } = null!;
private object dotNetHelper = default!;
private IJSInProcessObjectReference? editor;
private IJSInProcessObjectReference? editorModel;
private IJSInProcessObjectReference? disposableCompletionItemProvider;
private IJSInProcessObjectReference? disposableSignatureHelpProvider;
private IJSInProcessObjectReference? disposableHoverProvider;
private bool IsEditorInitialized;
private string Code = "";
private string NameFile = "";
public ProcessorState State { get; private set; } = ProcessorState.Idle;
private bool IsReadOnly = true;
private ElementReference EditorContainer;
protected override async Task OnAfterRenderAsync(bool firstRender)
{
await base.OnAfterRenderAsync(firstRender);
if (firstRender)
{
dotNetHelper = DotNetObjectReference.Create(this);
editor = await JsRuntime.InvokeAsync<IJSInProcessObjectReference>("monaco.editor.create", EditorContainer, new
{
Value = "",
Language = "csharp",
Theme = "vs-dark",
GlyphMargin = true,
AutomaticLayout = true,
ReadOnly = IsReadOnly,
});
editorModel = await editor.InvokeAsync<IJSInProcessObjectReference>("getModel");
await JsRuntime.InvokeVoidAsync("MonacoRuntime.OnCodeEditorDidChangeModelContent", editor, dotNetHelper, nameof(CodeEditorDidChangeModelContent));
disposableCompletionItemProvider = await JsRuntime.InvokeAsync<IJSInProcessObjectReference>("MonacoRuntime.CSharpLanguageRegisterCompletionItemProvider", dotNetHelper, nameof(GetCompletionItems));
disposableSignatureHelpProvider = await JsRuntime.InvokeAsync<IJSInProcessObjectReference>("MonacoRuntime.CSharpLanguageRegisterSignatureHelpProvider", dotNetHelper, nameof(GetSignatureHelp));
disposableHoverProvider = await JsRuntime.InvokeAsync<IJSInProcessObjectReference>("MonacoRuntime.CSharpLanguageRegisterHoverProvider", dotNetHelper, nameof(GetQuickInfo));
IsEditorInitialized = true;
Workspace.OnFileChanged += FileChanged;
Workspace.OnDiagnoticChanged += DiagnoticChanged;
}
}
public void OnProcessStateChanged(ProcessorState state)
{
State = state;
var isReadOnly = State != ProcessorState.Ready && State != ProcessorState.Idle && State != ProcessorState.BuildError;
if (isReadOnly != IsReadOnly)
{
IsReadOnly = isReadOnly;
if (editor != null)
{
_ = InvokeAsync(async Task () =>
{
await editor.InvokeVoidAsync("updateOptions", new
{
ReadOnly = IsReadOnly,
});
});
}
}
}
private async Task FileChanged(ScriptFileModel? file)
{
await this.InvokeAsync(async Task () =>
{
if (file is null)
{
NameFile = "";
Code = "";
}
else
{
NameFile = file.Name;
Code = file.EditCode;
}
if (IsEditorInitialized && editor is not null)
{
await editor.InvokeVoidAsync("setValue", Code);
await JsRuntime.InvokeVoidAsync("monaco.editor.setModelMarkers", editorModel, "default", file?.Diagnostics.Select(ToMonacoDiagnostic) ?? []);
// await editor.InvokeVoidAsync("updateOptions", new
// {
// ReadOnly = IsReadOnly,
// });
}
StateHasChanged();
});
}
private async Task DiagnoticChanged(IEnumerable<Diagnostic> diagnostics)
{
await this.InvokeAsync(async Task () =>
{
if (IsEditorInitialized && editor is not null)
{
await JsRuntime.InvokeVoidAsync("monaco.editor.setModelMarkers", editorModel, "default", diagnostics.Select(ToMonacoDiagnostic) ?? []);
}
});
}
[JSInvokable]
public async Task<CompletionList> GetCompletionItems(int line, int column, int kind, char? triggerCharacter)
{
return new()
{
Suggestions = [.. await Workspace.GetCompletionCurrentFileAsync(line, column, kind, triggerCharacter)],
};
}
[JSInvokable]
public async Task<string?> GetQuickInfo(int line, int column)
{
return await Workspace.GetQuickInfoCurrentFile(line, column);
}
[JSInvokable]
public async Task<SignatureHelpResult?> GetSignatureHelp(int line, int column)
{
return await Workspace.GetSignatureHelpCurrentFile(line, column);
}
[JSInvokable]
public async Task CodeEditorDidChangeModelContent(ModelContentChangedEvent e)
{
if (e.IsFlush) return;
if (e.Changes.Length != 0)
{
if (editor is not null)
{
var code = await editor.InvokeAsync<string>("getValue");
if (code != Code)
{
Code = code;
Workspace.WriteDocument(Code);
}
}
}
}
bool isSaving = false;
private async Task OnKeyPress(KeyboardEventArgs e)
{
if ((e.Key == "s" || e.Key == "S") && e.CtrlKey)
{
if(IsReadOnly)
{
Snackbar.Add($"Hệ thống đang ở trạng thái {State}, Không thể thay đổi script", Severity.Warning);
return;
}
if (isSaving) return;
isSaving = true;
var result = await Workspace.SaveCurrentFileAsync();
if (!result.IsSuccess)
{
Snackbar.Add(result.Message, Severity.Error);
}
isSaving = false;
}
}
public async ValueTask DisposeAsync()
{
if (disposableCompletionItemProvider != null)
{
await disposableCompletionItemProvider.InvokeVoidAsync("dispose");
await disposableCompletionItemProvider.DisposeAsync();
disposableCompletionItemProvider = null;
}
if (disposableSignatureHelpProvider != null)
{
await disposableSignatureHelpProvider.InvokeVoidAsync("dispose");
await disposableSignatureHelpProvider.DisposeAsync();
disposableSignatureHelpProvider = null;
}
if (disposableHoverProvider != null)
{
await disposableHoverProvider.InvokeVoidAsync("dispose");
await disposableHoverProvider.DisposeAsync();
disposableHoverProvider = null;
}
if (editorModel != null)
{
await editorModel.InvokeVoidAsync("dispose");
await editorModel.DisposeAsync();
editorModel = null;
}
if (editor != null)
{
await editor.InvokeVoidAsync("dispose");
await editor.DisposeAsync();
editor = null;
}
if (IsEditorInitialized)
{
Workspace.OnFileChanged -= FileChanged;
Workspace.OnDiagnoticChanged -= DiagnoticChanged;
}
GC.SuppressFinalize(this);
}
private static MarkerData ToMonacoDiagnostic(Diagnostic diagnostic)
{
var lineSpan = diagnostic.Location.GetLineSpan();
return new()
{
StartLineNumber = lineSpan.StartLinePosition.Line + 1,
StartColumn = lineSpan.StartLinePosition.Character + 1,
EndLineNumber = lineSpan.EndLinePosition.Line + 1,
EndColumn = lineSpan.EndLinePosition.Character + 1,
Message = diagnostic.GetMessage(),
Severity = diagnostic.Severity switch
{
DiagnosticSeverity.Info => MarkerSeverity.Info,
DiagnosticSeverity.Warning => MarkerSeverity.Warning,
DiagnosticSeverity.Error => MarkerSeverity.Error,
_ => MarkerSeverity.Hint,
},
};
}
}

View File

@@ -0,0 +1,113 @@
@using RobotNet.WebApp.Scripts.Components.Dialogs
@implements IDisposable
@inject IJSRuntime JsRuntime
@inject ISnackbar Snackbar
@inject IDialogService DialogService
<MudMenu Class="w-100 h-100" Dense ActivationEvent="@MouseEvent.RightClick" Size="@Size.Small" PositionAtCursor>
<ActivatorContent>
<div class="editor-hierachy" @onclick="ResetSelect">
<div>
<CascadingValue Value="ItemRadioName" Name="HierachyItemRadioName">
@foreach (var model in Workspace.Folders)
{
<FolderItem Model="model" />
}
@foreach (var model in Workspace.Files)
{
<FileItem Model="model" />
}
</CascadingValue>
</div>
</div>
</ActivatorContent>
<ChildContent>
<MudMenuItem Label="Save" OnClick="SaveSelect" />
<MudMenuItem Label="Rename" OnClick="RenameSelect" />
<MudDivider />
<MudMenuItem Label="Delete" Class="text-danger" OnClick="DeleteSelect" />
</ChildContent>
</MudMenu>
@code {
[CascadingParameter]
private ScriptWorkspace Workspace { get; set; } = null!;
readonly string ItemRadioName = $"script-{Guid.NewGuid()}";
protected override void OnInitialized()
{
base.OnInitialized();
Workspace.RootChanged += OnRootChanged;
}
private void OnRootChanged()
{
this.InvokeAsync(() =>
{
StateHasChanged();
});
}
private async Task ResetSelect()
{
Workspace.SelectFolder(null);
await JsRuntime.InvokeVoidAsync("UncheckRadioAll", ItemRadioName);
}
private async Task SaveSelect()
{
if (Workspace.IsReadOnly)
{
Snackbar.Add($"Hệ thống đang ở trạng thái {Workspace.ProcessorState}, Không thể thay đổi script", Severity.Warning);
return;
}
var results = await Workspace.SaveSelectAsync();
foreach (var result in results)
{
if (!result.IsSuccess)
{
Snackbar.Add(result.Message, Severity.Error);
}
}
}
private async Task DeleteSelect()
{
if (Workspace.IsReadOnly)
{
Snackbar.Add($"Hệ thống đang ở trạng thái {Workspace.ProcessorState}, Không thể thay đổi script", Severity.Warning);
return;
}
// Truyền Workspace vào DeleteFileOrFolderDialog qua parameters
var parameters = new DialogParameters
{
{ "Workspace", Workspace }
};
await DialogService.ShowAsync<DeleteFileOrFolderDialog>("", parameters: parameters);
}
private async Task RenameSelect()
{
if (Workspace.IsReadOnly)
{
Snackbar.Add($"Hệ thống đang ở trạng thái {Workspace.ProcessorState}, Không thể thay đổi script", Severity.Warning);
return;
}
var parameters = new DialogParameters
{
{ "Workspace", Workspace }
};
await DialogService.ShowAsync<RenameFileOrFolderDialog>("", parameters: parameters);
}
public void Dispose()
{
Workspace.RootChanged -= OnRootChanged;
GC.SuppressFinalize(this);
}
}

View File

@@ -0,0 +1,20 @@
.editor-hierachy {
width: 100%;
flex-grow: 1;
position: relative;
overflow: hidden;
background-color: rgb(30, 30, 30);
}
.editor-hierachy > div {
width: 100%;
height: 100%;
position: absolute;
top: 0px;
left: 0px;
overflow: hidden;
}
.editor-hierachy > div:hover {
overflow: auto;
}

View File

@@ -0,0 +1,70 @@
@implements IDisposable
@inject IJSRuntime JsRuntime
<div class="file-item" @onclick:stopPropagation @onclick:preventDefault @onclick="Click" @oncontextmenu="Click">
<input id="@ItemId" type="radio" name="@RadioName" hidden>
@for (int i = 0; i < Model.Level; i++)
{
<div class="indent-guide"></div>
}
<div class="file-icon">
<span class="mdi @Icon"></span>
</div>
<HierachyItemName Model="Model" />
<HierachyItemDiagnostics Model="Model" />
<HierachyItemModified Model="Model" />
</div>
@code {
[CascadingParameter]
private ScriptWorkspace Workspace { get; set; } = null!;
[CascadingParameter(Name = "HierachyItemRadioName")]
protected string RadioName { get; set; } = "script-explorer-item";
[Parameter, EditorRequired]
public ScriptFileModel Model { get; set; } = default!;
Guid ItemId = Guid.NewGuid();
private string Icon => "mdi-language-csharp";
protected override void OnAfterRender(bool firstRender)
{
base.OnAfterRender(firstRender);
if (!firstRender) return;
Model.OnModified += OnModified;
Model.OnDiagnosticsChanged += OnDiagnosticsChanged;
}
private void OnModified()
{
this.InvokeAsync(() =>
{
StateHasChanged();
});
}
private void OnDiagnosticsChanged(int warningCount, int errorCount)
{
this.InvokeAsync(() =>
{
StateHasChanged();
});
}
private async Task Click()
{
await JsRuntime.InvokeVoidAsync("SetRadioChecked", ItemId);
await Workspace.SelectFile(this.Model);
}
public void Dispose()
{
Model.OnModified -= OnModified;
Model.OnDiagnosticsChanged -= OnDiagnosticsChanged;
GC.SuppressFinalize(this);
}
}

View File

@@ -0,0 +1,44 @@
.file-item {
width: 100%;
height: 22px;
display: flex;
flex-direction: row;
align-items: center;
}
.file-item:hover {
background-color: rgba(0,0,0,0.3);
}
.file-item:active {
background-color: transparent !important;
}
.file-item:has(input:checked) {
background-color: rgb(55, 55, 61);
}
.file-item:has(input:checked):focus {
background-color: rgb(4, 57, 94);
outline-color: rgb(0, 120, 212);
}
.indent-guide {
border-right: 1px solid rgba(88,88,88,0.4);
width: 8px;
display: inline;
height: 100%;
}
.file-icon {
display: flex;
height: 16px;
width: 16px;
font-size: 16px;
overflow: hidden;
align-items: center;
justify-content: center;
margin-right: 6px;
margin-left: 6px;
color: #519aba;
}

View File

@@ -0,0 +1,96 @@
@implements IDisposable
@inject IJSRuntime JsRuntime
<div class="folder-item" @onclick:stopPropagation @onclick:preventDefault @onclick="Click" @oncontextmenu="Click">
<input id="@ItemId" type="radio" name="@RadioName" hidden>
@for (int i = 0; i < Model.Level; i++)
{
<div class="indent-guide"></div>
}
<div class="folder-icon">
<span class="mdi @Icon"></span>
</div>
<HierachyItemName Model="Model" />
<HierachyItemDiagnostics Model="Model" />
<HierachyItemModified Model="Model" />
</div>
@if (IsExpaned)
{
@foreach (var model in Model.Folders)
{
<FolderItem Model="model" />
}
@foreach (var model in Model.Files)
{
<FileItem Model="model" />
}
}
@code {
[CascadingParameter]
private ScriptWorkspace Workspace { get; set; } = null!;
[CascadingParameter(Name = "HierachyItemRadioName")]
protected string RadioName { get; set; } = "script-explorer-item";
[Parameter, EditorRequired]
public ScriptFolderModel Model { get; set; } = default!;
Guid ItemId = Guid.NewGuid();
public bool IsExpaned { get; private set; }
private string Icon => IsExpaned ? "mdi-chevron-down" : "mdi-chevron-right";
protected override void OnAfterRender(bool firstRender)
{
base.OnAfterRender(firstRender);
if (firstRender)
{
Model.OnChildrenChanged += OnChildrenChanged;
}
}
private void OnChildrenChanged()
{
this.InvokeAsync(() =>
{
StateHasChanged();
});
}
private async Task Click()
{
await JsRuntime.InvokeVoidAsync("SetRadioChecked", ItemId);
if (Workspace.SelectFolder(this.Model)) return;
if (IsExpaned)
{
Collapse();
}
else
{
Expand();
}
}
public void Collapse()
{
IsExpaned = false;
StateHasChanged();
}
public void Expand()
{
IsExpaned = true;
StateHasChanged();
}
public void Dispose()
{
Model.OnChildrenChanged -= OnChildrenChanged;
GC.SuppressFinalize(this);
}
}

View File

@@ -0,0 +1,47 @@
.folder-item {
width: 100%;
height: 22px;
display: flex;
flex-direction: row;
align-items: center;
}
.folder-item:hover {
background-color: rgba(0,0,0,0.3);
}
.folder-item:active {
background-color: transparent !important;
}
.folder-item:has(input:checked) {
background-color: rgb(55, 55, 61);
}
.folder-item:has(input:checked):focus {
background-color: rgb(4, 57, 94);
outline-color: rgb(0, 120, 212);
}
.indent-guide {
border-right: 1px solid rgba(88,88,88,0.4);
width: 8px;
display: inline;
height: 100%;
}
.folder-icon {
display: flex;
height: 16px;
width: 16px;
font-size: 16px;
overflow: hidden;
align-items: center;
justify-content: center;
margin-right: 6px;
margin-left: 6px;
}
.folder-icon .mdi-language-csharp {
color: #519aba;
}

View File

@@ -0,0 +1,44 @@
@implements IDisposable
@if (Model.ErrorCount > 0)
{
<div class="folder-error">
@ErrorStr
</div>
}
@if (Model.WarningCount > 0)
{
<div class="folder-warnning">
@WarningStr
</div>
}
@code {
[Parameter, EditorRequired]
public IHierachyItemModel Model { get; set; } = default!;
private string ErrorStr => Model.ErrorCount < 10 ? Model.ErrorCount.ToString() : "9+";
private string WarningStr => Model.WarningCount < 10 ? Model.WarningCount.ToString() : "9+";
protected override void OnAfterRender(bool firstRender)
{
base.OnAfterRender(firstRender);
if (firstRender)
{
Model.OnDiagnosticsChanged += OnDiagnosticsChanged;
}
}
private void OnDiagnosticsChanged(int warningCount, int errorCount)
{
StateHasChanged();
}
public void Dispose()
{
Model.OnDiagnosticsChanged -= OnDiagnosticsChanged;
GC.SuppressFinalize(this);
}
}

View File

@@ -0,0 +1,29 @@
.folder-error {
width: 18px;
height: 18px;
color: white;
font-size: 11px;
margin-right: 3px;
border-radius: 50%;
background-color: firebrick;
display: flex;
align-items: center;
justify-content: center;
text-align: center;
overflow: hidden;
}
.folder-warnning {
width: 18px;
height: 18px;
color: white;
font-size: 11px;
margin-right: 3px;
border-radius: 50%;
background-color: darkgoldenrod;
display: flex;
align-items: center;
justify-content: center;
text-align: center;
overflow: hidden;
}

View File

@@ -0,0 +1,28 @@
@if (Model.IsModified)
{
<div class="folder-modified">
M
</div>
}
@code {
[Parameter, EditorRequired]
public IHierachyItemModel Model { get; set; } = default!;
protected override void OnAfterRender(bool firstRender)
{
base.OnAfterRender(firstRender);
if (firstRender)
{
Model.OnModified += StateHasChanged;
}
}
public void Dispose()
{
Model.OnModified -= StateHasChanged;
GC.SuppressFinalize(this);
}
}

View File

@@ -0,0 +1,14 @@
.folder-modified {
width: 18px;
height: 18px;
color: white;
font-size: 11px;
margin-right: 3px;
border-radius: 3px;
background-color: teal;
display: flex;
align-items: center;
justify-content: center;
text-align: center;
overflow: hidden;
}

View File

@@ -0,0 +1,24 @@
<div class="folder-label">
@Model.Name
</div>
@code {
[Parameter, EditorRequired]
public IHierachyItemModel Model { get; set; } = default!;
protected override void OnAfterRender(bool firstRender)
{
base.OnAfterRender(firstRender);
if (firstRender)
{
Model.OnNameChanged += StateHasChanged;
}
}
public void Dispose()
{
Model.OnNameChanged -= StateHasChanged;
GC.SuppressFinalize(this);
}
}

View File

@@ -0,0 +1,6 @@
.folder-label {
color: rgb(204,204,204);
flex-grow: 1;
font-size: 13px;
user-select: none;
}

View File

@@ -0,0 +1,7 @@
<div class="w-100 h-100 d-flex justify-content-center align-items-center">
<MudProgressCircular Color="Color.Info" Indeterminate="true" />
</div>
@code {
}

View File

@@ -0,0 +1,70 @@
@using Microsoft.CodeAnalysis
@implements IAsyncDisposable
@inject ConsoleHubClient consoleHub
@inject IJSRuntime JS
<div class="w-100 h-100 position-relative overflow-hidden">
<div @ref="ScrollViewDiv" class="w-100 h-100 position-absolute overflow-x-hidden overflow-y-scroll">
<div class="ms-2" >
@foreach(var console in Consoles)
{
<ConsoleItem Model="console" />
}
</div>
</div>
</div>
@code {
private ElementReference ScrollViewDiv;
private List<ConsoleItemModel> Consoles = [];
public void AddInfo(string message) => AddMessage(DiagnosticSeverity.Info, message);
public void AddWarning(string message) => AddMessage(DiagnosticSeverity.Warning, message);
public void AddError(string message) => AddMessage(DiagnosticSeverity.Error, message);
public async void AddMessage(DiagnosticSeverity severity, string message)
{
if (Consoles.Any() && Consoles[^1].Severity == severity)
{
Consoles[^1].Append(message);
}
else
{
Consoles.Add(new ConsoleItemModel(severity, message));
StateHasChanged();
}
// Đợi UI cập nhật xong rồi scroll
await Task.Yield();
await JS.InvokeVoidAsync("ScrollToBottom", ScrollViewDiv);
}
public void Clear()
{
Consoles.Clear();
StateHasChanged();
}
protected override async Task OnInitializedAsync()
{
await base.OnInitializedAsync();
consoleHub.MessageInfo += AddInfo;
consoleHub.MessageWarning += AddWarning;
consoleHub.MessageError += AddError;
await consoleHub.StartAsync();
await consoleHub.RegisterAllConsoles();
}
public async ValueTask DisposeAsync()
{
consoleHub.MessageInfo -= AddInfo;
consoleHub.MessageWarning -= AddWarning;
consoleHub.MessageError -= AddError;
await consoleHub.UnregisterAllConsoles();
await consoleHub.StopAsync();
}
}

View File

@@ -0,0 +1,172 @@
@implements IAsyncDisposable
@using Microsoft.CodeAnalysis
@inject ProcessorHubClient processorHub
@inject ISnackbar Snackbar
@inject IDialogService DialogService
<div class="w-100 h-100 d-flex flex-column">
<div class="d-flex flex-row-reverse">
<div class="mx-1"></div>
<ActionButton Icon="mdi-stop text-danger" Large Tooltip="Stop" Disabled="@StopDisable" OnClick="Stop" />
<ActionButton Icon="mdi-play text-success" Large Tooltip="Run" Disabled="@RunDisable" OnClick="Run" />
<ActionButton Icon="mdi-cog-play text-primary" Large Tooltip="Build" Disabled="@BuildDisable" OnClick="Build" />
<ActionButton Icon="mdi-refresh text-primary" Large Tooltip="Reset" Disabled="@ResetDisable" OnClick="Reset" />
<ActionButton Icon="mdi-receipt-text-remove" Large Tooltip="Clear console" OnClick="ClearConsole" />
</div>
<div class="w-100 flex-grow-1">
<ProcessorConsole @ref="processorConsole" />
</div>
</div>
@code {
[CascadingParameter]
private ScriptWorkspace Workspace { get; set; } = null!;
private ProcessorConsole? processorConsole;
public ProcessorState State { get; private set; } = ProcessorState.Idle;
private ProcessorRequest Request = ProcessorRequest.None;
private bool ResetDisable => State != ProcessorState.Idle && State != ProcessorState.Ready && State != ProcessorState.Error && State != ProcessorState.BuildError;
private bool BuildDisable => State != ProcessorState.Idle && State != ProcessorState.Ready && State != ProcessorState.Error && State != ProcessorState.BuildError;
private bool RunDisable => State != ProcessorState.Ready;
private bool StopDisable => State != ProcessorState.Running;
protected override async Task OnInitializedAsync()
{
processorHub.StateChanged += OnStateChanged;
processorHub.RequestChanged += OnRequestChanged;
await processorHub.StartAsync();
OnStateChanged(await processorHub.GetState());
}
private void OnStateChanged(ProcessorState state)
{
if (State == state) return;
State = state;
StateHasChanged();
}
private void OnRequestChanged(ProcessorRequest request)
{
Request = request;
StateHasChanged();
}
private async Task Reset()
{
var result = await processorHub.Reset();
if (!result.IsSuccess)
{
Snackbar.Add($"Failed to reset processor: {result.Message}", Severity.Error);
}
}
private async Task Build()
{
if (Workspace.AnyChanges())
{
bool? confirm = await DialogService.ShowMessageBox("Cảnh báo", "Bạn có muốn lưu lại tất cả thay đổi trước khi build không?", yesText: "Save All", cancelText: "Cancel");
if (confirm != true) return;
bool isError = false;
var saveResults = await Workspace.SaveAllAsync();
foreach (var saveResult in saveResults)
{
if (!saveResult.IsSuccess)
{
if (processorConsole != null)
{
processorConsole.AddError(saveResult.Message);
}
else
{
Snackbar.Add(saveResult.Message, Severity.Error);
}
isError = true;
}
}
if (isError)
{
return;
}
else
{
await Task.Delay(500);
}
}
var diagnostics = await Workspace.GetAllDiagnostics();
if (diagnostics.Any(d => d.Severity == DiagnosticSeverity.Warning || d.Severity == DiagnosticSeverity.Error))
{
foreach (var diagnostic in diagnostics)
{
if (diagnostic.Severity == DiagnosticSeverity.Warning)
{
if (processorConsole != null)
{
processorConsole.AddWarning($"File /{diagnostic}");
}
else
{
Snackbar.Add($"File /{diagnostic}", Severity.Warning);
}
}
else if (diagnostic.Severity == DiagnosticSeverity.Error)
{
if (processorConsole != null)
{
processorConsole.AddError($"File /{diagnostic}");
}
else
{
Snackbar.Add($"File /{diagnostic}", Severity.Error);
}
}
}
}
else
{
var result = await processorHub.Build();
if (!result.IsSuccess)
{
Snackbar.Add($"Failed to build processor: {result.Message}", Severity.Error);
}
}
}
private async Task Run()
{
var result = await processorHub.Run();
if (!result.IsSuccess)
{
Snackbar.Add($"Failed to run processor: {result.Message}", Severity.Error);
}
}
private async Task Stop()
{
var result = await processorHub.Stop();
if (!result.IsSuccess)
{
Snackbar.Add($"Failed to stop processor: {result.Message}", Severity.Error);
}
}
private void ClearConsole()
{
processorConsole?.Clear();
}
public async ValueTask DisposeAsync()
{
processorHub.StateChanged -= OnStateChanged;
processorHub.RequestChanged -= OnRequestChanged;
await processorHub.StopAsync();
}
}

View File

@@ -0,0 +1,75 @@
@using RobotNet.WebApp.Scripts.Components.Dialogs
@inject IDialogService DialogService
@inject ISnackbar Snackbar
<div class="sidebar-actions">
<span></span>
<div class="d-flex flex-row">
<ActionButton Icon="mdi-content-save-all text-primary" Tooltip="Save all" OnClick="SaveAllFiles" />
<ActionButton Icon="mdi-file-plus-outline" Tooltip="New file" OnClick="OpenDialogCreateNewFile" />
<ActionButton Icon="mdi-folder-plus-outline" Tooltip="New folder" OnClick="OpenDialogCreateNewFolder" />
</div>
</div>
@code {
[CascadingParameter]
private ScriptWorkspace Workspace { get; set; } = null!;
private async Task OpenDialogCreateNewFile()
{
var parentPath = Workspace.SelectedFolder?.Path ?? "";
var parameters = new DialogParameters<CreateNewFileOrFolderDialog>()
{
{x => x.FolderName, parentPath},
};
var dialog = await DialogService.ShowAsync<CreateNewFileOrFolderDialog>("Create new file", parameters);
var resultDialog = await dialog.Result;
if (resultDialog is null || resultDialog.Canceled || resultDialog.Data is not string fileName) return;
fileName = fileName.EndsWith(".cs") ? fileName : fileName + ".cs";
var result = await Workspace.CreateNewFile(fileName);
if (!result.IsSuccess)
{
Snackbar.Add(result.Message, Severity.Error);
}
}
private async Task OpenDialogCreateNewFolder()
{
var parentPath = Workspace.SelectedFolder?.Path ?? "";
var parameters = new DialogParameters<CreateNewFileOrFolderDialog>()
{
{x => x.FolderName, parentPath},
{x => x.IsFolder, true },
};
var dialog = await DialogService.ShowAsync<CreateNewFileOrFolderDialog>("Create new folder", parameters);
var resultDialog = await dialog.Result;
if (resultDialog is null || resultDialog.Canceled || resultDialog.Data is not string folderName) return;
var result = await Workspace.CreateNewFolder(folderName);
if (!result.IsSuccess)
{
Snackbar.Add(result.Message, Severity.Error);
}
}
private async Task SaveAllFiles()
{
var results = await Workspace.SaveAllAsync();
foreach(var result in results)
{
if (!result.IsSuccess)
{
Snackbar.Add(result.Message, Severity.Error);
}
}
}
}

View File

@@ -0,0 +1,9 @@
.sidebar-actions {
width: 100%;
display: flex;
flex-direction: row;
justify-content: space-between;
align-items: center;
padding: 5px 5px;
border-bottom: 1px solid rgba(128, 128, 128, 0.3);
}

View File

@@ -0,0 +1,3 @@
@using RobotNet.Script.Shares
@using RobotNet.WebApp.Clients
@using RobotNet.WebApp.Scripts.Models

View File

@@ -0,0 +1,17 @@
using Microsoft.CodeAnalysis;
namespace RobotNet.WebApp.Scripts.Models;
public class ConsoleItemModel(DiagnosticSeverity severity, string message)
{
public string Message { get; private set; } = message;
public DiagnosticSeverity Severity { get; private set; } = severity;
public event Action? Changed;
public void Append(string message)
{
this.Message = $"{Message}{Environment.NewLine}{message}";
Changed?.Invoke();
}
}

View File

@@ -0,0 +1,12 @@
namespace RobotNet.WebApp.Scripts.Models;
public interface IHierachyItemModel
{
string Name { get; }
bool IsModified { get; }
int WarningCount { get; }
int ErrorCount { get; }
event Action? OnModified;
event Action? OnNameChanged;
event Action<int, int>? OnDiagnosticsChanged;
}

View File

@@ -0,0 +1,14 @@
using RobotNet.Script.Shares;
namespace RobotNet.WebApp.Scripts.Models;
public class InstanceMissionModel(int index, InstanceMissionDto mission)
{
public int Index { get; set; } = index;
public Guid Id { get; set; } = mission.Id;
public string MissionName { get; set; } = mission.MissionName;
public string Parameters { get; set; } = mission.Parameters;
public DateTime CreatedAt { get; set; } = mission.CreatedAt;
public MissionStatus Status { get; set; } = mission.Status;
public string? Log { get; set; } = mission.Log ?? string.Empty;
}

View File

@@ -0,0 +1,80 @@
using Microsoft.CodeAnalysis;
using RobotNet.Script.Shares;
namespace RobotNet.WebApp.Scripts.Models;
public class ScriptFileModel(DocumentId id, ScriptFile model, int level, ScriptFolderModel? parrent) : IHierachyItemModel
{
public int Level { get; } = level;
public ScriptFile Model { get; private set; } = model;
public ScriptFolderModel? Parrent { get; } = parrent;
public string Name => Model.Name;
public string Code => Model.Code;
public string Path => System.IO.Path.Combine(Parrent?.Path ?? "", Model.Name);
public DocumentId Id { get; } = id;
public bool IsModified { get; private set; }
public int WarningCount { get; private set; }
public int ErrorCount { get; private set; }
public string EditCode { get; private set; } = model.Code;
public IEnumerable<Diagnostic> Diagnostics { get; private set; } = [];
public event Action? OnModified;
public event Action? OnNameChanged;
public event Action<int, int>? OnDiagnosticsChanged;
public void ChangeCode(string code)
{
EditCode = code;
if (IsModified)
{
if (EditCode == Code)
{
IsModified = false;
OnModified?.Invoke();
}
}
else
{
if (EditCode != Code)
{
IsModified = true;
OnModified?.Invoke();
}
}
}
public void Saved()
{
if (!IsModified || EditCode == Code) return;
Model = new ScriptFile(Name, EditCode);
IsModified = false;
OnModified?.Invoke();
}
public void Rename(string newName)
{
if (string.IsNullOrEmpty(newName)) throw new ArgumentNullException("Tên file không được để trống");
if (Name == newName) return;
Model = new ScriptFile(newName, Code);
OnNameChanged?.Invoke();
}
public void SetDiagnostics(IEnumerable<Diagnostic> diagnostics)
{
Diagnostics = diagnostics;
var warning = Diagnostics.Count(d => d.Severity == DiagnosticSeverity.Warning);
var error = Diagnostics.Count(d => d.Severity == DiagnosticSeverity.Error);
if(WarningCount != warning || ErrorCount != error)
{
OnDiagnosticsChanged?.Invoke(warning - WarningCount, error - ErrorCount);
WarningCount = warning;
ErrorCount = error;
}
}
}

View File

@@ -0,0 +1,101 @@
namespace RobotNet.WebApp.Scripts.Models;
public class ScriptFolderModel(ScriptFolderModel? parrent, string name, int level) : IHierachyItemModel
{
public int Level { get; } = level;
public ScriptFolderModel? Parrent { get; } = parrent;
public string Path => System.IO.Path.Combine(Parrent?.Path ?? "", Name);
public readonly List<ScriptFolderModel> Folders = [];
public readonly List<ScriptFileModel> Files = [];
public bool IsModified { get; private set; }
public int WarningCount { get; private set; }
public int ErrorCount { get; private set; }
public event Action? OnChildrenChanged;
public event Action? OnModified;
public event Action? OnNameChanged;
public event Action<int, int>? OnDiagnosticsChanged;
public string Name { get; private set; } = name;
public void AddFiles(params IEnumerable<ScriptFileModel> files)
{
Files.AddRange(files);
Files.Sort((a, b) => string.Compare(a.Name, b.Name, StringComparison.Ordinal));
IsModified = IsModified || files.Any(file => file.IsModified);
WarningCount += files.Sum(folder => folder.WarningCount);
ErrorCount += files.Sum(folder => folder.ErrorCount);
foreach (var file in files)
{
file.OnModified += UpdateModified;
file.OnDiagnosticsChanged += DiagnosticsChanged;
}
OnModified?.Invoke();
OnChildrenChanged?.Invoke();
}
public void AddFolders(params IEnumerable<ScriptFolderModel> folders)
{
Folders.AddRange(folders);
Folders.Sort((a, b) => string.Compare(a.Name, b.Name, StringComparison.Ordinal));
IsModified = IsModified || folders.Any(folder => folder.IsModified);
WarningCount += folders.Sum(folder => folder.WarningCount);
ErrorCount += folders.Sum(folder => folder.ErrorCount);
foreach (var folder in folders)
{
folder.OnModified += UpdateModified;
folder.OnDiagnosticsChanged += DiagnosticsChanged;
}
OnModified?.Invoke();
OnChildrenChanged?.Invoke();
}
public void RemoveFile(ScriptFileModel file)
{
if(Files.Remove(file))
{
OnChildrenChanged?.Invoke();
}
}
public void RemoveFolder(ScriptFolderModel folder)
{
if(Folders.Remove(folder))
{
OnChildrenChanged?.Invoke();
}
}
public void Rename(string newName)
{
if(string.IsNullOrEmpty(newName)) throw new ArgumentNullException("Tên thư mục không được để trống");
if(Name == newName) return;
Name = newName;
OnNameChanged?.Invoke();
}
private void UpdateModified()
{
IsModified = Files.Any(file => file.IsModified) || Folders.Any(folder => folder.IsModified);
OnModified?.Invoke();
}
private void DiagnosticsChanged(int warningCount, int errorCount)
{
WarningCount += warningCount;
ErrorCount += errorCount;
//WarningCount = Files.Sum(file => file.WarningCount) + Folders.Sum(folder => folder.WarningCount);
//ErrorCount = Files.Sum(file => file.ErrorCount) + Folders.Sum(folder => folder.ErrorCount);
OnDiagnosticsChanged?.Invoke(warningCount, errorCount);
}
}

View File

@@ -0,0 +1,11 @@
using RobotNet.Script.Shares;
namespace RobotNet.WebApp.Scripts.Models;
public class ScriptMissionModel(int index, ScriptMissionDto data)
{
public int Index { get; } = index;
public string Name { get; } = data.Name;
public string Code { get; } = data.Code;
public IEnumerable<ScriptValueModel> Parameters { get; } = [.. data.Parameters.Select(p => new ScriptValueModel(p.Name, p.Type, p.Default ?? ""))];
}

View File

@@ -0,0 +1,247 @@
namespace RobotNet.WebApp.Scripts.Models;
public class ScriptValueModel(string name, string type, string valueDefault)
{
private static readonly Dictionary<string, Type> predefinedMap = new()
{
["System.Boolean"] = typeof(bool),
["System.Byte"] = typeof(byte),
["System.SByte"] = typeof(sbyte),
["System.Int16"] = typeof(short),
["System.UInt16"] = typeof(ushort),
["System.Int32"] = typeof(int),
["System.UInt32"] = typeof(uint),
["System.Int64"] = typeof(long),
["System.UInt64"] = typeof(ulong),
["System.Single"] = typeof(float),
["System.Double"] = typeof(double),
["System.Decimal"] = typeof(decimal),
["System.Char"] = typeof(char),
["System.String"] = typeof(string)
};
public string Name { get; } = name;
public string Type { get; } = type;
public string? Default { get; } = valueDefault;
public object? Value { get; set; } = null;
private void EnsureType(string expectedType)
{
if (Type != expectedType)
throw new InvalidOperationException($"Parameter '{Name}' is not of type '{expectedType}'. Actual type: '{Type}'.");
}
public override string ToString()
{
return Value?.ToString() ?? "null";
}
public bool BoolValue
{
get
{
EnsureType("System.Boolean");
return Value is not null && (bool)Value;
}
set
{
EnsureType("System.Boolean");
Value = value;
}
}
public byte ByteValue
{
get
{
EnsureType("System.Byte");
return Value is null ? default : (byte)Value;
}
set
{
EnsureType("System.Byte");
Value = value;
}
}
public sbyte SByteValue
{
get
{
EnsureType("System.SByte");
return Value is null ? default : (sbyte)Value;
}
set
{
EnsureType("System.SByte");
Value = value;
}
}
public short ShortValue
{
get
{
EnsureType("System.Int16");
return Value is null ? default : (short)Value;
}
set
{
EnsureType("System.Int16");
Value = value;
}
}
public ushort UShortValue
{
get
{
EnsureType("System.UInt16");
return Value is null ? default : (ushort)Value;
}
set
{
EnsureType("System.UInt16");
Value = value;
}
}
public int IntValue
{
get
{
EnsureType("System.Int32");
return Value is null ? default : (int)Value;
}
set
{
EnsureType("System.Int32");
Value = value;
}
}
public uint UIntValue
{
get
{
EnsureType("System.UInt32");
return Value is null ? default : (uint)Value;
}
set
{
EnsureType("System.UInt32");
Value = value;
}
}
public long LongValue
{
get
{
EnsureType("System.Int64");
return Value is null ? default : (long)Value;
}
set
{
EnsureType("System.Int64");
Value = value;
}
}
public ulong ULongValue
{
get
{
EnsureType("System.UInt64");
return Value is null ? default : (ulong)Value;
}
set
{
EnsureType("System.UInt64");
Value = value;
}
}
public float FloatValue
{
get
{
EnsureType("System.Single");
return Value is null ? default : (float)Value;
}
set
{
EnsureType("System.Single");
Value = value;
}
}
public double DoubleValue
{
get
{
EnsureType("System.Double");
return Value is null ? default : (double)Value;
}
set
{
EnsureType("System.Double");
Value = value;
}
}
public decimal DecimalValue
{
get
{
EnsureType("System.Decimal");
return Value is null ? default : (decimal)Value;
}
set
{
EnsureType("System.Decimal");
Value = value;
}
}
public char CharValue
{
get
{
EnsureType("System.Char");
return Value is null ? default : (char)Value;
}
set
{
EnsureType("System.Char");
Value = value;
}
}
public string StringValue
{
get
{
EnsureType("System.String");
return Value is null ? string.Empty : (string)Value;
}
set
{
EnsureType("System.String");
Value = value;
}
}
public void Reset()
{
if (predefinedMap.TryGetValue(Type, out var type))
{
Value = type.IsValueType ? Activator.CreateInstance(type) : (type == typeof(string) ? string.Empty : null);
}
else
{
Value = null;
}
}
}

View File

@@ -0,0 +1,12 @@
using RobotNet.Script.Shares;
namespace RobotNet.WebApp.Scripts.Models;
public class ScriptTaskModel(int index, ScriptTaskDto data)
{
public int Index { get; } = index;
public string Name { get; } = data.Name;
public int Interval { get; } = data.Interval;
public bool Enable { get; set; }
public string Code { get; } = data.Code;
}

View File

@@ -0,0 +1,11 @@
using RobotNet.Script.Shares;
namespace RobotNet.WebApp.Scripts.Models;
public class ScriptVariableModel(int index, ScriptVariableDto variableDto)
{
public int Index { get; } = index;
public string Name { get; } = variableDto.Name;
public string TypeName { get; } = variableDto.TypeName;
public string Value { get; } = variableDto.Value;
}

View File

@@ -0,0 +1,561 @@
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.QuickInfo;
using Microsoft.CodeAnalysis.Text;
using MudBlazor;
using RobotNet.Script.Shares;
using RobotNet.Shares;
using RobotNet.Clients;
using RobotNet.WebApp.Scripts.Monaco;
using RobotNet.WebApp.Scripts.Monaco.Languages;
using System.Net.Http.Json;
using System.Text;
using System.Timers;
namespace RobotNet.WebApp.Scripts.Models;
public class ScriptWorkspace(IHttpClientFactory httpFactory) : IDisposable
{
private static readonly CSharpParseOptions cSharpParse = CSharpParseOptions.Default.WithKind(SourceCodeKind.Script).WithLanguageVersion(LanguageVersion.Latest);
private readonly AdhocWorkspace adhocWorkspace = new();
private readonly ProjectId EditorProjectId = ProjectId.CreateNewId();
public readonly List<ScriptFolderModel> Folders = [];
public readonly List<ScriptFileModel> Files = [];
public ScriptFolderModel? SelectedFolder { get; private set; }
public ScriptFileModel? SelectedFile { get; private set; }
public ScriptFileModel? CurrentFile { get; private set; }
public ProcessorState ProcessorState { get; set; }
public bool IsReadOnly => ProcessorState != ProcessorState.Ready && ProcessorState != ProcessorState.Idle && ProcessorState != ProcessorState.BuildError;
public event Func<ScriptFileModel?, Task>? OnFileChanged;
public event Func<IEnumerable<Diagnostic>, Task>? OnDiagnoticChanged;
public event Action? RootChanged;
private readonly HttpClient http = httpFactory.CreateClient("ScriptManagerAPI");
private readonly System.Timers.Timer DiagnosticTimer = new()
{
AutoReset = false,
Interval = 1000,
};
private bool IsInitialized = false;
public async Task InitializeAsync()
{
if (IsInitialized) return;
IsInitialized = true;
var collectionsDllStream = await http.GetStreamAsync($"dlls/System.Collections.dll");
var runtimeDllStream = await http.GetStreamAsync($"dlls/System.Runtime.dll");
var expressionsDllStream = await http.GetStreamAsync($"dlls/System.Linq.Expressions.dll");
var robotNetDllStream = await http.GetStreamAsync($"dlls/RobotNet.Script.dll");
var robotNetDocBuf = await http.GetByteArrayAsync($"dlls/RobotNet.Script.xml");
var robotNetExpressionsDllStream = await http.GetStreamAsync($"dlls/RobotNet.Script.Expressions.dll");
var robotNetExpressionsDocBuf = await http.GetByteArrayAsync($"dlls/RobotNet.Script.Expressions.xml");
var usingNamespaces = await http.GetFromJsonAsync<IEnumerable<string>>("api/Script/UsingNamespaces") ?? [];
var preCode = await http.GetFromJsonAsync<string>("api/Script/PreCode") ?? "";
var projectInfo = ProjectInfo.Create(EditorProjectId, VersionStamp.Create(), "EditorProject", "EditorAssembly", LanguageNames.CSharp)
.WithMetadataReferences([
MetadataReference.CreateFromStream(collectionsDllStream, MetadataReferenceProperties.Assembly),
MetadataReference.CreateFromStream(runtimeDllStream, MetadataReferenceProperties.Assembly),
MetadataReference.CreateFromStream(expressionsDllStream, MetadataReferenceProperties.Assembly),
MetadataReference.CreateFromStream(robotNetDllStream, MetadataReferenceProperties.Assembly, documentation: XmlDocumentationProvider.CreateFromBytes(robotNetDocBuf)),
MetadataReference.CreateFromStream(robotNetExpressionsDllStream, MetadataReferenceProperties.Assembly, documentation: XmlDocumentationProvider.CreateFromBytes(robotNetExpressionsDocBuf)),
])
.WithCompilationOptions(new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, usings: usingNamespaces))
.WithParseOptions(cSharpParse);
Solution updatedSolution = adhocWorkspace.CurrentSolution.AddProject(projectInfo);
updatedSolution = updatedSolution.AddDocument(DocumentId.CreateNewId(EditorProjectId), "PreScript.cs", SourceText.From(preCode), ["/"], "/PreScript.cs");
if (!adhocWorkspace.TryApplyChanges(updatedSolution)) throw new InvalidOperationException("Khởi tạo project thất bại");
Folders.Clear();
Files.Clear();
var rootFolder = await http.GetFromJsonAsync<ScriptFolder>("api/Script") ?? new ScriptFolder("Script", [], []);
Files.AddRange([.. rootFolder.Files.Select(file => CreateFileModel(file, 0, null))]);
Files.Sort((a, b) => string.Compare(a.Name, b.Name, StringComparison.Ordinal));
Folders.AddRange([.. rootFolder.Folders.Select(folder => CreateFolderModel(folder, 0, null))]);
Folders.Sort((a, b) => string.Compare(a.Name, b.Name, StringComparison.Ordinal));
var editorProject = adhocWorkspace.CurrentSolution.GetProject(EditorProjectId);
if (editorProject == null) return;
var compilation = await editorProject.GetCompilationAsync();
var diagnostics = compilation?.GetDiagnostics() ?? [];
foreach (var file in Files)
{
await GetDiagnosticsToModel(editorProject, diagnostics, file);
}
foreach (var folder in Folders)
{
await GetDiagnosticsToModel(editorProject, diagnostics, folder);
}
DiagnosticTimer.Elapsed += DiagnosticTimer_Elapsed;
RootChanged?.Invoke();
}
private async void DiagnosticTimer_Elapsed(object? sender, ElapsedEventArgs e)
{
var editorProject = adhocWorkspace.CurrentSolution.GetProject(EditorProjectId);
if (editorProject == null) return;
var compilation = await editorProject.GetCompilationAsync();
var diagnostics = compilation?.GetDiagnostics() ?? [];
foreach (var file in Files)
{
await GetDiagnosticsToModel(editorProject, diagnostics, file);
}
foreach (var folder in Folders)
{
await GetDiagnosticsToModel(editorProject, diagnostics, folder);
}
if (OnDiagnoticChanged is not null && CurrentFile is not null)
{
await OnDiagnoticChanged.Invoke(CurrentFile.Diagnostics);
}
}
private static async Task GetDiagnosticsToModel(Project project, IEnumerable<Diagnostic> diagnostics, ScriptFileModel file)
{
var document = project.Solution.GetDocument(file.Id);
if (document == null) return;
var syntaxTree = await document.GetSyntaxTreeAsync();
if (syntaxTree == null) return;
file.SetDiagnostics(diagnostics.Where(d => d.Location.IsInSource && d.Location.SourceTree == syntaxTree));
}
private static async Task GetDiagnosticsToModel(Project project, IEnumerable<Diagnostic> diagnostics, ScriptFolderModel folders)
{
foreach (var file in folders.Files)
{
await GetDiagnosticsToModel(project, diagnostics, file);
}
foreach (var folder in folders.Folders)
{
await GetDiagnosticsToModel(project, diagnostics, folder);
}
}
private ScriptFileModel CreateFileModel(ScriptFile file, int level, ScriptFolderModel? parrent)
{
Solution updatedSolution = adhocWorkspace.CurrentSolution;
var newId = DocumentId.CreateNewId(EditorProjectId);
updatedSolution = updatedSolution.AddDocument(newId, file.Name, SourceText.From(file.Code), parrent?.Path.Split("/"), Path.Combine(parrent?.Path ?? "", file.Name));
if (!adhocWorkspace.TryApplyChanges(updatedSolution)) throw new InvalidOperationException("Tạo document mới thất bại");
var model = new ScriptFileModel(newId, file, level, parrent);
return model;
}
private ScriptFolderModel CreateFolderModel(ScriptFolder folder, int level, ScriptFolderModel? parrent)
{
var model = new ScriptFolderModel(parrent, folder.Name, level);
model.AddFiles([.. folder.Files.Select(file => CreateFileModel(file, level + 1, model))]);
model.AddFolders([.. folder.Folders.Select(dir => CreateFolderModel(dir, level + 1, model))]);
return model;
}
public bool SelectFolder(ScriptFolderModel? folder)
{
if (SelectedFolder != folder)
{
SelectedFolder = folder;
SelectedFile = null;
return true;
}
else
{
return false;
}
}
public async Task SelectFile(ScriptFileModel? file)
{
CurrentFile = file;
SelectedFile = CurrentFile;
SelectedFolder = file?.Parrent;
if (OnFileChanged is not null)
{
await OnFileChanged.Invoke(file);
}
}
public async Task<MessageResult> CreateNewFile(string name)
{
var result = await http.PostFromJsonAsync<MessageResult>("api/Script/File", new CreateModel(SelectedFolder?.Path ?? "", name));
if (result is null)
{
return new(false, "Không thể tạo file mới");
}
if (result.IsSuccess)
{
var file = new ScriptFile(name, "");
if (SelectedFolder is null)
{
Files.Add(CreateFileModel(file, 0, null));
Files.Sort((a, b) => string.Compare(a.Name, b.Name, StringComparison.Ordinal));
RootChanged?.Invoke();
}
else
{
SelectedFolder.AddFiles(CreateFileModel(file, SelectedFolder.Level + 1, SelectedFolder));
}
}
return result;
}
public async Task<MessageResult> CreateNewFolder(string name)
{
var result = await http.PostFromJsonAsync<MessageResult>("api/Script/Directory", new CreateModel(SelectedFolder?.Path ?? "", name));
if (result is null)
{
return new(false, "Không thể tạo thư mục mới");
}
if (result.IsSuccess)
{
var folder = new ScriptFolder(name, [], []);
if (SelectedFolder is null)
{
Folders.Add(CreateFolderModel(folder, 0, null));
Folders.Sort((a, b) => string.Compare(a.Name, b.Name, StringComparison.Ordinal));
RootChanged?.Invoke();
}
else
{
SelectedFolder.AddFolders(CreateFolderModel(folder, SelectedFolder.Level + 1, SelectedFolder));
}
}
return result;
}
public void WriteDocument(string text)
{
if (CurrentFile is null) return;
Solution updatedSolution = adhocWorkspace.CurrentSolution;
updatedSolution = updatedSolution.WithDocumentText(CurrentFile.Id, SourceText.From(text));
if (!adhocWorkspace.TryApplyChanges(updatedSolution)) throw new InvalidOperationException("Cập nhật project ban đầu thất bại");
CurrentFile.ChangeCode(text);
DiagnosticTimer.Stop();
DiagnosticTimer.Start();
}
public async Task<MessageResult> SaveCurrentFileAsync()
{
if (CurrentFile is null || !CurrentFile.IsModified || CurrentFile.EditCode == CurrentFile.Code) return new(true, "");
var result = await http.PatchFromJsonAsync<MessageResult>("api/Script/File", new UpdateModel(CurrentFile.Path, CurrentFile.EditCode));
if (result is null)
{
return new(false, "Không thể update được code");
}
if (result.IsSuccess)
{
CurrentFile.Saved();
}
return result;
}
public async Task<IEnumerable<MessageResult>> SaveSelectAsync()
{
if (SelectedFolder is not null)
{
var results = new List<MessageResult>();
foreach (var subFolder in SelectedFolder.Folders)
{
results.AddRange(await SaveAllAsync(subFolder));
}
results.AddRange(await SaveAllAsync(Files));
return results;
}
else if (SelectedFile is not null)
{
return await SaveAllAsync([SelectedFile]);
}
else
{
return [];
}
}
public async Task<IEnumerable<MessageResult>> SaveAllAsync()
{
var results = new List<MessageResult>();
foreach (var subFolder in Folders)
{
results.AddRange(await SaveAllAsync(subFolder));
}
results.AddRange(await SaveAllAsync(Files));
return results;
}
private async Task<IEnumerable<MessageResult>> SaveAllAsync(IEnumerable<ScriptFileModel> files)
{
var results = new List<MessageResult>();
foreach (var file in files)
{
if (!file.IsModified || file.EditCode == file.Code) continue;
var result = await http.PatchFromJsonAsync<MessageResult>("api/Script/File", new UpdateModel(file.Path, file.EditCode));
if (result is null)
{
results.Add(new(false, $"Không thể update được code của {file.Name}"));
continue;
}
if (result.IsSuccess)
{
file.Saved();
}
results.Add(result);
}
return results;
}
private async Task<IEnumerable<MessageResult>> SaveAllAsync(ScriptFolderModel folder)
{
var results = new List<MessageResult>();
results.AddRange(await SaveAllAsync(folder.Files));
foreach (var subFolder in folder.Folders)
{
results.AddRange(await SaveAllAsync(subFolder));
}
return results;
}
public async Task<MessageResult> DeleteFile(ScriptFileModel file)
{
var result = await http.DeleteFromJsonAsync<MessageResult>($"api/Script/File?path={file.Path}");
if (result?.IsSuccess ?? false)
{
if (Files.Remove(file))
{
RootChanged?.Invoke();
}
else
{
file.Parrent?.RemoveFile(file);
}
if (SelectedFile == file)
{
await SelectFile(null);
}
Solution updatedSolution = adhocWorkspace.CurrentSolution;
updatedSolution = updatedSolution.RemoveDocument(file.Id);
if (!adhocWorkspace.TryApplyChanges(updatedSolution))
{
return new(false, "Xóa document trong workspace mới thất bại");
}
DiagnosticTimer.Stop();
DiagnosticTimer.Start();
}
return result ?? new MessageResult(false, "Lỗi server response");
}
public async Task<MessageResult> DeleteFolder(ScriptFolderModel folder)
{
var result = await http.DeleteFromJsonAsync<MessageResult>($"api/Script/Directory?path={folder.Path}");
if (result?.IsSuccess ?? false)
{
if (Folders.Remove(folder))
{
RootChanged?.Invoke();
}
else
{
folder.Parrent?.RemoveFolder(folder);
}
Solution updatedSolution = adhocWorkspace.CurrentSolution;
await RemoveFolderFromWorkspace(updatedSolution, folder);
if (!adhocWorkspace.TryApplyChanges(updatedSolution))
{
return new(false, "Xóa document trong workspace mới thất bại");
}
DiagnosticTimer.Stop();
DiagnosticTimer.Start();
}
return result ?? new MessageResult(false, "Lỗi server response");
}
private async Task RemoveFolderFromWorkspace(Solution updatedSolution, ScriptFolderModel folder)
{
foreach (var dir in folder.Folders)
{
await RemoveFolderFromWorkspace(updatedSolution, dir);
}
foreach (var file in folder.Files)
{
if (SelectedFile == file)
{
_ = SelectFile(null);
}
updatedSolution = updatedSolution.RemoveDocument(file.Id);
}
}
public async Task<MessageResult> Rename(ScriptFolderModel folder, string newName)
{
var result = await http.PatchFromJsonAsync<MessageResult>("api/Script/DirectoryName", new RenameModel(folder.Path, newName));
if (result?.IsSuccess ?? false)
{
folder.Rename(newName);
}
return result ?? new MessageResult(false, "Lỗi server response");
}
public async Task<MessageResult> Rename(ScriptFileModel file, string newName)
{
var result = await http.PatchFromJsonAsync<MessageResult>("api/Script/FileName", new RenameModel(file.Path, newName));
if (result?.IsSuccess ?? false)
{
file.Rename(newName);
}
return result ?? new MessageResult(false, "Lỗi server response");
}
public bool AnyChanges() => AnyChanges(Files) || Folders.Any(AnyChanges);
private static bool AnyChanges(ScriptFolderModel folder) => AnyChanges(folder.Files) || folder.Folders.Any(AnyChanges);
private static bool AnyChanges(IEnumerable<ScriptFileModel> files) => files.Any(file => file.IsModified);
public async Task<IEnumerable<Diagnostic>> GetAllDiagnostics()
{
var editorProject = adhocWorkspace.CurrentSolution.GetProject(EditorProjectId);
if (editorProject == null) return [];
var compilation = await editorProject.GetCompilationAsync();
return compilation?.GetDiagnostics() ?? [];
}
public async Task<IEnumerable<Monaco.Languages.CompletionItem>> GetCompletionCurrentFileAsync(int line, int column, int kind, char? triggerCharacter)
{
return CurrentFile is null ? [] : await adhocWorkspace.GetCompletionAsync(CurrentFile.Id, line, column, kind, triggerCharacter);
}
public async Task<string?> GetQuickInfoCurrentFile(int line, int column)
{
if (CurrentFile is null) return null;
var document = adhocWorkspace.CurrentSolution.GetDocument(CurrentFile.Id);
if (document is null) return null;
var sourceText = await document.GetTextAsync();
var position = sourceText.Lines.GetPosition(new LinePosition(line - 1, column - 1));
var quickInfoService = QuickInfoService.GetService(document);
if (quickInfoService is null) return string.Empty;
var quickInfo = await quickInfoService.GetQuickInfoAsync(document, position);
if (quickInfo is null) return string.Empty;
var finalTextBuilder = new StringBuilder();
bool lastSectionHadLineBreak = true;
var description = quickInfo.Sections.FirstOrDefault(s => s.Kind == QuickInfoSectionKinds.Description);
if (description is not null)
{
finalTextBuilder.AppendSection(description, MarkdownFormat.AllTextAsCSharp, ref lastSectionHadLineBreak);
}
var summary = quickInfo.Sections.FirstOrDefault(s => s.Kind == QuickInfoSectionKinds.DocumentationComments);
if (summary is not null)
{
finalTextBuilder.AppendSection(summary, MarkdownFormat.Default, ref lastSectionHadLineBreak);
}
foreach (var section in quickInfo.Sections)
{
switch (section.Kind)
{
case QuickInfoSectionKinds.Description:
case QuickInfoSectionKinds.DocumentationComments:
continue;
case QuickInfoSectionKinds.TypeParameters:
finalTextBuilder.AppendSection(section, MarkdownFormat.AllTextAsCSharp, ref lastSectionHadLineBreak);
break;
case QuickInfoSectionKinds.AnonymousTypes:
// The first line is "Anonymous Types:"
// Then we want all anonymous types to be C# highlighted
finalTextBuilder.AppendSection(section, MarkdownFormat.FirstLineDefaultRestCSharp, ref lastSectionHadLineBreak);
break;
case "NullabilityAnalysis":
// Italicize the nullable analysis for emphasis.
finalTextBuilder.AppendSection(section, MarkdownFormat.Italicize, ref lastSectionHadLineBreak);
break;
default:
finalTextBuilder.AppendSection(section, MarkdownFormat.Default, ref lastSectionHadLineBreak);
break;
}
}
return finalTextBuilder.ToString().Trim();
}
public async Task<SignatureHelpResult?> GetSignatureHelpCurrentFile(int line, int column)
{
if (CurrentFile is null) return null;
var document = adhocWorkspace.CurrentSolution.GetDocument(CurrentFile.Id);
if (document is null) return null;
return await document.GetSignatureHelpAsync(line, column);
}
private bool isDisposed = false;
public void Dispose()
{
if (isDisposed) throw new NotImplementedException();
isDisposed = true;
DiagnosticTimer.Elapsed -= DiagnosticTimer_Elapsed;
DiagnosticTimer.Stop();
adhocWorkspace.Dispose();
DiagnosticTimer.Dispose();
GC.SuppressFinalize(this);
}
}

View File

@@ -0,0 +1,196 @@
using System.Text;
using System.Xml;
namespace RobotNet.WebApp.Scripts.Monaco.Documentation;
public class DocumentationComment(
string summaryText = "",
DocumentationItem[]? typeParamElements = null,
DocumentationItem[]? paramElements = null,
string returnsText = "",
string remarksText = "",
string exampleText = "",
string valueText = "",
DocumentationItem[]? exception = null)
{
public string SummaryText { get; } = summaryText;
public DocumentationItem[] TypeParamElements { get; } = typeParamElements ?? [];
public DocumentationItem[] ParamElements { get; } = paramElements ?? [];
public string ReturnsText { get; } = returnsText;
public string RemarksText { get; } = remarksText;
public string ExampleText { get; } = exampleText;
public string ValueText { get; } = valueText;
public DocumentationItem[] Exception { get; } = exception ?? [];
public static DocumentationComment? From(string xmlDocumentation, string lineEnding)
{
if (string.IsNullOrEmpty(xmlDocumentation))
return Empty;
var reader = new StringReader("<docroot>" + xmlDocumentation + "</docroot>");
var summaryText = new StringBuilder();
var typeParamElements = new List<DocumentationItemBuilder>();
var paramElements = new List<DocumentationItemBuilder>();
var returnsText = new StringBuilder();
var remarksText = new StringBuilder();
var exampleText = new StringBuilder();
var valueText = new StringBuilder();
var exception = new List<DocumentationItemBuilder>();
using (var xml = XmlReader.Create(reader))
{
try
{
xml.Read();
string? elementName = null;
StringBuilder? currentSectionBuilder = null;
do
{
if (xml.NodeType == XmlNodeType.Element)
{
elementName = xml.Name.ToLowerInvariant();
switch (elementName)
{
case "filterpriority":
xml.Skip();
break;
case "remarks":
currentSectionBuilder = remarksText;
break;
case "example":
currentSectionBuilder = exampleText;
break;
case "exception":
DocumentationItemBuilder exceptionInstance = new(GetCref(xml["cref"]).TrimEnd());
currentSectionBuilder = exceptionInstance.Documentation;
exception.Add(exceptionInstance);
break;
case "returns":
currentSectionBuilder = returnsText;
break;
case "summary":
currentSectionBuilder = summaryText;
break;
case "see":
if (currentSectionBuilder is null) continue;
currentSectionBuilder.Append(GetCref(xml["cref"]));
currentSectionBuilder.Append(xml["langword"]);
break;
case "seealso":
if (currentSectionBuilder is null) continue;
currentSectionBuilder.Append("See also: ");
currentSectionBuilder.Append(GetCref(xml["cref"]));
break;
case "paramref":
if (currentSectionBuilder is null) continue;
currentSectionBuilder.Append(xml["name"]);
currentSectionBuilder.Append(' ');
break;
case "param":
DocumentationItemBuilder paramInstance = new(TrimMultiLineString(xml["name"] ?? "", lineEnding));
currentSectionBuilder = paramInstance.Documentation;
paramElements.Add(paramInstance);
break;
case "typeparamref":
if (currentSectionBuilder is null) continue;
currentSectionBuilder.Append(xml["name"]);
currentSectionBuilder.Append(' ');
break;
case "typeparam":
DocumentationItemBuilder typeParamInstance = new(TrimMultiLineString(xml["name"] ?? "", lineEnding));
currentSectionBuilder = typeParamInstance.Documentation;
typeParamElements.Add(typeParamInstance);
break;
case "value":
currentSectionBuilder = valueText;
break;
case "br":
case "para":
if (currentSectionBuilder is null) continue;
currentSectionBuilder.Append(lineEnding);
break;
}
}
else if (xml.NodeType == XmlNodeType.Text && currentSectionBuilder != null)
{
if (elementName == "code")
{
currentSectionBuilder.Append(xml.Value);
}
else
{
currentSectionBuilder.Append(TrimMultiLineString(xml.Value, lineEnding));
}
}
} while (xml.Read());
}
catch (Exception)
{
return null;
}
}
return new DocumentationComment(
summaryText.ToString(),
typeParamElements.Select(s => s.ConvertToDocumentedObject()).ToArray(),
paramElements.Select(s => s.ConvertToDocumentedObject()).ToArray(),
returnsText.ToString(),
remarksText.ToString(),
exampleText.ToString(),
valueText.ToString(),
exception.Select(s => s.ConvertToDocumentedObject()).ToArray());
}
private static string TrimMultiLineString(string input, string lineEnding)
{
var lines = input.Split(separator, StringSplitOptions.RemoveEmptyEntries);
return string.Join(lineEnding, lines.Select(l => TrimStartRetainingSingleLeadingSpace(l)));
}
private static string GetCref(string? cref)
{
if (cref == null || cref.Trim().Length == 0)
{
return "";
}
if (cref.Length < 2)
{
return cref;
}
if (cref.Substring(1, 1) == ":")
{
return string.Concat(cref.AsSpan(2, cref.Length - 2), " ");
}
return cref + " ";
}
private static string TrimStartRetainingSingleLeadingSpace(string input)
{
if (string.IsNullOrWhiteSpace(input))
return string.Empty;
if (!char.IsWhiteSpace(input[0]))
return input;
return $" {input.TrimStart()}";
}
public string GetParameterText(string name)
=> Array.Find(ParamElements, parameter => parameter.Name == name)?.Documentation ?? string.Empty;
public string GetTypeParameterText(string name)
=> Array.Find(TypeParamElements, typeParam => typeParam.Name == name)?.Documentation ?? string.Empty;
public static readonly DocumentationComment Empty = new();
private static readonly string[] separator = ["\n", "\r\n"];
}
class DocumentationItemBuilder(string name)
{
public string Name { get; set; } = name;
public StringBuilder Documentation { get; set; } = new StringBuilder();
public DocumentationItem ConvertToDocumentedObject()
{
return new DocumentationItem(Name, Documentation.ToString());
}
}

View File

@@ -0,0 +1,169 @@
using Microsoft.CodeAnalysis;
using System.Text;
using System.Xml;
namespace RobotNet.WebApp.Scripts.Monaco.Documentation;
public class DocumentationConverter
{/// <summary>
/// Converts the xml documentation string into a plain text string.
/// </summary>
public static string ConvertDocumentation(string xmlDocumentation, string lineEnding)
{
if (string.IsNullOrEmpty(xmlDocumentation))
return string.Empty;
var reader = new StringReader("<docroot>" + xmlDocumentation + "</docroot>");
using var xml = XmlReader.Create(reader);
var ret = new StringBuilder();
try
{
xml.Read();
string? elementName = null;
do
{
if (xml.NodeType == XmlNodeType.Element)
{
elementName = xml.Name.ToLowerInvariant();
switch (elementName)
{
case "filterpriority":
xml.Skip();
break;
case "remarks":
ret.Append(lineEnding);
ret.Append("Remarks:");
ret.Append(lineEnding);
break;
case "example":
ret.Append(lineEnding);
ret.Append("Example:");
ret.Append(lineEnding);
break;
case "exception":
ret.Append(lineEnding);
ret.Append(GetCref(xml["cref"]).TrimEnd());
ret.Append(": ");
break;
case "returns":
ret.Append(lineEnding);
ret.Append("Returns: ");
break;
case "see":
ret.Append(GetCref(xml["cref"]));
ret.Append(xml["langword"]);
break;
case "seealso":
ret.Append(lineEnding);
ret.Append("See also: ");
ret.Append(GetCref(xml["cref"]));
break;
case "paramref":
ret.Append(xml["name"]);
ret.Append(' ');
break;
case "typeparam":
ret.Append(lineEnding);
ret.Append('<');
ret.Append(TrimMultiLineString(xml["name"], lineEnding));
ret.Append(">: ");
break;
case "param":
ret.Append(lineEnding);
ret.Append(TrimMultiLineString(xml["name"], lineEnding));
ret.Append(": ");
break;
case "value":
ret.Append(lineEnding);
ret.Append("Value: ");
ret.Append(lineEnding);
break;
case "br":
case "para":
ret.Append(lineEnding);
break;
}
}
else if (xml.NodeType == XmlNodeType.Text)
{
if (elementName == "code")
{
ret.Append(xml.Value);
}
else
{
ret.Append(TrimMultiLineString(xml.Value, lineEnding));
}
}
} while (xml.Read());
}
catch (Exception)
{
return xmlDocumentation;
}
return ret.ToString();
}
private static readonly string[] separator = ["\n", "\r\n"];
private static string TrimMultiLineString(string? input, string lineEnding)
{
if (string.IsNullOrEmpty(input)) return "";
var lines = input.Split(separator, StringSplitOptions.RemoveEmptyEntries);
return string.Join(lineEnding, lines.Select(l => l.TrimStart()));
}
private static string GetCref(string? cref)
{
if (cref == null || cref.Trim().Length == 0)
{
return "";
}
if (cref.Length < 2)
{
return cref;
}
if (cref.Substring(1, 1) == ":")
{
return cref[2..] + " ";
}
return cref + " ";
}
public static DocumentationComment? GetStructuredDocumentation(string? xmlDocumentation, string lineEnding)
{
if (string.IsNullOrEmpty(xmlDocumentation)) return null;
return DocumentationComment.From(xmlDocumentation, lineEnding);
}
public static DocumentationComment? GetStructuredDocumentation(ISymbol symbol, string lineEnding = "\n")
{
return symbol switch
{
IParameterSymbol parameter => new DocumentationComment(summaryText: GetParameterDocumentation(parameter, lineEnding) ?? ""),
ITypeParameterSymbol typeParam => new DocumentationComment(summaryText: GetTypeParameterDocumentation(typeParam, lineEnding) ?? ""),
IAliasSymbol alias => new DocumentationComment(summaryText: GetAliasDocumentation(alias, lineEnding) ?? ""),
_ => GetStructuredDocumentation(symbol.GetDocumentationCommentXml(), lineEnding),
};
}
private static string? GetParameterDocumentation(IParameterSymbol parameter, string lineEnding = "\n")
{
var contaningSymbolDef = parameter.ContainingSymbol.OriginalDefinition;
return GetStructuredDocumentation(contaningSymbolDef.GetDocumentationCommentXml(), lineEnding)
?.GetParameterText(parameter.Name);
}
private static string? GetTypeParameterDocumentation(ITypeParameterSymbol typeParam, string lineEnding = "\n")
{
var contaningSymbol = typeParam.ContainingSymbol;
return GetStructuredDocumentation(contaningSymbol.GetDocumentationCommentXml(), lineEnding)
?.GetTypeParameterText(typeParam.Name);
}
private static string? GetAliasDocumentation(IAliasSymbol alias, string lineEnding = "\n")
{
return GetStructuredDocumentation(alias.Target.GetDocumentationCommentXml(), lineEnding)?.SummaryText;
}
}

View File

@@ -0,0 +1,7 @@
namespace RobotNet.WebApp.Scripts.Monaco.Documentation;
public class DocumentationItem(string name, string documentation)
{
public string Name { get; } = name;
public string Documentation { get; } = documentation;
}

View File

@@ -0,0 +1,16 @@
namespace RobotNet.WebApp.Scripts.Monaco.Editor;
public struct MarkerData
{
public string Code { get; set; }
public int EndColumn { get; set; }
public int EndLineNumber { get; set; }
public string Message { get; set; }
public int ModelVersionId { get; set; }
public RelatedInformation[] RelatedInformation { get; set; }
public MarkerSeverity Severity { get; set; }
public string Source { get; set; }
public int StartColumn { get; set; }
public int StartLineNumber { get; set; }
public MarkerData[] Tags { get; set; }
}

View File

@@ -0,0 +1,9 @@
namespace RobotNet.WebApp.Scripts.Monaco.Editor;
public struct ModelContentChange
{
public Range Range { get; set; }
public int RangeLength { get; set; }
public int RangeOffset { get; set; }
public string Text { get; set; }
}

View File

@@ -0,0 +1,12 @@
namespace RobotNet.WebApp.Scripts.Monaco.Editor;
public struct ModelContentChangedEvent
{
public ModelContentChange[] Changes { get; set; }
public string Eol { get; set; }
public bool IsEolChange { get; set; }
public bool IsFlush { get; set; }
public bool IsRedoing { get; set; }
public bool IsUndoing { get; set; }
public int VersionId { get; set; }
}

View File

@@ -0,0 +1,11 @@
namespace RobotNet.WebApp.Scripts.Monaco.Editor;
public struct RelatedInformation
{
public int EndColumn { get; set; }
public int EndLineNumber { get; set; }
public string Message { get; set; }
public string Resource { get; set; }
public int StartColumn { get; set; }
public int StartLineNumber { get; set; }
}

View File

@@ -0,0 +1,8 @@
namespace RobotNet.WebApp.Scripts.Monaco.Editor;
public struct SingleEditOperation
{
public bool? ForceMoveMarkers { get; set; }
public Range Range { get; set; }
public string Text { get; set; }
}

View File

@@ -0,0 +1,34 @@
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis;
namespace RobotNet.WebApp.Scripts.Monaco;
public class InvocationContext
{
public SemanticModel SemanticModel { get; }
public int Position { get; }
public SyntaxNode Receiver { get; }
public IEnumerable<TypeInfo> ArgumentTypes { get; }
public IEnumerable<SyntaxToken> Separators { get; }
public bool IsInStaticContext { get; }
public InvocationContext(SemanticModel semModel, int position, SyntaxNode receiver, ArgumentListSyntax argList, bool isStatic)
{
SemanticModel = semModel;
Position = position;
Receiver = receiver;
ArgumentTypes = argList.Arguments.Select(argument => semModel.GetTypeInfo(argument.Expression));
Separators = argList.Arguments.GetSeparators();
IsInStaticContext = isStatic;
}
public InvocationContext(SemanticModel semModel, int position, SyntaxNode receiver, AttributeArgumentListSyntax argList, bool isStatic)
{
SemanticModel = semModel;
Position = position;
Receiver = receiver;
ArgumentTypes = argList.Arguments.Select(argument => semModel.GetTypeInfo(argument.Expression));
Separators = argList.Arguments.GetSeparators();
IsInStaticContext = isStatic;
}
}

View File

@@ -0,0 +1,9 @@
namespace RobotNet.WebApp.Scripts.Monaco.Languages;
public struct Command
{
public string Id { get; set; }
public string Title { get; set; }
public string? Tooltip { get; set; }
public object[]? Arguments { get; set; }
}

View File

@@ -0,0 +1,248 @@
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Completion;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Tags;
using Microsoft.CodeAnalysis.Text;
using RobotNet.WebApp.Scripts.Monaco.Editor;
using System.Collections.Immutable;
using System.Reflection;
using System.Text.RegularExpressions;
namespace RobotNet.WebApp.Scripts.Monaco.Languages;
public static class CompletionExtensions
{
private static readonly Dictionary<string, CompletionItemKind> s_roslynTagToCompletionItemKind = new()
{
{ WellKnownTags.Public, CompletionItemKind.Keyword },
{ WellKnownTags.Protected, CompletionItemKind.Keyword },
{ WellKnownTags.Private, CompletionItemKind.Keyword },
{ WellKnownTags.Internal, CompletionItemKind.Keyword },
{ WellKnownTags.File, CompletionItemKind.File },
{ WellKnownTags.Project, CompletionItemKind.File },
{ WellKnownTags.Folder, CompletionItemKind.Folder },
{ WellKnownTags.Assembly, CompletionItemKind.File },
{ WellKnownTags.Class, CompletionItemKind.Class },
{ WellKnownTags.Constant, CompletionItemKind.Constant },
{ WellKnownTags.Delegate, CompletionItemKind.Function },
{ WellKnownTags.Enum, CompletionItemKind.Enum },
{ WellKnownTags.EnumMember, CompletionItemKind.EnumMember },
{ WellKnownTags.Event, CompletionItemKind.Event },
{ WellKnownTags.ExtensionMethod, CompletionItemKind.Method },
{ WellKnownTags.Field, CompletionItemKind.Field },
{ WellKnownTags.Interface, CompletionItemKind.Interface },
{ WellKnownTags.Intrinsic, CompletionItemKind.Text },
{ WellKnownTags.Keyword, CompletionItemKind.Keyword },
{ WellKnownTags.Label, CompletionItemKind.Text },
{ WellKnownTags.Local, CompletionItemKind.Variable },
{ WellKnownTags.Namespace, CompletionItemKind.Module },
{ WellKnownTags.Method, CompletionItemKind.Method },
{ WellKnownTags.Module, CompletionItemKind.Module },
{ WellKnownTags.Operator, CompletionItemKind.Operator },
{ WellKnownTags.Parameter, CompletionItemKind.Value },
{ WellKnownTags.Property, CompletionItemKind.Property },
{ WellKnownTags.RangeVariable, CompletionItemKind.Variable },
{ WellKnownTags.Reference, CompletionItemKind.Reference },
{ WellKnownTags.Structure, CompletionItemKind.Struct },
{ WellKnownTags.TypeParameter, CompletionItemKind.TypeParameter },
{ WellKnownTags.Snippet, CompletionItemKind.Snippet },
{ WellKnownTags.Error, CompletionItemKind.Text },
{ WellKnownTags.Warning, CompletionItemKind.Text },
};
private static CompletionTrigger GetCompletionTrigger(int kind, char? triggerCharacter, bool includeTriggerCharacter)
=> kind switch
{
1 => CompletionTrigger.Invoke,
// https://github.com/dotnet/roslyn/issues/42982: Passing a trigger character
// to GetCompletionsAsync causes a null ref currently.
2 when includeTriggerCharacter => CompletionTrigger.CreateInsertionTrigger((char)triggerCharacter!),
_ => CompletionTrigger.Invoke,
};
//private static readonly Regex EscapeRegex = new(@"([\\\$}])", RegexOptions.Compiled);
//private static string GetAdjustedInsertTextWithPosition(
// CompletionChange change,
// int originalPosition,
// int newOffset,
// string? prependText = null)
//{
// string newText = change.TextChange.NewText!;
// if (change.NewPosition is not int newPosition
// || newPosition >= change.TextChange.Span.Start + newText.Length)
// {
// return prependText + newText[newOffset..];
// }
// int midpoint = newPosition - change.TextChange.Span.Start;
// var beforeText = prependText + newText[newOffset..midpoint];
// if (beforeText != null) beforeText = EscapeRegex.Replace(beforeText, @"\$1");
// var afterText = newText[midpoint..];
// if (afterText != null) afterText = EscapeRegex.Replace(afterText, @"\$1");
// return beforeText + "$0" + afterText;
//}
private static ImmutableArray<char> BuildCommitCharacters(Microsoft.CodeAnalysis.Completion.CompletionList completions, ImmutableArray<CharacterSetModificationRule> characterRules, ImmutableArray<char>.Builder triggerCharactersBuilder)
{
if (completions is null) return [];
triggerCharactersBuilder.AddRange(completions.Rules.DefaultCommitCharacters);
foreach (var modifiedRule in characterRules)
{
switch (modifiedRule.Kind)
{
case CharacterSetModificationKind.Add:
triggerCharactersBuilder.AddRange(modifiedRule.Characters);
break;
case CharacterSetModificationKind.Remove:
for (int i = 0; i < triggerCharactersBuilder.Count; i++)
{
if (modifiedRule.Characters.Contains(triggerCharactersBuilder[i]))
{
triggerCharactersBuilder.RemoveAt(i);
i--;
}
}
break;
case CharacterSetModificationKind.Replace:
triggerCharactersBuilder.Clear();
triggerCharactersBuilder.AddRange(modifiedRule.Characters);
break;
}
}
if (completions.SuggestionModeItem is not null)
{
triggerCharactersBuilder.Remove(' ');
}
if (triggerCharactersBuilder.Capacity == triggerCharactersBuilder.Count)
{
return triggerCharactersBuilder.MoveToImmutable();
}
else
{
var result = triggerCharactersBuilder.ToImmutable();
triggerCharactersBuilder.Clear();
return result;
}
}
private static CompletionItemKind GetCompletionItemKind(ImmutableArray<string> tags)
{
foreach (var tag in tags)
{
if (s_roslynTagToCompletionItemKind.TryGetValue(tag, out var itemKind))
{
return itemKind;
}
}
return CompletionItemKind.Text;
}
public static async Task<IEnumerable<CompletionItem>> GetCompletionAsync(this AdhocWorkspace workspace, DocumentId documentId, int line, int column, int kind, char? triggerCharacter)
{
if (triggerCharacter == ' ') return [];
var document = workspace.CurrentSolution.GetDocument(documentId);
if (document is null) return [];
var sourceText = await document.GetTextAsync();
var position = sourceText.Lines.GetPosition(new LinePosition(line - 1, column - 1));
var completionService = CompletionService.GetService(document);
if (completionService == null) return [];
if (kind == 3 && !completionService.ShouldTriggerCompletion(sourceText, position, GetCompletionTrigger(kind - 1, triggerCharacter, includeTriggerCharacter: true)))
{
return [];
}
Microsoft.CodeAnalysis.Completion.CompletionList? completionList = null;
try
{
completionList = await completionService.GetCompletionsAsync(
document,
position,
GetCompletionTrigger(kind - 1, triggerCharacter, includeTriggerCharacter: false));
}
catch (Exception ex)
{
// Log the exception or handle it as needed
Console.WriteLine($"Error getting completions: position:{position} \n {ex}");
}
if (completionList is null || completionList.ItemsList.Count <= 0) return [];
var typedSpan = completionService.GetDefaultCompletionListSpan(sourceText, position);
string typedText = sourceText.GetSubText(typedSpan).ToString();
ImmutableArray<string> filteredItems = typedText != string.Empty
? [.. completionService.FilterItems(document, [.. completionList.ItemsList], typedText).Select(i => i.DisplayText)]
: [];
bool expectingImportedItems = workspace.Options.GetOption(new PerLanguageOption<bool?>("CompletionOptions", "ShowItemsFromUnimportedNamespaces", defaultValue: null), LanguageNames.CSharp) == true;
var syntax = await document.GetSyntaxTreeAsync();
var replacingSpanStartPosition = sourceText.Lines.GetLinePosition(typedSpan.Start);
var replacingSpanEndPosition = sourceText.Lines.GetLinePosition(typedSpan.End);
var triggerCharactersBuilder = ImmutableArray.CreateBuilder<char>(completionList.Rules.DefaultCommitCharacters.Length);
var completionsBuilder = new List<CompletionItem>();
foreach (var completion in completionList.ItemsList)
{
SingleEditOperation[]? additionalTextEdits = null;
char sortTextPrepend = '0';
if (!completion.Properties.TryGetValue("InsertionText", out string? insertText))
{
if (GetCompletionItemKind(completion.Tags) == CompletionItemKind.Keyword)
{
insertText = completion.DisplayText;
}
else
{
continue;
}
}
if (string.IsNullOrEmpty(insertText)) continue;
var commitCharacters = BuildCommitCharacters(completionList, completion.Rules.CommitCharacterRules, triggerCharactersBuilder).Select(c => c.ToString());
completionsBuilder.Add(new CompletionItem
{
Label = completion.DisplayTextPrefix + completion.DisplayText + completion.DisplayTextSuffix,
Kind = GetCompletionItemKind(completion.Tags),
Documentation = "",
InsertText = insertText,
Range = new Range
{
StartLineNumber = replacingSpanStartPosition.Line + 1,
EndLineNumber = replacingSpanEndPosition.Line + 1,
StartColumn = replacingSpanStartPosition.Character + 1,
EndColumn = replacingSpanEndPosition.Character + 1,
},
AdditionalTextEdits = additionalTextEdits,
// Ensure that unimported items are sorted after things already imported.
SortText = expectingImportedItems ? sortTextPrepend + completion.SortText : completion.SortText,
FilterText = completion.FilterText,
Detail = completion.InlineDescription,
Preselect = completion.Rules.MatchPriority == MatchPriority.Preselect || filteredItems.Contains(completion.DisplayText),
CommitCharacters = [.. commitCharacters],
Tags = null,
Command = null,
InsertTextRules = null,
});
}
return completionsBuilder;
}
}

View File

@@ -0,0 +1,21 @@
using RobotNet.WebApp.Scripts.Monaco.Editor;
namespace RobotNet.WebApp.Scripts.Monaco.Languages;
public struct CompletionItem
{
public string Label { get; set; }
public CompletionItemKind Kind { get; set; }
public string? Documentation { get; set; }
public string InsertText { get; set; }
public Range Range { get; set; }
public SingleEditOperation[]? AdditionalTextEdits { get; set; }
public Command? Command { get; set; }
public string[]? CommitCharacters { get; set; }
public string? Detail { get; set; }
public string? FilterText { get; set; }
public CompletionItemInsertTextRule? InsertTextRules { get; set; }
public bool Preselect { get; set; }
public string? SortText { get; set; }
public int[]? Tags { get; set; }
}

View File

@@ -0,0 +1,15 @@
namespace RobotNet.WebApp.Scripts.Monaco.Languages;
public enum CompletionItemInsertTextRule
{
None = 0,
/**
* Adjust whitespace/indentation of multiline insert texts to
* match the current line indentation.
*/
KeepWhitespace = 1,
/**
* `insertText` is a snippet.
*/
InsertAsSnippet = 4
}

View File

@@ -0,0 +1,33 @@
namespace RobotNet.WebApp.Scripts.Monaco.Languages;
public enum CompletionItemKind
{
Method = 0,
Function = 1,
Constructor = 2,
Field = 3,
Variable = 4,
Class = 5,
Struct = 6,
Interface = 7,
Module = 8,
Property = 9,
Event = 10,
Operator = 11,
Unit = 12,
Value = 13,
Constant = 14,
Enum = 15,
EnumMember = 16,
Keyword = 17,
Text = 18,
Color = 19,
File = 20,
Reference = 21,
Customcolor = 22,
Folder = 23,
TypeParameter = 24,
User = 25,
Issue = 26,
Snippet = 27
}

View File

@@ -0,0 +1,8 @@
namespace RobotNet.WebApp.Scripts.Monaco.Languages;
public struct CompletionItemLabel
{
public string? Description { get; set; }
public string? Detail { get; set; }
public string Label { get; set; }
}

View File

@@ -0,0 +1,9 @@
using RobotNet.WebApp.Scripts.Monaco;
namespace RobotNet.WebApp.Scripts.Monaco.Languages;
public struct CompletionItemRanges
{
public Range Intert { get; set; }
public Range Replace { get; set; }
}

View File

@@ -0,0 +1,6 @@
namespace RobotNet.WebApp.Scripts.Monaco.Languages;
public enum CompletionItemTag
{
Deprecated = 1
}

View File

@@ -0,0 +1,7 @@
namespace RobotNet.WebApp.Scripts.Monaco.Languages;
public struct CompletionList
{
public bool? Incomplete { get; set; }
public CompletionItem[] Suggestions { get; set; }
}

View File

@@ -0,0 +1,7 @@
namespace RobotNet.WebApp.Scripts.Monaco.Languages;
public struct ParameterInformation
{
public string Label { get; set; }
public MarkdownString? Documentation { get; set; }
}

View File

@@ -0,0 +1,8 @@
namespace RobotNet.WebApp.Scripts.Monaco.Languages;
public struct SignatureHelp
{
public int ActiveParameter { get; set; }
public int ActiveSignature { get; set; }
public SignatureInformation[] Signatures { get; set; }
}

View File

@@ -0,0 +1,169 @@
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
using RobotNet.WebApp.Scripts.Monaco.Documentation;
namespace RobotNet.WebApp.Scripts.Monaco.Languages;
public static class SignatureHelpExtensions
{
public static async Task<SignatureHelpResult?> GetSignatureHelpAsync(this Document document, int line, int column)
{
var invocation = await GetInvocation(document, line - 1, column - 1);
if (invocation is null) return null;
var response = new SignatureHelp();
foreach (var comma in invocation.Separators)
{
if (comma.Span.Start > invocation.Position)
{
break;
}
response.ActiveParameter += 1;
}
var signaturesSet = new HashSet<SignatureInformation>();
var bestScore = int.MinValue;
SignatureInformation? bestScoredItem = null;
var types = invocation.ArgumentTypes;
ISymbol? throughSymbol = null;
ISymbol? throughType = null;
var methodGroup = invocation.SemanticModel.GetMemberGroup(invocation.Receiver).OfType<IMethodSymbol>();
if (invocation.Receiver is MemberAccessExpressionSyntax syntax)
{
var throughExpression = syntax.Expression;
throughSymbol = invocation.SemanticModel.GetSpeculativeSymbolInfo(invocation.Position, throughExpression, SpeculativeBindingOption.BindAsExpression).Symbol;
throughType = invocation.SemanticModel.GetSpeculativeTypeInfo(invocation.Position, throughExpression, SpeculativeBindingOption.BindAsTypeOrNamespace).Type;
var includeInstance = throughSymbol != null && throughSymbol is not ITypeSymbol ||
throughExpression is LiteralExpressionSyntax ||
throughExpression is TypeOfExpressionSyntax;
var includeStatic = throughSymbol is INamedTypeSymbol || throughType != null;
methodGroup = methodGroup.Where(m => m.IsStatic && includeStatic || !m.IsStatic && includeInstance);
}
else if (invocation.Receiver is SimpleNameSyntax && invocation.IsInStaticContext)
{
methodGroup = methodGroup.Where(m => m.IsStatic || m.MethodKind == MethodKind.LocalFunction);
}
foreach (var methodOverload in methodGroup)
{
var signature = BuildSignature(methodOverload);
signaturesSet.Add(signature);
var score = InvocationScore(methodOverload, types);
if (score > bestScore)
{
bestScore = score;
bestScoredItem = signature;
}
}
var signaturesList = signaturesSet.ToList();
response.Signatures = [.. signaturesList];
if(bestScoredItem == null)
{
response.ActiveSignature = -1;
}
else
{
response.ActiveSignature = signaturesList.IndexOf((SignatureInformation)bestScoredItem);
}
return new SignatureHelpResult()
{
Value = response,
};
}
private static async Task<InvocationContext?> GetInvocation(Document document, int line, int column)
{
var sourceText = await document.GetTextAsync();
var position = sourceText.Lines.GetPosition(new LinePosition(line, column));
var tree = await document.GetSyntaxTreeAsync();
if (tree is null) return null;
var root = await tree.GetRootAsync();
var node = root.FindToken(position).Parent;
// Walk up until we find a node that we're interested in.
while (node != null)
{
if (node is InvocationExpressionSyntax invocation && invocation.ArgumentList.Span.Contains(position))
{
var semanticModel = await document.GetSemanticModelAsync();
return semanticModel is null ? null : new InvocationContext(semanticModel, position, invocation.Expression, invocation.ArgumentList, invocation.IsInStaticContext());
}
if (node is BaseObjectCreationExpressionSyntax objectCreation && (objectCreation.ArgumentList?.Span.Contains(position) ?? false))
{
var semanticModel = await document.GetSemanticModelAsync();
return semanticModel is null ? null : new InvocationContext(semanticModel, position, objectCreation, objectCreation.ArgumentList, objectCreation.IsInStaticContext());
}
if (node is AttributeSyntax attributeSyntax && (attributeSyntax.ArgumentList?.Span.Contains(position) ?? false))
{
var semanticModel = await document.GetSemanticModelAsync();
return semanticModel is null ? null : new InvocationContext(semanticModel, position, attributeSyntax, attributeSyntax.ArgumentList, attributeSyntax.IsInStaticContext());
}
node = node.Parent;
}
return null;
}
private static int InvocationScore(IMethodSymbol symbol, IEnumerable<TypeInfo> types)
{
var parameters = symbol.Parameters;
if (parameters.Length < types.Count())
{
return int.MinValue;
}
var score = 0;
var invocationEnum = types.GetEnumerator();
var definitionEnum = parameters.GetEnumerator();
while (invocationEnum.MoveNext() && definitionEnum.MoveNext())
{
if (invocationEnum.Current.ConvertedType == null)
{
// 1 point for having a parameter
score += 1;
}
else if (SymbolEqualityComparer.Default.Equals(invocationEnum.Current.ConvertedType, definitionEnum.Current.Type))
{
// 2 points for having a parameter and being
// the same type
score += 2;
}
}
return score;
}
private static SignatureInformation BuildSignature(IMethodSymbol symbol)
{
var StructuredDocumentation = DocumentationConverter.GetStructuredDocumentation(symbol);
return new SignatureInformation
{
Documentation = new MarkdownString()
{
Value = StructuredDocumentation?.SummaryText ?? "",
},
Label = symbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat),
Parameters = [..symbol.Parameters.Select(parameter => new ParameterInformation()
{
Label = parameter.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat),
Documentation = new MarkdownString()
{
Value = StructuredDocumentation?.GetParameterText(parameter.Name) ?? string.Empty,
},
})],
ActiveParameter = null,
};
}
}

View File

@@ -0,0 +1,6 @@
namespace RobotNet.WebApp.Scripts.Monaco.Languages;
public struct SignatureHelpResult
{
public SignatureHelp Value { get; set; }
}

View File

@@ -0,0 +1,9 @@
namespace RobotNet.WebApp.Scripts.Monaco.Languages;
public struct SignatureInformation
{
public int? ActiveParameter { get; set; }
public MarkdownString? Documentation { get; set; }
public string Label { get; set; }
public ParameterInformation[] Parameters { get; set; }
}

View File

@@ -0,0 +1,260 @@
using Microsoft.CodeAnalysis;
using System.Collections.Immutable;
using System.Text.RegularExpressions;
using System.Text;
namespace RobotNet.WebApp.Scripts.Monaco;
public enum MarkdownFormat
{
Default,
Italicize,
FirstLineAsCSharp,
FirstLineDefaultRestCSharp,
AllTextAsCSharp
}
public static class MarkdownHelpers
{
private static readonly Regex EscapeRegex = new("([\\\\`\\*_\\{\\}\\[\\]\\(\\)#+\\-\\.!])", RegexOptions.Compiled);
private const string ContainerStart = "ContainerStart";
private const string ContainerEnd = "ContainerEnd";
public static string Escape(string markdown) => string.IsNullOrEmpty(markdown) ? string.Empty : EscapeRegex.Replace(markdown, "\\$1");
public static void TaggedTextToMarkdown(ImmutableArray<TaggedText> taggedParts, StringBuilder stringBuilder, string newLine, MarkdownFormat markdownFormat, out bool endedWithLineBreak)
{
bool isInCodeBlock = false;
bool brokeLine = true;
bool afterFirstLine = false;
if (markdownFormat == MarkdownFormat.Italicize)
{
stringBuilder.Append('_');
}
int num = 0;
while (num < taggedParts.Length)
{
TaggedText taggedText = taggedParts[num];
bool flag;
if (brokeLine && markdownFormat != MarkdownFormat.Italicize)
{
brokeLine = false;
if (!afterFirstLine)
{
if (markdownFormat != MarkdownFormat.FirstLineAsCSharp)
{
goto IL_00a2;
}
flag = true;
}
else
{
if (markdownFormat != MarkdownFormat.FirstLineDefaultRestCSharp)
{
goto IL_00a2;
}
flag = true;
}
goto IL_00bf;
}
goto IL_0279;
IL_00a2:
flag = markdownFormat == MarkdownFormat.AllTextAsCSharp;
goto IL_00bf;
IL_0279:
switch (taggedText.Tag)
{
case "Text":
if (!isInCodeBlock)
{
addText(taggedText.Text);
break;
}
endBlock();
addText(taggedText.Text);
break;
case "Space":
if (isInCodeBlock)
{
if (indexIsTag(num + 1, ["Text"]))
{
endBlock();
}
addText(taggedText.Text);
break;
}
goto case "Punctuation";
case "Punctuation":
addText(taggedText.Text);
break;
case ContainerStart:
addNewline();
addText(taggedText.Text);
break;
case ContainerEnd:
addNewline();
break;
case "LineBreak":
if (stringBuilder.Length != 0 && !indexIsTag(num + 1, [ContainerStart, ContainerEnd]) && num + 1 != taggedParts.Length)
{
addNewline();
}
break;
default:
if (!isInCodeBlock)
{
isInCodeBlock = true;
stringBuilder.Append('`');
}
stringBuilder.Append(taggedText.Text);
brokeLine = false;
break;
}
num++;
continue;
IL_00bf:
bool flag2 = flag;
if (!flag2)
{
for (int j = num; j < taggedParts.Length; flag2 = true, j++)
{
switch (taggedParts[j].Tag)
{
case "Text":
flag2 = false;
break;
default:
continue;
case ContainerStart:
case ContainerEnd:
case "LineBreak":
break;
}
break;
}
}
else
{
flag2 = !indexIsTag(num,
[
ContainerStart,
ContainerEnd,
"LineBreak"
]);
}
if (flag2)
{
afterFirstLine = true;
stringBuilder.Append("```csharp");
stringBuilder.Append(newLine);
while (true)
{
if (num < taggedParts.Length)
{
taggedText = taggedParts[num];
if (taggedText.Tag == ContainerStart || taggedText.Tag == ContainerEnd || taggedText.Tag == "LineBreak")
{
stringBuilder.Append(newLine);
if (markdownFormat != MarkdownFormat.AllTextAsCSharp && markdownFormat != MarkdownFormat.FirstLineDefaultRestCSharp)
{
break;
}
}
else
{
stringBuilder.Append(taggedText.Text);
}
num++;
continue;
}
stringBuilder.Append(newLine);
stringBuilder.Append("```");
endedWithLineBreak = false;
return;
}
stringBuilder.Append("```");
}
goto IL_0279;
}
if (isInCodeBlock)
{
endBlock();
}
if (!brokeLine && markdownFormat == MarkdownFormat.Italicize)
{
stringBuilder.Append('_');
}
endedWithLineBreak = brokeLine;
void addNewline()
{
if (isInCodeBlock)
{
endBlock();
}
if (markdownFormat == MarkdownFormat.Italicize)
{
stringBuilder.Append('_');
}
stringBuilder.Append(newLine);
stringBuilder.Append(newLine);
brokeLine = true;
if (markdownFormat == MarkdownFormat.Italicize)
{
stringBuilder.Append('_');
}
}
void addText(string text)
{
brokeLine = false;
afterFirstLine = true;
if (!isInCodeBlock)
{
text = Escape(text);
}
stringBuilder.Append(text);
}
void endBlock()
{
stringBuilder.Append('`');
isInCodeBlock = false;
}
bool indexIsTag(int i, string[] tags)
{
if (i < taggedParts.Length)
{
return tags.Contains(taggedParts[i].Tag);
}
return false;
}
}
}

View File

@@ -0,0 +1,11 @@
namespace RobotNet.WebApp.Scripts.Monaco;
public struct MarkdownString
{
public string Value { get; set; }
public bool? IsTrusted { get; set; } // TODO | MarkdownStringTrustedOptions;
public bool? SupportThemeIcons { get; set; }
public bool? SupportHtml { get; set; }
public UriComponents? BaseUri { get; set; }
public IDictionary<string, UriComponents>? Uris { get; set; }
}

View File

@@ -0,0 +1,9 @@
namespace RobotNet.WebApp.Scripts.Monaco;
public enum MarkerSeverity
{
Hint = 1,
Info = 2,
Warning = 4,
Error = 8,
}

View File

@@ -0,0 +1,7 @@
namespace RobotNet.WebApp.Scripts.Monaco;
public enum MarkerTag
{
Unnecessary = 1,
Deprecated = 2,
}

View File

@@ -0,0 +1,150 @@
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
namespace RobotNet.WebApp.Scripts.Monaco;
public static class MonacoExtensions
{
public static bool IsInStaticContext(this SyntaxNode node)
{
// this/base calls are always static.
if (node.FirstAncestorOrSelf<ConstructorInitializerSyntax>() != null)
{
return true;
}
var memberDeclaration = node.FirstAncestorOrSelf<MemberDeclarationSyntax>();
if (memberDeclaration == null)
{
return false;
}
switch (memberDeclaration.Kind())
{
case SyntaxKind.MethodDeclaration:
case SyntaxKind.ConstructorDeclaration:
case SyntaxKind.EventDeclaration:
case SyntaxKind.IndexerDeclaration:
return GetModifiers(memberDeclaration).Any(SyntaxKind.StaticKeyword);
case SyntaxKind.PropertyDeclaration:
return GetModifiers(memberDeclaration).Any(SyntaxKind.StaticKeyword) ||
node.IsFoundUnder((PropertyDeclarationSyntax p) => p.Initializer);
case SyntaxKind.FieldDeclaration:
case SyntaxKind.EventFieldDeclaration:
// Inside a field one can only access static members of a type (unless it's top-level).
return !memberDeclaration.Parent.IsKind(SyntaxKind.CompilationUnit);
case SyntaxKind.DestructorDeclaration:
return false;
}
// Global statements are not a static context.
if (node.FirstAncestorOrSelf<GlobalStatementSyntax>() != null)
{
return false;
}
// any other location is considered static
return true;
}
public static SyntaxTokenList GetModifiers(SyntaxNode member)
{
if (member != null)
{
switch (member.Kind())
{
case SyntaxKind.EnumDeclaration:
return ((EnumDeclarationSyntax)member).Modifiers;
case SyntaxKind.ClassDeclaration:
case SyntaxKind.InterfaceDeclaration:
case SyntaxKind.StructDeclaration:
return ((TypeDeclarationSyntax)member).Modifiers;
case SyntaxKind.DelegateDeclaration:
return ((DelegateDeclarationSyntax)member).Modifiers;
case SyntaxKind.FieldDeclaration:
return ((FieldDeclarationSyntax)member).Modifiers;
case SyntaxKind.EventFieldDeclaration:
return ((EventFieldDeclarationSyntax)member).Modifiers;
case SyntaxKind.ConstructorDeclaration:
return ((ConstructorDeclarationSyntax)member).Modifiers;
case SyntaxKind.DestructorDeclaration:
return ((DestructorDeclarationSyntax)member).Modifiers;
case SyntaxKind.PropertyDeclaration:
return ((PropertyDeclarationSyntax)member).Modifiers;
case SyntaxKind.EventDeclaration:
return ((EventDeclarationSyntax)member).Modifiers;
case SyntaxKind.IndexerDeclaration:
return ((IndexerDeclarationSyntax)member).Modifiers;
case SyntaxKind.OperatorDeclaration:
return ((OperatorDeclarationSyntax)member).Modifiers;
case SyntaxKind.ConversionOperatorDeclaration:
return ((ConversionOperatorDeclarationSyntax)member).Modifiers;
case SyntaxKind.MethodDeclaration:
return ((MethodDeclarationSyntax)member).Modifiers;
case SyntaxKind.GetAccessorDeclaration:
case SyntaxKind.SetAccessorDeclaration:
case SyntaxKind.AddAccessorDeclaration:
case SyntaxKind.RemoveAccessorDeclaration:
return ((AccessorDeclarationSyntax)member).Modifiers;
}
}
return default;
}
public static bool IsFoundUnder<TParent>(this SyntaxNode node, Func<TParent, SyntaxNode?> childGetter)
where TParent : SyntaxNode
{
var ancestor = node.GetAncestor<TParent>();
if (ancestor == null)
{
return false;
}
var child = childGetter(ancestor);
// See if node passes through child on the way up to ancestor.
return node.GetAncestorsOrThis<SyntaxNode>().Contains(child);
}
public static TNode? GetAncestor<TNode>(this SyntaxNode node)
where TNode : SyntaxNode
{
var current = node.Parent;
while (current != null)
{
if (current is TNode tNode)
{
return tNode;
}
current = current.GetParent();
}
return null;
}
public static IEnumerable<TNode> GetAncestorsOrThis<TNode>(this SyntaxNode node)
where TNode : SyntaxNode
{
var current = node;
while (current != null)
{
if (current is TNode tNode)
{
yield return tNode;
}
current = current.GetParent();
}
}
private static SyntaxNode? GetParent(this SyntaxNode node)
{
return node is IStructuredTriviaSyntax trivia ? trivia.ParentTrivia.Token.Parent : node.Parent;
}
}

View File

@@ -0,0 +1,9 @@
namespace RobotNet.WebApp.Scripts.Monaco;
public struct Range
{
public int EndColumn { get; set; }
public int EndLineNumber { get; set; }
public int StartColumn { get; set; }
public int StartLineNumber { get; set; }
}

View File

@@ -0,0 +1,16 @@
using Microsoft.CodeAnalysis.QuickInfo;
using System.Text;
namespace RobotNet.WebApp.Scripts.Monaco;
public static class StringBuilderExtension
{
public static void AppendSection(this StringBuilder builder, QuickInfoSection section, MarkdownFormat format, ref bool lastLineBreak)
{
if (!lastLineBreak && section.TaggedParts.Length > 0 && section.TaggedParts[0].Tag != "LineBreak")
{
builder.Append("\n\n");
}
MarkdownHelpers.TaggedTextToMarkdown(section.TaggedParts, builder, "\n", format, out lastLineBreak);
}
}

View File

@@ -0,0 +1,10 @@
namespace RobotNet.WebApp.Scripts.Monaco;
public struct UriComponents
{
public string? Scheme { get; set; }
public string? Authority { get; set; }
public string? Path { get; set; }
public string? Query { get; set; }
public string? Fragment { get; set; }
}