From 96ca0fef8fb20e8e197bee820741c85914a0f9e1 Mon Sep 17 00:00:00 2001 From: Antonio De Lucreziis Date: Wed, 14 Sep 2022 14:55:42 +0200 Subject: [PATCH] Added localstorage support --- src/main.jsx | 18 +++++++++--------- src/utils.jsx | 18 ++++++++++++++++++ 2 files changed, 27 insertions(+), 9 deletions(-) diff --git a/src/main.jsx b/src/main.jsx index e82b31c..adb197c 100644 --- a/src/main.jsx +++ b/src/main.jsx @@ -10,6 +10,7 @@ import { Icon } from './components/Icon.jsx' import { Popup } from './components/Popup.jsx' import { Toolbar } from './components/Toolbar.jsx' import { OptionBar } from './components/OptionBar.jsx' +import { usePersistentState } from './utils.jsx' window._ = _ window.dataBuffer = {} @@ -68,15 +69,15 @@ async function loadEventi(ids) { const App = ({}) => { // Data Sources - const [source, setSource] = useState('magistrale') + const [source, setSource] = usePersistentState('orario.source', 'magistrale') const [eventi, setEventi] = useState([]) // View Modes - const [mode, setMode] = useState(MODE_COURSE) + const [mode, setMode] = usePersistentState('orario.mode', MODE_COURSE) // Selection - const [selectedCourses, setSelectedCourses] = useState([]) - const [hideOtherCourses, setHideOtherCourses] = useState(false) + const [selectedCourses, setSelectedCourses] = usePersistentState('orario.selection', []) + const [hideOtherCourses, setHideOtherCourses] = usePersistentState('orario.hide-other', false) // Menus const [helpVisible, setHelpVisible] = useState(false) @@ -99,19 +100,18 @@ const App = ({}) => { if ( selectedCourses.length === 0 || - selectedCourses.filter(id => groupIds.has(id)).length === 0 + (eventi.length > 0 && selectedCourses.filter(id => groupIds.has(id)).length === 0) ) { setHideOtherCourses(false) } }, [eventi, selectedCourses.length]) - const [theme, setTheme] = useState( - localStorage.getItem('theme') ?? - (window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light') + const [theme, setTheme] = usePersistentState( + 'orario.theme', + window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light' ) document.body.classList.toggle('dark-mode', theme === 'dark') - localStorage.setItem('theme', theme) return ( <> diff --git a/src/utils.jsx b/src/utils.jsx index 242939d..48fcf14 100644 --- a/src/utils.jsx +++ b/src/utils.jsx @@ -1,5 +1,7 @@ // Calendar +import { useEffect, useState } from 'preact/hooks' + export const WEEK_DAYS = [ 'Domenica', 'Lunedì', @@ -53,3 +55,19 @@ export const withClasses = classes => .filter(([, value]) => value) .map(([key]) => key) .join(' ') + +// Hooks + +export const usePersistentState = (key, initialValue) => { + const previousValue = localStorage.getItem(key) + + const [value, setValue] = useState( + previousValue !== null ? JSON.parse(previousValue) : initialValue + ) + + useEffect(() => { + localStorage.setItem(key, JSON.stringify(value)) + }, [value]) + + return [value, setValue] +}