YamlFileComponent.razor 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  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. await Resources.LoadAsync();
  145. _currentText = _editText;
  146. _isEditing = false;
  147. }
  148. void ConfirmDelete()
  149. {
  150. _confirmDeleteOpen = true;
  151. }
  152. async Task DeleteFile()
  153. {
  154. _confirmDeleteOpen = false;
  155. // if your store supports delete, call it here
  156. await FileStore.WriteAllTextAsync(Path, "");
  157. if (OnDeleted.HasDelegate)
  158. await OnDeleted.InvokeAsync(Path);
  159. }
  160. private bool ValidateYamlRoundTrip(string yaml, out YamlEditError? error)
  161. {
  162. try
  163. {
  164. if (string.IsNullOrWhiteSpace(yaml))
  165. {
  166. error = new YamlEditError("YAML is empty.", null, null, null);
  167. return false;
  168. }
  169. // ---------- DESERIALIZER (same as resource loader) ----------
  170. var deserializer = new DeserializerBuilder()
  171. .WithNamingConvention(CamelCaseNamingConvention.Instance)
  172. .WithCaseInsensitivePropertyMatching()
  173. .WithTypeConverter(new StorageSizeYamlConverter())
  174. .WithTypeDiscriminatingNodeDeserializer(options =>
  175. {
  176. options.AddKeyValueTypeDiscriminator<Resource>("kind", new Dictionary<string, Type>
  177. {
  178. { Server.KindLabel, typeof(Server) },
  179. { Switch.KindLabel, typeof(Switch) },
  180. { Firewall.KindLabel, typeof(Firewall) },
  181. { Router.KindLabel, typeof(Router) },
  182. { Desktop.KindLabel, typeof(Desktop) },
  183. { Laptop.KindLabel, typeof(Laptop) },
  184. { AccessPoint.KindLabel, typeof(AccessPoint) },
  185. { RackPeek.Domain.Resources.UpsUnits.Ups.KindLabel, typeof(RackPeek.Domain.Resources.UpsUnits.Ups) },
  186. { SystemResource.KindLabel, typeof(SystemResource) },
  187. { Service.KindLabel, typeof(Service) }
  188. });
  189. })
  190. .Build();
  191. var root = deserializer.Deserialize<YamlRoot>(yaml);
  192. if (root?.Resources == null)
  193. {
  194. error = new YamlEditError("No resources section found.", null, null, null);
  195. return false;
  196. }
  197. // ---------- SERIALIZE AGAIN ----------
  198. var serializer = new SerializerBuilder()
  199. .WithNamingConvention(CamelCaseNamingConvention.Instance)
  200. .Build();
  201. var payload = new OrderedDictionary
  202. {
  203. ["resources"] = root.Resources
  204. };
  205. var roundTripYaml = serializer.Serialize(payload);
  206. // ---------- DESERIALIZE AGAIN ----------
  207. var root2 = deserializer.Deserialize<YamlRoot>(roundTripYaml);
  208. if (root2?.Resources == null)
  209. {
  210. error = new YamlEditError("Round-trip serialization failed.", null, null, null);
  211. return false;
  212. }
  213. // ---------- DUPLICATE NAME CHECK ----------
  214. var dup = root2.Resources
  215. .GroupBy(r => r.Name, StringComparer.OrdinalIgnoreCase)
  216. .FirstOrDefault(g => g.Count() > 1);
  217. if (dup != null)
  218. {
  219. error = new YamlEditError($"Duplicate resource name: '{dup.Key}'", null, null, null);
  220. return false;
  221. }
  222. error = null;
  223. return true;
  224. }
  225. catch (Exception ex)
  226. {
  227. error = BuildEditError(ex, yaml);
  228. return false;
  229. }
  230. }
  231. private static YamlEditError BuildEditError(Exception ex, string yaml)
  232. {
  233. YamlException? ye = FindYamlException(ex);
  234. if (ye is not null)
  235. {
  236. long? line = ye.Start.Line > 0 ? ye.Start.Line : null;
  237. long? col = ye.Start.Column > 0 ? ye.Start.Column : null;
  238. return new YamlEditError(
  239. $"YAML invalid: {FirstLine(ye.Message)}",
  240. line,
  241. col,
  242. line is long l ? ExtractSnippet(yaml, (int)l) : null);
  243. }
  244. return new YamlEditError($"YAML validation failed: {FirstLine(ex.Message)}", null, null, null);
  245. }
  246. private static YamlException? FindYamlException(Exception? ex)
  247. {
  248. while (ex is not null)
  249. {
  250. if (ex is YamlException ye) return ye;
  251. ex = ex.InnerException;
  252. }
  253. return null;
  254. }
  255. private static string FirstLine(string message)
  256. {
  257. if (string.IsNullOrEmpty(message)) return string.Empty;
  258. var nl = message.IndexOf('\n');
  259. return nl < 0 ? message.Trim() : message[..nl].Trim();
  260. }
  261. private static string ExtractSnippet(string yaml, int lineNumber, int context = 2)
  262. {
  263. var lines = yaml.Replace("\r\n", "\n").Split('\n');
  264. if (lineNumber < 1 || lineNumber > lines.Length) return string.Empty;
  265. var start = Math.Max(1, lineNumber - context);
  266. var end = Math.Min(lines.Length, lineNumber + context);
  267. var sb = new StringBuilder();
  268. for (int i = start; i <= end; i++)
  269. {
  270. sb.Append(i == lineNumber ? "→ " : " ")
  271. .Append(i.ToString().PadLeft(4))
  272. .Append(" ")
  273. .Append(lines[i - 1]);
  274. if (i < end) sb.Append('\n');
  275. }
  276. return sb.ToString();
  277. }
  278. private sealed record YamlEditError(string Headline, long? Line, long? Column, string? Snippet);
  279. }