using Microsoft.JSInterop; using System.Text.Json; using System.Text.Json.Serialization; namespace Shogi.UI.Shared; public class LocalStorage : ILocalStorage { private readonly JsonSerializerOptions jsonOptions; private readonly IJSRuntime jSRuntime; public LocalStorage(IJSRuntime jSRuntime) { this.jsonOptions = new JsonSerializerOptions(); this.jsonOptions.Converters.Add(new JsonStringEnumConverter()); this.jSRuntime = jSRuntime; } public ValueTask Set(string key, T value) { var serialized = JsonSerializer.Serialize(value); return this.jSRuntime.InvokeVoidAsync("localStorage.setItem", key, serialized); } public async ValueTask Get(string key) where T : struct { var value = await this.jSRuntime.InvokeAsync("localStorage.getItem", key); try { return JsonSerializer.Deserialize(value, this.jsonOptions); } catch (ArgumentNullException) { return default; } } public ValueTask Delete(string key) { return this.jSRuntime.InvokeVoidAsync("localStorage.removeItem", key); } } public interface ILocalStorage { ValueTask Delete(string key); ValueTask Get(string key) where T : struct; ValueTask Set(string key, T value); }