Skip to content

Commit

Permalink
[5.x] Save dark mode theme preference to local storage (#10140)
Browse files Browse the repository at this point in the history
  • Loading branch information
jasonvarga authored May 21, 2024
1 parent 730f05d commit f9bad98
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 2 deletions.
11 changes: 10 additions & 1 deletion resources/js/components/DarkModeToggle.vue
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,16 @@ export default {
methods: {
prefer(mode) {
this.preference = mode;
this.$preferences.set('theme', mode === 'auto' ? null : mode);
// Saving to user preference allows it to persist across browsers, whereas saving to local
// storage allows it to work before the user is authenticated, e.g. on the login screen.
if (mode === 'auto') {
this.$preferences.remove('theme');
localStorage.removeItem('statamic.theme');
} else {
this.$preferences.set('theme', mode);
localStorage.setItem('statamic.theme', mode);
}
}
}
}
Expand Down
3 changes: 2 additions & 1 deletion resources/views/partials/head.blade.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@

<script>
(function () {
let theme = '{{ $user?->preferredTheme() ?? "auto" }}';
let theme = {!! ($userTheme = $user?->preferredTheme()) ? "'".$userTheme."'" : "null" !!};
if (! theme) theme = localStorage.getItem('statamic.theme') ?? 'auto';
if (theme === 'auto' && window.matchMedia('(prefers-color-scheme: dark)').matches) theme = 'dark';
if (theme === 'dark') document.documentElement.classList.add('dark');
})();
Expand Down

0 comments on commit f9bad98

Please sign in to comment.