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,121 @@
@inject IJSRuntime JSRuntime
@implements IDisposable
<path @ref="ErrorRef" style="stroke: red; opacity: 0.6; stroke-width: 0.6px;" />
<path @ref="Ref" @ondblclick="@(async () => await DoubleClick.InvokeAsync(Model))" class="@(IsSetting ? "setting" : "")" />
@code {
[Parameter, EditorRequired]
public EdgeModel Model { get; set; } = null!;
[Parameter]
public EventCallback<EdgeModel> DoubleClick { get; set; }
[CascadingParameter]
protected bool MapIsActive { get; set; }
[Parameter]
public EditorState EditorState { get; set; }
private ElementReference Ref;
private ElementReference ErrorRef;
private DotNetObjectReference<Edge> DotNetObj = null!;
private bool IsError = false;
private bool IsSetting => EditorState == EditorState.NavigationEdit || EditorState == EditorState.CreateStraighEdge || EditorState == EditorState.CreateCurveEdge ||
EditorState == EditorState.CreateDoubleCurveEdge;
protected override async Task OnAfterRenderAsync(bool firstRender)
{
await base.OnAfterRenderAsync(firstRender);
if (!firstRender) return;
DotNetObj = DotNetObjectReference.Create(this);
await JSRuntime.InvokeVoidAsync("AddEventListener", DotNetObj, Ref, "click", nameof(Click), false);
await UpdatePathData();
await JSRuntime.InvokeVoidAsync("ElementSetAttribute", ErrorRef, "visibility", "hidden");
}
public override async Task SetParametersAsync(ParameterView parameters)
{
bool updateLine = false;
if (parameters.TryGetValue(nameof(Model), out EdgeModel? model))
{
if (((Model?.Id ?? Guid.Empty) != (model?.Id ?? Guid.Empty)))
{
if (Model != null)
{
Model.StartNodePositionChanged -= UpdatePathData;
Model.EndNodePositionChanged -= UpdatePathData;
Model.ControlPoint1PositionChanged -= UpdatePathData;
Model.ControlPoint2PositionChanged -= UpdatePathData;
Model.ActiveChanged -= ActivedChanged;
Model.ErrorChanged -= ErrorChanged;
}
if (model != null)
{
model.StartNodePositionChanged += UpdatePathData;
model.EndNodePositionChanged += UpdatePathData;
model.ControlPoint1PositionChanged += UpdatePathData;
model.ControlPoint2PositionChanged += UpdatePathData;
model.ActiveChanged += ActivedChanged;
model.ErrorChanged += ErrorChanged;
updateLine = true;
}
}
}
await base.SetParametersAsync(parameters);
if (updateLine) await UpdatePathData();
}
private async Task UpdatePathData()
{
var data = $"M {Model.X1} {Model.Y1}";
if (Model.TrajectoryDegree == TrajectoryDegree.One)
{
data = $"{data} L {(Model.X1 + Model.X2) / 2} {(Model.Y1 + Model.Y2) / 2} L {Model.X2} {Model.Y2}";
}
else if (Model.TrajectoryDegree == TrajectoryDegree.Two)
{
data = $"{data} Q {Model.ControlPoint1X} {Model.ControlPoint1Y} {Model.X2} {Model.Y2}";
}
else if (Model.TrajectoryDegree == TrajectoryDegree.Three)
{
data = $"{data} C {Model.ControlPoint1X} {Model.ControlPoint1Y}, {Model.ControlPoint2X} {Model.ControlPoint2Y}, {Model.X2} {Model.Y2}";
}
await JSRuntime.InvokeVoidAsync("ElementSetAttribute", Ref, "d", data);
if (IsError) await JSRuntime.InvokeVoidAsync("ElementSetAttribute", ErrorRef, "d", data);
}
private async void ActivedChanged(bool state) => await JSRuntime.InvokeVoidAsync(state ? "AddSelected" : "RemoveSelected", Ref);
private async void ErrorChanged(bool state)
{
IsError = state;
await JSRuntime.InvokeVoidAsync("ElementSetAttribute", ErrorRef, "visibility", state ? "visible" : "hidden");
await UpdatePathData();
}
[JSInvokable]
public void Click() => Model.Selected();
public void Dispose()
{
if (Model != null)
{
Model.StartNodePositionChanged -= UpdatePathData;
Model.EndNodePositionChanged -= UpdatePathData;
Model.ControlPoint1PositionChanged -= UpdatePathData;
Model.ControlPoint2PositionChanged -= UpdatePathData;
Model.ActiveChanged -= ActivedChanged;
Model.ErrorChanged -= ErrorChanged;
}
if (DotNetObj != null) DotNetObj.Dispose();
GC.SuppressFinalize(this);
}
}

View File

@@ -0,0 +1,24 @@
path {
cursor: default;
stroke: #22B3FF;
stroke-width: var(--edge-stroke-width);
fill: none;
}
path.setting:hover {
stroke: #1E9DDF;
cursor: pointer;
}
path.setting:active {
stroke: #227CFF;
}
path.setting.active:hover {
stroke: #227CFF;
}
path.active {
stroke: #227CFF;
}

View File

@@ -0,0 +1,128 @@
@inject IJSRuntime JSRuntime
@implements IDisposable
<g visibility="@Visibility">
<path d="@EdgeData" />
<line x1="@X1" y1="@Y1" x2="@CX1" y2="@CY1"/>
<line x1="@CX1" y1="@CY1" x2="@X2" y2="@Y2" />
<circle @ref="CP1Ref" cx="@CX1" cy="@CY1" />
</g>
<g visibility="@ControlPoint2Visibility">
<line x1="@X1" y1="@Y1" x2="@CX2" y2="@CY2" />
<line x1="@CX2" y1="@CY2" x2="@X2" y2="@Y2" />
<circle @ref="CP2Ref" cx="@CX2" cy="@CY2" />
</g>
@code {
private ElementReference CP1Ref;
private ElementReference CP2Ref;
private DotNetObjectReference<EdgeControlPoint> DotNetObj = null!;
private double X1;
private double Y1;
private double CX1;
private double CY1;
private double CX2;
private double CY2;
private double X2;
private double Y2;
private string EdgeData = "";
private EdgeModel? Model;
private string Visibility = "hidden";
private string ControlPoint2Visibility = "hidden";
protected override async Task OnAfterRenderAsync(bool firstRender)
{
await base.OnAfterRenderAsync(firstRender);
if (!firstRender) return;
DotNetObj = DotNetObjectReference.Create(this);
await JSRuntime.InvokeVoidAsync("AddMouseDownEventListener", DotNetObj, CP1Ref, nameof(OnMouseDown1), false);
await JSRuntime.InvokeVoidAsync("AddMouseDownEventListener", DotNetObj, CP2Ref, nameof(OnMouseDown2), false);
}
public void SetControl(EdgeModel? model)
{
if (Model != null)
{
Model.StartNodePositionChanged -= CaculatePath;
Model.EndNodePositionChanged -= CaculatePath;
Model.ControlPoint1PositionChanged -= CaculatePath;
Model.ControlPoint2PositionChanged -= CaculatePath;
}
Model = model;
if (Model != null)
{
Visibility = "visible";
if (Model.TrajectoryDegree == TrajectoryDegree.Three) ControlPoint2Visibility = "visible";
CaculatePath();
Model.StartNodePositionChanged += CaculatePath;
Model.EndNodePositionChanged += CaculatePath;
Model.ControlPoint1PositionChanged += CaculatePath;
Model.ControlPoint2PositionChanged += CaculatePath;
if (Model.TrajectoryDegree == TrajectoryDegree.Three) ControlPoint2Visibility = "visible";
else ControlPoint2Visibility = "hidden";
Visibility = "visible";
}
else
{
Visibility = "hidden";
ControlPoint2Visibility = "hidden";
}
StateHasChanged();
}
private Task CaculatePath()
{
if (Model == null) return Task.CompletedTask;
X1 = Model.X1;
Y1 = Model.Y1;
X2 = Model.X2;
Y2 = Model.Y2;
CX1 = Model.ControlPoint1X;
CY1 = Model.ControlPoint1Y;
CX2 = Model.ControlPoint2X;
CY2 = Model.ControlPoint2Y;
StateHasChanged();
return Task.CompletedTask;
}
[JSInvokable]
public void OnMouseDown1(int button, bool altKey, bool ctrlKey, bool shiftKey)
{
if (Model != null)
{
Model.ActivedControlPoint1 = true;
Model.ActivedControlPoint2 = false;
}
}
[JSInvokable]
public void OnMouseDown2(int button, bool altKey, bool ctrlKey, bool shiftKey)
{
if (Model != null)
{
Model.ActivedControlPoint2 = true;
Model.ActivedControlPoint1 = false;
}
}
public void Dispose()
{
if (Model != null)
{
Model.StartNodePositionChanged -= CaculatePath;
Model.EndNodePositionChanged -= CaculatePath;
Model.ControlPoint1PositionChanged -= CaculatePath;
Model.ControlPoint2PositionChanged -= CaculatePath;
Model = null;
}
GC.SuppressFinalize(this);
}
}

View File

@@ -0,0 +1,23 @@
circle {
cursor: default;
fill: #FFBD33;
stroke: #FF5733;
stroke-width: 0;
r: var(--node-r);
}
circle:hover {
stroke-width: 0.02px;
}
circle:active {
stroke-width: 0.02px;
cursor: pointer;
stroke: green;
}
line {
stroke-width: 0.03px;
stroke: #d63384;
stroke-dasharray: 0.1 0.1;
}

View File

@@ -0,0 +1,163 @@
@inject IJSRuntime JSRuntime
<g @ref="Ref" visibility="hidden">
<defs>
<marker id="arrowhead" markerWidth="5" markerHeight="4" refX="5" refY="2" orient="auto">
<line x1="0" y1="0" x2="5" y2="2" style="stroke: #ff0000; stroke-width: 1px;" />
<line x1="5" y1="2" x2="0" y2="4" style="stroke: #ff0000; stroke-width: 1px;" />
</marker>
</defs>
<path @ref="PathRef" />
<line @ref="SubPath1Ref" x1="@StartNode.X" x2="@SubStartNode.X" y1="@StartNode.Y" y2="@SubStartNode.Y" stroke="#ff0000" stroke-width="0.05" marker-end="url(#arrowhead)" />
<line @ref="SubPath2Ref" x1="@EndNode.X" x2="@SubEndNode.X" y1="@EndNode.Y" y2="@SubEndNode.Y" stroke="#ff0000" stroke-width="0.05" marker-end="url(#arrowhead)" />
<circle cx="@StartNode.X" cy="@StartNode.Y" />
<circle cx="@EndNode.X" cy="@EndNode.Y" />
</g>
@code {
private ElementReference Ref;
private ElementReference PathRef;
private ElementReference SubPath1Ref;
private ElementReference SubPath2Ref;
private (double X, double Y) StartNode;
private (double X, double Y) SubStartNode;
private (double X, double Y) EndNode;
private (double X, double Y) SubEndNode;
private TrajectoryDegree Degree;
private (double X, double Y) ControlPoint1;
private (double X, double Y) ControlPoint2;
public CreateCurveEdgeStep CreateStep { get; set; } = CreateCurveEdgeStep.Hidden;
public async Task Update(double x, double y)
{
if (CreateStep == CreateCurveEdgeStep.CreateSubStartEdge)
{
SubStartNode.X = x;
SubStartNode.Y = y;
}
else if (CreateStep == CreateCurveEdgeStep.FinishCreateSubStartEdge)
{
EndNode.X = x;
EndNode.Y = y;
await CreateTangentPath();
}
else if (CreateStep == CreateCurveEdgeStep.CreateSubEndEdge)
{
SubEndNode.X = x;
SubEndNode.Y = y;
await CreateTangentPath();
}
StateHasChanged();
}
public async Task CreateSubEdgeAsync(double x, double y, TrajectoryDegree degree = TrajectoryDegree.Two)
{
Degree = degree;
if (CreateStep == CreateCurveEdgeStep.Hidden)
{
await Visible();
StartNode.X = x;
StartNode.Y = y;
SubStartNode.X = x;
SubStartNode.Y = y;
CreateStep = CreateCurveEdgeStep.CreateSubStartEdge;
}
else if (CreateStep == CreateCurveEdgeStep.FinishCreateSubStartEdge)
{
EndNode.X = x;
EndNode.Y = y;
SubEndNode.X = x;
SubEndNode.Y = y;
CreateStep = CreateCurveEdgeStep.CreateSubEndEdge;
await JSRuntime.InvokeVoidAsync("ElementSetAttribute", SubPath2Ref, "visibility", "visible");
}
StateHasChanged();
}
public async Task FinishSubEdgeAsync(double x, double y)
{
if (CreateStep == CreateCurveEdgeStep.CreateSubStartEdge)
{
SubStartNode.X = x;
SubStartNode.Y = y;
EndNode.X = x;
EndNode.Y = y;
CreateStep = CreateCurveEdgeStep.FinishCreateSubStartEdge;
await CreateTangentPath();
}
else if (CreateStep == CreateCurveEdgeStep.CreateSubEndEdge) CreateStep = CreateCurveEdgeStep.Finish;
}
public EdgeCreateModel GetEdgeCreateModel()
{
return new()
{
X1 = StartNode.X,
Y1 = StartNode.Y,
X2 = EndNode.X,
Y2 = EndNode.Y,
ControlPoint1X = ControlPoint1.X,
ControlPoint1Y = ControlPoint1.Y,
ControlPoint2X = ControlPoint2.X,
ControlPoint2Y = ControlPoint2.Y,
TrajectoryDegree = Degree,
};
}
private async Task CreateTangentPath()
{
var data = $"M {StartNode.X} {StartNode.Y}";
if(Degree == TrajectoryDegree.Two)
{
var cp = MapEditorHelper.CaculateIntersectionPoint(SubStartNode.X, SubStartNode.Y, StartNode.X, StartNode.Y, EndNode.X, EndNode.Y, SubEndNode.X, SubEndNode.Y);
if (cp is null || CreateStep == CreateCurveEdgeStep.FinishCreateSubStartEdge) cp = MapEditorHelper.CaculateControlPoint(StartNode.X, StartNode.Y, EndNode.X, EndNode.Y, 45, 1 / Math.Sqrt(2));
data = $"{data} Q {cp.Value.X} {cp.Value.Y} {EndNode.X} {EndNode.Y}";
ControlPoint1 = (cp.Value.X, cp.Value.Y);
}
else if(Degree == TrajectoryDegree.Three)
{
if (CreateStep == CreateCurveEdgeStep.FinishCreateSubStartEdge)
{
ControlPoint1 = MapEditorHelper.CaculateControlPoint(StartNode.X, StartNode.Y, EndNode.X, EndNode.Y, 45, 1 / Math.Sqrt(2));
ControlPoint2 = MapEditorHelper.CaculateControlPoint(StartNode.X, StartNode.Y, EndNode.X, EndNode.Y, -45, 1 / Math.Sqrt(2));
}
else (ControlPoint1.X, ControlPoint1.Y, ControlPoint2.X, ControlPoint2.Y) = MapEditorHelper.CaculateDoubleControlPoint(SubStartNode.X, SubStartNode.Y, StartNode.X, StartNode.Y, EndNode.X, EndNode.Y, SubEndNode.X, SubEndNode.Y);
data = $"{data} C {ControlPoint1.X} {ControlPoint1.Y}, {ControlPoint2.X} {ControlPoint2.Y}, {EndNode.X} {EndNode.Y}";
}
await JSRuntime.InvokeVoidAsync("ElementSetAttribute", PathRef, "d", data);
StateHasChanged();
}
public async Task Visible()
{
EndNode = (0, 0);
await JSRuntime.InvokeVoidAsync("ElementSetAttribute", PathRef, "d", "");
await JSRuntime.InvokeVoidAsync("ElementSetAttribute", SubPath1Ref, "visibility", "visible");
await JSRuntime.InvokeVoidAsync("ElementSetAttribute", SubPath2Ref, "visibility", "hidden");
await JSRuntime.InvokeVoidAsync("ElementSetAttribute", Ref, "visibility", "visible");
}
public async Task Hidden()
{
CreateStep = CreateCurveEdgeStep.Hidden;
await JSRuntime.InvokeVoidAsync("ElementSetAttribute", SubPath1Ref, "visibility", "hidden");
await JSRuntime.InvokeVoidAsync("ElementSetAttribute", SubPath2Ref, "visibility", "hidden");
await JSRuntime.InvokeVoidAsync("ElementSetAttribute", Ref, "visibility", "hidden");
}
public enum CreateCurveEdgeStep
{
Hidden,
CreateSubStartEdge,
FinishCreateSubStartEdge,
CreateSubEndEdge,
Finish,
}
}

View File

@@ -0,0 +1,12 @@
path {
stroke: red;
stroke-width: var(--edge-stroke-width);
fill: none;
}
circle {
fill: #FFBD33;
stroke: #FF5733;
stroke-width: 0;
r: var(--node-r);
}

View File

@@ -0,0 +1,113 @@
@implements IDisposable
@inject IJSRuntime JSRuntime
<polyline @ref="Ref" />
@code {
[Parameter, EditorRequired]
public EdgeModel Model { get; set; } = null!;
private ElementReference Ref;
protected override async Task OnAfterRenderAsync(bool firstRender)
{
await base.OnAfterRenderAsync(firstRender);
if (!firstRender) return;
await UpdatePathData();
await UpdateMaker();
}
public override async Task SetParametersAsync(ParameterView parameters)
{
bool updateLine = false;
if (parameters.TryGetValue(nameof(Model), out EdgeModel? model))
{
if (((Model?.Id ?? Guid.Empty) != (model?.Id ?? Guid.Empty)))
{
if (Model != null)
{
Model.StartNodePositionChanged -= UpdatePathData;
Model.EndNodePositionChanged -= UpdatePathData;
Model.ControlPoint1PositionChanged -= UpdatePathData;
Model.ControlPoint2PositionChanged -= UpdatePathData;
Model.DirectionChanged -= UpdateMaker;
}
if (model != null)
{
model.StartNodePositionChanged += UpdatePathData;
model.EndNodePositionChanged += UpdatePathData;
model.ControlPoint1PositionChanged += UpdatePathData;
model.ControlPoint2PositionChanged += UpdatePathData;
model.DirectionChanged += UpdateMaker;
updateLine = true;
}
}
}
await base.SetParametersAsync(parameters);
if (updateLine)
{
await UpdatePathData();
await UpdateMaker();
}
}
private async Task UpdatePathData()
{
string data = string.Empty;
double sx = 0, sy = 0, mx = 0, my = 0, ex = 0, ey = 0;
double sTime = 0.49, eTime = 0.5;
if (Model.TrajectoryDegree == TrajectoryDegree.One)
{
sx = Model.X1;
sy = Model.Y1;
ex = Model.X2;
ey = Model.Y2;
}
else if (Model.TrajectoryDegree == TrajectoryDegree.Two)
{
sx = (Model.X1 + Model.ControlPoint1X) / 2;
sy = (Model.Y1 + Model.ControlPoint1Y) / 2;
ex = (Model.X2 + Model.ControlPoint1X) / 2;
ey = (Model.Y2 + Model.ControlPoint1Y) / 2;
}
else if (Model.TrajectoryDegree == TrajectoryDegree.Three)
{
sx = Math.Pow(1 - sTime, 3) * Model.X1 + 3 * Math.Pow(1 - sTime, 2) * sTime * Model.ControlPoint1X + 3 * Math.Pow(sTime, 2) * (1 - sTime) * Model.ControlPoint2X + Math.Pow(sTime, 3) * Model.X2;
sy = Math.Pow(1 - sTime, 3) * Model.Y1 + 3 * Math.Pow(1 - sTime, 2) * sTime * Model.ControlPoint1Y + 3 * Math.Pow(sTime, 2) * (1 - sTime) * Model.ControlPoint2Y + Math.Pow(sTime, 3) * Model.Y2;
ex = Math.Pow(1 - eTime, 3) * Model.X1 + 3 * Math.Pow(1 - eTime, 2) * eTime * Model.ControlPoint1X + 3 * Math.Pow(eTime, 2) * (1 - eTime) * Model.ControlPoint2X + Math.Pow(eTime, 3) * Model.X2;
ey = Math.Pow(1 - eTime, 3) * Model.Y1 + 3 * Math.Pow(1 - eTime, 2) * eTime * Model.ControlPoint1Y + 3 * Math.Pow(eTime, 2) * (1 - eTime) * Model.ControlPoint2Y + Math.Pow(eTime, 3) * Model.Y2;
}
mx = (sx + ex) / 2;
my = (sy + ey) / 2;
await JSRuntime.InvokeVoidAsync("ElementSetAttribute", Ref, "points", $"{sx},{sy} {mx},{my} {ex},{ey}");
}
private async Task UpdateMaker()
{
if (Model == null) return;
await JSRuntime.InvokeVoidAsync("ElementSetAttribute", Ref, "marker-mid", MapSvgDefs.GetMakerMid(Model.DirectionAllowed));
}
public void Dispose()
{
if (Model != null)
{
Model.StartNodePositionChanged -= UpdatePathData;
Model.EndNodePositionChanged -= UpdatePathData;
Model.ControlPoint1PositionChanged -= UpdatePathData;
Model.ControlPoint2PositionChanged -= UpdatePathData;
Model.DirectionChanged -= UpdateMaker;
}
GC.SuppressFinalize(this);
}
}

View File

@@ -0,0 +1,5 @@
polyline {
stroke-width: var(--edge-direction-stroke-width);
stroke: none;
fill: none;
}

View File

@@ -0,0 +1,46 @@
@inject IJSRuntime JSRuntime
<g @ref="Ref" visibility="hidden">
<path @ref="PathRef" />
<circle cx="@X1" cy="@Y1" />
<circle cx="@X2" cy="@Y2" />
</g>
@code {
private ElementReference Ref;
private ElementReference PathRef;
public double X1;
public double Y1;
public double X2;
public double Y2;
public async Task Update(double x, double y)
{
X2 = x;
Y2 = y;
await CaculatePath();
}
public async Task StartCreateAsync(double x, double y)
{
X1 = x;
Y1 = y;
X2 = x;
Y2 = y;
await CaculatePath();
await Visible();
}
private async Task CaculatePath()
{
var data = $"M {X1} {Y1} L {(X1 + X2) / 2} {(Y1 + Y2) / 2} L {X2} {Y2}";
await JSRuntime.InvokeVoidAsync("ElementSetAttribute", PathRef, "d", data);
StateHasChanged();
}
public async Task Visible() => await JSRuntime.InvokeVoidAsync("ElementSetAttribute", Ref, "visibility", "visible");
public async Task Hidden() => await JSRuntime.InvokeVoidAsync("ElementSetAttribute", Ref, "visibility", "hidden");
}

View File

@@ -0,0 +1,12 @@
path {
stroke: red;
stroke-width: var(--edge-stroke-width);
fill: none;
}
circle {
fill: #FFBD33;
stroke: #FF5733;
stroke-width: 0;
r: var(--node-r);
}

View File

@@ -0,0 +1,255 @@
@implements IDisposable
@inject IJSRuntime JSRuntime
@inject IHttpClientFactory HttpClientFactory
@inject ISnackbar Snackbar
<g>
@foreach (var edge in Models)
{
<Edge Model="edge" DoubleClick="OnEdgeDoubleClick" EditorState="@EditorState" />
}
@foreach (var edge in Models)
{
<EdgeDirection Model="edge" />
}
</g>
<MudDialog @bind-Visible="updateEdgeVisible">
<TitleContent>
<MudText Typo="Typo.h6">
Update edge @UpdateModel.Id
</MudText>
</TitleContent>
<DialogContent>
<div class="d-flex flex-row align-items-center">
<MudText>
Length: @SelectModelLength m
</MudText>
</div>
<div class="d-flex flex-row mt-2">
<div class="d-flex flex-column">
<div class="mb-2">
<MudNumericField @bind-Value="UpdateModel.ControlPoint1X" Label="Control Point 1 X" Variant="Variant.Outlined" Margin="Margin.Dense" Step="0.1" ReadOnly=@(MapIsActive) />
</div>
<div class="mb-2">
<MudNumericField @bind-Value="UpdateModel.ControlPoint2X" Label="Control Point 2 X" Variant="Variant.Outlined" Margin="Margin.Dense" Step="0.1" ReadOnly=@(MapIsActive) />
</div>
<div class="mb-2">
<MudSelect @bind-Value="UpdateModel.DirectionAllowed" Label="Direction Allowed" Variant="Variant.Outlined" AnchorOrigin="Origin.BottomLeft" Margin="Margin.Dense" Dense ReadOnly=@(MapIsActive)>
<MudSelectItem Value="@(DirectionAllowed.None)" />
<MudSelectItem Value="@(DirectionAllowed.Backward)" />
<MudSelectItem Value="@(DirectionAllowed.Forward)" />
<MudSelectItem Value="@(DirectionAllowed.Both)" />
</MudSelect>
</div>
<div class="mb-2">
<MudNumericField @bind-Value="UpdateModel.AllowedDeviationXy" Label="AllowedDeviationXy" Step="0.01" Min="0" Variant="Variant.Outlined" Margin="Margin.Dense" ReadOnly=@(MapIsActive) />
</div>
<div class="mb-2">
<MudNumericField @bind-Value="UpdateModel.AllowedDeviationTheta" Label="AllowedDeviationTheta" Step="1" Min="0" Max="180" Variant="Variant.Outlined" Margin="Margin.Dense" ReadOnly=@(MapIsActive) />
</div>
<div class="d-flex">
<MudCheckBox @bind-Value="UpdateModel.RotationAllowed" Label="Rotation Allowed" LabelPlacement="Placement.Start" ReadOnly=@(MapIsActive) UncheckedColor="Color.Default" Color="Color.Success" />
</div>
</div>
<div class="d-flex flex-column ms-2">
<div class="mb-2">
<MudNumericField @bind-Value="UpdateModel.ControlPoint1Y" Label="Control Point 1 Y" Variant="Variant.Outlined" Margin="Margin.Dense" Step="0.1" ReadOnly=@(MapIsActive) />
</div>
<div class="mb-2">
<MudNumericField @bind-Value="UpdateModel.ControlPoint2Y" Label="Control Point 2 Y" Variant="Variant.Outlined" Margin="Margin.Dense" Step="0.1" ReadOnly=@(MapIsActive) />
</div>
<div class="mb-2">
<MudNumericField @bind-Value="UpdateModel.MaxSpeed" Label="Max Speed" Variant="Variant.Outlined" Margin="Margin.Dense" Step="0.1" Min="0" ReadOnly=@(MapIsActive) />
</div>
<div class="mb-2">
<MudNumericField @bind-Value="UpdateModel.MaxRotationSpeed" Label="Max Rotation Speed" Variant="Variant.Outlined" Margin="Margin.Dense" Step="0.1" Min="0" ReadOnly=@(MapIsActive) />
</div>
<div class="mb-2">
<MudNumericField @bind-Value="UpdateModel.MaxHeight" Label="Max Height" Variant="Variant.Outlined" Margin="Margin.Dense" Step="0.1" Min="0" ReadOnly=@(MapIsActive) />
</div>
<div class="mb-2">
<MudNumericField @bind-Value="UpdateModel.MinHeight" Label="Min Height" Variant="Variant.Outlined" Margin="Margin.Dense" Step="0.1" Min="0" ReadOnly=@(MapIsActive) />
</div>
</div>
<div class="d-flex flex-column ms-2 flex-grow-1">
<div class="d-flex flex-row mb-2">
<MudSelect @bind-Value=ActionSelected Margin="Margin.Dense" T="ActionDto" Label="Action" Variant="Variant.Outlined" Class="w-100" AnchorOrigin="Origin.BottomLeft">
@foreach (var action in Actions)
{
<MudSelectItem Value="@action">@action.Name</MudSelectItem>
}
</MudSelect>
<MudFab Class="ms-2" Color="Color.Secondary" StartIcon="@Icons.Material.Filled.Add" Size="Size.Medium" OnClick="AddAction" />
</div>
<div class="paper-action">
@foreach (var actionId in UpdateModel.Actions)
{
<div class="m-1" style="height: fit-content">
<MudButton Variant="Variant.Filled" Color="Color.Info" Style="text-transform:none" OnClick="(() => DeleteAction(actionId))">
@(Actions.FirstOrDefault(ac => ac.Id == actionId)?.Name)
</MudButton>
</div>
}
</div>
</div>
</div>
</DialogContent>
<DialogActions>
<MudButton OnClick="CancelUpdateEdge" Class="px-10" Variant="Variant.Filled">Cancel</MudButton>
<MudButton OnClick="UpdateEdge" Variant="Variant.Filled" Color="Color.Primary" Class="px-10" Disabled=@(MapIsActive || EditorState == EditorState.View)>Update</MudButton>
</DialogActions>
</MudDialog>
@code {
[Parameter, EditorRequired]
public MapEdgeModel Models { get; set; } = null!;
[CascadingParameter]
protected bool MapIsActive { get; set; }
[Parameter]
public EventCallback<EdgeModel?> EdgeSelectedChanged { get; set; }
[Parameter]
public EditorState EditorState { get; set; }
private EdgeUpdateModel UpdateModel = new();
private bool updateEdgeVisible;
private string ActionsText { get; set; } = "";
private double SelectModelLength;
private List<ActionDto> Actions = [];
private ActionDto? ActionSelected = null;
private HttpClient Http = default!;
protected override async Task OnAfterRenderAsync(bool firstRender)
{
await base.OnAfterRenderAsync(firstRender);
if (!firstRender) return;
Http = HttpClientFactory.CreateClient("MapManagerAPI");
Models.Changed += StateHasChanged;
Models.EdgeSelectedChanged += async (model) => await EdgeSelectedChanged.InvokeAsync(model);
}
private async Task LoadActionAsync(Guid mapVersionId)
{
var result = await Http.GetFromJsonAsync<IEnumerable<ActionDto>>($"api/Actions/{mapVersionId}");
if (result is not null && result.Any())
{
Actions.Clear();
Actions.AddRange(result);
}
if (Actions.Any()) ActionSelected = Actions.First();
StateHasChanged();
}
private void AddAction()
{
if (ActionSelected is null) return;
if (UpdateModel.Actions.Any(action => action == ActionSelected.Id))
{
Snackbar.Add("Action đã tồn tại", Severity.Warning);
return;
}
UpdateModel.Actions = [.. UpdateModel.Actions, ActionSelected.Id];
StateHasChanged();
}
private void DeleteAction(Guid actionId)
{
UpdateModel.Actions = UpdateModel.Actions.Where(a => actionId != a).ToArray();
StateHasChanged();
}
private async Task OnEdgeDoubleClick(EdgeModel model)
{
if (model == null || EditorState != EditorState.NavigationEdit) return;
await LoadActionAsync(model.MapId);
UpdateModel.Id = model.Id;
UpdateModel.ControlPoint1X = model.ControlPoint1X;
UpdateModel.ControlPoint1Y = model.ControlPoint1Y;
UpdateModel.ControlPoint2X = model.ControlPoint2X;
UpdateModel.ControlPoint2Y = model.ControlPoint2Y;
UpdateModel.DirectionAllowed = model.DirectionAllowed;
UpdateModel.MaxSpeed = model.MaxSpeed;
UpdateModel.MaxHeight = model.MaxHeight;
UpdateModel.MinHeight = model.MinHeight;
UpdateModel.RotationAllowed = model.RotationAllowed;
UpdateModel.MaxRotationSpeed = model.MaxRotationSpeed;
UpdateModel.AllowedDeviationXy = model.AllowedDeviationXy;
UpdateModel.AllowedDeviationTheta = model.AllowedDeviationTheta;
UpdateModel.Actions = [];
var actions = JsonSerializer.Deserialize<Guid[]>(model.Actions);
if (actions is not null && actions.Length > 0)
{
UpdateModel.Actions = [.. actions];
}
SelectModelLength = MapEditorHelper.GetEdgeLength(new()
{
TrajectoryDegree = model.TrajectoryDegree,
X1 = model.X1,
Y1 = model.Y1,
X2 = model.X2,
Y2 = model.Y2,
ControlPoint1X = model.ControlPoint1X,
ControlPoint1Y = model.ControlPoint1Y,
ControlPoint2X = model.ControlPoint2X,
ControlPoint2Y = model.ControlPoint2Y,
});
updateEdgeVisible = true;
StateHasChanged();
}
private void CancelUpdateEdge()
{
updateEdgeVisible = false;
StateHasChanged();
}
private async Task UpdateEdge()
{
var selectedModel = Models.FirstOrDefault(e => e.Id == UpdateModel.Id);
if (selectedModel == null)
{
updateEdgeVisible = false;
StateHasChanged();
return;
}
var result = await (await Http.PutAsJsonAsync($"api/Edges", UpdateModel)).Content.ReadFromJsonAsync<MessageResult>();
if (result is null)
{
Snackbar.Add("Lỗi giao tiếp với hệ thống", Severity.Error);
return;
}
else if (!result.IsSuccess)
{
Snackbar.Add(result.Message, Severity.Error);
return;
}
selectedModel.UpdateData(UpdateModel);
updateEdgeVisible = false;
Snackbar.Add("Cập nhật thành công", Severity.Success);
StateHasChanged();
}
public void Dispose()
{
Models.Changed -= StateHasChanged;
GC.SuppressFinalize(this);
}
}

View File

@@ -0,0 +1,13 @@
.paper-action {
padding: 5px;
border: 1px solid silver;
border-radius: 10px;
display: flex;
flex-wrap: wrap;
align-content: flex-start;
overflow-x: hidden;
overflow-y: auto;
width: 280px;
max-height: 288px;
height: 100%;
}

View File

@@ -0,0 +1,113 @@
@implements IDisposable
@inject IHttpClientFactory HttpClientFactory
@inject IJSRuntime JSRuntime
<g class="element" visibility="@(IsShow ? "visible" : "hidden")" @ondblclick="@(async () => await DoubleClick.InvokeAsync(Model))">
<image @ref="@ImageRef" />
<text @ref="textRef" visibility="@(ShowName && IsShow ? "visible" : "hidden")">@Model?.Name</text>
</g>
@code {
[Parameter, EditorRequired]
public ElementModel Model { get; set; } = null!;
[Parameter]
public bool ShowName { get; set; }
[Parameter]
public EditorState EditorState { get; set; }
[Parameter]
public EventCallback<ElementModel> DoubleClick { get; set; }
private ElementReference ImageRef;
private ElementReference textRef;
private ElementModelDto ElementModel = new();
private bool IsSetting => EditorState == EditorState.View;
private bool IsShow => EditorState == EditorState.View;
private HttpClient? Http;
protected override async Task OnAfterRenderAsync(bool firstRender)
{
await base.OnAfterRenderAsync(firstRender);
if (!firstRender) return;
Http = HttpClientFactory.CreateClient("MapManagerAPI");
var model = await Http.GetFromJsonAsync<MessageResult<ElementModelDto?>>($"api/ElementModels/{Model.ModelId}");
if (model is not null && model.Data is not null)
{
await JSRuntime.InvokeVoidAsync("SetImageAttribute", ImageRef, model.Data.Width, model.Data.Height, -model.Data.Width / 2, -model.Data.Height / 2, $"{Http.BaseAddress}api/images/elementModel/{model.Data.Id}?IsOpen={Model.IsOpen}");
ElementModel = model.Data;
}
if (Model is not null)
{
Model.PositionChanged += Model_PositionChanged;
Model.OffsetChanged += Model_OffsetChanged;
await UpdatePosition(Model.X, Model.Y, Model.Theta);
}
}
public override async Task SetParametersAsync(ParameterView parameters)
{
bool updateRobot = false;
if (parameters.TryGetValue(nameof(Model), out ElementModel? model) && ((Model?.Id ?? Guid.Empty) != (model?.Id ?? Guid.Empty)))
{
if (Model != null)
{
Model.OffsetChanged -= Model_OffsetChanged;
Model.PositionChanged -= Model_PositionChanged;
}
if (model != null)
{
updateRobot = true;
model.OffsetChanged += Model_OffsetChanged;
model.PositionChanged += Model_PositionChanged;
}
}
await base.SetParametersAsync(parameters);
if (updateRobot && model != null)
{
if (Http is null) Http = HttpClientFactory.CreateClient("MapManagerAPI");
var elementModel = await Http.GetFromJsonAsync<MessageResult<ElementModelDto?>>($"api/ElementModels/{model.ModelId}");
if (elementModel is not null && elementModel.Data is not null) ElementModel = elementModel.Data;
await SetElementImage(model.IsOpen);
await UpdatePosition(model.X, model.Y, model.Theta);
}
}
private async Task SetElementImage(bool isOpen)
{
if (Http is null) Http = HttpClientFactory.CreateClient("MapManagerAPI");
if(ElementModel is null)
{
var elementModel = await Http.GetFromJsonAsync<MessageResult<ElementModelDto?>>($"api/ElementModels/{Model.ModelId}");
if (elementModel is not null && elementModel.Data is not null) ElementModel = elementModel.Data;
}
if (ElementModel is not null)
{
await JSRuntime.InvokeVoidAsync("SetImageAttribute", ImageRef, ElementModel.Width, ElementModel.Height, (-ElementModel.Width / 2), (-ElementModel.Height / 2), $"{Http.BaseAddress}api/images/elementModel/{ElementModel.Id}?IsOpen={isOpen}");
}
}
public async Task UpdatePosition(double x, double y, double theta)
=> await JSRuntime.InvokeVoidAsync("SetElementPosition", ImageRef, textRef, x + Model.OffsetX, y + Model.OffsetY, theta, -ElementModel.Width / 2, -ElementModel.Height / 2);
public async Task UpdatePosition(double offsetX, double offsetY)
=> await JSRuntime.InvokeVoidAsync("SetElementPosition", ImageRef, textRef, Model.X + offsetX, Model.Y + offsetY, Model.Theta, -ElementModel.Width / 2, -ElementModel.Height / 2);
private async Task Model_PositionChanged() => await UpdatePosition(Model.X, Model.Y, Model.Theta);
private async Task Model_OffsetChanged() => await UpdatePosition(Model.OffsetX, Model.OffsetY);
public void Dispose()
{
if (Model != null)
{
Model.OffsetChanged -= Model_OffsetChanged;
Model.PositionChanged -= Model_PositionChanged;
}
GC.SuppressFinalize(this);
}
}

View File

@@ -0,0 +1,21 @@
text {
dominant-baseline: middle;
text-anchor: middle;
fill: red;
transform: scale(1, -1);
font-size: 0.01em;
user-select: none;
font-weight: normal;
}
.element {
transform-origin: center;
transform-box: fill-box;
}
.element:hover {
cursor: pointer;
transform: scale(1.2);
filter: drop-shadow(0 0 5px rgba(0, 0, 0, 0.3));
transition: all 0.5s ease;
}

View File

@@ -0,0 +1,558 @@
@using RobotNet.MapShares.Models
@using RobotNet.WebApp.Maps.Components.Editor.Edge
@using RobotNet.WebApp.Maps.Components.Editor.Node
@using RobotNet.WebApp.Maps.Components.Editor.Zone
@inject IJSRuntime JSRuntime
@inject IHttpClientFactory HttpClientFactory
@inject IDialogService Dialog
@inject ISnackbar Snackbar
<div class="map-viewer-container" @ref="ViewContainerRef" tabindex="1">
<div @ref=ViewMovementRef>
<svg @ref=MapContainerRef class="map-editor" letter-spacing="normal">
<MapSvgDefs />
<image @ref="MapImageRef" class="map-image" visibility="@(ShowMapSlam ? "visible" : "hidden")" />
<OriginVector />
<CascadingValue Value="MapIsActive">
<MapGrid @ref="@MapGridRef" Show="@ShowGrid" />
<MapZone Models="@Zones" IsShow="@(EditorState != EditorState.CreateZone && EditorState != EditorState.SettingZone)" />
<MapEdge @ref="MapEdgesRef" Models="@Edges" EdgeSelectedChanged="OnSelectedEdgeChanged" EditorState="@EditorState" />
<MapNode Models="@Nodes" Elements="Elements" ShowName="@ShowName" EditorState="@EditorState" />
<EdgeControlPoint @ref="EdgeControlPointRef" />
<EdgeStraightCreating @ref="EdgeStraightCreatingRef" />
<EdgeCurveCreating @ref="EdgeCurveCreatingRef" />
<MapZone @ref=@MapZoneRef Models="@Zones" IsShow="@(EditorState == EditorState.CreateZone || EditorState == EditorState.SettingZone)" IsSetting="@(EditorState == EditorState.SettingZone)" ActivedZoneChanged="OnActivedZoneChanged" EditorState="@EditorState" />
<MapScaner @ref=MapScanerRef />
<ZoneCreating @ref=ZoneCreatingRef />
<ZoneControlPoint @ref="ZoneControlPointRef"/>
<MapCopy @ref=MapCopyRef />
</CascadingValue>
</svg>
</div>
<MapMousePosition @ref="MapInfoRef" />
<MudOverlay @bind-Visible="OverlayIsVisible" DarkBackground="true" Absolute="true">
<MudText Typo="Typo.h1" Color="@Color.Error" Style="font-weight: bold;">@OverlayIsStr</MudText>
</MudOverlay>
</div>
@code {
[Parameter]
public bool ShowGrid { get; set; }
[Parameter]
public bool ShowName { get; set; }
[Parameter]
public bool ShowMapSlam { get; set; }
[Parameter]
public bool MapIsActive { get; set; }
[Parameter]
public ZoneType ZoneType { get; set; }
[Parameter]
public EditorState EditorState { get; set; }
[Parameter]
public EventCallback<bool> MultiselectedEdgeChanged { get; set; }
[Parameter]
public EventCallback<bool> MultiselectedNodeChanged { get; set; }
[Parameter]
public EventCallback<bool> ZoneselectedChanged { get; set; }
[Parameter]
public EventCallback<bool> NodesUndoableChanged { get; set; }
[Parameter]
public EventCallback<EditorState> KeyPress { get; set; }
[Parameter]
public EventCallback<bool> MapIsChecking { get; set; }
private MapMousePosition MapInfoRef = null!;
private EdgeStraightCreating EdgeStraightCreatingRef = null!;
private EdgeCurveCreating EdgeCurveCreatingRef = null!;
private MapEdge MapEdgesRef = null!;
private MapGrid MapGridRef = null!;
private EdgeControlPoint EdgeControlPointRef = null!;
private MapScaner MapScanerRef = null!;
private ZoneCreating ZoneCreatingRef = null!;
private MapZone MapZoneRef = null!;
private ZoneControlPoint ZoneControlPointRef = null!;
private MapCopy MapCopyRef = null!;
private DotNetObjectReference<MapContainer> DotNetObj = null!;
private ElementReference ViewContainerRef;
private ElementReference ViewMovementRef;
private ElementReference MapContainerRef;
private ElementReference MapImageRef;
private double ViewContainerRectX;
private double ViewContainerRectY;
private double ViewContainerRectWidth;
private double ViewContainerRectHeight;
private double ViewContainerRectTop;
private double ViewContainerRectRight;
private double ViewContainerRectBottom;
private double ViewContainerRectLeft;
private double CursorX;
private double CursorY;
private double ClientOriginX;
private double ClientOriginY;
private double Scale = 1;
private double Left;
private double Top;
private double FitScale = 1;
private double Resolution = 1;
private double OriginX;
private double OriginY;
private double ImageWidth;
private double ImageHeight;
private MapDataDto MapData = new();
public MapEdgeModel Edges { get; set; } = [];
public MapNodeModel Nodes { get; set; } = [];
public MapZoneModel Zones { get; set; } = [];
public MapElementModel Elements { get; set; } = [];
private HttpClient Http = default!;
private bool OverlayIsVisible = false;
private string OverlayIsStr = "Loading...";
protected override async Task OnAfterRenderAsync(bool firstRender)
{
await base.OnAfterRenderAsync(firstRender);
if (!firstRender) return;
Http = HttpClientFactory.CreateClient("MapManagerAPI");
DotNetObj = DotNetObjectReference.Create(this);
await JSRuntime.InvokeVoidAsync("DOMCssLoaded");
await JSRuntime.InvokeVoidAsync("UpdateViewContainerRect", DotNetObj, ViewContainerRef, nameof(ViewContainerResize));
await JSRuntime.InvokeVoidAsync("ResizeObserverRegister", DotNetObj, ViewContainerRef, nameof(ViewContainerResize));
await JSRuntime.InvokeVoidAsync("AddMouseMoveEventListener", DotNetObj, ViewContainerRef, nameof(MouseMoveOnMapContainer));
await JSRuntime.InvokeVoidAsync("AddEventListener", DotNetObj, ViewContainerRef, "click", nameof(ViewContainerClick));
await JSRuntime.InvokeVoidAsync("AddKeyUpEventListener", DotNetObj, ViewContainerRef, nameof(ViewContainerKeyUp));
await JSRuntime.InvokeVoidAsync("AddMouseWheelEventListener", DotNetObj, MapContainerRef, nameof(MouseWheelOnMapContainer));
await JSRuntime.InvokeVoidAsync("AddMouseUpEventListener", DotNetObj, MapContainerRef, nameof(MouseUpOnMapContainer));
await JSRuntime.InvokeVoidAsync("AddMouseDownEventListener", DotNetObj, MapContainerRef, nameof(MouseDownOnMapContainer));
await JSRuntime.InvokeVoidAsync("AddTouchMoveEventListener", DotNetObj, ViewContainerRef, nameof(TouchMoveOnMapContainer));
}
private async Task LoadMap()
{
try
{
OverlayIsVisible = true;
StateHasChanged();
var mapDataResult = await Http.GetFromJsonAsync<MessageResult<MapDataDto>>($"api/MapsData/{MapData.Id}");
if (mapDataResult is not null && mapDataResult.Data is not null)
{
MapIsActive = mapDataResult.Data.Active;
await LoadMap(mapDataResult.Data);
OverlayIsVisible = false;
}
else OverlayIsStr = "Map Not Existed";
StateHasChanged();
}
catch
{
OverlayIsStr = "Map Not Existed";
StateHasChanged();
return;
}
}
public async Task LoadMap(MapDataDto? mapData)
{
if (mapData == null)
{
MapData = new();
Nodes.ReplaceAll([]);
Edges.ReplaceAll([]);
Zones.ReplaceAll([]);
Elements.ReplaceAll([]);
Resolution = 1.0;
OriginY = 0;
OriginX = 0;
ImageHeight = 0;
ImageWidth = 0;
MapGridRef.Resize(OriginX, OriginY, ImageHeight, ImageWidth);
await JSRuntime.InvokeVoidAsync("SetMapSvgConfig", MapContainerRef, ImageWidth, ImageHeight, OriginX, 1.0);
await JSRuntime.InvokeVoidAsync("SetImageAttribute", MapImageRef, ImageWidth, ImageHeight, OriginX, OriginY, "");
}
else
{
MapData = mapData;
Nodes.ReplaceAll(MapData.Nodes);
Edges.ReplaceAll(MapData.Edges.Select(edge => new EdgeModel(edge, Nodes[edge.StartNodeId], Nodes[edge.EndNodeId])));
Zones.ReplaceAll(MapData.Zones);
Elements.ReplaceAll(MapData.Elements.Select(element => new ElementModel(element, Nodes[element.NodeId])));
Resolution = mapData.Resolution;
OriginY = -mapData.ImageHeight * Resolution - mapData.OriginY;
OriginX = mapData.OriginX;
ImageHeight = mapData.ImageHeight * Resolution;
ImageWidth = mapData.ImageWidth * Resolution;
MapGridRef.Resize(OriginX, OriginY, ImageHeight, ImageWidth);
await JSRuntime.InvokeVoidAsync("SetMapSvgConfig", MapContainerRef, ImageWidth, ImageHeight, OriginX, mapData.OriginY);
await JSRuntime.InvokeVoidAsync("SetImageAttribute", MapImageRef, ImageWidth, ImageHeight, OriginX, OriginY, $"{Http.BaseAddress}api/images/map/{mapData.Id}");
await JSRuntime.InvokeVoidAsync("UpdateViewContainerRect", DotNetObj, ViewContainerRef, nameof(ViewContainerResize));
await ScaleFitContentAsync();
}
}
public async Task ScaleFitContentAsync()
{
Scale = FitScale;
await SetViewMovement((ViewContainerRectWidth - ImageWidth * Scale) / 2, (ViewContainerRectHeight - ImageHeight * Scale) / 2);
await JSRuntime.InvokeVoidAsync("SetMapSvgRect", MapContainerRef, ImageWidth * Scale, ImageHeight * Scale);
}
private async Task SetViewMovement(double left, double top)
{
Top = top;
Left = left;
ClientOriginX = ViewContainerRectLeft + Left - OriginX * Scale;
ClientOriginY = ViewContainerRectTop + Top - OriginY * Scale;
await JSRuntime.InvokeVoidAsync("SetMapMovement", ViewMovementRef, Top, Left);
}
public async Task ScaleZoom(double deltaY)
{
if (deltaY > 0)
{
if (Scale >= FitScale * 20) return;
}
else
{
if (Scale <= FitScale / 2) return;
}
double oldScale = Scale;
Scale += deltaY;
double centerXBefore = ((ViewContainerRectLeft + ViewContainerRectWidth / 2) - ClientOriginX) / oldScale - OriginX;
double centerYBefore = (ClientOriginY - (ViewContainerRectHeight / 2 + ViewContainerRectTop)) / oldScale - (MapData is null ? 0 : MapData.OriginY);
await SetViewMovement(Left - centerXBefore * deltaY, Top - (ImageHeight - centerYBefore) * deltaY);
await JSRuntime.InvokeVoidAsync("SetMapSvgRect", MapContainerRef, ImageWidth * Scale, ImageHeight * Scale);
}
[JSInvokable]
public async Task ViewContainerClick() => await ViewContainerRef.FocusAsync();
[JSInvokable]
public void ViewContainerResize(double x, double y, double width, double height, double top, double right, double bottom, double left)
{
ViewContainerRectX = x;
ViewContainerRectY = y;
ViewContainerRectWidth = width;
ViewContainerRectHeight = height;
ViewContainerRectTop = top;
ViewContainerRectRight = right;
ViewContainerRectBottom = bottom;
ViewContainerRectLeft = left;
ClientOriginX = ViewContainerRectLeft + Left - OriginX * Scale;
ClientOriginY = ViewContainerRectTop + Top - OriginY * Scale;
FitScale = Math.Min(ViewContainerRectWidth / ImageWidth, ViewContainerRectHeight / ImageHeight);
}
[JSInvokable]
public async Task TouchMoveOnMapContainer(double clientX, double clientY, int touchCount, double movementX, double movementY)
{
CursorX = (clientX - ClientOriginX) / Scale;
CursorY = (ClientOriginY - clientY) / Scale;
MapInfoRef.Update(CursorX, CursorY);
if (touchCount == 1) await SetViewMovement(Left + movementX, Top + movementY);
}
[JSInvokable]
public async Task MouseWheelOnMapContainer(double deltaY, double offsetX, double offsetY)
{
double scaleChange;
if (deltaY > 0)
{
if (Scale <= FitScale / 2) return;
scaleChange = Scale > FitScale ? -(Scale / FitScale) : -0.1;
}
else
{
if (Scale >= FitScale * 100) return;
scaleChange = Scale < FitScale ? 0.5 : (Scale / FitScale);
}
double oldScale = Scale;
Scale += scaleChange;
await JSRuntime.InvokeVoidAsync("SetMapSvgRect", MapContainerRef, ImageWidth * Scale, ImageHeight * Scale);
double mouseX = CursorX - OriginX;
double mouseY = CursorY - (MapData is null ? 0 : MapData.OriginY);
await SetViewMovement(Left - mouseX * scaleChange, Top - (ImageHeight - mouseY) * scaleChange);
}
[JSInvokable]
public async Task MouseMoveOnMapContainer(double clientX, double clientY, long buttons, bool ctrlKey, double movementX, double movementY)
{
CursorX = (clientX - ClientOriginX) / Scale;
CursorY = (ClientOriginY - clientY) / Scale;
MapInfoRef.Update(CursorX, CursorY);
if (EditorState == EditorState.CreateCurveEdge || EditorState == EditorState.CreateDoubleCurveEdge) await EdgeCurveCreatingRef.Update(CursorX, CursorY);
else if (EditorState == EditorState.CreateZone) await ZoneCreatingRef.Update(CursorX, CursorY);
switch (buttons)
{
case 1:
if (MapIsActive) break;
switch (EditorState)
{
case EditorState.CreateStraighEdge:
await EdgeStraightCreatingRef.Update(CursorX, CursorY);
break;
case EditorState.CreateCurveEdge:
case EditorState.CreateDoubleCurveEdge:
await EdgeCurveCreatingRef.Update(CursorX, CursorY);
break;
case EditorState.Scaner:
await MapScanerRef.Update(CursorX, CursorY);
break;
case EditorState.NavigationEdit:
if (ctrlKey) NodePositionMove(CursorX, CursorY);
break;
case EditorState.SettingZone:
if (ctrlKey) ZoneUpdateShape(CursorX, CursorY);
break;
case EditorState.Move:
if (ctrlKey)
{
if (Edges.ActivedEdges.Count > 0) EdgesPositionMove(CursorX, CursorY);
else NodesPositionMove(CursorX, CursorY);
}
break;
case EditorState.Copy:
if (ctrlKey) MapCopyRef.UpdateMove(CursorX, CursorY);
break;
}
break;
case 4:
await SetViewMovement(Left + movementX, Top + movementY);
break;
}
}
[JSInvokable]
public async Task ViewContainerKeyUp(string code, string key, bool altKey, bool ctrlKey, bool shiftKey)
{
if (MapIsActive) return;
switch (code)
{
case "Escape":
await EditStateChange();
break;
case "Delete":
_ = InvokeAsync(async Task () =>
{
if (EditorState == EditorState.NavigationEdit || EditorState == EditorState.Scaner) await DeleteEdge();
else if (EditorState == EditorState.SettingZone) await DeleteZone();
});
break;
case "KeyZ":
if (ctrlKey) UndoEditorBackup();
break;
case "KeyS":
if (ctrlKey) await SaveChanged();
break;
case "KeyM":
if (EditorState != EditorState.Scaner) return;
if (ctrlKey)
{
if (EditorBackup.Count > 0)
{
var save = await SaveChanged();
if (!save) break;
}
await SetCursor("grab");
await KeyPress.InvokeAsync(EditorState.Move);
}
break;
case "KeyC":
if (EditorState != EditorState.Scaner) return;
if (ctrlKey) await KeyPress.InvokeAsync(EditorState.Copy);
break;
}
StateHasChanged();
}
[JSInvokable]
public async Task MouseUpOnMapContainer(int button, bool altKey, bool ctrlKey, bool shiftKey)
{
if (button == 0 && !MapIsActive)
{
switch (EditorState)
{
case EditorState.CreateStraighEdge:
await CreateEdge(EdgeStraightCreatingRef.X1, EdgeStraightCreatingRef.Y1, EdgeStraightCreatingRef.X2, EdgeStraightCreatingRef.Y2);
await EdgeStraightCreatingRef.Hidden();
break;
case EditorState.CreateCurveEdge:
case EditorState.CreateDoubleCurveEdge:
await EdgeCurveCreatingRef.FinishSubEdgeAsync(CursorX, CursorY);
if (EdgeCurveCreatingRef.CreateStep == EdgeCurveCreating.CreateCurveEdgeStep.Finish)
{
var edgeCreateModel = EdgeCurveCreatingRef.GetEdgeCreateModel();
await CreateEdge(edgeCreateModel.X1, edgeCreateModel.Y1, edgeCreateModel.X2, edgeCreateModel.Y2, edgeCreateModel.TrajectoryDegree, edgeCreateModel.ControlPoint1X, edgeCreateModel.ControlPoint1Y, edgeCreateModel.ControlPoint2X, edgeCreateModel.ControlPoint2Y);
await EdgeCurveCreatingRef.Hidden();
}
break;
case EditorState.Scaner:
await ScanerActive(MapScanerRef.X1, MapScanerRef.Y1, MapScanerRef.X2, MapScanerRef.Y2);
await MapScanerRef.Hidden();
break;
case EditorState.CreateZone:
if (ZoneCreatingRef.Step == 4)
{
await CreateZone(ZoneCreatingRef.X1, ZoneCreatingRef.Y1, ZoneCreatingRef.X2, ZoneCreatingRef.Y2, ZoneCreatingRef.X3, ZoneCreatingRef.Y3, ZoneCreatingRef.X4, ZoneCreatingRef.Y4, ZoneType);
await ZoneCreatingRef.Hidden();
}
break;
case EditorState.SettingZone:
if (Zones.ZoneActived is not null && Zones.ZoneActived.ActiveNode != 5) Zones.ZoneActived.ActiveNode = 5;
break;
case EditorState.NavigationEdit:
if (Edges.ActivedEdges.Count == 1)
{
Edges.ActivedEdges[0].ActivedControlPoint1 = false;
Edges.ActivedEdges[0].ActivedControlPoint2 = false;
}
Nodes.SelectedNode = null;
break;
case EditorState.Move:
await SetCursor("grab");
break;
}
StateHasChanged();
}
}
[JSInvokable]
public async Task MouseDownOnMapContainer(int button, bool altKey, bool ctrlKey, bool shiftKey)
{
if (button == 0 && !MapIsActive)
{
var startNode = MapEditorHelper.GetClosesNode(CursorX, CursorY, Nodes.Select(node => new NodeDto() { X = node.X, Y = node.Y }).ToList());
switch (EditorState)
{
case EditorState.CreateStraighEdge:
await EdgeStraightCreatingRef.StartCreateAsync(startNode?.X ?? CursorX, startNode?.Y ?? CursorY);
break;
case EditorState.CreateCurveEdge:
await EdgeCurveCreatingRef.CreateSubEdgeAsync(startNode?.X ?? CursorX, startNode?.Y ?? CursorY);
break;
case EditorState.CreateDoubleCurveEdge:
await EdgeCurveCreatingRef.CreateSubEdgeAsync(startNode?.X ?? CursorX, startNode?.Y ?? CursorY, TrajectoryDegree.Three);
break;
case EditorState.Scaner:
await MapScanerRef.CreateAsync(CursorX, CursorY);
break;
case EditorState.CreateZone:
await ZoneCreatingRef.CreateAsync(CursorX, CursorY);
break;
case EditorState.SettingZone:
if (Zones.ZoneActived is not null) Zones.ZoneActived.SetStartMovePosition(CursorX, CursorY);
break;
case EditorState.Move:
await SetCursor("grabbing");
Edges.SetStartMovePosition(CursorX, CursorY);
Nodes.SetStartMovePosition(CursorX, CursorY);
break;
case EditorState.Copy:
MapCopyRef.SetStartMovePosition(CursorX, CursorY);
break;
}
}
}
private async Task OnSelectedEdgeChanged(EdgeModel? model)
{
if (model is not null && EditorState == EditorState.NavigationEdit)
{
if (model.TrajectoryDegree == TrajectoryDegree.One) EdgeControlPointRef.SetControl(null);
else EdgeControlPointRef.SetControl(model);
Edges.ActivedEdge([model]);
await MultiselectedEdgeChanged.InvokeAsync(Edges.ActivedEdges.Count > 0);
}
else EdgeControlPointRef.SetControl(null);
}
private void OnActivedZoneChanged((ZoneModel model, bool state) data)
{
if (EditorState == EditorState.SettingZone)
{
if (data.state)
{
ZoneControlPointRef.SetControl(data.model);
_ = ZoneselectedChanged.InvokeAsync(true);
return;
}
}
ZoneControlPointRef.SetControl(null);
}
public async Task EditStateChange()
{
await EdgeCurveCreatingRef.Hidden();
await EdgeStraightCreatingRef.Hidden();
await ZoneCreatingRef.Hidden();
MapCopyRef.OnShow(false, []);
Zones.UnActivedZone();
EdgeControlPointRef.SetControl(null);
if (EditorState == EditorState.Copy) await CreateMapCopy();
if (EditorState != EditorState.Move)
{
Edges.UnActivedEdge();
Nodes.UnActivedNode();
}
if (EditorState != EditorState.Copy) await SaveChanged();
if (EditorState != EditorState.Copy && EditorState != EditorState.Move) await SetCursor("initial");
await MultiselectedEdgeChanged.InvokeAsync(Edges.ActivedEdges.Count() > 0);
await MultiselectedNodeChanged.InvokeAsync(Nodes.ActivedNodes.Count() > 0);
await ZoneselectedChanged.InvokeAsync(false);
StateHasChanged();
}
public async Task CreateMapCopy()
{
if (Edges.ActivedEdges.Count > 0)
{
if (EditorBackup.Count > 0)
{
var save = await SaveChanged();
if (!save) return;
}
MapCopyRef.OnShow(true, Edges.ActivedEdges);
EditorBackup.Add(new()
{
Type = MapEditorBackupType.Copy,
});
await NodesUndoableChanged.InvokeAsync(true);
await SetCursor("copy");
}
}
public async Task SetCursor(string data) => await JSRuntime.InvokeVoidAsync("ElementSetAttribute", MapContainerRef, "cursor", data);
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,28 @@
.map-viewer-container {
background-color: #bfbfbf;
width: 100%;
height: 100%;
cursor: not-allowed;
border-top: solid 2px #808080;
overflow: hidden;
position: relative;
}
.map-viewer-container > div {
width: fit-content;
height: fit-content;
position: absolute;
cursor: default;
display: flex;
overflow: hidden;
}
.map-image {
user-select: none;
image-rendering: pixelated;
transform: scale(1, -1);
}
.map-editor {
transform: scale(1, -1);
}

View File

@@ -0,0 +1,121 @@
@implements IDisposable
@using RobotNet.WebApp.Maps.Components.Editor.Edge
@using RobotNet.WebApp.Maps.Components.Editor.Node
<MapEdge Models="@this.EdgeModels" />
<MapNode Models="@this.NodeModels" />
@code {
public MapEdgeModel EdgeModels { get; set; } = [];
public MapNodeModel NodeModels { get; set; } = [];
public bool isMoving = false;
private bool isShowing = false;
private (Guid Id, double X, double Y) StartPosition = new();
public void OnShow(bool isShow, List<EdgeModel> edgeModels)
{
isShowing = isShow;
if (isShow && edgeModels.Count > 0)
{
isMoving = false;
List<NodeDto> nodeDtos = [];
foreach (var edge in edgeModels)
{
if (!nodeDtos.Any(n => n.Id == edge.StartNode.Id)) nodeDtos.Add(new()
{
Id = edge.StartNode.Id,
MapId = edge.StartNode.MapId,
Name = edge.StartNode.Name,
X = edge.StartNode.X,
Y = edge.StartNode.Y,
Theta = edge.StartNode.Theta,
AllowedDeviationXy = edge.StartNode.AllowedDeviationXy,
AllowedDeviationTheta = edge.StartNode.AllowedDeviationTheta,
Actions = edge.StartNode.Actions,
});
if (!nodeDtos.Any(n => n.Id == edge.EndNode.Id)) nodeDtos.Add(new()
{
Id = edge.EndNode.Id,
MapId = edge.EndNode.MapId,
Name = edge.EndNode.Name,
X = edge.EndNode.X,
Y = edge.EndNode.Y,
Theta = edge.EndNode.Theta,
AllowedDeviationXy = edge.EndNode.AllowedDeviationXy,
AllowedDeviationTheta = edge.EndNode.AllowedDeviationTheta,
Actions = edge.EndNode.Actions,
});
}
NodeModels.ReplaceAll(nodeDtos);
List<EdgeModel> edges = edgeModels.Select(edge => new EdgeModel(new()
{
Id = edge.Id,
MapId = edge.MapId,
DirectionAllowed = edge.DirectionAllowed,
TrajectoryDegree = edge.TrajectoryDegree,
Actions = edge.Actions,
AllowedDeviationTheta = edge.AllowedDeviationTheta,
AllowedDeviationXy = edge.AllowedDeviationXy,
RotationAllowed = edge.RotationAllowed,
MaxHeight = edge.MaxHeight,
MinHeight = edge.MinHeight,
MaxRotationSpeed = edge.MaxRotationSpeed,
MaxSpeed = edge.MaxRotationSpeed,
ControlPoint1X = edge.ControlPoint1X,
ControlPoint1Y = edge.ControlPoint1Y,
ControlPoint2X = edge.ControlPoint2X,
ControlPoint2Y = edge.ControlPoint2Y,
},
NodeModels[edge.StartNode.Id],
NodeModels[edge.EndNode.Id]
)).ToList();
EdgeModels.ReplaceAll(edges);
EdgeModels.ActivedEdge(edges);
if (NodeModels.Count() > 0)
{
StartPosition.Id = NodeModels[0].Id;
StartPosition.X = NodeModels[0].X;
StartPosition.Y = NodeModels[0].Y;
}
}
else
{
isMoving = false;
NodeModels.ReplaceAll([]);
EdgeModels.ReplaceAll([]);
}
StateHasChanged();
}
public void UpdateMove(double x, double y)
{
if (!isShowing) return;
if (NodeModels.Count() > 0)
{
var nodeChange = NodeModels[StartPosition.Id];
if (nodeChange is not null)
{
var distance = Math.Sqrt(Math.Pow(StartPosition.X - nodeChange.X, 2) + Math.Pow(StartPosition.Y - nodeChange.Y, 2));
if (distance > 0.25) isMoving = true;
else isMoving = false;
}
EdgeModels.UpdateMoveEdge(x, y);
}
}
public void SetStartMovePosition(double x, double y)
{
EdgeModels.SetStartMovePosition(x, y);
}
public void Dispose()
{
GC.SuppressFinalize(this);
}
}

View File

@@ -0,0 +1,37 @@
<g visibility="@(Show ? "visible" : "hidden")">
@for (int x = startX; x <= endX; x += 1)
{
<line x1="@x" y1="@originY" x2="@x" y2="@(height + originY)" />
}
@for (int y = startY; y <= endY; y += 1)
{
<line x1="@originX" y1="@y" x2="@(width + originX)" y2="@y" />
}
</g>
@code {
[Parameter, EditorRequired]
public bool Show { get; set; }
private double originX;
private double originY;
private int startX;
private int startY;
private int endX;
private int endY;
private double width;
private double height;
public void Resize(double mapOriginX, double mapOriginY, double mapheight, double mapwidth)
{
width = mapwidth;
height = mapheight;
originX = mapOriginX;
originY = -height - mapOriginY;
startX = (int)Math.Ceiling(originX);
startY = (int)Math.Ceiling(originY);
endX = (int)Math.Floor(width + mapOriginX);
endY = (int)Math.Floor(-mapOriginY);
StateHasChanged();
}
}

View File

@@ -0,0 +1,6 @@
line {
stroke: gray;
stroke-width: 0.04px;
stroke-opacity: 1;
stroke-dasharray: 0.05 0.1;
}

View File

@@ -0,0 +1,20 @@
<div class="map-editor-info">
<div class="px-1 pt-1">
@X
</div>
<div class ="px-1 pb-1">
@Y
</div>
</div>
@code {
private double X;
private double Y;
public void Update(double x, double y)
{
X = Math.Round(x, 3);
Y = Math.Round(y, 3);
StateHasChanged();
}
}

View File

@@ -0,0 +1,14 @@
div {
width:fit-content;
height: fit-content;
}
.map-editor-info {
color: #00cc66;
font-size: 15px;
position: absolute;
top: 5px;
left: 5px;
font-weight: bold;
background-color:white;
border-radius:4px
}

View File

@@ -0,0 +1,40 @@
@inject IJSRuntime JSRuntime
<polygon @ref="Ref" visibility="hidden" />
@code {
private ElementReference Ref;
public double X1 { get; private set; }
public double Y1 { get; private set; }
public double X2 { get; private set; }
public double Y2 { get; private set; }
public async Task CreateAsync(double x, double y)
{
X1 = x;
Y1 = y;
X2 = x;
Y2 = y;
await CalculatorZone();
await Visible();
}
public async Task Update(double x, double y)
{
X2 = x;
Y2 = y;
await CalculatorZone();
}
private async Task CalculatorZone()
{
var points = $"{X1},{Y1} {X1},{Y2} {X2},{Y2} {X2},{Y1}";
await JSRuntime.InvokeVoidAsync("ElementSetAttribute", Ref, "points", points);
}
public async Task Visible() => await JSRuntime.InvokeVoidAsync("ElementSetAttribute", Ref, "visibility", "visible");
public async Task Hidden() => await JSRuntime.InvokeVoidAsync("ElementSetAttribute", Ref, "visibility", "hidden");
}

View File

@@ -0,0 +1,5 @@
polygon {
fill: #c2c2a3;
stroke: none;
fill-opacity: 0.5;
}

View File

@@ -0,0 +1,32 @@
<defs>
<marker id="edge-two-way" markerWidth="2" markerHeight="1" refX="1" refY="0.5" orient="auto">
<polyline points="0.8,0.3 0.6,0.5 0.8,0.7"/>
<polyline points="1.2,0.3 1.4,0.5 1.2,0.7"/>
<polyline points="0.6,0.5 1.4,0.5" />
</marker>
<marker id="edge-forward" markerWidth="2" markerHeight="1" refX="1" refY="0.5" orient="auto">
<polyline points="1.2,0.3 1.4,0.5 1.2,0.7"/>
<polyline points="0.6,0.5 1.4,0.5"/>
</marker>
<marker id="edge-backward" markerWidth="2" markerHeight="1" refX="1" refY="0.5" orient="auto">
<polyline points="0.8,0.3 0.6,0.5 0.8,0.7"/>
<polyline points="0.6,0.5 1.4,0.5"/>
</marker>
<marker id="edge-none" markerWidth="2" markerHeight="1" refX="1" refY="0.5" orient="auto">
<polyline points="0.6,0.5 1.4,0.5"/>
</marker>
</defs>
@code {
public static string GetMakerMid(DirectionAllowed direction)
{
return direction switch
{
DirectionAllowed.Both => $"url(#edge-two-way)",
DirectionAllowed.Forward => $"url(#edge-forward)",
DirectionAllowed.Backward => $"url(#edge-backward)",
DirectionAllowed.None => $"url(#edge-none)",
_ => "",
};
}
}

View File

@@ -0,0 +1,5 @@
polyline {
stroke: #DD22FF;
stroke-width: 0.05px;
fill: none;
}

View File

@@ -0,0 +1,489 @@
@using System.Text.Json
@using Microsoft.AspNetCore.Components.WebAssembly.Authentication
@using RobotNet.WebApp.Maps.Components.Editor.Element
@inject ISnackbar Snackbar
@inject IHttpClientFactory HttpClientFactory
@inject IDialogService Dialog
@foreach (var node in Models)
{
<Node Model="node" ShowName="@ShowName" OnClick="NodeClickChanged" DoubleClick="OnNodeDoubleClick" EditorState="@EditorState" />
}
@foreach (var element in Elements)
{
<Element Model="@element" ShowName="@ShowName" EditorState="EditorState" DoubleClick="ElementDoubleClick" />
}
<MudDialog @bind-Visible="updateNodeVisible">
<TitleContent>
<MudText Typo="Typo.h6">
Update node @UpdateModel.Id
</MudText>
</TitleContent>
<DialogContent>
<div class="d-flex flex-row">
<div class="d-flex flex-column">
<div class="mb-2">
<MudTextField @bind-Value="UpdateModel.Name" Label="Name" ShrinkLabel Variant="Variant.Outlined" Margin="Margin.Dense" ReadOnly=@(MapIsActive) />
</div>
<div class="mb-2">
<MudNumericField @bind-Value="UpdateModel.X" Label="X" ShrinkLabel Variant="Variant.Outlined" Margin="Margin.Dense" ReadOnly=@(MapIsActive) />
</div>
<div class="mb-2">
<MudNumericField @bind-Value="UpdateModel.Y" Label="Y" ShrinkLabel Variant="Variant.Outlined" Margin="Margin.Dense" ReadOnly=@(MapIsActive) />
</div>
<div class="mb-2">
<MudNumericField @bind-Value="UpdateModel.Theta" Label="Theta" AdornmentText="Degree" Max="180" Min="-180" ShrinkLabel Variant="Variant.Outlined" Margin="Margin.Dense" ReadOnly=@(MapIsActive) />
</div>
<div class="mb-2">
<MudNumericField @bind-Value="UpdateModel.AllowedDeviationXy" Label="AllowedDeviationXy" Step="0.01" Min="0" ShrinkLabel Variant="Variant.Outlined" Margin="Margin.Dense" ReadOnly=@(MapIsActive) />
</div>
<div>
<MudNumericField @bind-Value="UpdateModel.AllowedDeviationTheta" Label="AllowedDeviationTheta" Step="1" Min="0" Max="180" ShrinkLabel Variant="Variant.Outlined" Margin="Margin.Dense" ReadOnly=@(MapIsActive) />
</div>
</div>
<div class="d-flex flex-column ms-2 flex-grow-1">
<div class="d-flex flex-row mb-5">
<MudSelect @bind-Value=ActionSelected Margin="Margin.Dense" T="ActionDto" Label="Action" Variant="Variant.Outlined" Class="w-100" AnchorOrigin="Origin.BottomLeft">
@foreach (var action in Actions)
{
<MudSelectItem Value="@action">@action.Name</MudSelectItem>
}
</MudSelect>
<MudFab Class="ms-2" Color="Color.Secondary" StartIcon="@Icons.Material.Filled.Add" Size="Size.Medium" OnClick="AddAction" />
</div>
<div class="paper-action">
@foreach (var actionId in UpdateModel.Actions)
{
<div class="m-1" style="height: fit-content">
<MudButton Variant="Variant.Filled" Color="Color.Info" Style="text-transform:none" OnClick="(() => DeleteAction(actionId))">
@(Actions.FirstOrDefault(ac => ac.Id == actionId)?.Name)
</MudButton>
</div>
}
</div>
</div>
</div>
</DialogContent>
<DialogActions>
<MudButton OnClick="(() => updateNodeVisible = false)" Class="px-10" Variant="Variant.Filled">Cancel</MudButton>
<MudButton OnClick="UpdateNode" Variant="Variant.Filled" Color="Color.Primary" Class="px-10 me-4" Disabled=@(MapIsActive)>Update</MudButton>
</DialogActions>
</MudDialog>
<MudDialog @bind-Visible="createElementVisible">
<TitleContent>
<MudText Typo="Typo.h6">
Create Element Node @ElementCreateModel.NodeId
</MudText>
</TitleContent>
<DialogContent>
<div class="d-flex flex-column" style="max-height: 700px; overflow-y: auto">
<MudTextField Class="my-2"
@bind-Value="ElementCreateModel.Name" T="string"
Label="Name" Required="true" RequiredError="Name is required!"
Counter="18" Variant="Variant.Outlined"
Validation="@(new Func<string, IEnumerable<string>>(MapEditorHelper.NameValidation))" />
<div class="d-flex flex-row mb-2">
<MudNumericField Class="me-2" @bind-Value="ElementCreateModel.OffsetX" Label="Offset X" Step="0.1" Variant="Variant.Outlined" />
<MudNumericField Class="ms-2" @bind-Value="ElementCreateModel.OffsetY" Label="Offset Y" Step="0.1" Variant="Variant.Outlined" />
</div>
<MudSelect Class="mb-2" T="ElementModelDto" Variant="Variant.Outlined" Label="Type" Required="true" RequiredError="Type is required!"
@bind-Value="@ElementModelSelected">
@foreach (var model in ElementModels)
{
<MudSelectItem Value="@model">@model.Name</MudSelectItem>
}
</MudSelect>
</div>
</DialogContent>
<DialogActions>
<MudButton OnClick="(() => createElementVisible = false)" Class="px-10" Variant="Variant.Filled">Cancel</MudButton>
<MudButton OnClick="CreateElement" Variant="Variant.Filled" Color="Color.Primary" Class="px-10" Disabled=@(MapIsActive)>Create</MudButton>
</DialogActions>
</MudDialog>
<MudDialog @bind-Visible="updateElementVisble">
<TitleContent>
<MudText Typo="Typo.h6">
Update Element @ElementUpdateModel.Name
</MudText>
</TitleContent>
<DialogContent>
<div class="d-flex flex-row" style="max-height: 700px; overflow-y: auto; width: 600px">
<div class="d-flex flex-column h-100 me-2" style="width: 47%">
<MudTextField T="string" Label="Name" @bind-value="ElementUpdateModel.Name" Variant="Variant.Outlined" ReadOnly="@(MapIsActive)"
Required="true" RequiredError="Name is required!"
Validation="@(new Func<string, IEnumerable<string>>(MapEditorHelper.NameValidation))" />
<MudNumericField T="double" Label="Offset X" @bind-value="ElementUpdateModel.OffsetX" Variant="Variant.Outlined" Step="0.1" ReadOnly="@(MapIsActive)" />
<MudNumericField T="double" Label="Offset Y" @bind-value="ElementUpdateModel.OffsetY" Variant="Variant.Outlined" Step="0.1" ReadOnly="@(MapIsActive)" />
@* <MudCheckBox Size="Size.Small" T="bool" LabelPlacement="Placement.Start" Label="IsOpen" @bind-value="ElementUpdateModel.IsOpen" Color="Color.Success"
UncheckedColor="Color.Default" ReadOnly /> *@
</div>
<div class="paper-property-container">
<div class="paper-property ms-2">
@foreach (var property in ElementProperties)
{
@if (property.Type == typeof(int).ToString())
{
if (int.TryParse(property.DefaultValue, out int value))
{
<MudNumericField T="int" Margin="Margin.Dense" Label="@property.Name" Value="value" Variant="Variant.Outlined" ReadOnly="@(MapIsActive)"
ValueChanged="((data) => DefaultIntValueChanged(property.Id, data))" />
}
}
else if (property.Type == typeof(double).ToString())
{
if (double.TryParse(property.DefaultValue, out double value))
{
<MudNumericField T="double" Margin="Margin.Dense" Label="@property.Name" Value="value" Variant="Variant.Outlined" Step="0.1" ReadOnly="@(MapIsActive)"
ValueChanged="((data) => DefaultDoubleValueChanged(property.Id, data))" />
}
}
else if (property.Type == typeof(bool).ToString())
{
if (bool.TryParse(property.DefaultValue, out bool value))
{
<MudCheckBox Class="m-0" Size="Size.Small" T="bool" LabelPlacement="Placement.Start" Label="@property.Name" Value="value" Color="Color.Success"
UncheckedColor="Color.Default" ReadOnly="@(MapIsActive)" ValueChanged="((data) => DefaultBooleanValueChanged(property.Id, data))" />
}
}
else if (property.Type == typeof(string).ToString())
{
<MudTextField T="string" Label="@property.Name" Value="@property.DefaultValue" Variant="Variant.Outlined" Margin="Margin.Dense" ReadOnly="@(MapIsActive)"
ValueChanged="((data) => property.DefaultValue = data)" />
}
}
</div>
<span class="paper-title">Properties</span>
</div>
</div>
</DialogContent>
<DialogActions>
<MudButton OnClick="Delete" Variant="Variant.Filled" Color="Color.Secondary" Class="px-10" Disabled=@(MapIsActive)>Delete</MudButton>
<MudButton OnClick="(() => updateElementVisble = false)" Class="px-10" Variant="Variant.Filled">Cancel</MudButton>
<MudButton OnClick="UpdateElement" Variant="Variant.Filled" Color="Color.Primary" Class="px-10" Disabled=@(MapIsActive)>Update</MudButton>
</DialogActions>
</MudDialog>
@code {
[Parameter, EditorRequired]
public MapNodeModel Models { get; set; } = null!;
[Parameter]
public MapElementModel Elements { get; set; } = [];
[CascadingParameter]
protected bool MapIsActive { get; set; }
[Parameter]
public bool ShowName { get; set; }
[Parameter]
public EditorState EditorState { get; set; }
private NodeUpdateModel UpdateModel = new();
private bool updateNodeVisible;
private List<ActionDto> Actions = [];
private ActionDto? ActionSelected = null;
public List<ElementModelDto> ElementModels { get; set; } = [];
private bool createElementVisible;
private ElementCreateModel ElementCreateModel = new();
private ElementModelDto? ElementModelSelected = null;
private NodeModel? NodeModelDoubleClick = null;
private bool updateElementVisble;
private ElementUpdateModel ElementUpdateModel = new();
private List<ElementProperty> ElementProperties = [];
private HttpClient Http = default!;
protected override void OnAfterRender(bool firstRender)
{
base.OnAfterRender(firstRender);
if (!firstRender) return;
Http = HttpClientFactory.CreateClient("MapManagerAPI");
Models.Changed += StateHasChanged;
Elements.Changed += StateHasChanged;
}
private void NodeClickChanged(NodeModel? node) => Models.SelectedNode = node;
private async Task LoadActionAsync(Guid mapId)
{
var result = await Http.GetFromJsonAsync<IEnumerable<ActionDto>>($"api/Actions/{mapId}");
if (result is not null && result.Any())
{
Actions.Clear();
Actions.AddRange(result);
}
if (Actions.Any()) ActionSelected = Actions.First();
StateHasChanged();
}
private async Task LoadElementModels(Guid mapId)
{
ElementModels.Clear();
var elModels = await Http.GetFromJsonAsync<MessageResult<IEnumerable<ElementModelDto>>>($"api/ElementModels/map/{mapId}");
if (elModels is null) Snackbar.Add("Lỗi giao tiếp với hệ thống", Severity.Error);
else if (!elModels.IsSuccess) Snackbar.Add($"Có lỗi xảy ra: {elModels.Message}", Severity.Error);
else if(elModels.Data is null || !elModels.Data.Any())
{
Snackbar.Add("Không có Element model nào trong bản đồ này", Severity.Warning);
ElementModelSelected = null;
}
else
{
ElementModels.AddRange(elModels.Data.OrderBy(el => el.Name));
if (ElementModels.Count > 0)
{
ElementModelSelected = ElementModelSelected is null ? ElementModels.First() : ElementModels.FirstOrDefault(em => em.Id == ElementModelSelected.Id) ?? ElementModels.First();
}
}
StateHasChanged();
}
private void AddAction()
{
if (ActionSelected is null) return;
if (UpdateModel.Actions.Any(action => action == ActionSelected.Id))
{
Snackbar.Add("Action đã tồn tại", Severity.Warning);
return;
}
UpdateModel.Actions = [.. UpdateModel.Actions, ActionSelected.Id];
StateHasChanged();
}
private void DeleteAction(Guid actionId)
{
UpdateModel.Actions = UpdateModel.Actions.Where(a => actionId != a).ToArray();
StateHasChanged();
}
private async Task OnNodeDoubleClick(NodeModel model)
{
if (model == null || (EditorState != EditorState.NavigationEdit && EditorState != EditorState.View)) return;
NodeModelDoubleClick = model;
if (EditorState == EditorState.NavigationEdit)
{
await LoadActionAsync(model.MapId);
UpdateModel.Id = model.Id;
UpdateModel.Name = model.Name;
UpdateModel.X = model.X;
UpdateModel.Y = model.Y;
UpdateModel.Theta = model.Theta;
UpdateModel.AllowedDeviationXy = model.AllowedDeviationXy;
UpdateModel.AllowedDeviationTheta = model.AllowedDeviationTheta;
UpdateModel.Actions = [];
var actions = JsonSerializer.Deserialize<Guid[]>(model.Actions ?? "");
if (actions is not null && actions.Length > 0)
{
UpdateModel.Actions = [.. actions];
}
updateNodeVisible = true;
}
else if (EditorState == EditorState.View)
{
await LoadElementModels(model.MapId);
ElementCreateModel.Name = "";
ElementCreateModel.MapId = model.MapId;
ElementCreateModel.NodeId = model.Id;
createElementVisible = true;
}
StateHasChanged();
}
private async Task UpdateNode()
{
var selectedModel = Models.FirstOrDefault(e => e.Id == UpdateModel.Id);
if (selectedModel == null)
{
updateNodeVisible = false;
StateHasChanged();
return;
}
var result = await (await Http.PutAsJsonAsync($"api/Nodes", UpdateModel)).Content.ReadFromJsonAsync<MessageResult>();
if (result is null)
{
Snackbar.Add("Lỗi giao tiếp với hệ thống", Severity.Error);
return;
}
else if (!result.IsSuccess)
{
Snackbar.Add(result.Message, Severity.Error);
return;
}
selectedModel.UpdateData(UpdateModel);
updateNodeVisible = false;
Snackbar.Add("Cập nhật thành công", Severity.Success);
StateHasChanged();
}
private async Task CreateElement()
{
try
{
if (NodeModelDoubleClick is null) return;
if (ElementModelSelected is null)
{
Snackbar.Add("Hãy chọn Element model!", Severity.Warning);
return;
}
if (string.IsNullOrEmpty(ElementCreateModel.Name))
{
Snackbar.Add("Name không được để trống.", Severity.Warning);
return;
}
var nameInvalid = MapEditorHelper.NameChecking(ElementCreateModel.Name);
if (!nameInvalid.IsSuccess)
{
Snackbar.Add(nameInvalid.returnStr, Severity.Warning);
return;
}
ElementCreateModel.ModelId = ElementModelSelected.Id;
var create = await (await Http.PostAsJsonAsync("api/Elements", ElementCreateModel)).Content.ReadFromJsonAsync<MessageResult<ElementDto>>();
if (create is null) Snackbar.Add("Lỗi giao tiếp với hệ thống", Severity.Error);
else if (!create.IsSuccess) Snackbar.Add($"Có lỗi xảy ra: {create.Message}", Severity.Error);
else if (create.Data is null) Snackbar.Add("Tạo Element không thành công", Severity.Error);
else
{
Elements.Add(new(create.Data, NodeModelDoubleClick));
createElementVisible = false;
Snackbar.Add("Tạo Element thành công!", Severity.Success);
}
StateHasChanged();
}
catch (AccessTokenNotAvailableException ex)
{
ex.Redirect();
return;
}
}
private void ElementDoubleClick(ElementModel model)
{
ElementUpdateModel.Id = model.Id;
ElementUpdateModel.Name = model.Name;
ElementUpdateModel.IsOpen = model.IsOpen;
ElementUpdateModel.OffsetX = model.OffsetX;
ElementUpdateModel.OffsetY = model.OffsetY;
ElementUpdateModel.Content = model.Content;
if (model is not null && !string.IsNullOrEmpty(model.Content))
{
var properties = JsonSerializer.Deserialize<List<ElementProperty>>(model.Content, JsonOptionExtends.Read);
if (properties is not null) ElementProperties = [.. properties];
}
updateElementVisble = true;
StateHasChanged();
}
private async Task Delete()
{
var parameters = new DialogParameters<ConfirmDialog>
{
{ x => x.Content, $"Bạn có chắc chắn muốn xóa element {ElementUpdateModel.Name} đi không?" },
{ x => x.ConfirmText, "Delete" },
{ x => x.Color, Color.Secondary }
};
var ConfirmDelete = await Dialog.ShowAsync<ConfirmDialog>("Xoá Element", parameters);
var result = await ConfirmDelete.Result;
if (result is not null && result.Data is not null && bool.TryParse(result.Data.ToString(), out bool data) && data)
{
var response = await Http.DeleteFromJsonAsync<MessageResult>($"api/Elements/{ElementUpdateModel.Id}");
if (response is null) Snackbar.Add("Lỗi giao tiếp với hệ thống", Severity.Error);
else if (!response.IsSuccess) Snackbar.Add(response.Message ?? "Lỗi chưa xác định.", Severity.Error);
else
{
var elementData = Elements.FirstOrDefault(m => m.Id == ElementUpdateModel.Id);
if (elementData is not null)
{
Elements.Remove(elementData);
Snackbar.Add($"Xóa element thành công.", Severity.Success);
}
else Snackbar.Add($"Element không tồn tại.", Severity.Warning);
}
updateElementVisble = false;
StateHasChanged();
}
}
private void DefaultIntValueChanged(Guid id, int value)
{
var property = ElementProperties.FirstOrDefault(p => p.Id == id);
if (property is null) return;
property.DefaultValue = value.ToString();
}
private void DefaultDoubleValueChanged(Guid id, double value)
{
var property = ElementProperties.FirstOrDefault(p => p.Id == id);
if (property is null) return;
property.DefaultValue = value.ToString();
}
private void DefaultBooleanValueChanged(Guid id, bool value)
{
var property = ElementProperties.FirstOrDefault(p => p.Id == id);
if (property is null) return;
property.DefaultValue = value.ToString();
}
private async Task UpdateElement()
{
var selectedElement = Elements.FirstOrDefault(e => e.Id == ElementUpdateModel.Id);
if (selectedElement is null) return;
var result = await (await Http.PutAsJsonAsync($"api/Elements", new ElementUpdateModel()
{
Id = ElementUpdateModel.Id,
Name = ElementUpdateModel.Name,
IsOpen = ElementUpdateModel.IsOpen,
OffsetX = ElementUpdateModel.OffsetX,
OffsetY = ElementUpdateModel.OffsetY,
Content = JsonSerializer.Serialize(ElementProperties, JsonOptionExtends.Write),
})).Content.ReadFromJsonAsync<MessageResult<ElementDto>>();
if (result == null) Snackbar.Add("Lỗi giao tiếp với hệ thống", Severity.Error);
else if (!result.IsSuccess) Snackbar.Add(result.Message, Severity.Error);
else if (result.Data is null) Snackbar.Add("Lỗi dữ liệu", Severity.Error);
else
{
selectedElement.UpdateElement(result.Data);
Snackbar.Add("Cập nhật thành công", Severity.Success);
}
updateElementVisble = false;
StateHasChanged();
}
public void Dispose()
{
Models.Changed -= StateHasChanged;
Elements.Changed -= StateHasChanged;
GC.SuppressFinalize(this);
}
}

View File

@@ -0,0 +1,44 @@
.paper-action {
padding: 5px;
border: 1px solid silver;
border-radius: 10px;
display: flex;
flex-wrap: wrap;
align-content: flex-start;
overflow-x: hidden;
overflow-y: auto;
width: 100%;
max-width: 290px;
height: 100%;
max-height: 277px;
}
.paper-property-container {
position: relative;
display: inline-block;
width: 50%;
height: 193px;
}
.paper-title {
font-size: 12px;
padding: 0 5px;
position: absolute;
background-color: var(--mud-palette-surface);
top: 0px;
left: 15px;
}
.paper-property {
padding: 10px;
border-radius: var(--mud-default-borderradius);
border: 1px solid var(--mud-palette-lines-inputs);
display: flex;
flex-direction: column;
width: 100%;
height: 100%;
position: relative;
overflow-x: hidden;
overflow-y: auto;
margin: 8px;
}

View File

@@ -0,0 +1,102 @@
@implements IDisposable
@inject IJSRuntime JSRuntime
<circle @ref="circleErrorRef" style="fill: red; opacity: 0.6; r: 0.3px;"/>
<circle @ref="circleRef" @ondblclick="@(async () => await DoubleClick.InvokeAsync(Model))" class="@(IsSetting ? "setting" : "")" />
<text @ref="textRef" visibility="@(ShowName ? "visible" : "hidden")" class="@(IsSetting ? "setting" : "")">@Model?.Name</text>
@code {
[Parameter, EditorRequired]
public NodeModel Model { get; set; } = null!;
[Parameter]
public EventCallback<NodeModel> DoubleClick { get; set; }
[Parameter]
public EventCallback<NodeModel?> OnClick { get; set; }
[CascadingParameter]
protected bool MapIsActive { get; set; }
[Parameter]
public bool ShowName { get; set; }
[Parameter]
public EditorState EditorState { get; set; }
private ElementReference circleRef;
private ElementReference textRef;
private ElementReference circleErrorRef;
private DotNetObjectReference<Node> DotNetObj = null!;
private bool IsError = false;
private bool IsSetting => EditorState == EditorState.NavigationEdit || EditorState == EditorState.CreateStraighEdge || EditorState == EditorState.CreateCurveEdge ||
EditorState == EditorState.CreateDoubleCurveEdge || EditorState == EditorState.View;
protected override async Task OnAfterRenderAsync(bool firstRender)
{
await base.OnAfterRenderAsync(firstRender);
if (!firstRender) return;
DotNetObj = DotNetObjectReference.Create(this);
await JSRuntime.InvokeVoidAsync("AddMouseDownEventListener", DotNetObj, circleRef, nameof(OnMouseDown), false);
await UpdatePosition(Model.X, Model.Y);
await JSRuntime.InvokeVoidAsync("ElementSetAttribute", circleErrorRef, "visibility", "hidden");
}
public override async Task SetParametersAsync(ParameterView parameters)
{
bool updateNode = false;
if (parameters.TryGetValue(nameof(Model), out NodeModel? model) && ((Model?.Id ?? Guid.Empty) != (model?.Id ?? Guid.Empty)))
{
if (Model != null)
{
Model.PositionChanged -= Model_PositionChanged;
Model.ActivedChanged -= ActivedChanged;
Model.ErrorChanged -= ErrorChanged;
}
if (model != null)
{
updateNode = true;
model.PositionChanged += Model_PositionChanged;
model.ActivedChanged += ActivedChanged;
model.ErrorChanged += ErrorChanged;
}
}
await base.SetParametersAsync(parameters);
if (updateNode && model != null) await UpdatePosition(model.X, model.Y);
}
private async void Model_PositionChanged() => await UpdatePosition(Model.X, Model.Y);
[JSInvokable]
public async Task OnMouseDown(int button, bool altKey, bool ctrlKey, bool shiftKey) => await OnClick.InvokeAsync(Model);
private async Task UpdatePosition(double x, double y)
{
await JSRuntime.InvokeVoidAsync("SetNodePosition", circleRef, textRef, x, y);
if (IsError) await JSRuntime.InvokeVoidAsync("SetNodePosition", circleErrorRef, textRef, x, y);
}
private async void ActivedChanged(bool state) => await JSRuntime.InvokeVoidAsync(state ? "AddSelected" : "RemoveSelected", circleRef);
private async void ErrorChanged(bool state)
{
IsError = state;
await JSRuntime.InvokeVoidAsync("ElementSetAttribute", circleErrorRef, "visibility", state ? "visible" : "hidden");
if (IsError) await JSRuntime.InvokeVoidAsync("SetNodePosition", circleErrorRef, textRef, Model.X, Model.Y);
}
public void Dispose()
{
if (Model != null)
{
Model.PositionChanged -= Model_PositionChanged;
Model.ActivedChanged -= ActivedChanged;
Model.ErrorChanged -= ErrorChanged;
}
if (DotNetObj != null) DotNetObj.Dispose();
GC.SuppressFinalize(this);
}
}

View File

@@ -0,0 +1,41 @@
circle {
cursor: default;
fill: #FFBD33;
stroke: #FF5733;
stroke-width: 0;
r: var(--node-r);
}
circle.setting:hover {
stroke-width: 0.02px;
cursor: pointer;
}
circle.setting:active {
stroke-width: 0.02px;
stroke: green;
}
circle.active {
stroke-width: 0.02px;
stroke: green;
}
circle:hover + text.setting {
transition-delay: 0.1s;
font-weight: bold;
}
circle + text {
transition-delay: 0.3s;
font-size: 0.01em;
font-weight: normal;
}
text {
dominant-baseline: middle;
text-anchor: middle;
fill: red;
transform: scale(1, -1);
user-select: none;
}

View File

@@ -0,0 +1,10 @@
<defs>
<marker id="originvector" markerWidth="2.4" markerHeight="2.4" refX="0.4" refY="0.4">
<line x1="0" y1="0.4" x2="2" y2="0.4" stroke="red" stroke-width="0.15" />
<path d="M 2 0.6 L 2.4 0.4 L 2 0.2 Z" fill="red" stroke-width="0" />
<line x1="0.4" y1="0" x2="0.4" y2="2" stroke="blue" stroke-width="0.15" />
<path d="M 0.6 2 L 0.4 2.4 L 0.2 2 Z" fill="blue" stroke-width="0" />
</marker>
</defs>
<line class="origin" marker-end="url(#originvector)" />

View File

@@ -0,0 +1,4 @@
line.origin {
stroke-width: var(--origin-vector-stroke-width);
fill: none;
}

View File

@@ -0,0 +1,156 @@
@implements IDisposable
@inject IHttpClientFactory HttpClientFactory
@inject ISnackbar Snackbar
@foreach (var zone in Models)
{
<Zone Model="@zone" IsSetting="@IsSetting" DoubleClick="ZoneDoubleClick" IsShow="IsShow" />
}
<MudDialog @bind-Visible="@UpdateZoneVisiable">
<TitleContent>
<MudText Typo="Typo.h6">
Update zone @UpdateModel.Id
</MudText>
</TitleContent>
<DialogContent>
<MudSelect Class="mt-2" @bind-Value="UpdateModel.Type" Label="Type" Variant="Variant.Outlined" AnchorOrigin="Origin.BottomLeft" Margin="Margin.Dense" Dense ReadOnly=@(MapIsActive)>
<MudSelectItem Value="@(ZoneType.Operating)" />
<MudSelectItem Value="@(ZoneType.OperatingHazard)" />
<MudSelectItem Value="@(ZoneType.Restricted)" />
<MudSelectItem Value="@(ZoneType.LoadTransfer)" />
<MudSelectItem Value="@(ZoneType.Confined)" />
<MudSelectItem Value="@(ZoneType.Forbidden)" />
</MudSelect>
<MudTextField Class="mt-2" @bind-Value="UpdateModel.Name" Label="Name" ShrinkLabel Variant="Variant.Outlined" Margin="Margin.Dense" ReadOnly=@(MapIsActive) />
<div class="d-flex flex-row mt-5">
<div class="d-flex flex-column me-2 w-50">
<div class="mb-4">
<MudNumericField Class="mb-3" @bind-Value="UpdateModel.X1" Label="X1" ShrinkLabel Variant="Variant.Outlined" Margin="Margin.Dense" ReadOnly=@(MapIsActive) />
<MudNumericField @bind-Value="UpdateModel.Y1" Label="Y1" ShrinkLabel Variant="Variant.Outlined" Margin="Margin.Dense" ReadOnly=@(MapIsActive) />
</div>
<div>
<MudNumericField Class="mb-3" @bind-Value="UpdateModel.X2" Label="X2" ShrinkLabel Variant="Variant.Outlined" Margin="Margin.Dense" ReadOnly=@(MapIsActive) />
<MudNumericField @bind-Value="UpdateModel.Y2" Label="Y2" ShrinkLabel Variant="Variant.Outlined" Margin="Margin.Dense" ReadOnly=@(MapIsActive) />
</div>
</div>
<div class="d-flex flex-column ms-2 w-50">
<div class="mb-4">
<MudNumericField Class="mb-3" @bind-Value="UpdateModel.X3" Label="X3" ShrinkLabel Variant="Variant.Outlined" Margin="Margin.Dense" ReadOnly=@(MapIsActive) />
<MudNumericField @bind-Value="UpdateModel.Y3" Label="Y3" ShrinkLabel Variant="Variant.Outlined" Margin="Margin.Dense" ReadOnly=@(MapIsActive) />
</div>
<div>
<MudNumericField Class="mb-3" @bind-Value="UpdateModel.X4" Label="X4" ShrinkLabel Variant="Variant.Outlined" Margin="Margin.Dense" ReadOnly=@(MapIsActive) />
<MudNumericField @bind-Value="UpdateModel.Y4" Label="Y4" ShrinkLabel Variant="Variant.Outlined" Margin="Margin.Dense" ReadOnly=@(MapIsActive) />
</div>
</div>
</div>
</DialogContent>
<DialogActions>
<MudButton OnClick="CancelUpdateZone" Class="px-10" Variant="Variant.Filled">Cancel</MudButton>
<MudButton OnClick="UpdateZone" Variant="Variant.Filled" Color="Color.Primary" Class="px-10" Disabled=@(MapIsActive)>Update</MudButton>
</DialogActions>
</MudDialog>
@code {
[Parameter, EditorRequired]
public MapZoneModel Models { get; set; } = null!;
[Parameter]
public bool IsShow { get; set; }
[Parameter]
public bool IsSetting { get; set; }
[CascadingParameter]
protected bool MapIsActive { get; set; }
[Parameter]
public EditorState EditorState { get; set; }
[Parameter]
public EventCallback<(ZoneModel, bool)> ActivedZoneChanged { get; set; }
private ZoneUpdateModel UpdateModel = new();
private bool UpdateZoneVisiable = false;
private HttpClient Http = default!;
protected override async Task OnAfterRenderAsync(bool firstRender)
{
await base.OnAfterRenderAsync(firstRender);
if (!firstRender) return;
Http = HttpClientFactory.CreateClient("MapManagerAPI");
Models.Changed += StateHasChanged;
Models.ActivedZoneChanged += OnActivedZoneChanged;
}
private void OnActivedZoneChanged(ZoneModel model, bool state)
{
_ = ActivedZoneChanged.InvokeAsync((model, state));
}
private void ZoneDoubleClick(ZoneModel model)
{
if (model == null || EditorState != EditorState.SettingZone) return;
UpdateModel.Id = model.Id;
UpdateModel.Type = model.Type;
UpdateModel.Name = model.Name;
UpdateModel.X1 = model.X1;
UpdateModel.Y1 = model.Y1;
UpdateModel.X2 = model.X2;
UpdateModel.Y2 = model.Y2;
UpdateModel.X3 = model.X3;
UpdateModel.Y3 = model.Y3;
UpdateModel.X4 = model.X4;
UpdateModel.Y4 = model.Y4;
UpdateZoneVisiable = true;
StateHasChanged();
}
private void CancelUpdateZone()
{
UpdateZoneVisiable = false;
StateHasChanged();
}
private async Task UpdateZone()
{
var selectedModel = Models.FirstOrDefault(e => e.Id == UpdateModel.Id);
if (selectedModel == null)
{
UpdateZoneVisiable = false;
StateHasChanged();
return;
}
var result = await (await Http.PutAsJsonAsync($"api/Zones", UpdateModel)).Content.ReadFromJsonAsync<MessageResult>();
if (result is null)
{
Snackbar.Add("Lỗi giao tiếp với hệ thống", Severity.Error);
return;
}
else if (!result.IsSuccess)
{
Snackbar.Add(result.Message, Severity.Error);
return;
}
selectedModel.UpdateData(UpdateModel);
UpdateZoneVisiable = false;
Snackbar.Add("Cập nhật thành công", Severity.Success);
StateHasChanged();
}
public void Dispose()
{
Models.Changed -= StateHasChanged;
Models.ActivedZoneChanged -= OnActivedZoneChanged;
GC.SuppressFinalize(this);
}
}

View File

@@ -0,0 +1,95 @@
@inject IJSRuntime JSRuntime
@implements IDisposable
<polygon @ref="Ref" class="@(IsSetting ? "setting" : "")" fill="@Model.Fill" @ondblclick="OnDoubleClick" style="visibility: @(IsShow ? "visible" : "hidden")" />
@code {
[Parameter, EditorRequired]
public ZoneModel Model { get; set; } = null!;
[Parameter]
public EventCallback<ZoneModel> DoubleClick { get; set; }
[Parameter]
public bool IsSetting { get; set; }
[Parameter]
public bool IsShow { get; set; }
[CascadingParameter]
protected bool MapIsActive { get; set; }
private ElementReference Ref;
private DotNetObjectReference<Zone> DotNetObj = null!;
protected override async Task OnAfterRenderAsync(bool firstRender)
{
await base.OnAfterRenderAsync(firstRender);
if (!firstRender) return;
DotNetObj = DotNetObjectReference.Create(this);
await JSRuntime.InvokeVoidAsync("AddEventListener", DotNetObj, Ref, "click", nameof(Click), false);
await UpdateData();
}
public override async Task SetParametersAsync(ParameterView parameters)
{
bool UpdateZone = false;
if (parameters.TryGetValue(nameof(Model), out ZoneModel? model))
{
if (((Model?.Id ?? Guid.Empty) != (model?.Id ?? Guid.Empty)))
{
if (Model != null)
{
Model.ControlNodePosittionChanged -= UpdateData;
Model.TypeChanged -= StateHasChanged;
Model.ActiveChanged -= ActiveChanged;
}
if (model != null)
{
model.ControlNodePosittionChanged += UpdateData;
model.TypeChanged += StateHasChanged;
model.ActiveChanged += ActiveChanged;
UpdateZone = true;
}
}
}
await base.SetParametersAsync(parameters);
if (UpdateZone) await UpdateData();
}
private async Task OnDoubleClick()
{
await DoubleClick.InvokeAsync(Model);
}
[JSInvokable]
public void Click()
{
Model.Active();
}
private async void ActiveChanged(ZoneModel zone, bool state) => await JSRuntime.InvokeVoidAsync(state ? "AddSelected" : "RemoveSelected", Ref);
private async Task UpdateData()
{
string data = $"{Model.X1},{Model.Y1} {Model.X2},{Model.Y2} {Model.X3},{Model.Y3} {Model.X4},{Model.Y4}";
await JSRuntime.InvokeVoidAsync("ElementSetAttribute", Ref, "points", data);
}
public void Dispose()
{
if (Model != null)
{
Model.ControlNodePosittionChanged -= UpdateData;
Model.ActiveChanged -= ActiveChanged;
Model.TypeChanged -= StateHasChanged;
}
if (DotNetObj != null) DotNetObj.Dispose();
GC.SuppressFinalize(this);
}
}

View File

@@ -0,0 +1,29 @@
polygon {
stroke: none;
fill-opacity: 0.5;
stroke-linejoin: round;
stroke-linecap: butt;
position: relative;
z-index: 1;
}
polygon.setting:hover {
stroke-width: 0.02px;
stroke: red;
cursor: pointer;
}
polygon.setting:active {
fill-opacity: 0.7;
stroke-width: 0.02px;
stroke: green;
cursor: pointer;
}
polygon.setting.active {
fill-opacity: 0.7;
stroke-width: 0.02px;
stroke: green;
cursor: pointer;
z-index: 2;
}

View File

@@ -0,0 +1,137 @@
@inject IJSRuntime JSRuntime
@implements IDisposable
<g visibility="@Visibility">
<circle @ref="Node1Ref" cx="@X1" cy="@Y1" />
<text x="@X1" y="@(-Y1 - 0.15)">1</text>
<circle @ref="Node2Ref" cx="@X2" cy="@Y2" />
<text x="@X2" y="@(-Y2 - 0.15)">2</text>
<circle @ref="Node3Ref" cx="@X3" cy="@Y3" />
<text x="@X3" y="@(-Y3 - 0.15)">3</text>
<circle @ref="Node4Ref" cx="@X4" cy="@Y4" />
<text x="@X4" y="@(-Y4 - 0.15)">4</text>
</g>
@code {
private ElementReference Node1Ref;
private ElementReference Node2Ref;
private ElementReference Node3Ref;
private ElementReference Node4Ref;
private DotNetObjectReference<ZoneControlPoint> DotNetObj = null!;
private double X1;
private double Y1;
private double X2;
private double Y2;
private double X3;
private double Y3;
private double X4;
private double Y4;
private ZoneModel? Model;
private string Visibility = "hidden";
protected override async Task OnAfterRenderAsync(bool firstRender)
{
await base.OnAfterRenderAsync(firstRender);
if (!firstRender) return;
DotNetObj = DotNetObjectReference.Create(this);
await JSRuntime.InvokeVoidAsync("AddMouseDownEventListener", DotNetObj, Node1Ref, nameof(OnMouseDownNode1), false);
await JSRuntime.InvokeVoidAsync("AddMouseDownEventListener", DotNetObj, Node2Ref, nameof(OnMouseDownNode2), false);
await JSRuntime.InvokeVoidAsync("AddMouseDownEventListener", DotNetObj, Node3Ref, nameof(OnMouseDownNode3), false);
await JSRuntime.InvokeVoidAsync("AddMouseDownEventListener", DotNetObj, Node4Ref, nameof(OnMouseDownNode4), false);
}
public void SetControl(ZoneModel? model)
{
if (Model != null)
{
Model.ControlNodePosittionChanged -= CaculateZoneAsync;
}
Model = model;
if (Model != null)
{
Visibility = "visible";
CaculateZone();
Model.ControlNodePosittionChanged += CaculateZoneAsync;
Visibility = "visible";
}
else
{
Visibility = "hidden";
}
StateHasChanged();
}
private Task CaculateZoneAsync()
{
CaculateZone();
return Task.CompletedTask;
}
private void CaculateZone()
{
if (Model == null) return;
X1 = Model.X1;
Y1 = Model.Y1;
X2 = Model.X2;
Y2 = Model.Y2;
X3 = Model.X3;
Y3 = Model.Y3;
X4 = Model.X4;
Y4 = Model.Y4;
StateHasChanged();
}
[JSInvokable]
public void OnMouseDownNode1(int button, bool altKey, bool ctrlKey, bool shiftKey)
{
if (Model != null)
{
Model.ActiveNode = 1;
}
}
[JSInvokable]
public void OnMouseDownNode2(int button, bool altKey, bool ctrlKey, bool shiftKey)
{
if (Model != null)
{
Model.ActiveNode = 2;
}
}
[JSInvokable]
public void OnMouseDownNode3(int button, bool altKey, bool ctrlKey, bool shiftKey)
{
if (Model != null)
{
Model.ActiveNode = 3;
}
}
[JSInvokable]
public void OnMouseDownNode4(int button, bool altKey, bool ctrlKey, bool shiftKey)
{
if (Model != null)
{
Model.ActiveNode = 4;
}
}
public void Dispose()
{
if (Model != null)
{
Model.ControlNodePosittionChanged -= CaculateZoneAsync;
Model = null;
}
if (DotNetObj is not null) DotNetObj.Dispose();
GC.SuppressFinalize(this);
}
}

View File

@@ -0,0 +1,31 @@
circle {
cursor: default;
fill: #FFBD33;
stroke-width: 0;
r: var(--node-r);
}
circle:hover {
stroke-width: 0.03px;
cursor: pointer;
stroke: green;
}
circle:active {
stroke-width: 0.03px;
stroke: #FF5733;
}
circle + text {
transition-delay: 0.1s;
font-size: 0.01em;
font-weight: normal;
}
text {
dominant-baseline: middle;
text-anchor: middle;
fill: red;
transform: scale(1, -1);
user-select: none;
}

View File

@@ -0,0 +1,92 @@
@inject IJSRuntime JSRuntime
<polygon @ref="Ref" visibility="hidden" />
<g @ref="PointRef" visibility="hidden">
<circle cx="@X1" cy="@Y1" />
<circle cx="@X2" cy="@Y2" />
<circle cx="@X3" cy="@Y3" />
<circle cx="@X4" cy="@Y4" />
<circle cx="@X5" cy="@Y5" />
</g>
@code {
private ElementReference Ref;
private ElementReference PointRef;
public double X1 { get; private set; }
public double Y1 { get; private set; }
public double X2 { get; private set; }
public double Y2 { get; private set; }
public double X3 { get; private set; }
public double Y3 { get; private set; }
public double X4 { get; private set; }
public double Y4 { get; private set; }
public double X5 { get; private set; }
public double Y5 { get; private set; }
public int Step { get; private set; }
public async Task CreateAsync(double x, double y)
{
if (Step == 0)
{
await Visible();
Step = 1;
X1 = x;
Y1 = y;
}
else if (Step == 1) Step = 2;
else if (Step == 2) Step = 3;
else if (Step == 3)
{
X4 = x;
Y4 = y;
Step = 4;
await CalculatorZone();
}
}
public async Task Update(double x, double y)
{
if (Step == 1)
{
X2 = x;
Y2 = y;
}
else if (Step == 2)
{
X3 = x;
Y3 = y;
}
else if (Step == 3)
{
X4 = x;
Y4 = y;
}
await CalculatorZone();
StateHasChanged();
}
private async Task CalculatorZone()
{
var points = $"{X1},{Y1} {X2},{Y2}";
if (Step == 2) points += $" {X3},{Y3}";
if (Step == 3) points += $" {X3},{Y3} {X4},{Y4}";
await JSRuntime.InvokeVoidAsync("ElementSetAttribute", Ref, "points", points);
}
public async Task Visible()
{
await JSRuntime.InvokeVoidAsync("ElementSetAttribute", Ref, "visibility", "visible");
await JSRuntime.InvokeVoidAsync("ElementSetAttribute", PointRef, "visibility", "visible");
}
public async Task Hidden()
{
Step = 0;
X1 = X2 = X3 = X4 = Y1 = Y2 = Y3 = Y4 = 0;
await JSRuntime.InvokeVoidAsync("ElementSetAttribute", Ref, "visibility", "hidden");
await JSRuntime.InvokeVoidAsync("ElementSetAttribute", PointRef, "visibility", "hidden");
}
}

View File

@@ -0,0 +1,12 @@
polygon {
fill: #c2c2a3;
stroke: none;
fill-opacity: 0.5;
}
circle {
fill: #FFBD33;
stroke: #FF5733;
stroke-width: 0;
r: var(--node-r);
}

View File

@@ -0,0 +1,238 @@
@inject IDialogService Dialog
@inject ISnackbar Snackbar
@inject IHttpClientFactory HttpClientFactory
<div class="d-flex w-100 h-100 flex-column px-2">
<div class="d-flex flex-row justify-content-between w-100 mb-2">
<MudText Typo="Typo.h5" Class="d-flex align-items-center">Default Properties</MudText>
<div class="d-flex flex-row">
<MudTooltip RootClass="d-flex align-items-center" Text="Create" Placement="Placement.Bottom" Color="Color.Primary" Arrow="true">
<MudIconButton Icon="@Icons.Material.Filled.Add" Variant="Variant.Text" Color="Color.Primary" Size="Size.Small" OnClick="OpenElementProperty" Disabled="@(ElementModel is null || ElementProperties.Count >= 10)"></MudIconButton>
</MudTooltip>
<MudTooltip RootClass="d-flex align-items-center" Text="Edit" Placement="Placement.Bottom" Color="Color.Info" Arrow="true">
<MudIconButton Icon="@Icons.Material.Filled.Edit" Size="Size.Small" Color="Color.Info" Disabled="@(ElementModel is null || IsEdit || ElementProperties.Count == 0)" OnClick="(() => IsEdit = true)" />
</MudTooltip>
<MudTooltip RootClass="d-flex align-items-center" Text="Save" Placement="Placement.Bottom" Color="Color.Info" Arrow="true">
<MudIconButton Icon="@Icons.Material.Filled.Save" Variant="Variant.Text" Color="Color.Info" Size="Size.Small" Disabled="@(ElementModel is null || !IsEdit)" OnClick="Save" />
</MudTooltip>
</div>
</div>
<div class="d-flex w-100 flex-grow-1 overflow-x-hidden overflow-y-auto flex-column ps-2">
@foreach (var property in ElementProperties)
{
<div class="d-flex flex-row w-100 justify-content-between mb-1">
@if (property.Type == typeof(int).ToString())
{
if (int.TryParse(property.DefaultValue, out int value))
{
<MudNumericField T="int" Margin="Margin.Dense" Label="@property.Name" Value="value" Variant="Variant.Outlined" ReadOnly="@(!IsEdit)"
ValueChanged="((data) => DefaultIntValueChanged(property.Id, data))" />
}
}
else if (property.Type == typeof(double).ToString())
{
if (double.TryParse(property.DefaultValue, out double value))
{
<MudNumericField T="double" Margin="Margin.Dense" Label="@property.Name" Value="value" Variant="Variant.Outlined" Step="0.1" ReadOnly="@(!IsEdit)"
ValueChanged="((data) => DefaultDoubleValueChanged(property.Id, data))" />
}
}
else if (property.Type == typeof(bool).ToString())
{
if (bool.TryParse(property.DefaultValue, out bool value))
{
<MudCheckBox Class="m-0" Size="Size.Small" T="bool" LabelPlacement="Placement.Start" Label="@property.Name" Value="value" Color="Color.Success"
UncheckedColor="Color.Default" ReadOnly="@(!IsEdit)" ValueChanged="((data) => DefaultBooleanValueChanged(property.Id, data))" />
}
}
else if (property.Type == typeof(string).ToString())
{
<MudTextField T="string" Label="@property.Name" Value="@property.DefaultValue" Variant="Variant.Outlined" Margin="Margin.Dense" ReadOnly="@(!IsEdit)"
ValueChanged="((data) => property.DefaultValue = data)" />
}
<MudTooltip RootClass="d-flex align-items-center" Text="Delete" Placement="Placement.Bottom" Color="Color.Secondary" Arrow="true">
<MudIconButton Class="ms-4" Icon="@Icons.Material.Filled.Cancel" Size="Size.Small" Color="Color.Secondary"
OnClick="(async() => await DeleteProperty(property))" Disabled="@(!IsEdit)" />
</MudTooltip>
</div>
}
</div>
</div>
<MudDialog @bind-Visible="@CreatePropertyIsVisible" DefaultFocus="DefaultFocus.FirstChild">
<TitleContent>
<MudText Typo="Typo.h5">Create Element Property</MudText>
</TitleContent>
<DialogContent>
<div class="d-flex flex-column" style="max-height: 700px; overflow-y: auto">
<MudForm @ref="Form" @bind-IsValid="@createPropertyValidate">
<MudTextField Class="mt-2" ShrinkLabel
@bind-Value="ElementPropertyCreateModel.Name" T="string"
Label="Name" Required="true" RequiredError="Name is required!"
Counter="16" Variant="Variant.Outlined"
Validation="@(new Func<string, IEnumerable<string>>(MapEditorHelper.NameValidation))" />
<MudSelect Class="mb-4" T="string" Variant="Variant.Outlined" Label="Type" Required="true" RequiredError="Type is required!"
@bind-Value="@ElementPropertyCreateModel.Type" @bind-Value:after="Form.Validate">
@foreach (var type in ElementProperty.PropertyTypes)
{
<MudSelectItem Value="@type.ToString()">@ElementProperty.GetPropertyTypeName(type)</MudSelectItem>
}
</MudSelect>
<MudTextField T="string" @bind-Value="@ElementPropertyCreateModel.DefaultValue" Variant="Variant.Outlined" Label="Default Value" ShrinkLabel
Validation="@(new Func<string, IEnumerable<string>>(DefaultValidation))" />
<MudCheckBox Size="Size.Small" T="bool" LabelPlacement="Placement.Start" Label="Monitor ReadOnly" @bind-value="ElementPropertyCreateModel.ReadOnly" Color="Color.Success"
UncheckedColor="Color.Default" />
</MudForm>
</div>
</DialogContent>
<DialogActions>
<MudButton Color="Color.Default" Variant="Variant.Filled" OnClick="(() => CreatePropertyIsVisible = false)">Cancel</MudButton>
<MudButton Color="Color.Primary" Variant="Variant.Filled" Disabled="@(!createPropertyValidate)" OnClick="CreateProperty">Create</MudButton>
</DialogActions>
</MudDialog>
@code {
private bool CreatePropertyIsVisible;
private ElementProperty ElementPropertyCreateModel = new();
private ElementModelDto? ElementModel = null;
private List<ElementProperty> ElementProperties = [];
private bool createPropertyValidate;
private MudForm Form = default!;
private bool IsEdit = false;
private HttpClient Http = default!;
protected override async Task OnAfterRenderAsync(bool firstRender)
{
await base.OnAfterRenderAsync(firstRender);
if (!firstRender) return;
Http = HttpClientFactory.CreateClient("MapManagerAPI");
}
private void OpenElementProperty()
{
ElementPropertyCreateModel.Name = "";
ElementPropertyCreateModel.Type = ElementProperty.PropertyTypes[0].ToString();
ElementPropertyCreateModel.DefaultValue = "";
ElementPropertyCreateModel.ReadOnly = false;
CreatePropertyIsVisible = true;
StateHasChanged();
}
public void SetElementModel(ElementModelDto? model)
{
ElementModel = model;
ElementProperties.Clear();
if (model is not null && !string.IsNullOrEmpty(model.Content))
{
var properties = JsonSerializer.Deserialize<List<ElementProperty>>(model.Content, JsonOptionExtends.Read);
if (properties is not null) ElementProperties = [.. properties];
}
StateHasChanged();
}
private async Task CreateProperty()
{
if (string.IsNullOrEmpty(ElementPropertyCreateModel.Name))
{
Snackbar.Add("Name không được để trống.", Severity.Warning);
return;
}
if (ElementProperties.Any(p => p.Name == ElementPropertyCreateModel.Name))
{
Snackbar.Add($"Tên Property {ElementPropertyCreateModel.Name} đã tồn tại, vui lòng chon tên khác!", Severity.Warning);
return;
}
ElementProperties.Add(new ElementProperty()
{
Id = Guid.NewGuid(),
Name = ElementPropertyCreateModel.Name,
Type = ElementPropertyCreateModel.Type,
DefaultValue = ElementPropertyCreateModel.DefaultValue,
ReadOnly = ElementPropertyCreateModel.ReadOnly,
});
await Save();
CreatePropertyIsVisible = false;
StateHasChanged();
}
public IEnumerable<string> DefaultValidation(string value)
{
if (ElementPropertyCreateModel.Type == typeof(int).ToString())
{
if (!int.TryParse(value, out _)) yield return "Giá trị mặc định không hợp lệ";
}
else if (ElementPropertyCreateModel.Type == typeof(double).ToString())
{
if (!double.TryParse(value, out _)) yield return "Giá trị mặc định không hợp lệ";
}
else if (ElementPropertyCreateModel.Type == typeof(bool).ToString())
{
if (!bool.TryParse(value, out _)) yield return "Giá trị mặc định không hợp lệ";
}
}
private void DefaultIntValueChanged(Guid id, int value)
{
var property = ElementProperties.FirstOrDefault(p => p.Id == id);
if (property is null) return;
property.DefaultValue = value.ToString();
}
private void DefaultDoubleValueChanged(Guid id, double value)
{
var property = ElementProperties.FirstOrDefault(p => p.Id == id);
if (property is null) return;
property.DefaultValue = value.ToString();
}
private void DefaultBooleanValueChanged(Guid id, bool value)
{
var property = ElementProperties.FirstOrDefault(p => p.Id == id);
if (property is null) return;
property.DefaultValue = value.ToString();
}
private async Task DeleteProperty(ElementProperty property)
{
var parameters = new DialogParameters<ConfirmDialog>
{
{ x => x.Content, $"Bạn có chắc chắn muốn xóa property {property.Name} đi không?" },
{ x => x.ConfirmText, "Delete" },
{ x => x.Color, Color.Secondary }
};
var ConfirmDelete = await Dialog.ShowAsync<ConfirmDialog>("Xoá Property", parameters);
var result = await ConfirmDelete.Result;
if (result is not null && result.Data is not null && bool.TryParse(result.Data.ToString(), out bool data) && data)
{
var prope = ElementProperties.Remove(property);
}
StateHasChanged();
}
private async Task Save()
{
if (ElementModel is null) return;
var result = await (await Http.PutAsJsonAsync($"api/ElementModels", new ElementModelUpdateModel()
{
Id = ElementModel.Id,
Name = ElementModel.Name,
MapId = ElementModel.MapId,
Width = ElementModel.Width,
Height = ElementModel.Height,
Content = JsonSerializer.Serialize(ElementProperties, JsonOptionExtends.Write),
})).Content.ReadFromJsonAsync<MessageResult<ElementModelDto>>();
if (result == null) Snackbar.Add("Lỗi giao tiếp với hệ thống", Severity.Error);
else if (!result.IsSuccess) Snackbar.Add(result.Message, Severity.Error);
else Snackbar.Add("Cập nhật thành công", Severity.Success);
IsEdit = false;
StateHasChanged();
}
}

View File

@@ -0,0 +1,187 @@
@using System.Net.Http.Headers
@inject IJSRuntime JSRuntime
@inject ISnackbar Snackbar
@inject IHttpClientFactory HttpClientFactory
<div class="d-flex w-100 h-100 flex-row justify-content-around">
<div class="d-flex flex-column w-50">
<div class="d-flex flex-row m-2 align-items-center justify-content-between">
<MudText Typo="Typo.h6">Open</MudText>
<div class="d-flex flex-row">
<MudIconButton Class="me-3" Size="Size.Small" Variant="Variant.Filled" Icon="@Icons.Material.Filled.Download" Color="Color.Primary" Disabled="@Disable" OnClick="@(async () => await DownloadImage(true))" />
<MudIconButton Class="me-3" Size="Size.Small" Variant="Variant.Filled" Icon="@Icons.Material.Filled.Upload" Color="Color.Primary" Disabled="@Disable" OnClick="(() => OpenUpdateElementImage(true))" />
</div>
</div>
<div class="element-item">
<img src="@imageOpenSrc" alt="element model image" onerror="this.onerror=null; this.src='/images/Image-not-found.png';" />
</div>
</div>
<div class="d-flex flex-column w-50">
<div class="d-flex flex-row m-2 align-items-center justify-content-between">
<MudText Typo="Typo.h6">Close</MudText>
<div class="d-flex flex-row">
<MudIconButton Class="me-3" Size="Size.Small" Variant="Variant.Filled" Icon="@Icons.Material.Filled.Download" Color="Color.Primary" Disabled="@Disable" OnClick="@(async () => await DownloadImage(true))" />
<MudIconButton Class="me-3" Size="Size.Small" Variant="Variant.Filled" Icon="@Icons.Material.Filled.Upload" Color="Color.Primary" Disabled="@Disable" OnClick="(() => OpenUpdateElementImage(false))" />
</div>
</div>
<div class="element-item">
<img src="@imageCloseSrc" alt="element model image" onerror="this.onerror=null; this.src='/images/Image-not-found.png';" />
</div>
</div>
</div>
<MudDialog @bind-Visible="@IsUpdateElementImageVisable">
<TitleContent>
<MudText Typo="Typo.h6">
Update ElementModel's Image
</MudText>
</TitleContent>
<DialogContent>
<div class="d-flex flex-column w-100 h-100 px-3">
<div class="d-flex flex-row mb-2">
<InputFile id="fileElementImageCreate" OnChange="ElementImageChanged" accept=".png" hidden />
<MudButton HtmlTag="label"
Variant="Variant.Filled"
Color="Color.Primary"
StartIcon="@Icons.Material.Filled.CloudUpload"
for="fileElementImageCreate">
Element Model Image
</MudButton>
</div>
<div class="d-flex mb-2">
<div class="element-update-item">
<img alt="Element Model Image" src="@ImagePreview" style="image-rendering: pixelated;" />
</div>
</div>
</div>
</DialogContent>
<DialogActions>
<MudButton OnClick="@(() => IsUpdateElementImageVisable = false)" Variant="Variant.Filled">Cancel</MudButton>
<MudButton Color="Color.Primary" OnClick="UpdateElementModelImage" Variant="Variant.Filled">Update</MudButton>
</DialogActions>
</MudDialog>
@code {
private bool Disable = true;
private string imageOpenSrc = "/images/Image-not-found.png";
private string imageCloseSrc = "/images/Image-not-found.png";
private string ElementModelName = "Element Model preview";
private Guid ElementModelId = Guid.Empty;
private string ImagePreview = "";
private IBrowserFile? ElementImageChange;
private bool IsUpdateElementImageVisable;
private bool IsOpen;
private HttpClient Http = default!;
protected override async Task OnAfterRenderAsync(bool firstRender)
{
await base.OnAfterRenderAsync(firstRender);
if (!firstRender) return;
Http = HttpClientFactory.CreateClient("MapManagerAPI");
}
public void SetElementModel(ElementModelDto? model)
{
if (model is null)
{
Disable = true;
ElementModelName = "Element Model preview";
imageOpenSrc = "/images/Image-not-found.png";
imageCloseSrc = "/images/Image-not-found.png";
ElementModelId = Guid.Empty;
}
else
{
imageOpenSrc = $"{Http.BaseAddress}api/images/elementmodel/{model.Id}?IsOpen=true&t={DateTime.Now}";
imageCloseSrc = $"{Http.BaseAddress}api/images/elementmodel/{model.Id}?IsOpen=false&t={DateTime.Now}";
ElementModelName = model.Name;
ElementModelId = model.Id;
Disable = false;
}
StateHasChanged();
}
private async Task DownloadImage(bool isOpen)
{
try
{
var response = await Http.GetAsync(isOpen ? imageOpenSrc : imageCloseSrc);
if (response.IsSuccessStatusCode)
{
var fileBytes = await response.Content.ReadAsByteArrayAsync();
var base64Data = Convert.ToBase64String(fileBytes);
var mimeType = "image/png";
var url = $"data:{mimeType};base64,{base64Data}";
await JSRuntime.InvokeVoidAsync("DownloadImage", base64Data, $"{ElementModelName}-{(isOpen ? "O" : "C")}.png");
}
else Snackbar.Add("Không thể tải ảnh robot", Severity.Warning);
}
catch (Exception ex)
{
Snackbar.Add($"Không thể tải ảnh robot: {ex.Message}", Severity.Warning);
}
}
private void OpenUpdateElementImage(bool isOpen)
{
IsOpen = isOpen;
ImagePreview = isOpen ? imageOpenSrc : imageCloseSrc;
ElementImageChange = null;
IsUpdateElementImageVisable = true;
StateHasChanged();
}
public async Task<string> UploadMedia(IBrowserFile file)
{
var path = Path.Combine(Path.GetTempPath(), ElementModelName);
await using var fs = new FileStream(path, FileMode.Create);
await file.OpenReadStream(file.Size).CopyToAsync(fs);
var bytes = new byte[file.Size];
fs.Position = 0;
await fs.ReadAsync(bytes);
fs.Close();
File.Delete(path);
return $"data:{file.ContentType};base64,{Convert.ToBase64String(bytes)}";
}
private async Task ElementImageChanged(InputFileChangeEventArgs e)
{
ElementImageChange = e.File;
if (ElementImageChange is not null)
{
ImagePreview = await UploadMedia(ElementImageChange);
StateHasChanged();
}
}
private async Task UpdateElementModelImage()
{
if (ElementImageChange is null) return;
using var content = new MultipartFormDataContent();
var fileContent = new StreamContent(ElementImageChange.OpenReadStream());
fileContent.Headers.ContentType = new MediaTypeHeaderValue(ElementImageChange.ContentType);
content.Add(fileContent, "image", ElementImageChange.Name);
var result = await (await Http.PutAsync($"api/ElementModels/{(IsOpen ? "openimage" : "closeimage")}/{ElementModelId}", content)).Content.ReadFromJsonAsync<MessageResult>();
if (result is null) Snackbar.Add("Lỗi giao tiếp với hệ thống", Severity.Error);
else if (!result.IsSuccess) Snackbar.Add(result.Message ?? "Lỗi chưa xác định.", Severity.Error);
else
{
if (IsOpen) imageOpenSrc = ImagePreview;
else imageCloseSrc = ImagePreview;
IsUpdateElementImageVisable = false;
Snackbar.Add("Thay đổi thành công", Severity.Success);
}
StateHasChanged();
}
}

View File

@@ -0,0 +1,31 @@
.element-item {
display: flex;
justify-content: center;
width: 100%;
height: fit-content;
}
.element-item img {
justify-content: center;
width: 95%;
height: 200px;
object-fit: contain;
border-radius: 10px;
image-rendering: pixelated;
}
.element-update-item {
display: flex;
justify-content: center;
width: 100%;
height: fit-content;
}
.element-update-item img {
width: 400px;
height: 300px;
object-fit: contain;
border-radius: 10px;
image-rendering: pixelated;
}

View File

@@ -0,0 +1,341 @@
@using System.Net.Http.Headers
@using Microsoft.AspNetCore.Components.WebAssembly.Authentication
@inject ISnackbar Snackbar
@inject IHttpClientFactory HttpClientFactory
@inject IDialogService Dialog
<div class="d-flex w-100 h-100 flex-column">
<div class="d-flex flex-row justify-content-between w-100 mb-3">
<MudText Typo="Typo.h5" Class="d-flex align-items-center">Element Models</MudText>
<div class="d-flex flex-row pe-2">
<MudTooltip RootClass="d-flex align-items-center" Text="Create" Placement="Placement.Bottom" Color="Color.Primary" Arrow="true">
<MudIconButton Icon="@Icons.Material.Filled.Add" Variant="Variant.Text" Color="Color.Primary" Size="Size.Small" OnClick="OpenCreateModel"></MudIconButton>
</MudTooltip>
<MudTooltip RootClass="d-flex align-items-center" Text="Edit" Placement="Placement.Bottom" Color="Color.Info" Arrow="true">
<MudIconButton Icon="@Icons.Material.Filled.Edit" Size="Size.Small" Color="Color.Info" OnClick="OpenUpdateElementModel" />
</MudTooltip>
<MudTooltip RootClass="d-flex align-items-center" Text="Delete" Placement="Placement.Bottom" Color="Color.Secondary" Arrow="true">
<MudIconButton Icon="@Icons.Material.Filled.Delete" Size="Size.Small" Color="Color.Secondary" OnClick="DeleteElementModel" />
</MudTooltip>
</div>
</div>
<div class="d-flex w-100 flex-grow-1 overflow-x-hidden overflow-y-auto">
<MudTreeView Class="d-flex w-100 h-100 flex-column" T="ElementModelDto" Hover SelectedValueChanged="ModelSelectedChanged" SelectedValue="ElementModelSelected">
@foreach (var model in ElementModels)
{
<MudTreeViewItem Value="@model" CanExpand="false" Style="border-bottom: 0.5px solid rgba(217, 217, 217, 0.5); "
Text="@model.Name" EndText="@($"{model.Width}x{model.Height}")" EndTextTypo="Typo.caption" />
}
</MudTreeView>
</div>
</div>
<MudDialog @bind-Visible="@CreateModelIsVisible" DefaultFocus="DefaultFocus.FirstChild">
<TitleContent>
<MudText Typo="Typo.h5">Create Element Model</MudText>
</TitleContent>
<DialogContent>
<div class="d-flex flex-column" style="max-height: 700px; overflow-y: auto">
<MudTextField Class="my-2"
@bind-Value="ElementModelCreateModel.Name" T="string"
Label="Name" Required="true" RequiredError="Name is required!"
Counter="18" Variant="Variant.Outlined"
Validation="@(new Func<string, IEnumerable<string>>(MapEditorHelper.NameValidation))" />
<div class="d-flex flex-row">
<MudNumericField Class="me-2" @bind-Value="ElementModelCreateModel.Width" Label="Width" Step="0.1" Min="0" Variant="Variant.Outlined" />
<MudNumericField Class="ms-2" @bind-Value="ElementModelCreateModel.Height" Label="Height" Step="0.1" Min="0" Variant="Variant.Outlined" />
</div>
<div class="d-flex flex-row justify-content-around">
<div class="d-flex flex-column me-2">
<div class="d-flex flex-row align-items-center justify-content-center">
<InputFile id="fileElementModelImage1Create" OnChange="ElementModelCreateImage1Changed" accept=".png" hidden />
<MudText>Open</MudText>
<MudIconButton Variant="Variant.Text" Color="Color.Primary" Icon="@Icons.Material.Filled.CloudUpload" for="fileElementModelImage1Create" HtmlTag="label" />
</div>
<div class="d-flex">
<div class="model-create-item">
<img alt="Element Model Image Open" src="@ProjectionImageFilePreview1" style="image-rendering: pixelated;" />
</div>
</div>
</div>
<div class="d-flex flex-column">
<div class="d-flex flex-row align-items-center justify-content-center">
<InputFile id="fileElementModelImage2Create" OnChange="ElementModelCreateImage2Changed" accept=".png" hidden />
<MudText>Close</MudText>
<MudIconButton Variant="Variant.Text" Color="Color.Primary" Icon="@Icons.Material.Filled.CloudUpload" for="fileElementModelImage2Create" HtmlTag="label" />
</div>
<div class="d-flex">
<div class="model-create-item">
<img alt=" Element Model Image Close" src="@ProjectionImageFilePreview2" style="image-rendering: pixelated;" />
</div>
</div>
</div>
</div>
</div>
</DialogContent>
<DialogActions>
<MudButton Color="Color.Default" Variant="Variant.Filled" OnClick="(() => CreateModelIsVisible = false)">Cancel</MudButton>
<MudButton Color="Color.Primary" Variant="Variant.Filled" OnClick="CreateElementModel" Disabled="string.IsNullOrEmpty(ElementModelCreateModel.Name)">Create</MudButton>
</DialogActions>
</MudDialog>
<MudDialog @bind-Visible="@UpdateElementModelVisible" DefaultFocus="DefaultFocus.FirstChild">
<TitleContent>
<MudText Typo="Typo.h5">Update Element Model</MudText>
</TitleContent>
<DialogContent>
<div class="d-flex flex-column" style="max-height: 700px; overflow-y: auto">
<MudTextField Class="my-2"
@bind-Value="ElementModelUpdateModel.Name" T="string"
Label="Name" Required="true" RequiredError="Name is required!"
Counter="18" Variant="Variant.Outlined"
Validation="@(new Func<string, IEnumerable<string>>(MapEditorHelper.NameValidation))" />
<div class="d-flex flex-row">
<MudNumericField Class="me-2" @bind-Value="ElementModelUpdateModel.Width" Label="Width" Step="0.1" Variant="Variant.Outlined" />
<MudNumericField Class="ms-2" @bind-Value="ElementModelUpdateModel.Height" Label="Height" Step="0.1" Variant="Variant.Outlined" />
</div>
</div>
</DialogContent>
<DialogActions>
<MudButton Color="Color.Default" Variant="Variant.Filled" OnClick="(() => UpdateElementModelVisible = false)">Cancel</MudButton>
<MudButton Color="Color.Primary" Variant="Variant.Filled" OnClick="UpdateElementModel" Disabled="string.IsNullOrEmpty(ElementModelUpdateModel.Name)">Update</MudButton>
</DialogActions>
</MudDialog>
@code {
[Parameter]
public List<ElementModelDto> ElementModels { get; set; } = [];
[Parameter]
public MapInfoDto MapInfo { get; set; } = new();
[Parameter]
public EventCallback<ElementModelDto?> ElementModelSelectChanged { get; set; }
private string? txtSearch { get; set; }
private bool CreateModelIsVisible;
private ElementModelCreateModel ElementModelCreateModel = new();
private IBrowserFile? ElementModelCreateImage1 { get; set; }
private string? ProjectionImageFilePreview1 { get; set; }
private IBrowserFile? ElementModelCreateImage2 { get; set; }
private string? ProjectionImageFilePreview2 { get; set; }
private ElementModelDto? ElementModelSelected = null;
private bool UpdateElementModelVisible;
private ElementModelUpdateModel ElementModelUpdateModel = new();
private HttpClient Http = default!;
protected override async Task OnAfterRenderAsync(bool firstRender)
{
await base.OnAfterRenderAsync(firstRender);
if (!firstRender) return;
Http = HttpClientFactory.CreateClient("MapManagerAPI");
}
private async Task DeleteElementModel()
{
if (ElementModelSelected is null) return;
var parameters = new DialogParameters<ConfirmDialog>
{
{ x => x.Content, $"Tất cả các Element thuộc model này cũng sẽ bị xóa! Bạn có chắc chắn muốn xóa element model {ElementModelSelected.Name} đi không?" },
{ x => x.ConfirmText, "Delete" },
{ x => x.Color, Color.Secondary }
};
var ConfirmDelete = await Dialog.ShowAsync<ConfirmDialog>("Xoá Element Model", parameters);
var result = await ConfirmDelete.Result;
if (result is not null && result.Data is not null && bool.TryParse(result.Data.ToString(), out bool data) && data)
{
var response = await Http.DeleteFromJsonAsync<MessageResult>($"api/ElementModels/{ElementModelSelected.Id}");
if (response is null) Snackbar.Add("Lỗi giao tiếp với hệ thống", Severity.Error);
else if (!response.IsSuccess) Snackbar.Add(response.Message ?? "Lỗi chưa xác định.", Severity.Error);
else
{
var elementmodel = ElementModels.FirstOrDefault(m => m.Id == ElementModelSelected.Id);
if (elementmodel is not null)
{
ElementModels.Remove(elementmodel);
await ElementModelSelectChanged.InvokeAsync(null);
ElementModelSelected = null;
Snackbar.Add($"Xóa element model thành công.", Severity.Success);
}
else Snackbar.Add($"Element Model không tồn tại.", Severity.Warning);
}
StateHasChanged();
}
}
private void OpenCreateModel()
{
ElementModelCreateModel.Name = "";
ElementModelCreateModel.MapId = MapInfo.Id;
ProjectionImageFilePreview1 = "/images/Image-not-found.png";
ProjectionImageFilePreview2 = "/images/Image-not-found.png";
ElementModelCreateImage1 = null;
ElementModelCreateImage2 = null;
CreateModelIsVisible = true;
StateHasChanged();
}
private async Task CreateElementModel()
{
try
{
if (ElementModelCreateImage1 is null || string.IsNullOrEmpty(ProjectionImageFilePreview1))
{
Snackbar.Add("Ảnh model chưa được chọn.", Severity.Warning);
return;
}
if (ElementModelCreateImage2 is null || string.IsNullOrEmpty(ProjectionImageFilePreview2))
{
Snackbar.Add("Ảnh model chưa được chọn.", Severity.Warning);
return;
}
if (string.IsNullOrEmpty(ElementModelCreateModel.Name))
{
Snackbar.Add("Name không được để trống.", Severity.Warning);
return;
}
var nameInvalid = MapEditorHelper.NameChecking(ElementModelCreateModel.Name);
if (!nameInvalid.IsSuccess)
{
Snackbar.Add(nameInvalid.returnStr, Severity.Warning);
return;
}
using var content = new MultipartFormDataContent
{
{ new StringContent(ElementModelCreateModel.MapId.ToString()), nameof(ElementModelCreateModel.MapId) },
{ new StringContent(ElementModelCreateModel.Name ?? String.Empty), nameof(ElementModelCreateModel.Name) },
{ new StringContent(ElementModelCreateModel.Width.ToString()), nameof(ElementModelCreateModel.Width) },
{ new StringContent(ElementModelCreateModel.Height.ToString()), nameof(ElementModelCreateModel.Height) },
};
var fileContent1 = new StreamContent(ElementModelCreateImage1.OpenReadStream());
fileContent1.Headers.ContentType = new MediaTypeHeaderValue(ElementModelCreateImage1.ContentType);
content.Add(fileContent1, "imageOpen", ElementModelCreateImage1.Name);
var fileContent2 = new StreamContent(ElementModelCreateImage2.OpenReadStream());
fileContent2.Headers.ContentType = new MediaTypeHeaderValue(ElementModelCreateImage2.ContentType);
content.Add(fileContent2, "imageClose", ElementModelCreateImage2.Name);
var response = await (await Http.PostAsync("api/ElementModels", content)).Content.ReadFromJsonAsync<MessageResult<ElementModelDto>>();
if (response is null) Snackbar.Add("Lỗi giao tiếp với hệ thống", Severity.Error);
else if (!response.IsSuccess) Snackbar.Add(response.Message ?? "Lỗi chưa xác định.", Severity.Error);
else if (response.Data is null) Snackbar.Add("Hệ thống không thể tạo Element model này", Severity.Error);
else
{
ElementModels.Add(response.Data);
Snackbar.Add($"Tạo Element model {response.Data.Name} thành công.", Severity.Success);
}
CreateModelIsVisible = false;
StateHasChanged();
}
catch (AccessTokenNotAvailableException ex)
{
ex.Redirect();
return;
}
}
private async Task ElementModelCreateImage1Changed(InputFileChangeEventArgs e)
{
ElementModelCreateImage1 = e.File;
if (ElementModelCreateImage1 is not null)
{
var buffers = new byte[ElementModelCreateImage1.Size];
var path = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
await using var fs = new FileStream(path, FileMode.Create);
await ElementModelCreateImage1.OpenReadStream(ElementModelCreateImage1.Size).CopyToAsync(fs);
fs.Position = 0;
await fs.ReadAsync(buffers);
fs.Close();
File.Delete(path);
ProjectionImageFilePreview1 = $"data:{ElementModelCreateImage1.ContentType};base64,{Convert.ToBase64String(buffers)}";
StateHasChanged();
}
}
private async Task ElementModelCreateImage2Changed(InputFileChangeEventArgs e)
{
ElementModelCreateImage2 = e.File;
if (ElementModelCreateImage2 is not null)
{
var buffers = new byte[ElementModelCreateImage2.Size];
var path = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
await using var fs = new FileStream(path, FileMode.Create);
await ElementModelCreateImage2.OpenReadStream(ElementModelCreateImage2.Size).CopyToAsync(fs);
fs.Position = 0;
await fs.ReadAsync(buffers);
fs.Close();
File.Delete(path);
ProjectionImageFilePreview2 = $"data:{ElementModelCreateImage2.ContentType};base64,{Convert.ToBase64String(buffers)}";
StateHasChanged();
}
}
private async Task ModelSelectedChanged(ElementModelDto model)
{
ElementModelSelected = model;
var elModel = await Http.GetFromJsonAsync<MessageResult<ElementModelDto>>($"api/ElementModels/{ElementModelSelected.Id}");
if (elModel is null) Snackbar.Add("Lỗi giao tiếp với hệ thống", Severity.Error);
else if (!elModel.IsSuccess) Snackbar.Add($"Có lỗi xảy ra: {elModel.Message}", Severity.Error);
else await ElementModelSelectChanged.InvokeAsync(elModel.Data);
}
private void OpenUpdateElementModel()
{
if (ElementModelSelected is null) return;
ElementModelUpdateModel.Id = ElementModelSelected.Id;
ElementModelUpdateModel.Name = ElementModelSelected.Name;
ElementModelUpdateModel.Width = ElementModelSelected.Width;
ElementModelUpdateModel.Height = ElementModelSelected.Height;
ElementModelUpdateModel.MapId = ElementModelSelected.MapId;
ElementModelUpdateModel.Content = ElementModelSelected.Content;
UpdateElementModelVisible = true;
StateHasChanged();
}
private async Task UpdateElementModel()
{
var result = await (await Http.PutAsJsonAsync($"api/ElementModels", new ElementModelUpdateModel()
{
Id = ElementModelUpdateModel.Id,
Name = ElementModelUpdateModel.Name,
Width = ElementModelUpdateModel.Width,
Height = ElementModelUpdateModel.Height,
MapId = ElementModelUpdateModel.MapId,
Content = ElementModelUpdateModel.Content,
})).Content.ReadFromJsonAsync<MessageResult<ElementModelDto>>();
if (result == null) Snackbar.Add("Lỗi giao tiếp với hệ thống", Severity.Error);
else if (!result.IsSuccess) Snackbar.Add(result.Message, Severity.Error);
else if (result.Data is null) Snackbar.Add("Lỗi dữ liệu", Severity.Error);
else
{
var elementModel = ElementModels.FirstOrDefault(m => m.Id == result.Data.Id);
if (elementModel is not null)
{
elementModel.Name = result.Data.Name;
elementModel.Width = result.Data.Width;
elementModel.Height = result.Data.Height;
}
Snackbar.Add("Cập nhật thành công", Severity.Success);
}
UpdateElementModelVisible = false;
StateHasChanged();
}
}

View File

@@ -0,0 +1,16 @@
.model-create-item {
display: flex;
justify-content: center;
width: 100%;
height: 200px;
}
.model-create-item img {
justify-content: center;
width: 200px;
height: 200px;
object-fit: contain;
border-radius: 10px;
image-rendering: pixelated;
border: 0.2px solid gray;
}

View File

@@ -0,0 +1,193 @@
@inject IHttpClientFactory HttpClientFactory
@inject ISnackbar Snackbar
@inject IDialogService Dialog
<div class="d-flex w-100 h-100 flex-column ps-2">
<div class="d-flex flex-row justify-content-between w-100 my-2">
<MudText Typo="Typo.h6" Class="d-flex align-items-center">Properties</MudText>
<div class="d-flex flex-row">
<MudTooltip RootClass="d-flex align-items-center" Text="Synchronize" Placement="Placement.Bottom" Color="Color.Primary" Arrow="true">
<MudIconButton Icon="@Icons.Material.Filled.Sync" Variant="Variant.Text" Color="Color.Primary" Size="Size.Small" Disabled="@(Element is null)" OnClick="SynchronizeProperty" />
</MudTooltip>
<MudTooltip RootClass="d-flex align-items-center" Text="Edit" Placement="Placement.Bottom" Color="Color.Info" Arrow="true">
<MudIconButton Icon="@Icons.Material.Filled.Edit" Size="Size.Small" Color="Color.Info" Disabled="@(IsEdit || ElementProperties.Count == 0 || Element is null)" OnClick="(() => IsEdit = true)" />
</MudTooltip>
<MudTooltip RootClass="d-flex align-items-center" Text="Save" Placement="Placement.Bottom" Color="Color.Info" Arrow="true">
<MudIconButton Icon="@Icons.Material.Filled.Save" Variant="Variant.Text" Color="Color.Info" Size="Size.Small" Disabled="@(!IsEdit || Element is null)" OnClick="Save" />
</MudTooltip>
</div>
</div>
<div class="d-flex w-100 flex-grow-1 overflow-x-hidden overflow-y-auto mt-2 align-content-start flex-wrap ps-3">
@foreach (var property in ElementProperties)
{
<div class="d-flex mb-1 pe-3" style="width:33%">
@if (property.Type == typeof(int).ToString())
{
if (int.TryParse(property.DefaultValue, out int value))
{
<MudNumericField T="int" Margin="Margin.Dense" Label="@property.Name" Value="value" Variant="Variant.Outlined" ReadOnly="@(!IsEdit)"
ValueChanged="((data) => DefaultIntValueChanged(property.Id, data))" />
}
}
else if (property.Type == typeof(double).ToString())
{
if (double.TryParse(property.DefaultValue, out double value))
{
<MudNumericField T="double" Margin="Margin.Dense" Label="@property.Name" Value="value" Variant="Variant.Outlined" Step="0.1" ReadOnly="@(!IsEdit)"
ValueChanged="((data) => DefaultDoubleValueChanged(property.Id, data))" />
}
}
else if (property.Type == typeof(bool).ToString())
{
if (bool.TryParse(property.DefaultValue, out bool value))
{
<MudCheckBox Class="m-0" Size="Size.Small" T="bool" LabelPlacement="Placement.Start" Label="@property.Name" Value="value" Color="Color.Success"
UncheckedColor="Color.Default" ReadOnly="@(!IsEdit)" ValueChanged="((data) => DefaultBooleanValueChanged(property.Id, data))" />
}
}
else if (property.Type == typeof(string).ToString())
{
<MudTextField T="string" Label="@property.Name" Value="@property.DefaultValue" Variant="Variant.Outlined" Margin="Margin.Dense" ReadOnly="@(!IsEdit)"
ValueChanged="((data) => property.DefaultValue = data)" />
}
</div>
}
</div>
</div>
@code {
[Parameter]
public EventCallback<ElementDto> ElementPropertyChagned { get; set; }
private List<ElementProperty> ElementProperties = [];
private bool IsEdit = false;
private ElementDto? Element = null;
private HttpClient Http = default!;
protected override async Task OnAfterRenderAsync(bool firstRender)
{
await base.OnAfterRenderAsync(firstRender);
if (!firstRender) return;
Http = HttpClientFactory.CreateClient("MapManagerAPI");
}
public void SetProperties(ElementDto? element)
{
ElementProperties.Clear();
Element = element;
if (element is not null && !string.IsNullOrEmpty(element.Content))
{
var properties = JsonSerializer.Deserialize<List<ElementProperty>>(element.Content, JsonOptionExtends.Read);
if (properties is not null) ElementProperties.AddRange(properties);
}
StateHasChanged();
}
private void DefaultIntValueChanged(Guid id, int value)
{
var property = ElementProperties.FirstOrDefault(p => p.Id == id);
if (property is null) return;
property.DefaultValue = value.ToString();
}
private void DefaultDoubleValueChanged(Guid id, double value)
{
var property = ElementProperties.FirstOrDefault(p => p.Id == id);
if (property is null) return;
property.DefaultValue = value.ToString();
}
private void DefaultBooleanValueChanged(Guid id, bool value)
{
var property = ElementProperties.FirstOrDefault(p => p.Id == id);
if (property is null) return;
property.DefaultValue = value.ToString();
}
private async Task Save()
{
if (Element is null) return;
var result = await (await Http.PutAsJsonAsync($"api/Elements", new ElementUpdateModel()
{
Id = Element.Id,
Name = Element.Name,
IsOpen = Element.IsOpen,
OffsetX = Element.OffsetX,
OffsetY = Element.OffsetY,
Content = JsonSerializer.Serialize(ElementProperties, JsonOptionExtends.Write),
})).Content.ReadFromJsonAsync<MessageResult<ElementDto>>();
if (result == null) Snackbar.Add("Lỗi giao tiếp với hệ thống", Severity.Error);
else if (!result.IsSuccess) Snackbar.Add(result.Message, Severity.Error);
else if (result.Data is null) Snackbar.Add("Lỗi dữ liệu", Severity.Error);
else
{
await ElementPropertyChagned.InvokeAsync(result.Data);
Snackbar.Add("Cập nhật thành công", Severity.Success);
}
IsEdit = false;
StateHasChanged();
}
private async Task SynchronizeProperty()
{
if (Element is null) return;
var parameters = new DialogParameters<ConfirmDialog>
{
{ x => x.Content, $"Bạn có chắc chắn muốn đồng bộ tham số với Element Model không?" },
{ x => x.ConfirmText, "Yes" },
{ x => x.Color, Color.Primary }
};
var confirm = await Dialog.ShowAsync<ConfirmDialog>("Đồng bộ tham số", parameters);
var result = await confirm.Result;
if (result is not null && result.Data is not null && bool.TryParse(result.Data.ToString(), out bool data) && data)
{
var elementModel = await LoadElementModels(Element.ModelId);
if (elementModel is null) Snackbar.Add("Element Model không tồn tại", Severity.Error);
else
{
List<ElementProperty> ModelProperties = [];
var modelProperties = JsonSerializer.Deserialize<List<ElementProperty>>(elementModel.Content, JsonOptionExtends.Read);
if (modelProperties is not null) ModelProperties.AddRange(modelProperties);
parameters = new DialogParameters<ConfirmDialog>
{
{ x => x.Content, $"Bạn có muốn đồng bộ giá trị với Element Model không?" },
{ x => x.CancelText, "No" },
{ x => x.ConfirmText, "Yes" },
{ x => x.Color, Color.Primary }
};
confirm = await Dialog.ShowAsync<ConfirmDialog>("Đồng bộ tham số", parameters);
result = await confirm.Result;
if (result is not null)
{
var valueSynchronize = result.Data is not null && bool.TryParse(result.Data.ToString(), out _);
foreach (var modelProperty in ModelProperties)
{
var property = ElementProperties.FirstOrDefault(em => em.Id == modelProperty.Id);
if(property is null) ElementProperties.Add(modelProperty);
else
{
property.Name = modelProperty.Name;
property.DefaultValue = valueSynchronize ? modelProperty.DefaultValue : property.DefaultValue;
}
}
ElementProperties.RemoveAll(ep => !ModelProperties.Any(mp => mp.Id == ep.Id));
await Save();
}
}
StateHasChanged();
}
}
private async Task<ElementModelDto?> LoadElementModels(Guid modelId)
{
var elModel = await Http.GetFromJsonAsync<MessageResult<ElementModelDto>>($"api/ElementModels/{modelId}");
if (elModel is null) Snackbar.Add("Lỗi giao tiếp với hệ thống", Severity.Error);
else if (!elModel.IsSuccess) Snackbar.Add($"Có lỗi xảy ra: {elModel.Message}", Severity.Error);
else return elModel.Data;
return null;
}
}

View File

@@ -0,0 +1,288 @@
@inject IHttpClientFactory HttpClientFactory
@inject ISnackbar Snackbar
@inject IDialogService Dialog
@inject NavigationManager Nav
<div class="d-flex w-100 h-100 flex-column ps-2">
<div class="d-flex flex-row justify-content-between w-100 pb-1">
<MudText Typo="Typo.h5" Class="d-flex align-items-start">Elements</MudText>
<MudSpacer />
<MudTextField @bind-Value="txtSearch" Placeholder="Search" Adornment="Adornment.End" AdornmentIcon="@Icons.Material.Filled.Search" IconSize="Size.Medium"
Class="mt-0" Variant="Variant.Outlined" Margin="Margin.Dense" TextChanged="TextSearchChanged" />
<MudTooltip RootClass="d-flex align-items-center" Text="Exit" Placement="Placement.Bottom" Color="Color.Info" Arrow="true">
<MudIconButton Class="mx-2 mb-1" Icon="@Icons.Material.Filled.KeyboardReturn" Variant="Variant.Filled" Color="Color.Info" OnClick="@(() => Nav.NavigateTo($"/navigation-maps"))"></MudIconButton>
</MudTooltip>
</div>
<div class="d-flex w-100" style="height: 93%">
<MudTable Class="w-100" T="ElementDto" @ref="Table" Items="@ElementsShow" Dense Hover ReadOnly Striped Elevation="0" FixedHeader="true"
Height="92%" RowClass="cursor-pointer" ServerData="ReloadData" Loading="@IsLoading"
RowClassFunc="@SelectedRowClassFunc" OnRowClick="RowClickEvent">
<HeaderContent>
<MudTh>Name</MudTh>
<MudTh>Model</MudTh>
<MudTh>IsOpen</MudTh>
<MudTh>OffsetX</MudTh>
<MudTh>OffsetY</MudTh>
<MudTh>NodeId</MudTh>
<MudTh></MudTh>
</HeaderContent>
<RowTemplate>
<MudTd DataLabel="Name">@context.Name</MudTd>
<MudTd DataLabel="Model">@context.ModelName</MudTd>
<MudTd DataLabel="IsOpen">@context.IsOpen</MudTd>
<MudTd DataLabel="OffsetX">@context.OffsetX</MudTd>
<MudTd DataLabel="OffsetY">@context.OffsetY</MudTd>
<MudTd DataLabel="Node">@context.NodeId</MudTd>
<MudTd>
<div class="d-flex flex-row-reverse">
<MudMenu Icon="@Icons.Material.Filled.MoreVert" AnchorOrigin="Origin.BottomCenter">
<MudMenuItem OnClick="(() => OpenEditElement(context))" Icon="@Icons.Material.Filled.Edit" IconColor="Color.Info">Edit</MudMenuItem>
<MudMenuItem OnClick="(async () => await Delete(context))" Icon="@Icons.Material.Filled.Delete" IconColor="Color.Error">Delete</MudMenuItem>
</MudMenu>
</div>
</MudTd>
</RowTemplate>
<PagerContent>
<MudTablePager />
</PagerContent>
</MudTable>
</div>
</div>
<style>
.selected {
background-color: #3399ff !important;
}
.selected > td {
color: white !important;
}
.selected > td .mud-input {
color: white !important;
}
</style>
<MudDialog @bind-Visible="updateElementVisble">
<TitleContent>
<MudText Typo="Typo.h6">
Update Element @ElementUpdateModel.Name
</MudText>
</TitleContent>
<DialogContent>
<div class="d-flex flex-column" style="max-height: 700px; overflow-y: auto; width: 300px">
<MudTextField T="string" Label="Name" @bind-value="ElementUpdateModel.Name" Variant="Variant.Outlined"
Required="true" RequiredError="Name is required!"
Validation="@(new Func<string, IEnumerable<string>>(MapEditorHelper.NameValidation))" />
<MudNumericField T="double" Label="OffsetX" @bind-value="ElementUpdateModel.OffsetX" Variant="Variant.Outlined" Step="0.1" />
<MudNumericField T="double" Label="OffsetY" @bind-value="ElementUpdateModel.OffsetY" Variant="Variant.Outlined" Step="0.1" />
<MudCheckBox Size="Size.Small" T="bool" LabelPlacement="Placement.Start" Label="IsOpen" @bind-value="ElementUpdateModel.IsOpen" Color="Color.Success"
UncheckedColor="Color.Default" />
</div>
</DialogContent>
<DialogActions>
<MudButton OnClick="(() => updateElementVisble = false)" Class="px-10" Variant="Variant.Filled">Cancel</MudButton>
<MudButton OnClick="UpdateElement" Variant="Variant.Filled" Color="Color.Primary" Class="px-10">Update</MudButton>
</DialogActions>
</MudDialog>
@code {
[Parameter]
public EventCallback<ElementDto?> ElementSelectChanged { get; set; }
private List<ElementDto> Elements { get; set; } = [];
private List<ElementDto> ElementsShow { get; set; } = [];
private string txtSearch = "";
private bool IsLoading;
private MudTable<ElementDto> Table = default!;
private int selectedRowNumber = -1;
private bool updateElementVisble;
private ElementUpdateModel ElementUpdateModel = new();
private HttpClient Http = default!;
protected override async Task OnAfterRenderAsync(bool firstRender)
{
await base.OnAfterRenderAsync(firstRender);
if (!firstRender) return;
Http = HttpClientFactory.CreateClient("MapManagerAPI");
}
private bool FilterFunc(ElementDto element)
{
if (string.IsNullOrWhiteSpace(txtSearch))
return true;
if (element.Name.Contains(txtSearch, StringComparison.OrdinalIgnoreCase))
return true;
return false;
}
private Task<TableData<ElementDto>> ReloadData(TableState state, CancellationToken _)
{
var robots = new List<ElementDto>();
ElementsShow.Clear();
Elements.ForEach(robot =>
{
if (FilterFunc(robot)) robots.Add(robot);
});
ElementsShow = robots.Skip(state.Page * state.PageSize).Take(state.PageSize).ToList();
return Task.FromResult(new TableData<ElementDto>() { TotalItems = robots.Count(), Items = ElementsShow });
}
private async Task LoadElements(Guid modelId)
{
IsLoading = true;
Elements.Clear();
StateHasChanged();
var elements = await Http.GetFromJsonAsync<MessageResult<IEnumerable<ElementDto>>>($"api/Elements/{modelId}");
if (elements is null) Snackbar.Add("Lỗi giao tiếp với hệ thống", Severity.Error);
else if (!elements.IsSuccess) Snackbar.Add($"Có lỗi xảy ra: {elements.Message}", Severity.Error);
else if (elements.Data is null || !elements.Data.Any())
{
Snackbar.Add("Không có element nào trong model này.", Severity.Warning);
ElementsShow.Clear();
Table?.ReloadServerData();
}
else
{
Elements.AddRange(elements.Data.OrderBy(el => el.Name));
Table?.ReloadServerData();
}
IsLoading = false;
StateHasChanged();
}
public async Task SetData(ElementModelDto? model)
{
selectedRowNumber = -1;
Table.SetSelectedItem(null);
_ = ElementSelectChanged.InvokeAsync(null);
if (model is null)
{
Elements.Clear();
await Table.ReloadServerData();
}
else await LoadElements(model.Id);
}
private void RowClickEvent(TableRowClickEventArgs<ElementDto> tableRowClickEventArgs) { }
private string SelectedRowClassFunc(ElementDto element, int rowNumber)
{
if (selectedRowNumber == rowNumber && Table?.SelectedItem != null && !Table.SelectedItem.Equals(element))
{
return string.Empty;
}
else if (selectedRowNumber == rowNumber && Table?.SelectedItem != null && Table.SelectedItem.Equals(element))
{
return "selected";
}
else if (Table?.SelectedItem != null && Table.SelectedItem.Equals(element))
{
selectedRowNumber = rowNumber;
_ = ElementSelectChanged.InvokeAsync(element);
return "selected";
}
else
{
return string.Empty;
}
}
private void TextSearchChanged(string text)
{
txtSearch = text;
Table?.ReloadServerData();
}
private async Task Delete(ElementDto element)
{
var parameters = new DialogParameters<ConfirmDialog>
{
{ x => x.Content, $"Bạn có chắc chắn muốn xóa element {element.Name} đi không?" },
{ x => x.ConfirmText, "Delete" },
{ x => x.Color, Color.Secondary }
};
var ConfirmDelete = await Dialog.ShowAsync<ConfirmDialog>("Xoá Element", parameters);
var result = await ConfirmDelete.Result;
if (result is not null && result.Data is not null && bool.TryParse(result.Data.ToString(), out bool data) && data)
{
var response = await Http.DeleteFromJsonAsync<MessageResult>($"api/Elements/{element.Id}");
if (response is null) Snackbar.Add("Lỗi giao tiếp với hệ thống", Severity.Error);
else if (!response.IsSuccess) Snackbar.Add(response.Message ?? "Lỗi chưa xác định.", Severity.Error);
else
{
var elementData = Elements.FirstOrDefault(m => m.Id == element.Id);
if (elementData is not null)
{
Elements.Remove(elementData);
await Table.ReloadServerData();
await ElementSelectChanged.InvokeAsync(null);
selectedRowNumber = -1;
Snackbar.Add($"Xóa element thành công.", Severity.Success);
}
else Snackbar.Add($"Element không tồn tại.", Severity.Warning);
}
StateHasChanged();
}
}
private void OpenEditElement(ElementDto model)
{
ElementUpdateModel.Id = model.Id;
ElementUpdateModel.Name = model.Name;
ElementUpdateModel.IsOpen = model.IsOpen;
ElementUpdateModel.OffsetX = model.OffsetX;
ElementUpdateModel.OffsetY = model.OffsetY;
ElementUpdateModel.Content = model.Content;
updateElementVisble = true;
StateHasChanged();
}
private async Task UpdateElement()
{
var selectedElement = Elements.FirstOrDefault(e => e.Id == ElementUpdateModel.Id);
if (selectedElement is null) return;
var result = await (await Http.PutAsJsonAsync($"api/Elements", new ElementUpdateModel()
{
Id = ElementUpdateModel.Id,
Name = ElementUpdateModel.Name,
IsOpen = ElementUpdateModel.IsOpen,
OffsetX = ElementUpdateModel.OffsetX,
OffsetY = ElementUpdateModel.OffsetY,
Content = ElementUpdateModel.Content,
})).Content.ReadFromJsonAsync<MessageResult<ElementDto>>();
if (result == null) Snackbar.Add("Lỗi giao tiếp với hệ thống", Severity.Error);
else if (!result.IsSuccess) Snackbar.Add(result.Message, Severity.Error);
else if (result.Data is null) Snackbar.Add("Lỗi dữ liệu", Severity.Error);
else
{
selectedElement.Name = result.Data.Name;
selectedElement.OffsetX = result.Data.OffsetX;
selectedElement.OffsetY = result.Data.OffsetY;
selectedElement.IsOpen = result.Data.IsOpen;
Snackbar.Add("Cập nhật thành công", Severity.Success);
}
updateElementVisble = false;
StateHasChanged();
}
public void UpdateProperty(ElementDto model)
{
var element = Elements.FirstOrDefault(e => e.Id == model.Id);
if (element is null) return;
element.Name = model.Name;
element.OffsetX = model.OffsetX;
element.OffsetY = model.OffsetY;
element.IsOpen = model.IsOpen;
element.Content = model.Content;
StateHasChanged();
}
}

View File

@@ -0,0 +1,207 @@
@using System.Net.Http.Headers
@using Microsoft.AspNetCore.Components.WebAssembly.Authentication
@inject IHttpClientFactory HttpClientFactory
@inject IJSRuntime JSRuntime
@inject NavigationManager Nav
@inject ISnackbar Snackbar
<div class="d-flex flex-column h-100 w-100">
<span Class="title">@MapName</span>
<div class="d-flex flex-grow-1 w-100 flex-column">
<div class="map-item">
<img src="@imageSrc" alt="map image" onerror="this.onerror=null; this.src='/images/Image-not-found.png';" />
</div>
<div class="d-flex flex-row m-3 align-items-center justify-content-between">
<MudText Typo="Typo.h5">Map's Image</MudText>
<div class="d-flex flex-row">
<MudIconButton Class="me-3" Size="Size.Small" Variant="Variant.Filled" Icon="@Icons.Material.Filled.Download" Color="Color.Primary" Disabled="@Disable" OnClick="@(async () => await DownloadImage())" />
<MudIconButton Class="me-3" Size="Size.Small" Variant="Variant.Filled" Icon="@Icons.Material.Filled.Upload" Color="Color.Primary" Disabled="@Disable" OnClick="OpenUpdateMapImage" />
</div>
</div>
<MudButton StartIcon="@Icons.Material.Filled.BorderColor" Class="m-2" Size="Size.Small" Variant="Variant.Filled" Color="Color.Primary" OnClick="@(() => Nav.NavigateTo($"/navigation-maps/editor/{MapId}"))" Disabled="Disable">
Design
</MudButton>
<MudButton StartIcon="@Icons.Material.Filled.Settings" Class="m-2" Size="Size.Small" Variant="Variant.Filled" Color="Color.Primary" OnClick="@(() => Nav.NavigateTo($"/navigation-maps/settings/{MapId}"))" Disabled="Disable">
Setting
</MudButton>
<MudButton StartIcon="@Icons.Material.Filled.LocationOn" Class="m-2" Size="Size.Small" Variant="Variant.Filled" Color="Color.Primary" OnClick="@(() => Nav.NavigateTo($"/navigation-maps/elements/{MapId}"))" Disabled="Disable">
Element
</MudButton>
<MudButton StartIcon="@Icons.Material.Filled.FileDownload" Class="m-2" Size="Size.Small" Variant="Variant.Filled" Color="Color.Primary" Disabled="Disable" OnClick="ExportMap">
Export
</MudButton>
<MudSpacer />
@* <LoginDisplay /> *@
</div>
</div>
<MudDialog @bind-Visible="@IsUpdateMapImageVisable">
<TitleContent>
<MudText Typo="Typo.h6">
Update Map's Image
</MudText>
</TitleContent>
<DialogContent>
<div class="d-flex flex-column w-100 h-100 px-3">
<div class="d-flex flex-row mb-2">
<InputFile id="fileMapImageCreate" OnChange="MapImageChanged" accept=".png" hidden />
<MudButton HtmlTag="label"
Variant="Variant.Filled"
Color="Color.Primary"
StartIcon="@Icons.Material.Filled.CloudUpload"
for="fileMapImageCreate">
Map Image
</MudButton>
</div>
<div class="d-flex mb-2">
<div class="map-update-item">
<img alt="Map Image" src="@ImagePreview" style="image-rendering: pixelated;" />
</div>
</div>
</div>
</DialogContent>
<DialogActions>
<MudButton OnClick="@(() => IsUpdateMapImageVisable = false)" Variant="Variant.Filled">Cancel</MudButton>
<MudButton Color="Color.Primary" OnClick="UpdateMapImage" Variant="Variant.Filled">Update</MudButton>
</DialogActions>
</MudDialog>
@code {
[Parameter]
public EventCallback<Guid> MapImageChangedCallBack { get; set; }
private bool Disable = true;
private string imageSrc = "/images/Image-not-found.png";
private string MapName = "Map preview";
private Guid MapId = Guid.Empty;
private string ImagePreview = "";
private IBrowserFile? MapImageChange;
private bool IsUpdateMapImageVisable;
private HttpClient Http = default!;
protected override void OnInitialized()
{
base.OnInitialized();
Http = HttpClientFactory.CreateClient("MapManagerAPI");
}
public void SetMapPreview(MapInfoDto? map)
{
if (map is null)
{
Disable = true;
MapName = "Map preview";
imageSrc = "/images/Image-not-found.png";
MapId = Guid.Empty;
}
else
{
imageSrc = $"{Http.BaseAddress}api/Images/map/{map.Id}?t={DateTime.Now}";
MapName = map.Name;
MapId = map.Id;
Disable = false;
}
StateHasChanged();
}
private async Task DownloadImage()
{
try
{
var response = await Http.GetAsync(imageSrc);
if (response.IsSuccessStatusCode)
{
var fileBytes = await response.Content.ReadAsByteArrayAsync();
var base64Data = Convert.ToBase64String(fileBytes);
var mimeType = "image/png";
var url = $"data:{mimeType};base64,{base64Data}";
await JSRuntime.InvokeVoidAsync("DownloadImage", url, $"{MapName}.png");
}
else Snackbar.Add("Không thể tải ảnh map", Severity.Warning);
}
catch (Exception ex)
{
Snackbar.Add($"Không thể tải ảnh map: {ex.Message}", Severity.Warning);
}
}
private void OpenUpdateMapImage()
{
ImagePreview = imageSrc;
MapImageChange = null;
IsUpdateMapImageVisable = true;
StateHasChanged();
}
public async Task<string> UploadMedia(IBrowserFile file)
{
var path = Path.Combine(Path.GetTempPath(), MapName);
await using var fs = new FileStream(path, FileMode.Create);
await file.OpenReadStream(file.Size).CopyToAsync(fs);
var bytes = new byte[file.Size];
fs.Position = 0;
await fs.ReadAsync(bytes);
fs.Close();
File.Delete(path);
return $"data:{file.ContentType};base64,{Convert.ToBase64String(bytes)}";
}
private async Task MapImageChanged(InputFileChangeEventArgs e)
{
MapImageChange = e.File;
if (MapImageChange is not null)
{
ImagePreview = await UploadMedia(MapImageChange);
StateHasChanged();
}
}
private async Task UpdateMapImage()
{
if (MapImageChange is null) return;
using var content = new MultipartFormDataContent();
var fileContent = new StreamContent(MapImageChange.OpenReadStream(maxAllowedSize: 20480000));
fileContent.Headers.ContentType = new MediaTypeHeaderValue(MapImageChange.ContentType);
content.Add(fileContent, "image", MapImageChange.Name);
var result = await (await Http.PutAsync($"api/MapsManager/image/{MapId}", content)).Content.ReadFromJsonAsync<MessageResult>();
if (result is null) Snackbar.Add("Lỗi giao tiếp với hệ thống", Severity.Error);
else if (!result.IsSuccess) Snackbar.Add(result.Message ?? "Lỗi chưa xác định.", Severity.Error);
else
{
imageSrc = ImagePreview;
await MapImageChangedCallBack.InvokeAsync(MapId);
IsUpdateMapImageVisable = false;
Snackbar.Add("Thay đổi thành công", Severity.Success);
}
StateHasChanged();
}
private async Task ExportMap()
{
try
{
if (MapId == Guid.Empty) return;
var response = await Http.GetAsync($"api/MapExport/encrypt/{MapId}");
if (response is not null && response.IsSuccessStatusCode)
{
var fileBytes = await response.Content.ReadAsByteArrayAsync();
var fileName = response.Content.Headers.ContentDisposition?.FileName;
using var streamRef = new DotNetStreamReference(stream: new MemoryStream(fileBytes));
await JSRuntime.InvokeVoidAsync("DownloadMap", string.IsNullOrEmpty(fileName) ? $"{MapName}.map" : fileName, streamRef);
}
}
catch (AccessTokenNotAvailableException ex)
{
ex.Redirect();
return;
}
}
}

View File

@@ -0,0 +1,42 @@
.map-item {
display: flex;
justify-content: center;
width: 100%;
height: fit-content;
}
.map-item img {
justify-content: center;
width: 95%;
height: 400px;
object-fit: contain;
border-radius: 10px;
image-rendering: pixelated;
}
.title {
display: flex;
height: 77px;
width: 100%;
justify-content: center;
align-content: center;
/*border-bottom: 0.5px solid gray;*/
font-size: 30px;
flex-wrap: wrap;
padding-bottom: .5rem;
}
.map-update-item {
display: flex;
justify-content: center;
width: 100%;
height: fit-content;
}
.map-update-item img {
width: 100%;
height: 400px;
object-fit: contain;
border-radius: 10px;
image-rendering: pixelated;
}

View File

@@ -0,0 +1,390 @@
@inject IHttpClientFactory HttpClientFactory
@inject ISnackbar Snackbar
@inject IDialogService Dialog
<div class="d-flex flex-row w-100 h-100 overflow-hidden position-relative">
<div class="actions-list">
<MudGrid Class="m-2" Justify="Justify.FlexStart" Style="width: 93%">
@foreach (var action in Actions)
{
<MudItem Class="p-0 w-100">
<MudButton Class="m-1" Variant="Variant.Filled" Color="Color.Info" OnClick="(() => ActionSelectedChanged(action))" Style="text-transform:none">
@action.Name
</MudButton>
</MudItem>
}
</MudGrid>
</div>
<MudDivider Vertical="true" Style="height: 100%; border: 1px solid gray; opacity: 0.7" />
<div class="d-flex flex-grow-1 flex-row">
<div class="d-flex flex-grow-1 m-2 flex-column">
<MudText Typo="Typo.h5">Action: @ActionSelected?.Name</MudText>
<div class="d-flex flex-column m-2">
<MudTextField Class="my-2" T="string" @bind-Value="@VDAActionSelected.ActionId" @bind-Value:after="PreviewAction" Variant="Variant.Outlined" Label="Action Id" Immediate />
<div class="d-flex flex-row my-2">
<MudTextField Class="me-1" T="string" @bind-Value="@VDAActionSelected.ActionType" @bind-Value:after="PreviewAction" Variant="Variant.Outlined" Label="Action Type" Immediate />
<MudSelect Class="ms-1" T="string" @bind-Value="@VDAActionSelected.BlockingType" @bind-Value:after="PreviewAction" Label="Blocking Type" AnchorOrigin="Origin.BottomLeft" Variant="Variant.Outlined">
<MudSelectItem Value="@BlockingType.NONE.ToString()" />
<MudSelectItem Value="@BlockingType.SOFT.ToString()" />
<MudSelectItem Value="@BlockingType.HARD.ToString()" />
</MudSelect>
</div>
<MudTextField Class="my-2" T="string" @bind-Value="@VDAActionSelected.ActionDescription" @bind-Value:after="PreviewAction" Variant="Variant.Outlined" Label="Action Description" Lines="3" MaxLines="3" Immediate />
<div class="d-flex flex-row my-2">
<div class="d-flex flex-column w-50 me-1">
<MudTextField T="string" Label="Key" Variant="Variant.Outlined" @bind-Value=ActionParameter.Key />
<MudTextField T="string" Label="Value" Variant="Variant.Outlined" @bind-Value=ActionParameter.Value />
</div>
<div class="d-flex flex-grow-1 justify-content-left ms-3 align-items-center">
<div>
<MudButton Variant="Variant.Filled" Color="Color.Primary" OnClick="AddParamterClick" Disabled="@(ActionSelected == null)">Add Parameter</MudButton>
</div>
</div>
</div>
<div class="flex-grow-1 my-2 position-relative">
<MudDataGrid T="ActionParameter" Items="@VDAActionSelected.ActionParameters" EditMode="@DataGridEditMode.Cell" ReadOnly="false" Outlined="true"
CommittedItemChanges="@CommittedItemChanges"
Bordered="true" Dense="true" EditTrigger="DataGridEditTrigger.OnRowClick" Elevation="0" FixedHeader="true" Height="41vh">
<ColGroup>
<col style="width: 30px" />
<col style="width: 35%" />
<col style="width: 35%" />
<col />
</ColGroup>
<Columns>
<PropertyColumn Property="x => (Array.IndexOf(VDAActionSelected.ActionParameters, x) + 1)" Title="Nr" Editable="false" Required="false" />
<PropertyColumn Property="x => x.Key" Editable="true" Title="Key" />
<PropertyColumn Property="x => x.Value" Editable="true" Title="Value" />
<TemplateColumn Editable="false">
<CellTemplate>
<div class="d-flex justify-content-end">
<MudIconButton Size="@Size.Small" Icon="@Icons.Material.Outlined.Delete" Color="Color.Secondary" Variant="Variant.Filled" OnClick="(() => DeleteParameter(context.Item))" />
</div>
</CellTemplate>
</TemplateColumn>
</Columns>
</MudDataGrid>
</div>
</div>
</div>
<div class="actions-preview">
<MudPaper Outlined="true" Height="100%" Class="p-2" Style="border: 1px solid black; border-radius: 20px">
<div>
@ActionSelected?.Content
</div>
</MudPaper>
</div>
</div>
<MudOverlay Visible="OverlayVisible" DarkBackground="true" Absolute="true">
<MudProgressCircular Color="Color.Secondary" Indeterminate="true" />
</MudOverlay>
</div>
<MudDialog @bind-Visible="@CreateActionVisible" DefaultFocus="DefaultFocus.FirstChild">
<TitleContent>
<MudText Typo="Typo.h5">Create Action</MudText>
</TitleContent>
<DialogContent>
<MudTextField @bind-Value="ActionCreateModel.Name" T="string" Label="Name" Variant="Variant.Outlined" Required="true" RequiredError="Name is Required!" Validation="@(new Func<string, IEnumerable<string>>(MapEditorHelper.NameValidation))" />
</DialogContent>
<DialogActions>
<MudButton Color="Color.Default" Variant="Variant.Filled" OnClick="(() => CreateActionVisible = false)">Cancel</MudButton>
<MudButton Color="Color.Primary" Variant="Variant.Filled" OnClick="CreateAction" Disabled="string.IsNullOrEmpty(ActionCreateModel.Name)">Create</MudButton>
</DialogActions>
</MudDialog>
@code {
[Parameter, EditorRequired]
public Guid Id { get; set; }
private bool CreateActionVisible = false;
private ActionCreateModel ActionCreateModel = new();
private List<ActionDto> Actions = [];
private ActionDto? ActionSelected = null;
private readonly ActionModel VDAActionSelected = new();
private readonly ActionModel VDAActionSelectedReset = new();
private bool OverlayVisible;
private ActionParameter ActionParameter = new();
private HttpClient Http = default!;
protected override async Task OnAfterRenderAsync(bool firstRender)
{
await base.OnAfterRenderAsync(firstRender);
if (!firstRender) return;
Http = HttpClientFactory.CreateClient("MapManagerAPI");
await LoadAction();
StateHasChanged();
}
private async Task LoadAction()
{
OverlayVisible = true;
Actions.Clear();
var result = await Http.GetFromJsonAsync<IEnumerable<ActionDto>>($"api/Actions/{Id}");
if (result is not null && result.Any())
{
Actions.AddRange(result);
ActionSelectedChanged(Actions.First());
}
OverlayVisible = false;
StateHasChanged();
}
private async Task CreateAction()
{
var nameInvalid = MapEditorHelper.NameValidation(ActionCreateModel.Name);
if (nameInvalid.Any())
{
Snackbar.Add(string.Join(';', nameInvalid), Severity.Error);
return;
}
var actionDefault = new ActionModel()
{
ActionId = Guid.NewGuid().ToString(),
ActionType = ActionCreateModel.Name,
ActionDescription = "",
BlockingType = BlockingType.NONE.ToString(),
ActionParameters = [],
};
ActionCreateModel.Content = JsonSerializer.Serialize(actionDefault, JsonOptionExtends.Write);
var result = await (await Http.PostAsJsonAsync<ActionCreateModel>("api/Actions", ActionCreateModel)).Content.ReadFromJsonAsync<MessageResult<ActionDto>>();
if (result == null)
{
Snackbar.Add("Lỗi giao tiếp với hệ thống", Severity.Error);
return;
}
else if (!result.IsSuccess)
{
Snackbar.Add(result.Message, Severity.Error);
return;
}
else if (result.Data is null)
{
Snackbar.Add("Không có dữ liệu trả về", Severity.Error);
return;
}
Actions.Add(result.Data);
if (Actions.Any()) ActionSelectedChanged(Actions.First());
else ActionSelected = new();
Snackbar.Add("Tạo Action thành công", Severity.Success);
CreateActionVisible = false;
StateHasChanged();
}
public async Task DeleteAction()
{
if (ActionSelected is null) return;
var parameters = new DialogParameters<ConfirmDialog>
{
{ x => x.Content, $"Bạn có chắc chắn muốn xóa Action {ActionSelected.Name} đi không?" },
{ x => x.ConfirmText, "Delete" },
{ x => x.Color, Color.Secondary }
};
var ConfirmDelete = await Dialog.ShowAsync<ConfirmDialog>("Xoá Action", parameters);
var result = await ConfirmDelete.Result;
if (result is not null && result.Data is not null && bool.TryParse(result.Data.ToString(), out bool data) && data)
{
var deletResult = await Http.DeleteFromJsonAsync<MessageResult>($"api/Actions/{ActionSelected.Id}");
if (deletResult == null)
{
Snackbar.Add("Lỗi giao tiếp với hệ thống", Severity.Error);
return;
}
else if (!deletResult.IsSuccess)
{
Snackbar.Add(deletResult.Message, Severity.Error);
return;
}
var action = Actions.FirstOrDefault(action => action.Id == ActionSelected.Id);
if (action is not null) Actions.Remove(action);
if (Actions.Any()) ActionSelectedChanged(Actions.First());
else
{
ActionSelected = null;
ActionModel actionNew = new();
SetActionSelectedDto(actionNew);
SetActionSelectedResetDto(actionNew);
}
Snackbar.Add("Xóa Action thành công", Severity.Success);
StateHasChanged();
}
}
private void ActionSelectedChanged(ActionDto action)
{
if (ActionSelected != action)
{
ActionSelected = action;
var vdaAction = JsonSerializer.Deserialize<ActionModel>(ActionSelected.Content, JsonOptionExtends.Read);
if (vdaAction is not null)
{
SetActionSelectedDto(vdaAction);
SetActionSelectedResetDto(vdaAction);
}
StateHasChanged();
}
}
public void ShowCreateAction()
{
ActionCreateModel.MapId = Id;
ActionCreateModel.Content = "";
CreateActionVisible = true;
StateHasChanged();
}
public void Reset()
{
if (ActionSelected is null) return;
SetActionSelectedDto(VDAActionSelectedReset);
PreviewAction();
StateHasChanged();
}
public async Task Save()
{
if (ActionSelected is null) return;
if (!ValidateUpdateData(VDAActionSelectedReset, VDAActionSelected))
{
Snackbar.Add("Không có sự thay đổi", Severity.Warning);
return;
}
ActionSelected.Content = JsonSerializer.Serialize(VDAActionSelected, JsonOptionExtends.Write);
var result = await (await Http.PutAsJsonAsync<ActionDto>("api/Actions", ActionSelected)).Content.ReadFromJsonAsync<MessageResult>();
if (result == null)
{
Snackbar.Add("Lỗi giao tiếp với hệ thống", Severity.Error);
return;
}
else if (!result.IsSuccess)
{
Snackbar.Add(result.Message, Severity.Error);
return;
}
SetActionSelectedResetDto(VDAActionSelected);
Snackbar.Add("Cập nhật thành công", Severity.Success);
StateHasChanged();
}
private void PreviewAction()
{
if (ActionSelected is null) return;
ActionSelected.Content = JsonSerializer.Serialize(VDAActionSelected, JsonOptionExtends.Write);
StateHasChanged();
}
private void SetActionSelectedDto(ActionModel dto)
{
VDAActionSelected.ActionId = dto.ActionId;
VDAActionSelected.ActionType = dto.ActionType;
VDAActionSelected.ActionDescription = dto.ActionDescription;
VDAActionSelected.BlockingType = dto.BlockingType;
List<ActionParameter> actionParameters = [];
foreach (var param in dto.ActionParameters)
{
actionParameters.Add(new() { Value = param.Value, Key = param.Key });
}
VDAActionSelected.ActionParameters = [..actionParameters];
}
private void SetActionSelectedResetDto(ActionModel dto)
{
VDAActionSelectedReset.ActionId = dto.ActionId;
VDAActionSelectedReset.ActionType = dto.ActionType;
VDAActionSelectedReset.ActionDescription = dto.ActionDescription;
VDAActionSelectedReset.BlockingType = dto.BlockingType;
List<ActionParameter> actionParameters = [];
foreach (var param in dto.ActionParameters)
{
actionParameters.Add(new() { Value = param.Value, Key = param.Key });
}
VDAActionSelectedReset.ActionParameters = [.. actionParameters];
}
private bool ValidateUpdateData(ActionModel old, ActionModel update)
{
if (old.ActionId != update.ActionId) return true;
if (old.ActionType != update.ActionType) return true;
if (old.ActionDescription != update.ActionDescription) return true;
if (old.BlockingType != update.BlockingType) return true;
if (old.ActionParameters.Length != update.ActionParameters.Length) return true;
foreach (var param in old.ActionParameters)
{
if (!update.ActionParameters.Any(a => a.Key == param.Key && a.Value == param.Value)) return true;
}
return false;
}
private void AddParamterClick()
{
if (ActionSelected is null) return;
if (string.IsNullOrEmpty(ActionParameter.Key))
{
Snackbar.Add("Key không được để trống", Severity.Warning);
return;
}
if (string.IsNullOrEmpty(ActionParameter.Value))
{
Snackbar.Add("Value không được để trống", Severity.Warning);
return;
}
List<ActionParameter> parameters = [];
if (VDAActionSelected.ActionParameters is not null && VDAActionSelected.ActionParameters.Any()) parameters.AddRange(VDAActionSelected.ActionParameters.ToList());
parameters.Add(new()
{
Key = ActionParameter.Key,
Value = ActionParameter.Value
});
VDAActionSelected.ActionParameters = [.. parameters];
PreviewAction();
ActionParameter.Key = string.Empty;
ActionParameter.Value = string.Empty;
StateHasChanged();
}
private void CommittedItemChanges(ActionParameter item)
{
PreviewAction();
StateHasChanged();
}
private async Task DeleteParameter(ActionParameter item)
{
var parameters = new DialogParameters<ConfirmDialog>
{
{ x => x.Content, "Bạn có chắc chắn muốn xóa paramter đi không?" },
{ x => x.ConfirmText, "Delete" },
{ x => x.Color, Color.Secondary }
};
var ConfirmDelete = await Dialog.ShowAsync<ConfirmDialog>("Xoá Paramter", parameters);
var result = await ConfirmDelete.Result;
if (result is not null && result.Data is not null && bool.TryParse(result.Data.ToString(), out bool data) && data)
{
List<ActionParameter> actionParameters = [];
if (VDAActionSelected.ActionParameters is not null && VDAActionSelected.ActionParameters.Any()) actionParameters.AddRange(VDAActionSelected.ActionParameters.ToList());
if (actionParameters.Any()) actionParameters.Remove(item);
VDAActionSelected.ActionParameters = [.. actionParameters];
PreviewAction();
StateHasChanged();
}
}
}

View File

@@ -0,0 +1,24 @@
.actions-list {
display: flex;
flex-direction: column;
height: 100%;
width: 250px;
justify-content: flex-start;
align-items: flex-start;
overflow-y: auto;
overflow-x: hidden;
}
.actions-preview {
height: 100%;
width: 40%;
overflow: hidden;
padding: 10px;
}
.actions-preview div {
white-space: pre;
overflow: auto;
font-size: 17px;
height: 100%;
}

View File

@@ -0,0 +1,277 @@
@inject IHttpClientFactory HttpClientFactory
@inject ISnackbar Snackbar
<div class="d-flex flex-column position-relative w-100 h-100">
<MudCard Class="w-100" Elevation="5">
<MudCardHeader>
<MudText Typo="Typo.h5">Edge</MudText>
</MudCardHeader>
<MudCardContent>
<div class="d-flex flex-column">
<MudSelect Style="margin-left: 2rem" Margin="Margin.Dense" T="DirectionAllowed" @bind-Value="MapSettingDefaultDto.EdgeDirectionAllowed"
Label="Chiều cho phép di chuyển" Variant="Variant.Text" AnchorOrigin="Origin.BottomLeft">
<MudSelectItem Value="DirectionAllowed.Both" />
<MudSelectItem Value="DirectionAllowed.Forward" />
<MudSelectItem Value="DirectionAllowed.Backward" />
<MudSelectItem Value="DirectionAllowed.None" />
</MudSelect>
<div class="config-item">
<MudSlider T="double" Class="me-2" @bind-Value="MapSettingDefaultDto.EdgeMinLength" Min="0.1" Max="5" Step="0.1" Color="Color.Info">
Chiều dài tối thiểu khi tạo Edge (m)
</MudSlider>
<MudNumericField Class="mb-0 mt-0" Margin="Margin.Dense" Style="width: 100px;margin-top: 6px;" T="double" @bind-Value="MapSettingDefaultDto.EdgeMinLength" Variant="Variant.Outlined" Min="0.1" Max="50" Step="0.1" />
</div>
<div class="config-item">
<MudSlider T="double" Class="me-2" @bind-Value="MapSettingDefaultDto.EdgeStraightMaxSpeed" Min="0" Max="5" Step="0.05" Color="Color.Info">
Vận tốc lớn nhất cho phép khi di chuyển trên Edge (thẳng) (m/s)
</MudSlider>
<MudNumericField Class="mb-0 mt-0" Margin="Margin.Dense" Style="width: 100px;margin-top: 6px;" T="double" @bind-Value="MapSettingDefaultDto.EdgeStraightMaxSpeed" Variant="Variant.Outlined" Min="0" Max="5" Step="0.05" />
</div>
<div class="config-item">
<MudSlider T="double" Class="me-2" @bind-Value="MapSettingDefaultDto.EdgeCurveMaxSpeed" Min="0" Max="5" Step="0.05" Color="Color.Info">
Vận tốc lớn nhất cho phép khi di chuyển trên Edge (cong) (m/s)
</MudSlider>
<MudNumericField Class="mb-0 mt-0" Margin="Margin.Dense" Style="width: 100px;margin-top: 6px;" T="double" @bind-Value="MapSettingDefaultDto.EdgeCurveMaxSpeed" Variant="Variant.Outlined" Min="0" Max="5" Step="0.05" />
</div>
<div class="config-item">
<MudSlider T="double" Class="me-2" @bind-Value="MapSettingDefaultDto.EdgeMaxHeight" Min="0.1" Max="5" Step="0.05" Color="Color.Info">
Chiều cao lớn nhất cho phép di chuyển trên Edge (m)
</MudSlider>
<MudNumericField Class="mb-0 mt-0" Margin="Margin.Dense" Style="width: 100px;margin-top: 6px;" T="double" @bind-Value="MapSettingDefaultDto.EdgeMaxHeight" Variant="Variant.Outlined" Min="0.1" Max="50" Step="0.05" />
</div>
<div class="config-item">
<MudSlider T="double" Class="me-2" @bind-Value="MapSettingDefaultDto.EdgeMinHeight" Min="0.1" Max="5" Step="0.05" Color="Color.Info">
Chiều cao tối thiểu cho phép di chuyển trên Edge (m)
</MudSlider>
<MudNumericField Class="mb-0 mt-0" Margin="Margin.Dense" Style="width: 100px;margin-top: 6px;" T="double" @bind-Value="MapSettingDefaultDto.EdgeMinHeight" Variant="Variant.Outlined" Min="0.1" Max="50" Step="0.05" />
</div>
<div class="config-item">
<MudSlider T="double" Class="me-2" @bind-Value="MapSettingDefaultDto.EdgeMaxRotationSpeed" Min="0" Max="5" Step="0.05" Color="Color.Info">
Vận tốc quay lớn nhất cho phép di chuyển trên Edge (rad/s)
</MudSlider>
<MudNumericField Class="mb-0 mt-0" Margin="Margin.Dense" Style="width: 100px;margin-top: 6px;" T="double" @bind-Value="MapSettingDefaultDto.EdgeMaxRotationSpeed" Variant="Variant.Outlined" Min="0" Max="5" Step="0.05" />
</div>
<div class="config-item">
<MudSlider T="double" Class="me-2" @bind-Value="MapSettingDefaultDto.EdgeAllowedDeviationXy" Min="0" Max="1" Step="0.005" Color="Color.Info">
Sai số cho phép về tọa độ X,Y khi đi qua Edge (m)
</MudSlider>
<MudNumericField Class="mb-0 mt-0" Margin="Margin.Dense" Style="width: 100px;margin-top: 6px;" T="double" @bind-Value="MapSettingDefaultDto.EdgeAllowedDeviationXy" Variant="Variant.Outlined" Min="0" Max="1" Step="0.005" />
</div>
<div class="config-item">
<MudSlider T="double" Class="me-2" @bind-Value="MapSettingDefaultDto.EdgeAllowedDeviationTheta" Min="0" Max="180" Step="1" Color="Color.Info">
Sai số cho phép về góc khi đi qua Edge (degree)
</MudSlider>
<MudNumericField Class="mb-0 mt-0" Margin="Margin.Dense" Style="width: 100px;margin-top: 6px;" T="double" @bind-Value="MapSettingDefaultDto.EdgeAllowedDeviationTheta" Variant="Variant.Outlined" Min="0" Max="180" Step="1" />
</div>
<div class="config-item">
<MudCheckBox @bind-Value="MapSettingDefaultDto.EdgeRotationAllowed" Label="Cho phép quay tại Edge" LabelPlacement="Placement.Start" UncheckedColor="Color.Default" Color="Color.Success"></MudCheckBox>
</div>
</div>
</MudCardContent>
</MudCard>
<MudCard Class="w-100 mt-6" Elevation="5">
<MudCardHeader>
<MudText Typo="Typo.h5">Node</MudText>
</MudCardHeader>
<MudCardContent>
<div class="d-flex flex-column">
<div class="config-item">
<MudSlider T="double" Class="me-2" @bind-Value="MapSettingDefaultDto.NodeAllowedDeviationXy" Min="0" Max="1" Step="0.005" Color="Color.Info">
Sai số cho phép về tọa độ X,Y khi đi qua Node (m)
</MudSlider>
<MudNumericField Class="mb-0 mt-0" Margin="Margin.Dense" Style="width: 100px;margin-top: 6px;" T="double" @bind-Value="MapSettingDefaultDto.NodeAllowedDeviationXy" Variant="Variant.Outlined" Min="0" Max="1" Step="0.005" />
</div>
<div class="config-item">
<MudSlider T="double" Class="me-2" @bind-Value="MapSettingDefaultDto.NodeAllowedDeviationTheta" Min="0" Max="180" Step="1" Color="Color.Info">
Sai số cho phép về góc khi đi qua Node (degree)
</MudSlider>
<MudNumericField Class="mb-0 mt-0" Margin="Margin.Dense" Style="width: 100px;margin-top: 6px;" T="double" @bind-Value="MapSettingDefaultDto.NodeAllowedDeviationTheta" Variant="Variant.Outlined" Min="0" Max="180" Step="1" />
</div>
<div class="config-item">
<MudCheckBox @bind-Value="MapSettingDefaultDto.NodeNameAutoGenerate" Class="mt-2" Label="Tự động tạo tên cho Node" LabelPlacement="Placement.Start" UncheckedColor="Color.Default" Color="Color.Success"></MudCheckBox>
<MudTextField @bind-Value="MapSettingDefaultDto.NodeNameTemplate" Label="Template" Disabled="@(!MapSettingDefaultDto.NodeNameAutoGenerate)" Style="width: 20%" ShrinkLabel Variant="Variant.Outlined" />
</div>
</div>
</MudCardContent>
</MudCard>
<MudCard Class="w-100 mt-6" Elevation="5">
<MudCardHeader>
<MudText Typo="Typo.h5">Zone</MudText>
</MudCardHeader>
<MudCardContent>
<div class="d-flex flex-column">
<div class="config-item">
<MudSlider T="double" Class="me-2" @bind-Value="MapSettingDefaultDto.ZoneMinSquare" Min="0.1" Max="5" Step="0.1" Color="Color.Info">
Diện tích tối thiểu khi tạo Zone (m2)
</MudSlider>
<MudNumericField Class="mb-0 mt-0" Margin="Margin.Dense" Style="width: 100px;margin-top: 6px;" T="double" @bind-Value="MapSettingDefaultDto.ZoneMinSquare" Variant="Variant.Outlined" Min="0.1" Max="50" Step="0.1" />
</div>
</div>
</MudCardContent>
</MudCard>
<MudOverlay Visible="OverlayVisible" DarkBackground="true" Absolute="true">
<MudProgressCircular Color="Color.Secondary" Indeterminate="true" />
</MudOverlay>
</div>
@code {
[Parameter, EditorRequired]
public Guid Id { get; set; }
private readonly MapSettingDefaultDto MapSettingDefaultDto = new();
private readonly MapSettingDefaultDto MapSettingDefaultResetDto = new();
private bool OverlayVisible;
private HttpClient Http = default!;
protected override async Task OnAfterRenderAsync(bool firstRender)
{
await base.OnAfterRenderAsync(firstRender);
if (!firstRender) return;
Http = HttpClientFactory.CreateClient("MapManagerAPI");
await LoadMapVersionConfig();
StateHasChanged();
}
private async Task LoadMapVersionConfig()
{
OverlayVisible = true;
StateHasChanged();
var result = await Http.GetFromJsonAsync<MessageResult<MapSettingDefaultDto>>($"api/MapsSetting/{Id}");
if (result == null)
{
Snackbar.Add("Lỗi giao tiếp với hệ thống", Severity.Error);
return;
}
if (!result.IsSuccess)
{
Snackbar.Add(result.Message, Severity.Error);
return;
}
if (result.Data == null)
{
Snackbar.Add("Không tìm thấy cấu hình mặc định cho bản đồ này", Severity.Error);
return;
}
SetConfigBindingDto(result.Data);
SetConfigResetDto(result.Data);
OverlayVisible = false;
StateHasChanged();
}
private void SetConfigResetDto(MapSettingDefaultDto dto)
{
MapSettingDefaultResetDto.Id = dto.Id;
MapSettingDefaultResetDto.EdgeMinLength = dto.EdgeMinLength;
MapSettingDefaultResetDto.EdgeMinHeight = dto.EdgeMinHeight;
MapSettingDefaultResetDto.EdgeMaxHeight = dto.EdgeMaxHeight;
MapSettingDefaultResetDto.EdgeMaxRotationSpeed = dto.EdgeMaxRotationSpeed;
MapSettingDefaultResetDto.EdgeStraightMaxSpeed = dto.EdgeStraightMaxSpeed;
MapSettingDefaultResetDto.EdgeCurveMaxSpeed = dto.EdgeCurveMaxSpeed;
MapSettingDefaultResetDto.EdgeDirectionAllowed = dto.EdgeDirectionAllowed;
MapSettingDefaultResetDto.EdgeRotationAllowed = dto.EdgeRotationAllowed;
MapSettingDefaultResetDto.EdgeAllowedDeviationXy = dto.EdgeAllowedDeviationXy;
MapSettingDefaultResetDto.EdgeAllowedDeviationTheta = dto.EdgeAllowedDeviationTheta;
MapSettingDefaultResetDto.NodeAllowedDeviationXy = dto.NodeAllowedDeviationXy;
MapSettingDefaultResetDto.NodeAllowedDeviationTheta = dto.NodeAllowedDeviationTheta;
MapSettingDefaultResetDto.NodeNameAutoGenerate = dto.NodeNameAutoGenerate;
MapSettingDefaultResetDto.NodeNameTemplate = dto.NodeNameTemplate;
MapSettingDefaultResetDto.ZoneMinSquare = dto.ZoneMinSquare;
}
private void SetConfigBindingDto(MapSettingDefaultDto dto)
{
MapSettingDefaultDto.Id = dto.Id;
MapSettingDefaultDto.EdgeMinLength = dto.EdgeMinLength;
MapSettingDefaultDto.EdgeMinHeight = dto.EdgeMinHeight;
MapSettingDefaultDto.EdgeMaxHeight = dto.EdgeMaxHeight;
MapSettingDefaultDto.EdgeMaxRotationSpeed = dto.EdgeMaxRotationSpeed;
MapSettingDefaultDto.EdgeStraightMaxSpeed = dto.EdgeStraightMaxSpeed;
MapSettingDefaultDto.EdgeCurveMaxSpeed = dto.EdgeCurveMaxSpeed;
MapSettingDefaultDto.EdgeDirectionAllowed = dto.EdgeDirectionAllowed;
MapSettingDefaultDto.EdgeRotationAllowed = dto.EdgeRotationAllowed;
MapSettingDefaultDto.EdgeAllowedDeviationXy = dto.EdgeAllowedDeviationXy;
MapSettingDefaultDto.EdgeAllowedDeviationTheta = dto.EdgeAllowedDeviationTheta;
MapSettingDefaultDto.NodeAllowedDeviationXy = dto.NodeAllowedDeviationXy;
MapSettingDefaultDto.NodeAllowedDeviationTheta = dto.NodeAllowedDeviationTheta;
MapSettingDefaultDto.NodeNameAutoGenerate = dto.NodeNameAutoGenerate;
MapSettingDefaultDto.NodeNameTemplate = dto.NodeNameTemplate;
MapSettingDefaultDto.ZoneMinSquare = dto.ZoneMinSquare;
}
public void Reset()
{
SetConfigBindingDto(MapSettingDefaultResetDto);
StateHasChanged();
}
public async Task Save()
{
if (!ValidateUpdateData(MapSettingDefaultResetDto, MapSettingDefaultDto))
{
Snackbar.Add("Không có sự thay đổi", Severity.Warning);
return;
}
var result = await (await Http.PutAsJsonAsync<MapSettingDefaultDto>("api/MapsSetting", MapSettingDefaultDto)).Content.ReadFromJsonAsync<MessageResult>();
if (result == null)
{
Snackbar.Add("Lỗi giao tiếp với hệ thống", Severity.Error);
return;
}
else if (!result.IsSuccess)
{
Snackbar.Add(result.Message, Severity.Error);
return;
}
SetConfigResetDto(MapSettingDefaultDto);
Snackbar.Add("Cập nhật thành công", Severity.Success);
StateHasChanged();
}
private bool ValidateUpdateData(MapSettingDefaultDto old, MapSettingDefaultDto update)
{
if (old.EdgeStraightMaxSpeed != update.EdgeStraightMaxSpeed) return true;
if (old.EdgeCurveMaxSpeed != update.EdgeCurveMaxSpeed) return true;
if (old.EdgeMaxRotationSpeed != update.EdgeMaxRotationSpeed) return true;
if (old.EdgeMinLength != update.EdgeMinLength) return true;
if (old.EdgeMinHeight != update.EdgeMinHeight) return true;
if (old.EdgeMaxHeight != update.EdgeMaxHeight) return true;
if (old.EdgeDirectionAllowed != update.EdgeDirectionAllowed) return true;
if (old.EdgeRotationAllowed != update.EdgeRotationAllowed) return true;
if (old.EdgeAllowedDeviationXy != update.EdgeAllowedDeviationXy) return true;
if (old.EdgeAllowedDeviationTheta != update.EdgeAllowedDeviationTheta) return true;
if (old.NodeAllowedDeviationXy != update.NodeAllowedDeviationXy) return true;
if (old.NodeAllowedDeviationTheta != update.NodeAllowedDeviationTheta) return true;
if (old.NodeNameAutoGenerate != update.NodeNameAutoGenerate) return true;
if (old.NodeNameTemplate != update.NodeNameTemplate) return true;
if (old.ZoneMinSquare != update.ZoneMinSquare) return true;
return false;
}
}

View File

@@ -0,0 +1,6 @@
.config-item {
display: flex;
flex-direction: row;
margin-left: 2rem;
margin-top: 1rem;
}

View File

@@ -0,0 +1,81 @@
<div class="align-toolbar">
<MudTooltip Text="Copy" role="button" Placement="Placement.Bottom" Color="Color.Info">
<button type="button" class="btn btn-primary align-button" disabled="@copyDisable" @onclick="@(async () => await EditButtonChanged(EditorState.Copy))">
<i class="mdi mdi-content-copy icon-button"></i>
</button>
</MudTooltip>
<MudTooltip Text="Move" role="button" Placement="Placement.Bottom" Color="Color.Info">
<button type="button" class="btn btn-primary align-button" disabled="@moveDisable" @onclick="@(async () => await EditButtonChanged(EditorState.Move))">
<i class="mdi mdi-content-duplicate icon-button"></i>
</button>
</MudTooltip>
<MudTooltip Text="Tách Node" role="button" Placement="Placement.Bottom" Color="Color.Info">
<button type="button" class="btn btn-primary align-button" disabled="@alignDisable" @onclick="@(async () => await AlignButtonCick(AlignState.SplitNode))">
<i class="mdi mdi-call-split icon-button"></i>
</button>
</MudTooltip>
<MudTooltip Text="Gộp Node" role="button" Placement="Placement.Bottom" Color="Color.Info">
<button type="button" class="btn btn-primary align-button" disabled="@alignDisable" @onclick="@(async () => await AlignButtonCick(AlignState.MergeNode))">
<i class="mdi mdi-call-merge icon-button"></i>
</button>
</MudTooltip>
<MudTooltip Text="Horizontal Left" role="button" Placement="Placement.Bottom" Color="Color.Info">
<button type="button" class="btn btn-primary align-button" disabled="@alignDisable" @onclick="@(async () => await AlignButtonCick(AlignState.HorizontalLeft))">
<i class="mdi mdi-format-horizontal-align-left icon-button"></i>
</button>
</MudTooltip>
<MudTooltip Text="Horizontal Right" role="button" Placement="Placement.Bottom" Color="Color.Info">
<button type="button" class="btn btn-primary align-button" disabled="@alignDisable" @onclick="@(async () => await AlignButtonCick(AlignState.HorizontalRight))">
<i class="mdi mdi-format-horizontal-align-right icon-button"></i>
</button>
</MudTooltip>
<MudTooltip Text="Vertical Top" role="button" Placement="Placement.Bottom" Color="Color.Info">
<button type="button" class="btn btn-primary align-button" disabled="@alignDisable" @onclick="@(async () => await AlignButtonCick(AlignState.VerticalTop))">
<i class="mdi mdi-format-vertical-align-top icon-button"></i>
</button>
</MudTooltip>
<MudTooltip Text="Vertical Bottom" role="button" Placement="Placement.Bottom" Color="Color.Info">
<button type="button" class="btn btn-primary align-button" disabled="@alignDisable" @onclick="@(async () => await AlignButtonCick(AlignState.VerticalBottom))">
<i class="mdi mdi-format-vertical-align-bottom icon-button"></i>
</button>
</MudTooltip>
<MudTooltip Text="Horizontal Center" role="button" Placement="Placement.Bottom" Color="Color.Info">
<button type="button" class="btn btn-primary align-button" disabled="@alignDisable" @onclick="@(async () => await AlignButtonCick(AlignState.HorizontalCenter))">
<i class="mdi mdi-format-horizontal-align-center icon-button"></i>
</button>
</MudTooltip>
<MudTooltip Text="Vertical Center" role="button" Placement="Placement.Bottom" Color="Color.Info">
<button type="button" class="btn btn-primary align-button" disabled="@alignDisable" @onclick="@(async () => await AlignButtonCick(AlignState.VerticalCenter))">
<i class="mdi mdi-format-vertical-align-center icon-button"></i>
</button>
</MudTooltip>
</div>
@code {
[Parameter]
public EventCallback<EditorState> EditorStateChanged { get; set; }
[Parameter]
public EventCallback<AlignState> AlignStateClick { get; set; }
[CascadingParameter]
public bool MapIsActive { get; set; }
[Parameter]
public EditorState EditorState { get; set; }
[Parameter]
public bool MultiSelectedNode { get; set; }
[Parameter]
public bool MultiSelectedEdge { get; set; }
private bool alignDisable => MapIsActive || EditorState != EditorState.Scaner || !MultiSelectedNode;
private bool moveDisable => MapIsActive || (EditorState != EditorState.Scaner && EditorState != EditorState.Move) || !MultiSelectedNode;
private bool copyDisable => MapIsActive || (EditorState != EditorState.Scaner && EditorState != EditorState.Copy) || !MultiSelectedEdge;
private async Task EditButtonChanged(EditorState state) => await EditorStateChanged.InvokeAsync(state);
private async Task AlignButtonCick(AlignState state) => await AlignStateClick.InvokeAsync(state);
}

View File

@@ -0,0 +1,19 @@
.align-toolbar {
display: flex;
flex-direction: row;
align-items: center;
margin: 0 10px;
padding: 0 5px 0 10px;
border-left: 1px solid gray;
border-right: 1px solid gray;
margin-top: 1px
}
.align-button {
padding: 1px 0.4rem;
margin-right: 5px;
}
.icon-button {
font-size: 1.6rem;
}

View File

@@ -0,0 +1,209 @@
@inject IJSRuntime JSRuntime
@inject NavigationManager Nav
<div class="control-toolbar">
<div class="check-box">
<div class="form-check me-2">
<input class="form-check-input" type="checkbox" id="showname" @bind="@ShowName" @bind:after="ShowNameChanged">
<label class="form-check-label" for="showname">
Name
</label>
</div>
<div class="form-check me-2">
<input class="form-check-input" type="checkbox" id="showgrid" @bind="@ShowGrid" @bind:after="ShowGridChanged">
<label class="form-check-label" for="showgrid">
Grid
</label>
</div>
<div class="form-check me-2">
<input class="form-check-input" type="checkbox" id="showslammap" @bind="@ShowMapSlam" @bind:after="ShowSlamMapChanged">
<label class="form-check-label" for="showslammap">
Slam Map
</label>
</div>
</div>
<div class="control-button">
<div class="extension">
<MudTooltip Text="Exit" Placement="Placement.Bottom" Color="Color.Info">
<button type="button" class="btn btn-primary button" @onclick="@(() => Nav.NavigateTo($"/navigation-maps"))">
<i class="mdi mdi-keyboard-return icon"></i>
</button>
</MudTooltip>
<MudMenu AnchorOrigin="Origin.BottomRight" Variant="Variant.Filled" ListClass="overflow-x-hidden">
<ActivatorContent>
<button type="button" class="btn btn-primary button-dropdown dropdown-toggle" data-bs-toggle="dropdown" aria-expanded="false">
<i class="mdi mdi-dots-vertical icon"></i>
</button>
</ActivatorContent>
<ChildContent>
<MudSlider Class="mx-4 my-2" T="double" Style="width:95%" Value="EdgeWidth" Min="0.01" Max="0.5" Color="Color.Info" Step="0.01" ValueChanged="EdgeWidthChanged" ValueLabel="true" Variant="Variant.Filled">
Edge Width
</MudSlider>
<MudSlider Class="mx-4 my-2" T="double" Style="width:95%" Value="EdgeDirectionWidth" Min="0.05" Max="0.8" Color="Color.Info" Step="0.01" ValueChanged="EdgeDirectionWidthChanged" ValueLabel="true" Variant="Variant.Filled">
Edge Direction Width
</MudSlider>
<MudSlider Class="mx-4 my-2" T="double" Style="width:95%" Value="NodeRadius" Min="0.01" Max="0.25" Color="Color.Info" Step="0.01" ValueChanged="NodeRadiusChanged" ValueLabel="true" Variant="Variant.Filled">
Node Radius
</MudSlider>
<MudSlider Class="mx-4 my-2" T="double" Style="width:95%" Value="OriginVectorWidth" Min="0.1" Max="1" Color="Color.Info" Step="0.05" ValueChanged="OriginVectorWidthChanged" ValueLabel="true" Variant="Variant.Filled">
Origin Width
</MudSlider>
</ChildContent>
</MudMenu>
<MudTooltip Text="Delete" role="button" Placement="Placement.Bottom" Color="Color.Info">
<button type="button" class="btn btn-danger button" disabled="@(MapIsActive || (!MultiSelectedEdge && !ZoneSelected))" @onclick="@(async () => await ControlStateClick.InvokeAsync(ControlState.Delete))">
<i class="mdi mdi-trash-can-outline icon"></i>
</button>
</MudTooltip>
<MudTooltip Text="Undo" role="button" Placement="Placement.Bottom" Color="Color.Info">
<button type="button" class="btn btn-primary button" disabled="@(MapIsActive || !NodesUndoable)" @onclick="@(async () => await ControlStateClick.InvokeAsync(ControlState.Undo))">
<i class="mdi mdi-undo-variant icon"></i>
</button>
</MudTooltip>
<MudTooltip Text="Save" role="button" Placement="Placement.Bottom" Color="Color.Info">
<button type="button" class="btn btn-primary button" disabled="@(MapIsActive || !NodesUndoable)" @onclick="@(async () => await ControlStateClick.InvokeAsync(ControlState.Save))">
<i class="mdi mdi-content-save icon"></i>
</button>
</MudTooltip>
<MudTooltip Text="Checking Map" role="button" Placement="Placement.Bottom" Color="Color.Info">
<button type="button" class="btn btn-primary button" disabled="@(MapIsActive)" @onclick="@(async () => await ControlStateClick.InvokeAsync(ControlState.CheckMap))">
<i class="mdi mdi mdi-alert-circle icon"></i>
</button>
</MudTooltip>
</div>
<div class="scale-map">
<MudTooltip Text="Scale Fit" role="button" Placement="Placement.Bottom" Color="Color.Info">
<button type="button" class="btn btn-primary button" @onclick="@(async () => await ControlStateClick.InvokeAsync(ControlState.FitScreen))">
<i class="mdi mdi-fit-to-screen icon"></i>
</button>
</MudTooltip>
<MudTooltip Text="Zoom In" role="button" Placement="Placement.Bottom" Color="Color.Info">
<button type="button" class="btn btn-primary button" @onclick="@(async () => await ControlStateClick.InvokeAsync(ControlState.ZoomIn))">
<i class="mdi mdi-magnify-plus-outline icon"></i>
</button>
</MudTooltip>
<MudTooltip Text="Zoom Out" role="button" Placement="Placement.Bottom" Color="Color.Info">
<button type="button" class="btn btn-primary button" @onclick="@(async () => await ControlStateClick.InvokeAsync(ControlState.ZoomOut))">
<i class="mdi mdi-magnify-minus-outline icon"></i>
</button>
</MudTooltip>
</div>
</div>
</div>
@code {
[Parameter]
public EventCallback<ControlState> ControlStateClick { get; set; }
[Parameter]
public EventCallback<(ControlState, bool)> EditorExtensionChanged { get; set; }
[CascadingParameter]
public bool MapIsActive { get; set; }
[Parameter]
public bool ShowGrid { get; set; }
[Parameter]
public bool ShowName { get; set; }
[Parameter]
public bool ShowMapSlam { get; set; }
[Parameter]
public bool NodesUndoable { get; set; }
[Parameter]
public bool MultiSelectedEdge { get; set; }
[Parameter]
public bool ZoneSelected { get; set; }
private double EdgeWidth = 0.15;
private double EdgeDirectionWidth = 0.3;
private double NodeRadius = 0.1;
private double OriginVectorWidth = 0.35;
protected override async Task OnAfterRenderAsync(bool firstRender)
{
await base.OnAfterRenderAsync(firstRender);
if (!firstRender) return;
var width = await JSRuntime.InvokeAsync<string>("getCssVariable", "--edge-stroke-width");
if (!string.IsNullOrEmpty(width))
{
if (double.TryParse(width.Replace("px", ""), out double edgewidth))
{
EdgeWidth = edgewidth;
}
}
else await JSRuntime.InvokeVoidAsync("setCssVariable", "--edge-stroke-width", $"{EdgeWidth}px");
var directionwidth = await JSRuntime.InvokeAsync<string>("getCssVariable", "--edge-direction-stroke-width");
if (!string.IsNullOrEmpty(directionwidth))
{
if (double.TryParse(directionwidth.Replace("px", ""), out double edgedirectionwidth))
{
EdgeDirectionWidth = edgedirectionwidth;
}
}
else await JSRuntime.InvokeVoidAsync("setCssVariable", "--edge-direction-stroke-width", $"{EdgeDirectionWidth}px");
var radius = await JSRuntime.InvokeAsync<string>("getCssVariable", "--node-r");
if (!string.IsNullOrEmpty(radius))
{
if (double.TryParse(radius.Replace("px", ""), out double noderadius))
{
NodeRadius = noderadius;
}
}
else await JSRuntime.InvokeVoidAsync("setCssVariable", "--node-r", $"{NodeRadius}px");
var originwidth = await JSRuntime.InvokeAsync<string>("getCssVariable", "--origin-vector-stroke-width");
if (!string.IsNullOrEmpty(originwidth))
{
if (double.TryParse(originwidth.Replace("px", ""), out double originVectorWidth))
{
OriginVectorWidth = originVectorWidth;
}
}
else await JSRuntime.InvokeVoidAsync("setCssVariable", "--origin-vector-stroke-width", $"{OriginVectorWidth}px");
StateHasChanged();
}
private async Task ShowNameChanged() => await EditorExtensionChanged.InvokeAsync((ControlState.ShowName, ShowName));
private async Task ShowGridChanged() => await EditorExtensionChanged.InvokeAsync((ControlState.ShowGrid, ShowGrid));
private async Task ShowSlamMapChanged() => await EditorExtensionChanged.InvokeAsync((ControlState.ShowMapSlam, ShowMapSlam));
private async Task EdgeWidthChanged(double value)
{
EdgeWidth = value;
var width = $"{EdgeWidth}px";
await JSRuntime.InvokeVoidAsync("setCssVariable", "--edge-stroke-width", width);
}
private async Task EdgeDirectionWidthChanged(double value)
{
EdgeDirectionWidth = value;
var width = $"{EdgeDirectionWidth}px";
await JSRuntime.InvokeVoidAsync("setCssVariable", "--edge-direction-stroke-width", width);
}
private async Task NodeRadiusChanged(double value)
{
NodeRadius = value;
var width = $"{NodeRadius}px";
await JSRuntime.InvokeVoidAsync("setCssVariable", "--node-r", width);
}
private async Task OriginVectorWidthChanged(double value)
{
OriginVectorWidth = value;
var width = $"{OriginVectorWidth}px";
await JSRuntime.InvokeVoidAsync("setCssVariable", "--origin-vector-stroke-width", width);
}
}

View File

@@ -0,0 +1,63 @@
.control-toolbar {
display: flex;
flex-direction: row;
align-items: center;
margin-top: 1px;
flex-grow: 1;
}
.control-toolbar .check-box {
display: flex;
flex-direction: row;
align-items: center;
}
.control-toolbar .control-button {
display: flex;
flex-direction: row-reverse;
flex-grow: 1;
}
.control-toolbar .control-button .extension {
display: flex;
flex-direction: row-reverse;
padding-left: 10px;
}
.control-toolbar .control-button .scale-map {
display: flex;
flex-direction: row-reverse;
flex-grow: 1;
padding-right: 5px;
padding-left: 10px;
border-left: 1px solid gray;
border-right: 1px solid gray;
}
.button {
padding: 1px 0.4rem;
margin-right: 5px;
}
.icon {
font-size: 1.6rem;
}
.button-dropdown {
padding: 1px 0.3rem 1px 0.5rem;
margin-right: 5px;
}
.dropdown-toggle::after {
border: 0px;
}
.custom-range {
--progress: 0%;
}
.custom-range::-webkit-slider-runnable-track {
height: 8px;
border-radius: 5px;
background: linear-gradient(to right, #0d6efd 0%, #0d6efd var(--progress), #e9ecef 0%);
}

View File

@@ -0,0 +1,106 @@
<div class="edit-toolbar">
<div class="btn-group" role="group">
<input type="radio" class="btn-check" name="btnradio" id="btnview" autocomplete="off" checked="@(State == EditorState.View)" disabled="@(MapIsActive)">
<label class="btn btn-outline-primary p-0 align-content-center" for="btnview" aria-label="View" @onclick="@(() => EditorButtonChanged(EditorState.View))">
<MudTooltip Text="View" role="button" Placement="Placement.Bottom" Color="Color.Info">
<i class="mdi mdi-eye-outline icon-button"></i>
</MudTooltip>
</label>
<input type="radio" class="btn-check" name="btnradio" id="btnscan" autocomplete="off" checked="@(State == EditorState.Scaner)" disabled="@(MapIsActive)">
<label class="btn btn-outline-primary p-0 align-content-center" for="btnscan" @onclick="@(() => EditorButtonChanged(EditorState.Scaner))">
<MudTooltip Text="Scan" role="button" Placement="Placement.Bottom" Color="Color.Info">
<i class="mdi mdi-cursor-default-outline icon-button"></i>
</MudTooltip>
</label>
<input type="radio" class="btn-check" name="btnradio" id="btnedit" autocomplete="off" checked="@(State == EditorState.NavigationEdit)" disabled="@(MapIsActive)">
<label class="btn btn-outline-primary p-0 align-content-center" for="btnedit" @onclick="@(() => EditorButtonChanged(EditorState.NavigationEdit))">
<MudTooltip Text="Edit Path" role="button" Placement="Placement.Bottom" Color="Color.Info">
<i class="mdi mdi-vector-point-edit icon-button"></i>
</MudTooltip>
</label>
<input type="radio" class="btn-check" name="btnradio" id="btncreatedge" autocomplete="off" checked="@(State == EditorState.CreateStraighEdge)" disabled="@(MapIsActive)">
<label class="btn btn-outline-primary p-0 align-content-center" for="btncreatedge" @onclick="@(() => EditorButtonChanged(EditorState.CreateStraighEdge))">
<MudTooltip Text="Create Straight Edge" role="button" Placement="Placement.Bottom" Color="Color.Info">
<i class="mdi mdi-vector-line icon-button"></i>
</MudTooltip>
</label>
<input type="radio" class="btn-check" name="btnradio" id="btncreatecurveedge" autocomplete="off" checked="@(State == EditorState.CreateCurveEdge)" disabled="@(MapIsActive)">
<label class="btn btn-outline-primary p-0 align-content-center" for="btncreatecurveedge" @onclick="@(() => EditorButtonChanged(EditorState.CreateCurveEdge))">
<MudTooltip Text="Create Curve Edge" role="button" Placement="Placement.Bottom" Color="Color.Info">
<i class="mdi mdi-vector-radius icon-button"></i>
</MudTooltip>
</label>
<input type="radio" class="btn-check" name="btnradio" id="btncreatecurve2edge" autocomplete="off" checked="@(State == EditorState.CreateDoubleCurveEdge)" disabled="@(MapIsActive)">
<label class="btn btn-outline-primary p-0 align-content-center" for="btncreatecurve2edge" @onclick="@(() => EditorButtonChanged(EditorState.CreateDoubleCurveEdge))">
<MudTooltip Text="Create Bezier Edge" role="button" Placement="Placement.Bottom" Color="Color.Info">
<i class="mdi mdi-vector-bezier icon-button"></i>
</MudTooltip>
</label>
<input type="radio" class="btn-check" name="btnradio" id="btncreatezone" autocomplete="off" checked="@(State == EditorState.CreateZone)" disabled="@(MapIsActive)">
<label class="btn btn-outline-primary p-0 align-content-center" for="btncreatezone" @onclick="@(() => EditorButtonChanged(EditorState.CreateZone))">
<MudTooltip Text="Create Zone" role="button" Placement="Placement.Bottom" Color="Color.Info">
<i class="mdi mdi-vector-square-plus icon-button"></i>
</MudTooltip>
</label>
<input type="radio" class="btn-check" name="btnradio" id="btneditzone" autocomplete="off" checked="@(State == EditorState.SettingZone)" disabled="@(MapIsActive)">
<label class="btn btn-outline-primary p-0 align-content-center" for="btneditzone" @onclick="@(() => EditorButtonChanged(EditorState.SettingZone))">
<MudTooltip Text="Edit Zone" role="button" Placement="Placement.Bottom" Color="Color.Info">
<i class="mdi mdi-vector-square icon-button"></i>
</MudTooltip>
</label>
</div>
<div class="zone-select">
<MudSelect T="ZoneType" Variant="Variant.Outlined" Margin="Margin.Dense" @bind-Value="@Type" @bind-Value:after="ZoneTypeButtonChanged" Disabled="@MapIsActive" Label="Zone Type" Style="width: 175px">
<MudSelectItem Value="@(ZoneType.Operating)">Operating</MudSelectItem>
<MudSelectItem Value="@(ZoneType.OperatingHazard)">OperatingHazard</MudSelectItem>
<MudSelectItem Value="@(ZoneType.Restricted)">Restricted</MudSelectItem>
<MudSelectItem Value="@(ZoneType.LoadTransfer)">LoadTransfer</MudSelectItem>
<MudSelectItem Value="@(ZoneType.Confined)">Confined</MudSelectItem>
<MudSelectItem Value="@(ZoneType.Forbidden)">Forbidden</MudSelectItem>
</MudSelect>
</div>
</div>
@code {
[Parameter]
public EventCallback<EditorState> EditorStateChanged { get; set; }
[Parameter]
public EventCallback<ZoneType> EditorZoneTypeChanged { get; set; }
[CascadingParameter]
public bool MapIsActive { get; set; }
private EditorState State = EditorState.View;
private ZoneType Type = ZoneType.Operating;
private async Task EditorButtonChanged(EditorState state)
{
if (state != State)
{
State = state;
await EditorStateChanged.InvokeAsync(state);
}
}
private async Task ZoneTypeButtonChanged()
{
await EditorZoneTypeChanged.InvokeAsync(Type);
}
public void SetEditorState(EditorState state)
{
if (State != state)
{
State = state;
StateHasChanged();
}
}
}

View File

@@ -0,0 +1,16 @@
.edit-toolbar {
display: flex;
flex-direction: row;
align-items: center;
}
.icon-button {
font-size: 1.7rem;
padding: 0.4rem;
}
.zone-select {
margin-left: 10px;
margin-top: 1px;
align-content: center;
}

View File

@@ -0,0 +1,62 @@
<div class="d-flex flex-row w-100 overflow-x-auto p-1">
<CascadingValue Value="@MapIsActive">
<EditorFunctionToolbar @ref="EditorFunctionToolbarRef" EditorStateChanged="(async(state) => await EditorStateChanged.InvokeAsync(state))"
EditorZoneTypeChanged="(async(zonetype) => await EditorZoneTypeChanged.InvokeAsync(zonetype))" />
<AlignmentToolbar MultiSelectedEdge="@MultiSelectedEdge" MultiSelectedNode="@MultiSelectedNode" EditorState="@EditorState"
AlignStateClick="(async(state) => await AlignStateClick.InvokeAsync(state))"
EditorStateChanged="(async(state) => await EditorStateChanged.InvokeAsync(state))" />
<ControlToolbar ShowGrid="@ShowGrid" ShowName="@ShowName" ShowMapSlam="@ShowMapSlam" NodesUndoable="@NodesUndoable"
ControlStateClick="(async(state) => await ControlStateClick.InvokeAsync(state))"
EditorExtensionChanged="(async (data) => await EditorExtensionChanged.InvokeAsync(data))"
ZoneSelected="@ZoneSelected"
MultiSelectedEdge="@MultiSelectedEdge" />
</CascadingValue>
</div>
@code {
[Parameter]
public bool MapIsActive { get; set; }
[Parameter]
public EventCallback<EditorState> EditorStateChanged { get; set; }
[Parameter]
public EventCallback<ZoneType> EditorZoneTypeChanged { get; set; }
[Parameter]
public EditorState EditorState { get; set; }
[Parameter]
public bool MultiSelectedNode { get; set; }
[Parameter]
public bool MultiSelectedEdge { get; set; }
[Parameter]
public bool ZoneSelected { get; set; }
[Parameter]
public EventCallback<AlignState> AlignStateClick { get; set; }
[Parameter]
public EventCallback<ControlState> ControlStateClick { get; set; }
[Parameter]
public EventCallback<(ControlState, bool)> EditorExtensionChanged { get; set; }
[Parameter]
public bool ShowGrid { get; set; }
[Parameter]
public bool ShowName { get; set; }
[Parameter]
public bool ShowMapSlam { get; set; }
[Parameter]
public bool NodesUndoable { get; set; }
private EditorFunctionToolbar EditorFunctionToolbarRef = null!;
public void SetEditorState(EditorState state) => EditorFunctionToolbarRef.SetEditorState(state);
}

View File

@@ -0,0 +1,8 @@
@using RobotNet.MapShares
@using RobotNet.MapShares.Dtos
@using RobotNet.MapShares.Enums
@using RobotNet.MapShares.Property
@using RobotNet.Shares
@using RobotNet.WebApp.Clients
@using RobotNet.WebApp.Maps.Models
@using System.Text.Json

View File

@@ -0,0 +1,131 @@
using RobotNet.MapShares.Dtos;
using RobotNet.MapShares.Enums;
using System.Text.Json;
namespace RobotNet.WebApp.Maps.Models;
public class EdgeModel : IDisposable
{
public Guid Id => Data.Id;
public Guid MapId => Data.MapId;
public double X1 => StartNode.X;
public double Y1 => StartNode.Y;
public double X2 => EndNode.X;
public double Y2 => EndNode.Y;
public DirectionAllowed DirectionAllowed => Data.DirectionAllowed;
public TrajectoryDegree TrajectoryDegree => Data.TrajectoryDegree;
public double ControlPoint1X => Data.ControlPoint1X;
public double ControlPoint1Y => Data.ControlPoint1Y;
public double ControlPoint2X => Data.ControlPoint2X;
public double ControlPoint2Y => Data.ControlPoint2Y;
public double MaxSpeed => Data.MaxSpeed;
public double MaxHeight => Data.MaxHeight;
public double MinHeight => Data.MinHeight;
public bool RotationAllowed => Data.RotationAllowed;
public double MaxRotationSpeed => Data.MaxRotationSpeed;
public string Actions => Data.Actions;
public double AllowedDeviationXy => Data.AllowedDeviationXy;
public double AllowedDeviationTheta => Data.AllowedDeviationTheta;
public bool ActivedControlPoint1 { get; set; }
public bool ActivedControlPoint2 { get; set; }
public NodeModel StartNode { get; private set; }
public NodeModel EndNode { get; private set; }
public event Func<Task>? StartNodePositionChanged;
public event Func<Task>? EndNodePositionChanged;
public event Func<Task>? ControlPoint1PositionChanged;
public event Func<Task>? ControlPoint2PositionChanged;
public event Func<Task>? DirectionChanged;
public event Action<bool>? ActiveChanged;
public event Action<EdgeModel>? SelectedChanged;
public event Action<bool>? ErrorChanged;
private readonly EdgeDto Data;
public EdgeModel(EdgeDto data, NodeModel startNode, NodeModel endNode)
{
Data = data;
StartNode = startNode;
EndNode = endNode;
StartNode.PositionChanged += StartNode_PositionChanged;
EndNode.PositionChanged += EndNode_PositionChanged;
}
private void EndNode_PositionChanged() => EndNodePositionChanged?.Invoke();
private void StartNode_PositionChanged() => StartNodePositionChanged?.Invoke();
public void Active() => ActiveChanged?.Invoke(true);
public void UnActive() => ActiveChanged?.Invoke(false);
public void Selected() => SelectedChanged?.Invoke(this);
public void UpdateNode(Guid id, NodeModel node)
{
if (StartNode.Id == id)
{
StartNode.PositionChanged -= StartNode_PositionChanged;
StartNode = node;
StartNode.PositionChanged += StartNode_PositionChanged;
StartNodePositionChanged?.Invoke();
}
else if (EndNode.Id == id)
{
EndNode.PositionChanged -= EndNode_PositionChanged;
EndNode = node;
EndNode.PositionChanged += EndNode_PositionChanged;
EndNodePositionChanged?.Invoke();
}
}
public void UpdateData(EdgeUpdateModel model)
{
if(Data.ControlPoint1X != model.ControlPoint1X || Data.ControlPoint1Y != model.ControlPoint1Y)
{
Data.ControlPoint1X = model.ControlPoint1X;
Data.ControlPoint1Y = model.ControlPoint1Y;
ControlPoint1PositionChanged?.Invoke();
}
if (Data.ControlPoint2X != model.ControlPoint2X || Data.ControlPoint2Y != model.ControlPoint2Y)
{
Data.ControlPoint2X = model.ControlPoint2X;
Data.ControlPoint2Y = model.ControlPoint2Y;
ControlPoint2PositionChanged?.Invoke();
}
Data.RotationAllowed = model.RotationAllowed;
Data.MaxSpeed = model.MaxSpeed;
Data.MaxRotationSpeed = model.MaxRotationSpeed;
Data.MaxHeight = model.MaxHeight;
Data.MinHeight = model.MinHeight;
Data.Actions = JsonSerializer.Serialize(model.Actions);
if (Data.DirectionAllowed != model.DirectionAllowed)
{
Data.DirectionAllowed = model.DirectionAllowed;
DirectionChanged?.Invoke();
}
}
public void UpdateControlPoint1(double x, double y)
{
Data.ControlPoint1X = x;
Data.ControlPoint1Y = y;
ControlPoint1PositionChanged?.Invoke();
}
public void UpdateControlPoint2(double x, double y)
{
Data.ControlPoint2X = x;
Data.ControlPoint2Y = y;
ControlPoint2PositionChanged?.Invoke();
}
public void SetError(bool state) => ErrorChanged?.Invoke(state);
public void Dispose()
{
StartNode.PositionChanged -= StartNode_PositionChanged;
EndNode.PositionChanged -= EndNode_PositionChanged;
GC.SuppressFinalize(this);
}
}

View File

@@ -0,0 +1,60 @@
using RobotNet.MapShares.Dtos;
namespace RobotNet.WebApp.Maps.Models;
#nullable disable
public class ElementModel : IDisposable
{
public Guid Id => Element.Id;
public Guid ModelId => Element.ModelId;
public Guid NodeId => Element.NodeId;
public Guid MapId => Element.MapId;
public string Name => Element.Name;
public double X => Node.X;
public double Y => Node.Y;
public double Theta => Node.Theta;
public double OffsetX => Element.OffsetX;
public double OffsetY => Element.OffsetY;
public bool IsOpen => Element.IsOpen;
public string Content => Element.Content;
public event Func<Task> PositionChanged;
public event Func<Task> OffsetChanged;
public ElementDto Element { get; private set; }
public NodeModel Node { get; private set; }
public ElementModel(ElementDto element, NodeModel node)
{
Element = element;
Node = node;
Node.PositionChanged += Node_PositionChanged;
}
public void Node_PositionChanged() => PositionChanged?.Invoke();
public void UpdateOffset(double offsetX, double offsetY)
{
if (Element.OffsetX == offsetX && Element.OffsetY == offsetY) return;
Element.OffsetX = offsetX;
Element.OffsetY = offsetY;
OffsetChanged?.Invoke();
}
public void UpdateElement(ElementDto model)
{
Element.Name = model.Name;
Element.IsOpen = model.IsOpen;
Element.Content = model.Content;
UpdateOffset(model.OffsetX, model.OffsetY);
}
public void Dispose()
{
Node.PositionChanged -= Node_PositionChanged;
GC.SuppressFinalize(this);
}
}

View File

@@ -0,0 +1,123 @@
using RobotNet.MapShares.Dtos;
using RobotNet.MapShares.Enums;
namespace RobotNet.WebApp.Maps.Models;
public class MapEdgeModel : IEnumerable<EdgeModel>
{
private readonly Dictionary<Guid, EdgeModel> dicEdges = [];
public EdgeModel this[int i] => dicEdges.Values.ElementAt(i);
public EdgeModel this[Guid id] => dicEdges[id];
public IEnumerator<EdgeModel> GetEnumerator() => dicEdges.Values.GetEnumerator();
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() => GetEnumerator();
public bool TryGetValue(Guid id, out EdgeModel? value) => dicEdges.TryGetValue(id, out value);
public bool ContainsKey(Guid key) => dicEdges.ContainsKey(key);
public List<EdgeModel> ActivedEdges { get; private set; } = [];
public event Action? Changed;
public event Action<EdgeModel?>? EdgeSelectedChanged;
private (double X, double Y) StartMovePosition;
public void Add(EdgeDto edge, NodeModel start, NodeModel end)
{
if (dicEdges.ContainsKey(edge.Id)) return;
var model = new EdgeModel(edge, start, end);
dicEdges.Add(model.Id, model);
model.SelectedChanged += EdgeSelectedChange;
Changed?.Invoke();
}
public void ReplaceAll(IEnumerable<EdgeModel> edges)
{
foreach (var edge in dicEdges.Values)
{
if (ActivedEdges.Any(e => e.Id == edge.Id))
{
edge.SelectedChanged -= EdgeSelectedChange;
edge.UnActive();
ActivedEdges.Remove(edge);
}
edge.Dispose();
}
dicEdges.Clear();
foreach (var edge in edges)
{
dicEdges.Add(edge.Id, edge);
edge.SelectedChanged += EdgeSelectedChange;
}
Changed?.Invoke();
}
public void Remove(EdgeModel edge)
{
if (!dicEdges.ContainsKey(edge.Id)) return;
edge.SelectedChanged -= EdgeSelectedChange;
if (ActivedEdges.Any(e => e.Id == edge.Id))
{
ActivedEdges.Remove(edge);
}
edge.Dispose();
dicEdges.Remove(edge.Id);
Changed?.Invoke();
}
private void EdgeSelectedChange(EdgeModel edge)
{
EdgeSelectedChanged?.Invoke(edge);
}
public void UnActivedEdge(EdgeModel? exceptedModel = null)
{
foreach (var edge in ActivedEdges)
{
if (exceptedModel is not null && edge.Id == exceptedModel.Id) continue;
var edgeInDic = dicEdges.Values.FirstOrDefault(e => e.Id.Equals(edge.Id));
edgeInDic?.UnActive();
}
ActivedEdges.Clear();
if (exceptedModel is not null) ActivedEdges.Add(exceptedModel);
}
public void ActivedEdge(IEnumerable<EdgeModel> edges)
{
UnActivedEdge();
foreach (var edge in edges)
{
var edgeInDic = dicEdges[edge.Id];
edgeInDic?.Active();
ActivedEdges.Add(edge);
}
}
public void SetStartMovePosition(double x, double y)
{
StartMovePosition.X = x;
StartMovePosition.Y = y;
}
public void UpdateMoveEdge(double x, double y)
{
double deltaX = x - StartMovePosition.X;
double deltaY = y - StartMovePosition.Y;
List<Guid> NodeUpdated = [];
foreach (var edge in ActivedEdges)
{
if (!NodeUpdated.Any(n => n == edge.StartNode.Id)) edge.StartNode.UpdatePosition(edge.StartNode.X + deltaX, edge.StartNode.Y + deltaY);
if (!NodeUpdated.Any(n => n == edge.EndNode.Id)) edge.EndNode.UpdatePosition(edge.EndNode.X + deltaX, edge.EndNode.Y + deltaY);
if (edge.TrajectoryDegree == TrajectoryDegree.Two) edge.UpdateControlPoint1(edge.ControlPoint1X + deltaX, edge.ControlPoint1Y + deltaY);
if (edge.TrajectoryDegree == TrajectoryDegree.Three)
{
edge.UpdateControlPoint1(edge.ControlPoint1X + deltaX, edge.ControlPoint1Y + deltaY);
edge.UpdateControlPoint2(edge.ControlPoint2X + deltaX, edge.ControlPoint2Y + deltaY);
}
NodeUpdated.Add(edge.StartNode.Id);
NodeUpdated.Add(edge.EndNode.Id);
}
StartMovePosition.X = x;
StartMovePosition.Y = y;
}
}

View File

@@ -0,0 +1,45 @@
using System.Collections;
namespace RobotNet.WebApp.Maps.Models;
public class MapElementModel : IEnumerable<ElementModel>
{
private readonly Dictionary<Guid, ElementModel> dicElements = [];
public IEnumerator<ElementModel> GetEnumerator() => dicElements.Values.GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
public bool TryGetValue(Guid id, out ElementModel? value) => dicElements.TryGetValue(id, out value);
public bool ContainsKey(Guid key) => dicElements.ContainsKey(key);
public event Action? Changed;
public void Add(ElementModel element)
{
if (dicElements.ContainsKey(element.Id)) return;
dicElements.Add(element.Id, element);
Changed?.Invoke();
}
public void ReplaceAll(IEnumerable<ElementModel> elements)
{
foreach (var robot in dicElements.Values)
{
robot.Dispose();
}
dicElements.Clear();
foreach (var element in elements)
{
dicElements.Add(element.Id, element);
}
Changed?.Invoke();
}
public void Remove(ElementModel element)
{
if (!dicElements.ContainsKey(element.Id)) return;
element.Dispose();
dicElements.Remove(element.Id);
Changed?.Invoke();
}
}

View File

@@ -0,0 +1,86 @@
using RobotNet.MapShares.Dtos;
namespace RobotNet.WebApp.Maps.Models;
public class MapNodeModel : IEnumerable<NodeModel>
{
private readonly Dictionary<Guid, NodeModel> dicNodes = [];
public NodeModel this[int i] => dicNodes.Values.ElementAt(i);
public NodeModel this[Guid id] => dicNodes[id];
public IEnumerator<NodeModel> GetEnumerator() => dicNodes.Values.GetEnumerator();
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() => GetEnumerator();
public bool ContainsKey(Guid key) => dicNodes.ContainsKey(key);
public bool TryGetValue(Guid id, out NodeModel? value) => dicNodes.TryGetValue(id, out value);
public NodeModel? SelectedNode { get; set; }
public List<NodeModel> ActivedNodes { get; private set; } = [];
public event Action? Changed;
private (double X, double Y) StartMovePosition;
public void Add(NodeDto node)
{
if (dicNodes.ContainsKey(node.Id)) return;
var model = new NodeModel(node);
dicNodes.Add(model.Id, model);
Changed?.Invoke();
}
public void ReplaceAll(IEnumerable<NodeDto> nodes)
{
dicNodes.Clear();
foreach (var node in nodes)
{
var model = new NodeModel(node);
dicNodes.Add(model.Id, model);
}
Changed?.Invoke();
}
public void Remove(NodeModel node)
{
if (!dicNodes.ContainsKey(node.Id)) return;
node.Dispose();
dicNodes.Remove(node.Id);
Changed?.Invoke();
}
public void ActivedNode(IEnumerable<NodeModel> nodes)
{
UnActivedNode();
foreach (var node in nodes)
{
var nodeInDic = dicNodes.Values.FirstOrDefault(e => e.Id.Equals(node.Id));
nodeInDic?.Active();
ActivedNodes.Add(node);
}
}
public void UnActivedNode()
{
foreach (var node in ActivedNodes)
{
var nodeInDic = dicNodes.Values.FirstOrDefault(e => e.Id.Equals(node.Id));
nodeInDic?.UnActive();
}
ActivedNodes.Clear();
}
public void SetStartMovePosition(double x, double y)
{
StartMovePosition.X = x;
StartMovePosition.Y = y;
}
public void UpdateMoveNode(double x, double y)
{
double deltaX = x - StartMovePosition.X;
double deltaY = y - StartMovePosition.Y;
ActivedNodes.ForEach(n => n.UpdatePosition(n.X + deltaX, n.Y + deltaY));
StartMovePosition.X = x;
StartMovePosition.Y = y;
}
}

View File

@@ -0,0 +1,73 @@
using RobotNet.MapShares.Dtos;
namespace RobotNet.WebApp.Maps.Models;
public class MapZoneModel : IEnumerable<ZoneModel>
{
private readonly Dictionary<Guid, ZoneModel> dicZones = [];
public ZoneModel this[int i] => dicZones.Values.ElementAt(i);
public ZoneModel this[Guid id] => dicZones[id];
public IEnumerator<ZoneModel> GetEnumerator() => dicZones.Values.GetEnumerator();
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() => GetEnumerator();
public bool TryGetValue(Guid id, out ZoneModel? value) => dicZones.TryGetValue(id, out value);
public ZoneModel? ZoneActived { get; private set; }
public event Action? Changed;
public event Action<ZoneModel, bool>? ActivedZoneChanged;
public void ReplaceAll(IEnumerable<ZoneDto> zones)
{
foreach (var zone in dicZones.Values)
{
zone.ActiveChanged -= Zone_ActiveChanged;
zone.Dispose();
if (ZoneActived is not null && ZoneActived == zone) ZoneActived = null;
}
dicZones.Clear();
foreach (var zone in zones)
{
var model = new ZoneModel(zone);
model.ActiveChanged += Zone_ActiveChanged;
dicZones.Add(zone.Id, model);
}
Changed?.Invoke();
}
public void Add(ZoneDto zone)
{
if (dicZones.ContainsKey(zone.Id)) return;
var model = new ZoneModel(zone);
dicZones.Add(model.Id, model);
model.ActiveChanged += Zone_ActiveChanged;
Changed?.Invoke();
}
public void Remove(ZoneModel zone)
{
if (!dicZones.ContainsKey(zone.Id)) return;
zone.UnActive();
zone.ActiveChanged -= Zone_ActiveChanged;
if (ZoneActived is not null && zone.Id == ZoneActived.Id) ZoneActived = null;
zone.Dispose();
dicZones.Remove(zone.Id);
Changed?.Invoke();
}
private void Zone_ActiveChanged(ZoneModel zone, bool state)
{
if (state)
{
if (ZoneActived is not null && ZoneActived != zone || ZoneActived is null)
{
ZoneActived?.UnActive();
ZoneActived = zone;
}
}
ActivedZoneChanged?.Invoke(zone, state);
}
public void UnActivedZone() => ZoneActived?.UnActive();
}

View File

@@ -0,0 +1,59 @@
using RobotNet.MapShares.Dtos;
using System.Text.Json;
namespace RobotNet.WebApp.Maps.Models;
public class NodeModel(NodeDto Data) : IDisposable
{
public Guid Id => Data.Id;
public Guid MapId => Data.MapId;
public string Name => Data.Name;
public double X => Data.X;
public double Y => Data.Y;
public double Theta => Data.Theta;
public string Actions => Data.Actions;
public double AllowedDeviationXy => Data.AllowedDeviationXy;
public double AllowedDeviationTheta => Data.AllowedDeviationTheta;
public event Action? PositionChanged;
public event Action<bool>? ActivedChanged;
public event Action<bool>? ErrorChanged;
public int NumberOfEdgeReference => PositionChanged?.GetInvocationList().Length ?? 0;
public void UpdatePosition(double x, double y)
{
if (Data.X == x && Data.Y == y) return;
Data.X = x;
Data.Y = y;
PositionChanged?.Invoke();
}
public void UpdatePosition(double x, double y, double theta)
{
if (Data.X == x && Data.Y == y && Data.Theta == theta) return;
Data.X = x;
Data.Y = y;
Data.Theta = theta;
PositionChanged?.Invoke();
}
public void UpdateData(NodeUpdateModel model)
{
Data.Name = model.Name;
Data.AllowedDeviationXy = model.AllowedDeviationXy;
Data.AllowedDeviationTheta = model.AllowedDeviationTheta;
Data.Actions = JsonSerializer.Serialize(model.Actions);
UpdatePosition(model.X, model.Y, model.Theta);
}
public void Active() => ActivedChanged?.Invoke(true);
public void UnActive() => ActivedChanged?.Invoke(false);
public void SetError(bool state) => ErrorChanged?.Invoke(state);
public void Dispose()
{
GC.SuppressFinalize(this);
}
}

View File

@@ -0,0 +1,121 @@
using RobotNet.MapShares;
using RobotNet.MapShares.Dtos;
using RobotNet.MapShares.Enums;
namespace RobotNet.WebApp.Maps.Models;
public class ZoneModel(ZoneDto Data) : IDisposable
{
public Guid Id => Data.Id;
public Guid MapId => Data.MapId;
public ZoneType Type => Data.Type;
public string Name => Data.Name;
public double X1 => Data.X1;
public double Y1 => Data.Y1;
public double X2 => Data.X2;
public double Y2 => Data.Y2;
public double X3 => Data.X3;
public double Y3 => Data.Y3;
public double X4 => Data.X4;
public double Y4 => Data.Y4;
public string Fill => Data.Type switch
{
ZoneType.Confined => "#c29ffa", // Vùng hoạt động hạn chế
ZoneType.Forbidden => "#ea868f", // Vùng cấm di chuyển
ZoneType.Operating => "#79dfc1", // Vùng hoạt động bình thường
ZoneType.OperatingHazard => "#ffda6a", // Vùng hoạt động nguy hiểm
ZoneType.Restricted => "#fd9843", // Vùng hoạt động giới hạn
ZoneType.LoadTransfer => "#e685b5", // Vùng chuyển hàng
_ => "none",
};
public int ActiveNode = -1;
public event Action<ZoneModel, bool>? ActiveChanged;
public event Func<Task>? ControlNodePosittionChanged;
public event Action? TypeChanged;
private (double X, double Y) StartMovePosition;
public void Active()
{
if (ActiveNode == -1) ActiveNode = 5;
ActiveChanged?.Invoke(this, true);
}
public void UnActive() => ActiveChanged?.Invoke(this, false);
public void UpdateControlNode(double x1, double y1, double x2, double y2, double x3, double y3, double x4, double y4)
{
Data.X1 = x1;
Data.Y1 = y1;
Data.X2 = x2;
Data.Y2 = y2;
Data.X3 = x3;
Data.Y3 = y3;
Data.X4 = x4;
Data.Y4 = y4;
ControlNodePosittionChanged?.Invoke();
}
public void UpdateData(ZoneUpdateModel data)
{
if (data.Type != Data.Type)
{
Data.Type = data.Type;
TypeChanged?.Invoke();
}
if (data.Name != Data.Name) Data.Name = data.Name;
UpdateControlNode(data.X1, data.Y1, data.X2, data.Y2, data.X3, data.Y3, data.X4, data.Y4);
}
public void SetStartMovePosition(double x, double y)
{
StartMovePosition.X = x;
StartMovePosition.Y = y;
}
public void UpdateControlNode(int node, double x, double y)
{
double deltaX = x - StartMovePosition.X;
double deltaY = y - StartMovePosition.Y;
switch (node)
{
case 1:
Data.X1 = x;
Data.Y1 = y;
break;
case 2:
Data.X2 = x;
Data.Y2 = y;
break;
case 3:
Data.X3 = x;
Data.Y3 = y;
break;
case 4:
Data.X4 = x;
Data.Y4 = y;
break;
case 5:
if (!MapEditorHelper.IsPointInside(StartMovePosition.X, StartMovePosition.Y, Data)) return;
Data.X1 += deltaX;
Data.Y1 += deltaY;
Data.X2 += deltaX;
Data.Y2 += deltaY;
Data.X3 += deltaX;
Data.Y3 += deltaY;
Data.X4 += deltaX;
Data.Y4 += deltaY;
break;
}
StartMovePosition.X = x;
StartMovePosition.Y = y;
ControlNodePosittionChanged?.Invoke();
}
public void Dispose()
{
GC.SuppressFinalize(this);
}
}