refactor: LocalStorage state integration

This commit is contained in:
Taso committed 2021-01-12 11:28:20 -05:00
1 parent 5af6e4936d
commit 8912650f0e
10 files changed
+93 -144

No files matched your search

+1 -1
View File
@@ -31,7 +31,7 @@
"react-popper": "^2.2.3", "react-popper": "^2.2.3",
"react-router-dom": "^5.2.0", "react-router-dom": "^5.2.0",
"react-scripts": "3.4.3", "react-scripts": "3.4.3",
"recoil": "^0.0.10", "recoil": "^0.1.2",
"styled-components": "^5.1.1" "styled-components": "^5.1.1"
}, },
"devDependencies": { "devDependencies": {
+13 -10
View File
@@ -2,11 +2,10 @@ import React from 'react';
import './Phone.css'; import './Phone.css';
import './i18n'; import './i18n';
import { Route } from 'react-router-dom'; import { Route } from 'react-router-dom';
import { useSettings } from './apps/settings/hooks/useSettings';
import MessageIcon from '@material-ui/icons/Email'; import MessageIcon from '@material-ui/icons/Email';
import { CallModal } from './modal/components/CallModal'; import { CallModal } from './modal/components/CallModal';
import { HomeApp } from './apps/home/components/Home'; import { HomeApp } from './apps/home/components/Home';
import { ThemeProvider } from '@material-ui/core'; import { createMuiTheme, ThemeProvider } from '@material-ui/core';
import { useInitKeyboard } from './os/keyboard/hooks/useKeyboard'; import { useInitKeyboard } from './os/keyboard/hooks/useKeyboard';
import { NotificationIcon } from './os/notifications/components/NotificationIcon'; import { NotificationIcon } from './os/notifications/components/NotificationIcon';
import { NotificationBar } from './os/notifications/components/NotificationBar'; import { NotificationBar } from './os/notifications/components/NotificationBar';
@@ -25,7 +24,10 @@ import { useNotesService } from './apps/notes/hooks/useNotesService';
import { usePhotoService } from './apps/camera/hooks/usePhotoService'; import { usePhotoService } from './apps/camera/hooks/usePhotoService';
import Nui from './os/nui-events/utils/Nui'; import Nui from './os/nui-events/utils/Nui';
import { usePhone } from './os/phone/hooks/usePhone'; import { usePhone } from './os/phone/hooks/usePhone';
import { getStorage } from './os/phone/hooks/useLocalStorage'; import { settingsState } from './apps/settings/hooks/useSettings';
import config from './config/default.json';
import { useRecoilState } from 'recoil';
// Inject mock data when in development env. // Inject mock data when in development env.
if (process.env.NODE_ENV === 'development') { if (process.env.NODE_ENV === 'development') {
@@ -246,7 +248,6 @@ function Phone() {
useNuiService(); useNuiService();
usePhoneService(); usePhoneService();
const { visibility } = usePhone(); const { visibility } = usePhone();
const { settings, currentTheme } = useSettings();
const { allApps } = useApps(); const { allApps } = useApps();
useSimcardService(); useSimcardService();
useContactsService(); useContactsService();
@@ -258,10 +259,14 @@ function Phone() {
useNotesService(); useNotesService();
usePhotoService(); usePhotoService();
const [settings] = useRecoilState(settingsState);
if (visibility === false) { if (visibility === false) {
return null; return null;
} }
const currentTheme = () => createMuiTheme(config.themes[settings.theme]);
const calling = false; const calling = false;
document.onkeyup = function (data) { document.onkeyup = function (data) {
@@ -273,21 +278,19 @@ function Phone() {
return ( return (
<ThemeProvider theme={currentTheme()}> <ThemeProvider theme={currentTheme()}>
<div className='PhoneWrapper'> <div className='PhoneWrapper'>
<div style={{ zoom: getStorage('zoom') }}> <div style={{ zoom: settings.zoom }}>
<div className='Phone'> <div className='Phone'>
<div <div
className='PhoneFrame' className='PhoneFrame'
style={{ style={{
backgroundImage: `url(./media/frames/${getStorage('frame')})`, backgroundImage: `url(./media/frames/${settings.frame})`,
}} }}
></div> />
<div <div
id='phone' id='phone'
className='PhoneScreen' className='PhoneScreen'
style={{ style={{
backgroundImage: `url(./media/backgrounds/${getStorage( backgroundImage: `url(./media/backgrounds/${settings.wallpaper})`,
'wallpaper'
)})`,
}} }}
> >
<> <>
@@ -7,7 +7,6 @@ import {
MapStringOptions, MapStringOptions,
} from '../../../ui/hooks/useContextMenu'; } from '../../../ui/hooks/useContextMenu';
import { useConfig } from '../../../config/hooks/useConfig'; import { useConfig } from '../../../config/hooks/useConfig';
import { useSettings } from '../hooks/useSettings';
import { List } from '../../../ui/components/List'; import { List } from '../../../ui/components/List';
import { useSimcard } from '../../../os/simcard/hooks/useSimcard'; import { useSimcard } from '../../../os/simcard/hooks/useSimcard';
import { useApp } from '../../../os/apps/hooks/useApps'; import { useApp } from '../../../os/apps/hooks/useApps';
@@ -24,7 +23,8 @@ import {
} from '@material-ui/icons'; } from '@material-ui/icons';
import { ListSubheader } from '@material-ui/core'; import { ListSubheader } from '@material-ui/core';
import useLocalStorage from '../../../os/phone/hooks/useLocalStorage'; import { useRecoilState } from 'recoil';
import { settingsState } from '../hooks/useSettings';
const SubHeaderComp = (props: { text: string }) => ( const SubHeaderComp = (props: { text: string }) => (
<ListSubheader component='div' disableSticky> <ListSubheader component='div' disableSticky>
@@ -36,31 +36,37 @@ export const SettingsApp = () => {
const settingsApp = useApp('SETTINGS'); const settingsApp = useApp('SETTINGS');
const [config] = useConfig(); const [config] = useConfig();
const simcard = useSimcard(); const simcard = useSimcard();
const [settings, setSettings] = useRecoilState(settingsState);
const [wallpaper, setWallpaper] = useLocalStorage<any>( const handleSettingChange = (key: string | number, value: unknown) => {
'wallpaper', setSettings({ ...settings, [key]: value });
'surf.jpg' };
);
const [frame, setFrame] = useLocalStorage<any>('frame', 's10.png');
const [theme, setTheme] = useLocalStorage<any>('theme', 'default-dark');
const [zoom, setZoom] = useLocalStorage<any>('zoom', '100%');
const [ringtone, setRingtone] = useLocalStorage<any>('ringtone', '');
const wallpapers = config.wallpapers.map( const wallpapers = config.wallpapers.map(
MapStringOptions(wallpaper, (val: string) => setWallpaper(val)) MapStringOptions(settings.wallpaper, (val: string) =>
handleSettingChange('wallpaper', val)
)
); );
const frames = config.frames.map( const frames = config.frames.map(
MapStringOptions(frame, (val: string) => setFrame(val)) MapStringOptions(settings.frame, (val: string) =>
handleSettingChange('frame', val)
)
); );
const themes = Object.keys(config.themes).map( const themes = Object.keys(config.themes).map(
MapStringOptions(theme, (val: string) => setTheme(val)) MapStringOptions(settings.theme, (val: string) =>
handleSettingChange('theme', val)
)
); );
const zoomOptions = config.zoomOptions.map( const zoomOptions = config.zoomOptions.map(
MapStringOptions(zoom, (val: string) => setZoom(val)) MapStringOptions(settings.zoom, (val: string) =>
handleSettingChange('zoom', val)
)
); );
// Doesn't actually do anything for the time being // Doesn't actually do anything for the time being
const ringtones = config.ringtones.map( const ringtones = config.ringtones.map(
MapStringOptions(ringtone, (val: string) => setRingtone(val)) MapStringOptions(settings.ringtone, (val: string) =>
handleSettingChange('ringtone', val)
)
); );
// * Probably gonna make this a slider component in the future // * Probably gonna make this a slider component in the future
// const ringtoneVols = config.ringtoneVols.map( // const ringtoneVols = config.ringtoneVols.map(
@@ -69,8 +75,6 @@ export const SettingsApp = () => {
// TODO: These new settings all work // TODO: These new settings all work
useEffect(() => {}, [theme]);
const [openMenu, closeMenu, ContextMenu, isMenuOpen] = useContextMenu(); const [openMenu, closeMenu, ContextMenu, isMenuOpen] = useContextMenu();
return ( return (
<AppWrapper> <AppWrapper>
@@ -84,7 +88,7 @@ export const SettingsApp = () => {
/> />
<SettingItem <SettingItem
label='Ringtone' label='Ringtone'
value={ringtone} value={settings.ringtone}
options={ringtones} options={ringtones}
onClick={openMenu} onClick={openMenu}
icon={<LibraryMusic />} icon={<LibraryMusic />}
@@ -104,28 +108,28 @@ export const SettingsApp = () => {
<List disablePadding subheader={<SubHeaderComp text='Appearance' />}> <List disablePadding subheader={<SubHeaderComp text='Appearance' />}>
<SettingItem <SettingItem
label='Theme' label='Theme'
value={theme} value={settings.theme}
options={themes} options={themes}
onClick={openMenu} onClick={openMenu}
icon={<Brush />} icon={<Brush />}
/> />
<SettingItem <SettingItem
label='Wallpaper' label='Wallpaper'
value={wallpaper} value={settings.wallpaper}
options={wallpapers} options={wallpapers}
onClick={openMenu} onClick={openMenu}
icon={<Wallpaper />} icon={<Wallpaper />}
/> />
<SettingItem <SettingItem
label='Frame' label='Frame'
value={frame} value={settings.frame}
options={frames} options={frames}
onClick={openMenu} onClick={openMenu}
icon={<Smartphone />} icon={<Smartphone />}
/> />
<SettingItem <SettingItem
label='Zoom' label='Zoom'
value={zoom} value={settings.zoom}
options={zoomOptions} options={zoomOptions}
onClick={openMenu} onClick={openMenu}
icon={<ZoomIn />} icon={<ZoomIn />}
-8
View File
@@ -1,8 +0,0 @@
{
"wallpaper": "default.png",
"frame": "s10.png",
"theme": "taso-dark",
"zoom": "100%",
"ringtone": "pixel",
"ringtoneVol": 100
}
+23 -14
View File
@@ -1,19 +1,28 @@
import Default from '../default.json'; import { atom, DefaultValue, useRecoilState } from 'recoil';
import { useConfig } from '../../../config/hooks/useConfig'; import config from '../../../config/default.json';
import { atom } from 'recoil';
import { createMuiTheme } from '@material-ui/core';
import useLocalStorage, {
getStorage,
} from '../../../os/phone/hooks/useLocalStorage';
const settingsState = atom({ const localStorageEffect = (key) => ({ setSelf, onSet }) => {
const savedVal = localStorage.getItem(key);
if (savedVal != null) {
setSelf(JSON.parse(savedVal));
}
onSet((newValue) => {
if (newValue instanceof DefaultValue) {
localStorage.removeItem(key);
} else {
localStorage.setItem(key, JSON.stringify(newValue));
}
});
};
export const settingsState = atom({
key: 'settings', key: 'settings',
default: Default, default: config.defaultSettings,
effects_UNSTABLE: [localStorageEffect('settings')],
}); });
export const useSettings = (): any => { export const useSettings = () => {
const theme = getStorage('theme'); const [settings, setSettings] = useRecoilState(settingsState);
const [config] = useConfig(); return [settings, setSettings];
const currentTheme = () => createMuiTheme(config.themes[theme]);
return { currentTheme };
}; };
+8
View File
@@ -10,6 +10,14 @@
"surf.jpg", "surf.jpg",
"beach.jpg" "beach.jpg"
], ],
"defaultSettings": {
"wallpaper": "default.png",
"frame": "s10.png",
"theme": "taso-dark",
"zoom": "100%",
"ringtone": "pixel",
"ringtoneVol": 100
},
"frames": ["default.png", "s10.png", "tw.png", "samsung.png"], "frames": ["default.png", "s10.png", "tw.png", "samsung.png"],
"zoomOptions": ["120%", "100%", "80%", "60%", "40%"], "zoomOptions": ["120%", "100%", "80%", "60%", "40%"],
"ringtones": ["marimba", "pixel"], "ringtones": ["marimba", "pixel"],
-1
View File
@@ -1,6 +1,5 @@
import Default from '../default.json'; import Default from '../default.json';
import { atom, useRecoilState } from 'recoil'; import { atom, useRecoilState } from 'recoil';
import useLocalStorage from '../../os/phone/hooks/useLocalStorage';
const configState = atom({ const configState = atom({
key: 'config', key: 'config',
@@ -1,69 +0,0 @@
import { useState } from 'react';
// TODO: Integrate debug log to fetch when that branch is merged
/**
* A LocalStorage hook designed to behave like the useState hook.
* @param {string} key - The unique identifier to be used as a key
* @param {string} intialValue - The initialValue to be used
* if there is no savedState
*/
function useLocalStorage<T>(key: string, initialValue: T) {
// Serves as a nice identifying prefix for the key
const UNIQ_PREFIX = 'npwd_phone_';
const [localVal, setLocalVal] = useState<T>(() => {
try {
const data = window.localStorage.getItem(UNIQ_PREFIX + key);
// return stored or initValue if none stored
return data ? JSON.parse(data) : initialValue;
} catch (e) {
// TODO: Integrate debug error state here
console.log(e);
// We still return initVal if error is thrown
return initialValue;
}
});
// Trying to rep useState setter pretty close just with localStorage
const setVal = (value: T | ((val: T) => T)) => {
try {
// Same API as useState meaning we can accept a function for value
const valForStore = value instanceof Function ? value(localVal) : value;
// Save that state so we repli useState
setLocalVal(valForStore);
// Set that localStorage yo
window.localStorage.setItem(
UNIQ_PREFIX + key,
JSON.stringify(valForStore)
);
} catch (e) {
// TODO: Also integrate debug log state error here
console.log(e);
}
};
return [localVal, setVal];
}
export const writeStorage = <T>(key: string, value: T) => {
const UNIQ_PREFIX = 'npwd_phone_';
try {
window.localStorage.setItem(UNIQ_PREFIX + key, JSON.stringify(value));
} catch (error) {
console.log(error);
}
};
export const getStorage = (key: string) => {
const UNIQ_PREFIX = 'npwd_phone_';
try {
const data = window.localStorage.getItem(UNIQ_PREFIX + key);
return JSON.parse(data);
} catch (error) {
console.log(error);
}
};
export default useLocalStorage;
+18 -15
View File
@@ -1,17 +1,17 @@
import React from "react"; import React from 'react';
import { ThemeProvider } from "@material-ui/core"; import { createMuiTheme, ThemeProvider } from '@material-ui/core';
import Paper from "@material-ui/core/Paper"; import Paper from '@material-ui/core/Paper';
import Snackbar from "@material-ui/core/Snackbar"; import Snackbar from '@material-ui/core/Snackbar';
import Fade from "@material-ui/core/Fade"; import Fade from '@material-ui/core/Fade';
import { makeStyles } from "@material-ui/core/styles"; import { makeStyles } from '@material-ui/core/styles';
import { useSettings } from "../../apps/settings/hooks/useSettings"; import { useSettings } from '../../apps/settings/hooks/useSettings';
import { usePhone } from "../../os/phone/hooks/usePhone"; import { usePhone } from '../../os/phone/hooks/usePhone';
const useStyles = makeStyles({ const useStyles = makeStyles({
paper: { paper: {
width: "350px", width: '350px',
height: "100px", height: '100px',
opacity: "0.93", opacity: '0.93',
}, },
snackBar: { snackBar: {
zIndex: -5, // we want this to appear behind other active NUI events...probably zIndex: -5, // we want this to appear behind other active NUI events...probably
@@ -20,7 +20,7 @@ const useStyles = makeStyles({
function Notification({ children, handleClose, open }) { function Notification({ children, handleClose, open }) {
const classes = useStyles(); const classes = useStyles();
const { currentTheme } = useSettings(); const [settings] = useSettings();
const { config } = usePhone(); const { config } = usePhone();
if (!config) return null; if (!config) return null;
@@ -28,11 +28,15 @@ function Notification({ children, handleClose, open }) {
const { horizontal, vertical } = config.notificationPosition; const { horizontal, vertical } = config.notificationPosition;
return ( return (
<ThemeProvider theme={currentTheme()}>
<Snackbar <Snackbar
className={classes.snackBar} className={classes.snackBar}
anchorOrigin={{ horizontal, vertical }} anchorOrigin={{ horizontal, vertical }}
ClickAwayListenerProps={{ onClickAway: () => setTimeout(() => { handleClose() }, 5000) }} ClickAwayListenerProps={{
onClickAway: () =>
setTimeout(() => {
handleClose();
}, 5000),
}}
onClose={handleClose} onClose={handleClose}
open={open} open={open}
TransitionComponent={Fade} TransitionComponent={Fade}
@@ -40,7 +44,6 @@ function Notification({ children, handleClose, open }) {
> >
<Paper className={classes.paper}>{children}</Paper> <Paper className={classes.paper}>{children}</Paper>
</Snackbar> </Snackbar>
</ThemeProvider>
); );
} }
+4 -4
View File
@@ -10124,10 +10124,10 @@ recast@~0.11.12:
private "~0.1.5" private "~0.1.5"
source-map "~0.5.0" source-map "~0.5.0"
recoil@^0.0.10: recoil@^0.1.2:
version "0.0.10" version "0.1.2"
resolved "https://registry.yarnpkg.com/recoil/-/recoil-0.0.10.tgz#679ab22306f559f8a63c46fd5ff5241539f9248f" resolved "https://registry.yarnpkg.com/recoil/-/recoil-0.1.2.tgz#844c612f535826dbe54c977761a67ded16f6d063"
integrity sha512-+9gRqehw3yKETmoZbhSnWu4GO10HDb5xYf1CjLF1oXGK2uT6GX5Lu9mfTXwjxV/jXxEKx8MIRUUbgPxvbJ8SEw== integrity sha512-hIRrHlkmW4yITlBFprVYjVPhzPKYrJKoaDrrJtAtbkMeXfXaa/XE5OlyR10n+rNfnKWNToCKb3Z4fo86IGjkzg==
[email protected]: [email protected]:
version "2.2.2" version "2.2.2"