|
| 1 | +using System; |
| 2 | +using System.Collections.Generic; |
| 3 | +using System.IO; |
| 4 | +using System.Text.Json; |
| 5 | +using System.Windows.Controls; |
| 6 | + |
| 7 | +namespace DevTools.Helpers |
| 8 | +{ |
| 9 | + public class PageStateManager |
| 10 | + { |
| 11 | + private static readonly string StateFilePath = Path.Combine( |
| 12 | + Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), |
| 13 | + "DevTools", |
| 14 | + "page_states.json"); |
| 15 | + |
| 16 | + private static Dictionary<string, Dictionary<string, string>> _pageStates = new(); |
| 17 | + |
| 18 | + static PageStateManager() |
| 19 | + { |
| 20 | + LoadStates(); |
| 21 | + } |
| 22 | + |
| 23 | + private static void LoadStates() |
| 24 | + { |
| 25 | + try |
| 26 | + { |
| 27 | + if (File.Exists(StateFilePath)) |
| 28 | + { |
| 29 | + var json = File.ReadAllText(StateFilePath); |
| 30 | + _pageStates = JsonSerializer.Deserialize<Dictionary<string, Dictionary<string, string>>>(json) ?? new Dictionary<string, Dictionary<string, string>>(); |
| 31 | + } |
| 32 | + } |
| 33 | + catch |
| 34 | + { |
| 35 | + _pageStates = new Dictionary<string, Dictionary<string, string>>(); |
| 36 | + } |
| 37 | + } |
| 38 | + |
| 39 | + private static void SaveStates() |
| 40 | + { |
| 41 | + try |
| 42 | + { |
| 43 | + var directory = Path.GetDirectoryName(StateFilePath); |
| 44 | + if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory)) |
| 45 | + { |
| 46 | + Directory.CreateDirectory(directory); |
| 47 | + } |
| 48 | + |
| 49 | + var json = JsonSerializer.Serialize(_pageStates, new JsonSerializerOptions { WriteIndented = true }); |
| 50 | + File.WriteAllText(StateFilePath, json); |
| 51 | + } |
| 52 | + catch |
| 53 | + { |
| 54 | + } |
| 55 | + } |
| 56 | + |
| 57 | + public static void SavePageState(Page page, Dictionary<string, string> state) |
| 58 | + { |
| 59 | + var pageName = page.GetType().Name; |
| 60 | + _pageStates[pageName] = state; |
| 61 | + SaveStates(); |
| 62 | + } |
| 63 | + |
| 64 | + public static Dictionary<string, string>? GetPageState(Page page) |
| 65 | + { |
| 66 | + var pageName = page.GetType().Name; |
| 67 | + return _pageStates.TryGetValue(pageName, out var state) ? state : null; |
| 68 | + } |
| 69 | + |
| 70 | + public static void ClearPageState(Page page) |
| 71 | + { |
| 72 | + var pageName = page.GetType().Name; |
| 73 | + _pageStates.Remove(pageName); |
| 74 | + SaveStates(); |
| 75 | + } |
| 76 | + |
| 77 | + public static void ClearAllStates() |
| 78 | + { |
| 79 | + _pageStates.Clear(); |
| 80 | + SaveStates(); |
| 81 | + } |
| 82 | + } |
| 83 | +} |
0 commit comments