remnantchat/src/Bootstrap.tsx

99 lines
2.6 KiB
TypeScript
Raw Normal View History

import { useEffect, useState } from 'react'
2022-09-01 03:05:24 +00:00
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom'
2022-08-20 19:20:51 +00:00
import { v4 as uuid } from 'uuid'
2022-08-20 21:52:31 +00:00
import localforage from 'localforage'
2022-08-10 02:28:46 +00:00
2022-09-05 22:35:40 +00:00
import { SettingsContext } from 'contexts/SettingsContext'
2022-08-20 21:52:31 +00:00
import { Home } from 'pages/Home/'
import { PublicRoom } from 'pages/PublicRoom/'
import { UserSettings } from 'models/settings'
import { PersistedStorageKeys } from 'models/storage'
import { Shell } from 'components/Shell'
2022-08-09 14:35:49 +00:00
2022-08-20 21:52:31 +00:00
export interface BootstrapProps {
persistedStorage?: typeof localforage
getUuid?: typeof uuid
}
function Bootstrap({
persistedStorage = localforage.createInstance({
name: 'chitchatter',
description: 'Persisted settings data for chitchatter',
}),
getUuid = uuid,
}: BootstrapProps) {
const [hasLoadedSettings, setHasLoadedSettings] = useState(false)
2022-09-05 22:35:40 +00:00
const [userSettings, setUserSettings] = useState<UserSettings>({
userId: getUuid(),
colorMode: 'dark',
})
const { userId } = userSettings
2022-08-20 21:52:31 +00:00
useEffect(() => {
;(async () => {
if (hasLoadedSettings) return
const persistedUserSettings =
await persistedStorage.getItem<UserSettings>(
PersistedStorageKeys.USER_SETTINGS
)
if (persistedUserSettings) {
2022-09-05 22:35:40 +00:00
setUserSettings(persistedUserSettings)
2022-08-20 21:52:31 +00:00
} else {
await persistedStorage.setItem(
PersistedStorageKeys.USER_SETTINGS,
2022-09-05 22:35:40 +00:00
userSettings
2022-08-20 21:52:31 +00:00
)
}
setHasLoadedSettings(true)
})()
2022-09-05 22:35:40 +00:00
}, [hasLoadedSettings, persistedStorage, userSettings, userId])
const settingsContextValue = {
updateUserSettings: async (changedSettings: Partial<UserSettings>) => {
const newSettings = {
...userSettings,
...changedSettings,
}
await persistedStorage.setItem(
PersistedStorageKeys.USER_SETTINGS,
newSettings
)
setUserSettings(newSettings)
},
getUserSettings: () => ({ ...userSettings }),
}
2022-08-20 19:20:51 +00:00
2022-08-10 02:28:46 +00:00
return (
2022-09-01 03:05:24 +00:00
<Router>
2022-09-05 22:35:40 +00:00
<SettingsContext.Provider value={settingsContextValue}>
<Shell userPeerId={userId}>
{hasLoadedSettings ? (
<Routes>
{['/', '/index.html'].map(path => (
2022-09-05 23:59:59 +00:00
<Route
key={path}
path={path}
element={<Home userId={userId} />}
/>
2022-09-05 22:35:40 +00:00
))}
<Route
path="/public/:roomId"
element={<PublicRoom userId={userId} />}
/>
</Routes>
) : (
<></>
)}
</Shell>
</SettingsContext.Provider>
2022-09-01 03:05:24 +00:00
</Router>
2022-08-10 02:28:46 +00:00
)
2022-08-09 14:35:49 +00:00
}
export default Bootstrap