Spaces:
Sleeping
Sleeping
File size: 1,161 Bytes
6f32ae8 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | using Microsoft.JSInterop;
namespace BlazorWebAssembly.Services
{
public class ThemeService
{
private readonly IJSRuntime _jsRuntime;
private string _currentTheme = "light";
public event Action<string>? OnThemeChanged;
public ThemeService(IJSRuntime jsRuntime)
{
_jsRuntime = jsRuntime;
}
public string CurrentTheme => _currentTheme;
public async Task InitializeAsync()
{
var savedTheme = await _jsRuntime.InvokeAsync<string>("localStorage.getItem", "app-theme");
if (!string.IsNullOrEmpty(savedTheme))
{
await SetThemeAsync(savedTheme);
}
else
{
await SetThemeAsync("light");
}
}
public async Task SetThemeAsync(string theme)
{
_currentTheme = theme;
await _jsRuntime.InvokeVoidAsync("localStorage.setItem", "app-theme", theme);
await _jsRuntime.InvokeVoidAsync("document.documentElement.setAttribute", "data-theme", theme);
OnThemeChanged?.Invoke(theme);
}
}
}
|