Skip to content

Commit

Permalink
Implement backend JS theme switch feature
Browse files Browse the repository at this point in the history
Co-Authored-By: Elia Schito <[email protected]>
  • Loading branch information
MassimilianoLattanzio and elia committed Apr 14, 2023
1 parent 474745a commit 0e0f322
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 0 deletions.
1 change: 1 addition & 0 deletions backend/app/assets/javascripts/spree/backend.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
//= require spree/backend/images/index
//= require spree/backend/images/upload
//= require spree/backend/locale_selection
//= require spree/backend/theme_selection
//= require spree/backend/navigation
//= require spree/backend/option_type_autocomplete
//= require spree/backend/option_value_picker
Expand Down
21 changes: 21 additions & 0 deletions backend/app/assets/javascripts/spree/backend/theme_selection.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
Spree.ready(function () {
const darkModePreference = window.matchMedia("(prefers-color-scheme: dark)")
const themeSelect = document.querySelector(".js-theme-selection")

const updateTheme = () => {
const theme = window.localStorage.getItem("theme") || "system"
const systemTheme = darkModePreference.matches ? "dark" : "light"
document.querySelector("html").dataset.theme = theme === "system" ? systemTheme : theme
return theme
}

themeSelect.value = updateTheme()
themeSelect.addEventListener("change", () => {
window.localStorage.setItem("theme", themeSelect.value)
updateTheme()
})

darkModePreference.addEventListener("change", () => {
updateTheme()
})
})

0 comments on commit 0e0f322

Please sign in to comment.