| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333 |
- @using System.Collections.Specialized
- @using System.Text
- @using YamlDotNet.Core
- @using RackPeek.Domain.Persistence
- @using RackPeek.Domain.Persistence.Yaml
- @using RackPeek.Domain.Resources
- @using RackPeek.Domain.Resources.AccessPoints
- @using RackPeek.Domain.Resources.Desktops
- @using RackPeek.Domain.Resources.Firewalls
- @using RackPeek.Domain.Resources.Laptops
- @using RackPeek.Domain.Resources.Servers
- @using RackPeek.Domain.Resources.Switches
- @using RackPeek.Domain.Resources.SystemResources
- @using YamlDotNet.Serialization
- @using YamlDotNet.Serialization.NamingConventions
- @using Router = RackPeek.Domain.Resources.Routers.Router
- @inject ITextFileStore FileStore
- @inject IResourceCollection Resources
- <div class="border border-zinc-800 rounded p-4 bg-zinc-900">
- <div class="flex justify-between items-center mb-3">
- <div class="text-zinc-100">
- @Title
- </div>
- <div class="flex gap-3 text-xs">
- @if (!_isEditing)
- {
- <button class="text-zinc-400 hover:text-zinc-200"
- @onclick="BeginEdit">
- Edit
- </button>
- }
- else
- {
- <button class="text-emerald-400 hover:text-emerald-300"
- @onclick="Save">
- Save
- </button>
- <button class="text-zinc-500 hover:text-zinc-300"
- @onclick="Cancel">
- Cancel
- </button>
- }
- </div>
- </div>
- @if (!_exists)
- {
- <div class="text-red-400 text-sm">
- File does not exist.
- </div>
- }
- else if (_isEditing)
- {
- <textarea class="w-full input font-mono text-xs"
- style="min-height: 40rem"
- @bind="_editText">
- </textarea>
- @if (_error is not null)
- {
- <div class="mt-3 border border-red-500/40 bg-red-500/10 rounded p-3"
- data-testid="yaml-file-error"
- role="alert">
- <div class="flex items-start gap-2">
- <svg xmlns="http://www.w3.org/2000/svg" class="w-5 h-5 flex-shrink-0 text-red-400 mt-0.5"
- fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
- <path stroke-linecap="round" stroke-linejoin="round"
- d="M12 9v3.75m9-.75a9 9 0 11-18 0 9 9 0 0118 0zm-9 3.75h.008v.008H12v-.008z"/>
- </svg>
- <div class="min-w-0 flex-1">
- <div class="text-red-400 text-sm font-semibold">
- @_error.Headline
- </div>
- @if (_error.Line is long line)
- {
- <div class="text-zinc-400 text-xs mt-1">
- Line @line@(_error.Column is long col ? $", column {col}" : "")
- </div>
- }
- @if (!string.IsNullOrEmpty(_error.Snippet))
- {
- <pre class="mt-2 p-2 rounded bg-zinc-950 border border-zinc-800 text-xs overflow-x-auto text-zinc-300"
- data-testid="yaml-file-error-snippet">@_error.Snippet</pre>
- }
- </div>
- </div>
- </div>
- }
- }
- else
- {
- <pre class="text-zinc-300 text-xs whitespace-pre-wrap">@_currentText</pre>
- }
- </div>
- <ConfirmModal
- IsOpen="_confirmDeleteOpen"
- IsOpenChanged="v => _confirmDeleteOpen = v"
- Title="Delete File"
- ConfirmText="Delete"
- ConfirmClass="bg-red-600 hover:bg-red-500"
- OnConfirm="DeleteFile"
- TestIdPrefix="File">>
- Are you sure you want to delete <strong>@Path</strong>?
- </ConfirmModal>
- @code {
- [Parameter] [EditorRequired] public string Path { get; set; } = default!;
- [Parameter] public string Title { get; set; } = "Edit YAML";
- [Parameter] public EventCallback<string> OnDeleted { get; set; }
- bool _isEditing;
- bool _exists;
- bool _confirmDeleteOpen;
- string _currentText = "";
- string _editText = "";
- YamlEditError? _error;
- protected override async Task OnParametersSetAsync()
- {
- await Load();
- }
- async Task Load()
- {
- _exists = await FileStore.ExistsAsync(Path);
- if (!_exists)
- return;
- _currentText = await FileStore.ReadAllTextAsync(Path);
- }
- void BeginEdit()
- {
- _editText = _currentText;
- _error = null;
- _isEditing = true;
- }
- void Cancel()
- {
- _isEditing = false;
- _error = null;
- }
- async Task Save()
- {
- if (!ValidateYamlRoundTrip(_editText, out var err))
- {
- _error = err;
- return;
- }
- await FileStore.WriteAllTextAsync(Path, _editText);
- await Resources.LoadAsync();
- _currentText = _editText;
- _isEditing = false;
- }
- void ConfirmDelete()
- {
- _confirmDeleteOpen = true;
- }
- async Task DeleteFile()
- {
- _confirmDeleteOpen = false;
- // if your store supports delete, call it here
- await FileStore.WriteAllTextAsync(Path, "");
- if (OnDeleted.HasDelegate)
- await OnDeleted.InvokeAsync(Path);
- }
- private bool ValidateYamlRoundTrip(string yaml, out YamlEditError? error)
- {
- try
- {
- if (string.IsNullOrWhiteSpace(yaml))
- {
- error = new YamlEditError("YAML is empty.", null, null, null);
- return false;
- }
- // ---------- DESERIALIZER (same as resource loader) ----------
- var deserializer = new DeserializerBuilder()
- .WithNamingConvention(CamelCaseNamingConvention.Instance)
- .WithCaseInsensitivePropertyMatching()
- .WithTypeConverter(new StorageSizeYamlConverter())
- .WithTypeDiscriminatingNodeDeserializer(options =>
- {
- options.AddKeyValueTypeDiscriminator<Resource>("kind", new Dictionary<string, Type>
- {
- { Server.KindLabel, typeof(Server) },
- { Switch.KindLabel, typeof(Switch) },
- { Firewall.KindLabel, typeof(Firewall) },
- { Router.KindLabel, typeof(Router) },
- { Desktop.KindLabel, typeof(Desktop) },
- { Laptop.KindLabel, typeof(Laptop) },
- { AccessPoint.KindLabel, typeof(AccessPoint) },
- { RackPeek.Domain.Resources.UpsUnits.Ups.KindLabel, typeof(RackPeek.Domain.Resources.UpsUnits.Ups) },
- { SystemResource.KindLabel, typeof(SystemResource) },
- { Service.KindLabel, typeof(Service) }
- });
- })
- .Build();
- var root = deserializer.Deserialize<YamlRoot>(yaml);
- if (root?.Resources == null)
- {
- error = new YamlEditError("No resources section found.", null, null, null);
- return false;
- }
- // ---------- SERIALIZE AGAIN ----------
- var serializer = new SerializerBuilder()
- .WithNamingConvention(CamelCaseNamingConvention.Instance)
- .Build();
- var payload = new OrderedDictionary
- {
- ["resources"] = root.Resources
- };
- var roundTripYaml = serializer.Serialize(payload);
- // ---------- DESERIALIZE AGAIN ----------
- var root2 = deserializer.Deserialize<YamlRoot>(roundTripYaml);
- if (root2?.Resources == null)
- {
- error = new YamlEditError("Round-trip serialization failed.", null, null, null);
- return false;
- }
- // ---------- DUPLICATE NAME CHECK ----------
- var dup = root2.Resources
- .GroupBy(r => r.Name, StringComparer.OrdinalIgnoreCase)
- .FirstOrDefault(g => g.Count() > 1);
- if (dup != null)
- {
- error = new YamlEditError($"Duplicate resource name: '{dup.Key}'", null, null, null);
- return false;
- }
- error = null;
- return true;
- }
- catch (Exception ex)
- {
- error = BuildEditError(ex, yaml);
- return false;
- }
- }
- private static YamlEditError BuildEditError(Exception ex, string yaml)
- {
- YamlException? ye = FindYamlException(ex);
- if (ye is not null)
- {
- long? line = ye.Start.Line > 0 ? ye.Start.Line : null;
- long? col = ye.Start.Column > 0 ? ye.Start.Column : null;
- return new YamlEditError(
- $"YAML invalid: {FirstLine(ye.Message)}",
- line,
- col,
- line is long l ? ExtractSnippet(yaml, (int)l) : null);
- }
- return new YamlEditError($"YAML validation failed: {FirstLine(ex.Message)}", null, null, null);
- }
- private static YamlException? FindYamlException(Exception? ex)
- {
- while (ex is not null)
- {
- if (ex is YamlException ye) return ye;
- ex = ex.InnerException;
- }
- return null;
- }
- private static string FirstLine(string message)
- {
- if (string.IsNullOrEmpty(message)) return string.Empty;
- var nl = message.IndexOf('\n');
- return nl < 0 ? message.Trim() : message[..nl].Trim();
- }
- private static string ExtractSnippet(string yaml, int lineNumber, int context = 2)
- {
- var lines = yaml.Replace("\r\n", "\n").Split('\n');
- if (lineNumber < 1 || lineNumber > lines.Length) return string.Empty;
- var start = Math.Max(1, lineNumber - context);
- var end = Math.Min(lines.Length, lineNumber + context);
- var sb = new StringBuilder();
- for (int i = start; i <= end; i++)
- {
- sb.Append(i == lineNumber ? "→ " : " ")
- .Append(i.ToString().PadLeft(4))
- .Append(" ")
- .Append(lines[i - 1]);
- if (i < end) sb.Append('\n');
- }
- return sb.ToString();
- }
- private sealed record YamlEditError(string Headline, long? Line, long? Column, string? Snippet);
- }
|