Added localstorage support

pull/4/head
Antonio De Lucreziis 2 years ago
parent d623df9158
commit 96ca0fef8f

@ -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 (
<>

@ -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]
}

Loading…
Cancel
Save