@rendermode @(new InteractiveWebAssemblyRenderMode(prerender: false)) @implements IAsyncDisposable @using Microsoft.AspNetCore.SignalR.Client @inject StateService State @inject LangService Lang @inject ScriptLogService ScriptLog @if (_loadedName != null) { @_loadedName } @Lang.T("Code sẽ được thực thi:", "Code to be executed:")
@_pendingCode
@Lang.T("Chạy", "Run")
SCRIPT Run @Lang.T("Hủy", "Cancel") @if (IsLockBlocked) { @Lang.T("Cần giữ lock để chạy script", "Lock required to run script") } else if (IsWorkflowMode) { Workflow } else if (IsManualMode) { Manual } @if (_hubOk) { Connected } else { Disconnect }
@if (_saveOpen) { } else { @if (_loadedName != null) { @_loadedName } @Lang.T("Lưu", "Save") } @Lang.Current.ToUpper()
@* ── Output / History tabs ── *@
Output @if (_isManager) { @Lang.T("Lịch sử", "History") @if (_historyLoading) { } } @{ var activeFilters = _historyTab ? _histFilters : _logFilters; }
@foreach (var lvl in _logLevels) { var badge = lvl.Badge; var color = lvl.Color; var isOn = activeFilters.Contains(badge); @badge } @if (!_historyTab) { } else { @if (_isManager) { } }
@if (!_historyTab) {
@foreach (var line in FilteredLines) {
@((MarkupString)line)
}
} else {
@if (_historyLoading) {
@Lang.T("Đang tải...", "Loading...")
} else if (_historyLogs.Count == 0) {
@Lang.T("Chưa có lịch sử.", "No history yet.")
} else { @foreach (var log in FilteredHistory) {
@log.StartedAt @if (_isManager) { @log.Username } @(string.IsNullOrEmpty(log.ScriptName) ? "(anonymous)" : log.ScriptName) @log.Status @if (!string.IsNullOrEmpty(log.Error)) { }
} }
}
@* end outputPane *@
@code { [Inject] HttpClient Http { get; set; } = default!; [Inject] IJSRuntime JS { get; set; } = default!; // ── Output filter ───────────────────────────────────────────────────────── private ElementReference _outputPanel; private readonly HashSet _logFilters = new(); private readonly HashSet _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 FilteredLines { get { var lines = (IEnumerable)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 FilteredHistory { get { var items = (IEnumerable)_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 _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>(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 _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("/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("(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("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("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>("/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("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(); _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($"/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); }