11using System . Threading . Tasks ;
2- using Blazored . LocalStorage ;
32using Blazorise . Docs . Services ;
4- using Blazorise . Modules ;
53using Microsoft . AspNetCore . Components ;
4+ using Microsoft . AspNetCore . Http ;
5+ using Microsoft . JSInterop ;
66
77namespace Blazorise . Docs ;
88
99public partial class Routes
1010{
11+ private const string ThemeCookieName = "bdocs-theme" ;
12+ private const string SystemThemeCookieName = "bdocs-system" ;
13+ private bool jsReady ;
14+
1115 [ Inject ] private ThemeService ThemeService { get ; set ; }
12- [ Inject ] private IJSUtilitiesModule JSUtilitiesModule { get ; set ; }
13- [ Inject ] ILocalStorageService LocalStorage { get ; set ; }
16+ [ Inject ] private IHttpContextAccessor HttpContextAccessor { get ; set ; }
17+ [ Inject ] private IJSRuntime JSRuntime { get ; set ; }
1418
1519 protected override void OnInitialized ( )
1620 {
1721 ThemeService . ThemeChanged += OnThemeChanged ;
1822
23+ TryLoadThemeFromCookie ( ) ;
24+
1925 base . OnInitialized ( ) ;
2026 }
2127
2228 protected override async Task OnAfterRenderAsync ( bool firstRender )
2329 {
2430 if ( firstRender )
2531 {
26- var theme = await LocalStorage . GetItemAsync < string > ( "theme" ) ;
27- var systemIsDarkMode = await JSUtilitiesModule . IsSystemDarkMode ( ) ;
32+ var theme = await JSRuntime . InvokeAsync < string > ( "blazoriseDocs.theme.getStoredTheme" ) ;
33+ var systemIsDarkMode = await JSRuntime . InvokeAsync < bool > ( "blazoriseDocs.theme.isSystemDark" ) ;
34+
35+ jsReady = true ;
2836
2937 ThemeService . SetTheme ( theme , systemIsDarkMode ) ;
3038 }
@@ -39,17 +47,28 @@ public void Dispose()
3947
4048 async void OnThemeChanged ( object sender , string theme )
4149 {
42- if ( ThemeService . ShouldDark )
43- {
44- await JSUtilitiesModule . AddAttributeToBody ( "data-bs-theme" , "dark" ) ;
45- }
46- else
47- {
48- await JSUtilitiesModule . RemoveAttributeFromBody ( "data-bs-theme" ) ;
49- }
50+ if ( ! jsReady )
51+ return ;
5052
51- await LocalStorage . SetItemAsync ( "theme" , theme ) ;
53+ await JSRuntime . InvokeVoidAsync ( "blazoriseDocs. theme.save " , theme , ThemeService . SystemIsDarkMode ) ;
5254
5355 await InvokeAsync ( StateHasChanged ) ;
5456 }
57+
58+ private void TryLoadThemeFromCookie ( )
59+ {
60+ var httpContext = HttpContextAccessor . HttpContext ;
61+
62+ if ( httpContext is null )
63+ return ;
64+
65+ if ( httpContext . Request . Cookies . TryGetValue ( ThemeCookieName , out var themeFromCookie ) )
66+ {
67+ var systemIsDarkMode = httpContext . Request . Cookies . TryGetValue ( SystemThemeCookieName , out var systemCookie )
68+ && bool . TryParse ( systemCookie , out var parsedSystemDark )
69+ && parsedSystemDark ;
70+
71+ ThemeService . SetTheme ( themeFromCookie , systemIsDarkMode ) ;
72+ }
73+ }
5574}
0 commit comments