From 4eb5d222e083effe7d87bb3a30d2d64ca4094d75 Mon Sep 17 00:00:00 2001 From: Nick Hawke Date: Thu, 5 Sep 2024 20:08:50 -0400 Subject: Remember theme setting between page loads Previously, the theme setting would default to the device preference on each load. So, if a user preferred light theme for slskd despite having a dark device theme, they would need to toggle the theme on each page load. By saving the theme preference in localStorage, we can override the device default with the user's manual preference. --- src/web/src/components/App.jsx | 52 ++++++++++++++++++++++++++++-------------- 1 file changed, 35 insertions(+), 17 deletions(-) (limited to 'src') diff --git a/src/web/src/components/App.jsx b/src/web/src/components/App.jsx index 1580db8e..7796cb1c 100644 --- a/src/web/src/components/App.jsx +++ b/src/web/src/components/App.jsx @@ -136,18 +136,21 @@ class App extends Component { } componentDidMount() { - window - .matchMedia('(prefers-color-scheme: dark)') - .addEventListener( - 'change', - (event) => event.matches && this.setState({ theme: 'dark' }), - ); - window - .matchMedia('(prefers-color-scheme: light)') - .addEventListener( - 'change', - (event) => event.matches && this.setState({ theme: 'light' }), - ); + if (this.getSavedTheme() == null) { + window + .matchMedia('(prefers-color-scheme: dark)') + .addEventListener( + 'change', + (event) => event.matches && this.setState({ theme: 'dark' }), + ); + window + .matchMedia('(prefers-color-scheme: light)') + .addEventListener( + 'change', + (event) => event.matches && this.setState({ theme: 'light' }), + ); + + } this.init(); } @@ -185,6 +188,11 @@ class App extends Component { await appHub.start(); } + let savedTheme = this.getSavedTheme(); + if (savedTheme != null) { + this.setState({theme: savedTheme}); + } + this.setState({ error: false, }); @@ -197,6 +205,18 @@ class App extends Component { }); }; + getSavedTheme = () => { + return localStorage.getItem("slskd-theme"); + }; + + toggleTheme = () => { + this.setState((state) => { + let newTheme = state.theme === 'dark' ? 'light' : 'dark'; + localStorage.setItem("slskd-theme", newTheme); + return {theme: newTheme} + }) + }; + handleLogin = (username, password, rememberMe) => { this.setState( (previousState) => ({ @@ -238,9 +258,9 @@ class App extends Component { initialized, login, retriesExhausted, - theme = window.matchMedia('(prefers-color-scheme: dark)').matches + theme = this.getSavedTheme() || (window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' - : 'light', + : 'light'), } = this.state; const { pendingReconnect, @@ -384,9 +404,7 @@ class App extends Component { inverted > - this.setState({ theme: theme === 'dark' ? 'light' : 'dark' }) - } + onClick={() => this.toggleTheme()} > Theme -- cgit v1.2.3