YamlFileComponent.razor 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  1. @using System.Collections.Specialized
  2. @using System.Text
  3. @using YamlDotNet.Core
  4. @using RackPeek.Domain.Persistence
  5. @using RackPeek.Domain.Persistence.Yaml
  6. @using RackPeek.Domain.Resources
  7. @using RackPeek.Domain.Resources.AccessPoints
  8. @using RackPeek.Domain.Resources.Desktops
  9. @using RackPeek.Domain.Resources.Firewalls
  10. @using RackPeek.Domain.Resources.Laptops
  11. @using RackPeek.Domain.Resources.Servers
  12. @using RackPeek.Domain.Resources.Switches
  13. @using RackPeek.Domain.Resources.SystemResources
  14. @using YamlDotNet.Serialization
  15. @using YamlDotNet.Serialization.NamingConventions
  16. @using Router = RackPeek.Domain.Resources.Routers.Router
  17. @inject ITextFileStore FileStore
  18. @inject IResourceCollection Resources
  19. <div class="border border-zinc-800 rounded p-4 bg-zinc-900">
  20. <div class="flex justify-between items-center mb-3">
  21. <div class="text-zinc-100">
  22. @Title
  23. </div>
  24. <div class="flex gap-3 text-xs">
  25. @if (!_isEditing)
  26. {
  27. <button class="text-zinc-400 hover:text-zinc-200"
  28. @onclick="BeginEdit">
  29. Edit
  30. </button>
  31. }
  32. else
  33. {
  34. <button class="text-emerald-400 hover:text-emerald-300"
  35. @onclick="Save">
  36. Save
  37. </button>
  38. <button class="text-zinc-500 hover:text-zinc-300"
  39. @onclick="Cancel">
  40. Cancel
  41. </button>
  42. }
  43. </div>
  44. </div>
  45. @if (!_exists)
  46. {
  47. <div class="text-red-400 text-sm">
  48. File does not exist.
  49. </div>
  50. }
  51. else if (_isEditing)
  52. {
  53. <textarea class="w-full input font-mono text-xs"
  54. style="min-height: 40rem"
  55. @bind="_editText">
  56. </textarea>
  57. @if (_error is not null)
  58. {
  59. <div class="mt-3 border border-red-500/40 bg-red-500/10 rounded p-3"
  60. data-testid="yaml-file-error"
  61. role="alert">
  62. <div class="flex items-start gap-2">
  63. <svg xmlns="http://www.w3.org/2000/svg" class="w-5 h-5 flex-shrink-0 text-red-400 mt-0.5"
  64. fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
  65. <path stroke-linecap="round" stroke-linejoin="round"
  66. d="M12 9v3.75m9-.75a9 9 0 11-18 0 9 9 0 0118 0zm-9 3.75h.008v.008H12v-.008z"/>
  67. </svg>
  68. <div class="min-w-0 flex-1">
  69. <div class="text-red-400 text-sm font-semibold">
  70. @_error.Headline
  71. </div>
  72. @if (_error.Line is long line)
  73. {
  74. <div class="text-zinc-400 text-xs mt-1">
  75. Line @line@(_error.Column is long col ? $", column {col}" : "")
  76. </div>
  77. }
  78. @if (!string.IsNullOrEmpty(_error.Snippet))
  79. {
  80. <pre class="mt-2 p-2 rounded bg-zinc-950 border border-zinc-800 text-xs overflow-x-auto text-zinc-300"
  81. data-testid="yaml-file-error-snippet">@_error.Snippet</pre>
  82. }
  83. </div>
  84. </div>
  85. </div>
  86. }
  87. }
  88. else
  89. {
  90. <pre class="text-zinc-300 text-xs whitespace-pre-wrap"
  91. data-testid="yaml-file-content">@_currentText</pre>
  92. }
  93. </div>
  94. <ConfirmModal
  95. IsOpen="_confirmDeleteOpen"
  96. IsOpenChanged="v => _confirmDeleteOpen = v"
  97. Title="Delete File"
  98. ConfirmText="Delete"
  99. ConfirmClass="bg-red-600 hover:bg-red-500"
  100. OnConfirm="DeleteFile"
  101. TestIdPrefix="File">>
  102. Are you sure you want to delete <strong>@Path</strong>?
  103. </ConfirmModal>
  104. @code {
  105. [Parameter] [EditorRequired] public string Path { get; set; } = default!;
  106. [Parameter] public string Title { get; set; } = "Edit YAML";
  107. [Parameter] public EventCallback<string> OnDeleted { get; set; }
  108. bool _isEditing;
  109. bool _exists;
  110. bool _confirmDeleteOpen;
  111. string _currentText = "";
  112. string _editText = "";
  113. YamlEditError? _error;
  114. protected override async Task OnParametersSetAsync()
  115. {
  116. await Load();
  117. }
  118. async Task Load()
  119. {
  120. _exists = await FileStore.ExistsAsync(Path);
  121. if (!_exists)
  122. return;
  123. _currentText = await FileStore.ReadAllTextAsync(Path);
  124. }
  125. void BeginEdit()
  126. {
  127. _editText = _currentText;
  128. _error = null;
  129. _isEditing = true;
  130. }
  131. void Cancel()
  132. {
  133. _isEditing = false;
  134. _error = null;
  135. }
  136. async Task Save()
  137. {
  138. if (!ValidateYamlRoundTrip(_editText, out var err))
  139. {
  140. _error = err;
  141. return;
  142. }
  143. await FileStore.WriteAllTextAsync(Path, _editText);
  144. try
  145. {
  146. await Resources.LoadAsync();
  147. }
  148. catch (RackPeek.Domain.Helpers.ConfigLoadException ex)
  149. {
  150. // The edit was saved but the app still cannot read it. Report it here
  151. // rather than tearing down the circuit — this editor is the repair tool.
  152. _error = new YamlEditError(ex.Message, null, null, null);
  153. _currentText = _editText;
  154. return;
  155. }
  156. _currentText = _editText;
  157. _isEditing = false;
  158. }
  159. void ConfirmDelete()
  160. {
  161. _confirmDeleteOpen = true;
  162. }
  163. async Task DeleteFile()
  164. {
  165. _confirmDeleteOpen = false;
  166. // if your store supports delete, call it here
  167. await FileStore.WriteAllTextAsync(Path, "");
  168. if (OnDeleted.HasDelegate)
  169. await OnDeleted.InvokeAsync(Path);
  170. }
  171. private bool ValidateYamlRoundTrip(string yaml, out YamlEditError? error)
  172. {
  173. try
  174. {
  175. if (string.IsNullOrWhiteSpace(yaml))
  176. {
  177. error = new YamlEditError("YAML is empty.", null, null, null);
  178. return false;
  179. }
  180. // ---------- DESERIALIZER (same as resource loader) ----------
  181. var deserializer = new DeserializerBuilder()
  182. .WithNamingConvention(CamelCaseNamingConvention.Instance)
  183. .WithCaseInsensitivePropertyMatching()
  184. .WithTypeConverter(new StorageSizeYamlConverter())
  185. .WithTypeDiscriminatingNodeDeserializer(options =>
  186. {
  187. options.AddKeyValueTypeDiscriminator<Resource>("kind", new Dictionary<string, Type>
  188. {
  189. { Server.KindLabel, typeof(Server) },
  190. { Switch.KindLabel, typeof(Switch) },
  191. { Firewall.KindLabel, typeof(Firewall) },
  192. { Router.KindLabel, typeof(Router) },
  193. { Desktop.KindLabel, typeof(Desktop) },
  194. { Laptop.KindLabel, typeof(Laptop) },
  195. { AccessPoint.KindLabel, typeof(AccessPoint) },
  196. { RackPeek.Domain.Resources.UpsUnits.Ups.KindLabel, typeof(RackPeek.Domain.Resources.UpsUnits.Ups) },
  197. { SystemResource.KindLabel, typeof(SystemResource) },
  198. { Service.KindLabel, typeof(Service) }
  199. });
  200. })
  201. .Build();
  202. var root = deserializer.Deserialize<YamlRoot>(yaml);
  203. if (root?.Resources == null)
  204. {
  205. error = new YamlEditError("No resources section found.", null, null, null);
  206. return false;
  207. }
  208. // ---------- SERIALIZE AGAIN ----------
  209. var serializer = new SerializerBuilder()
  210. .WithNamingConvention(CamelCaseNamingConvention.Instance)
  211. .Build();
  212. var payload = new OrderedDictionary
  213. {
  214. ["resources"] = root.Resources
  215. };
  216. var roundTripYaml = serializer.Serialize(payload);
  217. // ---------- DESERIALIZE AGAIN ----------
  218. var root2 = deserializer.Deserialize<YamlRoot>(roundTripYaml);
  219. if (root2?.Resources == null)
  220. {
  221. error = new YamlEditError("Round-trip serialization failed.", null, null, null);
  222. return false;
  223. }
  224. // ---------- DUPLICATE NAME CHECK ----------
  225. var dup = root2.Resources
  226. .GroupBy(r => r.Name, StringComparer.OrdinalIgnoreCase)
  227. .FirstOrDefault(g => g.Count() > 1);
  228. if (dup != null)
  229. {
  230. error = new YamlEditError($"Duplicate resource name: '{dup.Key}'", null, null, null);
  231. return false;
  232. }
  233. error = null;
  234. return true;
  235. }
  236. catch (Exception ex)
  237. {
  238. error = BuildEditError(ex, yaml);
  239. return false;
  240. }
  241. }
  242. private static YamlEditError BuildEditError(Exception ex, string yaml)
  243. {
  244. YamlException? ye = FindYamlException(ex);
  245. if (ye is not null)
  246. {
  247. long? line = ye.Start.Line > 0 ? ye.Start.Line : null;
  248. long? col = ye.Start.Column > 0 ? ye.Start.Column : null;
  249. return new YamlEditError(
  250. $"YAML invalid: {FirstLine(ye.Message)}",
  251. line,
  252. col,
  253. line is long l ? ExtractSnippet(yaml, (int)l) : null);
  254. }
  255. return new YamlEditError($"YAML validation failed: {FirstLine(ex.Message)}", null, null, null);
  256. }
  257. private static YamlException? FindYamlException(Exception? ex)
  258. {
  259. while (ex is not null)
  260. {
  261. if (ex is YamlException ye) return ye;
  262. ex = ex.InnerException;
  263. }
  264. return null;
  265. }
  266. private static string FirstLine(string message)
  267. {
  268. if (string.IsNullOrEmpty(message)) return string.Empty;
  269. var nl = message.IndexOf('\n');
  270. return nl < 0 ? message.Trim() : message[..nl].Trim();
  271. }
  272. private static string ExtractSnippet(string yaml, int lineNumber, int context = 2)
  273. {
  274. var lines = yaml.Replace("\r\n", "\n").Split('\n');
  275. if (lineNumber < 1 || lineNumber > lines.Length) return string.Empty;
  276. var start = Math.Max(1, lineNumber - context);
  277. var end = Math.Min(lines.Length, lineNumber + context);
  278. var sb = new StringBuilder();
  279. for (int i = start; i <= end; i++)
  280. {
  281. sb.Append(i == lineNumber ? "→ " : " ")
  282. .Append(i.ToString().PadLeft(4))
  283. .Append(" ")
  284. .Append(lines[i - 1]);
  285. if (i < end) sb.Append('\n');
  286. }
  287. return sb.ToString();
  288. }
  289. private sealed record YamlEditError(string Headline, long? Line, long? Column, string? Snippet);
  290. }