diff --git a/pontoon/base/static/js/theme-switcher.js b/pontoon/base/static/js/theme-switcher.js index 5cd793e6c4..feba8d48a3 100644 --- a/pontoon/base/static/js/theme-switcher.js +++ b/pontoon/base/static/js/theme-switcher.js @@ -19,6 +19,17 @@ $(function () { .addClass(`${newTheme}-theme`); } + /* + Storing system theme setting in a cookie makes the setting available to the server. + That allows us to set the theme class already in the Django template, which (unlike + setting it on the client) prevents FOUC. + */ + function storeSystemTheme(systemTheme) { + document.cookie = `system_theme=${systemTheme}; path=/; max-age=${ + 60 * 60 * 24 * 365 + }; Secure`; + } + window .matchMedia('(prefers-color-scheme: dark)') .addEventListener('change', function (e) { @@ -26,13 +37,15 @@ $(function () { let userThemeSetting = $('body').data('theme'); if (userThemeSetting === 'system') { - applyTheme(e.matches ? 'dark' : 'light'); + const systemTheme = e.matches ? 'dark' : 'light'; + applyTheme(systemTheme); + storeSystemTheme(systemTheme); } }); - if ($('body').hasClass('system-theme')) { + if ($('body').data('theme') === 'system') { let systemTheme = getSystemTheme(); - $('body').removeClass('system-theme').addClass(`${systemTheme}-theme`); + storeSystemTheme(systemTheme); } $('.appearance .toggle-button button').click(function (e) { diff --git a/pontoon/base/templates/base.html b/pontoon/base/templates/base.html index 117fa90058..e89144c445 100644 --- a/pontoon/base/templates/base.html +++ b/pontoon/base/templates/base.html @@ -33,9 +33,9 @@ {% block content %} diff --git a/pontoon/base/templatetags/helpers.py b/pontoon/base/templatetags/helpers.py index 4507d91e5c..74dd0de541 100644 --- a/pontoon/base/templatetags/helpers.py +++ b/pontoon/base/templatetags/helpers.py @@ -37,13 +37,28 @@ def return_url(request): @library.global_function -def theme(user): +def user_theme(user): """Get user's theme or return 'dark' if user is not authenticated.""" if user.is_authenticated: return user.profile.theme return "dark" +@library.global_function +def theme_class(request): + """Get theme class name based on user preferences and system settings.""" + theme = "dark" + user = request.user + + if user.is_authenticated: + theme = user.profile.theme + + if theme == "system": + theme = request.COOKIES.get("system_theme", "dark") + + return f"{theme}-theme" + + @library.global_function def static(path): return staticfiles_storage.url(path) diff --git a/translate/public/translate.html b/translate/public/translate.html index ff50a3d79a..eb50047835 100644 --- a/translate/public/translate.html +++ b/translate/public/translate.html @@ -24,7 +24,7 @@ {% include "tracker.html" %} - +