YamlFileComponent.razor 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. @using System.Collections.Specialized
  2. @using RackPeek.Domain.Persistence
  3. @using RackPeek.Domain.Persistence.Yaml
  4. @using RackPeek.Domain.Resources
  5. @using RackPeek.Domain.Resources.Hardware.AccessPoints
  6. @using RackPeek.Domain.Resources.Hardware.Desktops
  7. @using RackPeek.Domain.Resources.Hardware.Firewalls
  8. @using RackPeek.Domain.Resources.Hardware.Laptops
  9. @using RackPeek.Domain.Resources.Hardware.Servers
  10. @using RackPeek.Domain.Resources.Hardware.Switches
  11. @using RackPeek.Domain.Resources.Services
  12. @using RackPeek.Domain.Resources.SystemResources
  13. @using YamlDotNet.RepresentationModel
  14. @using YamlDotNet.Serialization
  15. @using YamlDotNet.Serialization.NamingConventions
  16. @using Router = RackPeek.Domain.Resources.Hardware.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 (!string.IsNullOrEmpty(_validationError))
  58. {
  59. <div class="mt-2 text-red-400 text-xs">
  60. @_validationError
  61. </div>
  62. }
  63. }
  64. else
  65. {
  66. <pre class="text-zinc-300 text-xs whitespace-pre-wrap">@_currentText</pre>
  67. }
  68. </div>
  69. <ConfirmModal
  70. IsOpen="_confirmDeleteOpen"
  71. IsOpenChanged="v => _confirmDeleteOpen = v"
  72. Title="Delete File"
  73. ConfirmText="Delete"
  74. ConfirmClass="bg-red-600 hover:bg-red-500"
  75. OnConfirm="DeleteFile"
  76. TestIdPrefix="File">>
  77. Are you sure you want to delete <strong>@Path</strong>?
  78. </ConfirmModal>
  79. @code {
  80. [Parameter, EditorRequired]
  81. public string Path { get; set; } = default!;
  82. [Parameter]
  83. public string Title { get; set; } = "Edit YAML";
  84. [Parameter]
  85. public EventCallback<string> OnDeleted { get; set; }
  86. bool _isEditing;
  87. bool _exists;
  88. bool _confirmDeleteOpen;
  89. string _currentText = "";
  90. string _editText = "";
  91. string? _validationError;
  92. protected override async Task OnParametersSetAsync()
  93. {
  94. await Load();
  95. }
  96. async Task Load()
  97. {
  98. _exists = await FileStore.ExistsAsync(Path);
  99. if (!_exists)
  100. return;
  101. _currentText = await FileStore.ReadAllTextAsync(Path);
  102. }
  103. void BeginEdit()
  104. {
  105. _editText = _currentText;
  106. _validationError = null;
  107. _isEditing = true;
  108. }
  109. void Cancel()
  110. {
  111. _isEditing = false;
  112. _validationError = null;
  113. }
  114. async Task Save()
  115. {
  116. if (!ValidateYamlRoundTrip(_editText, out var error))
  117. {
  118. _validationError = error;
  119. return;
  120. }
  121. await FileStore.WriteAllTextAsync(Path, _editText);
  122. await Resources.LoadAsync();
  123. _currentText = _editText;
  124. _isEditing = false;
  125. }
  126. void ConfirmDelete()
  127. {
  128. _confirmDeleteOpen = true;
  129. }
  130. async Task DeleteFile()
  131. {
  132. _confirmDeleteOpen = false;
  133. // if your store supports delete, call it here
  134. await FileStore.WriteAllTextAsync(Path, "");
  135. if (OnDeleted.HasDelegate)
  136. await OnDeleted.InvokeAsync(Path);
  137. }
  138. private bool ValidateYamlRoundTrip(string yaml, out string? error)
  139. {
  140. try
  141. {
  142. if (string.IsNullOrWhiteSpace(yaml))
  143. {
  144. error = "YAML is empty.";
  145. return false;
  146. }
  147. // ---------- DESERIALIZER (same as resource loader) ----------
  148. var deserializer = new DeserializerBuilder()
  149. .WithNamingConvention(CamelCaseNamingConvention.Instance)
  150. .WithCaseInsensitivePropertyMatching()
  151. .WithTypeConverter(new StorageSizeYamlConverter())
  152. .WithTypeDiscriminatingNodeDeserializer(options =>
  153. {
  154. options.AddKeyValueTypeDiscriminator<Resource>("kind", new Dictionary<string, Type>
  155. {
  156. { Server.KindLabel, typeof(Server) },
  157. { Switch.KindLabel, typeof(Switch) },
  158. { Firewall.KindLabel, typeof(Firewall) },
  159. { Router.KindLabel, typeof(Router) },
  160. { Desktop.KindLabel, typeof(Desktop) },
  161. { Laptop.KindLabel, typeof(Laptop) },
  162. { AccessPoint.KindLabel, typeof(AccessPoint) },
  163. { RackPeek.Domain.Resources.Hardware.UpsUnits.Ups.KindLabel, typeof(RackPeek.Domain.Resources.Hardware.UpsUnits.Ups) },
  164. { SystemResource.KindLabel, typeof(SystemResource) },
  165. { Service.KindLabel, typeof(Service) }
  166. });
  167. })
  168. .Build();
  169. var root = deserializer.Deserialize<YamlRoot>(yaml);
  170. if (root?.Resources == null)
  171. {
  172. error = "No resources section found.";
  173. return false;
  174. }
  175. // ---------- SERIALIZE AGAIN ----------
  176. var serializer = new SerializerBuilder()
  177. .WithNamingConvention(CamelCaseNamingConvention.Instance)
  178. .Build();
  179. var payload = new OrderedDictionary
  180. {
  181. ["resources"] = root.Resources
  182. };
  183. var roundTripYaml = serializer.Serialize(payload);
  184. // ---------- DESERIALIZE AGAIN ----------
  185. var root2 = deserializer.Deserialize<YamlRoot>(roundTripYaml);
  186. if (root2?.Resources == null)
  187. {
  188. error = "Round-trip serialization failed.";
  189. return false;
  190. }
  191. // ---------- DUPLICATE NAME CHECK ----------
  192. var dup = root2.Resources
  193. .GroupBy(r => r.Name, StringComparer.OrdinalIgnoreCase)
  194. .FirstOrDefault(g => g.Count() > 1);
  195. if (dup != null)
  196. {
  197. error = $"Duplicate resource name: '{dup.Key}'";
  198. return false;
  199. }
  200. error = null;
  201. return true;
  202. }
  203. catch (Exception ex)
  204. {
  205. error = $"YAML validation failed: {ex.Message}";
  206. return false;
  207. }
  208. }
  209. }