106 lines
2.6 KiB
JavaScript
106 lines
2.6 KiB
JavaScript
import { useState } from 'react'
|
|
import set from 'lodash.set'
|
|
// Stores state in local storage
|
|
import useLocalStorage from 'shared/hooks/useLocalStorage.js'
|
|
// Prebuild navigation
|
|
import prebuildNavigation from 'site/prebuild/navigation.js'
|
|
// Translation
|
|
import { useTranslation } from 'next-i18next'
|
|
|
|
/*
|
|
* Helper method for a simple navigation item
|
|
*/
|
|
const simpleNav = (term, t, lng, prefix='') => ({
|
|
__title: t(term, { lng }),
|
|
__linktitle: t(term, { lng }),
|
|
__slug: prefix+term,
|
|
__order: t(term, { lng })
|
|
})
|
|
|
|
/*
|
|
* Generated the static navigation
|
|
* Static means not mdx, not strapi
|
|
*/
|
|
const staticNavigation = (t, lang) => ({
|
|
designs: simpleNav('designs', t, lang),
|
|
community: simpleNav('community', t, lang),
|
|
account: simpleNav('account', t, lang),
|
|
})
|
|
|
|
/*
|
|
* Merges prebuild navigation with the static navigation
|
|
*/
|
|
const buildNavigation = (lang, t) => ({
|
|
...prebuildNavigation[lang],
|
|
...staticNavigation(t, lang),
|
|
})
|
|
|
|
/*
|
|
* The actual hook
|
|
*/
|
|
function useApp(full = true) {
|
|
|
|
// Load translation method
|
|
const { t } = useTranslation()
|
|
|
|
// User color scheme preference
|
|
const prefersDarkMode = (typeof window !== 'undefined' && typeof window.matchMedia === 'function')
|
|
? window.matchMedia(`(prefers-color-scheme: dark`).matches
|
|
: null
|
|
|
|
// Persistent state
|
|
const [account, setAccount] = useLocalStorage('account', { username: false })
|
|
const [theme, setTheme] = useLocalStorage('theme', prefersDarkMode ? 'dark' : 'light')
|
|
const [language, setLanguage] = useLocalStorage('language', 'en')
|
|
|
|
// React State
|
|
const [primaryMenu, setPrimaryMenu] = useState(false)
|
|
const [navigation, setNavigation] = useState(buildNavigation(language, t))
|
|
const [slug, setSlug] = useState('/')
|
|
const [loading, setLoading] = useState(false)
|
|
|
|
// State methods
|
|
const togglePrimaryMenu = () => setPrimaryMenu(!primaryMenu)
|
|
|
|
/*
|
|
* Hot-update navigation method
|
|
*/
|
|
const updateNavigation = (path, content) => {
|
|
if (typeof path === 'string') {
|
|
path = (path.slice(0,1) === '/')
|
|
? path.slice(1).split('/')
|
|
: path.split('/')
|
|
}
|
|
setNavigation(set(navigation, path, content))
|
|
}
|
|
|
|
return {
|
|
// Static vars
|
|
site: 'dev',
|
|
|
|
// State
|
|
language,
|
|
loading,
|
|
navigation,
|
|
primaryMenu,
|
|
slug,
|
|
theme,
|
|
|
|
// State setters
|
|
setLanguage,
|
|
setLoading,
|
|
setNavigation,
|
|
setPrimaryMenu,
|
|
setSlug,
|
|
setTheme,
|
|
startLoading: () => { setLoading(true); setPrimaryMenu(false) }, // Always close menu when navigating
|
|
stopLoading: () => setLoading(false),
|
|
updateNavigation,
|
|
|
|
// State handlers
|
|
togglePrimaryMenu,
|
|
}
|
|
}
|
|
|
|
export default useApp
|
|
|