initial commit
This commit is contained in:
920
Lab505.Client/Pages/ScriptPanel.razor
Normal file
920
Lab505.Client/Pages/ScriptPanel.razor
Normal file
@@ -0,0 +1,920 @@
|
||||
@rendermode @(new InteractiveWebAssemblyRenderMode(prerender: false))
|
||||
@implements IAsyncDisposable
|
||||
@using Microsoft.AspNetCore.SignalR.Client
|
||||
@inject StateService State
|
||||
@inject LangService Lang
|
||||
@inject ScriptLogService ScriptLog
|
||||
|
||||
<MudMessageBox @ref="_confirmRunBox" Title="@Lang.T("Xác nhận chạy script (REAL)", "Confirm run script (REAL)")" CancelText="@Lang.T("Hủy", "Cancel")">
|
||||
<MessageContent>
|
||||
@if (_loadedName != null)
|
||||
{
|
||||
<MudText Typo="Typo.caption" Style="color:#4a9eff;margin-bottom:6px;"><MudIcon Icon="@Icons.Material.Filled.FiberManualRecord" Size="Size.Small" /> @_loadedName</MudText>
|
||||
}
|
||||
<MudText Typo="Typo.caption" Style="color:#aaa;margin-bottom:4px;">@Lang.T("Code sẽ được thực thi:", "Code to be executed:")</MudText>
|
||||
<pre style="max-height:300px;overflow-y:auto;background:#27292b;color:#cfc;font-size:11px;
|
||||
padding:8px;border-radius:4px;border:1px solid #333;margin:0;white-space:pre-wrap;
|
||||
word-wrap:break-word;">@_pendingCode</pre>
|
||||
</MessageContent>
|
||||
<YesButton>
|
||||
<MudButton Color="Color.Primary" Variant="Variant.Filled" StartIcon="@Icons.Material.Filled.PlayArrow">@Lang.T("Chạy", "Run")</MudButton>
|
||||
</YesButton>
|
||||
</MudMessageBox>
|
||||
|
||||
<div class="script-root">
|
||||
|
||||
<div class="script-toolbar">
|
||||
<MudText Typo="Typo.subtitle2" Style="color:#ddd;">SCRIPT</MudText>
|
||||
<MudButton Variant="Variant.Filled" Color="Color.Primary" Size="Size.Small"
|
||||
StartIcon="@Icons.Material.Filled.PlayArrow"
|
||||
OnClick="RunScript" Disabled="@(_isRunning || IsLockBlocked)">Run</MudButton>
|
||||
<MudButton Variant="Variant.Filled" Color="Color.Error" Size="Size.Small"
|
||||
StartIcon="@Icons.Material.Filled.Stop"
|
||||
OnClick="StopScript" Disabled="!_isRunning">@Lang.T("Hủy", "Cancel")</MudButton>
|
||||
@if (IsLockBlocked)
|
||||
{
|
||||
<MudChip T="string" Icon="@Icons.Material.Filled.Warning" Color="Color.Warning"
|
||||
Variant="Variant.Outlined" Size="Size.Small"
|
||||
Style="height:24px;font-size:10px;margin:0;">@Lang.T("Cần giữ lock để chạy script", "Lock required to run script")</MudChip>
|
||||
}
|
||||
else if (IsWorkflowMode)
|
||||
{
|
||||
<MudChip T="string" Icon="@Icons.Material.Filled.Bolt" Color="Color.Warning"
|
||||
Variant="Variant.Outlined" Size="Size.Small"
|
||||
Style="height:24px;font-size:10px;margin:0;opacity:0.8;">Workflow</MudChip>
|
||||
}
|
||||
else if (IsManualMode)
|
||||
{
|
||||
<MudChip T="string" Icon="@Icons.Material.Filled.Settings" Color="Color.Info"
|
||||
Variant="Variant.Outlined" Size="Size.Small"
|
||||
Style="height:24px;font-size:10px;margin:0;opacity:0.8;">Manual</MudChip>
|
||||
}
|
||||
@if (_hubOk)
|
||||
{
|
||||
<MudChip T="string" Icon="@Icons.Material.Filled.CheckCircle" Color="Color.Success"
|
||||
Variant="Variant.Text" Size="Size.Small"
|
||||
Style="height:24px;font-size:11px;margin:0;">Connected</MudChip>
|
||||
}
|
||||
else
|
||||
{
|
||||
<MudButton Variant="Variant.Text" Color="Color.Error" Size="Size.Small"
|
||||
OnClick="ConnectHub"
|
||||
Style="font-size:11px;padding:0 4px;min-height:auto;min-width:auto;text-decoration:underline dotted;">Disconnect</MudButton>
|
||||
}
|
||||
|
||||
<div style="margin-left:auto;display:flex;align-items:center;gap:4px;">
|
||||
@if (_saveOpen)
|
||||
{
|
||||
<MudTextField @bind-Value="_saveName" Immediate="true"
|
||||
Placeholder="@Lang.T("Tên script...", "Script name...")" OnKeyDown="SaveKeyDown" AutoFocus="true"
|
||||
Variant="Variant.Outlined" Margin="Margin.Dense"
|
||||
Style="width:140px;" />
|
||||
<MudIconButton Icon="@Icons.Material.Filled.Check" Size="Size.Small"
|
||||
Style="color:#2ecc71;padding:4px;" OnClick="DoSave" />
|
||||
<MudIconButton Icon="@Icons.Material.Filled.Close" Size="Size.Small"
|
||||
Style="color:#e74c3c;padding:4px;" OnClick="() => _saveOpen = false" />
|
||||
}
|
||||
else
|
||||
{
|
||||
@if (_loadedName != null)
|
||||
{
|
||||
<MudChip T="string" Icon="@Icons.Material.Filled.FiberManualRecord"
|
||||
Color="Color.Info" Variant="Variant.Text" Size="Size.Small"
|
||||
Style="max-width:160px;height:24px;font-size:11px;margin:0;"
|
||||
title="@_loadedName">@_loadedName</MudChip>
|
||||
}
|
||||
<MudButton Variant="Variant.Text" Size="Size.Small" OnClick="OpenSave"
|
||||
Style="color:#aaa;padding:0 6px;min-width:0;font-size:11px;">
|
||||
@Lang.T("Lưu", "Save")
|
||||
</MudButton>
|
||||
}
|
||||
<MudButton Variant="Variant.Outlined" Size="Size.Small"
|
||||
Style="min-width:40px;color:#aaa;border-color:#555;padding:0 8px;"
|
||||
OnClick="ToggleLang">@Lang.Current.ToUpper()</MudButton>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="script-body">
|
||||
|
||||
<!-- ── File sidebar ─────────────────────────────────────── -->
|
||||
<div id="fileSidebar" class="file-sidebar @(_sidebarOpen ? "" : "collapsed")">
|
||||
<div class="sidebar-header">
|
||||
<span>FILES</span>
|
||||
<MudButton Variant="Variant.Text" Size="Size.Small" OnClick="NewScript"
|
||||
Style="color:#888;padding:0 4px;min-width:0;height:22px;font-size:12px;border:1px solid #444;border-radius:3px;">+</MudButton>
|
||||
</div>
|
||||
<div class="sidebar-list">
|
||||
@if (_scripts.Count == 0)
|
||||
{
|
||||
<div class="sidebar-empty">@Lang.T("Chưa có script", "No scripts")</div>
|
||||
}
|
||||
else
|
||||
{
|
||||
@foreach (var s in _scripts)
|
||||
{
|
||||
var item = s;
|
||||
var isActive = _loadedId == item.Id;
|
||||
<div class="@("sidebar-item" + (isActive ? " active" : ""))"
|
||||
@onclick="() => LoadScript(item)">
|
||||
<div class="sidebar-item-name" title="@item.Name">@item.Name</div>
|
||||
<div class="sidebar-item-meta">@item.UpdatedDisplay</div>
|
||||
<span class="sidebar-del-wrap" @onclick:stopPropagation="true">
|
||||
<MudIconButton Class="sidebar-del-btn" Icon="@Icons.Material.Filled.Close"
|
||||
Size="Size.Small"
|
||||
OnClick="() => DeleteScript(item.Id)" />
|
||||
</span>
|
||||
</div>
|
||||
}
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ── Toggle / drag strip ──────────────────────────────── -->
|
||||
<MudIconButton id="sidebarToggle" Class="sidebar-toggle"
|
||||
Icon="@(_sidebarOpen ? Icons.Material.Filled.ChevronLeft : Icons.Material.Filled.ChevronRight)"
|
||||
Size="Size.Small"
|
||||
OnClick="ToggleSidebar"
|
||||
Style="width:14px;padding:0;min-width:0;border-radius:0;height:100%;"
|
||||
title="Kéo để thay đổi kích thước · Click để thu/mở" />
|
||||
|
||||
<!-- ── Editor + output column ───────────────────────────── -->
|
||||
<div class="editor-column">
|
||||
<div id="scriptEditor" class="monaco-editor-host"></div>
|
||||
|
||||
<div id="outputResizeHandle" class="output-resize-handle"></div>
|
||||
|
||||
<div id="outputPane" class="output-pane">
|
||||
@* ── Output / History tabs ── *@
|
||||
<div class="output-tabs">
|
||||
<MudButton Variant="Variant.Text" Size="Size.Small"
|
||||
Class="@("tab-btn" + (!_historyTab ? " tab-on" : ""))"
|
||||
OnClick="() => SetTab(false)">Output</MudButton>
|
||||
@if (_isManager)
|
||||
{
|
||||
<MudButton Variant="Variant.Text" Size="Size.Small"
|
||||
Class="@("tab-btn" + (_historyTab ? " tab-on" : ""))"
|
||||
OnClick="() => SetTab(true)">
|
||||
@Lang.T("Lịch sử", "History")
|
||||
@if (_historyLoading) { <MudProgressCircular Size="Size.Small" Indeterminate="true" Style="width:10px;height:10px;margin-left:4px;" /> }
|
||||
</MudButton>
|
||||
}
|
||||
@{
|
||||
var activeFilters = _historyTab ? _histFilters : _logFilters;
|
||||
}
|
||||
<div class="lf-bar">
|
||||
@foreach (var lvl in _logLevels)
|
||||
{
|
||||
var badge = lvl.Badge;
|
||||
var color = lvl.Color;
|
||||
var isOn = activeFilters.Contains(badge);
|
||||
<MudButton Size="Size.Small" Variant="Variant.Outlined"
|
||||
Style="@($"min-width:0;padding:0 7px;height:22px;font-size:10px;font-family:Consolas,monospace;font-weight:700;letter-spacing:0.3px;flex-shrink:0;{(isOn ? $"color:{color};border-color:{color};background:rgba(255,255,255,0.05);" : "color:#555;border-color:#2a2a2a;")}")"
|
||||
OnClick="@(() => { if (!activeFilters.Add(badge)) activeFilters.Remove(badge); })">@badge</MudButton>
|
||||
}
|
||||
@if (!_historyTab)
|
||||
{
|
||||
<MudTextField @bind-Value="_logSearch" Immediate="true"
|
||||
Placeholder="search log..."
|
||||
Variant="Variant.Outlined" Margin="Margin.Dense"
|
||||
Class="lf-field" Style="flex:1;min-width:60px;" />
|
||||
}
|
||||
else
|
||||
{
|
||||
<MudTextField @bind-Value="_histSearch" Immediate="true"
|
||||
Placeholder="search log..."
|
||||
Variant="Variant.Outlined" Margin="Margin.Dense"
|
||||
Class="lf-field" Style="flex:1;min-width:60px;" />
|
||||
@if (_isManager)
|
||||
{
|
||||
<MudTextField @bind-Value="_searchUsername" Immediate="true"
|
||||
Placeholder="search user..."
|
||||
Variant="Variant.Outlined" Margin="Margin.Dense"
|
||||
Class="lf-field" Style="width:110px;flex-shrink:0;"
|
||||
OnKeyDown="SearchKeyDown" />
|
||||
}
|
||||
}
|
||||
</div>
|
||||
<MudTooltip Text="@Lang.T("Xóa", "Clear")" Placement="Placement.Left">
|
||||
<MudIconButton Icon="@Icons.Material.Filled.DeleteSweep" Size="Size.Small"
|
||||
OnClick="ClearActive"
|
||||
Style="color:#3a3a3a;padding:0 8px;flex-shrink:0;" />
|
||||
</MudTooltip>
|
||||
</div>
|
||||
|
||||
@if (!_historyTab)
|
||||
{
|
||||
<div class="output-area" @ref="_outputPanel">
|
||||
|
||||
@foreach (var line in FilteredLines)
|
||||
{
|
||||
<div class="log-line">@((MarkupString)line)</div>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
else
|
||||
{
|
||||
<div class="output-area history-area">
|
||||
@if (_historyLoading)
|
||||
{
|
||||
<div style="display:flex;align-items:center;gap:8px;padding:12px;">
|
||||
<MudProgressCircular Size="Size.Small" Indeterminate="true" Color="Color.Default" />
|
||||
<MudText Typo="Typo.caption" Style="color:#444;">@Lang.T("Đang tải...", "Loading...")</MudText>
|
||||
</div>
|
||||
}
|
||||
else if (_historyLogs.Count == 0)
|
||||
{
|
||||
<div style="padding:16px;text-align:center;">
|
||||
<MudIcon Icon="@Icons.Material.Filled.Inbox" Style="color:#2a2a2a;font-size:32px;" />
|
||||
<MudText Typo="Typo.caption" Style="color:#444;display:block;margin-top:4px;">@Lang.T("Chưa có lịch sử.", "No history yet.")</MudText>
|
||||
</div>
|
||||
}
|
||||
else
|
||||
{
|
||||
@foreach (var log in FilteredHistory)
|
||||
{
|
||||
<div class="history-row">
|
||||
<span class="hist-time">@log.StartedAt</span>
|
||||
@if (_isManager)
|
||||
{
|
||||
<span class="hist-user">@log.Username</span>
|
||||
}
|
||||
<span class="hist-name" title="@log.ScriptName">
|
||||
@(string.IsNullOrEmpty(log.ScriptName) ? "(anonymous)" : log.ScriptName)
|
||||
</span>
|
||||
<MudChip T="string" Color="@StatusColor(log.Status)" Size="Size.Small"
|
||||
Variant="Variant.Text" Class="hist-chip">@log.Status</MudChip>
|
||||
@if (!string.IsNullOrEmpty(log.Error))
|
||||
{
|
||||
<MudTooltip Text="@log.Error" Placement="Placement.Left">
|
||||
<MudIcon Icon="@Icons.Material.Filled.ErrorOutline"
|
||||
Size="Size.Small" Color="Color.Error" Style="font-size:14px;" />
|
||||
</MudTooltip>
|
||||
}
|
||||
</div>
|
||||
}
|
||||
}
|
||||
</div>
|
||||
}
|
||||
</div> @* end outputPane *@
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
@code {
|
||||
[Inject] HttpClient Http { get; set; } = default!;
|
||||
[Inject] IJSRuntime JS { get; set; } = default!;
|
||||
|
||||
// ── Output filter ─────────────────────────────────────────────────────────
|
||||
private ElementReference _outputPanel;
|
||||
private readonly HashSet<string> _logFilters = new();
|
||||
private readonly HashSet<string> _histFilters = new();
|
||||
private string _logSearch = "";
|
||||
private string _histSearch = "";
|
||||
|
||||
private static readonly (string Badge, string Color)[] _logLevels =
|
||||
[
|
||||
("INFO", "#42a5f5"), ("DONE", "#66bb6a"), ("WARN", "#ffa726"),
|
||||
("ERR", "#ef5350"), ("DEV", "#9575cd")
|
||||
];
|
||||
|
||||
private IEnumerable<string> FilteredLines
|
||||
{
|
||||
get
|
||||
{
|
||||
var lines = (IEnumerable<string>)ScriptLog.Lines;
|
||||
if (_logFilters.Count > 0)
|
||||
lines = lines.Where(l => _logFilters.Any(f => l.Contains($">{f}<")));
|
||||
if (!string.IsNullOrEmpty(_logSearch))
|
||||
lines = lines.Where(l => l.Contains(_logSearch, StringComparison.OrdinalIgnoreCase));
|
||||
return lines;
|
||||
}
|
||||
}
|
||||
|
||||
private static string StatusToLevel(string s) => s switch
|
||||
{
|
||||
"Success" => "DONE",
|
||||
"Cancelled" => "WARN",
|
||||
"Running" => "INFO",
|
||||
_ => "ERR"
|
||||
};
|
||||
|
||||
private IEnumerable<LogItem> FilteredHistory
|
||||
{
|
||||
get
|
||||
{
|
||||
var items = (IEnumerable<LogItem>)_historyLogs;
|
||||
if (_histFilters.Count > 0)
|
||||
items = items.Where(l => _histFilters.Contains(StatusToLevel(l.Status)));
|
||||
if (!string.IsNullOrEmpty(_histSearch))
|
||||
items = items.Where(l =>
|
||||
(l.ScriptName ?? "").Contains(_histSearch, StringComparison.OrdinalIgnoreCase) ||
|
||||
l.StartedAt.Contains(_histSearch, StringComparison.OrdinalIgnoreCase));
|
||||
if (!string.IsNullOrEmpty(_searchUsername))
|
||||
items = items.Where(l =>
|
||||
(l.Username ?? "").Contains(_searchUsername, StringComparison.OrdinalIgnoreCase));
|
||||
return items;
|
||||
}
|
||||
}
|
||||
|
||||
private void ClearActive()
|
||||
{
|
||||
if (_historyTab) _historyLogs.Clear();
|
||||
else ScriptLog.Clear();
|
||||
}
|
||||
|
||||
private Color StatusColor(string s) => s switch
|
||||
{
|
||||
"Success" => Color.Success,
|
||||
"Cancelled" => Color.Warning,
|
||||
"Running" => Color.Info,
|
||||
_ => Color.Error
|
||||
};
|
||||
private bool _isRunning;
|
||||
private bool _hubOk;
|
||||
private CancellationTokenSource? _cts;
|
||||
private HubConnection? _hub;
|
||||
|
||||
// ── History ───────────────────────────────────────────────────────────────
|
||||
private bool _isManager;
|
||||
private bool _historyTab;
|
||||
private bool _historyLoading;
|
||||
private string _searchUsername = "";
|
||||
private List<LogItem> _historyLogs = [];
|
||||
record LogItem(string StartedAt, string Username, string ScriptName, string Status, string? Error);
|
||||
|
||||
private async Task SetTab(bool history)
|
||||
{
|
||||
_historyTab = history;
|
||||
if (history && _historyLogs.Count == 0) await LoadHistory();
|
||||
}
|
||||
|
||||
private async Task SearchKeyDown(KeyboardEventArgs e)
|
||||
{
|
||||
if (e.Key == "Enter") await LoadHistory();
|
||||
}
|
||||
|
||||
private async Task LoadHistory()
|
||||
{
|
||||
_historyLoading = true;
|
||||
StateHasChanged();
|
||||
try
|
||||
{
|
||||
string url = _isManager
|
||||
? $"/api/script/logs{(string.IsNullOrWhiteSpace(_searchUsername) ? "" : $"?username={Uri.EscapeDataString(_searchUsername)}")}"
|
||||
: "/api/script/logs/me";
|
||||
var list = await Http.GetFromJsonAsync<List<LogItem>>(url);
|
||||
_historyLogs = list ?? [];
|
||||
}
|
||||
catch { }
|
||||
_historyLoading = false;
|
||||
StateHasChanged();
|
||||
}
|
||||
|
||||
// ── Lock awareness ────────────────────────────────────────────────────────
|
||||
private string _myUserId = "";
|
||||
|
||||
/// Script chạy trên real hardware → phải giữ workflow lock hoặc ít nhất 1 group lock
|
||||
private bool IsLockBlocked
|
||||
{
|
||||
get
|
||||
{
|
||||
if (State.System.IsSimulation) return false; // sim: không cần lock
|
||||
var ls = State.LockState;
|
||||
if (ls is null) return false; // real nhưng chưa có snapshot
|
||||
bool hasWorkflow = ls.Workflow?.UserId == _myUserId;
|
||||
bool hasGroup = ls.Groups?.Values.Any(h => h?.UserId == _myUserId) == true;
|
||||
return !hasWorkflow && !hasGroup;
|
||||
}
|
||||
}
|
||||
|
||||
private bool IsWorkflowMode =>
|
||||
!State.System.IsSimulation && State.LockState?.Workflow?.UserId == _myUserId;
|
||||
|
||||
private bool IsManualMode =>
|
||||
!State.System.IsSimulation && !IsWorkflowMode
|
||||
&& (State.LockState?.Groups?.Values.Any(h => h?.UserId == _myUserId) == true);
|
||||
|
||||
// ── Script storage ────────────────────────────────────────────────────────
|
||||
private List<ScriptItem> _scripts = [];
|
||||
private int? _loadedId;
|
||||
private string? _loadedName;
|
||||
private bool _saveOpen;
|
||||
private string _saveName = "";
|
||||
private bool _sidebarOpen = true;
|
||||
|
||||
MudMessageBox? _confirmRunBox;
|
||||
private string _pendingCode = "";
|
||||
|
||||
record ScriptItem(int Id, string Name, string UpdatedDisplay);
|
||||
|
||||
protected override async Task OnInitializedAsync()
|
||||
{
|
||||
await State.StartAsync();
|
||||
State.LockStateChanged += OnStateChanged;
|
||||
State.SystemChanged += OnStateChanged;
|
||||
|
||||
Lang.LangChanged += OnLangChanged;
|
||||
ScriptLog.LogChanged += OnLogChanged;
|
||||
await ConnectHub();
|
||||
await RefreshScriptList();
|
||||
try
|
||||
{
|
||||
var me = await Http.GetFromJsonAsync<MeDto>("/api/auth/me");
|
||||
_myUserId = me?.UserId ?? "";
|
||||
_isManager = me?.Role is "Manager" or "Admin";
|
||||
ScriptLog.IsDevMode = me?.Role is "Admin";
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
private void OnStateChanged() => InvokeAsync(StateHasChanged);
|
||||
private void OnLogChanged() => InvokeAsync(async () =>
|
||||
{
|
||||
StateHasChanged();
|
||||
try { await JS.InvokeVoidAsync("eval",
|
||||
"var el=document.querySelector('.output-area');if(el)el.scrollTop=0;"); }
|
||||
catch { }
|
||||
});
|
||||
|
||||
private void OnLangChanged() => _ = InvokeAsync(async () =>
|
||||
{
|
||||
try { await JS.InvokeVoidAsync("setEditorLang", Lang.Current); } catch { }
|
||||
StateHasChanged();
|
||||
});
|
||||
|
||||
protected override async Task OnAfterRenderAsync(bool firstRender)
|
||||
{
|
||||
if (firstRender)
|
||||
{
|
||||
await JS.InvokeVoidAsync("initScriptEditor");
|
||||
await JS.InvokeVoidAsync("splitter.initSidebarSplit");
|
||||
await JS.InvokeVoidAsync("splitter.initOutputSplit");
|
||||
}
|
||||
}
|
||||
|
||||
private async Task ToggleSidebar()
|
||||
{
|
||||
// Skip toggle if the mousedown was actually a drag
|
||||
bool wasDrag = false;
|
||||
try { wasDrag = await JS.InvokeAsync<bool>("(function(){ var h=document.getElementById('sidebarToggle'); return h && h._wasDragged ? h._wasDragged() : false; })"); }
|
||||
catch { }
|
||||
if (wasDrag) return;
|
||||
|
||||
_sidebarOpen = !_sidebarOpen;
|
||||
var w = _sidebarOpen ? "180px" : "0px";
|
||||
try { await JS.InvokeVoidAsync("eval", $"var s=document.getElementById('fileSidebar');if(s)s.style.width='{w}';"); }
|
||||
catch { }
|
||||
}
|
||||
|
||||
// ── Hub connections ───────────────────────────────────────────────────────
|
||||
private async Task ConnectHub()
|
||||
{
|
||||
try
|
||||
{
|
||||
if (_hub != null)
|
||||
{
|
||||
await _hub.DisposeAsync();
|
||||
_hub = null;
|
||||
}
|
||||
_hub = new HubConnectionBuilder()
|
||||
.WithUrl(new Uri(Http.BaseAddress!, "/scriptHub"))
|
||||
.WithAutomaticReconnect()
|
||||
.Build();
|
||||
|
||||
_hub.On<string>("scriptLog", line =>
|
||||
{
|
||||
ScriptLog.Log(line); // fires LogChanged → OnLogChanged → StateHasChanged
|
||||
});
|
||||
|
||||
_hub.Reconnected += async _ => { _hubOk = true; await InvokeAsync(StateHasChanged); };
|
||||
_hub.Closed += async _ => { _hubOk = false; await InvokeAsync(StateHasChanged); };
|
||||
|
||||
await _hub.StartAsync();
|
||||
_hubOk = true;
|
||||
await InvokeAsync(StateHasChanged);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
ScriptLog.Log($"❌ Hub: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
// ── Run / Stop ────────────────────────────────────────────────────────────
|
||||
private async Task RunScript()
|
||||
{
|
||||
if (!_hubOk) { ScriptLog.Log(Lang.T("❌ Hub chưa kết nối.", "❌ Hub not connected.")); return; }
|
||||
|
||||
string code;
|
||||
try { code = await JS.InvokeAsync<string>("getEditorValue"); }
|
||||
catch { ScriptLog.Log(Lang.T("❌ Không đọc được code.", "❌ Failed to read code.")); return; }
|
||||
|
||||
// SIM mode: run immediately without confirmation
|
||||
// REAL mode: show code in dialog for review before executing
|
||||
if (!State.System.IsSimulation)
|
||||
{
|
||||
_pendingCode = code;
|
||||
var confirmed = await _confirmRunBox!.ShowAsync();
|
||||
if (confirmed != true) return;
|
||||
}
|
||||
|
||||
if (string.IsNullOrWhiteSpace(code))
|
||||
{
|
||||
ScriptLog.Log(Lang.T("⚠️ Không có code.", "⚠️ No code."));
|
||||
return;
|
||||
}
|
||||
|
||||
_cts = new CancellationTokenSource();
|
||||
_isRunning = true;
|
||||
await InvokeAsync(StateHasChanged);
|
||||
|
||||
try
|
||||
{
|
||||
var resp = await Http.PostAsJsonAsync("/api/script/run",
|
||||
new { Code = code, Name = _loadedName ?? "" }, _cts.Token);
|
||||
|
||||
if ((int)resp.StatusCode == 423)
|
||||
ScriptLog.Log(Lang.T("⚠ Cần giữ lock (CONTROL ACCESS → TAKE CONTROL) trước khi chạy script.", "⚠ Lock required (CONTROL ACCESS → TAKE CONTROL) before running script."));
|
||||
else if (!resp.IsSuccessStatusCode)
|
||||
ScriptLog.Log($"❌ Server: {resp.StatusCode}");
|
||||
}
|
||||
catch (OperationCanceledException) { ScriptLog.Log(Lang.T("⛔ Đã dừng.", "⛔ Stopped.")); }
|
||||
catch (Exception ex) { ScriptLog.Log($"❌ {ex.Message}"); }
|
||||
finally
|
||||
{
|
||||
_isRunning = false;
|
||||
_cts?.Dispose();
|
||||
_cts = null;
|
||||
await InvokeAsync(StateHasChanged);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task StopScript()
|
||||
{
|
||||
_cts?.Cancel();
|
||||
try { await Http.PostAsync("/api/script/cancel", null); } catch { }
|
||||
}
|
||||
|
||||
// ── Language toggle ───────────────────────────────────────────────────────
|
||||
private Task ToggleLang() => Lang.ToggleAsync(Http); // OnLangChanged fires setEditorLang
|
||||
|
||||
// ── Script save / load ────────────────────────────────────────────────────
|
||||
private async Task RefreshScriptList()
|
||||
{
|
||||
try
|
||||
{
|
||||
var list = await Http.GetFromJsonAsync<List<ScriptDto>>("/api/scripts");
|
||||
_scripts = (list ?? []).Select(s => new ScriptItem(
|
||||
s.Id, s.Name,
|
||||
DateTime.TryParse(s.Updated, out var dt)
|
||||
? dt.ToLocalTime().ToString("dd/MM HH:mm")
|
||||
: "")).ToList();
|
||||
await InvokeAsync(StateHasChanged);
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
private void OpenSave()
|
||||
{
|
||||
_saveName = _loadedName ?? "";
|
||||
_saveOpen = true;
|
||||
}
|
||||
|
||||
private void NewScript()
|
||||
{
|
||||
_loadedId = null;
|
||||
_loadedName = null;
|
||||
_saveName = "";
|
||||
_saveOpen = true;
|
||||
}
|
||||
|
||||
private async Task DoSave()
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(_saveName)) return;
|
||||
string code;
|
||||
try { code = await JS.InvokeAsync<string>("getEditorValue"); }
|
||||
catch { return; }
|
||||
|
||||
var resp = await Http.PostAsJsonAsync("/api/scripts",
|
||||
new { Id = _loadedId, Name = _saveName.Trim(), Content = code });
|
||||
|
||||
if (resp.IsSuccessStatusCode)
|
||||
{
|
||||
var saved = await resp.Content.ReadFromJsonAsync<ScriptDto>();
|
||||
_loadedId = saved?.Id;
|
||||
_loadedName = _saveName.Trim();
|
||||
_saveOpen = false;
|
||||
await RefreshScriptList();
|
||||
}
|
||||
}
|
||||
|
||||
private async Task SaveKeyDown(KeyboardEventArgs e)
|
||||
{
|
||||
if (e.Key == "Enter") await DoSave();
|
||||
if (e.Key == "Escape") _saveOpen = false;
|
||||
}
|
||||
|
||||
private async Task LoadScript(ScriptItem item)
|
||||
{
|
||||
try
|
||||
{
|
||||
var resp = await Http.GetFromJsonAsync<ScriptContentDto>($"/api/scripts/{item.Id}");
|
||||
if (resp is null) return;
|
||||
await JS.InvokeVoidAsync("setEditorValue", resp.Content);
|
||||
_loadedId = item.Id;
|
||||
_loadedName = item.Name;
|
||||
await InvokeAsync(StateHasChanged);
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
private async Task DeleteScript(int id)
|
||||
{
|
||||
await Http.DeleteAsync($"/api/scripts/{id}");
|
||||
if (_loadedId == id) { _loadedId = null; _loadedName = null; }
|
||||
await RefreshScriptList();
|
||||
}
|
||||
|
||||
record ScriptDto(int Id, string Name, string Updated);
|
||||
record ScriptContentDto(int Id, string Name, string Content, string Updated);
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
State.LockStateChanged -= OnStateChanged;
|
||||
State.SystemChanged -= OnStateChanged;
|
||||
Lang.LangChanged -= OnLangChanged;
|
||||
ScriptLog.LogChanged -= OnLogChanged;
|
||||
_cts?.Cancel();
|
||||
_cts?.Dispose();
|
||||
if (_hub != null) await _hub.DisposeAsync();
|
||||
}
|
||||
|
||||
record MeDto(string? UserId, string? Role);
|
||||
}
|
||||
|
||||
<style>
|
||||
.script-root {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
background: #27292b;
|
||||
}
|
||||
|
||||
.script-toolbar {
|
||||
flex-shrink: 0;
|
||||
min-height: 42px;
|
||||
background: #27292b;
|
||||
border-bottom: 1px solid #444;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 0 10px;
|
||||
}
|
||||
|
||||
/* ── body: sidebar + editor side by side ── */
|
||||
.script-body {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
}
|
||||
|
||||
/* ── file sidebar ── */
|
||||
.file-sidebar {
|
||||
width: 180px;
|
||||
flex-shrink: 0;
|
||||
background: #27292b;
|
||||
border-right: 1px solid #333;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
transition: width 0.18s ease;
|
||||
}
|
||||
.file-sidebar.collapsed {
|
||||
width: 0;
|
||||
border-right: none;
|
||||
}
|
||||
|
||||
.sidebar-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: 7px 10px;
|
||||
font-size: 10px;
|
||||
font-weight: 700;
|
||||
color: #555;
|
||||
letter-spacing: 0.8px;
|
||||
border-bottom: 1px solid #252525;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.sidebar-list {
|
||||
flex: 1;
|
||||
overflow-y: auto;
|
||||
overflow-x: hidden;
|
||||
}
|
||||
|
||||
.sidebar-empty {
|
||||
padding: 12px 10px;
|
||||
font-size: 11px;
|
||||
color: #9CA3AF;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.sidebar-item {
|
||||
position: relative;
|
||||
padding: 7px 28px 7px 10px;
|
||||
cursor: pointer;
|
||||
border-left: 2px solid transparent;
|
||||
transition: background 0.1s;
|
||||
}
|
||||
.sidebar-item:hover { background: #2f3235; }
|
||||
.sidebar-item.active {
|
||||
background: #27292b;
|
||||
border-left-color: #4a9eff;
|
||||
}
|
||||
|
||||
.sidebar-item-name {
|
||||
font-size: 12px;
|
||||
color: #F1F5F9;
|
||||
font-weight: 500;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
.sidebar-item.active .sidebar-item-name { color: #F1F5F9; font-weight: 700; }
|
||||
|
||||
.sidebar-item-meta {
|
||||
font-size: 10px;
|
||||
color: #9CA3AF;
|
||||
margin-top: 1px;
|
||||
}
|
||||
|
||||
.sidebar-del-wrap {
|
||||
position: absolute;
|
||||
right: 2px;
|
||||
top: 50%;
|
||||
transform: translateY(-50%);
|
||||
opacity: 0;
|
||||
transition: opacity 0.15s;
|
||||
}
|
||||
.sidebar-item:hover .sidebar-del-wrap { opacity: 1; }
|
||||
.sidebar-del-btn {
|
||||
color: #9CA3AF !important;
|
||||
padding: 2px !important;
|
||||
min-width: 0 !important;
|
||||
width: 22px !important;
|
||||
height: 22px !important;
|
||||
border-radius: 3px !important;
|
||||
}
|
||||
.sidebar-del-btn:hover { color: #e74c3c !important; }
|
||||
|
||||
.sidebar-toggle {
|
||||
flex-shrink: 0 !important;
|
||||
width: 14px !important;
|
||||
background: #27292b !important;
|
||||
border: none !important;
|
||||
border-left: 1px solid #2a2a2a !important;
|
||||
border-right: 1px solid #2a2a2a !important;
|
||||
color: #9CA3AF !important;
|
||||
cursor: pointer !important;
|
||||
padding: 0 !important;
|
||||
border-radius: 0 !important;
|
||||
min-width: 0 !important;
|
||||
height: 100% !important;
|
||||
transition: color 0.15s, background 0.15s !important;
|
||||
}
|
||||
.sidebar-toggle:hover { color: #4a9eff !important; background: #2f3235 !important; }
|
||||
|
||||
/* ── editor + output column ── */
|
||||
.editor-column {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.monaco-editor-host {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
width: 100%;
|
||||
border-bottom: 1px solid #333;
|
||||
}
|
||||
|
||||
.output-resize-handle {
|
||||
flex-shrink: 0;
|
||||
height: 5px;
|
||||
background: #27292b;
|
||||
cursor: row-resize;
|
||||
position: relative;
|
||||
transition: background 0.15s;
|
||||
}
|
||||
.output-resize-handle::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
left: 50%;
|
||||
top: 50%;
|
||||
transform: translate(-50%, -50%);
|
||||
width: 36px;
|
||||
height: 2px;
|
||||
border-radius: 1px;
|
||||
background: #2a2a2a;
|
||||
transition: background 0.15s;
|
||||
}
|
||||
.output-resize-handle:hover { background: #27292b; }
|
||||
.output-resize-handle:hover::after { background: #4a9eff; }
|
||||
|
||||
.output-pane {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
flex-shrink: 0;
|
||||
height: 210px;
|
||||
min-height: 80px;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.output-tabs {
|
||||
flex-shrink: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
background: #27292b;
|
||||
border-top: 1px solid #222;
|
||||
border-bottom: 1px solid #1a1a1a;
|
||||
}
|
||||
.tab-btn {
|
||||
padding: 5px 14px !important;
|
||||
font-size: 11px !important;
|
||||
color: #9CA3AF !important;
|
||||
border-bottom: 2px solid transparent !important;
|
||||
border-radius: 0 !important;
|
||||
min-height: 0 !important;
|
||||
height: auto !important;
|
||||
text-transform: none !important;
|
||||
font-weight: 400 !important;
|
||||
letter-spacing: 0 !important;
|
||||
line-height: 1.4 !important;
|
||||
transition: color 0.15s !important;
|
||||
user-select: none;
|
||||
}
|
||||
.tab-btn:hover { color: #9CA3AF !important; }
|
||||
.tab-on { color: #F1F5F9 !important; border-bottom-color: #4a9eff !important; }
|
||||
|
||||
.lf-bar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
margin-left: auto;
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
padding: 0 4px;
|
||||
}
|
||||
/* Compact MudTextField inside tab bar */
|
||||
.lf-field { margin: 0 !important; }
|
||||
.lf-field .mud-input-root-outlined { height: 22px !important; min-height: 22px !important; }
|
||||
.lf-field .mud-input-outlined { padding: 0 6px !important; height: 22px !important; font-size: 11px !important; font-family: Consolas, 'Cascadia Code', monospace; color: #9CA3AF !important; }
|
||||
.lf-field fieldset { top: 0 !important; border-color: #2a2a2a !important; }
|
||||
.lf-field .mud-input-outlined:focus { color: #F1F5F9 !important; }
|
||||
.lf-field:focus-within fieldset { border-color: #4a9eff !important; }
|
||||
.lf-field .mud-input-slot-helper-text { display: none; }
|
||||
.lf-field input::placeholder { color: #3a3a3a; font-size: 11px; }
|
||||
|
||||
.output-area {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
background: #27292b;
|
||||
font-family: Consolas, 'Cascadia Code', monospace;
|
||||
font-size: 11.5px;
|
||||
padding: 4px 0;
|
||||
overflow-y: auto;
|
||||
word-wrap: break-word;
|
||||
}
|
||||
|
||||
.log-line {
|
||||
padding: 1.5px 10px;
|
||||
line-height: 1.55;
|
||||
border-left: 2px solid transparent;
|
||||
transition: background 0.1s, border-color 0.1s;
|
||||
}
|
||||
.log-line:hover {
|
||||
background: rgba(255,255,255,0.025);
|
||||
border-left-color: #2a2a2a;
|
||||
}
|
||||
|
||||
.history-area { font-family: Consolas, monospace; }
|
||||
|
||||
.history-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
padding: 4px 10px;
|
||||
border-bottom: 1px solid #131313;
|
||||
transition: background 0.1s;
|
||||
}
|
||||
.history-row:hover { background: rgba(255,255,255,0.02); }
|
||||
.hist-time { color: #9CA3AF; font-size: 10px; min-width: 128px; font-family: Consolas, monospace; flex-shrink: 0; }
|
||||
.hist-user { color: #4a9eff; font-size: 11px; min-width: 80px; flex-shrink: 0; }
|
||||
.hist-name { color: #9CA3AF; font-size: 11px; flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.hist-chip { height: 18px !important; min-height: 18px !important; font-size: 10px !important; padding: 0 6px !important; flex-shrink: 0; }
|
||||
</style>
|
||||
Reference in New Issue
Block a user